# Agent quickstart: pay x402 APIs privately with px402

This guide is for you if your AI agent pays x402 APIs and you do not want those payments to
publish what it buys. It walks through the TypeScript wallet, `px402`, from a new seed to
a paid call, and through what goes wrong.

## What px402 does for you

Your agent pays with blind-signed coins withdrawn from a reserve you fund once, so nobody
watching the chain or the px402 services can link a payment to your deposit, or link two of your
payments to each other by address. It pays two kinds of x402 merchant:

- **A merchant whose 402 has a px402 entry** is paid directly. It names a px402 facilitator in
  its x402 terms and receives plain USDC from a relayer.
- **A merchant that quotes only `exact`**, as nearly every x402 merchant does today, is paid
  through a **bridge facilitator** that you name: a relayer signs the merchant's USDC transfer
  authorization and your wallet delivers it. The merchant changes nothing
  ([section 6](#paying-a-merchant-that-quotes-only-exact)).

Pre-fund early: your deposit and each withdrawal are public on chain, and a payment made soon
after your own withdrawal can be matched to it by timing when few other wallets withdraw in
between (section 4).

Every TypeScript block below is an excerpt of a file in [`examples/`](../examples/), which
ships in this package (`node_modules/px402/examples/`). Every release typechecks those files
against the SDK and checks that each block here still matches them.

**Two ways in.** [The drop-in](#the-drop-in-three-lines-funded-once) is x402's own three lines:
give `wrapFetchWithPayment` a private key or an account and it funds itself from that key's
address, withdraws, waits out the hold and pays. Sections 1 to 12 are the explicit path: a seed
of the agent's own, a depositor whose key never enters the SDK, and every step in view. Both
pay the same merchants through the same services.

### Which path does my merchant need?

Ask the merchant's URL once without paying and read its 402. This line works the same in bash
and PowerShell; it prints the status, the decoded `PAYMENT-REQUIRED` header when there is one,
then the body:

```bash
node -e "fetch(process.argv[1]).then(async (r) => { const h = r.headers.get('payment-required'); console.log(r.status, h ? Buffer.from(h, 'base64').toString() : 'no PAYMENT-REQUIRED header'); console.log(await r.text()); })" https://api.example.com/data
```

| What the 402's `accepts[]` holds | How px402 pays it | What you configure |
|---|---|---|
| An entry with `"scheme": "batch-settlement"`, `extra.binding: "px402"` and `extra.tier: 0` | Directly, through the facilitator the entry names (`extra.facilitator`) | Nothing beyond the issuer and registry |
| Only `"scheme": "exact"` entries, in USDC on your wallet's chain or in a token on another network the bridge facilitator lists, with `maxTimeoutSeconds` of 120 or more | Through the bridge ([section 6](#paying-a-merchant-that-quotes-only-exact)) | Nothing: the bridge facilitator defaults to PRXVT's `https://facilitator.prxvt.com`. `PX402_BRIDGE_FACILITATOR` names another, one whose `/supported` lists the merchant's token |
| Neither; `exact` only on a network the bridge facilitator does not list; or a `maxTimeoutSeconds` under 120 (too short for a relayer's authorization to reach the merchant) | Not paid: the 402 comes back as it arrived | |

x402 comes in two forms. **Version 1** puts the requirements in the JSON body: `x402Version: 1`,
a network name (`"base"`), the price in `maxAmountRequired`. **Version 2** puts them,
base64-encoded, in the `PAYMENT-REQUIRED` response header: a CAIP-2 network (`"eip155:8453"`),
the price in `amount`; the body may repeat them. When a 402 carries both, the wallet reads the
header first, pays under version 2 and sends the payment in `PAYMENT-SIGNATURE`; from a version 1
body alone it sends `X-PAYMENT`. A px402 entry is read
from the JSON body, and a 402 that offers px402 at all is never paid through the bridge. In code,
`quotedPrice(response, { network, bridgeFacilitator })` reads a 402 the way the paid fetch with
that bridge facilitator does (it reads the facilitator's `/supported` for the networks it pays
on) and returns the price, the path (`"px402"` or `"exact"`) and the version; the demo agent
calls it before it starts the wallet. Without `bridgeFacilitator` it quotes only an `exact`
entry on `network`. A wallet already open has `wallet.quotedPrice(response, { bridge })`, which
reads through the wallet's own `/supported` cache.

## The drop-in: three lines, funded once

x402's client pays with `wrapFetchWithPayment(fetch, account)`. So does px402's
([`examples/three-lines.ts`](../examples/three-lines.ts)):

```ts
import { wrapFetchWithPayment } from "px402";
// …
const pay = wrapFetchWithPayment(fetch, account);
const res = await pay(process.argv[2] ?? "https://api.example.com/data");
```

`account` is a `0x` private key, or an account object (a viem local account is one). The
returned `fetch` pays a merchant's own px402 entry directly and a merchant that quotes only
`exact` through the bridge, and passes anything that is not a 402 through untouched. Calling
`wrapFetchWithPayment` does no I/O; the first request starts the wallet beside itself:
recovery, then a first top-up.

**Send USDC to the key's address. That's all.** The wallet deposits from the key's own address,
so that address needs USDC on Base and nothing else. With no ETH there, the deposit is gasless:
the key signs a USDC authorization (EIP-3009) for px402's gasless depositor, and a relayer
submits it through `facilitator.prxvt.com`, paying the gas for a small fee taken out of the
deposit. If you do not know the address, run the agent once: before it sends anything it stops
with `PX402InsufficientFundsError`, naming the address and how much USDC it needs.

The authorization names the wallet's own reserve and the fee, and the depositor recomputes both
from it: the relayer can submit it, delay it or refuse it, and cannot send the USDC anywhere
else. The wallet signs only for the depositor its network names (`gaslessDepositor`,
`PX402_GASLESS_DEPOSITOR`), never one a server suggests, and pays a fee no higher than
`maxSponsorFee`. An address that holds ETH deposits directly (an approve and a `deposit`, no
fee); `gasless: true` makes every deposit gasless, `gasless: false` none. An account that signs
typed data but not transactions funds the wallet gaslessly too.

What the wallet then does on its own:

- **Deposits in whole floats, never the price.** The float (`float`, $5.00 by default) is both
  the coin buffer it keeps and the unit of every deposit: `k × float` from the key's address
  (gaslessly, the reserve is credited `k × float` less the fee): the fewest floats the payment in
  hand needs, net of the fee, else the refill rounded to the nearest float, so an address holding
  one float (and a little more) is enough.
  A $0.37 call and a $4.20 call on an empty wallet both deposit one float; an observer of the
  deposit learns your float, not your price. `maxAutoDeposit` (ten floats by default) caps what
  it deposits in one process (`PX402AutoFundLimitError`). `autoFund: false` turns deposits off:
  then fund the reserve by hand with `wallet.depositTx`, as in section 4.
- **Withdraws by its own refill rule** (section 9), when it starts and again a random moment
  after a payment that left the buffer low: not at the head of the next payment.
- **Waits out the hold.** A payment the buffer cannot cover funds itself, then waits the fresh
  coins' 60 to 120 seconds inside the call instead of throwing `PX402NoCoinsError` (61 seconds in
  the end-to-end test, nearly all of it the hold).

**Start the wallet when the agent boots**, with `createWallet`
([`examples/drop-in.ts`](../examples/drop-in.ts)). It resolves once the first deposit
and withdrawal are done, so the first payment is already funded and spends coins withdrawn long
before it. That distance matters: a payment made soon after its own withdrawal can be matched to
it by timing (section 4).

```ts
export async function bootDropIn(): Promise<Wallet> {
  const wallet = await createWallet({
    privateKey: keyFromEnv("PX402_PRIVATE_KEY"),
    // Base by default; PX402_NETWORK names another network.
    // The receipts (your purchase history) and the recovery checkpoint,
    // across restarts. Without a store they live in memory.
    store: walletStore(DROP_IN_RECEIPTS_FILE),
  });
  // …
  return wallet;
}
```

Pay with that wallet through `wrapFetchWithPayment(fetch, wallet)`, which keeps the funding, the
bridge and the store `createWallet` set up; `wallet.wrapFetch` is the explicit path, with none of
them. `createWallet` also takes `{ account }` or `{ seed }`.

Before a short-lived process exits, `await pay.close()`: it melts the change a payment left and
finishes saving. Skipping it loses nothing (the next start recovers and melts the change); it only
waits until then.

**One key controls the address and the coins.** The wallet's seed is derived from the key that
also holds the USDC: whoever holds the key holds the address's balance, the reserve and the
coins. Keep the key like the funds it controls, and the address's balance near what the agent
spends. (On the explicit path the depositor's key never enters the SDK, so a compromised agent
reaches its reserve and buffer and nothing more.)

Where the seed comes from: the key's signature over a fixed px402 EIP-712 message naming the
chain id, hashed under `"px402/v1/wallet-seed/eip712-signature"`. The wallet is derived per chain
from the key, so the same key gives the same wallet however it is passed.

- **A private key** (hex, or an account exposing `privateKey`, as ethers' `Wallet` does) signs
  the message in the SDK: RFC 6979, the same bytes every time.
- **An account that only signs** (`signTypedData`, as viem's `privateKeyToAccount` does) is
  asked for the signature twice. A signer whose two signatures differ (a KMS, an MPC wallet, a
  smart account) would derive a new wallet on every start, so it is refused with
  `PX402NondeterministicSignerError`: pass `seed` (32 random bytes, kept like a key) instead.
  Never sign that message for any other app: the signature is the key to the coins.
- **`seed`, when given, always wins**; the key then only funds the wallet.

**Where the services are.** On Base (`network: "base"`, the default) the issuer, the registry
and the bridge facilitator default to PRXVT's hosted `https://issuer.prxvt.com`,
`https://registry.prxvt.com` and `https://facilitator.prxvt.com`. The options `issuerUrl`,
`registryUrl` and `bridgeFacilitator` come first, then `PX402_ISSUER_URL`, `PX402_REGISTRY_URL`
and `PX402_BRIDGE_FACILITATOR`, then the preset. The bridge is on whenever a facilitator
resolves; `bridge: false` turns it off. A deployment of your own is passed as a full network
object. As on the explicit path, recovery refuses an issuer whose keyset the reserve did not
commit on chain.

| Option | Default | What it is |
|---|---|---|
| `network` | `PX402_NETWORK`, else `"base"` | A preset's name, or a network object (`chainId`, `reserveContract`, `usdc`, `domainSeparator`, `deployBlock`, `rpcUrl`, `services`). |
| `float` | `"5.00"` | The coin buffer kept and the deposit unit: a USDC amount, or base units as a `bigint`. |
| `maxAutoDeposit` | ten floats | The most deposited on its own while the process runs. |
| `autoFund` | on when the signer can sign transactions or typed data | `false`: never deposit. |
| `gasless` | when the address has no ETH for the gas | `true`: every deposit is gasless; `false`: never. |
| `gaslessDepositor` | `PX402_GASLESS_DEPOSITOR`, else the preset's | The gasless depositor the key signs its USDC authorization for. |
| `sponsorFacilitator` | `PX402_SPONSOR_FACILITATOR`, else the bridge facilitator | Where a gasless deposit is posted (`/deposit/sponsor`) and its fee read (`/supported`). |
| `maxSponsorFee` | `"0.10"` | The most fee one gasless deposit pays: a USDC amount, or base units as a `bigint`. |
| `bridge`, `bridgeFacilitator` | on, PRXVT's facilitator | `false` turns the bridge off. |
| `store` | none | A `WalletStore` (`load`, `save`) for the receipt chain and the recovery checkpoint; `walletStore` in `examples/receipts-file.ts` keeps them in the same files section 8 does. Coins need no store: every start recovers them. |
| `rpcUrl` | `PX402_RPC_URL`, else the preset's public endpoints (on Base, publicnode for reads, `mainnet.base.org` for the deposits) | The chain's JSON-RPC endpoint: recovery's reads and the deposits. Set your own for production. |
| `serviceFetch` | the `fetch` `wrapFetchWithPayment` wraps (`createWallet`: the global `fetch`) | The issuer, the registry, `/supported` and the bridge go through it: route it through a proxy you control (section 11). |
| `rpcFetch` | the global `fetch` | The chain's JSON-RPC calls, deposits included. |
| `walletConfig` | | Anything `px402.recover` takes (`privacy`, `maxFeeBps`, ...). |

| What you see | What it means |
|---|---|
| `PX402InsufficientFundsError` | The key's address has too little USDC (`asset: "USDC"`) for the deposit, or no ETH for gas while no gasless deposit could stand in (`"ETH"`, with the reason); `required` and `available` say how much. Nothing was sent. |
| `PX402SponsorError` | A gasless deposit did not happen: no relayer sponsors the depositor right now (`reason: "unavailable"`), the fee is above `maxSponsorFee` (`"fee"`), a relayer refused the authorization before sending anything (`"refused"`, with `sponsorCode`), or the facilitator did not answer (`"unreachable"`). Nothing left the address. |
| `PX402AutoFundLimitError` | The deposit would pass `maxAutoDeposit`. Nothing was sent. |
| `PX402MissingSettingError` | A network object that names no issuer or registry, with neither an option nor a variable set. It names both. |
| `PX402NetworkNotDeployedError` | The network names no reserve (a network object marked `deployed: false`). Pass one with `reserveContract`, `domainSeparator` and `deployBlock`. |
| `PX402NondeterministicSignerError` | The account signed the seed message twice, differently. Pass `seed`. |

Everything else is the explicit path's own, in section 10. Run the examples with
`node --env-file=.env dist/three-lines.js <url>`, or `dist/drop-in.js <url> [<url> ...]` to
start at boot and pay several; `.env` then needs only `PX402_PRIVATE_KEY`. Write it without
showing it:

```bash
node -e "console.log('PX402_PRIVATE_KEY=0x' + require('node:crypto').randomBytes(32).toString('hex'))" > .env && chmod 600 .env
```

```powershell
node -e "console.log('PX402_PRIVATE_KEY=0x' + require('node:crypto').randomBytes(32).toString('hex'))" | Out-File -Encoding ascii .env
```

The rest of this guide is the explicit path.

## 1. Prerequisites

You need:

- **Node 22 or later.**
- **USDC on Base.** px402 runs on Base (chain id 8453) and takes Circle's native USDC.
- **An EOA with USDC and a little ETH for gas: the depositor.** It funds the reserve with two
  transactions. The SDK never sees its key.
- **The service URLs:** the px402 issuer and registry your agent withdraws from, and a bridge
  facilitator if you will pay merchants that quote only `exact`. All three default to PRXVT's
  hosted services (below). A px402 merchant names its own facilitator in its 402 and the wallet
  reads it from there. A merchant that quotes only `exact` names none, so for those (nearly every
  x402 merchant today) the wallet uses the bridge facilitator: PRXVT's by default, or one you
  name in `PX402_BRIDGE_FACILITATOR`.
- **The reserve contract's address, its `DOMAIN_SEPARATOR()`, the USDC address**, and an RPC
  URL for the chain. The SDK's `base` preset carries all of them, and `chainConfig()` turns it
  into the wallet's `chain` in one call.

| Value | Base |
|---|---|
| Chain id | `8453` (x402 network `eip155:8453`) |
| Reserve, domain separator, deployment block | In the SDK's preset: `networks.base.reserveContract`, `.domainSeparator`, `.deployBlock` (where a recovery scan starts) |
| USDC | `0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913`, Circle's native USDC on Base |
| RPC | The preset reads through `https://base-rpc.publicnode.com` and sends the drop-in's deposits, and reads their receipts, through `https://mainnet.base.org` (publicnode serves no receipts without a token). For production pass your own (`rpcUrl`, or `PX402_RPC_URL`): it serves both. `mainnet.base.org` rate-limits a wallet's first sync and serves at most 500 blocks per `eth_getLogs` |

To print the reserve address: `node -e "import('px402').then((m) => console.log(m.networks.base.reserveContract))"`.

You deposit USDC; the merchants you pay through the bridge are paid in their own token (on Base,
Circle's USDC) by a relayer that holds it.

**Where the services are.** PRXVT runs the px402 services against the Base reserve:

| Service | URL |
|---|---|
| Issuer | `https://issuer.prxvt.com` |
| Registry | `https://registry.prxvt.com` |
| Facilitator (px402 merchants name it in their 402s; the wallet's bridge facilitator) | `https://facilitator.prxvt.com` |

The SDK's `base` preset uses them by default, and the examples too; the variables below point an
agent at others: a deployment of your own, or a proxy in front of these.

**Check that the URLs you use belong to this deployment.**

- **The issuer.** `px402.recover` (and `open`) read the issuer's keyset, recompute its id and
  compare it with what the reserve committed on chain, `keysets(epochId)`, through your own RPC.
  An issuer that is not this reserve's fails with `PX402KeysetCommitmentError` and you get no
  wallet. `node --env-file=.env dist/inspect.js` runs exactly that check and spends nothing.
- **A facilitator.** Its `GET /supported` lists the relayers it pays through
  (`kinds[i].extra.relayers[j].address`). Each should be registered on this reserve, with a bond
  and not revoked:

  ```bash
  cast call <reserve address> "relayers(address)(uint256,uint256,uint16,string,bool,bool)" <relayer address> --rpc-url https://mainnet.base.org
  ```

  prints the bond, the unbonding time, the relayer's `feeBps`, its endpoint, `registered` (should
  be `true`) and `revoked` (should be `false`).

The examples read their configuration from the environment:

| Variable | Required | What it is |
|---|---|---|
| `PX402_SEED` | yes (explicit path) | The wallet seed, 64 hex characters (section 3). |
| `PX402_PRIVATE_KEY` | yes (the drop-in) | The agent's key, 64 hex characters: its address funds the wallet and its seed is derived from it. |
| `PX402_NETWORK` | no | The network: a preset's name or its CAIP-2 id; defaults to `base`. |
| `PX402_ISSUER_URL`, `PX402_REGISTRY_URL` | no | The issuer and the registry; default `https://issuer.prxvt.com` and `https://registry.prxvt.com`. |
| `PX402_BRIDGE_FACILITATOR` | no | The bridge facilitator that pays `exact`-only merchants (section 6); defaults to `https://facilitator.prxvt.com`. |
| `PX402_RPC_URL`, `PX402_CHAIN_ID`, `PX402_RESERVE`, `PX402_USDC`, `PX402_DOMAIN_SEPARATOR`, `PX402_DEPLOY_BLOCK`, `PX402_LOG_BLOCK_RANGE` | no | The chain; each defaults to the network preset's value above (`PX402_LOG_BLOCK_RANGE` to 500). |
| `PX402_RECEIPTS_FILE` | no | Where the receipts go (default `px402-receipts.json`); the recovery checkpoint goes beside it. |

## 2. Install

```bash
npm install px402
```

(Every command in this guide runs as written in bash and in PowerShell, except where a
PowerShell form is given beside it.)

Its only dependencies are `@noble/curves` and `@noble/hashes`. It opens no network connection
of its own: every request goes through a `fetch` you give it, and every chain read through the
RPC endpoint you name (or a function you give it). The drop-in also signs and sends its own
deposit transactions, with the same two libraries, through that same endpoint.

The package is `px402`, and you import from `"px402"`.

### Run the examples in your own project

The examples are TypeScript ES modules (they use top-level `await`), and they ship in this
package: [`examples/`](../examples/), `node_modules/px402/examples/` once installed. In an empty
directory:

```bash
npm init -y
npm pkg set type=module                   # npm init writes "commonjs"; the examples need ESM
npm install px402
npm install -D typescript @types/node
cp node_modules/px402/examples/*.ts .
```

Any current TypeScript builds them: they were checked with 5.9, 6.0 and 7.0 (the SDK itself
builds with 6). Put a `tsconfig.json` beside them:

```json
{
  "compilerOptions": {
    "target": "ES2022",
    "lib": ["ES2022"],
    "module": "NodeNext",
    "moduleResolution": "NodeNext",
    "types": ["node"],
    "strict": true,
    "skipLibCheck": true,
    "outDir": "dist"
  },
  "include": ["*.ts"]
}
```

Then `npx tsc` compiles them to `dist/`. Without `"type": "module"`, `tsc` refuses every file
(`TS1295`, `TS1287`, and `TS1309` for the top-level `await`).

### Keep the seed in `.env`, out of git and out of your shell history

The examples read their configuration from the environment, and Node loads it from a file with
`--env-file=.env` (Node 20.6 and later, on Windows, macOS and Linux alike). Write the seed
straight into that file, so it never appears on screen or in your shell history, and keep the
file out of git together with the purchase history the agent writes:

```bash
printf 'PX402_SEED=%s\n' "$(node dist/seed.js)" > .env && chmod 600 .env
printf '.env\npx402-receipts*.json\n' >> .gitignore
```

```powershell
"PX402_SEED=$(node dist/seed.js)" | Out-File -Encoding ascii .env
Add-Content -Encoding ascii .gitignore ".env", "px402-receipts*.json"
```

In Windows PowerShell 5.1, keep `-Encoding ascii`: its default encodings (UTF-16, or UTF-8 with a
byte-order mark) make Node read the file as holding no variables. `chmod` has no Windows
equivalent here: keep the project in a folder under your user profile, which by default only you,
SYSTEM and administrators can read. That is all the file needs: the issuer, the registry and the
bridge facilitator default to PRXVT's (section 1). To use others, add them with an editor
(Notepad saves plain UTF-8, which is fine):

```text
PX402_SEED=<written by the command above>
PX402_ISSUER_URL=<only for an issuer other than https://issuer.prxvt.com>
PX402_REGISTRY_URL=<only for a registry other than https://registry.prxvt.com>
PX402_BRIDGE_FACILITATOR=<only for a bridge facilitator other than https://facilitator.prxvt.com>
```

Do not `export PX402_SEED=…` (or `$env:PX402_SEED = "…"`) at a prompt: the seed then sits in
your shell history and in the environment of every process the shell starts. In production, give
the agent its seed from a secret manager instead of a file.

Run every example with the file:

```bash
node --env-file=.env dist/fund.js 25.00     # prints the two deposit transactions
node --env-file=.env dist/inspect.js        # recovers and reports; spends nothing
node --env-file=.env dist/agent.js https://api.example.com/data 20000
```

The same lines work in PowerShell. The agent's optional last argument is the most it will pay,
in base units; the price itself comes from the merchant's 402.

## 3. Create a wallet

### The seed

One 32-byte seed derives your reserve key and every coin key. Generate it once per agent
(`node dist/seed.js`, written into `.env` as above) and keep it like a private key:

```ts
import { randomBytes } from "node:crypto";
import { SEED_LEN } from "px402";
import { hex, unhex } from "./bytes.js";

/** A new seed, as the hex you store. Run once per agent. */
export function newSeedHex(): string {
  return hex(new Uint8Array(randomBytes(SEED_LEN)));
}

/** The seed from an environment variable holding 64 hex characters. */
export function seedFromEnv(name: string): Uint8Array {
  const value = process.env[name];
  if (value === undefined || !/^(0x)?[0-9a-fA-F]{64}$/.test(value)) {
    throw new Error(`${name} must hold the 32-byte wallet seed as 64 hex characters`);
  }
  return unhex(value);
}
```

Whoever holds the seed can withdraw your whole reserve balance and sweep it with
`reclaimBalance`. The depositor key is the part an attacker cannot reach: the SDK only ever
builds unsigned transactions for it. So keep the reserve near one refill cycle, not a year of
spending.

### Where the wallet reads the chain

The wallet reads three things from the reserve contract: your reserve's withdraw nonce, the
keyset commitment for an epoch, and, when it recovers, your reserve's deposit history. Give it a
JSON-RPC endpoint and it makes those reads itself, through `chain.rpcFetch` (the global `fetch`
when you pass none). The SDK has no RPC dependency and opens no socket of its own:

```ts
export function walletConfig(seed: Uint8Array, cfg: AgentConfig): WalletConfig {
  return {
    seed,
    // /melt-attempt and /spent are registry routes; everything else is the issuer's.
    issuer: new IssuerClient({ baseUrl: cfg.issuerUrl, registryUrl: cfg.registryUrl, fetch: serviceFetch }),
    chain: {
      chainId: cfg.chainId,
      reserveContract: cfg.reserve,
      usdc: cfg.usdc,
      domainSeparator: unhex(cfg.domainSeparator),
      // The wallet reads the reserve through this endpoint: its withdraw
      // nonce, the keyset commitment open() and recover() check, and, for
      // recovery, the deposit logs from the deployment block.
      rpcUrl: cfg.rpcUrl,
      deployBlock: cfg.deployBlock,
      logBlockRange: cfg.logBlockRange,
    },
    maxFeeBps: MAX_FEE_BPS,
    // prewarm() refills to max(2 h of observed spend, this), jittered ±20 %.
    minRunwayBaseUnits: BUFFER_BASE_UNITS,
    assumedCallCostBaseUnits: TYPICAL_PRICE_BASE_UNITS,
    supportedFetch: serviceFetch,
    // A bridge payment, and its follow-up, go from this wallet to the bridge
    // facilitator: through the same proxy as the rest.
    bridgeFetch: serviceFetch,
    onWarning: (message) => {
      console.warn(`[px402] ${message}`);
    },
  };
}
```

The RPC provider sees which reserve addresses you read: use one you trust, or your own node.
`chain.reserveNonce` and `chain.keysetCommitment` still take readers of your own, and those win
over the endpoint. `domainSeparator` is bytes, not the hex string from the deployment record.
To take every chain value from the SDK's preset instead, pass `chain: chainConfig()`: the
network (`PX402_NETWORK`, else Base), its reserve, the domain separator as bytes, and the RPC
endpoint (`PX402_RPC_URL`, else the preset's).

### Start it with `px402.recover`, every time

```ts
export function recoverWallet(
  seed: Uint8Array,
  cfg: AgentConfig,
  receipts: readonly StoredReceipt[],
  checkpoint?: string,
): Promise<Wallet> {
  return px402.recover({
    ...walletConfig(seed, cfg),
    receipts,
    // On a used seed recovery reads for a minute or more: say what it is doing.
    onProgress: printProgress(),
    // Where the last recovery's log scan reached. A missing, corrupt or
    // implausible one only means the scan starts at the deployment block.
    ...(checkpoint === undefined ? {} : { recoveryCheckpoint: checkpoint }),
  });
}
```

```ts
export async function bootWallet(cfg: AgentConfig = loadConfig()): Promise<Wallet> {
  const started = Date.now();
  const wallet = await recoverWallet(
    seedFromEnv("PX402_SEED"),
    cfg,
    loadReceipts(RECEIPTS_FILE),
    loadCheckpoint(CHECKPOINT_FILE),
  );
  saveReceipts(RECEIPTS_FILE, wallet);
  // Where this recovery's log scan reached: the next start reads only the blocks since.
  saveCheckpoint(CHECKPOINT_FILE, wallet);
  // …
  return wallet;
}
```

The wallet keeps its coins, its withdraw counter and its price history in memory, so every
start is a recovery. On a seed that has never been used, `px402.recover` returns an empty
wallet; on a used one it rebuilds the buffer and resumes the withdraw counter above every coin it
finds. `px402.open` is for a seed that has never been used, and refuses one that has: when the
reserve's withdraw nonce on chain is not zero, or when you pass it stored receipts, it throws
`PX402SeedUsedError`, which names `px402.recover`. (Opened fresh, a used seed would start the
counter at 0 and re-derive coins it already took: its next withdrawal would buy coins that may
already be spent, under keys already used.) `px402.open(config, { fresh: true })` skips that
check. It exists for tests; anywhere else it is the bug it guards against.

Both read the keyset from the issuer, recompute its id and compare it with what the reserve
committed on chain. If they differ they throw `PX402KeysetCommitmentError` and you get no wallet.
Do not work around that error: an issuer that serves you keys nobody else holds can recognise
every coin you spend. With no `rpcUrl` and no `keysetCommitment` reader the wallet cannot check
and only warns.

### When the issuer starts a new key epoch

The issuer's signing keys belong to an epoch: 30 days of withdrawals, after which each coin of
the epoch still spends until 90 days from the epoch's start and can be refreshed for 30 days
more. The operator starts a new epoch on a schedule. **Your agent does nothing:**

- The wallet holds every epoch it has coins of. `px402.recover` reads every epoch the issuer
  lists and checks each against the reserve, so a wallet started after a rotation holds both. A
  process that keeps running notices the new epoch the first time the issuer refuses a withdrawal
  or a refresh under the old one (`KEYSET_UNKNOWN`), reads it, checks it, and carries on.
  `wallet.keysets` lists the epochs held; `wallet.keyset` is the one it withdraws under.
- Old coins keep paying. One payment may mix coins of two epochs; each coin names its own.
- Change from an old coin is refreshed into the new epoch: that is how old coins migrate, with
  nothing beyond spending. A coin whose epoch's spend window has closed is not offered to a
  merchant; the wallet melts it whole into the new epoch.
- Withdrawals use the newest epoch the reserve has committed.
- `readiness()` and `runway()` report the buffer by epoch (`epochs`) while it spans more than one.

The one case that asks something of you is an issuer that lost an epoch's keys (its database)
and so cannot refresh that epoch's coins. The wallet reports it as `PX402EpochRetiredError`:
in `wallet.refresh()`'s `retired`, in `readiness().retiredEpochs`, and through `onWarning`,
naming the epoch, its whole coins and the change it strands. The wallet stops splitting that
epoch's coins and spends them whole, older epochs first, while the registry still accepts them
(until the error's `spendableUntil`); change already stranded comes back only through a recoup
the operator announces. To keep spending an epoch the issuer no longer lists after a restart,
keep a copy of each keyset (`keysetToJson` of each of `wallet.keysets`) and pass them back as
`keysets: savedCopies.map(keysetFromJson)` when you recover; each is checked against the chain
like any other.

### What recovery reads, and how long it takes

With no `sources`, recovery reads the SDK's public ones (`publicRecoverySources`):

- **The issuer's whole public log** (`GET /log`), and looks your coins up in it locally. Reading
  all of it names nothing of yours.
- **The chain**, through `rpcUrl`: `reserves(addr)` for each reserve index the seed derives,
  until 20 in a row were never funded (21 calls for a wallet that uses one reserve), and the
  `Deposit` and `BalanceReclaimed` logs of the funded ones from `deployBlock`, both events in one
  `eth_getLogs` per `logBlockRange` blocks (2,000 in the Base preset; `mainnet.base.org` refuses
  more than 500; a window a node refuses is halved, with a warning). A node's rate limit (HTTP 429, or its
  JSON-RPC code) pauses every call to it, for the node's `Retry-After` or an exponential backoff,
  and fewer go at once (four at most, halved on each limit, grown back as answers come); a call
  refused eight times fails with a retryable `PX402TransportError` that names the RPC's host.
- **The registry's spent total for each coin it finds** (`GET /spent/{coin}`), with the refund
  credit beside it: a refunded payment's value comes back as fresh coins at the wallet's next
  melt. That shows the registry your coins together, from your network address, so send it
  through a proxy (the `IssuerClient`'s `fetch`). It is not read from the registry's public
  `/log`, because that log lists a spend only once a spend root covers it, every 12 hours by
  default on mainnet: a coin spent since then would come back as unspent, and the next payment
  with it would be refused.

The log scan is what takes time, and it grows with the chain: Base adds 43,200 blocks a day,
about 86 calls (16 seconds at the 0.19 s a call measured on 2026-10-05, when a first recovery read
189,065 blocks in 383 calls, 71 seconds). A seed never funded skips the scan: 21
`reserves(addr)` calls, a few seconds. The other phases add the issuer's log (a few pages on a
young deployment) and one registry request per coin the seed has ever held.

Two things keep it short:

- **Progress.** `onProgress` in the recovery config is told each phase as it goes: `issuer-log`
  (entries of the log's size), `reserve-discovery` (each index), `deposit-logs` (blocks done of
  total), `coin-search` (each counter) and `spent-lookups` (done of total). The examples print a
  line per phase and one every five seconds inside one (`printProgress` in `wallet.ts`).
- **The scan checkpoint.** `wallet.recoveryCheckpoint()` returns where the scan reached: per
  funded reserve, the last block it fully read (at least 1,000 blocks below the head, about 33
  minutes on Base), that block's hash, and the deposit and reclaim sums up to it. The examples save it
  beside the receipts (`px402-receipts.checkpoint.json`) and pass it back as
  `recoveryCheckpoint`, so a restart reads only the blocks since: measured right after a full
  recovery, 1,035 blocks in 8 calls, 1.4 seconds; a day later, about 90 calls.

```ts
/** Save where this recovery's log scan reached, atomically. Public data, but it names your reserve. */
export function saveCheckpoint(path: string, wallet: Wallet): void {
  const checkpoint = wallet.recoveryCheckpoint();
  if (checkpoint === undefined) {
    return;
  }
  writeFileSync(`${path}.tmp`, checkpoint, { mode: 0o600 });
  renameSync(`${path}.tmp`, path);
}
```

The checkpoint is trusted for one thing, where to start reading logs (and so for the two sums
before that point, which feed only `wallet.reconcile()`'s chain totals). Which reserves are
funded is still read from `reserves(addr)`; your coins, the withdraw counter and the spent totals
still come from the issuer's log and the registry. And it is used only when it holds up. With no
checkpoint the scan simply starts at the deployment block. One that does not parse, is for
another chain id, reserve contract or deployment block, points past the chain head, or whose
block's hash is not that block's hash on the chain now (a reorganisation, or another chain under
the same id) is set aside with a warning, and that reserve is read from the deployment block.
Losing the file costs one slow start, nothing else. It holds only public data, but it names your
reserve: keep it with the receipts.

To read through your own node or mirrors instead, pass `sources`, an implementation of the
SDK's `RecoverySources` interface (the checkpoint applies only to the public sources).

Run one process per seed. Two processes on one seed present the same coins, and the second
payment is refused `INSUFFICIENT_VALUE`.

## 4. Deposit and pre-fund

### Deposit

`depositTx` returns two unsigned transactions: an ERC-20 `approve` to the reserve, then
`deposit(reserveAddr, amount)`. Send them from the depositor wallet, in that order. `fund.js`
prints them as calldata and as `cast send` commands for Foundry:

```ts
/** What to send, in order: an ERC-20 approve to the reserve, then the deposit. */
export function depositPlan(wallet: Wallet, usdcAmount: string, rpcUrl: string): readonly UnsignedTx[] {
  const { reserveAddr, usdc, amountBaseUnits, approve, deposit } = wallet.depositTx(usdcAmount);
  console.log(`deposit ${usdc} USDC (${amountBaseUnits.toString()} base units) into reserve ${reserveAddr}`);
  // The same two calls with Foundry, signed by your depositor key. Without
  // --rpc-url, cast sends to http://localhost:8545.
  const signer = `--account depositor --rpc-url ${rpcUrl}`;
  console.log(`cast send ${approve.to} "approve(address,uint256)" ${deposit.to} ${amountBaseUnits.toString()} ${signer}`);
  console.log(`cast send ${deposit.to} "deposit(address,uint256)" ${reserveAddr} ${amountBaseUnits.toString()} ${signer}`);
  return [approve, deposit];
}
```

The printed commands sign with the Foundry account `depositor`: create it once with
`cast wallet import depositor --interactive` (it asks for the key and a password, and keeps the
key encrypted under `~/.foundry/keystores`), or replace `--account depositor` with
`--keystore <file>`. A public endpoint that balances several nodes can refuse a transaction sent
right after another from the same account with `nonce too low` (one node lags the other); send
it again.

The deposit is public: anyone can see your depositor fund your reserve address, and how much.
Every later withdrawal is public too: your reserve address, the amount, the time. What nobody can
see is which payments those coins became.

### Pre-fund a buffer with `prewarm`

`prewarm` withdraws coins from your reserve into the wallet's buffer:

```ts
export async function prefund(wallet: Wallet, cost: bigint): Promise<void> {
  const coins = await wallet.prewarm();
  if (wallet.readiness(cost).status === "insufficient") {
    coins.push(...(await wallet.prewarm(cost)));
  }
  const runway = wallet.runway();
  console.log(
    `withdrew ${String(coins.length)} coins; ${runway.heldBaseUnits.toString()} base units in their hold, ` +
      `the first spendable at ${runway.heldUntil === null ? "once" : new Date(runway.heldUntil * 1000).toISOString()}`,
  );
}
```

Two things decide when you should call it.

**The hold.** A new coin cannot be spent at once. Under the default `privacy: "strict"`, each
coin waits one 60-second issuance window plus its own random 0 to 60 seconds. A wallet that
withdraws and pays straight away throws `PX402NoCoinsError`.

**The distance from the withdrawal.** The hold delays a spend; it does not hide where the coin
came from. Withdrawals are public, so when few other wallets withdraw between your withdrawal and
your payment, the latest withdrawal before a payment is likely the payer's (section 11 has the
measurements). Keep your payments far from your withdrawals:

- **Pre-fund well before you spend.** Call `prewarm` at start-up, or on a schedule of your own,
  long before the calls that need it.
- **Let the hold pass, then wait more.** The further a payment is from its withdrawal, the less
  the timing says.
- **Keep a buffer**, so most payments spend coins withdrawn long ago.
- **Do not withdraw when you do not need to.** Ask the wallet first. The demo withdraws only when
  the wallet cannot already pay the call, or is below its refill target, and goes on when the
  issuer refuses a refill it did not need:

```ts
export async function fundFor(wallet: Wallet, cost: bigint): Promise<boolean> {
  const before = wallet.readiness(cost);
  if (before.status !== "insufficient" && !wallet.needsRefill()) {
    console.log(`the wallet already covers ${cost.toString()} base units (${before.status}): no withdrawal`);
    return true;
  }
  try {
    // This demo withdraws right before it pays, to show every step in one
    // run. In production, pre-fund at start-up or on a schedule and pay
    // later, so each payment is far from the withdrawal its coins came from.
    await prefund(wallet, cost);
  } catch (error) {
    if (!reserveTooSmall(error)) {
      throw error;
    }
    if (before.status !== "insufficient") {
      console.warn(
        "the issuer refused the refill (INSUFFICIENT_VALUE): the reserve holds less than it. " +
          "The wallet still covers this call; deposit before the next refill (node fund.js 25.00).",
      );
      return true;
    }
    // …
    return false;
  }
  // …
}
```

`reserveTooSmall` is `error instanceof PX402Error && error.code === "INSUFFICIENT_VALUE"`: the
issuer refuses a withdrawal larger than the reserve's balance with that code.

With no argument, `prewarm` tops the buffer up to the wallet's refill target: the larger of two
hours of observed spending and `minRunwayBaseUnits`, moved up or down by up to 20 % at random so
your withdrawals do not fall into a pattern. Set `minRunwayBaseUnits` from the prices you
expect: left unset it is $1.00, which says nothing about your calls. One withdrawal holds at most
64 coins (the issuer's limit); the wallet warns through `onWarning` when a plan hits it. A
48-coin withdrawal takes 14 to 17 seconds.

## 5. Wait for the hold: `ready()`

`wallet.readiness(amount)` answers "can I pay this now?" without I/O. It returns one of three
statuses:

| `status` | Meaning | What to do |
|---|---|---|
| `"ready"` | Spendable coins cover the amount. | Pay. |
| `"holding"` | They will at `at` (`secondsRemaining` from now): coins in their hold, or change being melted back into fresh coins (`refreshingBaseUnits`). | Wait, or `await wallet.ready(...)`. |
| `"insufficient"` | Waiting will not help. `shortfallBaseUnits` says by how much; `fragmented: true` means the value is there in coins too small for one payment (section 6). | `prewarm`, and deposit first if the reserve is empty. |

`await wallet.ready({ amountBaseUnits })` waits until the amount is spendable, with one timer per
coin unlock, no polling. It throws `PX402NoCoinsError` at once when the amount is out of reach,
and after `timeoutMs` (default 125 seconds, the longest hold plus a margin). It also melts change
an earlier process left behind.

Ask about what the call will **present**, not the bare price: the price plus the relayer fee,
rounded up (section 7). This bound needs no network read:

```ts
export function worstCaseCost(wallet: Wallet, price: bigint): bigint {
  const keyset = wallet.keyset;
  if (keyset === undefined) {
    throw new Error("the wallet has no keyset");
  }
  return price + feeCeiling(price, MAX_FEE_BPS, smallestDenomination(keyset));
}
```

`node --env-file=.env dist/inspect.js [url]` prints the runway, the readiness for that
merchant's price (or a typical one) and the key epochs held, and spends nothing: no withdrawal,
no payment, no melt.

## 6. Make a paid call

Wrap `fetch` once and use it as you would `fetch`. With a bridge facilitator it pays both kinds
of merchant:

```ts
/** A fetch that pays 402s, px402 or (with a bridge facilitator) exact, and saves the receipt chain after every payment. */
export function paidFetch(wallet: Wallet, bridgeFacilitator: string | undefined): FetchLike {
  return wallet.wrapFetch(fetch, {
    // Off unless you name one: without it, a 402 that quotes only `exact` comes back unpaid.
    ...(bridgeFacilitator === undefined ? {} : { bridge: { facilitator: bridgeFacilitator } }),
    onPayment: (info) => {
      console.log(
        `paid ${info.resourceUrl}: price ${info.priceBaseUnits.toString()} + fee ` +
          `${info.feeBaseUnits.toString()} (${String(info.feeBps)} bps) in ${String(info.coinPubs.length)} coin(s), ` +
          `settlement ${info.settlement}, delivered ${String(info.delivered)}`,
      );
      if (info.bridge !== undefined) {
        // The merchant's own settlement transaction is the on-chain payment.
        // info.commitId is the registry's commit id, not a chain transaction.
        console.log(
          `  bridge: relayer ${info.bridge.relayer ?? "none"}, asset ${info.bridge.asset}, ` +
            `${info.bridge.state}, merchant transaction ${info.bridge.merchantTransaction ?? "none"}`,
        );
      }
      saveReceipts(RECEIPTS_FILE, wallet);
    },
  });
}
```

The whole demo agent, end to end. The price comes from the merchant's own 402, read before the
wallet starts; the optional second argument is the most the agent will pay:

```ts
async function main(): Promise<void> {
  const url = process.argv[2];
  const most = process.argv[3] === undefined ? undefined : BigInt(process.argv[3]);
  if (url === undefined) {
    throw new Error("usage: node agent.js <url> [the most to pay, in base units]");
  }
  const cfg = loadConfig();
  // What the merchant asks, from its own 402, before the wallet is started.
  const quote = await quoteFor(url, cfg);
  if (quote === undefined || (quote.path === "exact" && cfg.bridgeFacilitator === undefined)) {
    return;
  }
  if (most !== undefined && quote.priceBaseUnits > most) {
    console.warn(`refusing: the price is above the ${most.toString()} base units you allowed`);
    return;
  }
  const wallet = await bootWallet(cfg);
  // Bridge payments an earlier run left undelivered: followed up when due.
  await followUpBridgePayments(wallet, RECEIPTS_FILE);
  const cost = worstCaseCost(wallet, quote.priceBaseUnits);
  if (!(await fundFor(wallet, cost))) {
    return;
  }
  // …
  const route = { network: `eip155:${String(cfg.chainId)}`, bridged: cfg.bridgeFacilitator !== undefined };
  const response = await paidGet(wallet, paidFetch(wallet, cfg.bridgeFacilitator), url, route);
  if (response !== undefined) {
    console.log(`${String(response.status)} ${await response.text()}`);
  }
  await refillIfLow(wallet);
  // Melt the change now, while the process still runs.
  await wallet.refresh();
}
```

`quoteFor` makes one unpaid request and reads it with `quotedPrice`. When the merchant quotes
only `exact` and `PX402_BRIDGE_FACILITATOR` is not set, it stops there, before anything is
withdrawn or paid, and says which variable to set:

```ts
export async function quoteFor(url: string, cfg: AgentConfig): Promise<QuotedPrice | undefined> {
  const first = await fetch(url);
  if (first.status !== 402) {
    console.log(`${url} answered ${String(first.status)} without asking to be paid`);
    return undefined;
  }
  const network = `eip155:${String(cfg.chainId)}`;
  let quote: QuotedPrice | undefined;
  try {
    // With a bridge facilitator, the entry its paid fetch would pay: on this
    // network, or on another network that facilitator lists.
    quote = await quotedPrice(first, {
      network,
      ...(cfg.bridgeFacilitator === undefined ? {} : { bridgeFacilitator: cfg.bridgeFacilitator }),
    });
  } catch (error) {
    // …
  }
  // …
  if (quote.path === "exact" && cfg.bridgeFacilitator === undefined) {
    console.warn(exactWithoutBridge(url));
  }
  return quote;
}
```

What happens on one call to a px402 merchant:

```text
your agent          wallet                               merchant               facilitator
fetch402(url) ----> GET url --------------------------> 
                    <---------------------------------- 402 { accepts: [ ... ] }
                    pick the entry with extra.binding "px402", extra.tier 0
                    GET <extra.facilitator>/supported   (cached 5 minutes) -> feeBps
                    presented = price + fee, rounded up to the smallest coin
                    pick coins, sign each to these terms
                    GET url + X-PAYMENT ---------------> POST /verify --------> checks coins and terms
                                                         POST /settle --------> registry commits the coins;
                                                                                a relayer pays the merchant
                    <---------------------------------- 200 + X-PAYMENT-RESPONSE
<---- Response      append a receipt, call onPayment
```

What your agent sees is the merchant's `Response`. Anything but a 402 passes through untouched,
and a 402 with no px402 entry comes back as it arrived, unless you name a bridge facilitator for
merchants that quote only `exact` (the end of this section). A px402 entry is paid under the
Instant tier, `extra.tier: 0`: when a 402's px402 entries all name another tier or none, the
wallet throws `PX402TierError` before it selects a coin. A POST is re-sent with the same method,
headers and body. A paid call takes about 10 seconds (median 9.7 to 10.4 s over PRXVT's live
runs): the facilitator answers once the relayer's transfer to the merchant has three
confirmations.

**One payment, one header.** x402 sends the coins in the `X-PAYMENT` request header, and the
server in front of a merchant refuses a header too large before the merchant's code runs: nginx,
by default, any single header line over 8 KiB (`400`); Node a request whose headers pass 16 KiB
(`431`). So by default the wallet keeps every `X-PAYMENT` within 7.5 KiB, 7,680 bytes
(`maxPaymentHeaderBytes`), which fits both: at most 9 coins (768 bytes each), fewer when the
resource URL is over 228 bytes. A price whose cover would take more coins is paid with fewer,
larger ones: one coin is split, and its residual is change the wallet refreshes into fresh coins,
so the payment still goes through. When the coins you hold are too small for one payment to carry
the price (forty $0.001 coins asked for $0.030, say), the paid fetch throws
`PX402HeaderBudgetError` before anything is sent or any coin retired, `readiness(price)` says
`"insufficient"` with `fragmented: true`, and `needsRefill()` turns true. Call `prewarm()`: the
wallet has recorded the price and buys coins that carry it in one payment. To carry more coins per
payment, raise the budget when you open the wallet,
`px402.open({ ..., maxPaymentHeaderBytes: 12_288 })`: 15 coins, the facilitator's cap, which a
larger budget does not raise. Do that only if every merchant you pay accepts headers that large,
for example none behind an nginx left at its 8 KiB default.

`onPayment` receives a `PaymentInfo`:

| Field | What it is |
|---|---|
| `amount` | What the coins covered: price plus fee. |
| `priceBaseUnits`, `feeBaseUnits`, `feeBps` | What the merchant receives, what the relayer earns (rounding included), and the rate. |
| `settlement` | `"confirmed"` when the merchant returned `X-PAYMENT-RESPONSE`; `"assumed"` when the wallet inferred it from the status. |
| `delivered` | `false` when the payment settled and the merchant did not serve (see section 10). |
| `commitId` | The registry's commit id for the payment: what the px402 settle response carries in its `transaction` field (x402 names the field; px402 puts the commit id there). **Not a chain transaction hash**: a block explorer will not find it. The wallet is not told the relayer's transfer of a px402 payment; for a bridge payment the chain transaction is `bridge.merchantTransaction`. |
| `contractTermsHash`, `coinPubs` | What the registry's public spend log records for this payment. |
| `termsSalt` | The per-payment salt that opens the terms hash's two salted fields. Keep it only if you may need to dispute. |
| `bridge` | Present for a payment through the bridge (below): the relayer that signed (`relayer`), the token (`asset`), how it ended (`state`), and `merchantTransaction`, the merchant's settlement transaction hash on chain, from its own `X-PAYMENT-RESPONSE` / `PAYMENT-RESPONSE`. |

### Paying a merchant that quotes only `exact`

Most x402 merchants today quote only the `exact` scheme: a USDC transfer authorization
(EIP-3009) signed by the payer, which the merchant's own facilitator executes. Your wallet holds
coins, not USDC at an address, so by default it hands such a 402 back untouched. Name a **bridge
facilitator** and the wallet pays these merchants too, with nothing changed on their side: it
commits your coins at the facilitator, a relayer signs the authorization from its own USDC, and
the wallet checks it and delivers it to the merchant. On chain the merchant is paid by a relayer,
as every px402 payment is.

The demo does it with one option, `bridge: { facilitator }`, set from `PX402_BRIDGE_FACILITATOR`
or, unset, PRXVT's `https://facilitator.prxvt.com` (`paidFetch` above), and with `bridgeFetch` in
the wallet config so the payment goes through your proxy. A 402 names no px402 facilitator for an
`exact` entry, so the wallet's side names it. (`wallet.wrapFetch` itself stays off without a
`bridge` option; the drop-in turns it on whenever a facilitator resolves.) Paid this way, an
ordinary x402 merchant's 0.01 USDC call took 4.4 seconds: price 10,000 plus a fee of 1,000 base
units, five coins, and the merchant's `PAYMENT-RESPONSE` naming its transaction.

The bridge pays a 402 that has no px402 entry and an `exact` entry on your wallet's chain
(`chain.chainId`), in a token the facilitator's `/supported` lists under `extra.bridge.assets`.
Merchants on other networks the facilitator lists are paid the same way: an `exact` entry on
another network is paid from the same coins when the facilitator's `/supported` lists that network and token under `extra.bridge.networks`, and the
receipt's `bridge.network` names the network the merchant was paid on. When a 402 offers
entries on several listed networks, the one on your wallet's chain is paid, else the merchant's
first. Nothing new is configured. It reads x402 v1 (a JSON body, `network: "base"`, `maxAmountRequired`) and
v2 (CAIP-2 networks and `amount`, in the body or the `PAYMENT-REQUIRED` header, the header
first). Every other 402 still comes back untouched. You present the price plus the facilitator's
fee, rounded as in section 7; the merchant receives its price.

Before it hands the merchant anything, the wallet checks the authorization the facilitator
returned: it pays the merchant's `payTo` exactly the price, is valid from 0 and for more than 10
more seconds, carries this payment's own nonce (so it cannot pay for any other payment), is in
the merchant's token, comes from a relayer payout address the facilitator's `/supported` lists,
and its signature recovers to that address under the token's own EIP-712 domain. Then it re-sends
your request with `X-PAYMENT` (x402 v1) or `PAYMENT-SIGNATURE` (v2). If the merchant answers 402,
usually because its own facilitator failed to send the transfer, the wallet sends the identical
request again, up to twice more, 1 to 2 seconds apart, while the authorization has at least 30
seconds left; this cannot pay twice, because the token accepts each authorization only once.
`settlement` is `"confirmed"` when the merchant's `X-PAYMENT-RESPONSE` / `PAYMENT-RESPONSE` says
`success: true`, and `info.bridge.merchantTransaction` is its transaction hash.

A bridge payment that stops throws `PX402BridgeError`. Its `committed` flag is the answer that
matters:

```ts
/** What a bridge payment that stopped means for the caller. */
export function explainBridgeError(error: PX402BridgeError): string {
  if (!error.committed) {
    // Nothing was paid: refused before the coins were committed.
    return `not paid (${error.reason}); ${error.retryable ? "retry later" : "do not retry"}`;
  }
  // The coins are committed and the merchant was not handed a payment.
  // Never retry: a retry pays again. The recourse brings the coins back.
  return `paid, not delivered (${error.reason}): wallet.pursueBridgeRecourse() follows it up`;
}
```

`committed: false` covers a merchant timeout under 120 seconds (refused before anything is sent)
and the facilitator refusing at `/verify` or `/settle`. `committed: true` covers no relayer
signing (`no-relayer`), a lost `/settle` answer (`settle-unknown`), and an authorization that
failed a check (`to`, `value`, `nonce`, `asset`, `from`, `signature`, …): the receipt says
`settled` and `delivered: false`.

**The recourse.** Until the coins come back, the bridge facilitator holds your payment's amount,
and it is also the party expected to refund it when the merchant was not paid: no relayer signed,
the merchant never used the authorization, or a relayer recorded a payout it never made. So the
wallet does not rely on it. Every bridge payment not confirmed delivered keeps a recourse beside
its receipt, and `wallet.pursueBridgeRecourse()` follows it up:

```ts
/** Between calls, like refresh(): follow up bridge payments the merchant did not take. */
export async function followUpBridgePayments(wallet: Wallet, receiptsFile: string): Promise<void> {
  const report = await wallet.pursueBridgeRecourse();
  for (const step of report.pursued) {
    console.log(`bridge payment ${String(step.seq)}: ${step.stage} (${step.outcome ?? "pending"})`);
  }
  // The schedule lives in the receipt file: save it, so a restart carries on.
  saveReceipts(receiptsFile, wallet);
}
```

Call it between calls, as you call `refresh()` (the demo calls it right after it boots); it does
nothing until something is due. Two hours after the payment (`LEASE_TTL + 2 × RECORD_GRACE`,
7,260 seconds) it asks the facilitator (`POST /bridge/lookup`) how the payment ended. Unless the
answer is `paid` or `refunded`, it files your own dispute with the issuer (`POST /disputes`, with
the payment's terms as the only credential), which revokes a relayer that recorded without
paying. When no relayer recorded at all, it asks the registry to cancel the payment
(`POST /bridge/cancel-request`), which opens the cancel refund a day later even if the
facilitator never acts, and asks again then. When the coins come back, or the registry never
committed them, it appends a `refunded` receipt for the whole amount and reads the coins back:
`balance()` and `reconcile()` count the value at once, and the next melt turns it into fresh coins.
The schedule survives restarts through the receipt file (`loadReceipts` above reads it back with
`receiptsFromJson`).

**Privacy.** To the merchant's facilitator and on chain, a bridge payment looks like any px402
payout: a relayer paying `payTo`. The merchant sees your network address, as with any x402
client. What changes is that your wallet, not a merchant, sends the payment to the px402
facilitator, from your network address. Route `bridgeFetch` (or `bridge.fetch`) through a proxy
you control, as you do `supportedFetch`. The recourse, when it runs, shows the payment's terms,
the merchant's `payTo` included, to the issuer and the registry from your address: give the
`IssuerClient` a proxied `fetch` too.

## 7. Fees

The facilitator charges one fee rate for every payment it settles, `feeBps` in its
`/supported`. The protocol caps it at 100 basis points (1 %). You pay it on top of the price;
the merchant always receives exactly the price; the relayer that paid the merchant earns the fee.
At a fee of 0 nothing changes. Under a fee, the wallet presents:

```text
presented = roundUp(price + ceil(price × feeBps / 10 000), smallest coin)
```

The smallest coin on the launch ladder is $0.001. Rounding to it means the coins always cover
the total exactly and no payment leaves change too small to melt. The rounding is part of the
fee, so **on small calls the fee is a large share of the price**: at least $0.001 a call, which
is 10 % of a $0.01 call and the whole price of a $0.001 one.

| Price | Fee at 100 bps | Presented | Fee as a share of the price |
|---|---|---|---|
| $0.001 | $0.001 | $0.002 | 100 % |
| $0.003 | $0.001 | $0.004 | 33 % |
| $0.01 | $0.001 | $0.011 | 10 % |
| $0.05 | $0.001 | $0.051 | 2 % |
| $0.25 | $0.003 | $0.253 | 1.2 % |
| $1.33 | $0.014 | $1.344 | 1.05 % |

```ts
export function threeTenthsOfACent(): void {
  const { price, fee, presented } = presentedAmount(3_000n, 100, 1_000n);
  // price 3000, fee 1000, presented 4000. The rate owes ceil(3000 × 100 / 10 000) = 30;
  // 3030 rounds up to 4000, and the 970 of rounding is part of the relayer's fee.
  console.log(price, fee, presented);
  // The most a wallet with maxFeeBps 100 will ever pay in fee on this price: 30 + 1000 - 1.
  console.log(feeCeiling(3_000n, 100, 1_000n)); // 1029n
}
```

**Reading a facilitator's `/supported`.** It carries two kinds of `feeBps`, and only one is what
you pay:

- `kinds[i].extra.feeBps` is **the facilitator's fee**: the one rate every payer presents on top
  of the price, whichever relayer pays the merchant. This is the number the wallet reads, checks
  against your `maxFeeBps`, and pays.
- `kinds[i].extra.relayers[j].feeBps` is **each relayer's reservation price**, from its on-chain
  registration: the lowest fee it will work for. A relayer is eligible when its `feeBps` is at
  most the facilitator's, and it then earns the facilitator's fee, not its own. It is disclosure;
  it changes nothing you pay.

Beside them, `kinds[i].extra.bridge.assets` lists the tokens the facilitator pays `exact`
merchants in (absent: it does not bridge), and each relayer's `bridgeAssets` the tokens that
relayer fronts. A merchant's `exact` entry is paid only in a token on the facilitator's list. To
read it: `node -e "fetch(process.argv[1] + '/supported').then((r) => r.json()).then((j) => console.log(JSON.stringify(j, null, 2)))" <facilitator URL>`.

`maxFeeBps` in the wallet config is your cap (default 100). Before it presents any coin, the
wallet reads the facilitator's `/supported` and refuses when the rate is above your cap, or when
the fee on this price, rounding included, is above `ceil(price × maxFeeBps / 10 000) + smallest
coin − 1`. It throws `PX402FeeError`. Nothing was presented and no coin was retired:

```ts
export function explainFeeRefusal(error: PX402FeeError): string {
  switch (error.refusal) {
    case "fee-over-max":
      return `${error.facilitator} charges ${String(error.feeBps)} bps (${String(error.feeBaseUnits)} base units here); your maxFeeBps is ${String(error.maxFeeBps)}`;
    case "unreachable":
      return `${error.facilitator}/supported did not answer; retry later`;
    default:
      return `${error.facilitator} publishes a fee this wallet cannot use (${error.refusal})`;
  }
}
```

The other refusals: `malformed` (not a `/supported` the wallet can read), `unsupported` (no
px402 kind for this network), `fee-missing` (a relayer list and no `feeBps`), and
`fee-rule-unknown` (a fee with no `extra.feeRounding: "smallest-denomination"`). Each means you
cannot pay that merchant through that facilitator; only `unreachable` is worth retrying.

The fee is not refundable: a refund returns at most the price. `runway().callFeeBaseUnits` and
each receipt's `feeBaseUnits` show what fees have cost you.

## 8. Receipts

The wallet appends one receipt for every payment that settled: `seq`, `ts`, `resourceUrl`,
`payTo`, `amount`, `priceBaseUnits`, `feeBaseUnits`, `coinPubs`, `contractTermsHash`, `status`
(`settled`, `refunded` or `failed`), `delivered`, `prevHash` and `hash`. A payment through the
bridge (section 6) also carries `bridge` (the facilitator, the relayer, the token, the merchant's
transaction and how it ended) and, while it is being followed up, `recourse`. The receipt log is
your purchase history, and the only place it exists: what you paid for, to whom, and when. The
SDK has no way to send it anywhere. Keep it private.

It lives in memory, so save it after every payment and pass it back when you recover:

```ts
/** Write the whole chain, atomically: a crash mid-write leaves the previous file. */
export function saveReceipts(path: string, wallet: Wallet): void {
  writeFileSync(`${path}.tmp`, wallet.receipts.export("json"), { mode: 0o600 });
  renameSync(`${path}.tmp`, path);
}

/** The saved chain, verified when the wallet loads it; empty on a first run. */
export function loadReceipts(path: string): StoredReceipt[] {
  if (!existsSync(path)) {
    return [];
  }
  // …
}
```

`mode: 0o600` makes a new file readable by your user alone on Linux and macOS. **Windows ignores
it**: there, keep the receipt file (and the checkpoint beside it) in a folder under your user
profile, which by default only you, SYSTEM and administrators can read (check with
`icacls <folder>`), and not in a shared or synced folder. Everywhere, keep it out of git
(`px402-receipts*.json` in `.gitignore`, section 2).

What a receipt proves:

- **Your log was not edited.** Each receipt hashes the one before it. Changing, reordering or
  deleting an entry breaks the chain; `wallet.receipts.assertValid()` and loading both check it.
  Cutting entries off the end does not break it.
- **Which public record is yours.** The registry's public spend log lists each coin key with its
  amount and terms hash. `coinPubs` and `contractTermsHash` point at those entries. Showing them to
  anyone ties you to that payment.
- **Not, by itself, that you paid.** Nobody else signed it. The merchant's `X-PAYMENT-RESPONSE`
  (`settlement: "confirmed"`, `commitId`) is the evidence that the registry committed.

`wallet.reconcile()` compares the receipts with the chain: deposits minus reclaims minus the
coins you hold should equal what the receipts say you spent. It counts USDC still sitting in your
reserve as spent, so pass `deposits` as what left the reserve into coins (your deposits minus the
reserve's current balance), or the difference it reports is that balance. A payment that settled
and was not delivered is a `settled` receipt with `delivered: false`. Ask the merchant for a
refund; when it refunds, `wallet.recordRefund(seq)` appends the compensating entry for the price
(the relayer's fee is not refunded; pass `{ amountBaseUnits }` when the merchant refunded less),
and the wallet reads the payment's coins back from the registry at its next melt and melts the
refunded value into fresh coins. `await wallet.readRefunds()` counts it in `balance()` and
`reconcile()` at once. A bridge payment's recourse does both by itself, for the whole amount: its
cancel refund returns the fee too.

## 9. Runway and refills

`wallet.runway()` reports what the buffer can pay for, without I/O:

| Field | Meaning |
|---|---|
| `calls`, `days`, `usdc` | Calls the spendable value covers at `callCostBaseUnits`, how long that lasts at your observed rate, and the spendable value in USDC. |
| `spendableBaseUnits`, `heldBaseUnits`, `balanceBaseUnits` | Payable now; payable once the hold lifts (at `heldUntil`); everything, including change waiting to be melted. |
| `callCostBaseUnits`, `callFeeBaseUnits` | The average presented cost per call, and its fee part. |
| `costBasis` | `"observed"` once the wallet has paid; `"assumed"` before, when the cost is `assumedCallCostBaseUnits`. |

Refill between calls, not in the request path:

```ts
/** Refill when spendable value falls below the jittered target. Run it between calls, not right before one. */
export async function refillIfLow(wallet: Wallet): Promise<void> {
  const runway = wallet.runway();
  console.log(
    `runway: ${String(runway.calls)} calls at ${runway.callCostBaseUnits.toString()} (${runway.costBasis}), ` +
      `${runway.spendableBaseUnits.toString()} spendable, ${runway.heldBaseUnits.toString()} held`,
  );
  if (!wallet.needsRefill()) {
    return;
  }
  try {
    await wallet.prewarm();
  } catch (error) {
    if (!reserveTooSmall(error)) {
      throw error;
    }
    console.warn("refill refused (INSUFFICIENT_VALUE): the reserve is nearly empty; deposit (node fund.js 25.00)");
  }
}
```

Use the wallet's own `needsRefill()` and `prewarm()`. They apply the random ±20 % to the target.
A fixed threshold of your own refills on a schedule an observer can match.

**Change.** A coin is shown to one merchant only, ever. When a payment uses part of a coin, the
rest is retired and comes back as fresh coins through a melt (refresh). The wallet melts in the
background at a random moment up to 120 seconds after the payment, never within 3 seconds of
another payment. Until then the change counts in `balanceBaseUnits` but not as spendable or
held, `readiness()` reports it as `refreshingBaseUnits` with status `"holding"`, and the fresh
coins from the melt wait out their own hold.
`wallet.refresh()` melts at once; call it before a planned exit. The wallet prefers whole coins
that add up to the presented total, and withdraws coins in the sizes you have been paying, so most
payments leave no change.

## 10. Errors you will meet

| What you see | What it means | What to do |
|---|---|---|
| `PX402NoCoinsError` from the paid fetch or `ready()` | Nothing spendable covers the presented total. Strict mode never falls back to a fresh coin. | `readiness(error.requested)`: wait if `"holding"`, `prewarm` (and deposit) if `"insufficient"`. |
| `PX402HeaderBudgetError` from the paid fetch or `ready()` | The value is there, in coins too small for one payment to carry: covering the price takes more coins than fit one `X-PAYMENT` (9 at the default 7,680 bytes; 15 at most). Nothing was sent or retired. | `prewarm()`: it buys coins sized to that price (section 6). |
| `PX402FeeError` | The facilitator's fee is over your `maxFeeBps`, or it publishes no fee the wallet can use. Nothing was presented. | See section 7. Retry only `unreachable`. |
| `PX402TierError` | The merchant's px402 terms name a tier other than Instant (`extra.tier: 0`), or none; a facilitator refuses any other tier `TIER_UNSUPPORTED`. Nothing was presented. | Do not retry. The merchant has to quote `tier: 0`. |
| A 402 that quotes only `exact` comes back unpaid | No bridge facilitator is configured, or its `/supported` does not list the merchant's token. | Set `PX402_BRIDGE_FACILITATOR` (section 6); check the facilitator's `extra.bridge.assets` (section 7). |
| `PX402BridgeError` with `committed: false` | A bridge payment (section 6) stopped before the coins were committed: the merchant's `maxTimeoutSeconds` is under 120, or the bridge facilitator refused it. | Retry only `reason: "unreachable"`. |
| `PX402BridgeError` with `committed: true` | The coins are committed and the merchant got nothing: no relayer signed, the answer was lost, or the authorization failed the wallet's checks. | Never retry: it pays again. Keep calling `wallet.pursueBridgeRecourse()` between calls. |
| `PX402SeedUsedError` from `open` | The seed has been used: its reserve has withdrawn on chain, or you passed stored receipts. | Start it with `px402.recover`. |
| `PX402RequestError` with `code: "INSUFFICIENT_VALUE"` from `prewarm` | The issuer will not withdraw more than the reserve holds: the reserve is empty, or holds less than the refill. | Deposit (`fund.js`). Check `readiness()` before withdrawing: a wallet that already covers the call need not withdraw at all (`fundFor`, section 4). |
| The paid fetch returns 402 with `error: "INSUFFICIENT_VALUE"` | The facilitator says the coins do not add up to price plus fee. Its fee changed inside the wallet's 5-minute `/supported` cache, or a coin was already spent (two processes on one seed, a used seed opened with `{ fresh: true }`). | Retry after `supportedTtlSeconds`. Run one process per seed, and restart with `px402.recover`. |
| 402 with `error: "TERMS_MISMATCH"` | The terms the coins were signed to are not the ones the facilitator recomputes: your clock is more than 5 minutes off, the merchant asks a `maxTimeoutSeconds` over 3600, or it served different terms on the retry. | Fix your clock (NTP). If it keeps happening at one merchant, tell the merchant. |
| 402 with `KEYSET_UNKNOWN` or `KEYSET_NOT_COMMITTED` | The facilitator has not loaded the keyset of a coin you presented, usually after a restart or a new epoch. | Retry later. It is the operator's to fix. |
| `PX402EpochRetiredError` in `refresh()`'s `retired` and `readiness().retiredEpochs` (never thrown by the paid fetch) | The issuer can no longer refresh one epoch's coins: it lost that epoch's keys (section 3). | Nothing to retry. The wallet spends that epoch's whole coins whole before `spendableUntil`; stranded change returns only through a recoup the operator announces. |
| 402 with `DENOM_REVOKED` or `DENOM_EXPIRED` | Those coins can no longer be spent. | Do not retry with them. Their value comes back through the issuer's recoup, a day after the revocation at the earliest, made on the contract outside the SDK. |
| 402 with `PAYEE_SCREENED` | The facilitator will not pay this merchant's `payTo`. Your coins were not committed. | Do not pay this merchant through this facilitator. |
| 402 or 503 with `SCREENING_UNAVAILABLE` | A screening source could not be checked, and the service failed closed. | Retry with backoff. |
| `PX402Error` with `httpStatus` 403 from `prewarm` | `RESERVE_SCREENED`: the issuer will not issue coins to your reserve. | Withdrawals stay refused. Your deposit is not frozen: the contract's `reclaimBalance`, signed by the reserve key (`deriveReserveKey` derives it from the seed), pays it back to your reserve address; send it from outside the SDK. |
| `PX402Error` with `httpStatus` 429 from `prewarm` | `ISSUANCE_CAP_EXCEEDED`: your reserve's rolling 24-hour issuance cap. | Withdraw less, or later. |
| `PX402ServerError` with `httpStatus` 503 or 500 from `prewarm` | `SCREENING_UNAVAILABLE`, or an issuer fault. The client already retried three times. | Retry with backoff. (`refresh()` never throws for these: a failed melt stays queued and is retried.) |
| `PX402KeysetCommitmentError` from `open` or `recover` | The issuer served a keyset the reserve did not commit on chain: it is not this deployment's issuer, or it is misbehaving. | Stop. Do not withdraw. Check the issuer URL (section 1). |
| A recovery warning that the scan checkpoint was not used | The saved checkpoint is corrupt, for another chain or contract, or its block is not on the chain now. | Nothing: that recovery reads from the deployment block and saves a new checkpoint. |
| `PX402TransportError`: "the chain RPC at ... is rate limiting this wallet" | The chain's RPC kept refusing with a rate limit through eight tries and their backoff. It is `retryable`. | Set `rpcUrl` or `PX402_RPC_URL` to your own Base RPC; a public endpoint is rate-limited. |
| `PX402RpcUnsupportedError` | The chain's RPC keeps the request for clients with a key (publicnode's "Archive requests require a personal token"). Not retryable. | Set `rpcUrl` or `PX402_RPC_URL` to your own Base RPC. |
| `PX402ConfigError` | The wallet was not given something it needs (an issuer, a keyset, the chain reads, or for recovery `rpcUrl` and `deployBlock`). | Fix the configuration. |
| A non-2xx response and `delivered: false` | Paid, undelivered: the coins are committed and the merchant did not serve. | Ask the merchant for a refund. A retry pays a second time. |

The SDK classifies issuer errors by the protocol's eleven codes (`PX402_ERROR_CODES`, each one's
HTTP status in `CANONICAL_STATUS`). It does not carry the issuer's `RESERVE_SCREENED`,
`ISSUANCE_CAP_EXCEEDED` and `SCREENING_UNAVAILABLE` through as `error.code`, so branch on
`error.httpStatus` (403, 429, 503) for those. A refused payment does not throw: the merchant
answers with a fresh 402, and the reason is in its body when the merchant passes the
facilitator's code on, as x402 servers do in `error`. This handles each case:

```ts
  } catch (error) {
    if (error instanceof PX402NoCoinsError) {
      // Strict mode failed closed: nothing spendable covers the price plus fee.
      const state = wallet.readiness(error.requested);
      if (state.status === "holding") {
        console.warn(`coins are in their hold; spendable in ${String(state.secondsRemaining)} s (await wallet.ready)`);
      } else {
        console.warn(`short by ${state.shortfallBaseUnits.toString()} base units: prewarm, or deposit first`);
      }
      return undefined;
    }
    if (error instanceof PX402FeeError) {
      // Nothing was presented. `unreachable` is worth a retry later; the rest
      // mean this facilitator's fee or terms are not ones this wallet accepts.
      console.warn(`not paying through ${error.facilitator}: ${error.refusal}`);
      return undefined;
    }
    if (error instanceof PX402BridgeError) {
      // `committed` decides: a committed bridge payment is never retried.
      console.warn(explainBridgeError(error));
      return undefined;
    }
    if (paidUndelivered()) {
      // The payment went out and the answer never came back. The wallet
      // counts it as settled. A retry would pay a second time.
      console.warn(`the connection failed after paying ${url}; do not retry blindly`);
    }
    if (error instanceof PX402Error && error.retryable) {
      console.warn(`transient failure (${error.name}); retry with backoff`);
      return undefined;
    }
    throw error;
  }
  if (response.status === 402) {
    // Either the merchant offers nothing this wallet pays (its first 402,
    // returned untouched), or it refused the payment and quoted again.
    console.warn(`402 from ${url}: ${(await refusalReason(response)) ?? "no reason given"}`);
    const quote = await quotedPrice(response, { network: route.network }).catch(() => undefined);
    if (quote?.path === "exact" && !route.bridged) {
      console.warn(exactWithoutBridge(url));
    }
    return undefined;
  }
```

A coin shown to a merchant that then refused the payment is retired all the same: that merchant
has seen its key. Its value is not lost; the wallet melts it back into fresh coins.

## 11. Privacy and security

- **Pre-fund well before you spend**, let the hold pass, and keep a buffer, so a payment and the
  withdrawal it came from are far apart (section 4).
- **Refill between calls on your own schedule**, with `needsRefill()` and `prewarm()`, never right
  before a call.
- **Stay in `privacy: "strict"`.** `"besteffort"` spends fresh coins at once and gives up the
  hold. Choose it only if you have decided linkability does not matter for this agent.
- **Route px402 traffic through a proxy if your IP identifies you.** The issuer sees your address
  when you withdraw and melt; the facilitator sees it when the wallet reads `/supported` just
  before a payment; the registry sees it during recovery. Give the `IssuerClient` a `fetch` and the
  wallet a `supportedFetch` that go through a proxy you control (`serviceFetch` in the examples).
  With the bridge, the facilitator also receives the payment itself from your address: proxy
  `bridgeFetch` too. The merchant sees your address on every call, as it does for any x402
  client.
- **One seed per agent, one process per seed**, and keep the reserve near one refill cycle.
- **Never share receipts.** A receipt is exactly the payer-to-merchant link px402 keeps every
  service from holding.

What each party can and cannot see:

| Party | Sees | Cannot see |
|---|---|---|
| Public chain | Your deposit (depositor, reserve address, amount) and each withdrawal (reserve, amount, time); every payout to a merchant | Which payout your coins paid for, except by timing (section 4) |
| Issuer | Your reserve address, its withdrawals and melts, and your network address when you make them | Which coins it signed for you (they are blinded), what you buy, whom you pay |
| Registry | Every coin spent, its amount and terms hash, published in a public log | The resource, the merchant, the payer |
| Facilitator | Each payment's resource URL, `payTo`, amount and coins; your network address when the wallet reads `/supported`, and with every bridge payment | Your reserve, your deposit, your other payments |
| Relayer | The merchant's `payTo` and the price it pays | Which coins paid, or who paid |
| Merchant | A valid payment, its coins and your network address | Your reserve, your deposit, your other payments |
| One operator running issuer, registry and facilitator, logging network addresses | Everything above; an address seen at your withdrawal and again at a `/supported` read joins your reserve to your payment | Which payment your coins made, beyond what timing shows, once you proxy issuer and facilitator traffic |

**Timing.** Withdrawals are public, so keep each payment far from your own withdrawal in time.
Pre-funding well before you spend, as section 4 and the drop-in's `createWallet` at boot do, is
what does it.

## 12. Where to look when something is wrong

- **`node --env-file=.env dist/inspect.js [url]`**: recovers and prints the runway, the readiness
  for a call and the epochs held, spending nothing.
- **`onWarning`.** The wallet warns instead of failing when a withdrawal plan hits the 64-coin cap,
  when a buffer is below one call, when it could not check the keyset on chain, and when a saved
  scan checkpoint was not used.
- **`onProgress`** during recovery says which phase it is in and how far along.
- **`wallet.readiness(amount)`** says whether the next call can go and what is in the way.
- **The receipt and `PaymentInfo`**: `settlement` and `delivered` separate "paid" from "paid and
  served"; for a bridge payment, `bridge.merchantTransaction` is the transaction to look up.
- **The merchant's 402 body** carries the facilitator's reason when the merchant passes it on.
- **`error.httpStatus`, `error.code`, `error.retryable`** on every `PX402Error`.
- **Background:** the SDK's own documentation, which ships with its types: `dist/index.d.ts`
  lists every layer, `dist/wallet.d.ts` documents the wallet (`px402.open`, `px402.recover`,
  `Wallet`), and `dist/errors.d.ts` every error and code; timing is in the
  [README's Security section](../README.md#security).
- **The merchant's side.** A merchant is paid directly once its 402 carries the px402 entry in
  the table at the top of this guide; a merchant that quotes only `exact` is paid through the
  bridge (section 6), with nothing changed on its side.
