/** * An agent's wallet, start to finish: read what the merchant asks, boot, fund * only when the wallet cannot already pay, wait out the hold, pay (a px402 * merchant directly, an exact-only one through a bridge facilitator), keep * receipts, refill. * * node --env-file=.env agent.js [the most to pay, in base units] * * .env holds PX402_SEED. On Base, the issuer, the registry and the bridge * facilitator (which pays merchants that quote only `exact`) default to * PRXVT's hosted ones; PX402_ISSUER_URL, PX402_REGISTRY_URL and * PX402_BRIDGE_FACILITATOR point the agent elsewhere. * * This is the explicit path: the seed is the agent's own, the depositor's key * never enters the SDK (fund.js prints the two transactions to send), and * every step -- fund, pre-fund, wait, pay, refill -- is in view. drop-in.ts * is the same agent in three lines, funded from one key. */ import { feeCeiling, quotedPrice, smallestDenomination, PX402Error, PX402HeaderBudgetError, PX402NoCoinsError, PX402TierError, type FetchLike, type QuotedPrice, type Wallet, } from "px402"; import { exactWithoutBridge, followUpBridgePayments } from "./bridge.js"; import { loadConfig, type AgentConfig } from "./config.js"; import { paidGet } from "./pay.js"; import { checkpointFileFor, loadCheckpoint, loadReceipts, saveCheckpoint, saveReceipts } from "./receipts-file.js"; import { seedFromEnv } from "./seed.js"; import { MAX_FEE_BPS, recoverWallet } from "./wallet.js"; /** Where this agent keeps its receipt chain: its purchase history. */ export const RECEIPTS_FILE = process.env["PX402_RECEIPTS_FILE"] ?? "px402-receipts.json"; /** Where it keeps the recovery checkpoint: beside the receipts. */ export const CHECKPOINT_FILE = checkpointFileFor(RECEIPTS_FILE); /** * Boot. `px402.recover` on a fresh seed returns an empty wallet, so recovering * at every start is safe, and it is the only way to restart a seed that has * withdrawn before: `px402.open` refuses one. */ export async function bootWallet(cfg: AgentConfig = loadConfig()): Promise { const started = Date.now(); const wallet = await recoverWallet( seedFromEnv("PX402_SEED"), cfg, loadReceipts(RECEIPTS_FILE), loadCheckpoint(CHECKPOINT_FILE), ); saveReceipts(RECEIPTS_FILE, wallet); // Where this recovery's log scan reached: the next start reads only the blocks since. saveCheckpoint(CHECKPOINT_FILE, wallet); const runway = wallet.runway(); console.log( `recovered in ${String(Math.round((Date.now() - started) / 1000))} s: ${runway.balanceBaseUnits.toString()} ` + `base units, ${runway.spendableBaseUnits.toString()} spendable now, ${runway.heldBaseUnits.toString()} in their hold`, ); return wallet; } /** * What the merchant asks, read from its 402 before anything is paid: one * unpaid request, read the way the paid fetch will read it. `undefined`, with * the reason printed, when there is nothing to pay or nothing this wallet * can pay. An `exact` quote with no bridge facilitator configured is returned * with a warning: the paid fetch would hand it back unpaid. */ export async function quoteFor(url: string, cfg: AgentConfig): Promise { const first = await fetch(url); if (first.status !== 402) { console.log(`${url} answered ${String(first.status)} without asking to be paid`); return undefined; } const network = `eip155:${String(cfg.chainId)}`; let quote: QuotedPrice | undefined; try { // With a bridge facilitator, the entry its paid fetch would pay: on this // network, or on another network that facilitator lists. quote = await quotedPrice(first, { network, ...(cfg.bridgeFacilitator === undefined ? {} : { bridgeFacilitator: cfg.bridgeFacilitator }), }); } catch (error) { if (error instanceof PX402TierError) { // px402 pays the Instant tier (tier 0). console.warn(`${url} quotes px402 only under a tier other than Instant (tier 0); nothing to pay`); return undefined; } throw error; } if (quote === undefined) { console.warn(`${url}'s 402 has no px402 entry and no exact entry this wallet pays from ${network}`); return undefined; } console.log( `${url} asks ${quote.priceBaseUnits.toString()} base units ` + `(${quote.path === "px402" ? "px402" : "exact, through the bridge"}, x402 v${String(quote.x402Version)})`, ); if (quote.path === "exact" && cfg.bridgeFacilitator === undefined) { console.warn(exactWithoutBridge(url)); } return quote; } /** * The most a call at `price` can cost through any facilitator this wallet * accepts: the price, the fee at MAX_FEE_BPS, and up to one smallest coin of * rounding. Arithmetic only, no network read. */ export function worstCaseCost(wallet: Wallet, price: bigint): bigint { const keyset = wallet.keyset; if (keyset === undefined) { throw new Error("the wallet has no keyset"); } return price + feeCeiling(price, MAX_FEE_BPS, smallestDenomination(keyset)); } /** The issuer refused a withdrawal larger than what the reserve holds. */ function reserveTooSmall(error: unknown): boolean { return error instanceof PX402Error && error.code === "INSUFFICIENT_VALUE"; } /** * Pre-fund, long before the calls that need it. The withdrawal is public; * the further your payments are from it, the less its timing says. With no * argument, prewarm() refills to the wallet's jittered refill target (here * max(2 h of observed spend, BUFFER_BASE_UNITS) ±20 %); a price above that * target is withdrawn too. */ export async function prefund(wallet: Wallet, cost: bigint): Promise { const coins = await wallet.prewarm(); if (wallet.readiness(cost).status === "insufficient") { coins.push(...(await wallet.prewarm(cost))); } const runway = wallet.runway(); console.log( `withdrew ${String(coins.length)} coins; ${runway.heldBaseUnits.toString()} base units in their hold, ` + `the first spendable at ${runway.heldUntil === null ? "once" : new Date(runway.heldUntil * 1000).toISOString()}`, ); } /** * Withdraw only when it is needed: when the wallet cannot pay `cost` (even * after its hold), or is below its refill target. Returns whether the wallet * can pay `cost` once any hold passes. */ export async function fundFor(wallet: Wallet, cost: bigint): Promise { const before = wallet.readiness(cost); if (before.status !== "insufficient" && !wallet.needsRefill()) { console.log(`the wallet already covers ${cost.toString()} base units (${before.status}): no withdrawal`); return true; } try { // This demo withdraws right before it pays, to show every step in one // run. In production, pre-fund at start-up or on a schedule and pay // later, so each payment is far from the withdrawal its coins came from. await prefund(wallet, cost); } catch (error) { if (!reserveTooSmall(error)) { throw error; } if (before.status !== "insufficient") { console.warn( "the issuer refused the refill (INSUFFICIENT_VALUE): the reserve holds less than it. " + "The wallet still covers this call; deposit before the next refill (node fund.js 25.00).", ); return true; } console.warn( `the issuer refused the withdrawal (INSUFFICIENT_VALUE): the reserve holds less, and the wallet ` + `cannot cover ${cost.toString()} base units. Deposit first (node fund.js 25.00). Nothing was paid.`, ); return false; } const after = wallet.readiness(cost); if (after.status === "insufficient") { console.warn(`still short by ${after.shortfallBaseUnits.toString()} base units after withdrawing; nothing was paid`); return false; } return true; } /** A fetch that pays 402s, px402 or (with a bridge facilitator) exact, and saves the receipt chain after every payment. */ export function paidFetch(wallet: Wallet, bridgeFacilitator: string | undefined): FetchLike { return wallet.wrapFetch(fetch, { // Off unless you name one: without it, a 402 that quotes only `exact` comes back unpaid. ...(bridgeFacilitator === undefined ? {} : { bridge: { facilitator: bridgeFacilitator } }), onPayment: (info) => { console.log( `paid ${info.resourceUrl}: price ${info.priceBaseUnits.toString()} + fee ` + `${info.feeBaseUnits.toString()} (${String(info.feeBps)} bps) in ${String(info.coinPubs.length)} coin(s), ` + `settlement ${info.settlement}, delivered ${String(info.delivered)}`, ); if (info.bridge !== undefined) { // The merchant's own settlement transaction is the on-chain payment. // info.commitId is the registry's commit id, not a chain transaction. console.log( ` bridge: relayer ${info.bridge.relayer ?? "none"}, asset ${info.bridge.asset}, ` + `${info.bridge.state}, merchant transaction ${info.bridge.merchantTransaction ?? "none"}`, ); } saveReceipts(RECEIPTS_FILE, wallet); }, }); } /** Refill when spendable value falls below the jittered target. Run it between calls, not right before one. */ export async function refillIfLow(wallet: Wallet): Promise { const runway = wallet.runway(); console.log( `runway: ${String(runway.calls)} calls at ${runway.callCostBaseUnits.toString()} (${runway.costBasis}), ` + `${runway.spendableBaseUnits.toString()} spendable, ${runway.heldBaseUnits.toString()} held`, ); if (!wallet.needsRefill()) { return; } try { await wallet.prewarm(); } catch (error) { if (!reserveTooSmall(error)) { throw error; } console.warn("refill refused (INSUFFICIENT_VALUE): the reserve is nearly empty; deposit (node fund.js 25.00)"); } } async function main(): Promise { const url = process.argv[2]; const most = process.argv[3] === undefined ? undefined : BigInt(process.argv[3]); if (url === undefined) { throw new Error("usage: node agent.js [the most to pay, in base units]"); } const cfg = loadConfig(); // What the merchant asks, from its own 402, before the wallet is started. const quote = await quoteFor(url, cfg); if (quote === undefined || (quote.path === "exact" && cfg.bridgeFacilitator === undefined)) { return; } if (most !== undefined && quote.priceBaseUnits > most) { console.warn(`refusing: the price is above the ${most.toString()} base units you allowed`); return; } const wallet = await bootWallet(cfg); // Bridge payments an earlier run left undelivered: followed up when due. await followUpBridgePayments(wallet, RECEIPTS_FILE); const cost = worstCaseCost(wallet, quote.priceBaseUnits); if (!(await fundFor(wallet, cost))) { return; } try { await wallet.ready({ amountBaseUnits: cost }); } catch (error) { if (error instanceof PX402NoCoinsError || error instanceof PX402HeaderBudgetError) { console.warn(`cannot pay ${cost.toString()} base units now: ${error.message}`); return; } throw error; } const route = { network: `eip155:${String(cfg.chainId)}`, bridged: cfg.bridgeFacilitator !== undefined }; const response = await paidGet(wallet, paidFetch(wallet, cfg.bridgeFacilitator), url, route); if (response !== undefined) { console.log(`${String(response.status)} ${await response.text()}`); } await refillIfLow(wallet); // Melt the change now, while the process still runs. await wallet.refresh(); } if (process.argv[1]?.endsWith("agent.js") === true) { await main(); }