{"id":50293346,"url":"https://github.com/tang-vu/reasoning-receipt","last_synced_at":"2026-05-28T07:06:47.018Z","repository":{"id":357315235,"uuid":"1235708408","full_name":"tang-vu/reasoning-receipt","owner":"tang-vu","description":"x402-paywalled AI oracle for prediction markets — every price ships with a hashed reasoning trace, settled on Arc in \u003c1s for ~$0.01. Agora Agents Hackathon submission.","archived":false,"fork":false,"pushed_at":"2026-05-22T18:12:02.000Z","size":1813,"stargazers_count":4,"open_issues_count":0,"forks_count":0,"subscribers_count":0,"default_branch":"main","last_synced_at":"2026-05-22T20:57:46.086Z","etag":null,"topics":["agora-hackathon","ai-agent","arc-network","circle-usdc","fastapi","foundry","gemini","nextjs","oracle","polymarket","prediction-markets","solidity","vertex-ai","x402"],"latest_commit_sha":null,"homepage":"https://rrtrace.xyz","language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/tang-vu.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":null,"dco":null,"cla":null}},"created_at":"2026-05-11T15:22:01.000Z","updated_at":"2026-05-22T18:12:06.000Z","dependencies_parsed_at":null,"dependency_job_id":null,"html_url":"https://github.com/tang-vu/reasoning-receipt","commit_stats":null,"previous_names":["tang-vu/reasoning-receipt"],"tags_count":1,"template":false,"template_full_name":null,"purl":"pkg:github/tang-vu/reasoning-receipt","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/tang-vu%2Freasoning-receipt","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/tang-vu%2Freasoning-receipt/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/tang-vu%2Freasoning-receipt/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/tang-vu%2Freasoning-receipt/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/tang-vu","download_url":"https://codeload.github.com/tang-vu/reasoning-receipt/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/tang-vu%2Freasoning-receipt/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":33597930,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-05-26T15:22:16.424Z","status":"online","status_checked_at":"2026-05-28T02:00:06.440Z","response_time":99,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["agora-hackathon","ai-agent","arc-network","circle-usdc","fastapi","foundry","gemini","nextjs","oracle","polymarket","prediction-markets","solidity","vertex-ai","x402"],"created_at":"2026-05-28T07:06:38.622Z","updated_at":"2026-05-28T07:06:47.003Z","avatar_url":"https://github.com/tang-vu.png","language":"Python","funding_links":[],"categories":[],"sub_categories":[],"readme":"# ReasoningReceipt\n\n\u003e **An x402-paywalled AI oracle for prediction markets where the reasoning trace *is* the product.**\n\u003e Every price ships with a hashed, byte-verifiable chain-of-thought. Settled on Arc in under a second for ~$0.0007 gas.\n\n[![CI](https://github.com/tang-vu/reasoning-receipt/actions/workflows/ci.yml/badge.svg)](https://github.com/tang-vu/reasoning-receipt/actions/workflows/ci.yml)\n[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](LICENSE)\n[![Python 3.11+](https://img.shields.io/badge/python-3.11+-blue.svg)](https://www.python.org/downloads/)\n[![Solidity 0.8.26](https://img.shields.io/badge/solidity-0.8.26-363636.svg)](https://soliditylang.org)\n[![Next.js 15](https://img.shields.io/badge/next.js-15-black.svg)](https://nextjs.org)\n\n---\n\n## Live now\n\n| | |\n|---|---|\n| 🌐 **Dashboard** (live + snapshot fallback) | https://rrtrace.xyz |\n| 🔌 **Live API** (FastAPI via Cloudflare Tunnel) | https://api.rrtrace.xyz/stats |\n| 📡 **SSE event stream** | https://events.rrtrace.xyz/events/stream |\n| 🌳 **ReceiptRegistryV2** (Merkle root + schemaVersion, source-verified) | https://testnet.arcscan.app/address/0x27d93c52fea923f956345af27f61d7bf47f0c4c1 |\n| 🔍 **ReceiptRegistry V1** (source-verified) | https://testnet.arcscan.app/address/0x59022EFd46a697bbf2fAd36CcfA8F2099f0bd1Bf |\n| 📜 **Receipts emitted on-chain** | **4,558** and rising (V1: 2,281 legacy · V2: 2,277 Merkle-rooted rr-trace/3, byte-verifiable from #2273 forward) |\n| 🎯 **Distinct markets priced** | **217** across **Polymarket Gamma + Kalshi Trade API** (RFB 03 plural) |\n| 💰 **Per-receipt gas cost** | **$0.000683 USDC** (~1/15 of a cent) |\n| 🧪 **Cross-chain demo** | 1 USDC moved Sepolia → Arc via CCTP V2 ([burn tx](https://sepolia.etherscan.io/tx/0x2aebe23128bb7742c6c3babbd32889c29f3b938940176c41d794169a28f4d615) / [mint tx](https://testnet.arcscan.app/tx/0x8a4ae433cfef773298bb766e1ea4c2d5d1f5005f3a5002fbe03439c370baeccf)) |\n| 🏷️ **Latest release** | [v0.4.0 — Kalshi + App Kit + Merkle playground](https://github.com/tang-vu/reasoning-receipt/releases/tag/v0.4.0) |\n\n**Verify the wedge yourself** — pull any v3 trace from the public Irys gateway and re-hash it client-side:\n\n```bash\nuv run python -m scripts.verify-receipt 2580 --base-url https://api.rrtrace.xyz\n# verdict           : VERIFIED [OK]\n```\n\nOr offline, without trusting our server: pass a `--cid` and `--expected-hash`, the script fetches from `gateway.irys.xyz` directly and recomputes SHA-256. For a single evidence URL inside the trace, the V2 contract's `verifyInclusion(root, leaf, proof)` view accepts a ~200-byte Merkle proof — no full trace download required.\n\n---\n\n## What it is\n\nA paid oracle: pay a few cents of USDC over [x402 v2](https://docs.cdp.coinbase.com/x402/docs/welcome), get a probability for a **Polymarket or Kalshi event**, **plus a receipt** — a hashed, byte-verifiable, **Merkle-rooted reasoning DAG** committed to Arc.\n\nEach market goes through a **5-agent ensemble**:\n\n1. **Bull**, **Bear**, **Edge** — three Gemini researchers run in parallel with **isolated context**. Bull argues YES, Bear argues NO, Edge surfaces tail risks both partisans take for granted. Default model is Gemini 3 Flash Preview (advocacy generators don't need Pro reasoning; Pro is reserved for synthesis below — see `docs/ARCHITECTURE.md`).\n2. **Supervisor** (Gemini 3.1 Pro Preview) — weighted-Bayesian merge with stance weights ∈ [0.1, 0.7] summing to 1.0. Mandates ≥ 1 falsifiable claim with a `checkable_by` date. Consumes a per-category Brier prior from past resolutions.\n3. **Critic** (Gemini Flash) — audits across six rigor dimensions: evidence relevance, falsifiability, scope, coherence, exploration integrity, methodology. Verdict gates publication; rejected receipts never reach the chain.\n\nEvery node of the resulting DAG (claim, evidence, counter-arguments, sensitivity factors, falsifiable claims, critic dimensions) gets its own SHA-256, and a **Merkle root** over all nodes lives on Arc inside `ReceiptRegistryV2.sol`. Anyone can pull the trace from Irys, re-canonicalise it, re-hash it, and byte-match — or challenge a single evidence URL with a ~200-byte inclusion proof via `verifyInclusion(root, leaf, proof)`. **There is no \"trust the publisher\" step.**\n\nThe product isn't the number. The product is the auditable trace.\n\n## Architecture\n\n```mermaid\ngraph LR\n  A[Polymarket / Kalshi] --\u003e|events| B(Scanner)\n  B --\u003e BU{Bull}\n  B --\u003e BE{Bear}\n  B --\u003e ED{Edge}\n  BU \u0026 BE \u0026 ED --\u003e|isolated-context drafts| SV{Supervisor\u003cbr/\u003eGemini 3.1 Pro\u003cbr/\u003eweighted-Bayesian merge}\n  SV --\u003e|merged trace| K{Critic\u003cbr/\u003eGemini Flash\u003cbr/\u003e6-dim audit}\n  K --\u003e|needs_revision| SV\n  K --\u003e|approved trace| S[Canonicalise\u003cbr/\u003eper-node SHA-256 + Merkle root]\n  S --\u003e|JSON bytes| F[Irys upload]\n  S --\u003e|hashes + root| G[ReceiptRegistryV2 on Arc]\n  G -.-\u003e|Receipt event| H[Dashboard - GitHub Pages]\n  G -.-\u003e|resolved outcomes| Q[Resolver → Brier calibration]\n  Q -.-\u003e|category prior| SV\n  D[Trader - Kelly sizing] -.-\u003e|reads probability| SV\n  D --\u003e|positions| W[Circle Wallet portfolio]\n  I[External consumer] --\u003e|GET /price| J(FastAPI)\n  J -.-\u003e|402 + PAYMENT-REQUIRED| I\n  I --\u003e|EIP-3009 signed payload| J\n  J --\u003e|/v1/settle| C[Circle Gateway]\n  C --\u003e G\n  M[Claude Desktop / Cursor] -.-\u003e|MCP tools| J\n```\n\nThe agent loop runs continuously. The **scanner** filters Polymarket Gamma and Kalshi's Trade API for liquid, near-resolution, single-question markets. Each market then goes through the **5-agent ensemble**: **Bull**, **Bear** and **Edge** draft competing stances in parallel with isolated context (Google Search grounded); the **Supervisor** (Gemini 3.1 Pro Preview via Vertex AI on the `global` endpoint) merges them weighted-Bayesian, mandates a falsifiable claim, and folds in a per-category Brier prior from past resolutions; the **Critic** (Gemini Flash) audits across six rigor dimensions and gates publication — on `needs_revision` the Supervisor revises once, on `rejected` the receipt never reaches the chain. The approved trace is canonicalised, every node SHA-256'd, a Merkle root computed, the JSON pinned to Irys, and a `Receipt(...)` event emitted on `ReceiptRegistryV2`. The **trader** Kelly-sizes a position from the agent's portfolio wallet. The **FastAPI server** exposes the same oracle behind an x402-v2 paywall. The **resolver** polls for closed markets and back-fills resolved outcomes so the **calibration** module reports a per-category Brier score — which loops back into the Supervisor's prior.\n\n## Six Circle products in production\n\n| Product | Role |\n|---|---|\n| **Arc Testnet** | Settlement chain. Per-receipt gas $0.000683 measured across 4,500+ emissions. |\n| **USDC** | Native gas + paywall asset. |\n| **Circle Wallets** (developer-controlled) | Portfolio wallet (trader) + consumer wallet (agent pays own oracle), provisioned headlessly via [`scripts/circle-setup.py`](scripts/circle-setup.py) in ~4 seconds — entity secret RSA-OAEP-encrypted client-side, walletSet + 2 wallets via one POST each. |\n| **Gateway / Nanopayments (x402 v2)** | `PAYMENT-REQUIRED` headers, EIP-3009 `TransferWithAuthorization` typed-data, settle via `gateway-api-testnet.circle.com/v1/settle`. |\n| **CCTP V2** | [`scripts/cctp-demo.py`](scripts/cctp-demo.py) — direct-mint path, Sepolia → Arc Testnet, attestation `pending_confirmations` → `complete` in ~12 s, end-to-end in ~60 s. Burn + mint tx hashes linked above. |\n| **App Kit · Unified Balance** | [`services/app-kit/demo.ts`](services/app-kit/demo.ts) — `@circle-fin/app-kit@1.5.1` + `@circle-fin/adapter-viem-v2@1.11.0`. Returns a structured per-chain USDC breakdown across **all 12 testnet chains incl. Arc Testnet** for the agent operator EOA. SDK is wired end-to-end; `kit.unifiedBalance.spend()` ready for a Gateway-deposited spend. |\n\n## Quick start\n\n```bash\n# 1. Clone + install\ngit clone https://github.com/tang-vu/reasoning-receipt \u0026\u0026 cd reasoning-receipt\nuv sync --extra dev\n\n# 2. Provision Circle wallets headlessly (one-time, fills .env)\ncp .env.example .env\n# (set CIRCLE_API_KEY from console.circle.com, then:)\nuv run python -m scripts.circle-setup\n\n# 3. Deploy ReceiptRegistry to Arc (one-time)\n./scripts/deploy-contract.sh   # writes RECEIPT_REGISTRY_ADDRESS to .env\n\n# 4. Run the agent loop (continuous)\nuv run python -m agent.loop\n\n# 5. (optional) Serve x402-paywalled /price endpoint for external consumers\nuv run uvicorn server.main:app --reload\n\n# 6. (optional) Local dashboard\ncd dashboard \u0026\u0026 npm install \u0026\u0026 npm run dev\n```\n\nSee [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md) for the full design, [docs/DEMO.md](docs/DEMO.md) for the demo walkthrough, [docs/SUBMISSION.md](docs/SUBMISSION.md) for the Agora form text, and [docs/mcp.md](docs/mcp.md) for the Claude Desktop / Cursor integration.\n\n## MCP — oracle as a tool in Claude Desktop / Cursor\n\n`services/mcp/server.js` wraps the oracle as a stdio MCP server. Drop this into your `claude_desktop_config.json` and Claude calls our oracle as a first-class tool:\n\n```json\n{\n  \"mcpServers\": {\n    \"reasoning-receipt\": {\n      \"command\": \"node\",\n      \"args\": [\"\u003cpath-to-repo\u003e/services/mcp/server.js\"],\n      \"env\": { \"RR_API_BASE\": \"http://localhost:8000\" }\n    }\n  }\n}\n```\n\nFour tools: `get_price`, `verify_receipt`, `get_stats`, `get_calibration`. Full setup in [docs/mcp.md](docs/mcp.md).\n\n### Paywalled MCP — agents pay x402 to call the oracle\n\nFor agent-to-agent commerce we also expose an x402-paywalled HTTP variant under `/mcp/v1/` on the same FastAPI server. Two tools:\n\n```\nGET https://api.rrtrace.xyz/mcp/v1/get_price/{market_id}    # $0.01 USDC\nGET https://api.rrtrace.xyz/mcp/v1/audit/{receipt_id}       # $0.01 USDC\n```\n\nBoth return a Circle x402 v2 challenge on first call (`network: eip155:5042002`, `amount: 10000` micro-USDC, `payTo`: oracle receiver, `verifyingContract`: Arc Testnet Gateway Wallet). The consumer agent signs an EIP-3009 `TransferWithAuthorization`, retries with `X-Payment`, the server settles via `gateway-api-testnet.circle.com/v1/settle` and returns the cached latest price (or byte-for-byte audit) for that market. Pure agent-to-agent revenue path: no upstream Gemini / Arc gas cost per call because the receipt was already pre-minted by the daemon.\n\n## Repo layout\n\n```\nagent/        Scanner (Polymarket + Kalshi, round-robin interleave), 5-agent\n              ensemble (Bull/Bear/Edge + Supervisor + Critic), trace_v3\n              (Merkle DAG), trader, resolver (Polymarket Gamma + Kalshi Trade\n              API → resolved outcomes), calibration (per-category Brier feed)\nserver/       FastAPI + x402-v2 paywall + Arc chain client (V1 + V2) + SSE\n              event stream + verify endpoint + paywalled MCP HTTP variant\ncontracts/    ReceiptRegistry.sol (V1) + ReceiptRegistryV2.sol (V2 with\n              merkleRoot + verifyInclusion view), both source-verified on Arc\nstorage/      Irys sidecar dispatcher + SQLAlchemy ORM (SQLite dev / Postgres prod)\nwallets/      Circle developer-controlled wallets + Kelly trader portfolio\ndashboard/    Next.js 15 — Home / Agents / Traces / Trace detail / Inclusion\n              / Calibration / Events / Stats / Try. Hybrid mode: live API\n              first, snapshot fallback. Auto-deployed to GitHub Pages.\nservices/\n  irys/         Node sidecar for @irys/upload Bundlr-signed uploads\n  mcp/          MCP stdio server for Claude Desktop / Cursor / Cline\n  app-kit/      Circle App Kit Unified Balance demo (TypeScript, tsx)\nscripts/      Setup, demo runner, healthcheck, safe-push, deploy-contract\n              (V1 + V2), circle-setup (headless), cctp-demo, verify-receipt\n              CLI, record-demo, export-snapshot, seed-demo, multi-consumer-\n              burst, services-watchdog\ntests/        115 pytest tests (e2e + unit, incl. Kalshi scanner + resolver\n              + interleave + ensemble) — all green in CI; 33 forge tests on\n              ReceiptRegistry + V2 + CanteenUSDC\ndocs/         architecture / demo / submission / mcp / canteen-walkthrough /\n              x402-real-settlement / pitch-script\n```\n\n## Tech stack\n\n- **Agent**: Python 3.11+, `uv`, FastAPI, `google-genai` SDK against Vertex AI (`global` endpoint, with Google Search grounding). Role-tuned model routing — stances on **Gemini 3 Flash Preview** (advocacy generators, ~50× cheaper output than Pro), supervisor on **Gemini 3.1 Pro Preview**, critic on Flash. Per-call fallback chain handles quota / 429 / empty-response across all roles.\n- **Multi-agent loop (rr-trace/3)**: Bull / Bear / Edge in parallel (isolated context, Google Search grounded) → Supervisor weighted-Bayesian merge with mandatory falsifiable claim → Critic six-dim ARA audit. Single-pass revision when any dim \u003c 0.4; rejected receipts never reach the chain.\n- **Markets**: Polymarket Gamma API + Kalshi Trade API (both public reads, no auth). Round-robin interleave so `per_tick` slices both sources every tick. Source-specific liquidity floors ($10k Polymarket 24h volume / $2k Kalshi open-interest × last-price).\n- **Settlement**: Arc Testnet (chain id 5042002), Solidity 0.8.26 via Foundry 1.7.1. **V1 + V2 contracts**, both source-verified on testnet.arcscan.app. V2 commits `merkleRoot` + `schemaVersion` and exposes `verifyInclusion(root, leaf, proof)`.\n- **Paywall**: x402 v2 spec-compliant headers (`PAYMENT-REQUIRED`, `eip155:5042002`, Gateway Wallet `verifyingContract`), Circle facilitator `/v1/settle`.\n- **Wallets**: Circle developer-controlled — portfolio + consumer pair, entity secret registered via API (`scripts/circle-setup.py`).\n- **Cross-chain**: CCTP V2 direct-mint path (TokenMessengerV2 + MessageTransmitterV2 + Iris attestation).\n- **Unified Balance**: Circle App Kit (`@circle-fin/app-kit@1.5.1` + adapter-viem-v2) — reads agent operator USDC across 12 testnet chains incl. Arc as one pool. See `services/app-kit/`.\n- **Storage**: Irys (Bundlr-signed uploads via tiny Node sidecar) + SQLAlchemy 2.0.\n- **Dashboard**: Next.js 15 static export, deployed automatically to GitHub Pages on every push. Hybrid mode — live API first (`api.rrtrace.xyz` via Cloudflare Tunnel) with client-side refresh on mount, snapshot fallback when the tunnel hiccups.\n- **MCP**: `@modelcontextprotocol/sdk` stdio server (4 tools, free) + paywalled HTTP variant at `/mcp/v1/{get_price,audit}` ($0.01 USDC per call, same x402 envelope).\n\n## Why this is interesting\n\nMost \"AI agents on chain\" emit hashes of opaque blobs. ReasoningReceipt commits to the **full chain-of-thought** — including the sources the Bull/Bear/Edge stances actually cited (Google Search grounded), the counter-arguments they weighed, the sensitivity factors considered, and the critic's six-dimension audit of all of the above. Then we measure ourselves: the resolver scrapes Polymarket for closed markets, and the calibration module reports a Brier score against actual outcomes.\n\nThe wedge is per-call economics: classical L1 gas makes a $0.01 oracle query nonsensical. On Arc, the receipt costs **less than the answer it commits to** — and that flips the entire product shape from \"trust me\" to \"verify me.\"\n\n## Arc OSS — composable for other Arc builders\n\nReasoningReceipt isn't just an app — it's four fork-ready Arc primitives in a\nclass the reference repos (`arc-commerce`, `arc-p2p-payments`) don't cover:\n**verifiable-data infrastructure**.\n\n- **Merkle-anchored audit registry** — `ReceiptRegistryV2.sol` + `agent/merkle.py`. Commit a hash + Merkle root, then prove any single leaf on-chain via `verifyInclusion(root, leaf, proof)` with a ~200-byte proof. Zero imports, $0.000683/emit.\n- **x402 v2 paywall middleware** — `server/x402.py`. Per-call USDC monetization for any FastAPI route or MCP tool, with a swappable Circle Gateway facilitator.\n- **Headless Circle wallet provisioning** — `scripts/circle-setup.py`. Dev-controlled wallets, RSA-OAEP entity secret, zero console clicks, ~4s.\n- **Canonical-JSON byte-verifier** — `agent/trace_v3.py`. Deterministic JSON → SHA-256 so any artifact becomes byte-reproducible.\n\nEach is MIT-licensed, self-contained, and documented to fork. See **[docs/ARC-OSS.md](docs/ARC-OSS.md)** for the lift-it-out manual.\n\n## License\n\nMIT — see [LICENSE](LICENSE).\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ftang-vu%2Freasoning-receipt","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Ftang-vu%2Freasoning-receipt","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ftang-vu%2Freasoning-receipt/lists"}