Charge for a route
You describe your paid routes once, in a PaymentGate. The gate answers 402 with the price, checks the payment, opens
the sealed request, runs your handler, seals the answer, settles the payment on chain and signs a receipt. Your handler
only sees the opened request and the payer’s address.
1. Configure the gate
Section titled “1. Configure the gate”/** * A payment gate for the QoreChain testnet: which routes cost what, who gets * paid, and the keys the server seals and signs with. The three server files * (Node http, Express, Hono) all use it. */import type { Hex } from "@pq402/core";import { EvmChainReader, EvmSettler, PqErc20Facilitator, PqPerennialFacilitator, qorechainTestnet, viemChainOf,} from "@pq402/scheme-qorechain";import { PaymentGate, type Handler } from "@pq402/server";import { x402Facilitator } from "@x402/core/facilitator";import { createPublicClient, createWalletClient, http, type PublicClient } from "viem";import { accountFromMnemonic, env } from "./account.js";
const gateway = await accountFromMnemonic(env("GATEWAY_MNEMONIC"));const chain = viemChainOf(qorechainTestnet);const publicClient = createPublicClient({ chain, transport: http() }) as PublicClient;
// Reads keys, balances and positions from the chain.const reader = new EvmChainReader({ network: qorechainTestnet, publicClient });
// Submits settlements from the gateway's account, which pays the gas.const settler = new EvmSettler({ publicClient, walletClient: createWalletClient({ account: gateway.evm, chain, transport: http() }), maxGas: 600_000n, // refuse to send anything the estimate puts above this maxFeePerGas: 250_000_000_000n, maxPriorityFeePerGas: 1_000_000_000n,});
const networks = [qorechainTestnet.network];const vault = process.env.PERENNIAL_VAULT?.trim() as Hex | undefined;const facilitator = new x402Facilitator().register( qorechainTestnet.network, new PqErc20Facilitator({ networks, reader, settler }),);if (vault) facilitator.register(qorechainTestnet.network, new PqPerennialFacilitator({ networks, reader, settler }));
export const gate = new PaymentGate({ network: qorechainTestnet, escrow: env("ESCROW_ADDRESS") as Hex, // offers pq-erc20 ...(vault ? { vault } : {}), // also offers pq-perennial (agent budgets) facilitator, kemKeys: reader, // the payer's ML-KEM-1024 key, to seal the answer gateway: { address: gateway.address, mldsaSecretKey: gateway.mldsa.secretKey, sealKeys: gateway.seal }, routes: { "POST /v1/answer": { price: "0.002 fUSD", payTo: gateway.address, description: "One answer", requestSealing: "required", }, },});
/** Your application: it sees the opened request and the payer's address. */export const handler: Handler = async (req) => { if (req.target === "/health") { return { status: 200, contentType: "text/plain", body: new TextEncoder().encode("ok") }; } const question = new TextDecoder().decode(req.body); return { status: 200, contentType: "application/json", body: new TextEncoder().encode(JSON.stringify({ payer: req.payer, answer: `You asked: ${question}` })), };};What each part does:
routesis keyed by"METHOD /path", without the query.priceis"0.002 fUSD","$0.01"(resolved to fUSD) or{ asset, amount }in atomic units.requestSealing: "required"refuses a plaintext body.escrowoffers thepq-erc20scheme: payment from a deposit inPQ402Escrow.vaultofferspq-perennial: payment from an agent budget. Offer one or both; the client picks.facilitatorverifies and settles. Register a facilitator for every scheme you offer.EvmSettlersubmits settlements from the gateway’s account, which needs an open EVM window scoped to the escrow (and the vault). It estimates the gas of each call, adds 20%, and refuses to send anything abovemaxGas.gatewayturns on sealing and receipts: its ML-KEM-1024 key opens requests and its ML-DSA-87 key signs receipts. Both must be registered on chain for the gateway’s address.
All options are listed in configuration.
2. Serve it
Section titled “2. Serve it”/** Charge for a route with plain node:http. */import { createServer } from "node:http";import { nodeListener } from "@pq402/server";import { gate, handler } from "./gate.js";
// Every request goes through the gate; unpriced routes reach the handler for free.createServer(nodeListener(gate, handler)).listen(4021, () => { console.log("paid endpoint on http://localhost:4021/v1/answer");});/** Charge for a route in an Express app. */import express from "express";import { nodeListener } from "@pq402/server";import { gate, handler } from "./gate.js";
const app = express();const paid = nodeListener(gate, handler);
// Mount the gate before any body parser: it needs the raw bytes the client signed.app.post("/v1/answer", (req, res) => paid(req, res));
// Free routes stay ordinary Express routes, with whatever middleware you like.app.get("/health", (_req, res) => { res.send("ok");});
app.listen(4021, () => console.log("paid endpoint on http://localhost:4021/v1/answer"));/** * Charge for a route in a Hono app. The adapter maps a Fetch API Request to * the gate and back, so the same code runs on Node, Bun, Deno or Workers. */import { serve } from "@hono/node-server";import type { GateRequest, Handler, PaymentGate } from "@pq402/server";import { Hono } from "hono";import { gate, handler } from "./gate.js";
async function paidFetch(gate: PaymentGate, handler: Handler, request: Request): Promise<Response> { const url = new URL(request.url); const gateRequest: GateRequest = { method: request.method, target: url.pathname + url.search, url: request.url, header: (name) => request.headers.get(name) ?? undefined, body: new Uint8Array(await request.arrayBuffer()), }; const out = await gate.handle(gateRequest, handler); return new Response(new Uint8Array(out.body), { status: out.status, headers: out.headers });}
const app = new Hono();app.post("/v1/answer", (c) => paidFetch(gate, handler, c.req.raw));app.get("/health", (c) => c.text("ok"));
serve({ fetch: app.fetch, port: 4021 }, () => console.log("paid endpoint on http://localhost:4021/v1/answer"),);3. Check it
Section titled “3. Check it”Without paying, the route answers 402:
curl -i -X POST http://localhost:4021/v1/answerHTTP/1.1 402 Payment RequiredPAYMENT-REQUIRED: <base64 JSON: the price, the payee and the schemes offered>Content-Type: application/jsonThen pay it from a script.
Good to know
Section titled “Good to know”- A handler result with status 400 or above is returned as is and not charged: the payment is not settled.
- The payment signature header is about 9.4 KB. Node accepts it by default; a proxy with an 8 KB header limit (nginx’s default) drops it. Allow at least 16 KB.
- Accepted payments are remembered in memory until they expire, to refuse replays. A restart forgets them; the chain still refuses a second settlement.