@asterpay-io/x402
v1.0.0
Published
x402 Protocol SDK - AI Agent Payment Infrastructure for Europe
Maintainers
Readme
@asterpay/x402
The European x402 Leader - AI Agent Payment Infrastructure
x402 Protocol SDK for autonomous AI agent payments. MiCA-compliant, GDPR-ready, with EUR off-ramp support.
Features
- 🤖 AI Agent Wallet - Autonomous wallets with spending controls
- ⚡ x402 Protocol - HTTP 402 Payment Required handling
- 🔒 Spending Limits - Per-transaction, hourly, daily, monthly limits
- 🛡️ Service Allowlists - Control which services can be paid
- 🔗 LangChain Integration - Ready-to-use tools for AI agents
- 🇪🇺 EU Compliant - MiCA-ready, GDPR compliant
Installation
npm install @asterpay/x402
# or
yarn add @asterpay/x402
# or
pnpm add @asterpay/x402Quick Start
Basic Usage
import { createX402Client, createAgentWallet } from '@asterpay/x402';
// Create a wallet for your AI agent
const wallet = createAgentWallet({
name: 'Research Agent',
privateKey: process.env.AGENT_PRIVATE_KEY!,
network: 'base',
spendingLimits: {
perTransaction: 1.00, // Max $1 per transaction
daily: 10.00, // Max $10 per day
monthly: 100.00 // Max $100 per month
},
allowedServices: [
'api.openai.com',
'api.anthropic.com',
'api.coingecko.com'
]
});
// Create x402 client
const client = createX402Client({
wallet: {
name: 'Research Agent',
privateKey: process.env.AGENT_PRIVATE_KEY!,
network: 'base',
spendingLimits: { daily: 10.00 }
},
autoPayEnabled: true,
debug: true
});
// Make requests - 402 responses are handled automatically
const response = await client.fetch('https://api.paid-service.com/premium-data');
const data = await response.json();LangChain Integration
import { setupAsterPayForLangChain } from '@asterpay/x402/langchain';
import { ChatOpenAI } from '@langchain/openai';
import { AgentExecutor, createOpenAIFunctionsAgent } from 'langchain/agents';
// Quick setup
const { tools, wallet, client } = setupAsterPayForLangChain({
privateKey: process.env.AGENT_KEY!,
network: 'base',
dailyLimit: 10,
monthlyLimit: 100
});
// Available tools:
// - asterpay_check_balance: Check wallet balance
// - asterpay_check_spending: Check spending limits
// - asterpay_paid_fetch: Fetch URLs with automatic payment
// - asterpay_get_transactions: Get transaction history
const llm = new ChatOpenAI({ model: 'gpt-4' });
const agent = await createOpenAIFunctionsAgent({ llm, tools, prompt });
const executor = new AgentExecutor({ agent, tools });
// Agent can now make paid API calls autonomously
const result = await executor.invoke({
input: 'Fetch the latest Bitcoin price from the premium API'
});Agent Wallet Features
import { createAgentWallet } from '@asterpay/x402';
const wallet = createAgentWallet({
name: 'Trading Bot',
privateKey: process.env.BOT_KEY!,
network: 'base',
spendingLimits: {
perTransaction: 0.50,
hourly: 5.00,
daily: 20.00,
monthly: 200.00
},
allowedServices: ['api.coingecko.com', 'api.dexscreener.com'],
blockedServices: ['gambling.com'],
autoPayEnabled: true,
maxAutoPayAmount: 0.10
});
// Check balance
const balance = await wallet.getBalance();
console.log(`Balance: $${balance}`);
// Check if payment would be allowed
const check = wallet.canPay({
amount: 0.05,
service: 'api.coingecko.com'
});
console.log(check); // { allowed: true }
// Get spending summary
const spending = wallet.getSpendingSummary();
console.log(spending.daily); // { spent: 2.50, limit: 20, remaining: 17.50 }
// Get transaction history
const txs = wallet.getTransactions({ limit: 10 });Custom Approval Logic
const client = createX402Client({
wallet: walletConfig,
autoPayEnabled: true,
onApproval: async (payment, context) => {
// Custom logic before payment
console.log(`Payment request from ${context.url}`);
console.log(`Amount: ${payment.maxAmountRequired}`);
// Return true to approve, false to reject
const amountUsd = parseInt(payment.maxAmountRequired) / 1_000_000;
return amountUsd < 1.00; // Only approve < $1
},
onTransaction: (tx) => {
console.log(`Payment completed: ${tx.txHash}`);
// Log to analytics, update UI, etc.
},
onError: (error) => {
console.error('Payment error:', error);
// Alert, retry logic, etc.
}
});Supported Networks
| Network | Chain ID | Status | |---------|----------|--------| | Base | 8453 | ✅ Mainnet | | Base Sepolia | 84532 | ✅ Testnet | | Polygon | 137 | ✅ Mainnet | | Polygon Amoy | 80002 | ✅ Testnet | | Arbitrum | 42161 | ✅ Mainnet | | Arbitrum Sepolia | 421614 | ✅ Testnet | | Ethereum | 1 | ✅ Mainnet | | Ethereum Sepolia | 11155111 | ✅ Testnet | | BNB Chain | 56 | ✅ Mainnet | | BNB Testnet | 97 | ✅ Testnet |
API Reference
createX402Client(options)
Creates an x402 client for handling HTTP 402 responses.
const client = createX402Client({
wallet: AgentWalletConfig,
autoPayEnabled?: boolean, // Default: true
onApproval?: PaymentApprovalCallback,
onTransaction?: TransactionCallback,
onError?: ErrorCallback,
debug?: boolean // Default: false
});createAgentWallet(config)
Creates an AI agent wallet with spending controls.
const wallet = createAgentWallet({
name: string,
privateKey: string,
network: SupportedNetwork,
spendingLimits?: SpendingLimits,
allowedServices?: string[],
blockedServices?: string[],
autoPayEnabled?: boolean,
maxAutoPayAmount?: number
});setupAsterPayForLangChain(config)
Quick setup for LangChain integration.
const { tools, wallet, client } = setupAsterPayForLangChain({
privateKey: string,
network?: string,
name?: string,
dailyLimit?: number,
monthlyLimit?: number,
perTransactionLimit?: number
});Security Best Practices
- Never commit private keys - Use environment variables
- Set spending limits - Always configure limits for agent wallets
- Use allowlists - Restrict which services can receive payments
- Monitor transactions - Use
onTransactioncallback for logging - Test on testnet first - Use Base Sepolia or Polygon Amoy
// ✅ Good: Environment variable
const wallet = createAgentWallet({
privateKey: process.env.AGENT_PRIVATE_KEY!,
...
});
// ❌ Bad: Hardcoded key
const wallet = createAgentWallet({
privateKey: '0x1234...', // NEVER DO THIS
...
});EUR Off-Ramp (Coming Soon)
AsterPay is the only x402 facilitator with EUR off-ramp support:
// Coming in v1.1
import { createEurOffRamp } from '@asterpay/x402';
const offRamp = createEurOffRamp({
apiKey: process.env.ASTERPAY_API_KEY!,
iban: 'DE89370400440532013000'
});
// Automatically convert USDC to EUR
await offRamp.withdraw({
amount: 100, // $100 USDC
// Arrives in EUR via SEPA Instant
});Support
- 📧 Email: [email protected]
- 📚 Docs: https://asterpay.io/docs
- 💬 Telegram: https://t.me/asterpaycommunity
- 🐦 Twitter: https://x.com/asterpayio
License
MIT © AsterPay
