Errors and retries
When a paid request does not go through, createPq402Fetch throws a Pq402Error. Its reason is a stable code you
can branch on; its message adds a sentence for people. Every code is listed in errors.
Most failures will fail again if you retry unchanged: a missing key, an empty escrow, a used-up budget, a bad
signature. Two can succeed on a second try: the chain could not be read (invalid_pq402_chain_unavailable), or the
settlement transaction failed (invalid_transaction_state). Retry those, with a backoff, and nothing else.
This file runs locally. It makes the in-memory chain fail on purpose:
/** * What a failed payment looks like, and a retry that only retries what is * worth retrying. Runs locally: the in-memory chain is made to fail on purpose. * * npx tsx errors.ts */import { createServer } from "node:http";import type { AddressInfo } from "node:net";import { Pq402Error, createPq402Fetch } from "@pq402/client";import { ErrorCode, generateSealKeys, mldsaKeyPair, type Hex } from "@pq402/core";import { MemoryChain, PqErc20Facilitator, qorechainTestnet } from "@pq402/scheme-qorechain";import { PaymentGate, nodeListener } from "@pq402/server";import { x402Facilitator } from "@x402/core/facilitator";
/** Codes where trying again, unchanged, can succeed. */const TRANSIENT = new Set<string>([ErrorCode.ChainUnavailable, ErrorCode.SettlementFailed]);
/** Calls `attempt` up to `tries` times, backing off, but only on transient errors. */export async function withRetry<T>(attempt: () => Promise<T>, tries = 3): Promise<T> { for (let i = 1; ; i++) { try { return await attempt(); } catch (err) { const transient = err instanceof Pq402Error && err.reason !== undefined && TRANSIENT.has(err.reason); if (!transient || i >= tries) throw err; console.log(` attempt ${i}: ${err.reason}, retrying`); await new Promise((resolve) => setTimeout(resolve, 500 * 2 ** i)); } }}
// A local server, as in the quickstart, but the client starts with an empty escrow.const server = { address: "0x00000000000000000000000000000000000000a1" as Hex, mldsa: mldsaKeyPair(), seal: generateSealKeys(),};const client = { address: "0x00000000000000000000000000000000000000b2" as Hex, mldsa: mldsaKeyPair(), seal: generateSealKeys(),};const escrow: Hex = "0x00000000000000000000000000000000000000e5";const chain = new MemoryChain(escrow);for (const account of [server, client]) { chain.registerKey(account.address, account.mldsa.publicKey); chain.registerKemKey(account.address, account.seal.mlkemPublicKey);}const facilitator = new x402Facilitator().register( qorechainTestnet.network, new PqErc20Facilitator({ networks: [qorechainTestnet.network], reader: chain, settler: chain.settler(server.address), }),);const gate = new PaymentGate({ network: qorechainTestnet, escrow, facilitator, kemKeys: chain, gateway: { address: server.address, mldsaSecretKey: server.mldsa.secretKey, sealKeys: server.seal }, routes: { "GET /answer": { price: "0.002 fUSD", payTo: server.address } },});const http = createServer( nodeListener(gate, async () => ({ status: 200, contentType: "text/plain", body: new TextEncoder().encode("42"), })),);await new Promise<void>((resolve) => http.listen(0, "127.0.0.1", resolve));const url = `http://127.0.0.1:${(http.address() as AddressInfo).port}/answer`;const options = { payer: client.address, mldsaSecretKey: client.mldsa.secretKey, sealKeys: client.seal, keys: chain, chainId: qorechainTestnet.chainId,};
async function show(label: string, attempt: () => Promise<Response>) { try { const res = await attempt(); console.log(`${label}: ${res.status} ${await res.text()}`); } catch (err) { if (!(err instanceof Pq402Error)) throw err; console.log(`${label}: ${err.reason ?? "no code"}\n ${err.message}`); }}
// 1. The price is above what this client allows: refused before anything is signed.await show("price above maxAmount", () => createPq402Fetch({ ...options, maxAmount: 1_000n })(url));
// 2. Nothing in the escrow: the server refuses the payment.const pay = createPq402Fetch({ ...options, maxAmount: 5_000n });await show("empty escrow", () => pay(url));
// 3. The chain cannot be read: refused rather than trusted, and worth retrying.chain.deposit(client.address, 1_000_000n);chain.offline = true;setTimeout(() => (chain.offline = false), 1_500);await show("node down, then back", () => withRetry(() => pay(url)));
http.close();npx tsx errors.tsprice above maxAmount: no code price 2000 exceeds the limit 1000empty escrow: insufficient_funds payment refused: insufficient_funds: not enough money behind the payment: the escrow balance, or the Perennial position's buffer and principal, cannot cover it attempt 1: invalid_pq402_chain_unavailable, retrying attempt 2: invalid_pq402_chain_unavailable, retryingnode down, then back: 200 42Is a retry safe?
Section titled “Is a retry safe?”For the two codes above, yes. Each attempt signs a new payment with a new nonce, and the server returns your answer only after its settlement succeeds. If a settlement did land but the server could not see it, the old payment’s nonce is spent on chain and cannot be charged again. A response with status 400 or above from the handler is never charged.