Building Agentic Commerce #4: x402 Stablecoin Payments — When Agents Pay in USDC
How AI agents make on-chain USDC payments using the x402 protocol — multi-chain settlement, EIP-712 signatures, and production-ready stablecoin checkout.
Executive summary
Part 4 of 'Building Agentic Commerce' explains the x402 stablecoin payment protocol — how AI agents discover x402-enabled merchants, sign EIP-712 authorizations, settle on-chain via facilitators, and handle retries with exponential backoff. Covers 5 supported chains, USDC amount conversion, SSRF protection, and 197 tests.
Published
2026-04-06
14 min
Author
AgenticMCPStores Engineering
Core Protocol Team
Category
developer-guide
In the first three parts of this series, we covered multi-protocol checkout, agent discovery via NLWeb, and trust scores. Now we tackle the protocol that makes agents truly autonomous: x402 — stablecoin payments where agents pay directly on-chain in USDC.
Why Stablecoin Payments Matter for Agents
Traditional payment protocols (card networks, PayPal) require human identity — a cardholder, a PayPal account, a billing address. AI agents don't have these. The x402 protocol solves this by using wallet-based authentication: an agent proves it can pay by signing a cryptographic authorization, and settlement happens on-chain without any human identity requirement.
The HTTP 402 status code ("Payment Required") was reserved in the original HTTP specification but never standardized. The x402 protocol finally gives it a concrete implementation: when a server returns HTTP 402, it includes a machine-readable payment requirement that an agent can fulfill autonomously.
How x402 Works: The Complete Flow
Step 1: Agent Requests a Resource
PAYMENT-SIGNATURE (V2 format, confidence 0.95) or X-PAYMENT (V1 legacy, confidence 0.90). An explicit X-Protocol: X402 header yields confidence 1.0. POST /api/v1/agent/checkout HTTP/1.1
Host: api.agenticmcpstores.com
Content-Type: application/json
PAYMENT-SIGNATURE: eyJzaWduYXR1cmUiOiIweGFiYy4uLiIsImF1dGhvcml6YXRpb24iOnsiZnJvbSI6IjB4MTExMSIsInRvIjoiMHgyMjIyIiwidmFsdWUiOiI1MDAwMDAwIiwidmFsaWRBZnRlciI6IjE3MTI1MDAwMDAiLCJ2YWxpZEJlZm9yZSI6IjE3MTI1MDM2MDAiLCJub25jZSI6IjB4ZGVhZGJlZWYifSwic2NoZW1lIjoiZXhhY3QiLCJuZXR3b3JrIjoiYmFzZSJ9
{"items": [{"productId": "prod_001", "quantity": 1}]}Step 2: Server Returns HTTP 402
PaymentRequired object with the merchant's wallet, network, and USDC token address. This is base64-encoded into the PAYMENT-REQUIRED header: HTTP/1.1 402 Payment Required
PAYMENT-REQUIRED: eyJzY2hlbWUiOiJleGFjdCIsIm5ldHdvcmsiOiJiYXNlIi4uLn0=
{
"paymentRequired": {
"scheme": "exact",
"network": "base",
"maxAmountRequired": "5000000",
"payTo": "0x2222...merchant_wallet",
"maxTimeoutSeconds": 1800,
"extra": {
"tokenAddress": "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",
"name": "USDC",
"version": "2"
}
},
"facilitator": {
"verifyUrl": "https://x402.org/facilitator/verify",
"settleUrl": "https://x402.org/facilitator/settle"
}
}The amount 5000000 represents 5 USDC. USDC uses 6 decimal places, so 1 USDC = 1,000,000 smallest units. The conversion: USD cents × 10,000 = USDC smallest units.
Step 3: Agent Signs and Settles
PaymentRequired, signs an EIP-712 typed data authorization with its private key, and submits to the settlement endpoint. The V2 authorization includes replay protection (nonce), time bounds (validAfter, validBefore), and the exact amount:// V2 PAYMENT-SIGNATURE payload (base64-decoded)
{
"signature": "0xabc123...eip712_sig",
"authorization": {
"from": "0x1111...agent_wallet",
"to": "0x2222...merchant_wallet",
"value": "5000000",
"validAfter": "1712500000",
"validBefore": "1712503600",
"nonce": "0xdeadbeef"
},
"scheme": "exact",
"network": "base"
}Step 4: Settlement with Exponential Backoff
x402_pending_payment, (2) verify the signature via the facilitator's /verify endpoint — if invalid, the order fails immediately with no retry, (3) attempt settlement via /settle with up to 5 retries using exponential backoff (5s → 10s → 20s → 40s), and (4) update the order to completed with the on-chain transaction hash, or x402_failed if all retries are exhausted.// Settlement retry logic (simplified)
for (let attempt = 0; attempt < 5; attempt++) {
if (attempt > 0) {
await sleep(5000 * Math.pow(2, attempt - 1)); // 5s, 10s, 20s, 40s
}
const result = await fetch(facilitator.settleUrl, {
method: "POST",
body: JSON.stringify({ paymentPayload, paymentRequired }),
signal: AbortSignal.timeout(15_000) // 15s per-request timeout
});
if (result.success) {
return { status: "COMPLETED", txHash: result.txHash };
}
}
return { status: "FAILED" };Supported Chains and Tokens
AgenticMCPStores supports x402 payments across 5 blockchain networks, all using USDC as the settlement token:
- 1Base — USDC at
0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913(recommended: lowest fees) - 2Ethereum — USDC at
0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48 - 3Polygon — USDC at
0x3c499c542cEF5E3811e1192ce70d8cC03d5c3359 - 4Arbitrum — USDC at
0xaf88d065e77c8cC2239327C5EDb3A432268e5831 - 5Solana — USDC at
EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v
Merchants can override the default USDC address with a custom tokenAddress in their protocol configuration. A maxTransactionAmount safety cap is also supported.
Amount Conversion: USDC ↔ USD Cents
// Inbound: USDC smallest units → USD cents
// 1 USDC (1,000,000 units) = 100 cents → divide by 10,000
const cents = parseInt(usdcSmallestUnit) / 10_000;
// Example: "5000000" (5 USDC) → 500 cents ($5.00)
// Outbound: USD cents → USDC smallest units
const usdc = String(Math.round(cents * 10_000));
// Example: 500 cents → "5000000" (5 USDC)Safety checks prevent sub-cent precision errors (values must be divisible by 10,000), reject negative amounts, and enforce IEEE-754 safe integer bounds (~$9 billion max).
Protocol Detection: How x402 Is Identified
x402 is one of 8 payment protocols in the AgenticMCPStores detection system. The multi-protocol detector assigns confidence scores to determine which adapter handles each request:
- 1
X-Protocol: X402header → confidence 1.0 (explicit declaration) - 2
PAYMENT-SIGNATUREheader (V2) → confidence 0.95 - 3
X-PAYMENTheader (V1 legacy) → confidence 0.90 - 4Body shape match (
paymentPayload,x402, orpaymentRequiredfields) → confidence 0.85 - 5No match → falls back to ACP at confidence 0.5
This means x402 coexists with ACP, UCP, PayPal, Visa VIC, Mastercard Agent Pay, and other protocols. The highest-confidence adapter wins, and the protocol bridge routes the payment to the correct settlement path.
Merchant Configuration
// Stored in MerchantProtocol.config (database)
{
"protocol": "X402",
"enabled": true,
"priority": 100,
"config": {
"walletAddress": "0xAbCd...merchant_wallet",
"network": "base",
"facilitatorUrl": "https://x402.org/facilitator",
"supportedTokens": ["USDC"],
"maxTransactionAmount": 100000000 // 100 USDC safety cap
}
}facilitatorUrl. Wallet addresses are validated for both EVM (0x + 40 hex chars) and Solana formats.Security Model
- 1No sensitive data in audit logs — wallet addresses, signatures, and nonces are never stored in OrderEvent records. Only protocol name, network, and transaction hash references are logged.
- 2Facilitator-delegated verification — the bridge never validates EIP-712 signatures locally (no key material on the server). Verification is delegated to the facilitator's
/verifyendpoint. - 3Atomic state transitions — order status updates use database-level atomicity. The expiration job double-checks status before updating to prevent race conditions.
- 4SSRF protection — merchant-provided facilitator URLs are validated against private IP ranges and internal hostnames.
- 515-second fetch timeout — all facilitator requests have a hard timeout to prevent hanging connections.
Order Status State Machine
┌──────────┐ verify ┌──────────────────────┐
│ PENDING │ ──────────────→ │ x402_pending_payment │
└──────────┘ └──────────┬───────────┘
│
┌─────────────┼─────────────┐
↓ ↓ ↓
┌───────────┐ ┌───────────┐ ┌─────────┐
│ completed │ │ x402_failed│ │ expired │
└───────────┘ └───────────┘ └─────────┘
Terminal states cannot be overwritten.
Expiration: 30-minute background job catches stuck payments.V1 vs V2 Header Format
nonce, time-bounded validity (validAfter/validBefore), and structured EIP-712 typed data. V1 (X-PAYMENT) is maintained for backward compatibility but lacks nonce and time bounds, making it less secure. New integrations should always use V2.Production Tips
- 1Choose Base for lowest fees — L2 transaction costs are a fraction of Ethereum mainnet. Most agent-to-merchant payments are small (<$100), making Base the optimal default.
- 2Set maxTransactionAmount — a per-merchant safety cap prevents accidental large settlements. Start conservative (e.g., 100 USDC) and increase as trust builds.
- 3Monitor the expiration job — orders stuck in
x402_pending_paymentfor >30 minutes indicate facilitator issues or network congestion. Set up alerts on thex402_payment_expiredOrderEvent. - 4Use V2 headers exclusively — V1 lacks replay protection. Disable V1 support in production if your agent ecosystem supports V2.
- 5Handle 402 responses gracefully — when building agent clients, parse the
PAYMENT-REQUIREDheader, extract the facilitator URLs, and implement the sign-and-settle flow. The facilitator handles all on-chain complexity.
Test Coverage
The x402 implementation is backed by 197 test cases across 6 test files (~2,554 lines of test code). Coverage includes: detection (8 tests), normalization (12 tests), settlement with backoff (45+ tests), configuration validation with SSRF (18 tests), end-to-end integration (22 tests), and 92+ edge cases covering precision errors, timeouts, network failures, and concurrent state updates.
What's Next
Frequently asked questions
What is x402 and how does it relate to HTTP 402?
x402 is a payment protocol that implements the long-reserved HTTP 402 (Payment Required) status code. When a server returns 402, it includes a machine-readable PaymentRequired object that AI agents can fulfill autonomously using USDC stablecoin payments on-chain.
Which blockchains does x402 support?
AgenticMCPStores supports x402 on 5 networks: Base (recommended for lowest fees), Ethereum, Polygon, Arbitrum, and Solana. All use USDC as the settlement token with well-known contract addresses per chain.
How does x402 handle failed settlements?
The settlement service uses exponential backoff with up to 5 retry attempts (delays of 5s, 10s, 20s, 40s). Each facilitator request has a 15-second timeout. If all retries fail, the order is marked x402_failed. A background job expires stuck orders after 30 minutes.
Is x402 secure? How are signatures verified?
Yes. x402 V2 uses EIP-712 typed data signatures with replay protection (nonce) and time bounds. Signature verification is delegated to the facilitator — no private key material exists on the server. Wallet addresses and signatures are never stored in audit logs.
Can x402 work alongside other payment protocols?
Absolutely. x402 is one of 8 payment protocols in the AgenticMCPStores detection system. The multi-protocol detector assigns confidence scores, and the highest-confidence adapter wins. If a merchant doesn't have x402 enabled, the bridge falls back to their preferred protocol (ACP, PayPal, etc.).
Sources and references
- x402 Protocol Specification
x402 Project (Coinbase CDP)
- EIP-712: Typed structured data hashing and signing
Ethereum Foundation
- USDC Documentation — Circle
Circle
- HTTP 402 Payment Required — MDN Web Docs
Mozilla
Related articles
developer-guide
Building Agentic Commerce #1: Multi-Protocol Checkout — MCP + x402 + ACP in One Flow
One agent, three protocols, one checkout. Here's how MCP, x402 stablecoin payments, and ACP work together to let AI agents buy products — with code examples you can run today.
developer-guide
Building Agentic Commerce #3: Trust Scores — How Agents Decide Who to Buy From
When an AI agent evaluates merchants, it doesn't read reviews or recognize logos. It reads trust scores — 12 machine-verifiable signals that determine search ranking, checkout eligibility, and payment friction. Here's how the system works.
developer-guide
Building Agentic Commerce #2: How AI Agents Discover Your Store Without an API Key
Before an agent can buy anything, it needs to find your store. Here's the 6-phase discovery chain that takes an AI agent from zero knowledge to checkout-ready in under 2 seconds — no pre-configuration required.