nirium-avalanche 0.1.0 → 0.3.0

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/README.md CHANGED
@@ -36,12 +36,14 @@ app. Settlement is done by PayAI, an independent x402 facilitator.
36
36
  | `nirium-avalanche` | `x402Serve`, `createX402Fetch`, `settlementOf`, `bindReceipt`, `verifyReceipt`, `createRulesPolicy` |
37
37
  | `nirium-avalanche/policy` | The pre-sign policy gate (decodes what is about to be signed, asks your policy, signs only on a bound ALLOW) |
38
38
  | `nirium-avalanche/policy/rules` | A small reference policy engine: max amount, approval line, allowlists |
39
- | `nirium-avalanche/verify` | The receipt verifier as a library |
39
+ | `nirium-avalanche/receipt` | `bindReceipt` and `verifyReceipt` on their own, without the Express middleware |
40
+ | `nirium-avalanche/decision` | Decision receipts: `bindDecision`, `verifyDecision`, `collectDecisions` (also exported from `nirium-avalanche`) |
41
+ | `nirium-avalanche/verify` | The receipt verifier as a library. No Node-only code, so it runs in Node and in the browser |
40
42
 
41
43
  Check a receipt from the command line:
42
44
 
43
45
  ```bash
44
- npx nirium-verify-evm receipt.json
46
+ npx -p nirium-avalanche nirium-verify-evm receipt.json
45
47
  ```
46
48
 
47
49
  Exit code 0 means valid, 1 means a check failed, 2 means bad input.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "nirium-avalanche",
3
- "version": "0.1.0",
3
+ "version": "0.3.0",
4
4
  "description": "Pay and charge with x402 on Avalanche, refuse a payment before it is signed, and keep a payer-signed receipt bound to the exact USDC transfer",
5
5
  "type": "module",
6
6
  "license": "Apache-2.0",
@@ -28,21 +28,25 @@
28
28
  "./policy": "./policy/evm-policy.mjs",
29
29
  "./policy/x402-fetch": "./policy/x402-fetch.mjs",
30
30
  "./policy/rules": "./policy/rules-policy.mjs",
31
- "./verify": "./verify-evm-receipt.mjs",
31
+ "./receipt": "./sdk/receipt.mjs",
32
+ "./decision": "./sdk/decision.mjs",
33
+ "./verify": "./verify-evm-core.mjs",
32
34
  "./package.json": "./package.json"
33
35
  },
34
36
  "bin": {
35
- "nirium-verify-evm": "./verify-evm-receipt.mjs"
37
+ "nirium-verify-evm": "verify-evm-receipt.mjs"
36
38
  },
37
39
  "files": [
38
40
  "sdk/*.mjs",
39
41
  "policy/evm-policy.mjs",
40
42
  "policy/x402-fetch.mjs",
41
43
  "policy/rules-policy.mjs",
44
+ "verify-evm-core.mjs",
42
45
  "verify-evm-receipt.mjs"
43
46
  ],
44
47
  "scripts": {
45
- "test": "node --test policy/test/*.test.mjs sdk/test/*.test.mjs",
48
+ "test": "node --test test/*.test.mjs policy/test/*.test.mjs sdk/test/*.test.mjs",
49
+ "test:verify": "node --test test/*.test.mjs",
46
50
  "test:policy": "node --test policy/test/*.test.mjs",
47
51
  "test:sdk": "node --test sdk/test/*.test.mjs",
48
52
  "test:live": "bash run-tests.sh"
@@ -14,8 +14,7 @@
14
14
  // Not a security boundary against code in the same process: whoever holds the base signer
15
15
  // can still call it directly.
16
16
 
17
- import { createHash } from "node:crypto";
18
- import { getAddress, hashTypedData, isAddress } from "viem";
17
+ import { getAddress, hashTypedData, isAddress, sha256, stringToBytes } from "viem";
19
18
 
20
19
  const DEFAULT_TIMEOUT_MS = 5000;
21
20
  const HEX32 = /^0x[0-9a-fA-F]{64}$/;
@@ -77,7 +76,7 @@ export class X402PolicyError extends Error {
77
76
  }
78
77
  }
79
78
 
80
- const sha256hex = (s) => createHash("sha256").update(s, "utf8").digest("hex");
79
+ const sha256hex = (s) => sha256(stringToBytes(s)).slice(2);
81
80
  const nonempty = (v) => typeof v === "string" && v.trim().length > 0;
82
81
 
83
82
  /** Validates a policy hook when it is configured, so bad config fails before any payment. */
@@ -0,0 +1,108 @@
1
+ // Decision receipts ("nirium-decision-v1") on Avalanche: a payer-signed record of what the pre-sign
2
+ // policy decided about an x402 payment, including the ones that were never signed (DENY, WAIT and
3
+ // every other refusal), which leave no trace on the chain. Format: docs/decision-receipt-v1.md.
4
+ //
5
+ // No Node-only APIs: runs in Node and in the browser, like the receipt verifier.
6
+
7
+ import { getAddress, isAddressEqual, verifyMessage } from "viem";
8
+ import { canonicalize, contentSha256, STATEMENT_PREFIX } from "../verify-evm-core.mjs";
9
+ import { NETWORKS, USDC_DECIMALS } from "./networks.mjs";
10
+
11
+ export const DECISION_VERSION = "nirium-decision-v1";
12
+ export const DECISION_OUTCOMES = Object.freeze([
13
+ "ALLOWED", "SIGNED", "DENY", "WAIT", "TIMEOUT", "ENGINE_ERROR", "EXPIRED", "UNBOUND", "MALFORMED",
14
+ "STALE", "VERSION_UNAVAILABLE", "SIGNER_CHANGED", "CLOCK_INVALID",
15
+ ]);
16
+ const EVM_NETWORK = /^eip155:\d{1,12}$/;
17
+ const HEX64 = /^[0-9a-f]{64}$/;
18
+ const nonempty = (v) => typeof v === "string" && v.trim().length > 0;
19
+ const sameAddr = (a, b) => { try { return isAddressEqual(a, b); } catch { return false; } };
20
+
21
+ /**
22
+ * The record for one policy decision, in canonical key order, or null when the policy refused
23
+ * before it had decoded a payment (CONTEXT_MISMATCH): there is nothing to describe then.
24
+ * @param {object} policyRecord what the policy passed to onDecision: { outcome, context, decision, error }
25
+ * @param {object} [o] { ref, note, labels }
26
+ */
27
+ export function decisionRecord(policyRecord, { ref, note, labels = [] } = {}) {
28
+ const c = policyRecord?.context;
29
+ const a = c?.authorization;
30
+ const network = c?.requirements?.network;
31
+ if (!a || !network) return null;
32
+ const outcome = policyRecord.outcome;
33
+ if (!DECISION_OUTCOMES.includes(outcome)) throw new Error(`decisionRecord: unknown outcome ${outcome}`);
34
+ const usdc = NETWORKS[network]?.usdc;
35
+ if (!usdc || !sameAddr(a.verifyingContract, usdc)) throw new Error(`decisionRecord: ${a.verifyingContract} is not USDC on ${network}`);
36
+ const d = policyRecord.decision ?? {};
37
+ const decision = { outcome };
38
+ if (nonempty(d.policyVersion)) decision.policyVersion = String(d.policyVersion);
39
+ const reason = nonempty(d.reason) ? d.reason : (nonempty(policyRecord.error) ? policyRecord.error : undefined);
40
+ if (reason) decision.reason = String(reason).slice(0, 280);
41
+ const intent = {
42
+ amount: String(a.amount), asset: getAddress(a.verifyingContract), contextHash: String(c.contextHash),
43
+ decimals: USDC_DECIMALS, from: getAddress(a.from), method: String(c.method), network: String(network),
44
+ nonce: String(a.nonce), payloadHash: String(a.payloadHash), resource: String(c.url), to: getAddress(a.to),
45
+ };
46
+ const record = { decision, intent, labels: [...labels].map(String) };
47
+ if (nonempty(ref)) record.purpose = note ? { note: String(note), ref } : { ref };
48
+ return JSON.parse(canonicalize(record));
49
+ }
50
+
51
+ /**
52
+ * Builds and signs a decision receipt with the payer's viem account (EIP-191 over the statement).
53
+ * Returns { doc, record } (null when there is no decoded payment). With hashOnly, `doc` has no
54
+ * record: keep `record` yourself to show it later.
55
+ */
56
+ export async function bindDecision(policyRecord, { signer, ref, note, labels, hashOnly = false } = {}) {
57
+ const record = decisionRecord(policyRecord, { ref, note, labels });
58
+ if (!record) return null;
59
+ if (!signer || typeof signer.signMessage !== "function") throw new Error("bindDecision: signer must be the payer's viem account (signMessage)");
60
+ if (!sameAddr(signer.address, record.intent.from)) throw new Error(`bindDecision: signer ${signer.address} is not the payer ${record.intent.from}`);
61
+ const content_sha256 = contentSha256(record);
62
+ const statement = STATEMENT_PREFIX + content_sha256;
63
+ const agent = { alg: "eip191-secp256k1", key: getAddress(signer.address), signature: await signer.signMessage({ message: statement }), statement };
64
+ const network = record.intent.network;
65
+ const doc = hashOnly
66
+ ? { version: DECISION_VERSION, content_sha256, agent, network }
67
+ : { version: DECISION_VERSION, content_sha256, record, agent, network };
68
+ return { doc, record };
69
+ }
70
+
71
+ /**
72
+ * Checks a decision receipt: format, hash (with a record), payer signature. Nothing on-chain: a
73
+ * refusal leaves nothing there. For a hash-only document, pass { record } to check that it is the
74
+ * record behind content_sha256. Returns { ok, checks: [{ name, ok, detail }] }.
75
+ */
76
+ export async function verifyDecision(doc, { record: heldRecord } = {}) {
77
+ const checks = [];
78
+ const check = (name, ok, detail) => { checks.push({ name, ok: Boolean(ok), ...(detail ? { detail } : {}) }); return Boolean(ok); };
79
+ const d = doc ?? {};
80
+ check("version == nirium-decision-v1", d.version === DECISION_VERSION, String(d.version));
81
+ check("network is an EVM CAIP-2 id", EVM_NETWORK.test(String(d.network)), String(d.network));
82
+ check("content_sha256 is 64 hex", HEX64.test(String(d.content_sha256)));
83
+ const record = d.record ?? heldRecord;
84
+ if (record) {
85
+ let canon;
86
+ try { canon = canonicalize(record); } catch { canon = null; }
87
+ check("content_sha256 == sha256(canonical(record))", canon !== null && contentSha256(record) === d.content_sha256,
88
+ d.record ? undefined : "record held by the verifier (hash-only document)");
89
+ check("decision.outcome is a known outcome", DECISION_OUTCOMES.includes(record?.decision?.outcome), String(record?.decision?.outcome));
90
+ check("record.intent.network == network", record?.intent?.network === d.network);
91
+ }
92
+ const ag = d.agent ?? {};
93
+ const statementOk = check("agent.statement == nirium-audit-v1:<content_sha256>", ag.statement === STATEMENT_PREFIX + d.content_sha256);
94
+ check("agent.alg == eip191-secp256k1", ag.alg === "eip191-secp256k1", String(ag.alg));
95
+ if (record) check("agent.key == record.intent.from (the payer signs)", sameAddr(ag.key, record?.intent?.from));
96
+ let sigOk = false;
97
+ if (statementOk && typeof ag.key === "string" && typeof ag.signature === "string") {
98
+ try { sigOk = await verifyMessage({ address: ag.key, message: ag.statement, signature: ag.signature }); } catch { sigOk = false; }
99
+ }
100
+ check("EIP-191 signature by agent.key over agent.statement", sigOk);
101
+ return { ok: checks.every((c) => c.ok), checks };
102
+ }
103
+
104
+ /** An onDecision observer that keeps every policy record, to sign after the payment attempt. */
105
+ export function collectDecisions() {
106
+ const records = [];
107
+ return { records, onDecision: (r) => { records.push(r); } };
108
+ }
package/sdk/index.mjs CHANGED
@@ -2,9 +2,11 @@
2
2
  // pay: createX402Fetch, settlementOf (optional pre-sign policy)
3
3
  // charge: x402Serve (Express middleware, PayAI by default)
4
4
  // prove: bindReceipt, verifyReceipt (payer-signed receipt bound to the transfer)
5
+ // decide: bindDecision, verifyDecision (payer-signed receipt of a policy decision, incl. DENY/WAIT)
5
6
  export { createX402Fetch, settlementOf } from "./pay.mjs";
6
7
  export { x402Serve } from "./serve.mjs";
7
8
  export { bindReceipt, verifyReceipt } from "./receipt.mjs";
9
+ export { bindDecision, verifyDecision, decisionRecord, collectDecisions, DECISION_VERSION, DECISION_OUTCOMES } from "./decision.mjs";
8
10
  export { NETWORKS, USDC_EXTRA, PAYAI_FACILITATOR, getNetwork, dollarsToAtomic } from "./networks.mjs";
9
11
  export { createRulesPolicy } from "../policy/rules-policy.mjs";
10
12
  export { X402PolicyError } from "../policy/evm-policy.mjs";
package/sdk/receipt.mjs CHANGED
@@ -5,9 +5,8 @@
5
5
  // The receipt adds what the chain does not keep: who declared the payment and what it was for
6
6
  // (`purpose`). It does not prove delivery.
7
7
 
8
- import { createHash } from "node:crypto";
9
8
  import { createPublicClient, http, decodeEventLog, parseAbi, isAddressEqual, getAddress } from "viem";
10
- import { contentSha256, canonicalize, verifyBinding, VERSION, STATEMENT_PREFIX } from "../verify-evm-receipt.mjs";
9
+ import { contentSha256, canonicalize, sha256Hex, verifyBinding, VERSION, STATEMENT_PREFIX } from "../verify-evm-core.mjs";
11
10
  import { getNetwork, USDC_DECIMALS } from "./networks.mjs";
12
11
 
13
12
  const ABI = parseAbi([
@@ -78,7 +77,7 @@ export async function bindReceipt(o) {
78
77
  });
79
78
  const hash = contentSha256(record);
80
79
  // Compatible with the Audit Trail verifier: sha256(JSON.stringify(record)) is the same hash.
81
- const plain = createHash("sha256").update(JSON.stringify(record), "utf8").digest("hex");
80
+ const plain = sha256Hex(JSON.stringify(record));
82
81
  if (plain !== hash || JSON.stringify(record) !== canonicalize(record)) throw new Error("record is not in canonical order (bug)");
83
82
 
84
83
  const doc = { version: VERSION, content_sha256: hash, record };
@@ -0,0 +1,159 @@
1
+ // verify-evm-core.mjs - read-only check of a Nirium EVM payment binding.
2
+ //
3
+ // The one verifier: the CLI (verify-evm-receipt.mjs), verifyReceipt() and the browser all run
4
+ // this file. It has no Node-only imports (no node:crypto, no fs), so it also runs in a browser:
5
+ // sha256 comes from viem (built on @noble/hashes).
6
+ //
7
+ // Format "nirium-payment-binding-v1" (fixed 26-nov-2026):
8
+ // {
9
+ // "version": "nirium-payment-binding-v1",
10
+ // "content_sha256": "<hex sha256 of canonical(record)>",
11
+ // "record": {
12
+ // "labels": ["selftest"],
13
+ // "payment": {
14
+ // "amount": "10000", "asset": "0x...", "decimals": 6,
15
+ // "from": "0x..payer", "to": "0x..payTo", "tx": "0x..",
16
+ // "locator": { "index": 17, "kind": "evm-log" }, // block-level log index
17
+ // "network": "eip155:43113",
18
+ // "x402": { "nonce": "0x..authNonce", "resource": "https://...", "scheme": "exact" }
19
+ // },
20
+ // "purpose": { "note": "...", "ref": "..." }
21
+ // },
22
+ // "agent": { "alg": "eip191-secp256k1", "key": "0x..payer",
23
+ // "signature": "0x..", "statement": "nirium-audit-v1:<content_sha256>" },
24
+ // "network": "eip155:43113"
25
+ // }
26
+ //
27
+ // canonical() = keys sorted recursively, no whitespace, values as JSON.stringify
28
+ // writes them; applied ONLY to `record`.
29
+ // --no-sig skips the `agent` block entirely (used for third-party txs we did
30
+ // not sign); the record hash and every on-chain check still run.
31
+ //
32
+ // Not supported yet: payers that are smart wallets (ERC-1271/6492)
33
+ // need publicClient.verifyMessage instead of the standalone ECDSA verifyMessage.
34
+ // Not supported yet: seller-signed bindings (agent.key == payment.to) once that role exists.
35
+ //
36
+ // No keys, no writes: only eth_chainId and eth_getTransactionReceipt.
37
+
38
+ import {
39
+ createPublicClient, http, decodeEventLog, parseAbi, getAddress,
40
+ isAddressEqual, verifyMessage, sha256, stringToBytes,
41
+ } from "viem";
42
+ import { avalanche, avalancheFuji } from "viem/chains";
43
+
44
+ export const VERSION = "nirium-payment-binding-v1";
45
+ export const STATEMENT_PREFIX = "nirium-audit-v1:";
46
+
47
+ const CHAINS = {
48
+ "eip155:43114": { chain: avalanche, usdc: "0xB97EF9Ef8734C71904D8002F8b6Bc66Dd9c48a6E" },
49
+ "eip155:43113": { chain: avalancheFuji, usdc: "0x5425890298aed601595a70AB815c96711a31Bc65" },
50
+ };
51
+
52
+ const ABI = parseAbi([
53
+ "event Transfer(address indexed from, address indexed to, uint256 value)",
54
+ "event AuthorizationUsed(address indexed authorizer, bytes32 indexed nonce)",
55
+ ]);
56
+
57
+ export function canonicalize(v) {
58
+ if (v === null || typeof v !== "object") return JSON.stringify(v);
59
+ if (Array.isArray(v)) return "[" + v.map(canonicalize).join(",") + "]";
60
+ return "{" + Object.keys(v).sort()
61
+ .filter((k) => v[k] !== undefined)
62
+ .map((k) => JSON.stringify(k) + ":" + canonicalize(v[k])).join(",") + "}";
63
+ }
64
+
65
+ /** sha256 of the UTF-8 bytes of a string, as lowercase hex without 0x. */
66
+ export function sha256Hex(s) {
67
+ return sha256(stringToBytes(s)).slice(2);
68
+ }
69
+
70
+ export function contentSha256(record) {
71
+ return sha256Hex(canonicalize(record));
72
+ }
73
+
74
+ const eqAddr = (a, b) => { try { return isAddressEqual(a, b); } catch { return false; } };
75
+
76
+ export async function verifyBinding(doc, { requireSig = true, rpc } = {}) {
77
+ const checks = [];
78
+ const add = (name, ok, detail = "") => checks.push({ name, ok: !!ok, detail });
79
+
80
+ const p = doc?.record?.payment;
81
+ if (!p) throw new Error("missing record.payment");
82
+ for (const k of ["amount", "asset", "from", "to", "tx", "network"]) {
83
+ if (p[k] === undefined || p[k] === null || p[k] === "") throw new Error(`missing record.payment.${k}`);
84
+ }
85
+ if (!p.locator || p.locator.index === undefined) throw new Error("missing record.payment.locator.index");
86
+ if (!p.x402?.nonce) throw new Error("missing record.payment.x402.nonce");
87
+ const net = CHAINS[p.network];
88
+ if (!net) throw new Error(`unsupported network ${p.network}`);
89
+
90
+ // Document-level consistency.
91
+ add("version == nirium-payment-binding-v1", doc.version === VERSION, `version=${doc.version}`);
92
+ add("network == record.payment.network", doc.network === p.network, `doc=${doc.network} payment=${p.network}`);
93
+ add("locator.kind == evm-log", p.locator.kind === "evm-log", `kind=${p.locator.kind}`);
94
+ const computed = contentSha256(doc.record);
95
+ add("content_sha256 == sha256(canonical(record))", doc.content_sha256 === computed,
96
+ `doc=${doc.content_sha256} computed=${computed}`);
97
+ add("asset is Circle USDC for this network", eqAddr(p.asset, net.usdc), `asset=${p.asset} expected=${net.usdc}`);
98
+ add("decimals == 6", p.decimals === 6, `decimals=${p.decimals}`);
99
+
100
+ // Chain.
101
+ const client = createPublicClient({ chain: net.chain, transport: http(rpc) });
102
+ const chainId = await client.getChainId();
103
+ add("network == eip155:<RPC chainId>", p.network === `eip155:${chainId}`, `rpc chainId=${chainId}`);
104
+
105
+ let receipt = null;
106
+ try {
107
+ receipt = await client.getTransactionReceipt({ hash: p.tx });
108
+ } catch (e) {
109
+ add("tx receipt found", false, e.shortMessage || e.message);
110
+ }
111
+ if (receipt) {
112
+ add("tx status success (1)", receipt.status === "success", `status=${receipt.status} block=${receipt.blockNumber}`);
113
+
114
+ const idx = Number(p.locator.index);
115
+ const amount = BigInt(p.amount);
116
+ const log = receipt.logs.find((l) => l.logIndex === idx);
117
+ if (!log) {
118
+ add(`log ${idx} exists in tx`, false, `tx log indexes: ${receipt.logs.map((l) => l.logIndex).join(",")}`);
119
+ } else {
120
+ add(`log ${idx} emitted by asset`, eqAddr(log.address, p.asset), `emitter=${log.address}`);
121
+ let ev = null;
122
+ try { ev = decodeEventLog({ abi: ABI, data: log.data, topics: log.topics }); } catch {}
123
+ const isTransfer = ev?.eventName === "Transfer";
124
+ add(`log ${idx} is Transfer`, isTransfer, ev ? `event=${ev.eventName}` : "not decodable");
125
+ if (isTransfer) {
126
+ add("Transfer.from == payment.from", eqAddr(ev.args.from, p.from), `log=${ev.args.from}`);
127
+ add("Transfer.to == payment.to", eqAddr(ev.args.to, p.to), `log=${ev.args.to}`);
128
+ add("Transfer.value == payment.amount", ev.args.value === amount, `log=${ev.args.value} record=${amount}`);
129
+ }
130
+ }
131
+
132
+ const auths = receipt.logs
133
+ .filter((l) => eqAddr(l.address, p.asset))
134
+ .map((l) => { try { return decodeEventLog({ abi: ABI, data: l.data, topics: l.topics }); } catch { return null; } })
135
+ .filter((e) => e?.eventName === "AuthorizationUsed");
136
+ const match = auths.find((e) => eqAddr(e.args.authorizer, p.from)
137
+ && e.args.nonce.toLowerCase() === String(p.x402.nonce).toLowerCase());
138
+ add("AuthorizationUsed(payment.from, x402.nonce) in same tx", match,
139
+ `found ${auths.length}: ${auths.map((e) => `${e.args.authorizer}/${e.args.nonce}`).join(" ; ") || "none"}`);
140
+ }
141
+
142
+ // Agent signature (payer).
143
+ if (!requireSig) {
144
+ add("agent signature (skipped: --no-sig)", true, "NOT checked");
145
+ } else if (!doc.agent?.signature || !doc.agent?.key || !doc.agent?.statement) {
146
+ add("agent block present", false, "agent.key, agent.statement and agent.signature are required");
147
+ } else {
148
+ const a = doc.agent;
149
+ add("agent.alg == eip191-secp256k1", a.alg === "eip191-secp256k1", `alg=${a.alg}`);
150
+ add("agent.statement == nirium-audit-v1:<content_sha256>", a.statement === STATEMENT_PREFIX + doc.content_sha256,
151
+ `statement=${a.statement}`);
152
+ add("agent.key == payment.from (payer signs)", eqAddr(a.key, p.from), `key=${a.key}`);
153
+ let valid = false;
154
+ try { valid = await verifyMessage({ address: a.key, message: a.statement, signature: a.signature }); } catch {}
155
+ add("EIP-191 signature by agent.key over agent.statement", valid);
156
+ }
157
+
158
+ return { ok: checks.every((c) => c.ok), checks };
159
+ }
@@ -1,161 +1,18 @@
1
1
  #!/usr/bin/env node
2
- // verify-evm-receipt.mjs - read-only check of a Nirium EVM payment binding.
2
+ // verify-evm-receipt.mjs - command line for the EVM receipt verifier.
3
3
  //
4
4
  // Usage:
5
5
  // node verify-evm-receipt.mjs <binding.json> [--no-sig] [--rpc <url>] [--json]
6
6
  //
7
- // Format "nirium-payment-binding-v1" (fixed 26-nov-2026):
8
- // {
9
- // "version": "nirium-payment-binding-v1",
10
- // "content_sha256": "<hex sha256 of canonical(record)>",
11
- // "record": {
12
- // "labels": ["selftest"],
13
- // "payment": {
14
- // "amount": "10000", "asset": "0x...", "decimals": 6,
15
- // "from": "0x..payer", "to": "0x..payTo", "tx": "0x..",
16
- // "locator": { "index": 17, "kind": "evm-log" }, // block-level log index
17
- // "network": "eip155:43113",
18
- // "x402": { "nonce": "0x..authNonce", "resource": "https://...", "scheme": "exact" }
19
- // },
20
- // "purpose": { "note": "...", "ref": "..." }
21
- // },
22
- // "agent": { "alg": "eip191-secp256k1", "key": "0x..payer",
23
- // "signature": "0x..", "statement": "nirium-audit-v1:<content_sha256>" },
24
- // "network": "eip155:43113"
25
- // }
26
- //
27
- // canonical() = keys sorted recursively, no whitespace, values as JSON.stringify
28
- // writes them; applied ONLY to `record`.
29
- // --no-sig skips the `agent` block entirely (used for third-party txs we did
30
- // not sign); the record hash and every on-chain check still run.
31
- //
32
- // Not supported yet: payers that are smart wallets (ERC-1271/6492)
33
- // need publicClient.verifyMessage instead of the standalone ECDSA verifyMessage.
34
- // Not supported yet: seller-signed bindings (agent.key == payment.to) once that role exists.
35
- //
36
- // No keys, no writes: only eth_chainId and eth_getTransactionReceipt.
37
- // Exit code 0 = every check passed, 1 = at least one failed, 2 = bad input.
7
+ // Every check lives in verify-evm-core.mjs, the same file verifyReceipt() and the browser run.
8
+ // This file only reads the receipt, prints the checks and sets the exit code:
9
+ // 0 = every check passed, 1 = at least one failed, 2 = bad input.
38
10
 
39
11
  import { readFileSync, realpathSync } from "node:fs";
40
- import { createHash } from "node:crypto";
41
12
  import { fileURLToPath } from "node:url";
42
- import {
43
- createPublicClient, http, decodeEventLog, parseAbi, getAddress,
44
- isAddressEqual, verifyMessage,
45
- } from "viem";
46
- import { avalanche, avalancheFuji } from "viem/chains";
47
-
48
- export const VERSION = "nirium-payment-binding-v1";
49
- export const STATEMENT_PREFIX = "nirium-audit-v1:";
50
-
51
- const CHAINS = {
52
- "eip155:43114": { chain: avalanche, usdc: "0xB97EF9Ef8734C71904D8002F8b6Bc66Dd9c48a6E" },
53
- "eip155:43113": { chain: avalancheFuji, usdc: "0x5425890298aed601595a70AB815c96711a31Bc65" },
54
- };
55
-
56
- const ABI = parseAbi([
57
- "event Transfer(address indexed from, address indexed to, uint256 value)",
58
- "event AuthorizationUsed(address indexed authorizer, bytes32 indexed nonce)",
59
- ]);
60
-
61
- export function canonicalize(v) {
62
- if (v === null || typeof v !== "object") return JSON.stringify(v);
63
- if (Array.isArray(v)) return "[" + v.map(canonicalize).join(",") + "]";
64
- return "{" + Object.keys(v).sort()
65
- .filter((k) => v[k] !== undefined)
66
- .map((k) => JSON.stringify(k) + ":" + canonicalize(v[k])).join(",") + "}";
67
- }
68
-
69
- export function contentSha256(record) {
70
- return createHash("sha256").update(canonicalize(record), "utf8").digest("hex");
71
- }
72
-
73
- const eqAddr = (a, b) => { try { return isAddressEqual(a, b); } catch { return false; } };
74
-
75
- export async function verifyBinding(doc, { requireSig = true, rpc } = {}) {
76
- const checks = [];
77
- const add = (name, ok, detail = "") => checks.push({ name, ok: !!ok, detail });
13
+ import { verifyBinding } from "./verify-evm-core.mjs";
78
14
 
79
- const p = doc?.record?.payment;
80
- if (!p) throw new Error("missing record.payment");
81
- for (const k of ["amount", "asset", "from", "to", "tx", "network"]) {
82
- if (p[k] === undefined || p[k] === null || p[k] === "") throw new Error(`missing record.payment.${k}`);
83
- }
84
- if (!p.locator || p.locator.index === undefined) throw new Error("missing record.payment.locator.index");
85
- if (!p.x402?.nonce) throw new Error("missing record.payment.x402.nonce");
86
- const net = CHAINS[p.network];
87
- if (!net) throw new Error(`unsupported network ${p.network}`);
88
-
89
- // Document-level consistency.
90
- add("version == nirium-payment-binding-v1", doc.version === VERSION, `version=${doc.version}`);
91
- add("network == record.payment.network", doc.network === p.network, `doc=${doc.network} payment=${p.network}`);
92
- add("locator.kind == evm-log", p.locator.kind === "evm-log", `kind=${p.locator.kind}`);
93
- const computed = contentSha256(doc.record);
94
- add("content_sha256 == sha256(canonical(record))", doc.content_sha256 === computed,
95
- `doc=${doc.content_sha256} computed=${computed}`);
96
- add("asset is Circle USDC for this network", eqAddr(p.asset, net.usdc), `asset=${p.asset} expected=${net.usdc}`);
97
- add("decimals == 6", p.decimals === 6, `decimals=${p.decimals}`);
98
-
99
- // Chain.
100
- const client = createPublicClient({ chain: net.chain, transport: http(rpc) });
101
- const chainId = await client.getChainId();
102
- add("network == eip155:<RPC chainId>", p.network === `eip155:${chainId}`, `rpc chainId=${chainId}`);
103
-
104
- let receipt = null;
105
- try {
106
- receipt = await client.getTransactionReceipt({ hash: p.tx });
107
- } catch (e) {
108
- add("tx receipt found", false, e.shortMessage || e.message);
109
- }
110
- if (receipt) {
111
- add("tx status success (1)", receipt.status === "success", `status=${receipt.status} block=${receipt.blockNumber}`);
112
-
113
- const idx = Number(p.locator.index);
114
- const amount = BigInt(p.amount);
115
- const log = receipt.logs.find((l) => l.logIndex === idx);
116
- if (!log) {
117
- add(`log ${idx} exists in tx`, false, `tx log indexes: ${receipt.logs.map((l) => l.logIndex).join(",")}`);
118
- } else {
119
- add(`log ${idx} emitted by asset`, eqAddr(log.address, p.asset), `emitter=${log.address}`);
120
- let ev = null;
121
- try { ev = decodeEventLog({ abi: ABI, data: log.data, topics: log.topics }); } catch {}
122
- const isTransfer = ev?.eventName === "Transfer";
123
- add(`log ${idx} is Transfer`, isTransfer, ev ? `event=${ev.eventName}` : "not decodable");
124
- if (isTransfer) {
125
- add("Transfer.from == payment.from", eqAddr(ev.args.from, p.from), `log=${ev.args.from}`);
126
- add("Transfer.to == payment.to", eqAddr(ev.args.to, p.to), `log=${ev.args.to}`);
127
- add("Transfer.value == payment.amount", ev.args.value === amount, `log=${ev.args.value} record=${amount}`);
128
- }
129
- }
130
-
131
- const auths = receipt.logs
132
- .filter((l) => eqAddr(l.address, p.asset))
133
- .map((l) => { try { return decodeEventLog({ abi: ABI, data: l.data, topics: l.topics }); } catch { return null; } })
134
- .filter((e) => e?.eventName === "AuthorizationUsed");
135
- const match = auths.find((e) => eqAddr(e.args.authorizer, p.from)
136
- && e.args.nonce.toLowerCase() === String(p.x402.nonce).toLowerCase());
137
- add("AuthorizationUsed(payment.from, x402.nonce) in same tx", match,
138
- `found ${auths.length}: ${auths.map((e) => `${e.args.authorizer}/${e.args.nonce}`).join(" ; ") || "none"}`);
139
- }
140
-
141
- // Agent signature (payer).
142
- if (!requireSig) {
143
- add("agent signature (skipped: --no-sig)", true, "NOT checked");
144
- } else if (!doc.agent?.signature || !doc.agent?.key || !doc.agent?.statement) {
145
- add("agent block present", false, "agent.key, agent.statement and agent.signature are required");
146
- } else {
147
- const a = doc.agent;
148
- add("agent.alg == eip191-secp256k1", a.alg === "eip191-secp256k1", `alg=${a.alg}`);
149
- add("agent.statement == nirium-audit-v1:<content_sha256>", a.statement === STATEMENT_PREFIX + doc.content_sha256,
150
- `statement=${a.statement}`);
151
- add("agent.key == payment.from (payer signs)", eqAddr(a.key, p.from), `key=${a.key}`);
152
- let valid = false;
153
- try { valid = await verifyMessage({ address: a.key, message: a.statement, signature: a.signature }); } catch {}
154
- add("EIP-191 signature by agent.key over agent.statement", valid);
155
- }
156
-
157
- return { ok: checks.every((c) => c.ok), checks };
158
- }
15
+ export * from "./verify-evm-core.mjs";
159
16
 
160
17
  async function main() {
161
18
  const args = process.argv.slice(2);