---
id: SI0008
title: "x402 payment verifier"
url: https://carbium.sh/library/si/x402-payment-verifier
collection: AI and blockchain
category: Agent payments
revision: 1
updated: 2026-11-22
author: Carbium
code: MIT (LICENSE in the zip); text: all rights reserved, Carbium Corporation
---

# x402 payment verifier

x402 turns HTTP 402 into a payment step: the client retries with a signed transaction and the server or a facilitator submits it. The server's read-only check confirms the payment landed, paid enough to the right address and was never used before.

## What x402 asks of a Solana server

x402 puts payment inside an HTTP exchange. A client asks for a resource and the server answers `402 Payment Required` with the terms it accepts. In the standard x402 flow the client asks again with a signed transaction in the payment header, and the server or a facilitator submits it and serves the resource once it lands. On Solana the payment is usually a USDC transfer.

A facilitator service can check and settle the payment for you. The verifier below is the check you run yourself when you want to read the result off the chain: given a transaction signature, it decides whether that transaction paid you. It holds no key, signs nothing and sends nothing.

## The four checks

| Check | How the code does it | Refusal it returns |
|---|---|---|
| Never used before | Looks the signature up in a SQLite table first, and inserts it only after every other check passes | `already used` |
| Landed and succeeded | `getTransaction` at finalized, with `meta.err` empty | `not at finalized yet, retry` or `transaction failed` |
| Fresh | Block time within `MAX_AGE_S` seconds of now, 300 by default | `older than 300 s` or `no block time, retry` |
| Paid enough | The recipient's USDC balance after the transaction minus its balance before, at least the price in base units | `paid 0 of 1` |

The paid check reads `preTokenBalances` and `postTokenBalances` from the transaction meta. Those lists hold every token balance the transaction touched, with its owner and mint. Summing the recipient's entries for the mint before and after gives the net amount received, whatever instructions produced it: a plain transfer, a transfer that created the recipient's token account, or a call routed through another program. A transaction that pays the recipient 1 USDC and takes 0.4 back counts as 0.6. [SPL token balance](https://carbium.sh/library/howsolana/spl-token-balance) reads one token account's balance directly.

Amounts are integers in base units. USDC has 6 decimals, so 1,000,000 base units is 1 USDC, and the code uses `BigInt` for every amount.

The used-before lookup runs first and costs nothing. A `getTransaction` call costs 50 cells, so a client that sends junk or repeated signatures is refused before the call. The SQLite insert at the end is the atomic guard when two requests carry the same signature at once.

## The verifier file

One file. Node 24 runs the TypeScript directly, `node:sqlite` holds the used signatures and `@solana/kit` 8.6.0 makes the RPC calls. `PAID_DB` names the database file and defaults to `:memory:`, so a demo run leaves nothing behind. `MAX_AGE_S` sets the age limit in seconds and defaults to 300.

`main.ts` (run: `node main.ts`)

```ts
// SI0008 · x402 payment verifier
// https://carbium.sh/library/si/x402-payment-verifier
// Copyright (c) Carbium Corporation. MIT License (LICENSE). Keep this notice.
// SPDX-License-Identifier: MIT

// x402 payment verifier, read-only. Run: CARBIUM_KEY=... node main.ts [payTo] [minBaseUnits] [signature]
import { address, createDefaultRpcTransport, createSolanaRpcFromTransport, getAddressEncoder, getProgramDerivedAddress, isSignature, type Signature } from "@solana/kit";
import { DatabaseSync } from "node:sqlite";

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 = "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA";
const ATA_PROGRAM = "ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL";
const maxAge = Number(process.env.MAX_AGE_S ?? 300);
const db = new DatabaseSync(process.env.PAID_DB ?? ":memory:");
db.exec("CREATE TABLE IF NOT EXISTS paid (sig TEXT PRIMARY KEY)");

type Balance = { mint: string; owner?: string; uiTokenAmount: { amount: string } };
const held = (list: readonly Balance[] | null | undefined, owner: string) =>
  (list ?? []).filter((b) => b.mint === USDC && b.owner === owner).reduce((n, b) => n + BigInt(b.uiTokenAmount.amount), 0n);
const no = (reason: string) => ({ ok: false, reason });
const getTx = (sig: Signature) =>
  rpc.getTransaction(sig, { commitment: "finalized", encoding: "json", maxSupportedTransactionVersion: 1 }).send();

export async function verify(sig: string, payTo: string, price: bigint) {
  if (!isSignature(sig)) return no("not a signature");
  if (db.prepare("SELECT 1 FROM paid WHERE sig = ?").get(sig)) return no("already used");
  const tx = await getTx(sig).catch(() => undefined);
  if (tx === undefined) return no("rpc unavailable, retry");
  // null: still landing, or below the node's ledger floor
  if (tx === null) return no("not at finalized yet, retry");
  if (tx.meta?.err) return no("transaction failed");
  if (tx.blockTime === null) return no("no block time, retry");
  if (Date.now() / 1000 - Number(tx.blockTime) > maxAge) return no(`older than ${maxAge} s`);
  const paid = held(tx.meta?.postTokenBalances, payTo) - held(tx.meta?.preTokenBalances, payTo);
  if (paid < price) return no(`paid ${paid} of ${price}`);
  const spent = db.prepare("INSERT OR IGNORE INTO paid (sig) VALUES (?)").run(sig);
  return Number(spent.changes) === 1 ? { ok: true, reason: `paid ${paid}` } : no("already used");
}

if (import.meta.main) {
  const pause = () => new Promise((done) => setTimeout(done, 4500));
  try {
    let [payTo, min = "1", one] = process.argv.slice(2);
    if (!payTo) {
      // No argument: take a recipient whose USDC balance rose in one of the newest USDC transactions.
      const newest = await rpc.getSignaturesForAddress(address(USDC), { limit: 25, commitment: "finalized" }).send();
      for (const s of newest.filter((n) => !n.err).slice(0, 3)) {
        await pause();
        const skip = (why: string) => console.log(`skip ${s.signature.slice(0, 12)}: ${why}`);
        const tx = await getTx(s.signature).catch((e) => { skip(`error ${e instanceof Error ? e.message : e}`); return undefined; });
        if (tx === null) skip("null from getTransaction");
        const to = tx?.meta?.postTokenBalances?.find(
          (b) => b.mint === USDC && held(tx?.meta?.postTokenBalances, b.owner ?? "") > held(tx?.meta?.preTokenBalances, b.owner ?? ""),
        )?.owner;
        if (tx && !to) skip("no balance rise");
        if (to) { payTo = to; one = s.signature; break; }
      }
      if (!payTo) throw new Error("no USDC recipient found in the newest transactions");
    }
    // A USDC transfer to an existing token account does not list the owner wallet, so list the token account.
    const enc = getAddressEncoder();
    const [ata] = await getProgramDerivedAddress({
      programAddress: address(ATA_PROGRAM),
      seeds: [payTo, TOKEN, USDC].map((a) => enc.encode(address(a))),
    });
    const sigs: string[] = one
      ? [one]
      : (await rpc.getSignaturesForAddress(ata, { limit: 3, commitment: "finalized" }).send())
          .filter((s) => !s.err)
          .map((s) => s.signature);
    console.log(`${sigs.length} signature(s) for ${ata}`);
    for (const sig of sigs) {
      await pause();
      const v = await verify(sig, payTo, BigInt(min));
      console.log(sig.slice(0, 12), v.ok ? "ACCEPT" : "REFUSE", v.reason);
      if (!one && v.reason.startsWith("not at finalized")) console.log("  listed at finalized but missing from getTransaction: below the ledger floor");
      if (v.ok) console.log("again:", (await verify(sig, payTo, BigInt(min))).reason);
    }
  } catch (e) {
    console.error("failed:", e instanceof Error ? e.message : e);
    process.exitCode = 1;
  }
}
```

`verify` is the function to import. The main block is a demo that takes a recipient wallet address, a price in base units and optionally one signature. With a signature it verifies that one. With only a wallet it derives the wallet's USDC token account with `getProgramDerivedAddress`, lists that account's last 3 successful signatures with `getSignaturesForAddress` and verifies each. With no argument it lists the USDC mint's 25 newest signatures, tries the first 3 that succeeded, takes a wallet whose USDC balance rose in one of them and verifies that signature. A candidate it skips prints one line saying whether `getTransaction` returned null, raised an error or showed no balance rise. It prints `ACCEPT` or `REFUSE` and the reason, and a larger `MAX_AGE_S` lets it check older signatures. It lists the token account because a USDC transfer to an existing token account does not carry the owner wallet among its account keys, so the wallet's own signature list would miss it. After the first `ACCEPT` the demo submits the same signature again, and the replay refusal comes from the table with no RPC call.

The list reaches below the node's ledger floor, so a signature it shows at finalized can come back null from `getTransaction`. The verifier answers `not at finalized yet, retry` for it, and the demo adds a line saying the signature was listed at finalized but is missing from `getTransaction`, so it sits below the ledger floor.

`isSignature` from `@solana/kit` rejects malformed input before any call. The demo waits 4.5 s before each `getTransaction` call so a Free key can run it, because that method runs at 0.24 req/s there.

## Answering the client

Wire `verify` into the retry the client sends after a 402. In your handler, map the verdict like this.

- `ok: true`: serve the resource.
- `already used`, `transaction failed`, `older than ...` or `paid ... of ...`: answer 402 again with the same terms and put the reason in the body.
- `not at finalized yet, retry`: answer 503 with a short retry-after, since the transaction may still be landing, and stop after a fixed number of attempts per signature.
- `rpc unavailable, retry` or `no block time, retry`: answer 503 too.

> Never turn your own RPC trouble into a 402. The client already paid, and a 402 tells it to pay again.

## Commitment, cost and waiting

Both calls ask for the `finalized` commitment. The server's default is finalized, but `@solana/kit` 8.6.0 fills in confirmed when a call leaves commitment out, so naming it keeps the choice in the file. A paid resource should go out only on a payment that cannot be rolled back, and finalized now lands within a slot of the first sighting, so waiting for it costs little.

A client that submits its signature as it sends the transaction may arrive before it lands. The verifier answers `not at finalized yet, retry` and the client tries again. To wait on the server instead, open a `signatureSubscribe` on the WebSocket endpoint with `?api-key=` in the URL. It sends one confirmation and the subscription ends. A signature subscription opens at 5 credits, then costs 20 credits per MiB sent.

A verification is one `getTransaction` call at 50 cells. The demo adds one `getSignaturesForAddress` at 50 and, when it picks a recipient itself, up to 3 more `getTransaction` calls. [Limits are per account](https://carbium.sh/docs#limits), so an account's keys share one budget with the rest of your services. `@solana/kit` raises an error on a non-200 answer, and the file maps every error to `rpc unavailable, retry`, so a 429 from the RPC reaches your handler as that reason and gets a 503. A JSON-RPC error such as -32015, the answer for a v1 transaction when `maxSupportedTransactionVersion` is below 1, lands in the same catch, so a handler that counts retries per signature also caps this path. [RPC rate-limit alerts](https://carbium.sh/library/usecase/rpc-rate-limit-alerts) covers alerting on those limits.

## Where it ends

- The check proves that a transaction paid your address. It does not say who paid: the fee payer can be a third party, so the code never compares senders.
- One signature buys once, but any 1 USDC payment can buy any 1 USDC resource. To bind a payment to a request, put a unique reference in the 402 terms, require it in the transaction and check for it here. The file does not.
- It starts from a signature. In the standard flow the client sends a signed transaction in the payment header, and the signature exists only after someone submits it. This file checks the result of that submission. It does not simulate or submit an unsent payment.
- It reads SPL token balances. A SOL payment needs the same difference taken over `preBalances` and `postBalances`.
- `getSignaturesForAddress` reaches back 30 days at most, from Carbium's own address index. An empty page past that only shows the index's age limit.
- The table lives in one SQLite file. Processes on one host can share it because the insert is atomic. Several hosts that serve one price list need a shared database.

## When it goes wrong

| What goes wrong | What to do |
|---|---|
| A client that just paid gets `not at finalized yet, retry` on its first request. | Answer 503 with a short retry-after and let the client send the same signature again, since the transaction may still be landing. A signature from below the node's ledger floor also returns null, so a stale signature gets `retry` forever. Count attempts per signature and stop after a fixed number, such as 10, then answer 402 with the reason: the transaction probably never landed and the client should check its own send. |
| A payment that landed is refused with `paid 0 of 1`. | Balances match on the owner wallet address and the USDC mint. A payment to another wallet, or in another token, nets zero for yours. Compare `payTo` and the mint constant with the terms in your 402. |
| One payment buys two things. | The table stops a signature from being used twice. Two different requests can still share one payment unless the transaction carries a reference unique to the request, so add one to the terms and check for it. |
| After a restart the verifier accepts old signatures again. | The default database is in memory. Set `PAID_DB` to a file path. The age limit still refuses anything older than `MAX_AGE_S`, so the exposure is the last 300 s at most. |
| A burst of junk signatures spends the account's budget. | The signature shape check and the table lookup run before the RPC call, so malformed and repeated input costs nothing. Add a per-client rate limit in front, because an account's keys share one budget. |
| A 429 from the RPC reaches the client as a 402. | Map `rpc unavailable, retry` to 503. The client has paid, and a 402 tells it to pay again. |

## Questions

### Does an x402 server on Solana need a facilitator?

No. A facilitator checks and settles payments as a service. This verifier is the check you run yourself against the chain, and it fits when the client pays on its own or when a facilitator settled and you want to confirm the result.

### Which commitment should a payment check use?

This file asks for finalized, because the resource goes out on that answer and a finalized payment cannot be rolled back. @solana/kit 8.6.0 fills in confirmed when a call leaves commitment out, so name it in every call.

### Can I accept SOL instead of USDC?

Not with this file, which reads token balances. A SOL version takes the same before-and-after difference over the recipient's entries in `preBalances` and `postBalances`, found through the transaction's account keys.

### How much does one verification cost?

One `getTransaction` call, 50 cells, drawn from the budget your account's keys share. A replay or a malformed signature costs nothing because it is refused before the call.

### Can I list payments to my address instead of waiting for signatures?

Yes. List your USDC token account with `getSignaturesForAddress` and verify each signature it returns, as the demo does. The age limit refuses old ones, and a listed signature can still come back null from `getTransaction`.

## Related

- [SPL token balance](https://carbium.sh/library/howsolana/spl-token-balance) (How to use Solana, HS0001)
- [RPC rate-limit alerts](https://carbium.sh/library/usecase/rpc-rate-limit-alerts) (Use cases, UC0001)
- [carbium.sh/docs#rpc](https://carbium.sh/docs#rpc)
- [carbium.sh/docs#limits](https://carbium.sh/docs#limits)
- [carbium.sh/docs#auth](https://carbium.sh/docs#auth)
- [carbium.sh/docs#endpoints](https://carbium.sh/docs#endpoints)
- [carbium.sh/docs#websocket](https://carbium.sh/docs#websocket)
