Part 3 β Module 5: MEV Deep Dive
Difficulty: Advanced
Estimated reading time: ~30 minutes | Exercises: ~2 hours
π Table of Contents
- The Invisible Tax
- Sandwich Attacks: Anatomy & Math
- Build Exercise: Sandwich Attack Simulation
- Arbitrage & Liquidation MEV
- The Post-Merge MEV Supply Chain
- MEV Protection Mechanisms
- MEV-Aware Protocol Design
- Build Exercise: MEV-Aware Dynamic Fee Hook
- Summary: MEV Defense & Protocol Design
- 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")
| Type | Mechanism | Impact | Who Profits |
|---|---|---|---|
| Arbitrage | Buy low on DEX A, sell high on DEX B | Aligns prices across markets β benign | Searcher |
| Liquidation | Race to liquidate undercollateralized positions | Keeps lending protocols solvent β useful | Searcher (bonus) |
| Backrunning | Place tx after a large trade to capture leftover value | Mild β doesnβt affect the target tx | Searcher |
| JIT Liquidity | Flash-add/remove concentrated liquidity around a swap | Takes LP fees from passive LPs | JIT LP |
| Frontrunning | Copy a profitable tx and submit with higher priority | Steals opportunities β harmful | Searcher |
| Sandwich | Frontrun + backrun a userβs swap | Directly extracts from user β most harmful | Searcher |
| Cross-domain | Arbitrage between L1 β L2 or L2 β L2 | Growing with L2 adoption | Sequencer/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:
- AMM swaps β the primary attack surface (Part 2 Module 2)
- Liquidation collateral sales β liquidatorsβ swap of seized collateral can be sandwiched
- Vault rebalances β automated vault strategies that swap on-chain are sandwich targets
- Oracle updates β TWAP oracles can be manipulated through related ordering attacks
- 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:
- β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 withswap()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:
| Concern | Why It Matters | Proposed Solutions |
|---|---|---|
| Builder centralization | Few builders = potential censorship | Inclusion lists, decentralized builders |
| Relay trust | Relays can censor or front-run | Relay diversity, enshrined PBS (ePBS) |
| OFAC compliance | Builders/relays may exclude sanctioned txs | Inclusion lists (force-include txs) |
| Latency advantage | Builders closer to validators win more | Timing 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
- Start with MEV-Boost docs β how validators connect to the relay network
- Read the Builder API spec β how builders submit blocks
- Study Flashbots Protect β the user-facing privacy layer
- Look at MEV-Share β how users capture MEV rebates
- 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:
- β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:
- User sends tx to MEV-Share
- MEV-Share reveals hints to searchers (e.g., βa swap on Uniswap V3 ETH/USDC poolβ β not the exact amount or direction)
- Searchers simulate potential backruns based on hints
- Searchers bid for the right to backrun
- Winning bundle: user tx β searcher backrun
- 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:
| Protection | Where It Appears | Module |
|---|---|---|
| Slippage limits | AMM swaps, vault withdrawals | Part 2 Modules 2, 7 |
| Intent-based execution | UniswapX, CoW Protocol | Part 3 Module 4 |
| Dutch auction liquidation | MakerDAO Dog, Part 2 capstone | Part 2 Modules 6, 9 |
| Oracle-based execution | GMX perpetuals | Part 3 Module 2 |
| Batch settlement | CoW Protocol | Part 3 Module 4 |
| Time-weighted prices | TWAP oracles | Part 2 Module 3 |
| Keeper delay | GMX two-step execution | Part 3 Module 2 |
πΌ Job Market Context
What DeFi teams expect you to know:
-
β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.β
-
β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:
- β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 blockbeforeSwap()β 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
π Cross-Module Concept Links
- 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
- Flashbots MEV-Boost relay β builder API, block submission flow
- Flashbots Protect RPC β private transaction submission, frontrunning protection
- MEV-Share contracts β programmable MEV redistribution, order flow auctions
- UniswapX β MEV-aware execution via Dutch auctions, filler network
- CoW Protocol β batch auctions as MEV defense, solver competition
- Notable MEV bot contracts on Etherscan β study real searcher strategies and gas optimization
π Resources
Production Code
- Flashbots MEV-Boost β validator sidecar for PBS
- Flashbots Builder β reference block builder implementation
- MEV-Share Node β order flow auction implementation
- CoW Protocol Solver β batch auction solver
Documentation
- Flashbots Docs β full architecture docs for MEV-Boost, Protect, and MEV-Share
- Ethereum.org: MEV β official MEV explainer
- Builder API Specification β Ethereum builder API spec
Key Reading
- Paradigm: Priority Is All You Need (MEV Taxes) β the MEV tax framework
- Flashbots: The Future of MEV β post-Merge supply chain analysis
- Flashbots: MEV-Share Design β OFA design and economics
- Frontier Research: Order Flow Auctions β design space analysis
- MEV-Explore Dashboard β historical MEV extraction data
π How to Study: MEV Ecosystem
- Start with Ethereum.org MEV page β the 10,000-foot overview
- Read Flashbots Protect docs β understand user-facing protection
- Study MEV-Share design β understand order flow auctions
- Read Paradigmβs MEV Taxes paper β the theoretical framework
- Explore MEV-Explore β look at real extraction data
- 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 β