Keyboard shortcuts

Press ← or β†’ to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Part 3 β€” Module 5: MEV Deep Dive

Difficulty: Advanced

Estimated reading time: ~30 minutes | Exercises: ~2 hours

πŸ“š Table of Contents

  1. The Invisible Tax
  2. Sandwich Attacks: Anatomy & Math
  3. Build Exercise: Sandwich Attack Simulation
  4. Arbitrage & Liquidation MEV
  5. The Post-Merge MEV Supply Chain
  6. MEV Protection Mechanisms
  7. MEV-Aware Protocol Design
  8. Build Exercise: MEV-Aware Dynamic Fee Hook
  9. Summary: MEV Defense & Protocol Design
  10. Resources

πŸ’‘ The Invisible Tax

Maximal Extractable Value (MEV) is the invisible tax on every DeFi transaction. If you swap on a DEX, someone might sandwich you. If you submit a liquidation, someone might front-run it. If you create a new pool, someone will arbitrage it within the same block.

Understanding MEV is essential for both sides: as a protocol designer (minimizing user harm) and as a DeFi developer (writing MEV-aware code). The AMMs module (Part 2 Module 2) introduced sandwich attacks β€” this module covers the full picture: attack taxonomy, the post-Merge supply chain, protection mechanisms, and how to design protocols that resist extraction.

Why this matters for you:

  • Every DeFi protocol you build will face MEV β€” designing around it is non-negotiable
  • MEV knowledge is a top interview differentiator β€” teams want engineers who think about ordering attacks
  • The solver/searcher space is one of the hottest hiring areas in DeFi right now
  • Module 4’s intent paradigm was designed specifically to combat MEV β€” this module explains what it’s combating

πŸ’‘ Concept: What is MEV?

Originally β€œMiner Extractable Value” (pre-Merge), now Maximal Extractable Value β€” the total value that can be extracted by anyone who controls transaction ordering within a block.

The core insight: Transaction ordering affects outcomes. If you can see a pending transaction and place yours before or after it, you can capture value. MEV exists because Ethereum’s mempool is public β€” anyone can see pending transactions and reorder them for profit.

Scale: Billions of dollars extracted since DeFi Summer (2020). Flashbots MEV-Explore tracks historical extraction.

The MEV Spectrum

Not all MEV is harmful. Understanding the spectrum is critical for protocol design:

BENIGN ──────────────────────────────────────────── HARMFUL
  β”‚                    β”‚                    β”‚            β”‚
  Arbitrage        Liquidation         Backrunning   Sandwich
  β”‚                    β”‚                    β”‚            β”‚
  Keeps prices     Keeps protocols      Captures       Directly
  aligned across   solvent β€” socially   leftover       harms users
  DEXes            useful               value          (the "tax")
TypeMechanismImpactWho Profits
ArbitrageBuy low on DEX A, sell high on DEX BAligns prices across markets β€” benignSearcher
LiquidationRace to liquidate undercollateralized positionsKeeps lending protocols solvent β€” usefulSearcher (bonus)
BackrunningPlace tx after a large trade to capture leftover valueMild β€” doesn’t affect the target txSearcher
JIT LiquidityFlash-add/remove concentrated liquidity around a swapTakes LP fees from passive LPsJIT LP
FrontrunningCopy a profitable tx and submit with higher prioritySteals opportunities β€” harmfulSearcher
SandwichFrontrun + backrun a user’s swapDirectly extracts from user β€” most harmfulSearcher
Cross-domainArbitrage between L1 ↔ L2 or L2 ↔ L2Growing with L2 adoptionSequencer/Searcher

πŸ’‘ Sandwich Attacks: Anatomy & Math

πŸ’‘ Concept: How a Sandwich Attack Works

This is the most important MEV attack to understand β€” it directly costs users money on every unprotected swap.

Setup: User submits a swap to the public mempool. Attacker sees it, calculates profit, and submits a front-run + back-run that wraps the user’s transaction:

Block N:
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚  tx 1: Attacker buys ETH         (front-run)       β”‚
β”‚  tx 2: User buys ETH             (victim swap)     β”‚
β”‚  tx 3: Attacker sells ETH        (back-run)        β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
         ↑ Attacker controls ordering via higher gas / builder tip

πŸ” Deep Dive: Sandwich Profit Calculation

Pool: 100 ETH / 200,000 USDC (spot price: $2,000/ETH) User: Buying ETH with 20,000 USDC (expects ~10 ETH) Attacker: Front-runs with 10,000 USDC

Without sandwich β€” user swaps alone:

User output = 100 Γ— 20,000 / (200,000 + 20,000)
            = 2,000,000 / 220,000
            = 9.091 ETH

Effective price: $2,200/ETH  (9.1% slippage on a large trade)

With sandwich β€” three transactions in sequence:

Step 1: FRONT-RUN β€” Attacker buys ETH with 10,000 USDC
────────────────────────────────────────────────────
  attacker_eth = 100 Γ— 10,000 / (200,000 + 10,000)
               = 1,000,000 / 210,000
               = 4.762 ETH

  Pool after:  (95.238 ETH, 210,000 USDC)
               ↑ Less ETH available, price pushed UP

Step 2: USER SWAP β€” User buys ETH with 20,000 USDC
────────────────────────────────────────────────────
  user_eth = 95.238 Γ— 20,000 / (210,000 + 20,000)
           = 1,904,760 / 230,000
           = 8.282 ETH         ← 0.809 ETH LESS than without sandwich

  Pool after:  (86.956 ETH, 230,000 USDC)

Step 3: BACK-RUN β€” Attacker sells 4.762 ETH for USDC
────────────────────────────────────────────────────
  attacker_usdc = 230,000 Γ— 4.762 / (86.956 + 4.762)
                = 1,095,260 / 91.718
                = 11,940 USDC

  Attacker profit: 11,940 - 10,000 = 1,940 USDC

Summary:

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚  User loss:       9.091 - 8.282 = 0.809 ETH     β”‚
β”‚                   β‰ˆ $1,618 at $2,000/ETH         β”‚
β”‚                                                   β”‚
β”‚  Attacker profit: 11,940 - 10,000 = $1,940       β”‚
β”‚  Attacker gas:    ~$3-10                          β”‚
β”‚  Attacker net:    ~$1,930                         β”‚
β”‚                                                   β”‚
β”‚  The user paid an invisible $1,618 "sandwich tax" β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

Key insight: Attacker profit ($1,940) exceeds user loss ($1,618). This isn’t a contradiction β€” the pool’s nonlinear pricing creates value redistribution. The pool ends with different reserves in each scenario; LPs implicitly absorb part of the cost.

What determines sandwich profitability?

Profitable when: attacker_profit > gas_cost

Profit scales with:
  βœ“ User's trade size (larger trade = more price impact to exploit)
  βœ“ Pool's illiquidity (shallower pool = more price impact per unit)
  βœ“ User's slippage tolerance (wider tolerance = more room to extract)

Profit is limited by:
  βœ— Gas costs (two extra transactions)
  βœ— User's slippage limit (if sandwich pushes beyond limit, user tx reverts)
  βœ— Competition (other sandwich bots bid up gas, compressing profit)

Slippage as Defense

User's slippage = 0.5%:
  User expects β‰₯ 9.091 Γ— 0.995 = 9.046 ETH
  Sandwich gives user 8.282 ETH β†’ REVERTS (below minimum)
  Sandwich attack fails βœ“

User's slippage = 10%:
  User expects β‰₯ 9.091 Γ— 0.90 = 8.182 ETH
  Sandwich gives user 8.282 ETH β†’ passes (above minimum)
  Sandwich attack succeeds βœ—

Tight slippage makes sandwiches unprofitable. But too tight β†’ your transaction reverts on normal volatility. This tension drives the move to intent-based execution (Module 4).

πŸ’» Quick Try:

Deploy in Remix to see the sandwich tax:

contract SandwichDemo {
    uint256 public x = 100e18;     // 100 ETH
    uint256 public y = 200_000e18; // 200,000 USDC

    function cleanSwap(uint256 usdcIn) external view returns (uint256 ethOut) {
        return x * usdcIn / (y + usdcIn);
    }

    function sandwichedSwap(uint256 usdcIn, uint256 frontrunUsdc)
        external view returns (uint256 userEth, uint256 attackerProfit)
    {
        // Step 1: front-run
        uint256 atkEth = x * frontrunUsdc / (y + frontrunUsdc);
        uint256 x1 = x - atkEth;
        uint256 y1 = y + frontrunUsdc;
        // Step 2: user swap
        userEth = x1 * usdcIn / (y1 + usdcIn);
        uint256 x2 = x1 - userEth;
        uint256 y2 = y1 + usdcIn;
        // Step 3: back-run
        uint256 atkUsdc = y2 * atkEth / (x2 + atkEth);
        attackerProfit = atkUsdc > frontrunUsdc ? atkUsdc - frontrunUsdc : 0;
    }
}

Try: cleanSwap(20000e18) β†’ 9.091 ETH. Then sandwichedSwap(20000e18, 10000e18) β†’ 8.282 ETH + $1,940 profit. Now try a tiny trade: sandwichedSwap(100e18, 10000e18) β€” profit drops to nearly zero. Sandwiches only work on trades large enough to create exploitable price impact.

πŸ”— DeFi Pattern Connection

Where sandwich risk matters in DeFi:

  1. AMM swaps β€” the primary attack surface (Part 2 Module 2)
  2. Liquidation collateral sales β€” liquidators’ swap of seized collateral can be sandwiched
  3. Vault rebalances β€” automated vault strategies that swap on-chain are sandwich targets
  4. Oracle updates β€” TWAP oracles can be manipulated through related ordering attacks
  5. Module 4’s intent paradigm β€” designed specifically to eliminate the sandwich surface by moving execution off-chain

πŸ’Ό Job Market Context

What DeFi teams expect you to know:

  1. β€œExplain how a sandwich attack works and how to prevent it.”
    • Good answer: β€œAn attacker front-runs and back-runs a user’s swap. The front-run pushes the price up, the user swaps at a worse rate, and the attacker sells for profit. Prevention: tight slippage limits or private mempools.”
    • Great answer: β€œA sandwich exploits the public mempool and AMM nonlinear price impact. The attacker calculates the optimal front-run amount β€” enough to shift the price but within the user’s slippage tolerance β€” then submits front-run, victim, back-run as an atomic bundle to a builder. Prevention exists at multiple levels: user-level tight slippage, private RPCs like Flashbots Protect, application-level intent systems like UniswapX where there’s no on-chain tx to sandwich, and protocol-level V4 hooks that surcharge same-block opposite-direction swaps.”

Interview Red Flags:

  • 🚩 Thinking MEV only means sandwich attacks β€” it’s a broad spectrum including arb, liquidation, backrunning, and JIT liquidity
  • 🚩 Not knowing that slippage tolerance is the primary defense variable β€” and that too-tight slippage causes reverts on normal volatility
  • 🚩 Describing sandwich prevention without mentioning the intent paradigm (UniswapX, CoW Protocol) β€” that’s the direction the industry is moving

Pro tip: When discussing sandwiches, show you understand the economics: attacker profit scales with user trade size and pool illiquidity, and is bounded by the user’s slippage tolerance. Explaining why a sandwich is profitable (not just how it works) immediately signals deeper understanding.


🎯 Build Exercise: Sandwich Attack Simulation

Workspace: workspace/src/part3/module5/

Build a test-only exercise that simulates a sandwich attack on a simple constant-product pool, measures the extraction, and verifies that slippage protection defeats it.

What you’ll implement:

  • SimplePool β€” a minimal constant-product AMM with swap()
  • SandwichBot β€” a contract that executes front-run β†’ victim swap β†’ back-run atomically
  • Test scenarios measuring user loss and attacker profit
  • Slippage defense: verify that tight slippage makes sandwich revert

Concepts exercised:

  • Sandwich attack mechanics (the three-step pattern)
  • AMM price impact math applied to adversarial scenarios
  • Slippage as a defense mechanism
  • Thinking adversarially about transaction ordering

🎯 Goal: Prove quantitatively that sandwiches work on large trades with loose slippage, and fail against tight slippage limits.

Run: forge test --match-contract SandwichSimTest -vvv


πŸ“‹ Summary: MEV Attacks

βœ“ Covered:

  • MEV as the invisible tax on DeFi transactions β€” value extracted through transaction ordering
  • The MEV spectrum from benign (arbitrage, liquidation) to harmful (sandwich attacks)
  • Sandwich attack mechanics: front-run to push price, victim swap at worse rate, back-run to capture profit
  • Price impact math in constant-product AMMs and how attackers calculate optimal extraction
  • Slippage tolerance as the primary user defense β€” tight limits make sandwiches revert
  • AMM vulnerability to ordering-based extraction due to public mempool visibility

Next: Arbitrage and liquidation MEV β€” the β€œgood” side of the spectrum that keeps prices aligned and protocols solvent.


πŸ’‘ Arbitrage & Liquidation MEV

πŸ’‘ Concept: The β€œGood” MEV

Not all MEV harms users. Arbitrage and liquidation MEV serve essential functions in DeFi.

Arbitrage β€” keeping prices aligned:

// Simplified arbitrage logic (searcher contract)
contract SimpleArbitrage {
    function execute(
        IPool poolA,      // ETH is cheap here
        IPool poolB,      // ETH is expensive here
        IERC20 usdc,
        IERC20 weth,
        uint256 amountIn
    ) external {
        // Buy ETH cheap on pool A
        usdc.approve(address(poolA), amountIn);
        uint256 ethReceived = poolA.swap(address(usdc), address(weth), amountIn);

        // Sell ETH expensive on pool B
        weth.approve(address(poolB), ethReceived);
        uint256 usdcReceived = poolB.swap(address(weth), address(usdc), ethReceived);

        // Profit = output - input (minus gas + builder tip)
        require(usdcReceived > amountIn, "Not profitable");
    }
}

With flash loans β€” capital-free arbitrage:

// The most common searcher pattern: flash-funded arb
// (Simplified interfaces β€” real DEX routers have different function signatures)
function onFlashLoan(
    address, address token, uint256 amount, uint256 fee, bytes calldata data
) external returns (bytes32) {
    // Received `amount` tokens (no upfront capital needed)
    (address poolA, address poolB, address tokenB) = abi.decode(data, (address, address, address));

    // Route through profitable path
    IERC20(token).approve(poolA, amount);
    uint256 intermediate = IPool(poolA).swap(token, tokenB, amount);

    IERC20(tokenB).approve(poolB, intermediate);
    uint256 output = IPool(poolB).swap(tokenB, token, intermediate);

    // output > amount + fee β†’ profitable
    IERC20(token).approve(msg.sender, amount + fee);
    return keccak256("ERC3156FlashBorrower.onFlashLoan");
    // Profit: output - amount - fee (kept in this contract)
}

Why arbitrage is socially useful: Without arb bots, the same token would trade at wildly different prices across DEXes. Arbitrage keeps prices consistent β€” a public good that happens to be profitable.

Liquidation MEV β€” keeping protocols solvent:

Lending protocols (Aave, Compound β€” Part 2 Module 4) rely on liquidation bots racing to close undercollateralized positions. The liquidation bonus (5-10%) is the MEV incentive. Without it, bad debt accumulates and protocols become insolvent.

User's position goes underwater:
  Collateral: 1 ETH ($2,000) | Debt: $1,800 USDC | Health Factor < 1

  Bot A sees liquidation opportunity β†’ submits tx with 30 gwei priority
  Bot B sees same opportunity       β†’ submits tx with 35 gwei priority
  Bot C sees same opportunity       β†’ submits tx with 40 gwei priority
                                                  ↑ Wins β€” gas priority auction

  Winner: repays $900 debt, receives $945 of ETH (5% bonus)
  Profit: $45 - gas cost

The gas auction is β€œwasteful” (bots overpay for gas), but the underlying liquidation is essential. This is why some protocols use Dutch auctions for liquidations (Part 2 Module 9 capstone) β€” they replace gas priority auctions with time-based price discovery.


πŸ’‘ The Post-Merge MEV Supply Chain

πŸ’‘ Concept: Proposer-Builder Separation (PBS)

Before the Merge, miners both built and proposed blocks β€” they could extract MEV directly. Post-Merge, Proposer-Builder Separation splits these roles:

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”     β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”     β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚  Users    β”‚     β”‚  Searchers   β”‚     β”‚  Builders    β”‚
β”‚           β”‚     β”‚              β”‚     β”‚              β”‚
β”‚ Submit    │────→│ Find MEV     │────→│ Construct    β”‚
β”‚ to public β”‚     β”‚ opportunitiesβ”‚     β”‚ full blocks  β”‚
β”‚ mempool   β”‚     β”‚              β”‚     β”‚ from txs +   β”‚
β”‚           β”‚     β”‚ Submit       β”‚     β”‚ bundles      β”‚
β”‚   OR      β”‚     β”‚ "bundles"    β”‚     β”‚              β”‚
β”‚           β”‚     β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜     β”‚ Bid to       β”‚
β”‚ Submit to β”‚                          β”‚ proposer     β”‚
β”‚ private   β”‚                          β””β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”˜
β”‚ mempool   β”‚                                 β”‚
β”‚ (protect) β”‚                          β”Œβ”€β”€β”€β”€β”€β”€β–Όβ”€β”€β”€β”€β”€β”€β”€β”
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜                          β”‚  Relays      β”‚
                                       β”‚              β”‚
                                       β”‚ Blind escrow β”‚
                                       β”‚ (proposer    β”‚
                                       β”‚ can't peek)  β”‚
                                       β””β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”˜
                                              β”‚
                                       β”Œβ”€β”€β”€β”€β”€β”€β–Όβ”€β”€β”€β”€β”€β”€β”€β”
                                       β”‚  Proposers   β”‚
                                       β”‚ (Validators) β”‚
                                       β”‚              β”‚
                                       β”‚ Pick highest β”‚
                                       β”‚ bid block    β”‚
                                       β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

Each role in detail:

Searchers β€” the MEV hunters:

  • Bots that scan the mempool for profitable opportunities (arb, liquidation, sandwich)
  • Write smart contracts that atomically capture value
  • Submit bundles to builders β€” ordered transaction sets that execute atomically
  • Revenue: MEV profit minus gas cost minus builder tip

Builders β€” the block architects:

  • Receive user transactions from the mempool + searcher bundles
  • Construct the most valuable block possible (optimize transaction ordering)
  • Bid to proposer: β€œMy block earns you X ETH”
  • Top builders (2025): Titan, BeaverBuild, Flashbots (builder), rsync
  • Centralization concern: top 3 builders construct the majority of blocks

Relays β€” the trusted middlemen:

  • Sit between builders and proposers
  • Critical property: proposer can’t see block contents until they commit to it
  • Prevents proposers from stealing MEV by peeking at the block and rebuilding it themselves
  • Major relays: Flashbots, bloXroute, Ultra Sound, Aestus

Proposers (Validators) β€” the block selectors:

  • Run MEV-Boost to connect to the relay network
  • Simply pick the block with the highest bid β€” no MEV knowledge needed
  • Revenue: execution layer base fee + builder’s bid

Economics of the Supply Chain

Example: $10,000 MEV opportunity in a block

  Searcher extracts:    $10,000 gross
  β†’ Tips builder:       -$7,000 (70% β€” bidding war among searchers)
  β†’ Gas costs:          -$500
  Searcher profit:      $2,500

  Builder receives:     $7,000 from searchers (+ regular user tx fees)
  β†’ Bids to proposer:  -$6,000 (bidding war among builders)
  Builder profit:       $1,000

  Proposer receives:    $6,000 block bid
  (No work beyond running MEV-Boost)

The key insight: Competition at each level drives most MEV to the proposer (validator). Searcher margins are thin; builder margins are thinner. Most value flows β€œup” the supply chain through competitive bidding.

Centralization Concerns

This is the most debated topic in Ethereum governance:

ConcernWhy It MattersProposed Solutions
Builder centralizationFew builders = potential censorshipInclusion lists, decentralized builders
Relay trustRelays can censor or front-runRelay diversity, enshrined PBS (ePBS)
OFAC complianceBuilders/relays may exclude sanctioned txsInclusion lists (force-include txs)
Latency advantageBuilders closer to validators win moreTiming games research, committee-based PBS

Inclusion lists (actively being designed): Proposers specify transactions that MUST be included in the next block, regardless of builder preferences. This prevents censorship while preserving the efficiency of builder markets.

πŸ“– How to Study: Flashbots Architecture

  1. Start with MEV-Boost docs β€” how validators connect to the relay network
  2. Read the Builder API spec β€” how builders submit blocks
  3. Study Flashbots Protect β€” the user-facing privacy layer
  4. Look at MEV-Share β€” how users capture MEV rebates
  5. Skip relay internals initially β€” focus on the flow: user β†’ searcher β†’ builder β†’ relay β†’ proposer

πŸ” Code: MEV-Boost | Flashbots Builder

πŸ’Ό Job Market Context

What DeFi teams expect you to know:

  1. β€œWhat is Proposer-Builder Separation and why does it matter?”
    • Good answer: β€œPBS separates block construction from block proposal. Builders create blocks, proposers select the highest bid. This prevents validators from directly extracting MEV.”
    • Great answer: β€œPBS is Ethereum’s architectural response to MEV centralization. Post-Merge, specialized builders construct optimized blocks from user transactions plus searcher bundles, and proposers simply select the highest bid via MEV-Boost. Relays sit in between as blind escrows so proposers can’t steal MEV. Competition at each layer drives most value up to the proposer. The current tension is builder centralization β€” top 3 builders produce the majority of blocks, creating censorship risk. The community is addressing this through inclusion lists and longer-term enshrined PBS (ePBS).”

Interview Red Flags:

  • 🚩 Not knowing about PBS or the post-Merge supply chain β€” this is foundational Ethereum infrastructure knowledge
  • 🚩 Confusing MEV privacy (hiding txs) with MEV elimination β€” arb and liquidation MEV is permanent and socially useful
  • 🚩 Not mentioning builder centralization or censorship risk as the current open problem in PBS

Pro tip: Mention the economic flow: searchers tip builders, builders bid to proposers, competition drives most value to validators. Showing you understand the incentive structure β€” not just the architecture diagram β€” signals that you think about mechanism design, not just code.


πŸ’‘ MEV Protection Mechanisms

πŸ’‘ Concept: Defending Against the Invisible Tax

Protection operates at four levels: transaction privacy, order flow auctions, application design, and cryptographic schemes.

Level 1: Transaction Privacy

Flashbots Protect β€” private transaction submission:

Standard flow (vulnerable):
  User β†’ Public Mempool β†’ Sandwich bots see it β†’ Sandwiched

Flashbots Protect flow:
  User β†’ Flashbots RPC β†’ Directly to builder β†’ No public visibility
  (Add https://rpc.flashbots.net to your wallet)

Trade-off: You trust Flashbots not to exploit your transaction. The transaction may take slightly longer to be included (fewer builders see it). Other private RPCs exist with different trust assumptions (bloXroute, MEV Blocker).

MEV Blocker (CoW Protocol):

  • Similar private submission
  • Additionally: searchers bid for the right to backrun your transaction
  • You receive a rebate from the backrun profit
  • Your tx is sandwich-protected AND you earn from the MEV it creates

Level 2: Order Flow Auctions (OFA)

MEV-Share (Flashbots) β€” turning MEV from a tax into a rebate:

Without MEV-Share:
  User swap β†’ Public mempool β†’ Searcher sandwiches β†’ User loses $50

With MEV-Share:
  User swap β†’ MEV-Share (private) β†’ Searcher sees partial tx info
  β†’ Searcher bids $30 for backrun rights β†’ Bundle: user tx + backrun
  β†’ User receives rebate: $20 (configurable %)
  β†’ User's net MEV cost: -$20 (they EARNED from their own MEV)

How partial information sharing works:

  1. User sends tx to MEV-Share
  2. MEV-Share reveals hints to searchers (e.g., β€œa swap on Uniswap V3 ETH/USDC pool” β€” not the exact amount or direction)
  3. Searchers simulate potential backruns based on hints
  4. Searchers bid for the right to backrun
  5. Winning bundle: user tx β†’ searcher backrun
  6. User receives configured percentage of searcher’s profit

Level 3: Application-Level Protection

Intent-based systems (Module 4 connection):

This is the deepest connection in Part 3. Module 4’s entire intent paradigm exists because of MEV:

Why intents protect against MEV:
─────────────────────────────────
Traditional swap:
  User publishes: "swap(1 ETH, USDC, Uniswap, 0.3% pool)"
  β†’ Attacker sees EXACTLY what to sandwich

Intent-based:
  User signs: "I want β‰₯1900 USDC for 1 ETH"
  β†’ No on-chain tx in mempool β†’ nothing to sandwich
  β†’ Solver fills from private inventory or routes through private channels
  β†’ Settlement is atomic β€” by the time it's on-chain, it's already done

Batch auctions (CoW Protocol model):

  • Collect orders over a time window
  • Execute all at uniform clearing prices in a single transaction
  • No individual transaction to sandwich β€” the batch IS the atomic unit
  • Coincidence of Wants (CoW) matching means some trades never touch AMMs at all

Level 4: Cryptographic Protection

Commit-reveal schemes:

// Phase 1: User commits hash of their action (hidden)
mapping(address => bytes32) public commits;
mapping(address => uint256) public commitBlock;

function commit(bytes32 hash) external {
    commits[msg.sender] = hash;
    commitBlock[msg.sender] = block.number;
}

// Phase 2: User reveals after N blocks (can't be front-run)
function reveal(uint256 amount, bytes32 salt) external {
    require(block.number > commitBlock[msg.sender] + DELAY, "Too early");
    require(
        keccak256(abi.encodePacked(amount, salt)) == commits[msg.sender],
        "Invalid reveal"
    );
    delete commits[msg.sender];

    // Execute the action β€” safe from frontrunning
    _execute(msg.sender, amount);
}

Use cases: Governance votes, NFT mints, sealed-bid auctions β€” any action where seeing the intent enables extraction. Trade-off: Two transactions, delay between commit and reveal.

Threshold encryption (Shutter Network):

  • Transactions encrypted before submission
  • Decryption key revealed only after block ordering is committed
  • Prevents ALL forms of frontrunning (can’t frontrun what you can’t read)
  • Trade-off: requires a decryption committee (trust assumption), added latency

πŸ”— DeFi Pattern Connection

MEV protection across the curriculum:

ProtectionWhere It AppearsModule
Slippage limitsAMM swaps, vault withdrawalsPart 2 Modules 2, 7
Intent-based executionUniswapX, CoW ProtocolPart 3 Module 4
Dutch auction liquidationMakerDAO Dog, Part 2 capstonePart 2 Modules 6, 9
Oracle-based executionGMX perpetualsPart 3 Module 2
Batch settlementCoW ProtocolPart 3 Module 4
Time-weighted pricesTWAP oraclesPart 2 Module 3
Keeper delayGMX two-step executionPart 3 Module 2

πŸ’Ό Job Market Context

What DeFi teams expect you to know:

  1. β€œWhat’s the difference between MEV-Share and Flashbots Protect?”

    • Good answer: β€œFlashbots Protect hides your transaction from sandwich bots. MEV-Share goes further by letting searchers bid for backrun rights and giving users a rebate.”
    • Great answer: β€œThey’re different layers of the same stack. Protect is simple privacy β€” your tx goes to a private mempool, preventing sandwiches. MEV-Share adds an economic layer: your tx is still private from sandwich bots, but hints are revealed to searchers β€” enough to evaluate backrun opportunities, not enough to sandwich. Searchers competitively bid for backrun rights, and the user receives a configurable rebate. Protect eliminates the tax; MEV-Share eliminates the tax AND turns leftover MEV into user revenue.”
  2. β€œHow does cross-domain MEV work with L2s?”

    • Good answer: β€œPrice differences between L1 and L2 create arbitrage. L2 sequencers control ordering, creating L2-specific MEV.”
    • Great answer: β€œPrices on L2s lag mainnet by the sequencer’s batch submission delay, creating predictable arb windows. The centralized L2 sequencer is the de facto block builder and can extract MEV directly. This drives shared sequencing proposals that coordinate ordering across L2s, reducing cross-domain MEV. As L2 volume grows, cross-domain MEV is becoming dominant β€” which is why protocols like UniswapX V2 are building cross-chain intent settlement.”

Interview Red Flags:

  • 🚩 Saying β€œjust use a private mempool” without understanding the trust tradeoffs β€” you’re trusting Flashbots/bloXroute not to exploit your tx
  • 🚩 Not knowing the difference between privacy (hiding txs) and redistribution (MEV-Share rebates) β€” they solve different problems
  • 🚩 Ignoring cross-domain MEV when discussing L2s β€” it’s becoming the dominant extraction vector as volume moves off mainnet

Pro tip: When discussing MEV protection, frame it as a spectrum: privacy (Protect) prevents harm, order flow auctions (MEV-Share) turn harm into revenue, and intent systems (UniswapX) eliminate the attack surface entirely. Showing you understand the progression signals architectural thinking about MEV defense.


πŸ’‘ MEV-Aware Protocol Design

πŸ’‘ Concept: Building Protocols That Resist Extraction

Four design principles that every DeFi protocol should follow:

Principle 1: Minimize Information Leakage

Less visible = less extractable. If attackers can’t see what’s coming, they can’t front-run it.

  • Private execution paths β€” route through private mempools or intent systems
  • Encrypted transactions β€” commit-reveal or threshold encryption
  • Delayed revelation β€” oracle-based execution (GMX: submit order β†’ keeper fills at oracle price later)

Principle 2: Reduce Ordering Dependence

If transaction order doesn’t matter, MEV disappears.

  • Batch operations β€” CoW Protocol’s batch auctions execute at uniform prices regardless of order
  • Frequent batch auctions β€” academic proposal: discrete time intervals instead of continuous matching
  • Time-weighted execution β€” TWAP orders spread impact across blocks, reducing per-block extraction

Principle 3: Internalize MEV

Instead of MEV leaking to external searchers β†’ capture and redistribute it.

Uniswap V4 hooks β€” dynamic MEV fees:

/// @notice A V4-style hook that charges higher fees on suspected MEV swaps
contract MEVFeeHook {
    struct BlockSwapInfo {
        bool hasSwapZeroForOne;   // swapped token0 β†’ token1
        bool hasSwapOneForZero;   // swapped token1 β†’ token0
    }

    // Track swap directions per pool per block
    mapping(bytes32 => mapping(uint256 => BlockSwapInfo)) public blockSwaps;

    /// @notice Called before each swap β€” returns dynamic fee
    function getDynamicFee(
        bytes32 poolId,
        bool zeroForOne
    ) external returns (uint24 fee) {
        BlockSwapInfo storage info = blockSwaps[poolId][block.number];

        // If opposite-direction swap already happened β†’ likely sandwich
        bool isSuspicious = zeroForOne
            ? info.hasSwapOneForZero
            : info.hasSwapZeroForOne;

        // Record this swap's direction
        if (zeroForOne) info.hasSwapZeroForOne = true;
        else info.hasSwapOneForZero = true;

        // Normal swap: 0.3%  |  Suspicious: 1.0%
        return isSuspicious ? 10000 : 3000;
    }
}

The intuition: If the same pool sees a buy AND a sell in the same block, that’s the signature of a sandwich. Charging the second swap a higher fee makes the sandwich unprofitable while leaving normal trades unaffected.

Osmosis ProtoRev β€” protocol-owned backrunning:

Standard model:
  External searcher captures arb β†’ profit leaves the protocol

ProtoRev model:
  Protocol detects arb opportunities after each swap
  Protocol captures the backrun profit itself
  Revenue β†’ community pool (protocol treasury)
  Result: MEV stays in the ecosystem instead of leaking

Principle 4: MEV Taxes (Paradigm Research)

A powerful theoretical framework: make fees proportional to the priority fee the transaction pays.

Normal user swap:
  Priority fee: 1 gwei β†’ Swap fee: 0.01% β†’ Cheap execution

MEV bot sandwich:
  Priority fee: 50 gwei β†’ Swap fee: 0.5% β†’ Expensive execution
  (Most MEV captured by LPs via the higher fee)

Why it works: MEV extraction requires transaction ordering priority. Priority requires higher gas bids. If swap fees scale with gas bids, MEV extractors pay proportionally more β€” and that value goes to LPs instead of searchers. Ordinary users with low-priority transactions pay minimal fees.

πŸ” Read: Paradigm β€” Priority Is All You Need β€” the full MEV tax framework

πŸ’» Quick Try:

Deploy in Remix to experiment with commit-reveal protection:

contract CommitRevealDemo {
    mapping(address => bytes32) public commits;

    function getHash(uint256 bid, bytes32 salt) external pure returns (bytes32) {
        return keccak256(abi.encodePacked(bid, salt));
    }

    function commit(bytes32 hash) external {
        commits[msg.sender] = hash;
    }

    function reveal(uint256 bid, bytes32 salt)
        external view returns (bool valid)
    {
        return keccak256(abi.encodePacked(bid, salt)) == commits[msg.sender];
    }
}

Try: call getHash(1000, 0xdead000000000000000000000000000000000000000000000000000000000000) β†’ copy the returned hash β†’ commit(hash) β†’ reveal(1000, 0xdead...) β†’ returns true. The bid was hidden until reveal. This is how governance votes and sealed-bid auctions prevent frontrunning.

πŸ’Ό Job Market Context

What DeFi teams expect you to know:

  1. β€œHow would you design a protocol to minimize MEV extraction?”
    • Good answer: β€œUse batch auctions, private execution, and tight slippage controls to reduce the MEV surface.”
    • Great answer: β€œFour principles: (1) Minimize information leakage β€” route through intents or private channels. (2) Reduce ordering dependence β€” batch operations so tx order doesn’t affect outcomes. (3) Internalize MEV β€” use V4 hooks or MEV taxes to capture extraction value for LPs. (4) Time-weight operations β€” spread large actions via TWAP execution to reduce per-block extractable value. The key mindset is: assume adversarial ordering and design so that ordering doesn’t affect outcomes.”

Interview Red Flags:

  • 🚩 Not connecting MEV to protocol design decisions β€” every swap, liquidation, and vault rebalance has an MEV surface
  • 🚩 Only knowing defensive patterns (slippage, privacy) without knowing internalization (dynamic fees, MEV taxes, protocol-owned backrunning)
  • 🚩 Thinking MEV can be eliminated rather than redirected β€” the value always goes somewhere; good design chooses where

Pro tip: The strongest signal of MEV expertise is understanding that MEV can’t be eliminated β€” only redirected. Protocol designers choose WHERE the value goes: to searchers (bad), to validators (neutral), or back to users/LPs (good). Showing you think about this tradeoff immediately separates you from candidates who only know the attack taxonomy.


🎯 Build Exercise: MEV-Aware Dynamic Fee Hook

Workspace: workspace/src/part3/module5/

Implement a simplified V4-style hook that detects potential sandwich patterns and applies a dynamic fee surcharge.

What you’ll implement:

  • MEVFeeHook β€” tracks swap directions per pool per block
  • beforeSwap() β€” detects opposite-direction swaps in the same block and returns a dynamic fee (normal or surcharge)
  • isSandwichLikely() β€” view function that checks whether both swap directions occurred in the current block
  • Test scenarios: normal swaps (low fee) vs sandwich-pattern swaps (high fee)

Concepts exercised:

  • MEV detection heuristics (opposite-direction swaps in same block)
  • Dynamic fee mechanism design
  • The MEV internalization principle (capturing MEV for LPs)
  • Uniswap V4 hook design patterns

🎯 Goal: Build a fee mechanism where normal users pay 0.3% but sandwich bots effectively pay 1%+, making the attack unprofitable.

Run: forge test --match-contract MEVFeeHookTest -vvv


πŸ“‹ Summary: MEV Defense & Protocol Design

βœ“ Covered:

  • Post-Merge MEV supply chain: searchers, builders, relays, and proposers (PBS)
  • MEV economics: competitive bidding drives most value up to validators
  • Flashbots ecosystem: Protect (private mempool), MEV-Share (order flow auctions with rebates)
  • Protection mechanisms: transaction privacy, commit-reveal, batch auctions, threshold encryption
  • Intent-based execution as the deepest MEV defense (Module 4 connection)
  • MEV-aware protocol design: minimize info leakage, reduce ordering dependence, internalize MEV
  • Dynamic fee hooks (V4 pattern) that detect sandwich signatures and surcharge suspected MEV
  • MEV taxes: priority-fee-proportional swap fees that redirect extraction to LPs

  • AMM price impact β†’ P2 M2 constant product formula, slippage calculations
  • Sandwich attacks on swaps β†’ P2 M2 swap mechanics, minimum output enforcement
  • Flash loan arbitrage β†’ P2 M5 flash loan patterns, atomic execution
  • Oracle manipulation β†’ P2 M3 TWAP vs spot price, multi-block attacks
  • Liquidation MEV β†’ P2 M4 liquidation mechanics, health factor thresholds
  • PBS and block building β†’ P3 M7 L2 sequencer ordering, centralized block production
  • Dynamic fees as MEV defense β†’ P2 M2 Uniswap V4 hooks, fee adjustment

πŸ“– Production Study Order

  1. Flashbots MEV-Boost relay β€” builder API, block submission flow
  2. Flashbots Protect RPC β€” private transaction submission, frontrunning protection
  3. MEV-Share contracts β€” programmable MEV redistribution, order flow auctions
  4. UniswapX β€” MEV-aware execution via Dutch auctions, filler network
  5. CoW Protocol β€” batch auctions as MEV defense, solver competition
  6. Notable MEV bot contracts on Etherscan β€” study real searcher strategies and gas optimization

πŸ“š Resources

Production Code

Documentation

Key Reading

πŸ“– How to Study: MEV Ecosystem

  1. Start with Ethereum.org MEV page β€” the 10,000-foot overview
  2. Read Flashbots Protect docs β€” understand user-facing protection
  3. Study MEV-Share design β€” understand order flow auctions
  4. Read Paradigm’s MEV Taxes paper β€” the theoretical framework
  5. Explore MEV-Explore β€” look at real extraction data
  6. Don’t try to build a searcher from docs alone β€” the competitive advantage is in execution speed and gas optimization, which is best learned by doing

Navigation: ← Module 4: DEX Aggregation | Part 3 Overview | Next: Module 6 β€” Cross-Chain & Bridges β†’