Are you an LLM? Read llms.txt for a summary of the docs, or llms-full.txt for the full context.
Buyer side (x402-client) · Boson Protocol
Skip to content

Buyer side (x402-client)

A buyer's code (an agent, a CLI, a server) needs to:

  1. Issue a normal HTTP request.
  2. Handle a 402 Payment Required response by signing a Boson escrow payment.
  3. Re-issue the request with an X-PAYMENT header.

The x402-client package handles steps 2 and 3 transparently.

Fetch adapter

The simplest integration is x402-client-fetch, which wraps fetch:

import { createX402bClientFetch } from "@bosonprotocol/x402-client-fetch"
import { ethers } from "ethers"
 
const wallet = new ethers.Wallet(process.env.PRIVATE_KEY!)
const fetchWithPayment = createX402bClientFetch({
  signer: wallet,
  // Optional: pick token-auth + fulfillment preferences
  preferredTokenAuth: ["ERC3009", "Permit2", "Permit"],
})
 
const res = await fetchWithPayment("https://api.example.com/premium-thing")
console.log(await res.json())

When the upstream returns 402, the wrapper signs and retries automatically.

Lower-level API

If you're not using fetch, use the core x402-client:

import { createX402bClient } from "@bosonprotocol/x402-client"
 
const client = createX402bClient({ signer: wallet })
 
const challenge = parseChallenge(rawResponse)  // your HTTP lib's job
const payment = await client.buildPayment(challenge)
// payment is the value for the X-PAYMENT header

Preferences

PreferenceWhat it controls
preferredTokenAuthOrder in which to try ERC-3009 / Permit / Permit2 / approve
preferredFulfillmentOrder in which to pick inline / email / XMTP / webhook / IPFS
maxValueReject challenges asking for more than this
allowAtomicRedeemWhether to accept atomic commit-and-redeem flows

Common gotchas

  • Token-auth mismatch. If the seller doesn't advertise any of your preferred strategies, the client throws. Have a fallback.
  • Network mismatch. The 402 specifies a chain; your wallet must be on it.
  • Repeated 402s. If the seller's facilitator is down, you'll get 402 forever. Cap retries.

Next