# Arbitrage Service Documentation ## Overview The Arbitrage Service is the core component of the MEV bot that detects and executes arbitrage opportunities on the Arbitrum network. It monitors Uniswap V3 swap events and identifies profitable price discrepancies across different pools. ## Core Components ### `ArbitrageService` Structure The main service structure contains: 1. **Ethereum Client** - Connection to the Arbitrum network 2. **Logger** - Structured logging for monitoring and debugging 3. **Configuration** - Service configuration parameters 4. **Key Manager** - Secure management of private keys for transaction signing 5. **MultiHopScanner** - Scanner for multi-hop arbitrage paths 6. **ArbitrageExecutor** - Component responsible for executing arbitrage transactions 7. **Market Managers** - Two different market managers for pool data management 8. **Token Cache** - Caching layer for pool token information 9. **Statistics** - Runtime metrics and performance data 10. **Database Interface** - Persistence layer for opportunities and executions ### Key Data Structures #### `ArbitrageOpportunity` Represents a detected arbitrage opportunity: - **ID** - Unique identifier for the opportunity - **Path** - Multi-hop path for the arbitrage - **TriggerEvent** - The swap event that triggered the opportunity - **DetectedAt** - Timestamp when the opportunity was detected - **EstimatedProfit** - Estimated profit in wei - **RequiredAmount** - Input amount required for the arbitrage - **Urgency** - Priority level (1-10) - **ExpiresAt** - Expiration time for the opportunity #### `SimpleSwapEvent` Represents a Uniswap V3 swap event: - **TxHash** - Transaction hash - **PoolAddress** - Address of the pool where the swap occurred - **Token0/Token1** - Tokens involved in the swap - **Amount0/Amount1** - Swap amounts - **SqrtPriceX96** - Price after the swap - **Liquidity** - Current liquidity in the pool - **Tick** - Current tick in the pool - **BlockNumber** - Block number of the swap - **LogIndex** - Index of the log in the block - **Timestamp** - When the event was detected ## Core Functions ### Service Lifecycle 1. **NewArbitrageService** - Constructor for creating a new arbitrage service 2. **Start** - Begins monitoring the blockchain for swap events 3. **Stop** - Gracefully stops the service ### Event Processing 1. **ProcessSwapEvent** - Main entry point for processing swap events 2. **isSignificantSwap** - Determines if a swap is large enough to trigger arbitrage detection 3. **detectArbitrageOpportunities** - Scans for arbitrage paths based on a swap event 4. **executeOpportunity** - Executes a detected arbitrage opportunity ### Helper Functions 1. **isValidOpportunity** - Validates if an opportunity meets profitability criteria 2. **calculateScanAmount** - Determines the amount to use for scanning based on the swap 3. **calculateUrgency** - Calculates priority level for an opportunity 4. **rankOpportunities** - Sorts opportunities by urgency and profit 5. **calculateMinOutput** - Calculates minimum output with slippage protection 6. **processExecutionResult** - Handles results from executed arbitrage transactions ### Blockchain Monitoring 1. **blockchainMonitor** - Main monitoring function using Arbitrum sequencer reader 2. **fallbackBlockPolling** - Fallback polling mechanism for block monitoring 3. **processNewBlock** - Processes new blocks for swap events 4. **getSwapEventsFromBlock** - Extracts swap events from a block 5. **parseSwapEvent** - Parses Ethereum logs into swap events 6. **getPoolTokens** - Retrieves token addresses for a pool with caching ### Market Data Management 1. **marketDataSyncer** - Synchronizes data between market managers 2. **syncMarketData** - Performs actual synchronization of market data 3. **convertPoolDataToMarket** - Converts pool data formats 4. **convertMarketToPoolData** - Converts market data to pool format ## Workflow ### 1. Initialization - Create Ethereum client connection - Initialize market managers - Set up token caching - Configure logging and statistics ### 2. Monitoring - Connect to Arbitrum sequencer via WebSocket - Monitor for Uniswap V3 swap events - Parse events into `SimpleSwapEvent` structures - Cache pool token information for performance ### 3. Opportunity Detection - Filter significant swaps based on configured thresholds - Scan for multi-hop arbitrage paths using `MultiHopScanner` - Validate opportunities based on profitability criteria - Rank opportunities by urgency and estimated profit ### 4. Execution - Execute profitable opportunities asynchronously - Apply slippage protection to transactions - Track execution results and update statistics - Persist results to database ### 5. Statistics and Monitoring - Update runtime statistics - Log performance metrics periodically - Handle graceful shutdown with final statistics ## Configuration Parameters ### Arbitrage Parameters - **MinSignificantSwapSize** - Minimum swap size to trigger detection - **MinProfitWei** - Minimum profit threshold - **MinROIPercent** - Minimum ROI percentage - **MaxPathAge** - Maximum age of arbitrage paths - **MaxGasPriceWei** - Maximum gas price for transactions - **SlippageTolerance** - Slippage tolerance for trades - **MinScanAmountWei** - Minimum scan amount - **MaxScanAmountWei** - Maximum scan amount - **OpportunityTTL** - Time-to-live for opportunities - **MaxOpportunitiesPerEvent** - Maximum opportunities per swap event - **MaxConcurrentExecutions** - Maximum concurrent executions ### Timing Parameters - **StatsUpdateInterval** - How often to log statistics ## Performance Considerations ### Caching - Pool token information is cached to avoid repeated contract calls - Market data synchronization between managers optimizes data access ### Concurrency - Asynchronous execution of arbitrage opportunities - Separate goroutines for monitoring, statistics, and market data sync - Concurrent processing of swap events ### Resource Management - Context-based cancellation for graceful shutdown - Timeout-based contract calls to prevent hanging - Rate limiting for RPC calls ## Error Handling ### Critical Failures - Fallback from sequencer monitoring to block polling - Graceful degradation when contract calls fail - Continued operation despite individual execution failures ### Logging - Extensive logging for monitoring and debugging - Different log levels for various types of information - Structured logging for metrics and performance data ## Security Features ### Key Management - Secure key management with encryption - Key rotation policies - Session timeout mechanisms - Audit logging for all key operations ### Transaction Security - Slippage protection for all trades - Gas price limits to prevent excessive costs - Validation of all arbitrage opportunities before execution ## Testing and Validation ### Unit Tests - Comprehensive testing of all core functions - Mock implementations for external dependencies - Edge case validation ### Integration Tests - End-to-end testing with testnet deployments - Performance benchmarking - Stress testing under various network conditions ## Future Enhancements ### Advanced Features - Integration with additional DEX protocols - Machine learning for opportunity prediction - Advanced risk management algorithms - Cross-chain arbitrage capabilities ### Performance Improvements - Further optimization of mathematical calculations - Enhanced caching strategies - Parallel processing of market data