/** * Opening a wallet, and rebuilding one from its seed. * * The wallet keeps its coins, its withdraw counter and its price history in * memory. `px402.open` is for a seed that has never been used, and refuses * one that has (`PX402SeedUsedError`). Every start of an agent is a * `px402.recover`: on a fresh seed it returns an empty wallet, and on a used * one it finds the coins on the issuer's public log and resumes the counter * above every one it finds. */ import { IssuerClient, px402, type FetchLike, type RecoveryProgress, type StoredReceipt, type Wallet, type WalletConfig, } from "px402"; import { unhex } from "./bytes.js"; import type { AgentConfig } from "./config.js"; /** The most this wallet pays a relayer, in basis points: the protocol's launch cap, 1 %. */ export const MAX_FEE_BPS = 100; /** * The buffer to keep, in base units: here twenty $0.25 calls. Size it from * the prices you expect. Left unset, the refill floor is $1.00, which says * nothing about what your calls cost. */ export const BUFFER_BASE_UNITS = 5_000_000n; /** What a call is assumed to cost until the wallet has paid for one. */ export const TYPICAL_PRICE_BASE_UNITS = 250_000n; /** * The fetch the wallet uses for the issuer, the registry, a facilitator's * /supported and a bridge facilitator. If this machine's IP identifies you, * make it a fetch that goes through a proxy you control. */ export const serviceFetch: FetchLike = (input, init) => fetch(input, init); export function walletConfig(seed: Uint8Array, cfg: AgentConfig): WalletConfig { return { seed, // /melt-attempt and /spent are registry routes; everything else is the issuer's. issuer: new IssuerClient({ baseUrl: cfg.issuerUrl, registryUrl: cfg.registryUrl, fetch: serviceFetch }), chain: { chainId: cfg.chainId, reserveContract: cfg.reserve, usdc: cfg.usdc, domainSeparator: unhex(cfg.domainSeparator), // The wallet reads the reserve through this endpoint: its withdraw // nonce, the keyset commitment open() and recover() check, and, for // recovery, the deposit logs from the deployment block. rpcUrl: cfg.rpcUrl, deployBlock: cfg.deployBlock, logBlockRange: cfg.logBlockRange, }, maxFeeBps: MAX_FEE_BPS, // prewarm() refills to max(2 h of observed spend, this), jittered ±20 %. minRunwayBaseUnits: BUFFER_BASE_UNITS, assumedCallCostBaseUnits: TYPICAL_PRICE_BASE_UNITS, supportedFetch: serviceFetch, // A bridge payment, and its follow-up, go from this wallet to the bridge // facilitator: through the same proxy as the rest. bridgeFetch: serviceFetch, onWarning: (message) => { console.warn(`[px402] ${message}`); }, }; } /** A seed that has never been used. Refuses a used one, naming px402.recover. */ export function openWallet(seed: Uint8Array, cfg: AgentConfig): Promise { return px402.open(walletConfig(seed, cfg)); } /** * Every start: rebuild the buffer and the counter from the seed and public * data. With no `sources`, the SDK reads its public ones: the issuer's whole * /log, the chain through rpcUrl, and the registry's spent total for each * coin it finds. */ export function recoverWallet( seed: Uint8Array, cfg: AgentConfig, receipts: readonly StoredReceipt[], checkpoint?: string, ): Promise { return px402.recover({ ...walletConfig(seed, cfg), receipts, // On a used seed recovery reads for a minute or more: say what it is doing. onProgress: printProgress(), // Where the last recovery's log scan reached. A missing, corrupt or // implausible one only means the scan starts at the deployment block. ...(checkpoint === undefined ? {} : { recoveryCheckpoint: checkpoint }), }); } /** Recovery's progress on the console: a line per phase, and one every five seconds within one. */ export function printProgress(): (progress: RecoveryProgress) => void { let phase = ""; let printedAt = 0; return (progress) => { const finished = (progress.phase === "issuer-log" && progress.done) || (progress.phase === "reserve-discovery" && progress.done) || (progress.phase === "deposit-logs" && progress.blocksDone === progress.blocksTotal) || (progress.phase === "spent-lookups" && progress.done === progress.total); if (progress.phase === phase && !finished && Date.now() - printedAt < 5_000) { return; } phase = progress.phase; printedAt = Date.now(); console.log(`recovery: ${describeProgress(progress)}`); }; } function describeProgress(progress: RecoveryProgress): string { switch (progress.phase) { case "issuer-log": return `issuer log, ${String(progress.entries)}${progress.logSize === undefined ? "" : ` of ${String(progress.logSize)}`} entries read`; case "reserve-discovery": return progress.done ? `reserve indices 0 to ${String(progress.index)} checked, ${String(progress.funded)} funded` : `checking reserve index ${String(progress.index)}`; case "deposit-logs": return ( `deposit logs, ${progress.blocksDone.toString()} of ${progress.blocksTotal.toString()} blocks ` + `(from ${progress.startedFrom === "checkpoint" ? "the saved checkpoint" : "the deployment block"})` ); case "coin-search": return `coins, counter ${progress.counter.toString()} searched, ${String(progress.found)} found`; case "spent-lookups": return `spent totals from the registry, ${String(progress.done)} of ${String(progress.total)}`; } }