x402 Explained: HTTP‑Native Micropayments for AI Agents (With Real Code)
Introduction
When autonomous AI agents need to call external services—LLM inference, data feeds, compute functions—they often encounter two practical problems:
- Payment friction: Traditional API keys or subscription models require manual billing setup, which is hard to automate at scale.
- Granular pricing: Many useful services are cheap enough that per‑call pricing in fractions of a cent makes sense, yet most payment rails are optimized for larger transactions.
The x402 specification addresses both by embedding a lightweight payment handshake directly into HTTP status codes. Agents can discover a price, pay it with a stablecoin, and receive the requested resource—all without leaving the HTTP request/response flow.
What x402 Actually Is
x402 is an extension of the HTTP status code space. It repurposes the 402 Payment Required code (originally reserved for future use) to signal that a resource is behind a paywall. The response includes a WWW-Authenticate header that conveys:
- The payment scheme (e.g.,
x402). - The required amount and currency.
- Instructions for constructing a payment payload (usually a signed transaction or a payment pointer).
Upon receiving a 402, the client can:
- Verify the amount is acceptable.
- Construct and submit a payment transaction to the specified blockchain.
- Include proof of payment (e.g., transaction hash) in a retry request, typically via an
Authorizationheader. - If the server validates the proof, it returns the desired resource with a 2xx status.
Because the flow stays within HTTP, existing libraries, proxies, and caching layers continue to work unchanged—only the client needs to understand the 402 flow.
Core Components
| Component | Role |
|---|---|
| Resource Server | Exposes endpoints that may return 402. Holds a price list and validates payments. |
| Payment Processor | Usually a smart contract on a low‑cost L2 (e.g., Base) that escrowed USDC and emits an event on successful transfer. |
| Client (Agent) | Implements the 402 handshake: reads the challenge, signs/pays, retries with proof. |
| Metadata | The WWW-Authenticate header contains a JSON object (x402 scheme) with fields: amount, asset, network, paymentPointer, maxTimeout. |
Example Challenge Header
WWW-Authenticate: x402 amount="0.05", asset="USDC", network="base:8453", paymentPointer="pay:0xA1b2.../invoice"
Honest Trade‑offs
- Latency: Each paid request adds at least one blockchain round‑trip (submit transaction, wait for inclusion, verify). On Base, finality is ~2 seconds; on Ethereum L1 it can be >10 seconds.
- Complexity: Agents must manage wallets, sign transactions, and handle nonce/replay protection. This is non‑trivial for lightweight scripts.
- Price Volatility Mitigation: Using a stablecoin (USDC) removes price swing risk, but you still need to maintain a USDC balance and approve the spender contract.
- Granularity Limits: Sub‑cent pricing is feasible only when transaction fees are negligible. On Base, a typical USDC transfer costs <$0.001, making $0.01 calls viable. On L1, the same call would be uneconomical.
-
Caching: Standard HTTP caching (Cache‑Control, ETag) works, but a cached 200 response must be invalidated if the underlying price changes. Servers often set
Cache-Control: no-storefor paid resources to avoid stale content.
These trade‑offs mean x402 is best suited for services where the per‑call cost is low enough to absorb the blockchain overhead, and where agents can tolerate a few seconds of latency for guaranteed payment.
Minimal Working Example (Node.js)
Below is a self‑contained example that demonstrates:
- A simple Express server that protects a
/summarizeendpoint with x402. - A client agent that reads the 402 challenge, pays using a mock USDC contract on Base, and retries.
Note: For brevity, the payment processor is a mock contract that simply records the payer and amount. In production you would deploy a real ERC‑20 escrow contract (e.g., OpenZeppelin’s
ERC20Voteswith areceive()fallback) and verify the transaction via an RPC call or a subgraph.
Server (server.js)
// server.js
const express = require('express');
const app = express();
const PORT = 3000;
// Mock price: $0.05 USDC per call
const PRICE_USDC = BigInt('5000000'); // 6 decimals => 0.05 * 1e6
const USDC_ADDRESS = '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913'; // Base USDC
app.use(express.json());
function x402Challenge() {
return `x402 amount="${Number(PRICE_USDC/1e6)}", asset="USDC", network="base:8453", paymentPointer="pay:${USDC_ADDRESS}/invoice"`;
}
// Protect endpoint
app.get('/summarize', (req, res) => {
const auth = req.headers.authorization || '';
// Expect proof: "x402 <txHash>"
if (!auth.startsWith('x402 ')) {
return res.status(402)
.set('WWW-Authenticate', x402Challenge())
.json({error: 'Payment required'});
}
const txHash = auth.slice(5);
// In real code: verify txHash on-chain, confirm amount >= PRICE_USDC, and that sender is allowed.
// Here we just accept any hash for demo.
res.json({summary: 'This is a dummy summary of the requested content.'});
});
app.listen(PORT, () => console.log(`Server listening on :${PORT}`));
Agent Client (agent.js)
javascript
// agent.js
const fetch = require('node-fetch');
const { ethers } = require('ethers');
// Configure provider (Base Sepolia testnet for demo)
const provider = new ethers.JsonRpcProvider('https://sepolia.base.org');
const USDC_ABI = [
"function balanceOf(address) view returns (uint256)",
"function transfer(address to, uint256 amount) returns (bool)"
];
const USDC_ADDRESS = '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913';
const USDC = new ethers.Contract(USDC_ADDRESS, USDC_ABI, provider);
// Wallet funded with USDC on Base Sepolia (replace with your own)
const PRIVATE_KEY = '0xYOUR_PRIVATE_KEY';
const wallet = new ethers.Wallet(PRIVATE_KEY, provider);
const usdcWithSigner = USDC.connect(wallet);
async function callSummarize(text) {
const url = 'http://localhost:3000/summarize';
let attempts = 0;
while (true) {
attempts++;
const resp = await fetch(url, {
method: 'GET',
headers: { 'Content-Type': 'application/json' }
});
if (resp.ok) {
const data = await resp.json();
return data.summary;
}
if (resp.status !== 402) {
throw new Error(`Unexpected status ${resp.status}`);
}
// Parse challenge
const wwwAuth = resp.headers.get('www-authenticate') || '';
const match = wwwAuth.match(/amount="([^"]+)"/);
if (!match) throw new Error('Malformed 402 challenge');
const amountUSDC = parseFloat(match[1]); // e.g., 0.05
const amountWei = ethers.parseUnits(amountUSDC.toString(), 6); // USDC has 6 decimals
// Ensure we have enough balance
const bal = await USDC.balanceOf(wallet.address);
if (bal < amountWei) {
throw new Error(`Insufficient USDC balance: ${ethers.formatUnits(bal,6)} < ${amountUSDC}`);
}
// Send payment (mock: just transfer to a fixed payee)
const payee = '0xPayeeAddressHere'; // In real scenario, this is the escrow contract
const tx = await usdcWithSigner.transfer(payee, amountWei);
await tx.wait(); // wait for inclusion on Base (~2s)
// Retry with proof
const authHeader = `x402 ${tx.hash}`;
console.log(`Paid ${amountUSDC} USDC (tx ${tx.hash}), retrying…`);
const secondResp = await fetch(url, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
'Authorization': authHeader
}
});
if (secondResp.ok) {
return (await secondResp.json()).summary;
}
// If still 402, something went wrong; break to avoid loop
throw new Error('Payment not recognized by server');
}
}
// Example usage
(async () => {
try {
const summary = await callSummarize('Explain quantum entanglement in two sentences.');
console.log('Result:', summary);
} catch (e) {
console.error('Failed:', e.message);
}
Top comments (0)