nirium-avalanche 0.3.0 → 0.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/sdk/pq.mjs ADDED
@@ -0,0 +1,58 @@
1
+ // Post-quantum signature for Nirium receipts on Avalanche (ML-DSA-65, NIST FIPS 204).
2
+ //
3
+ // const pq = pqKeygen(); // keep pq.seed safe; it rebuilds the pair
4
+ // await registerPqKey({ account, publicKey: pq.publicKey, network: "eip155:43113" }); // once, ever
5
+ // const doc = await bindReceipt({ ..., signer: account, pqSigner: pq });
6
+ //
7
+ // Only the first key an address registers counts, and it cannot be changed later: register it once,
8
+ // before the payments it will cover. The secret never leaves this process; Nirium never sees it.
9
+ // It protects the receipt, not the payment (the payment stays signed with secp256k1).
10
+
11
+ import { ml_dsa65 } from "@noble/post-quantum/ml-dsa.js";
12
+ import { createPublicClient, createWalletClient, http, stringToBytes } from "viem";
13
+ import {
14
+ PQ_ALG, PQ_REGISTRY, PQ_REGISTRY_ABI, pqKeyId, pqStatement, bytesToBase64,
15
+ verifyPqSignature, readPqRegistration, checkPqRegistration,
16
+ } from "../verify-evm-pq.mjs";
17
+ import { getNetwork } from "./networks.mjs";
18
+
19
+ export { PQ_ALG, PQ_REGISTRY, pqKeyId, verifyPqSignature, readPqRegistration, checkPqRegistration };
20
+
21
+ const SEED_BYTES = 32;
22
+
23
+ /** New ML-DSA-65 key pair. Pass a 32-byte seed to rebuild one you already have. */
24
+ export function pqKeygen(seed) {
25
+ const s = seed ?? globalThis.crypto.getRandomValues(new Uint8Array(SEED_BYTES));
26
+ if (!(s instanceof Uint8Array) || s.length !== SEED_BYTES) throw new Error(`pqKeygen: seed must be ${SEED_BYTES} bytes`);
27
+ const { publicKey, secretKey } = ml_dsa65.keygen(s);
28
+ return { seed: s, publicKey, secretKey };
29
+ }
30
+
31
+ /** The `pq` block: ML-DSA-65 over nirium-audit-v1:<content_sha256>, the statement `agent` signs. */
32
+ export function attestPq(contentSha256, keys) {
33
+ if (!keys?.publicKey || !keys?.secretKey) throw new Error("attestPq: keys need publicKey and secretKey");
34
+ const signature = ml_dsa65.sign(stringToBytes(pqStatement(contentSha256)), keys.secretKey);
35
+ return { alg: PQ_ALG, key: bytesToBase64(keys.publicKey), signature: bytesToBase64(signature) };
36
+ }
37
+
38
+ /**
39
+ * Registers sha-256 of the ML-DSA-65 public key for `account` in NiriumPqKeyRegistry.
40
+ * The account sends the transaction itself and pays its gas. Reverts with AlreadyRegistered if the
41
+ * account registered before (any key): there is no second registration.
42
+ * @param {object} o { account (viem account), publicKey, network, rpcUrl? }
43
+ * @returns {Promise<{ tx, keyId, registry, blockNumber }>}
44
+ */
45
+ export async function registerPqKey({ account, publicKey, network, rpcUrl }) {
46
+ const net = getNetwork(network);
47
+ const registry = PQ_REGISTRY[network];
48
+ if (!registry) throw new Error(`registerPqKey: no NiriumPqKeyRegistry on ${network} yet`);
49
+ const keyId = pqKeyId(publicKey);
50
+ const pub = createPublicClient({ chain: net.chain, transport: http(rpcUrl) });
51
+ const existing = await readPqRegistration(pub, network, account.address);
52
+ if (existing) throw new Error(`registerPqKey: ${account.address} already registered ${existing.keyId} in block ${existing.blockNumber}`);
53
+ const wallet = createWalletClient({ chain: net.chain, account, transport: http(rpcUrl) });
54
+ const tx = await wallet.writeContract({ address: registry, abi: PQ_REGISTRY_ABI, functionName: "register", args: [keyId] });
55
+ const receipt = await pub.waitForTransactionReceipt({ hash: tx, timeout: 120_000 });
56
+ if (receipt.status !== "success") throw new Error(`registerPqKey: tx ${tx} ${receipt.status}`);
57
+ return { tx, keyId, registry, blockNumber: Number(receipt.blockNumber) };
58
+ }
package/sdk/receipt.mjs CHANGED
@@ -1,96 +1,102 @@
1
- // bindReceipt(): builds a "nirium-payment-binding-v1" receipt for a settled x402 payment on
2
- // Avalanche, bound to the exact USDC Transfer log (block-level logIndex) and its EIP-3009 nonce,
3
- // and signs it as the payer when a signer is given. Format: docs/payment-binding-v1.md.
4
- //
5
- // The receipt adds what the chain does not keep: who declared the payment and what it was for
6
- // (`purpose`). It does not prove delivery.
7
-
8
- import { createPublicClient, http, decodeEventLog, parseAbi, isAddressEqual, getAddress } from "viem";
9
- import { contentSha256, canonicalize, sha256Hex, verifyBinding, VERSION, STATEMENT_PREFIX } from "../verify-evm-core.mjs";
10
- import { getNetwork, USDC_DECIMALS } from "./networks.mjs";
11
-
12
- const ABI = parseAbi([
13
- "event Transfer(address indexed from, address indexed to, uint256 value)",
14
- "event AuthorizationUsed(address indexed authorizer, bytes32 indexed nonce)",
15
- ]);
16
-
17
- function sortKeys(v) {
18
- if (v === null || typeof v !== "object") return v;
19
- if (Array.isArray(v)) return v.map(sortKeys);
20
- return Object.fromEntries(Object.keys(v).sort().map((k) => [k, sortKeys(v[k])]));
21
- }
22
-
23
- /**
24
- * @param {object} o
25
- * @param {string} o.tx settled tx hash (from the PAYMENT-RESPONSE header's `transaction`)
26
- * @param {string} o.network "eip155:43113" | "eip155:43114"
27
- * @param {string} o.ref order reference (purpose.ref)
28
- * @param {string} [o.resource] the paid URL
29
- * @param {string} [o.note] short, no personal data
30
- * @param {string[]} [o.labels] e.g. ["selftest"]; default []
31
- * @param {object} [o.signer] viem account of the payer ({ address, signMessage }); omit for an unsigned receipt
32
- * @param {string} [o.payer] narrow the Transfer when the tx settled several (batch)
33
- * @param {string} [o.payTo]
34
- * @param {string} [o.rpcUrl]
35
- * @param {number} [o.waitMs] how long to wait for the tx to appear on the RPC, default 60000
36
- */
37
- export async function bindReceipt(o) {
38
- const { tx, network, ref } = o;
39
- if (!/^0x[0-9a-fA-F]{64}$/.test(String(tx))) throw new Error("bindReceipt: tx must be a 0x 32-byte hash");
40
- if (typeof ref !== "string" || !ref.trim()) throw new Error("bindReceipt: ref (purpose.ref) is required");
41
- const net = getNetwork(network);
42
- const client = createPublicClient({ chain: net.chain, transport: http(o.rpcUrl) });
43
- const chainId = await client.getChainId();
44
- if (`eip155:${chainId}` !== network) throw new Error(`RPC chainId ${chainId} does not match ${network}`);
45
- // Right after settlement the public RPC may not have the receipt yet: wait for it (bounded).
46
- const receipt = await client.waitForTransactionReceipt({ hash: tx, timeout: o.waitMs ?? 60_000, pollingInterval: 2_000 });
47
- if (receipt.status !== "success") throw new Error(`tx status ${receipt.status}`);
48
-
49
- const decoded = receipt.logs
50
- .filter((l) => isAddressEqual(l.address, net.usdc))
51
- .map((l) => { try { return { log: l, ev: decodeEventLog({ abi: ABI, data: l.data, topics: l.topics }) }; } catch { return null; } })
52
- .filter(Boolean);
53
- const payerHint = o.signer?.address ?? o.payer;
54
- let transfers = decoded.filter((d) => d.ev.eventName === "Transfer");
55
- if (payerHint) transfers = transfers.filter((d) => isAddressEqual(d.ev.args.from, payerHint));
56
- if (o.payTo) transfers = transfers.filter((d) => isAddressEqual(d.ev.args.to, o.payTo));
57
- if (transfers.length !== 1) throw new Error(`expected exactly 1 USDC Transfer${payerHint ? " from " + payerHint : ""}${o.payTo ? " to " + o.payTo : ""}, found ${transfers.length}`);
58
- const t = transfers[0];
59
- const payer = getAddress(t.ev.args.from);
60
- const auths = decoded.filter((d) => d.ev.eventName === "AuthorizationUsed" && isAddressEqual(d.ev.args.authorizer, payer));
61
- if (auths.length !== 1) throw new Error(`expected exactly 1 AuthorizationUsed by ${payer}, found ${auths.length}`);
62
-
63
- const record = sortKeys({
64
- labels: o.labels ?? [],
65
- payment: {
66
- amount: t.ev.args.value.toString(),
67
- asset: getAddress(net.usdc),
68
- decimals: USDC_DECIMALS,
69
- from: payer,
70
- locator: { index: t.log.logIndex, kind: "evm-log" },
71
- network,
72
- to: getAddress(t.ev.args.to),
73
- tx,
74
- x402: { nonce: auths[0].ev.args.nonce, resource: o.resource ?? "unknown", scheme: "exact" },
75
- },
76
- purpose: { note: o.note ?? "", ref },
77
- });
78
- const hash = contentSha256(record);
79
- // Compatible with the Audit Trail verifier: sha256(JSON.stringify(record)) is the same hash.
80
- const plain = sha256Hex(JSON.stringify(record));
81
- if (plain !== hash || JSON.stringify(record) !== canonicalize(record)) throw new Error("record is not in canonical order (bug)");
82
-
83
- const doc = { version: VERSION, content_sha256: hash, record };
84
- if (o.signer) {
85
- if (!isAddressEqual(o.signer.address, payer)) throw new Error(`signer ${o.signer.address} is not the payer ${payer}`);
86
- const statement = STATEMENT_PREFIX + hash;
87
- doc.agent = { alg: "eip191-secp256k1", key: getAddress(o.signer.address), signature: await o.signer.signMessage({ message: statement }), statement };
88
- }
89
- doc.network = network;
90
- return doc;
91
- }
92
-
93
- /** Verifies a receipt against the chain. Returns { ok, checks }. */
94
- export function verifyReceipt(doc, { requireSignature = true, rpcUrl } = {}) {
95
- return verifyBinding(doc, { requireSig: requireSignature, rpc: rpcUrl });
96
- }
1
+ // bindReceipt(): builds a "nirium-payment-binding-v1" receipt for a settled x402 payment on
2
+ // Avalanche, bound to the exact USDC Transfer log (block-level logIndex) and its EIP-3009 nonce,
3
+ // and signs it as the payer when a signer is given. Format: docs/payment-binding-v1.md.
4
+ //
5
+ // The receipt adds what the chain does not keep: who declared the payment and what it was for
6
+ // (`purpose`). It does not prove delivery.
7
+
8
+ import { createPublicClient, http, decodeEventLog, parseAbi, isAddressEqual, getAddress } from "viem";
9
+ import { contentSha256, canonicalize, sha256Hex, verifyBinding, VERSION, STATEMENT_PREFIX } from "../verify-evm-core.mjs";
10
+ import { getNetwork, USDC_DECIMALS } from "./networks.mjs";
11
+ import { attestPq } from "./pq.mjs";
12
+
13
+ const ABI = parseAbi([
14
+ "event Transfer(address indexed from, address indexed to, uint256 value)",
15
+ "event AuthorizationUsed(address indexed authorizer, bytes32 indexed nonce)",
16
+ ]);
17
+
18
+ function sortKeys(v) {
19
+ if (v === null || typeof v !== "object") return v;
20
+ if (Array.isArray(v)) return v.map(sortKeys);
21
+ return Object.fromEntries(Object.keys(v).sort().map((k) => [k, sortKeys(v[k])]));
22
+ }
23
+
24
+ /**
25
+ * @param {object} o
26
+ * @param {string} o.tx settled tx hash (from the PAYMENT-RESPONSE header's `transaction`)
27
+ * @param {string} o.network "eip155:43113" | "eip155:43114"
28
+ * @param {string} o.ref order reference (purpose.ref)
29
+ * @param {string} [o.resource] the paid URL
30
+ * @param {string} [o.note] short, no personal data
31
+ * @param {string[]} [o.labels] e.g. ["selftest"]; default []
32
+ * @param {object} [o.signer] viem account of the payer ({ address, signMessage }); omit for an unsigned receipt
33
+ * @param {object} [o.pqSigner] ML-DSA-65 key pair from pqKeygen(); adds a post-quantum `pq` signature (needs `signer`)
34
+ * @param {string} [o.payer] narrow the Transfer when the tx settled several (batch)
35
+ * @param {string} [o.payTo]
36
+ * @param {string} [o.rpcUrl]
37
+ * @param {number} [o.waitMs] how long to wait for the tx to appear on the RPC, default 60000
38
+ */
39
+ export async function bindReceipt(o) {
40
+ const { tx, network, ref } = o;
41
+ if (!/^0x[0-9a-fA-F]{64}$/.test(String(tx))) throw new Error("bindReceipt: tx must be a 0x 32-byte hash");
42
+ if (typeof ref !== "string" || !ref.trim()) throw new Error("bindReceipt: ref (purpose.ref) is required");
43
+ const net = getNetwork(network);
44
+ const client = createPublicClient({ chain: net.chain, transport: http(o.rpcUrl) });
45
+ const chainId = await client.getChainId();
46
+ if (`eip155:${chainId}` !== network) throw new Error(`RPC chainId ${chainId} does not match ${network}`);
47
+ // Right after settlement the public RPC may not have the receipt yet: wait for it (bounded).
48
+ const receipt = await client.waitForTransactionReceipt({ hash: tx, timeout: o.waitMs ?? 60_000, pollingInterval: 2_000 });
49
+ if (receipt.status !== "success") throw new Error(`tx status ${receipt.status}`);
50
+
51
+ const decoded = receipt.logs
52
+ .filter((l) => isAddressEqual(l.address, net.usdc))
53
+ .map((l) => { try { return { log: l, ev: decodeEventLog({ abi: ABI, data: l.data, topics: l.topics }) }; } catch { return null; } })
54
+ .filter(Boolean);
55
+ const payerHint = o.signer?.address ?? o.payer;
56
+ let transfers = decoded.filter((d) => d.ev.eventName === "Transfer");
57
+ if (payerHint) transfers = transfers.filter((d) => isAddressEqual(d.ev.args.from, payerHint));
58
+ if (o.payTo) transfers = transfers.filter((d) => isAddressEqual(d.ev.args.to, o.payTo));
59
+ if (transfers.length !== 1) throw new Error(`expected exactly 1 USDC Transfer${payerHint ? " from " + payerHint : ""}${o.payTo ? " to " + o.payTo : ""}, found ${transfers.length}`);
60
+ const t = transfers[0];
61
+ const payer = getAddress(t.ev.args.from);
62
+ const auths = decoded.filter((d) => d.ev.eventName === "AuthorizationUsed" && isAddressEqual(d.ev.args.authorizer, payer));
63
+ if (auths.length !== 1) throw new Error(`expected exactly 1 AuthorizationUsed by ${payer}, found ${auths.length}`);
64
+
65
+ const record = sortKeys({
66
+ labels: o.labels ?? [],
67
+ payment: {
68
+ amount: t.ev.args.value.toString(),
69
+ asset: getAddress(net.usdc),
70
+ decimals: USDC_DECIMALS,
71
+ from: payer,
72
+ locator: { index: t.log.logIndex, kind: "evm-log" },
73
+ network,
74
+ to: getAddress(t.ev.args.to),
75
+ tx,
76
+ x402: { nonce: auths[0].ev.args.nonce, resource: o.resource ?? "unknown", scheme: "exact" },
77
+ },
78
+ purpose: { note: o.note ?? "", ref },
79
+ });
80
+ const hash = contentSha256(record);
81
+ // Compatible with the Audit Trail verifier: sha256(JSON.stringify(record)) is the same hash.
82
+ const plain = sha256Hex(JSON.stringify(record));
83
+ if (plain !== hash || JSON.stringify(record) !== canonicalize(record)) throw new Error("record is not in canonical order (bug)");
84
+
85
+ const doc = { version: VERSION, content_sha256: hash, record };
86
+ if (o.signer) {
87
+ if (!isAddressEqual(o.signer.address, payer)) throw new Error(`signer ${o.signer.address} is not the payer ${payer}`);
88
+ const statement = STATEMENT_PREFIX + hash;
89
+ doc.agent = { alg: "eip191-secp256k1", key: getAddress(o.signer.address), signature: await o.signer.signMessage({ message: statement }), statement };
90
+ }
91
+ if (o.pqSigner) {
92
+ if (!o.signer) throw new Error("bindReceipt: pqSigner needs signer (the key is registered by the payer's address)");
93
+ doc.pq = attestPq(hash, o.pqSigner);
94
+ }
95
+ doc.network = network;
96
+ return doc;
97
+ }
98
+
99
+ /** Verifies a receipt against the chain. Returns { ok, checks }. */
100
+ export function verifyReceipt(doc, { requireSignature = true, requirePq = false, rpcUrl } = {}) {
101
+ return verifyBinding(doc, { requireSig: requireSignature, requirePq, rpc: rpcUrl });
102
+ }
package/sdk/serve.mjs CHANGED
@@ -1,106 +1,106 @@
1
- // x402Serve(): charge for your own API on Avalanche in three lines, same shape as the Stellar one
2
- // in the `nirium` package:
3
- //
4
- // app.use(x402Serve({ payTo: "0x...", routes: { "GET /signals": "$0.02" } }));
5
- //
6
- // Runs on YOUR server. Nirium runs nothing here and receives nothing: the buyer pays your payTo
7
- // directly and an independent facilitator (PayAI by default) verifies and settles. No telemetry.
8
- //
9
- // Prices are converted to an explicit USDC amount with the token's EIP-712 domain, because Fuji
10
- // USDC is not a default asset in @x402/evm 2.32.0. The middleware is built on the first request,
11
- // after a /supported preflight, so a facilitator that is down or rejects you answers 503 with a
12
- // hint instead of crashing the process (the same lesson as the Stellar x402Serve).
13
-
14
- import { isAddress, getAddress } from "viem";
15
- import { getNetwork, dollarsToAtomic, USDC_EXTRA, PAYAI_FACILITATOR } from "./networks.mjs";
16
-
17
- // Linear time. A `/\/+$/` replace is polynomial on input made of many slashes (CodeQL
18
- // js/polynomial-redos); the URL comes from config, but there is no reason to keep the risk.
19
- export function trimTrailingSlashes(url) {
20
- let s = String(url);
21
- let end = s.length;
22
- while (end > 0 && s.charCodeAt(end - 1) === 47) end--;
23
- return s.slice(0, end);
24
- }
25
-
26
- /**
27
- * @param {object} config
28
- * @param {string} config.payTo address that receives the USDC
29
- * @param {Record<string, string | {price?: string, amount?: string, description?: string}>} config.routes
30
- * "GET /signals": "$0.02"; `amount` takes atomic units instead of dollars; method defaults to GET
31
- * @param {"eip155:43113"|"eip155:43114"} [config.network] default Fuji
32
- * @param {string} [config.facilitatorUrl] default PayAI
33
- * @param {number} [config.maxTimeoutSeconds] default 120
34
- * @param {string} [config.appName]
35
- */
36
- export function x402Serve(config) {
37
- if (!config || !isAddress(String(config.payTo ?? ""))) throw new Error("x402Serve: `payTo` must be a 0x address. Without it there is nobody to pay.");
38
- const entries = Object.entries(config.routes || {});
39
- if (entries.length === 0) throw new Error("x402Serve: `routes` is empty; nothing would ever be charged for.");
40
- const network = config.network || "eip155:43113";
41
- const net = getNetwork(network);
42
- const payTo = getAddress(config.payTo);
43
- const facilitatorUrl = trimTrailingSlashes(config.facilitatorUrl || PAYAI_FACILITATOR);
44
-
45
- const routes = {};
46
- for (const [key, value] of entries) {
47
- const spec = typeof value === "string" ? { price: value } : value;
48
- const amount = spec.amount !== undefined ? String(spec.amount) : dollarsToAtomic(spec.price);
49
- if (!/^\d+$/.test(amount) || BigInt(amount) <= 0n) throw new Error(`x402Serve: route "${key}" needs a positive amount`);
50
- const routeKey = /^[A-Z]+\s/.test(key) ? key : `GET ${key}`;
51
- routes[routeKey] = {
52
- ...(spec.description ? { description: spec.description } : {}),
53
- accepts: [{
54
- scheme: "exact", network, payTo,
55
- price: { amount, asset: net.usdc, extra: { ...USDC_EXTRA } },
56
- maxTimeoutSeconds: config.maxTimeoutSeconds ?? 120,
57
- }],
58
- };
59
- }
60
-
61
- const preflight = async () => {
62
- const r = await fetch(`${facilitatorUrl}/supported`, { signal: AbortSignal.timeout(10_000) });
63
- if (!r.ok) throw new Error(`facilitator returned ${r.status}`);
64
- const body = await r.json();
65
- const ok = (body?.kinds ?? []).some((k) => k.network === network && k.scheme === "exact");
66
- if (!ok) throw new Error(`facilitator does not support exact on ${network}`);
67
- };
68
-
69
- let cached;
70
- const build = async () => {
71
- await preflight();
72
- const [{ paymentMiddleware, x402ResourceServer }, { HTTPFacilitatorClient }, { ExactEvmScheme }] = await Promise.all([
73
- import("@x402/express"), import("@x402/core/server"), import("@x402/evm/exact/server"),
74
- ]);
75
- const facilitator = new HTTPFacilitatorClient({ url: facilitatorUrl });
76
- const server = new x402ResourceServer(facilitator).register(network, new ExactEvmScheme());
77
- return paymentMiddleware(routes, server);
78
- };
79
-
80
- // Only requests to a paid route touch the facilitator. Everything else passes straight
81
- // through, so a facilitator outage never takes down the rest of the app.
82
- const paid = Object.keys(routes).map((k) => {
83
- const [method, path] = k.split(/\s+/, 2);
84
- return { method: method.toUpperCase(), path, prefix: path.endsWith("/*") ? path.slice(0, -1) : undefined };
85
- });
86
- const isPaid = (req) => {
87
- const path = String(req.path ?? req.url ?? "").split("?")[0];
88
- return paid.some((r) => r.method === String(req.method).toUpperCase() && (r.prefix ? path.startsWith(r.prefix) : path === r.path));
89
- };
90
-
91
- return async function niriumX402(req, res, next) {
92
- if (!isPaid(req)) return next();
93
- try {
94
- if (!cached) cached = build().catch((e) => { cached = undefined; throw e; });
95
- const mw = await cached;
96
- return mw(req, res, next);
97
- } catch (err) {
98
- if (res.headersSent) return;
99
- res.status(503).json({
100
- error: "x402 payments unavailable",
101
- detail: String(err?.message ?? err).slice(0, 200),
102
- hint: "the facilitator could not be reached or does not support this network",
103
- });
104
- }
105
- };
106
- }
1
+ // x402Serve(): charge for your own API on Avalanche in three lines, same shape as the Stellar one
2
+ // in the `nirium` package:
3
+ //
4
+ // app.use(x402Serve({ payTo: "0x...", routes: { "GET /signals": "$0.02" } }));
5
+ //
6
+ // Runs on YOUR server. Nirium runs nothing here and receives nothing: the buyer pays your payTo
7
+ // directly and an independent facilitator (PayAI by default) verifies and settles. No telemetry.
8
+ //
9
+ // Prices are converted to an explicit USDC amount with the token's EIP-712 domain, because Fuji
10
+ // USDC is not a default asset in @x402/evm 2.32.0. The middleware is built on the first request,
11
+ // after a /supported preflight, so a facilitator that is down or rejects you answers 503 with a
12
+ // hint instead of crashing the process (the same lesson as the Stellar x402Serve).
13
+
14
+ import { isAddress, getAddress } from "viem";
15
+ import { getNetwork, dollarsToAtomic, USDC_EXTRA, PAYAI_FACILITATOR } from "./networks.mjs";
16
+
17
+ // Linear time. A `/\/+$/` replace is polynomial on input made of many slashes (CodeQL
18
+ // js/polynomial-redos); the URL comes from config, but there is no reason to keep the risk.
19
+ export function trimTrailingSlashes(url) {
20
+ let s = String(url);
21
+ let end = s.length;
22
+ while (end > 0 && s.charCodeAt(end - 1) === 47) end--;
23
+ return s.slice(0, end);
24
+ }
25
+
26
+ /**
27
+ * @param {object} config
28
+ * @param {string} config.payTo address that receives the USDC
29
+ * @param {Record<string, string | {price?: string, amount?: string, description?: string}>} config.routes
30
+ * "GET /signals": "$0.02"; `amount` takes atomic units instead of dollars; method defaults to GET
31
+ * @param {"eip155:43113"|"eip155:43114"} [config.network] default Fuji
32
+ * @param {string} [config.facilitatorUrl] default PayAI
33
+ * @param {number} [config.maxTimeoutSeconds] default 120
34
+ * @param {string} [config.appName]
35
+ */
36
+ export function x402Serve(config) {
37
+ if (!config || !isAddress(String(config.payTo ?? ""))) throw new Error("x402Serve: `payTo` must be a 0x address. Without it there is nobody to pay.");
38
+ const entries = Object.entries(config.routes || {});
39
+ if (entries.length === 0) throw new Error("x402Serve: `routes` is empty; nothing would ever be charged for.");
40
+ const network = config.network || "eip155:43113";
41
+ const net = getNetwork(network);
42
+ const payTo = getAddress(config.payTo);
43
+ const facilitatorUrl = trimTrailingSlashes(config.facilitatorUrl || PAYAI_FACILITATOR);
44
+
45
+ const routes = {};
46
+ for (const [key, value] of entries) {
47
+ const spec = typeof value === "string" ? { price: value } : value;
48
+ const amount = spec.amount !== undefined ? String(spec.amount) : dollarsToAtomic(spec.price);
49
+ if (!/^\d+$/.test(amount) || BigInt(amount) <= 0n) throw new Error(`x402Serve: route "${key}" needs a positive amount`);
50
+ const routeKey = /^[A-Z]+\s/.test(key) ? key : `GET ${key}`;
51
+ routes[routeKey] = {
52
+ ...(spec.description ? { description: spec.description } : {}),
53
+ accepts: [{
54
+ scheme: "exact", network, payTo,
55
+ price: { amount, asset: net.usdc, extra: { ...USDC_EXTRA } },
56
+ maxTimeoutSeconds: config.maxTimeoutSeconds ?? 120,
57
+ }],
58
+ };
59
+ }
60
+
61
+ const preflight = async () => {
62
+ const r = await fetch(`${facilitatorUrl}/supported`, { signal: AbortSignal.timeout(10_000) });
63
+ if (!r.ok) throw new Error(`facilitator returned ${r.status}`);
64
+ const body = await r.json();
65
+ const ok = (body?.kinds ?? []).some((k) => k.network === network && k.scheme === "exact");
66
+ if (!ok) throw new Error(`facilitator does not support exact on ${network}`);
67
+ };
68
+
69
+ let cached;
70
+ const build = async () => {
71
+ await preflight();
72
+ const [{ paymentMiddleware, x402ResourceServer }, { HTTPFacilitatorClient }, { ExactEvmScheme }] = await Promise.all([
73
+ import("@x402/express"), import("@x402/core/server"), import("@x402/evm/exact/server"),
74
+ ]);
75
+ const facilitator = new HTTPFacilitatorClient({ url: facilitatorUrl });
76
+ const server = new x402ResourceServer(facilitator).register(network, new ExactEvmScheme());
77
+ return paymentMiddleware(routes, server);
78
+ };
79
+
80
+ // Only requests to a paid route touch the facilitator. Everything else passes straight
81
+ // through, so a facilitator outage never takes down the rest of the app.
82
+ const paid = Object.keys(routes).map((k) => {
83
+ const [method, path] = k.split(/\s+/, 2);
84
+ return { method: method.toUpperCase(), path, prefix: path.endsWith("/*") ? path.slice(0, -1) : undefined };
85
+ });
86
+ const isPaid = (req) => {
87
+ const path = String(req.path ?? req.url ?? "").split("?")[0];
88
+ return paid.some((r) => r.method === String(req.method).toUpperCase() && (r.prefix ? path.startsWith(r.prefix) : path === r.path));
89
+ };
90
+
91
+ return async function niriumX402(req, res, next) {
92
+ if (!isPaid(req)) return next();
93
+ try {
94
+ if (!cached) cached = build().catch((e) => { cached = undefined; throw e; });
95
+ const mw = await cached;
96
+ return mw(req, res, next);
97
+ } catch (err) {
98
+ if (res.headersSent) return;
99
+ res.status(503).json({
100
+ error: "x402 payments unavailable",
101
+ detail: String(err?.message ?? err).slice(0, 200),
102
+ hint: "the facilitator could not be reached or does not support this network",
103
+ });
104
+ }
105
+ };
106
+ }