// PaywallWatch quickstart: one paid email check, one payment attempt, a charge cap. // // node --env-file-if-exists=.env --import tsx first-check.ts jane@iana.org // // Needs BUYER_EVM_PK in .env: a private key generated for this purpose, holding a little USDC on Base. It stays in .env // on your machine: never in a browser, never in a repository. The facilitator pays the gas, so the wallet needs no ETH. // Optional: PAYWALLWATCH_URL to point at a local copy of the service that settles on Base Sepolia. import { wrapFetchWithPayment, x402Client, decodePaymentResponseHeader } from "@x402/fetch"; import { ExactEvmScheme } from "@x402/evm/exact/client"; import { privateKeyToAccount } from "viem/accounts"; const MAX_CHARGE_USD = 0.003; // the script refuses to pay more than this for one check; the route costs $0.003 const origin = process.env.PAYWALLWATCH_URL ?? "https://api.paywallwatch.com"; const localTest = ["localhost", "127.0.0.1"].includes(new URL(origin).hostname); const expectedNetwork = localTest ? "eip155:84532" : "eip155:8453"; const expectedAsset = localTest ? "0x036cbd53842c5426634e7929541ec2318f3dcf7e" : "0x833589fcd6edb6e08f4c7c32d4f71b54bda02913"; const email = process.argv[2]; if (!email) { console.error("usage: first-check.ts "); process.exit(2); } const pk = process.env.BUYER_EVM_PK; if (!pk || !pk.startsWith("0x")) { console.error("BUYER_EVM_PK is not set. Put it in .env, never in code and never in a browser."); process.exit(2); } const url = `${origin}/v1/email/verify?email=${encodeURIComponent(email)}`; // 1. Read the terms without paying. An unpaid request answers 402 with the price; nothing is charged. const unpaid = await fetch(url); if (unpaid.status !== 402) { console.error(`expected 402 with the terms, got ${unpaid.status}: ${(await unpaid.text()).slice(0, 200)}`); process.exit(1); } const terms = JSON.parse(atob(unpaid.headers.get("PAYMENT-REQUIRED") ?? "")) as { accepts: { network: string; amount: string; extra?: { name?: string } }[] }; const evm = terms.accepts.find(a => a.network.startsWith("eip155:")); if (!evm) { console.error("no EVM payment option in the terms"); process.exit(1); } const usd = Number(evm.amount) / 1_000_000; // USDC has six decimals console.log(`terms: ${usd.toFixed(6)} ${evm.extra?.name ?? "USDC"} on ${evm.network}`); if (!Number.isFinite(usd) || usd <= 0 || usd > MAX_CHARGE_USD) { console.error(`refusing to pay ${usd}: above MAX_CHARGE_USD ${MAX_CHARGE_USD}`); process.exit(1); } // 2. Pay once. wrapFetchWithPayment signs one USDC authorization for exactly the amount in the terms and sends the // request once more with it. It does not loop: a rejected payment comes back as a 402 with the reason, uncharged. const client = new x402Client(); client.register("eip155:*", new ExactEvmScheme(privateKeyToAccount(pk as `0x${string}`))); client.registerPolicy((version, requirements) => version === 2 ? requirements.filter(r => r.scheme === "exact" && r.network === expectedNetwork && r.asset.toLowerCase() === expectedAsset && /^\d+$/.test(r.amount) && BigInt(r.amount) > 0n && BigInt(r.amount) <= BigInt(Math.floor(MAX_CHARGE_USD * 1_000_000)) ) : []); const paidFetch = wrapFetchWithPayment(fetch, client); const res = await paidFetch(url); const text = await res.text(); let body: Record = {}; try { body = JSON.parse(text) as Record; } catch { /* a non-JSON body is reported below as text */ } const settlement = res.headers.get("PAYMENT-RESPONSE"); // 3. Read the answer. Only a 200 is charged, and it carries the settlement in PAYMENT-RESPONSE. if (res.status === 200) { console.log(`charged ${usd.toFixed(6)} USDC:`, settlement ? decodePaymentResponseHeader(settlement) : "(no PAYMENT-RESPONSE header)"); console.log(`verdict ${String(body.verdict)} for ${String(body.email)}; reasons ${JSON.stringify(body.reasons)}; suggestion ${String(body.suggestion ?? "none")}`); console.log("mailbox_verified:", body.mailbox_verified, "(screening never verifies that the mailbox exists)"); } else if (res.status === 503) { console.log(`503: the DNS lookup failed; not charged. Retry-After ${res.headers.get("Retry-After")} s. Run again later: this script does not retry on its own.`); } else if (res.status === 402) { console.log(`402 after payment: not charged. ${String(body.error ?? text.slice(0, 200))}`); } else if (res.status === 400) { console.log(`400: not charged. ${String(body.error)}`); } else { console.log(`${res.status}: settlement status uncertain; reconcile before retrying. ${text.slice(0, 200)}`); } process.exit(res.status === 200 ? 0 : 1);