Seamless USDC payments for AI agents using the x402 protocol
x402-agent-pay is an early-stage TypeScript project in the AI payments / x402 ecosystem, focused on ai-agents, crypto-payments, mcp-server, micropayments. It currently has 1 GitHub stars and 0 forks, and sits alongside related tools like APIbase, piprail, APIMesh, x402-wiki, conway, x402-discovery-mcp.
Seamless USDC payments for AI agents using the x402 protocol.
Built on the official @x402/fetch SDK with spending controls and audit trails for autonomous agents.
✅ Real USDC transaction on Base Sepolia:
0x51c7440999aebc9419ebb51a448e3f26f2f95d5e2f7b002b80c434e940d938a5When an AI agent hits a paid API (HTTP 402 Payment Required), this skill handles payment automatically — with safety guardrails:
Agent → Paid API → 402 Response → Policy Check → Auto-Pay → Access Granted
Before: Agent hits 402, crashes or needs human intervention
After: Agent pays automatically within defined limits, continues working
Autonomous agents need to pay for things, but giving them unlimited wallet access is dangerous. This library adds:
There are dozens of x402 projects. Here's why this one matters:
| Feature | Raw @x402/fetch | x402-agent-pay |
|---|---|---|
| Auto-402 handling | ✅ | ✅ |
| Spending limits | ❌ | ✅ Per-tx, daily, weekly, monthly |
| Velocity limits | ❌ | ✅ Max tx/hour |
| Recipient controls | ❌ | ✅ Whitelist + blacklist |
| Receipt logging | ❌ | ✅ Full audit trail |
| OpenClaw integration | ❌ | ✅ Native skill |
| Policy enforcement | ❌ | ✅ Block before signing |
The unique angle: Purpose-built for autonomous OpenClaw agents with guardrails that prevent wallet drain from bugs, prompt injections, or infinite loops.
x402-agent-pay includes an optional 0.5% protocol fee to support ongoing development.
| Property | Value |
|---|---|
| Rate | 0.5% (50 basis points) |
| Recipient | 0xe6Df117d19C7a5D08f20154BFa353caF1f9dB110 |
| Minimum | Fees under $0.001 skipped (gas savings) |
| Code path | src/client.ts → transferProtocolFee() |
Full transparency: The fee is a separate USDC transfer after each successful payment. You get full functionality with or without it.
// Disable fee (full functionality retained)
const client = new AgentPayClient({
privateKey: '0x...',
disableProtocolFee: true,
});
Why it exists: Sustainable open-source. If you find value, the fee supports maintenance. If not, disable it — no hard feelings.
npm install x402-agent-pay
# or
git clone https://github.com/Omnivalent/x402-agent-pay
cd x402-agent-pay && npm install
import { AgentPayClient } from 'x402-agent-pay';
const client = new AgentPayClient({
privateKey: process.env.WALLET_PRIVATE_KEY,
network: 'base',
policy: {
maxPerTransaction: 1.00, // Max $1 per request
dailyLimit: 10.00, // Max $10 per day
},
onPayment: (receipt) => {
console.log(`Paid ${receipt.amount} USDC to ${receipt.recipient}`);
},
onBlocked: (reason) => {
console.log(`Payment blocked: ${reason}`);
},
});
// Auto-handles 402 with policy enforcement
const response = await client.fetch('https://paid-api.example.com/data');
const data = await response.json();
| Policy | Default | Description |
|---|---|---|
maxPerTransaction |
$1.00 | Maximum per single payment |
dailyLimit |
$10.00 | Maximum total per 24 hours |
weeklyLimit |
none | Maximum per week (optional) |
monthlyLimit |
none | Maximum per month (optional) |
maxTransactionsPerHour |
60 | Velocity limit — prevents loops |
perRecipientDailyLimit |
none | Max to any single address per day |
approvedRecipients |
none | Whitelist of allowed addresses |
blockedRecipients |
none | Blacklist of blocked addresses |
autoApproveUnder |
$0.10 | Skip detailed logging for tiny amounts |
const client = new AgentPayClient({
privateKey: process.env.WALLET_PRIVATE_KEY,
policy: {
maxPerTransaction: 5.00,
dailyLimit: 50.00,
weeklyLimit: 200.00,
monthlyLimit: 500.00,
maxTransactionsPerHour: 30, // Prevent rapid loops
perRecipientDailyLimit: 10.00, // Max $10 to any one address
approvedRecipients: ['0x1234...'], // Only these can receive
blockedRecipients: ['0xScam...'], // Never pay these
},
});
Find x402-enabled APIs without hardcoding URLs — a first for agent payment infrastructure:
import { discoverServices, ServiceDiscovery } from 'x402-agent-pay';
// Find all weather APIs
const weatherApis = await discoverServices({ category: 'weather' });
// Find cheap services under $0.01
const cheapServices = await discoverServices({ maxPrice: 0.01 });
// Find services on Base network
const baseServices = await discoverServices({ network: 'eip155:8453' });
// Search by keyword
const aiServices = await discoverServices({ query: 'trading' });
// Get the cheapest option in a category
const discovery = new ServiceDiscovery();
const cheapestWeather = await discovery.findCheapest('weather');
console.log(cheapestWeather?.url); // → Use with client.fetch()
Available Categories: weather, data, ai, compute, storage, oracle, search, media, finance
The registry is open — submit your x402-enabled service via PR to registry.json.
x402-agent-pay includes an MCP server for direct integration with Claude, GPT, and other LLM agents:
# Run the MCP server
X402_WALLET_KEY=0x... npm run mcp
MCP Tools:
| Tool | Description |
|---|---|
x402_pay |
Make a paid request to an x402 endpoint |
x402_discover |
Find services by category/price/network |
x402_balance |
Check USDC balance |
x402_status |
Get spending limits and usage |
x402_history |
Get payment receipts |
Claude Desktop config (~/.config/claude/mcp.json):
{
"mcpServers": {
"x402": {
"command": "npx",
"args": ["x402-agent-pay"],
"env": {
"X402_WALLET_KEY": "0x..."
}
}
}
}
# Set your wallet key
export WALLET_PRIVATE_KEY=0x...
# Make a paid request
npx ts-node scripts/x402-fetch.ts https://paid-api.example.com/data
# Check balance
npx ts-node scripts/x402-fetch.ts balance 0xYourWallet --network base
# View spending status
npx ts-node scripts/x402-fetch.ts status
# View payment history
npx ts-node scripts/x402-fetch.ts history 10
# Custom limits
npx ts-node scripts/x402-fetch.ts https://api.example.com --max-per-tx 5 --daily-limit 50
| Network | Chain ID | Status |
|---|---|---|
| Base | 8453 | ✅ Primary |
| Ethereum | 1 | ✅ Supported |
| Arbitrum | 42161 | ✅ Supported |
| Optimism | 10 | ✅ Supported |
| Polygon | 137 | ✅ Supported |
| Base Sepolia | 84532 | ✅ Testnet |
Main client with policy enforcement and receipt tracking.
const client = new AgentPayClient(config: AgentPayConfig);
// Make payment-enabled request
await client.fetch(url, init?, options?);
// Get spending status
client.getSpendingStatus();
// Get payment history
client.getHistory(limit?);
// Export receipts
client.exportReceiptsCsv();
For cases where you want direct SDK access without policy enforcement:
import { createSimpleFetch } from 'x402-agent-pay';
const fetch402 = createSimpleFetch(process.env.WALLET_PRIVATE_KEY);
const response = await fetch402('https://paid-api.com/data');
import { checkBalance, checkAllBalances } from 'x402-agent-pay';
// Single network
const balance = await checkBalance('0xYourWallet', 'base');
console.log(`${balance.balanceUsdc} USDC`);
// All networks
const balances = await checkAllBalances('0xYourWallet');
All payment attempts are logged to receipts.json:
{
"id": "550e8400-e29b-41d4-a716-446655440000",
"timestamp": "2026-02-09T07:30:00.000Z",
"url": "https://api.example.com/data",
"amount": "0.500000",
"currency": "USDC",
"network": "base",
"recipient": "0x1234...",
"txHash": "0xabc123...",
"status": "success"
}
Built-in protections:
Recommended practices:
| Risk | Mitigation |
|---|---|
| Wallet drain | Use a hot wallet with small balance (~$50). Never use your main wallet. |
| Infinite loops | Set maxTransactionsPerHour: 30 to cap velocity |
| Prompt injection | Policy enforcement happens in code, not LLM — can't be bypassed by prompts |
| Malicious 402 endpoints | Use approvedRecipients whitelist for production |
| Key exposure | Use env vars, never hardcode. Consider Circle Programmable Wallets for production. |
Default policy is conservative:
{
maxPerTransaction: 1.00, // Max $1 per tx
dailyLimit: 10.00, // Max $10/day
maxTransactionsPerHour: 60, // Velocity limit
}
One-command proof that it works:
# Clone and install
git clone https://github.com/Omnivalent/x402-agent-pay
cd x402-agent-pay && npm install
# Set wallet key (get testnet USDC from faucet.circle.com)
export WALLET_PRIVATE_KEY=0x...
# Check balance
npm run x402 balance 0xYourWallet --network baseSepolia
# Make a test payment (uses demo endpoint)
npm run x402 https://weather.x402.org/current?city=berlin --network baseSepolia
Expected flow:
→ GET /current?city=berlin
← 402 Payment Required (0.001 USDC)
→ Policy check: ✓ under $1 limit
→ Sign EIP-712 payment
← 200 OK + weather data
→ Receipt saved to receipts.json
See SKILL.md for OpenClaw integration.
~/.openclaw/workspace/skills/x402/
├── SKILL.md # Skill manifest
├── src/ # Source code
├── scripts/ # CLI tools
└── receipts.json # Payment history
MIT
Built by ClawMD 🩺 for the USDC Hackathon 2026
Universal MCP gateway for AI agents — 1108 tools, 307 providers. One endpoint (https://apibase.pro/mcp), pay-per-call with x402 USDC on Base + MPP USDC on Tempo.
x402 (HTTP 402 Payment Required) SDK + MCP server: let any API charge for itself and any AI agent pay for itself, USDC & stablecoins across EVM, Solana & 8 more chain families, in a couple of lines. Backendless, no fee, self-custodial, paid straight to your wallet. TypeScript, MIT.
APIMesh — 23 pay-per-call web analysis APIs + 16-tool MCP server with autonomous API generation. Security audits, SEO, tech stack detection. x402 + Stripe MPP payments.
The x402 Service Encyclopedia — Every service ranked, reviewed, and documented. Community knowledge base for the AI agent economy.
APIMesh — 23 pay-per-call web analysis APIs + 16-tool MCP server with autonomous API generation. Security audits, SEO, tech stack detection. x402 + Stripe MPP payments.
MCP server for x402 Service Discovery — continuously growing catalog of services, real-time quality signals, facilitator-compat checks. For Claude, Cursor, Windsurf.
The agent-native LLM router for autonomous agents. 55+ models (8 free), <1ms local routing, USDC payments on Base & Solana via x402.
The AI agent with a wallet — spends USDC autonomously to get real work done. Apache-2.0, TypeScript.
DePIN for Vintage Hardware — Proof-of-Antiquity blockchain where old machines outmine new ones. AI-powered hardware fingerprinting, 15+ CPU architectures, Solana bridge (wRTC). $0 VC.
🚀 Curated list of x402 resources: HTTP 402 Payment Required protocol for blockchain payments, crypto micropayments, AI agents, API monetization. Includes SDKs (TypeScript, Python, Rust), examples, facilitators (Coinbase, Cloudflare), MCP integration, tutorials. Accept USDC payments with one line of code. Perfect for AI agent economy.
Client SDK for the Vybe x402 API. Pay-per-call USDC over HTTP and prepaid-credit WebSocket streaming for Vybe's Solana analytics API. Built for AI agents.
The financial operating system for AI agents. A single HTTP client that intercepts '402 Payment Required', routes across x402, L402, and MPP, persists credentials as recoverable assets, enforces per-envelope budgets, and emits a structured trace.