Skip to content
On this page

L3-9: MEV Bot

1. Problem

Ethereum's block-building process creates a unique economic phenomenon: miners/validators have discretionary power over transaction ordering. They can choose which transactions to include and in what order. This gives rise to MEV (Maximal Extractable Value) -- the activity of extracting additional profit from transaction ordering. MEV searchers monitor pending transactions in the mempool to find arbitrage, liquidation, and sandwich attack opportunities.

Understanding MEV from the defender's perspective is a prerequisite for writing secure DeFi contracts. Many contract vulnerabilities (such as flash loan attacks) are actually actively exploited by MEV searchers. Understanding how they operate -- from mempool monitoring to Flashbots bundle submission -- helps developers design MEV-resistant contracts. At the same time, MEV bots themselves demonstrate many important engineering skills: real-time event listening, gas bidding strategies, transaction simulation, and atomic bundle execution.

2. Why

MEV is one of the most important and controversial areas in Ethereum economics. According to Flashbots statistics, over $1 billion in MEV has been extracted since 2020. MEV negatively affects ordinary users -- sandwich attacks lead to higher gas fees and worse execution prices -- but also provides positive contributions -- arbitrage keeps DEX prices consistent, and liquidations keep lending protocols healthy.

Understanding MEV is crucial for developers for three reasons: (1) Defensive design -- understanding how to prevent contracts from becoming victims of MEV attacks; (2) Market efficiency -- arbitrage and liquidation bot logic is directly related to the design of DEX aggregators and leveraged protocols; (3) PBS (Proposer-Builder Separation) -- MEV has driven fundamental changes in Ethereum's block-building architecture, and understanding it is central to understanding L1 economics.

3. Solution

scripts/mev-bot.js is an educational MEV searcher skeleton that demonstrates the complete architecture of an MEV bot:

Architecture Layers:

  1. Mempool Monitoring: Subscribes to pendingTransactions via WebSocket to receive pending transaction hashes in real-time. For each transaction, fetches full transaction details and parses its interaction target and method signature. In production, searchers typically run their own full nodes for minimum latency.

  2. Arbitrage Detection: Uses Uniswap V2's x*y=k AMM formula to calculate price differences between two DEXes.

    • Fetches reserves from Uniswap and SushiSwap Pair contracts (getReserves())
    • Calculates profits from cycling between the two DEXes (Uniswap -> SushiSwap or reverse)
    • If profit > gas cost + bribe, an arbitrage opportunity exists
    • Calculation formula: amountOut = (amountIn * 997 * reserveOut) / (reserveIn * 1000 + amountIn * 997)
  3. Sandwich Attack Detection: Identifies large swap transactions in the mempool. The principle:

    • Frontrun: buy before the victim's transaction, pushing the price up
    • Victim transaction: executes at high slippage
    • Backrun: sell after the victim's transaction, profiting from the price difference
  4. Liquidation Detection: Monitors positions in lending protocols (Aave, Compound) that are close to the liquidation threshold. When a position's health factor drops below 1, triggers liquidation and earns the liquidation bonus (typically 5-10%).

  5. Flashbots Bundle Submission:

    • Packages multiple transactions into an atomic bundle
    • Sends directly to validators via Flashbots relay, bypassing the public mempool
    • Atomic bundle: either all succeed or all fail (prevents partial execution leading to losses)
    • Includes a validator tip (bundle tip) as economic incentive

Reference source file: scripts/mev-bot.js

4. Pitfalls Encountered

  • Latency competition: MEV searching is a speed game -- millisecond-level latency differences determine winners and losers. Relying on public RPC nodes typically has >100ms latency, while competitors using dedicated nodes have <10ms latency
  • Simulation vs execution divergence: A bundle that simulates successfully in eth_call may fail in actual execution due to state changes. Other searchers' transactions may have changed state before your bundle
  • Gas bidding spiral: Multiple searchers bidding priority fees for the same opportunity causes profits to be consumed by gas costs. All three transactions in a sandwich attack require gas, and the total cost may exceed the profit
  • Transaction decoding errors: Transactions in the mempool can be any contract call; decoding with the wrong ABI leads to misjudging opportunities or missing them
  • Non-atomic risk: Without using Flashbots bundles, transactions in the public mempool can be frontrun (others see your transaction and copy it)
  • Token approval security: The wallet running an MEV bot needs to approve multiple tokens and router contracts -- if the wallet's private key is leaked, all funds are at risk

5. Why the Pitfalls Occur

Latency competition is the most fundamental challenge of MEV. On Ethereum with 12-second block times, there is only one chance per block. Searcher networks (such as bloXroute, Eden Network) provide faster mempool data than public nodes, and professional searchers have established direct connections with validators (PBS pipelines). The WebSocket monitoring in mev-bot.js is only a starting point -- the real competition happens at sub-millisecond levels.

The gas bidding spiral stems from the zero-sum nature of MEV: for each arbitrage opportunity, only one searcher can win. If the opportunity is worth 0.1 ETH, searchers are willing to bid up to 0.099 ETH in priority fees (or validator bribes). As more searchers enter the market, profit margins approach zero -- the economics of perfect competition playing out in real-time on-chain. The minProfitEth = 0.01 in mev-bot.js is a reasonable lower bound, but for highly competitive trading pairs (like WETH-USDC), a higher threshold may be needed.

Simulation vs execution divergence ("revert risk") is a technical challenge unique to MEV. eth_call simulates using the current block's state, but when the bundle actually executes, it may be included in the next or a later block -- during which time other transactions have already changed DEX reserves, lending positions, and other state. Flashbots' eth_callBundle attempts to mitigate this by simulating on a specific block number, but it cannot eliminate the issue entirely.

6. How to Resolve the Pitfalls

Latency Optimization:

  • Use dedicated nodes (not shared RPCs) for minimum latency
  • Use WebSocket instead of polling to receive real-time mempool data
  • Deploy nodes in the same region as validators (e.g., AWS us-east-1)
  • Precompute and cache DEX reserve data to reduce RPC calls

Gas Strategy:

  • Use eth_maxPriorityFeePerGas to query the current priority fee market rate
  • Set a maximum acceptable gas budget; abandon the opportunity if exceeded
  • Include a validator tip transaction in the bundle paid directly to block.coinbase
  • Use historical gas data analysis to optimize bidding strategy

Simulation Safety:

  • Submit the bundle immediately after eth_callBundle simulation, shortening the simulate-submit window
  • Set a buffer (e.g., require profit > GasCost * 1.5)
  • Submit the same bundle to multiple relays simultaneously (Flashbots + bloXroute + Eden)
  • Include the same transaction across multiple blocks in the bundle (Flashbots supports multi-block range specification)

Security Practices (from mev-bot.js's risk checklist):

  • Use an independent low-balance wallet; do not store large amounts of funds in the MEV bot wallet
  • Simulate and confirm profit with eth_call before every transaction
  • Set slippage protection (e.g., 0.5% slippage)
  • Monitor execution results for all transactions, logging for audit purposes
  • Do not hardcode private keys in code (use environment variables or secure key management)

7. Technical Highlights

TechniqueDescription
Mempool MonitoringWebSocket subscription to pendingTransactions, discovering opportunities in real-time
AMM Arbitragex*y=k formula for calculating price differences across DEXes
Sandwich AttackFrontrun buy + victim trade + backrun sell
Liquidation DetectionMonitoring lending protocol health factors; trigger liquidation below threshold
Flashbots BundleAtomic bundles bypassing the public mempool, submitted directly to validators
Transaction Simulationeth_call/eth_callBundle to verify profit before submission
PBS PipelineProposer-Builder Separation; searchers submit bundles through builders
Gas BiddingPriority fee + validator bribe determining whether a bundle is included
Zero-Sum CompetitionOnly one searcher can win per opportunity
Security BoundariesIndependent wallet, simulation verification, slippage protection, private key management

Built with AiAda