/** * The drop-in surface: paying with px402 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"); * ``` * * and, for the wallet object, * * ```ts * const wallet = await createWallet({ privateKey }); * ``` * * Underneath it is the explicit path, unchanged: `px402.recover` on a seed * derived from the key (`keyseed.ts`), the wallet's own `wrapFetch`, its * refill rule. What the drop-in adds: * * - **Where things are** (`networks.ts`): the chain from a preset (the * `network` option, else `PX402_NETWORK`, else Base), the services from the * options, then `PX402_ISSUER_URL`, `PX402_REGISTRY_URL`, * `PX402_BRIDGE_FACILITATOR`, `PX402_RPC_URL`, then the preset; a missing * one is `PX402MissingSettingError`, naming both. * - **A lazy start.** `wrapFetchWithPayment` does no I/O when called. The * first request starts the wallet beside itself -- recovery, then a first * top-up -- once: concurrent first calls share it, and a start that fails is * tried again at the next 402 rather than kept. * - **Funding** (`topup.ts`): with a key that can sign, the wallet deposits * whole floats from that key's address and withdraws by its own refill * rule, at start and between calls; a payment the buffer cannot cover funds * itself, then waits out the fresh coins' hold. The address needs USDC and * nothing else: with no ETH for gas, a deposit goes through the network's * gasless depositor (`gasless.ts`), a relayer paying the gas for a fee * taken out of the deposit -- so one float credits the reserve one float * less that fee. * - **The bridge on by default**, whenever a bridge facilitator resolves, so * a merchant that quotes only `exact` -- nearly every x402 merchant -- is * paid with no option at all. `bridge: false` turns it off. * - **State, when given a store** ({@link WalletStore}): the receipt chain and * the recovery checkpoint are loaded before recovery and saved after it and * after every payment. Coins need no store: every start recovers them from * the seed and public data, as `px402.recover` always has. * * # One key controls the address and the coins * * The explicit path keeps the depositor's key out of the SDK. This one * derives the seed from it: whoever holds the key holds the address's USDC, * the reserve and the coins. Keep the address's balance near what the agent * spends; `maxAutoDeposit` caps what the wallet deposits in one process. * * # Start the wallet when the agent boots * * A coin is held 60 to 120 seconds after its withdrawal before it can be * spent (§9.1), and a payment made soon after its own withdrawal can be * matched to that withdrawal by its timing. `createWallet` at boot funds the * wallet before anything is bought, so the first payment spends coins * withdrawn long before it; `wrapFetchWithPayment` starts on its first * request, paid or not. A payment the buffer cannot cover funds itself and * waits out the hold inside the call rather than throw `PX402NoCoinsError`. */ import { type FetchLike } from "./client.js"; import { type PaymentInfo } from "./fetch.js"; import { type PaymentAccount } from "./keyseed.js"; import { type Network, type NetworkName, type UndeployedNetwork } from "./networks.js"; import { type RecoveryProgress } from "./recover.js"; import { Wallet, type RecoverConfig } from "./wallet.js"; /** * What a drop-in wallet keeps across restarts, as text: its receipt chain * and where its last recovery's log scan reached. Never its coins: those are * recovered from the seed and public data on every start. */ export interface WalletState { /** The receipt chain, as `wallet.receipts.export("json")` writes it: your purchase history. Keep it private. */ readonly receipts?: string; /** `wallet.recoveryCheckpoint()`: public data, but it names your reserve. */ readonly checkpoint?: string; } /** * Where a drop-in wallet keeps its {@link WalletState}: a file, a database * row, a secret store. `load` answers `undefined` the first time. */ export interface WalletStore { load(): WalletState | undefined | Promise; save(state: WalletState): void | Promise; } /** What both drop-in entry points take. Everything is optional. */ export interface DropInOptions { /** A preset's name, or a deployment of your own. Else `PX402_NETWORK`, else `"base"`. */ readonly network?: NetworkName | Network | UndeployedNetwork; /** * The wallet seed: 32 bytes, or 64 hex characters. When given it wins over * the key's own: the key then only funds the wallet. */ readonly seed?: Uint8Array | string; /** The issuer. Else `PX402_ISSUER_URL`, else the preset's. */ readonly issuerUrl?: string; /** The registry. Else `PX402_REGISTRY_URL`, else the preset's. */ readonly registryUrl?: string; /** The bridge facilitator. Else `PX402_BRIDGE_FACILITATOR`, else the preset's. */ readonly bridgeFacilitator?: string; /** `false` turns the bridge off: a merchant that quotes only `exact` gets its 402 back. On whenever a facilitator resolves. */ readonly bridge?: boolean; /** * The chain's JSON-RPC endpoint, for every read and every deposit. Else * `PX402_RPC_URL`, else the preset's public ones (on Base, publicnode for * reads and `mainnet.base.org` for the deposits and what follows them). */ readonly rpcUrl?: string; /** * Deposit from the signer's address when the reserve runs short (`topup.ts`). * On whenever the signer can sign transactions; `false` turns it off, and * the reserve is funded by hand (`wallet.depositTx`). The wallet still * withdraws from what the reserve holds. */ readonly autoFund?: boolean; /** * The float: the coin buffer the wallet keeps (its refill floor, jittered * ±20 %) and the unit every deposit is a whole number of. A USDC amount * (`"5.00"`, `5`) or base units (`5_000_000n`). Defaults to $5.00. */ readonly float?: string | number | bigint; /** The most the wallet deposits on its own while the process runs. Defaults to ten floats. */ readonly maxAutoDeposit?: string | number | bigint; /** * Gasless deposits: the wallet funds its reserve from the address's USDC * alone, through the network's gasless depositor and a relayer that pays * the gas for a fee taken out of the deposit (`gasless.ts`). Unset: used * whenever the address cannot pay a deposit's gas itself -- it holds no * ETH, or the account signs typed data and no transactions. `true`: every * deposit. `false`: never. */ readonly gasless?: boolean; /** The gasless depositor. Else `PX402_GASLESS_DEPOSITOR`, else the preset's. */ readonly gaslessDepositor?: string; /** The facilitator gasless deposits go through. Else `PX402_SPONSOR_FACILITATOR`, else the bridge facilitator. */ readonly sponsorFacilitator?: string; /** The most fee one gasless deposit may pay: a USDC amount or base units. Defaults to $0.10. */ readonly maxSponsorFee?: string | number | bigint; /** Where the receipts and the recovery checkpoint persist. Without one they live in memory. */ readonly store?: WalletStore; /** * The `fetch` px402's own services are reached through: the issuer, the * registry, a facilitator's `/supported`, the bridge. If your network * address identifies you, make it go through a proxy you control. Defaults * to the `fetch` `wrapFetchWithPayment` wraps, and to the global `fetch` * for `createWallet`. */ readonly serviceFetch?: FetchLike; /** The `fetch` the chain's JSON-RPC calls go through. Defaults to the global `fetch`. */ readonly rpcFetch?: FetchLike; /** Where the environment variables are read. Defaults to `process.env`. */ readonly env?: Readonly>; readonly onWarning?: (message: string) => void; /** Recovery's progress, phase by phase (`px402.recover`'s `onProgress`). */ readonly onProgress?: (progress: RecoveryProgress) => void; /** * Anything else `px402.recover` takes (`privacy`, `maxFeeBps`, * `minRunwayBaseUnits`, ...), laid over what the drop-in builds. */ readonly walletConfig?: Partial>; } /** {@link wrapFetchWithPayment}'s options. */ export interface PaymentOptions extends DropInOptions { /** Told of each payment, after the wallet has appended its receipt. */ readonly onPayment?: (info: PaymentInfo) => void; } /** {@link createWallet}'s options: one of `privateKey`, `account` or `seed`. */ export interface CreateWalletOptions extends DropInOptions { /** A `0x` hex secp256k1 key: the seed and the deposits both come from it. */ readonly privateKey?: string; /** An account that signs: a viem local account, for one (`keyseed.ts`). */ readonly account?: PaymentAccount; } /** What {@link wrapFetchWithPayment} pays with: a `0x` private key, an account, or a wallet already open. */ export type PaymentSigner = string | PaymentAccount | Wallet; /** * How long after a payment the between-calls refill may wait, at most: one * issuance window plus the default hold band, the window a melt is drawn * from too (`meltScheduler.ts`). A refill straight after the payment that * drained the buffer would put the reserve's withdrawal beside that payment. */ export declare const REFILL_DELAY_MAX_SECONDS: number; /** * The `fetch` {@link wrapFetchWithPayment} returns: a `fetch`, and `close()`. * * `close()` is for a process about to exit: it waits for a top-up in flight, * melts now the change a payment left (which the wallet would otherwise melt * a random moment later, up to two minutes), and finishes saving to the * store. Skipping it loses nothing: the change is recovered from the seed * and melted at the next start, before its first payment. It only waits that * long -- and an epoch's change can no longer be melted once the epoch's * refresh window closes, so a process that never restarts should close. */ export type PaidFetch = FetchLike & { close(): Promise; }; /** * x402's `wrapFetchWithPayment`, paid with px402: a `fetch` that pays the * 402s it meets -- a merchant's own px402 entry directly, an `exact`-only * merchant through the bridge -- from a wallet derived from `signer`. * * Returns at once, with no I/O. The first request starts the wallet beside * itself; see the module docs for what starting does, and for the wait a * cold wallet's first payment makes. * * `signer` is a `0x` private key, an account ({@link PaymentAccount}; a viem * local account is one), or a {@link Wallet}: one `px402.open` or * `px402.recover` made is paid through its own `wrapFetch` (the bridge on * when a facilitator resolves), and one {@link createWallet} made keeps the * funding and the store it was created with. * * @throws RangeError at once for a malformed key; everything else when a * payment needs it (`PX402MissingSettingError`, `PX402InsufficientFundsError`, * `PX402NoCoinsError`, ...). */ export declare function wrapFetchWithPayment(fetchImpl: FetchLike, signer: PaymentSigner, options?: PaymentOptions): PaidFetch; /** * A wallet from a key, an account or a seed, recovered, and -- with a key * that can sign -- funded ahead of need: it resolves once the first top-up * has deposited (whole floats, when the reserve is short) and withdrawn to * the float, so its coins' hold starts now, long before anything is bought. * * Pay with it through `wrapFetchWithPayment(fetch, wallet)`, which keeps the * funding, the bridge and the store set here; `wallet.wrapFetch` is the * explicit path, with none of them. * * @throws PX402MissingSettingError, PX402NetworkNotDeployedError, * PX402NondeterministicSignerError, PX402InsufficientFundsError, * PX402AutoFundLimitError, and recovery's own errors. */ export declare function createWallet(options: CreateWalletOptions): Promise;