Guide

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.

In Buff v1.0.0, x402 payments go through REST API endpoints instead of a client-side createX402Fetch() wrapper. The API handles payment, round-up calculation, and investment logic server-side.

Basic Usage

x402-flow.ts
typescript
1import { Buff } from "buff-protocol-sdk"
2
3const buff = new Buff({
4 apiKey: "your-api-key",
5 plan: "sprout",
6 investInto: "BTC",
7})
8
9// 1. Make a request to an x402-enabled API
10const res = await fetch("https://api.example.com/data")
11
12if (res.status === 402) {
13 // 2. Read payment details from 402 response headers
14 const paymentAddress = res.headers.get("X-Payment-Address")
15 const amountUsd = parseFloat(res.headers.get("X-Payment-Amount") || "0")
16
17 // 3. Calculate round-up via Buff
18 const breakdown = await buff.calculateRoundUp(amountUsd)
19 console.log("Payment:", amountUsd, "Round-up:", breakdown.roundUpUsd)
20
21 // 4. Get wrap instructions (transfers payment + round-up)
22 const { instructions } = await buff.getWrapInstructions(
23 amountUsd, agentPubkey, buffWalletPubkey
24 )
25
26 // 5. Build, sign, and send the transaction
27 // ... add instructions to transaction, sign, send ...
28
29 // 6. Retry the request with payment receipt
30 const paid = await fetch("https://api.example.com/data", {
31 headers: { "X-Payment-Receipt": txSignature, "X-Payment-Payer": agentPubkey },
32 })
33 const data = await paid.json()
34}

How It Works

When the server returns a 402 response, your code reads the payment details from response headers, uses the Buff SDK to calculate the round-up and get transfer instructions, sends the payment on Solana, then retries the request with a payment receipt header. The round-up accumulates in the Buff wallet and auto-invests at threshold.

x402 Headers

HeaderDirectionDescription
X-Payment-AddressResponse (402)Solana address to pay
X-Payment-AmountResponse (402)Amount in lamports or USD
X-Payment-CurrencyResponse (402)"SOL" or "USD"
X-Payment-NetworkResponse (402)"solana" (mainnet or devnet)
X-Payment-ReceiptRequest (retry)Transaction signature proving payment
X-Payment-PayerRequest (retry)Payer public key

Agent x402 Flow

For AI agents making frequent x402 payments, combine the Buff SDK with your agent's transaction signing to handle payments automatically.

x402-agent.ts
typescript
1import { Buff } from "buff-protocol-sdk"
2
3const buff = new Buff({
4 apiKey: process.env.BUFF_API_KEY,
5 plan: "tree",
6 investInto: "BTC",
7 investThreshold: 5,
8})
9
10async function x402Fetch(url: string, opts?: RequestInit) {
11 const res = await fetch(url, opts)
12
13 if (res.status !== 402) return res
14
15 const amountUsd = parseFloat(res.headers.get("X-Payment-Amount") || "0")
16 const payTo = res.headers.get("X-Payment-Address")
17
18 // Get Buff wrap instructions (includes round-up transfer)
19 const { instructions, breakdown } = await buff.getWrapInstructions(
20 amountUsd, agentPubkey, buffWalletPubkey
21 )
22
23 // Build and send the payment transaction
24 const tx = buildTransaction(instructions, payTo, amountUsd)
25 const signed = signWithAgentKey(tx)
26 const txSig = await sendTransaction(signed)
27
28 // Check if ready to swap accumulated round-ups
29 const { ready, transactions } = await buff.buildSwap(buffWalletPubkey)
30 if (ready) {
31 for (const swapTx of transactions) {
32 await buff.executeSwap(signAndSerialize(swapTx))
33 }
34 }
35
36 // Retry with receipt
37 return fetch(url, {
38 ...opts,
39 headers: {
40 ...opts?.headers,
41 "X-Payment-Receipt": txSig,
42 "X-Payment-Payer": agentPubkey,
43 },
44 })
45}
Note
x402 payments go through the same round-up logic as regular transactions. If an API call costs $0.30, Buff rounds up to $1.00 and invests the $0.70 difference into your chosen asset. All fee logic is handled server-side via the buff.finance API.