/** * One paid GET, with each failure an agent meets turned into its next step. */ import { PX402BridgeError, PX402Error, PX402FeeError, PX402NoCoinsError, quotedPrice, type FetchLike, type Wallet, } from "px402"; import { exactWithoutBridge, explainBridgeError } from "./bridge.js"; /** How the paid fetch was set up: what a 402 that came back unpaid is measured against. */ export interface PayRoute { /** The wallet's network, CAIP-2 (`eip155:8453`): where an `exact` entry is payable. */ readonly network: string; /** Whether the paid fetch was given a bridge facilitator. */ readonly bridged: boolean; } /** * The reason a merchant gave with a 402. x402 servers put it in `error`; the * facilitator's codes (`INSUFFICIENT_VALUE`, `TERMS_MISMATCH`, …) arrive there * when the merchant passes them on. */ async function refusalReason(response: Response): Promise { try { const body: unknown = await response.clone().json(); if (typeof body === "object" && body !== null && "error" in body && typeof body.error === "string") { return body.error; } } catch { // not JSON } return undefined; } export async function paidGet( wallet: Wallet, fetch402: FetchLike, url: string, route: PayRoute, ): Promise { const receiptsBefore = wallet.receipts.length; const paidUndelivered = (): boolean => wallet.receipts.length > receiptsBefore && wallet.receipts.list().at(-1)?.delivered === false; let response: Response; try { response = await fetch402(url); } catch (error) { if (error instanceof PX402NoCoinsError) { // Strict mode failed closed: nothing spendable covers the price plus fee. const state = wallet.readiness(error.requested); if (state.status === "holding") { console.warn(`coins are in their hold; spendable in ${String(state.secondsRemaining)} s (await wallet.ready)`); } else { console.warn(`short by ${state.shortfallBaseUnits.toString()} base units: prewarm, or deposit first`); } return undefined; } if (error instanceof PX402FeeError) { // Nothing was presented. `unreachable` is worth a retry later; the rest // mean this facilitator's fee or terms are not ones this wallet accepts. console.warn(`not paying through ${error.facilitator}: ${error.refusal}`); return undefined; } if (error instanceof PX402BridgeError) { // `committed` decides: a committed bridge payment is never retried. console.warn(explainBridgeError(error)); return undefined; } if (paidUndelivered()) { // The payment went out and the answer never came back. The wallet // counts it as settled. A retry would pay a second time. console.warn(`the connection failed after paying ${url}; do not retry blindly`); } if (error instanceof PX402Error && error.retryable) { console.warn(`transient failure (${error.name}); retry with backoff`); return undefined; } throw error; } if (response.status === 402) { // Either the merchant offers nothing this wallet pays (its first 402, // returned untouched), or it refused the payment and quoted again. console.warn(`402 from ${url}: ${(await refusalReason(response)) ?? "no reason given"}`); const quote = await quotedPrice(response, { network: route.network }).catch(() => undefined); if (quote?.path === "exact" && !route.bridged) { console.warn(exactWithoutBridge(url)); } return undefined; } if (paidUndelivered()) { // Paid, undelivered: the coins are committed and the merchant did not serve. console.warn(`paid ${url} and got ${String(response.status)}: ask the merchant for a refund; a retry pays again`); } return response; }