{"id":50373172,"url":"https://github.com/lancekrogers/cre-risk-router","last_synced_at":"2026-05-30T08:04:12.387Z","repository":{"id":343306593,"uuid":"1170506324","full_name":"lancekrogers/cre-risk-router","owner":"lancekrogers","description":"On-chain risk decision layer for autonomous DeFi agents - 8 sequential risk gates with immutable decision receipts via Chainlink CRE","archived":false,"fork":false,"pushed_at":"2026-04-19T06:48:25.000Z","size":6384,"stargazers_count":1,"open_issues_count":0,"forks_count":0,"subscribers_count":0,"default_branch":"main","last_synced_at":"2026-04-19T08:33:38.151Z","etag":null,"topics":["autonomous-agents","blockchain","chainlink","defi","defi-security","ethereum","golang","risk-management","solidity","wasm"],"latest_commit_sha":null,"homepage":"","language":"Go","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/lancekrogers.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-03-02T07:43:07.000Z","updated_at":"2026-04-19T06:48:29.000Z","dependencies_parsed_at":null,"dependency_job_id":null,"html_url":"https://github.com/lancekrogers/cre-risk-router","commit_stats":null,"previous_names":["lancekrogers/cre-risk-router"],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/lancekrogers/cre-risk-router","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/lancekrogers%2Fcre-risk-router","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/lancekrogers%2Fcre-risk-router/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/lancekrogers%2Fcre-risk-router/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/lancekrogers%2Fcre-risk-router/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/lancekrogers","download_url":"https://codeload.github.com/lancekrogers/cre-risk-router/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/lancekrogers%2Fcre-risk-router/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":33684419,"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-30T02:00:06.278Z","response_time":92,"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":["autonomous-agents","blockchain","chainlink","defi","defi-security","ethereum","golang","risk-management","solidity","wasm"],"created_at":"2026-05-30T08:04:10.018Z","updated_at":"2026-05-30T08:04:12.378Z","avatar_url":"https://github.com/lancekrogers.png","language":"Go","funding_links":[],"categories":[],"sub_categories":[],"readme":"# CRE Risk Router\n\n[![Go](https://img.shields.io/badge/Go-1.25+-00ADD8?logo=go\u0026logoColor=white)](https://go.dev)\n[![Solidity](https://img.shields.io/badge/Solidity-0.8.x-363636?logo=solidity)](https://soliditylang.org)\n[![Chainlink CRE](https://img.shields.io/badge/Chainlink-CRE%20v1.2.0-375BD2?logo=chainlink)](https://chain.link)\n[![Chain](https://img.shields.io/badge/Ethereum-Sepolia-3C3C3D?logo=ethereum)](https://sepolia.etherscan.io)\n[![Built with Foundry](https://img.shields.io/badge/Built%20with-Foundry-FFDB1C)](https://getfoundry.sh)\n[![Hackathon](https://img.shields.io/badge/Chainlink%20Convergence-2nd%20Place%20Autonomous%20Agents-FFD700)](https://chain.link/hackathon/winners/cre-risk-router)\n\n**2nd Place, Autonomous Agents** -- [Convergence: A Chainlink Hackathon 2026](https://chain.link/hackathon/winners/cre-risk-router)\n\nAn **on-chain risk decision layer** for autonomous DeFi agents, built on the [Chainlink Runtime Environment (CRE)](https://chain.link). The Risk Router evaluates trade signals through **8 sequential risk gates** and writes immutable decision receipts to Ethereum via Chainlink DON consensus.\n\nPart of the [Obey Agent Economy](https://github.com/lancekrogers/Obey-Agent-Economy) project, where this workflow serves as the CRE-based risk control layer.\n\n\u003e **TL;DR** — An agent sends a trade signal. The Risk Router runs it through 8 gates (confidence, risk score, staleness, oracle health, price deviation, position sizing, heartbeat). If it passes, a constrained position is approved. The decision is ABI-encoded, signed by DON consensus, and written on-chain as an immutable receipt.\n\n---\n\n## Architecture\n\n```mermaid\nflowchart TD\n    A[Cron Trigger] --\u003e B[RiskRequest]\n    B --\u003e C{8 Risk Gates}\n    C --\u003e|Gate 7| D[Hold Signal Filter]\n    C --\u003e|Gate 1| E[Signal Confidence]\n    C --\u003e|Gate 2| F[Risk Score Ceiling]\n    C --\u003e|Gate 3| G[Signal Staleness]\n    C --\u003e|Gate 4| H[Oracle Health]\n    C --\u003e|Gate 5| I[Price Deviation]\n    C --\u003e|Gate 6| J[Position Sizing]\n    C --\u003e|Gate 8| K[Heartbeat]\n    D \u0026 E \u0026 F \u0026 G \u0026 H \u0026 I \u0026 J \u0026 K --\u003e L{RiskDecision}\n    L --\u003e|Denied| M[Denied Receipt]\n    L --\u003e|Approved| N[Approved + Constraints]\n    N --\u003e O[ABI Encode]\n    M --\u003e O\n    O --\u003e P[GenerateReport]\n    P --\u003e Q[DON Consensus]\n    Q --\u003e R[WriteReport]\n    R --\u003e S[\"RiskDecisionReceipt.sol\\n(on-chain, Sepolia)\"]\n```\n\n## Risk Gates\n\nAll gates run **sequentially** — the first denial short-circuits the pipeline.\n\n| Gate | Name | Type | What It Does |\n|:----:|------|:----:|-------------|\n| 7 | Hold Signal Filter | **Deny** | Rejects `hold` signals immediately (fast-path) |\n| 1 | Signal Confidence | **Deny** | Requires confidence \u003e= threshold (default 0.6) |\n| 2 | Risk Score Ceiling | **Deny** | Rejects scores above maximum (default 75) |\n| 3 | Signal Staleness | **Deny** | Rejects signals older than TTL (default 300s) |\n| 4 | Oracle Health | **Deny** | Validates Chainlink `latestRoundData()` 5-tuple |\n| 5 | Price Deviation | **Deny** | Rejects if market vs oracle diverge \u003e 500 BPS |\n| 6 | Position Sizing | **Constrain** | Adjusts position based on volatility and risk score |\n| 8 | Heartbeat | **Deny** | Circuit breaker for agent liveness (optional) |\n\n## Prerequisites\n\n| Tool | Version | Purpose |\n|------|---------|---------|\n| [Go](https://go.dev/dl/) | 1.25+ | Build WASM binary and bridge server |\n| [CRE CLI](https://github.com/smartcontractkit/cre-cli) | latest | Simulate and deploy CRE workflows |\n| [Foundry](https://getfoundry.sh) | latest | Compile and test Solidity contracts |\n| [just](https://github.com/casey/just) | latest | Task runner (optional but recommended) |\n\n## Quick Start\n\n```bash\n# 1. Clone and enter project\ngit clone https://github.com/lancekrogers/cre-risk-router.git\ncd cre-risk-router\n\n# 2. Install CRE CLI\ngo install github.com/smartcontractkit/cre-cli@latest\n\n# 3. Login to CRE\ncre auth login\n\n# 4. Run simulation (dry-run, no on-chain write)\njust simulate\n# or without just:\ncre workflow simulate . --non-interactive --trigger-index=0 --target=staging-settings\n```\n\n## Usage\n\n### CRE Simulation\n\n**Dry-run** (no on-chain transaction):\n```bash\njust simulate\n```\n\n**Broadcast** (writes receipt on-chain — requires `CRE_ETH_PRIVATE_KEY` in `.env`):\n```bash\njust broadcast\n```\n\n**E2E demo script:**\n```bash\njust demo                      # dry-run\n./demo/e2e.sh --broadcast      # on-chain write\n```\n\n### HTTP Bridge\n\nThe bridge wraps the risk evaluation pipeline as an HTTP server for coordinator integration:\n\n```bash\njust bridge\n```\n\n**Endpoints:**\n\n| Method | Path | Description |\n|--------|------|-------------|\n| `POST` | `/evaluate-risk` | Canonical risk evaluation endpoint |\n| `POST` | `/evaluate` | Compatibility alias |\n| `GET` | `/health` | Health check |\n\n**Request body** (`POST /evaluate-risk`):\n\n```json\n{\n  \"agent_id\": \"agent-inference-001\",\n  \"task_id\": \"task-001\",\n  \"signal\": \"buy\",\n  \"signal_confidence\": 0.85,\n  \"risk_score\": 10,\n  \"market_pair\": \"ETH/USD\",\n  \"requested_position\": 1000000000,\n  \"timestamp\": 1740900000\n}\n```\n\n**Response** (HTTP 200 — both approved and denied):\n\n```json\n{\n  \"run_id\": \"qYRcvrpNcByCDTeEMfE/hTWqjZIM+rm+91XnPWWFOCA=\",\n  \"decision_hash\": \"07DEGCyEw8BniT6K8/A+n2SBsrDsx83WU9QZdmoA8Yg=\",\n  \"approved\": true,\n  \"max_position_usd\": 810000000,\n  \"max_slippage_bps\": 500,\n  \"ttl_seconds\": 300,\n  \"reason\": \"approved\",\n  \"chainlink_price\": 200000000000,\n  \"timestamp\": 1772943222\n}\n```\n\n**Error** (HTTP 400): `{\"error\":\"invalid request body\"}`\n\n**Denial reason codes:** `hold_signal_no_trade`, `signal_confidence_below_threshold`, `risk_score_exceeds_maximum`, `signal_expired`, `chainlink_feed_invalid`, `chainlink_feed_not_updated`, `chainlink_round_incomplete`, `chainlink_feed_stale`, `price_deviation_exceeds_threshold`, `agent_heartbeat_stale`\n\n**Coordinator integration:** The `agent-coordinator` connects via `CRE_ENDPOINT` env var. Only DeFi tasks (`defi`, `trade`, `execute_trade`) trigger a risk check. The bridge is **fail-closed** — if unreachable or if the decision is denied, the task is rejected and a `risk_check_denied` event is published to HCS.\n\n## Scenarios\n\nPre-built simulation scenarios in `scenarios/`:\n\n| Scenario | Signal | Confidence | Risk | Expected |\n|----------|:------:|:----------:|:----:|----------|\n| `approved_trade.json` | buy | 0.85 | 10 | Approved, $810 constrained |\n| `denied_low_confidence.json` | buy | 0.45 | 35 | Denied: confidence below threshold |\n| `denied_high_risk.json` | sell | 0.90 | 82 | Denied: risk score exceeds max |\n| `denied_stale_signal.json` | buy | 0.80 | 40 | Denied: signal expired |\n| `denied_price_deviation.json` | buy | 0.85 | 20 | Denied: price deviation \u003e5% |\n\n## Configuration\n\nGate thresholds are defined in `config.staging.json` and `config.production.json`:\n\n| Field | Default | Description |\n|-------|:-------:|-------------|\n| `signal_confidence_threshold` | `0.6` | Minimum signal confidence (0.0-1.0) |\n| `max_risk_score` | `75` | Maximum allowed risk score (0-100) |\n| `decision_ttl_seconds` | `300` | Signal freshness window |\n| `price_deviation_max_bps` | `500` | Max oracle-market divergence (5%) |\n| `volatility_scale_factor` | `1.0` | Position scaling sensitivity |\n| `oracle_staleness_seconds` | `3600` | Max Chainlink feed age |\n| `enable_heartbeat_gate` | `false` | Agent liveness check |\n\n## Contract\n\n**[`RiskDecisionReceipt.sol`](contracts/evm/src/RiskDecisionReceipt.sol)** deployed on Sepolia:\n\n| | |\n|---|---|\n| **Address** | [`0x9C7Aa5502ad229c80894E272Be6d697Fd02001d7`](https://sepolia.etherscan.io/address/0x9C7Aa5502ad229c80894E272Be6d697Fd02001d7) |\n| **Evidence tx** | [`0x0c72922...242dabd1`](https://sepolia.etherscan.io/tx/0x0c72922fd8e31f859dc5ce30364d87e86c939f7c2a2282899db11b65242dabd1) |\n\n**Features:**\n- Implements CRE `IReceiver` interface — `onReport(bytes,bytes)` receives DON-forwarded reports via KeystoneForwarder\n- `recordDecision()` — direct entry point for testing; writes decision with duplicate prevention per `runId`\n- `isDecisionValid()` — TTL-based expiry check\n- `DecisionRecorded` event — for off-chain indexing\n- ERC165 `supportsInterface()` — interface detection for CRE compatibility\n- On-chain approval/denial counters\n\n## Project Structure\n\n```\ncre-risk-router/\n├── main.go                    # WASM entrypoint (wasip1 build tag)\n├── workflow.go                # CRE handlers (onScheduledSweep, executeRiskPipeline)\n├── workflow_test.go           # CRE workflow tests\n├── pkg/riskeval/\n│   ├── types.go               # Config, RiskRequest, RiskDecision, MarketData, OracleData\n│   ├── risk.go                # 8 risk gates + EvaluateRisk pipeline\n│   ├── risk_test.go           # Gate unit tests\n│   └── helpers.go             # keccak256 hashing, slippage, position math\n├── cmd/bridge/\n│   └── main.go                # HTTP bridge server for coordinator integration\n├── contracts/evm/src/\n│   ├── RiskDecisionReceipt.sol\n│   ├── abi/                   # Contract ABI\n│   └── generated/             # CRE-generated Go bindings\n├── scenarios/                 # Pre-built simulation inputs\n├── demo/e2e.sh                # End-to-end demo script\n├── test/                      # Foundry tests\n├── evidence/                  # Broadcast evidence (tx hashes, logs)\n├── workflow.yaml              # CRE workflow settings\n├── project.yaml               # RPC endpoints\n├── config.staging.json        # Gate thresholds (staging)\n├── config.production.json     # Gate thresholds (production)\n├── justfile                   # Task runner recipes\n└── foundry.toml               # Foundry configuration\n```\n\n## Just Recipes\n\nAll common operations are available via [`just`](https://github.com/casey/just):\n\n```bash\njust              # List all recipes\njust install      # go mod tidy\njust build        # Build WASM binary\njust bridge       # Run HTTP bridge server\njust simulate     # CRE dry-run simulation\njust broadcast    # CRE on-chain broadcast\njust test         # Run all tests (Go + Solidity)\njust test-go      # Run Go tests only\njust test-sol     # Run Solidity tests only\njust lint         # go vet\njust fmt          # gofmt\njust bindings     # Generate EVM bindings from ABI\njust forge-build  # Build Solidity contracts\njust deploy       # Deploy contract to Sepolia\njust demo         # Run e2e demo script\n```\n\n## Tech Stack\n\n| Component | Technology |\n|-----------|-----------|\n| **Runtime** | Chainlink Runtime Environment (CRE) v1.2.0 |\n| **Language** | Go (compiled to WASM via `wasip1`) |\n| **Chain** | Ethereum Sepolia testnet |\n| **Oracle** | Chainlink price feeds (`latestRoundData`) |\n| **Contracts** | Solidity 0.8.x, Foundry |\n| **Consensus** | CRE report-based DON consensus |\n| **Bridge** | Go HTTP server (`net/http`) |\n\n## Environment Variables\n\nCopy `.env.example` to `.env` and configure:\n\n```bash\nDEPLOYER_PRIVATE_KEY=       # For forge create contract deployment\nCRE_ETH_PRIVATE_KEY=        # For CRE broadcast (on-chain writes)\nCOINGECKO_API_KEY=           # Optional: market data for Gate 5\nBRIDGE_ADDR=:8080            # Optional: bridge listen address\n```\n\n## License\n\nMIT\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Flancekrogers%2Fcre-risk-router","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Flancekrogers%2Fcre-risk-router","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Flancekrogers%2Fcre-risk-router/lists"}