Are you an LLM? Read llms.txt for a summary of the docs, or llms-full.txt for the full context.
Recipe — x402 buyer paying for a digital asset · Boson Protocol
Skip to content

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

  1. Plain GET → server returned 402 with a Boson escrow option.
  2. Client signed a meta-tx + ERC-3009 token authorization.
  3. Re-issued with X-PAYMENT header.
  4. Server forwarded to the facilitator → on-chain commit → atomic redeem.
  5. Server returned the asset inline.

Common gotchas

  • No matching token-auth — if the server advertises only approve and 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.

Related