services
Get a key

library / AI and blockchain / Agent payments / SI0100

x402 payment requirements check

A client-side check of an x402 payment requirements object before an agent pays: whether the asset is a real mint, whether the amount fits its decimals, and whether payTo can receive it. A read-only Solana example in one TypeScript file.

By Carbium · Agent payments · SI0100 · updated 2026-11-22

01

Fields of a 402 response

When an x402 server wants payment, it answers 402 Payment Required with one or more payment options. Each option is a requirements object. The client picks one it can meet, signs a transaction for it and sends the payment back. Before that signature exists, only the server's own words say what the payment will be.

FieldMeaningClient's question
schemeHow the payment is made; exact asks for one fixed amountDoes my client implement it?
networkThe cluster as a CAIP-2 id; mainnet is solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdpIs it the cluster my RPC reads?
assetMint address of the tokenIs it a real mint, and one I accept?
amountBase units as a decimal stringDoes it fit the mint's decimals and my ceiling?
payToWallet that receives the paymentCan it receive this token?
extraExtras the scheme defines, such as a fee payerHave I read it before signing?

The server writes every one of those values. A client that signs whatever arrives hands its funds to whoever controls that text, whether the server is hostile, compromised or only wrong about a decimal. The preflight below reads the terms against the chain first. It is the client-side partner of the verifier in x402 payment verifier, which reads a landed payment from the server's side.

$Field names differ a little between x402 versions. The table and the file use version 2, where the amount is amount and the network is a CAIP-2 id. Version 1 calls the amount maxAmountRequired and writes the network as solana. The checks care about meaning, so map the names your version uses.
02

The checks and why each

The four checks share two chain reads, and the allow-list check reads nothing. Each one answers a question the server cannot answer for you.

CheckChain readWhy it matters
Asset is a mintgetAccountInfo on asset as jsonParsed: owned by the Token program or Token-2022, parsed type mintA wallet, a token account or a missing account cannot be paid in, whatever the field claims
Asset is acceptedThe address against your allow-listAnyone can create a mint with any name, so the chain shows a mint and never that it is the one you mean
Amount fitsDecimals from the mint; amount is digits only, above zero and at most one whole tokenThe same number is 1 USDC at 6 decimals and a thousandth of a token at 9, so the ceiling converts through the mint's decimals
payTo can receivegetTokenAccountsByOwner for payTo with the mint filter: at least one account in state initializedA wallet with no account for the mint needs one created, and a frozen account refuses transfers

A wallet can own more than one token account for one mint, so the answer is a list and the check counts the initialized entries. One open account shows the wallet has used the mint. It does not show where the payment will land, so a stricter client derives the associated token address and looks for it in the list. Token accounts by owner covers the listing call.

A preflight makes two reads per requirements object, both at finalized commitment: getAccountInfo, an account read at 10 cells, and getTokenAccountsByOwner. An account's keys share one budget.

03

The worked example

No x402 server is needed to run it. main.ts builds a requirements object for USDC with an amount of 0.01 USDC, finds a payTo on its own and runs the four checks. It then runs them again on a tampered copy to show that each one can fail. Pass a wallet address as the first argument to skip the search. Node 24 runs the file and @solana/kit 8.6.0 makes the calls.

main.ts
// SI0100 · x402 payment requirements check// https://carbium.sh/library/si/x402-payment-requirements-check// Copyright (c) Carbium Corporation. MIT License (LICENSE). Keep this notice.// SPDX-License-Identifier: MIT// x402 payment requirements preflight, read-only. Run: CARBIUM_KEY=... node main.ts [payTo]import { address, createDefaultRpcTransport, createSolanaRpcFromTransport } from "@solana/kit";const key = process.env.CARBIUM_KEY;if (!key) {  console.error("Set CARBIUM_KEY to your Carbium API key.");  process.exit(1);}const url = process.env.CARBIUM_RPC_URL ?? "https://services.carbium.sh";const rpc = createSolanaRpcFromTransport(createDefaultRpcTransport({ url, headers: { "x-api-key": key } }));const USDC = "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v";const TOKEN_PROGRAMS = ["TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA", "TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb"];const TRUSTED = [USDC];type Req = { scheme: string; network: string; asset: string; amount: string; payTo: string };type Mint = { owner: string; data: { parsed?: { type: string; info: { decimals: number } } } };type Held = { account: { data: { parsed: { info: { state: string } } } } };// The demo has no 402 server, so take a wallet that just received USDC.async function findPayTo(): Promise<string> {  const listed = await rpc.getSignaturesForAddress(address(USDC), { limit: 10, commitment: "finalized" }).send();  for (const s of listed.filter((n) => !n.err).slice(0, 3)) {    const tx = await rpc      .getTransaction(s.signature, { commitment: "finalized", encoding: "jsonParsed", maxSupportedTransactionVersion: 1 })      .send()      .catch(() => undefined);    const owner = tx?.meta?.postTokenBalances?.find((b) => b.mint === USDC && b.owner)?.owner;    if (owner) return owner;    console.log(`skip ${s.signature.slice(0, 12)}: ${tx === null ? "null from getTransaction" : "no USDC owner"}`);    await new Promise((done) => setTimeout(done, 4500));  }  throw new Error("no USDC owner found in the newest transactions");}async function preflight(r: Req) {  const [mint, accounts] = await Promise.allSettled([    (async () => rpc.getAccountInfo(address(r.asset), { encoding: "jsonParsed", commitment: "finalized" }).send())(),    (async () =>      rpc.getTokenAccountsByOwner(address(r.payTo), { mint: address(r.asset) }, { encoding: "jsonParsed", commitment: "finalized" }).send())(),  ]);  for (const s of [mint, accounts]) {    if (s.status === "rejected") console.log("  call failed:", s.reason instanceof Error ? s.reason.message : s.reason);  }  const info = mint.status === "fulfilled" ? (mint.value.value as unknown as Mint | null) : null;  const parsed = info?.data.parsed;  const decimals = parsed?.type === "mint" ? parsed.info.decimals : undefined;  const held = accounts.status === "fulfilled" ? (accounts.value.value as unknown as Held[]) : [];  const open = held.filter((h) => h.account.data.parsed.info.state === "initialized").length;  const ceiling = 10n ** BigInt(decimals ?? 0); // one whole token, in base units  const fits = decimals !== undefined && /^\d+$/.test(r.amount) && BigInt(r.amount) > 0n && BigInt(r.amount) <= ceiling;  const checks: [string, boolean, string][] = [    ["asset is a token mint", decimals !== undefined && TOKEN_PROGRAMS.includes(info?.owner ?? ""), `decimals ${decimals}`],    ["asset is on the allow-list", TRUSTED.includes(r.asset), r.asset.slice(0, 8)],    ["amount fits the decimals", fits, `${r.amount} of at most ${ceiling} base units`],    ["payTo has an open account for the mint", open > 0, `${open} of ${held.length} initialized`],  ];  for (const [name, ok, why] of checks) console.log(ok ? "pass" : "fail", name, `(${why})`);}try {  const payTo = process.argv[2] ?? (await findPayTo());  const good: Req = { scheme: "exact", network: "solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp", asset: USDC, amount: "10000", payTo };  console.log("requirements", JSON.stringify(good));  await preflight(good);  console.log("tampered copy");  await preflight({ ...good, asset: payTo, amount: "0.01", payTo: USDC });} catch (e) {  console.error("failed:", e instanceof Error ? e.message : e);  process.exitCode = 1;}

run: node main.ts

To find a payTo, the file lists the newest signatures of the USDC mint, reads up to 3 successful ones with getTransaction as jsonParsed and takes the first owner in postTokenBalances. Pages from getSignaturesForAddress come from an address index that reaches below the node's ledger floor, so a listed signature can come back null. The file prints a skip line and moves to the next one. maxSupportedTransactionVersion: 1 is set because mainnet carries v1 transactions, and the call answers -32015 for one without it.

getTransaction runs at 0.24 req/s on a Free key, so the file waits 4.5 s between lookups. The two chain reads of a preflight run through Promise.allSettled. A call that fails prints its error, and the checks that needed it print fail.

The first block of output shows four pass lines for the real USDC terms. The tampered copy swaps asset for a wallet address, writes the amount as 0.01 and points payTo at the mint, and all four lines print fail.

04

What to refuse

Treat a check that could not run as a failed check. A 429 or a timeout says nothing about the terms, and signing on silence is the mistake to avoid.

  • An asset that is not a mint, or not on your allow-list. Never swap in a similar token.
  • An amount with a decimal point, a sign, an exponent or a zero value, or one above your ceiling. Convert whole tokens to base units yourself before comparing.
  • A payTo with no initialized account for the mint, unless you have decided to pay for the account's creation.
  • A network or scheme your client does not implement. The file leaves those two to your client's own list.
!A pass means the terms are well formed and payable. It does not mean the server is honest or will serve the resource after payment.
05

Where it ends

  • It reads terms. It does not prove the server will deliver, and it does not build, sign or send the payment.
  • The allow-list is your decision. The chain shows that an address is a mint, and anyone can create one with any name.
  • Decimals are read and extensions are not. A Token-2022 mint can carry a transfer fee that changes what arrives; Transfer fee calculator computes it.
  • State moves. An account can be frozen or closed between the preflight and the send, so run it again just before signing. x402 payment verifier checks the result afterwards.
  • The payTo search exists for the demo. A real client takes payTo from the 402 response, and the signature listing reaches back 30 days at most.
  • The example reads the chain through the RPC endpoint and talks to no x402 server or facilitator.
06

When it goes wrong

what goes wrongwhat to do
A listed signature answers -32015 from getTransaction.The transaction is v1 and the call left maxSupportedTransactionVersion out or set it to 0. Set it to 1. The failed call is uncharged.
getTransaction returns null for a signature the list just gave.The list reaches below the validator's ledger floor, so an older signature can be listed and missing. Skip it and try the next one, as the file does for up to 3.
Every read fails with 401.The key was left off or cut short. Send the whole key in the x-api-key header. The file exits before any call when CARBIUM_KEY is unset.
Reads fail with 429 during a run.Wait for the retry-after hint and run again. The file prints the failed call and reports its checks as fail, so never sign on a check that could not run.
A wallet that has held USDC shows 0 open accounts.The 402 may carry a token account address in payTo where a wallet is expected. Read that account with getAccountInfo and use its owner.
The preflight passes and the payment then fails.An account can be frozen or closed in between. Run the preflight again just before signing, and have the server side verify the landed payment.
07

Questions

Does the preflight replace the facilitator's checks?

No. It reads the terms before anything is signed. A facilitator or a server-side verifier reads the payment afterwards, and the two cover different moments.

Why read decimals from the mint?

amount is in base units, so its size depends on the mint's decimals, and the 402 response does not carry them. A mint's decimals are fixed at creation, so one read settles it.

What should a client do when a 402 lists several payment options?

It picks one it can meet, so it drops options whose scheme or network its client does not implement. It runs the preflight on each remaining option and pays with one that passes all four checks.

How many RPC calls does one run make?

Two per requirements object, and the run checks two objects. Finding a payTo adds one getSignaturesForAddress at 50 cells and up to 3 getTransaction calls at 50 cells each.

Does it work for Token-2022 mints?

The mint check accepts both token programs and reads decimals. It does not read extensions such as a transfer fee.