/** * The public wallet surface of §7: `px402.open`, `px402.recover`, and the * `Wallet` they both produce. * * Everything below this file is a protocol layer that can be used on its own; * this is the layer an agent developer actually holds. It owns four things — * the coin buffer, the receipt chain, the withdraw counter, and the observed * spend rate — and it owns them because each one is wrong if two callers keep * their own copy. */ import { type IssuedCoin, type KeysetStatus } from "./client.js"; import { IssuerClient, type FetchLike } from "./client.js"; import { type KeysetCommitmentReader } from "./commitment.js"; import { denomById, type Keyset } from "./denom.js"; import { PX402EpochRetiredError } from "./errors.js"; import { KeyRing } from "./keyring.js"; import { type BridgeOptions, type PaymentInfo, type QuotedPrice } from "./fetch.js"; import { type BridgeRecourseReport, type RecourseTiming } from "./recourse.js"; import { type MeltTimers } from "./meltScheduler.js"; import { type RecoveryProgress, type RecoverySources, type RecoveryResult } from "./recover.js"; import { type RefreshOutcome } from "./refresher.js"; import { ReceiptLog, type Receipt, type Reconciliation, type StoredReceipt } from "./receipts.js"; import { CoinStore, type AnonymityGauges, type PrivacyMode } from "./store.js"; /** USDC has 6 decimals; every amount in this SDK is in those base units. */ export declare const USDC_DECIMALS = 6; /** * §7's refill horizon: the wallet aims to hold at least what it spent in the * last two hours. */ export declare const REFILL_HORIZON_SECONDS: number; /** * §7's `±20 %` refill jitter. * * Not decoration: a wallet that refilled at exactly its threshold, every * time, would emit a withdrawal pattern whose timing is a function of its own * spending — which is the correlation §9.1's timing controls exist to break. */ export declare const REFILL_JITTER = 0.2; /** How far back {@link Wallet.runway} looks when measuring the spend rate. */ export declare const DEFAULT_OBSERVATION_WINDOW_SECONDS: number; /** The floor `runway ≥ max(2 h observed rate, config.min)` falls back to: $1.00. */ export declare const DEFAULT_MIN_RUNWAY_BASE_UNITS = 1000000n; /** * What a call is assumed to cost before any has been observed: $0.01, the * launch ladder's smallest rung (§4). */ export declare const DEFAULT_ASSUMED_CALL_COST_BASE_UNITS = 10000n; /** A ceiling on coins per refill, so a large target cannot become a huge request. */ export declare const DEFAULT_MAX_COINS_PER_REFILL = 64; /** * The issuer's own bound on one `/withdraw` batch. * * Mirrors `MAX_WITHDRAW_ITEMS` in `crates/px402-issuer/src/withdraw.rs`. It is * a hard ceiling rather than a preference: a larger batch is refused outright, * after the wallet has already burned the counters it planned against. So * {@link WalletConfig.maxCoinsPerRefill} is clamped to it rather than trusted. */ export declare const ISSUER_MAX_WITHDRAW_ITEMS = 64; /** * How many observed prices {@link Wallet.priceHistory} keeps. * * Bounded because it is a *shape*, not a ledger: what the next refill needs to * know is which rungs recent calls have been costing, and a longer tail only * makes the plan slower to follow a price that has moved. */ export declare const DEFAULT_PRICE_HISTORY_LIMIT = 256; /** How long a withdraw authorization stays valid, in seconds. */ export declare const DEFAULT_WITHDRAW_DEADLINE_SECONDS = 600; /** * A capability the wallet was not given. * * Its own class so that "you did not configure a reserve contract" is * distinguishable from a protocol failure: one is fixed by the operator, the * other by retrying or by recouping. */ export declare class PX402ConfigError extends Error { constructor(what: string); } /** The deployed contracts a wallet needs to fund or refill itself (§5). */ export interface ChainConfig { /** EIP-155 chain id, e.g. 8453 for Base. */ readonly chainId: number; /** The `PX402Reserve` address, `0x`-prefixed (§6.14). */ readonly reserveContract: string; /** The USDC token address, `0x`-prefixed. */ readonly usdc: string; /** `DOMAIN_SEPARATOR()`, read from the reserve contract. Required to withdraw. */ readonly domainSeparator?: Uint8Array; /** * `reserves[reserveAddr].nonce`, read from the contract. * * §5.2.2 consumes the reserve's nonce **in order** (`if (r.nonce != nonce) * revert BadNonce`), so this is not a value a wallet may invent: it has to * be read, or the authorization is rejected on chain after the issuer has * already been asked to submit it. */ readonly reserveNonce?: () => Promise; /** * `keysets(epochId)` on the reserve — §4's on-chain keyset commitment. * * Supplied by the caller, exactly like {@link reserveNonce}, or read * through {@link rpcUrl}. Without either {@link px402.open} cannot run §4's * mandatory check and warns loudly instead; see {@link KeysetVerification}. */ readonly keysetCommitment?: KeysetCommitmentReader; /** * An Ethereum JSON-RPC endpoint for this chain. With it the wallet reads * {@link reserveNonce} and {@link keysetCommitment} itself when they are not * given, and {@link px402.recover} reads the chain for its default sources * (which also need {@link deployBlock}). Every call goes through * {@link rpcFetch}; the SDK still opens no socket of its own. The provider * learns which reserve addresses you read: use one you trust. */ readonly rpcUrl?: string; /** The `fetch` the {@link rpcUrl} calls go through. Defaults to the global `fetch`. */ readonly rpcFetch?: FetchLike; /** The reserve's deployment block: where recovery's log scan starts (unless a checkpoint lets it start later). */ readonly deployBlock?: bigint; /** * Blocks per `eth_getLogs` during recovery. Defaults to 500 * (Base's public endpoints refuse more); a window the node refuses is halved. */ readonly logBlockRange?: bigint; } /** Options for {@link px402.open}. */ export interface OpenOptions { /** * **Dangerous; for tests only.** Skip the check that this seed has never * been used ({@link PX402SeedUsedError}). Opening a used seed fresh * restarts the withdraw counter at 0: the next withdrawal re-derives coins * the seed already took, which may be spent and whose reuse can link them * (§6.13). A wallet that restarts calls {@link px402.recover}. */ readonly fresh?: boolean; } /** * How {@link px402.open} satisfies §4's *"wallets and facilitators MUST reject * any keyset not committed on-chain"*. * * - `"onchain"` (the default) recomputes the keyset id and compares it against * `chain.keysetCommitment(epochId)`, refusing to open on any mismatch. * - `"caller-verified-onchain"` skips the read because the caller states they * have already done it. Spelled out rather than a boolean, because * `verify: false` is a thing that gets passed by accident and this is the * single control standing between a wallet and an issuer that can * deanonymise it. It warns either way. */ export type KeysetVerification = "onchain" | "caller-verified-onchain"; /** Shared configuration for {@link px402.open} and {@link px402.recover}. */ export interface WalletConfig { /** The 32-byte wallet seed. Every key below is derived from it. */ readonly seed: Uint8Array; /** The issuer to withdraw and refresh against. */ readonly issuer?: IssuerClient; /** * The keyset to withdraw and spend under. Verified against the chain (§4). * Without it, the wallet reads every epoch the `issuer` lists (K1). */ readonly keyset?: Keyset; /** * Keysets of earlier epochs the caller kept (K1; `keysetToJson` / * `keysetFromJson`), beside whatever the issuer serves. Only needed for an * epoch the issuer no longer lists -- one whose keys it lost -- whose coins * can still be spent whole while the registry accepts them, and found by * `px402.recover` only under their keyset. Each is checked against the * chain (§4) like any other. */ readonly keysets?: readonly Keyset[]; /** Defaults to `"onchain"`. See {@link KeysetVerification}. */ readonly keysetVerification?: KeysetVerification; /** How long the §4 check waits on `chain.keysetCommitment`. */ readonly keysetCommitmentTimeoutMs?: number; /** Which reserve index this wallet uses. Defaults to 0. */ readonly reserveIndex?: number; readonly chain?: ChainConfig; /** Defaults to `"strict"` (§7). */ readonly privacy?: PrivacyMode; /** * The width of the band each coin's §9.1 hold is drawn from, in whole * seconds: a coin is spendable under `strict` after * `ISSUANCE_WINDOW_SECONDS + U[0, holdJitterSeconds)`, one draw per coin. * Defaults to {@link DEFAULT_HOLD_JITTER_SECONDS}; `0` is a fixed * one-window hold. The draw is derived from the coin itself, so a wallet * recovered from its seed lands every coin on the same instant. */ readonly holdJitterSeconds?: number; /** The `config.min` of §7's refill rule. */ readonly minRunwayBaseUnits?: bigint; /** Used by {@link Wallet.runway} until a real call cost has been observed. */ readonly assumedCallCostBaseUnits?: bigint; readonly observationWindowSeconds?: number; /** * Coins per refill. Defaults to {@link DEFAULT_MAX_COINS_PER_REFILL} and is * clamped to {@link ISSUER_MAX_WITHDRAW_ITEMS}, which the issuer enforces. */ readonly maxCoinsPerRefill?: number; /** How many observed prices to keep. Defaults to {@link DEFAULT_PRICE_HISTORY_LIMIT}. */ readonly priceHistoryLimit?: number; readonly withdrawDeadlineSeconds?: number; readonly now?: () => number; readonly randomBytes?: (n: number) => Uint8Array; readonly onWarning?: (message: string) => void; /** The published §8 crowd-size gauges, when the wallet has them. */ readonly anonymity?: AnonymityGauges; /** A stored receipt chain to resume. Verified on load. */ readonly receipts?: readonly StoredReceipt[]; /** * The most this wallet will pay a relayer, in basis points (v3 §7). * Defaults to the protocol's launch `MAX_FEE_BPS`, 100. A facilitator * quoting more is refused with `PX402FeeError` before any coin is presented. */ readonly maxFeeBps?: number; /** How long a facilitator's `/supported` is trusted. Defaults to 300 s. */ readonly supportedTtlSeconds?: number; /** * The most bytes one `X-PAYMENT` header may take. Defaults to * `DEFAULT_MAX_PAYMENT_HEADER_BYTES`, 7,680 bytes (nine launch-ladder * coins), under nginx's default 8 KiB for one header line and Node's 16 KiB * for the header section. A price whose cover needs more coins is paid in * fewer, larger ones (one split, its residual refreshed); a pool with no * cover that fits is refused with `PX402HeaderBudgetError` before any coin * is retired, and the wallet's readiness and refill plan count only what one * payment can carry. Raise it only if every merchant you pay accepts larger * headers (12,288 reaches fifteen coins); the facilitator's coin cap * (`MAX_COINS_PER_SPEND`) bounds a payment either way. */ readonly maxPaymentHeaderBytes?: number; /** * The `fetch` that reads a facilitator's `/supported`. Defaults to the * `fetch` each {@link Wallet.wrapFetch} wraps — the wallet's own network * path — so a wallet opens no sockets of its own. */ readonly supportedFetch?: FetchLike; /** * The `fetch` for a bridge facilitator (v3 §26): `/verify` and `/settle` * when a wrapper's `bridge` names no `fetch` of its own, and the * `/bridge/lookup` of {@link Wallet.pursueBridgeRecourse}. The wallet, not * a merchant, posts a bridge payment from its own network path (§26.9): * route this through a proxy you control. Defaults to the wrapped `fetch` * for payments, and to {@link supportedFetch} -- then the global `fetch` -- * for the recourse, which runs outside any wrapper. */ readonly bridgeFetch?: FetchLike; /** * The protocol windows {@link Wallet.pursueBridgeRecourse} is timed by. * Defaults to the launch values: `LEASE_TTL` 60 s, `RECORD_GRACE` 3600 s, * `PAYOUT_DEADLINE` 86400 s. Set them only to match a deployment whose * contract was built with other values. */ readonly bridgeRecourse?: Partial; /** * The registry's own view of a coin's residual, for §6.6 refresh. * * Optional, and off by default: reading `GET /spent/{C_p}` from the wallet * tells the registry which network address holds that coin, which is the * payer↔coin edge §9 keeps it from having. Without it the wallet melts * against its own `spent`, which is a safe floor — see * {@link RefresherOptions.residualOf}. The registry's residual is * `face − spent + refundCredit` ({@link IssuerClient.coinSpent}). */ readonly residualOf?: (coin: IssuedCoin) => Promise; /** Chain totals for reconciliation, when they are known without a scan. */ readonly chainTotals?: { readonly deposits: bigint; readonly reclaims: bigint; }; /** * How the wallet waits for its background melts and for the separation * between a melt and a spend (v3 §25.2, `meltScheduler.ts`), and, in a * bridge payment, before it delivers an authorization again (v3 §26.8 * step 5). Defaults to `setTimeout`, with the background melt `unref`'d so * it never keeps a process alive. Injectable for the same reason * {@link now} is: a test that pins the clock must own the timers. */ readonly meltTimers?: MeltTimers; } /** {@link px402.recover}'s configuration: {@link WalletConfig} plus the read ports. */ export interface RecoverConfig extends WalletConfig { /** * The read ports §6.10 walks. Optional: without them the wallet builds the * SDK's public ones ({@link publicRecoverySources}) from its `issuer` (which * needs a `registryUrl`) and `chain.rpcUrl` with `chain.deployBlock`. Pass * your own to read through your own node or mirrors. */ readonly sources?: RecoverySources; readonly reserveGapLimit?: number; readonly coinGapLimit?: number; readonly maxRefreshDepth?: number; /** * Told how far recovery has got, phase by phase ({@link RecoveryProgress}): * the issuer's log, each reserve index, each `eth_getLogs` window of a * funded reserve (blocks done of total), each counter searched, each spent * total read. On a used seed recovery reads for a minute or more; say so. * A hook that throws is ignored. */ readonly onProgress?: (progress: RecoveryProgress) => void; /** * The text a previous recovery's {@link Wallet.recoveryCheckpoint} returned, * so the deposit-log scan starts where that one left off instead of at * `chain.deployBlock`. Used only with the SDK's public sources (no * `sources`), only where to start reading logs, and only when it holds up: * 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 this chain now is ignored with a warning, and the * scan reads from `chain.deployBlock` (`sources.ts`). */ readonly recoveryCheckpoint?: string; /** * When the reserves' `Deposit` / `BalanceReclaimed` logs are read, with the * SDK's public sources. Their sums feed only {@link Wallet.reconcile}'s * chain totals; finding the coins and the withdraw counter needs no more * of a reserve than whether it was ever funded (one `eth_call`). * * - `"blocking"` (the default): read before `recover` returns, as always. * Without a checkpoint that is every block since `chain.deployBlock`. * - `"background"`: `recover` returns once the coins are found, and the * logs are read after it. Until they are, `reconcile()` without totals * throws; {@link Wallet.chainTotals} resolves once they are in, and * {@link Wallet.recoveryCheckpoint} then says where the scan reached. The * drop-in uses this with a store, so a restart pays without waiting for * the scan and the next one starts where it reached. * - `"on-demand"`: as `"background"`, but the logs are read only when * {@link Wallet.chainTotals} is first asked for. The drop-in uses this * without a store: there the scan's checkpoint cannot be kept, its totals * feed nothing but `reconcile()`, and its few hundred calls would keep a * short-lived process from exiting. */ readonly depositLogScan?: "blocking" | "background" | "on-demand"; } /** A reserve's chain totals: what {@link Wallet.reconcile} measures the receipts against. */ export interface ReserveTotals { readonly deposits: bigint; readonly reclaims: bigint; } /** * Whether a figure was measured from this wallet's own payments or assumed. * * The distinction is not decoration: `"assumed"` is what a wallet reports * before it has ever paid for anything, which is exactly when an agent asks * "can I start working?". */ export type CostBasis = "observed" | "assumed"; /** * §7's `{ calls, days, usdc }`, plus what a caller needs to tell capacity from * money. * * # Everything here is measured against **spendable** value * * Not `balance()`. A coin inside §9.1's issuance-window hold, and a coin §7 * retired at a merchant, are both real money and neither can pay for the next * call. A runway computed on the balance therefore reports capacity the wallet * does not have — measured in dogfooding as 81 calls for a wallet that could * not make one. * * The three value fields are a partition of the buffer, so the money that is * *not* capacity is visible rather than absent: * * - {@link spendableBaseUnits} — offerable to a merchant right now; * - {@link heldBaseUnits} — inside the hold, offerable at {@link heldUntil}; * - the rest of {@link balanceBaseUnits} — retired residual, offerable only * after a §6.6 {@link Wallet.refresh}. */ export interface Runway { /** * How many more calls the **spendable** value covers at * {@link callCostBaseUnits}. * * Zero with a non-zero {@link heldBaseUnits} means "not yet", not "broke"; * {@link heldUntil} says when. */ readonly calls: number; /** * How many days that lasts at the observed call rate. * * `Infinity` when nothing has been spent yet and there is spendable value — * at zero burn a balance does last forever, and reporting `0` would read as * "refill now", which is the opposite of the truth. */ readonly days: number; /** * The **spendable** value as a USDC display value, matching {@link calls}. * * Exact base units are the three fields below; {@link Wallet.balance} is the * whole buffer. */ readonly usdc: number; /** Residual a merchant can be offered right now, in base units. */ readonly spendableBaseUnits: bigint; /** Residual waiting out §9.1's hold. Becomes spendable by waiting. */ readonly heldBaseUnits: bigint; /** The whole buffer, equal to {@link Wallet.balance}. */ readonly balanceBaseUnits: bigint; /** * The per-call cost {@link calls} divides by: the **presented** cost, price * plus relayer fee (v3 §7), because that is what the next call's coins must * cover. Under a fee the presented total is rounded up to the smallest * denomination (§25.1): a wallet paying 25 bps on $0.40 calls reports $0.401 * here, and at 100 bps on $0.003 calls $0.004. */ readonly callCostBaseUnits: bigint; /** * The part of {@link callCostBaseUnits} that is relayer fee -- the rate's * fee plus the rounding overage, averaged over the observed calls (v3 §7, * §25.1). `0n` while {@link costBasis} is `"assumed"`: nothing measured it. * `callCostBaseUnits − callFeeBaseUnits` is what the merchants were paid. */ readonly callFeeBaseUnits: bigint; /** * Where {@link callCostBaseUnits} came from. * * `"assumed"` means no payment has been observed inside the observation * window and this is `assumedCallCostBaseUnits` — a configured guess. A * wallet holding $0.81 reports 81 calls at the $0.01 default while facing a * $2.50 resource it cannot afford once, so a caller that acts on `calls` * without reading this is acting on a number nothing measured. */ readonly costBasis: CostBasis; /** * Unix seconds at which the first held coin becomes spendable, or `null` * when nothing is held. * * `null` therefore means "waiting changes nothing" — either there is * spendable value already, or the remedy is a withdrawal or a refresh rather * than the clock. */ readonly heldUntil: number | null; /** * The buffer by key epoch, oldest first -- present only while the wallet * holds coins of more than one epoch (K1). A new epoch changes nothing an * agent has to do: old coins spend, and their change melts into the new * epoch. This is where that migration shows. */ readonly epochs?: readonly EpochBalance[]; } /** * One key epoch's share of the buffer (K1), in {@link Runway.epochs} and * {@link Readiness.epochs}. The value fields are this epoch's part of the * wallet's: spendable now, held by §9.1's hold, and retired residual * waiting for a melt (which mints into the {@link status} `current` epoch). */ export interface EpochBalance { readonly epochId: bigint; /** `0x`-prefixed. */ readonly keysetId: string; /** * The wallet's view of the epoch: `current` -- it withdraws under it; * `signing-retired` -- an older epoch whose coins still spend and melt; * `melt-only` -- its spend window closed, its coins wait for a melt; * `expired` -- its refresh window closed too; `retired` -- the issuer no * longer holds it (`EPOCH_RETIRED`): spend its coins whole while they * spend, see {@link Readiness.retiredEpochs}. */ readonly status: Exclude | "retired"; readonly spendableBaseUnits: bigint; readonly heldBaseUnits: bigint; /** Residual of this epoch's coins that a melt returns as coins of the current epoch. */ readonly refreshingBaseUnits: bigint; /** Coins of the epoch with value on them. */ readonly coins: number; /** Unix seconds: the epoch's spend window closes (§4). */ readonly spendableUntil: number; /** Unix seconds: its refresh window closes; after it, its coins are dead. */ readonly refreshableUntil: number; } /** * Why a wallet can or cannot pay right now. * * Three states, because three different things go wrong and each has a * different remedy: * * - `"ready"` — spendable value covers the amount. Pay. * - `"holding"` — it will, at {@link Readiness.at}, once §9.1's issuance-window * hold expires — or once the residual an earlier payment retired has been * melted (§6.6) and its fresh coins' hold has expired. Wait, or * {@link Wallet.ready}. * - `"insufficient"` — waiting will not fix it. Withdraw * ({@link Wallet.prewarm}) or reclaim retired residual * ({@link Wallet.refresh}). {@link Readiness.fragmented} says when the * value is there and its coins are too small for one payment to carry it. * * "Covers" means what **one payment** can carry: the largest coins a payment * holds -- the facilitator's cap, or fewer under the `X-PAYMENT` header * budget -- not the buffer's total. */ export type ReadyStatus = "ready" | "holding" | "insufficient"; /** * The answer to "can I spend, and if not, when?" — synchronous, no I/O. * * Flat rather than a discriminated union so it logs and serializes as one * object; {@link status} says which of {@link at} and * {@link shortfallBaseUnits} carries the news. */ export interface Readiness { readonly status: ReadyStatus; /** The amount asked about. Defaults to 1 base unit: "anything at all". */ readonly requestedBaseUnits: bigint; /** Residual a merchant can be offered right now. */ readonly spendableBaseUnits: bigint; /** Residual inside §9.1's hold — value the clock alone will release. */ readonly heldBaseUnits: bigint; /** * Residual earlier payments retired (§7) that this wallet's own melt * returns as fresh coins (§6.6) — value a melt and then the fresh coins' * hold release. Since v3 §25.2 that melt runs in the background, up to a * hold window after the payment that made the residual, so this is often * non-zero just after a payment. Zero for a wallet with no issuer to melt * at: no wait reaches its retired residual. */ readonly refreshingBaseUnits: bigint; /** * Unix seconds at which spendable value first covers * {@link requestedBaseUnits}, or `null` when waiting is not the answer. * * `null` under `"ready"` (nothing to wait for) and under `"insufficient"` * (nothing that waiting reaches). A caller therefore never has to guess * whether `null` means "now" or "never" — {@link status} already said. * * When only {@link refreshingBaseUnits} closes the gap, the fresh coins do * not exist yet and this is a bound: the background melt's due time (or * now) plus the longest hold a coin carries. {@link Wallet.ready} melts at * once in that case and wakes at the fresh coins' own unlocks. */ readonly at: number | null; /** `at` minus now, in seconds, or `null` in the same two cases. */ readonly secondsRemaining: number | null; /** * How much more value the wallet needs beyond spendable, held **and** * refreshing, in base units -- or, when {@link fragmented}, how far the * most one payment can carry falls short. Zero unless {@link status} is * `"insufficient"`. */ readonly shortfallBaseUnits: bigint; /** * `true` when the wallet holds the value and cannot present it in one * payment: every cover needs more coins than one `X-PAYMENT` header * carries (`PX402HeaderBudgetError` on the spend path). Only ever `true` * under `"insufficient"`. Waiting does not change it; larger coins do -- * {@link Wallet.prewarm} withdraws them. */ readonly fragmented: boolean; /** The buffer by key epoch, while it spans more than one (K1); see {@link Runway.epochs}. */ readonly epochs?: readonly EpochBalance[]; /** * Every epoch whose coins the issuer can no longer refresh * (`EPOCH_RETIRED`, K1), each naming what it strands: whole coins to spend * whole before {@link PX402EpochRetiredError.spendableUntil}, and residual * only a recoup returns. Usually empty. Their whole coins still count as * spendable above; their residual is in no field but this one. */ readonly retiredEpochs: readonly PX402EpochRetiredError[]; } /** Options for {@link Wallet.recordRefund}. */ export interface RecordRefundOptions { /** * What the refund restored, in base units: for a px402 payment, the * `amount` the merchant signed its refund over (§6.7), at most the price, * since the relayer's fee is not refunded (v3 §7); for a bridge payment, at * most the presented total. Defaults to that most: the whole price, or the * whole presented total. */ readonly amountBaseUnits?: bigint; } /** Options for {@link Wallet.ready}. */ export interface ReadyOptions { /** How much must be spendable. Defaults to 1 base unit: "anything at all". */ readonly amountBaseUnits?: bigint; /** How long to wait before giving up. Defaults to {@link DEFAULT_READY_TIMEOUT_MS}. */ readonly timeoutMs?: number; /** * How to wait. Defaults to a real timer. * * Injectable because the wallet's clock is (`config.now`): a test that pins * one and not the other would wait on wall time for a clock that never * moves, which is the hang this parameter exists to make impossible. */ readonly sleep?: (ms: number) => Promise; } /** * {@link Wallet.ready}'s default patience at the default band: the longest * hold a coin can carry — one issuance window plus the whole jitter band — * plus a margin. * * Sized to the thing being waited for — §9.1's hold is the only delay `ready` * can wait out — so a timeout means something went wrong rather than "you * guessed the number too low". A wallet with a wider `holdJitterSeconds` * sizes its own default from that band; this constant is the default case. */ export declare const DEFAULT_READY_TIMEOUT_MS: number; /** An EVM transaction the SDK builds but never signs. */ export interface UnsignedTx { /** `0x`-prefixed contract address. */ readonly to: string; /** `0x`-prefixed calldata. */ readonly data: string; /** Always `"0x0"`: USDC moves as an ERC-20 transfer, never as native value. */ readonly value: string; readonly chainId: number; } /** * What {@link Wallet.depositTx} returns: the two calls a depositor sends, in * order, and neither of them signed. */ export interface DepositRequest { /** The reserve being credited — this wallet's own address. */ readonly reserveAddr: string; readonly amountBaseUnits: bigint; /** The same amount as a USDC decimal string. */ readonly usdc: string; /** ERC-20 `approve(reserveContract, amount)`, sent first. */ readonly approve: UnsignedTx; /** `deposit(reserveAddr, amount)` on the reserve contract. */ readonly deposit: UnsignedTx; } /** Per-call overrides for {@link Wallet.wrapFetch}. */ export interface WrapOptions { readonly privacy?: PrivacyMode; readonly onPayment?: (info: PaymentInfo) => void; /** * Pay merchants that quote only `exact` through this bridge facilitator * (v3 §26). Off by default. Its `fetch` defaults to * {@link WalletConfig.bridgeFetch}, then to the wrapped `fetch`. */ readonly bridge?: BridgeOptions; } /** * A USDC amount to base units, without ever touching a float. * * `bigint` is taken as base units already. A string or number is a USDC * decimal — `"41.55"` is 41_550_000 — parsed by shifting the decimal string, * because `41.55 * 1e6` is `41549999.999999996` in IEEE-754 and this is a * payments API (§6.14). Shared with `dropin.ts`, whose `float` reads the same * way; not part of the package's exports. */ export declare function toBaseUnits(usdc: string | number | bigint): bigint; /** * A px402 wallet. * * Holds coin secrets and the seed, so the whole object is secret material. * Nothing here logs, prints or embeds key bytes in an error. */ export declare class Wallet { /** The coin buffer. Exposed because recovery and pre-warm both write to it. */ readonly store: CoinStore; /** The local receipt chain (§7). Never transmitted — see `receipts.ts`. */ readonly receipts: ReceiptLog; readonly reserveIndex: number; /** This wallet's 20-byte reserve address, derived from the seed. */ readonly reserveAddress: Uint8Array; private readonly config; private readonly seed; private readonly samples; /** The bounded price histogram §7's refill plan is shaped by; see {@link priceHistory}. */ private readonly prices; /** * Every keyset this wallet holds coins of, each checked against the chain * (K1). `undefined` for a wallet given no keyset at all. */ private readonly ring; private counter; private totals; private refresher; /** * When this wallet melts (v3 §25.2): after the payment that made the * residual, in the background, never beside a spend. `undefined` for a * wallet with no issuer or no keyset, which cannot melt at all. */ private readonly melts; /** One `/supported` cache for every wrapper this wallet hands out (v3 §7). */ private readonly supported; /** {@link coinsPerPayment}, once computed per (keyset, tagged). */ private readonly paymentCoinCaps; /** The {@link pursueBridgeRecourse} in flight, which a second call joins. */ private recoursePursuit; /** * Coins of a payment recorded refunded (§6.7) whose registry standing is * not read yet, by key: never melted until it is ({@link readRefunds}). */ private readonly refundReads; /** The {@link readRefunds} in flight, which a second call joins. */ private refundRead; /** What {@link recoveryCheckpoint} returns: set by {@link px402.recover}. */ private scanCheckpoint; /** * The chain totals being read after recovery (`depositLogScan: * "background"`), and how to read them again if that read failed. */ private totalsRead; /** * `keysets` is one keyset, or (K1) a {@link KeyRing} of every epoch the * wallet holds -- what `px402.open` and `px402.recover` build. */ constructor(config: WalletConfig, keysets: Keyset | KeyRing | undefined); /** * The keyset this wallet withdraws under, and mints change under, now: the * newest it holds whose spend window is open (K1) -- or, with none open, * the newest it holds. `undefined` for a wallet with no keyset. */ get keyset(): Keyset | undefined; /** `keccak256(canonicalBytes(keyset))`, 32 bytes — verified, never trusted. */ get keysetId(): Uint8Array | undefined; /** * Every keyset this wallet holds coins of, oldest epoch first (K1): the * epochs the issuer lists and any kept copies given, each checked against * the chain. Keep a copy of each (`keysetToJson`) if you want to spend an * epoch's coins after its issuer stops listing it. */ get keysets(): readonly Keyset[]; /** The {@link KeyRing} behind {@link keysets}, or `undefined` with no keyset. */ get keyring(): KeyRing | undefined; /** * Re-reads the issuer's epochs and adds every new one the chain commits * (K1), marking retired any held epoch the issuer no longer lists. * * A new epoch asks nothing of an agent: the wallet calls this itself when * the issuer refuses a withdrawal or a melt `KEYSET_UNKNOWN` -- what a * long-running process sees once the issuer's new epoch is committed -- * and every `px402.recover` reads the epochs afresh. Resolves to how many * keysets were added; `0` for a wallet opened with a pinned `keyset` or * with no issuer, which this never re-reads. * * @throws PX402KeysetCommitmentError when the issuer serves a keyset the * chain commits differently -- the §4 refusal `open` makes. */ syncKeysets(): Promise; /** The withdraw keyset now, else the newest held. */ private currentKeyset; /** * The next withdraw counter. Strictly monotonic for the wallet's lifetime. * * §6.13: `r` is a function of the blinding ikm alone, so two coins reaching * the same counter reuse `r` under the same denomination key — a silent * unlinkability failure nothing downstream can detect. */ get nextCounter(): bigint; /** Total residual value in the buffer, in base units. */ balance(): bigint; /** * The prices this wallet has actually paid, oldest first, bounded to * {@link WalletConfig.priceHistoryLimit}. * * This is what {@link prewarm} shapes its denomination plan from, and it is * deliberately a list of amounts rather than a mean: the mean of $0.001 and * $4.096 is a price nothing costs, while the *multiset* of rungs those two * decompose into is a pool that covers both exactly. See {@link Runway} for * the mean, which answers a different question (how many calls are left). * * Derived from the receipt chain on load, so a wallet resumed with * `config.receipts` resumes it. A wallet rebuilt by §6.10 recovery has no * receipts and therefore no histogram — correctly: the registry knows what * each coin was worth and never what it bought. * * A price a payment was refused for because its coins were too small for * one `X-PAYMENT` header (`PX402HeaderBudgetError`) is recorded too, for * this process: it is a price the wallet faces, and the next refill has to * buy coins that carry it. It leaves no receipt, so a resumed wallet does * not see it. */ priceHistory(): readonly bigint[]; /** * The part of {@link balance} that can still be offered to a merchant. * * §7 retires a coin the moment a merchant sees it, so a wallet can hold a * full balance and have nothing to pay with: the difference is residual * waiting on §6.6 refresh. Every decision about *whether to withdraw* is * taken against this figure rather than `balance()`, because a refill sized * against money that cannot be offered is a refill that never happens, and a * `strict` wallet then fails closed with a full buffer. */ spendableBalance(): bigint; /** * Reclaim the residual §7 retired, as fresh coins (§6.6). * * Safe to call at any time and safe to call concurrently — a second call * while one is running joins it rather than opening a second melt session * for the same coin. An application rarely needs it: the wallet melts by * itself after each payment that leaves residual, in the background and * never beside a spend, and `ready()` melts what an earlier process left, * and residual only a melt can turn into the amount it waits for (v3 * §25.2). A call here melts **now**, whatever is in flight; the next * payment still keeps its separation from it. * * Never throws for a protocol failure: a coin whose melt did not complete * stays queued and is retried, because `γ` is idempotent per * `⟨C⁰_p, attempt, h_C⟩` and a re-request resumes the same session. It does * throw {@link PX402ConfigError} when the wallet was never given an issuer * or a keyset, which is a deployment mistake rather than a protocol one. */ refresh(): Promise; /** * Pursue the payer's recourse for every bridge payment not confirmed * delivered (v3 §26.8 step 7; `recourse.ts`). Call it between calls, like * {@link refresh}, and save the receipt file after it: the schedule lives * there, so a restarted wallet carries on where this one stopped. * * A bridge facilitator holds the payment's amount until the merchant is * paid or the coins come back. For each receipt whose recourse is due -- * first at `settleAt + LEASE_TTL + 2·RECORD_GRACE` -- this asks the * facilitator's `/bridge/lookup`; unless it says `paid` or `refunded`, it * files the payer's own dispute with the issuer, and when no relayer * recorded, the registry's cancel request, whose fallback opens * `PAYOUT_DEADLINE` later, and asks again then. A recourse that ends * `refunded` appends the compensating `refunded` receipt, and the registry * credits the coins: the wallet reads them back before this returns * ({@link readRefunds}), counts the value, and its melt collects it. One * that ends `not-committed` -- the registry never committed the payment, * so its coins were never debited -- closes the same way: the compensating * receipt for the presented total, and the coins read back, counted and * melted. * * Never throws for a service's failure: a request that fails is asked * again later. Throws {@link PX402ConfigError} for a wallet with no issuer. * A second call while one runs joins it. */ pursueBridgeRecourse(): Promise; private pursueRecourseOnce; /** {@link WalletConfig.bridgeRecourse} over the launch values. */ private recourseTiming; /** Whether the chain already holds a `refunded` entry for these terms. */ private hasRefund; /** The chain's `refunded` entry for these terms, when it holds one. */ private refundOf; /** * §7's `{ calls, days, usdc }`, measured against what can actually be spent. * * One synchronous pass over the buffer, no I/O: it is on the hot path * because an agent asks it before every batch of work. * * See {@link Runway} for why this is not computed from {@link balance}, and * for what {@link Runway.costBasis} is protecting a caller from. */ runway(): Runway; /** * The buffer by key epoch (K1), as `{ epochs }` -- or nothing while every * coin with value is of one epoch. */ private epochsField; /** {@link EpochBalance.status}: the wallet's own view of one epoch at `now`. */ private epochStatus; /** * Every epoch the issuer can no longer refresh, with what it strands * (K1): {@link Readiness.retiredEpochs}. */ retiredEpochs(): readonly PX402EpochRetiredError[]; /** * Can this wallet spend `amountBaseUnits` right now, and if not, when? * * Synchronous, no I/O, safe on a hot path. This is the affordance the naive * boot sequence was missing: `open → deposit → prewarm → pay` throws under * `strict`, correctly, because §9.1 holds every coin for at least one * issuance window — each coin its own hold, drawn from a band — so a * withdrawal cannot be timing-linked to the spend that follows it. The hold * is not the defect. Having no way to ask about it was. * * The answer for an amount is the **k-th soonest** coin that covers it, not * the last coin to clear: with per-coin holds those differ, and waiting for * the whole buffer to clear when three coins would do is a minute parked for * nothing. * * The default amount is one base unit — "is anything at all spendable?" — * rather than a call's cost, because the cost estimate is a guess until a * payment has been observed (see {@link Runway.costBasis}) and a readiness * answer built on a guess is the defect one layer up. Pass the price you * actually face. */ readiness(amountBaseUnits?: bigint): Readiness; /** * Wait until `amountBaseUnits` is spendable (§9.1's hold) -- in coins one * payment can carry -- then return. * * What an agent's boot sequence wants to write: * * ```ts * await wallet.prewarm(target); * await wallet.ready({ amountBaseUnits: price }); * const res = await fetch402(url); * ``` * * # What the hold does not do: a first spend soon after a withdrawal * * The hold delays a coin's first spend by one issuance window plus a * per-coin jitter (60-120 s by default). It does not hide which withdrawal * the spend came from. A payment made shortly after the payer's own * withdrawal can be linked to it by timing whenever few other wallets * withdraw in between. The §9.1 anonymity floor (reserves, coins per * denomination) does not bound this. The answer is the order of operations: * **pre-fund a buffer well before you spend** -- `prewarm` at start-up or on * a schedule, long before the calls that need it -- and let the hold pass, * so the withdrawal and the spend are separated by much more than the hold. * The sequence above is correct; pre-funding earlier keeps the spend further * from its withdrawal. A hold measured against the crowd (spend only after * enough other reserves have withdrawn) is the documented future option * (v3 §25.3). * * # It melts what an earlier process left -- here, never inside a payment * * Residual an earlier process retired and never melted (an agent that paid * and exited before its background melt ran) is melted when this returns or * throws, after its hold logic and before the first payment of this process, * and the first payment then keeps its separation from that melt (v3 §25.2). * Once this process has paid, residual belongs to the background timetable * and this melts it only for the next case. * * # It melts residual now when only that residual covers the amount * * Residual a payment retired waits up to a hold window for its background * melt, and {@link readiness} reports it as `"holding"`, not * `"insufficient"`. When the amount needs it, this melts it at once -- * after any payment in flight and out the separation after it, never * beside a spend -- then waits out the fresh coins' hold, which keeps the * payment that follows at least an issuance window from the melt. The melt * itself is not counted against `timeoutMs`. * * # It waits for the clock and its own melt, and for nothing else * * A wallet that is short of money, rather than short of *aged* money, gets * {@link PX402NoCoinsError} immediately instead of burning the timeout: the * remedy there is {@link prewarm} or {@link refresh}, and sleeping through a * minute to be told so is worse than being told now. * * # No polling * * Each wait is sized to the next unlock {@link readiness} named, so a * one-minute hold costs one sleep. The loop is bounded by the timeout * divided by the minimum wait, which is what keeps an injected clock that * never advances from becoming a hang — it becomes a * {@link PX402NoCoinsError} naming the state instead. * * @throws PX402NoCoinsError when the amount is unreachable by waiting, or * when the timeout expires first. * @throws PX402HeaderBudgetError when the value is there and its coins are * too small for one payment to carry it ({@link Readiness.fragmented}): * waiting does not change that, {@link prewarm} does. */ ready(options?: ReadyOptions): Promise; /** * v3 §25.2's boot melt: residual already queued before this process made * its first payment, melted now. Never throws -- a melt that fails stays * queued for the background timetable, exactly as a failed background melt * does. */ private meltLeftovers; /** {@link ready}'s hold logic. */ private waitOutHold; /** * §7's refill target: `max(2 h observed rate, config.min)`, jittered ±20 %. * * The jitter is applied here rather than at the call site so that every * path into a refill gets it — a caller who computed the target themselves * and skipped the jitter would emit exactly the periodic withdrawal pattern * §9.1 is trying to avoid. */ refillTarget(): bigint; /** * True when the **spendable** buffer is below {@link refillTarget} -- or * when it holds the value of the largest price this wallet has seen and * cannot present it in one payment, because its coins are too small for one * `X-PAYMENT` header to carry (see {@link Readiness.fragmented}). Either * way {@link prewarm} is the remedy. */ needsRefill(): boolean; /** * Pre-warm the buffer to `target` base units (§7), withdrawing the * difference. * * Coins arrive unspendable: `strict` holds each for at least one issuance * window (§9.1), and for a per-coin span beyond it, which is why this is * called *pre*-warm — a wallet that withdraws at the moment it needs to pay * has already lost the timing separation. The hold alone does not restore * it: at low withdrawal rates a first spend made soon after its own * withdrawal can be linked to it by timing (v3 §25.3). Withdraw well before you spend -- at start-up, or on a * schedule of your own -- and let the hold pass; see {@link ready}. * * The counter advances only on success, so an interrupted withdrawal is * finished by calling this again: the plan is a pure function of * `(seed, reserveAddr, counter)` and re-posting it is idempotent at the * issuer. * * The deficit is measured against {@link spendableBalance}, not * {@link balance}: residual that §7 has retired is real money and cannot pay * for anything, so counting it here would make a wallet decline to withdraw * while it has nothing to spend. {@link refresh} is what returns that value * to the spendable side; this is what covers the gap until it does. * * # With no argument this funds a policy floor, not a price * * `target` defaults to {@link refillTarget} — `max(2 h observed rate, * config.min)` — which before any observed spend is `config.min` and has no * relationship to what a call costs. Dogfooding put 0.81 USDC behind a 50 * USDC deposit facing a 2.50 USDC resource. The policy is deliberate and * unchanged; what changed is that a buffer too small for a single call now * says so through `onWarning` instead of failing on the next payment. * * # Coins a payment can carry * * One payment carries what the `X-PAYMENT` header budget holds -- nine * coins at the default 7,680 bytes, never more than the facilitator's * fifteen (`payload.ts`). So the plan never shapes a price into more * coins than that -- a price whose exact cover would need more is bought as * fewer, larger coins -- and when the buffer holds the value of the largest * price it has seen but in coins too small to carry it * ({@link Readiness.fragmented}), this withdraws at least one cover of that * price even at or above `target`. A price a payment was refused for * (`PX402HeaderBudgetError`) counts as seen. */ prewarm(target?: bigint): Promise; /** * §7's refill policy is a floor, not a price. Say so when the floor lands * below one call. * * Measured against spendable **plus** held value, because coins inside * §9.1's hold are money that is on its way — warning about those would train * an integrator to ignore this. Measured against the *current* estimate, * which before a first payment is `assumedCallCostBaseUnits`; the message * names that basis, because a warning derived from a guess should not read * like a measurement. */ private warnIfBelowOneCall; /** `onWarning` if the caller wired one, `console.warn` otherwise (as `store.ts`). */ private warn; /** * An **unsigned** deposit for the user's own external wallet (§7). * * The SDK never holds the depositor key and this call proves it: what comes * back is calldata. §5.2.1 does not record `msg.sender`, so the funder may * be any address — only `reserveAddr` can ever reclaim — which is what * makes an external depositor wallet a real boundary rather than a * bookkeeping one. * * Two transactions, in order: ERC-20 `approve` to the reserve contract, * then `deposit`. USDC is an ERC-20, so a bare transfer to the contract * would credit nobody. */ depositTx(usdc: string | number | bigint): DepositRequest; /** * Wrap a `fetch` so x402 payments happen transparently (§7). * * `privacy: "strict"` is the default and fails closed with * `PX402NoCoinsError`; `"besteffort"` is the explicit opt-in to spending * fresh coins. There is no silent fallback between them. * * Every settled payment appends one receipt. A payment that does not settle * appends nothing — no value moved, so there is nothing to reconcile. * * A payment whose cheapest cover would not fit one `X-PAYMENT` header * (`maxPaymentHeaderBytes`) throws `PX402HeaderBudgetError` before any coin * is retired or sent. The wallet does not withdraw inside the payment -- a * withdrawal just before a spend is the timing link §9.1's hold exists to * break, and fresh coins could not pay before the hold anyway. It records * the price, so {@link needsRefill} turns true and the next {@link prewarm} * buys coins that carry it. */ wrapFetch(inner: FetchLike, options?: WrapOptions): FetchLike; /** * What a 402 asks, read as {@link wrapFetch} with the same `bridge` would * pay it ({@link quotedPrice}): on this wallet's network, through this * wallet's `/supported` cache and {@link WalletConfig.supportedFetch}, so * the quote and the payment choose the same entry (v3 §28.7) and read * `/supported` once between them. */ quotedPrice(response: Response, options?: { readonly bridge?: BridgeOptions; }): Promise; /** * The bridge (v3 §26) a wrapper is given, with its `fetch` defaulting to * {@link WalletConfig.bridgeFetch}, and the network the bridge pays on: the * reserve's chain, when the wallet knows it. */ private bridgeOptions; /** * Append the compensating entry for a refunded spend (§6.7). * * Appended, never edited: an in-place status change is precisely the * rewrite the receipt chain exists to make impossible. * * The entry is for what the refund **restored**, which is what * {@link reconcile} nets against the coins once they are read back: * * - a px402 payment: the `amount` the merchant signed the refund over * (`⟨H(contractTerms), amount⟩`), at most the price -- the relayer's fee * is never refunded (v3 §7), and the registry restores no more than * `merchant_amount`. Defaults to the whole price. * - a bridge payment: its cancel refund restores the presented total, fee * included (v3 §26.6). Defaults to that. * * Pass {@link RecordRefundOptions.amountBaseUnits} when the merchant * refunded less. The entry's fee is the part of the refund above the price * -- zero for a px402 refund, the whole fee for a bridge cancel -- so its * price and fee stay readable. The registry keeps one refund per payment: * recording the same refund again returns the entry already there, and a * different amount for it, or one over what the payment can restore, is a * `RangeError`. * * The registry credits the payment's coins (§6.7) rather than lowering * what they spent, so the coins are also queued to be read back from it: * at the wallet's next melt pass, or when {@link readRefunds} is awaited. * Until then {@link balance} and {@link reconcile} do not count the value, * and the coins are not melted. */ recordRefund(seq: number, options?: RecordRefundOptions): Receipt; /** * Read back from the registry the coins of every payment recorded * refunded since the last read (§6.7; {@link recordRefund}, * {@link pursueBridgeRecourse}), and set each to the registry's books: * `face − spent + refund_credit` left, the exact residual its melt locks, * and retired, never offered again (§7). The wallet's next melt pass * collects the value, and one is armed now. * * Runs by itself at the start of every melt pass and at the end of * {@link pursueBridgeRecourse}; await it after {@link recordRefund} for * {@link balance} and {@link reconcile} to count the refund at once. A * second call while one runs joins it. Never throws: a coin the registry * did not answer for stays queued, is not melted, and is read again next * time. Resolves to how many coins are still waiting. * * Each read names one coin to the registry from this caller's network * address -- as the melt that follows does anyway (`GET /melt-attempt`). */ readRefunds(): Promise; private readRefundsOnce; /** * §7's reconciliation, with `Σ live coin value` taken from the buffer. * * Chain totals come from the caller (or from a recovery scan, which * collected them while enumerating reserves). They are the external anchor * a hash chain cannot supply for itself — see `receipts.ts`. */ reconcile(totals?: { deposits: bigint; reclaims: bigint; }): Reconciliation; /** * Where this wallet's recovery read the chain to, as text to save beside * the receipt file and pass back as `recoveryCheckpoint` to the next * {@link px402.recover}: per funded reserve, the last block the * deposit-log scan fully read (at least 1,000 blocks below the head), that * block's hash, and the deposit and reclaim sums up to it. With it the next * recovery reads only the blocks since; without it, every block since * `chain.deployBlock`. * * Nothing secret: block numbers, hashes, the reserve addresses and their * deposit totals, all public on chain -- but it does name your reserves, * so keep it where you keep the receipts. `undefined` for a wallet that was * opened rather than recovered, or recovered from caller-given `sources`. */ recoveryCheckpoint(): string | undefined; /** * The chain totals {@link reconcile} measures against: the reserves' * deposits and reclaims. Known at once for a wallet recovered with the * default `depositLogScan: "blocking"`; for one recovered with * `"background"`, resolves once the deposit-log scan is in (and * {@link recoveryCheckpoint} then says where it reached). A scan that * failed is tried again here. */ chainTotals(): Promise; /** * Set by {@link px402.recover} under `depositLogScan: "background"` or * `"on-demand"`: the chain totals are read later -- at once, in the * background, when `startNow`; else when {@link chainTotals} is first * asked. A failure is said through `onWarning`, and `chainTotals` tries * again. */ deferChainTotals(read: () => Promise<{ readonly totals: ReserveTotals; readonly checkpoint: string; }>, startNow: boolean): void; private readTotals; /** * Set by {@link px402.recover}; the counter must resume above what it found. * `checkpoint` is what {@link recoveryCheckpoint} will return. */ resumeFrom(result: RecoveryResult, issuedAtFallback: number, checkpoint?: string): void; /** * The fail-closed error {@link ready} raises, carrying the same counts * {@link CoinStore.select} would have reported — so a caller branches on one * error shape whether it asked in advance or found out on the spend path. */ private notReady; private now; /** * {@link DEFAULT_READY_TIMEOUT_MS}, sized to **this** wallet's band: the * longest hold any of its coins can carry, plus the same margin. */ private defaultReadyTimeoutMs; /** The longest §9.1 hold a coin of this wallet carries: one issuance window plus its jitter band. */ private longestHoldSeconds; private observationWindow; /** Samples inside the trailing observation window, pruning the rest. */ private live; private observedSpend; private observedCallCost; /** The mean relayer fee per observed call, rounding included; `0n` with nothing observed. */ private observedCallFee; /** * Calls per day, measured against the **whole** observation window rather * than the time since the first sample. * * A wallet that made its first call a second ago would otherwise report a * rate of 86,400 calls per day and a runway of minutes. Dividing by the * window makes an early rate an underestimate, which errs toward a longer * reported runway; the refill rule uses the same measurement, so a wallet * that is genuinely spending fast still refills as its samples accumulate. */ private observedCallsPerDay; /** `base × (1 ± 20 %)`, drawn from the injected byte source. */ private jittered; /** * Record a price a payment was refused for size ({@link wrapFetch}), so the * next refill plans coins that carry it -- unless no pool could: a price * past what `coinsPerPayment()` top-rung coins carry is not one larger * coins fix, and shaping a refill to it would only buy coins for a payment * that can never be made. */ private observeRefusedPrice; /** * The largest price this wallet has paid or been refused for size, or the * assumed call cost before it has seen any: the price its pool has to be * able to carry in one payment. */ private largestPrice; /** * Does the buffer hold `price` in unpresented value and still not carry it * in one payment? Measured as a refill decision is, ignoring the hold: * coins inside it are on their way, and are the wrong size all the same. */ private fragmentedFor; /** The residual of every coin no merchant has seen, held or not. */ private unpresentedResiduals; /** {@link WalletConfig.maxPaymentHeaderBytes}, or the default 7,680 bytes. */ private maxPaymentHeaderBytes; /** * How many coins one payment can carry: the facilitator's cap, or fewer * when the header budget fits fewer of this keyset's largest coins with a * reference-length resource URL (`maxCoinsWithinHeaderBudget`). Computed * once -- the keyset and the budget are fixed for the wallet's life. The * spend path measures each payment itself, URL and all. */ private coinsPerPayment; /** How many epochs the buffer's unpresented coins span. */ private unpresentedEpochs; /** Record one observed price, keeping the histogram bounded. */ private observePrice; /** * Coins one refill may buy: the caller's ceiling, clamped to the issuer's. * * Both bounds are real and neither subsumes the other, so the plan is built * against the smaller. Exceeding the issuer's is not a degraded outcome but * a rejected request, after the wallet has already planned the counters. */ private coinBudget; /** * The *unit* the refill is built out of: one repetition of the price mix * this wallet has been paying, as rung counts. * * Frequency-weighted and then reduced by the gcd of its counts, so the unit * describes the **shape** of the observed prices rather than their volume — * see {@link reduceByGcd}. With no observation it is {@link hedgeMix}. * * A price history diverse enough that its mix does not fit one withdraw * falls back to the single most frequent price, which is the best remaining * guess; if even that does not fit, the mix is empty and the plan is the * floor plus a largest-first top-up. */ private priceMix; /** * Which rungs to withdraw to cover `deficit` — shaped by what this wallet * has been paying, not split largest-first. * * # Why largest-first was the wrong split * * It is the minimum-coin cover of the *deficit*, and the deficit is not what * gets spent. On the original six-rung ladder a 20 USDC refill came back as * one $10.24 coin, three $2.56, three $0.64 and one $0.16 — and no subset of that sums * to $2.50, so every $2.50 call split a coin, retired its residual under §7, * and paid for a §6.6 melt plus a fresh §9.1 hold. Dogfooding ran dry after * four calls with the rest of the money in refresh holds. The wallet was * buying coins sized for the refill instead of coins sized for the calls. * * # The plan, in four steps * * 1. **Repeat the price mix.** {@link priceMix} is one repetition of what * recent calls decompose into; the deficit buys as many copies as it can * afford — but never more than the remaining coin slots could finish the * target with, because a shaped pool that undershoots its own target is * a refill that did not happen. * 2. **Hold a floor of small rungs.** {@link CANONICAL_DIGIT_MAX} of every * rung below the mix's own ceiling, so a price the wallet has not seen * yet can still usually be covered exactly. * 3. **Top up largest-first**, which is the old rule, now applied only to * what is left over rather than to the whole deficit. * 4. **Round up** rather than stop short of the target. * * Bounded throughout by {@link coinBudget}; a plan that hits it and lands * below the deficit says so through `onWarning`, because a shaped pool wants * more coins than a largest-first split did and silence there would read as * a refill that worked. */ private planDenominations; /** * A plan that hit its coin ceiling short of the target, said out loud. * * The shaped plan wants more coins than the largest-first split did — a * $2.50 cover is seven coins where a $4.096 coin was one, and the no-history * hedge alone is 54 coins on seven rungs — so the ceiling binds where it * never used to; a 20 USDC first refill lands at 64 coins and $19.999. * Silence would leave an integrator with a wallet that refilled to less * than it asked for and no way to see why. */ private warnIfPlanTruncated; private requireIssuer; /** * The keyset to withdraw under: the newest held whose spend window is open * (K1). Refused when there is none -- every epoch held has closed its * spend window, and the issuer's newer one has not been read. */ private requireKeyset; /** * The one {@link Refresher} this wallet uses, built on first need. * * One instance, not one per call: it carries the in-flight guard that keeps * two melt sessions off one coin, and the set of coins whose residual is * below the smallest rung and must never be melted at all. */ private requireRefresher; private requireChain; } export declare const px402: { /** * Open a wallet on a seed. * * **Read the key-separation note on {@link px402} before deploying this.** * The seed this call takes is the entire authority over the reserve. * * With an `issuer` configured, this fetches the keyset and recomputes its id * rather than trusting the served one (§4). * * # This reads the chain, and refuses on a mismatch * * §4: *"wallets and facilitators MUST reject any keyset not committed * on-chain"*. That check is the whole of what replaces per-coin DLEQ proofs, * so it is no longer the caller's to remember: with * `chain.keysetCommitment` configured this recomputes the keyset id, reads * `keysets(epochId)` from the reserve, and throws * {@link PX402KeysetCommitmentError} rather than returning a wallet. * * With no reader it warns instead of throwing — the check cannot be run and * refusing would break every deployment that predates it — and a caller who * has verified elsewhere says so with * `keysetVerification: "caller-verified-onchain"`. Both paths are loud; * neither is silent. * * # Only for a seed that has never been used * * `open` starts the withdraw counter at 0. On a seed that has withdrawn, * that re-derives coins it already took (§6.13), so it refuses with * {@link PX402SeedUsedError} -- before anything else is read -- when * `config.receipts` holds a stored receipt chain, or the reserve's on-chain * withdraw nonce is not zero (read through `chain.reserveNonce` or * `chain.rpcUrl`; a wallet with neither cannot withdraw at all). Restart a * used seed with {@link px402.recover}. `{ fresh: true }` skips the check; * see {@link OpenOptions.fresh} before you use it. */ open(config: WalletConfig, options?: OpenOptions): Promise; /** * Rebuild a wallet from its seed (§6.10), then keep using it. * * The returned wallet holds every spendable coin the scan found, resumes * its withdraw counter above every counter it saw, and carries the chain * totals the scan collected so {@link Wallet.reconcile} works immediately. * * A coin the log did not date is treated as issued at the wallet's `now` * minus one issuance window — recovered coins were published in the past, * and holding them for another window would be a hold against nothing. * * On a seed that was never used it returns an empty wallet, so an agent * can boot with it every time. Without `sources` it reads the SDK's public * ones ({@link publicRecoverySources}): the issuer's whole `/log`, the * chain through `chain.rpcUrl` from `chain.deployBlock`, and the * registry's spent total for each coin found -- which names those coins to * the registry together, so route the issuer client's `fetch` through a * proxy you control. */ recover(config: RecoverConfig): Promise; }; /** Re-exported so a consumer resolving a `denomId` needs one import. */ export { denomById };