x402 Protocol
Auto-pay HTTP 402 responses and round up every machine-to-machine payment.
What is x402?
HTTP status 402 ("Payment Required") was reserved for future use since HTTP/1.1. The x402 protocol gives it a purpose: servers respond with 402 and a payment address, and compliant clients pay automatically. This enables machine-to-machine payments for APIs, data feeds, and AI tool calls without API keys or subscriptions.
Buff's createX402Fetch() wraps the standard fetch API. When a server responds with 402, it pays the requested amount and automatically records a Buff round-up on top.
Basic Usage
1import { Buff, createX402Fetch } from "@buff/sdk"23const buff = await Buff.init({ agentKeypair, platformId: "my-agent" })4const x402Fetch = createX402Fetch(buff, {5 autoPay: true,6 maxPaymentUsd: 1.00,7})89// Use like normal fetch — auto-pays 402 responses10const res = await x402Fetch("https://api.example.com/data")11// If 402, Buff pays + rounds up automatically1213const data = await res.json()14console.log(data)How It Works
When the server returns a 402 response, the x402 client reads the payment details from response headers, sends the payment on Solana, then retries the request with a payment receipt header. The round-up is recorded in the Buff wallet automatically.
x402 Headers
| Header | Direction | Description |
|---|---|---|
| X-Payment-Address | Response (402) | Solana address to pay |
| X-Payment-Amount | Response (402) | Amount in lamports or USD |
| X-Payment-Currency | Response (402) | "SOL" or "USD" |
| X-Payment-Network | Response (402) | "solana" (mainnet or devnet) |
| X-Payment-Receipt | Request (retry) | Transaction signature proving payment |
| X-Payment-Payer | Request (retry) | Payer public key |
Configuration Options
1const x402Fetch = createX402Fetch(buff, {2 // Auto-pay 402 responses without prompting3 autoPay: true,45 // Maximum amount to pay per request (safety limit)6 maxPaymentUsd: 1.00,78 // Retry the original request after payment (default: true)9 retryAfterPayment: true,1011 // Custom callback when payment is made12 onPayment: ({ amountUsd, recipient, txSignature }) => {13 console.log("Paid", amountUsd, "to", recipient)14 },1516 // Custom callback when round-up is recorded17 onRoundUp: ({ breakdown }) => {18 console.log("Round-up:", breakdown.roundUpUsd)19 },20})Manual Payment Handling
If you want to inspect 402 responses before paying, set autoPay: false and handle the payment yourself.
1const x402Fetch = createX402Fetch(buff, {2 autoPay: false,3 maxPaymentUsd: 5.00,4})56const res = await x402Fetch("https://api.example.com/premium")78if (res.status === 402) {9 const paymentDetails = res.headers.get("X-Payment-Amount")10 console.log("Server wants:", paymentDetails)1112 // Approve and retry13 const paid = await x402Fetch("https://api.example.com/premium", {14 x402: { approve: true },15 })16 const data = await paid.json()17}