Skip to content

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.

gate.ts
/**
* 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:

  • routes is keyed by "METHOD /path", without the query. price is "0.002 fUSD", "$0.01" (resolved to fUSD) or { asset, amount } in atomic units. requestSealing: "required" refuses a plaintext body.
  • escrow offers the pq-erc20 scheme: payment from a deposit in PQ402Escrow. vault offers pq-perennial: payment from an agent budget. Offer one or both; the client picks.
  • facilitator verifies and settles. Register a facilitator for every scheme you offer.
  • EvmSettler submits 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 above maxGas.
  • gateway turns 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.

server-node.ts
/** 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");
});

Without paying, the route answers 402:

Terminal window
curl -i -X POST http://localhost:4021/v1/answer
HTTP/1.1 402 Payment Required
PAYMENT-REQUIRED: <base64 JSON: the price, the payee and the schemes offered>
Content-Type: application/json

Then pay it from a script.

  • 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.