import { type IssuedCoin } from "./client.js"; import { type BridgeState } from "./receipts.js"; import { CoinStore, type AnonymityGauges, type PrivacyMode } from "./store.js"; import { SupportedCache } from "./supported.js"; import { type ContractTerms } from "./terms.js"; /** The x402 request header carrying a payment payload. */ export declare const PAYMENT_HEADER = "X-PAYMENT"; /** * The x402 response header carrying the merchant's base64 `SettleResponse`. * * The only positive evidence a wallet gets that the registry committed. §11 * puts the registry `commitId` in its `transaction` field. */ export declare const PAYMENT_RESPONSE_HEADER = "X-PAYMENT-RESPONSE"; /** The px402 binding version this SDK speaks. */ export declare const PX402_VERSION = 1; /** §11's wire nonce width, in bytes. */ export declare const NONCE_LEN = 16; /** * The one payout tier this wallet pays under: Instant, `extra.tier: 0` (v3 * §16's 2026-10-01 note). See `selectAccepts`. */ export declare const INSTANT_TIER = 0; /** The subset of `fetch` this module wraps. */ export type FetchLike = (input: string | URL | Request, init?: RequestInit) => Promise; /** What was paid, for receipts (§7) and for callers that want to observe. */ export interface PaymentInfo { readonly resourceUrl: string; /** The merchant's `payTo`, `0x`-prefixed as it appeared in `accepts[]`. */ readonly payTo: string; /** * What was presented, in base units: `priceBaseUnits + feeBaseUnits`. * * The presented **total**, not the merchant's price — kept under this name * because it is what `ContractTerms.amount` carries, what the coins * covered, and what every consumer of this field before v3 was reading. */ readonly amount: bigint; /** The merchant's `accepts[].amount`: what the merchant receives. */ readonly priceBaseUnits: bigint; /** * The relayer's fee: `ceil(price × feeBps / 10 000)` plus the rounding of * the total up to the smallest denomination (v3 §7, §25.1), i.e. `amount − * priceBaseUnits`. Zero with no facilitator, and at a fee of zero. */ readonly feeBaseUnits: bigint; /** The fee rate the facilitator advertised. */ readonly feeBps: number; /** The facilitator URL the requirements named, when they named one. */ readonly facilitator?: string; /** The EIP-712 struct hash the permissions bind to, 32 bytes. */ readonly contractTermsHash: Uint8Array; /** * The 32-byte per-payment salt under which `acceptedHash` and * `resourceUrlHash` were derived (§6.3). It went to the merchant and the * facilitator in the payload and to nobody else; a caller that keeps it can * later open those two hashes -- in a dispute, say -- and a caller that * does not keep it loses nothing else. */ readonly termsSalt: Uint8Array; /** The coin public keys spent, in payload order. */ readonly coinPubs: readonly Uint8Array[]; /** The 16-byte wire nonce. */ readonly nonce: Uint8Array; readonly validUntil: bigint; /** The chosen `accepts[]` entry, with §9.3's prose fields removed. */ readonly accepted: unknown; /** * Whether the resource actually arrived. * * `false` is §6.7's **paid, undelivered**: the coins are committed at the * registry and the merchant did not serve. The remedy is a refund request * against `payTo` (§6.7), not a retry — a retry pays twice. */ readonly delivered: boolean; /** * How the wallet knows this settled. * * `"confirmed"` — the merchant returned an `X-PAYMENT-RESPONSE`, which is a * `SettleResponse` and therefore evidence the registry committed. * `"assumed"` — inferred from the HTTP outcome, because the merchant * returned no settlement response. See the module docs for why the inference * errs toward "settled". */ readonly settlement: "confirmed" | "assumed"; /** The registry `commitId`, when the merchant returned one (§11). */ readonly commitId?: string; /** * Present when the payment went through the exact-scheme bridge (v3 §26): * then {@link facilitator} is the bridge facilitator, {@link commitId} is * its `/settle`'s `transaction`, and {@link settlement} is `"confirmed"` * only when the merchant's own settlement header said `success: true`. */ readonly bridge?: PaymentBridge; } /** A bridge payment's own facts (v3 §26.8 step 6). */ export interface PaymentBridge { /** * The relayer that signed: its payout address, the authorization's `from`, * once the wallet verified it. Absent when no relayer signed or the answer * failed a check. */ readonly relayer?: string; /** The token the merchant is paid in: the entry's `asset`. */ readonly asset: string; /** * The network the merchant is paid on, CAIP-2 (`eip155:8453`): the * wallet's own, or a foreign payout network its facilitator lists (v3 §28). * Always set by this wallet; optional, as on the receipt, where absent * means the wallet's own network. */ readonly network?: string; /** The merchant's settlement transaction on chain, from its settlement header. */ readonly merchantTransaction?: string; readonly state: BridgeState; /** * The payment's preimage: what the wallet's recourse presents (§26.7). * Local, like the receipt it goes into. */ readonly contractTerms: ContractTerms; /** Unix seconds, the wallet's clock, when `/settle` was asked. */ readonly settledAt: number; } /** * The exact-scheme bridge (v3 §26): the facilitator that pays a merchant's * `exact` requirements through a relayer's EIP-3009 authorization. */ export interface BridgeOptions { /** * The bridge facilitator's URL. A merchant's 402 names no facilitator for * an `exact` entry, so the wallet's operator names one: it is trusted with * the payment's amount until the coins come back (§26.8 step 7). */ readonly facilitator: string; /** * The `fetch` its `/verify` and `/settle` go through. Defaults to the * wrapped `fetch`. The wallet, not a merchant, posts the payment from its * own network path (§26.9): route this through a proxy you control. */ readonly fetch?: FetchLike; } /** * What a wrapper tells its wallet about each payment, so the wallet can keep * its melts away from them (v3 §25.2; `meltScheduler.ts`). * * {@link beforeSpend} is awaited once a 402 is found payable and before * anything about the payment is fetched, built or sent; {@link afterSpend} is * called once it is over -- settled, refused, or failed. Neither melts at the * head of a spend: a melt is the wallet's to schedule after the payment that * made the residual. */ export interface SpendLifecycle { beforeSpend(): Promise; afterSpend(): void; } /** * The keysets a wallet's coins are drawn from (K1), as a payment needs them: * which keyset each coin names, and each keyset's smallest rung. */ export interface PaymentKeysets { /** The coin's keyset id, `0x`-prefixed lowercase; `undefined` for {@link WrapFetchOptions.keysetId}'s. */ of(coin: IssuedCoin): string | undefined; /** A keyset's smallest denomination, by its `0x` id; `undefined` for one not held. */ smallest(keysetId: string): bigint | undefined; } /** Options for {@link wrapFetch}. */ export interface WrapFetchOptions { readonly store: CoinStore; /** * The keyset id the wallet verified against the on-chain commitment, * `0x`-prefixed: the keyset a payment's payload names unless most of its * coins are of another ({@link keysets}). */ readonly keysetId: string; /** * The keysets of a wallet holding coins of several epochs (K1). With it, a * payment may present coins of any of them, each tagged with its own * keyset when it is not the payload's (`payload.ts`). Without it, every * coin is presented as {@link keysetId}'s. */ readonly keysets?: PaymentKeysets; /** * The smallest denomination of that keyset, in base units: a fee-bearing * total is rounded up to a whole number of it (v3 §25.1). Read from the * keyset (`smallestDenomination(keyset)`), never a constant -- ladders are * per epoch. */ readonly smallestDenomination: bigint; /** Defaults to `"strict"` (§7). */ readonly privacy?: PrivacyMode; /** Unix seconds. Defaults to the system clock. */ readonly now?: () => number; /** * How the wrapper waits before it delivers a bridge authorization again * (v3 §26.8 step 5). Defaults to a real timer. Injectable for the reason * {@link now} is: a caller that pins the clock owns the waits too. */ readonly sleep?: (ms: number) => Promise; readonly randomBytes?: (n: number) => Uint8Array; readonly onWarning?: (message: string) => void; /** The published §8 gauges, when the wallet has them. */ readonly anonymity?: AnonymityGauges; readonly onPayment?: (info: PaymentInfo) => void; /** Overrides the server's `maxTimeoutSeconds`, downward only. */ readonly maxTimeoutSeconds?: number; /** * The wallet's melt timetable (v3 §25.2): told when each payment begins * and ends. A wallet passes its own; a bare wrapper with none melts * nothing, and its caller runs §6.6 refresh itself -- never at the head of * a payment. */ readonly lifecycle?: SpendLifecycle; /** * The per-facilitator `/supported` cache (v3 §7). One is built per wrapper * when none is given; a wallet passes its own so every wrapper it hands out * shares one read. */ readonly supported?: SupportedCache; /** Used only when {@link supported} is not given. Defaults to 300 s. */ readonly supportedTtlSeconds?: number; /** The `fetch` that reads `/supported`. Defaults to the wrapped `fetch`. */ readonly supportedFetch?: FetchLike; /** * The most this wallet will pay a relayer, in basis points. Defaults to the * protocol's launch `MAX_FEE_BPS`, 100. A facilitator quoting more is * refused with {@link PX402FeeError} before any coin is selected. */ readonly maxFeeBps?: number; /** * The most bytes one `X-PAYMENT` header may take. Defaults to * {@link 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 whole header section. Selection plans inside it -- fewer, * larger coins, one split, when a cover needs more -- and refuses with * `PX402HeaderBudgetError`, before any coin is retired, when nothing fits * (`payload.ts`). */ readonly maxHeaderBytes?: number; /** * Pay a merchant that quotes only `exact` through this bridge facilitator * (v3 §26). Off by default: without it a 402 with no px402 entry comes back * as it arrived. With it, a 402 with no px402 entry and an `exact` entry on * a network, in an asset, the facilitator's `/supported` lists for * {@link network} under `extra.bridge.networks` (v3 §28.7) is paid; every * other 402 still comes back untouched. See the module docs. */ readonly bridge?: BridgeOptions; /** * The CAIP-2 network this wallet's coins are on (`eip155:8453`): the * bridge pays `exact` entries on the networks its facilitator lists for * it. Unset, it pays under any network the bridge facilitator settles. A * wallet passes `eip155:`. */ readonly network?: string; } /** * Recursively drop `description` and `reason` (§9.3). * * Returns a copy; the input is never mutated, because the caller may still be * holding the parsed 402 body and a wrapper that quietly edited it would make * "what the server said" depend on whether payment was attempted. */ export declare function stripPrivacyFields(value: unknown): unknown; /** * RFC 8785 (JCS) canonical JSON, used to serialize the chosen `accepts[]` * entry before hashing it into `acceptedHash` (§11: "JCS is used only * *inside* `contractTerms`"). * * Object members are emitted in ascending order of their keys' UTF-16 code * units — which is exactly `Array.prototype.sort()`'s default — with no * insignificant whitespace. Arrays keep their order. * * Values JCS cannot represent are **refused**, not coerced: `undefined`, * `NaN`, `Infinity`, `bigint`, functions and symbols all throw. Every one of * them has a plausible-looking JSON coercion (`null`, `"1"`, omission) that * would produce a hash the facilitator recomputes differently — and the only * symptom would be `TERMS_MISMATCH` on an otherwise correct payment. */ export declare function jcsStringify(value: unknown): string; /** * The `bytes32 nonce` member of `ContractTerms`, from §11's 16-byte wire * nonce. * * **An SDK decision the spec leaves open.** §11 pins the payload's `nonce` as * `b64(16)` while §6.3's struct member is a `bytes32`, and nothing says how * one becomes the other. Left-zero-padding is chosen because it is what * `i2osp` already does everywhere else in this SDK and because it is * reversible: the wire value is recoverable from the struct member, so a * facilitator recomputing the terms from the payload gets the same word. A * 32-byte nonce passes through unchanged, so a deployment that widens the * wire nonce needs no second rule. */ export declare function termsNonce(wireNonce: Uint8Array): Uint8Array; /** A header budget is a positive whole number of bytes; anything else is refused, not rounded. */ export declare function checkMaxHeaderBytes(value: number): number; /** What a merchant's 402 asks a wallet to pay, read before anything is paid. See {@link quotedPrice}. */ export interface QuotedPrice { /** * `"px402"`: the merchant's own px402 entry (`extra.binding: "px402"`, * `extra.tier: 0`), which the paid fetch pays directly. `"exact"`: no px402 * entry, and an `exact` entry on the wallet's network, which the paid fetch * pays only through a bridge facilitator ({@link WrapFetchOptions.bridge}); * without one it hands this 402 back unpaid. */ readonly path: "px402" | "exact"; /** * The merchant's price in the asset's base units: what it receives. A * payment presents this plus the facilitator's fee, rounded up to the * smallest coin (v3 §7, §25.1), so ask the wallet's `readiness` about that * total (at most `price + feeCeiling(price, maxFeeBps, smallest)`), not * about this. */ readonly priceBaseUnits: bigint; /** The merchant's `payTo`, as served. */ readonly payTo: string; /** The entry's network: CAIP-2 (`eip155:8453`) for an `exact` entry, as served for a px402 one. */ readonly network: string; /** The token the merchant is paid in, as served; `undefined` when a px402 entry names none. */ readonly asset: string | undefined; /** * For `"px402"`, the facilitator the entry names (`extra.facilitator`), * whose `/supported` sets the fee; `undefined` when it names none. For * `"exact"`, always `undefined`: the merchant names no px402 facilitator, * and the wallet's operator names the bridge facilitator. */ readonly facilitator: string | undefined; /** The merchant's x402 version: 1 (a JSON body, `maxAmountRequired`) or 2. */ readonly x402Version: number; } /** Options for {@link quotedPrice}. */ export interface QuotedPriceOptions { /** * The CAIP-2 network the wallet's coins are on (`eip155:`). * With the bridge facilitator's list ({@link bridgeFacilitator} or * {@link bridgeNetworks}), an entry on it is preferred over one on a * foreign payout network; without, an `exact` entry on another network is * not quoted. Unset, any network. */ readonly network?: string; /** * The bridge facilitator the paid fetch would use (`bridge: { facilitator }`). * Set, an `exact` 402 is quoted exactly as that fetch would pay it: its * `/supported` is read for {@link network} and the entry is chosen among * the networks and tokens it lists (v3 §28.7), the wallet's own network * first, then the merchant's order. A px402 402 reads nothing. * * @throws PX402FeeError when that `/supported` cannot be read and an * entry is on {@link network}, as the paid fetch would. */ readonly bridgeFacilitator?: string; /** The `fetch` {@link bridgeFacilitator}'s `/supported` is read through. Defaults to the global `fetch`. */ readonly supportedFetch?: FetchLike; /** A `/supported` cache to read through, such as the one a paid fetch shares. Defaults to a fresh one. */ readonly supported?: SupportedCache; /** * The tokens the bridge facilitator pays in (its `/supported`'s * `extra.bridge.assets`), when the caller has read them and names no * {@link bridgeFacilitator}. Unset, the first `exact` entry on the network * is reported, and the bridge pays it only if its facilitator lists that * token. */ readonly bridgeAssets?: readonly string[]; /** * The networks the bridge facilitator pays on, each with its tokens (its * `/supported`'s {@link FacilitatorSupport.bridgeNetworks} for the wallet's * network, v3 §28.7), when the caller has read them. Set, the entry is * chosen among the ones this lists, the one on {@link network} first, then * the merchant's order, and {@link bridgeAssets} and * {@link bridgeFacilitator} are not consulted. */ readonly bridgeNetworks?: Readonly>; } /** * The price a 402 quotes for the entry a wallet would pay, with nothing * selected, signed or sent: the px402 entry when the 402 has one, else an * `exact` entry (x402 v1 body or v2 `PAYMENT-REQUIRED` header, the header * first). Given the bridge facilitator * ({@link QuotedPriceOptions.bridgeFacilitator}), the `exact` entry is the * one the paid fetch ({@link wrapFetch}) with that facilitator pays, on the * wallet's network or on another network the facilitator lists (v3 §28.7); * without it, the first `exact` entry on * {@link QuotedPriceOptions.network}. `undefined` for a response that is * not a 402, and for a 402 neither path pays -- one whose px402 entry is only * in the header (the bridge stays out of any 402 that offers px402, and the * px402 path reads the body), or one with no `exact` entry the bridge pays. * * Use it on an unpaid first response to size a refill, check readiness and * refuse a price above a cap before paying. Reads a clone: the response's * body is still the caller's. * * @throws PX402TierError when the 402's only px402 entries name a tier other * than Instant (`extra.tier: 0`), exactly as the paid fetch would. */ export declare function quotedPrice(response: Response, options?: QuotedPriceOptions): Promise; /** * Wrap a `fetch` so x402 payments happen transparently. * * The returned function has `fetch`'s own signature and returns `fetch`'s own * `Response`, so it drops into existing calling code. The only behaviour a * caller must handle that plain `fetch` does not have is * {@link PX402NoCoinsError}, which is exactly the point: strict mode's refusal * is loud. */ export declare function wrapFetch(inner: FetchLike, options: WrapFetchOptions): FetchLike; export type { IssuedCoin };