Recipe: x402 buyer paying for a digital asset
import { createX402bClientFetch } from "@bosonprotocol/x402-client-fetch"
import { ethers } from "ethers"
const wallet = new ethers.Wallet(process.env.BUYER_PRIVATE_KEY!)
const fetchWithPayment = createX402bClientFetch({
signer: wallet,
preferredTokenAuth: ["ERC3009", "Permit2", "Permit"],
preferredFulfillment: ["inline", "ipfsPointer"],
maxValue: { token: USDC_ADDRESS, amount: 5_000_000n }, // ≤ 5 USDC
})
const res = await fetchWithPayment("https://api.example.com/premium-data")
if (!res.ok) {
console.error("payment failed:", await res.text())
process.exit(1)
}
const asset = await res.json()
console.log("got it:", asset)What just happened
- Plain GET → server returned 402 with a Boson escrow option.
- Client signed a meta-tx + ERC-3009 token authorization.
- Re-issued with
X-PAYMENTheader. - Server forwarded to the facilitator → on-chain commit → atomic redeem.
- Server returned the asset inline.
Common gotchas
- No matching token-auth — if the server advertises only
approveand your client only accepts signed authorizations, the call fails. Loosen preferences or fall back to a manual approve. - Server's facilitator is down — you'll get 503 from the server. Retry with backoff; ultimately, you may need to find a different seller.