Skip to content

Pay from a script

createPq402Fetch returns a fetch. Use it like fetch. When a server answers 402, it:

  1. reads the price and refuses it if it is above your maxAmount;
  2. reads the server’s ML-KEM-1024 key from the chain and seals your request body to it;
  3. signs a payment with your ML-DSA-87 key that commits to the exact request bytes;
  4. sends the request again with the payment;
  5. checks the server’s signed receipt against the server’s registered ML-DSA-87 key;
  6. opens the sealed answer with your ML-KEM-1024 key.

Requests that are not paid pass through unchanged.

pay.ts
/**
* Pay for an API call from a script. The fetch this returns answers a 402 by
* signing a payment with your ML-DSA-87 key, seals the body to the server's
* registered ML-KEM-1024 key, checks the signed receipt and opens the answer.
*
* PAYER_MNEMONIC="..." npx tsx pay.ts http://localhost:4021/v1/answer
*/
import { createPq402Fetch } from "@pq402/client";
import { EvmChainReader, qorechainTestnet } from "@pq402/scheme-qorechain";
import { accountFromMnemonic, env } from "./account.js";
const payer = await accountFromMnemonic(env("PAYER_MNEMONIC"));
const pay = createPq402Fetch({
payer: payer.address,
mldsaSecretKey: payer.mldsa.secretKey,
sealKeys: payer.seal,
keys: new EvmChainReader({ network: qorechainTestnet }), // the server's keys come from the chain
chainId: qorechainTestnet.chainId,
maxAmount: 10_000n, // refuse any price above 0.01 fUSD
});
const url = process.argv[2] ?? "http://localhost:4021/v1/answer";
const res = await pay(url, {
method: "POST",
headers: { "content-type": "text/plain" },
body: "What is 6 x 7?",
});
console.log(res.status, await res.text());
console.log(`settled in ${res.payment?.settlement.transaction}`);
console.log(`https://explore.qore.network/tx/${res.payment?.settlement.transaction}`);
Terminal window
PAYER_MNEMONIC="..." npx tsx pay.ts http://localhost:4021/v1/answer

The payer needs fUSD deposited in the escrow the server names, and both registered keys. It needs no QOR for paying: the server pays the gas.

The response is a normal Response with the opened body, plus payment:

Field What it is
payment.requirements the price you paid: scheme, amount (atomic units), payTo, asset
payment.settlement.transaction the settlement transaction hash on the testnet
payment.receipt the server’s signed receipt, already checked
payment.requestSealed whether your body travelled sealed
  • maxAmount: the most you pay for one call, in atomic units (fUSD has 6 decimals, so 10_000n is 0.01 fUSD). A higher price throws before anything is signed.
  • sealRequests: false: send bodies in plain text when the server allows it. Off by default.
  • perennial: { positionId }: pay from an agent budget instead of the escrow.

When a payment fails, createPq402Fetch throws a Pq402Error with a stable reason code. See errors and retries.