From e86473ec6923fdf08af0bfb1f3da6ee683b5cc23 Mon Sep 17 00:00:00 2001 From: Giovanny Amador <219895655+Eras256@users.noreply.github.com> Date: Tue, 1 Dec 2026 15:29:35 -0600 Subject: [PATCH 1/2] feat: Nirium on Base - verifier, policy, pay/charge library, market Ported from the nirium-avalanche EVM code with Base networks and USDC domains. Selftests on 1 Dec 2026 (team funds, not usage): Base Sepolia 0xa89dde53 and Base mainnet 0xaa086c5e, each with a payer-signed receipt that verifies 18/18. Verifier fixtures: 10/10. Co-Authored-By: Claude Opus 5.5 --- .dockerignore | 11 + .github/dependabot.yml | 30 + .github/workflows/codeql.yml | 30 + .github/workflows/tests.yml | 68 + .gitignore | 9 + README.md | 98 ++ SECURITY.md | 27 + base/LICENSE | 190 +++ base/README.md | 52 + base/demo/README.md | 32 + base/demo/client.mjs | 64 + base/demo/make-binding.mjs | 47 + base/demo/networks.mjs | 30 + base/demo/package-lock.json | 1292 ++++++++++++++++ base/demo/package.json | 19 + base/demo/server.mjs | 67 + base/fixtures/payai-bad-amount.json | 32 + base/fixtures/payai-bad-content-sha256.json | 32 + base/fixtures/payai-bad-index.json | 32 + base/fixtures/payai-bad-nonce.json | 32 + base/fixtures/payai-bad-to.json | 32 + base/fixtures/payai-ok.json | 32 + base/fixtures/payai-sig-ephemeral.json | 38 + base/fixtures/payai-sig-forged-payer.json | 38 + base/fixtures/payai-sig-tampered.json | 38 + base/make-fixtures.mjs | 52 + base/market/Dockerfile | 19 + base/market/README.md | 41 + base/market/buy.mjs | 30 + base/market/data.mjs | 62 + base/market/geo.mjs | 35 + base/market/package-lock.json | 1248 ++++++++++++++++ base/market/package.json | 21 + base/market/server.mjs | 71 + base/market/test/geo.test.mjs | 46 + base/market/test/market.test.mjs | 81 + base/package-lock.json | 1305 +++++++++++++++++ base/package.json | 74 + base/policy/README.md | 76 + base/policy/demo-pay.mjs | 66 + base/policy/evm-policy.mjs | 367 +++++ base/policy/rules-policy.mjs | 35 + base/policy/test/evm-policy.test.mjs | 272 ++++ base/policy/x402-fetch.mjs | 56 + base/run-tests.sh | 17 + base/sdk/README.md | 49 + base/sdk/decision.mjs | 108 ++ base/sdk/examples/decision-selftest.mjs | 58 + base/sdk/examples/selftest.mjs | 46 + base/sdk/index.mjs | 12 + base/sdk/networks.mjs | 30 + base/sdk/pay.mjs | 46 + base/sdk/receipt.mjs | 96 ++ base/sdk/serve.mjs | 106 ++ base/sdk/test/decision.test.mjs | 113 ++ base/sdk/test/sdk.test.mjs | 149 ++ base/sdk/test/trim.test.mjs | 16 + base/test/verify-core.test.mjs | 128 ++ base/verify-evm-core.mjs | 159 ++ base/verify-evm-receipt.mjs | 38 + docs/decision-receipt-v1.md | 95 ++ docs/payment-binding-v1.md | 69 + .../selftest-base-mainnet-binding.json | 38 + .../selftest-base-sepolia-binding.json | 38 + evidence/README.md | 17 + fly.market.toml | 35 + scripts/new-testnet-keys.sh | 34 + 67 files changed, 7826 insertions(+) create mode 100644 .dockerignore create mode 100644 .github/dependabot.yml create mode 100755 .github/workflows/codeql.yml create mode 100644 .github/workflows/tests.yml create mode 100755 .gitignore create mode 100755 README.md create mode 100755 SECURITY.md create mode 100755 base/LICENSE create mode 100644 base/README.md create mode 100755 base/demo/README.md create mode 100755 base/demo/client.mjs create mode 100644 base/demo/make-binding.mjs create mode 100755 base/demo/networks.mjs create mode 100755 base/demo/package-lock.json create mode 100755 base/demo/package.json create mode 100755 base/demo/server.mjs create mode 100644 base/fixtures/payai-bad-amount.json create mode 100644 base/fixtures/payai-bad-content-sha256.json create mode 100644 base/fixtures/payai-bad-index.json create mode 100644 base/fixtures/payai-bad-nonce.json create mode 100644 base/fixtures/payai-bad-to.json create mode 100644 base/fixtures/payai-ok.json create mode 100644 base/fixtures/payai-sig-ephemeral.json create mode 100644 base/fixtures/payai-sig-forged-payer.json create mode 100644 base/fixtures/payai-sig-tampered.json create mode 100755 base/make-fixtures.mjs create mode 100644 base/market/Dockerfile create mode 100644 base/market/README.md create mode 100644 base/market/buy.mjs create mode 100644 base/market/data.mjs create mode 100755 base/market/geo.mjs create mode 100644 base/market/package-lock.json create mode 100644 base/market/package.json create mode 100644 base/market/server.mjs create mode 100644 base/market/test/geo.test.mjs create mode 100644 base/market/test/market.test.mjs create mode 100644 base/package-lock.json create mode 100755 base/package.json create mode 100644 base/policy/README.md create mode 100644 base/policy/demo-pay.mjs create mode 100644 base/policy/evm-policy.mjs create mode 100644 base/policy/rules-policy.mjs create mode 100644 base/policy/test/evm-policy.test.mjs create mode 100644 base/policy/x402-fetch.mjs create mode 100644 base/run-tests.sh create mode 100644 base/sdk/README.md create mode 100755 base/sdk/decision.mjs create mode 100755 base/sdk/examples/decision-selftest.mjs create mode 100644 base/sdk/examples/selftest.mjs create mode 100644 base/sdk/index.mjs create mode 100644 base/sdk/networks.mjs create mode 100644 base/sdk/pay.mjs create mode 100644 base/sdk/receipt.mjs create mode 100644 base/sdk/serve.mjs create mode 100755 base/sdk/test/decision.test.mjs create mode 100644 base/sdk/test/sdk.test.mjs create mode 100755 base/sdk/test/trim.test.mjs create mode 100644 base/test/verify-core.test.mjs create mode 100644 base/verify-evm-core.mjs create mode 100755 base/verify-evm-receipt.mjs create mode 100755 docs/decision-receipt-v1.md create mode 100755 docs/payment-binding-v1.md create mode 100644 evidence/2026-12-01/selftest-base-mainnet-binding.json create mode 100644 evidence/2026-12-01/selftest-base-sepolia-binding.json create mode 100644 evidence/README.md create mode 100644 fly.market.toml create mode 100755 scripts/new-testnet-keys.sh diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..e950aa4 --- /dev/null +++ b/.dockerignore @@ -0,0 +1,11 @@ +**/node_modules +**/.env +**/.env.* +**/*keypair*.json +**/*.key +.git +evidence +docs +scripts +**/test +**/examples diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 0000000..aefdaf6 --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,30 @@ +version: 2 +updates: + - package-ecosystem: npm + directory: "/base" + schedule: + interval: weekly + open-pull-requests-limit: 5 + groups: + x402-and-solana-evm: + patterns: ["@x402/*", "@solana/*", "viem"] + - package-ecosystem: npm + directory: "/base/market" + schedule: + interval: weekly + open-pull-requests-limit: 5 + groups: + x402-and-solana-evm: + patterns: ["@x402/*", "@solana/*", "viem"] + - package-ecosystem: npm + directory: "/base/demo" + schedule: + interval: weekly + open-pull-requests-limit: 5 + groups: + x402-and-solana-evm: + patterns: ["@x402/*", "@solana/*", "viem"] + - package-ecosystem: github-actions + directory: "/" + schedule: + interval: weekly diff --git a/.github/workflows/codeql.yml b/.github/workflows/codeql.yml new file mode 100755 index 0000000..c055c8c --- /dev/null +++ b/.github/workflows/codeql.yml @@ -0,0 +1,30 @@ +name: CodeQL + +on: + push: + branches: [main] + pull_request: + schedule: + - cron: "17 6 * * 1" + workflow_dispatch: + +permissions: + contents: read + +jobs: + analyze: + runs-on: ubuntu-latest + timeout-minutes: 20 + permissions: + actions: read + contents: read + security-events: write + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - uses: github/codeql-action/init@915412ff23e8b7659517e607487dbeae018f2934 # v4.39.5 + with: + languages: javascript-typescript + queries: security-extended + - uses: github/codeql-action/analyze@915412ff23e8b7659517e607487dbeae018f2934 # v4.39.5 + with: + category: "/language:javascript-typescript" diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml new file mode 100644 index 0000000..dce1235 --- /dev/null +++ b/.github/workflows/tests.yml @@ -0,0 +1,68 @@ +name: tests + +on: + pull_request: + push: + branches: [main] + +permissions: + contents: read + +jobs: + base: + runs-on: ubuntu-latest + timeout-minutes: 15 + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 + with: + node-version: 24 + - name: Install + run: | + (cd base && npm ci --no-audit --no-fund) + (cd base/demo && npm ci --no-audit --no-fund) + (cd base/market && npm ci --no-audit --no-fund) + - name: Syntax + run: for f in $(git ls-files "base/*.mjs"); do node --check "$f"; done + - name: Receipt verifier core (7 tests, no network) + working-directory: base + run: npm run test:verify + - name: Pre-sign policy (19 tests, no network) + working-directory: base + run: npm run test:policy + - name: Library (pay, charge, receipts, decisions; 14 tests, one reads the public Base Sepolia RPC) + working-directory: base + run: npm run test:sdk + - name: x402 market (4 tests, no network) + working-directory: base/market + run: npm test + - name: Verifier against a real third-party Base mainnet payment (10 cases, public RPC) + working-directory: base + run: npm run test:live + - name: Package (pack, install in an empty project, import every subpath, run the bin) + working-directory: base + run: | + npm pack --pack-destination "$RUNNER_TEMP" + mkdir "$RUNNER_TEMP/consumer" && cd "$RUNNER_TEMP/consumer" + npm init -y >/dev/null + npm install --no-audit --no-fund "$RUNNER_TEMP"/nirium-base-*.tgz + node --input-type=module -e "for (const p of ['nirium-base','nirium-base/policy','nirium-base/policy/x402-fetch','nirium-base/policy/rules','nirium-base/receipt','nirium-base/verify','nirium-base/decision']) await import(p); console.log('imports ok')" + npx --no-install nirium-verify-evm "$GITHUB_WORKSPACE/base/fixtures/payai-ok.json" --no-sig | tail -1 | grep -q "RESULT: VALID" + if tar -tzf "$RUNNER_TEMP"/nirium-base-*.tgz | grep -E -i "test|example|evidence|fixture|market|demo"; then echo "unexpected files in the package"; exit 1; fi + + market-image: + runs-on: ubuntu-latest + timeout-minutes: 15 + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - name: Build the market image (same Dockerfile Fly uses) + run: docker build -f base/market/Dockerfile -t nirium-market . + - name: Run it with the testnet config of fly.market.toml; /health must be 200 and the paid route 402 + run: | + docker run -d --name market -p 8080:8080 -e NIRIUM_NETWORK=eip155:84532 -e NIRIUM_EVM_PAYTO=0xC7484059c45Cf89dDc487C836A6f821Dc5882051 nirium-market + for i in $(seq 1 30); do curl -sf http://localhost:8080/health && break; sleep 1; done + code=$(curl -s -o /dev/null -w "%{http_code}" http://localhost:8080/v1/market) + info=$(curl -s http://localhost:8080/v1/market/info) + docker logs market | tail -20 + echo "paid route: $code"; echo "info: $info" + test "$code" = 402 diff --git a/.gitignore b/.gitignore new file mode 100755 index 0000000..cd366bd --- /dev/null +++ b/.gitignore @@ -0,0 +1,9 @@ +node_modules/ +out/ +.env +.env.* +*.key +*keypair*.json +keys/ +settle.json +binding.json diff --git a/README.md b/README.md new file mode 100755 index 0000000..dd0cb0a --- /dev/null +++ b/README.md @@ -0,0 +1,98 @@ +# nirium-base + +[![tests](https://github.com/nirium-protocol/nirium-base/actions/workflows/tests.yml/badge.svg)](https://github.com/nirium-protocol/nirium-base/actions/workflows/tests.yml) +[![CodeQL](https://github.com/nirium-protocol/nirium-base/actions/workflows/codeql.yml/badge.svg)](https://github.com/nirium-protocol/nirium-base/actions/workflows/codeql.yml) +[![License: Apache-2.0](https://img.shields.io/badge/license-Apache--2.0-blue.svg)](LICENSE) + +Pay and charge with x402 on Base, refuse a payment before it is signed, and keep a receipt that +says what the payment was for. + +The chain already shows who paid whom, how much, and when. A Nirium receipt adds what the chain +does not keep: which order a payment was for and who declared it, signed by the payer and bound +to one specific USDC `Transfer` log. Anyone can check it against Base with a public RPC and +nothing else from us. + +This is [Nirium](https://nirium.xyz) on Base. Nirium started on Stellar; this repo brings the +same receipt format and the same pre-sign policy contract to Base and Base Sepolia. The code is +the EVM code of [`nirium-avalanche`](https://github.com/nirium-protocol/nirium-avalanche) with +Base's network table. + +## Status + +| Piece | Base Sepolia | Base mainnet | +|---|---|---| +| Receipt verifier (`base/verify-evm-receipt.mjs`) | yes, our selftest receipt | yes, our selftest receipt; fixtures from a third-party payment | +| Pre-sign policy (`base/policy/`) | offline tests | not yet | +| Pay and charge library (`base/sdk/`) | yes (selftest, 1 Dec 2026) | yes (selftest, 1 Dec 2026) | +| x402 market (`base/market/`) | offline tests | not yet | + +A row says "yes" only once a settled payment's hash is in [`evidence/`](evidence/README.md). +Every payment there is made by the team to test the flow, labeled `selftest`, and is not usage. +Nothing here has had an external audit. + +## One Base detail + +The USDC contracts do not share an EIP-712 domain name: Base Sepolia USDC signs as `USDC`, +Base mainnet USDC as `USD Coin` (both version `2`). The name lives in each row of +[`base/sdk/networks.mjs`](base/sdk/networks.mjs); with the wrong one every signature is invalid. + +## What is here + +| Path | What it does | +|---|---| +| [`docs/payment-binding-v1.md`](docs/payment-binding-v1.md) | The receipt format and what a verifier checks | +| [`docs/decision-receipt-v1.md`](docs/decision-receipt-v1.md) | Decision receipts: a payer-signed record of what the pre-sign policy decided, including payments it refused (DENY, WAIT), which leave nothing on-chain | +| [`base/verify-evm-core.mjs`](base/verify-evm-core.mjs) | Checks a receipt against a USDC `Transfer` log (tx hash + block logIndex), the EIP-3009 `AuthorizationUsed` nonce and the payer's signature. The CLI, `verifyReceipt` and a browser run this file | +| [`base/verify-evm-receipt.mjs`](base/verify-evm-receipt.mjs) | The command line for it | +| [`base/sdk/`](base/sdk/README.md) | The library: `x402Serve` to charge, `createX402Fetch` to pay (with an optional policy), `bindReceipt` and `verifyReceipt` | +| [`base/policy/`](base/policy/README.md) | Pre-sign policy: DENY, WAIT, a timeout and every malformed answer sign nothing | +| [`base/market/`](base/market/README.md) | x402 market: Base network conditions (fees, block fill, block time) for $0.01 per query | +| [`base/demo/`](base/demo/README.md) | Reference x402 `exact` payment with PayAI as facilitator, then the receipt | +| [`scripts/`](scripts) | Base Sepolia key setup | +| [`evidence/`](evidence/README.md) | The team's test payments, each with its receipt and explorer link | + +## Quick start + +```js +import { x402Serve, createX402Fetch, settlementOf, bindReceipt, createRulesPolicy } from "nirium-base"; + +app.use(x402Serve({ payTo: "0x...", network: "eip155:84532", routes: { "GET /data": "$0.01" } })); + +const pay = createX402Fetch({ signer: account, network: "eip155:84532", maxAmountPerPayment: "10000", + policy: createRulesPolicy({ maxAmount: "10000" }) }); +const res = await pay("https://seller.example/data"); +const receipt = await bindReceipt({ tx: settlementOf(res).transaction, network: "eip155:84532", ref: "order-42", signer: account }); +``` + +`x402Serve` runs on your server: Nirium runs nothing in the middle and receives nothing. + +## Tests + +| Suite | Command | Network | +|---|---|---| +| Verifier core (hash against `node:crypto`, EIP-191, the full check on recorded RPC answers, altered fields) | `cd base && npm ci && npm run test:verify` | none | +| Verifier, 10 cases against a real third-party Base mainnet payment | `cd base && npm ci && bash run-tests.sh` | public Base RPC | +| Pre-sign policy, 19 tests | `cd base && npm ci && npm run test:policy` | none | +| Library | `cd base && npm ci && npm run test:sdk` | one test reads the public Base Sepolia RPC | +| Market | `cd base && npm ci && cd market && npm ci && npm test` | none | + +CI runs all of them on every pull request. The verifier fixtures point at a third-party payment +and are labeled as such: they test the verifier, they are not usage of this project. + +## Rules this code follows + +- Non-custodial: every key belongs to whoever pays or receives. Nirium never holds one. +- Mainnet payments need an explicit opt-in on the client (`NIRIUM_ALLOW_MAINNET=1` or + `allowMainnet: true`). +- Settlement is done by PayAI, an independent facilitator. Nirium runs no facilitator. +- Receipts are tamper-evident, not tamper-proof: an edited receipt no longer matches its hash or + its signature. A receipt does not prove that goods or a service were delivered. +- Keys never go in this repo. The key script writes outside it and refuses to run inside it. + +## Security + +See [SECURITY.md](SECURITY.md). Please report vulnerabilities privately, not in a public issue. + +## License + +[Apache-2.0](LICENSE) diff --git a/SECURITY.md b/SECURITY.md new file mode 100755 index 0000000..94efebb --- /dev/null +++ b/SECURITY.md @@ -0,0 +1,27 @@ +# Security policy + +## Reporting a vulnerability + +Please do not open a public issue for a security problem. Report it privately through GitHub: +the **Security** tab of this repository, then **Report a vulnerability**. That opens a private +advisory that only the maintainers can see. + +Include what you found, how to reproduce it, and what an attacker could do with it. If you have +a fix, describe it in the report; we will set up a private branch for it. + +We aim to acknowledge a report within 3 business days and to tell you what we plan to do within +10. There is no bug bounty for this repository. + +## Scope + +In scope: the code in this repository, in particular anything that could make a client sign a +payment its policy refused, make a verifier accept a receipt that does not match the chain, or +make a payment go somewhere other than the requested `payTo`. + +Out of scope: the x402 packages, the PayAI facilitator and the public RPC endpoints this code +talks to. Please report those to their own maintainers. + +## Keys + +No key belongs in this repository. If you ever see a private key, keypair file or seed phrase in +a commit, report it the same private way so it can be revoked. diff --git a/base/LICENSE b/base/LICENSE new file mode 100755 index 0000000..4e589c6 --- /dev/null +++ b/base/LICENSE @@ -0,0 +1,190 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + Copyright 2026 Nirium Protocol Contributors + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/base/README.md b/base/README.md new file mode 100644 index 0000000..32f3b62 --- /dev/null +++ b/base/README.md @@ -0,0 +1,52 @@ +# nirium-base + +Pay and charge with x402 on Base, refuse a payment before it is signed, and keep a payer-signed +receipt bound to the exact USDC `Transfer` log. + +The chain already shows who paid whom, how much and when. The receipt adds what the chain does +not keep: which order the payment was for and who declared it. Anyone can check it against Base +with a public RPC. Part of [Nirium](https://nirium.xyz). Source, tests and the team's test +payments: [nirium-base](https://github.com/nirium-protocol/nirium-base). + +```js +import { x402Serve, createX402Fetch, settlementOf, bindReceipt, verifyReceipt, createRulesPolicy } from "nirium-base"; + +// Charge for your own API. Runs on your server: Nirium runs nothing in the middle. +app.use(x402Serve({ payTo: "0x...", network: "eip155:84532", routes: { "GET /data": "$0.01" } })); + +// Pay, with a policy: a payment it refuses is never signed. +const pay = createX402Fetch({ signer: account, network: "eip155:84532", maxAmountPerPayment: "10000", + policy: createRulesPolicy({ maxAmount: "10000" }) }); +const res = await pay("https://seller.example/data", { headers: { "X-Nirium-Ref": "order-42" } }); + +// A payer-signed receipt bound to the transfer, and its check against the chain. +const receipt = await bindReceipt({ tx: settlementOf(res).transaction, network: "eip155:84532", ref: "order-42", signer: account }); +const { ok } = await verifyReceipt(receipt); +``` + +`account` is a viem account for the payer's own key. Networks: Base Sepolia (`eip155:84532`) and +Base mainnet (`eip155:8453`, needs `allowMainnet: true`). `x402Serve` needs `express` (4.22.3+ or +5.3.0+) in your app. Settlement is done by PayAI, an independent x402 facilitator. + +| Import | What it is | +|---|---| +| `nirium-base` | `x402Serve`, `createX402Fetch`, `settlementOf`, `bindReceipt`, `verifyReceipt`, `createRulesPolicy` | +| `nirium-base/policy` | The pre-sign policy gate (decodes what is about to be signed, asks your policy, signs only on a bound ALLOW) | +| `nirium-base/policy/rules` | A small reference policy engine: max amount, approval line, allowlists | +| `nirium-base/receipt` | `bindReceipt` and `verifyReceipt` on their own, without the Express middleware | +| `nirium-base/decision` | Decision receipts: `bindDecision`, `verifyDecision`, `collectDecisions` (also exported from `nirium-base`) | +| `nirium-base/verify` | The receipt verifier as a library. No Node-only code, so it runs in Node and in the browser | + +Check a receipt from the command line: + +```bash +npx -p nirium-base nirium-verify-evm receipt.json +``` + +Exit code 0 means valid, 1 means a check failed, 2 means bad input. + +Receipts are tamper-evident, not tamper-proof, and they do not prove that goods or a service +were delivered. Non-custodial: every key stays with whoever pays or receives. No external audit +yet. Report security problems privately: [SECURITY.md](https://github.com/nirium-protocol/nirium-base/blob/main/SECURITY.md). + +License: Apache-2.0 diff --git a/base/demo/README.md b/base/demo/README.md new file mode 100755 index 0000000..6e8e689 --- /dev/null +++ b/base/demo/README.md @@ -0,0 +1,32 @@ +# demo: x402 payment + Nirium binding on Base + +Reference code. Packages pinned: `@x402/express`, `@x402/evm`, `@x402/fetch`, `@x402/core` 2.32.0, `viem` 2.58.7, `express` 5.3.0. No keys are stored here. + +## Before you start + +- Two fresh keys: a **payer** and a **payTo** (`../../scripts/new-testnet-keys.sh`). Use keys made for this project only. +- Base Sepolia: the payer needs Base Sepolia USDC (`0x036CbD53842c5426634e7929541eC2318f3dCF7e`) from faucet.circle.com (browser). It needs **no ETH**: PayAI pays the gas. +- `npm ci` in this folder. + +## Steps (Base Sepolia) + +| # | Command | Env it needs | +|---|---|---| +| 1 | `node server.mjs` (leave running) | `NIRIUM_EVM_PAYTO` (required); optional `NIRIUM_NETWORK`, `NIRIUM_AMOUNT` (default `10000` = 0.01 USDC), `PORT` (4021), `FACILITATOR_URL` (PayAI) | +| 2 | `curl -i http://localhost:4021/paid` should return 402 with a `PAYMENT-REQUIRED` header | none | +| 3 | `node client.mjs` pays and writes `settle.json` with the tx hash | `NIRIUM_EVM_PAYER_KEY` (required, never printed); optional `NIRIUM_URL`, `NIRIUM_MAX_ATOMIC` (cap, default `10000`) | +| 4 | `node make-binding.mjs --settle settle.json --ref selftest--base-sepolia-01` writes `binding.json`, signed by the payer | `NIRIUM_EVM_PAYER_KEY` (must be the payer of that tx, or nothing is written) | +| 5 | `node ../verify-evm-receipt.mjs binding.json` should end with `RESULT: VALID` | none | + +`make-binding.mjs` also takes `--tx 0x.. --network eip155:84532` instead of `--settle`, plus `--resource`, `--note`, `--payer`/`--payto` (to narrow a batched tx), `--no-sign` and `--out`. + +## Base mainnet selftest + +Same steps with `NIRIUM_NETWORK=eip155:8453` on server and client, plus `NIRIUM_ALLOW_MAINNET=1` on the client (without it, the client refuses to pay on mainnet). The asset switches to `0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913`. PayAI publishes a per-settlement rate for Base mainnet on its `/supported` page (0.00142 USD on 30-nov-2026); Base Sepolia is free. Keep the `selftest` label. + +## Notes + +- The EIP-712 domain name of USDC differs per network: `USDC` on Base Sepolia, `USD Coin` on Base mainnet (both version `2`). The server takes it from `networks.mjs` and sends it in `price.extra`; the client allows the asset through `spendControls.allowedAssets`, which is also the per-payment cap. +- The transfer method defaults to EIP-3009 (`transferWithAuthorization`) when `extra.assetTransferMethod` is not set. +- `locator.index` is the log index within the **block**, not within the tx. PayAI settles through Multicall3 on Base too (seen on mainnet, 30-nov-2026), so the tx `to` is not the USDC contract. +- `record` is written with keys already sorted, so `sha256(JSON.stringify(record))` equals the canonical hash. diff --git a/base/demo/client.mjs b/base/demo/client.mjs new file mode 100755 index 0000000..cbe8b1b --- /dev/null +++ b/base/demo/client.mjs @@ -0,0 +1,64 @@ +// client.mjs - pays GET /paid with x402 v2 (EIP-3009 USDC), prints the settlement tx. +// +// Env: +// NIRIUM_EVM_PAYER_KEY (required) payer private key, 0x-prefixed. Never printed or written. +// NIRIUM_NETWORK eip155:84532 (default) | eip155:8453 +// NIRIUM_URL default http://localhost:4021/paid +// NIRIUM_MAX_ATOMIC per-payment cap in atomic USDC, default "10000" (0.01 USDC) +// NIRIUM_ALLOW_MAINNET must be "1" to pay on eip155:8453 +// +// Writes settle.json (tx, network, payer, resource) for make-binding.mjs --settle. +import { writeFileSync } from "node:fs"; +import { privateKeyToAccount } from "viem/accounts"; +import { wrapFetchWithPaymentFromConfig, decodePaymentResponseHeader } from "@x402/fetch"; +import { ExactEvmScheme } from "@x402/evm/exact/client"; +import { getNetwork } from "./networks.mjs"; + +const network = process.env.NIRIUM_NETWORK || "eip155:84532"; +const net = getNetwork(network); +const url = process.env.NIRIUM_URL || "http://localhost:4021/paid"; +const maxAtomic = process.env.NIRIUM_MAX_ATOMIC || "10000"; +const key = process.env.NIRIUM_EVM_PAYER_KEY; + +if (!key || !/^0x[0-9a-fA-F]{64}$/.test(key)) { + console.error("NIRIUM_EVM_PAYER_KEY must be a 0x-prefixed 32-byte hex key"); + process.exit(2); +} +if (net.mainnet && process.env.NIRIUM_ALLOW_MAINNET !== "1") { + console.error("refusing to pay on mainnet without NIRIUM_ALLOW_MAINNET=1"); + process.exit(2); +} + +const account = privateKeyToAccount(key); +console.log(`payer=${account.address} network=${network} url=${url} cap=${maxAtomic} atomic`); + +const fetchWithPayment = wrapFetchWithPaymentFromConfig(fetch, { + schemes: [{ network, client: new ExactEvmScheme(account) }], + // The asset is allowed explicitly, so a seller cannot swap in another token. + // The same entry is the per-payment cap (atomic units) on both networks. + spendControls: { + allowedAssets: [{ network, asset: net.usdc, maxAmountPerPayment: maxAtomic }], + }, +}); + +const res = await fetchWithPayment(url, { method: "GET" }); +const body = await res.text(); +console.log(`HTTP ${res.status}`); +console.log(`body: ${body.slice(0, 500)}`); + +const header = res.headers.get("PAYMENT-RESPONSE"); +if (!header) { + console.error("no PAYMENT-RESPONSE header: nothing settled"); + process.exit(1); +} +const settle = decodePaymentResponseHeader(header); +console.log("settle:", JSON.stringify(settle)); +if (!settle.success || !settle.transaction) { + console.error(`settlement failed: ${settle.errorReason || "unknown"} ${settle.errorMessage || ""}`); + process.exit(1); +} +const out = { tx: settle.transaction, network: settle.network || network, payer: settle.payer || account.address, resource: url }; +writeFileSync("settle.json", JSON.stringify(out, null, 2)); +console.log(`tx: ${settle.transaction}`); +console.log(`explorer: ${net.explorer}${settle.transaction}`); +console.log("wrote settle.json"); diff --git a/base/demo/make-binding.mjs b/base/demo/make-binding.mjs new file mode 100644 index 0000000..4e3d6ec --- /dev/null +++ b/base/demo/make-binding.mjs @@ -0,0 +1,47 @@ +// make-binding.mjs - builds a "nirium-payment-binding-v1" JSON from a settled x402 tx. +// Thin CLI over bindReceipt() in ../sdk (the logic lives there, once). +// +// Usage: +// node make-binding.mjs --ref [--settle settle.json | --tx 0x.. --network eip155:84532] +// [--resource ] [--note ] [--payer 0x..] [--payto 0x..] +// [--no-sign] [--out binding.json] +// +// Env (only when signing): +// NIRIUM_EVM_PAYER_KEY payer private key. Never printed or written. Its address must equal +// the Transfer.from found on chain, or nothing is written. +import { readFileSync, writeFileSync } from "node:fs"; +import { privateKeyToAccount } from "viem/accounts"; +import { bindReceipt } from "../sdk/receipt.mjs"; + +const arg = (name, def) => { const i = process.argv.indexOf(`--${name}`); return i >= 0 ? process.argv[i + 1] : def; }; +const die = (msg, code = 2) => { console.error(msg); process.exit(code); }; + +const settle = arg("settle") ? JSON.parse(readFileSync(arg("settle"), "utf8")) : {}; +const tx = arg("tx", settle.tx); +const network = arg("network", settle.network || "eip155:84532"); +const ref = arg("ref"); +if (!tx || !/^0x[0-9a-fA-F]{64}$/.test(tx)) die("need --tx 0x<64 hex> or --settle settle.json"); +if (!ref) die("need --ref , e.g. selftest-2026-11-26-base-sepolia-01"); + +let signer; +if (!process.argv.includes("--no-sign")) { + const key = process.env.NIRIUM_EVM_PAYER_KEY; + if (!key || !/^0x[0-9a-fA-F]{64}$/.test(key)) die("NIRIUM_EVM_PAYER_KEY required to sign (or pass --no-sign)"); + signer = privateKeyToAccount(key); +} + +let doc; +try { + doc = await bindReceipt({ + tx, network, ref, signer, + resource: arg("resource", settle.resource || "unknown"), + note: arg("note", "Nirium selftest payment, our own keys"), + labels: ["selftest"], + payer: arg("payer", settle.payer), payTo: arg("payto"), + }); +} catch (e) { die(e.message, 1); } + +const out = arg("out", "binding.json"); +writeFileSync(out, JSON.stringify(doc, null, 2)); +const p = doc.record.payment; +console.log(`wrote ${out} tx=${p.tx} logIndex=${p.locator.index} amount=${p.amount} from=${p.from} to=${p.to} nonce=${p.x402.nonce} content_sha256=${doc.content_sha256} signed=${!!doc.agent}`); diff --git a/base/demo/networks.mjs b/base/demo/networks.mjs new file mode 100755 index 0000000..2c5e2ee --- /dev/null +++ b/base/demo/networks.mjs @@ -0,0 +1,30 @@ +// Network table shared by server, client and make-binding. +// USDC addresses: Circle's official page (developers.circle.com/stablecoins/usdc-contract-addresses). +// EIP-712 domain read from the contracts on 30-nov-2026: Base Sepolia name "USDC", Base mainnet +// name "USD Coin", both version "2". It differs per network, so it lives in each row. +import { base, baseSepolia } from "viem/chains"; + +export const NETWORKS = { + "eip155:84532": { + chain: baseSepolia, + usdc: "0x036CbD53842c5426634e7929541eC2318f3dCF7e", + extra: { name: "USDC", version: "2" }, + explorer: "https://sepolia.basescan.org/tx/", + mainnet: false, + }, + "eip155:8453": { + chain: base, + usdc: "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913", + extra: { name: "USD Coin", version: "2" }, + explorer: "https://basescan.org/tx/", + mainnet: true, + }, +}; + +export const PAYAI_FACILITATOR = "https://facilitator.payai.network"; + +export function getNetwork(id) { + const n = NETWORKS[id]; + if (!n) throw new Error(`unsupported network ${id}; use one of ${Object.keys(NETWORKS).join(", ")}`); + return n; +} diff --git a/base/demo/package-lock.json b/base/demo/package-lock.json new file mode 100755 index 0000000..f19b916 --- /dev/null +++ b/base/demo/package-lock.json @@ -0,0 +1,1292 @@ +{ + "name": "nirium-base-demo", + "version": "1.0.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "nirium-base-demo", + "version": "1.0.0", + "license": "Apache-2.0", + "dependencies": { + "@x402/core": "2.32.0", + "@x402/evm": "2.32.0", + "@x402/express": "2.32.0", + "@x402/fetch": "2.32.0", + "express": "5.3.0", + "viem": "2.58.7" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/@adraffy/ens-normalize": { + "version": "1.11.1", + "resolved": "https://registry.npmjs.org/@adraffy/ens-normalize/-/ens-normalize-1.11.1.tgz", + "integrity": "sha512-nhCBV3quEgesuf7c7KYfperqSS14T8bYuvJ8PcLJp6znkZpFc0AuW4qBtr8eKVyPPe/8RSr7sglCWPU5eaxwKQ==", + "license": "MIT" + }, + "node_modules/@noble/ciphers": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/@noble/ciphers/-/ciphers-1.3.0.tgz", + "integrity": "sha512-2I0gnIVPtfnMw9ee9h1dJG7tp81+8Ob3OJb3Mv37rx5L40/b0i7djjCVvGOVqc9AEIQyvyu1i6ypKdFw8R8gQw==", + "license": "MIT", + "engines": { + "node": "^14.21.3 || >=16" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, + "node_modules/@noble/curves": { + "version": "1.9.7", + "resolved": "https://registry.npmjs.org/@noble/curves/-/curves-1.9.7.tgz", + "integrity": "sha512-gbKGcRUYIjA3/zCCNaWDciTMFI0dCkvou3TL8Zmy5Nc7sJ47a0jtOeZoTaMxkuqRo9cRhjOdZJXegxYE5FN/xw==", + "license": "MIT", + "dependencies": { + "@noble/hashes": "1.8.0" + }, + "engines": { + "node": "^14.21.3 || >=16" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, + "node_modules/@noble/hashes": { + "version": "1.8.0", + "resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-1.8.0.tgz", + "integrity": "sha512-jCs9ldd7NwzpgXDIf6P3+NrHh9/sD6CQdxHyjQI+h/6rDNo88ypBxxz45UDuZHz9r3tNz7N/VInSVoVdtXEI4A==", + "license": "MIT", + "engines": { + "node": "^14.21.3 || >=16" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, + "node_modules/@scure/base": { + "version": "1.2.6", + "resolved": "https://registry.npmjs.org/@scure/base/-/base-1.2.6.tgz", + "integrity": "sha512-g/nm5FgUa//MCj1gV09zTJTaM6KBAHqLN907YVQqf7zC49+DcO4B1so4ZX07Ef10Twr6nuqYEH9GEggFXA4Fmg==", + "license": "MIT", + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, + "node_modules/@scure/bip32": { + "version": "1.7.0", + "resolved": "https://registry.npmjs.org/@scure/bip32/-/bip32-1.7.0.tgz", + "integrity": "sha512-E4FFX/N3f4B80AKWp5dP6ow+flD1LQZo/w8UnLGYZO674jS6YnYeepycOOksv+vLPSpgN35wgKgy+ybfTb2SMw==", + "license": "MIT", + "dependencies": { + "@noble/curves": "~1.9.0", + "@noble/hashes": "~1.8.0", + "@scure/base": "~1.2.5" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, + "node_modules/@scure/bip39": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/@scure/bip39/-/bip39-1.6.0.tgz", + "integrity": "sha512-+lF0BbLiJNwVlev4eKelw1WWLaiKXw7sSl8T6FvBlWkdX+94aGJ4o8XjUdlyhTCjd8c+B3KT3JfS8P0bLRNU6A==", + "license": "MIT", + "dependencies": { + "@noble/hashes": "~1.8.0", + "@scure/base": "~1.2.5" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, + "node_modules/@signinwithethereum/siwe": { + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/@signinwithethereum/siwe/-/siwe-4.2.1.tgz", + "integrity": "sha512-CQEQhCIgN9blil1YpaGR+wvGPdsBVK6zed5DBu03s1IdbSO3kA/n7Zp+SAkZGiHy3HY6OJm1Su0/Bd33vKK6nQ==", + "license": "Apache-2.0", + "dependencies": { + "@signinwithethereum/siwe-parser": "^4.2.1" + }, + "peerDependencies": { + "ethers": "^5.7.0 || ^6.13.0", + "viem": "^2.7.0" + }, + "peerDependenciesMeta": { + "ethers": { + "optional": true + }, + "viem": { + "optional": true + } + } + }, + "node_modules/@signinwithethereum/siwe-parser": { + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/@signinwithethereum/siwe-parser/-/siwe-parser-4.2.1.tgz", + "integrity": "sha512-GAdwNiBaRpUMTiFfPrbQ3e/RBhPbEhRRN1sZmDMLgLEZuKqKwO7V0ksVzCerE9l8HFKTNw5R/q3kPDCWJRz4zA==", + "license": "Apache-2.0", + "dependencies": { + "@noble/hashes": "^1.7.0", + "apg-js": "^4.4.0" + } + }, + "node_modules/@x402/core": { + "version": "2.32.0", + "resolved": "https://registry.npmjs.org/@x402/core/-/core-2.32.0.tgz", + "integrity": "sha512-HyS8vbaR3XP79EIATKGMt8eL0Ql46yrfVDrtv1Inmlx4qJl4NU61cJmTh/pSGOCJIeb7ETNhWR/GQ4XsWZcQIA==", + "license": "Apache-2.0", + "dependencies": { + "zod": "^4.6.6" + } + }, + "node_modules/@x402/evm": { + "version": "2.32.0", + "resolved": "https://registry.npmjs.org/@x402/evm/-/evm-2.32.0.tgz", + "integrity": "sha512-dgsBYsUGs2Qem2NVV5QkhpyWJ4dssigE4LJ662LKcN1+9PKxBbX2Q5l2dpzkmHmXXzUoyapG5yBkYhMkckRZ7Q==", + "license": "Apache-2.0", + "dependencies": { + "@x402/core": "~2.32.0", + "viem": "^2.48.11", + "zod": "^4.6.6" + } + }, + "node_modules/@x402/express": { + "version": "2.32.0", + "resolved": "https://registry.npmjs.org/@x402/express/-/express-2.32.0.tgz", + "integrity": "sha512-aPZDcDsSIAy6dz5YmcuosoBRy4t2VUCwzeZG/S5bxE7xZfxouyRbm3M+mlUNHymAjy4Z/lNqK6jummRe770AGw==", + "license": "Apache-2.0", + "dependencies": { + "@x402/core": "~2.32.0", + "@x402/extensions": "~2.32.0" + }, + "peerDependencies": { + "@x402/paywall": "^2.32.0", + "express": "^4.22.3 || ^5.3.0" + }, + "peerDependenciesMeta": { + "@x402/paywall": { + "optional": true + } + } + }, + "node_modules/@x402/extensions": { + "version": "2.32.0", + "resolved": "https://registry.npmjs.org/@x402/extensions/-/extensions-2.32.0.tgz", + "integrity": "sha512-bvhqNqCjmULkjCpjM1fJvDfoL8tzp1IFcMTXN7QJTwqM22ucNe8B4UefKeQOCpjJ3tuIEbp8k9A0fR0CiYtjrQ==", + "license": "Apache-2.0", + "dependencies": { + "@noble/curves": "^1.9.0", + "@scure/base": "^1.2.6", + "@signinwithethereum/siwe": "^4.1.0", + "@x402/core": "~2.32.0", + "ajv": "^8.18.0", + "jose": "^5.9.6", + "tweetnacl": "^1.0.3", + "viem": "^2.48.11", + "zod": "^4.6.6" + } + }, + "node_modules/@x402/fetch": { + "version": "2.32.0", + "resolved": "https://registry.npmjs.org/@x402/fetch/-/fetch-2.32.0.tgz", + "integrity": "sha512-MxDqmBxQz6I5NWUVu90cQ1XRZayAi8oDpGllDwrwihxfAHloE7eqXkNuFC80IRE3BbMwj8h65aBEaOaiq3EBUQ==", + "license": "Apache-2.0", + "dependencies": { + "@x402/core": "~2.32.0" + } + }, + "node_modules/abitype": { + "version": "1.2.3", + "resolved": "https://registry.npmjs.org/abitype/-/abitype-1.2.3.tgz", + "integrity": "sha512-Ofer5QUnuUdTFsBRwARMoWKOH1ND5ehwYhJ3OJ/BQO+StkwQjHw0XyVh4vDttzHB7QOFhPHa/o413PJ82gU/Tg==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/wevm" + }, + "peerDependencies": { + "typescript": ">=5.0.4", + "zod": "^3.22.0 || ^4.0.0" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + }, + "zod": { + "optional": true + } + } + }, + "node_modules/accepts": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/accepts/-/accepts-2.0.0.tgz", + "integrity": "sha512-5cvg6CtKwfgdmVqY1WIiXKc3Q1bkRqGLi+2W/6ao+6Y7gu/RCwRuAhGEzh5B4KlszSuTLgZYuqFqo5bImjNKng==", + "license": "MIT", + "dependencies": { + "mime-types": "^3.0.0", + "negotiator": "^1.0.0" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/ajv": { + "version": "8.20.0", + "resolved": "https://registry.npmjs.org/ajv/-/ajv-8.20.0.tgz", + "integrity": "sha512-Thbli+OlOj+iMPYFBVBfJ3OmCAnaSyNn4M1vz9T6Gka5Jt9ba/HIR56joy65tY6kx/FCF5VXNB819Y7/GUrBGA==", + "license": "MIT", + "dependencies": { + "fast-deep-equal": "^3.1.3", + "fast-uri": "^3.0.1", + "json-schema-traverse": "^1.0.0", + "require-from-string": "^2.0.2" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/epoberezkin" + } + }, + "node_modules/apg-js": { + "version": "4.4.0", + "resolved": "https://registry.npmjs.org/apg-js/-/apg-js-4.4.0.tgz", + "integrity": "sha512-fefmXFknJmtgtNEXfPwZKYkMFX4Fyeyz+fNF6JWp87biGOPslJbCBVU158zvKRZfHBKnJDy8CMM40oLFGkXT8Q==", + "license": "BSD-2-Clause" + }, + "node_modules/body-parser": { + "version": "2.4.0", + "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-2.4.0.tgz", + "integrity": "sha512-Ifk1KcLrxaGt1occQagQNFNNOqRt1LFuehEnHHzB8Z6cRgIxRU1TBaiIsUiCdA+gy5PL7Y1IX31DNKkRmxtXjQ==", + "license": "MIT", + "dependencies": { + "bytes": "^3.1.2", + "content-type": "^2.1.0", + "debug": "^4.4.3", + "http-errors": "^2.0.1", + "iconv-lite": "^0.7.3", + "on-finished": "^2.4.1", + "qs": "^6.16.1", + "raw-body": "^3.0.2", + "type-is": "^2.1.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/bytes": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.2.tgz", + "integrity": "sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/call-bind-apply-helpers": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz", + "integrity": "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/call-bound": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/call-bound/-/call-bound-1.0.4.tgz", + "integrity": "sha512-+ys997U96po4Kx/ABpBCqhA9EuxJaQWDQg7295H4hBphv3IZg0boBKuwYpt4YXp6MZ5AmZQnU/tyMTlRpaSejg==", + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.2", + "get-intrinsic": "^1.3.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/content-disposition": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-2.0.1.tgz", + "integrity": "sha512-e+H0ZXHSWYrENhQzw1LPuP4oF5MzVKmDU6d3hxlvaPEYLLg62MxtQNPRx4SYSuYJSBUgnQIG4HIN2tEtNv7Dog==", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/content-type": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/content-type/-/content-type-2.1.0.tgz", + "integrity": "sha512-mj7UPXE0jaqaOsukNZRUEfEi2AcL7C/vwmwcHV0O97eO1E1pxBZuyjlZrx5seTaNBg1U6+o35wpa35Qfcc+7ag==", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/cookie": { + "version": "0.7.2", + "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.7.2.tgz", + "integrity": "sha512-yki5XnKuf750l50uGTllt6kKILY4nQ1eNIQatoXEByZ5dWgnKqbnqmTrBE5B4N7lrMJKQ2ytWMiTO2o0v6Ew/w==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/cookie-signature": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.2.2.tgz", + "integrity": "sha512-D76uU73ulSXrD1UXF4KE2TMxVVwhsnCgfAyTg9k8P6KGZjlXKrOLe4dJQKI3Bxi5wjesZoFXJWElNWBjPZMbhg==", + "license": "MIT", + "engines": { + "node": ">=6.6.0" + } + }, + "node_modules/debug": { + "version": "4.4.3", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", + "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", + "license": "MIT", + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/depd": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz", + "integrity": "sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/dunder-proto": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz", + "integrity": "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==", + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.1", + "es-errors": "^1.3.0", + "gopd": "^1.2.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/ee-first": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz", + "integrity": "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==", + "license": "MIT" + }, + "node_modules/encodeurl": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-2.0.3.tgz", + "integrity": "sha512-mIteYONiEfc4xWf2F1WXovh1c8npzS00vNeiUPdwFF+QlVJni+gNvpQltLMQhob8rew/bWWc/bGTuUr0EUGt0w==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/es-define-property": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz", + "integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-errors": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz", + "integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-object-atoms": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.2.tgz", + "integrity": "sha512-HWcBoN6NileqtSydK2FqHbS/LoDd2pqrnQHLyJzBj4kOp/ky2MWMN694xOfkK8/SnUsW2DH7EfyVlydKCsm1Zw==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/escape-html": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/escape-html/-/escape-html-1.0.3.tgz", + "integrity": "sha512-NiSupZ4OeuGwr68lGIeym/ksIZMJodUGOSCZ/FSnTxcrekbvqrgdUxlJOMpijaKZVjAJrWrGs/6Jy8OMuyj9ow==", + "license": "MIT" + }, + "node_modules/etag": { + "version": "1.8.1", + "resolved": "https://registry.npmjs.org/etag/-/etag-1.8.1.tgz", + "integrity": "sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/eventemitter3": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/eventemitter3/-/eventemitter3-5.0.1.tgz", + "integrity": "sha512-GWkBvjiSZK87ELrYOSESUYeVIc9mvLLf/nXalMOS5dYrgZq9o5OVkbZAVM06CVxYsCwH9BDZFPlQTlPA1j4ahA==", + "license": "MIT" + }, + "node_modules/express": { + "version": "5.3.0", + "resolved": "https://registry.npmjs.org/express/-/express-5.3.0.tgz", + "integrity": "sha512-qCqy1xSoaugxOD4IVHb1ZWdkvCF2W3aE2okKouWj8VwJ+ztskSiXoBnCSJqfKT+cVPJhuJqe9YLbY425+Zh00g==", + "license": "MIT", + "dependencies": { + "accepts": "^2.0.0", + "body-parser": "^2.3.0", + "content-disposition": "^2.0.1", + "content-type": "^2.0.0", + "cookie": "^0.7.1", + "cookie-signature": "^1.2.1", + "debug": "^4.4.0", + "depd": "^2.0.0", + "encodeurl": "^2.0.0", + "escape-html": "^1.0.3", + "etag": "^1.8.1", + "finalhandler": "^2.1.0", + "fresh": "^2.0.0", + "http-errors": "^2.0.0", + "merge-descriptors": "^2.0.0", + "mime-types": "^3.0.0", + "on-finished": "^2.4.1", + "once": "^1.4.0", + "parseurl": "^1.3.3", + "proxy-addr": "^2.0.8", + "qs": "^6.16.0", + "range-parser": "^1.2.1", + "router": "^2.2.0", + "send": "^1.1.0", + "serve-static": "^2.2.0", + "statuses": "^2.0.1", + "type-is": "^2.1.0", + "vary": "^1.1.2" + }, + "engines": { + "node": ">= 18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/fast-deep-equal": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz", + "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==", + "license": "MIT" + }, + "node_modules/fast-uri": { + "version": "3.1.9", + "resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.9.tgz", + "integrity": "sha512-hS/0Wt3Ya043oKXs0sIxrMpKQITXhMLIrVAKKXi4gozGC9v7YRWVnXIZzjNPTO02M9BdxLCWqK1yRXgNziVyJQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/fastify" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/fastify" + } + ], + "license": "BSD-3-Clause" + }, + "node_modules/finalhandler": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-2.1.1.tgz", + "integrity": "sha512-S8KoZgRZN+a5rNwqTxlZZePjT/4cnm0ROV70LedRHZ0p8u9fRID0hJUZQpkKLzro8LfmC8sx23bY6tVNxv8pQA==", + "license": "MIT", + "dependencies": { + "debug": "^4.4.0", + "encodeurl": "^2.0.0", + "escape-html": "^1.0.3", + "on-finished": "^2.4.1", + "parseurl": "^1.3.3", + "statuses": "^2.0.1" + }, + "engines": { + "node": ">= 18.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/forwarded": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/forwarded/-/forwarded-0.2.0.tgz", + "integrity": "sha512-buRG0fpBtRHSTCOASe6hD258tEubFoRLb4ZNA6NxMVHNw2gOcwHo9wyablzMzOA5z9xA9L1KNjk/Nt6MT9aYow==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/fresh": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/fresh/-/fresh-2.0.0.tgz", + "integrity": "sha512-Rx/WycZ60HOaqLKAi6cHRKKI7zxWbJ31MhntmtwMoaTeF7XFH9hhBp8vITaMidfljRQ6eYWCKkaTK+ykVJHP2A==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/function-bind": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz", + "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/get-intrinsic": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz", + "integrity": "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==", + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.2", + "es-define-property": "^1.0.1", + "es-errors": "^1.3.0", + "es-object-atoms": "^1.1.1", + "function-bind": "^1.1.2", + "get-proto": "^1.0.1", + "gopd": "^1.2.0", + "has-symbols": "^1.1.0", + "hasown": "^2.0.2", + "math-intrinsics": "^1.1.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/get-proto": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/get-proto/-/get-proto-1.0.1.tgz", + "integrity": "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==", + "license": "MIT", + "dependencies": { + "dunder-proto": "^1.0.1", + "es-object-atoms": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/gopd": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz", + "integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-symbols": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.1.0.tgz", + "integrity": "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/hasown": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.4.tgz", + "integrity": "sha512-T2UbfbBEF32wiepXIsMlTW9+dDYC6wMh/t/vYA4tuOMKqWz/n3vr1NFSxQiyP+zk2mXsoMA/i/7qV6LKut1t1A==", + "license": "MIT", + "dependencies": { + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/http-errors": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.1.tgz", + "integrity": "sha512-4FbRdAX+bSdmo4AUFuS0WNiPz8NgFt+r8ThgNWmlrjQjt1Q7ZR9+zTlce2859x4KSXrwIsaeTqDoKQmtP8pLmQ==", + "license": "MIT", + "dependencies": { + "depd": "~2.0.0", + "inherits": "~2.0.4", + "setprototypeof": "~1.2.0", + "statuses": "~2.0.2", + "toidentifier": "~1.0.1" + }, + "engines": { + "node": ">= 0.8" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/iconv-lite": { + "version": "0.7.3", + "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.7.3.tgz", + "integrity": "sha512-IKXpvIzjnC9XTAUbVBcMfGS0EPaIXtW6v+zr+RRp+hqULEpo0owZax6wyRwPOJbWbzjYspQwusTsfVr0ifh4uQ==", + "license": "MIT", + "dependencies": { + "safer-buffer": ">= 2.1.2 < 3.0.0" + }, + "engines": { + "node": ">=0.10.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/inherits": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", + "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", + "license": "ISC" + }, + "node_modules/ipaddr.js": { + "version": "1.9.1", + "resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-1.9.1.tgz", + "integrity": "sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g==", + "license": "MIT", + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/is-promise": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/is-promise/-/is-promise-4.0.0.tgz", + "integrity": "sha512-hvpoI6korhJMnej285dSg6nu1+e6uxs7zG3BYAm5byqDsgJNWwxzM6z6iZiAgQR4TJ30JmBTOwqZUw3WlyH3AQ==", + "license": "MIT" + }, + "node_modules/isows": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/isows/-/isows-1.0.7.tgz", + "integrity": "sha512-I1fSfDCZL5P0v33sVqeTDSpcstAg/N+wF5HS033mogOVIp4B+oHC7oOCsA3axAbBSGTJ8QubbNmnIRN/h8U7hg==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/wevm" + } + ], + "license": "MIT", + "peerDependencies": { + "ws": "*" + } + }, + "node_modules/jose": { + "version": "5.10.0", + "resolved": "https://registry.npmjs.org/jose/-/jose-5.10.0.tgz", + "integrity": "sha512-s+3Al/p9g32Iq+oqXxkW//7jk2Vig6FF1CFqzVXoTUXt2qz89YWbL+OwS17NFYEvxC35n0FKeGO2LGYSxeM2Gg==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/panva" + } + }, + "node_modules/json-schema-traverse": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz", + "integrity": "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==", + "license": "MIT" + }, + "node_modules/math-intrinsics": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz", + "integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/media-typer": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/media-typer/-/media-typer-1.1.1.tgz", + "integrity": "sha512-yz3xRaG20c6/BOzvYoDaGtPmGscs7YivItZEEqe6GbwNfHuxu9YNmvnEkMzKldAGY4/80pRcQRZSEnhquk9XuQ==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/merge-descriptors": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-2.0.0.tgz", + "integrity": "sha512-Snk314V5ayFLhp3fkUREub6WtjBfPdCPY1Ln8/8munuLuiYhsABgBVWsozAG+MWMbVEvcdcpbi9R7ww22l9Q3g==", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/mime-db": { + "version": "1.54.0", + "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.54.0.tgz", + "integrity": "sha512-aU5EJuIN2WDemCcAp2vFBfp/m4EAhWJnUNSSw0ixs7/kXbd6Pg64EmwJkNdFhB8aWt1sH2CTXrLxo/iAGV3oPQ==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/mime-types": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-3.0.2.tgz", + "integrity": "sha512-Lbgzdk0h4juoQ9fCKXW4by0UJqj+nOOrI9MJ1sSj4nI8aI2eo1qmvQEie4VD1glsS250n15LsWsYtCugiStS5A==", + "license": "MIT", + "dependencies": { + "mime-db": "^1.54.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", + "license": "MIT" + }, + "node_modules/negotiator": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/negotiator/-/negotiator-1.1.0.tgz", + "integrity": "sha512-NMPBRMJgiQHjbd8phG3Vebdx4kZ1H121rbl5IkMqeOsahptB9BKo/d7oJ3zTXqTgagn2bWlNSXkh0QUGM31RYg==", + "license": "MIT", + "dependencies": { + "content-type": "^2.1.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/object-inspect": { + "version": "1.14.0", + "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.14.0.tgz", + "integrity": "sha512-IVgHNlp/jwQX271+Xzoq9LZNTWXxZK+cEOrGBOBxXNbn7fapnZ+Ts6TVMgNOuAezwG2wdtnMX97tTPK6VEnuOQ==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/on-finished": { + "version": "2.4.2", + "resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.4.2.tgz", + "integrity": "sha512-ATWUv387i+nLD49EiDoOft5scf32Vsdz3ktrQJG9bi7jRFmaXTssvyvj1EmeKVVgvesbqUtvQQvaS2TpTukAZQ==", + "license": "MIT", + "dependencies": { + "ee-first": "1.1.1" + }, + "engines": { + "node": ">= 0.8" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/once": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", + "integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==", + "license": "ISC", + "dependencies": { + "wrappy": "1" + } + }, + "node_modules/ox": { + "version": "0.14.67", + "resolved": "https://registry.npmjs.org/ox/-/ox-0.14.67.tgz", + "integrity": "sha512-6v6UlwgsmiyTujZp0aVDuN8uIBAtl/QZadBADFRZ2zp1+CM9TqDzd+rPKJ5PYvWPlCvz8JvoO9dTr42+1PhBhA==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/wevm" + } + ], + "license": "MIT", + "dependencies": { + "@adraffy/ens-normalize": "^1.11.0", + "@noble/ciphers": "^1.3.0", + "@noble/curves": "1.9.1", + "@noble/hashes": "^1.8.0", + "@scure/bip32": "^1.7.0", + "@scure/bip39": "^1.6.0", + "abitype": "^1.2.3", + "eventemitter3": "5.0.1" + }, + "peerDependencies": { + "typescript": ">=5.4.0" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + } + } + }, + "node_modules/ox/node_modules/@noble/curves": { + "version": "1.9.1", + "resolved": "https://registry.npmjs.org/@noble/curves/-/curves-1.9.1.tgz", + "integrity": "sha512-k11yZxZg+t+gWvBbIswW0yoJlu8cHOC7dhunwOzoWH/mXGBiYyR4YY6hAEK/3EUs4UpB8la1RfdRpeGsFHkWsA==", + "license": "MIT", + "dependencies": { + "@noble/hashes": "1.8.0" + }, + "engines": { + "node": "^14.21.3 || >=16" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, + "node_modules/parseurl": { + "version": "1.3.3", + "resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz", + "integrity": "sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/path-to-regexp": { + "version": "8.4.2", + "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-8.4.2.tgz", + "integrity": "sha512-qRcuIdP69NPm4qbACK+aDogI5CBDMi1jKe0ry5rSQJz8JVLsC7jV8XpiJjGRLLol3N+R5ihGYcrPLTno6pAdBA==", + "license": "MIT", + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/proxy-addr": { + "version": "2.0.8", + "resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.8.tgz", + "integrity": "sha512-5nnx0yGyVUcY6t9RnWcARWtwT9F1D8O9rt08htPvnd49W1IgZtmLkhu9WfMzQj1cFxjHIO6connUNVW5k7AVyQ==", + "license": "MIT", + "dependencies": { + "forwarded": "0.2.0", + "ipaddr.js": "1.9.1" + }, + "engines": { + "node": ">= 0.10" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/qs": { + "version": "6.17.1", + "resolved": "https://registry.npmjs.org/qs/-/qs-6.17.1.tgz", + "integrity": "sha512-jd3COkaKVgGUW+ZHyEHCG9bH7RoaaiWuMgzsIBjUMVjLAaWGWpoUAVwljVvBHxRu/2qEHnadLGZrkutYUBPQJA==", + "license": "BSD-3-Clause", + "dependencies": { + "es-define-property": "^1.0.1", + "side-channel": "^1.1.1" + }, + "engines": { + "node": ">=0.6" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/range-parser": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.3.0.tgz", + "integrity": "sha512-hek2mFQpPuI4E1BBKrSto+BU3e3x4xuarsbiwr3+lf7p44juvFMV0XFWQAP3xUyqXA4RrXLIoaSUGbSt056ZMw==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/raw-body": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/raw-body/-/raw-body-3.0.2.tgz", + "integrity": "sha512-K5zQjDllxWkf7Z5xJdV0/B0WTNqx6vxG70zJE4N0kBs4LovmEYWJzQGxC9bS9RAKu3bgM40lrd5zoLJ12MQ5BA==", + "license": "MIT", + "dependencies": { + "bytes": "~3.1.2", + "http-errors": "~2.0.1", + "iconv-lite": "~0.7.0", + "unpipe": "~1.0.0" + }, + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/require-from-string": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/require-from-string/-/require-from-string-2.0.2.tgz", + "integrity": "sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/router": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/router/-/router-2.3.0.tgz", + "integrity": "sha512-bpowRfGjEPe8t9R6fJIzhwmyCGAXwKvxBUsgJm+bJukwdcWmUXbMo7p22w7aYmQBPQTUMNqMV39YX0kMou3z8w==", + "license": "MIT", + "dependencies": { + "debug": "^4.4.0", + "depd": "^2.0.0", + "is-promise": "^4.0.0", + "parseurl": "^1.3.3", + "path-to-regexp": "^8.0.0" + }, + "engines": { + "node": ">= 18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/safer-buffer": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", + "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==", + "license": "MIT" + }, + "node_modules/send": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/send/-/send-1.2.1.tgz", + "integrity": "sha512-1gnZf7DFcoIcajTjTwjwuDjzuz4PPcY2StKPlsGAQ1+YH20IRVrBaXSWmdjowTJ6u8Rc01PoYOGHXfP1mYcZNQ==", + "license": "MIT", + "dependencies": { + "debug": "^4.4.3", + "encodeurl": "^2.0.0", + "escape-html": "^1.0.3", + "etag": "^1.8.1", + "fresh": "^2.0.0", + "http-errors": "^2.0.1", + "mime-types": "^3.0.2", + "ms": "^2.1.3", + "on-finished": "^2.4.1", + "range-parser": "^1.2.1", + "statuses": "^2.0.2" + }, + "engines": { + "node": ">= 18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/serve-static": { + "version": "2.2.1", + "resolved": "https://registry.npmjs.org/serve-static/-/serve-static-2.2.1.tgz", + "integrity": "sha512-xRXBn0pPqQTVQiC8wyQrKs2MOlX24zQ0POGaj0kultvoOCstBQM5yvOhAVSUwOMjQtTvsPWoNCHfPGwaaQJhTw==", + "license": "MIT", + "dependencies": { + "encodeurl": "^2.0.0", + "escape-html": "^1.0.3", + "parseurl": "^1.3.3", + "send": "^1.2.0" + }, + "engines": { + "node": ">= 18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/setprototypeof": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.2.0.tgz", + "integrity": "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==", + "license": "ISC" + }, + "node_modules/side-channel": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.1.1.tgz", + "integrity": "sha512-6x6dK6zJdpTzF4sQeNYxwtvBzf6Eg4GtlesS94HOvTudUeyK2WXAaIfmDgsyslYrRBeFIlsi54AYsFGUuhmvrQ==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "object-inspect": "^1.13.4", + "side-channel-list": "^1.0.1", + "side-channel-map": "^1.0.1", + "side-channel-weakmap": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-list": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/side-channel-list/-/side-channel-list-1.0.1.tgz", + "integrity": "sha512-mjn/0bi/oUURjc5Xl7IaWi/OJJJumuoJFQJfDDyO46+hBWsfaVM65TBHq2eoZBhzl9EchxOijpkbRC8SVBQU0w==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "object-inspect": "^1.13.4" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-map": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/side-channel-map/-/side-channel-map-1.0.1.tgz", + "integrity": "sha512-VCjCNfgMsby3tTdo02nbjtM/ewra6jPHmpThenkTYh8pG9ucZ/1P8So4u4FGBek/BjpOVsDCMoLA/iuBKIFXRA==", + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.2", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.5", + "object-inspect": "^1.13.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-weakmap": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/side-channel-weakmap/-/side-channel-weakmap-1.0.2.tgz", + "integrity": "sha512-WPS/HvHQTYnHisLo9McqBHOJk2FkHO/tlpvldyrnem4aeQp4hai3gythswg6p01oSoTl58rcpiFAjF2br2Ak2A==", + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.2", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.5", + "object-inspect": "^1.13.3", + "side-channel-map": "^1.0.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/statuses": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.2.tgz", + "integrity": "sha512-DvEy55V3DB7uknRo+4iOGT5fP1slR8wQohVdknigZPMpMstaKJQWhwiYBACJE3Ul2pTnATihhBYnRhZQHGBiRw==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/toidentifier": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/toidentifier/-/toidentifier-1.0.1.tgz", + "integrity": "sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA==", + "license": "MIT", + "engines": { + "node": ">=0.6" + } + }, + "node_modules/tweetnacl": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/tweetnacl/-/tweetnacl-1.0.3.tgz", + "integrity": "sha512-6rt+RN7aOi1nGMyC4Xa5DdYiukl2UWCbcJft7YhxReBGQD7OAM8Pbxw6YMo4r2diNEA8FEmu32YOn9rhaiE5yw==", + "license": "Unlicense" + }, + "node_modules/type-is": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/type-is/-/type-is-2.1.0.tgz", + "integrity": "sha512-faYHw0anBbc/kWF3zFTEnxSFOAGUX9GFbOBthvDdLsIlEoWOFOtS0zgCiQYwIskL9iGXZL3kAXD8OoZ4GmMATA==", + "license": "MIT", + "dependencies": { + "content-type": "^2.0.0", + "media-typer": "^1.1.0", + "mime-types": "^3.0.0" + }, + "engines": { + "node": ">= 18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/unpipe": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz", + "integrity": "sha512-pjy2bYhSsufwWlKwPc+l3cN7+wuJlK6uz0YdJEOlQDbl6jo/YlPi4mb8agUkVC8BF7V8NuzeyPNqRksA3hztKQ==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/vary": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz", + "integrity": "sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/viem": { + "version": "2.58.7", + "resolved": "https://registry.npmjs.org/viem/-/viem-2.58.7.tgz", + "integrity": "sha512-9s29POkcUOdlvEN5ePdBTBryhoEQE+ikXuuwjvJRqTc99yCMVkVqwvrjogYpTaJLo2rIrgOEjAglbdr6DCRdkg==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/wevm" + } + ], + "license": "MIT", + "dependencies": { + "@noble/curves": "1.9.1", + "@noble/hashes": "1.8.0", + "@scure/bip32": "1.7.0", + "@scure/bip39": "1.6.0", + "abitype": "1.2.3", + "isows": "1.0.7", + "ox": "0.14.67", + "ws": "8.21.0" + }, + "peerDependencies": { + "mppx": ">=0.17.0", + "typescript": ">=5.0.4" + }, + "peerDependenciesMeta": { + "mppx": { + "optional": true + }, + "typescript": { + "optional": true + } + } + }, + "node_modules/viem/node_modules/@noble/curves": { + "version": "1.9.1", + "resolved": "https://registry.npmjs.org/@noble/curves/-/curves-1.9.1.tgz", + "integrity": "sha512-k11yZxZg+t+gWvBbIswW0yoJlu8cHOC7dhunwOzoWH/mXGBiYyR4YY6hAEK/3EUs4UpB8la1RfdRpeGsFHkWsA==", + "license": "MIT", + "dependencies": { + "@noble/hashes": "1.8.0" + }, + "engines": { + "node": "^14.21.3 || >=16" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, + "node_modules/wrappy": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", + "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==", + "license": "ISC" + }, + "node_modules/ws": { + "version": "8.21.0", + "resolved": "https://registry.npmjs.org/ws/-/ws-8.21.0.tgz", + "integrity": "sha512-Vsp28b7DRcimFQvrqu2Wek3z1iYxDCWqHYB8Qsnk/S4RfaCQzPGPyBNuVjJV3cd6UiKtUtp6sNM77gWvzcCH+g==", + "license": "MIT", + "engines": { + "node": ">=10.0.0" + }, + "peerDependencies": { + "bufferutil": "^4.0.1", + "utf-8-validate": ">=5.0.2" + }, + "peerDependenciesMeta": { + "bufferutil": { + "optional": true + }, + "utf-8-validate": { + "optional": true + } + } + }, + "node_modules/zod": { + "version": "4.6.7", + "resolved": "https://registry.npmjs.org/zod/-/zod-4.6.7.tgz", + "integrity": "sha512-g8W2D2kU6a8untc053fX1uVBKzM7yqAxW/3zwk83+6RyF2+SKOuV+c0wBDhUwzV1PaGapmZH+rmcUzPf+3CGwg==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/colinhacks" + } + } + } +} diff --git a/base/demo/package.json b/base/demo/package.json new file mode 100755 index 0000000..06e2469 --- /dev/null +++ b/base/demo/package.json @@ -0,0 +1,19 @@ +{ + "name": "nirium-base-demo", + "version": "1.0.0", + "private": true, + "description": "Reference x402 exact payment on Base with a Nirium payment binding", + "type": "module", + "license": "Apache-2.0", + "engines": { + "node": ">=20" + }, + "dependencies": { + "@x402/core": "2.32.0", + "@x402/evm": "2.32.0", + "@x402/express": "2.32.0", + "@x402/fetch": "2.32.0", + "express": "5.3.0", + "viem": "2.58.7" + } +} diff --git a/base/demo/server.mjs b/base/demo/server.mjs new file mode 100755 index 0000000..4c9567b --- /dev/null +++ b/base/demo/server.mjs @@ -0,0 +1,67 @@ +// server.mjs - minimal x402 v2 seller: GET /paid costs 0.01 USDC, settled by PayAI. +// +// Env: +// NIRIUM_EVM_PAYTO (required) address that receives the USDC +// NIRIUM_NETWORK eip155:84532 (default, Base Sepolia) | eip155:8453 (Base mainnet) +// NIRIUM_AMOUNT atomic USDC units, default "10000" (= 0.01 USDC) +// PORT default 4021 +// FACILITATOR_URL default https://facilitator.payai.network +// +// Holds no keys: the seller only receives. PayAI verifies and settles. +import express from "express"; +import { isAddress } from "viem"; +import { paymentMiddleware, x402ResourceServer } from "@x402/express"; +import { ExactEvmScheme } from "@x402/evm/exact/server"; +import { HTTPFacilitatorClient } from "@x402/core/server"; +import { getNetwork, PAYAI_FACILITATOR } from "./networks.mjs"; + +const network = process.env.NIRIUM_NETWORK || "eip155:84532"; +const net = getNetwork(network); +const payTo = process.env.NIRIUM_EVM_PAYTO; +const amount = process.env.NIRIUM_AMOUNT || "10000"; +const port = Number(process.env.PORT || 4021); +const facilitatorUrl = process.env.FACILITATOR_URL || PAYAI_FACILITATOR; + +if (!payTo || !isAddress(payTo)) { + console.error("NIRIUM_EVM_PAYTO must be set to a valid 0x address"); + process.exit(2); +} +if (!/^\d+$/.test(amount)) { + console.error("NIRIUM_AMOUNT must be an integer in atomic units"); + process.exit(2); +} + +const facilitator = new HTTPFacilitatorClient({ url: facilitatorUrl }); +const resourceServer = new x402ResourceServer(facilitator).register(network, new ExactEvmScheme()); + +const app = express(); +app.use( + paymentMiddleware( + { + "GET /paid": { + accepts: [ + { + scheme: "exact", + network, + payTo, + // Explicit asset + EIP-712 domain from our table (it matches @x402/evm 2.32.0 DEFAULT_ASSETS). + price: { amount, asset: net.usdc, extra: { ...net.extra } }, + maxTimeoutSeconds: 120, + }, + ], + description: "Nirium selftest resource", + mimeType: "application/json", + }, + }, + resourceServer, + ), +); + +app.get("/paid", (req, res) => { + res.json({ ok: true, resource: "nirium-selftest", network, at: new Date().toISOString() }); +}); + +app.listen(port, () => { + console.log(`seller on http://localhost:${port}/paid network=${network} asset=${net.usdc} amount=${amount} payTo=${payTo} facilitator=${facilitatorUrl}`); + if (net.mainnet) console.log("WARNING: mainnet. Real USDC."); +}); diff --git a/base/fixtures/payai-bad-amount.json b/base/fixtures/payai-bad-amount.json new file mode 100644 index 0000000..f638167 --- /dev/null +++ b/base/fixtures/payai-bad-amount.json @@ -0,0 +1,32 @@ +{ + "version": "nirium-payment-binding-v1", + "content_sha256": "9937dbe714cfc3b38236186f01a2d953f87e7587bf118be0a126ffab67ddf42d", + "record": { + "labels": [ + "selftest" + ], + "payment": { + "amount": "1001", + "asset": "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913", + "decimals": 6, + "from": "0x6417804584b589da23a31e98ccd0077812fe2da2", + "locator": { + "index": 281, + "kind": "evm-log" + }, + "network": "eip155:8453", + "to": "0x73fc43d426a89577c7b58f5fee50ec95d4396079", + "tx": "0x1cf6ef8fbe84f00a4e1599639cc01f7b29b8924ed2f32807e1dcc46fe758cf7c", + "x402": { + "nonce": "0xa515b9fa790e20c71b3e582059e582b2e92db36d7e26d7ced33bdd3a16da8852", + "resource": "unknown (third-party tx, test fixture only)", + "scheme": "exact" + } + }, + "purpose": { + "note": "verifier test against a third-party PayAI settlement, not ours", + "ref": "fixture-base-2026-11-30" + } + }, + "network": "eip155:8453" +} \ No newline at end of file diff --git a/base/fixtures/payai-bad-content-sha256.json b/base/fixtures/payai-bad-content-sha256.json new file mode 100644 index 0000000..2524102 --- /dev/null +++ b/base/fixtures/payai-bad-content-sha256.json @@ -0,0 +1,32 @@ +{ + "version": "nirium-payment-binding-v1", + "content_sha256": "00a0d3e664e378b5a5817e1b07f4dcc7e4528814d1cd778d229f3b4fd230fc9f", + "record": { + "labels": [ + "selftest" + ], + "payment": { + "amount": "1000", + "asset": "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913", + "decimals": 6, + "from": "0x6417804584b589da23a31e98ccd0077812fe2da2", + "locator": { + "index": 281, + "kind": "evm-log" + }, + "network": "eip155:8453", + "to": "0x73fc43d426a89577c7b58f5fee50ec95d4396079", + "tx": "0x1cf6ef8fbe84f00a4e1599639cc01f7b29b8924ed2f32807e1dcc46fe758cf7c", + "x402": { + "nonce": "0xa515b9fa790e20c71b3e582059e582b2e92db36d7e26d7ced33bdd3a16da8852", + "resource": "unknown (third-party tx, test fixture only)", + "scheme": "exact" + } + }, + "purpose": { + "note": "verifier test against a third-party PayAI settlement, not ours", + "ref": "fixture-base-2026-11-30" + } + }, + "network": "eip155:8453" +} \ No newline at end of file diff --git a/base/fixtures/payai-bad-index.json b/base/fixtures/payai-bad-index.json new file mode 100644 index 0000000..17e9832 --- /dev/null +++ b/base/fixtures/payai-bad-index.json @@ -0,0 +1,32 @@ +{ + "version": "nirium-payment-binding-v1", + "content_sha256": "7f0ab338dc85d9cb32b7f7afe202062c488fd6e38ab2bfa73b89d1c7b55450c6", + "record": { + "labels": [ + "selftest" + ], + "payment": { + "amount": "1000", + "asset": "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913", + "decimals": 6, + "from": "0x6417804584b589da23a31e98ccd0077812fe2da2", + "locator": { + "index": 280, + "kind": "evm-log" + }, + "network": "eip155:8453", + "to": "0x73fc43d426a89577c7b58f5fee50ec95d4396079", + "tx": "0x1cf6ef8fbe84f00a4e1599639cc01f7b29b8924ed2f32807e1dcc46fe758cf7c", + "x402": { + "nonce": "0xa515b9fa790e20c71b3e582059e582b2e92db36d7e26d7ced33bdd3a16da8852", + "resource": "unknown (third-party tx, test fixture only)", + "scheme": "exact" + } + }, + "purpose": { + "note": "verifier test against a third-party PayAI settlement, not ours", + "ref": "fixture-base-2026-11-30" + } + }, + "network": "eip155:8453" +} \ No newline at end of file diff --git a/base/fixtures/payai-bad-nonce.json b/base/fixtures/payai-bad-nonce.json new file mode 100644 index 0000000..6b0acec --- /dev/null +++ b/base/fixtures/payai-bad-nonce.json @@ -0,0 +1,32 @@ +{ + "version": "nirium-payment-binding-v1", + "content_sha256": "320bd996db2c6fcf85375156a3ea926db6f5aa38d58b85dd45fecd357a8ae8e7", + "record": { + "labels": [ + "selftest" + ], + "payment": { + "amount": "1000", + "asset": "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913", + "decimals": 6, + "from": "0x6417804584b589da23a31e98ccd0077812fe2da2", + "locator": { + "index": 281, + "kind": "evm-log" + }, + "network": "eip155:8453", + "to": "0x73fc43d426a89577c7b58f5fee50ec95d4396079", + "tx": "0x1cf6ef8fbe84f00a4e1599639cc01f7b29b8924ed2f32807e1dcc46fe758cf7c", + "x402": { + "nonce": "0x0000000000000000000000000000000000000000000000000000000000000000", + "resource": "unknown (third-party tx, test fixture only)", + "scheme": "exact" + } + }, + "purpose": { + "note": "verifier test against a third-party PayAI settlement, not ours", + "ref": "fixture-base-2026-11-30" + } + }, + "network": "eip155:8453" +} \ No newline at end of file diff --git a/base/fixtures/payai-bad-to.json b/base/fixtures/payai-bad-to.json new file mode 100644 index 0000000..ddbe02e --- /dev/null +++ b/base/fixtures/payai-bad-to.json @@ -0,0 +1,32 @@ +{ + "version": "nirium-payment-binding-v1", + "content_sha256": "8367424c2b222d26147ea83d5b464bab622ea6aa2ce78cb16f0b96049afde255", + "record": { + "labels": [ + "selftest" + ], + "payment": { + "amount": "1000", + "asset": "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913", + "decimals": 6, + "from": "0x6417804584b589da23a31e98ccd0077812fe2da2", + "locator": { + "index": 281, + "kind": "evm-log" + }, + "network": "eip155:8453", + "to": "0xc6699d2aada6c36dfea5c248dd70f9cb0235cb63", + "tx": "0x1cf6ef8fbe84f00a4e1599639cc01f7b29b8924ed2f32807e1dcc46fe758cf7c", + "x402": { + "nonce": "0xa515b9fa790e20c71b3e582059e582b2e92db36d7e26d7ced33bdd3a16da8852", + "resource": "unknown (third-party tx, test fixture only)", + "scheme": "exact" + } + }, + "purpose": { + "note": "verifier test against a third-party PayAI settlement, not ours", + "ref": "fixture-base-2026-11-30" + } + }, + "network": "eip155:8453" +} \ No newline at end of file diff --git a/base/fixtures/payai-ok.json b/base/fixtures/payai-ok.json new file mode 100644 index 0000000..f687af7 --- /dev/null +++ b/base/fixtures/payai-ok.json @@ -0,0 +1,32 @@ +{ + "version": "nirium-payment-binding-v1", + "content_sha256": "22a0d3e664e378b5a5817e1b07f4dcc7e4528814d1cd778d229f3b4fd230fc9f", + "record": { + "labels": [ + "selftest" + ], + "payment": { + "amount": "1000", + "asset": "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913", + "decimals": 6, + "from": "0x6417804584b589da23a31e98ccd0077812fe2da2", + "locator": { + "index": 281, + "kind": "evm-log" + }, + "network": "eip155:8453", + "to": "0x73fc43d426a89577c7b58f5fee50ec95d4396079", + "tx": "0x1cf6ef8fbe84f00a4e1599639cc01f7b29b8924ed2f32807e1dcc46fe758cf7c", + "x402": { + "nonce": "0xa515b9fa790e20c71b3e582059e582b2e92db36d7e26d7ced33bdd3a16da8852", + "resource": "unknown (third-party tx, test fixture only)", + "scheme": "exact" + } + }, + "purpose": { + "note": "verifier test against a third-party PayAI settlement, not ours", + "ref": "fixture-base-2026-11-30" + } + }, + "network": "eip155:8453" +} \ No newline at end of file diff --git a/base/fixtures/payai-sig-ephemeral.json b/base/fixtures/payai-sig-ephemeral.json new file mode 100644 index 0000000..0e08355 --- /dev/null +++ b/base/fixtures/payai-sig-ephemeral.json @@ -0,0 +1,38 @@ +{ + "version": "nirium-payment-binding-v1", + "content_sha256": "22a0d3e664e378b5a5817e1b07f4dcc7e4528814d1cd778d229f3b4fd230fc9f", + "record": { + "labels": [ + "selftest" + ], + "payment": { + "amount": "1000", + "asset": "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913", + "decimals": 6, + "from": "0x6417804584b589da23a31e98ccd0077812fe2da2", + "locator": { + "index": 281, + "kind": "evm-log" + }, + "network": "eip155:8453", + "to": "0x73fc43d426a89577c7b58f5fee50ec95d4396079", + "tx": "0x1cf6ef8fbe84f00a4e1599639cc01f7b29b8924ed2f32807e1dcc46fe758cf7c", + "x402": { + "nonce": "0xa515b9fa790e20c71b3e582059e582b2e92db36d7e26d7ced33bdd3a16da8852", + "resource": "unknown (third-party tx, test fixture only)", + "scheme": "exact" + } + }, + "purpose": { + "note": "verifier test against a third-party PayAI settlement, not ours", + "ref": "fixture-base-2026-11-30" + } + }, + "network": "eip155:8453", + "agent": { + "alg": "eip191-secp256k1", + "key": "0x3586649b219970f933485839a465Cc2bB3959b10", + "statement": "nirium-audit-v1:22a0d3e664e378b5a5817e1b07f4dcc7e4528814d1cd778d229f3b4fd230fc9f", + "signature": "0x3e235662a4396f96f88987a94b4bb0a13c344eea76a399ecc87fe5487e6de8c437e5b0a3673ca8f5e85d5fa6a5f29b0788c33e88fdd13a9b71defa4445fec6fd1c" + } +} \ No newline at end of file diff --git a/base/fixtures/payai-sig-forged-payer.json b/base/fixtures/payai-sig-forged-payer.json new file mode 100644 index 0000000..3d3dc9b --- /dev/null +++ b/base/fixtures/payai-sig-forged-payer.json @@ -0,0 +1,38 @@ +{ + "version": "nirium-payment-binding-v1", + "content_sha256": "22a0d3e664e378b5a5817e1b07f4dcc7e4528814d1cd778d229f3b4fd230fc9f", + "record": { + "labels": [ + "selftest" + ], + "payment": { + "amount": "1000", + "asset": "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913", + "decimals": 6, + "from": "0x6417804584b589da23a31e98ccd0077812fe2da2", + "locator": { + "index": 281, + "kind": "evm-log" + }, + "network": "eip155:8453", + "to": "0x73fc43d426a89577c7b58f5fee50ec95d4396079", + "tx": "0x1cf6ef8fbe84f00a4e1599639cc01f7b29b8924ed2f32807e1dcc46fe758cf7c", + "x402": { + "nonce": "0xa515b9fa790e20c71b3e582059e582b2e92db36d7e26d7ced33bdd3a16da8852", + "resource": "unknown (third-party tx, test fixture only)", + "scheme": "exact" + } + }, + "purpose": { + "note": "verifier test against a third-party PayAI settlement, not ours", + "ref": "fixture-base-2026-11-30" + } + }, + "network": "eip155:8453", + "agent": { + "alg": "eip191-secp256k1", + "key": "0x6417804584b589da23a31e98ccd0077812fe2da2", + "statement": "nirium-audit-v1:22a0d3e664e378b5a5817e1b07f4dcc7e4528814d1cd778d229f3b4fd230fc9f", + "signature": "0x3e235662a4396f96f88987a94b4bb0a13c344eea76a399ecc87fe5487e6de8c437e5b0a3673ca8f5e85d5fa6a5f29b0788c33e88fdd13a9b71defa4445fec6fd1c" + } +} \ No newline at end of file diff --git a/base/fixtures/payai-sig-tampered.json b/base/fixtures/payai-sig-tampered.json new file mode 100644 index 0000000..6accaa6 --- /dev/null +++ b/base/fixtures/payai-sig-tampered.json @@ -0,0 +1,38 @@ +{ + "version": "nirium-payment-binding-v1", + "content_sha256": "22a0d3e664e378b5a5817e1b07f4dcc7e4528814d1cd778d229f3b4fd230fc9f", + "record": { + "labels": [ + "selftest" + ], + "payment": { + "amount": "1001", + "asset": "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913", + "decimals": 6, + "from": "0x6417804584b589da23a31e98ccd0077812fe2da2", + "locator": { + "index": 281, + "kind": "evm-log" + }, + "network": "eip155:8453", + "to": "0x73fc43d426a89577c7b58f5fee50ec95d4396079", + "tx": "0x1cf6ef8fbe84f00a4e1599639cc01f7b29b8924ed2f32807e1dcc46fe758cf7c", + "x402": { + "nonce": "0xa515b9fa790e20c71b3e582059e582b2e92db36d7e26d7ced33bdd3a16da8852", + "resource": "unknown (third-party tx, test fixture only)", + "scheme": "exact" + } + }, + "purpose": { + "note": "verifier test against a third-party PayAI settlement, not ours", + "ref": "fixture-base-2026-11-30" + } + }, + "network": "eip155:8453", + "agent": { + "alg": "eip191-secp256k1", + "key": "0x3586649b219970f933485839a465Cc2bB3959b10", + "statement": "nirium-audit-v1:22a0d3e664e378b5a5817e1b07f4dcc7e4528814d1cd778d229f3b4fd230fc9f", + "signature": "0x3e235662a4396f96f88987a94b4bb0a13c344eea76a399ecc87fe5487e6de8c437e5b0a3673ca8f5e85d5fa6a5f29b0788c33e88fdd13a9b71defa4445fec6fd1c" + } +} \ No newline at end of file diff --git a/base/make-fixtures.mjs b/base/make-fixtures.mjs new file mode 100755 index 0000000..5cdf604 --- /dev/null +++ b/base/make-fixtures.mjs @@ -0,0 +1,52 @@ +// Builds test fixtures from a real third-party PayAI settlement on Base mainnet (block 64356193, +// 30-nov-2026, settled through Multicall3). Not ours: it only proves the verifier against the chain. +// The signature cases use a throwaway key generated in memory, never saved. +import { mkdirSync, writeFileSync } from "node:fs"; +import { generatePrivateKey, privateKeyToAccount } from "viem/accounts"; +import { contentSha256, STATEMENT_PREFIX, VERSION } from "./verify-evm-receipt.mjs"; + +const clone = (o) => JSON.parse(JSON.stringify(o)); +const record = { + labels: ["selftest"], + payment: { + amount: "1000", + asset: "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913", + decimals: 6, + from: "0x6417804584b589da23a31e98ccd0077812fe2da2", + locator: { index: 281, kind: "evm-log" }, + network: "eip155:8453", + to: "0x73fc43d426a89577c7b58f5fee50ec95d4396079", + tx: "0x1cf6ef8fbe84f00a4e1599639cc01f7b29b8924ed2f32807e1dcc46fe758cf7c", + x402: { + nonce: "0xa515b9fa790e20c71b3e582059e582b2e92db36d7e26d7ced33bdd3a16da8852", + resource: "unknown (third-party tx, test fixture only)", + scheme: "exact", + }, + }, + purpose: { note: "verifier test against a third-party PayAI settlement, not ours", ref: "fixture-base-2026-11-30" }, +}; +const doc = (rec) => ({ version: VERSION, content_sha256: contentSha256(rec), record: rec, network: rec.payment.network }); +const withPayment = (patch) => { const r = clone(record); Object.assign(r.payment, patch); return doc(r); }; + +mkdirSync("fixtures", { recursive: true }); +const w = (name, d) => writeFileSync(`fixtures/${name}.json`, JSON.stringify(d, null, 2)); + +w("payai-ok", doc(clone(record))); +w("payai-bad-index", withPayment({ locator: { index: 280, kind: "evm-log" } })); +w("payai-bad-amount", withPayment({ amount: "1001" })); +w("payai-bad-to", withPayment({ to: "0xc6699d2aada6c36dfea5c248dd70f9cb0235cb63" })); +w("payai-bad-nonce", withPayment({ x402: { ...record.payment.x402, nonce: "0x" + "00".repeat(32) } })); +w("payai-bad-content-sha256", { ...doc(clone(record)), content_sha256: "00" + contentSha256(record).slice(2) }); + +const acct = privateKeyToAccount(generatePrivateKey()); +const signed = doc(clone(record)); +signed.agent = { alg: "eip191-secp256k1", key: acct.address, statement: STATEMENT_PREFIX + signed.content_sha256 }; +signed.agent.signature = await acct.signMessage({ message: signed.agent.statement }); +w("payai-sig-ephemeral", signed); +const tampered = clone(signed); +tampered.record.payment.amount = "1001"; // altered after signing, hash not recomputed +w("payai-sig-tampered", tampered); +const forged = clone(signed); +forged.agent.key = record.payment.from; // claims to be the payer, signed by someone else +w("payai-sig-forged-payer", forged); +console.log(`fixtures written; ephemeral signer ${acct.address}`); diff --git a/base/market/Dockerfile b/base/market/Dockerfile new file mode 100644 index 0000000..6e4b640 --- /dev/null +++ b/base/market/Dockerfile @@ -0,0 +1,19 @@ +# Image for the Base x402 market. Build context: the repository root. +# fly deploy -c fly.market.toml --remote-only (from the repository root) +FROM node:24-slim +ENV NODE_ENV=production +WORKDIR /app/base +# The market uses the nirium-base package from the folder above (file:..). +COPY base/package.json base/package-lock.json ./ +RUN npm ci --ignore-scripts --no-audit --no-fund +COPY base/sdk ./sdk +COPY base/policy ./policy +COPY base/verify-evm-core.mjs base/verify-evm-receipt.mjs ./ +COPY base/market/package.json base/market/package-lock.json ./market/ +WORKDIR /app/base/market +RUN npm ci --ignore-scripts --no-audit --no-fund +COPY base/market/data.mjs base/market/server.mjs base/market/geo.mjs ./ +USER node +ENV PORT=8080 +EXPOSE 8080 +CMD ["node", "server.mjs"] diff --git a/base/market/README.md b/base/market/README.md new file mode 100644 index 0000000..3137e34 --- /dev/null +++ b/base/market/README.md @@ -0,0 +1,41 @@ +# Nirium x402 market (Base) + +Network conditions of Base for $0.01 per query, paid with x402. + +| Route | Paid | What | +|---|---|---| +| `GET /v1/market` | $0.01 (USDC, x402 `exact`) | Base fee now and its change over the last 20 blocks, median priority fees (p25/p50/p90), gas price, average block fill, average block time, and `feePressure` (HIGH or NORMAL) with its published rule | +| `GET /v1/market/info` | free | What is sold, price, network, payTo, facilitator, data source | +| `GET /health` | free | | + +- Data comes from the chain's public RPC at request time (`eth_feeHistory`, `eth_gasPrice`, + `eth_getBlockByNumber`). Network data only: no token prices and no recommendation to transact. +- Payment goes from the buyer straight to the market's `payTo`, settled by an independent + facilitator (PayAI). The market stores nothing about buyers. +- Not deployed yet. It goes to Fly as `nirium-market-base`, on Base Sepolia first. Team test sales + are self-tests (see `../../evidence/README.md`), not usage. On mainnet each sale is income for Nirium, + which is why the server refuses mainnet unless `NIRIUM_MARKET_ALLOW_MAINNET=1`, set on purpose + in `fly.market.toml`. + +```bash +(cd .. && npm ci) # the market uses the nirium-base package from the folder above +npm ci +NIRIUM_EVM_PAYTO=0x... node server.mjs # port 4022 +NIRIUM_EVM_PAYER_KEY=0x... node buy.mjs --payto 0x... --ref order-1 # buys one query, writes a receipt +npm test # 4 tests, offline +``` + +`buy.mjs` uses the SDK with a policy, so the buyer only signs what the policy allows, and it +leaves a payer-signed receipt bound to the payment. + +## Deploy + +The repository root has the Fly config (`fly.market.toml`) and this folder has the image +(`Dockerfile`). From the repository root: + +```bash +fly deploy -c fly.market.toml --remote-only +``` + +The server holds no key: the only payment setting is the public address that receives each sale. +The config runs on mainnet; its comments list the values that take it back to testnet. CI builds the same image and checks that `/health` answers 200 and `/v1/market` 402. diff --git a/base/market/buy.mjs b/base/market/buy.mjs new file mode 100644 index 0000000..d74a9f2 --- /dev/null +++ b/base/market/buy.mjs @@ -0,0 +1,30 @@ +// buy.mjs - buys one query from the market with the SDK (policy on), prints the data, and writes +// the payer-signed receipt. Team self-test with test tokens. +// +// NIRIUM_EVM_PAYER_KEY=0x.. node buy.mjs --url http://localhost:4022/v1/market --payto 0x.. --ref [--out receipt.json] + +import { writeFileSync } from "node:fs"; +import { privateKeyToAccount } from "viem/accounts"; +import { createX402Fetch, settlementOf, bindReceipt, verifyReceipt, createRulesPolicy } from "nirium-base"; + +const arg = (k, d) => { const i = process.argv.indexOf(`--${k}`); return i >= 0 ? process.argv[i + 1] : d; }; +const url = arg("url", "http://localhost:4022/v1/market"); +const ref = arg("ref"); +const payTo = arg("payto"); +const key = process.env.NIRIUM_EVM_PAYER_KEY; +if (!ref || !payTo || !key) { console.error("need --ref, --payto and NIRIUM_EVM_PAYER_KEY"); process.exit(2); } +const network = "eip155:84532"; + +const signer = privateKeyToAccount(key); +const pay = createX402Fetch({ signer, network, maxAmountPerPayment: "10000", policy: createRulesPolicy({ maxAmount: "10000", allowPayTo: [payTo], onDecision: (r) => console.log(`policy ${r.outcome}`) }) }); +const res = await pay(url); +const s = settlementOf(res); +const data = await res.json(); +console.log(`HTTP ${res.status} tx=${s?.transaction}`); +console.log(`market: block ${data.block}, base fee ${data.fees?.baseFeeNow} wei, fill ${data.congestion?.avgBlockFill}, pressure ${data.feePressure}`); +if (!s) process.exit(1); +const receipt = await bindReceipt({ tx: s.transaction, network, ref, resource: url, note: "Nirium x402 market query (Base network conditions)", labels: ["selftest"], signer }); +const v = await verifyReceipt(receipt); +console.log(`receipt ${v.ok ? "VALID" : "INVALID"} (${v.checks.filter((c) => c.ok).length}/${v.checks.length})`); +if (arg("out")) writeFileSync(arg("out"), JSON.stringify(receipt, null, 2) + "\n"); +process.exitCode = v.ok ? 0 : 1; diff --git a/base/market/data.mjs b/base/market/data.mjs new file mode 100644 index 0000000..81a45b2 --- /dev/null +++ b/base/market/data.mjs @@ -0,0 +1,62 @@ +// Network conditions for an Base chain, read from its public RPC. What the x402 market sells. +// Only network facts (fees, block fill, block time). No token prices, no trading language. + +export const FEE_PRESSURE_RULE = Object.freeze({ + description: "HIGH when the base fee rose by more than 25% across the window, or blocks were more than 50% full on average. A published heuristic, not a forecast.", + baseFeeRisePct: 25, + blockFill: 0.5, +}); + +async function rpc(url, method, params) { + const res = await fetch(url, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ jsonrpc: "2.0", id: 1, method, params }) }); + if (!res.ok) throw new Error(`${method}: HTTP ${res.status}`); + const body = await res.json(); + if (body.error) throw new Error(`${method}: ${body.error.message}`); + return body.result; +} + +const hex = (h) => BigInt(h); +const median = (xs) => { const s = [...xs].sort((a, b) => (a < b ? -1 : a > b ? 1 : 0)); return s.length ? s[Math.floor((s.length - 1) / 2)] : 0n; }; + +/** Pure: builds the market answer from raw RPC results (testable offline). */ +export function summarize({ network, feeHistory, gasPrice, newestBlock, oldestBlock, blocks }) { + const base = feeHistory.baseFeePerGas.map(hex); + const first = base[0]; + const last = base[base.length - 1]; + const risePct = first > 0n ? Number(((last - first) * 10_000n) / first) / 100 : 0; + const fills = feeHistory.gasUsedRatio; + const avgFill = fills.length ? fills.reduce((a, b) => a + b, 0) / fills.length : 0; + const tip = (i) => median(feeHistory.reward.map((r) => hex(r[i]))); + const span = Number(hex(newestBlock.timestamp) - hex(oldestBlock.timestamp)); + const avgBlockTimeSec = blocks > 1 ? Math.round((span / (blocks - 1)) * 100) / 100 : null; + const high = risePct > FEE_PRESSURE_RULE.baseFeeRisePct || avgFill > FEE_PRESSURE_RULE.blockFill; + return { + network, + block: Number(hex(newestBlock.number)), + window: { blocks, oldestBlock: Number(hex(feeHistory.oldestBlock)) }, + fees: { + unit: "wei per gas", + baseFeeNow: last.toString(), + baseFeeWindowStart: first.toString(), + baseFeeChangePct: risePct, + priorityFeeMedian: { p25: tip(0).toString(), p50: tip(1).toString(), p90: tip(2).toString() }, + gasPrice: hex(gasPrice).toString(), + }, + congestion: { avgBlockFill: Math.round(avgFill * 10_000) / 10_000, avgBlockTimeSec }, + feePressure: high ? "HIGH" : "NORMAL", + feePressureRule: FEE_PRESSURE_RULE.description, + }; +} + +/** Reads the last `blocks` blocks from `rpcUrl` and summarizes them. */ +export async function readMarket({ rpcUrl, network, blocks = 20 }) { + const n = `0x${blocks.toString(16)}`; + const [feeHistory, gasPrice, newestBlock] = await Promise.all([ + rpc(rpcUrl, "eth_feeHistory", [n, "latest", [25, 50, 90]]), + rpc(rpcUrl, "eth_gasPrice", []), + rpc(rpcUrl, "eth_getBlockByNumber", ["latest", false]), + ]); + const oldestNumber = hex(newestBlock.number) - BigInt(blocks - 1); + const oldestBlock = await rpc(rpcUrl, "eth_getBlockByNumber", [`0x${oldestNumber.toString(16)}`, false]); + return { ...summarize({ network, feeHistory, gasPrice, newestBlock, oldestBlock, blocks }), asOf: new Date().toISOString(), source: "public RPC: eth_feeHistory, eth_gasPrice, eth_getBlockByNumber" }; +} diff --git a/base/market/geo.mjs b/base/market/geo.mjs new file mode 100755 index 0000000..f2fc704 --- /dev/null +++ b/base/market/geo.mjs @@ -0,0 +1,35 @@ +// Tier A of Nirium's Restricted Jurisdictions & Sanctions Policy (nirium.xyz/legal/restricted-jurisdictions-v1.md, +// §2): no access to any Nirium service, paid or free. The market sells data for USDC, so it must not sell +// it there. Same countries and the same geoip-lite data as the Nirium node (packages/agent, 27-nov-2026). +// Tier B (EEA, UK, US) is not restricted here: the policy only closes Payouts and Treasury there. +// /health stays open for Fly's checks. An unknown country passes: IP geolocation is imperfect, as §7 says. + +import geoip from "geoip-lite"; + +export const TIER_A_COUNTRIES = new Set([ + "CU", "IR", "KP", "SY", // comprehensive sanctions + "AF", "MM", // FATF call for action / high risk + "RU", "BY", // prudential restriction, pending review + "CN", // PBoC 2021, extraterritorial reach +]); + +const POLICY_URL = "https://nirium.xyz/legal/restricted-jurisdictions-v1.md"; + +/** Express middleware. `lookup` is injectable for tests. */ +export function blockTierA(lookup = (ip) => geoip.lookup(ip)?.country ?? null) { + return (req, res, next) => { + if (req.path === "/health") return next(); + let country = null; + try { country = lookup(req.ip); } catch { country = null; } + if (country && TIER_A_COUNTRIES.has(country)) { + return res.status(451).set("X-Restricted-Jurisdiction", country).json({ + error: "unavailable_for_legal_reasons", + message: "Nirium does not offer any service in your jurisdiction.", + jurisdiction: country, + policy: POLICY_URL, + contact: "niriumprotocol@gmail.com", + }); + } + next(); + }; +} diff --git a/base/market/package-lock.json b/base/market/package-lock.json new file mode 100644 index 0000000..f540c11 --- /dev/null +++ b/base/market/package-lock.json @@ -0,0 +1,1248 @@ +{ + "name": "nirium-base-market", + "version": "0.1.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "nirium-base-market", + "version": "0.1.0", + "license": "Apache-2.0", + "dependencies": { + "express": "5.3.0", + "geoip-lite": "2.0.3", + "nirium-base": "file:..", + "viem": "2.58.7" + }, + "engines": { + "node": ">=20" + } + }, + "..": { + "name": "nirium-base", + "version": "0.2.0", + "license": "Apache-2.0", + "dependencies": { + "@x402/core": "2.32.0", + "@x402/evm": "2.32.0", + "@x402/express": "2.32.0", + "@x402/fetch": "2.32.0", + "viem": "2.58.7" + }, + "bin": { + "nirium-verify-evm": "verify-evm-receipt.mjs" + }, + "devDependencies": { + "express": "5.3.0" + }, + "engines": { + "node": ">=20" + }, + "peerDependencies": { + "express": "^4.22.3 || ^5.3.0" + }, + "peerDependenciesMeta": { + "express": { + "optional": true + } + } + }, + "node_modules/@adraffy/ens-normalize": { + "version": "1.11.1", + "resolved": "https://registry.npmjs.org/@adraffy/ens-normalize/-/ens-normalize-1.11.1.tgz", + "integrity": "sha512-nhCBV3quEgesuf7c7KYfperqSS14T8bYuvJ8PcLJp6znkZpFc0AuW4qBtr8eKVyPPe/8RSr7sglCWPU5eaxwKQ==", + "license": "MIT" + }, + "node_modules/@noble/ciphers": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/@noble/ciphers/-/ciphers-1.3.0.tgz", + "integrity": "sha512-2I0gnIVPtfnMw9ee9h1dJG7tp81+8Ob3OJb3Mv37rx5L40/b0i7djjCVvGOVqc9AEIQyvyu1i6ypKdFw8R8gQw==", + "license": "MIT", + "engines": { + "node": "^14.21.3 || >=16" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, + "node_modules/@noble/curves": { + "version": "1.9.1", + "resolved": "https://registry.npmjs.org/@noble/curves/-/curves-1.9.1.tgz", + "integrity": "sha512-k11yZxZg+t+gWvBbIswW0yoJlu8cHOC7dhunwOzoWH/mXGBiYyR4YY6hAEK/3EUs4UpB8la1RfdRpeGsFHkWsA==", + "license": "MIT", + "dependencies": { + "@noble/hashes": "1.8.0" + }, + "engines": { + "node": "^14.21.3 || >=16" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, + "node_modules/@noble/hashes": { + "version": "1.8.0", + "resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-1.8.0.tgz", + "integrity": "sha512-jCs9ldd7NwzpgXDIf6P3+NrHh9/sD6CQdxHyjQI+h/6rDNo88ypBxxz45UDuZHz9r3tNz7N/VInSVoVdtXEI4A==", + "license": "MIT", + "engines": { + "node": "^14.21.3 || >=16" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, + "node_modules/@scure/base": { + "version": "1.2.6", + "resolved": "https://registry.npmjs.org/@scure/base/-/base-1.2.6.tgz", + "integrity": "sha512-g/nm5FgUa//MCj1gV09zTJTaM6KBAHqLN907YVQqf7zC49+DcO4B1so4ZX07Ef10Twr6nuqYEH9GEggFXA4Fmg==", + "license": "MIT", + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, + "node_modules/@scure/bip32": { + "version": "1.7.0", + "resolved": "https://registry.npmjs.org/@scure/bip32/-/bip32-1.7.0.tgz", + "integrity": "sha512-E4FFX/N3f4B80AKWp5dP6ow+flD1LQZo/w8UnLGYZO674jS6YnYeepycOOksv+vLPSpgN35wgKgy+ybfTb2SMw==", + "license": "MIT", + "dependencies": { + "@noble/curves": "~1.9.0", + "@noble/hashes": "~1.8.0", + "@scure/base": "~1.2.5" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, + "node_modules/@scure/bip39": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/@scure/bip39/-/bip39-1.6.0.tgz", + "integrity": "sha512-+lF0BbLiJNwVlev4eKelw1WWLaiKXw7sSl8T6FvBlWkdX+94aGJ4o8XjUdlyhTCjd8c+B3KT3JfS8P0bLRNU6A==", + "license": "MIT", + "dependencies": { + "@noble/hashes": "~1.8.0", + "@scure/base": "~1.2.5" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, + "node_modules/abitype": { + "version": "1.2.3", + "resolved": "https://registry.npmjs.org/abitype/-/abitype-1.2.3.tgz", + "integrity": "sha512-Ofer5QUnuUdTFsBRwARMoWKOH1ND5ehwYhJ3OJ/BQO+StkwQjHw0XyVh4vDttzHB7QOFhPHa/o413PJ82gU/Tg==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/wevm" + }, + "peerDependencies": { + "typescript": ">=5.0.4", + "zod": "^3.22.0 || ^4.0.0" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + }, + "zod": { + "optional": true + } + } + }, + "node_modules/accepts": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/accepts/-/accepts-2.0.0.tgz", + "integrity": "sha512-5cvg6CtKwfgdmVqY1WIiXKc3Q1bkRqGLi+2W/6ao+6Y7gu/RCwRuAhGEzh5B4KlszSuTLgZYuqFqo5bImjNKng==", + "license": "MIT", + "dependencies": { + "mime-types": "^3.0.0", + "negotiator": "^1.0.0" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/ansi-styles": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", + "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", + "license": "MIT", + "dependencies": { + "color-convert": "^2.0.1" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/body-parser": { + "version": "2.4.0", + "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-2.4.0.tgz", + "integrity": "sha512-Ifk1KcLrxaGt1occQagQNFNNOqRt1LFuehEnHHzB8Z6cRgIxRU1TBaiIsUiCdA+gy5PL7Y1IX31DNKkRmxtXjQ==", + "license": "MIT", + "dependencies": { + "bytes": "^3.1.2", + "content-type": "^2.1.0", + "debug": "^4.4.3", + "http-errors": "^2.0.1", + "iconv-lite": "^0.7.3", + "on-finished": "^2.4.1", + "qs": "^6.16.1", + "raw-body": "^3.0.2", + "type-is": "^2.1.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/bytes": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.2.tgz", + "integrity": "sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/call-bind-apply-helpers": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz", + "integrity": "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/call-bound": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/call-bound/-/call-bound-1.0.4.tgz", + "integrity": "sha512-+ys997U96po4Kx/ABpBCqhA9EuxJaQWDQg7295H4hBphv3IZg0boBKuwYpt4YXp6MZ5AmZQnU/tyMTlRpaSejg==", + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.2", + "get-intrinsic": "^1.3.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/chalk": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz", + "integrity": "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==", + "license": "MIT", + "dependencies": { + "ansi-styles": "^4.1.0", + "supports-color": "^7.1.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/chalk?sponsor=1" + } + }, + "node_modules/color-convert": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", + "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", + "license": "MIT", + "dependencies": { + "color-name": "~1.1.4" + }, + "engines": { + "node": ">=7.0.0" + } + }, + "node_modules/color-name": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", + "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", + "license": "MIT" + }, + "node_modules/content-disposition": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-2.0.1.tgz", + "integrity": "sha512-e+H0ZXHSWYrENhQzw1LPuP4oF5MzVKmDU6d3hxlvaPEYLLg62MxtQNPRx4SYSuYJSBUgnQIG4HIN2tEtNv7Dog==", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/content-type": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/content-type/-/content-type-2.1.0.tgz", + "integrity": "sha512-mj7UPXE0jaqaOsukNZRUEfEi2AcL7C/vwmwcHV0O97eO1E1pxBZuyjlZrx5seTaNBg1U6+o35wpa35Qfcc+7ag==", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/cookie": { + "version": "0.7.2", + "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.7.2.tgz", + "integrity": "sha512-yki5XnKuf750l50uGTllt6kKILY4nQ1eNIQatoXEByZ5dWgnKqbnqmTrBE5B4N7lrMJKQ2ytWMiTO2o0v6Ew/w==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/cookie-signature": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.2.2.tgz", + "integrity": "sha512-D76uU73ulSXrD1UXF4KE2TMxVVwhsnCgfAyTg9k8P6KGZjlXKrOLe4dJQKI3Bxi5wjesZoFXJWElNWBjPZMbhg==", + "license": "MIT", + "engines": { + "node": ">=6.6.0" + } + }, + "node_modules/debug": { + "version": "4.4.3", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", + "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", + "license": "MIT", + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/depd": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz", + "integrity": "sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/dunder-proto": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz", + "integrity": "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==", + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.1", + "es-errors": "^1.3.0", + "gopd": "^1.2.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/ee-first": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz", + "integrity": "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==", + "license": "MIT" + }, + "node_modules/encodeurl": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-2.0.3.tgz", + "integrity": "sha512-mIteYONiEfc4xWf2F1WXovh1c8npzS00vNeiUPdwFF+QlVJni+gNvpQltLMQhob8rew/bWWc/bGTuUr0EUGt0w==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/es-define-property": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz", + "integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-errors": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz", + "integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-object-atoms": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.2.tgz", + "integrity": "sha512-HWcBoN6NileqtSydK2FqHbS/LoDd2pqrnQHLyJzBj4kOp/ky2MWMN694xOfkK8/SnUsW2DH7EfyVlydKCsm1Zw==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/escape-html": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/escape-html/-/escape-html-1.0.3.tgz", + "integrity": "sha512-NiSupZ4OeuGwr68lGIeym/ksIZMJodUGOSCZ/FSnTxcrekbvqrgdUxlJOMpijaKZVjAJrWrGs/6Jy8OMuyj9ow==", + "license": "MIT" + }, + "node_modules/etag": { + "version": "1.8.1", + "resolved": "https://registry.npmjs.org/etag/-/etag-1.8.1.tgz", + "integrity": "sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/eventemitter3": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/eventemitter3/-/eventemitter3-5.0.1.tgz", + "integrity": "sha512-GWkBvjiSZK87ELrYOSESUYeVIc9mvLLf/nXalMOS5dYrgZq9o5OVkbZAVM06CVxYsCwH9BDZFPlQTlPA1j4ahA==", + "license": "MIT" + }, + "node_modules/express": { + "version": "5.3.0", + "resolved": "https://registry.npmjs.org/express/-/express-5.3.0.tgz", + "integrity": "sha512-qCqy1xSoaugxOD4IVHb1ZWdkvCF2W3aE2okKouWj8VwJ+ztskSiXoBnCSJqfKT+cVPJhuJqe9YLbY425+Zh00g==", + "license": "MIT", + "dependencies": { + "accepts": "^2.0.0", + "body-parser": "^2.3.0", + "content-disposition": "^2.0.1", + "content-type": "^2.0.0", + "cookie": "^0.7.1", + "cookie-signature": "^1.2.1", + "debug": "^4.4.0", + "depd": "^2.0.0", + "encodeurl": "^2.0.0", + "escape-html": "^1.0.3", + "etag": "^1.8.1", + "finalhandler": "^2.1.0", + "fresh": "^2.0.0", + "http-errors": "^2.0.0", + "merge-descriptors": "^2.0.0", + "mime-types": "^3.0.0", + "on-finished": "^2.4.1", + "once": "^1.4.0", + "parseurl": "^1.3.3", + "proxy-addr": "^2.0.8", + "qs": "^6.16.0", + "range-parser": "^1.2.1", + "router": "^2.2.0", + "send": "^1.1.0", + "serve-static": "^2.2.0", + "statuses": "^2.0.1", + "type-is": "^2.1.0", + "vary": "^1.1.2" + }, + "engines": { + "node": ">= 18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/finalhandler": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-2.1.1.tgz", + "integrity": "sha512-S8KoZgRZN+a5rNwqTxlZZePjT/4cnm0ROV70LedRHZ0p8u9fRID0hJUZQpkKLzro8LfmC8sx23bY6tVNxv8pQA==", + "license": "MIT", + "dependencies": { + "debug": "^4.4.0", + "encodeurl": "^2.0.0", + "escape-html": "^1.0.3", + "on-finished": "^2.4.1", + "parseurl": "^1.3.3", + "statuses": "^2.0.1" + }, + "engines": { + "node": ">= 18.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/forwarded": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/forwarded/-/forwarded-0.2.0.tgz", + "integrity": "sha512-buRG0fpBtRHSTCOASe6hD258tEubFoRLb4ZNA6NxMVHNw2gOcwHo9wyablzMzOA5z9xA9L1KNjk/Nt6MT9aYow==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/fresh": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/fresh/-/fresh-2.0.0.tgz", + "integrity": "sha512-Rx/WycZ60HOaqLKAi6cHRKKI7zxWbJ31MhntmtwMoaTeF7XFH9hhBp8vITaMidfljRQ6eYWCKkaTK+ykVJHP2A==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/function-bind": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz", + "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/geoip-lite": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/geoip-lite/-/geoip-lite-2.0.3.tgz", + "integrity": "sha512-I0v/6sITK5FhEXHmatGSPBMply2nHN/2D743LIx4KkksttZt/E505lDaV6qUwt5RM08MbZW+/4E0KxusLVN39w==", + "license": "Apache-2.0", + "dependencies": { + "chalk": "4.1 - 4.1.2", + "iconv-lite": "0.4.13 - 0.6.3", + "ip-address": "^10.2.0", + "lazy": "1.0.11", + "yauzl": "^3.3.1" + }, + "engines": { + "node": ">=24.0.0" + } + }, + "node_modules/geoip-lite/node_modules/iconv-lite": { + "version": "0.6.3", + "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.6.3.tgz", + "integrity": "sha512-4fCk79wshMdzMp2rH06qWrJE4iolqLhCUH+OiuIgU++RB0+94NlDL81atO7GX55uUKueo0txHNtvEyI6D7WdMw==", + "license": "MIT", + "dependencies": { + "safer-buffer": ">= 2.1.2 < 3.0.0" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/get-intrinsic": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz", + "integrity": "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==", + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.2", + "es-define-property": "^1.0.1", + "es-errors": "^1.3.0", + "es-object-atoms": "^1.1.1", + "function-bind": "^1.1.2", + "get-proto": "^1.0.1", + "gopd": "^1.2.0", + "has-symbols": "^1.1.0", + "hasown": "^2.0.2", + "math-intrinsics": "^1.1.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/get-proto": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/get-proto/-/get-proto-1.0.1.tgz", + "integrity": "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==", + "license": "MIT", + "dependencies": { + "dunder-proto": "^1.0.1", + "es-object-atoms": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/gopd": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz", + "integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-flag": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", + "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/has-symbols": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.1.0.tgz", + "integrity": "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/hasown": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.4.tgz", + "integrity": "sha512-T2UbfbBEF32wiepXIsMlTW9+dDYC6wMh/t/vYA4tuOMKqWz/n3vr1NFSxQiyP+zk2mXsoMA/i/7qV6LKut1t1A==", + "license": "MIT", + "dependencies": { + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/http-errors": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.1.tgz", + "integrity": "sha512-4FbRdAX+bSdmo4AUFuS0WNiPz8NgFt+r8ThgNWmlrjQjt1Q7ZR9+zTlce2859x4KSXrwIsaeTqDoKQmtP8pLmQ==", + "license": "MIT", + "dependencies": { + "depd": "~2.0.0", + "inherits": "~2.0.4", + "setprototypeof": "~1.2.0", + "statuses": "~2.0.2", + "toidentifier": "~1.0.1" + }, + "engines": { + "node": ">= 0.8" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/iconv-lite": { + "version": "0.7.3", + "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.7.3.tgz", + "integrity": "sha512-IKXpvIzjnC9XTAUbVBcMfGS0EPaIXtW6v+zr+RRp+hqULEpo0owZax6wyRwPOJbWbzjYspQwusTsfVr0ifh4uQ==", + "license": "MIT", + "dependencies": { + "safer-buffer": ">= 2.1.2 < 3.0.0" + }, + "engines": { + "node": ">=0.10.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/inherits": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", + "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", + "license": "ISC" + }, + "node_modules/ip-address": { + "version": "10.7.6", + "resolved": "https://registry.npmjs.org/ip-address/-/ip-address-10.7.6.tgz", + "integrity": "sha512-00LYkM6byILa9eQIx6qoaXCM40xTLd56AZ4vyaPW3YTyb49VZYPo5xsiAq4tuQ54GH4R7gVdYScJ1B7B77PuTg==", + "license": "MIT", + "engines": { + "node": ">= 12" + } + }, + "node_modules/ipaddr.js": { + "version": "1.9.1", + "resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-1.9.1.tgz", + "integrity": "sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g==", + "license": "MIT", + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/is-promise": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/is-promise/-/is-promise-4.0.0.tgz", + "integrity": "sha512-hvpoI6korhJMnej285dSg6nu1+e6uxs7zG3BYAm5byqDsgJNWwxzM6z6iZiAgQR4TJ30JmBTOwqZUw3WlyH3AQ==", + "license": "MIT" + }, + "node_modules/isows": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/isows/-/isows-1.0.7.tgz", + "integrity": "sha512-I1fSfDCZL5P0v33sVqeTDSpcstAg/N+wF5HS033mogOVIp4B+oHC7oOCsA3axAbBSGTJ8QubbNmnIRN/h8U7hg==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/wevm" + } + ], + "license": "MIT", + "peerDependencies": { + "ws": "*" + } + }, + "node_modules/lazy": { + "version": "1.0.11", + "resolved": "https://registry.npmjs.org/lazy/-/lazy-1.0.11.tgz", + "integrity": "sha512-Y+CjUfLmIpoUCCRl0ub4smrYtGGr5AOa2AKOaWelGHOGz33X/Y/KizefGqbkwfz44+cnq/+9habclf8vOmu2LA==", + "license": "MIT", + "engines": { + "node": ">=0.2.0" + } + }, + "node_modules/math-intrinsics": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz", + "integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/media-typer": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/media-typer/-/media-typer-1.1.1.tgz", + "integrity": "sha512-yz3xRaG20c6/BOzvYoDaGtPmGscs7YivItZEEqe6GbwNfHuxu9YNmvnEkMzKldAGY4/80pRcQRZSEnhquk9XuQ==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/merge-descriptors": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-2.0.0.tgz", + "integrity": "sha512-Snk314V5ayFLhp3fkUREub6WtjBfPdCPY1Ln8/8munuLuiYhsABgBVWsozAG+MWMbVEvcdcpbi9R7ww22l9Q3g==", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/mime-db": { + "version": "1.54.0", + "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.54.0.tgz", + "integrity": "sha512-aU5EJuIN2WDemCcAp2vFBfp/m4EAhWJnUNSSw0ixs7/kXbd6Pg64EmwJkNdFhB8aWt1sH2CTXrLxo/iAGV3oPQ==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/mime-types": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-3.0.2.tgz", + "integrity": "sha512-Lbgzdk0h4juoQ9fCKXW4by0UJqj+nOOrI9MJ1sSj4nI8aI2eo1qmvQEie4VD1glsS250n15LsWsYtCugiStS5A==", + "license": "MIT", + "dependencies": { + "mime-db": "^1.54.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", + "license": "MIT" + }, + "node_modules/negotiator": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/negotiator/-/negotiator-1.1.0.tgz", + "integrity": "sha512-NMPBRMJgiQHjbd8phG3Vebdx4kZ1H121rbl5IkMqeOsahptB9BKo/d7oJ3zTXqTgagn2bWlNSXkh0QUGM31RYg==", + "license": "MIT", + "dependencies": { + "content-type": "^2.1.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/nirium-base": { + "resolved": "..", + "link": true + }, + "node_modules/object-inspect": { + "version": "1.14.0", + "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.14.0.tgz", + "integrity": "sha512-IVgHNlp/jwQX271+Xzoq9LZNTWXxZK+cEOrGBOBxXNbn7fapnZ+Ts6TVMgNOuAezwG2wdtnMX97tTPK6VEnuOQ==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/on-finished": { + "version": "2.4.2", + "resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.4.2.tgz", + "integrity": "sha512-ATWUv387i+nLD49EiDoOft5scf32Vsdz3ktrQJG9bi7jRFmaXTssvyvj1EmeKVVgvesbqUtvQQvaS2TpTukAZQ==", + "license": "MIT", + "dependencies": { + "ee-first": "1.1.1" + }, + "engines": { + "node": ">= 0.8" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/once": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", + "integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==", + "license": "ISC", + "dependencies": { + "wrappy": "1" + } + }, + "node_modules/ox": { + "version": "0.14.67", + "resolved": "https://registry.npmjs.org/ox/-/ox-0.14.67.tgz", + "integrity": "sha512-6v6UlwgsmiyTujZp0aVDuN8uIBAtl/QZadBADFRZ2zp1+CM9TqDzd+rPKJ5PYvWPlCvz8JvoO9dTr42+1PhBhA==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/wevm" + } + ], + "license": "MIT", + "dependencies": { + "@adraffy/ens-normalize": "^1.11.0", + "@noble/ciphers": "^1.3.0", + "@noble/curves": "1.9.1", + "@noble/hashes": "^1.8.0", + "@scure/bip32": "^1.7.0", + "@scure/bip39": "^1.6.0", + "abitype": "^1.2.3", + "eventemitter3": "5.0.1" + }, + "peerDependencies": { + "typescript": ">=5.4.0" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + } + } + }, + "node_modules/parseurl": { + "version": "1.3.3", + "resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz", + "integrity": "sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/path-to-regexp": { + "version": "8.4.2", + "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-8.4.2.tgz", + "integrity": "sha512-qRcuIdP69NPm4qbACK+aDogI5CBDMi1jKe0ry5rSQJz8JVLsC7jV8XpiJjGRLLol3N+R5ihGYcrPLTno6pAdBA==", + "license": "MIT", + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/pend": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/pend/-/pend-1.2.0.tgz", + "integrity": "sha512-F3asv42UuXchdzt+xXqfW1OGlVBe+mxa2mqI0pg5yAHZPvFmY3Y6drSf/GQ1A86WgWEN9Kzh/WrgKa6iGcHXLg==", + "license": "MIT" + }, + "node_modules/proxy-addr": { + "version": "2.0.8", + "resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.8.tgz", + "integrity": "sha512-5nnx0yGyVUcY6t9RnWcARWtwT9F1D8O9rt08htPvnd49W1IgZtmLkhu9WfMzQj1cFxjHIO6connUNVW5k7AVyQ==", + "license": "MIT", + "dependencies": { + "forwarded": "0.2.0", + "ipaddr.js": "1.9.1" + }, + "engines": { + "node": ">= 0.10" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/qs": { + "version": "6.17.1", + "resolved": "https://registry.npmjs.org/qs/-/qs-6.17.1.tgz", + "integrity": "sha512-jd3COkaKVgGUW+ZHyEHCG9bH7RoaaiWuMgzsIBjUMVjLAaWGWpoUAVwljVvBHxRu/2qEHnadLGZrkutYUBPQJA==", + "license": "BSD-3-Clause", + "dependencies": { + "es-define-property": "^1.0.1", + "side-channel": "^1.1.1" + }, + "engines": { + "node": ">=0.6" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/range-parser": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.3.0.tgz", + "integrity": "sha512-hek2mFQpPuI4E1BBKrSto+BU3e3x4xuarsbiwr3+lf7p44juvFMV0XFWQAP3xUyqXA4RrXLIoaSUGbSt056ZMw==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/raw-body": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/raw-body/-/raw-body-3.0.2.tgz", + "integrity": "sha512-K5zQjDllxWkf7Z5xJdV0/B0WTNqx6vxG70zJE4N0kBs4LovmEYWJzQGxC9bS9RAKu3bgM40lrd5zoLJ12MQ5BA==", + "license": "MIT", + "dependencies": { + "bytes": "~3.1.2", + "http-errors": "~2.0.1", + "iconv-lite": "~0.7.0", + "unpipe": "~1.0.0" + }, + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/router": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/router/-/router-2.3.0.tgz", + "integrity": "sha512-bpowRfGjEPe8t9R6fJIzhwmyCGAXwKvxBUsgJm+bJukwdcWmUXbMo7p22w7aYmQBPQTUMNqMV39YX0kMou3z8w==", + "license": "MIT", + "dependencies": { + "debug": "^4.4.0", + "depd": "^2.0.0", + "is-promise": "^4.0.0", + "parseurl": "^1.3.3", + "path-to-regexp": "^8.0.0" + }, + "engines": { + "node": ">= 18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/safer-buffer": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", + "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==", + "license": "MIT" + }, + "node_modules/send": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/send/-/send-1.2.1.tgz", + "integrity": "sha512-1gnZf7DFcoIcajTjTwjwuDjzuz4PPcY2StKPlsGAQ1+YH20IRVrBaXSWmdjowTJ6u8Rc01PoYOGHXfP1mYcZNQ==", + "license": "MIT", + "dependencies": { + "debug": "^4.4.3", + "encodeurl": "^2.0.0", + "escape-html": "^1.0.3", + "etag": "^1.8.1", + "fresh": "^2.0.0", + "http-errors": "^2.0.1", + "mime-types": "^3.0.2", + "ms": "^2.1.3", + "on-finished": "^2.4.1", + "range-parser": "^1.2.1", + "statuses": "^2.0.2" + }, + "engines": { + "node": ">= 18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/serve-static": { + "version": "2.2.1", + "resolved": "https://registry.npmjs.org/serve-static/-/serve-static-2.2.1.tgz", + "integrity": "sha512-xRXBn0pPqQTVQiC8wyQrKs2MOlX24zQ0POGaj0kultvoOCstBQM5yvOhAVSUwOMjQtTvsPWoNCHfPGwaaQJhTw==", + "license": "MIT", + "dependencies": { + "encodeurl": "^2.0.0", + "escape-html": "^1.0.3", + "parseurl": "^1.3.3", + "send": "^1.2.0" + }, + "engines": { + "node": ">= 18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/setprototypeof": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.2.0.tgz", + "integrity": "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==", + "license": "ISC" + }, + "node_modules/side-channel": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.1.1.tgz", + "integrity": "sha512-6x6dK6zJdpTzF4sQeNYxwtvBzf6Eg4GtlesS94HOvTudUeyK2WXAaIfmDgsyslYrRBeFIlsi54AYsFGUuhmvrQ==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "object-inspect": "^1.13.4", + "side-channel-list": "^1.0.1", + "side-channel-map": "^1.0.1", + "side-channel-weakmap": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-list": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/side-channel-list/-/side-channel-list-1.0.1.tgz", + "integrity": "sha512-mjn/0bi/oUURjc5Xl7IaWi/OJJJumuoJFQJfDDyO46+hBWsfaVM65TBHq2eoZBhzl9EchxOijpkbRC8SVBQU0w==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "object-inspect": "^1.13.4" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-map": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/side-channel-map/-/side-channel-map-1.0.1.tgz", + "integrity": "sha512-VCjCNfgMsby3tTdo02nbjtM/ewra6jPHmpThenkTYh8pG9ucZ/1P8So4u4FGBek/BjpOVsDCMoLA/iuBKIFXRA==", + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.2", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.5", + "object-inspect": "^1.13.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-weakmap": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/side-channel-weakmap/-/side-channel-weakmap-1.0.2.tgz", + "integrity": "sha512-WPS/HvHQTYnHisLo9McqBHOJk2FkHO/tlpvldyrnem4aeQp4hai3gythswg6p01oSoTl58rcpiFAjF2br2Ak2A==", + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.2", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.5", + "object-inspect": "^1.13.3", + "side-channel-map": "^1.0.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/statuses": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.2.tgz", + "integrity": "sha512-DvEy55V3DB7uknRo+4iOGT5fP1slR8wQohVdknigZPMpMstaKJQWhwiYBACJE3Ul2pTnATihhBYnRhZQHGBiRw==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/supports-color": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", + "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", + "license": "MIT", + "dependencies": { + "has-flag": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/toidentifier": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/toidentifier/-/toidentifier-1.0.1.tgz", + "integrity": "sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA==", + "license": "MIT", + "engines": { + "node": ">=0.6" + } + }, + "node_modules/type-is": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/type-is/-/type-is-2.1.0.tgz", + "integrity": "sha512-faYHw0anBbc/kWF3zFTEnxSFOAGUX9GFbOBthvDdLsIlEoWOFOtS0zgCiQYwIskL9iGXZL3kAXD8OoZ4GmMATA==", + "license": "MIT", + "dependencies": { + "content-type": "^2.0.0", + "media-typer": "^1.1.0", + "mime-types": "^3.0.0" + }, + "engines": { + "node": ">= 18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/unpipe": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz", + "integrity": "sha512-pjy2bYhSsufwWlKwPc+l3cN7+wuJlK6uz0YdJEOlQDbl6jo/YlPi4mb8agUkVC8BF7V8NuzeyPNqRksA3hztKQ==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/vary": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz", + "integrity": "sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/viem": { + "version": "2.58.7", + "resolved": "https://registry.npmjs.org/viem/-/viem-2.58.7.tgz", + "integrity": "sha512-9s29POkcUOdlvEN5ePdBTBryhoEQE+ikXuuwjvJRqTc99yCMVkVqwvrjogYpTaJLo2rIrgOEjAglbdr6DCRdkg==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/wevm" + } + ], + "license": "MIT", + "dependencies": { + "@noble/curves": "1.9.1", + "@noble/hashes": "1.8.0", + "@scure/bip32": "1.7.0", + "@scure/bip39": "1.6.0", + "abitype": "1.2.3", + "isows": "1.0.7", + "ox": "0.14.67", + "ws": "8.21.0" + }, + "peerDependencies": { + "mppx": ">=0.17.0", + "typescript": ">=5.0.4" + }, + "peerDependenciesMeta": { + "mppx": { + "optional": true + }, + "typescript": { + "optional": true + } + } + }, + "node_modules/wrappy": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", + "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==", + "license": "ISC" + }, + "node_modules/ws": { + "version": "8.21.0", + "resolved": "https://registry.npmjs.org/ws/-/ws-8.21.0.tgz", + "integrity": "sha512-Vsp28b7DRcimFQvrqu2Wek3z1iYxDCWqHYB8Qsnk/S4RfaCQzPGPyBNuVjJV3cd6UiKtUtp6sNM77gWvzcCH+g==", + "license": "MIT", + "engines": { + "node": ">=10.0.0" + }, + "peerDependencies": { + "bufferutil": "^4.0.1", + "utf-8-validate": ">=5.0.2" + }, + "peerDependenciesMeta": { + "bufferutil": { + "optional": true + }, + "utf-8-validate": { + "optional": true + } + } + }, + "node_modules/yauzl": { + "version": "3.4.0", + "resolved": "https://registry.npmjs.org/yauzl/-/yauzl-3.4.0.tgz", + "integrity": "sha512-jIH9yLR9wqr0wOS0TpBvo/g/2UgZH5qePVbjgRliiF0BYvOZyaBknKsF+x9Iht0O6sqgnB93rCICdOZFecJuDw==", + "license": "MIT", + "dependencies": { + "pend": "~1.2.0" + }, + "engines": { + "node": ">=12" + } + } + } +} diff --git a/base/market/package.json b/base/market/package.json new file mode 100644 index 0000000..64bb138 --- /dev/null +++ b/base/market/package.json @@ -0,0 +1,21 @@ +{ + "name": "nirium-base-market", + "version": "0.1.0", + "private": true, + "description": "Nirium x402 market for Base: network conditions for $0.01 per query", + "type": "module", + "license": "Apache-2.0", + "scripts": { + "start": "node server.mjs", + "test": "node --test test/*.test.mjs" + }, + "engines": { + "node": ">=20" + }, + "dependencies": { + "express": "5.3.0", + "geoip-lite": "2.0.3", + "nirium-base": "file:..", + "viem": "2.58.7" + } +} diff --git a/base/market/server.mjs b/base/market/server.mjs new file mode 100644 index 0000000..f6770e7 --- /dev/null +++ b/base/market/server.mjs @@ -0,0 +1,71 @@ +// Nirium x402 market for Base: sells this chain's network conditions for $0.01 per query, +// paid with x402 through an independent facilitator (PayAI). The buyer pays Nirium's payTo +// directly; the market stores nothing about buyers (no addresses, no logs of who paid). +// +// Runs on mainnet since 27-nov-2026, where every sale is income for Nirium, so the server still +// refuses mainnet unless NIRIUM_MARKET_ALLOW_MAINNET=1 is set on purpose (fly.market.toml does). +// +// NIRIUM_EVM_PAYTO=0x... node server.mjs # PORT (4022), NIRIUM_NETWORK, FACILITATOR_URL, DATA_RPC_URL + +import express from "express"; +import { pathToFileURL } from "node:url"; +import { x402Serve, getNetwork, PAYAI_FACILITATOR } from "nirium-base"; +import { readMarket, FEE_PRESSURE_RULE } from "./data.mjs"; +import { blockTierA } from "./geo.mjs"; + +const PUBLIC_RPC = { "eip155:84532": "https://sepolia.base.org", "eip155:8453": "https://mainnet.base.org" }; + +/** What a buyer should know about the network the market runs on. */ +export function networkNote(net) { + return net.mainnet + ? "Mainnet: real USDC. Each sale is income for Nirium and settles straight to the payTo above." + : "Test network: test tokens only."; +} + +export function createMarketApp({ payTo, network = "eip155:84532", price = "$0.01", facilitatorUrl, dataRpcUrl, allowMainnet = false, read = readMarket }) { + const net = getNetwork(network); + if (net.mainnet && !allowMainnet) throw new Error("market: refusing mainnet (every sale would be income); set allowMainnet explicitly"); + const rpcUrl = dataRpcUrl || PUBLIC_RPC[network]; + const app = express(); + app.disable("x-powered-by"); + // Fly sits in front: the client IP is the trusted hop of X-Forwarded-For. Tier A gets 451 (geo.mjs). + app.set("trust proxy", 1); + app.use(blockTierA()); + app.get("/health", (req, res) => res.json({ ok: true })); + // The bare URL used to answer "Cannot GET /". It now says what this is and where to go. + app.get("/", (req, res) => res.json({ + service: "Nirium x402 market (Base)", + what: "Network conditions of this chain, sold per query with x402.", + network, price, payTo, + routes: { paid: "/v1/market", info: "/v1/market/info", health: "/health" }, + verifyReceipts: "npx -p nirium-base nirium-verify-evm receipt.json", + source: "https://github.com/nirium-protocol/nirium-base/tree/main/base/market", + note: networkNote(net), + })); + app.get("/v1/market/info", (req, res) => res.json({ + what: "Network conditions of Base: base fee and its trend, priority fees, gas price, block fill, block time.", + network, price, payTo, paidWith: "x402 exact, USDC, settled by an independent facilitator", + facilitator: facilitatorUrl || PAYAI_FACILITATOR, + source: "the chain's public RPC, read at request time", + feePressureRule: FEE_PRESSURE_RULE.description, + notes: ["Network data only. No token prices and no recommendation to transact.", "Nothing about the buyer is stored.", networkNote(net)], + })); + app.use(x402Serve({ payTo, network, facilitatorUrl, routes: { "GET /v1/market": { price, description: "Base network conditions" } } })); + app.get("/v1/market", async (req, res) => { + try { res.json(await read({ rpcUrl, network })); } + catch (e) { res.status(502).json({ error: "could not read the chain right now", detail: String(e.message).slice(0, 160) }); } + }); + return app; +} + +if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) { + const app = createMarketApp({ + payTo: process.env.NIRIUM_EVM_PAYTO, + network: process.env.NIRIUM_NETWORK || "eip155:84532", + facilitatorUrl: process.env.FACILITATOR_URL, + dataRpcUrl: process.env.DATA_RPC_URL, + allowMainnet: process.env.NIRIUM_MARKET_ALLOW_MAINNET === "1", + }); + const port = Number(process.env.PORT || 4022); + app.listen(port, () => console.log(`nirium market on http://localhost:${port}/v1/market (info: /v1/market/info)`)); +} diff --git a/base/market/test/geo.test.mjs b/base/market/test/geo.test.mjs new file mode 100644 index 0000000..1c1696c --- /dev/null +++ b/base/market/test/geo.test.mjs @@ -0,0 +1,46 @@ +// Tier A is closed on the market, with the real geoip-lite data and the real app (X-Forwarded-For plays +// the trusted proxy hop, as on Fly). Tier B and allowed countries are never geo-blocked; /health stays open. + +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { createServer } from "node:http"; +import { createMarketApp } from "../server.mjs"; +import { TIER_A_COUNTRIES } from "../geo.mjs"; + +const IRAN = "5.160.0.1", NORTH_KOREA = "175.45.176.1", CHINA = "180.76.76.76", US = "8.8.8.8", MEXICO = "187.191.37.227"; + +async function start() { + const app = createMarketApp({ payTo: "0xC7484059c45Cf89dDc487C836A6f821Dc5882051", read: async () => ({ ok: true }) }); + const server = createServer(app); + await new Promise((r) => server.listen(0, "127.0.0.1", r)); + return { base: `http://127.0.0.1:${server.address().port}`, close: () => server.close() }; +} +const get = (base, path, ip) => fetch(base + path, { headers: { "X-Forwarded-For": ip } }); + +test("Tier A list matches the Nirium node", () => { + assert.deepEqual([...TIER_A_COUNTRIES].sort(), ["AF", "BY", "CN", "CU", "IR", "KP", "MM", "RU", "SY"]); +}); + +test("Tier A gets 451 on every market route, including the paid one", async () => { + const { base, close } = await start(); + try { + for (const ip of [IRAN, NORTH_KOREA, CHINA]) { + for (const path of ["/", "/v1/market/info", "/v1/market"]) { + const res = await get(base, path, ip); + assert.equal(res.status, 451, `${path} from ${ip}`); + assert.equal((await res.json()).error, "unavailable_for_legal_reasons"); + } + } + } finally { close(); } +}); + +test("the US (Tier B) and Mexico are not geo-blocked; /health stays open from Tier A", async () => { + const { base, close } = await start(); + try { + for (const ip of [US, MEXICO]) { + assert.equal((await get(base, "/v1/market/info", ip)).status, 200, ip); + assert.equal((await get(base, "/", ip)).status, 200, ip); + } + assert.equal((await get(base, "/health", IRAN)).status, 200); + } finally { close(); } +}); diff --git a/base/market/test/market.test.mjs b/base/market/test/market.test.mjs new file mode 100644 index 0000000..167a7e0 --- /dev/null +++ b/base/market/test/market.test.mjs @@ -0,0 +1,81 @@ +// Tests for the Base x402 market. Offline: the summary is computed from fixed RPC results, +// and the paid flow runs against a local fake facilitator; the data reader is stubbed. + +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { createServer } from "node:http"; +import { generatePrivateKey, privateKeyToAccount } from "viem/accounts"; +import { createX402Fetch, settlementOf } from "nirium-base"; +import { summarize } from "../data.mjs"; +import { createMarketApp, networkNote } from "../server.mjs"; + +const SEPOLIA = "eip155:84532"; +const h = (n) => `0x${BigInt(n).toString(16)}`; + +test("summarize: base fee trend, median priority fees, block fill and time, fee pressure", () => { + const base = { network: SEPOLIA, gasPrice: h(160), newestBlock: { number: h(1019), timestamp: h(2038) }, oldestBlock: { number: h(1000), timestamp: h(2000) }, blocks: 20 }; + const quiet = summarize({ ...base, feeHistory: { oldestBlock: h(1000), baseFeePerGas: [h(10), h(10), h(11)], gasUsedRatio: [0.1, 0.2], reward: [[h(1), h(5), h(9)], [h(3), h(7), h(20)]] } }); + assert.equal(quiet.fees.baseFeeNow, "11"); + assert.equal(quiet.fees.baseFeeChangePct, 10); + assert.deepEqual(quiet.fees.priorityFeeMedian, { p25: "1", p50: "5", p90: "9" }); + assert.equal(quiet.congestion.avgBlockFill, 0.15); + assert.equal(quiet.congestion.avgBlockTimeSec, 2); + assert.equal(quiet.feePressure, "NORMAL"); + const busy = summarize({ ...base, feeHistory: { oldestBlock: h(1000), baseFeePerGas: [h(10), h(20)], gasUsedRatio: [0.9], reward: [[h(1), h(1), h(1)]] } }); + assert.equal(busy.feePressure, "HIGH"); + for (const k of Object.keys(busy)) assert.doesNotMatch(k, /price(?!s)|opportunit|arbitrage|signal/i); +}); + +test("the market refuses mainnet unless allowed explicitly", () => { + const payTo = privateKeyToAccount(generatePrivateKey()).address; + assert.throws(() => createMarketApp({ payTo, network: "eip155:8453" }), /mainnet/); +}); + +test("info is free, the data is paid, and a paid query returns the network conditions", async () => { + const payTo = privateKeyToAccount(generatePrivateKey()).address; + let settled = 0; + const fac = createServer((req, res) => { + let b = ""; req.on("data", (c) => { b += c; }); + req.on("end", () => { + res.writeHead(200, { "content-type": "application/json" }); + if (req.url.endsWith("/supported")) return res.end(JSON.stringify({ kinds: [{ x402Version: 2, scheme: "exact", network: SEPOLIA }], extensions: [], signers: {} })); + const a = JSON.parse(b).paymentPayload.payload.authorization; + if (req.url.endsWith("/verify")) return res.end(JSON.stringify({ isValid: true, payer: a.from })); + settled++; res.end(JSON.stringify({ success: true, transaction: "0x" + "cd".repeat(32), network: SEPOLIA, payer: a.from })); + }); + }); + await new Promise((r) => fac.listen(0, "127.0.0.1", r)); + const app = createMarketApp({ payTo, facilitatorUrl: `http://127.0.0.1:${fac.address().port}`, read: async () => ({ network: SEPOLIA, feePressure: "NORMAL" }) }); + const srv = createServer(app); + await new Promise((r) => srv.listen(0, "127.0.0.1", r)); + const base = `http://127.0.0.1:${srv.address().port}`; + try { + const info = await (await fetch(`${base}/v1/market/info`)).json(); + assert.equal(info.price, "$0.01"); + assert.equal(info.payTo, payTo); + assert.equal((await fetch(`${base}/v1/market`)).status, 402); + const pay = createX402Fetch({ signer: privateKeyToAccount(generatePrivateKey()), network: SEPOLIA, maxAmountPerPayment: "10000" }); + const res = await pay(`${base}/v1/market`); + assert.equal(res.status, 200); + assert.deepEqual(await res.json(), { network: SEPOLIA, feePressure: "NORMAL" }); + assert.equal(settled, 1); + assert.ok(settlementOf(res)); + } finally { srv.close(); fac.close(); } +}); + +test("the bare URL describes the market, and the network note tells the truth on each network", async () => { + const app = createMarketApp({ payTo: "0xC7484059c45Cf89dDc487C836A6f821Dc5882051", network: "eip155:84532" }); + const srv = await new Promise((ok) => { const s = app.listen(0, () => ok(s)); }); + try { + const base = `http://127.0.0.1:${srv.address().port}`; + const root = await (await fetch(base + "/")).json(); + assert.equal(root.routes.paid, "/v1/market"); + assert.equal(root.routes.info, "/v1/market/info"); + assert.equal(root.verifyReceipts, "npx -p nirium-base nirium-verify-evm receipt.json"); + assert.equal(root.note, "Test network: test tokens only."); + const info = await (await fetch(base + "/v1/market/info")).json(); + assert.ok(info.notes.includes("Test network: test tokens only.")); + } finally { srv.close(); } + assert.match(networkNote({ mainnet: true }), /^Mainnet: real USDC/); + assert.equal(networkNote({ mainnet: false }), "Test network: test tokens only."); +}); diff --git a/base/package-lock.json b/base/package-lock.json new file mode 100644 index 0000000..c573721 --- /dev/null +++ b/base/package-lock.json @@ -0,0 +1,1305 @@ +{ + "name": "nirium-base", + "version": "0.3.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "nirium-base", + "version": "0.3.0", + "license": "Apache-2.0", + "dependencies": { + "@x402/core": "2.32.0", + "@x402/evm": "2.32.0", + "@x402/express": "2.32.0", + "@x402/fetch": "2.32.0", + "viem": "2.58.7" + }, + "bin": { + "nirium-verify-evm": "verify-evm-receipt.mjs" + }, + "devDependencies": { + "express": "5.3.0" + }, + "engines": { + "node": ">=20" + }, + "peerDependencies": { + "express": "^4.22.3 || ^5.3.0" + }, + "peerDependenciesMeta": { + "express": { + "optional": true + } + } + }, + "node_modules/@adraffy/ens-normalize": { + "version": "1.11.1", + "resolved": "https://registry.npmjs.org/@adraffy/ens-normalize/-/ens-normalize-1.11.1.tgz", + "integrity": "sha512-nhCBV3quEgesuf7c7KYfperqSS14T8bYuvJ8PcLJp6znkZpFc0AuW4qBtr8eKVyPPe/8RSr7sglCWPU5eaxwKQ==", + "license": "MIT" + }, + "node_modules/@noble/ciphers": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/@noble/ciphers/-/ciphers-1.3.0.tgz", + "integrity": "sha512-2I0gnIVPtfnMw9ee9h1dJG7tp81+8Ob3OJb3Mv37rx5L40/b0i7djjCVvGOVqc9AEIQyvyu1i6ypKdFw8R8gQw==", + "license": "MIT", + "engines": { + "node": "^14.21.3 || >=16" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, + "node_modules/@noble/curves": { + "version": "1.9.7", + "resolved": "https://registry.npmjs.org/@noble/curves/-/curves-1.9.7.tgz", + "integrity": "sha512-gbKGcRUYIjA3/zCCNaWDciTMFI0dCkvou3TL8Zmy5Nc7sJ47a0jtOeZoTaMxkuqRo9cRhjOdZJXegxYE5FN/xw==", + "license": "MIT", + "dependencies": { + "@noble/hashes": "1.8.0" + }, + "engines": { + "node": "^14.21.3 || >=16" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, + "node_modules/@noble/hashes": { + "version": "1.8.0", + "resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-1.8.0.tgz", + "integrity": "sha512-jCs9ldd7NwzpgXDIf6P3+NrHh9/sD6CQdxHyjQI+h/6rDNo88ypBxxz45UDuZHz9r3tNz7N/VInSVoVdtXEI4A==", + "license": "MIT", + "engines": { + "node": "^14.21.3 || >=16" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, + "node_modules/@scure/base": { + "version": "1.2.6", + "resolved": "https://registry.npmjs.org/@scure/base/-/base-1.2.6.tgz", + "integrity": "sha512-g/nm5FgUa//MCj1gV09zTJTaM6KBAHqLN907YVQqf7zC49+DcO4B1so4ZX07Ef10Twr6nuqYEH9GEggFXA4Fmg==", + "license": "MIT", + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, + "node_modules/@scure/bip32": { + "version": "1.7.0", + "resolved": "https://registry.npmjs.org/@scure/bip32/-/bip32-1.7.0.tgz", + "integrity": "sha512-E4FFX/N3f4B80AKWp5dP6ow+flD1LQZo/w8UnLGYZO674jS6YnYeepycOOksv+vLPSpgN35wgKgy+ybfTb2SMw==", + "license": "MIT", + "dependencies": { + "@noble/curves": "~1.9.0", + "@noble/hashes": "~1.8.0", + "@scure/base": "~1.2.5" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, + "node_modules/@scure/bip39": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/@scure/bip39/-/bip39-1.6.0.tgz", + "integrity": "sha512-+lF0BbLiJNwVlev4eKelw1WWLaiKXw7sSl8T6FvBlWkdX+94aGJ4o8XjUdlyhTCjd8c+B3KT3JfS8P0bLRNU6A==", + "license": "MIT", + "dependencies": { + "@noble/hashes": "~1.8.0", + "@scure/base": "~1.2.5" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, + "node_modules/@signinwithethereum/siwe": { + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/@signinwithethereum/siwe/-/siwe-4.2.1.tgz", + "integrity": "sha512-CQEQhCIgN9blil1YpaGR+wvGPdsBVK6zed5DBu03s1IdbSO3kA/n7Zp+SAkZGiHy3HY6OJm1Su0/Bd33vKK6nQ==", + "license": "Apache-2.0", + "dependencies": { + "@signinwithethereum/siwe-parser": "^4.2.1" + }, + "peerDependencies": { + "ethers": "^5.7.0 || ^6.13.0", + "viem": "^2.7.0" + }, + "peerDependenciesMeta": { + "ethers": { + "optional": true + }, + "viem": { + "optional": true + } + } + }, + "node_modules/@signinwithethereum/siwe-parser": { + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/@signinwithethereum/siwe-parser/-/siwe-parser-4.2.1.tgz", + "integrity": "sha512-GAdwNiBaRpUMTiFfPrbQ3e/RBhPbEhRRN1sZmDMLgLEZuKqKwO7V0ksVzCerE9l8HFKTNw5R/q3kPDCWJRz4zA==", + "license": "Apache-2.0", + "dependencies": { + "@noble/hashes": "^1.7.0", + "apg-js": "^4.4.0" + } + }, + "node_modules/@x402/core": { + "version": "2.32.0", + "resolved": "https://registry.npmjs.org/@x402/core/-/core-2.32.0.tgz", + "integrity": "sha512-HyS8vbaR3XP79EIATKGMt8eL0Ql46yrfVDrtv1Inmlx4qJl4NU61cJmTh/pSGOCJIeb7ETNhWR/GQ4XsWZcQIA==", + "license": "Apache-2.0", + "dependencies": { + "zod": "^4.6.6" + } + }, + "node_modules/@x402/evm": { + "version": "2.32.0", + "resolved": "https://registry.npmjs.org/@x402/evm/-/evm-2.32.0.tgz", + "integrity": "sha512-dgsBYsUGs2Qem2NVV5QkhpyWJ4dssigE4LJ662LKcN1+9PKxBbX2Q5l2dpzkmHmXXzUoyapG5yBkYhMkckRZ7Q==", + "license": "Apache-2.0", + "dependencies": { + "@x402/core": "~2.32.0", + "viem": "^2.48.11", + "zod": "^4.6.6" + } + }, + "node_modules/@x402/express": { + "version": "2.32.0", + "resolved": "https://registry.npmjs.org/@x402/express/-/express-2.32.0.tgz", + "integrity": "sha512-aPZDcDsSIAy6dz5YmcuosoBRy4t2VUCwzeZG/S5bxE7xZfxouyRbm3M+mlUNHymAjy4Z/lNqK6jummRe770AGw==", + "license": "Apache-2.0", + "dependencies": { + "@x402/core": "~2.32.0", + "@x402/extensions": "~2.32.0" + }, + "peerDependencies": { + "@x402/paywall": "^2.32.0", + "express": "^4.22.3 || ^5.3.0" + }, + "peerDependenciesMeta": { + "@x402/paywall": { + "optional": true + } + } + }, + "node_modules/@x402/extensions": { + "version": "2.32.0", + "resolved": "https://registry.npmjs.org/@x402/extensions/-/extensions-2.32.0.tgz", + "integrity": "sha512-bvhqNqCjmULkjCpjM1fJvDfoL8tzp1IFcMTXN7QJTwqM22ucNe8B4UefKeQOCpjJ3tuIEbp8k9A0fR0CiYtjrQ==", + "license": "Apache-2.0", + "dependencies": { + "@noble/curves": "^1.9.0", + "@scure/base": "^1.2.6", + "@signinwithethereum/siwe": "^4.1.0", + "@x402/core": "~2.32.0", + "ajv": "^8.18.0", + "jose": "^5.9.6", + "tweetnacl": "^1.0.3", + "viem": "^2.48.11", + "zod": "^4.6.6" + } + }, + "node_modules/@x402/fetch": { + "version": "2.32.0", + "resolved": "https://registry.npmjs.org/@x402/fetch/-/fetch-2.32.0.tgz", + "integrity": "sha512-MxDqmBxQz6I5NWUVu90cQ1XRZayAi8oDpGllDwrwihxfAHloE7eqXkNuFC80IRE3BbMwj8h65aBEaOaiq3EBUQ==", + "license": "Apache-2.0", + "dependencies": { + "@x402/core": "~2.32.0" + } + }, + "node_modules/abitype": { + "version": "1.2.3", + "resolved": "https://registry.npmjs.org/abitype/-/abitype-1.2.3.tgz", + "integrity": "sha512-Ofer5QUnuUdTFsBRwARMoWKOH1ND5ehwYhJ3OJ/BQO+StkwQjHw0XyVh4vDttzHB7QOFhPHa/o413PJ82gU/Tg==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/wevm" + }, + "peerDependencies": { + "typescript": ">=5.0.4", + "zod": "^3.22.0 || ^4.0.0" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + }, + "zod": { + "optional": true + } + } + }, + "node_modules/accepts": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/accepts/-/accepts-2.0.0.tgz", + "integrity": "sha512-5cvg6CtKwfgdmVqY1WIiXKc3Q1bkRqGLi+2W/6ao+6Y7gu/RCwRuAhGEzh5B4KlszSuTLgZYuqFqo5bImjNKng==", + "license": "MIT", + "dependencies": { + "mime-types": "^3.0.0", + "negotiator": "^1.0.0" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/ajv": { + "version": "8.20.0", + "resolved": "https://registry.npmjs.org/ajv/-/ajv-8.20.0.tgz", + "integrity": "sha512-Thbli+OlOj+iMPYFBVBfJ3OmCAnaSyNn4M1vz9T6Gka5Jt9ba/HIR56joy65tY6kx/FCF5VXNB819Y7/GUrBGA==", + "license": "MIT", + "dependencies": { + "fast-deep-equal": "^3.1.3", + "fast-uri": "^3.0.1", + "json-schema-traverse": "^1.0.0", + "require-from-string": "^2.0.2" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/epoberezkin" + } + }, + "node_modules/apg-js": { + "version": "4.4.0", + "resolved": "https://registry.npmjs.org/apg-js/-/apg-js-4.4.0.tgz", + "integrity": "sha512-fefmXFknJmtgtNEXfPwZKYkMFX4Fyeyz+fNF6JWp87biGOPslJbCBVU158zvKRZfHBKnJDy8CMM40oLFGkXT8Q==", + "license": "BSD-2-Clause" + }, + "node_modules/body-parser": { + "version": "2.4.0", + "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-2.4.0.tgz", + "integrity": "sha512-Ifk1KcLrxaGt1occQagQNFNNOqRt1LFuehEnHHzB8Z6cRgIxRU1TBaiIsUiCdA+gy5PL7Y1IX31DNKkRmxtXjQ==", + "license": "MIT", + "dependencies": { + "bytes": "^3.1.2", + "content-type": "^2.1.0", + "debug": "^4.4.3", + "http-errors": "^2.0.1", + "iconv-lite": "^0.7.3", + "on-finished": "^2.4.1", + "qs": "^6.16.1", + "raw-body": "^3.0.2", + "type-is": "^2.1.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/bytes": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.2.tgz", + "integrity": "sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/call-bind-apply-helpers": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz", + "integrity": "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/call-bound": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/call-bound/-/call-bound-1.0.4.tgz", + "integrity": "sha512-+ys997U96po4Kx/ABpBCqhA9EuxJaQWDQg7295H4hBphv3IZg0boBKuwYpt4YXp6MZ5AmZQnU/tyMTlRpaSejg==", + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.2", + "get-intrinsic": "^1.3.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/content-disposition": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-2.0.1.tgz", + "integrity": "sha512-e+H0ZXHSWYrENhQzw1LPuP4oF5MzVKmDU6d3hxlvaPEYLLg62MxtQNPRx4SYSuYJSBUgnQIG4HIN2tEtNv7Dog==", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/content-type": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/content-type/-/content-type-2.1.0.tgz", + "integrity": "sha512-mj7UPXE0jaqaOsukNZRUEfEi2AcL7C/vwmwcHV0O97eO1E1pxBZuyjlZrx5seTaNBg1U6+o35wpa35Qfcc+7ag==", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/cookie": { + "version": "0.7.2", + "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.7.2.tgz", + "integrity": "sha512-yki5XnKuf750l50uGTllt6kKILY4nQ1eNIQatoXEByZ5dWgnKqbnqmTrBE5B4N7lrMJKQ2ytWMiTO2o0v6Ew/w==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/cookie-signature": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.2.2.tgz", + "integrity": "sha512-D76uU73ulSXrD1UXF4KE2TMxVVwhsnCgfAyTg9k8P6KGZjlXKrOLe4dJQKI3Bxi5wjesZoFXJWElNWBjPZMbhg==", + "license": "MIT", + "engines": { + "node": ">=6.6.0" + } + }, + "node_modules/debug": { + "version": "4.4.3", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", + "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", + "license": "MIT", + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/depd": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz", + "integrity": "sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/dunder-proto": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz", + "integrity": "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==", + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.1", + "es-errors": "^1.3.0", + "gopd": "^1.2.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/ee-first": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz", + "integrity": "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==", + "license": "MIT" + }, + "node_modules/encodeurl": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-2.0.3.tgz", + "integrity": "sha512-mIteYONiEfc4xWf2F1WXovh1c8npzS00vNeiUPdwFF+QlVJni+gNvpQltLMQhob8rew/bWWc/bGTuUr0EUGt0w==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/es-define-property": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz", + "integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-errors": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz", + "integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-object-atoms": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.2.tgz", + "integrity": "sha512-HWcBoN6NileqtSydK2FqHbS/LoDd2pqrnQHLyJzBj4kOp/ky2MWMN694xOfkK8/SnUsW2DH7EfyVlydKCsm1Zw==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/escape-html": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/escape-html/-/escape-html-1.0.3.tgz", + "integrity": "sha512-NiSupZ4OeuGwr68lGIeym/ksIZMJodUGOSCZ/FSnTxcrekbvqrgdUxlJOMpijaKZVjAJrWrGs/6Jy8OMuyj9ow==", + "license": "MIT" + }, + "node_modules/etag": { + "version": "1.8.1", + "resolved": "https://registry.npmjs.org/etag/-/etag-1.8.1.tgz", + "integrity": "sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/eventemitter3": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/eventemitter3/-/eventemitter3-5.0.1.tgz", + "integrity": "sha512-GWkBvjiSZK87ELrYOSESUYeVIc9mvLLf/nXalMOS5dYrgZq9o5OVkbZAVM06CVxYsCwH9BDZFPlQTlPA1j4ahA==", + "license": "MIT" + }, + "node_modules/express": { + "version": "5.3.0", + "resolved": "https://registry.npmjs.org/express/-/express-5.3.0.tgz", + "integrity": "sha512-qCqy1xSoaugxOD4IVHb1ZWdkvCF2W3aE2okKouWj8VwJ+ztskSiXoBnCSJqfKT+cVPJhuJqe9YLbY425+Zh00g==", + "license": "MIT", + "dependencies": { + "accepts": "^2.0.0", + "body-parser": "^2.3.0", + "content-disposition": "^2.0.1", + "content-type": "^2.0.0", + "cookie": "^0.7.1", + "cookie-signature": "^1.2.1", + "debug": "^4.4.0", + "depd": "^2.0.0", + "encodeurl": "^2.0.0", + "escape-html": "^1.0.3", + "etag": "^1.8.1", + "finalhandler": "^2.1.0", + "fresh": "^2.0.0", + "http-errors": "^2.0.0", + "merge-descriptors": "^2.0.0", + "mime-types": "^3.0.0", + "on-finished": "^2.4.1", + "once": "^1.4.0", + "parseurl": "^1.3.3", + "proxy-addr": "^2.0.8", + "qs": "^6.16.0", + "range-parser": "^1.2.1", + "router": "^2.2.0", + "send": "^1.1.0", + "serve-static": "^2.2.0", + "statuses": "^2.0.1", + "type-is": "^2.1.0", + "vary": "^1.1.2" + }, + "engines": { + "node": ">= 18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/fast-deep-equal": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz", + "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==", + "license": "MIT" + }, + "node_modules/fast-uri": { + "version": "3.1.9", + "resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.9.tgz", + "integrity": "sha512-hS/0Wt3Ya043oKXs0sIxrMpKQITXhMLIrVAKKXi4gozGC9v7YRWVnXIZzjNPTO02M9BdxLCWqK1yRXgNziVyJQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/fastify" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/fastify" + } + ], + "license": "BSD-3-Clause" + }, + "node_modules/finalhandler": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-2.1.1.tgz", + "integrity": "sha512-S8KoZgRZN+a5rNwqTxlZZePjT/4cnm0ROV70LedRHZ0p8u9fRID0hJUZQpkKLzro8LfmC8sx23bY6tVNxv8pQA==", + "license": "MIT", + "dependencies": { + "debug": "^4.4.0", + "encodeurl": "^2.0.0", + "escape-html": "^1.0.3", + "on-finished": "^2.4.1", + "parseurl": "^1.3.3", + "statuses": "^2.0.1" + }, + "engines": { + "node": ">= 18.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/forwarded": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/forwarded/-/forwarded-0.2.0.tgz", + "integrity": "sha512-buRG0fpBtRHSTCOASe6hD258tEubFoRLb4ZNA6NxMVHNw2gOcwHo9wyablzMzOA5z9xA9L1KNjk/Nt6MT9aYow==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/fresh": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/fresh/-/fresh-2.0.0.tgz", + "integrity": "sha512-Rx/WycZ60HOaqLKAi6cHRKKI7zxWbJ31MhntmtwMoaTeF7XFH9hhBp8vITaMidfljRQ6eYWCKkaTK+ykVJHP2A==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/function-bind": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz", + "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/get-intrinsic": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz", + "integrity": "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==", + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.2", + "es-define-property": "^1.0.1", + "es-errors": "^1.3.0", + "es-object-atoms": "^1.1.1", + "function-bind": "^1.1.2", + "get-proto": "^1.0.1", + "gopd": "^1.2.0", + "has-symbols": "^1.1.0", + "hasown": "^2.0.2", + "math-intrinsics": "^1.1.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/get-proto": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/get-proto/-/get-proto-1.0.1.tgz", + "integrity": "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==", + "license": "MIT", + "dependencies": { + "dunder-proto": "^1.0.1", + "es-object-atoms": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/gopd": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz", + "integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-symbols": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.1.0.tgz", + "integrity": "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/hasown": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.4.tgz", + "integrity": "sha512-T2UbfbBEF32wiepXIsMlTW9+dDYC6wMh/t/vYA4tuOMKqWz/n3vr1NFSxQiyP+zk2mXsoMA/i/7qV6LKut1t1A==", + "license": "MIT", + "dependencies": { + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/http-errors": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.1.tgz", + "integrity": "sha512-4FbRdAX+bSdmo4AUFuS0WNiPz8NgFt+r8ThgNWmlrjQjt1Q7ZR9+zTlce2859x4KSXrwIsaeTqDoKQmtP8pLmQ==", + "license": "MIT", + "dependencies": { + "depd": "~2.0.0", + "inherits": "~2.0.4", + "setprototypeof": "~1.2.0", + "statuses": "~2.0.2", + "toidentifier": "~1.0.1" + }, + "engines": { + "node": ">= 0.8" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/iconv-lite": { + "version": "0.7.3", + "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.7.3.tgz", + "integrity": "sha512-IKXpvIzjnC9XTAUbVBcMfGS0EPaIXtW6v+zr+RRp+hqULEpo0owZax6wyRwPOJbWbzjYspQwusTsfVr0ifh4uQ==", + "license": "MIT", + "dependencies": { + "safer-buffer": ">= 2.1.2 < 3.0.0" + }, + "engines": { + "node": ">=0.10.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/inherits": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", + "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", + "license": "ISC" + }, + "node_modules/ipaddr.js": { + "version": "1.9.1", + "resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-1.9.1.tgz", + "integrity": "sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g==", + "license": "MIT", + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/is-promise": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/is-promise/-/is-promise-4.0.0.tgz", + "integrity": "sha512-hvpoI6korhJMnej285dSg6nu1+e6uxs7zG3BYAm5byqDsgJNWwxzM6z6iZiAgQR4TJ30JmBTOwqZUw3WlyH3AQ==", + "license": "MIT" + }, + "node_modules/isows": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/isows/-/isows-1.0.7.tgz", + "integrity": "sha512-I1fSfDCZL5P0v33sVqeTDSpcstAg/N+wF5HS033mogOVIp4B+oHC7oOCsA3axAbBSGTJ8QubbNmnIRN/h8U7hg==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/wevm" + } + ], + "license": "MIT", + "peerDependencies": { + "ws": "*" + } + }, + "node_modules/jose": { + "version": "5.10.0", + "resolved": "https://registry.npmjs.org/jose/-/jose-5.10.0.tgz", + "integrity": "sha512-s+3Al/p9g32Iq+oqXxkW//7jk2Vig6FF1CFqzVXoTUXt2qz89YWbL+OwS17NFYEvxC35n0FKeGO2LGYSxeM2Gg==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/panva" + } + }, + "node_modules/json-schema-traverse": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz", + "integrity": "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==", + "license": "MIT" + }, + "node_modules/math-intrinsics": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz", + "integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/media-typer": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/media-typer/-/media-typer-1.1.1.tgz", + "integrity": "sha512-yz3xRaG20c6/BOzvYoDaGtPmGscs7YivItZEEqe6GbwNfHuxu9YNmvnEkMzKldAGY4/80pRcQRZSEnhquk9XuQ==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/merge-descriptors": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-2.0.0.tgz", + "integrity": "sha512-Snk314V5ayFLhp3fkUREub6WtjBfPdCPY1Ln8/8munuLuiYhsABgBVWsozAG+MWMbVEvcdcpbi9R7ww22l9Q3g==", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/mime-db": { + "version": "1.54.0", + "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.54.0.tgz", + "integrity": "sha512-aU5EJuIN2WDemCcAp2vFBfp/m4EAhWJnUNSSw0ixs7/kXbd6Pg64EmwJkNdFhB8aWt1sH2CTXrLxo/iAGV3oPQ==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/mime-types": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-3.0.2.tgz", + "integrity": "sha512-Lbgzdk0h4juoQ9fCKXW4by0UJqj+nOOrI9MJ1sSj4nI8aI2eo1qmvQEie4VD1glsS250n15LsWsYtCugiStS5A==", + "license": "MIT", + "dependencies": { + "mime-db": "^1.54.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", + "license": "MIT" + }, + "node_modules/negotiator": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/negotiator/-/negotiator-1.1.0.tgz", + "integrity": "sha512-NMPBRMJgiQHjbd8phG3Vebdx4kZ1H121rbl5IkMqeOsahptB9BKo/d7oJ3zTXqTgagn2bWlNSXkh0QUGM31RYg==", + "license": "MIT", + "dependencies": { + "content-type": "^2.1.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/object-inspect": { + "version": "1.14.0", + "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.14.0.tgz", + "integrity": "sha512-IVgHNlp/jwQX271+Xzoq9LZNTWXxZK+cEOrGBOBxXNbn7fapnZ+Ts6TVMgNOuAezwG2wdtnMX97tTPK6VEnuOQ==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/on-finished": { + "version": "2.4.2", + "resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.4.2.tgz", + "integrity": "sha512-ATWUv387i+nLD49EiDoOft5scf32Vsdz3ktrQJG9bi7jRFmaXTssvyvj1EmeKVVgvesbqUtvQQvaS2TpTukAZQ==", + "license": "MIT", + "dependencies": { + "ee-first": "1.1.1" + }, + "engines": { + "node": ">= 0.8" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/once": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", + "integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==", + "license": "ISC", + "dependencies": { + "wrappy": "1" + } + }, + "node_modules/ox": { + "version": "0.14.67", + "resolved": "https://registry.npmjs.org/ox/-/ox-0.14.67.tgz", + "integrity": "sha512-6v6UlwgsmiyTujZp0aVDuN8uIBAtl/QZadBADFRZ2zp1+CM9TqDzd+rPKJ5PYvWPlCvz8JvoO9dTr42+1PhBhA==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/wevm" + } + ], + "license": "MIT", + "dependencies": { + "@adraffy/ens-normalize": "^1.11.0", + "@noble/ciphers": "^1.3.0", + "@noble/curves": "1.9.1", + "@noble/hashes": "^1.8.0", + "@scure/bip32": "^1.7.0", + "@scure/bip39": "^1.6.0", + "abitype": "^1.2.3", + "eventemitter3": "5.0.1" + }, + "peerDependencies": { + "typescript": ">=5.4.0" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + } + } + }, + "node_modules/ox/node_modules/@noble/curves": { + "version": "1.9.1", + "resolved": "https://registry.npmjs.org/@noble/curves/-/curves-1.9.1.tgz", + "integrity": "sha512-k11yZxZg+t+gWvBbIswW0yoJlu8cHOC7dhunwOzoWH/mXGBiYyR4YY6hAEK/3EUs4UpB8la1RfdRpeGsFHkWsA==", + "license": "MIT", + "dependencies": { + "@noble/hashes": "1.8.0" + }, + "engines": { + "node": "^14.21.3 || >=16" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, + "node_modules/parseurl": { + "version": "1.3.3", + "resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz", + "integrity": "sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/path-to-regexp": { + "version": "8.4.2", + "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-8.4.2.tgz", + "integrity": "sha512-qRcuIdP69NPm4qbACK+aDogI5CBDMi1jKe0ry5rSQJz8JVLsC7jV8XpiJjGRLLol3N+R5ihGYcrPLTno6pAdBA==", + "license": "MIT", + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/proxy-addr": { + "version": "2.0.8", + "resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.8.tgz", + "integrity": "sha512-5nnx0yGyVUcY6t9RnWcARWtwT9F1D8O9rt08htPvnd49W1IgZtmLkhu9WfMzQj1cFxjHIO6connUNVW5k7AVyQ==", + "license": "MIT", + "dependencies": { + "forwarded": "0.2.0", + "ipaddr.js": "1.9.1" + }, + "engines": { + "node": ">= 0.10" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/qs": { + "version": "6.17.1", + "resolved": "https://registry.npmjs.org/qs/-/qs-6.17.1.tgz", + "integrity": "sha512-jd3COkaKVgGUW+ZHyEHCG9bH7RoaaiWuMgzsIBjUMVjLAaWGWpoUAVwljVvBHxRu/2qEHnadLGZrkutYUBPQJA==", + "license": "BSD-3-Clause", + "dependencies": { + "es-define-property": "^1.0.1", + "side-channel": "^1.1.1" + }, + "engines": { + "node": ">=0.6" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/range-parser": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.3.0.tgz", + "integrity": "sha512-hek2mFQpPuI4E1BBKrSto+BU3e3x4xuarsbiwr3+lf7p44juvFMV0XFWQAP3xUyqXA4RrXLIoaSUGbSt056ZMw==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/raw-body": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/raw-body/-/raw-body-3.0.2.tgz", + "integrity": "sha512-K5zQjDllxWkf7Z5xJdV0/B0WTNqx6vxG70zJE4N0kBs4LovmEYWJzQGxC9bS9RAKu3bgM40lrd5zoLJ12MQ5BA==", + "license": "MIT", + "dependencies": { + "bytes": "~3.1.2", + "http-errors": "~2.0.1", + "iconv-lite": "~0.7.0", + "unpipe": "~1.0.0" + }, + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/require-from-string": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/require-from-string/-/require-from-string-2.0.2.tgz", + "integrity": "sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/router": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/router/-/router-2.3.0.tgz", + "integrity": "sha512-bpowRfGjEPe8t9R6fJIzhwmyCGAXwKvxBUsgJm+bJukwdcWmUXbMo7p22w7aYmQBPQTUMNqMV39YX0kMou3z8w==", + "license": "MIT", + "dependencies": { + "debug": "^4.4.0", + "depd": "^2.0.0", + "is-promise": "^4.0.0", + "parseurl": "^1.3.3", + "path-to-regexp": "^8.0.0" + }, + "engines": { + "node": ">= 18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/safer-buffer": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", + "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==", + "license": "MIT" + }, + "node_modules/send": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/send/-/send-1.2.1.tgz", + "integrity": "sha512-1gnZf7DFcoIcajTjTwjwuDjzuz4PPcY2StKPlsGAQ1+YH20IRVrBaXSWmdjowTJ6u8Rc01PoYOGHXfP1mYcZNQ==", + "license": "MIT", + "dependencies": { + "debug": "^4.4.3", + "encodeurl": "^2.0.0", + "escape-html": "^1.0.3", + "etag": "^1.8.1", + "fresh": "^2.0.0", + "http-errors": "^2.0.1", + "mime-types": "^3.0.2", + "ms": "^2.1.3", + "on-finished": "^2.4.1", + "range-parser": "^1.2.1", + "statuses": "^2.0.2" + }, + "engines": { + "node": ">= 18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/serve-static": { + "version": "2.2.1", + "resolved": "https://registry.npmjs.org/serve-static/-/serve-static-2.2.1.tgz", + "integrity": "sha512-xRXBn0pPqQTVQiC8wyQrKs2MOlX24zQ0POGaj0kultvoOCstBQM5yvOhAVSUwOMjQtTvsPWoNCHfPGwaaQJhTw==", + "license": "MIT", + "dependencies": { + "encodeurl": "^2.0.0", + "escape-html": "^1.0.3", + "parseurl": "^1.3.3", + "send": "^1.2.0" + }, + "engines": { + "node": ">= 18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/setprototypeof": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.2.0.tgz", + "integrity": "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==", + "license": "ISC" + }, + "node_modules/side-channel": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.1.1.tgz", + "integrity": "sha512-6x6dK6zJdpTzF4sQeNYxwtvBzf6Eg4GtlesS94HOvTudUeyK2WXAaIfmDgsyslYrRBeFIlsi54AYsFGUuhmvrQ==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "object-inspect": "^1.13.4", + "side-channel-list": "^1.0.1", + "side-channel-map": "^1.0.1", + "side-channel-weakmap": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-list": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/side-channel-list/-/side-channel-list-1.0.1.tgz", + "integrity": "sha512-mjn/0bi/oUURjc5Xl7IaWi/OJJJumuoJFQJfDDyO46+hBWsfaVM65TBHq2eoZBhzl9EchxOijpkbRC8SVBQU0w==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "object-inspect": "^1.13.4" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-map": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/side-channel-map/-/side-channel-map-1.0.1.tgz", + "integrity": "sha512-VCjCNfgMsby3tTdo02nbjtM/ewra6jPHmpThenkTYh8pG9ucZ/1P8So4u4FGBek/BjpOVsDCMoLA/iuBKIFXRA==", + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.2", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.5", + "object-inspect": "^1.13.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-weakmap": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/side-channel-weakmap/-/side-channel-weakmap-1.0.2.tgz", + "integrity": "sha512-WPS/HvHQTYnHisLo9McqBHOJk2FkHO/tlpvldyrnem4aeQp4hai3gythswg6p01oSoTl58rcpiFAjF2br2Ak2A==", + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.2", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.5", + "object-inspect": "^1.13.3", + "side-channel-map": "^1.0.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/statuses": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.2.tgz", + "integrity": "sha512-DvEy55V3DB7uknRo+4iOGT5fP1slR8wQohVdknigZPMpMstaKJQWhwiYBACJE3Ul2pTnATihhBYnRhZQHGBiRw==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/toidentifier": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/toidentifier/-/toidentifier-1.0.1.tgz", + "integrity": "sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA==", + "license": "MIT", + "engines": { + "node": ">=0.6" + } + }, + "node_modules/tweetnacl": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/tweetnacl/-/tweetnacl-1.0.3.tgz", + "integrity": "sha512-6rt+RN7aOi1nGMyC4Xa5DdYiukl2UWCbcJft7YhxReBGQD7OAM8Pbxw6YMo4r2diNEA8FEmu32YOn9rhaiE5yw==", + "license": "Unlicense" + }, + "node_modules/type-is": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/type-is/-/type-is-2.1.0.tgz", + "integrity": "sha512-faYHw0anBbc/kWF3zFTEnxSFOAGUX9GFbOBthvDdLsIlEoWOFOtS0zgCiQYwIskL9iGXZL3kAXD8OoZ4GmMATA==", + "license": "MIT", + "dependencies": { + "content-type": "^2.0.0", + "media-typer": "^1.1.0", + "mime-types": "^3.0.0" + }, + "engines": { + "node": ">= 18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/unpipe": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz", + "integrity": "sha512-pjy2bYhSsufwWlKwPc+l3cN7+wuJlK6uz0YdJEOlQDbl6jo/YlPi4mb8agUkVC8BF7V8NuzeyPNqRksA3hztKQ==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/vary": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz", + "integrity": "sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/viem": { + "version": "2.58.7", + "resolved": "https://registry.npmjs.org/viem/-/viem-2.58.7.tgz", + "integrity": "sha512-9s29POkcUOdlvEN5ePdBTBryhoEQE+ikXuuwjvJRqTc99yCMVkVqwvrjogYpTaJLo2rIrgOEjAglbdr6DCRdkg==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/wevm" + } + ], + "license": "MIT", + "dependencies": { + "@noble/curves": "1.9.1", + "@noble/hashes": "1.8.0", + "@scure/bip32": "1.7.0", + "@scure/bip39": "1.6.0", + "abitype": "1.2.3", + "isows": "1.0.7", + "ox": "0.14.67", + "ws": "8.21.0" + }, + "peerDependencies": { + "mppx": ">=0.17.0", + "typescript": ">=5.0.4" + }, + "peerDependenciesMeta": { + "mppx": { + "optional": true + }, + "typescript": { + "optional": true + } + } + }, + "node_modules/viem/node_modules/@noble/curves": { + "version": "1.9.1", + "resolved": "https://registry.npmjs.org/@noble/curves/-/curves-1.9.1.tgz", + "integrity": "sha512-k11yZxZg+t+gWvBbIswW0yoJlu8cHOC7dhunwOzoWH/mXGBiYyR4YY6hAEK/3EUs4UpB8la1RfdRpeGsFHkWsA==", + "license": "MIT", + "dependencies": { + "@noble/hashes": "1.8.0" + }, + "engines": { + "node": "^14.21.3 || >=16" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, + "node_modules/wrappy": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", + "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==", + "license": "ISC" + }, + "node_modules/ws": { + "version": "8.21.0", + "resolved": "https://registry.npmjs.org/ws/-/ws-8.21.0.tgz", + "integrity": "sha512-Vsp28b7DRcimFQvrqu2Wek3z1iYxDCWqHYB8Qsnk/S4RfaCQzPGPyBNuVjJV3cd6UiKtUtp6sNM77gWvzcCH+g==", + "license": "MIT", + "engines": { + "node": ">=10.0.0" + }, + "peerDependencies": { + "bufferutil": "^4.0.1", + "utf-8-validate": ">=5.0.2" + }, + "peerDependenciesMeta": { + "bufferutil": { + "optional": true + }, + "utf-8-validate": { + "optional": true + } + } + }, + "node_modules/zod": { + "version": "4.6.7", + "resolved": "https://registry.npmjs.org/zod/-/zod-4.6.7.tgz", + "integrity": "sha512-g8W2D2kU6a8untc053fX1uVBKzM7yqAxW/3zwk83+6RyF2+SKOuV+c0wBDhUwzV1PaGapmZH+rmcUzPf+3CGwg==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/colinhacks" + } + } + } +} diff --git a/base/package.json b/base/package.json new file mode 100755 index 0000000..61cd8c4 --- /dev/null +++ b/base/package.json @@ -0,0 +1,74 @@ +{ + "name": "nirium-base", + "version": "0.3.0", + "description": "Pay and charge with x402 on Base, refuse a payment before it is signed, and keep a payer-signed receipt bound to the exact USDC transfer", + "type": "module", + "license": "Apache-2.0", + "repository": { + "type": "git", + "url": "git+https://github.com/nirium-protocol/nirium-base.git", + "directory": "base" + }, + "homepage": "https://github.com/nirium-protocol/nirium-base#readme", + "bugs": { + "url": "https://github.com/nirium-protocol/nirium-base/issues" + }, + "keywords": [ + "x402", + "base", + "usdc", + "payments", + "receipts", + "ai-agents", + "eip-3009" + ], + "exports": { + ".": "./sdk/index.mjs", + "./policy": "./policy/evm-policy.mjs", + "./policy/x402-fetch": "./policy/x402-fetch.mjs", + "./policy/rules": "./policy/rules-policy.mjs", + "./receipt": "./sdk/receipt.mjs", + "./decision": "./sdk/decision.mjs", + "./verify": "./verify-evm-core.mjs", + "./package.json": "./package.json" + }, + "bin": { + "nirium-verify-evm": "verify-evm-receipt.mjs" + }, + "files": [ + "sdk/*.mjs", + "policy/evm-policy.mjs", + "policy/x402-fetch.mjs", + "policy/rules-policy.mjs", + "verify-evm-core.mjs", + "verify-evm-receipt.mjs" + ], + "scripts": { + "test": "node --test test/*.test.mjs policy/test/*.test.mjs sdk/test/*.test.mjs", + "test:verify": "node --test test/*.test.mjs", + "test:policy": "node --test policy/test/*.test.mjs", + "test:sdk": "node --test sdk/test/*.test.mjs", + "test:live": "bash run-tests.sh" + }, + "engines": { + "node": ">=20" + }, + "dependencies": { + "viem": "2.58.7", + "@x402/core": "2.32.0", + "@x402/evm": "2.32.0", + "@x402/express": "2.32.0", + "@x402/fetch": "2.32.0" + }, + "peerDependencies": { + "express": "^4.22.3 || ^5.3.0" + }, + "peerDependenciesMeta": { + "express": { + "optional": true + } + }, + "devDependencies": { + "express": "5.3.0" + } +} diff --git a/base/policy/README.md b/base/policy/README.md new file mode 100644 index 0000000..1b3b3a5 --- /dev/null +++ b/base/policy/README.md @@ -0,0 +1,76 @@ +# Pre-sign policy for x402 on Base + +A payment that your policy refuses is never signed. + +`@x402/evm` builds the EIP-3009 `TransferWithAuthorization` (amount, destination, token, chain, +nonce) and hands it to the signer. This package wraps that signer: it decodes exactly what is +about to be signed, checks it matches what the seller asked for, asks your policy, and only +signs on an ALLOW that is bound to that exact authorization and still valid. Everything else +ends without a signature, so nothing reaches the seller or the facilitator. + +It is the same contract as the Stellar policy hook in the `nirium` package: same verdicts, same +outcomes, same `contextHash`. + +## Use + +```js +import { privateKeyToAccount } from "viem/accounts"; +import { createPolicyX402Fetch } from "nirium-base/policy/x402-fetch"; +import { createRulesPolicy } from "nirium-base/policy/rules"; + +const pay = createPolicyX402Fetch({ + signer: privateKeyToAccount(process.env.NIRIUM_EVM_PAYER_KEY), + policy: createRulesPolicy({ maxAmount: "10000", allowPayTo: ["0x..."] }), + network: "eip155:84532", + asset: "0x036CbD53842c5426634e7929541eC2318f3dCF7e", // Base Sepolia USDC + maxAmountPerPayment: "10000", +}); +const res = await pay("https://seller.example/paid"); // throws X402PolicyError on a refusal +``` + +`createRulesPolicy` is a small reference engine (max amount, approval line, allowed payTo and +tokens). Any engine works if it implements `evaluate(context) -> { decision, contextHash, ... }`. + +## What the policy sees + +`context.authorization` is decoded from the typed data itself, not from what the seller said: +`amount`, `to`, `from`, `verifyingContract` (token), `chainId`, `domainName`, `domainVersion`, +`validAfter`, `validBefore`, `nonce`, and `payloadHash` (the EIP-712 digest). `context.contextHash` +is sha256 of `{v: 1, url, method, payloadHash}`; an ALLOW must return it unchanged. + +## Verdicts and outcomes + +| Engine answer | Outcome | Signed? | +|---|---|---| +| ALLOW with this `contextHash`, not expired, current `policyVersion` | `ALLOWED` then `SIGNED` | yes | +| DENY | `DENY` | no | +| WAIT (a person has to approve) | `WAIT` | no | +| ALLOW with another or no `contextHash` | `UNBOUND` | no | +| ALLOW past `expiresAt`, or without it when `requireExpiry` | `EXPIRED` | no | +| ALLOW under an older `policyVersion` | `STALE` | no | +| no answer in time (5 s, never more than half the payment window) | `TIMEOUT` | no | +| engine throws, unknown verdict, malformed fields | `ENGINE_ERROR` / `MALFORMED` | no | +| typed data that is not EIP-3009, or differs from the requirements | `CONTEXT_MISMATCH` (engine not asked) | no | +| signer address changed, clock not a finite number | `SIGNER_CHANGED` / `CLOCK_INVALID` | no | + +`onDecision` is an observer for receipts: it sees every outcome and cannot change any of them. + +## Tests + +```bash +cd .. && npm ci && npm run test:policy # 19 tests, no network: typed data comes from the real @x402/evm 2.32.0 +``` + +The last test runs `@x402/fetch` end to end against a local seller: on DENY the seller never +receives a payment; on ALLOW it receives one whose signature verifies as the payer's. + +## Live run (Base Sepolia) + +`demo-pay.mjs` pays the `../demo` server through this gate. See `../../evidence/README.md` +for a DENY, a WAIT and an ALLOW against PayAI on Base Sepolia, with the payer's balance before and after. + +## Limits + +- Only EIP-3009 `exact` is gated. Permit2 and EIP-2612 typed data are refused, not evaluated. +- Not a security boundary against code in the same process: whoever holds the base signer can + call it directly. diff --git a/base/policy/demo-pay.mjs b/base/policy/demo-pay.mjs new file mode 100644 index 0000000..ae452d3 --- /dev/null +++ b/base/policy/demo-pay.mjs @@ -0,0 +1,66 @@ +// demo-pay.mjs - pays an x402 resource on Base only if the rules policy says ALLOW. +// +// Usage: +// NIRIUM_EVM_PAYER_KEY=0x.. node demo-pay.mjs --url http://localhost:4021/paid \ +// --max 10000 [--approval-above 5000] [--allow-payto 0x..] [--network eip155:84532] +// +// Prints every decision the gate records (ALLOWED, SIGNED or the refusal) and, when paid, +// the settlement tx. On DENY or WAIT nothing is signed and nothing is sent to the seller. +// Mainnet (eip155:8453) needs NIRIUM_ALLOW_MAINNET=1. + +import { writeFileSync } from "node:fs"; +import { privateKeyToAccount } from "viem/accounts"; +import { decodePaymentResponseHeader } from "@x402/fetch"; +import { createPolicyX402Fetch } from "./x402-fetch.mjs"; +import { createRulesPolicy } from "./rules-policy.mjs"; +import { X402PolicyError } from "./evm-policy.mjs"; + +const USDC = { + "eip155:84532": "0x036CbD53842c5426634e7929541eC2318f3dCF7e", + "eip155:8453": "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913", +}; +const args = process.argv.slice(2); +const opt = (k, d) => { const i = args.indexOf(k); return i >= 0 && args[i + 1] ? args[i + 1] : d; }; +const network = opt("--network", "eip155:84532"); +const url = opt("--url"); +const max = opt("--max"); +const key = process.env.NIRIUM_EVM_PAYER_KEY; + +if (!url || !max) { console.error("usage: node demo-pay.mjs --url --max [--approval-above n] [--allow-payto 0x..] [--network caip2]"); process.exit(2); } +if (!USDC[network]) { console.error(`unsupported network ${network}`); process.exit(2); } +if (network === "eip155:8453" && process.env.NIRIUM_ALLOW_MAINNET !== "1") { console.error("refusing to pay on mainnet without NIRIUM_ALLOW_MAINNET=1"); process.exit(2); } +if (!key || !/^0x[0-9a-fA-F]{64}$/.test(key)) { console.error("NIRIUM_EVM_PAYER_KEY must be a 0x-prefixed 32-byte hex key"); process.exit(2); } + +const signer = privateKeyToAccount(key); +const records = []; +const policy = createRulesPolicy({ + maxAmount: max, + approvalAbove: opt("--approval-above"), + allowPayTo: opt("--allow-payto") ? [opt("--allow-payto")] : undefined, + allowAssets: [USDC[network]], + onDecision: (r) => { + records.push(r.outcome); + const a = r.context?.authorization; + console.log(`policy ${r.outcome}${a ? ` amount=${a.amount} to=${a.to}` : ""}${r.decision?.reason ? ` reason="${r.decision.reason}"` : ""}`); + }, +}); + +const pay = createPolicyX402Fetch({ signer, policy, network, asset: USDC[network], maxAmountPerPayment: "1000000" }); +console.log(`payer=${signer.address} network=${network} url=${url} policy: max=${max}${opt("--approval-above") ? ` approvalAbove=${opt("--approval-above")}` : ""}`); +try { + const res = await pay(url); + const header = res.headers.get("PAYMENT-RESPONSE"); + console.log(`HTTP ${res.status}`); + if (!header) { console.error("no PAYMENT-RESPONSE header: nothing settled"); process.exit(1); } + const settle = decodePaymentResponseHeader(header); + if (!settle.success) { console.error(`settlement failed: ${settle.errorReason}`); process.exit(1); } + writeFileSync("settle.json", JSON.stringify({ tx: settle.transaction, network, payer: signer.address, resource: url }, null, 2)); + console.log(`tx: ${settle.transaction}`); + console.log("wrote settle.json"); +} catch (e) { + if (e instanceof X402PolicyError) { + console.log(`REFUSED by policy: ${e.outcome}. Nothing was signed and nothing was sent to the seller.`); + process.exit(3); + } + throw e; +} diff --git a/base/policy/evm-policy.mjs b/base/policy/evm-policy.mjs new file mode 100644 index 0000000..383170b --- /dev/null +++ b/base/policy/evm-policy.mjs @@ -0,0 +1,367 @@ +// Pre-sign policy gate for x402 `exact` payments on EVM chains (Base and Base Sepolia). +// +// Same contract as the Stellar gate in the `nirium` SDK (x402-policy.ts): the policy engine +// is asked AFTER the exact authorization is built and BEFORE anything is signed, and only an +// ALLOW bound to that exact authorization, still valid, reaches the signer. DENY, WAIT, an +// error, a timeout, a malformed or stale answer, or a bad clock sign nothing. +// +// Where it hooks in: @x402/evm 2.32.0 builds the EIP-3009 `TransferWithAuthorization` +// message inside createPaymentPayload and hands it to `signer.signTypedData`. That call is +// the only place where amount, destination, token, chain and nonce all exist together, so +// the gate wraps it. Any other typed data (Permit2, EIP-2612 Permit, anything else) is +// refused before the policy is consulted: this gate only knows how to read EIP-3009. +// +// Not a security boundary against code in the same process: whoever holds the base signer +// can still call it directly. + +import { getAddress, hashTypedData, isAddress, sha256, stringToBytes } from "viem"; + +const DEFAULT_TIMEOUT_MS = 5000; +const HEX32 = /^0x[0-9a-fA-F]{64}$/; +const SIG65 = /^0x[0-9a-fA-F]{130}$/; + +// The exact EIP-3009 type @x402/evm signs (field order matters for the EIP-712 hash). +const TRANSFER_WITH_AUTHORIZATION = [ + { name: "from", type: "address" }, + { name: "to", type: "address" }, + { name: "value", type: "uint256" }, + { name: "validAfter", type: "uint256" }, + { name: "validBefore", type: "uint256" }, + { name: "nonce", type: "bytes32" }, +]; + +/** @typedef {'ALLOW'|'DENY'|'WAIT'} X402PolicyVerdict */ +/** + * @typedef {Object} X402PaymentRequirementsView + * @property {string} scheme + * @property {string} network CAIP-2, e.g. "eip155:84532" + * @property {string} asset ERC-20 contract (EIP-3009 token) + * @property {string} payTo + * @property {string} amount atomic units, decimal string + * @property {number} maxTimeoutSeconds + * @property {{name?: string, version?: string}} [extra] EIP-712 domain the server asked for + */ +/** + * @typedef {Object} X402PolicyDecision + * @property {X402PolicyVerdict} decision + * @property {string} [contextHash] required on ALLOW, must equal the context's + * @property {string} [reason] + * @property {string} [policyVersion] required on ALLOW when `currentVersion` is set + * @property {number} [expiresAt] epoch ms; equality counts as expired + * @property {string} [decisionId] + */ +/** + * @typedef {Object} X402PolicyHook + * @property {(ctx: object, opts: {signal: AbortSignal}) => Promise} evaluate + * @property {(ctx: object, opts: {signal: AbortSignal}) => Promise} [currentVersion] + * @property {number} [timeoutMs] default 5000, never more than half of maxTimeoutSeconds + * @property {boolean} [requireExpiry] an ALLOW without expiresAt is unsignable + * @property {(record: object) => void} [onDecision] observer; cannot change the outcome + * @property {() => number} [now] injectable clock (epoch ms), for tests + */ + +/** Outcomes that mean no signature was released. */ +export const REFUSALS = Object.freeze([ + "SIGNER_ERROR", "DENY", "WAIT", "TIMEOUT", "ENGINE_ERROR", "EXPIRED", "UNBOUND", "MALFORMED", + "CONTEXT_MISMATCH", "STALE", "VERSION_UNAVAILABLE", "SIGNER_CHANGED", "CLOCK_INVALID", +]); + +export class X402PolicyError extends Error { + constructor(outcome, message, extra = {}) { + super(`x402 policy ${outcome}: ${message}`); + this.name = "X402PolicyError"; + this.outcome = outcome; + this.decision = extra.decision; + this.contextHash = extra.contextHash; + } +} + +const sha256hex = (s) => sha256(stringToBytes(s)).slice(2); +const nonempty = (v) => typeof v === "string" && v.trim().length > 0; + +/** Validates a policy hook when it is configured, so bad config fails before any payment. */ +export function assertValidPolicyHook(policy) { + if (!policy || typeof policy !== "object" || typeof policy.evaluate !== "function") { + throw new Error("policy: `evaluate` must be a function."); + } + if (policy.currentVersion !== undefined && typeof policy.currentVersion !== "function") { + throw new Error("policy: `currentVersion`, when set, must be a function."); + } + if (policy.timeoutMs !== undefined && (!Number.isSafeInteger(policy.timeoutMs) || policy.timeoutMs <= 0)) { + throw new Error("policy: `timeoutMs` must be a positive integer (ms)."); + } + if (policy.now !== undefined && typeof policy.now !== "function") { + throw new Error("policy: `now`, when set, must be a function returning epoch milliseconds."); + } +} + +function chainIdOf(network) { + const m = /^eip155:(\d+)$/.exec(String(network)); + if (!m) throw new X402PolicyError("CONTEXT_MISMATCH", `not an EVM network: ${network}`); + return BigInt(m[1]); +} + +function toBigInt(v, field) { + try { + if (typeof v === "bigint") return v; + if (typeof v === "number" && Number.isSafeInteger(v)) return BigInt(v); + if (typeof v === "string" && /^(0x[0-9a-fA-F]+|\d+)$/.test(v)) return BigInt(v); + } catch { /* falls through */ } + throw new X402PolicyError("CONTEXT_MISMATCH", `${field} is not an integer`); +} + +function sameAddress(a, b) { + return isAddress(String(a)) && isAddress(String(b)) && getAddress(a) === getAddress(b); +} + +/** + * Decodes the typed data about to be signed and checks it describes exactly the payment x402 + * selected. This is not policy (that belongs to the engine): it is context integrity, so that + * what the engine evaluates is what gets signed. + */ +export function describeAuthorization(typedData, requirements, signerAddress) { + if (!typedData || typeof typedData !== "object") { + throw new X402PolicyError("CONTEXT_MISMATCH", "no typed data to sign"); + } + const { domain, types, primaryType, message } = typedData; + if (primaryType !== "TransferWithAuthorization") { + throw new X402PolicyError("CONTEXT_MISMATCH", `unsupported primaryType ${String(primaryType)} (only EIP-3009 TransferWithAuthorization is gated)`); + } + if (!types || typeof types !== "object") throw new X402PolicyError("CONTEXT_MISMATCH", "typed data has no types"); + const extraTypes = Object.keys(types).filter((k) => k !== "EIP712Domain" && k !== "TransferWithAuthorization"); + if (extraTypes.length) throw new X402PolicyError("CONTEXT_MISMATCH", `unexpected extra types: ${extraTypes.join(", ")}`); + const fields = types.TransferWithAuthorization; + const sameFields = Array.isArray(fields) && fields.length === TRANSFER_WITH_AUTHORIZATION.length + && fields.every((f, i) => f && f.name === TRANSFER_WITH_AUTHORIZATION[i].name && f.type === TRANSFER_WITH_AUTHORIZATION[i].type); + if (!sameFields) throw new X402PolicyError("CONTEXT_MISMATCH", "TransferWithAuthorization fields differ from EIP-3009"); + if (!domain || typeof domain !== "object" || !message || typeof message !== "object") { + throw new X402PolicyError("CONTEXT_MISMATCH", "typed data has no domain or message"); + } + + const chainId = chainIdOf(requirements.network); + if (toBigInt(domain.chainId, "domain.chainId") !== chainId) { + throw new X402PolicyError("CONTEXT_MISMATCH", "domain.chainId differs from requirements.network"); + } + if (!sameAddress(domain.verifyingContract, requirements.asset)) { + throw new X402PolicyError("CONTEXT_MISMATCH", "token contract differs from requirements.asset"); + } + const extra = requirements.extra || {}; + if (!nonempty(extra.name) || !nonempty(extra.version)) { + throw new X402PolicyError("CONTEXT_MISMATCH", "requirements.extra has no EIP-712 name/version"); + } + if (domain.name !== extra.name || domain.version !== extra.version) { + throw new X402PolicyError("CONTEXT_MISMATCH", "EIP-712 domain name/version differ from requirements.extra"); + } + if (!sameAddress(message.to, requirements.payTo)) { + throw new X402PolicyError("CONTEXT_MISMATCH", "destination differs from requirements.payTo"); + } + const value = toBigInt(message.value, "value"); + if (value !== toBigInt(requirements.amount, "requirements.amount")) { + throw new X402PolicyError("CONTEXT_MISMATCH", "amount differs from requirements.amount"); + } + if (!sameAddress(message.from, signerAddress)) { + throw new X402PolicyError("CONTEXT_MISMATCH", "from differs from signer address"); + } + if (typeof message.nonce !== "string" || !HEX32.test(message.nonce)) { + throw new X402PolicyError("CONTEXT_MISMATCH", "nonce is not bytes32"); + } + const validAfter = toBigInt(message.validAfter, "validAfter"); + const validBefore = toBigInt(message.validBefore, "validBefore"); + + let payloadHash; + try { + payloadHash = hashTypedData({ domain, types, primaryType, message }).slice(2).toLowerCase(); + } catch (e) { + throw new X402PolicyError("CONTEXT_MISMATCH", `typed data does not hash (${e?.shortMessage ?? e?.message})`); + } + return Object.freeze({ + primaryType, + payloadHash, + chainId: chainId.toString(), + verifyingContract: getAddress(domain.verifyingContract), + domainName: domain.name, + domainVersion: domain.version, + from: getAddress(message.from), + to: getAddress(message.to), + amount: value.toString(), + validAfter: validAfter.toString(), + validBefore: validBefore.toString(), + nonce: message.nonce.toLowerCase(), + }); +} + +/** min(timeoutMs ?? 5000, maxTimeoutSeconds * 1000 / 2): a slow engine must not eat the payment window. */ +export function effectiveTimeoutMs(policy, maxTimeoutSeconds) { + const base = policy.timeoutMs ?? DEFAULT_TIMEOUT_MS; + if (typeof maxTimeoutSeconds === "number" && Number.isFinite(maxTimeoutSeconds) && maxTimeoutSeconds > 0) { + return Math.max(1, Math.min(base, Math.floor((maxTimeoutSeconds * 1000) / 2))); + } + return base; +} + +/** sha256 of {v, url, method, payloadHash}: the value an ALLOW must echo back. */ +export function computeContextHash(url, method, payloadHash) { + return sha256hex(JSON.stringify({ v: 1, url, method, payloadHash })); +} + +/** + * Wraps an EVM signer ({ address, signTypedData }) so it only signs with a current ALLOW bound + * to this exact authorization. Anything else ends without a signature. + * + * `getCall` supplies the per-call context (URL, method, requirements): create one gated signer + * per payment so two concurrent payments never share state. `onRefused` receives the error + * before it is thrown, because @x402/fetch re-wraps errors and loses their class. + */ +export function createPolicyGatedSigner(base, policy, getCall, onRefused) { + assertValidPolicyHook(policy); + if (!base || typeof base.signTypedData !== "function" || !isAddress(String(base.address))) { + throw new Error("createPolicyGatedSigner: base signer needs an address and signTypedData()."); + } + // Identity is fixed here. If the base signer changes address mid-payment, nothing is signed. + const account = getAddress(base.address); + const now = policy.now ?? Date.now; + + const report = (r) => { + try { + const out = policy.onDecision?.(r); + if (out !== null && (typeof out === "object" || typeof out === "function")) { + Promise.resolve(out).catch(() => { /* an observer decides nothing */ }); + } + } catch { /* an observer decides nothing */ } + }; + const refuse = (outcome, msg, context, decision) => { + report({ outcome, context, decision, error: msg }); + const err = new X402PolicyError(outcome, msg, { decision, contextHash: context?.contextHash }); + try { onRefused?.(err); } catch { /* idem */ } + throw err; + }; + // A clock that does not return a finite number closes: NaN makes every comparison false. + const readClock = (context, decision) => { + let t; + try { t = now(); } catch (e) { + return refuse("CLOCK_INVALID", `clock threw (${e?.message ?? String(e)})`, context, decision); + } + if (typeof t !== "number" || !Number.isFinite(t)) { + return refuse("CLOCK_INVALID", `clock returned ${String(t)}, not epoch milliseconds`, context, decision); + } + return t; + }; + + const signTypedData = async (typedData) => { + const call = getCall(); + if (!call || !call.requirements) refuse("CONTEXT_MISMATCH", "no payment requirements bound to this signing call"); + if (!sameAddress(base.address, account)) refuse("SIGNER_CHANGED", "base signer address changed after the gate was created"); + + let authorization; + try { + authorization = describeAuthorization(typedData, call.requirements, account); + } catch (e) { + return refuse(e instanceof X402PolicyError ? e.outcome : "CONTEXT_MISMATCH", e?.message ?? String(e)); + } + const contextHash = computeContextHash(call.url, call.method, authorization.payloadHash); + // Frozen: the engine reads, it does not rewrite what gets signed. + const context = Object.freeze({ + contextVersion: 1, + url: call.url, + method: call.method, + requirements: Object.freeze({ ...call.requirements, extra: Object.freeze({ ...(call.requirements.extra || {}) }) }), + authorization, + signer: account, + contextHash, + }); + + const timeoutMs = effectiveTimeoutMs(policy, call.requirements.maxTimeoutSeconds); + const controller = new AbortController(); + // One deadline for the whole pre-sign phase (evaluate + currentVersion). + const deadline = readClock(context) + timeoutMs; + let timer; + const TIMED_OUT = Symbol("timeout"); + const timeout = new Promise((_, reject) => { + timer = setTimeout(() => { controller.abort(); reject(TIMED_OUT); }, timeoutMs); + }); + timeout.catch(() => { /* observed by each race */ }); + + try { + let decision; + try { + decision = await Promise.race([ + Promise.resolve().then(() => policy.evaluate(context, { signal: controller.signal })), + timeout, + ]); + } catch (e) { + if (e === TIMED_OUT) return refuse("TIMEOUT", `no decision within ${timeoutMs} ms`, context); + return refuse("ENGINE_ERROR", e?.message ?? String(e), context); + } + + // Anything that is not a well-formed ALLOW closes. + if (!decision || typeof decision !== "object") return refuse("MALFORMED", "engine returned no decision object", context); + if (decision.decision === "DENY") return refuse("DENY", decision.reason ?? "denied", context, decision); + if (decision.decision === "WAIT") return refuse("WAIT", decision.reason ?? "wait", context, decision); + if (decision.decision !== "ALLOW") return refuse("MALFORMED", `unknown verdict ${String(decision.decision)}`, context, decision); + // Copied before any await: mutating the engine's object later changes nothing. + const allow = Object.freeze({ ...decision }); + if (allow.contextHash !== contextHash) return refuse("UNBOUND", "ALLOW is not bound to this authorization", context, allow); + if (allow.expiresAt !== undefined && (typeof allow.expiresAt !== "number" || !Number.isFinite(allow.expiresAt))) { + return refuse("MALFORMED", "expiresAt must be epoch milliseconds", context, allow); + } + if (allow.expiresAt === undefined && policy.requireExpiry) { + return refuse("EXPIRED", "ALLOW without expiresAt while requireExpiry is set", context, allow); + } + const checkClock = () => { + const t = readClock(context, allow); + if (t >= deadline) refuse("TIMEOUT", "decision arrived after the deadline", context, allow); + if (allow.expiresAt !== undefined && t >= allow.expiresAt) refuse("EXPIRED", "ALLOW expired before signing", context, allow); + }; + if (policy.currentVersion && !nonempty(allow.policyVersion)) { + return refuse("MALFORMED", "ALLOW has no policyVersion to check against currentVersion", context, allow); + } + checkClock(); + + // The observer runs HERE, not next to the signer: whatever it changes (the clock, the + // policy version, the signer's address) is seen by the checks that follow. + report({ outcome: "ALLOWED", context, decision: allow }); + + if (policy.currentVersion) { + let current; + try { + current = await Promise.race([ + Promise.resolve().then(() => policy.currentVersion(context, { signal: controller.signal })), + timeout, + ]); + } catch (e) { + if (e === TIMED_OUT) return refuse("TIMEOUT", `no current policy version within ${timeoutMs} ms`, context, allow); + return refuse("VERSION_UNAVAILABLE", `currentVersion failed (${e?.message ?? String(e)})`, context, allow); + } + if (!nonempty(current)) return refuse("VERSION_UNAVAILABLE", "currentVersion returned no version", context, allow); + if (current !== allow.policyVersion) { + return refuse("STALE", `ALLOW was issued under policy ${allow.policyVersion}, current is ${current}`, context, allow); + } + } + + // Final checks, always, with no await before the signer. + checkClock(); + if (!sameAddress(base.address, account)) return refuse("SIGNER_CHANGED", "base signer address changed while the policy was evaluated", context, allow); + if (timer) clearTimeout(timer); + let signature; + try { + // The original object, not a copy someone could have touched. + signature = await base.signTypedData(typedData); + } catch (e) { + report({ outcome: "SIGNER_ERROR", context, decision: allow, error: e?.message ?? String(e) }); + throw e; + } + if (typeof signature !== "string" || !SIG65.test(signature)) { + return refuse("SIGNER_ERROR", "signer returned no 65-byte signature", context, allow); + } + report({ outcome: "SIGNED", context, decision: allow }); + return signature; + } finally { + if (timer) clearTimeout(timer); + } + }; + + // Read-only chain access may be forwarded; no other signing method is exposed. + const gated = { address: account, signTypedData }; + if (typeof base.readContract === "function") gated.readContract = (args) => base.readContract(args); + return Object.freeze(gated); +} diff --git a/base/policy/rules-policy.mjs b/base/policy/rules-policy.mjs new file mode 100644 index 0000000..2bebc5f --- /dev/null +++ b/base/policy/rules-policy.mjs @@ -0,0 +1,35 @@ +// A small reference policy engine, for demos and tests. Real deployments plug in their own. +// +// Rules, checked against what is actually about to be signed (context.authorization): +// - the token must be in `allowAssets` (if given), +// - the destination must be in `allowPayTo` (if given), +// - amount > `maxAmount` gives DENY, +// - amount > `approvalAbove` (and <= maxAmount) gives WAIT: a person has to approve it, +// - anything else gives ALLOW, bound to this authorization, valid for `ttlMs`. + +import { getAddress } from "viem"; + +export function createRulesPolicy({ + maxAmount, approvalAbove, allowPayTo, allowAssets, ttlMs = 30_000, policyVersion = "rules-v1", + now = Date.now, onDecision, +} = {}) { + if (maxAmount === undefined) throw new Error("createRulesPolicy: maxAmount (atomic units) is required"); + const max = BigInt(maxAmount); + const approval = approvalAbove === undefined ? undefined : BigInt(approvalAbove); + const payTo = allowPayTo ? new Set(allowPayTo.map((a) => getAddress(a))) : undefined; + const assets = allowAssets ? new Set(allowAssets.map((a) => getAddress(a))) : undefined; + + return { + now, + onDecision, + async evaluate(ctx) { + const a = ctx.authorization; + const amount = BigInt(a.amount); + if (assets && !assets.has(getAddress(a.verifyingContract))) return { decision: "DENY", reason: "token not allowed", policyVersion }; + if (payTo && !payTo.has(getAddress(a.to))) return { decision: "DENY", reason: "destination not allowed", policyVersion }; + if (amount > max) return { decision: "DENY", reason: `amount ${amount} above limit ${max}`, policyVersion }; + if (approval !== undefined && amount > approval) return { decision: "WAIT", reason: `amount ${amount} needs approval (above ${approval})`, policyVersion }; + return { decision: "ALLOW", contextHash: ctx.contextHash, expiresAt: now() + ttlMs, policyVersion }; + }, + }; +} diff --git a/base/policy/test/evm-policy.test.mjs b/base/policy/test/evm-policy.test.mjs new file mode 100644 index 0000000..fa9426c --- /dev/null +++ b/base/policy/test/evm-policy.test.mjs @@ -0,0 +1,272 @@ +// Tests for the EVM pre-sign gate. No RPC, no network, nothing broadcast. +// Typed data comes from the real @x402/evm 2.32.0 ExactEvmScheme, so the gate is tested +// against exactly what the package asks a signer to sign. + +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { createServer } from "node:http"; +import { generatePrivateKey, privateKeyToAccount } from "viem/accounts"; +import { verifyTypedData } from "viem"; +import { ExactEvmScheme } from "@x402/evm/exact/client"; +import { + encodePaymentRequiredHeader, decodePaymentSignatureHeader, encodePaymentResponseHeader, +} from "@x402/core/http"; +import { + createPolicyGatedSigner, describeAuthorization, computeContextHash, effectiveTimeoutMs, + X402PolicyError, +} from "../evm-policy.mjs"; +import { createPolicyX402Fetch } from "../x402-fetch.mjs"; +import { createRulesPolicy } from "../rules-policy.mjs"; + +const SEPOLIA = "eip155:84532"; +const SEPOLIA_USDC = "0x036CbD53842c5426634e7929541eC2318f3dCF7e"; +const PAY_TO = privateKeyToAccount(generatePrivateKey()).address; +const URL_ = "https://policy.test/paid"; + +const requirements = (over = {}) => ({ + scheme: "exact", network: SEPOLIA, asset: SEPOLIA_USDC, payTo: PAY_TO, amount: "10000", + maxTimeoutSeconds: 120, extra: { name: "USDC", version: "2" }, ...over, +}); + +/** A base signer that records whether it was ever asked to sign. */ +function spySigner() { + const account = privateKeyToAccount(generatePrivateKey()); + const spy = { calls: 0, address: account.address }; + spy.signTypedData = async (td) => { spy.calls++; return account.signTypedData(td); }; + return spy; +} + +/** Runs the real ExactEvmScheme through a gate; resolves to { error, records, base }. */ +async function pay(policy, { req = requirements(), base = spySigner(), method = "GET" } = {}) { + const records = []; + // Returns the observer's own result, so the gate sees (and swallows) an async rejection. + const p = { ...policy, onDecision: (r) => { records.push(r.outcome); return policy.onDecision?.(r); } }; + let refused; + const gated = createPolicyGatedSigner(base, p, () => ({ url: URL_, method, requirements: req }), (e) => { refused = e; }); + try { + const result = await new ExactEvmScheme(gated).createPaymentPayload(2, { ...req }); + return { result, records, base }; + } catch (e) { + return { error: refused ?? e, records, base }; + } +} + +const allowBound = (over = {}) => ({ async evaluate(ctx) { return { decision: "ALLOW", contextHash: ctx.contextHash, ...over }; } }); + +test("ALLOW bound to the context signs exactly once, and the signature is the payer's", async () => { + const { result, records, base, error } = await pay(allowBound()); + assert.equal(error, undefined); + assert.equal(base.calls, 1); + assert.deepEqual(records, ["ALLOWED", "SIGNED"]); + const auth = result.payload.authorization; + assert.equal(auth.to.toLowerCase(), PAY_TO.toLowerCase()); + assert.equal(String(auth.value), "10000"); +}); + +for (const [name, decision, outcome] of [ + ["DENY", { decision: "DENY", reason: "no" }, "DENY"], + ["WAIT", { decision: "WAIT", reason: "needs a person" }, "WAIT"], + ["unknown verdict", { decision: "MAYBE" }, "MALFORMED"], + ["ALLOW with a wrong contextHash", { decision: "ALLOW", contextHash: "00".repeat(32) }, "UNBOUND"], + ["ALLOW without contextHash", { decision: "ALLOW" }, "UNBOUND"], +]) { + test(`${name} signs nothing (${outcome})`, async () => { + const { error, base } = await pay({ async evaluate() { return decision; } }); + assert.ok(error instanceof X402PolicyError, String(error)); + assert.equal(error.outcome, outcome); + assert.equal(base.calls, 0); + }); +} + +test("no decision object, engine throw and timeout sign nothing", async () => { + for (const [policy, outcome] of [ + [{ async evaluate() { return null; } }, "MALFORMED"], + [{ async evaluate() { throw new Error("engine down"); } }, "ENGINE_ERROR"], + [{ timeoutMs: 20, evaluate: () => new Promise(() => {}) }, "TIMEOUT"], + ]) { + const { error, base } = await pay(policy); + assert.equal(error.outcome, outcome); + assert.equal(base.calls, 0); + } +}); + +test("expiry: expired ALLOW, malformed expiresAt and requireExpiry sign nothing", async () => { + const fixed = 1_000_000; + for (const [policy, outcome] of [ + [{ now: () => fixed, async evaluate(c) { return { decision: "ALLOW", contextHash: c.contextHash, expiresAt: fixed }; } }, "EXPIRED"], + [{ async evaluate(c) { return { decision: "ALLOW", contextHash: c.contextHash, expiresAt: "soon" }; } }, "MALFORMED"], + [{ requireExpiry: true, async evaluate(c) { return { decision: "ALLOW", contextHash: c.contextHash }; } }, "EXPIRED"], + ]) { + const { error, base } = await pay(policy); + assert.equal(error.outcome, outcome); + assert.equal(base.calls, 0); + } +}); + +test("policy version: stale, unavailable and missing sign nothing; current signs", async () => { + const allowV = (v) => async (c) => ({ decision: "ALLOW", contextHash: c.contextHash, policyVersion: v }); + for (const [policy, outcome] of [ + [{ evaluate: allowV("v1"), currentVersion: async () => "v2" }, "STALE"], + [{ evaluate: allowV("v1"), currentVersion: async () => { throw new Error("db down"); } }, "VERSION_UNAVAILABLE"], + [{ evaluate: allowV("v1"), currentVersion: async () => "" }, "VERSION_UNAVAILABLE"], + [{ evaluate: allowV(undefined), currentVersion: async () => "v1" }, "MALFORMED"], + ]) { + const { error, base } = await pay(policy); + assert.equal(error.outcome, outcome); + assert.equal(base.calls, 0); + } + const ok = await pay({ evaluate: allowV("v1"), currentVersion: async () => "v1" }); + assert.equal(ok.error, undefined); + assert.equal(ok.base.calls, 1); +}); + +test("a clock that is not a finite number signs nothing", async () => { + for (const now of [() => NaN, () => "now", () => { throw new Error("no clock"); }]) { + const { error, base } = await pay({ now, async evaluate(c) { return { decision: "ALLOW", contextHash: c.contextHash }; } }); + assert.equal(error.outcome, "CLOCK_INVALID"); + assert.equal(base.calls, 0); + } +}); + +test("a signer that changes address during evaluation signs nothing", async () => { + const base = spySigner(); + const other = privateKeyToAccount(generatePrivateKey()).address; + const { error } = await pay({ async evaluate(c) { base.address = other; return { decision: "ALLOW", contextHash: c.contextHash }; } }, { base }); + assert.equal(error.outcome, "SIGNER_CHANGED"); + assert.equal(base.calls, 0); +}); + +test("an observer that throws or rejects cannot block or change the payment", async () => { + const policy = { ...allowBound(), onDecision() { throw new Error("observer bug"); } }; + const a = await pay(policy); + assert.equal(a.error, undefined); + const b = await pay({ ...allowBound(), onDecision: async () => { throw new Error("async observer bug"); } }); + assert.equal(b.error, undefined); +}); + +test("mutating the engine's ALLOW after returning it changes nothing", async () => { + let ref; + const { error, base } = await pay({ async evaluate(c) { ref = { decision: "ALLOW", contextHash: c.contextHash }; setTimeout(() => { ref.decision = "DENY"; }, 0); return ref; } }); + assert.equal(error, undefined); + assert.equal(base.calls, 1); +}); + +test("context integrity: the engine is never asked about a payment that differs from the requirements", async () => { + let asked = 0; + const policy = { async evaluate(c) { asked++; return { decision: "ALLOW", contextHash: c.contextHash }; } }; + const cases = [ + ["wrong chain", { network: "eip155:8453" }], + ["wrong token", { asset: "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913" }], + ["wrong domain name", { extra: { name: "Fake Coin", version: "2" } }], + ["no domain in extra", { extra: {} }], + ]; + for (const [name, over] of cases) { + // The scheme signs what `req` says; the gate is told the requirements differ. + const base = spySigner(); + const told = requirements(over); + let refused; + const gated = createPolicyGatedSigner(base, policy, () => ({ url: URL_, method: "GET", requirements: told }), (e) => { refused = e; }); + await assert.rejects(new ExactEvmScheme(gated).createPaymentPayload(2, requirements()), name); + assert.equal(refused?.outcome, "CONTEXT_MISMATCH", name); + assert.equal(base.calls, 0, name); + } + assert.equal(asked, 0); +}); + +test("describeAuthorization rejects other typed data (Permit, extra types, wrong payTo, amount or from)", async () => { + const signer = spySigner(); + let typed; + const capture = { address: signer.address, signTypedData: async (td) => { typed = td; return signer.signTypedData(td); } }; + await new ExactEvmScheme(capture).createPaymentPayload(2, requirements()); + const req = requirements(); + assert.equal(describeAuthorization(typed, req, signer.address).amount, "10000"); + const bad = (f) => { const t = structuredClone({ ...typed, message: { ...typed.message } }); f(t); return t; }; + for (const [name, td] of [ + ["Permit primaryType", bad((t) => { t.primaryType = "Permit"; })], + ["extra type", bad((t) => { t.types = { ...t.types, Extra: [{ name: "x", type: "uint256" }] }; })], + ["reordered fields", bad((t) => { t.types = { ...t.types, TransferWithAuthorization: [...t.types.TransferWithAuthorization].reverse() }; })], + ["other payTo", bad((t) => { t.message.to = privateKeyToAccount(generatePrivateKey()).address; })], + ["other amount", bad((t) => { t.message.value = 10001n; })], + ["other from", bad((t) => { t.message.from = privateKeyToAccount(generatePrivateKey()).address; })], + ["bad nonce", bad((t) => { t.message.nonce = "0x1234"; })], + ]) { + assert.throws(() => describeAuthorization(td, req, signer.address), (e) => e instanceof X402PolicyError && e.outcome === "CONTEXT_MISMATCH", name); + } +}); + +test("contextHash binds url, method and the EIP-712 digest", () => { + const h = computeContextHash(URL_, "GET", "ab".repeat(32)); + assert.notEqual(h, computeContextHash(URL_, "POST", "ab".repeat(32))); + assert.notEqual(h, computeContextHash(URL_ + "?x=1", "GET", "ab".repeat(32))); + assert.notEqual(h, computeContextHash(URL_, "GET", "cd".repeat(32))); +}); + +test("timeout never exceeds half of the payment window", () => { + assert.equal(effectiveTimeoutMs({}, 120), 5000); + assert.equal(effectiveTimeoutMs({}, 4), 2000); + assert.equal(effectiveTimeoutMs({ timeoutMs: 100 }, 120), 100); +}); + +test("rules policy: ALLOW under the limit, WAIT above the approval line, DENY above the max or to a stranger", async () => { + const allow = await pay(createRulesPolicy({ maxAmount: "20000", allowPayTo: [PAY_TO], allowAssets: [SEPOLIA_USDC] })); + assert.equal(allow.error, undefined); + for (const [policy, outcome] of [ + [createRulesPolicy({ maxAmount: "5000" }), "DENY"], + [createRulesPolicy({ maxAmount: "20000", approvalAbove: "5000" }), "WAIT"], + [createRulesPolicy({ maxAmount: "20000", allowPayTo: [privateKeyToAccount(generatePrivateKey()).address] }), "DENY"], + [createRulesPolicy({ maxAmount: "20000", allowAssets: ["0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913"] }), "DENY"], + ]) { + const { error, base } = await pay(policy); + assert.equal(error.outcome, outcome); + assert.equal(base.calls, 0); + } +}); + +// End to end through @x402/fetch against a local server that answers like an x402 seller. +// The server never forwards anything to a facilitator: it only checks what it receives. +async function withSeller(fn) { + const seen = { paid: 0, payloads: [] }; + const server = createServer((req, res) => { + const sig = req.headers["payment-signature"]; + if (!sig) { + const pr = { x402Version: 2, resource: { url: `http://localhost:${server.address().port}/paid` }, accepts: [requirements()] }; + res.writeHead(402, { "PAYMENT-REQUIRED": encodePaymentRequiredHeader(pr), "content-type": "application/json" }); + return res.end("{}"); + } + seen.paid++; + seen.payloads.push(decodePaymentSignatureHeader(sig)); + res.writeHead(200, { "PAYMENT-RESPONSE": encodePaymentResponseHeader({ success: true, transaction: "0x" + "11".repeat(32), network: SEPOLIA }), "content-type": "application/json" }); + res.end('{"ok":true}'); + }); + await new Promise((r) => server.listen(0, "127.0.0.1", r)); + try { return await fn(`http://127.0.0.1:${server.address().port}/paid`, seen); } finally { server.close(); } +} + +test("e2e: DENY never sends a payment to the seller; ALLOW sends one the payer really signed", async () => { + await withSeller(async (url, seen) => { + const base = spySigner(); + const deny = createPolicyX402Fetch({ signer: base, policy: createRulesPolicy({ maxAmount: "1" }), network: SEPOLIA, asset: SEPOLIA_USDC, maxAmountPerPayment: "10000" }); + await assert.rejects(deny(url), (e) => e instanceof X402PolicyError && e.outcome === "DENY"); + assert.equal(seen.paid, 0); + assert.equal(base.calls, 0); + + const allow = createPolicyX402Fetch({ signer: base, policy: createRulesPolicy({ maxAmount: "10000", allowPayTo: [PAY_TO] }), network: SEPOLIA, asset: SEPOLIA_USDC, maxAmountPerPayment: "10000" }); + const res = await allow(url); + assert.equal(res.status, 200); + assert.equal(seen.paid, 1); + assert.equal(base.calls, 1); + const { authorization, signature } = seen.payloads[0].payload; + const ok = await verifyTypedData({ + address: base.address, + domain: { name: "USDC", version: "2", chainId: 84532, verifyingContract: SEPOLIA_USDC }, + types: { TransferWithAuthorization: [ + { name: "from", type: "address" }, { name: "to", type: "address" }, { name: "value", type: "uint256" }, + { name: "validAfter", type: "uint256" }, { name: "validBefore", type: "uint256" }, { name: "nonce", type: "bytes32" }, + ] }, + primaryType: "TransferWithAuthorization", + message: { ...authorization, value: BigInt(authorization.value), validAfter: BigInt(authorization.validAfter), validBefore: BigInt(authorization.validBefore) }, + signature, + }); + assert.equal(ok, true); + }); +}); diff --git a/base/policy/x402-fetch.mjs b/base/policy/x402-fetch.mjs new file mode 100644 index 0000000..7796d9b --- /dev/null +++ b/base/policy/x402-fetch.mjs @@ -0,0 +1,56 @@ +// fetch() that pays x402 `exact` on an EVM chain only when the policy says ALLOW. +// +// One gated signer and one x402 client per call, so two concurrent payments never share +// state. The selected requirements are captured in onBeforePaymentCreation (that hook runs +// before the authorization exists) and handed to the gate, which checks them against the +// typed data it is asked to sign. +// +// NEVER register onPaymentCreationFailure here: it can return a payload that did not go +// through the signer, which would bypass the gate. + +import { wrapFetchWithPayment, x402Client } from "@x402/fetch"; +import { ExactEvmScheme } from "@x402/evm/exact/client"; +import { createPolicyGatedSigner, X402PolicyError } from "./evm-policy.mjs"; + +/** + * @param {object} cfg + * @param {{address: string, signTypedData: Function, readContract?: Function}} cfg.signer e.g. a viem account + * @param {object} cfg.policy X402PolicyHook (see evm-policy.mjs) + * @param {string} cfg.network "eip155:84532" or "eip155:8453" + * @param {string} cfg.asset USDC contract on that network + * @param {string} cfg.maxAmountPerPayment atomic units cap; also allows a non-default asset in @x402/core + * @param {typeof fetch} [cfg.fetch] + */ +export function createPolicyX402Fetch(cfg) { + const { signer, policy, network, asset, maxAmountPerPayment } = cfg; + const baseFetch = cfg.fetch ?? globalThis.fetch; + if (!/^eip155:\d+$/.test(String(network))) throw new Error("createPolicyX402Fetch: network must be eip155:"); + if (!asset || !maxAmountPerPayment) throw new Error("createPolicyX402Fetch: asset and maxAmountPerPayment are required"); + + return async function policyFetch(url, init) { + const slot = { requirements: undefined, error: undefined }; + const method = String(init?.method ?? "GET").toUpperCase(); + const gated = createPolicyGatedSigner( + signer, policy, + () => ({ url: String(url), method, requirements: slot.requirements }), + (err) => { slot.error = err; }, + ); + const client = new x402Client() + .register(network, new ExactEvmScheme(gated)) + .onBeforePaymentCreation(async ({ selectedRequirements: r }) => { + slot.requirements = { + scheme: r.scheme, network: r.network, asset: r.asset, payTo: r.payTo, + amount: r.amount, maxTimeoutSeconds: r.maxTimeoutSeconds, + extra: { name: r.extra?.name, version: r.extra?.version }, + }; + }); + client.setSpendControls({ allowedAssets: [{ network, asset, maxAmountPerPayment }] }); + try { + return await wrapFetchWithPayment(baseFetch, client)(url, init); + } catch (e) { + // @x402/fetch re-wraps errors and loses the class: hand back the gate's own error. + if (slot.error instanceof X402PolicyError) throw slot.error; + throw e; + } + }; +} diff --git a/base/run-tests.sh b/base/run-tests.sh new file mode 100644 index 0000000..21e37bd --- /dev/null +++ b/base/run-tests.sh @@ -0,0 +1,17 @@ +#!/usr/bin/env bash +# Runs every fixture against a real third-party PayAI settlement on Base mainnet, prints each check, +# and compares each exit code with the expected one. Exits 1 if any case is unexpected. +cd "$(dirname "$0")" +total=0; ok=0 +run() { # fixture, label, expected exit, extra flag + total=$((total + 1)) + echo; echo "### $1 ($2), expect exit $3" + node verify-evm-receipt.mjs "fixtures/$1.json" $4 + local code=$? + if [ "$code" = "$3" ]; then ok=$((ok + 1)); echo "OK exit=$code"; else echo "UNEXPECTED exit=$code"; fi +} +run payai-ok "--no-sig" 0 --no-sig +for f in payai-bad-index payai-bad-amount payai-bad-to payai-bad-nonce payai-bad-content-sha256; do run $f "--no-sig" 1 --no-sig; done +for f in payai-ok payai-sig-ephemeral payai-sig-tampered payai-sig-forged-payer; do run $f "signature required" 1; done +echo; echo "$ok/$total as expected" +[ "$ok" = "$total" ] diff --git a/base/sdk/README.md b/base/sdk/README.md new file mode 100644 index 0000000..eae061d --- /dev/null +++ b/base/sdk/README.md @@ -0,0 +1,49 @@ +# nirium-base + +Nirium on Base and Base Sepolia: pay and charge with x402, refuse payments before they are +signed, and prove what a payment was for. + +```js +import { x402Serve, createX402Fetch, settlementOf, bindReceipt, verifyReceipt, createRulesPolicy } from "nirium-base"; + +// Charge for your own API (runs on your server; Nirium runs nothing and receives nothing) +app.use(x402Serve({ payTo: "0x...", network: "eip155:84532", routes: { "GET /data": "$0.01" } })); + +// Pay, with a policy: a payment it refuses is never signed +const pay = createX402Fetch({ + signer: account, network: "eip155:84532", maxAmountPerPayment: "10000", + policy: createRulesPolicy({ maxAmount: "10000", allowPayTo: ["0x..."] }), +}); +const res = await pay("https://seller.example/data"); + +// Prove what it was for: a payer-signed receipt bound to the exact USDC transfer +const receipt = await bindReceipt({ tx: settlementOf(res).transaction, network: "eip155:84532", ref: "order-42", signer: account }); +const { ok } = await verifyReceipt(receipt); +``` + +| Function | What it does | +|---|---| +| `x402Serve(config)` | Express middleware. Prices in dollars (`"$0.01"`) or atomic units (`{ amount }`), converted to an explicit USDC amount with its EIP-712 domain. PayAI by default (an independent facilitator). Built on the first paid request after a `/supported` preflight: a facilitator that is down answers 503 with a hint on paid routes only; the rest of the app keeps serving. No telemetry. | +| `createX402Fetch(cfg)` | `fetch` that pays x402 `exact` with a per-payment cap. With `policy`, nothing is signed without the policy's ALLOW (see `../policy/`). Mainnet needs `allowMainnet: true`. | +| `settlementOf(res)` | The settlement from the `PAYMENT-RESPONSE` header, or `undefined`. | +| `bindReceipt(o)` | Reads the settled tx (waits for the RPC to have it), finds the USDC `Transfer` from the payer and its EIP-3009 nonce, builds the receipt in canonical order and signs it as the payer. Refuses a signer that is not the payer. | +| `bindDecision(policyRecord, o)` | A payer-signed receipt of one policy decision (`nirium-decision-v1`, see `../../docs/decision-receipt-v1.md`), built from what the policy passes to `onDecision`. A DENY or WAIT signs no payment, so this receipt is the only record of it. `hashOnly: true` keeps the content private. `collectDecisions()` gives an `onDecision` observer that keeps the records to sign after the attempt. | +| `verifyDecision(doc, { record })` | Format, hash and payer signature of a decision receipt. Nothing on-chain to check: a refusal leaves nothing there. | +| `verifyReceipt(doc)` | The chain verifier (`../verify-evm-core.mjs`), the same code the CLI and the browser run. | + +The receipt adds what the chain does not keep: who declared the payment and what it was for. It +does not prove delivery. Format: `../../docs/payment-binding-v1.md`. + +## Tests + +```bash +cd .. && npm ci && npm run test:sdk # 14 tests +``` + +The pay/charge loop runs offline against a local fake facilitator that checks the payer's +EIP-3009 signature before "settling": paid end to end, the per-payment cap, a policy DENY that +sends nothing to the seller or the facilitator, and a facilitator outage. The receipt test +rebuilds one of the team's real Base Sepolia receipts from the chain over the public RPC. + +`examples/selftest.mjs` runs the whole thing live on Base Sepolia through PayAI (team self-test, test +tokens). See `../../evidence/README.md`. diff --git a/base/sdk/decision.mjs b/base/sdk/decision.mjs new file mode 100755 index 0000000..a3e66e0 --- /dev/null +++ b/base/sdk/decision.mjs @@ -0,0 +1,108 @@ +// Decision receipts ("nirium-decision-v1") on Base: a payer-signed record of what the pre-sign +// policy decided about an x402 payment, including the ones that were never signed (DENY, WAIT and +// every other refusal), which leave no trace on the chain. Format: docs/decision-receipt-v1.md. +// +// No Node-only APIs: runs in Node and in the browser, like the receipt verifier. + +import { getAddress, isAddressEqual, verifyMessage } from "viem"; +import { canonicalize, contentSha256, STATEMENT_PREFIX } from "../verify-evm-core.mjs"; +import { NETWORKS, USDC_DECIMALS } from "./networks.mjs"; + +export const DECISION_VERSION = "nirium-decision-v1"; +export const DECISION_OUTCOMES = Object.freeze([ + "ALLOWED", "SIGNED", "DENY", "WAIT", "TIMEOUT", "ENGINE_ERROR", "EXPIRED", "UNBOUND", "MALFORMED", + "STALE", "VERSION_UNAVAILABLE", "SIGNER_CHANGED", "CLOCK_INVALID", +]); +const EVM_NETWORK = /^eip155:\d{1,12}$/; +const HEX64 = /^[0-9a-f]{64}$/; +const nonempty = (v) => typeof v === "string" && v.trim().length > 0; +const sameAddr = (a, b) => { try { return isAddressEqual(a, b); } catch { return false; } }; + +/** + * The record for one policy decision, in canonical key order, or null when the policy refused + * before it had decoded a payment (CONTEXT_MISMATCH): there is nothing to describe then. + * @param {object} policyRecord what the policy passed to onDecision: { outcome, context, decision, error } + * @param {object} [o] { ref, note, labels } + */ +export function decisionRecord(policyRecord, { ref, note, labels = [] } = {}) { + const c = policyRecord?.context; + const a = c?.authorization; + const network = c?.requirements?.network; + if (!a || !network) return null; + const outcome = policyRecord.outcome; + if (!DECISION_OUTCOMES.includes(outcome)) throw new Error(`decisionRecord: unknown outcome ${outcome}`); + const usdc = NETWORKS[network]?.usdc; + if (!usdc || !sameAddr(a.verifyingContract, usdc)) throw new Error(`decisionRecord: ${a.verifyingContract} is not USDC on ${network}`); + const d = policyRecord.decision ?? {}; + const decision = { outcome }; + if (nonempty(d.policyVersion)) decision.policyVersion = String(d.policyVersion); + const reason = nonempty(d.reason) ? d.reason : (nonempty(policyRecord.error) ? policyRecord.error : undefined); + if (reason) decision.reason = String(reason).slice(0, 280); + const intent = { + amount: String(a.amount), asset: getAddress(a.verifyingContract), contextHash: String(c.contextHash), + decimals: USDC_DECIMALS, from: getAddress(a.from), method: String(c.method), network: String(network), + nonce: String(a.nonce), payloadHash: String(a.payloadHash), resource: String(c.url), to: getAddress(a.to), + }; + const record = { decision, intent, labels: [...labels].map(String) }; + if (nonempty(ref)) record.purpose = note ? { note: String(note), ref } : { ref }; + return JSON.parse(canonicalize(record)); +} + +/** + * Builds and signs a decision receipt with the payer's viem account (EIP-191 over the statement). + * Returns { doc, record } (null when there is no decoded payment). With hashOnly, `doc` has no + * record: keep `record` yourself to show it later. + */ +export async function bindDecision(policyRecord, { signer, ref, note, labels, hashOnly = false } = {}) { + const record = decisionRecord(policyRecord, { ref, note, labels }); + if (!record) return null; + if (!signer || typeof signer.signMessage !== "function") throw new Error("bindDecision: signer must be the payer's viem account (signMessage)"); + if (!sameAddr(signer.address, record.intent.from)) throw new Error(`bindDecision: signer ${signer.address} is not the payer ${record.intent.from}`); + const content_sha256 = contentSha256(record); + const statement = STATEMENT_PREFIX + content_sha256; + const agent = { alg: "eip191-secp256k1", key: getAddress(signer.address), signature: await signer.signMessage({ message: statement }), statement }; + const network = record.intent.network; + const doc = hashOnly + ? { version: DECISION_VERSION, content_sha256, agent, network } + : { version: DECISION_VERSION, content_sha256, record, agent, network }; + return { doc, record }; +} + +/** + * Checks a decision receipt: format, hash (with a record), payer signature. Nothing on-chain: a + * refusal leaves nothing there. For a hash-only document, pass { record } to check that it is the + * record behind content_sha256. Returns { ok, checks: [{ name, ok, detail }] }. + */ +export async function verifyDecision(doc, { record: heldRecord } = {}) { + const checks = []; + const check = (name, ok, detail) => { checks.push({ name, ok: Boolean(ok), ...(detail ? { detail } : {}) }); return Boolean(ok); }; + const d = doc ?? {}; + check("version == nirium-decision-v1", d.version === DECISION_VERSION, String(d.version)); + check("network is an EVM CAIP-2 id", EVM_NETWORK.test(String(d.network)), String(d.network)); + check("content_sha256 is 64 hex", HEX64.test(String(d.content_sha256))); + const record = d.record ?? heldRecord; + if (record) { + let canon; + try { canon = canonicalize(record); } catch { canon = null; } + check("content_sha256 == sha256(canonical(record))", canon !== null && contentSha256(record) === d.content_sha256, + d.record ? undefined : "record held by the verifier (hash-only document)"); + check("decision.outcome is a known outcome", DECISION_OUTCOMES.includes(record?.decision?.outcome), String(record?.decision?.outcome)); + check("record.intent.network == network", record?.intent?.network === d.network); + } + const ag = d.agent ?? {}; + const statementOk = check("agent.statement == nirium-audit-v1:", ag.statement === STATEMENT_PREFIX + d.content_sha256); + check("agent.alg == eip191-secp256k1", ag.alg === "eip191-secp256k1", String(ag.alg)); + if (record) check("agent.key == record.intent.from (the payer signs)", sameAddr(ag.key, record?.intent?.from)); + let sigOk = false; + if (statementOk && typeof ag.key === "string" && typeof ag.signature === "string") { + try { sigOk = await verifyMessage({ address: ag.key, message: ag.statement, signature: ag.signature }); } catch { sigOk = false; } + } + check("EIP-191 signature by agent.key over agent.statement", sigOk); + return { ok: checks.every((c) => c.ok), checks }; +} + +/** An onDecision observer that keeps every policy record, to sign after the payment attempt. */ +export function collectDecisions() { + const records = []; + return { records, onDecision: (r) => { records.push(r); } }; +} diff --git a/base/sdk/examples/decision-selftest.mjs b/base/sdk/examples/decision-selftest.mjs new file mode 100755 index 0000000..f22e237 --- /dev/null +++ b/base/sdk/examples/decision-selftest.mjs @@ -0,0 +1,58 @@ +// decision-selftest.mjs - decision receipts on Base Sepolia: a seller charging $0.01 with +// x402Serve, and a buyer whose pre-sign policy refuses it twice, once as DENY (limit $0.005) and +// once as WAIT (above $0.005 needs a person). Nothing is signed or sent, so nothing reaches the +// chain; the payer signs a decision receipt for each refusal, checked with verifyDecision. Team +// self-test with test tokens; never usage. +// +// set -a; . ~/.nirium-keys/base-sepolia.env; set +a; node examples/decision-selftest.mjs --ref selftest--base-sepolia-decision [--out-dir dir] + +import { writeFileSync } from "node:fs"; +import { createServer } from "node:http"; +import express from "express"; +import { privateKeyToAccount } from "viem/accounts"; +import { x402Serve, createX402Fetch, settlementOf, bindDecision, verifyDecision, collectDecisions, createRulesPolicy } from "../index.mjs"; + +const arg = (k, d) => { const i = process.argv.indexOf(`--${k}`); return i >= 0 ? process.argv[i + 1] : d; }; +const ref = arg("ref"); +const outDir = arg("out-dir"); +const key = process.env.NIRIUM_EVM_PAYER_KEY; +const payTo = process.env.NIRIUM_EVM_PAYTO; +const network = "eip155:84532"; +if (!ref || !key || !payTo) { console.error("need --ref, NIRIUM_EVM_PAYER_KEY and NIRIUM_EVM_PAYTO"); process.exit(2); } + +const app = express(); +app.use(x402Serve({ payTo, network, routes: { "GET /data": { price: "$0.01", description: "Nirium decision selftest resource" } } })); +app.get("/data", (req, res) => res.json({ ok: true })); +const server = createServer(app); +await new Promise((r) => server.listen(0, "127.0.0.1", r)); +const url = `http://127.0.0.1:${server.address().port}/data`; + +const CASES = [ + { outcome: "DENY", rules: { maxAmount: "5000" }, note: "Refused before signing: $0.01 is above the $0.005 limit" }, + { outcome: "WAIT", rules: { maxAmount: "10000", approvalAbove: "5000" }, note: "Held before signing: above $0.005 needs a person's approval" }, +]; + +let failed = 0; +try { + const signer = privateKeyToAccount(key); + for (const c of CASES) { + const seen = collectDecisions(); + const pay = createX402Fetch({ + signer, network, maxAmountPerPayment: "10000", + policy: createRulesPolicy({ ...c.rules, allowPayTo: [payTo], onDecision: seen.onDecision }), + }); + let res = null; + try { res = await pay(url); } catch (e) { console.log(`${c.outcome}: payment refused (${e?.code ?? e?.name ?? "error"})`); } + if (res && settlementOf(res)) { console.error(`${c.outcome}: a payment settled, this must not happen`); failed++; continue; } + const rec = seen.records.find((r) => r.outcome === c.outcome); + if (!rec) { console.error(`${c.outcome}: the policy did not return it (got ${seen.records.map((r) => r.outcome).join(",") || "nothing"})`); failed++; continue; } + const { doc } = await bindDecision(rec, { signer, ref: `${ref}-${c.outcome.toLowerCase()}`, note: c.note, labels: ["selftest"] }); + const v = await verifyDecision(doc); + console.log(`${c.outcome}: receipt ${v.ok ? "VALID" : "INVALID"} (${v.checks.filter((k) => k.ok).length}/${v.checks.length} checks), nothing signed on-chain`); + if (!v.ok) failed++; + if (outDir) { const f = `${outDir}/sepolia-decision-${c.outcome.toLowerCase()}.json`; writeFileSync(f, JSON.stringify(doc, null, 2) + "\n"); console.log(`wrote ${f}`); } + } +} finally { + server.close(); +} +process.exitCode = failed ? 1 : 0; diff --git a/base/sdk/examples/selftest.mjs b/base/sdk/examples/selftest.mjs new file mode 100644 index 0000000..2b840e7 --- /dev/null +++ b/base/sdk/examples/selftest.mjs @@ -0,0 +1,46 @@ +// selftest.mjs - the whole SDK in one run on Base Sepolia: a seller charging with x402Serve, a buyer paying +// with createX402Fetch under a policy, a payer-signed receipt with bindReceipt, checked with +// verifyReceipt. Team self-test with test tokens; never usage. +// +// set -a; . ~/.nirium-keys/base-sepolia.env; set +a # NIRIUM_EVM_PAYER_KEY, NIRIUM_EVM_PAYTO +// node examples/selftest.mjs --ref selftest--base-sepolia-sdk-01 [--out receipt.json] + +import { writeFileSync } from "node:fs"; +import { createServer } from "node:http"; +import express from "express"; +import { privateKeyToAccount } from "viem/accounts"; +import { x402Serve, createX402Fetch, settlementOf, bindReceipt, verifyReceipt, createRulesPolicy } from "../index.mjs"; + +const arg = (k, d) => { const i = process.argv.indexOf(`--${k}`); return i >= 0 ? process.argv[i + 1] : d; }; +const ref = arg("ref"); +const key = process.env.NIRIUM_EVM_PAYER_KEY; +const payTo = process.env.NIRIUM_EVM_PAYTO; +if (!ref || !key || !payTo) { console.error("need --ref, NIRIUM_EVM_PAYER_KEY and NIRIUM_EVM_PAYTO"); process.exit(2); } +const network = arg("network", "eip155:84532"); +if (!["eip155:84532", "eip155:8453"].includes(network)) { console.error("--network must be eip155:84532 or eip155:8453"); process.exit(2); } + +const app = express(); +app.use(x402Serve({ payTo, network, routes: { "GET /data": { price: "$0.01", description: "Nirium SDK selftest resource" } } })); +app.get("/data", (req, res) => res.json({ ok: true, at: new Date().toISOString() })); +const server = createServer(app); +await new Promise((r) => server.listen(0, "127.0.0.1", r)); +const url = `http://127.0.0.1:${server.address().port}/data`; + +try { + const signer = privateKeyToAccount(key); + const pay = createX402Fetch({ + signer, network, maxAmountPerPayment: "10000", allowMainnet: process.argv.includes("--allow-mainnet"), + policy: createRulesPolicy({ maxAmount: "10000", allowPayTo: [payTo], onDecision: (r) => console.log(`policy ${r.outcome}`) }), + }); + const res = await pay(url); + const s = settlementOf(res); + console.log(`HTTP ${res.status} tx=${s?.transaction}`); + if (!s) throw new Error("nothing settled"); + const receipt = await bindReceipt({ tx: s.transaction, network, ref, resource: url, note: "Nirium SDK selftest: x402Serve + createX402Fetch with policy", labels: ["selftest"], signer }); + const v = await verifyReceipt(receipt); + console.log(`receipt ${v.ok ? "VALID" : "INVALID"} (${v.checks.filter((c) => c.ok).length}/${v.checks.length} checks)`); + if (arg("out")) { writeFileSync(arg("out"), JSON.stringify(receipt, null, 2)); console.log(`wrote ${arg("out")}`); } + process.exitCode = v.ok ? 0 : 1; +} finally { + server.close(); +} diff --git a/base/sdk/index.mjs b/base/sdk/index.mjs new file mode 100644 index 0000000..3300ec9 --- /dev/null +++ b/base/sdk/index.mjs @@ -0,0 +1,12 @@ +// nirium-base: Nirium on Base and Base Sepolia. +// pay: createX402Fetch, settlementOf (optional pre-sign policy) +// charge: x402Serve (Express middleware, PayAI by default) +// prove: bindReceipt, verifyReceipt (payer-signed receipt bound to the transfer) +// decide: bindDecision, verifyDecision (payer-signed receipt of a policy decision, incl. DENY/WAIT) +export { createX402Fetch, settlementOf } from "./pay.mjs"; +export { x402Serve } from "./serve.mjs"; +export { bindReceipt, verifyReceipt } from "./receipt.mjs"; +export { bindDecision, verifyDecision, decisionRecord, collectDecisions, DECISION_VERSION, DECISION_OUTCOMES } from "./decision.mjs"; +export { NETWORKS, TESTNET, MAINNET, PAYAI_FACILITATOR, getNetwork, dollarsToAtomic } from "./networks.mjs"; +export { createRulesPolicy } from "../policy/rules-policy.mjs"; +export { X402PolicyError } from "../policy/evm-policy.mjs"; diff --git a/base/sdk/networks.mjs b/base/sdk/networks.mjs new file mode 100644 index 0000000..acb7f6d --- /dev/null +++ b/base/sdk/networks.mjs @@ -0,0 +1,30 @@ +// Base networks Nirium supports. USDC addresses from Circle's official list +// (developers.circle.com/stablecoins/usdc-contract-addresses). The EIP-712 domain is NOT the same on +// both networks: read from the contracts on 30-nov-2026, Base Sepolia USDC answers name "USDC", +// Base mainnet USDC answers name "USD Coin", both version "2". A wrong name makes every signature invalid. +import { base, baseSepolia } from "viem/chains"; + +export const NETWORKS = Object.freeze({ + "eip155:84532": { chain: baseSepolia, usdc: "0x036CbD53842c5426634e7929541eC2318f3dCF7e", extra: Object.freeze({ name: "USDC", version: "2" }), explorer: "https://sepolia.basescan.org/tx/", mainnet: false }, + "eip155:8453": { chain: base, usdc: "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913", extra: Object.freeze({ name: "USD Coin", version: "2" }), explorer: "https://basescan.org/tx/", mainnet: true }, +}); +export const TESTNET = "eip155:84532"; +export const MAINNET = "eip155:8453"; +export const USDC_DECIMALS = 6; +/** Independent x402 facilitator used by default. Nirium does not run one. */ +export const PAYAI_FACILITATOR = "https://facilitator.payai.network"; + +export function getNetwork(id) { + const n = NETWORKS[id]; + if (!n) throw new Error(`unsupported network ${id}; use one of ${Object.keys(NETWORKS).join(", ")}`); + return n; +} + +/** "$0.01" or "0.01" -> atomic USDC units as a string. Rejects more than 6 decimals. */ +export function dollarsToAtomic(price) { + const m = /^\$?(\d+)(?:\.(\d{1,6}))?$/.exec(String(price).trim()); + if (!m) throw new Error(`price "${price}" must look like "$0.01" (at most 6 decimals)`); + const atomic = BigInt(m[1]) * 1_000_000n + BigInt((m[2] ?? "").padEnd(6, "0") || "0"); + if (atomic <= 0n) throw new Error(`price "${price}" must be above zero`); + return atomic.toString(); +} diff --git a/base/sdk/pay.mjs b/base/sdk/pay.mjs new file mode 100644 index 0000000..878ae9e --- /dev/null +++ b/base/sdk/pay.mjs @@ -0,0 +1,46 @@ +// createX402Fetch(): pay x402 resources on Base with a per-payment cap and, optionally, the +// pre-sign policy (a payment the policy refuses is never signed). Same idea as initX402 + +// x402Fetch in the `nirium` package. +// +// const pay = createX402Fetch({ signer: account, network: "eip155:84532", maxAmountPerPayment: "10000", policy }); +// const res = await pay("https://seller.example/paid"); +// const settlement = settlementOf(res); // { transaction, network, payer } or undefined + +import { wrapFetchWithPaymentFromConfig, decodePaymentResponseHeader } from "@x402/fetch"; +import { ExactEvmScheme } from "@x402/evm/exact/client"; +import { createPolicyX402Fetch } from "../policy/x402-fetch.mjs"; +import { getNetwork } from "./networks.mjs"; + +/** + * @param {object} cfg + * @param {{address: string, signTypedData: Function}} cfg.signer e.g. a viem account (the payer's own key) + * @param {"eip155:84532"|"eip155:8453"} [cfg.network] default Base Sepolia + * @param {string} cfg.maxAmountPerPayment cap in atomic USDC; refuses anything above before signing + * @param {object} [cfg.policy] X402PolicyHook; when set, nothing is signed without its ALLOW + * @param {boolean} [cfg.allowMainnet] must be true to pay on eip155:8453 + * @param {typeof fetch} [cfg.fetch] + */ +export function createX402Fetch(cfg) { + const network = cfg.network || "eip155:84532"; + const net = getNetwork(network); + if (net.mainnet && cfg.allowMainnet !== true) throw new Error("createX402Fetch: refusing mainnet without allowMainnet: true (real funds)"); + if (!/^\d+$/.test(String(cfg.maxAmountPerPayment ?? ""))) throw new Error("createX402Fetch: maxAmountPerPayment (atomic USDC) is required"); + if (cfg.policy) { + return createPolicyX402Fetch({ + signer: cfg.signer, policy: cfg.policy, network, asset: net.usdc, + maxAmountPerPayment: String(cfg.maxAmountPerPayment), fetch: cfg.fetch, + }); + } + return wrapFetchWithPaymentFromConfig(cfg.fetch ?? globalThis.fetch, { + schemes: [{ network, client: new ExactEvmScheme(cfg.signer) }], + spendControls: { allowedAssets: [{ network, asset: net.usdc, maxAmountPerPayment: String(cfg.maxAmountPerPayment) }] }, + }); +} + +/** Reads the settlement from a paid response, or undefined if nothing was settled. */ +export function settlementOf(response) { + const h = response?.headers?.get?.("PAYMENT-RESPONSE"); + if (!h) return undefined; + const s = decodePaymentResponseHeader(h); + return s?.success ? s : undefined; +} diff --git a/base/sdk/receipt.mjs b/base/sdk/receipt.mjs new file mode 100644 index 0000000..30880a8 --- /dev/null +++ b/base/sdk/receipt.mjs @@ -0,0 +1,96 @@ +// bindReceipt(): builds a "nirium-payment-binding-v1" receipt for a settled x402 payment on +// Base, bound to the exact USDC Transfer log (block-level logIndex) and its EIP-3009 nonce, +// and signs it as the payer when a signer is given. Format: docs/payment-binding-v1.md. +// +// The receipt adds what the chain does not keep: who declared the payment and what it was for +// (`purpose`). It does not prove delivery. + +import { createPublicClient, http, decodeEventLog, parseAbi, isAddressEqual, getAddress } from "viem"; +import { contentSha256, canonicalize, sha256Hex, verifyBinding, VERSION, STATEMENT_PREFIX } from "../verify-evm-core.mjs"; +import { getNetwork, USDC_DECIMALS } from "./networks.mjs"; + +const ABI = parseAbi([ + "event Transfer(address indexed from, address indexed to, uint256 value)", + "event AuthorizationUsed(address indexed authorizer, bytes32 indexed nonce)", +]); + +function sortKeys(v) { + if (v === null || typeof v !== "object") return v; + if (Array.isArray(v)) return v.map(sortKeys); + return Object.fromEntries(Object.keys(v).sort().map((k) => [k, sortKeys(v[k])])); +} + +/** + * @param {object} o + * @param {string} o.tx settled tx hash (from the PAYMENT-RESPONSE header's `transaction`) + * @param {string} o.network "eip155:84532" | "eip155:8453" + * @param {string} o.ref order reference (purpose.ref) + * @param {string} [o.resource] the paid URL + * @param {string} [o.note] short, no personal data + * @param {string[]} [o.labels] e.g. ["selftest"]; default [] + * @param {object} [o.signer] viem account of the payer ({ address, signMessage }); omit for an unsigned receipt + * @param {string} [o.payer] narrow the Transfer when the tx settled several (batch) + * @param {string} [o.payTo] + * @param {string} [o.rpcUrl] + * @param {number} [o.waitMs] how long to wait for the tx to appear on the RPC, default 60000 + */ +export async function bindReceipt(o) { + const { tx, network, ref } = o; + if (!/^0x[0-9a-fA-F]{64}$/.test(String(tx))) throw new Error("bindReceipt: tx must be a 0x 32-byte hash"); + if (typeof ref !== "string" || !ref.trim()) throw new Error("bindReceipt: ref (purpose.ref) is required"); + const net = getNetwork(network); + const client = createPublicClient({ chain: net.chain, transport: http(o.rpcUrl) }); + const chainId = await client.getChainId(); + if (`eip155:${chainId}` !== network) throw new Error(`RPC chainId ${chainId} does not match ${network}`); + // Right after settlement the public RPC may not have the receipt yet: wait for it (bounded). + const receipt = await client.waitForTransactionReceipt({ hash: tx, timeout: o.waitMs ?? 60_000, pollingInterval: 2_000 }); + if (receipt.status !== "success") throw new Error(`tx status ${receipt.status}`); + + const decoded = receipt.logs + .filter((l) => isAddressEqual(l.address, net.usdc)) + .map((l) => { try { return { log: l, ev: decodeEventLog({ abi: ABI, data: l.data, topics: l.topics }) }; } catch { return null; } }) + .filter(Boolean); + const payerHint = o.signer?.address ?? o.payer; + let transfers = decoded.filter((d) => d.ev.eventName === "Transfer"); + if (payerHint) transfers = transfers.filter((d) => isAddressEqual(d.ev.args.from, payerHint)); + if (o.payTo) transfers = transfers.filter((d) => isAddressEqual(d.ev.args.to, o.payTo)); + if (transfers.length !== 1) throw new Error(`expected exactly 1 USDC Transfer${payerHint ? " from " + payerHint : ""}${o.payTo ? " to " + o.payTo : ""}, found ${transfers.length}`); + const t = transfers[0]; + const payer = getAddress(t.ev.args.from); + const auths = decoded.filter((d) => d.ev.eventName === "AuthorizationUsed" && isAddressEqual(d.ev.args.authorizer, payer)); + if (auths.length !== 1) throw new Error(`expected exactly 1 AuthorizationUsed by ${payer}, found ${auths.length}`); + + const record = sortKeys({ + labels: o.labels ?? [], + payment: { + amount: t.ev.args.value.toString(), + asset: getAddress(net.usdc), + decimals: USDC_DECIMALS, + from: payer, + locator: { index: t.log.logIndex, kind: "evm-log" }, + network, + to: getAddress(t.ev.args.to), + tx, + x402: { nonce: auths[0].ev.args.nonce, resource: o.resource ?? "unknown", scheme: "exact" }, + }, + purpose: { note: o.note ?? "", ref }, + }); + const hash = contentSha256(record); + // Compatible with the Audit Trail verifier: sha256(JSON.stringify(record)) is the same hash. + const plain = sha256Hex(JSON.stringify(record)); + if (plain !== hash || JSON.stringify(record) !== canonicalize(record)) throw new Error("record is not in canonical order (bug)"); + + const doc = { version: VERSION, content_sha256: hash, record }; + if (o.signer) { + if (!isAddressEqual(o.signer.address, payer)) throw new Error(`signer ${o.signer.address} is not the payer ${payer}`); + const statement = STATEMENT_PREFIX + hash; + doc.agent = { alg: "eip191-secp256k1", key: getAddress(o.signer.address), signature: await o.signer.signMessage({ message: statement }), statement }; + } + doc.network = network; + return doc; +} + +/** Verifies a receipt against the chain. Returns { ok, checks }. */ +export function verifyReceipt(doc, { requireSignature = true, rpcUrl } = {}) { + return verifyBinding(doc, { requireSig: requireSignature, rpc: rpcUrl }); +} diff --git a/base/sdk/serve.mjs b/base/sdk/serve.mjs new file mode 100644 index 0000000..e35fcf8 --- /dev/null +++ b/base/sdk/serve.mjs @@ -0,0 +1,106 @@ +// x402Serve(): charge for your own API on Base in three lines, same shape as the Stellar one +// in the `nirium` package: +// +// app.use(x402Serve({ payTo: "0x...", routes: { "GET /signals": "$0.02" } })); +// +// Runs on YOUR server. Nirium runs nothing here and receives nothing: the buyer pays your payTo +// directly and an independent facilitator (PayAI by default) verifies and settles. No telemetry. +// +// Prices are converted to an explicit USDC amount with the token's EIP-712 domain from our own network +// table (Base USDC is also in @x402/evm 2.32.0 DEFAULT_ASSETS, with the same domain). The middleware is built on the first request, +// after a /supported preflight, so a facilitator that is down or rejects you answers 503 with a +// hint instead of crashing the process (the same lesson as the Stellar x402Serve). + +import { isAddress, getAddress } from "viem"; +import { getNetwork, dollarsToAtomic, PAYAI_FACILITATOR } from "./networks.mjs"; + +// Linear time. A `/\/+$/` replace is polynomial on input made of many slashes (CodeQL +// js/polynomial-redos); the URL comes from config, but there is no reason to keep the risk. +export function trimTrailingSlashes(url) { + let s = String(url); + let end = s.length; + while (end > 0 && s.charCodeAt(end - 1) === 47) end--; + return s.slice(0, end); +} + +/** + * @param {object} config + * @param {string} config.payTo address that receives the USDC + * @param {Record} config.routes + * "GET /signals": "$0.02"; `amount` takes atomic units instead of dollars; method defaults to GET + * @param {"eip155:84532"|"eip155:8453"} [config.network] default Base Sepolia + * @param {string} [config.facilitatorUrl] default PayAI + * @param {number} [config.maxTimeoutSeconds] default 120 + * @param {string} [config.appName] + */ +export function x402Serve(config) { + if (!config || !isAddress(String(config.payTo ?? ""))) throw new Error("x402Serve: `payTo` must be a 0x address. Without it there is nobody to pay."); + const entries = Object.entries(config.routes || {}); + if (entries.length === 0) throw new Error("x402Serve: `routes` is empty; nothing would ever be charged for."); + const network = config.network || "eip155:84532"; + const net = getNetwork(network); + const payTo = getAddress(config.payTo); + const facilitatorUrl = trimTrailingSlashes(config.facilitatorUrl || PAYAI_FACILITATOR); + + const routes = {}; + for (const [key, value] of entries) { + const spec = typeof value === "string" ? { price: value } : value; + const amount = spec.amount !== undefined ? String(spec.amount) : dollarsToAtomic(spec.price); + if (!/^\d+$/.test(amount) || BigInt(amount) <= 0n) throw new Error(`x402Serve: route "${key}" needs a positive amount`); + const routeKey = /^[A-Z]+\s/.test(key) ? key : `GET ${key}`; + routes[routeKey] = { + ...(spec.description ? { description: spec.description } : {}), + accepts: [{ + scheme: "exact", network, payTo, + price: { amount, asset: net.usdc, extra: { ...net.extra } }, + maxTimeoutSeconds: config.maxTimeoutSeconds ?? 120, + }], + }; + } + + const preflight = async () => { + const r = await fetch(`${facilitatorUrl}/supported`, { signal: AbortSignal.timeout(10_000) }); + if (!r.ok) throw new Error(`facilitator returned ${r.status}`); + const body = await r.json(); + const ok = (body?.kinds ?? []).some((k) => k.network === network && k.scheme === "exact"); + if (!ok) throw new Error(`facilitator does not support exact on ${network}`); + }; + + let cached; + const build = async () => { + await preflight(); + const [{ paymentMiddleware, x402ResourceServer }, { HTTPFacilitatorClient }, { ExactEvmScheme }] = await Promise.all([ + import("@x402/express"), import("@x402/core/server"), import("@x402/evm/exact/server"), + ]); + const facilitator = new HTTPFacilitatorClient({ url: facilitatorUrl }); + const server = new x402ResourceServer(facilitator).register(network, new ExactEvmScheme()); + return paymentMiddleware(routes, server); + }; + + // Only requests to a paid route touch the facilitator. Everything else passes straight + // through, so a facilitator outage never takes down the rest of the app. + const paid = Object.keys(routes).map((k) => { + const [method, path] = k.split(/\s+/, 2); + return { method: method.toUpperCase(), path, prefix: path.endsWith("/*") ? path.slice(0, -1) : undefined }; + }); + const isPaid = (req) => { + const path = String(req.path ?? req.url ?? "").split("?")[0]; + return paid.some((r) => r.method === String(req.method).toUpperCase() && (r.prefix ? path.startsWith(r.prefix) : path === r.path)); + }; + + return async function niriumX402(req, res, next) { + if (!isPaid(req)) return next(); + try { + if (!cached) cached = build().catch((e) => { cached = undefined; throw e; }); + const mw = await cached; + return mw(req, res, next); + } catch (err) { + if (res.headersSent) return; + res.status(503).json({ + error: "x402 payments unavailable", + detail: String(err?.message ?? err).slice(0, 200), + hint: "the facilitator could not be reached or does not support this network", + }); + } + }; +} diff --git a/base/sdk/test/decision.test.mjs b/base/sdk/test/decision.test.mjs new file mode 100755 index 0000000..da98729 --- /dev/null +++ b/base/sdk/test/decision.test.mjs @@ -0,0 +1,113 @@ +// Decision receipts from REAL policy decisions: the same offline pay loop as sdk.test.mjs (a fake +// facilitator that checks the payer's EIP-3009 signature), so the receipts are built from exactly +// what the policy hands to onDecision. + +import { test, before, after } from "node:test"; +import assert from "node:assert/strict"; +import { createServer } from "node:http"; +import express from "express"; +import { generatePrivateKey, privateKeyToAccount } from "viem/accounts"; +import { + x402Serve, createX402Fetch, createRulesPolicy, X402PolicyError, + bindDecision, verifyDecision, decisionRecord, collectDecisions, DECISION_VERSION, +} from "../index.mjs"; + +const SEPOLIA = "eip155:84532"; +const SEPOLIA_USDC = "0x036CbD53842c5426634e7929541eC2318f3dCF7e"; +let payer, other, payTo, fac, shop; + +async function listen(s) { await new Promise((r) => s.listen(0, "127.0.0.1", r)); return `http://127.0.0.1:${s.address().port}`; } + +before(async () => { + payer = privateKeyToAccount(generatePrivateKey()); + other = privateKeyToAccount(generatePrivateKey()); + payTo = privateKeyToAccount(generatePrivateKey()).address; + const facServer = createServer((req, res) => { + let body = ""; req.on("data", (c) => { body += c; }); + req.on("end", () => { + const send = (o) => { res.writeHead(200, { "content-type": "application/json" }); res.end(JSON.stringify(o)); }; + if (req.url.endsWith("/supported")) return send({ kinds: [{ x402Version: 2, scheme: "exact", network: SEPOLIA }], extensions: [], signers: { "eip155:*": [] } }); + const { paymentPayload: p } = JSON.parse(body); + const from = p.payload.authorization.from; + if (req.url.endsWith("/verify")) return send({ isValid: true, payer: from }); + return send({ success: true, transaction: "0x" + "ab".repeat(32), network: SEPOLIA, payer: from }); + }); + }); + fac = { server: facServer, url: await listen(facServer) }; + const app = express(); + app.use(x402Serve({ payTo, network: SEPOLIA, facilitatorUrl: fac.url, routes: { "GET /paid": "$0.01" } })); + app.get("/paid", (req, res) => res.json({ ok: true })); + const shopServer = createServer(app); + shop = { server: shopServer, url: await listen(shopServer) }; +}); +after(() => { fac.server.close(); shop.server.close(); }); + +async function attempt(rules) { + const col = collectDecisions(); + const pay = createX402Fetch({ signer: payer, network: SEPOLIA, maxAmountPerPayment: "10000", policy: createRulesPolicy({ ...rules, onDecision: col.onDecision }) }); + let error; + try { await pay(`${shop.url}/paid`); } catch (e) { error = e; } + return { records: col.records, error }; +} + +test("a DENY that never reached the chain gets a payer-signed receipt saying what it would have paid and why", async () => { + const { records, error } = await attempt({ maxAmount: "5000" }); + assert.ok(error instanceof X402PolicyError && error.outcome === "DENY"); + assert.deepEqual(records.map((r) => r.outcome), ["DENY"]); + const { doc, record } = await bindDecision(records[0], { signer: payer, ref: "order-deny", labels: ["test"] }); + assert.equal(doc.version, DECISION_VERSION); + assert.equal(doc.network, SEPOLIA); + assert.deepEqual(record.decision, { outcome: "DENY", policyVersion: "rules-v1", reason: "amount 10000 above limit 5000" }); + assert.equal(record.intent.amount, "10000"); + assert.equal(record.intent.asset, SEPOLIA_USDC); + assert.equal(record.intent.decimals, 6); + assert.equal(record.intent.from, payer.address); + assert.equal(record.intent.to, payTo); + assert.match(record.intent.nonce, /^0x[0-9a-f]{64}$/); + assert.equal(record.intent.resource, `${shop.url}/paid`); + assert.match(record.intent.payloadHash, /^[0-9a-f]{64}$/); + const v = await verifyDecision(doc); + assert.equal(v.ok, true, JSON.stringify(v.checks.filter((c) => !c.ok))); +}); + +test("WAIT, and an ALLOW followed by SIGNED, each get their own receipt", async () => { + const w = await attempt({ maxAmount: "20000", approvalAbove: "5000" }); + assert.deepEqual(w.records.map((r) => r.outcome), ["WAIT"]); + const wait = await bindDecision(w.records[0], { signer: payer, ref: "order-wait" }); + assert.equal(wait.record.decision.outcome, "WAIT"); + assert.equal((await verifyDecision(wait.doc)).ok, true); + + const a = await attempt({ maxAmount: "10000", allowPayTo: [payTo] }); + assert.equal(a.error, undefined); + assert.deepEqual(a.records.map((r) => r.outcome), ["ALLOWED", "SIGNED"]); + for (const r of a.records) { + const { doc } = await bindDecision(r, { signer: payer, ref: "order-allow" }); + assert.equal((await verifyDecision(doc)).ok, true); + } +}); + +test("hash-only receipts keep the content private and still verify; the held record must match", async () => { + const { records } = await attempt({ maxAmount: "5000" }); + const { doc, record } = await bindDecision(records[0], { signer: payer, ref: "order-private", hashOnly: true }); + assert.equal(doc.record, undefined); + assert.equal((await verifyDecision(doc)).ok, true); + assert.equal((await verifyDecision(doc, { record })).ok, true); + const changed = { ...record, decision: { ...record.decision, outcome: "ALLOWED" } }; + assert.equal((await verifyDecision(doc, { record: changed })).ok, false); +}); + +test("an edited decision, an altered signature or a key that is not the payer fail", async () => { + const { records } = await attempt({ maxAmount: "5000" }); + const { doc } = await bindDecision(records[0], { signer: payer, ref: "order-tamper" }); + const flipped = structuredClone(doc); flipped.record.decision.outcome = "ALLOWED"; + const v1 = await verifyDecision(flipped); + assert.equal(v1.ok, false); + assert.ok(v1.checks.some((c) => c.name.startsWith("content_sha256") && !c.ok)); + const badSig = structuredClone(doc); badSig.agent.signature = badSig.agent.signature.slice(0, -2) + (badSig.agent.signature.endsWith("1b") ? "1c" : "1b"); + assert.equal((await verifyDecision(badSig)).ok, false); + await assert.rejects(bindDecision(records[0], { signer: other, ref: "x" }), /is not the payer/); +}); + +test("a refusal before any payment was decoded has nothing to describe", () => { + assert.equal(decisionRecord({ outcome: "CONTEXT_MISMATCH", error: "not EIP-3009" }), null); +}); diff --git a/base/sdk/test/sdk.test.mjs b/base/sdk/test/sdk.test.mjs new file mode 100644 index 0000000..77d3519 --- /dev/null +++ b/base/sdk/test/sdk.test.mjs @@ -0,0 +1,149 @@ +// Tests for nirium-base. The pay/serve loop runs offline against a local fake facilitator +// that checks the payer's EIP-3009 signature before "settling". The receipt test reads one real +// Fuji transaction from the team's own evidence over the public RPC. + +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { createServer } from "node:http"; +import { readFileSync } from "node:fs"; +import express from "express"; +import { generatePrivateKey, privateKeyToAccount } from "viem/accounts"; +import { verifyTypedData } from "viem"; +import { + x402Serve, createX402Fetch, settlementOf, bindReceipt, verifyReceipt, dollarsToAtomic, + createRulesPolicy, X402PolicyError, +} from "../index.mjs"; + +const SEPOLIA = "eip155:84532"; +const SEPOLIA_USDC = "0x036CbD53842c5426634e7929541eC2318f3dCF7e"; +const TWA = [ + { name: "from", type: "address" }, { name: "to", type: "address" }, { name: "value", type: "uint256" }, + { name: "validAfter", type: "uint256" }, { name: "validBefore", type: "uint256" }, { name: "nonce", type: "bytes32" }, +]; + +async function listen(server) { await new Promise((r) => server.listen(0, "127.0.0.1", r)); return `http://127.0.0.1:${server.address().port}`; } + +/** Fake facilitator: answers /supported, and on /verify and /settle checks the EIP-3009 signature. */ +async function fakeFacilitator() { + const calls = { verify: 0, settle: 0, bad: 0, last: undefined }; + const server = createServer((req, res) => { + let body = ""; req.on("data", (c) => { body += c; }); + req.on("end", async () => { + const send = (o) => { res.writeHead(200, { "content-type": "application/json" }); res.end(JSON.stringify(o)); }; + if (req.url.endsWith("/supported")) return send({ kinds: [{ x402Version: 2, scheme: "exact", network: SEPOLIA }], extensions: [], signers: { "eip155:*": [] } }); + const { paymentPayload: p, paymentRequirements: r } = JSON.parse(body); + const a = p.payload.authorization; + const ok = await verifyTypedData({ + address: a.from, domain: { name: r.extra.name, version: r.extra.version, chainId: 84532, verifyingContract: r.asset }, + types: { TransferWithAuthorization: TWA }, primaryType: "TransferWithAuthorization", + message: { ...a, value: BigInt(a.value), validAfter: BigInt(a.validAfter), validBefore: BigInt(a.validBefore) }, + signature: p.payload.signature, + }).catch(() => false); + if (!ok) calls.bad++; + calls.last = { authorization: a, requirements: r }; + if (req.url.endsWith("/verify")) { calls.verify++; return send({ isValid: ok, payer: a.from, ...(ok ? {} : { invalidReason: "bad_signature" }) }); } + calls.settle++; + return send(ok ? { success: true, transaction: "0x" + "ab".repeat(32), network: SEPOLIA, payer: a.from } : { success: false, errorReason: "bad_signature", transaction: "", network: SEPOLIA }); + }); + }); + return { url: await listen(server), calls, close: () => server.close() }; +} + +async function seller(facilitatorUrl, payTo) { + const app = express(); + app.use(x402Serve({ payTo, network: SEPOLIA, facilitatorUrl, routes: { "GET /paid": "$0.01", "/free-ish": { amount: "1" } } })); + app.get("/paid", (req, res) => res.json({ ok: true })); + app.get("/health", (req, res) => res.json({ up: true })); + const server = createServer(app); + return { url: await listen(server), close: () => server.close() }; +} + +test("dollarsToAtomic converts exactly and rejects bad prices", () => { + assert.equal(dollarsToAtomic("$0.01"), "10000"); + assert.equal(dollarsToAtomic("1.5"), "1500000"); + assert.equal(dollarsToAtomic("$0.000001"), "1"); + for (const bad of ["$0", "0.0000001", "abc", "-1"]) assert.throws(() => dollarsToAtomic(bad), bad); +}); + +test("x402Serve refuses a bad config at mount, not at the first payment", () => { + assert.throws(() => x402Serve({ payTo: "nope", routes: { "/a": "$1" } }), /payTo/); + assert.throws(() => x402Serve({ payTo: privateKeyToAccount(generatePrivateKey()).address, routes: {} }), /routes/); + assert.throws(() => x402Serve({ payTo: privateKeyToAccount(generatePrivateKey()).address, routes: { "/a": "$1" }, network: "eip155:1" }), /unsupported network/); +}); + +test("createX402Fetch refuses mainnet unless allowMainnet is true", () => { + const signer = privateKeyToAccount(generatePrivateKey()); + assert.throws(() => createX402Fetch({ signer, network: "eip155:8453", maxAmountPerPayment: "10000" }), /mainnet/); + assert.ok(createX402Fetch({ signer, network: "eip155:8453", maxAmountPerPayment: "10000", allowMainnet: true })); +}); + +test("pay and charge end to end: the seller is paid with a signature the facilitator verifies as the payer's", async () => { + const fac = await fakeFacilitator(); + const payTo = privateKeyToAccount(generatePrivateKey()).address; + const s = await seller(fac.url, payTo); + try { + const unpaid = await fetch(`${s.url}/paid`); + assert.equal(unpaid.status, 402); + const signer = privateKeyToAccount(generatePrivateKey()); + const pay = createX402Fetch({ signer, network: SEPOLIA, maxAmountPerPayment: "10000" }); + const res = await pay(`${s.url}/paid`); + assert.equal(res.status, 200); + assert.deepEqual(await res.json(), { ok: true }); + assert.equal(fac.calls.verify, 1); + assert.equal(fac.calls.settle, 1); + assert.equal(fac.calls.bad, 0); + const { authorization: a, requirements: r } = fac.calls.last; + assert.equal(a.from.toLowerCase(), signer.address.toLowerCase()); + assert.equal(a.to.toLowerCase(), payTo.toLowerCase()); + assert.equal(String(a.value), "10000"); + assert.equal(r.asset.toLowerCase(), SEPOLIA_USDC.toLowerCase()); + assert.equal(settlementOf(res).transaction, "0x" + "ab".repeat(32)); + } finally { s.close(); fac.close(); } +}); + +test("the per-payment cap refuses a price above it before anything is signed", async () => { + const fac = await fakeFacilitator(); + const s = await seller(fac.url, privateKeyToAccount(generatePrivateKey()).address); + try { + const pay = createX402Fetch({ signer: privateKeyToAccount(generatePrivateKey()), network: SEPOLIA, maxAmountPerPayment: "9999" }); + await assert.rejects(pay(`${s.url}/paid`)); + assert.equal(fac.calls.verify + fac.calls.settle, 0); + } finally { s.close(); fac.close(); } +}); + +test("with a policy, DENY sends nothing to the seller or the facilitator; ALLOW pays", async () => { + const fac = await fakeFacilitator(); + const payTo = privateKeyToAccount(generatePrivateKey()).address; + const s = await seller(fac.url, payTo); + try { + const signer = privateKeyToAccount(generatePrivateKey()); + const deny = createX402Fetch({ signer, network: SEPOLIA, maxAmountPerPayment: "10000", policy: createRulesPolicy({ maxAmount: "5000" }) }); + await assert.rejects(deny(`${s.url}/paid`), (e) => e instanceof X402PolicyError && e.outcome === "DENY"); + assert.equal(fac.calls.verify + fac.calls.settle, 0); + const allow = createX402Fetch({ signer, network: SEPOLIA, maxAmountPerPayment: "10000", policy: createRulesPolicy({ maxAmount: "10000", allowPayTo: [payTo] }) }); + const res = await allow(`${s.url}/paid`); + assert.equal(res.status, 200); + assert.equal(fac.calls.settle, 1); + } finally { s.close(); fac.close(); } +}); + +test("a facilitator that is down answers 503 with a hint on paid routes only, and the app keeps serving", async () => { + const s = await seller("http://127.0.0.1:9", privateKeyToAccount(generatePrivateKey()).address); + try { + const r = await fetch(`${s.url}/paid`); + assert.equal(r.status, 503); + assert.match((await r.json()).hint, /facilitator/); + assert.equal((await fetch(`${s.url}/health`)).status, 200); + } finally { s.close(); } +}); + +test("bindReceipt rebuilds the team's real Fuji receipt from the chain, and refuses a signer that is not the payer", async () => { + const evidence = JSON.parse(readFileSync(new URL("../../../evidence/2026-11-26/fuji-a2-binding.json", import.meta.url), "utf8")); + const p = evidence.record.payment; + const doc = await bindReceipt({ tx: p.tx, network: p.network, ref: evidence.record.purpose.ref, note: evidence.record.purpose.note, resource: p.x402.resource, labels: evidence.record.labels }); + assert.deepEqual(doc.record, evidence.record); + assert.equal(doc.content_sha256, evidence.content_sha256); + const v = await verifyReceipt(doc, { requireSignature: false }); + assert.equal(v.ok, true); + await assert.rejects(bindReceipt({ tx: p.tx, network: p.network, ref: "x", signer: privateKeyToAccount(generatePrivateKey()) }), /expected exactly 1 USDC Transfer|not the payer/); +}); diff --git a/base/sdk/test/trim.test.mjs b/base/sdk/test/trim.test.mjs new file mode 100755 index 0000000..d88ea02 --- /dev/null +++ b/base/sdk/test/trim.test.mjs @@ -0,0 +1,16 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { trimTrailingSlashes } from "../serve.mjs"; + +test("trimTrailingSlashes removes only trailing slashes, in linear time", () => { + assert.equal(trimTrailingSlashes("https://facilitator.payai.network"), "https://facilitator.payai.network"); + assert.equal(trimTrailingSlashes("https://facilitator.payai.network/"), "https://facilitator.payai.network"); + assert.equal(trimTrailingSlashes("https://x.example/a///"), "https://x.example/a"); + assert.equal(trimTrailingSlashes("///"), ""); + assert.equal(trimTrailingSlashes(""), ""); + const evil = "/".repeat(200_000) + "x"; + const t0 = Date.now(); + assert.equal(trimTrailingSlashes(evil), evil); + assert.equal(trimTrailingSlashes("a" + "/".repeat(200_000)), "a"); + assert.ok(Date.now() - t0 < 200, "should be linear"); +}); diff --git a/base/test/verify-core.test.mjs b/base/test/verify-core.test.mjs new file mode 100644 index 0000000..4ecb759 --- /dev/null +++ b/base/test/verify-core.test.mjs @@ -0,0 +1,128 @@ +// Unit tests for verify-evm-core.mjs, the one verifier the CLI, verifyReceipt() and the browser +// share. No network: the full check runs against recorded public Fuji RPC answers for one of the +// team's self-test receipts (fixtures/fuji-sdk-selftest-rpc.json). +// +// node:crypto appears here only as the reference the code used before it moved to viem's sha256, +// so each hash test checks that the two agree. + +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { readFileSync, readdirSync } from "node:fs"; +import { spawnSync } from "node:child_process"; +import { createHash } from "node:crypto"; +import { verifyMessage } from "viem"; +import { privateKeyToAccount, generatePrivateKey } from "viem/accounts"; +import { canonicalize, contentSha256, sha256Hex, verifyBinding, STATEMENT_PREFIX } from "../verify-evm-core.mjs"; +import { computeContextHash } from "../policy/evm-policy.mjs"; + +const read = (p) => JSON.parse(readFileSync(new URL(p, import.meta.url), "utf8")); +const receipts = ["2026-11-26", "2026-11-27"].flatMap((d) => + readdirSync(new URL(`../../evidence/${d}/`, import.meta.url)).filter((f) => f.endsWith("-binding.json")) + .map((f) => ({ name: `${d}/${f}`, doc: read(`../../evidence/${d}/${f}`) }))); +const recorded = read("../fixtures/fuji-sdk-selftest-rpc.json"); +const selftest = read("../../evidence/2026-11-26/fuji-sdk-binding.json"); + +const nodeSha = (s) => createHash("sha256").update(s, "utf8").digest("hex"); +const clone = (d) => JSON.parse(JSON.stringify(d)); +const failing = (res) => res.checks.filter((c) => !c.ok).map((c) => c.name).sort(); + +// A fetch that answers eth_chainId and eth_getTransactionReceipt from the recording. +async function withRecordedRpc(fn) { + const real = globalThis.fetch; + globalThis.fetch = async (_url, init) => { + const body = JSON.parse(init.body); + const answer = ({ id, method, params }) => { + if (method === "eth_chainId") return { jsonrpc: "2.0", id, result: recorded.chainId }; + if (method === "eth_getTransactionReceipt") { + return { jsonrpc: "2.0", id, result: params[0].toLowerCase() === recorded.txReceipt.transactionHash.toLowerCase() ? recorded.txReceipt : null }; + } + throw new Error(`unexpected RPC method ${method}`); + }; + const out = Array.isArray(body) ? body.map(answer) : answer(body); + return new Response(JSON.stringify(out), { headers: { "content-type": "application/json" } }); + }; + try { return await fn(); } finally { globalThis.fetch = real; } +} + +test("record hash matches every evidence receipt and fixture, and matches node:crypto", () => { + const fixtures = readdirSync(new URL("../fixtures/", import.meta.url)).filter((f) => f.startsWith("june-")) + .map((f) => ({ name: f, doc: read(`../fixtures/${f}`) })); + assert.ok(receipts.length >= 7, `expected the evidence receipts, found ${receipts.length}`); + for (const { name, doc } of receipts) assert.equal(contentSha256(doc.record), doc.content_sha256, name); + for (const { name, doc } of [...receipts, ...fixtures]) { + assert.equal(contentSha256(doc.record), nodeSha(canonicalize(doc.record)), name); + } +}); + +test("sha256Hex agrees with node:crypto, including non-ASCII text", () => { + for (const s of ["", "a", "pago de prueba ñandú", "日本語", "emoji 🧾", "
", JSON.stringify(selftest.record)]) { + assert.equal(sha256Hex(s), nodeSha(s), JSON.stringify(s)); + } +}); + +test("the policy contextHash is unchanged (same value node:crypto gave)", () => { + const cases = [["https://seller.example/paid", "GET", "0x" + "ab".repeat(32)], ["http://localhost:4021/x?y=1", "POST", "0x" + "00".repeat(32)]]; + for (const [url, method, payloadHash] of cases) { + assert.equal(computeContextHash(url, method, payloadHash), nodeSha(JSON.stringify({ v: 1, url, method, payloadHash }))); + } +}); + +test("payer signatures on every evidence receipt verify", async () => { + for (const { name, doc } of receipts) { + const a = doc.agent; + assert.equal(a.statement, STATEMENT_PREFIX + doc.content_sha256, name); + assert.equal(await verifyMessage({ address: a.key, message: a.statement, signature: a.signature }), true, name); + } +}); + +test("full check offline: the team's Fuji self-test receipt is VALID", async () => { + const res = await withRecordedRpc(() => verifyBinding(clone(selftest))); + assert.deepEqual(failing(res), []); + assert.equal(res.ok, true); + assert.equal(res.checks.length, 18); +}); + +test("full check offline: each altered field fails for its own reason", async () => { + const STATEMENT = "agent.statement == nirium-audit-v1:"; + const HASH = "content_sha256 == sha256(canonical(record))"; + const rehash = (d) => { d.content_sha256 = contentSha256(d.record); return d; }; + const AUTH = "AuthorizationUsed(payment.from, x402.nonce) in same tx"; + const other = privateKeyToAccount(generatePrivateKey()).address; + const cases = [ + ["amount +1, hash not updated", (d) => { d.record.payment.amount = "10001"; }, [HASH, "Transfer.value == payment.amount"]], + ["amount +1, hash updated", (d) => { d.record.payment.amount = "10001"; rehash(d); }, [STATEMENT, "Transfer.value == payment.amount"]], + ["destination changed, hash updated", (d) => { d.record.payment.to = other; rehash(d); }, [STATEMENT, "Transfer.to == payment.to"]], + ["purpose edited, hash not updated", (d) => { d.record.purpose.note = "something else"; }, [HASH]], + ["purpose edited, hash updated", (d) => { d.record.purpose.ref = "order-99"; rehash(d); }, [STATEMENT]], + ["nonce changed, hash updated", (d) => { d.record.payment.x402.nonce = "0x" + "11".repeat(32); rehash(d); }, [STATEMENT, AUTH]], + ["log index moved, hash updated", (d) => { d.record.payment.locator.index = 0; rehash(d); }, [STATEMENT, "log 0 is Transfer"]], + ["signature altered", (d) => { const s = d.agent.signature; d.agent.signature = s.slice(0, 10) + (s[10] === "a" ? "b" : "a") + s.slice(11); }, + ["EIP-191 signature by agent.key over agent.statement"]], + ]; + for (const [name, mutate, expected] of cases) { + const d = clone(selftest); + mutate(d); + const res = await withRecordedRpc(() => verifyBinding(d)); + assert.equal(res.ok, false, name); + assert.deepEqual(failing(res), [...expected].sort(), name); + } +}); + +test("browser-safe: the verifier, receipt and policy modules use nothing Node-only, and load with browser exports", () => { + const files = ["../verify-evm-core.mjs", "../sdk/receipt.mjs", "../sdk/networks.mjs", "../policy/evm-policy.mjs", "../policy/rules-policy.mjs"]; + for (const f of files) { + // Comments may name what the file avoids, so only code is searched. + const src = readFileSync(new URL(f, import.meta.url), "utf8").replace(/\/\*[\s\S]*?\*\//g, "").replace(/(^|[^:])\/\/.*$/gm, "$1"); + assert.doesNotMatch(src, /from\s+["']node:|import\(["']node:|require\(|\bBuffer\b|\bprocess\./, f); + } + const urls = files.map((f) => new URL(f, import.meta.url).href); + const script = ` + for (const u of ${JSON.stringify(urls)}) await import(u); + const m = await import(${JSON.stringify(urls[0])}); + const doc = ${JSON.stringify(selftest)}; + if (m.contentSha256(doc.record) !== doc.content_sha256) throw new Error("hash"); + console.log("ok");`; + const r = spawnSync(process.execPath, ["--conditions=browser", "--input-type=module", "-e", script], { encoding: "utf8" }); + assert.equal(r.status, 0, r.stderr); + assert.equal(r.stdout.trim(), "ok"); +}); diff --git a/base/verify-evm-core.mjs b/base/verify-evm-core.mjs new file mode 100644 index 0000000..8baf0e2 --- /dev/null +++ b/base/verify-evm-core.mjs @@ -0,0 +1,159 @@ +// verify-evm-core.mjs - read-only check of a Nirium EVM payment binding. +// +// The one verifier: the CLI (verify-evm-receipt.mjs), verifyReceipt() and the browser all run +// this file. It has no Node-only imports (no node:crypto, no fs), so it also runs in a browser: +// sha256 comes from viem (built on @noble/hashes). +// +// Format "nirium-payment-binding-v1" (fixed 26-nov-2026): +// { +// "version": "nirium-payment-binding-v1", +// "content_sha256": "", +// "record": { +// "labels": ["selftest"], +// "payment": { +// "amount": "10000", "asset": "0x...", "decimals": 6, +// "from": "0x..payer", "to": "0x..payTo", "tx": "0x..", +// "locator": { "index": 17, "kind": "evm-log" }, // block-level log index +// "network": "eip155:84532", +// "x402": { "nonce": "0x..authNonce", "resource": "https://...", "scheme": "exact" } +// }, +// "purpose": { "note": "...", "ref": "..." } +// }, +// "agent": { "alg": "eip191-secp256k1", "key": "0x..payer", +// "signature": "0x..", "statement": "nirium-audit-v1:" }, +// "network": "eip155:84532" +// } +// +// canonical() = keys sorted recursively, no whitespace, values as JSON.stringify +// writes them; applied ONLY to `record`. +// --no-sig skips the `agent` block entirely (used for third-party txs we did +// not sign); the record hash and every on-chain check still run. +// +// Not supported yet: payers that are smart wallets (ERC-1271/6492) +// need publicClient.verifyMessage instead of the standalone ECDSA verifyMessage. +// Not supported yet: seller-signed bindings (agent.key == payment.to) once that role exists. +// +// No keys, no writes: only eth_chainId and eth_getTransactionReceipt. + +import { + createPublicClient, http, decodeEventLog, parseAbi, getAddress, + isAddressEqual, verifyMessage, sha256, stringToBytes, +} from "viem"; +import { base, baseSepolia } from "viem/chains"; + +export const VERSION = "nirium-payment-binding-v1"; +export const STATEMENT_PREFIX = "nirium-audit-v1:"; + +const CHAINS = { + "eip155:8453": { chain: base, usdc: "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913" }, + "eip155:84532": { chain: baseSepolia, usdc: "0x036CbD53842c5426634e7929541eC2318f3dCF7e" }, +}; + +const ABI = parseAbi([ + "event Transfer(address indexed from, address indexed to, uint256 value)", + "event AuthorizationUsed(address indexed authorizer, bytes32 indexed nonce)", +]); + +export function canonicalize(v) { + if (v === null || typeof v !== "object") return JSON.stringify(v); + if (Array.isArray(v)) return "[" + v.map(canonicalize).join(",") + "]"; + return "{" + Object.keys(v).sort() + .filter((k) => v[k] !== undefined) + .map((k) => JSON.stringify(k) + ":" + canonicalize(v[k])).join(",") + "}"; +} + +/** sha256 of the UTF-8 bytes of a string, as lowercase hex without 0x. */ +export function sha256Hex(s) { + return sha256(stringToBytes(s)).slice(2); +} + +export function contentSha256(record) { + return sha256Hex(canonicalize(record)); +} + +const eqAddr = (a, b) => { try { return isAddressEqual(a, b); } catch { return false; } }; + +export async function verifyBinding(doc, { requireSig = true, rpc } = {}) { + const checks = []; + const add = (name, ok, detail = "") => checks.push({ name, ok: !!ok, detail }); + + const p = doc?.record?.payment; + if (!p) throw new Error("missing record.payment"); + for (const k of ["amount", "asset", "from", "to", "tx", "network"]) { + if (p[k] === undefined || p[k] === null || p[k] === "") throw new Error(`missing record.payment.${k}`); + } + if (!p.locator || p.locator.index === undefined) throw new Error("missing record.payment.locator.index"); + if (!p.x402?.nonce) throw new Error("missing record.payment.x402.nonce"); + const net = CHAINS[p.network]; + if (!net) throw new Error(`unsupported network ${p.network}`); + + // Document-level consistency. + add("version == nirium-payment-binding-v1", doc.version === VERSION, `version=${doc.version}`); + add("network == record.payment.network", doc.network === p.network, `doc=${doc.network} payment=${p.network}`); + add("locator.kind == evm-log", p.locator.kind === "evm-log", `kind=${p.locator.kind}`); + const computed = contentSha256(doc.record); + add("content_sha256 == sha256(canonical(record))", doc.content_sha256 === computed, + `doc=${doc.content_sha256} computed=${computed}`); + add("asset is Circle USDC for this network", eqAddr(p.asset, net.usdc), `asset=${p.asset} expected=${net.usdc}`); + add("decimals == 6", p.decimals === 6, `decimals=${p.decimals}`); + + // Chain. + const client = createPublicClient({ chain: net.chain, transport: http(rpc) }); + const chainId = await client.getChainId(); + add("network == eip155:", p.network === `eip155:${chainId}`, `rpc chainId=${chainId}`); + + let receipt = null; + try { + receipt = await client.getTransactionReceipt({ hash: p.tx }); + } catch (e) { + add("tx receipt found", false, e.shortMessage || e.message); + } + if (receipt) { + add("tx status success (1)", receipt.status === "success", `status=${receipt.status} block=${receipt.blockNumber}`); + + const idx = Number(p.locator.index); + const amount = BigInt(p.amount); + const log = receipt.logs.find((l) => l.logIndex === idx); + if (!log) { + add(`log ${idx} exists in tx`, false, `tx log indexes: ${receipt.logs.map((l) => l.logIndex).join(",")}`); + } else { + add(`log ${idx} emitted by asset`, eqAddr(log.address, p.asset), `emitter=${log.address}`); + let ev = null; + try { ev = decodeEventLog({ abi: ABI, data: log.data, topics: log.topics }); } catch {} + const isTransfer = ev?.eventName === "Transfer"; + add(`log ${idx} is Transfer`, isTransfer, ev ? `event=${ev.eventName}` : "not decodable"); + if (isTransfer) { + add("Transfer.from == payment.from", eqAddr(ev.args.from, p.from), `log=${ev.args.from}`); + add("Transfer.to == payment.to", eqAddr(ev.args.to, p.to), `log=${ev.args.to}`); + add("Transfer.value == payment.amount", ev.args.value === amount, `log=${ev.args.value} record=${amount}`); + } + } + + const auths = receipt.logs + .filter((l) => eqAddr(l.address, p.asset)) + .map((l) => { try { return decodeEventLog({ abi: ABI, data: l.data, topics: l.topics }); } catch { return null; } }) + .filter((e) => e?.eventName === "AuthorizationUsed"); + const match = auths.find((e) => eqAddr(e.args.authorizer, p.from) + && e.args.nonce.toLowerCase() === String(p.x402.nonce).toLowerCase()); + add("AuthorizationUsed(payment.from, x402.nonce) in same tx", match, + `found ${auths.length}: ${auths.map((e) => `${e.args.authorizer}/${e.args.nonce}`).join(" ; ") || "none"}`); + } + + // Agent signature (payer). + if (!requireSig) { + add("agent signature (skipped: --no-sig)", true, "NOT checked"); + } else if (!doc.agent?.signature || !doc.agent?.key || !doc.agent?.statement) { + add("agent block present", false, "agent.key, agent.statement and agent.signature are required"); + } else { + const a = doc.agent; + add("agent.alg == eip191-secp256k1", a.alg === "eip191-secp256k1", `alg=${a.alg}`); + add("agent.statement == nirium-audit-v1:", a.statement === STATEMENT_PREFIX + doc.content_sha256, + `statement=${a.statement}`); + add("agent.key == payment.from (payer signs)", eqAddr(a.key, p.from), `key=${a.key}`); + let valid = false; + try { valid = await verifyMessage({ address: a.key, message: a.statement, signature: a.signature }); } catch {} + add("EIP-191 signature by agent.key over agent.statement", valid); + } + + return { ok: checks.every((c) => c.ok), checks }; +} diff --git a/base/verify-evm-receipt.mjs b/base/verify-evm-receipt.mjs new file mode 100755 index 0000000..0d8a202 --- /dev/null +++ b/base/verify-evm-receipt.mjs @@ -0,0 +1,38 @@ +#!/usr/bin/env node +// verify-evm-receipt.mjs - command line for the EVM receipt verifier. +// +// Usage: +// node verify-evm-receipt.mjs [--no-sig] [--rpc ] [--json] +// +// Every check lives in verify-evm-core.mjs, the same file verifyReceipt() and the browser run. +// This file only reads the receipt, prints the checks and sets the exit code: +// 0 = every check passed, 1 = at least one failed, 2 = bad input. + +import { readFileSync, realpathSync } from "node:fs"; +import { fileURLToPath } from "node:url"; +import { verifyBinding } from "./verify-evm-core.mjs"; + +export * from "./verify-evm-core.mjs"; + +async function main() { + const args = process.argv.slice(2); + const rpcIdx = args.indexOf("--rpc"); + const file = args.find((a, i) => !a.startsWith("--") && (rpcIdx < 0 || i !== rpcIdx + 1)); + if (!file) { console.error("usage: node verify-evm-receipt.mjs [--no-sig] [--rpc url] [--json]"); process.exit(2); } + const opts = { requireSig: !args.includes("--no-sig"), rpc: rpcIdx >= 0 ? args[rpcIdx + 1] : undefined }; + let doc; + try { doc = JSON.parse(readFileSync(file, "utf8")); } catch (e) { console.error(`bad binding file: ${e.message}`); process.exit(2); } + let res; + try { res = await verifyBinding(doc, opts); } catch (e) { console.error(`bad input: ${e.message}`); process.exit(2); } + if (args.includes("--json")) console.log(JSON.stringify(res, null, 2)); + else { + for (const c of res.checks) console.log(`${c.ok ? "PASS" : "FAIL"} ${c.name}${c.detail ? " [" + c.detail + "]" : ""}`); + console.log(res.ok ? "RESULT: VALID" : "RESULT: INVALID"); + } + process.exit(res.ok ? 0 : 1); +} + +// Run main() when executed directly, including through the npm bin symlink: compare real paths, +// or a symlinked call would skip main() and exit 0 without checking anything. +const invokedPath = (() => { try { return realpathSync(process.argv[1]); } catch { return undefined; } })(); +if (invokedPath && realpathSync(fileURLToPath(import.meta.url)) === invokedPath) main(); diff --git a/docs/decision-receipt-v1.md b/docs/decision-receipt-v1.md new file mode 100755 index 0000000..e77c905 --- /dev/null +++ b/docs/decision-receipt-v1.md @@ -0,0 +1,95 @@ +# nirium-decision-v1 + +A receipt for a decision the payer's pre-sign policy made about an x402 payment: ALLOWED, +DENY, WAIT, and every other refusal. It is signed by the payer's own key, so it records what the +payer's policy decided, in the payer's name. + +A payment receipt (`payment-binding-v1.md`) is bound to a transfer the chain already shows. A +decision receipt matters most when there is **no** transfer: a DENY or a WAIT signs nothing, so the +chain has no trace of it. The receipt is the only record that the payment was attempted, what it +would have paid, and why it was refused. That is the part the chain does not keep. + +## Document + +```json +{ + "version": "nirium-decision-v1", + "content_sha256": "", + "record": { + "decision": { + "outcome": "DENY", + "policyVersion": "rules-v1", + "reason": "amount 10000 above limit 5000" + }, + "intent": { + "amount": "10000", + "asset": "", + "contextHash": "", + "decimals": 6, + "from": "", + "method": "GET", + "network": "", + "nonce": "", + "payloadHash": "", + "resource": "", + "to": "" + }, + "labels": ["selftest"], + "purpose": { "note": "", "ref": "" } + }, + "agent": { + "alg": "ed25519-solana | eip191-secp256k1", + "key": "", + "signature": "", + "statement": "nirium-audit-v1:" + }, + "network": "" +} +``` + +- `record` keys are sorted recursively and serialized without whitespace (`canonical`), the same + rule as payment receipts, so `content_sha256 = sha256(canonical(record))`. +- `decision.outcome` is the policy outcome: `ALLOWED`, `SIGNED`, `DENY`, `WAIT`, `TIMEOUT`, + `ENGINE_ERROR`, `EXPIRED`, `UNBOUND`, `MALFORMED`, `STALE`, `VERSION_UNAVAILABLE`, + `SIGNER_CHANGED`, `CLOCK_INVALID`. `CONTEXT_MISMATCH` happens before there is a decoded + payment to describe, so it has no decision receipt. +- `reason` and `policyVersion` are what the engine returned, as text. Omit them when absent. +- `intent` comes from what the policy decoded from the transaction or the typed data itself, not + from what the seller said. +- The payer signs. `agent.key` must equal `record.intent.from`. + +### Hash-only mode + +To keep the content private, the document has no `record`: + +```json +{ + "version": "nirium-decision-v1", + "content_sha256": "", + "agent": { "alg": "...", "key": "", "signature": "...", "statement": "nirium-audit-v1:" }, + "network": "" +} +``` + +Anyone holding the record can later show it matches `content_sha256`; anyone else only sees that +the payer signed something at that time. + +## What a verifier checks + +1. `version`, `network` (CAIP-2, `solana:*` or `eip155:*`) and, with a record, + `record.intent.network == network`. +2. With a record: `content_sha256 == sha256(canonical(record))`, and the outcome is one listed + above. +3. `agent.statement == "nirium-audit-v1:" + content_sha256`, `agent.alg` matches the network + family, the signature is valid for `agent.key` (raw ed25519 over the UTF-8 statement on Solana; + EIP-191 address recovery on EVM), and with a record `agent.key == record.intent.from`. + +There is nothing to check on-chain: the point of a refusal is that nothing reached the chain. For +an `ALLOWED`/`SIGNED` decision, the payment receipt of the transfer that followed is the on-chain +proof. + +## What it does not prove + +That the policy was configured sensibly, that the payer's software really ran it, or that nothing +else signed with the same key. It proves that the holder of the payer's key declared this decision, +for this exact payment, and when it was anchored. diff --git a/docs/payment-binding-v1.md b/docs/payment-binding-v1.md new file mode 100755 index 0000000..13f7b1f --- /dev/null +++ b/docs/payment-binding-v1.md @@ -0,0 +1,69 @@ +# nirium-payment-binding-v1 + +A receipt that binds a signed statement to one specific on-chain transfer. It is the same document +shape Nirium Audit Trail already uses (`record` + `agent`), so existing Audit Trail verifiers +compute the same hash. + +## Document + +```json +{ + "version": "nirium-payment-binding-v1", + "content_sha256": "", + "record": { + "labels": ["selftest"], + "payment": { + "amount": "10000", + "asset": "", + "decimals": 6, + "from": "", + "locator": { "index": 2, "kind": "svm-top-level-ix", "txVersion": 0 }, + "network": "", + "to": "", + "tx": "", + "x402": { "nonce": "", "resource": "", "scheme": "exact" } + }, + "purpose": { "note": "", "ref": "" } + }, + "agent": { + "alg": "ed25519-solana | eip191-secp256k1", + "key": "", + "signature": "", + "statement": "nirium-audit-v1:" + }, + "network": "" +} +``` + +- On EVM, `locator` is `{ "index": , "kind": "evm-log" }`. `logIndex` is the log's index + within the block, as returned by `eth_getLogs` and transaction receipts. +- `canonical(record)`: keys sorted recursively, no whitespace, strings as `JSON.stringify` writes + them. Producers build `record` already in that order, so `JSON.stringify(record)` gives the same + bytes. +- Amounts are strings in atomic units (`"10000"` is 0.01 USDC). +- The payer signs. Verifiers require `agent.key == record.payment.from`. + +## What a verifier checks + +Solana (`getTransaction`, `finalized`, `maxSupportedTransactionVersion: 1`, `jsonParsed`): + +1. The transaction exists, is finalized and has no error; its version equals `locator.txVersion`. +2. The top-level instruction at `locator.index` is a Token or Token-2022 `transferChecked`. +3. Its mint, amount and decimals equal the receipt; its authority equals `from`; its destination + is the associated token account of `to` for that mint and token program. +4. There is one Memo instruction whose text equals `x402.nonce`. +5. The record hash matches `content_sha256`, and `agent.signature` is a valid ed25519 signature by + `agent.key` over `agent.statement`. + +EVM (`eth_getTransactionReceipt`): + +1. Status is success and the RPC chain id matches `network`. +2. The log at `locator.index` was emitted by `asset`, is a `Transfer`, and its from, to and value + equal the receipt. The transaction's own `to` is not used: facilitators may settle in a batch. +3. The same receipt has an `AuthorizationUsed(from, x402.nonce)` log emitted by `asset`. +4. The record hash matches `content_sha256`, and the EIP-191 signer of `agent.statement` is `from`. + +## What it does not prove + +The chain proves the transfer. The receipt adds who declared it and what it was for (`purpose`). +It does not prove that the goods or service were delivered. diff --git a/evidence/2026-12-01/selftest-base-mainnet-binding.json b/evidence/2026-12-01/selftest-base-mainnet-binding.json new file mode 100644 index 0000000..6dab09d --- /dev/null +++ b/evidence/2026-12-01/selftest-base-mainnet-binding.json @@ -0,0 +1,38 @@ +{ + "version": "nirium-payment-binding-v1", + "content_sha256": "af02049e56623146f2e81b5d63841e42261745ec0248abe0cc81a21ed23ab556", + "record": { + "labels": [ + "selftest" + ], + "payment": { + "amount": "10000", + "asset": "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913", + "decimals": 6, + "from": "0x32c645f72043F1E8Ca79E35Fc6E962F8DdB9774b", + "locator": { + "index": 13, + "kind": "evm-log" + }, + "network": "eip155:8453", + "to": "0xCEdE4f8F63d7A041b525B59e0E1AA5D0fa9a9C5B", + "tx": "0xaa086c5efae1d50afc7874bd3de68b3af70fae9c998f9a5f937f6b905b804d06", + "x402": { + "nonce": "0xdd5c919ec69d64a5ce7bd24e73e603c860341ad6a1c2cf9440e5eb3efb29f870", + "resource": "http://127.0.0.1:42817/data", + "scheme": "exact" + } + }, + "purpose": { + "note": "Nirium SDK selftest: x402Serve + createX402Fetch with policy", + "ref": "selftest-2026-12-01-base-mainnet-sdk-01" + } + }, + "agent": { + "alg": "eip191-secp256k1", + "key": "0x32c645f72043F1E8Ca79E35Fc6E962F8DdB9774b", + "signature": "0x8531b47b5c228d1d0a5a5e7b927c2169d67efbfc85120109e65d1f59343654cb1d5af431b0f457b1ad9728574c6e25600e8d4a11f69b4d3bcfb81431e8ad1de11c", + "statement": "nirium-audit-v1:af02049e56623146f2e81b5d63841e42261745ec0248abe0cc81a21ed23ab556" + }, + "network": "eip155:8453" +} \ No newline at end of file diff --git a/evidence/2026-12-01/selftest-base-sepolia-binding.json b/evidence/2026-12-01/selftest-base-sepolia-binding.json new file mode 100644 index 0000000..1f3eb9f --- /dev/null +++ b/evidence/2026-12-01/selftest-base-sepolia-binding.json @@ -0,0 +1,38 @@ +{ + "version": "nirium-payment-binding-v1", + "content_sha256": "0f84de9cf38b972fde56fd42597754ba6b66c1b64baabc8d2a4cd5799c576cf4", + "record": { + "labels": [ + "selftest" + ], + "payment": { + "amount": "10000", + "asset": "0x036CbD53842c5426634e7929541eC2318f3dCF7e", + "decimals": 6, + "from": "0xEC10B2aA06262f8e6777AAF038673568552CB142", + "locator": { + "index": 1, + "kind": "evm-log" + }, + "network": "eip155:84532", + "to": "0xC7484059c45Cf89dDc487C836A6f821Dc5882051", + "tx": "0xa89dde53b3096abf37c3307942026d0ffef47523f29519aef5e685853ae04cde", + "x402": { + "nonce": "0x62b6ba9c51c591809138be453e30961890848961ddd8c5ffa9e37b0be71d495f", + "resource": "http://127.0.0.1:42257/data", + "scheme": "exact" + } + }, + "purpose": { + "note": "Nirium SDK selftest: x402Serve + createX402Fetch with policy", + "ref": "selftest-2026-12-01-base-sepolia-sdk-01" + } + }, + "agent": { + "alg": "eip191-secp256k1", + "key": "0xEC10B2aA06262f8e6777AAF038673568552CB142", + "signature": "0x55887207cab4f9e9287148520c196ec39238410e825c137b8a09840492bfb43c3e437125962c09dca95dcf11ed6407d6e7ac7e03754f5e50271db860102737fb1b", + "statement": "nirium-audit-v1:0f84de9cf38b972fde56fd42597754ba6b66c1b64baabc8d2a4cd5799c576cf4" + }, + "network": "eip155:84532" +} \ No newline at end of file diff --git a/evidence/README.md b/evidence/README.md new file mode 100644 index 0000000..56812a5 --- /dev/null +++ b/evidence/README.md @@ -0,0 +1,17 @@ +# Evidence + +The team's own test payments on Base, each with its payer-signed receipt and an explorer link. +Every one is labeled `selftest`: they test the flow and are not usage. + +Check any receipt against the chain: + +```bash +cd base && npm ci && node verify-evm-receipt.mjs ../evidence//-binding.json +``` + +Exit code 0 means valid, 1 means a check failed, 2 means bad input. + +| Date | Network | What | Transaction | Receipt | +|---|---|---|---|---| +| 2026-12-01 | Base Sepolia | SDK selftest: x402Serve + createX402Fetch with a rules policy, 0.01 USDC, PayAI settles, payer-signed receipt | [`0xa89dde53…`](https://sepolia.basescan.org/tx/0xa89dde53b3096abf37c3307942026d0ffef47523f29519aef5e685853ae04cde) | [`2026-12-01/selftest-base-sepolia-binding.json`](2026-12-01/selftest-base-sepolia-binding.json) | +| 2026-12-01 | Base mainnet | SDK selftest: x402Serve + createX402Fetch with a rules policy, 0.01 USDC, PayAI settles, payer-signed receipt | [`0xaa086c5e…`](https://basescan.org/tx/0xaa086c5efae1d50afc7874bd3de68b3af70fae9c998f9a5f937f6b905b804d06) | [`2026-12-01/selftest-base-mainnet-binding.json`](2026-12-01/selftest-base-mainnet-binding.json) | diff --git a/fly.market.toml b/fly.market.toml new file mode 100644 index 0000000..d8d412f --- /dev/null +++ b/fly.market.toml @@ -0,0 +1,35 @@ +# Fly app for the Base x402 market. Deploy from the repository root: +# fly deploy -c fly.market.toml --remote-only +# The server holds no key: NIRIUM_EVM_PAYTO is the public address that receives each sale. +app = "nirium-market-base" +primary_region = "iad" + +[build] + dockerfile = "base/market/Dockerfile" + +[env] + PORT = "8080" + # Base Sepolia first (test tokens, the team's test payTo). Mainnet is a separate change: + # NIRIUM_NETWORK = "eip155:8453", the market-only payTo, and NIRIUM_MARKET_ALLOW_MAINNET = "1" + # (each mainnet sale is income for Nirium). + NIRIUM_NETWORK = "eip155:84532" + NIRIUM_EVM_PAYTO = "0xC7484059c45Cf89dDc487C836A6f821Dc5882051" + +[http_service] + internal_port = 8080 + force_https = true + # Stops when idle and starts on the first request: near zero cost with no traffic. + auto_stop_machines = "stop" + auto_start_machines = true + min_machines_running = 0 + + [[http_service.checks]] + grace_period = "10s" + interval = "30s" + method = "GET" + path = "/health" + timeout = "5s" + +[[vm]] + size = "shared-cpu-1x" + memory = "512mb" # geoip-lite (Tier A block) keeps its country data in memory; 256mb ran out (OOM, 27-nov-2026) diff --git a/scripts/new-testnet-keys.sh b/scripts/new-testnet-keys.sh new file mode 100755 index 0000000..2d0771e --- /dev/null +++ b/scripts/new-testnet-keys.sh @@ -0,0 +1,34 @@ +#!/usr/bin/env bash +# Creates fresh Base Sepolia keys for this project, outside the repo, readable only by you: +# a payer and a payTo in one env file (viem). +# Prints addresses only, never a secret. Refuses to overwrite existing keys. +# Mainnet keys are NOT made here: make them by hand and fund them with cents. +set -euo pipefail +umask 077 +REPO="$(cd "$(dirname "$0")/.." && pwd)" +KEYDIR="${NIRIUM_KEY_DIR:-$HOME/.nirium-keys}" +case "$KEYDIR" in "$REPO"*) echo "refusing: key dir is inside the repo ($KEYDIR)"; exit 2;; esac +mkdir -p "$KEYDIR"; chmod 700 "$KEYDIR" + +EVM_ENV="$KEYDIR/base-sepolia.env" +if [ -e "$EVM_ENV" ]; then echo "refusing: $EVM_ENV already exists (delete it yourself if you mean it)"; exit 2; fi + +[ -d "$REPO/base/demo/node_modules/viem" ] || (cd "$REPO/base/demo" && npm ci --silent --no-audit --no-fund) +(cd "$REPO/base/demo" && node --input-type=module -e " +import { generatePrivateKey, privateKeyToAccount } from \"viem/accounts\"; +import { writeFileSync } from \"node:fs\"; +const payer = generatePrivateKey(), payto = generatePrivateKey(); +const addr = (k) => privateKeyToAccount(k).address; +writeFileSync(process.argv[1], [ + \"# Base Sepolia TESTNET keys for nirium-base. Never commit, never paste.\", + \"NIRIUM_EVM_PAYER_KEY=\" + payer, + \"NIRIUM_EVM_PAYTO_KEY=\" + payto, + \"NIRIUM_EVM_PAYTO=\" + addr(payto), + \"\"].join(\"\n\"), { mode: 0o600 }); +console.log(\"base-sepolia payer \" + addr(payer) + \" <- USDC from faucet.circle.com (Base Sepolia); no ETH needed, PayAI pays the gas\"); +console.log(\"base-sepolia payTo \" + addr(payto)); +" "$EVM_ENV") + +echo +echo "keys written to $EVM_ENV (mode 600). Use them with:" +echo " set -a; . $EVM_ENV; set +a" From 2cd3500342b38eb3798bf92e0550fd46d964380d Mon Sep 17 00:00:00 2001 From: Giovanny Amador <219895655+Eras256@users.noreply.github.com> Date: Tue, 1 Dec 2026 15:32:57 -0600 Subject: [PATCH 2/2] test: run the verifier and SDK tests on this chain's own selftest receipts The tests were ported with the Avalanche code and still read Fuji evidence (evidence/2026-11-26), which this repo does not have, so CI failed. They now use the 1 Dec 2026 Sepolia selftest receipt and its recorded RPC answers. CodeQL is skipped while the repo is private (code scanning needs Advanced Security). npm test 40/40, run-tests.sh 10/10. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/codeql.yml | 2 + .../base-sepolia-sdk-selftest-rpc.json | 63 +++++++++++++++++++ base/sdk/test/sdk.test.mjs | 6 +- base/test/verify-core.test.mjs | 14 ++--- 4 files changed, 75 insertions(+), 10 deletions(-) create mode 100644 base/fixtures/base-sepolia-sdk-selftest-rpc.json diff --git a/.github/workflows/codeql.yml b/.github/workflows/codeql.yml index c055c8c..c12d5ab 100755 --- a/.github/workflows/codeql.yml +++ b/.github/workflows/codeql.yml @@ -13,6 +13,8 @@ permissions: jobs: analyze: + # Code scanning needs Advanced Security on a private repo; runs once the repo is public. + if: ${{ !github.event.repository.private }} runs-on: ubuntu-latest timeout-minutes: 20 permissions: diff --git a/base/fixtures/base-sepolia-sdk-selftest-rpc.json b/base/fixtures/base-sepolia-sdk-selftest-rpc.json new file mode 100644 index 0000000..51d0a78 --- /dev/null +++ b/base/fixtures/base-sepolia-sdk-selftest-rpc.json @@ -0,0 +1,63 @@ +{ + "note": "Recorded public Base Sepolia RPC answers for the team's 1 Dec 2026 selftest (not usage).", + "chainId": "0x14a34", + "txReceipt": { + "type": "0x2", + "status": "0x1", + "cumulativeGasUsed": "0x2dde3", + "logs": [ + { + "address": "0x036cbd53842c5426634e7929541ec2318f3dcf7e", + "topics": [ + "0x98de503528ee59b575ef0c0a2576a82497bfc029a5685b209e9ec333479b10a5", + "0x000000000000000000000000ec10b2aa06262f8e6777aaf038673568552cb142", + "0x62b6ba9c51c591809138be453e30961890848961ddd8c5ffa9e37b0be71d495f" + ], + "data": "0x", + "blockHash": "0xdf9d0851772739aac6a0f1dad244cd42428886d77acb9889ce0503a1f001281d", + "blockNumber": "0x3f203ff", + "blockTimestamp": "0x6b0f3b59", + "transactionHash": "0xa89dde53b3096abf37c3307942026d0ffef47523f29519aef5e685853ae04cde", + "transactionIndex": "0x2", + "logIndex": "0x0", + "removed": false, + "blockTimestampMs": "0x1a2337fd538" + }, + { + "address": "0x036cbd53842c5426634e7929541ec2318f3dcf7e", + "topics": [ + "0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef", + "0x000000000000000000000000ec10b2aa06262f8e6777aaf038673568552cb142", + "0x000000000000000000000000c7484059c45cf89ddc487c836a6f821dc5882051" + ], + "data": "0x0000000000000000000000000000000000000000000000000000000000002710", + "blockHash": "0xdf9d0851772739aac6a0f1dad244cd42428886d77acb9889ce0503a1f001281d", + "blockNumber": "0x3f203ff", + "blockTimestamp": "0x6b0f3b59", + "transactionHash": "0xa89dde53b3096abf37c3307942026d0ffef47523f29519aef5e685853ae04cde", + "transactionIndex": "0x2", + "logIndex": "0x1", + "removed": false, + "blockTimestampMs": "0x1a2337fd538" + } + ], + "logsBloom": "0x00000000040000000000000000000000004000000000000000000000000000020000000000000000100000000000000000000000000000000000000200000000800000000000000000000008000000000000000000000000000000000000000c00020000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000800000004200000000000000000000000000000000000000000100000004000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000", + "transactionHash": "0xa89dde53b3096abf37c3307942026d0ffef47523f29519aef5e685853ae04cde", + "transactionIndex": "0x2", + "blockHash": "0xdf9d0851772739aac6a0f1dad244cd42428886d77acb9889ce0503a1f001281d", + "blockNumber": "0x3f203ff", + "gasUsed": "0x1ad8c", + "effectiveGasPrice": "0x6acfc0", + "blobGasUsed": "0x1f93c", + "from": "0xc6699d2aada6c36dfea5c248dd70f9cb0235cb63", + "to": "0xca11bde05977b3631167028862be2a173976ca11", + "contractAddress": null, + "l1GasPrice": "0x8", + "l1GasUsed": "0x1225", + "l1Fee": "0x9ba8e2d591c", + "l1BaseFeeScalar": "0x44d", + "l1BlobBaseFee": "0xcfffc1611", + "l1BlobBaseFeeScalar": "0xa118b", + "daFootprintGasScalar": "0x1be" + } +} \ No newline at end of file diff --git a/base/sdk/test/sdk.test.mjs b/base/sdk/test/sdk.test.mjs index 77d3519..f7869d4 100644 --- a/base/sdk/test/sdk.test.mjs +++ b/base/sdk/test/sdk.test.mjs @@ -1,6 +1,6 @@ // Tests for nirium-base. The pay/serve loop runs offline against a local fake facilitator // that checks the payer's EIP-3009 signature before "settling". The receipt test reads one real -// Fuji transaction from the team's own evidence over the public RPC. +// Base Sepolia transaction from the team's own evidence over the public RPC. import { test } from "node:test"; import assert from "node:assert/strict"; @@ -137,8 +137,8 @@ test("a facilitator that is down answers 503 with a hint on paid routes only, an } finally { s.close(); } }); -test("bindReceipt rebuilds the team's real Fuji receipt from the chain, and refuses a signer that is not the payer", async () => { - const evidence = JSON.parse(readFileSync(new URL("../../../evidence/2026-11-26/fuji-a2-binding.json", import.meta.url), "utf8")); +test("bindReceipt rebuilds the team's real Base Sepolia receipt from the chain, and refuses a signer that is not the payer", async () => { + const evidence = JSON.parse(readFileSync(new URL("../../../evidence/2026-12-01/selftest-base-sepolia-binding.json", import.meta.url), "utf8")); const p = evidence.record.payment; const doc = await bindReceipt({ tx: p.tx, network: p.network, ref: evidence.record.purpose.ref, note: evidence.record.purpose.note, resource: p.x402.resource, labels: evidence.record.labels }); assert.deepEqual(doc.record, evidence.record); diff --git a/base/test/verify-core.test.mjs b/base/test/verify-core.test.mjs index 4ecb759..68e135a 100644 --- a/base/test/verify-core.test.mjs +++ b/base/test/verify-core.test.mjs @@ -1,6 +1,6 @@ // Unit tests for verify-evm-core.mjs, the one verifier the CLI, verifyReceipt() and the browser -// share. No network: the full check runs against recorded public Fuji RPC answers for one of the -// team's self-test receipts (fixtures/fuji-sdk-selftest-rpc.json). +// share. No network: the full check runs against recorded public Base Sepolia RPC answers for one of the +// team's self-test receipts (fixtures/base-sepolia-sdk-selftest-rpc.json). // // node:crypto appears here only as the reference the code used before it moved to viem's sha256, // so each hash test checks that the two agree. @@ -16,11 +16,11 @@ import { canonicalize, contentSha256, sha256Hex, verifyBinding, STATEMENT_PREFIX import { computeContextHash } from "../policy/evm-policy.mjs"; const read = (p) => JSON.parse(readFileSync(new URL(p, import.meta.url), "utf8")); -const receipts = ["2026-11-26", "2026-11-27"].flatMap((d) => +const receipts = ["2026-12-01"].flatMap((d) => readdirSync(new URL(`../../evidence/${d}/`, import.meta.url)).filter((f) => f.endsWith("-binding.json")) .map((f) => ({ name: `${d}/${f}`, doc: read(`../../evidence/${d}/${f}`) }))); -const recorded = read("../fixtures/fuji-sdk-selftest-rpc.json"); -const selftest = read("../../evidence/2026-11-26/fuji-sdk-binding.json"); +const recorded = read("../fixtures/base-sepolia-sdk-selftest-rpc.json"); +const selftest = read("../../evidence/2026-12-01/selftest-base-sepolia-binding.json"); const nodeSha = (s) => createHash("sha256").update(s, "utf8").digest("hex"); const clone = (d) => JSON.parse(JSON.stringify(d)); @@ -47,7 +47,7 @@ async function withRecordedRpc(fn) { test("record hash matches every evidence receipt and fixture, and matches node:crypto", () => { const fixtures = readdirSync(new URL("../fixtures/", import.meta.url)).filter((f) => f.startsWith("june-")) .map((f) => ({ name: f, doc: read(`../fixtures/${f}`) })); - assert.ok(receipts.length >= 7, `expected the evidence receipts, found ${receipts.length}`); + assert.ok(receipts.length >= 2, `expected the evidence receipts, found ${receipts.length}`); for (const { name, doc } of receipts) assert.equal(contentSha256(doc.record), doc.content_sha256, name); for (const { name, doc } of [...receipts, ...fixtures]) { assert.equal(contentSha256(doc.record), nodeSha(canonicalize(doc.record)), name); @@ -75,7 +75,7 @@ test("payer signatures on every evidence receipt verify", async () => { } }); -test("full check offline: the team's Fuji self-test receipt is VALID", async () => { +test("full check offline: the team's Base Sepolia self-test receipt is VALID", async () => { const res = await withRecordedRpc(() => verifyBinding(clone(selftest))); assert.deepEqual(failing(res), []); assert.equal(res.ok, true);