{"id":49437440,"url":"https://github.com/echenim/hydra","last_synced_at":"2026-04-29T17:15:22.770Z","repository":{"id":272675139,"uuid":"917369262","full_name":"echenim/Hydra","owner":"echenim","description":"Modular Rust infrastructure for automated DeFi trading — async agents for mempool monitoring, arbitrage detection, risk enforcement, and   deterministic transaction execution on Ethereum.","archived":false,"fork":false,"pushed_at":"2026-03-12T11:10:49.000Z","size":75,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"main","last_synced_at":"2026-04-05T16:27:19.102Z","etag":null,"topics":["agent","agentic-ai","arbitrage-opportunity","async","blockchain","blockchain-tool","cryptocurrency","decentralized","defi","ethereum","high-performance","mempool","permissionless","rust","tokio","tokio-postgres","trading-bot-analytics","uniswap"],"latest_commit_sha":null,"homepage":"","language":"Rust","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/echenim.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":"2025-01-15T21:12:45.000Z","updated_at":"2026-03-12T18:53:43.000Z","dependencies_parsed_at":"2025-01-16T00:28:17.632Z","dependency_job_id":null,"html_url":"https://github.com/echenim/Hydra","commit_stats":null,"previous_names":["echenim/high-performance-decentralized-permissionless-system","echenim/defi-trading-agent-infrastructure"],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/echenim/Hydra","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/echenim%2FHydra","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/echenim%2FHydra/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/echenim%2FHydra/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/echenim%2FHydra/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/echenim","download_url":"https://codeload.github.com/echenim/Hydra/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/echenim%2FHydra/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":32435470,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-04-29T13:34:34.882Z","status":"ssl_error","status_checked_at":"2026-04-29T13:34:29.830Z","response_time":110,"last_error":"SSL_read: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"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":["agent","agentic-ai","arbitrage-opportunity","async","blockchain","blockchain-tool","cryptocurrency","decentralized","defi","ethereum","high-performance","mempool","permissionless","rust","tokio","tokio-postgres","trading-bot-analytics","uniswap"],"created_at":"2026-04-29T17:15:21.524Z","updated_at":"2026-04-29T17:15:22.763Z","avatar_url":"https://github.com/echenim.png","language":"Rust","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Agent-Based DeFi Trading Infrastructure\n\nA modular Rust system for automated trading on decentralized finance networks. Four specialized async agents communicate via a broadcast message bus to process Ethereum mempool data, detect arbitrage opportunities, enforce risk constraints, and execute transactions deterministically.\n\n```\nBlockchain Mempool\n        │\n        ▼\nMarket Data Agent ── parse pending txs, detect DEX swaps, track prices\n        │\n        ▼\nStrategy Agent ───── evaluate signals, generate trade intents (plugin-based)\n        │\n        ▼\nRisk Agent ────────── validate exposure, slippage, gas, daily loss limits\n        │\n        ▼\nExecution Agent ──── build tx, manage nonce, sign, broadcast (or dry-run)\n        │\n        ▼\nEthereum Network\n```\n\n---\n\n## Quick Start\n\n```bash\n# Build\ncargo build --workspace\n\n# Run all tests (95 tests)\ncargo test --workspace\n\n# Start in dry-run mode (no real transactions)\nRUST_LOG=info cargo run -p orchestrator -- --config-dir ./configs --dry-run\n\n# Run benchmarks\ncargo bench -p messaging -p market-data-agent\n```\n\n---\n\n## Workspace Structure\n\n```\ncrates/\n  common/             Shared types, messages, config, errors\n  messaging/          Async message bus, circuit breaker, retry with backoff\n  market-data-agent/  Mempool RPC, Uniswap V2/V3 tx parser, price tracker\n  strategy-agent/     Strategy trait + arbitrage strategy plugin\n  risk-agent/         Trade validation rules, exposure tracking\n  execution-agent/    Signing, nonce management, tx building, broadcast\n  orchestrator/       Main binary — spawns all agents as Tokio tasks\n\nconfigs/\n  rpc.toml            RPC connection, retry, circuit breaker settings\n  trading.toml        Strategy thresholds, risk limits, execution params\n```\n\nAll agents are library crates. The `orchestrator` is the only binary — it wires agents together in a single Tokio runtime for local development. Agents communicate exclusively through the message bus; no shared state.\n\n### Crate Dependency Graph\n\n```\norchestrator → all agent crates → messaging → common\n```\n\nNo agent crate depends on another agent crate.\n\n---\n\n## Architecture\n\n### Message Pipeline\n\nEvery message flows through a typed enum on a broadcast channel:\n\n```rust\nenum Message {\n    Signal(Envelope\u003cMarketSignal\u003e),      // Market Data → Strategy\n    Intent(Envelope\u003cTradeIntent\u003e),       // Strategy → Risk\n    Validated(Envelope\u003cValidatedTrade\u003e), // Risk → Execution\n    Executed(Envelope\u003cExecutionResult\u003e), // Execution → (logging/monitoring)\n}\n```\n\nEach `Envelope\u003cT\u003e` carries a UUID for idempotency and a millisecond timestamp. The bus uses `tokio::sync::broadcast` with configurable capacity (default 4096). Lagging subscribers skip missed messages rather than erroring.\n\n### Market Data Agent\n\n- Subscribes to Ethereum mempool via `RpcClientTrait` (WebSocket)\n- Parses pending transactions for DEX swap calldata:\n  - Uniswap V2: `swapExactTokensForTokens` (`0x38ed1738`), `swapTokensForExactTokens` (`0x8803dbee`)\n  - Uniswap V3: `exactInputSingle` (`0x414bf389`)\n- Tracks prices per `(token_pair, dex)` and detects cross-DEX divergence in basis points\n- Publishes `MarketSignal` (LargeSwap or PriceDivergence) to the bus\n\n### Strategy Agent\n\n- Routes incoming `MarketSignal` messages to all registered strategies\n- **Strategy trait**: `fn name()` + `async fn evaluate(\u0026self, signal) -\u003e Option\u003cTradeIntent\u003e`\n- Built-in: `ArbitrageStrategy` — triggers on price divergence above a configurable BPS threshold\n- Extensible: implement `Strategy` to add liquidation, yield, or custom logic\n\n### Risk Agent\n\nValidates every `TradeIntent` through a chain of checks before forwarding:\n\n| Check | Rejects When |\n|-------|-------------|\n| Sanity | Zero amount, zero deadline, same token in/out |\n| Exposure limit | Projected position exceeds `max_position_size_eth` |\n| Slippage | Implied slippage exceeds `max_slippage_bps` |\n| Gas price | `max_gas_price_gwei` on intent exceeds configured limit |\n| Daily loss | Accumulated daily loss exceeds `daily_loss_limit_eth` |\n\nPassing intents become `ValidatedTrade` with a risk score (weighted: 40% exposure, 30% gas, 30% loss ratio).\n\n### Execution Agent\n\n- **NonceManager**: atomic `u64` counter, `sync()` from chain on startup\n- **GasEstimator**: base estimate with configurable multiplier\n- **TransactionBuilder**: deterministic tx construction from `ValidatedTrade`\n- **Signer trait**: `LocalSigner` (key from env) or `MockSigner` for testing\n- **Broadcaster trait**: `DryRunBroadcaster` (logs only) or real broadcast\n- Publishes `ExecutionResult` (Success, Failed, or DryRun) to the bus\n\n### Resilience\n\n- **Circuit breaker** (Closed → Open → HalfOpen) with configurable failure threshold and reset timeout\n- **Exponential backoff retry** with configurable max retries and backoff bounds\n- **CancellationToken** for graceful shutdown — agents drain their inbox before exiting\n- **Idempotency** via UUID message IDs\n\n---\n\n## Configuration\n\n### `configs/rpc.toml`\n\n```toml\n[ethereum]\nws_url = \"ws://localhost:8545\"\nhttp_url = \"http://localhost:8545\"\nchain_id = 1\n\n[retry]\nmax_retries = 3\ninitial_backoff_ms = 100\nmax_backoff_ms = 5000\n\n[circuit_breaker]\nfailure_threshold = 5\nreset_timeout_secs = 30\n```\n\n### `configs/trading.toml`\n\n```toml\n[market_data]\nmempool_buffer_size = 4096\nprice_staleness_secs = 30\n\n[strategy]\nmin_profit_bps = 50           # 0.5% minimum profit\nmax_trade_size_eth = 10.0\n\n[risk]\nmax_position_size_eth = 50.0\nmax_slippage_bps = 100        # 1%\nmax_gas_price_gwei = 200.0\ndaily_loss_limit_eth = 5.0\n\n[execution]\ngas_price_multiplier = 1.1\ndry_run = true\nconfirmation_blocks = 1\ntx_timeout_secs = 120\n```\n\n### Environment Variables\n\n```bash\nPRIVATE_KEY=\u003chex-encoded-private-key\u003e   # for LocalSigner\nRUST_LOG=info                            # tracing log level\n```\n\nSee `.env.example` for a template. **Never commit real private keys.**\n\n---\n\n## Performance\n\nBenchmarked with Criterion on local development hardware:\n\n| Metric | Result |\n|--------|--------|\n| Message bus publish (1 subscriber) | **~40M ops/sec** (~24ns/op) |\n| Message bus publish (4 subscribers) | **~38M ops/sec** (~25ns/op) |\n| Publish → receive roundtrip | **~9.4M ops/sec** (~106ns/op) |\n| Uniswap V2 swap parsing | **~83M ops/sec** (~12ns/op) |\n| Swap selector detection | **~795M ops/sec** (~1.3ns/op) |\n\nRun benchmarks: `cargo bench -p messaging -p market-data-agent`\n\n---\n\n## Testing\n\n**95 tests** across 7 crates covering:\n\n- Message serialization roundtrips\n- Config deserialization from TOML files\n- Circuit breaker state machine transitions\n- Retry backoff behavior\n- Transaction calldata parsing (Uniswap V2/V3)\n- Price divergence detection\n- All 5 risk validation rules (pass + reject cases)\n- Nonce manager concurrency\n- Execution agent dry-run and live modes\n- End-to-end pipeline (market signal → strategy → risk → execution)\n- Graceful shutdown (all agents respond to cancellation within timeout)\n\n```bash\ncargo test --workspace              # all tests\ncargo test -p risk-agent            # single crate\ncargo clippy --workspace            # lint (0 warnings)\n```\n\n---\n\n## Technology Stack\n\n| Component | Choice |\n|-----------|--------|\n| Language | Rust (Edition 2024) |\n| Async runtime | Tokio (full features) |\n| Message passing | `tokio::sync::broadcast` |\n| Serialization | serde + serde_json |\n| Configuration | TOML (serde-based) |\n| Observability | tracing + tracing-subscriber |\n| Error handling | thiserror |\n| Benchmarking | Criterion |\n| Shutdown | tokio-util CancellationToken |\n\nBlockchain integration uses trait abstractions (`RpcClientTrait`, `Signer`, `Broadcaster`) — swap in production implementations (e.g., `alloy`) without changing agent logic.\n\n---\n\n## Production Readiness\n\n| Layer | Status |\n|-------|--------|\n| Message bus \u0026 resilience | Production-ready |\n| Risk validation engine | Production-ready |\n| Transaction parser | Production-ready (Uniswap V2/V3) |\n| Price tracking \u0026 divergence | Production-ready |\n| Nonce management | Production-ready |\n| Config \u0026 observability | Production-ready |\n| RPC integration | Interface defined, mock implemented |\n| Transaction signing | Interface defined, mock implemented |\n| Transaction broadcast | Interface defined, dry-run implemented |\n| Strategy plugins | Arbitrage implemented, extensible |\n\nTo connect to a real Ethereum node: implement `RpcClientTrait` with `alloy` WebSocket provider, `Signer` with `alloy-signer`, and `Broadcaster` with `alloy` transaction sending.\n\n---\n\n## Extending\n\n### Add a new strategy\n\n```rust\nuse async_trait::async_trait;\nuse common::messages::{MarketSignal, TradeIntent};\nuse strategy_agent::Strategy;\n\npub struct MyStrategy { /* config */ }\n\n#[async_trait]\nimpl Strategy for MyStrategy {\n    fn name(\u0026self) -\u003e \u0026str { \"my_strategy\" }\n\n    async fn evaluate(\u0026self, signal: \u0026MarketSignal) -\u003e Option\u003cTradeIntent\u003e {\n        // Your logic here\n        None\n    }\n}\n```\n\nRegister it in the orchestrator's strategy list.\n\n### Add a new risk rule\n\nAdd a `check_*` function in `risk-agent/src/rules.rs` following the existing pattern, then call it from `RiskAgent::validate()`.\n\n---\n\n## Future Work\n\n- Real WebSocket RPC integration (alloy)\n- ECDSA transaction signing\n- Live transaction broadcasting\n- Liquidation and yield optimization strategies\n- Persistent nonce recovery from chain\n- HTTP monitoring API\n- Backtesting engine with historical tx replay\n- MEV bundle generation\n- Cross-chain support\n- Docker/CI pipeline\n\n---\n\n## License\n\nMIT License\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fechenim%2Fhydra","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fechenim%2Fhydra","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fechenim%2Fhydra/lists"}