42 Commits

Author SHA1 Message Date
1fa477b0df fix(near-x402): close transaction-hash payment replay across resources
Adversarial testing found a real, confirmed critical bug: the NEAR x402
self-verified facilitator only deduped payment proofs by sha256 of the
client-supplied PAYMENT-SIGNATURE header bytes, not by the real on-chain
transaction they decode to. Since a NEAR transfer is public ledger data,
anyone who observes ONE valid (signerId, transaction) pair for a payment
to the configured payTo account could re-encode it inside a byte-different
header (reordered JSON keys / an added ignored field) to mint a brand-new
paymentProofHash that the existing replay() barrier had never seen, and
ride that single real payment to an unlimited number of free paid
credit-score requests for unrelated agent_ids. Reproduced live against
the real store/gateway/finality code with a mocked RPC returning one
confirmed transaction: 3 distinct free settlements from 1 payment before
the fix, correctly reduced to 1 settlement + 2 rejections after it.

Fixes it with a second, independent, durably-atomic claim index keyed on
the transaction hash itself (NearPaymentAttemptStore.claimTransaction,
first-claim-wins via an exclusive `wx` file create, same primitive the
existing paymentProofHash claim uses), checked right after authorize()
and before the costly settle() RPC call. A legitimate retry of the SAME
resource with a re-encoded header still gets served the cached settled
response; a different resource request reusing someone else's already-
consumed transaction is rejected with 409.

Algorand/QIE x402 paths were checked for the same pattern and are not
affected: both settle through a real third-party x402 facilitator
(@x402/avm, @x402/evm) against a single-use signed-but-unbroadcast
payload, not a self-verified reference to an already-public transaction
— this exact replay primitive is unique to NEAR's hand-rolled facilitator
(no @x402/near package exists).

14/14 existing NEAR x402 tests still green, typecheck clean.
2026-11-07 01:31:31 +03:00
f40b54c983 feat(near-spend-guard): close the revolving-credit demo gap with top_up_allowance
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>
2026-11-05 19:33:05 +03:00
e99e8fe16a feat(near-spend-guard): real Testnet deploy + TS client + buyer/watchdog agents (Day 4-6, 11)
Deployed SpendGuard to NEAR Testnet for real via near-api-js, driven
programmatically (cargo-near's create-dev-account/sign-with-keychain are
interactive-only, confirmed in the plan's own rehearsal):
contract account spendguard-024e8dd6f7.testnet, deploy + init transactions
both SuccessValue, independently re-verified via a raw RPC call to
rpc.testnet.near.org.

- scripts/near_spend_guard_deploy.ts: generates a keypair, creates the
  account via the public testnet faucet, deploys the built wasm, calls
  new({admin}).
- lib/x402/near_spend_guard_client.ts: typed near-api-js client
  (SpendGuardClient) for request_spend_authorization / spend_to_seller /
  report_dispute_spike / view methods. Does not touch near_gateway.ts /
  near_rpc.ts / near_finality.ts.
- agents/near_spend_controlled_buyer_agent.ts: buyer_agent.ts-pattern agent
  — gets authorized, spends repeatedly through its scoped key.
- agents/near_watchdog_agent.ts: watchdog_agent.ts-pattern agent — triggers
  the dispute-spike circuit breaker.
- scripts/near_spend_guard_full_demo.ts (npm run demo:near-spend-guard):
  one command building the contract, running the full Rust test pass, and
  then a live Testnet bonus run — 25/25 real on-chain spend_to_seller calls
  settled against the real deployed contract, then a second real agent was
  frozen and its key revoked, confirmed by a genuine rejected transaction
  ("Access key ... does not exist").

Real protocol finding baked into the client/agent design: Function Call
Access Keys can never attach a deposit (InvalidAccessKeyError::
DepositWithFunctionCall, hit live against both the local sandbox and real
Testnet) — spend_to_seller takes `amount` as a plain argument instead, with
ExposureBook enforcing the yoctoNEAR cap and the FC key's allowance
enforcing a real, protocol-level prepaid-gas call budget.
2026-11-03 05:03:30 +03:00
086381d507 feat(gateway): make rate limiting org-scoped and plan-tiered
Rate limiting was per-API-key, so an org's `plan` field was decorative — a
free-plan org that minted 5 teammate keys got 5x the effective request
budget of a single-key free org. Org-scoped keys now share ONE rate-limit
bucket per org (`org:<id>`), sized by plan (free=120, pro=1000,
enterprise=10000 per window); orgless credentials (platform admin key,
anonymous dev identities) keep the prior per-identity behavior unchanged.

Adds GET /v1/orgs/usage (bucket status + total request count across an
org's keys) and a shared-bucket meter in the Orgs self-service console
panel.

Verified against a running dev server: 130 concurrent requests on a
free-plan org's owner key yielded exactly 120 successes + 10 real 429s,
and the org's teammate key immediately inherited the same depleted
remaining count (proving the bucket is shared, not per-key). A parallel
enterprise-plan org was unaffected. tsc + frontend build clean, 450/450
existing tests unchanged.
2026-10-24 00:40:11 +03:00
f1c6d5f26d feat(gateway): add multi-tenant organizations with self-service API keys
Backlog item 13: API keys had no tenant boundary — any valid admin key (or,
in dev, no key at all) could see or mutate every key, webhook, and resource
in the process, which isn't multi-tenant for real paying integrators.

Adds a real org layer: the platform operator onboards a new org once
(POST /v1/orgs, admin-scoped) and gets its first owner key back; from then
on the org is fully self-service through its OWN key — GET /v1/orgs/me,
POST /v1/orgs/keys (mint a sibling key for a teammate, capped to a subset of
the caller's own scopes, no self-escalation), DELETE /v1/orgs/keys/:id
(revoke, but only inside the caller's own org_id — a different org's valid
key gets a 404, not the target's real state). The platform admin key is
never touched again after the initial onboarding call.

Also fixes a related gap this surfaced: lib/gateway/index.ts's authenticate()
previously ignored any presented API key entirely when
CRED402_AUTH_REQUIRED=false (dev), skipping scope checks even for a valid
key. A valid presented key is now resolved onto AuthContext and still scope-
checked in dev; a missing key still never blocks, so the existing zero-key
console workflow is unaffected.

Frontend: new Orgs.tsx (operator onboarding + self-service panels), wired
into Developer.tsx; api.ts helpers for all five new routes.

Verified for real against a running dev server: onboarded two orgs, had one
self-mint a teammate key with no admin key involved, confirmed scope-
escalation is rejected (403), confirmed cross-tenant revoke is rejected
(404), and confirmed the admin-only org-detail route rejects a non-admin
org's own valid key (403) — this one actually leaked before the
authenticate() fix above, caught by running the flow, not by inspection.
tsc --noEmit + frontend vite build clean, 450/450 existing tests unchanged.
2026-10-24 00:30:40 +03:00
4d75f53563 feat(webhooks): add delivery dashboard with disable/enable + manual replay
Backlog item 14: outbound webhook deliveries (success and failure) are now
logged with their original payload, surfaced via GET /v1/webhooks/deliveries,
and individually replayable via POST /v1/webhooks/deliveries/:id/retry so an
integrator can fix a receiving endpoint and resend a failed event without
waiting for the protocol event to fire again. Subscriptions can be disabled
(DELETE /v1/webhooks/:id) and re-enabled (POST /v1/webhooks/:id/enable)
without losing their id/secret/filters.

Frontend: new Webhooks.tsx (extracted from Developer.tsx) renders the
delivery log with a per-subscription filter, auto-refresh, and a retry
button on failed deliveries; subscription table shows active/disabled
status with a toggle.

Verified for real: full tsc typecheck + frontend vite build clean, 450/450
existing tests still pass, exercised POST/DELETE/enable/deliveries routes
against a running dev server with curl, and ran the WebhookService directly
against a local HTTP receiver that rejects then accepts to confirm a failed
delivery logs correctly and a manual replay flips it to delivered.
2026-10-24 00:19:27 +03:00
7fdc321d79 feat: live-wire Casper writes, add marketing homepage, fix cold-start UX
Round 1 against STRATEGY-2026-10-23.md's backlog:

- Wire register_agent/stake/set_credit_score/deposit_liquidity to the real
  Casper Testnet contracts (lib/casper/live_bridge.ts), verified live against
  the real RPC node with a freshly generated (unfunded) keypair
  (npm run casper:keygen). Honesty flags built in for the Odra payable
  calling convention and the admin-gated set_credit_score call.
- Unblock NEAR's paid x402 route (npm run near:keygen generates a real
  implicit account id); QIE stays correctly flagged as blocked on unconfirmed
  external facts (asset contract, facilitator), not env plumbing.
- New public Home tab: live-stats hero, how-it-works, a real competitor
  comparison table, and a "90-second proof" that calls the real API live in
  the browser (verified end-to-end with gstack browse).
- Cold-start UX: visible retry state in X402Playground + the TS SDK, plus a
  keep-warm self-ping (lib/services/keepalive.ts) so the free Render dyno
  rarely idles out from under a real first-time caller.
- New GET /v1/credit-score/:agentId alias + docs/integrations/ samples for
  Skyfire/Nevermined/Coinbase x402.
- Self-hosting quickstart: root docker-compose.yml + scripts/bootstrap.sh,
  both run for real; fixed a real EACCES crash-loop bug in infra/Dockerfile
  (non-root user never owned the /data volume mount) found while verifying.

450/450 tests pass, typecheck clean, frontend build clean.
2026-10-23 19:57:40 +03:00
c80dda9e91 feat(near): add NEAR Hackathon x402 credit-score integration
Adds a third chain-priced rail (alongside the existing Algorand and QIE
integrations, both untouched) for the NEAR Hackathon (Nov 1-14, 2026,
Agent Economy track): GET /v1/x402/near/credit-score/:agentId, settled
in native NEAR on NEAR Testnet.

No @x402/near scheme package exists, so lib/x402/near_gateway.ts is a
from-scratch x402 v2 "exact" scheme built on @x402/core's chain-agnostic
header codecs and types. It needs no third-party facilitator: Cred402
verifies settlement itself directly against the configured NEAR RPC
(lib/x402/near_finality.ts), the same role the Algorand Indexer check and
QIE RPC check play for their chains.

- lib/x402/near_networks.ts, near_rpc.ts, near_finality.ts,
  near_payment_attempt_store.ts, near_gateway.ts: resource server,
  self-verifying settlement, durable exact-once replay protection.
- api/near_x402_routes.ts, api/near_receipt_anchor.ts: HTTP routes
  (status, usage, payment attempts, paid credit score) and Casper-rooted
  receipt anchoring, wired into api/server.ts and api/state.ts.
- examples/near-paid-score/typescript.ts (+ README): a real buyer that
  signs and submits a NEAR Testnet transaction via near-api-js.
- test/near_x402.test.ts: 14 new tests (TDD), full suite 450/450 green,
  typecheck clean.
- docs/near_x402.md, HACKATHON.md, SUBMISSION-CHECKLIST.md: protocol
  writeup (incl. Chain Signatures / NEAR Intents extension points),
  submission guide, and an explicit owner-only checklist (team info,
  payout account, demo video/post, form submission).
2026-10-21 03:11:37 +03:00
9b615993fa feat: add QIE readiness + release-check scripts to match Algorand parity
Mirrors scripts/algorand_x402_ready.ts and algorand_x402_release_check.ts
for QIE's EVM-based x402 integration: x402:qie:ready fetches live
payer/receiver ERC-20 balances over the configured QIE RPC and reports
readiness; x402:qie:release-check adds the public deployment-status gate
and writes a SHA-256-sealed evidence artifact (same hash-seal mechanism
as the Algorand artifact, no private key). Both fail closed with clear
errors (no guessed RPC URL or contract address) when required env vars
are unset. Closes the "no combined release-check / readiness script yet"
gap tracked in docs/qie_x402.md.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-10-19 13:46:48 +03:00
9a1cb7fa15 feat(qie): anchor QIE settlement receipts to Casper
Mirrors the Algorand route's existing anchoring pattern exactly
(api/algorand_receipt_anchor.ts): a settled QIE credit-score payment now
becomes the same Casper-rooted Universal Receipt Envelope used by every
other satellite chain, via a new api/qie_receipt_anchor.ts anchored
provisional (finalize: false) until reconcileQiePayment's own-RPC finality
check confirms it, then finalized or challenged exactly like Algorand's.

- api/qie_receipt_anchor.ts: anchorQieCreditScoreSettlement (idempotent on
  tx hash, refuses conflicting replays), finalizeQieExternalReceipt,
  challengeQieExternalReceipt, qieX402Usage.
- api/state.ts: wires the above through a qieAnchorContext(), reusing the
  existing chain-agnostic externalReceiptProof(receiptId) lookup.
- api/qie_x402_routes.ts: credit-score responses now carry
  external_receipt_id / external_receipt_url / casper_anchor_status;
  reconcileQiePayment finalizes/challenges the receipt alongside recording
  finality; the receipt proof is served by the existing chain-agnostic
  GET /v1/x402/external-receipts/:id route (unchanged, already shared).
- lib/x402/qie_payment_attempt_store.ts: StoredQieSettlement gained
  externalReceiptId, mirroring StoredAlgorandSettlement.

6 new tests (test/qie_receipt_anchor.test.ts) exercise the anchor function
directly against a real Ledger: idempotent replay, conflicting-replay
rejection, finalize/challenge transitions, and usage aggregation. Full
suite stays green: 408/408 tests, typecheck clean.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-10-19 12:53:48 +03:00
bd9004603a feat(qie): add QIE Hackathon 3.0 x402 credit-score integration
QIE is EVM-compatible (Cosmos SDK + eth_* JSON-RPC, testnet chain 1983 /
mainnet 1990), so this reuses the existing generic EVM x402 payment path
(same shape as the Flare integration) rather than bespoke chain code:

- lib/x402/qie_networks.ts, qie_rpc.ts, qie_finality.ts, qie_client.ts,
  qie_gateway.ts, qie_payment_attempt_store.ts
- api/qie_x402_routes.ts wired into api/server.ts
- scripts/qie_x402_check.ts (readiness/preflight, mirrors x402:algorand:check)
- docs/qie_x402.md + a QIE Hackathon section in docs/SUBMISSIONS.md

Fails closed without CRED402_QIE_PAY_TO / asset / facilitator configured,
same discipline as the Algorand integration. Honest gaps flagged rather
than faked: QUSDC's exact testnet contract address is unconfirmed (falls
back to pricing in native QIE), and a real signed transaction needs a
funded faucet key + live facilitator neither of which exist yet — both
documented as TODO with exact unblock steps in docs/SUBMISSIONS.md.

Track: AI + Autonomous Agents. Deadline: 2026-11-30, with a QIE Mainnet
(chain 1990) contract deployment required at submission, not just
testnet — confirmed via the hackathon's own dashboard + press coverage.

9/9 new tests pass (node:test via tsx --test), typecheck clean.
2026-10-19 02:43:44 +03:00
53d8ece384 fix: stop credit-line term reset from shrinking by elapsed time on full repayment
AgentCreditPool.repay() reset the term window after a full repayment by
overwriting line.opened_at with the current time, then computing
due_timestamp as now + (due_timestamp - opened_at) — but opened_at had
already been overwritten by that point. The subtraction therefore used
the *new* opened_at instead of the original one, so the "fresh" term was
silently shrunk by however much of the old term had already elapsed
(e.g. repaying 10 days into a 30-day term produced a 20-day term instead
of a full fresh 30-day term). This undermines the stated behavior
("reset the term window after full repayment") and skews due_timestamp,
which feeds isOverdue()/liquidation timing.

Fix: capture the original term length (due_timestamp - opened_at) before
mutating opened_at, then apply it to the new opened_at.

Added test/agent_credit_pool.test.ts, which fails against the prior
code (asserts a 30-day term, prior code produced 20 days) and passes
with the fix. Full suite: 393/393 passing, tsc --noEmit clean.

This is the in-memory ledger simulation (lib/ledger/*), not the real
on-chain/x402 Algorand payment or signing path — no fund-moving or
key-handling logic was touched.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-10-18 00:34:26 +03:00
334432dd02 fix: use the full Algorand genesis hash as the network id
The paid Mainnet endpoint returned 502 x402_facilitator_unavailable and
could never have sold anything:

  Facilitator does not support scheme "exact" on network
  "algorand:wGHE2Pwdvd7S12BL5FaOP20EGYesN73k"

@x402/avm exports ALGORAND_*_CAIP2 truncated to 32 chars, because CAIP-2
caps a chain reference at 32. The GoPlausible facilitator's /supported and
every catalogued Bazaar resource use the untruncated 44-char genesis hash,
and the resource server matches facilitator capabilities by exact string,
so registration failed outright. Latest @x402/avm (2.26.0) truncates too,
so this is an interop mismatch rather than a stale dependency.

The truncated id was also wrong on the wire: it is what we advertised in
PAYMENT-REQUIRED and what the Bazaar would have recorded, so buyers keyed
on the full hash could not have matched our offer.

Safe in both directions -- the SDK's own normalizeAlgorandNetwork accepts
algorand:<full genesis hash> and maps it back internally, so the AVM
scheme still resolves the right genesis hash when signing and verifying.
Config still accepts the friendly name and either id spelling.

Verified against the live facilitator with a real Mainnet configuration:
the endpoint now returns 402 with network
algorand:wGHE2Pwdvd7S12BL5FaOP20EGYesN73ktiC1qzkkit8=, USDC ASA 31566704,
extra.tag=x402-global-challenge, and a facilitator-injected feePayer.

Also adds the two secrets CRED402_ENV=mainnet requires. Without both,
loadConfig throws at import and the service crash-loops before binding a
port rather than degrading to a 503.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-16 16:14:32 +03:00
1ff795f53f fix: put the challenge tag where the facilitator actually reads it
The GoPlausible facilitator writes Global x402 Challenge attribution at
settlement time from accepts[].extra.tag, and never backfills it. It does
not persist the x402 resource.tags array into its Bazaar record: of 200
live Bazaar resources, 176 carry the tag via extra.tag and zero have a
tags field at all.

Cred402 advertised the tag only in resource.tags, so a real Mainnet
payment would have settled, catalogued into the Bazaar, and then been
filed under src=direct -- never reaching the challenge leaderboard.

- move the tag into the accepted option's extra, from a shared
  challenge_tag module so server and client cannot drift
- declare the x402-merchant extension so the leaderboard row carries a
  name and logo instead of a bare hostname
- reject a challenge missing extra.tag in inspectAlgorandChallenge, which
  fails both the preflight and the release gate
- assert it in the gateway test and in both buyer examples
- add x402:algorand:challenge-check, a read-only gate over the status
  probe, the Bazaar catalogue and the challenge leaderboard

Attribution is not retroactive, so this has to ship before the first real
payment.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-16 15:35:55 +03:00
abc69362c9 fix: label seeded demo agents + tell the truth in credit-score provenance
Seeded demo agents (the bootstrap seller, etc.) carry fabricated x402 revenue
history, yet x402CreditScore reported it under 'verified_x402_revenue' with a
provenance of 'Cred402 Casper-rooted receipt ledger' — presenting demo data as
verified on-chain revenue. Fatal for a credit product.

- add Agent.seeded_demo; set it in AgentRegistry.seed_profile (false on register)
- x402CreditScore now emits demo + data_source ('seeded_demo'|'observed_receipts'),
  renames verified_x402_revenue -> x402_revenue with data_source, and a truthful
  provenance (ledger_mode:'simulation', anchoring caveat, demo disclaimer)
- test: bootstrap seller report is flagged demo end-to-end
2026-09-06 09:56:08 +03:00
7eb53a0e03 fix: serve real Casper Testnet contract hashes + honest ledger provenance
The in-memory ledger minted a fresh random hash-<hex> per boot for every
contract and served it from /api/state, /api/contracts and the On-Chain tab
as if it were the canonical on-chain address. Those synthetic hashes never
matched the modules actually installed on Casper Testnet — a fatal-class
provenance gap for a credit/reputation product.

- add lib/ledger/contract_provenance.ts: installed contracts resolve to their
  REAL Testnet package hash (verifiable on cspr.live via the committed manifest);
  simulation-only contracts get a clearly-labeled sim-* id, never a hash- value
- ledger.contractHashes now sources real hashes; expose contractProvenance +
  ledgerMode:'simulation' on the snapshot and /api/contracts
- test: real hashes match deploys.testnet.json, sim contracts are labeled,
  hashes are deterministic across boots
2026-09-06 09:55:58 +03:00
fde5ad4129 fix: clamp underwriting inputs to documented domains in risk policy
The credit policy (policyV1/policyV2) converts agent metrics directly into
a credit line (real money) but trusted the raw fields. An out-of-range
accuracy_score (>100), a negative dispute_rate, or a negative stake — from
bad data or a hostile registrant — could inflate the line, and a negative
ratio through scaleMotes could even produce a negative credit line.

Normalize every underwriting input to its documented Agent domain before it
reaches a formula (accuracy 0..100, dispute_rate 0..1, reputation 0..100,
stake >= 0, jobs integer >= 0), floor 30-day revenue at 0, and clamp the
final line to >= 0. For already-valid inputs this is the identity, so
existing decisions are unchanged (376 tests pass, was 363).

Add test/risk_policy.test.ts: the module had no dedicated test. Covers the
formula, the 30-day window, and each new guard.
2026-09-06 09:49:58 +03:00
1a78614f89 fix: align Algorand USDC asset id to string across persistence and finality
The USDC ASA ids from @x402/avm are string literals and asset is a
string everywhere else, but the settlement persistence validator and the
finality checker declared it as number. This dropped every settled
Algorand payment on reload (durable replay barrier defeated) and flagged
every reconciliation as a mismatch (numeric asset-id !== string ASA id).

- algorand_payment_attempt_store: StoredAlgorandSettlement.asset -> string;
  validator now checks typeof string && /^\d+$/.
- algorand_finality: expected asset -> string; parse Indexer asset-id via
  unsignedIntegerString for a string-vs-string comparison.
- algorand_receipt_anchor / state: usdcAsset params -> string.
2026-09-06 09:49:58 +03:00
388d482cfc chore: add Apache-2.0 LICENSE (unblocks open-core) + extract http_utils from server god-file 2026-08-25 03:09:55 +03:00
099dd3c97a feat: add production Algorand x402 credit endpoint 2026-08-23 14:18:57 +03:00
24d073ee83 feat: KeeperHub execution layer + Flare interoperable/confidential credit
Two hackathon integrations spanning the whole credit stack, sim-first
(green with no keys) with real integrations behind env flags.

KeeperHub — the on-chain execution & reliability layer (lib/keeperhub/):
- OnchainExecutor: pay-per-execution (x402/MPP) -> simulate -> smart gas
  with exponential backoff -> MEV-protected private routing -> audit trail;
  real MCP client to app.keeperhub.com; deterministic sim fallback.
- Autonomous Credit Keeper: FTSO position health -> check->execute deleverage.
- Credit Automations: declarative price/health/schedule rules as workflows.
- Autonomous Scheduler: KeeperHub-cron loop running keeper + automations.

Flare — interoperable + confidential primitives (packages/.../flare, lib/flare):
- FXRP credit satellite: CAN-gated, FTSO-priced, FDC-attested; Coston2
  Solidity vault (contracts/flare/).
- Confidential Compute credit scoring (TEE-attested, private inputs).
- FTSO-priced multi-asset collateral; FAssets mint->collateralize lifecycle.

x402 Credit-Service Marketplace: sells cred402's intelligence pay-per-call
over x402 (402->pay->200); paid receipts feed the revenue->reputation loop.

Wiring: 78 MCP tools, /v1 + /api routes, console Flare + x402 tabs, 11 demo
CLIs, 8 feature docs + docs/SUBMISSIONS.md, recorded demo video (media/).
346 tests pass; 7 adversarial verification workflows caught + fixed ~37
correctness/security issues.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-08-11 23:34:23 +03:00
31c2bf1a7d fix: contract links 404'd — use cspr.live /contract-package route
The deploy manifest's contract_hash is the Odra contract *package* hash, which
cspr.live indexes at /contract-package/<hex>. We were linking /contract/<hex>,
which 404s for these (that route expects a per-version contract hash), so clicking
a contract link did not open the block explorer. Verified via the cspr.live API:
/contract-packages/<hex> resolves, /contracts/<hex> does not.

Fixes contract links across the On-Chain tab, footer, and Explorer search.
Deploy-tx and account links were already correct.
2026-07-16 20:47:06 +03:00
b25ef73300 feat: link real on-chain deploy transactions on the On-Chain tab
Surface the actual transactions we made on Casper Testnet. Pulled the 26 real
module-install deploys from the cspr.live account API (deploys.transactions.json,
committed for zero runtime dependency) and mapped each contract to its install
deploy via the Odra package-hash key name.

- data: deploys.transactions.json — real deploy hashes, blocks, timestamps
- backend: chain_manifest attaches deploy_hash + /deploy/<hash> cspr.live link to
  each contract (latest install) and exposes the full transactions list
- frontend: On-Chain tab gets a "tx ↗" link per contract and a dedicated
  "On-chain transactions — deploys we made" table (deploy hash, contract, block,
  time), plus an "all account txs" link; stat row shows on-chain deploy count
- test: transaction linking + per-contract install-deploy coverage (244 pass)

Verified: sample deploy c9609ec2… (AgentRegistry install) resolves as a
processed deploy at block 8,204,027 on cspr.live.
2026-07-16 19:18:05 +03:00
89b474fa53 feat: on-chain observability — cspr.live linking across the console
Make Casper Testnet activity observable end-to-end. The 14 deployed Odra
contracts, the deployer account, and protocol events now link to the real
cspr.live block explorer instead of showing opaque, per-boot-random hashes.

- backend: /api/chain serves the canonical deploys.testnet.json manifest
  enriched with cspr.live URLs (lib/services/chain_manifest.ts)
- backend: Explorer search resolves deployed contracts by name/crate/hash
  and returns their cspr.live link
- backend: /api/export/events.csv exports the full on-chain event log
- frontend: new On-Chain tab — contract registry with real hashes + copy,
  deployer account, per-contract live event counts, click-to-focus the feed,
  and event-log CSV export
- frontend: EventFeed upgraded — text/severity filters, pause/resume with
  buffered count, expand-to-JSON, contract-link, single-contract focus
- frontend: Explorer results link on-chain objects to cspr.live; header shows
  a live chain pill; footer contracts link out
- test: chain_manifest + explorer contract-resolution coverage (242 pass)

The Vercel /api/:path* rewrite already proxies the new endpoints. Deployed
contracts/hashes/accounts link to cspr.live; the session event log's synthetic
deploy hashes are deliberately not linked.
2026-07-16 19:02:32 +03:00
35f2bf60cb feat: GraphQL + CLI + SDK parity for p3/p5/p6/p7/p10 services
Brings the five new bureau services to full surface parity with REST/MCP:

GraphQL (lib/graphql): Query.creditCheck, creditChecks, riskScore, dataCommons,
exposure, agentExposure, verticals, vertical(name) — plus the matching
GraphQLDataSource methods (ServerState already satisfies them).

CLI (cred402 bureau): credit-check, risk-score, data-commons, exposure
[agent_id], verticals — each rendering a compact human view or --json.

TS SDK (packages/ts-sdk): client.creditCheck/creditChecks/riskScore/dataCommons/
exposure/agentExposure/verticals/vertical.

ServerState.verticalProfile(name) added for the GraphQL single-vertical field.
tsc clean, full suite 233 green; GraphQL + CLI smoke-tested live.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-17 23:09:43 +03:00
25ed718ad0 feat: p10 service verticals (per-vertical underwriting profiles)
ServiceVerticals makes each x402 family a first-class credit vertical with its
own underwriting profile: advance rate, revenue-volatility haircut, settlement
horizon, minimum track record, and required attestations. profileFor() resolves
a service type to its vertical; qualify() gates eligibility; sizeAdvance()
fronts revenue × advance_rate × (1 − volatility); register() lets governance
tune profiles. Seeded for all p1 category families (coverage-checked).

7 new tests, full suite 233 green. Completes roadmap p3–p10.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-17 17:45:42 +03:00
55012ad463 feat: p9 Enterprise RealFi GA (tenants, entitlements, audit trail)
EnterpriseRealFi adds the production access-control layer in front of the
oracle / data commons / attestation surfaces: named tenants on plans
(developer/growth/enterprise) with entitlement gating, a rolling 30-day quota,
a trailing 60s rate limit, suspend/resume, and a sequential, exportable audit
trail recording every allow/deny decision. guard() wraps authorize-then-run.

8 new tests, full suite 226 green.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-17 17:43:56 +03:00
19d6549230 feat: p8 zk receipt proofs (selective disclosure + Merkle anchoring)
ReceiptProofSystem lets an agent prove a receipt is anchored on-chain and
disclose only chosen fields while hiding the rest. Each attribute is a
secret-salted hiding commitment H(key=value|salt); receipt leaves form a
Merkle tree whose root is the on-chain anchor; a DisclosureProof opens the
revealed fields, ships opaque commitments for the rest, and a Merkle path.
verify() needs no prover secret — anyone can check inclusion from the root.

Honest scope: commitment-based selective-disclosure + membership (the
dependency-free, Casper-verifiable Stage-4 primitive), not a full zk-SNARK.

6 new tests, full suite 218 green.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-17 17:42:03 +03:00
295f975d5a feat: p7 ML risk-engine v2 (learned probability-of-default model)
RiskEngineV2 adds a logistic-regression PD model over a normalized agent
feature vector (reputation, accuracy, dispute rate, experience, revenue,
stake, category risk). train() fits weights by deterministic, L2-regularized
batch gradient descent on realized default/repay outcomes; score() returns
pd + ml_score + rules_score + a convex blended_score, so v2 augments the v1
rules policy rather than replacing it. A domain-calibrated prior makes it
useful before any training data.

5 new tests, full suite 212 green.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-17 17:39:55 +03:00
8696d265ad feat: p6 decentralization & data moat (dispute jury + credit-data commons)
DisputeJury: a deterministic, dispute-id-rooted panel of staked/reputable
agents votes the verdict; the plurality decision is issued on the DisputeCourt
with the median proposed slash, consensus jurors earn reputation and
dissenters/no-shows lose it. Decentralizes verdict authority off the single
judge agent.

CreditDataCommons: anonymized, k-anonymous public snapshot of protocol credit
performance (per-category + per-tier aggregates, dispute slash rate, no agent
ids, thin categories folded into 'other') — the data moat as a citable public
benchmark.

DAO parameter governance already shipped via GovernanceProposals.

9 new tests, full suite 207 green.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-17 17:37:39 +03:00
a59d2bfe5d feat: p5 omnichain credit reconciliation (satellites ↔ Casper exposure)
CrossChainReconciler ties satellite-reported draws/repayments back to the
Casper-rooted GlobalExposureManager (single source of truth for global
exposure across all chains). reconcile() flags the over-borrow failure mode,
Casper-vs-satellite divergence, and unauthorized draws (no issuing CAN);
globalHeadroom() is the per-agent over-borrow guard satellites must respect.

7 new tests, full suite 198 green.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-17 17:33:33 +03:00
81a0e533ed feat(p4): mainnet-beta market risk — exposure caps + insurance loss absorption
lib/services/market_risk.ts: MarketRiskManager gates every draw (per-agent +
per-category + pool-utilization caps, approved-category allowlist for the beta)
and absorbs default losses from the insurance reserve with honest shortfall
reporting + coverage ratio. test/market_risk.test.ts (5). Suite green.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-17 17:29:19 +03:00
deed9725d7 feat(p3): Credit Oracle — Cred402 Inside (credit-as-a-service)
lib/services/credit_oracle.ts: read-only creditCheck (policy-stamped), what-if
simulate, and batch checks so any third-party x402 platform queries Cred402 for
agent creditworthiness and gets the same Casper-rooted answer — works for non-RWA
services. test/credit_oracle.test.ts (5). 186 tests green.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-17 17:26:49 +03:00
afed64e4bd feat(p2): x402 Gateway middleware — any API becomes x402-payable + receipt-generating
Roadmap p2 shipped. The adoption wedge: drop one middleware in front of any route
and it issues 402 challenges, verifies EIP-712/ed25519 payments (replay-protected),
emits a receipt commitment to a sink, and proceeds — feeding the Cred402 credit moat.

- lib/x402/gateway.ts: framework-agnostic X402Gateway + Express and Web (Fetch)
  adapters, pluggable nonce store (replay guard), per-route analytics, receipt sink.
- Works for ANY p1 service category (inference/data/compute/…), not just RWA.
- Fix: eip712 uint256 now padded to 32 bytes (odd-length amounts no longer break signing).
- test/x402_gateway.test.ts (5 cases, real buyer→gateway round-trips), examples/paid-api-x402.ts,
  npm run demo:gateway, docs/roadmap (p2 ✅). 181 tests green.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-17 17:20:46 +03:00
0813724602 feat(p1): universal x402 receipts — credit for any service, not just RWA
Roadmap p1 shipped. Cred402 now underwrites ANY x402 service category, not just
RWA:
- lib/core/service_categories.ts: canonical category taxonomy + per-family
  credit-risk weights (rwa/data/compute/inference/storage/api/defi/compliance…),
  with legacy-type aliasing.
- ServiceCategoryRegistry (lib/ledger/contracts) — on-chain-style, governance-tunable
  weights, seeded defaults, wired into the Ledger.
- ServiceType generalized to an open category string (was a 6-value RWA union).
- Risk policy v1/v2 scale the credit line by the category risk weight; rationale
  records it. RWA evidence is now an optional boost, not a gate.
- test/universal_credit.test.ts (5 cases) + npm run demo:x402: a non-RWA
  inference.llm agent builds a credit line from x402 receipts alone.
- docs/risk_model.md + docs/roadmap (p1 ✅).

176 tests green; main demo unchanged (legacy RWA types keep the rwa weight).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-17 17:09:02 +03:00
5cf86893e3 feat(contracts): deploy Cred402 Odra contracts to Casper Testnet (Casper 2.0)
Migrate the contract suite to Odra 2.x (builds on the Casper 2.0 ABI; fixes the
1.x nightly/edition2024 toolchain deadlock) and deploy 9 contracts live to
casper-test via the Odra livenet deployer:

  AgentRegistry · X402ReceiptRegistry · RWAEvidenceRegistry · RWAAssetRegistry
  ReputationEngine · AgentCreditPool · RiskPolicyManager · AgentPassport · DisputeCourt

- contracts: odra "2", no_std headers, build.rs (odra-build), per-crate Odra.toml +
  build_contract/livenet bins; pinned nightly-2025-01-15 for reproducible wasm.
- tooling: scaffold_livenet.py, deploy_all_testnet.sh, deploy_one.mjs.
- deploys.testnet.json: live manifest; README: on-chain contract hashes.
- Deployer key kept out of git (.secrets/ gitignored); wasm artifacts gitignored.

Verified on-chain: AgentRegistry ContractPackage present in global state.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-17 02:34:49 +03:00
e40ea2aed2 feat: demo video of the live console + record script
- media/cred402-demo.mp4: 720p screencast of https://cred402.vercel.app driving the
  full loop with the Casper streaming-events feed updating live (proves the
  direct-CORS SSE end to end).
- scripts/record_demo.mjs + `npm run record:demo`: Playwright records the live site,
  ffmpeg muxes to MP4. Raw .webm is gitignored.
- README: link the demo video.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-17 01:08:27 +03:00
c763d5ddff docs: production- and hackathon-ready README + finalize live deployment
- Rewrite README around the live deployment (console on Vercel, API on Render),
  the magic loop, and the real (non-mocked) integrations across p8–p10:
  Casper Testnet deploys, x402 + EIP-712, casper-x402 facilitator, Open-Meteo,
  official MCP SDK (44 tools), casper-sidecar, Stripe/Plaid RealFi, Base Sepolia,
  Casper Wallet connect + sign-in. Accurate counts (14 Odra contracts, 151 tests,
  4 SDKs, 20 console tabs) and the contract↔simulation transport seam.
- Pick up concurrent graphql/openapi/sdk/mcp/tests refinements.

Readiness: tsc clean; 151 tests pass; frontend/vite, cargo check, forge build,
and go build all green; console + API both serving 200 in production.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-17 00:56:24 +03:00
e879a324c4 fix(deploy): point Vercel rewrites at live https://cred402.onrender.com
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-17 00:52:24 +03:00
51a56a66c7 feat(deploy): Render Blueprint for the API + Vercel rewrites to it
- render.yaml: always-on web service `cred402-api` (node runtime, installs dev
  deps so tsx is present, health check /v1/health) — Render runs the long-lived
  node:http + SSE server the serverless Vercel deploy can't.
- api/server.ts: honor the platform-provided PORT (Render) before CRED402_PORT.
- frontend/vercel.json: rewrite /api/*, /v1/*, /graphql → https://cred402-api.onrender.com
  so the deployed console reaches the backend same-origin (no CORS, no code change).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-17 00:50:11 +03:00
2d43618725 feat: real integrations (Casper Testnet, x402/EIP-712, MCP, RealFi, cross-chain), wallet sign-in, branding
Replace the design-note docs (p1–p7) with the implemented "make it real" phase
docs (p8–p10) and wire production-grade, env-gated real integrations:

- p8 Casper Testnet: byte-exact deploys + WASM install via casper-js-sdk; live
  node reads (node.testnet.casper.network); CRED402_CHAIN=sim|testnet transport.
- p9 x402 + data + MCP: real EIP-712 typed-data digests (@casper-ecosystem/
  casper-eip-712); casper-x402 facilitator client (x402 V2); live Open-Meteo GHI;
  official @modelcontextprotocol/sdk server; casper-sidecar SSE event feed.
- p10 RealFi + cross-chain: real Stripe test-mode webhooks (HMAC-verified) and
  Plaid sandbox → privacy-preserving on-chain envelopes; Base Sepolia EVM deploy
  (Foundry); reachable via /api/realfi/* and /api/x402/facilitator routes.
- Sign-in with Casper Wallet: real extension provider + challenge/ed25519/session
  flow (/v1/auth/wallet/*), console connect + sign-in button.
- Branding: Cred402 logo mark, favicon, OG image; Vercel config for the console.

All env-gated with sim/free-API fallbacks; full suite green, all toolchains
(TS/Rust/Go/Solidity) build.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-17 00:37:36 +03:00
f1e4bb712e first 2026-06-16 02:50:52 +03:00