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>
12 KiB
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:
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 sameencodePaymentRequiredHeader/decodePaymentSignatureHeader/encodePaymentResponseHeadercodecs andPaymentRequirements/PaymentPayloadtypes every other x402 integration in this repo uses (Networkis${string}:${string}, sonear:testnetis a valid id). - It needs no third-party facilitator. A NEAR account signs and submits
a native
Transferaction 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
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 for every variable and its defaults.
Inspect the unpaid challenge
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:
- Decodes
PAYMENT-SIGNATUREand checks it matches this route's network, asset, receiver, and price exactly (NearCreditScoreGateway.authorize). - 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 aTransferaction moved at least the expected amount of yoctoNEAR (NearCreditScoreGateway.settle→verifyNearAssetTransfer). - 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 leastCRED402_NEAR_MIN_FINALITY_BLOCKSblocks, 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/statusis free, secret-free, and never touches the NEAR RPC — it mirrors/v1/x402/algorand/status//v1/x402/qie/status.GET /v1/x402/near/usageis 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
- Fund and confirm a real NEAR Mainnet pay-to account.
- Set
CRED402_NEAR_RPC_URLto a trustworthy NEAR Mainnet RPC endpoint. - Mount a persistent volume and set
CRED402_DATA_DIRto that mount. - Set
CRED402_ENV=mainnet,CRED402_NEAR_NETWORK=mainnet, andCRED402_PUBLIC_URLto the public HTTPS origin. - Set
CRED402_NEAR_MAINNET_RELEASE_ACKexactly toI_ACKNOWLEDGE_REAL_NEAR_MAINNET_PAYMENTS. - Make one real external Mainnet payment and confirm the
Transferaction and finality depth reconcile viaGET /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
FunctionCallactions callingft_transferinstead ofTransferactions innear_finality.ts. - A fake/never-broadcast transaction hash does not get a clean, fast
402rejection today — it gets a502 x402_settlement_indeterminate. This is intentional, not a bug: NEAR Testnet'sEXPERIMENTAL_tx_statusreturnsTIMEOUT_ERROR/NOT_OBSERVED(notUNKNOWN_TRANSACTION) for a syntactically valid but never-seen transaction hash (confirmed live againsthttps://rpc.testnet.near.orgon 2026-11-02 — see Verification below).near_finality.tsonly mapsUNKNOWN_TRANSACTION/does not existto a cleannot_found; anything else (including this realTIMEOUT_ERRORshape) falls through tounavailable. CollapsingTIMEOUT_ERRORintonot_foundwas considered and rejected: a genuinely slow-to-propagate real payment can hit the same RPC error, andnot_foundis treated as a permanent rejection (markFailed/x402_settlement_rejected, replay-blocked), which would wrongly kill a legitimate pending payment.unavailable(indeterminate, retry viaGET /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):
GET /v1/x402/near/credit-score/:agentIdwith no payment → real402with a validPAYMENT-REQUIREDheader decoding to a correct x402 v2 challenge (near:testnet,near-native, exact configured price/payTo).- A garbage
PAYMENT-SIGNATURE→402/PAYMENT-SIGNATURE could not be decoded. - 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 is502and not402). - 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*.testnetsubaccounts viaCreateAccount— it does not work for implicit/hex accounts, which only activate via a directTransfer, soscripts/near_keygen.ts's implicit-account + near-faucet.io flow is still the right owner path for a permanent receiver). Test accounts used: payerc402pmvzucvyo.testnet, receiverc402rmvzucvyo.testnet, 10 NEAR each. - A real signed NEAR
Transferof exactly10000000000000000000000yoctoNEAR (0.01 NEAR) was submitted on-chain vianear-api-js: tx hashC1LNxQFEaR2AQj79U9WzToiB1eY86jwzmxoHKvr9W7jk. Presenting it asPAYMENT-SIGNATUREreturned a real200with a validPAYMENT-RESPONSEheader,near_finality: "confirmed", 41 real confirmations, and a finalized Casper-rooted receipt (0xd0f83e540ff2db873e5a0027b3e3d0af8dff76542f8b2549edc96c73315ea04a, verified independently at its ownGET /v1/x402/external-receipts/:idproof URL withintegrity.ok: true). - Replaying the exact same
PAYMENT-SIGNATUREreturned the identical cached200/PAYMENT-RESPONSE— no double-settlement, no second RPC call charged to the payer. - A second real Transfer of only
1000000000000000000000yoctoNEAR (0.001 NEAR, below the configured 0.01 NEAR price) — tx hashG33RhcX5zSMarmkY358ANHcCVpeGGasrNmjgiiruYQdn— was correctly rejected with a real402/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. GET /v1/x402/near/usageafter the real paid call reportedpaid_requests: 1,unique_payers: 1, and the correcttotal_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.)