{"id":50543532,"url":"https://github.com/namankumar/private-defi-agent","last_synced_at":"2026-06-03T22:01:12.928Z","repository":{"id":353416646,"uuid":"1219331262","full_name":"namankumar/private-defi-agent","owner":"namankumar","description":null,"archived":false,"fork":false,"pushed_at":"2026-04-23T19:15:13.000Z","size":35,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":0,"default_branch":"main","last_synced_at":"2026-04-23T21:18:40.991Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/namankumar.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"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-04-23T19:11:06.000Z","updated_at":"2026-04-23T19:15:17.000Z","dependencies_parsed_at":null,"dependency_job_id":null,"html_url":"https://github.com/namankumar/private-defi-agent","commit_stats":null,"previous_names":["namankumar/private-defi-agent"],"tags_count":null,"template":false,"template_full_name":null,"purl":"pkg:github/namankumar/private-defi-agent","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/namankumar%2Fprivate-defi-agent","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/namankumar%2Fprivate-defi-agent/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/namankumar%2Fprivate-defi-agent/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/namankumar%2Fprivate-defi-agent/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/namankumar","download_url":"https://codeload.github.com/namankumar/private-defi-agent/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/namankumar%2Fprivate-defi-agent/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":33881107,"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-06-03T02:00:06.370Z","response_time":59,"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":[],"created_at":"2026-06-03T22:01:11.960Z","updated_at":"2026-06-03T22:01:12.923Z","avatar_url":"https://github.com/namankumar.png","language":"Python","funding_links":[],"categories":[],"sub_categories":[],"readme":"# private-defi-agent\n\nA Python runtime for an LLM-owned cross-chain DeFi agent. The agent reads on-chain state, asks Claude to decide what to do next, and executes against Aleo and Polygon. It runs on a one-minute cron. State persists to disk between ticks, so restarts are transparent.\n\n## How it works\n\nEvery tick runs the same loop:\n\n```\nobserve → policy → LLM decides → validate → execute → persist\n```\n\n**Observe.** Read pool state from Aleo, yield position from Polygon (Morpho vault), participant registry from disk.\n\n**Policy.** Deterministically compute which actions are legal given the current phase. The LLM never sees a blank canvas. It picks from a pre-computed set.\n\n**LLM decides.** Claude receives the observation, the set of actions allowed in the current phase, and an economic summary. Returns one action with a reason, risk note, and expected outcome.\n\n**Validate.** Guardrails re-check the decision before execution. If the action is illegal, the amount is missing, or a live operation is already in flight, the agent pauses for human review.\n\n**Execute.** Aleo or Polygon adapter executes the chosen action on-chain.\n\n**Persist.** State and decision written to JSON. Agent exits. Next cron tick starts fresh.\n\n---\n\n## Why agent\n\nWe chose state machines over prompt chains because the constraint space for DeFi execution is finite and enumerable. A policy engine can prove it won't produce an illegal trade. A prompt chain can make the same mistake in a new way every time. The model chooses from legal actions. The policy engine defines them.\n\nA deterministic script could handle the happy path: bridge when funded, deposit to Morpho, withdraw when yield threshold is met. The LLM earns its keep in two places a script can't handle well:\n\n**Economic reasoning under uncertainty.** Should the agent withdraw from Morpho now? That depends on current yield bps, gas price, expected bridge time, and how close the timeout is. These tradeoffs don't reduce to a threshold. Claude weighs them and explains the call, including what it's uncertain about.\n\n**Ambiguous chain state.** What if a bridge confirmation is partial? What if pool total is above threshold but the bridge interface isn't deployed yet? A script throws an exception or proceeds blindly. The agent pauses, writes a human-readable reason, and waits for acknowledgment.\n\n**Protocol extensibility.** A script encodes one strategy: deposit to Morpho, withdraw when yield hits the threshold. Adding a new protocol means rewriting the script. The agent separates the concerns differently: the policy engine defines what actions are legal, the LLM reasons about which one is wise. Adding a new protocol means adding new actions to the policy layer. The reasoning handles the rest. Polymarket is a compelling next case: the agent could evaluate prediction market odds, size positions against the yield baseline, and exit before resolution. Same architecture, different policy.\n\n```json\n// Example pause entry in the decision log:\n{\n  \"phase\": \"PAUSED_REVIEW\",\n  \"decision\": \"NOOP\",\n  \"result\": \"Guardrail rejection: Live bridge_out operation already in progress\"\n}\n```\n\n---\n\n## The LLM interface\n\nClaude receives a structured JSON prompt on every tick. Here is the full system prompt:\n\n```\nYou are the operator of a cross-chain DeFi pool.\n\nChoose exactly one action from LEGAL_ACTIONS.\nNever invent balances, tx hashes, or phase transitions.\nNever invent an action not present in LEGAL_ACTIONS.\nPrefer NOOP over risky progression.\nReturn strict JSON with keys: action, reason, risk_note, expected_outcome.\n```\n\n\"Prefer NOOP over risky progression\" is a reliability constraint, not a style hint. It means the agent will wait through many NOOPs rather than take an aggressive action it's uncertain about.\n\n**Example input** (what Claude receives):\n\n```json\n{\n  \"goal\": \"Bridge pool funds to Polygon, deposit to Morpho for yield, bridge back with profit, distribute to depositors.\",\n  \"state\": {\n    \"phase\": \"FUNDS_ON_POLYGON\",\n    \"last_successful_action\": \"INITIATE_BRIDGE_OUT\",\n    \"last_observed_balances\": {\n      \"leo_pool\": 0,\n      \"evm_contract\": 5000000,\n      \"morpho_vault\": 0\n    }\n  },\n  \"observation\": {\n    \"pool_total_base_units\": 0,\n    \"evm_held_usdc_base_units\": 5000000,\n    \"evm_total_shares\": 0,\n    \"evm_current_value_base_units\": 0,\n    \"gas_price_gwei\": 14\n  },\n  \"legal_actions\": [\"NOOP\", \"DEPOSIT_TO_MORPHO\"],\n  \"payloads\": {\n    \"DEPOSIT_TO_MORPHO\": { \"amount_base_units\": 5000000 }\n  },\n  \"economic_summary\": {\n    \"bridge_eligible\": true,\n    \"unrealized_yield_bps\": 0,\n    \"withdraw_eligible\": false\n  }\n}\n```\n\n**Example output** (what Claude returns):\n\n```json\n{\n  \"action\": \"DEPOSIT_TO_MORPHO\",\n  \"reason\": \"Funds confirmed on Polygon (5 USDC). Bridge is complete. Depositing to Morpho is the correct next step — no reason to hold idle.\",\n  \"risk_note\": \"Deposit is irreversible until the withdraw cycle completes. Gas at 14 gwei is acceptable. Morpho share price risk is present but expected.\",\n  \"expected_outcome\": \"Phase transitions to MORPHO_DEPOSITED. Morpho shares minted. Yield accrual begins.\"\n}\n```\n\nThe `reason`, `risk_note`, and `expected_outcome` fields are persisted to `agent_state.json` on every tick, creating a full audit trail of the agent's reasoning.\n\n---\n\n## Phase state machine\n\n```\nIDLE\n  └─► POOL_REGISTERED\n        └─► POOL_FUNDED\n              └─► BRIDGE_OUT_PENDING\n                    └─► FUNDS_ON_POLYGON\n                          └─► MORPHO_DEPOSITED\n                                └─► WITHDRAW_PENDING\n                                      └─► BRIDGE_BACK_PENDING\n                                            └─► READY_TO_DISTRIBUTE\n                                                  └─► COMPLETED\n\nPAUSED_REVIEW  ◄── reachable from any phase on guardrail failure or timeout\n```\n\nPhase transitions are driven by on-chain observation, not by the LLM. The agent never trusts its own previous state over what the chain actually shows.\n\n---\n\n## Reliability\n\nSeveral independent layers prevent catastrophic failure:\n\n| Layer | Mechanism |\n|---|---|\n| Constrained decisions | LLM picks from pre-computed legal actions only |\n| Guardrail validation | Decision re-validated before execution |\n| Heuristic fallback | If Anthropic is unavailable, deterministic priority order runs instead |\n| PAUSED_REVIEW phase | Ambiguous state or rejection → pause + human acknowledgment |\n| Timeout detection | Pending operations that exceed `BRIDGE_TIMEOUT_SECS` trigger a pause |\n| File lock | Cron overlaps rejected. Only one agent run at a time. |\n| Safe reads | Chain reads that fail return zero/none rather than crashing |\n| File-based state | `agent_state.json` is human-inspectable and editable mid-run |\n\n---\n\n## Decision trace\n\n`docs/sample-run.json` contains a realistic end-to-end run showing the agent progressing from IDLE through MORPHO_DEPOSITED, including one NOOP tick while waiting for bridge confirmation. Each entry shows the phase, legal actions offered, Claude's choice, and the result.\n\n---\n\n## Install\n\n```bash\npython3 -m venv .venv\nsource .venv/bin/activate\npip install -r requirements.txt\n```\n\nRequires the [Leo CLI](https://developer.aleo.org/leo/installation) for account generation.\n\n## Quick start (dry run, no funds)\n\n```bash\nAGENT_LLM_MODE=heuristic python3 -m agent status\nAGENT_LLM_MODE=heuristic python3 -m agent run\ncat agent_state.json\n```\n\n`heuristic` mode runs without Anthropic configured. The agent executes the same loop using a deterministic priority order instead of Claude.\n\n## Environment\n\n```bash\n# LLM\nANTHROPIC_API_KEY=\nANTHROPIC_MODEL=claude-sonnet-4-5\nAGENT_LLM_MODE=auto              # auto | anthropic | heuristic\n\n# Aleo\nLEO_PROGRAM_ID=                  # your Leo program ID\nLEO_POOL_ID=                     # your pool ID\nALEO_API_BASE=https://api.explorer.provable.com/v2\nALEO_NETWORK=mainnet\nENABLE_ALEO_MUTATIONS=false      # keep false until Leo contract is ready\n\n# Polygon\nPOLYGON_RPC_URL=\nEVM_CONTRACT_ADDRESS=\nPOLYGON_PRIVATE_KEY=\n\n# Thresholds\nMIN_BRIDGE_OUT_AMOUNT=500000000  # 500 USDC (6 decimals)\nMIN_NET_YIELD_BPS=50\nBRIDGE_TIMEOUT_SECS=1800\n```\n\n## CLI\n\n```bash\npython3 -m agent run                 # full controller pass\npython3 -m agent status              # read-only snapshot, no LLM call\npython3 -m agent resume              # clear pause state after review\npython3 -m agent acknowledge-pause   # mark pause reviewed\npython3 -m agent withdraw-request    # trigger admin withdraw\npython3 -m agent force-withdraw      # from MORPHO_DEPOSITED only\npython3 -m agent force-distribute    # from READY_TO_DISTRIBUTE only\n```\n\n## Cron\n\n```bash\n* * * * * cd /path/to/repo \u0026\u0026 python3 -m agent run \u003e\u003e /tmp/agent.log 2\u003e\u00261\n```\n\nFile lock prevents overlapping invocations.\n\n## Tests\n\n```bash\npython3 -m unittest discover -s tests -t .\n```\n\n## Current limitations\n\n- Bridge-out, receive-state, and distribute are pending Leo contract updates. Aleo writes disabled by default.\n- `agent_state.json` is designed for single-operator use; multi-operator would need a proper store\n- In-memory rate limiting on API reads; no retry backoff on chain RPC failures yet\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fnamankumar%2Fprivate-defi-agent","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fnamankumar%2Fprivate-defi-agent","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fnamankumar%2Fprivate-defi-agent/lists"}