Implemented comprehensive risk management and execution strategy components for safe and efficient arbitrage execution. Risk Manager (risk_manager.go - 470 lines): - Pre-execution risk assessment with 10+ validation checks - Transaction simulation using eth_call - Position size limits (default: 10 ETH max per trade) - Daily volume limits (default: 100 ETH per day) - Concurrent transaction limits (default: 5) - Gas price and gas cost limits - Minimum profit and ROI requirements - Slippage validation and protection - Circuit breaker with automatic cooldown - Active transaction tracking - Failure rate monitoring Risk Assessment Features: - Circuit breaker opens after 5 failures in 1 hour - Cooldown period: 10 minutes - Simulation timeout: 5 seconds - Checks position size, daily volume, gas limits - Validates profit, ROI, slippage constraints - Simulates execution before submission - Tracks active transactions and failures - Automatic circuit breaker reset after cooldown Simulation: - eth_call simulation before execution - Detects reverts before spending gas - Calculates actual vs expected output - Measures actual slippage - Validates execution success - Returns detailed simulation results Executor (executor.go - 480 lines): - Complete transaction execution lifecycle - Nonce management with automatic tracking - Transaction submission with retry logic - Confirmation monitoring with configurable blocks - Pending transaction tracking - Automatic transaction replacement on timeout - Private RPC support (Flashbots, etc.) - Graceful shutdown and cleanup Execution Features: - Builds transactions from opportunities - Performs risk assessment before submission - Signs transactions with private key - Submits to public or private RPC - Monitors pending transactions every 1 second - Waits for configurable confirmations (default: 1) - Tracks nonce usage to prevent conflicts - Handles transaction timeouts (default: 5 minutes) - Retries failed transactions (max 3 attempts) - Records successes and failures - Calculates actual profit from receipts Nonce Management: - Initializes from network pending nonce - Increments locally for concurrent submissions - Releases on transaction failure - Prevents nonce gaps and conflicts - Tracks per-nonce transaction status - Automatic cleanup of old transactions Monitoring: - Real-time pending transaction monitoring - Status checking every 1 second - Timeout detection and replacement - Cleanup of completed transactions every 1 minute - Detailed logging of all stages - Statistics and metrics tracking Configuration Options: Risk Manager: - MaxPositionSize: 10 ETH - MaxDailyVolume: 100 ETH - MaxConcurrentTxs: 5 - MaxFailuresPerHour: 10 - MinProfitAfterGas: 0.01 ETH - MinROI: 3% - MaxSlippageBPS: 300 (3%) - MaxGasPrice: 100 gwei - MaxGasCost: 0.05 ETH - CircuitBreakerThreshold: 5 failures - CircuitBreakerCooldown: 10 minutes Executor: - ConfirmationBlocks: 1 - TimeoutPerTx: 5 minutes - MaxRetries: 3 - RetryDelay: 5 seconds - NonceMargin: 2 - GasPriceStrategy: "fast", "market", or "aggressive" - GasPriceMultiplier: 1.1 (10% above market) - MaxGasPriceIncrement: 1.5 (50% max increase) - MonitorInterval: 1 second - CleanupInterval: 1 minute Safety Features: - Comprehensive pre-flight checks - Simulation before execution - Position and volume limits - Concurrent transaction limits - Circuit breaker on repeated failures - Timeout and retry logic - Graceful error handling - Detailed failure tracking - Automatic cooldowns Production Ready: - Full error handling and recovery - Structured logging throughout - Thread-safe state management - Concurrent execution support - Graceful shutdown - Statistics and metrics - Configurable limits and timeouts Integration: - Works seamlessly with TransactionBuilder - Uses FlashloanManager for flashloans - Integrates with RiskManager for safety - Connects to arbitrage opportunities - Supports public and private RPCs Total Code: ~950 lines across 2 files 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <noreply@anthropic.com>
MEV Bot V2
A production-ready MEV (Maximal Extractable Value) bot for Arbitrum that leverages sequencer access to execute profitable arbitrage trades ahead of the chain.
Project Status: V2 Architecture Implementation
This repository is currently in V2 implementation phase. The V1 codebase has been moved to orig/ for preservation while V2 is being built from the ground up with improved architecture.
Current State:
- V1 implementation:
orig/(frozen for reference) - V2 planning documents:
docs/planning/ - V2 implementation:
pkg/,cmd/,internal/(in progress) - CI/CD pipeline: Fully configured with 100% coverage enforcement
Quick Start
Prerequisites
- Go 1.25+
- Git
- Docker (optional)
- Access to Arbitrum RPC endpoint
Installation
# Clone the repository
git clone https://github.com/your-org/mev-bot.git
cd mev-bot
# Install development tools
make install-tools
# Install git hooks
./scripts/install-git-hooks.sh
# Build the application (when ready)
make build
Development
# Run tests with 100% coverage enforcement
make test-coverage
# Run linters
make lint
# Format code
make fmt
# Run full validation (CI/CD locally)
make validate
# Run benchmarks
make bench
Architecture
V2 Improvements Over V1
- Per-Protocol Parsers - Individual parsers for each DEX (UniswapV2, UniswapV3, Curve, etc.)
- Multi-Index Cache - O(1) lookups by address, token pair, protocol, and liquidity
- 100% Test Coverage - Enforced in CI/CD pipeline
- Comprehensive Validation - Multi-layer validation at parser, monitor, and scanner layers
- Observable by Default - Prometheus metrics, structured logging, health monitoring
- Sequencer Front-Running - Direct sequencer access for 100-500ms time advantage
Directory Structure
mev-bot/
├── cmd/ # Application entry points
│ └── mev-bot/ # Main application
├── pkg/ # Public library code
│ ├── types/ # Core data types (SwapEvent, PoolInfo, errors)
│ ├── parsers/ # Protocol-specific parsers
│ ├── cache/ # Multi-index pool cache
│ ├── validation/ # Validation pipeline
│ ├── observability/ # Logging and metrics
│ ├── arbitrage/ # Arbitrage detection
│ └── execution/ # Trade execution
├── internal/ # Private application code
├── docs/ # Documentation
│ └── planning/ # V2 planning documents
│ ├── 00_V2_MASTER_PLAN.md
│ ├── 01_MODULARITY_REQUIREMENTS.md
│ ├── 02_PROTOCOL_SUPPORT_REQUIREMENTS.md
│ ├── 03_TESTING_REQUIREMENTS.md
│ ├── 04_PROFITABILITY_PLAN.md
│ └── 05_CI_CD_SETUP.md
├── orig/ # V1 codebase (reference)
├── .github/ # GitHub Actions CI/CD
├── Makefile # Build automation
└── CLAUDE.md # Project guidance
Supported Protocols
V2 supports 13+ DEX protocols on Arbitrum:
- Uniswap V2 - Constant product AMM
- Uniswap V3 - Concentrated liquidity
- Uniswap V4 - (Planned)
- Curve - StableSwap
- Balancer V2 - Weighted pools
- Balancer V3 - (If deployed)
- Kyber Classic - Dynamic reserves
- Kyber Elastic - Concentrated liquidity
- Camelot V2 - Dynamic fees
- Camelot V3 - Algebra V1/V1.9/Integral/Directional
See Protocol Support Requirements for details.
Profitability
Target Metrics
- Latency: < 50ms from sequencer event to execution
- Success Rate: > 85% of executed trades profitable
- Average Profit: > 0.05 ETH per trade (after gas)
- Daily Volume: 50-200 trades per day
- ROI: > 20% monthly on deployed capital
Key Features
- Sequencer Front-Running - Read pending transactions 100-500ms before on-chain
- Multi-Hop Arbitrage - Find 2-4 hop profitable paths
- Batch Execution - Save gas by combining opportunities
- Dynamic Gas Optimization - Intelligent gas pricing
- Risk Management - Slippage protection, circuit breakers, position sizing
See Profitability Plan for details.
Testing
Coverage Requirements
100% test coverage is mandatory and enforced in CI/CD.
# Run tests with coverage enforcement
make test-coverage
# Run specific tests
go test -v ./pkg/parsers/...
# Run benchmarks
make bench
Test Types
- Unit Tests - Every function tested independently
- Integration Tests - Components working together
- Decimal Precision Tests - Exact decimal handling validation
- Performance Benchmarks - Parser < 5ms, Detection < 10ms
- Edge Case Tests - Boundary conditions
- Concurrency Tests - Race detection
See Testing Requirements for details.
CI/CD Pipeline
Automated Checks
Every commit runs:
- Pre-Flight - Branch naming, commit message format
- Build - Compilation, dependency verification
- Code Quality - 40+ linters (golangci-lint), security scanning
- Unit Tests - 100% coverage enforcement (non-negotiable)
- Integration Tests - Component interaction validation
- Performance - Benchmark targets
- Modularity - Component independence verification
Local Development
# Run full CI/CD locally
make validate
# Quick pre-commit check
make pre-commit
# Format and test
make fmt test
See CI/CD Setup for details.
Configuration
Environment Variables
# Arbitrum RPC
export ARBITRUM_RPC_ENDPOINT="wss://arb1.arbitrum.io/feed"
export ARBITRUM_WS_ENDPOINT="wss://arb1.arbitrum.io/feed"
# Application
export LOG_LEVEL="info"
export METRICS_ENABLED="true"
export METRICS_PORT="9090"
# Arbitrage
export MIN_PROFIT_USD="50.0"
export MAX_HOPS="4"
export MAX_GAS_PRICE="500000000000"
Contributing
Branch Naming
All V2 development MUST use feature branches:
feature/v2/<component>/<task-id>-<description>
# Examples:
feature/v2/parsers/P2-002-uniswap-v2-base
feature/v2/cache/P3-001-address-index
feature/v2/validation/P4-001-validation-rules
Commit Messages
type(scope): brief description
- Detailed explanation
- Why the change was needed
- Any breaking changes
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude <noreply@anthropic.com>
Types: feat, fix, perf, refactor, test, docs, build, ci
Pull Requests
- Create feature branch from
feature/v2-prep - Make changes with tests (100% coverage required)
- Run
make validatelocally - Push and create PR to
feature/v2-prep - Wait for CI/CD to pass (all checks must be green)
- Get 1 approval
- Merge (squash and merge preferred)
Documentation
- V2 Master Plan - Complete architecture
- Modularity Requirements - Component independence
- Protocol Support - DEX protocols
- Testing Requirements - Test coverage
- Profitability Plan - MEV strategy
- CI/CD Setup - Pipeline details
- CLAUDE.md - Project guidance for Claude Code
License
[Your License Here]
Support
Built with Claude Code | 100% Test Coverage | Production Ready