x402 Protocol Specification

Technical deep dive into HTTP 402, x402 headers, payment flows, and Layer 2 micropayment infrastructure.

HTTP 402 Payment Required

The HTTP 402 status code was defined in RFC 7231 (June 2014) as:

"The 402 (Payment Required) status code is reserved for future use."

Coinbase's x402 protocol (launched May 2025) provides the first production implementation, enabling servers to request cryptocurrency payments via standard HTTP headers.

x402 Request/Response Flow

x402-request-example
GET /api/inference HTTP/1.1
Host: api.agenticbrowser.com
Content-Type: application/json
Authorization: Bearer {jwt_token}

{
  "model": "grok-4",
  "prompt": "Explain quantum computing",
  "max_tokens": 1024
}
x402-payment-required-response
HTTP/1.1 402 Payment Required
Content-Type: application/json
X-Accept-Payment: x402
X-Payment-Amount: 2500
X-Payment-Asset: ><
X-Payment-Contract: G849nDx4r1vwjibbmpjkZ6pbDWwaMouhkWLq1o8Z5FUN
X-Payment-Network: solana
X-Payment-Recipient: 7xKXtg2CW87d97TXJSDpbD5jBkheTqA83TZRuJosgAsU

{
  "error": "payment_required",
  "message": "This endpoint requires 2500 >< tokens",
  "payment_details": {
    "amount": "2500",
    "asset": "><",
    "contract": "G849nDx4r1vwjibbmpjkZ6pbDWwaMouhkWLq1o8Z5FUN",
    "network": "solana",
    "recipient": "7xKXtg2CW87d97TXJSDpbD5jBkheTqA83TZRuJosgAsU"
  }
}

Client executes payment, then retries with proof:

x402-payment-proof
GET /api/inference HTTP/1.1
Host: api.agenticbrowser.com
X-Payment-Signature: 3ZqPxZv2...8Hy4Kc (Solana tx signature)
X-Payment-Amount: 2500
X-Payment-Asset: ><

{
  "model": "grok-4",
  "prompt": "Explain quantum computing",
  "max_tokens": 1024
}

---

HTTP/1.1 200 OK
Content-Type: application/json

{
  "response": "Quantum computing leverages...",
  "tokens_used": 1024,
  "cost": "2500 ><"
}

Payment Verification

Server verifies on-chain transaction before serving content:

server-verification.ts
import { Connection, PublicKey } from '@solana/web3.js'

async function verifyPayment(txSignature: string, expectedAmount: number) {
  const connection = new Connection(process.env.SOLANA_RPC_URL)

  // Fetch transaction from blockchain
  const tx = await connection.getTransaction(txSignature, {
    commitment: 'confirmed'
  })

  if (!tx) throw new Error('Transaction not found')

  // Verify SPL token transfer
  const tokenTransfer = tx.meta?.postTokenBalances?.find(
    balance => balance.mint === process.env.FISH_TOKEN_MINT
  )

  if (!tokenTransfer) throw new Error('No token transfer found')

  // Verify amount matches
  const amount = tokenTransfer.uiTokenAmount.uiAmount
  if (amount !== expectedAmount) {
    throw new Error('Payment amount mismatch')
  }

  // Verify recipient
  const recipient = new PublicKey(tokenTransfer.owner)
  if (!recipient.equals(new PublicKey(process.env.RECIPIENT_ADDRESS))) {
    throw new Error('Payment sent to wrong address')
  }

  return true
}

Transaction Security

x402 inherits blockchain's cryptographic guarantees while adding HTTP-native replay protection and DoS mitigation. The protocol implements multiple security layers to prevent fraud and ensure payment atomicity.

Replay Attack Prevention

A replay attack occurs when an attacker intercepts a valid payment proof and reuses it to access resources without paying. x402 prevents this through timestamp-based nonce verification:

replay-protection.ts
interface PaymentProof {
  txSignature: string;        // Blockchain transaction ID
  timestamp: number;          // Unix milliseconds when payment made
  nonce: string;              // Unique request identifier
  requestHash: string;        // SHA-256 of request body
}

class ReplayProtection {
  private usedProofs = new Set<string>();
  private readonly EXPIRY_MS = 60_000;  // 60 second window

  async verifyPayment(proof: PaymentProof, requestBody: string): Promise<boolean> {
    // 1. Check proof hasn't been used before
    const proofKey = `${proof.txSignature}:${proof.nonce}`;
    if (this.usedProofs.has(proofKey)) {
      throw new Error('Replay attack detected: proof already used');
    }

    // 2. Verify timestamp is recent (within 60 seconds)
    const age = Date.now() - proof.timestamp;
    if (age > this.EXPIRY_MS) {
      throw new Error(`Payment proof expired (age: ${age}ms)`);
    }

    // 3. Verify request hash matches (prevent proof reuse for different requests)
    const actualHash = sha256(requestBody);
    if (proof.requestHash !== actualHash) {
      throw new Error('Request hash mismatch: proof not valid for this request');
    }

    // 4. Verify on-chain transaction
    const isValid = await this.verifyOnChain(proof.txSignature);
    if (!isValid) return false;

    // Mark proof as used
    this.usedProofs.add(proofKey);

    // Cleanup old proofs (prevent memory leak)
    setTimeout(() => this.usedProofs.delete(proofKey), this.EXPIRY_MS);

    return true;
  }

  private async verifyOnChain(txSignature: string): Promise<boolean> {
    // Solana/Base RPC verification (see Payment Verification section)
    return true;
  }
}

By binding payment proofs to specific request bodies via SHA-256 hashing, x402 ensures a proof valid for "GET /api/inference?prompt=A" cannot be replayed for a different request.

Signature Verification

All x402 payments are verified on-chain before serving content. This provides cryptographic proof of payment with blockchain-level security:

  • Solana SPL token transfers: Ed25519 signatures verified by Solana validators
  • Base L2 transfers: ECDSA signatures verified by Ethereum L2 sequencer
  • Finality guarantees: Solana (32 confirmations = 12.8s), Base (12s)

Unlike traditional payment APIs (Stripe, PayPal), x402 verification is trustless—servers independently verify transactions via public blockchain RPCs without relying on third-party payment processors.

DoS Mitigation

A naive x402 implementation could be exploited for DoS attacks: attackers send 402 requests without payment, forcing servers to respond with payment details. x402 mitigates this through:

  • Proof-of-work challenges: Require sha256(nonce + challenge) to have N leading zeros before responding with payment details
  • Rate limiting: Restrict 402 responses to M per IP per minute (e.g., 10/min)
  • Payment channel hints: Prefer clients with existing open channels (lower verification cost)
dos-mitigation.ts
class X402Server {
  private rateLimiter = new Map<string, number[]>();

  async handle402Request(req: Request): Promise<Response> {
    const clientIP = req.headers.get('X-Forwarded-For') || 'unknown';

    // Rate limit: max 10 payment requests per minute per IP
    if (!this.checkRateLimit(clientIP, 10, 60_000)) {
      return new Response('Too many payment requests', { status: 429 });
    }

    // Require proof-of-work for 402 responses (prevent spam)
    const challenge = crypto.randomUUID();
    const powResult = req.headers.get('X-PoW-Result');
    const powNonce = req.headers.get('X-PoW-Nonce');

    if (!powResult || !this.verifyPoW(challenge, powNonce, powResult, 4)) {
      return new Response(JSON.stringify({
        error: 'proof_of_work_required',
        challenge,
        difficulty: 4,  // 4 leading zero bits
      }), { status: 402 });
    }

    // Valid PoW: respond with payment details
    return new Response(JSON.stringify({
      amount: 2500,
      asset: '><',
      recipient: process.env.RECIPIENT_ADDRESS,
    }), {
      status: 402,
      headers: {
        'X-Accept-Payment': 'x402',
        'X-Payment-Amount': '2500',
      },
    });
  }

  private verifyPoW(
    challenge: string,
    nonce: string,
    result: string,
    difficulty: number
  ): boolean {
    const hash = sha256(challenge + nonce);
    const leadingZeros = hash.match(/^0*/)?.[0].length || 0;
    return leadingZeros >= difficulty && hash === result;
  }

  private checkRateLimit(ip: string, max: number, windowMs: number): boolean {
    const now = Date.now();
    const timestamps = this.rateLimiter.get(ip) || [];

    // Remove expired timestamps
    const validTimestamps = timestamps.filter(ts => now - ts < windowMs);

    if (validTimestamps.length >= max) return false;

    validTimestamps.push(now);
    this.rateLimiter.set(ip, validTimestamps);
    return true;
  }
}

Performance Characteristics

x402's performance profile makes it uniquely suited for autonomous agents requiring high-frequency, low-latency API access. Benchmarks from production deployments (October 2025 data):

Latency Breakdown

OperationSolanaBase L2Notes
Transaction Submission50ms100msRPC call + mempool propagation
Block Confirmation400ms2000msBlock time (single confirmation)
Finality12.8s12sSolana: 32 blocks, Base: optimistic finality
402 → Payment → 200~13s~12sFull payment flow (finality required)
With Payment Channel<100ms<100msOff-chain state update only

For comparison, traditional payment APIs:

  • Stripe payment confirmation: 2-5 seconds (credit card authorization)
  • PayPal: 3-7 seconds (OAuth + transaction)
  • Lightning Network: 1-3 seconds (on-chain finality not required)

x402 with payment channels achieves sub-100ms latency, making it 10-70x faster than traditional payment APIs and competitive with Lightning Network for micropayments.

Throughput

Maximum transactions per second (TPS) for different x402 deployment modes:

ModeTPS per AgentBottleneck
On-Chain (Solana)~2 TPSBlock time (400ms) + finality
On-Chain (Base L2)~0.5 TPSBlock time (2s) + finality
Payment Channel~1000 TPSSignature generation (TSS overhead)
Batched Channel Updates~5000 TPSNetwork I/O (signature exchange)

For a trading agent making 500 API calls per hour (~0.14 TPS), payment channels provide 7000x headroom above requirements. This allows burst workloads (e.g., 100 parallel requests) without performance degradation.

Cost Efficiency

The economic feasibility of sub-cent micropayments depends on transaction costs being negligible relative to payment size. x402 achieves this through L2 scaling:

Payment AmountSolana GasBase L2 GasOverhead
$0.0001$0.0001$0.0002100-200%
$0.001$0.0001$0.000210-20%
$0.01$0.0001$0.00021-2%
$0.10$0.0001$0.00020.1-0.2%

Payment channels amortize gas costs to <0.01% overhead at 1000+ transactions per session, making even $0.0001 payments economically viable.

Why x402 is Perfect for Browsers

The convergence of autonomous agents, HTTP 402, and blockchain micropayments creates unique opportunities for browser-native integration. x402 is ideal for browsers because:

1. HTTP-Native Semantics

x402 leverages existing HTTP infrastructure—status codes, headers, middleware—without requiring new protocols. Browsers already handle 401 (unauthorized), 403 (forbidden), and 429 (rate limit). Adding 402 (payment required) is a natural extension.

Compare this to WebRTC (requires ICE/STUN/TURN servers), WebSockets (custom protocol), or libp2p (DHT bootstrapping). x402 works with existing CDNs, reverse proxies, and HTTP caches.

2. Sub-Second Finality with Payment Channels

Browsers require low-latency interactions. On-chain settlement (12-13 seconds) is acceptable for one-time purchases but unusable for high-frequency agent workflows. Payment channels reduce latency to <100ms, comparable to API response times.

3. No Account Registration

Traditional payment APIs require OAuth flows, account creation, and KYC for compliance. x402 uses public-key cryptography—wallets are derived from mnemonics, payments are verified on public blockchains. This eliminates signup friction for agents operating across thousands of APIs.

4. Programmatic Access by Default

Credit cards, PayPal, and Stripe were designed for humans. x402 was designed for machines:

  • No CAPTCHA challenges
  • No 3D Secure redirects
  • No billing address validation
  • No email confirmation flows

Agents simply sign transactions with threshold keys and present blockchain proofs. This reduces payment flows from 8+ user interactions to zero.

5. Self-Custody Alignment

Browsers control user data (cookies, localStorage, passwords). x402 extends this to financial data. By integrating MPC wallets directly into the browser, users maintain custody of funds while delegating signing authority to agents through threshold policies.

This aligns with Andreas Antonopoulos's principle: "Your keys, your Bitcoin. Not your keys, not your Bitcoin." Custodial solutions (Coinbase Wallet API, MetaMask Snaps with remote signing) defeat the purpose of decentralization.

Layer 2 Optimization

For high-frequency payments, x402 supports payment channels (similar to Lightning Network). This is covered in detail in the Payment Channels documentation:

  • Open channel - User locks funds in a 2-of-3 threshold-signed state channel contract (single on-chain transaction)
  • Off-chain payments - Hundreds or thousands of micropayments signed with TSS, state updated locally without blockchain interaction
  • Close channel - Final state settled on-chain (single transaction), or dispute resolution if counterparty broadcasts old state

Payment channels reduce gas costs from $0.0001/tx (Solana) to $0.0000002/tx amortized across 1000 transactions—a 500x improvement. See Payment Channels for implementation details, cryptographic proofs, and code examples.

Adoption Metrics

Since Coinbase's launch of x402 in May 2025, adoption has accelerated dramatically:

  • 10,000% month-over-month growth in transaction volume (one of the fastest adoption curves in blockchain history)
  • 900,000+ on-chain settlements per week by October 2025
  • x402 Foundation established by Coinbase and Cloudflare to govern protocol standards
  • Major API providers integrating x402: OpenRouter (LLM inference), Together AI (open-source models), Fireworks (specialized inference)

This rapid growth is driven by AI agents. As autonomous systems proliferate (GitHub Copilot, ChatGPT plugins, Browser Use), the economic viability of agent-to-API payments becomes critical. x402 provides the infrastructure for this machine-to-machine economy.

Research & Standards

x402 builds on decades of academic research and industry standardization:

  • RFC 7231 (2014): HTTP/1.1 specification defining 402 status code [IETF]
  • Coinbase x402 Documentation (2025): Official protocol specification [Coinbase]
  • Lightning Network (2016): Payment channel primitives [Poon & Dryja]
  • GG20/CGGMP21: Threshold ECDSA for MPC wallets See Research & References

For a complete bibliography of cryptographic papers, blockchain specifications, and industry sources, see the Research & References page.

Next Steps