/** * The drop-in, started at boot: the wallet funds itself before anything is * bought, then pays each URL. * * node --env-file=.env drop-in.js [ ...] * * .env holds PX402_PRIVATE_KEY. On Base the issuer, the registry and the * bridge facilitator default to PRXVT's hosted ones (issuer.prxvt.com, * registry.prxvt.com, facilitator.prxvt.com); PX402_ISSUER_URL, * PX402_REGISTRY_URL and PX402_BRIDGE_FACILITATOR point it elsewhere. Send * USDC to the key's address, and nothing else: with no ETH there the * deposits are gasless. The wallet does the deposits, the withdrawals, the * hold and the bridge. * * One key controls the address and the coins: keep it like the funds it * holds. agent.ts is the explicit path, where the depositor's key never * enters the SDK. */ import { createWallet, wrapFetchWithPayment, type Wallet } from "px402"; import { walletStore } from "./receipts-file.js"; /** * Where this agent keeps its receipt chain and checkpoint. Not agent.ts's * file: the key derives a different wallet from PX402_SEED's. */ export const DROP_IN_RECEIPTS_FILE = process.env["PX402_RECEIPTS_FILE"] ?? "px402-receipts-dropin.json"; /** The agent's key from an environment variable holding 64 hex characters. Never printed. */ export function keyFromEnv(name: string): string { const value = process.env[name]; if (value === undefined || !/^(0x)?[0-9a-fA-F]{64}$/.test(value)) { throw new Error(`${name} must hold the agent's private key as 64 hex characters`); } return value; } /** * The wallet, started long before anything is bought: it recovers, deposits * (whole floats, when the reserve is short) and withdraws now, so its coins' * hold has passed by the first payment and the withdrawal is far from it. */ export async function bootDropIn(): Promise { const wallet = await createWallet({ privateKey: keyFromEnv("PX402_PRIVATE_KEY"), // Base by default; PX402_NETWORK names another network. // The receipts (your purchase history) and the recovery checkpoint, // across restarts. Without a store they live in memory. store: walletStore(DROP_IN_RECEIPTS_FILE), }); console.log(`started: ${wallet.runway().balanceBaseUnits.toString()} base units in coins`); return wallet; } async function main(): Promise { const urls = process.argv.slice(2); if (urls.length === 0) { throw new Error("usage: node drop-in.js [ ...]"); } const wallet = await bootDropIn(); // The same wallet, its funding, its bridge and its store: no second start. const pay = wrapFetchWithPayment(fetch, wallet, { onPayment: (info) => { console.log( `paid ${info.resourceUrl}: ${info.priceBaseUnits.toString()} + fee ${info.feeBaseUnits.toString()}` + (info.bridge === undefined ? "" : `, through the bridge (${info.bridge.state})`), ); }, }); for (const url of urls) { const res = await pay(url); console.log(`${String(res.status)} ${await res.text()}`); } } if (process.argv[1]?.endsWith("drop-in.js") === true) { await main(); }