/** * The wallet-level driver for §6.6 refresh: the thing that turns residual on a * retired coin back into coins nobody has seen. * * `refresh.ts` holds the protocol — the grid, `h_C`, the linking signature — * and `IssuerClient.melt` / `IssuerClient.reveal` speak it. Neither of them * knows about the coin buffer, and that gap is where finding P2 lived: the SDK * shipped the whole of its central privacy mechanism and never invoked it, so * a wallet's second payment reused the first payment's coin and the public * spend log clustered them. * * # What this owns * * One decision per retired coin: which rungs to mint the residual into, and * what to do when the answer is "none". Everything else is bookkeeping the * buffer would otherwise force each integrator to reimplement — which is what * the e2e harness had to do, and the clearest evidence the driver was missing. * * # A melt is not free and not reversible * * `meltReserve` locks the coin's **entire** residual at the registry, and an * expired session restores none of it (§6.6). So: * * - a residual smaller than the smallest rung cannot be minted into anything, * and melting it would destroy it for no coins at all. Those coins are * skipped permanently and reported as `dust`; * - the value the ladder cannot represent exactly (`10_000 × 4^k` does not * tile an arbitrary x402 price) is written off at the melt, and reported; * - a failure between `/melt-reserve` and `/melt-reveal` leaves the coin * queued, because `γ` is idempotent on re-request (§6.6) and the retry is * the crash-recovery path rather than a second attempt. * * # Change is not spendable immediately * * Refreshed coins enter the buffer at `now` and `strict` holds them for one * issuance window (§9.1) like any other new coin. Refresh funds *later* * payments; it is not a way to pay for the one in flight. A wallet still has * to pre-warm. * * # Across epochs (K1) * * With a {@link KeyRing}, a coin of any epoch the wallet holds is melted * under its own keyset and its change minted under the ring's withdraw * keyset -- the newest epoch -- which is how a wallet's old coins migrate, * with no step of their own. A coin whose epoch's spend window has closed is * queued whole (the store's `refreshable`), since a melt is all it is good * for until its refresh window closes too. An issuer that no longer holds a * coin's epoch answers `EPOCH_RETIRED`: the coin is not retried, the epoch is * marked retired in the ring (so the wallet stops splitting its coins), and * the pass reports it ({@link RefreshOutcome.retired}). */ import { IssuerClient, type IssuedCoin } from "./client.js"; import { type Keyset } from "./denom.js"; import { PX402EpochRetiredError } from "./errors.js"; import { type KeyRing } from "./keyring.js"; import { CoinStore } from "./store.js"; /** How many coins one {@link Refresher.run} melts before returning. */ export declare const DEFAULT_MAX_MELTS_PER_RUN = 8; /** What one refresh pass did. Every field is in USDC base units unless noted. */ export interface RefreshOutcome { /** Coins melted, in coins (not base units). */ readonly melted: number; /** Face value of the change coins minted. */ readonly reclaimed: bigint; /** * Residual the ladder could not represent, and which the melt therefore * consumed without minting. Zero is the normal case only for prices that * land on the ladder. */ readonly dust: bigint; /** Coins whose melt failed and stay queued for the next pass. */ readonly failed: number; /** The change coins, already added to the buffer. */ readonly coins: readonly IssuedCoin[]; /** * Epochs the issuer refused to refresh in this pass (`EPOCH_RETIRED`), one * error per epoch with the coins it strands counted (K1). Their coins are * not queued again. */ readonly retired: readonly PX402EpochRetiredError[]; } /** Construction-time wiring. */ export interface RefresherOptions { readonly issuer: IssuerClient; /** * The keyset the melted coins were issued under, and whose rungs the * change targets -- when there is no {@link keyring}. */ readonly keyset: Keyset; /** * Every keyset the wallet holds (K1). With it, a coin of any of them is * melted under its own keyset and the change minted under the ring's * withdraw keyset; {@link keyset} is then unused. */ readonly keyring?: KeyRing; /** * Re-reads the issuer's epochs into the {@link keyring} (K1; * `Wallet.syncKeysets`), called once a pass when the issuer refuses a * melt `KEYSET_UNKNOWN` -- it mints change under an epoch the wallet has * not read -- or when no keyset held is open to mint change under. * Resolves to how many keysets were added. */ readonly resync?: () => Promise; readonly store: CoinStore; /** Unix seconds. Defaults to the system clock. */ readonly now?: () => number; readonly onWarning?: (message: string) => void; /** Defaults to {@link DEFAULT_MAX_MELTS_PER_RUN}. */ readonly maxMeltsPerRun?: number; /** * The authoritative residual for a coin, when the wallet has a path to the * registry it is willing to use. * * Defaults to the buffer's own view, which is a **floor** on the truth: * `wrapFetch` debits whenever it cannot rule settlement out, so the local * `spent` is never below the registry's. Melting for at most the residual is * what the issuer's value-conservation check requires, so the floor is * always safe — it just writes off the difference. * * Reading `GET /spent/{C_p}` directly would make it exact, at the cost of * telling the registry which network address holds that coin. That is the * payer↔coin edge §9 keeps the registry from having, so it is the * integrator's decision, not the default. */ readonly residualOf?: (coin: IssuedCoin) => Promise; /** * Run before every pass picks its coins: the wallet reads back from the * registry the coins of a payment it learned was refunded (§6.7), so the * pass melts them for what the registry now holds. Must not throw. */ readonly beforePass?: () => Promise; /** * Coins not to melt yet: a refunded payment's coins whose registry * standing the wallet has not read. Their local residual predates the * credit, and a melt for it would be refused `INSUFFICIENT_VALUE`. */ readonly deferred?: (coin: IssuedCoin) => boolean; } /** * The greedy floor of `residual` onto `rungs`, largest first. * * `Σ value(D_j)` may be **at most** the residual — the issuer refuses * `total > residual` and accepts anything under it — so this is a floor and * not an exact decomposition. It has to be: the launch ladder is * `10_000 × 4^k`, so the residual left by an arbitrary x402 price is generally * not representable at all, and a refresh that insisted on exactness could * never run. * * The returned list is bounded in practice because a residual never exceeds * its own coin's face value, which is itself a rung: at most one of the * largest rung and at most three of every smaller one. */ export declare function ladderTargets(residual: bigint, rungs: readonly bigint[]): bigint[]; /** * Melts the coins §7 retired and puts their value back as fresh ones. * * One instance per wallet. Runs are serialized against each other: a second * `run()` while one is in flight joins the first rather than starting a * parallel pass, because two passes over the same queue would send two melt * sessions for one coin and the second would find its residual already locked. */ export declare class Refresher { private readonly options; /** Coins whose residual the ladder cannot represent; melting them destroys it. */ private readonly dustCoins; /** Coins the issuer refused to melt `EPOCH_RETIRED` (K1): never retried. */ private readonly retiredCoins; private inFlight; constructor(options: RefresherOptions); /** Coins this driver would melt on its next pass. */ pending(): readonly IssuedCoin[]; /** * Look at a coin afresh: its residual changed under the driver (a refund * credited it, §6.7), so a coin skipped as dust may now be worth a melt. */ reconsider(coinPub: Uint8Array): void; /** Whether a queued coin is melted on the next pass. */ private meltNext; /** * What melting {@link pending} would return as fresh coins, by the store's * own books: each coin's residual, as far as the ladder represents it. */ pendingValue(): bigint; /** Melt what is queued. Never throws: a failure leaves the coin queued. */ run(): Promise; private pass; /** * The keyset change is minted under: the ring's withdraw keyset (the * newest with an open spend window), or the one {@link RefresherOptions.keyset}. */ private targetKeyset; /** The keyset a coin was issued under, as far as this driver knows. */ private coinKeyset; /** Whether the issuer has said it cannot refresh this coin's epoch. */ private retired; /** * {@link PX402EpochRetiredError} for one retired epoch, with what it * strands counted from the buffer: whole coins (spendable whole until the * epoch's spend window closes) and residual only a melt could return. */ retirement(keysetIdHex: string): PX402EpochRetiredError; /** * One coin's melt, or `undefined` if it did not complete. * * A failure is deliberately not distinguished by cause here: every one of * them has the same remedy, which is to leave the coin queued and try again. * `γ` is idempotent per `⟨C⁰_p, attempt, h_C⟩` (§6.6), and every input to * the grid is derived from the coin secret, so re-running this after a crash * re-requests the same session rather than starting a second one. */ private melt; /** Whether the coin's own epoch can still be melted at all. */ private meltable; private residualOf; private now; private warn; }