Skip to content

MEV — The Dark Forest of Ethereum and How Arbitrage Bots Actually Work

Posted on:August 13, 2024 at 10:00 AM

In 2019, Daian et al. at Cornell published “Flash Boys 2.0” and coined the term MEV — originally Miner Extractable Value, later renamed to Maximal Extractable Value after Ethereum’s transition to proof-of-stake in 2022. They discovered something that many in DeFi had suspected but nobody had quantified: validators and miners could extract additional profit simply by reordering the transactions in a block. Since then, MEV has generated over $2 billion in extracted value on Ethereum alone.

Understanding MEV is essential for anyone building on or interacting with DeFi. It explains why your “reasonable” swap sometimes costs 2% more than expected. It explains the gas wars that locked out ordinary users. And it reveals an adversarial game theory layer that operates invisibly beneath every on-chain transaction.

Table of contents

Open Table of contents

What Is MEV?

When you submit a transaction to Ethereum, it enters the mempool — a public queue of pending transactions waiting to be included in a block. The block proposer (validator in PoS, miner in PoW) chooses which transactions to include and in what order.

By choosing the order carefully, a validator can make more money than just collecting gas fees. This extra extractable profit is MEV.

Three core MEV strategies:

  1. Arbitrage: Spot price differences between DEXs, trade to capture the spread
  2. Sandwich attacks: Front-run a large swap to profit from the price impact you cause
  3. Liquidations: Race to liquidate undercollateralized positions first (earns the liquidation bonus)

Strategy 1: DEX Arbitrage

This is the “good” MEV — it actually improves market efficiency.

Scenario: ETH/USDC on Uniswap V2 is at $2,000. ETH/USDC on SushiSwap is at $2,010 (due to recent trades). There’s a $10 price discrepancy.

An arbitrage bot sees this in the mempool (or monitors on-chain state) and constructs:

Transaction:
1. Borrow 200,000 USDC via flash loan (Aave, 0.05% fee)
2. Buy 100 ETH on Uniswap V2 with 200,000 USDC (cheap: $2,000/ETH)
3. Sell 100 ETH on SushiSwap → receive 201,000 USDC (expensive: $2,010/ETH)
4. Repay flash loan (200,000 + 100 USDC fee)
5. Keep profit: ~900 USDC ≈ $900 (minus gas)

This entire sequence executes atomically in one transaction. If any step fails (e.g., the price moved), the whole transaction reverts. No risk, no capital required.

The competitive dynamics: hundreds of bots monitor the same price discrepancies. They compete by bidding higher gas prices to get their transaction included first. This is a gas war — and it’s why during periods of high DeFi activity, Ethereum gas prices spike to hundreds of gwei.

Strategy 2: The Sandwich Attack

This is the predatory MEV. You submit a $50,000 USDC→ETH swap on Uniswap. A sandwich bot sees your transaction in the mempool:

The sandwich:

  1. Front-run: Bot submits a BUY ETH with higher gas → executes before yours, raises ETH price
  2. Victim transaction: Your swap executes at a worse price (you set 0.5% slippage tolerance, and the bot pushed price exactly to your limit)
  3. Back-run: Bot immediately sells the ETH it bought → profits from the price difference you created
Mempool (public, visible to all) Block (ordered by bot)
────────────────────────────── ──────────────────────────────────────
tx A: YOU USDC→ETH $50k ─────────────→ tx 1: BOT BUY ETH gas: 200 gwei ← front-run
gas: 50 gwei tx 2: YOU BUY ETH gas: 50 gwei ← victim
tx 3: BOT SELL ETH gas: 1 gwei ← back-run
Price timeline inside the block:
─────────────────────────────────────────────────────────────────
start after tx 1 after tx 2 after tx 3
ETH $2,000 → ETH $2,010 → ETH $2,060 → ETH $2,005
(bot buys, (you buy, (bot sells,
price up) price up more) price drops)
Bot P&L: bought at ~$2,000, sold at ~$2,060 → +$3,000 on $6M position
Your P&L: paid ~$2,010-$2,060 instead of $2,000 → ~$200 extracted from you

The bot’s profit scales with your swap size. Bigger swap = more price impact = bigger sandwich profit.

How to Defend Against Sandwich Attacks

  1. Lower slippage tolerance: Set 0.1-0.3% instead of the default 0.5-1%. Your transaction may fail more often in volatile markets, but sandwich attacks need enough room to be profitable.

  2. Use private mempools: MEV Blocker, Flashbots Protect, or direct submission through a trusted builder bypasses the public mempool entirely. Your transaction goes directly to validators without being visible to sandwich bots.

  3. Use aggregators: 1inch, Paraswap, and Cowswap route through multiple pools, reducing per-pool price impact and making sandwiching less profitable.

  4. Cowswap / batch auctions: CowSwap uses off-chain batch auctions (CoW Protocol). Your order is matched against other orders off-chain, with MEV protection built-in.

Strategy 3: Liquidation Bots

Lending protocols (Aave, Compound) allow users to borrow against collateral. When collateral value drops below a threshold (the “health factor”), the position becomes liquidatable — anyone can repay the debt and receive the collateral at a discount (5-10% bonus).

During volatile markets (e.g., ETH drops 20% in an hour), hundreds of positions become liquidatable simultaneously. Every second of delay means the collateral continues dropping. Liquidation bots compete to be first:

// Simplified liquidation bot loop
while (true) {
const unhealthyPositions = await aave.getUnhealthyPositions();
for (const position of unhealthyPositions) {
if (profitAfterGas(position) > MIN_PROFIT) {
await submitLiquidation(position, { gasPrice: urgentGasPrice });
}
}
await sleep(100); // Check every 100ms
}

The gas wars during March 2020 (“Black Thursday”) were primarily liquidation bots competing. Ethereum became essentially unusable for ordinary users for hours.

The MEV Infrastructure: Flashbots

The chaotic gas wars of 2020 were unsustainable. Enter Flashbots — a research and development organization that created a private transaction ordering channel.

Flashbots MEV-Boost architecture:

  1. Searchers (arbitrage bots): Find MEV opportunities, package them as “bundles”
  2. Builders: Accept bundles from searchers, construct full blocks, maximize profit
  3. Relays: Trust layer between builders and validators
  4. Validators: Receive blocks from relays, include the most profitable one

Searchers send their MEV bundles directly to builders — bypassing the public mempool. They specify:

// Flashbots bundle: atomic arbitrage with coinbase payment
contract FlashbotsArbitrage {
function execute(bytes calldata data) external {
// 1. Execute arbitrage (buy low, sell high)
uint256 profit = _doArbitrage(data);
// 2. Pay validator for block inclusion
uint256 bribe = profit * 90 / 100; // Keep 10%, give 90% to validator
block.coinbase.transfer(bribe);
}
}

The result: gas wars largely disappeared (searchers pay validators directly instead of bidding up gas), validators receive more revenue, and MEV became semi-institutionalized.

The Numbers

MEV extracted on Ethereum since 2020 (from Flashbots MEV-Explore data):

YearMEV ExtractedDominant Strategy
2020~$100MLiquidations (Black Thursday)
2021~$550MArbitrage + Sandwich
2022~$680MArbitrage (volatile markets)
2023~$290MArbitrage + NFT MEV
2024~$450M+Arbitrage + PBS MEV-Boost

These are only the detected on-chain MEV. Private MEV (via MEV-Boost, private builders) is substantially larger and harder to measure.

Writing a Simple Arbitrage Bot

For educational purposes — this is the skeleton of a real arbitrage searcher:

import { ethers } from 'ethers';
const UNISWAP_V2_ROUTER = '0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D';
const SUSHISWAP_ROUTER = '0xd9e1cE17f2641f24aE83637ab66a2cca9C378B9F';
async function findArbitrage(token0: string, token1: string, amount: bigint) {
const [uniswapPrice, sushiswapPrice] = await Promise.all([
getPrice(UNISWAP_V2_ROUTER, token0, token1, amount),
getPrice(SUSHISWAP_ROUTER, token0, token1, amount),
]);
const spread = uniswapPrice > sushiswapPrice
? uniswapPrice - sushiswapPrice
: sushiswapPrice - uniswapPrice;
const gasEstimate = 200_000n; // gas units
const gasPrice = await provider.getGasPrice();
const gasCost = gasEstimate * gasPrice;
if (spread > gasCost * 2n) { // 2x gas as minimum profit threshold
return {
profitable: true,
buyOn: uniswapPrice < sushiswapPrice ? 'uniswap' : 'sushiswap',
profit: spread - gasCost,
};
}
return { profitable: false };
}

A production bot also handles: flash loans (capital-free execution), bundle construction for Flashbots, gas price bidding strategy, nonce management for concurrent transactions, and monitoring for failed transactions.

MEV’s Impact on Protocol Design

MEV has fundamentally changed how DeFi protocols are designed:

MEV is not a bug — it’s an emergent property of transparent, composable smart contracts. The more sophisticated the DeFi ecosystem becomes, the more sophisticated the MEV extractors become. It’s an arms race, and understanding it is prerequisite to building anything serious on-chain.