nirium-avalanche 0.0.0-stage → 0.2.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/LICENSE +190 -0
- package/README.md +54 -3
- package/package.json +74 -6
- package/policy/evm-policy.mjs +367 -0
- package/policy/rules-policy.mjs +35 -0
- package/policy/x402-fetch.mjs +56 -0
- package/sdk/index.mjs +10 -0
- package/sdk/networks.mjs +28 -0
- package/sdk/pay.mjs +46 -0
- package/sdk/receipt.mjs +96 -0
- package/sdk/serve.mjs +106 -0
- package/verify-evm-core.mjs +159 -0
- package/verify-evm-receipt.mjs +38 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,190 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
Copyright 2026 Nirium Protocol Contributors
|
|
179
|
+
|
|
180
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
181
|
+
you may not use this file except in compliance with the License.
|
|
182
|
+
You may obtain a copy of the License at
|
|
183
|
+
|
|
184
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
185
|
+
|
|
186
|
+
Unless required by applicable law or agreed to in writing, software
|
|
187
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
188
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
189
|
+
See the License for the specific language governing permissions and
|
|
190
|
+
limitations under the License.
|
package/README.md
CHANGED
|
@@ -1,3 +1,54 @@
|
|
|
1
|
-
#
|
|
2
|
-
|
|
3
|
-
|
|
1
|
+
# nirium-avalanche
|
|
2
|
+
|
|
3
|
+
Pay and charge with x402 on Avalanche, refuse a payment before it is signed, and keep a
|
|
4
|
+
payer-signed receipt bound to the exact USDC `Transfer` log.
|
|
5
|
+
|
|
6
|
+
The chain already shows who paid whom, how much and when. The receipt adds what the chain does
|
|
7
|
+
not keep: which order the payment was for and who declared it. Anyone can check it against
|
|
8
|
+
Avalanche with a public RPC. Part of [Nirium](https://nirium.xyz). Source, tests and the team's
|
|
9
|
+
test payments: [nirium-avalanche](https://github.com/nirium-protocol/nirium-avalanche).
|
|
10
|
+
|
|
11
|
+
```bash
|
|
12
|
+
npm install nirium-avalanche
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
```js
|
|
16
|
+
import { x402Serve, createX402Fetch, settlementOf, bindReceipt, verifyReceipt, createRulesPolicy } from "nirium-avalanche";
|
|
17
|
+
|
|
18
|
+
// Charge for your own API. Runs on your server: Nirium runs nothing in the middle.
|
|
19
|
+
app.use(x402Serve({ payTo: "0x...", network: "eip155:43113", routes: { "GET /data": "$0.01" } }));
|
|
20
|
+
|
|
21
|
+
// Pay, with a policy: a payment it refuses is never signed.
|
|
22
|
+
const pay = createX402Fetch({ signer: account, network: "eip155:43113", maxAmountPerPayment: "10000",
|
|
23
|
+
policy: createRulesPolicy({ maxAmount: "10000" }) });
|
|
24
|
+
const res = await pay("https://seller.example/data", { headers: { "X-Nirium-Ref": "order-42" } });
|
|
25
|
+
|
|
26
|
+
// A payer-signed receipt bound to the transfer, and its check against the chain.
|
|
27
|
+
const receipt = await bindReceipt({ tx: settlementOf(res).transaction, network: "eip155:43113", ref: "order-42", signer: account });
|
|
28
|
+
const { ok } = await verifyReceipt(receipt);
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
`account` is a viem account for the payer's own key. Networks: Avalanche Fuji and C-Chain mainnet (mainnet needs `allowMainnet: true`). `x402Serve` needs `express` (4.22.3+ or 5.3.0+) in your
|
|
32
|
+
app. Settlement is done by PayAI, an independent x402 facilitator.
|
|
33
|
+
|
|
34
|
+
| Import | What it is |
|
|
35
|
+
|---|---|
|
|
36
|
+
| `nirium-avalanche` | `x402Serve`, `createX402Fetch`, `settlementOf`, `bindReceipt`, `verifyReceipt`, `createRulesPolicy` |
|
|
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
|
+
| `nirium-avalanche/policy/rules` | A small reference policy engine: max amount, approval line, allowlists |
|
|
39
|
+
| `nirium-avalanche/receipt` | `bindReceipt` and `verifyReceipt` on their own, without the Express middleware |
|
|
40
|
+
| `nirium-avalanche/verify` | The receipt verifier as a library. No Node-only code, so it runs in Node and in the browser |
|
|
41
|
+
|
|
42
|
+
Check a receipt from the command line:
|
|
43
|
+
|
|
44
|
+
```bash
|
|
45
|
+
npx nirium-verify-evm receipt.json
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
Exit code 0 means valid, 1 means a check failed, 2 means bad input.
|
|
49
|
+
|
|
50
|
+
Receipts are tamper-evident, not tamper-proof, and they do not prove that goods or a service
|
|
51
|
+
were delivered. Non-custodial: every key stays with whoever pays or receives. No external audit
|
|
52
|
+
yet. Report security problems privately: [SECURITY.md](https://github.com/nirium-protocol/nirium-avalanche/blob/main/SECURITY.md).
|
|
53
|
+
|
|
54
|
+
License: Apache-2.0
|
package/package.json
CHANGED
|
@@ -1,6 +1,74 @@
|
|
|
1
|
-
{
|
|
2
|
-
"name": "nirium-avalanche",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
1
|
+
{
|
|
2
|
+
"name": "nirium-avalanche",
|
|
3
|
+
"version": "0.2.0",
|
|
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
|
+
"type": "module",
|
|
6
|
+
"license": "Apache-2.0",
|
|
7
|
+
"repository": {
|
|
8
|
+
"type": "git",
|
|
9
|
+
"url": "git+https://github.com/nirium-protocol/nirium-avalanche.git",
|
|
10
|
+
"directory": "avalanche"
|
|
11
|
+
},
|
|
12
|
+
"homepage": "https://github.com/nirium-protocol/nirium-avalanche#readme",
|
|
13
|
+
"bugs": {
|
|
14
|
+
"url": "https://github.com/nirium-protocol/nirium-avalanche/issues"
|
|
15
|
+
},
|
|
16
|
+
"keywords": [
|
|
17
|
+
"x402",
|
|
18
|
+
"avalanche",
|
|
19
|
+
"usdc",
|
|
20
|
+
"payments",
|
|
21
|
+
"receipts",
|
|
22
|
+
"ai-agents",
|
|
23
|
+
"eip-3009",
|
|
24
|
+
"erc-8004"
|
|
25
|
+
],
|
|
26
|
+
"exports": {
|
|
27
|
+
".": "./sdk/index.mjs",
|
|
28
|
+
"./policy": "./policy/evm-policy.mjs",
|
|
29
|
+
"./policy/x402-fetch": "./policy/x402-fetch.mjs",
|
|
30
|
+
"./policy/rules": "./policy/rules-policy.mjs",
|
|
31
|
+
"./receipt": "./sdk/receipt.mjs",
|
|
32
|
+
"./verify": "./verify-evm-core.mjs",
|
|
33
|
+
"./package.json": "./package.json"
|
|
34
|
+
},
|
|
35
|
+
"bin": {
|
|
36
|
+
"nirium-verify-evm": "verify-evm-receipt.mjs"
|
|
37
|
+
},
|
|
38
|
+
"files": [
|
|
39
|
+
"sdk/*.mjs",
|
|
40
|
+
"policy/evm-policy.mjs",
|
|
41
|
+
"policy/x402-fetch.mjs",
|
|
42
|
+
"policy/rules-policy.mjs",
|
|
43
|
+
"verify-evm-core.mjs",
|
|
44
|
+
"verify-evm-receipt.mjs"
|
|
45
|
+
],
|
|
46
|
+
"scripts": {
|
|
47
|
+
"test": "node --test test/*.test.mjs policy/test/*.test.mjs sdk/test/*.test.mjs",
|
|
48
|
+
"test:verify": "node --test test/*.test.mjs",
|
|
49
|
+
"test:policy": "node --test policy/test/*.test.mjs",
|
|
50
|
+
"test:sdk": "node --test sdk/test/*.test.mjs",
|
|
51
|
+
"test:live": "bash run-tests.sh"
|
|
52
|
+
},
|
|
53
|
+
"engines": {
|
|
54
|
+
"node": ">=20"
|
|
55
|
+
},
|
|
56
|
+
"dependencies": {
|
|
57
|
+
"viem": "2.58.7",
|
|
58
|
+
"@x402/core": "2.32.0",
|
|
59
|
+
"@x402/evm": "2.32.0",
|
|
60
|
+
"@x402/express": "2.32.0",
|
|
61
|
+
"@x402/fetch": "2.32.0"
|
|
62
|
+
},
|
|
63
|
+
"peerDependencies": {
|
|
64
|
+
"express": "^4.22.3 || ^5.3.0"
|
|
65
|
+
},
|
|
66
|
+
"peerDependenciesMeta": {
|
|
67
|
+
"express": {
|
|
68
|
+
"optional": true
|
|
69
|
+
}
|
|
70
|
+
},
|
|
71
|
+
"devDependencies": {
|
|
72
|
+
"express": "5.3.0"
|
|
73
|
+
}
|
|
74
|
+
}
|
|
@@ -0,0 +1,367 @@
|
|
|
1
|
+
// Pre-sign policy gate for x402 `exact` payments on EVM chains (Avalanche C-Chain and Fuji).
|
|
2
|
+
//
|
|
3
|
+
// Same contract as the Stellar gate in the `nirium` SDK (x402-policy.ts): the policy engine
|
|
4
|
+
// is asked AFTER the exact authorization is built and BEFORE anything is signed, and only an
|
|
5
|
+
// ALLOW bound to that exact authorization, still valid, reaches the signer. DENY, WAIT, an
|
|
6
|
+
// error, a timeout, a malformed or stale answer, or a bad clock sign nothing.
|
|
7
|
+
//
|
|
8
|
+
// Where it hooks in: @x402/evm 2.32.0 builds the EIP-3009 `TransferWithAuthorization`
|
|
9
|
+
// message inside createPaymentPayload and hands it to `signer.signTypedData`. That call is
|
|
10
|
+
// the only place where amount, destination, token, chain and nonce all exist together, so
|
|
11
|
+
// the gate wraps it. Any other typed data (Permit2, EIP-2612 Permit, anything else) is
|
|
12
|
+
// refused before the policy is consulted: this gate only knows how to read EIP-3009.
|
|
13
|
+
//
|
|
14
|
+
// Not a security boundary against code in the same process: whoever holds the base signer
|
|
15
|
+
// can still call it directly.
|
|
16
|
+
|
|
17
|
+
import { getAddress, hashTypedData, isAddress, sha256, stringToBytes } from "viem";
|
|
18
|
+
|
|
19
|
+
const DEFAULT_TIMEOUT_MS = 5000;
|
|
20
|
+
const HEX32 = /^0x[0-9a-fA-F]{64}$/;
|
|
21
|
+
const SIG65 = /^0x[0-9a-fA-F]{130}$/;
|
|
22
|
+
|
|
23
|
+
// The exact EIP-3009 type @x402/evm signs (field order matters for the EIP-712 hash).
|
|
24
|
+
const TRANSFER_WITH_AUTHORIZATION = [
|
|
25
|
+
{ name: "from", type: "address" },
|
|
26
|
+
{ name: "to", type: "address" },
|
|
27
|
+
{ name: "value", type: "uint256" },
|
|
28
|
+
{ name: "validAfter", type: "uint256" },
|
|
29
|
+
{ name: "validBefore", type: "uint256" },
|
|
30
|
+
{ name: "nonce", type: "bytes32" },
|
|
31
|
+
];
|
|
32
|
+
|
|
33
|
+
/** @typedef {'ALLOW'|'DENY'|'WAIT'} X402PolicyVerdict */
|
|
34
|
+
/**
|
|
35
|
+
* @typedef {Object} X402PaymentRequirementsView
|
|
36
|
+
* @property {string} scheme
|
|
37
|
+
* @property {string} network CAIP-2, e.g. "eip155:43113"
|
|
38
|
+
* @property {string} asset ERC-20 contract (EIP-3009 token)
|
|
39
|
+
* @property {string} payTo
|
|
40
|
+
* @property {string} amount atomic units, decimal string
|
|
41
|
+
* @property {number} maxTimeoutSeconds
|
|
42
|
+
* @property {{name?: string, version?: string}} [extra] EIP-712 domain the server asked for
|
|
43
|
+
*/
|
|
44
|
+
/**
|
|
45
|
+
* @typedef {Object} X402PolicyDecision
|
|
46
|
+
* @property {X402PolicyVerdict} decision
|
|
47
|
+
* @property {string} [contextHash] required on ALLOW, must equal the context's
|
|
48
|
+
* @property {string} [reason]
|
|
49
|
+
* @property {string} [policyVersion] required on ALLOW when `currentVersion` is set
|
|
50
|
+
* @property {number} [expiresAt] epoch ms; equality counts as expired
|
|
51
|
+
* @property {string} [decisionId]
|
|
52
|
+
*/
|
|
53
|
+
/**
|
|
54
|
+
* @typedef {Object} X402PolicyHook
|
|
55
|
+
* @property {(ctx: object, opts: {signal: AbortSignal}) => Promise<X402PolicyDecision>} evaluate
|
|
56
|
+
* @property {(ctx: object, opts: {signal: AbortSignal}) => Promise<string>} [currentVersion]
|
|
57
|
+
* @property {number} [timeoutMs] default 5000, never more than half of maxTimeoutSeconds
|
|
58
|
+
* @property {boolean} [requireExpiry] an ALLOW without expiresAt is unsignable
|
|
59
|
+
* @property {(record: object) => void} [onDecision] observer; cannot change the outcome
|
|
60
|
+
* @property {() => number} [now] injectable clock (epoch ms), for tests
|
|
61
|
+
*/
|
|
62
|
+
|
|
63
|
+
/** Outcomes that mean no signature was released. */
|
|
64
|
+
export const REFUSALS = Object.freeze([
|
|
65
|
+
"SIGNER_ERROR", "DENY", "WAIT", "TIMEOUT", "ENGINE_ERROR", "EXPIRED", "UNBOUND", "MALFORMED",
|
|
66
|
+
"CONTEXT_MISMATCH", "STALE", "VERSION_UNAVAILABLE", "SIGNER_CHANGED", "CLOCK_INVALID",
|
|
67
|
+
]);
|
|
68
|
+
|
|
69
|
+
export class X402PolicyError extends Error {
|
|
70
|
+
constructor(outcome, message, extra = {}) {
|
|
71
|
+
super(`x402 policy ${outcome}: ${message}`);
|
|
72
|
+
this.name = "X402PolicyError";
|
|
73
|
+
this.outcome = outcome;
|
|
74
|
+
this.decision = extra.decision;
|
|
75
|
+
this.contextHash = extra.contextHash;
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
const sha256hex = (s) => sha256(stringToBytes(s)).slice(2);
|
|
80
|
+
const nonempty = (v) => typeof v === "string" && v.trim().length > 0;
|
|
81
|
+
|
|
82
|
+
/** Validates a policy hook when it is configured, so bad config fails before any payment. */
|
|
83
|
+
export function assertValidPolicyHook(policy) {
|
|
84
|
+
if (!policy || typeof policy !== "object" || typeof policy.evaluate !== "function") {
|
|
85
|
+
throw new Error("policy: `evaluate` must be a function.");
|
|
86
|
+
}
|
|
87
|
+
if (policy.currentVersion !== undefined && typeof policy.currentVersion !== "function") {
|
|
88
|
+
throw new Error("policy: `currentVersion`, when set, must be a function.");
|
|
89
|
+
}
|
|
90
|
+
if (policy.timeoutMs !== undefined && (!Number.isSafeInteger(policy.timeoutMs) || policy.timeoutMs <= 0)) {
|
|
91
|
+
throw new Error("policy: `timeoutMs` must be a positive integer (ms).");
|
|
92
|
+
}
|
|
93
|
+
if (policy.now !== undefined && typeof policy.now !== "function") {
|
|
94
|
+
throw new Error("policy: `now`, when set, must be a function returning epoch milliseconds.");
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
function chainIdOf(network) {
|
|
99
|
+
const m = /^eip155:(\d+)$/.exec(String(network));
|
|
100
|
+
if (!m) throw new X402PolicyError("CONTEXT_MISMATCH", `not an EVM network: ${network}`);
|
|
101
|
+
return BigInt(m[1]);
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
function toBigInt(v, field) {
|
|
105
|
+
try {
|
|
106
|
+
if (typeof v === "bigint") return v;
|
|
107
|
+
if (typeof v === "number" && Number.isSafeInteger(v)) return BigInt(v);
|
|
108
|
+
if (typeof v === "string" && /^(0x[0-9a-fA-F]+|\d+)$/.test(v)) return BigInt(v);
|
|
109
|
+
} catch { /* falls through */ }
|
|
110
|
+
throw new X402PolicyError("CONTEXT_MISMATCH", `${field} is not an integer`);
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
function sameAddress(a, b) {
|
|
114
|
+
return isAddress(String(a)) && isAddress(String(b)) && getAddress(a) === getAddress(b);
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/**
|
|
118
|
+
* Decodes the typed data about to be signed and checks it describes exactly the payment x402
|
|
119
|
+
* selected. This is not policy (that belongs to the engine): it is context integrity, so that
|
|
120
|
+
* what the engine evaluates is what gets signed.
|
|
121
|
+
*/
|
|
122
|
+
export function describeAuthorization(typedData, requirements, signerAddress) {
|
|
123
|
+
if (!typedData || typeof typedData !== "object") {
|
|
124
|
+
throw new X402PolicyError("CONTEXT_MISMATCH", "no typed data to sign");
|
|
125
|
+
}
|
|
126
|
+
const { domain, types, primaryType, message } = typedData;
|
|
127
|
+
if (primaryType !== "TransferWithAuthorization") {
|
|
128
|
+
throw new X402PolicyError("CONTEXT_MISMATCH", `unsupported primaryType ${String(primaryType)} (only EIP-3009 TransferWithAuthorization is gated)`);
|
|
129
|
+
}
|
|
130
|
+
if (!types || typeof types !== "object") throw new X402PolicyError("CONTEXT_MISMATCH", "typed data has no types");
|
|
131
|
+
const extraTypes = Object.keys(types).filter((k) => k !== "EIP712Domain" && k !== "TransferWithAuthorization");
|
|
132
|
+
if (extraTypes.length) throw new X402PolicyError("CONTEXT_MISMATCH", `unexpected extra types: ${extraTypes.join(", ")}`);
|
|
133
|
+
const fields = types.TransferWithAuthorization;
|
|
134
|
+
const sameFields = Array.isArray(fields) && fields.length === TRANSFER_WITH_AUTHORIZATION.length
|
|
135
|
+
&& fields.every((f, i) => f && f.name === TRANSFER_WITH_AUTHORIZATION[i].name && f.type === TRANSFER_WITH_AUTHORIZATION[i].type);
|
|
136
|
+
if (!sameFields) throw new X402PolicyError("CONTEXT_MISMATCH", "TransferWithAuthorization fields differ from EIP-3009");
|
|
137
|
+
if (!domain || typeof domain !== "object" || !message || typeof message !== "object") {
|
|
138
|
+
throw new X402PolicyError("CONTEXT_MISMATCH", "typed data has no domain or message");
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
const chainId = chainIdOf(requirements.network);
|
|
142
|
+
if (toBigInt(domain.chainId, "domain.chainId") !== chainId) {
|
|
143
|
+
throw new X402PolicyError("CONTEXT_MISMATCH", "domain.chainId differs from requirements.network");
|
|
144
|
+
}
|
|
145
|
+
if (!sameAddress(domain.verifyingContract, requirements.asset)) {
|
|
146
|
+
throw new X402PolicyError("CONTEXT_MISMATCH", "token contract differs from requirements.asset");
|
|
147
|
+
}
|
|
148
|
+
const extra = requirements.extra || {};
|
|
149
|
+
if (!nonempty(extra.name) || !nonempty(extra.version)) {
|
|
150
|
+
throw new X402PolicyError("CONTEXT_MISMATCH", "requirements.extra has no EIP-712 name/version");
|
|
151
|
+
}
|
|
152
|
+
if (domain.name !== extra.name || domain.version !== extra.version) {
|
|
153
|
+
throw new X402PolicyError("CONTEXT_MISMATCH", "EIP-712 domain name/version differ from requirements.extra");
|
|
154
|
+
}
|
|
155
|
+
if (!sameAddress(message.to, requirements.payTo)) {
|
|
156
|
+
throw new X402PolicyError("CONTEXT_MISMATCH", "destination differs from requirements.payTo");
|
|
157
|
+
}
|
|
158
|
+
const value = toBigInt(message.value, "value");
|
|
159
|
+
if (value !== toBigInt(requirements.amount, "requirements.amount")) {
|
|
160
|
+
throw new X402PolicyError("CONTEXT_MISMATCH", "amount differs from requirements.amount");
|
|
161
|
+
}
|
|
162
|
+
if (!sameAddress(message.from, signerAddress)) {
|
|
163
|
+
throw new X402PolicyError("CONTEXT_MISMATCH", "from differs from signer address");
|
|
164
|
+
}
|
|
165
|
+
if (typeof message.nonce !== "string" || !HEX32.test(message.nonce)) {
|
|
166
|
+
throw new X402PolicyError("CONTEXT_MISMATCH", "nonce is not bytes32");
|
|
167
|
+
}
|
|
168
|
+
const validAfter = toBigInt(message.validAfter, "validAfter");
|
|
169
|
+
const validBefore = toBigInt(message.validBefore, "validBefore");
|
|
170
|
+
|
|
171
|
+
let payloadHash;
|
|
172
|
+
try {
|
|
173
|
+
payloadHash = hashTypedData({ domain, types, primaryType, message }).slice(2).toLowerCase();
|
|
174
|
+
} catch (e) {
|
|
175
|
+
throw new X402PolicyError("CONTEXT_MISMATCH", `typed data does not hash (${e?.shortMessage ?? e?.message})`);
|
|
176
|
+
}
|
|
177
|
+
return Object.freeze({
|
|
178
|
+
primaryType,
|
|
179
|
+
payloadHash,
|
|
180
|
+
chainId: chainId.toString(),
|
|
181
|
+
verifyingContract: getAddress(domain.verifyingContract),
|
|
182
|
+
domainName: domain.name,
|
|
183
|
+
domainVersion: domain.version,
|
|
184
|
+
from: getAddress(message.from),
|
|
185
|
+
to: getAddress(message.to),
|
|
186
|
+
amount: value.toString(),
|
|
187
|
+
validAfter: validAfter.toString(),
|
|
188
|
+
validBefore: validBefore.toString(),
|
|
189
|
+
nonce: message.nonce.toLowerCase(),
|
|
190
|
+
});
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
/** min(timeoutMs ?? 5000, maxTimeoutSeconds * 1000 / 2): a slow engine must not eat the payment window. */
|
|
194
|
+
export function effectiveTimeoutMs(policy, maxTimeoutSeconds) {
|
|
195
|
+
const base = policy.timeoutMs ?? DEFAULT_TIMEOUT_MS;
|
|
196
|
+
if (typeof maxTimeoutSeconds === "number" && Number.isFinite(maxTimeoutSeconds) && maxTimeoutSeconds > 0) {
|
|
197
|
+
return Math.max(1, Math.min(base, Math.floor((maxTimeoutSeconds * 1000) / 2)));
|
|
198
|
+
}
|
|
199
|
+
return base;
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
/** sha256 of {v, url, method, payloadHash}: the value an ALLOW must echo back. */
|
|
203
|
+
export function computeContextHash(url, method, payloadHash) {
|
|
204
|
+
return sha256hex(JSON.stringify({ v: 1, url, method, payloadHash }));
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
/**
|
|
208
|
+
* Wraps an EVM signer ({ address, signTypedData }) so it only signs with a current ALLOW bound
|
|
209
|
+
* to this exact authorization. Anything else ends without a signature.
|
|
210
|
+
*
|
|
211
|
+
* `getCall` supplies the per-call context (URL, method, requirements): create one gated signer
|
|
212
|
+
* per payment so two concurrent payments never share state. `onRefused` receives the error
|
|
213
|
+
* before it is thrown, because @x402/fetch re-wraps errors and loses their class.
|
|
214
|
+
*/
|
|
215
|
+
export function createPolicyGatedSigner(base, policy, getCall, onRefused) {
|
|
216
|
+
assertValidPolicyHook(policy);
|
|
217
|
+
if (!base || typeof base.signTypedData !== "function" || !isAddress(String(base.address))) {
|
|
218
|
+
throw new Error("createPolicyGatedSigner: base signer needs an address and signTypedData().");
|
|
219
|
+
}
|
|
220
|
+
// Identity is fixed here. If the base signer changes address mid-payment, nothing is signed.
|
|
221
|
+
const account = getAddress(base.address);
|
|
222
|
+
const now = policy.now ?? Date.now;
|
|
223
|
+
|
|
224
|
+
const report = (r) => {
|
|
225
|
+
try {
|
|
226
|
+
const out = policy.onDecision?.(r);
|
|
227
|
+
if (out !== null && (typeof out === "object" || typeof out === "function")) {
|
|
228
|
+
Promise.resolve(out).catch(() => { /* an observer decides nothing */ });
|
|
229
|
+
}
|
|
230
|
+
} catch { /* an observer decides nothing */ }
|
|
231
|
+
};
|
|
232
|
+
const refuse = (outcome, msg, context, decision) => {
|
|
233
|
+
report({ outcome, context, decision, error: msg });
|
|
234
|
+
const err = new X402PolicyError(outcome, msg, { decision, contextHash: context?.contextHash });
|
|
235
|
+
try { onRefused?.(err); } catch { /* idem */ }
|
|
236
|
+
throw err;
|
|
237
|
+
};
|
|
238
|
+
// A clock that does not return a finite number closes: NaN makes every comparison false.
|
|
239
|
+
const readClock = (context, decision) => {
|
|
240
|
+
let t;
|
|
241
|
+
try { t = now(); } catch (e) {
|
|
242
|
+
return refuse("CLOCK_INVALID", `clock threw (${e?.message ?? String(e)})`, context, decision);
|
|
243
|
+
}
|
|
244
|
+
if (typeof t !== "number" || !Number.isFinite(t)) {
|
|
245
|
+
return refuse("CLOCK_INVALID", `clock returned ${String(t)}, not epoch milliseconds`, context, decision);
|
|
246
|
+
}
|
|
247
|
+
return t;
|
|
248
|
+
};
|
|
249
|
+
|
|
250
|
+
const signTypedData = async (typedData) => {
|
|
251
|
+
const call = getCall();
|
|
252
|
+
if (!call || !call.requirements) refuse("CONTEXT_MISMATCH", "no payment requirements bound to this signing call");
|
|
253
|
+
if (!sameAddress(base.address, account)) refuse("SIGNER_CHANGED", "base signer address changed after the gate was created");
|
|
254
|
+
|
|
255
|
+
let authorization;
|
|
256
|
+
try {
|
|
257
|
+
authorization = describeAuthorization(typedData, call.requirements, account);
|
|
258
|
+
} catch (e) {
|
|
259
|
+
return refuse(e instanceof X402PolicyError ? e.outcome : "CONTEXT_MISMATCH", e?.message ?? String(e));
|
|
260
|
+
}
|
|
261
|
+
const contextHash = computeContextHash(call.url, call.method, authorization.payloadHash);
|
|
262
|
+
// Frozen: the engine reads, it does not rewrite what gets signed.
|
|
263
|
+
const context = Object.freeze({
|
|
264
|
+
contextVersion: 1,
|
|
265
|
+
url: call.url,
|
|
266
|
+
method: call.method,
|
|
267
|
+
requirements: Object.freeze({ ...call.requirements, extra: Object.freeze({ ...(call.requirements.extra || {}) }) }),
|
|
268
|
+
authorization,
|
|
269
|
+
signer: account,
|
|
270
|
+
contextHash,
|
|
271
|
+
});
|
|
272
|
+
|
|
273
|
+
const timeoutMs = effectiveTimeoutMs(policy, call.requirements.maxTimeoutSeconds);
|
|
274
|
+
const controller = new AbortController();
|
|
275
|
+
// One deadline for the whole pre-sign phase (evaluate + currentVersion).
|
|
276
|
+
const deadline = readClock(context) + timeoutMs;
|
|
277
|
+
let timer;
|
|
278
|
+
const TIMED_OUT = Symbol("timeout");
|
|
279
|
+
const timeout = new Promise((_, reject) => {
|
|
280
|
+
timer = setTimeout(() => { controller.abort(); reject(TIMED_OUT); }, timeoutMs);
|
|
281
|
+
});
|
|
282
|
+
timeout.catch(() => { /* observed by each race */ });
|
|
283
|
+
|
|
284
|
+
try {
|
|
285
|
+
let decision;
|
|
286
|
+
try {
|
|
287
|
+
decision = await Promise.race([
|
|
288
|
+
Promise.resolve().then(() => policy.evaluate(context, { signal: controller.signal })),
|
|
289
|
+
timeout,
|
|
290
|
+
]);
|
|
291
|
+
} catch (e) {
|
|
292
|
+
if (e === TIMED_OUT) return refuse("TIMEOUT", `no decision within ${timeoutMs} ms`, context);
|
|
293
|
+
return refuse("ENGINE_ERROR", e?.message ?? String(e), context);
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
// Anything that is not a well-formed ALLOW closes.
|
|
297
|
+
if (!decision || typeof decision !== "object") return refuse("MALFORMED", "engine returned no decision object", context);
|
|
298
|
+
if (decision.decision === "DENY") return refuse("DENY", decision.reason ?? "denied", context, decision);
|
|
299
|
+
if (decision.decision === "WAIT") return refuse("WAIT", decision.reason ?? "wait", context, decision);
|
|
300
|
+
if (decision.decision !== "ALLOW") return refuse("MALFORMED", `unknown verdict ${String(decision.decision)}`, context, decision);
|
|
301
|
+
// Copied before any await: mutating the engine's object later changes nothing.
|
|
302
|
+
const allow = Object.freeze({ ...decision });
|
|
303
|
+
if (allow.contextHash !== contextHash) return refuse("UNBOUND", "ALLOW is not bound to this authorization", context, allow);
|
|
304
|
+
if (allow.expiresAt !== undefined && (typeof allow.expiresAt !== "number" || !Number.isFinite(allow.expiresAt))) {
|
|
305
|
+
return refuse("MALFORMED", "expiresAt must be epoch milliseconds", context, allow);
|
|
306
|
+
}
|
|
307
|
+
if (allow.expiresAt === undefined && policy.requireExpiry) {
|
|
308
|
+
return refuse("EXPIRED", "ALLOW without expiresAt while requireExpiry is set", context, allow);
|
|
309
|
+
}
|
|
310
|
+
const checkClock = () => {
|
|
311
|
+
const t = readClock(context, allow);
|
|
312
|
+
if (t >= deadline) refuse("TIMEOUT", "decision arrived after the deadline", context, allow);
|
|
313
|
+
if (allow.expiresAt !== undefined && t >= allow.expiresAt) refuse("EXPIRED", "ALLOW expired before signing", context, allow);
|
|
314
|
+
};
|
|
315
|
+
if (policy.currentVersion && !nonempty(allow.policyVersion)) {
|
|
316
|
+
return refuse("MALFORMED", "ALLOW has no policyVersion to check against currentVersion", context, allow);
|
|
317
|
+
}
|
|
318
|
+
checkClock();
|
|
319
|
+
|
|
320
|
+
// The observer runs HERE, not next to the signer: whatever it changes (the clock, the
|
|
321
|
+
// policy version, the signer's address) is seen by the checks that follow.
|
|
322
|
+
report({ outcome: "ALLOWED", context, decision: allow });
|
|
323
|
+
|
|
324
|
+
if (policy.currentVersion) {
|
|
325
|
+
let current;
|
|
326
|
+
try {
|
|
327
|
+
current = await Promise.race([
|
|
328
|
+
Promise.resolve().then(() => policy.currentVersion(context, { signal: controller.signal })),
|
|
329
|
+
timeout,
|
|
330
|
+
]);
|
|
331
|
+
} catch (e) {
|
|
332
|
+
if (e === TIMED_OUT) return refuse("TIMEOUT", `no current policy version within ${timeoutMs} ms`, context, allow);
|
|
333
|
+
return refuse("VERSION_UNAVAILABLE", `currentVersion failed (${e?.message ?? String(e)})`, context, allow);
|
|
334
|
+
}
|
|
335
|
+
if (!nonempty(current)) return refuse("VERSION_UNAVAILABLE", "currentVersion returned no version", context, allow);
|
|
336
|
+
if (current !== allow.policyVersion) {
|
|
337
|
+
return refuse("STALE", `ALLOW was issued under policy ${allow.policyVersion}, current is ${current}`, context, allow);
|
|
338
|
+
}
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
// Final checks, always, with no await before the signer.
|
|
342
|
+
checkClock();
|
|
343
|
+
if (!sameAddress(base.address, account)) return refuse("SIGNER_CHANGED", "base signer address changed while the policy was evaluated", context, allow);
|
|
344
|
+
if (timer) clearTimeout(timer);
|
|
345
|
+
let signature;
|
|
346
|
+
try {
|
|
347
|
+
// The original object, not a copy someone could have touched.
|
|
348
|
+
signature = await base.signTypedData(typedData);
|
|
349
|
+
} catch (e) {
|
|
350
|
+
report({ outcome: "SIGNER_ERROR", context, decision: allow, error: e?.message ?? String(e) });
|
|
351
|
+
throw e;
|
|
352
|
+
}
|
|
353
|
+
if (typeof signature !== "string" || !SIG65.test(signature)) {
|
|
354
|
+
return refuse("SIGNER_ERROR", "signer returned no 65-byte signature", context, allow);
|
|
355
|
+
}
|
|
356
|
+
report({ outcome: "SIGNED", context, decision: allow });
|
|
357
|
+
return signature;
|
|
358
|
+
} finally {
|
|
359
|
+
if (timer) clearTimeout(timer);
|
|
360
|
+
}
|
|
361
|
+
};
|
|
362
|
+
|
|
363
|
+
// Read-only chain access may be forwarded; no other signing method is exposed.
|
|
364
|
+
const gated = { address: account, signTypedData };
|
|
365
|
+
if (typeof base.readContract === "function") gated.readContract = (args) => base.readContract(args);
|
|
366
|
+
return Object.freeze(gated);
|
|
367
|
+
}
|
|
@@ -0,0 +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
|
+
}
|
|
@@ -0,0 +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
|
+
}
|
package/sdk/index.mjs
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
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
|
+
export { createX402Fetch, settlementOf } from "./pay.mjs";
|
|
6
|
+
export { x402Serve } from "./serve.mjs";
|
|
7
|
+
export { bindReceipt, verifyReceipt } from "./receipt.mjs";
|
|
8
|
+
export { NETWORKS, USDC_EXTRA, PAYAI_FACILITATOR, getNetwork, dollarsToAtomic } from "./networks.mjs";
|
|
9
|
+
export { createRulesPolicy } from "../policy/rules-policy.mjs";
|
|
10
|
+
export { X402PolicyError } from "../policy/evm-policy.mjs";
|
package/sdk/networks.mjs
ADDED
|
@@ -0,0 +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
|
+
}
|
package/sdk/pay.mjs
ADDED
|
@@ -0,0 +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
|
+
}
|
package/sdk/receipt.mjs
ADDED
|
@@ -0,0 +1,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
|
+
|
|
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
|
+
}
|
package/sdk/serve.mjs
ADDED
|
@@ -0,0 +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
|
+
}
|
|
@@ -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
|
+
}
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// verify-evm-receipt.mjs - command line for the EVM receipt verifier.
|
|
3
|
+
//
|
|
4
|
+
// Usage:
|
|
5
|
+
// node verify-evm-receipt.mjs <binding.json> [--no-sig] [--rpc <url>] [--json]
|
|
6
|
+
//
|
|
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.
|
|
10
|
+
|
|
11
|
+
import { readFileSync, realpathSync } from "node:fs";
|
|
12
|
+
import { fileURLToPath } from "node:url";
|
|
13
|
+
import { verifyBinding } from "./verify-evm-core.mjs";
|
|
14
|
+
|
|
15
|
+
export * from "./verify-evm-core.mjs";
|
|
16
|
+
|
|
17
|
+
async function main() {
|
|
18
|
+
const args = process.argv.slice(2);
|
|
19
|
+
const rpcIdx = args.indexOf("--rpc");
|
|
20
|
+
const file = args.find((a, i) => !a.startsWith("--") && (rpcIdx < 0 || i !== rpcIdx + 1));
|
|
21
|
+
if (!file) { console.error("usage: node verify-evm-receipt.mjs <binding.json> [--no-sig] [--rpc url] [--json]"); process.exit(2); }
|
|
22
|
+
const opts = { requireSig: !args.includes("--no-sig"), rpc: rpcIdx >= 0 ? args[rpcIdx + 1] : undefined };
|
|
23
|
+
let doc;
|
|
24
|
+
try { doc = JSON.parse(readFileSync(file, "utf8")); } catch (e) { console.error(`bad binding file: ${e.message}`); process.exit(2); }
|
|
25
|
+
let res;
|
|
26
|
+
try { res = await verifyBinding(doc, opts); } catch (e) { console.error(`bad input: ${e.message}`); process.exit(2); }
|
|
27
|
+
if (args.includes("--json")) console.log(JSON.stringify(res, null, 2));
|
|
28
|
+
else {
|
|
29
|
+
for (const c of res.checks) console.log(`${c.ok ? "PASS" : "FAIL"} ${c.name}${c.detail ? " [" + c.detail + "]" : ""}`);
|
|
30
|
+
console.log(res.ok ? "RESULT: VALID" : "RESULT: INVALID");
|
|
31
|
+
}
|
|
32
|
+
process.exit(res.ok ? 0 : 1);
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
// Run main() when executed directly, including through the npm bin symlink: compare real paths,
|
|
36
|
+
// or a symlinked call would skip main() and exit 0 without checking anything.
|
|
37
|
+
const invokedPath = (() => { try { return realpathSync(process.argv[1]); } catch { return undefined; } })();
|
|
38
|
+
if (invokedPath && realpathSync(fileURLToPath(import.meta.url)) === invokedPath) main();
|