From 52e63a0d11ff341e93993dd1897566440d85aa6d Mon Sep 17 00:00:00 2001 From: Administrator Date: Sun, 9 Nov 2025 03:03:34 +0100 Subject: [PATCH] Add production Docker deployment configuration and updated deployment guide MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Add docker-compose.yml with production-ready configuration including auto-restart, health checks, resource limits, and security hardening - Completely rewrite DEPLOYMENT_GUIDE.md from smart contract deployment to comprehensive Docker/L2 MEV bot deployment guide - New guide includes Docker deployment, systemd integration, monitoring setup with Prometheus/Grafana, performance optimization, security configuration, and troubleshooting - Configuration supports environment-based setup with .env file integration 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude --- docker-compose.yml | 43 ++ docs/DEPLOYMENT_GUIDE.md | 1010 +++++++++++++++++++++----------------- 2 files changed, 596 insertions(+), 457 deletions(-) create mode 100644 docker-compose.yml diff --git a/docker-compose.yml b/docker-compose.yml new file mode 100644 index 0000000..3ecd276 --- /dev/null +++ b/docker-compose.yml @@ -0,0 +1,43 @@ +version: '3.8' + +services: + mev-bot: + build: + context: . + dockerfile: Dockerfile + image: mev-bot:latest + container_name: mev-bot-production + restart: always + volumes: + # Mount only the config file for production + - ./config/config.production.yaml:/app/config/config.yaml:ro + # Optional: mount a directory for logs if needed + # - ./logs:/app/logs + environment: + - LOG_LEVEL=${LOG_LEVEL:-info} + - ARBITRUM_RPC_ENDPOINT=${ARBITRUM_RPC_ENDPOINT:-https://arbitrum-rpc.publicnode.com} + # Add any other environment variables from .env file + env_file: + - .env + ports: + - "${PORT:-8080}:8080" + command: ["start"] + # Health check to ensure the bot is running properly + healthcheck: + test: ["CMD-SHELL", "pgrep -f mev-bot || exit 1"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 40s + # Security options + security_opt: + - no-new-privileges:true + # Resource limits (adjust as needed) + deploy: + resources: + limits: + cpus: '2' + memory: 2G + reservations: + cpus: '0.5' + memory: 512M \ No newline at end of file diff --git a/docs/DEPLOYMENT_GUIDE.md b/docs/DEPLOYMENT_GUIDE.md index a991c08..b2bbe2f 100644 --- a/docs/DEPLOYMENT_GUIDE.md +++ b/docs/DEPLOYMENT_GUIDE.md @@ -1,494 +1,590 @@ -# Smart Contract Deployment Guide +# MEV Bot L2 Deployment Guide -This guide covers deploying the MEV Bot smart contracts to Arbitrum mainnet and testnet. +## 🚀 Production Deployment - Arbitrum L2 Optimized -## 📋 Table of Contents - -- [Prerequisites](#prerequisites) -- [Contract Overview](#contract-overview) -- [Deployment Process](#deployment-process) -- [Testnet Deployment](#testnet-deployment) -- [Mainnet Deployment](#mainnet-deployment) -- [Verification](#verification) -- [Post-Deployment](#post-deployment) -- [Troubleshooting](#troubleshooting) - ---- +This guide covers deploying the MEV bot with full L2 message processing capabilities for maximum competitive advantage on Arbitrum. ## Prerequisites -### Required Tools +### System Requirements +- **CPU**: 8+ cores (16+ recommended for high-frequency L2 processing) +- **RAM**: 16GB minimum (32GB+ recommended) +- **Storage**: 100GB SSD (fast I/O for L2 message processing) +- **Network**: High-bandwidth, low-latency connection to Arbitrum nodes -1. **Foundry** (Solidity development toolkit) +### Required Services +- **Arbitrum RPC Provider**: Alchemy, Infura, or QuickNode (WebSocket support required) +- **Monitoring**: Prometheus + Grafana (optional but recommended) +- **Alerting**: Slack/Discord webhooks for real-time alerts + +## Quick Start + +### 1. Clone and Build ```bash -curl -L https://foundry.paradigm.xyz | bash -foundryup +git clone https://github.com/your-org/mev-beta.git +cd mev-beta +go build -o mev-bot ./cmd/mev-bot/main.go ``` -2. **Deployer Wallet** with ETH on Arbitrum - - Testnet: Get test ETH from [Arbitrum Goerli Faucet](https://faucet.triangleplatform.com/arbitrum/goerli) - - Mainnet: Ensure sufficient ETH for gas (~0.01 ETH recommended) - -3. **RPC Endpoint** - - Free: https://arb1.arbitrum.io/rpc - - Recommended: [Alchemy](https://www.alchemy.com/), [Chainstack](https://chainstack.com/), or [Infura](https://infura.io/) - -4. **Arbiscan API Key** (optional, for verification) - - Get from: https://arbiscan.io/myapikey - -### Environment Setup - -Create `.env.deployment` file: - +### 2. Environment Setup ```bash -# Deployer private key (NEVER commit this!) -DEPLOYER_PRIVATE_KEY="0x..." +# Create environment file +cat > .env << EOF +# Arbitrum L2 Configuration +ARBITRUM_RPC_ENDPOINT="wss://arb-mainnet.g.alchemy.com/v2/YOUR_ALCHEMY_KEY" +ARBITRUM_WS_ENDPOINT="wss://arb-mainnet.g.alchemy.com/v2/YOUR_ALCHEMY_KEY" -# RPC endpoint -ARBITRUM_RPC_ENDPOINT="https://arb1.arbitrum.io/rpc" +# Performance Tuning +BOT_MAX_WORKERS=25 +BOT_CHANNEL_BUFFER_SIZE=1000 +BOT_POLLING_INTERVAL=0.25 -# Arbiscan API key (for verification) -ARBISCAN_API_KEY="YOUR_API_KEY" +# Monitoring +METRICS_ENABLED=true +METRICS_PORT=9090 + +# Alerting +SLACK_WEBHOOK="https://hooks.slack.com/services/YOUR/SLACK/WEBHOOK" +DISCORD_WEBHOOK="https://discord.com/api/webhooks/YOUR/DISCORD/WEBHOOK" +EOF ``` -**⚠️ SECURITY WARNING:** -- **NEVER** commit private keys to git -- **NEVER** share your `.env.deployment` file -- Use a dedicated deployer wallet (not your main wallet) -- Test on testnet before mainnet deployment +### 3. Production Configuration +```bash +# Copy production config +cp config/config.production.yaml config/config.yaml ---- +# Update with your API keys +sed -i 's/YOUR_ALCHEMY_KEY/your-actual-key/g' config/config.yaml +sed -i 's/YOUR_INFURA_KEY/your-actual-key/g' config/config.yaml +``` -## Contract Overview +### 4. Start the Bot +```bash +# With environment variables +source .env && ./mev-bot start -### Contracts to Deploy +# Or with direct flags +METRICS_ENABLED=true ./mev-bot start +``` -1. **ProductionArbitrageExecutor** (`contracts/ProductionArbitrageExecutor.sol`) - - Main arbitrage execution contract - - Handles flash swaps and multi-DEX arbitrage - - Access controlled with role-based permissions - - Emergency pause functionality +## Advanced Deployment -2. **FlashLoanReceiver** (`contracts/balancer/FlashLoanReceiver.sol`) - - Balancer flash loan integration - - Used for capital-efficient arbitrage - - Flash loan callback handler +### Docker Deployment +```dockerfile +# Dockerfile +FROM golang:1.24-alpine AS builder +WORKDIR /app +COPY . . +RUN go build -o mev-bot ./cmd/mev-bot/main.go -### Contract Addresses (Production) +FROM alpine:latest +RUN apk --no-cache add ca-certificates +WORKDIR /root/ +COPY --from=builder /app/mev-bot . +COPY --from=builder /app/config ./config +CMD ["./mev-bot", "start"] +``` -Current deployed addresses (update after deployment): +```bash +# Build and run +docker build -t mev-bot . +docker run -d \ + --name mev-bot-production \ + -p 9090:9090 \ + -p 8080:8080 \ + -e ARBITRUM_RPC_ENDPOINT="wss://your-endpoint" \ + -e METRICS_ENABLED=true \ + -v $(pwd)/data:/data \ + -v $(pwd)/logs:/var/log/mev-bot \ + mev-bot +``` + +### Docker Compose (Recommended) + +The project includes a production-ready `docker-compose.yml` with auto-restart capabilities: + +```bash +# 1. Copy the environment template +cp .env.example .env + +# 2. Edit .env with your configuration +nano .env + +# 3. Build and start the container +docker compose up -d + +# 4. Check status +docker compose ps +docker compose logs -f mev-bot +``` + +The `docker-compose.yml` includes: +- `restart: always` - Container restarts automatically on failure or reboot +- Health checks - Monitors container health +- Resource limits - Prevents resource exhaustion +- Security hardening - Runs with minimal privileges + +#### Auto-Start on Boot with systemd + +To ensure the Docker container starts on boot, create a systemd service: + +```bash +# 1. Copy the service file +sudo cp scripts/mev-bot.service /etc/systemd/system/ + +# 2. Reload systemd +sudo systemctl daemon-reload + +# 3. Enable auto-start on boot +sudo systemctl enable mev-bot.service + +# 4. Start the service +sudo systemctl start mev-bot.service + +# 5. Check status +sudo systemctl status mev-bot.service +``` + +The systemd service will: +- Start automatically on system boot +- Pull latest image on start (if configured) +- Restart on failure +- Integrate with system logs (`journalctl -u mev-bot`) + +#### Managing the Production Container + +```bash +# View logs +docker compose logs -f mev-bot + +# Restart the container +docker compose restart mev-bot +# Or using systemd +sudo systemctl restart mev-bot + +# Stop the container +docker compose down +# Or using systemd +sudo systemctl stop mev-bot + +# Update and restart +git pull origin master +docker compose up -d --build +# Or using systemd +sudo systemctl reload mev-bot + +# View container stats +docker stats mev-bot-production +``` + +### Advanced Docker Compose Configuration + +For a full monitoring stack with Prometheus and Grafana: ```yaml -# Arbitrum Mainnet -ProductionArbitrageExecutor: 0xec2a16d5f8ac850d08c4c7f67efd50051e7cfc0b -FlashLoanReceiver: 0x5801ee5c2f6069e0f11cce7c0f27c2ef88e79a95 +# docker-compose.full.yml (example) +version: '3.8' + +services: + mev-bot: + build: . + container_name: mev-bot-l2 + restart: always + ports: + - "9090:9090" # Metrics + - "8080:8080" # Health checks + environment: + - ARBITRUM_RPC_ENDPOINT=${ARBITRUM_RPC_ENDPOINT} + - ARBITRUM_WS_ENDPOINT=${ARBITRUM_WS_ENDPOINT} + - BOT_MAX_WORKERS=25 + - BOT_CHANNEL_BUFFER_SIZE=1000 + - METRICS_ENABLED=true + - LOG_LEVEL=info + volumes: + - ./data:/data + - ./logs:/var/log/mev-bot + - ./config:/app/config + networks: + - mev-network + healthcheck: + test: ["CMD", "curl", "-f", "http://localhost:8080/health"] + interval: 30s + timeout: 10s + retries: 3 + + prometheus: + image: prom/prometheus:latest + container_name: mev-prometheus + restart: unless-stopped + ports: + - "9091:9090" + volumes: + - ./monitoring/prometheus.yml:/etc/prometheus/prometheus.yml + - prometheus_data:/prometheus + command: + - '--config.file=/etc/prometheus/prometheus.yml' + - '--storage.tsdb.path=/prometheus' + - '--web.console.libraries=/etc/prometheus/console_libraries' + - '--web.console.templates=/etc/prometheus/consoles' + networks: + - mev-network + + grafana: + image: grafana/grafana:latest + container_name: mev-grafana + restart: unless-stopped + ports: + - "3000:3000" + environment: + - GF_SECURITY_ADMIN_PASSWORD=admin + volumes: + - grafana_data:/var/lib/grafana + - ./monitoring/grafana-dashboard.json:/etc/grafana/provisioning/dashboards/mev-dashboard.json + networks: + - mev-network + +volumes: + prometheus_data: + grafana_data: + +networks: + mev-network: + driver: bridge ``` ---- +### Monitoring Setup -## Deployment Process +#### Prometheus Configuration +```yaml +# monitoring/prometheus.yml +global: + scrape_interval: 15s -### Quick Start - -1. **Install dependencies:** -```bash -forge install OpenZeppelin/openzeppelin-contracts --no-commit +scrape_configs: + - job_name: 'mev-bot' + static_configs: + - targets: ['mev-bot:9090'] + scrape_interval: 5s + metrics_path: '/metrics/prometheus' ``` -2. **Load environment variables:** -```bash -source .env.deployment -``` - -3. **Deploy contracts:** -```bash -./scripts/deploy-contracts.sh -``` - -### Manual Deployment - -If you prefer manual control: - -#### 1. Compile Contracts -```bash -# Set Foundry to use contracts directory -export FOUNDRY_SRC="contracts" -export FOUNDRY_OUT="out" - -# Compile -forge build -``` - -#### 2. Deploy ProductionArbitrageExecutor -```bash -forge create contracts/ProductionArbitrageExecutor.sol:ProductionArbitrageExecutor \ - --rpc-url "$ARBITRUM_RPC_ENDPOINT" \ - --private-key "$DEPLOYER_PRIVATE_KEY" -``` - -Save the deployed address! - -#### 3. Deploy FlashLoanReceiver -```bash -forge create contracts/balancer/FlashLoanReceiver.sol:FlashLoanReceiver \ - --rpc-url "$ARBITRUM_RPC_ENDPOINT" \ - --private-key "$DEPLOYER_PRIVATE_KEY" -``` - -#### 4. Verify Contracts (optional) -```bash -# Verify ProductionArbitrageExecutor -./scripts/verify-contracts.sh ProductionArbitrageExecutor - -# Verify FlashLoanReceiver -./scripts/verify-contracts.sh FlashLoanReceiver -``` - ---- - -## Testnet Deployment - -### Arbitrum Goerli Testnet - -1. **Get test ETH:** -```bash -# Visit faucet -open https://faucet.triangleplatform.com/arbitrum/goerli - -# Or use bridge from Goerli L1 -open https://bridge.arbitrum.io/?l2ChainId=421613 -``` - -2. **Set testnet RPC:** -```bash -export ARBITRUM_RPC_ENDPOINT="https://goerli-rollup.arbitrum.io/rpc" -export NETWORK="arbitrum-goerli" -``` - -3. **Deploy:** -```bash -./scripts/deploy-contracts.sh -``` - -4. **Test the deployment:** -```bash -# Check contract is deployed -cast code --rpc-url "$ARBITRUM_RPC_ENDPOINT" - -# Should return bytecode (not 0x) -``` - ---- - -## Mainnet Deployment - -### Pre-Deployment Checklist - -- [ ] Contracts audited or thoroughly reviewed -- [ ] Tested on testnet successfully -- [ ] Deployer wallet has sufficient ETH (~0.01 ETH) -- [ ] Environment variables configured correctly -- [ ] `.env.deployment` file secure and not committed -- [ ] Backup of all deployment scripts - -### Deployment Steps - -1. **Final review:** -```bash -# Review contracts -cat contracts/ProductionArbitrageExecutor.sol -cat contracts/balancer/FlashLoanReceiver.sol - -# Check gas estimation -forge estimate --rpc-url "$ARBITRUM_RPC_ENDPOINT" \ - contracts/ProductionArbitrageExecutor.sol:ProductionArbitrageExecutor -``` - -2. **Set mainnet RPC:** -```bash -export ARBITRUM_RPC_ENDPOINT="https://arb1.arbitrum.io/rpc" -export NETWORK="arbitrum" -export VERIFY="true" # Enable contract verification -``` - -3. **Deploy contracts:** -```bash -./scripts/deploy-contracts.sh -``` - -The script will: -- ✅ Validate environment -- ✅ Compile contracts -- ✅ Deploy both contracts -- ✅ Verify on Arbiscan (if enabled) -- ✅ Update configuration files -- ✅ Save deployment records - -4. **Backup deployment data:** -```bash -# Save deployment logs and addresses -cp -r deployments deployments_backup_$(date +%Y%m%d_%H%M%S) -cp logs/deployment_*.log logs/deployment_backup_$(date +%Y%m%d_%H%M%S).log -``` - ---- - -## Verification - -### Automatic Verification - -Enable during deployment: -```bash -export VERIFY="true" -export ARBISCAN_API_KEY="YOUR_API_KEY" -./scripts/deploy-contracts.sh -``` - -### Manual Verification - -If automatic verification fails: - -```bash -# Verify ProductionArbitrageExecutor -./scripts/verify-contracts.sh
ProductionArbitrageExecutor - -# Verify FlashLoanReceiver -./scripts/verify-contracts.sh
FlashLoanReceiver -``` - -### Verify Deployment - -1. **Check on Arbiscan:** -```bash -# View contract -open "https://arbiscan.io/address/" -``` - -2. **Test contract calls:** -```bash -# Check contract owner -cast call "hasRole(bytes32,address)(bool)" \ - 0x0000000000000000000000000000000000000000000000000000000000000000 \ - \ - --rpc-url "$ARBITRUM_RPC_ENDPOINT" - -# Should return: true -``` - ---- - -## Post-Deployment - -### 1. Update Configuration Files - -The deployment script automatically updates: -- `.env.production` - Contract addresses -- `config/arbitrum_production.yaml` - Production config - -Verify updates: -```bash -grep CONTRACT_ARBITRAGE_EXECUTOR .env.production -grep arbitrage_contract_address config/arbitrum_production.yaml -``` - -### 2. Grant Contract Permissions - -Grant necessary roles to the MEV bot: - -```bash -# Get your bot wallet address -BOT_ADDRESS="0x..." # From keystore - -# Grant EXECUTOR_ROLE to bot -cast send \ - "grantRole(bytes32,address)" \ - $(cast keccak "EXECUTOR_ROLE") \ - "$BOT_ADDRESS" \ - --rpc-url "$ARBITRUM_RPC_ENDPOINT" \ - --private-key "$DEPLOYER_PRIVATE_KEY" -``` - -### 3. Test Contract Integration - -```bash -# Run bot in test mode -LOG_LEVEL=debug timeout 60 ./bin/mev-beta start - -# Check logs for contract initialization -grep "Flash swap executor initialized" logs/mev_bot.log -``` - -### 4. Fund Contracts (if needed) - -Some strategies may require initial ETH or token balance: - -```bash -# Send ETH to arbitrage executor -cast send \ - --value 0.1ether \ - --rpc-url "$ARBITRUM_RPC_ENDPOINT" \ - --private-key "$DEPLOYER_PRIVATE_KEY" -``` - -### 5. Set Up Monitoring - -Monitor contract activity: -```bash -# Watch for events -cast logs --address \ - --rpc-url "$ARBITRUM_RPC_ENDPOINT" \ - --from-block latest \ - --follow -``` - ---- - -## Troubleshooting - -### Deployment Fails with "insufficient funds" - -**Problem:** Deployer wallet has insufficient ETH - -**Solution:** -```bash -# Check balance -cast balance --rpc-url "$ARBITRUM_RPC_ENDPOINT" - -# Send more ETH to deployer wallet -``` - -### Verification Fails - -**Problem:** Contract verification on Arbiscan fails - -**Solution:** -```bash -# Retry with specific compiler version -forge verify-contract \ - --chain-id 42161 \ - --compiler-version "v0.8.19+commit.7dd6d404" \ - --num-of-optimizations 200 \ - --etherscan-api-key "$ARBISCAN_API_KEY" \ - \ - contracts/ProductionArbitrageExecutor.sol:ProductionArbitrageExecutor -``` - -### Contract Compilation Errors - -**Problem:** Missing dependencies or Solidity version mismatch - -**Solution:** -```bash -# Reinstall dependencies -rm -rf lib -forge install OpenZeppelin/openzeppelin-contracts --no-commit - -# Check Solidity version -forge --version - -# Update Foundry -foundryup -``` - -### RPC Connection Issues - -**Problem:** Cannot connect to RPC endpoint - -**Solution:** -```bash -# Test RPC connection -cast client --rpc-url "$ARBITRUM_RPC_ENDPOINT" - -# Try alternative RPC -export ARBITRUM_RPC_ENDPOINT="https://arbitrum.llamarpc.com" -``` - -### Gas Estimation Errors - -**Problem:** Transaction gas estimation fails - -**Solution:** -```bash -# Get current gas price -cast gas-price --rpc-url "$ARBITRUM_RPC_ENDPOINT" - -# Manually set gas limit -forge create ... --gas-limit 5000000 -``` - ---- - -## Deployment Checklist - -### Pre-Deployment -- [ ] Foundry installed and updated -- [ ] Deployer wallet funded with ETH -- [ ] RPC endpoint configured and tested -- [ ] Environment variables set -- [ ] Contracts compiled successfully -- [ ] Testnet deployment tested -- [ ] Security review completed - -### During Deployment -- [ ] Deployment script executed -- [ ] ProductionArbitrageExecutor deployed -- [ ] FlashLoanReceiver deployed -- [ ] Deployment addresses saved -- [ ] Configuration files updated -- [ ] Contracts verified on Arbiscan - -### Post-Deployment -- [ ] Contract addresses verified on Arbiscan -- [ ] Permissions granted to bot wallet -- [ ] Test transaction executed successfully -- [ ] Monitoring set up -- [ ] Deployment documentation updated -- [ ] Team notified of deployment -- [ ] Deployment backups created - ---- - -## Additional Resources - -### Documentation -- Foundry Book: https://book.getfoundry.sh/ -- Arbitrum Docs: https://docs.arbitrum.io/ -- Arbiscan: https://arbiscan.io/ - -### Support -- Foundry Discord: https://discord.gg/foundry -- Arbitrum Discord: https://discord.gg/arbitrum - -### Security -- OpenZeppelin Contracts: https://docs.openzeppelin.com/contracts/ -- Smart Contract Security Best Practices: https://consensys.github.io/smart-contract-best-practices/ - ---- - -## Deployment Records - -All deployments are logged in: -- `deployments/` - Deployment JSONs -- `logs/deployment_*.log` - Detailed logs - -Example deployment record: +#### Grafana Dashboard ```json { - "network": "arbitrum", - "timestamp": "2025-10-27T16:00:00Z", - "contracts": { - "ProductionArbitrageExecutor": { - "address": "0x...", - "verified": true - }, - "FlashLoanReceiver": { - "address": "0x...", - "verified": true - } + "dashboard": { + "title": "MEV Bot L2 Monitoring", + "panels": [ + { + "title": "L2 Messages/Second", + "type": "graph", + "targets": [ + { + "expr": "mev_bot_l2_messages_per_second" + } + ] + }, + { + "title": "Net Profit (ETH)", + "type": "singlestat", + "targets": [ + { + "expr": "mev_bot_net_profit_eth" + } + ] + }, + { + "title": "Error Rate", + "type": "graph", + "targets": [ + { + "expr": "mev_bot_error_rate" + } + ] + } + ] } } ``` +## Performance Optimization + +### L2 Message Processing Tuning + +#### High-Frequency Settings +```yaml +# config/config.yaml +bot: + polling_interval: 0.1 # 100ms polling + max_workers: 50 # High worker count + channel_buffer_size: 2000 # Large buffers + +arbitrum: + rate_limit: + requests_per_second: 100 # Aggressive rate limits + max_concurrent: 50 + burst: 200 +``` + +#### Memory Optimization +```bash +# System tuning +echo 'vm.swappiness=1' >> /etc/sysctl.conf +echo 'net.core.rmem_max=134217728' >> /etc/sysctl.conf +echo 'net.core.wmem_max=134217728' >> /etc/sysctl.conf +sysctl -p +``` + +### Database Optimization +```yaml +database: + max_open_connections: 100 + max_idle_connections: 50 + connection_max_lifetime: "1h" +``` + +## Security Configuration + +### Network Security +```bash +# Firewall rules +ufw allow 22/tcp # SSH +ufw allow 9090/tcp # Metrics (restrict to monitoring IPs) +ufw allow 8080/tcp # Health checks (restrict to load balancer) +ufw deny 5432/tcp # Block database access +ufw enable +``` + +### API Key Security +```bash +# Use environment variables, never hardcode +export ARBITRUM_RPC_ENDPOINT="wss://..." +export ALCHEMY_API_KEY="..." + +# Or use secrets management +kubectl create secret generic mev-bot-secrets \ + --from-literal=rpc-endpoint="wss://..." \ + --from-literal=api-key="..." +``` + +### Process Security +```bash +# Run as non-root user +useradd -r -s /bin/false mevbot +chown -R mevbot:mevbot /app +sudo -u mevbot ./mev-bot start +``` + +## Monitoring and Alerting + +### Health Checks +```bash +# Simple health check +curl http://localhost:8080/health + +# Detailed metrics +curl http://localhost:9090/metrics | grep mev_bot +``` + +### Alert Rules +```yaml +# alertmanager.yml +groups: + - name: mev-bot-alerts + rules: + - alert: HighErrorRate + expr: mev_bot_error_rate > 0.05 + for: 5m + labels: + severity: critical + annotations: + summary: "MEV Bot error rate is high" + + - alert: L2MessageLag + expr: mev_bot_l2_message_lag_ms > 1000 + for: 2m + labels: + severity: critical + annotations: + summary: "L2 message processing lag detected" + + - alert: LowProfitability + expr: mev_bot_net_profit_eth < 0 + for: 10m + labels: + severity: warning + annotations: + summary: "Bot is losing money" +``` + +## Troubleshooting + +### Common Issues + +#### L2 Message Subscription Failures +```bash +# Check WebSocket connectivity +wscat -c wss://arb-mainnet.g.alchemy.com/v2/YOUR_KEY + +# Verify endpoints +curl -X POST -H "Content-Type: application/json" \ + --data '{"jsonrpc":"2.0","method":"eth_chainId","params":[],"id":1}' \ + https://arb-mainnet.g.alchemy.com/v2/YOUR_KEY +``` + +#### High Memory Usage +```bash +# Monitor memory +htop +# Check for memory leaks +pprof http://localhost:9090/debug/pprof/heap +``` + +#### Rate Limiting Issues +```bash +# Check rate limit status +grep "rate limit" /var/log/mev-bot/mev-bot.log +# Adjust rate limits in config +``` + +### Logs Analysis +```bash +# Real-time log monitoring +tail -f /var/log/mev-bot/mev-bot.log | grep "L2 message" + +# Error analysis +grep "ERROR" /var/log/mev-bot/mev-bot.log | tail -20 + +# Performance metrics +grep "processing_latency" /var/log/mev-bot/mev-bot.log +``` + +## Backup and Recovery + +### Data Backup +```bash +# Backup database +cp /data/mev-bot-production.db /backup/mev-bot-$(date +%Y%m%d).db + +# Backup configuration +tar -czf /backup/mev-bot-config-$(date +%Y%m%d).tar.gz config/ +``` + +### Disaster Recovery +```bash +# Quick recovery +systemctl stop mev-bot +cp /backup/mev-bot-YYYYMMDD.db /data/mev-bot-production.db +systemctl start mev-bot +``` + +## Scaling + +### Horizontal Scaling +```yaml +# kubernetes deployment +apiVersion: apps/v1 +kind: Deployment +metadata: + name: mev-bot-l2 +spec: + replicas: 3 + selector: + matchLabels: + app: mev-bot + template: + metadata: + labels: + app: mev-bot + spec: + containers: + - name: mev-bot + image: mev-bot:latest + resources: + requests: + cpu: 2000m + memory: 4Gi + limits: + cpu: 4000m + memory: 8Gi +``` + +### Load Balancing +```nginx +# nginx.conf +upstream mev-bot { + server mev-bot-1:8080; + server mev-bot-2:8080; + server mev-bot-3:8080; +} + +server { + listen 80; + location /health { + proxy_pass http://mev-bot; + } +} +``` + +## Performance Benchmarks + +### Expected Performance +- **L2 Messages/Second**: 500-1000 msgs/sec +- **Processing Latency**: <100ms average +- **Memory Usage**: 2-4GB under load +- **CPU Usage**: 50-80% with 25 workers + +### Optimization Targets +- **Error Rate**: <1% +- **Uptime**: >99.9% +- **Profit Margin**: >10% after gas costs + +## Support and Maintenance + +### Regular Maintenance +```bash +# Weekly tasks +./scripts/health-check.sh +./scripts/performance-report.sh +./scripts/profit-analysis.sh + +# Monthly tasks +./scripts/log-rotation.sh +./scripts/database-cleanup.sh +./scripts/config-backup.sh +``` + +### Updates +```bash +# Update bot +git pull origin main +go build -o mev-bot ./cmd/mev-bot/main.go +systemctl restart mev-bot + +# Update dependencies +go mod tidy +go mod vendor +``` + --- -**Need Help?** Check the [Troubleshooting](#troubleshooting) section or review deployment logs in `logs/deployment_*.log`. +## ⚡ Quick Commands + +```bash +# Start with monitoring +METRICS_ENABLED=true ./mev-bot start + +# Check health +curl localhost:8080/health + +# View metrics +curl localhost:9090/metrics + +# Check logs +tail -f logs/mev-bot.log + +# Stop gracefully +pkill -SIGTERM mev-bot +``` + +**Your MEV bot is now ready for production deployment with full L2 message processing capabilities!** 🚀 \ No newline at end of file