# px402

Private x402 payments for TypeScript agents on Base. The wallet withdraws blind-signed coins
from a USDC reserve you fund, and pays x402 APIs with them through a wrapped `fetch`, so no
address links a payment to your deposit or to your other payments. It pays a merchant whose 402
has a px402 entry directly, and a merchant that quotes only `exact` (nearly every x402 merchant
today) through a bridge facilitator, with no change on the merchant's side.

```bash
npm install px402
```

Node 22 or later. Two dependencies, `@noble/curves` and `@noble/hashes`, and nothing else. The
SDK opens no connection of its own: requests go through the `fetch` you pass (the global one by
default), chain reads and the drop-in's deposits through the RPC endpoint you name.

The documentation ships in this package: the agent quickstart,
[`docs/QUICKSTART.md`](https://cdn.jsdelivr.net/npm/px402@2/docs/QUICKSTART.md), and the runnable examples it quotes,
[`examples/`](https://cdn.jsdelivr.net/npm/px402@2/examples/). Once installed they are in `node_modules/px402/`.

## Three lines

Pay the way x402's client pays:

```ts
import { wrapFetchWithPayment } from "px402";

const pay = wrapFetchWithPayment(fetch, account);          // or a 0x private key
const res = await pay("https://api.example.com/data");
```

`account` is a `0x` private key or an account object (viem's `privateKeyToAccount`, ethers'
`Wallet`). The returned `fetch` pays a 402 and passes everything else through untouched. To start
the wallet when the agent boots, `const wallet = await createWallet({ privateKey })` (it also
takes `{ account }` or `{ seed }`), then `wrapFetchWithPayment(fetch, wallet)`. Before a
short-lived process exits, `await pay.close()`.

It runs on Base (chain 8453) by default, through PRXVT's hosted `https://issuer.prxvt.com`,
`https://registry.prxvt.com` and `https://facilitator.prxvt.com`. Options, then
`PX402_ISSUER_URL`, `PX402_REGISTRY_URL`, `PX402_BRIDGE_FACILITATOR` and `PX402_RPC_URL`, point
it elsewhere; a deployment of your own is passed as `network`, a full network object. Chain reads
and deposits go through public Base RPCs by default (publicnode for reads, `mainnet.base.org` for
transactions); in production, set `PX402_RPC_URL` (or `rpcUrl`) to your own, which serves both.

[`examples/three-lines.ts`](https://cdn.jsdelivr.net/npm/px402@2/examples/three-lines.ts) is the above, runnable;
[`examples/drop-in.ts`](https://cdn.jsdelivr.net/npm/px402@2/examples/drop-in.ts) starts the wallet at boot and keeps its receipts
across restarts. The quickstart's "The drop-in" section has every option and error.

## Funding

Send USDC on Base to the key's address. That's all: no ETH, no approve, no deposit of your own.

The wallet deposits from that address itself, in whole floats (`float`, $5.00 by default), never
an amount sized by the call in hand, up to `maxAutoDeposit` (ten floats) per process. An address
with no ETH deposits gaslessly: the key signs a USDC authorization for px402's gasless depositor,
bound to the wallet's own reserve, and a relayer submits it and pays the gas for a small fee taken
out of the deposit, so a $5.00 float credits $5.00 less that fee (the facilitator publishes it;
`maxSponsorFee` caps it, $0.10 by default). An address that holds ETH deposits directly with an
approve and a `deposit`; `gasless: true` makes every deposit gasless, `gasless: false` none. It
withdraws coins by its own refill rule and waits out their 60 to 120 second hold. Too little USDC
is `PX402InsufficientFundsError`, naming the address and how much, before anything is sent. Start
the wallet at boot (`createWallet`), so the first payment spends coins withdrawn long before it.
`autoFund: false` turns the deposits off.

## The explicit path

A seed of the agent's own, a depositor whose key the SDK never sees, and every step in view:

```ts
import { chainConfig, IssuerClient, px402 } from "px402";

const wallet = await px402.recover({
  seed, // 32 bytes: every key is derived from it
  issuer: new IssuerClient({ baseUrl: "https://issuer.prxvt.com", registryUrl: "https://registry.prxvt.com" }),
  chain: chainConfig(), // Base: the reserve, its domain separator, the RPC endpoint
});
const { approve, deposit } = wallet.depositTx("50.00"); // unsigned: send both from your depositor
await wallet.prewarm(20_000_000n); // withdraw well before you spend
await wallet.ready({ amountBaseUnits: 2_525_000n }); // the price plus the facilitator's fee
const fetch402 = wallet.wrapFetch(fetch, { bridge: { facilitator: "https://facilitator.prxvt.com" } });
```

[`docs/QUICKSTART.md`](https://cdn.jsdelivr.net/npm/px402@2/docs/QUICKSTART.md) walks it through, sections 1 to 12: which path a
merchant needs, seed, deposit, pre-fund, the hold, a paid call, fees, receipts, refills, errors
and privacy practice, with every code block an excerpt of an example in this package, typechecked
on every release. [`examples/agent.ts`](https://cdn.jsdelivr.net/npm/px402@2/examples/agent.ts) is the whole agent. Run the examples
with `node --env-file=.env` (the quickstart's section 2 writes `.env` without showing the secret,
in bash and in PowerShell).

## Paying any x402 merchant

Most x402 merchants quote only `exact`: a USDC transfer authorization (EIP-3009) the payer signs.
The wallet pays them through a px402 bridge facilitator: it commits coins there as a merchant
would, a relayer signs the authorization from its own USDC, and the wallet checks it (amount,
`payTo`, validity, this payment's nonce, the token, a listed relayer, the signature) before it
delivers it with `X-PAYMENT` (x402 v1) or `PAYMENT-SIGNATURE` (v2). The drop-in turns the bridge
on whenever a facilitator resolves (`bridge: false` turns it off); `wallet.wrapFetch` takes
`{ bridge: { facilitator } }`. `quotedPrice(response, { network, bridgeFacilitator })` reads a 402
the way the paid fetch with that facilitator does and returns the price and the path (`"px402"`
or `"exact"`) before anything is paid; `wallet.quotedPrice(response, { bridge })` does the same
with the wallet's network and its `/supported` cache. Without `bridgeFacilitator` it quotes only
an `exact` entry on `network`.

Merchants on other networks the facilitator lists are paid the same way, from the same coins on
your wallet's chain: an `exact` entry on another network is paid when the facilitator's
`/supported` lists that network and token under
`extra.bridge.networks`, and the receipt records the network (`bridge.network`). 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.

A bridge payment that stops throws `PX402BridgeError`. With `committed: false` nothing was paid.
With `committed: true` the coins are committed and the merchant got nothing: never retry it (a
retry pays again), and call `wallet.pursueBridgeRecourse()` between calls, which follows the
payment up until the coins come back. The quickstart's section 6 and
[`examples/bridge.ts`](https://cdn.jsdelivr.net/npm/px402@2/examples/bridge.ts) have the details.

## Security

- **Your key.** The drop-in's key, or the explicit path's seed, controls both the reserve and the
  coins. Keep it like the funds it controls, and the balance near what the agent spends.
- **Timing.** Withdrawals are public, so a payment made soon after its own wallet's withdrawal can
  be linked to it when few other wallets withdraw in between. Pre-fund well before you spend:
  `createWallet` at boot does it for the drop-in, `prewarm` at start-up for the explicit path.
- **Network address.** The issuer sees the wallet's network address at withdraw and refresh, a
  facilitator when the wallet reads its `/supported` and with every bridge payment, and the
  registry during recovery and the bridge recourse. Route `serviceFetch` (the drop-in), or the
  `IssuerClient`'s `fetch`, `supportedFetch` and `bridgeFetch` (the explicit path), through a
  proxy you control.
- **The keyset check.** `px402.open` and `px402.recover` refuse an issuer's keyset the reserve
  did not commit on chain, the check that stops an issuer from recognising your coins. Without
  `chain.rpcUrl` or a `keysetCommitment` reader the wallet cannot check, and warns.

## Reference

- [`docs/QUICKSTART.md`](https://cdn.jsdelivr.net/npm/px402@2/docs/QUICKSTART.md): the agent guide. Running in production (restarts
  and recovery, the scan checkpoint, one process per seed, the payment-header budget, key epochs)
  is in its sections 3 to 10, and every error with what to do in section 10.
- [`examples/`](https://cdn.jsdelivr.net/npm/px402@2/examples/): the agent examples the guide quotes, in TypeScript; they import from
  `"px402"`.
- The typings carry the API documentation: `dist/index.d.ts` lists every layer,
  `dist/wallet.d.ts` documents the wallet (`px402.open`, `px402.recover`, `Wallet`),
  `dist/dropin.d.ts` the drop-in (`wrapFetchWithPayment`, `createWallet`), and `dist/errors.d.ts`
  every error.

MIT licensed. [prxvt.com](https://prxvt.com)
