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/LICENSE +0 -0
- package/README.md +77 -55
- package/package.json +81 -75
- package/policy/evm-policy.mjs +367 -367
- package/policy/rules-policy.mjs +35 -35
- package/policy/x402-fetch.mjs +56 -56
- package/sdk/decision.mjs +108 -108
- package/sdk/index.mjs +14 -12
- package/sdk/networks.mjs +28 -28
- package/sdk/pay.mjs +46 -46
- package/sdk/pq.mjs +58 -0
- package/sdk/receipt.mjs +102 -96
- package/sdk/serve.mjs +106 -106
- package/verify-evm-core.mjs +192 -159
- package/verify-evm-pq.mjs +113 -0
- package/verify-evm-receipt.mjs +38 -38
package/policy/rules-policy.mjs
CHANGED
|
@@ -1,35 +1,35 @@
|
|
|
1
|
-
// A small reference policy engine, for demos and tests. Real deployments plug in their own.
|
|
2
|
-
//
|
|
3
|
-
// Rules, checked against what is actually about to be signed (context.authorization):
|
|
4
|
-
// - the token must be in `allowAssets` (if given),
|
|
5
|
-
// - the destination must be in `allowPayTo` (if given),
|
|
6
|
-
// - amount > `maxAmount` gives DENY,
|
|
7
|
-
// - amount > `approvalAbove` (and <= maxAmount) gives WAIT: a person has to approve it,
|
|
8
|
-
// - anything else gives ALLOW, bound to this authorization, valid for `ttlMs`.
|
|
9
|
-
|
|
10
|
-
import { getAddress } from "viem";
|
|
11
|
-
|
|
12
|
-
export function createRulesPolicy({
|
|
13
|
-
maxAmount, approvalAbove, allowPayTo, allowAssets, ttlMs = 30_000, policyVersion = "rules-v1",
|
|
14
|
-
now = Date.now, onDecision,
|
|
15
|
-
} = {}) {
|
|
16
|
-
if (maxAmount === undefined) throw new Error("createRulesPolicy: maxAmount (atomic units) is required");
|
|
17
|
-
const max = BigInt(maxAmount);
|
|
18
|
-
const approval = approvalAbove === undefined ? undefined : BigInt(approvalAbove);
|
|
19
|
-
const payTo = allowPayTo ? new Set(allowPayTo.map((a) => getAddress(a))) : undefined;
|
|
20
|
-
const assets = allowAssets ? new Set(allowAssets.map((a) => getAddress(a))) : undefined;
|
|
21
|
-
|
|
22
|
-
return {
|
|
23
|
-
now,
|
|
24
|
-
onDecision,
|
|
25
|
-
async evaluate(ctx) {
|
|
26
|
-
const a = ctx.authorization;
|
|
27
|
-
const amount = BigInt(a.amount);
|
|
28
|
-
if (assets && !assets.has(getAddress(a.verifyingContract))) return { decision: "DENY", reason: "token not allowed", policyVersion };
|
|
29
|
-
if (payTo && !payTo.has(getAddress(a.to))) return { decision: "DENY", reason: "destination not allowed", policyVersion };
|
|
30
|
-
if (amount > max) return { decision: "DENY", reason: `amount ${amount} above limit ${max}`, policyVersion };
|
|
31
|
-
if (approval !== undefined && amount > approval) return { decision: "WAIT", reason: `amount ${amount} needs approval (above ${approval})`, policyVersion };
|
|
32
|
-
return { decision: "ALLOW", contextHash: ctx.contextHash, expiresAt: now() + ttlMs, policyVersion };
|
|
33
|
-
},
|
|
34
|
-
};
|
|
35
|
-
}
|
|
1
|
+
// A small reference policy engine, for demos and tests. Real deployments plug in their own.
|
|
2
|
+
//
|
|
3
|
+
// Rules, checked against what is actually about to be signed (context.authorization):
|
|
4
|
+
// - the token must be in `allowAssets` (if given),
|
|
5
|
+
// - the destination must be in `allowPayTo` (if given),
|
|
6
|
+
// - amount > `maxAmount` gives DENY,
|
|
7
|
+
// - amount > `approvalAbove` (and <= maxAmount) gives WAIT: a person has to approve it,
|
|
8
|
+
// - anything else gives ALLOW, bound to this authorization, valid for `ttlMs`.
|
|
9
|
+
|
|
10
|
+
import { getAddress } from "viem";
|
|
11
|
+
|
|
12
|
+
export function createRulesPolicy({
|
|
13
|
+
maxAmount, approvalAbove, allowPayTo, allowAssets, ttlMs = 30_000, policyVersion = "rules-v1",
|
|
14
|
+
now = Date.now, onDecision,
|
|
15
|
+
} = {}) {
|
|
16
|
+
if (maxAmount === undefined) throw new Error("createRulesPolicy: maxAmount (atomic units) is required");
|
|
17
|
+
const max = BigInt(maxAmount);
|
|
18
|
+
const approval = approvalAbove === undefined ? undefined : BigInt(approvalAbove);
|
|
19
|
+
const payTo = allowPayTo ? new Set(allowPayTo.map((a) => getAddress(a))) : undefined;
|
|
20
|
+
const assets = allowAssets ? new Set(allowAssets.map((a) => getAddress(a))) : undefined;
|
|
21
|
+
|
|
22
|
+
return {
|
|
23
|
+
now,
|
|
24
|
+
onDecision,
|
|
25
|
+
async evaluate(ctx) {
|
|
26
|
+
const a = ctx.authorization;
|
|
27
|
+
const amount = BigInt(a.amount);
|
|
28
|
+
if (assets && !assets.has(getAddress(a.verifyingContract))) return { decision: "DENY", reason: "token not allowed", policyVersion };
|
|
29
|
+
if (payTo && !payTo.has(getAddress(a.to))) return { decision: "DENY", reason: "destination not allowed", policyVersion };
|
|
30
|
+
if (amount > max) return { decision: "DENY", reason: `amount ${amount} above limit ${max}`, policyVersion };
|
|
31
|
+
if (approval !== undefined && amount > approval) return { decision: "WAIT", reason: `amount ${amount} needs approval (above ${approval})`, policyVersion };
|
|
32
|
+
return { decision: "ALLOW", contextHash: ctx.contextHash, expiresAt: now() + ttlMs, policyVersion };
|
|
33
|
+
},
|
|
34
|
+
};
|
|
35
|
+
}
|
package/policy/x402-fetch.mjs
CHANGED
|
@@ -1,56 +1,56 @@
|
|
|
1
|
-
// fetch() that pays x402 `exact` on an EVM chain only when the policy says ALLOW.
|
|
2
|
-
//
|
|
3
|
-
// One gated signer and one x402 client per call, so two concurrent payments never share
|
|
4
|
-
// state. The selected requirements are captured in onBeforePaymentCreation (that hook runs
|
|
5
|
-
// before the authorization exists) and handed to the gate, which checks them against the
|
|
6
|
-
// typed data it is asked to sign.
|
|
7
|
-
//
|
|
8
|
-
// NEVER register onPaymentCreationFailure here: it can return a payload that did not go
|
|
9
|
-
// through the signer, which would bypass the gate.
|
|
10
|
-
|
|
11
|
-
import { wrapFetchWithPayment, x402Client } from "@x402/fetch";
|
|
12
|
-
import { ExactEvmScheme } from "@x402/evm/exact/client";
|
|
13
|
-
import { createPolicyGatedSigner, X402PolicyError } from "./evm-policy.mjs";
|
|
14
|
-
|
|
15
|
-
/**
|
|
16
|
-
* @param {object} cfg
|
|
17
|
-
* @param {{address: string, signTypedData: Function, readContract?: Function}} cfg.signer e.g. a viem account
|
|
18
|
-
* @param {object} cfg.policy X402PolicyHook (see evm-policy.mjs)
|
|
19
|
-
* @param {string} cfg.network "eip155:43113" or "eip155:43114"
|
|
20
|
-
* @param {string} cfg.asset USDC contract on that network
|
|
21
|
-
* @param {string} cfg.maxAmountPerPayment atomic units cap; also allows a non-default asset in @x402/core
|
|
22
|
-
* @param {typeof fetch} [cfg.fetch]
|
|
23
|
-
*/
|
|
24
|
-
export function createPolicyX402Fetch(cfg) {
|
|
25
|
-
const { signer, policy, network, asset, maxAmountPerPayment } = cfg;
|
|
26
|
-
const baseFetch = cfg.fetch ?? globalThis.fetch;
|
|
27
|
-
if (!/^eip155:\d+$/.test(String(network))) throw new Error("createPolicyX402Fetch: network must be eip155:<chainId>");
|
|
28
|
-
if (!asset || !maxAmountPerPayment) throw new Error("createPolicyX402Fetch: asset and maxAmountPerPayment are required");
|
|
29
|
-
|
|
30
|
-
return async function policyFetch(url, init) {
|
|
31
|
-
const slot = { requirements: undefined, error: undefined };
|
|
32
|
-
const method = String(init?.method ?? "GET").toUpperCase();
|
|
33
|
-
const gated = createPolicyGatedSigner(
|
|
34
|
-
signer, policy,
|
|
35
|
-
() => ({ url: String(url), method, requirements: slot.requirements }),
|
|
36
|
-
(err) => { slot.error = err; },
|
|
37
|
-
);
|
|
38
|
-
const client = new x402Client()
|
|
39
|
-
.register(network, new ExactEvmScheme(gated))
|
|
40
|
-
.onBeforePaymentCreation(async ({ selectedRequirements: r }) => {
|
|
41
|
-
slot.requirements = {
|
|
42
|
-
scheme: r.scheme, network: r.network, asset: r.asset, payTo: r.payTo,
|
|
43
|
-
amount: r.amount, maxTimeoutSeconds: r.maxTimeoutSeconds,
|
|
44
|
-
extra: { name: r.extra?.name, version: r.extra?.version },
|
|
45
|
-
};
|
|
46
|
-
});
|
|
47
|
-
client.setSpendControls({ allowedAssets: [{ network, asset, maxAmountPerPayment }] });
|
|
48
|
-
try {
|
|
49
|
-
return await wrapFetchWithPayment(baseFetch, client)(url, init);
|
|
50
|
-
} catch (e) {
|
|
51
|
-
// @x402/fetch re-wraps errors and loses the class: hand back the gate's own error.
|
|
52
|
-
if (slot.error instanceof X402PolicyError) throw slot.error;
|
|
53
|
-
throw e;
|
|
54
|
-
}
|
|
55
|
-
};
|
|
56
|
-
}
|
|
1
|
+
// fetch() that pays x402 `exact` on an EVM chain only when the policy says ALLOW.
|
|
2
|
+
//
|
|
3
|
+
// One gated signer and one x402 client per call, so two concurrent payments never share
|
|
4
|
+
// state. The selected requirements are captured in onBeforePaymentCreation (that hook runs
|
|
5
|
+
// before the authorization exists) and handed to the gate, which checks them against the
|
|
6
|
+
// typed data it is asked to sign.
|
|
7
|
+
//
|
|
8
|
+
// NEVER register onPaymentCreationFailure here: it can return a payload that did not go
|
|
9
|
+
// through the signer, which would bypass the gate.
|
|
10
|
+
|
|
11
|
+
import { wrapFetchWithPayment, x402Client } from "@x402/fetch";
|
|
12
|
+
import { ExactEvmScheme } from "@x402/evm/exact/client";
|
|
13
|
+
import { createPolicyGatedSigner, X402PolicyError } from "./evm-policy.mjs";
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* @param {object} cfg
|
|
17
|
+
* @param {{address: string, signTypedData: Function, readContract?: Function}} cfg.signer e.g. a viem account
|
|
18
|
+
* @param {object} cfg.policy X402PolicyHook (see evm-policy.mjs)
|
|
19
|
+
* @param {string} cfg.network "eip155:43113" or "eip155:43114"
|
|
20
|
+
* @param {string} cfg.asset USDC contract on that network
|
|
21
|
+
* @param {string} cfg.maxAmountPerPayment atomic units cap; also allows a non-default asset in @x402/core
|
|
22
|
+
* @param {typeof fetch} [cfg.fetch]
|
|
23
|
+
*/
|
|
24
|
+
export function createPolicyX402Fetch(cfg) {
|
|
25
|
+
const { signer, policy, network, asset, maxAmountPerPayment } = cfg;
|
|
26
|
+
const baseFetch = cfg.fetch ?? globalThis.fetch;
|
|
27
|
+
if (!/^eip155:\d+$/.test(String(network))) throw new Error("createPolicyX402Fetch: network must be eip155:<chainId>");
|
|
28
|
+
if (!asset || !maxAmountPerPayment) throw new Error("createPolicyX402Fetch: asset and maxAmountPerPayment are required");
|
|
29
|
+
|
|
30
|
+
return async function policyFetch(url, init) {
|
|
31
|
+
const slot = { requirements: undefined, error: undefined };
|
|
32
|
+
const method = String(init?.method ?? "GET").toUpperCase();
|
|
33
|
+
const gated = createPolicyGatedSigner(
|
|
34
|
+
signer, policy,
|
|
35
|
+
() => ({ url: String(url), method, requirements: slot.requirements }),
|
|
36
|
+
(err) => { slot.error = err; },
|
|
37
|
+
);
|
|
38
|
+
const client = new x402Client()
|
|
39
|
+
.register(network, new ExactEvmScheme(gated))
|
|
40
|
+
.onBeforePaymentCreation(async ({ selectedRequirements: r }) => {
|
|
41
|
+
slot.requirements = {
|
|
42
|
+
scheme: r.scheme, network: r.network, asset: r.asset, payTo: r.payTo,
|
|
43
|
+
amount: r.amount, maxTimeoutSeconds: r.maxTimeoutSeconds,
|
|
44
|
+
extra: { name: r.extra?.name, version: r.extra?.version },
|
|
45
|
+
};
|
|
46
|
+
});
|
|
47
|
+
client.setSpendControls({ allowedAssets: [{ network, asset, maxAmountPerPayment }] });
|
|
48
|
+
try {
|
|
49
|
+
return await wrapFetchWithPayment(baseFetch, client)(url, init);
|
|
50
|
+
} catch (e) {
|
|
51
|
+
// @x402/fetch re-wraps errors and loses the class: hand back the gate's own error.
|
|
52
|
+
if (slot.error instanceof X402PolicyError) throw slot.error;
|
|
53
|
+
throw e;
|
|
54
|
+
}
|
|
55
|
+
};
|
|
56
|
+
}
|
package/sdk/decision.mjs
CHANGED
|
@@ -1,108 +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
|
-
}
|
|
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
|
@@ -1,12 +1,14 @@
|
|
|
1
|
-
// nirium-avalanche: Nirium on Avalanche C-Chain and Fuji.
|
|
2
|
-
// pay: createX402Fetch, settlementOf (optional pre-sign policy)
|
|
3
|
-
// charge: x402Serve (Express middleware, PayAI by default)
|
|
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)
|
|
6
|
-
|
|
7
|
-
export {
|
|
8
|
-
export {
|
|
9
|
-
export {
|
|
10
|
-
export {
|
|
11
|
-
export {
|
|
12
|
-
export {
|
|
1
|
+
// nirium-avalanche: Nirium on Avalanche C-Chain and Fuji.
|
|
2
|
+
// pay: createX402Fetch, settlementOf (optional pre-sign policy)
|
|
3
|
+
// charge: x402Serve (Express middleware, PayAI by default)
|
|
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)
|
|
6
|
+
// pq: pqKeygen, registerPqKey, attestPq (optional post-quantum ML-DSA-65 signature on receipts)
|
|
7
|
+
export { createX402Fetch, settlementOf } from "./pay.mjs";
|
|
8
|
+
export { x402Serve } from "./serve.mjs";
|
|
9
|
+
export { bindReceipt, verifyReceipt } from "./receipt.mjs";
|
|
10
|
+
export { pqKeygen, attestPq, registerPqKey, pqKeyId, verifyPqSignature, readPqRegistration, checkPqRegistration, PQ_ALG, PQ_REGISTRY } from "./pq.mjs";
|
|
11
|
+
export { bindDecision, verifyDecision, decisionRecord, collectDecisions, DECISION_VERSION, DECISION_OUTCOMES } from "./decision.mjs";
|
|
12
|
+
export { NETWORKS, USDC_EXTRA, PAYAI_FACILITATOR, getNetwork, dollarsToAtomic } from "./networks.mjs";
|
|
13
|
+
export { createRulesPolicy } from "../policy/rules-policy.mjs";
|
|
14
|
+
export { X402PolicyError } from "../policy/evm-policy.mjs";
|
package/sdk/networks.mjs
CHANGED
|
@@ -1,28 +1,28 @@
|
|
|
1
|
-
// Avalanche networks Nirium supports. USDC addresses from Circle's official list
|
|
2
|
-
// (developers.circle.com/stablecoins/usdc-contract-addresses, checked 25-nov-2026); EIP-712 domain
|
|
3
|
-
// of both contracts: name "USD Coin", version "2" (read from the contracts on 26-nov-2026).
|
|
4
|
-
import { avalanche, avalancheFuji } from "viem/chains";
|
|
5
|
-
|
|
6
|
-
export const NETWORKS = Object.freeze({
|
|
7
|
-
"eip155:43113": { chain: avalancheFuji, usdc: "0x5425890298aed601595a70AB815c96711a31Bc65", explorer: "https://testnet.snowtrace.io/tx/", mainnet: false },
|
|
8
|
-
"eip155:43114": { chain: avalanche, usdc: "0xB97EF9Ef8734C71904D8002F8b6Bc66Dd9c48a6E", explorer: "https://snowtrace.io/tx/", mainnet: true },
|
|
9
|
-
});
|
|
10
|
-
export const USDC_DECIMALS = 6;
|
|
11
|
-
export const USDC_EXTRA = Object.freeze({ name: "USD Coin", version: "2" });
|
|
12
|
-
/** Independent x402 facilitator used by default. Nirium does not run one. */
|
|
13
|
-
export const PAYAI_FACILITATOR = "https://facilitator.payai.network";
|
|
14
|
-
|
|
15
|
-
export function getNetwork(id) {
|
|
16
|
-
const n = NETWORKS[id];
|
|
17
|
-
if (!n) throw new Error(`unsupported network ${id}; use one of ${Object.keys(NETWORKS).join(", ")}`);
|
|
18
|
-
return n;
|
|
19
|
-
}
|
|
20
|
-
|
|
21
|
-
/** "$0.01" or "0.01" -> atomic USDC units as a string. Rejects more than 6 decimals. */
|
|
22
|
-
export function dollarsToAtomic(price) {
|
|
23
|
-
const m = /^\$?(\d+)(?:\.(\d{1,6}))?$/.exec(String(price).trim());
|
|
24
|
-
if (!m) throw new Error(`price "${price}" must look like "$0.01" (at most 6 decimals)`);
|
|
25
|
-
const atomic = BigInt(m[1]) * 1_000_000n + BigInt((m[2] ?? "").padEnd(6, "0") || "0");
|
|
26
|
-
if (atomic <= 0n) throw new Error(`price "${price}" must be above zero`);
|
|
27
|
-
return atomic.toString();
|
|
28
|
-
}
|
|
1
|
+
// Avalanche networks Nirium supports. USDC addresses from Circle's official list
|
|
2
|
+
// (developers.circle.com/stablecoins/usdc-contract-addresses, checked 25-nov-2026); EIP-712 domain
|
|
3
|
+
// of both contracts: name "USD Coin", version "2" (read from the contracts on 26-nov-2026).
|
|
4
|
+
import { avalanche, avalancheFuji } from "viem/chains";
|
|
5
|
+
|
|
6
|
+
export const NETWORKS = Object.freeze({
|
|
7
|
+
"eip155:43113": { chain: avalancheFuji, usdc: "0x5425890298aed601595a70AB815c96711a31Bc65", explorer: "https://testnet.snowtrace.io/tx/", mainnet: false },
|
|
8
|
+
"eip155:43114": { chain: avalanche, usdc: "0xB97EF9Ef8734C71904D8002F8b6Bc66Dd9c48a6E", explorer: "https://snowtrace.io/tx/", mainnet: true },
|
|
9
|
+
});
|
|
10
|
+
export const USDC_DECIMALS = 6;
|
|
11
|
+
export const USDC_EXTRA = Object.freeze({ name: "USD Coin", version: "2" });
|
|
12
|
+
/** Independent x402 facilitator used by default. Nirium does not run one. */
|
|
13
|
+
export const PAYAI_FACILITATOR = "https://facilitator.payai.network";
|
|
14
|
+
|
|
15
|
+
export function getNetwork(id) {
|
|
16
|
+
const n = NETWORKS[id];
|
|
17
|
+
if (!n) throw new Error(`unsupported network ${id}; use one of ${Object.keys(NETWORKS).join(", ")}`);
|
|
18
|
+
return n;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/** "$0.01" or "0.01" -> atomic USDC units as a string. Rejects more than 6 decimals. */
|
|
22
|
+
export function dollarsToAtomic(price) {
|
|
23
|
+
const m = /^\$?(\d+)(?:\.(\d{1,6}))?$/.exec(String(price).trim());
|
|
24
|
+
if (!m) throw new Error(`price "${price}" must look like "$0.01" (at most 6 decimals)`);
|
|
25
|
+
const atomic = BigInt(m[1]) * 1_000_000n + BigInt((m[2] ?? "").padEnd(6, "0") || "0");
|
|
26
|
+
if (atomic <= 0n) throw new Error(`price "${price}" must be above zero`);
|
|
27
|
+
return atomic.toString();
|
|
28
|
+
}
|
package/sdk/pay.mjs
CHANGED
|
@@ -1,46 +1,46 @@
|
|
|
1
|
-
// createX402Fetch(): pay x402 resources on Avalanche with a per-payment cap and, optionally, the
|
|
2
|
-
// pre-sign policy (a payment the policy refuses is never signed). Same idea as initX402 +
|
|
3
|
-
// x402Fetch in the `nirium` package.
|
|
4
|
-
//
|
|
5
|
-
// const pay = createX402Fetch({ signer: account, network: "eip155:43113", maxAmountPerPayment: "10000", policy });
|
|
6
|
-
// const res = await pay("https://seller.example/paid");
|
|
7
|
-
// const settlement = settlementOf(res); // { transaction, network, payer } or undefined
|
|
8
|
-
|
|
9
|
-
import { wrapFetchWithPaymentFromConfig, decodePaymentResponseHeader } from "@x402/fetch";
|
|
10
|
-
import { ExactEvmScheme } from "@x402/evm/exact/client";
|
|
11
|
-
import { createPolicyX402Fetch } from "../policy/x402-fetch.mjs";
|
|
12
|
-
import { getNetwork } from "./networks.mjs";
|
|
13
|
-
|
|
14
|
-
/**
|
|
15
|
-
* @param {object} cfg
|
|
16
|
-
* @param {{address: string, signTypedData: Function}} cfg.signer e.g. a viem account (the payer's own key)
|
|
17
|
-
* @param {"eip155:43113"|"eip155:43114"} [cfg.network] default Fuji
|
|
18
|
-
* @param {string} cfg.maxAmountPerPayment cap in atomic USDC; refuses anything above before signing
|
|
19
|
-
* @param {object} [cfg.policy] X402PolicyHook; when set, nothing is signed without its ALLOW
|
|
20
|
-
* @param {boolean} [cfg.allowMainnet] must be true to pay on eip155:43114
|
|
21
|
-
* @param {typeof fetch} [cfg.fetch]
|
|
22
|
-
*/
|
|
23
|
-
export function createX402Fetch(cfg) {
|
|
24
|
-
const network = cfg.network || "eip155:43113";
|
|
25
|
-
const net = getNetwork(network);
|
|
26
|
-
if (net.mainnet && cfg.allowMainnet !== true) throw new Error("createX402Fetch: refusing mainnet without allowMainnet: true (real funds)");
|
|
27
|
-
if (!/^\d+$/.test(String(cfg.maxAmountPerPayment ?? ""))) throw new Error("createX402Fetch: maxAmountPerPayment (atomic USDC) is required");
|
|
28
|
-
if (cfg.policy) {
|
|
29
|
-
return createPolicyX402Fetch({
|
|
30
|
-
signer: cfg.signer, policy: cfg.policy, network, asset: net.usdc,
|
|
31
|
-
maxAmountPerPayment: String(cfg.maxAmountPerPayment), fetch: cfg.fetch,
|
|
32
|
-
});
|
|
33
|
-
}
|
|
34
|
-
return wrapFetchWithPaymentFromConfig(cfg.fetch ?? globalThis.fetch, {
|
|
35
|
-
schemes: [{ network, client: new ExactEvmScheme(cfg.signer) }],
|
|
36
|
-
spendControls: { allowedAssets: [{ network, asset: net.usdc, maxAmountPerPayment: String(cfg.maxAmountPerPayment) }] },
|
|
37
|
-
});
|
|
38
|
-
}
|
|
39
|
-
|
|
40
|
-
/** Reads the settlement from a paid response, or undefined if nothing was settled. */
|
|
41
|
-
export function settlementOf(response) {
|
|
42
|
-
const h = response?.headers?.get?.("PAYMENT-RESPONSE");
|
|
43
|
-
if (!h) return undefined;
|
|
44
|
-
const s = decodePaymentResponseHeader(h);
|
|
45
|
-
return s?.success ? s : undefined;
|
|
46
|
-
}
|
|
1
|
+
// createX402Fetch(): pay x402 resources on Avalanche with a per-payment cap and, optionally, the
|
|
2
|
+
// pre-sign policy (a payment the policy refuses is never signed). Same idea as initX402 +
|
|
3
|
+
// x402Fetch in the `nirium` package.
|
|
4
|
+
//
|
|
5
|
+
// const pay = createX402Fetch({ signer: account, network: "eip155:43113", maxAmountPerPayment: "10000", policy });
|
|
6
|
+
// const res = await pay("https://seller.example/paid");
|
|
7
|
+
// const settlement = settlementOf(res); // { transaction, network, payer } or undefined
|
|
8
|
+
|
|
9
|
+
import { wrapFetchWithPaymentFromConfig, decodePaymentResponseHeader } from "@x402/fetch";
|
|
10
|
+
import { ExactEvmScheme } from "@x402/evm/exact/client";
|
|
11
|
+
import { createPolicyX402Fetch } from "../policy/x402-fetch.mjs";
|
|
12
|
+
import { getNetwork } from "./networks.mjs";
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* @param {object} cfg
|
|
16
|
+
* @param {{address: string, signTypedData: Function}} cfg.signer e.g. a viem account (the payer's own key)
|
|
17
|
+
* @param {"eip155:43113"|"eip155:43114"} [cfg.network] default Fuji
|
|
18
|
+
* @param {string} cfg.maxAmountPerPayment cap in atomic USDC; refuses anything above before signing
|
|
19
|
+
* @param {object} [cfg.policy] X402PolicyHook; when set, nothing is signed without its ALLOW
|
|
20
|
+
* @param {boolean} [cfg.allowMainnet] must be true to pay on eip155:43114
|
|
21
|
+
* @param {typeof fetch} [cfg.fetch]
|
|
22
|
+
*/
|
|
23
|
+
export function createX402Fetch(cfg) {
|
|
24
|
+
const network = cfg.network || "eip155:43113";
|
|
25
|
+
const net = getNetwork(network);
|
|
26
|
+
if (net.mainnet && cfg.allowMainnet !== true) throw new Error("createX402Fetch: refusing mainnet without allowMainnet: true (real funds)");
|
|
27
|
+
if (!/^\d+$/.test(String(cfg.maxAmountPerPayment ?? ""))) throw new Error("createX402Fetch: maxAmountPerPayment (atomic USDC) is required");
|
|
28
|
+
if (cfg.policy) {
|
|
29
|
+
return createPolicyX402Fetch({
|
|
30
|
+
signer: cfg.signer, policy: cfg.policy, network, asset: net.usdc,
|
|
31
|
+
maxAmountPerPayment: String(cfg.maxAmountPerPayment), fetch: cfg.fetch,
|
|
32
|
+
});
|
|
33
|
+
}
|
|
34
|
+
return wrapFetchWithPaymentFromConfig(cfg.fetch ?? globalThis.fetch, {
|
|
35
|
+
schemes: [{ network, client: new ExactEvmScheme(cfg.signer) }],
|
|
36
|
+
spendControls: { allowedAssets: [{ network, asset: net.usdc, maxAmountPerPayment: String(cfg.maxAmountPerPayment) }] },
|
|
37
|
+
});
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** Reads the settlement from a paid response, or undefined if nothing was settled. */
|
|
41
|
+
export function settlementOf(response) {
|
|
42
|
+
const h = response?.headers?.get?.("PAYMENT-RESPONSE");
|
|
43
|
+
if (!h) return undefined;
|
|
44
|
+
const s = decodePaymentResponseHeader(h);
|
|
45
|
+
return s?.success ? s : undefined;
|
|
46
|
+
}
|