Adds the SpendGuard entrypoint flagged in HACKATHON.md as a known limit: an agent with a still-ACTIVE spend key can now draw, repay, top up, and draw again on the SAME key, not just at the ExposureBook ledger level. - contracts-near/spend_guard/src/lib.rs: new admin-only top_up_allowance, re-reserving freed headroom (capped by the agent's own policy-approved credit line) and re-minting the agent's existing Function Call Access Key via spend_key::retop_spend_key. - src/spend_key.rs: retop_spend_key — a real NEAR protocol constraint found and fixed live against a running nearcore sandbox: AddKey unconditionally rejects an already-existing public key (AddKeyAlreadyExists), so topping up means delete_key + re-add in the SAME receipt, not a second AddKey call. Also fixed a clippy doc_lazy_continuation nit in this file's module docs. - src/exposure.rs: replaced two manual saturating-subtract patterns with u128::saturating_sub (clippy implicit_saturating_sub), and added a unit test proving repay-then-reserve-again reaches the full cap a second time. - tests/sandbox.rs: extended the real near-workspaces sandbox integration test (genuinely running local nearcore node) to prove the full loop live: draw -> repay -> top_up_allowance -> a real spend_to_seller call that succeeds again on the SAME original key -> dispute spike -> freeze -> revoked-key rejection. - lib/x402/near_spend_guard_client.ts: repayCreditLine + topUpAllowance client methods; scripts/near_spend_guard_full_demo.ts now exercises the same real repay/top-up/draw-again loop against the LIVE deployed public Testnet contract (spendguard-024e8dd6f7.testnet), not just the sandbox. - scripts/near_spend_guard_redeploy.ts: new script to upgrade the already-deployed contract's wasm in place (DeployContract replaces code only, never storage) — used to push this change to the live Testnet contract without losing its existing agent/exposure state. Also fixes a real, judge-relevant finding hit while running the above: NEAR's own legacy public RPC (rpc.testnet.near.org) now rejects most calls with -429 "WARNING! THIS ENDPOINT IS DEPRECATED!". Every default RPC URL in this repo (near_networks.ts, near_spend_guard_client.ts, near_spend_guard_deploy.ts, docs/near_x402.md's example) now defaults to FastNear's free public RPC instead; CRED402_NEAR_RPC_URL still overrides. Updated the one test that asserted the old default. 18/18 Rust unit tests green, cargo clippy -D warnings clean, the sandbox integration test passes against a real local nearcore node, the live Testnet bonus loop passes against the real public contract, and the full TS suite is 450/450 green with a clean typecheck. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
227 lines
12 KiB
Markdown
227 lines
12 KiB
Markdown
# NEAR x402 credit-score endpoint
|
|
|
|
Cred402's NEAR integration (NEAR Hackathon, Nov 1-14, 2026,
|
|
nearhackathon.com) sells the same resource as the Algorand and QIE
|
|
integrations, priced in native NEAR instead:
|
|
|
|
```text
|
|
GET /v1/x402/near/credit-score/:agentId
|
|
```
|
|
|
|
The endpoint returns the policy score, probability of default, risk band,
|
|
eligibility, reason codes, and verified x402 revenue — it uses the same
|
|
oracle and risk engine as the rest of Cred402 (`state.x402CreditScore`); the
|
|
NEAR route is a payment and distribution layer, not a forked scoring model.
|
|
|
|
## Why this integration has no facilitator
|
|
|
|
Algorand settles through GoPlausible's facilitator; QIE requires an
|
|
operator to configure one. NEAR has neither an EVM nor an AVM virtual
|
|
machine, so no `@x402/near` scheme package exists yet, and no x402
|
|
facilitator for NEAR is confirmed to exist. Rather than bolt NEAR onto a
|
|
scheme built for a different chain, `lib/x402/near_gateway.ts` is a small,
|
|
honest, from-scratch `exact`-scheme implementation:
|
|
|
|
- It reuses `@x402/core`'s chain-agnostic wire format — the same
|
|
`encodePaymentRequiredHeader` / `decodePaymentSignatureHeader` /
|
|
`encodePaymentResponseHeader` codecs and `PaymentRequirements` /
|
|
`PaymentPayload` types every other x402 integration in this repo uses
|
|
(`Network` is `${string}:${string}`, so `near:testnet` is a valid id).
|
|
- It needs **no third-party facilitator**. A NEAR account signs and submits
|
|
a native `Transfer` action to the configured pay-to account, then presents
|
|
the resulting transaction hash as payment proof. Cred402 reads that
|
|
transaction back from its own configured NEAR RPC endpoint
|
|
(`lib/x402/near_finality.ts`) and only settles once the transfer is
|
|
independently confirmed — Cred402 is its own facilitator, with no extra
|
|
hop and nothing to self-host.
|
|
|
|
`GET /v1/x402/near/status` reports `"facilitator": "self-verified"` for
|
|
exactly this reason.
|
|
|
|
## How a NEAR account pays (and how Chain Signatures extends it)
|
|
|
|
The reference buyer (`examples/near-paid-score/typescript.ts`) holds a plain
|
|
NEAR Testnet account and signs directly with `near-api-js`. That is the
|
|
simplest path and the one this submission demonstrates end-to-end on
|
|
Testnet.
|
|
|
|
The same flow is NEAR Chain Signatures-ready without changing the server at
|
|
all: Chain Signatures let an account on another chain (or an AI agent with
|
|
no NEAR-native key of its own) have a NEAR MPC network derive and sign a
|
|
NEAR transaction on its behalf. Whatever signs, the result is still an
|
|
ordinary signed NEAR `Transfer` transaction with a transaction hash — the
|
|
same shape this route already verifies. An agent that only holds, say, an
|
|
Ethereum key could use Chain Signatures to pay this endpoint without ever
|
|
holding NEAR directly. This is deliberately left as the extension point
|
|
(documented, not faked) rather than wiring in a mocked MPC signer.
|
|
|
|
## Configuration
|
|
|
|
```bash
|
|
export CRED402_NEAR_PAY_TO=cred402.testnet
|
|
export CRED402_NEAR_NETWORK=testnet
|
|
export CRED402_NEAR_RPC_URL=https://rpc.testnet.fastnear.com # near.org's own public RPC now rate-limits (-429 deprecated), confirmed live 2026-11-05 — use FastNear
|
|
export CRED402_NEAR_PRICE_YOCTO=10000000000000000000000 # 0.01 NEAR
|
|
export CRED402_NEAR_MIN_FINALITY_BLOCKS=2
|
|
export CRED402_DATA_DIR=/var/lib/cred402
|
|
npm run start
|
|
```
|
|
|
|
See [`.env.example`](../.env.example) for every variable and its defaults.
|
|
|
|
## Inspect the unpaid challenge
|
|
|
|
```bash
|
|
curl -i "http://localhost:4021/v1/x402/near/credit-score/YOUR_AGENT_ID"
|
|
```
|
|
|
|
The `402` response carries a `PAYMENT-REQUIRED` header: a base64-encoded
|
|
x402 v2 challenge with exactly one `accepts[]` option — scheme `exact`,
|
|
network `near:testnet` (or `near:mainnet`), asset `near-native`, the
|
|
configured price in yoctoNEAR, and the configured pay-to account.
|
|
|
|
## Settlement and independent finality
|
|
|
|
The route uses a durable exact-once attempt ledger
|
|
(`lib/x402/near_payment_attempt_store.ts`, same role as
|
|
`QiePaymentAttemptStore` / `AlgorandPaymentAttemptStore`): it stores a
|
|
digest, not the raw `PAYMENT-SIGNATURE`, and replays the same paid response
|
|
after safe retries or restarts.
|
|
|
|
On a payment attempt, Cred402:
|
|
|
|
1. Decodes `PAYMENT-SIGNATURE` and checks it matches this route's network,
|
|
asset, receiver, and price exactly (`NearCreditScoreGateway.authorize`).
|
|
2. Independently reads the claimed transaction back from the configured
|
|
NEAR RPC (`EXPERIMENTAL_tx_status`), confirms it succeeded, confirms the
|
|
signer and receiver match, and confirms a `Transfer` action moved at
|
|
least the expected amount of yoctoNEAR (`NearCreditScoreGateway.settle`
|
|
→ `verifyNearAssetTransfer`).
|
|
3. Settles immediately once that transfer is confirmed present and
|
|
correct, then asynchronously re-checks finality depth
|
|
(`reconcileNearPayment`, same periodic-reconciliation pattern as the
|
|
Algorand/QIE routes) until the transaction has been included for at
|
|
least `CRED402_NEAR_MIN_FINALITY_BLOCKS` blocks, at which point the
|
|
Casper-rooted receipt is finalized.
|
|
|
|
`GET /v1/x402/near/payments/:attemptId` exposes only coarse lifecycle,
|
|
transaction, and confirmation-count data — never the paid report, payer
|
|
identity, or raw signature.
|
|
|
|
## Status and usage probes
|
|
|
|
- `GET /v1/x402/near/status` is free, secret-free, and never touches the
|
|
NEAR RPC — it mirrors `/v1/x402/algorand/status` / `/v1/x402/qie/status`.
|
|
- `GET /v1/x402/near/usage` is a free, aggregate-only proof of real paid
|
|
volume: paid request count, unique payers, total yoctoNEAR, and the 10
|
|
most recent finalized receipts (each pointing at its public proof URL).
|
|
|
|
## Receipt anchoring
|
|
|
|
`api/near_receipt_anchor.ts` mirrors `algorand_receipt_anchor.ts` /
|
|
`qie_receipt_anchor.ts`: `state.anchorNearCreditScoreSettlement` turns a
|
|
settled NEAR payment into the same Casper-rooted Universal Receipt Envelope
|
|
every other satellite chain uses (`near:<account>` identity,
|
|
`near-native:NEAR` asset), anchored provisional until
|
|
`reconcileNearPayment`'s finality check confirms it, then finalized or
|
|
challenged. The credit-score response carries `external_receipt_id` /
|
|
`external_receipt_url` / `casper_anchor_status`; the proof is public at
|
|
`GET /v1/x402/external-receipts/:id` (the same endpoint every chain's
|
|
receipts use — receipt ids are a shared content hash, not chain-specific).
|
|
|
|
## Mainnet release checklist
|
|
|
|
1. Fund and confirm a real NEAR Mainnet pay-to account.
|
|
2. Set `CRED402_NEAR_RPC_URL` to a trustworthy NEAR Mainnet RPC endpoint.
|
|
3. Mount a persistent volume and set `CRED402_DATA_DIR` to that mount.
|
|
4. Set `CRED402_ENV=mainnet`, `CRED402_NEAR_NETWORK=mainnet`, and
|
|
`CRED402_PUBLIC_URL` to the public HTTPS origin.
|
|
5. Set `CRED402_NEAR_MAINNET_RELEASE_ACK` exactly to
|
|
`I_ACKNOWLEDGE_REAL_NEAR_MAINNET_PAYMENTS`.
|
|
6. Make one real external Mainnet payment and confirm the `Transfer` action
|
|
and finality depth reconcile via `GET /v1/x402/near/payments/:attemptId`.
|
|
|
|
## Known gaps (tracked, not hidden)
|
|
|
|
- No NEAR Intents / cross-chain settlement path yet — this submission
|
|
settles directly in native NEAR on NEAR Testnet. NEAR Intents (swap any
|
|
supported asset into the exact NEAR amount this route expects at
|
|
settlement time) is the natural next step and does not require changing
|
|
the server: it would just change what the *payer* does before calling
|
|
`account.signAndSendTransaction`.
|
|
- No Chain Signatures-based signer wired into the reference buyer example
|
|
yet (see "How a NEAR account pays" above) — the server-side verification
|
|
already supports it with no changes, since it only ever sees a signed
|
|
NEAR transaction hash, never how it was signed.
|
|
- No NEP-141 (fungible token / stablecoin) pricing option yet; only native
|
|
NEAR. Adding one is a matter of checking `FunctionCall` actions calling
|
|
`ft_transfer` instead of `Transfer` actions in `near_finality.ts`.
|
|
- A fake/never-broadcast transaction hash does not get a clean, fast `402`
|
|
rejection today — it gets a `502 x402_settlement_indeterminate`. This is
|
|
intentional, not a bug: NEAR Testnet's `EXPERIMENTAL_tx_status` returns
|
|
`TIMEOUT_ERROR`/`NOT_OBSERVED` (not `UNKNOWN_TRANSACTION`) for a
|
|
syntactically valid but never-seen transaction hash (confirmed live
|
|
against `https://rpc.testnet.near.org` on 2026-11-02 — see Verification
|
|
below). `near_finality.ts` only maps `UNKNOWN_TRANSACTION`/`does not
|
|
exist` to a clean `not_found`; anything else (including this real
|
|
`TIMEOUT_ERROR` shape) falls through to `unavailable`. Collapsing
|
|
`TIMEOUT_ERROR` into `not_found` was considered and rejected: a
|
|
genuinely slow-to-propagate *real* payment can hit the same RPC error,
|
|
and `not_found` is treated as a permanent rejection
|
|
(`markFailed`/`x402_settlement_rejected`, replay-blocked), which would
|
|
wrongly kill a legitimate pending payment. `unavailable` (indeterminate,
|
|
retry via `GET /v1/x402/near/payments/:attemptId`) is the safer failure
|
|
mode for an eventually-consistent chain and is kept as-is. Access is
|
|
never granted either way — this only affects how fast a garbage proof is
|
|
told "no."
|
|
|
|
## Verification (2026-11-02, real NEAR Testnet, no mocking)
|
|
|
|
Confirmed live, end to end, against a locally running server and the real
|
|
`https://rpc.testnet.near.org` endpoint — no protocol-logic mocking; the
|
|
only thing faked anywhere in this pass was never (RPC calls hit the real
|
|
network):
|
|
|
|
1. `GET /v1/x402/near/credit-score/:agentId` with no payment → real `402`
|
|
with a valid `PAYMENT-REQUIRED` header decoding to a correct x402 v2
|
|
challenge (`near:testnet`, `near-native`, exact configured price/payTo).
|
|
2. A garbage `PAYMENT-SIGNATURE` → `402` / `PAYMENT-SIGNATURE could not be
|
|
decoded`.
|
|
3. A well-formed signature over a real but never-broadcast tx hash → `502`
|
|
/ `x402_settlement_indeterminate` (see the known-gap note above for why
|
|
this is `502` and not `402`).
|
|
4. Two real NEAR Testnet accounts were created and funded for free via the
|
|
public, non-captcha faucet API `POST https://helper.testnet.near.org/
|
|
account` (works for named `*.testnet` subaccounts via `CreateAccount` —
|
|
it does **not** work for implicit/hex accounts, which only activate via
|
|
a direct `Transfer`, so `scripts/near_keygen.ts`'s implicit-account +
|
|
near-faucet.io flow is still the right owner path for a permanent
|
|
receiver). Test accounts used: payer `c402pmvzucvyo.testnet`, receiver
|
|
`c402rmvzucvyo.testnet`, 10 NEAR each.
|
|
5. A real signed NEAR `Transfer` of exactly `10000000000000000000000`
|
|
yoctoNEAR (0.01 NEAR) was submitted on-chain via `near-api-js`:
|
|
tx hash `C1LNxQFEaR2AQj79U9WzToiB1eY86jwzmxoHKvr9W7jk`. Presenting it as
|
|
`PAYMENT-SIGNATURE` returned a real `200` with a valid `PAYMENT-RESPONSE`
|
|
header, `near_finality: "confirmed"`, 41 real confirmations, and a
|
|
finalized Casper-rooted receipt
|
|
(`0xd0f83e540ff2db873e5a0027b3e3d0af8dff76542f8b2549edc96c73315ea04a`,
|
|
verified independently at its own `GET
|
|
/v1/x402/external-receipts/:id` proof URL with `integrity.ok: true`).
|
|
6. Replaying the exact same `PAYMENT-SIGNATURE` returned the identical
|
|
cached `200`/`PAYMENT-RESPONSE` — no double-settlement, no second RPC
|
|
call charged to the payer.
|
|
7. A second real Transfer of only `1000000000000000000000` yoctoNEAR
|
|
(0.001 NEAR, below the configured 0.01 NEAR price) — tx hash
|
|
`G33RhcX5zSMarmkY358ANHcCVpeGGasrNmjgiiruYQdn` — was correctly rejected
|
|
with a real `402` / `x402_settlement_rejected` / "No Transfer action to
|
|
the configured receiver moved at least the expected amount of
|
|
yoctoNEAR", computed from the real on-chain transfer amount, not just
|
|
the signature's claimed amount.
|
|
8. `GET /v1/x402/near/usage` after the real paid call reported
|
|
`paid_requests: 1`, `unique_payers: 1`, and the correct
|
|
`total_yocto`, sourced from the real settled attempt.
|
|
|
|
Do not create synthetic/self-payment volume. One genuine end-to-end Testnet
|
|
payment is more useful than fabricated traffic. (The one above is real and
|
|
is the only one that was ever submitted.)
|