# x402 & ERC‑8004 - Three‑Phase Integration Plan

A generalized, phased plan to enable x402 payments and ERC‑8004 compatibility across Cortensor, starting with COR Prover and expanding to core inference and agent flows.

### **Objective**

Become agentic AI infrastructure — an agent‑ready network offering one‑of‑a‑kind inference + validation (COR Prover) as first‑class, composable services discoverable via ERC‑8004 and callable via MCP with x402 payments.

### Key Points (TL;DR)

* **Three Phases**
  1. **Phase 1 — COR Prover x402 MVP (ERC‑8004‑ready):** delegated sessions, k‑redundant inference on the same input, time‑gated **commit → reveal** state machine, **PoI** consensus + **v3 LLM eval**, signed attestations, optional on‑chain anchoring.
  2. **Phase 2 — Hardening, Passes & 8004 Expansion:** webhook push, idempotent invoices, access passes/quotas, ops/observability, publish to ERC‑8004 Validation (and optional Reputation) registries by default.
  3. **Phase 3 — Core Inference & Agent Flows:** one‑shot x402 for `/v1/infer` + agent‑bound inference (ERC‑8004 agent bindings, `cnf`/DPoP), reuse the same rails.
* **Built on Cortensor core protocol**: multiple miners run the **same input** under a **time‑gated** commit→reveal state machine; results are aggregated via **PoI/consensus** to mitigate hallucinations and surface anomalies. No core protocol changes required for Phase 1 (uses **delegated sessions**).
* **Router Node → Router Agent (MCP + 8004)**: evolve the existing Web2 RESTful Router Node into a dual‑mode **Router Agent** that exposes both **Inference** and **Validation (COR Prover)** services via HTTP **and** MCP, discoverable as ERC‑8004 agents and payable via x402. Node operators can run/operate these agent roles alongside mining.

***

### Phase 1 — COR Prover x402 MVP (no core changes, ERC‑8004‑ready)

**What ships**

* x402 middleware (pull/JWS first; webhook optional)
* Prover API using **delegated sessions** (service account)
* **k‑redundant** commit→reveal orchestration via Session/SessionQueue
* **PoI** consensus + **v3 LLM evaluation**
* **Attestation** (JWS; optional EIP‑712) + evidence bundle (IPFS/Arweave)
* Minimal accounting (Invoices + Prover Jobs) + Redis single‑use replay cache
* **ERC‑8004**: register COR Prover identity; write **ValidationResponse** (Mode A: off‑chain first, on‑chain anchor)

**API**

* `POST /v1/prover/validate` → 402 challenge (scope bound to `jobHash`) → x402 receipt → 202 `{jobId}`
* `GET /v1/prover/jobs/{jobId}` → state
* `GET /v1/prover/jobs/{jobId}/attestation` → signed JWS/EIP‑712

**x402 challenge (template)**

```
WWW-Authenticate: X402 ver="1"; facilitators="onchain"; amount="0.002"; currency="ETH"; chain_id="42161"; pay_to="0xCOR_TREASURY"; price_version="p1"; invoice="inv_<opaque>"; jti="j_<uuid>"; nonce="n_<rand>"; scope="POST:/v1/prover/validate#job=<H(input,candidate,policy)>"; exp="<ISO8601+60s>"; proof="jws"; callback="https://api.cortensor.dev/x402/webhook"; jwks="<facilitator-jwks>"
```

**Attestation payload (sketch)**

```json
{
  "iss":"cor-prover","sub":"job_abc","aud":"https://api.cortensor.dev",
  "job":{"input_hash":"H(...)","candidate_hash":"H(...)","policy":{"k":5,"eval":"v3"}},
  "session":{"id":"sess_...","tasks":["t1","t2","t3","t4","t5"],"commit_ms":10000,"reveal_ms":10000},
  "poi":{"method":"cluster-median","dispersion":0.13,"anomalies":["m12"]},
  "v3_eval":{"score":0.87,"rubric":["factuality","consistency"]},
  "settlement":{"invoice":"inv_xyz","amount":"0.002","currency":"ETH","tx_hash":"0x..."},
  "iat": 1730088000, "exp": 1730091600
}
```

**Acceptance (Phase 1)**

* 402 challenge w/ correct scope + 60s TTL
* JWS receipt verification + **single‑use** enforcement
* Valid **Attestation** (offline‑verifiable)
* `invoice ↔ sessionId ↔ taskIds` linkage
* End‑to‑end success under target SLA with `k=5` on testnet

***

### Phase 2 — Hardening, Passes & ERC‑8004 Expansion

* **Webhook push** path + idempotent invoice state machine
* **Passes/Entitlements**: `POST /v1/prover/passes` (x402) → issue **Cortensor Access Token** (JWS) with `quota|window|sla_tier` → skip 402 on hot path
* **Observability**: job timelines; miner dispersion histograms; receipt‑verify metrics
* **Refunds**: admin tool; deterministic mapping to revoke/annotate attestations
* **Abuse controls**: per‑buyer rate‑limits; min/max `k`; payload caps; policy sanity checks
* **8004 defaults**: publish ValidationResponse by default; (optional) Reputation writes

***

### Phase 3 — Core Inference & Agent Flows (ERC‑8004)

* **Core one‑shot x402**: `POST /v1/infer` supports 402 + **passes**; server creates **ephemeral sessions** under caller (or OBO via service account)
* **Streaming**: `POST /v1/infer/stream` (scope bound to `streamTaskId`)
* **Agent flows**: `/v1/agents/{agentId}/infer` & `/v1/agents/{agentId}/prover/validate` with **Agent <8004>** + **X402** headers; require `cnf`/DPoP binding and include `agent_id` in scope
* **SessionPaymentStaking** (optional): credit pool after x402; settle via existing SessionPayment

#### MCP Integration (Model Context Protocol)

* **Expose Cortensor as an MCP server** so agent runtimes can discover and call tools without bespoke wiring.
* **Tools (methods & args)**
  * `cortensor.infer(prompt: string, policy?: { k?: number, modelHints?: object, sla?: string }, stream?: boolean)` → returns `jobId` and result (or streams tokens if `stream=true`).
  * `cortensor.prover.validate(input: any, candidate: any, policy?: { k?: number, timeBudgetSec?: number, eval?: "v3" })` → returns `jobId`, later `attestation`.
* **Auth & Payment over MCP**
  * On first call, server emits an **x402 challenge event** (same fields as HTTP 402). Client responds with a **facilitator receipt** (JWS) via MCP `tool/use` metadata.
  * Support **passes** to skip repeated challenges. Bind payment to caller via **`cnf`/DPoP**; include `agent_id` in `scope` for ERC‑8004 agents.
* **Streaming**
  * Use MCP `tool/result` streaming chunks for `infer(stream=true)`; scope binds to `streamTaskId`.
* **Discovery**
  * Advertise tools and schemas in MCP `capabilities`/`tools` manifest; link to `/.well-known/x402.json` for rails/pricing.
* **Lifecycle**
  * Server creates **ephemeral sessions** per call (or reuses when a **pass** is active). OBO supported via service account.
* **Errors & telemetry**
  * Map x402/payment errors to MCP error codes; include `invoice_id` and `requestHash` for audit.

***

#### ERC‑8004 Agent Registration (MCP‑backed Sessions)

* **Two discoverable services** registered as 8004 agents so other agents can find and pay via x402:
  1. **Cortensor Inference Agent** (`agent:cortensor:infer:v1`) — wraps `/v1/agents/{agentId}/infer` and MCP tool `cortensor.infer`; creates **ephemeral sessions** per call (or reuses when a pass is active).
  2. **COR Prover (Validation) Agent** (`agent:cortensor:prover:v1`) — wraps `/v1/agents/{agentId}/prover/validate` and MCP tool `cortensor.prover.validate`; runs **delegated sessions** to execute k‑redundant re‑inference and produce **attestations**.
* **Discovery/Manifests**: publish **Agent Cards** that reference both **HTTP endpoints** and **MCP tools**, with pricing/SLA and x402 rails.
* **Scope & binding**: include `agent_id` in `scope`; require **cnf/DPoP** so receipts are bound to the calling agent. Receipts/passes are accepted over HTTP or MCP.
* **Session semantics**: sessions are **ephemeral** and **bound to (agentId, jobId)**; OBO (on‑behalf‑of) supported via service account. Validation agent writes **ValidationResponse** to the 8004 registry (Mode A now; Mode B later).

**Minimal Agent Card (illustrative)**

```json
{
  "id": "agent:cortensor:infer:v1",
  "capabilities": ["infer"],
  "endpoints": {
    "http": {"infer": "/v1/agents/{agentId}/infer"},
    "mcp": {"tools": ["cortensor.infer"]}
  },
  "payments": {"protocol": "x402", "discovery": "/.well-known/x402.json"},
  "slaTiers": [{"k":1,"latency":"P10S"},{"k":3,"latency":"P25S"},{"k":5,"latency":"P30S"}]
}
```

```json
{
  "id": "agent:cortensor:prover:v1",
  "capabilities": ["prover.validate"],
  "endpoints": {
    "http": {"validate": "/v1/agents/{agentId}/prover/validate"},
    "mcp": {"tools": ["cortensor.prover.validate"]}
  },
  "payments": {"protocol": "x402", "discovery": "/.well-known/x402.json"},
  "attestation": {"formats": ["JWS","EIP-712"], "evidence": ["ipfs","arweave"]}
}
```

#### Router Node → Router Agent (MCP + 8004)

* **Dual‑mode server**: keep today’s REST endpoints and add an **MCP server**; both surfaces emit/accept x402 challenges/receipts.
* **Two services**: (1) **Inference** (ephemeral sessions per call or pass‑backed reuse), (2) **Validation** (delegated sessions running k‑redundant re‑inference + PoI + PoUW + v3 eval to produce attestations).
* **ERC‑8004 identity**: register Router Agent identities for **Inference** and **Validation** (or a multi‑capability single agent). Include `agent_id` in x402 `scope`; require **cnf/DPoP** binding for agent callers.
* **NodeOps packaging**: single Docker image / Helm chart with flags: `--enable-mcp`, `--enable-validation`, `--mcp-port`, `--http-port`, `--agent-id`, `--erc8004-key`, `--x402-discovery-url`, `--service-account-key`. Defaults keep behavior backward‑compatible (REST‑only) until enabled.
* **Security**: DPoP on agent flows; short‑TTL receipts; single‑use with Redis; attestation signer keys managed per node (rotatable), with public JWKS for verification.
* **Migration path**: start by enabling Inference over MCP; add Validation once COR Prover pipeline is stable; optional Mode B (on‑chain requests) later.
* **Observability**: per‑agent metrics (402 rate, job latency, k, dispersion), webhook success, MCP tool usage, and attestation issuance counts.

### Pricing & SLA Matrix (example)

| Tier       |  k | SLA (p50) | What you get                           | Price (ETH) |
| ---------- | -: | --------: | -------------------------------------- | ----------: |
| Cheap‑Fast |  1 |     5–10s | Single run, no eval                    |     0.00006 |
| Balanced   |  3 |    15–25s | PoI consensus, eval on high dispersion |     0.00012 |
| Critical   |  5 |      ≤30s | PoI + eval always, stronger finality   |     0.00020 |

> Price = base + k multiplier + SLA uplift; adjust for testnet/mainnet.

***

### Security & Compliance Notes

* **Replay**: bind `scope` to `jobHash/sessionId/agentId`; enforce **single‑use** via Redis & invoice state
* **Finality**: facilitator guarantee for UX; background confirmation checks
* **Client binding**: support `cnf`/DPoP for agent‑bound calls
* **Privacy**: hash inputs; store raw evidence off‑chain; gate bundle access

***

### Minimal Data Model (sketch)

* **invoices**: `invoice_id, scope_hash, amount, currency, chain_id, pay_to, facilitator, tx_hash, status, exp, used_at, price_version, jti, buyer_wallet`
* **prover\_jobs**: `job_id, invoice_id, job_hash, session_id, task_ids[], k, policy_json, status, dispersion, score, attestation_jws`
