import { readFile, writeFile } from "node:fs/promises"; import { x402Client } from "@x402/core/client"; import { wrapFetchWithPayment } from "@x402/fetch"; import { ExactEvmScheme } from "@x402/evm/exact/client"; import { privateKeyToAccount } from "viem/accounts"; type RecoveryOperation = { id: string; token?: string; statusUrl: string; resultUrl: string; }; // Performs a REAL testnet payment. Keep this key and wallet credentials private. // Save IDEMPOTENCY_KEY before running; reuse it with the same PDF/options on retries. const base = process.env.API_URL ?? "http://localhost:3000"; const filename = process.argv[2]; const privateKey = process.env.TEST_PRIVATE_KEY; const maximum = process.env.MAX_PAYMENT_ATOMIC; const payTo = process.env.PAYMENT_ADDRESS; const key = process.env.IDEMPOTENCY_KEY; if ( !filename || !privateKey?.match(/^0x[\da-fA-F]{64}$/) || !maximum?.match(/^[1-9]\d*$/) || !payTo?.match(/^0x[\da-fA-F]{40}$/) || !key?.match( /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i, ) ) throw new Error( "Set TEST_PRIVATE_KEY, MAX_PAYMENT_ATOMIC, PAYMENT_ADDRESS and a saved random UUIDv4 IDEMPOTENCY_KEY; pass a PDF path", ); const endpoint = `${base}/v1/extract?format=markdown`; const client = new x402Client() .register( "eip155:84532", new ExactEvmScheme(privateKeyToAccount(privateKey as `0x${string}`)), ) .registerPolicy((version, requirements) => requirements.filter( (r) => version === 2 && r.scheme === "exact" && r.network === "eip155:84532" && r.asset.toLowerCase() === "0x036cbd53842c5426634e7929541ec2318f3dcf7e" && r.payTo.toLowerCase() === payTo.toLowerCase() && BigInt(r.amount) <= BigInt(maximum), ), ); client.onBeforePaymentCreation(async ({ paymentRequired }) => { if (paymentRequired.resource?.url !== endpoint) return { abort: true, reason: "Unexpected payment resource" }; }); const paidFetch = wrapFetchWithPayment(fetch, client); const form = new FormData(); form.set( "file", new Blob([await readFile(filename)], { type: "application/pdf" }), "input.pdf", ); const response = await paidFetch(endpoint, { method: "POST", headers: { "Idempotency-Key": key }, body: form, }); if (!response.ok) { // Save recovery credentials privately, never in public logs. const failure = (await response.json()) as { error?: { code: string; message: string }; operation?: RecoveryOperation; }; if (failure.operation) await saveRecovery({ key, operation: failure.operation }); throw new Error( `${failure.error?.code}: ${failure.error?.message}; operation ${failure.operation?.id ?? "not created"}`, ); } console.log(await response.text()); async function saveRecovery({ key, operation, }: { key: string; operation: RecoveryOperation; }) { const filename = `.micropdf-${key}.json`; // Exclusive creation never follows an existing symlink or overwrites a saved secret. try { await writeFile(filename, JSON.stringify(operation, null, 2) + "\n", { mode: 0o600, flag: "wx", }); } catch (error) { if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error; const saved = JSON.parse(await readFile(filename, "utf8")) as { id?: string; }; if (saved.id !== operation.id) throw new Error( "Recovery file belongs to a different operation; preserve both operations before retrying", ); } console.error( `Recovery saved to ${filename}. Poll status or retry with the same key; do not create a new payment.`, ); }