Skip to content

MEV: Miner Extractable Value in Blockchain

DodaTech Updated 2026-06-22 8 min read

In this tutorial, you'll learn MEV including front-running, sandwich attacks, arbitrage, liquidations, and strategies for protection against value extraction. Why it matters: MEV has extracted over $1.5 billion in value from Ethereum users, affecting every DeFi trade, liquidation, and DEX swap through invisible tax on transactions. By the end, you'll understand MEV strategies and how to protect users.

MEV (Maximal Extractable Value, formerly Miner Extractable Value) is the profit that block proposers (validators/miners) can extract by including, excluding, or reordering transactions within a block.

How MEV Works

Block proposers control transaction ordering. They can front-run profitable transactions or capture arbitrage opportunities.

flowchart TD
  subgraph "Mempool (Pending Transactions)"
    TX1["Swap: 10 ETH for DAI
User A"] TX2["Liquidation: 100 ETH
User B (position at risk)"] TX3["Arbitrage: DEX1->DEX2
Price difference detected"] end subgraph "MEV Searcher Bot" B[Monitor mempool] B --> C{Identify profit} C --> D[Front-run: Insert tx before] C --> E[Sandwich: Before + after] C --> F[Back-run: Insert tx after] C --> G[Liquidate: Repay + seize] end subgraph "Block Construction" D --> H[Block with
reordered txs] E --> H F --> H G --> H end H --> I[Validator signs block] I --> J[MEV profit sent to bot]
// Simulating a sandwich attack
class SandwichBot {
  constructor() {
    this.flashbotsProvider = null;
  }
  
  async detectSandwich(targetTx) {
    // Parse the pending transaction
    const tx = await this.parseTransaction(targetTx);
    
    // Check if it's a profitable DEX swap
    if (tx.type === "swap" && tx.amount > 5) {
      // Calculate sandwich profit
      const swapImpact = await this.calculatePriceImpact(tx);
      const sandwichProfit = swapImpact * 0.8; // Capture 80% of slippage
      
      if (sandwichProfit > 0.01) { // Min 0.01 ETH profit
        console.log("Sandwich opportunity detected!");
        console.log(`Expected profit: ${sandwichProfit} ETH`);
        
        return {
          shouldExecute: true,
          frontRunAmount: tx.amount * 0.1, // 10% of target's size
          expectedProfit: sandwichProfit,
        };
      }
    }
    
    return { shouldExecute: false };
  }
  
  async executeSandwich(targetTx, frontRunAmount) {
    // Front-run: Buy before victim (drives price up)
    const frontRunTx = await this.createBuyTx(frontRunAmount);
    
    // Victim's transaction (now buys at higher price)
    const victimTx = targetTx;
    
    // Back-run: Sell after victim (at even higher price)
    const backRunTx = await this.createSellTx(frontRunAmount * 1.1);
    
    console.log("Sandwich executed:");
    console.log(`1. Bought at 100 (front-run)`);
    console.log(`2. Victim bought at 102 (slippage)`);
    console.log(`3. Sold at 101 (back-run)`);
    console.log(`Profit: ${(102 - 100) * frontRunAmount - (101 - 102) * 0} ETH`);
  }
}

Types of MEV

MEV Type Description Profit Source Impact on Users
Front-running Inserting tx before a profitable tx Price movement Worse execution price
Sandwich Buy before, sell after a trade Slippage capture Maximum slippage
Arbitrage Profit from price differences across DEXes Risk-free profit Market efficiency
Liquidation Repaying undercollateralized loans Liquidation bonus Position loss
JIT Liquidity Adding/removing liquidity around a trade Fee capture + price movement Worse LP returns

Arbitrage MEV

Arbitrage is the most common form of MEV, exploiting price differences across DEXes.

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;

contract ArbitrageBot {
    address public uniswapV2;
    address public sushiswap;
    
    function executeArbitrage(uint256 _amount) external {
        // Step 1: Buy on Uniswap (cheaper)
        uint256 bought = swap(uniswapV2, address(WETH), address(USDC), _amount);
        
        // Step 2: Sell on Sushiswap (more expensive)
        uint256 received = swap(sushiswap, address(USDC), address(WETH), bought);
        
        // Profit check
        require(received > _amount, "No profit");
        uint256 profit = received - _amount;
        
        // Transfer profit to caller
        payable(msg.sender).transfer(profit);
    }
    
    function findArbitrage() external view returns (bool hasOpportunity, uint256 profit) {
        uint256 priceUni = getPrice(uniswapV2);
        uint256 priceSushi = getPrice(sushiswap);
        
        if (priceSushi > priceUni) {
            uint256 amountOut = (100 * priceUni) / 1e18;
            uint256 received = (amountOut * 1e18) / priceSushi;
            profit = received - 100;
            hasOpportunity = profit > 105; // 5% min profit after fees
        }
    }
}

Expected behavior: The bot monitors Uniswap and Sushiswap for price differences of the same pair. If the price difference exceeds gas + fees, it executes a flash loan-funded arbitrage.

MEV Protection Strategies

Users and protocols can protect against MEV extraction.

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;

// Strategy 1: Commit-Reveal (prevents front-running)
contract CommitReveal {
    struct Commit {
        bytes32 hash;
        uint256 block;
        address user;
    }
    
    Commit[] public commits;
    
    function commit(bytes32 _hash) external {
        commits.push(Commit(_hash, block.number, msg.sender));
    }
    
    function reveal(uint256 _index, uint256 _value, bytes32 _secret) external {
        Commit storage c = commits[_index];
        require(msg.sender == c.user, "Not your commit");
        require(keccak256(abi.encodePacked(_value, _secret)) == c.hash, "Invalid reveal");
        require(block.number > c.block, "Too early");
        
        // Process the revealed value
        processValue(_value);
    }
}

// Strategy 2: Slippage Protection
contract SlippageProtected {
    function swap(uint256 _amountIn, uint256 _minAmountOut) external {
        uint256 amountOut = getAmountOut(_amountIn);
        require(amountOut >= _minAmountOut, "Slippage too high");
        // Execute swap
    }
}

// Strategy 3: Private Mempool (Flashbots)
// Users send bundles directly to validators, bypassing the public mempool
contract FlashbotsIntegration {
    // Bundle: [tx1, tx2, tx3] submitted as a unit
    // Either all execute or none execute (atomic)
    // Cannot be front-run because the bundle is private
}

MEV-Boost and PBS

With Ethereum's transition to Proof of Stake, MEV extraction shifted to MEV-Boost and Proposer-Builder Separation (PBS).

// MEV-Boost flow
class MEVBoost {
  constructor() {
    this.builders = [];
    this.relays = [];
  }
  
  async proposeBlock(validator) {
    // Validator queries relays for the best block
    const bids = await Promise.all(
      this.relays.map(relay => relay.getHeader())
    );
    
    // Select the block with highest MEV payment
    const bestBid = bids.reduce((max, bid) => 
      bid.value > max.value ? bid : max
    );
    
    console.log(`Best block bid: ${bestBid.value} ETH`);
    console.log(`Builder: ${bestBid.builder}`);
    console.log(`Relay: ${bestBid.relay}`);
    
    // Sign the block header (without seeing contents)
    const signature = await validator.sign(bestBid.header);
    
    // Get full block from relay
    const block = await bestBid.relay.getPayload(bestBid.header, signature);
    
    return block;
  }
}

// Expected output:
// Best block bid: 0.15 ETH
// Builder: Flashbots
// Relay: Flashbots Relay

MEV in DeFi Protocols

Protocols can be designed to minimize or redistribute MEV.

Protocol MEV Approach Mechanism
Uniswap V3 Slippage via TWAP Time-weighted average price oracle
CoW Protocol Batch auctions Coincidence of wants, solvers compete
0x RFQ-based Request-for-quote, private market makers
Lido MEV redistribution Staking rewards include MEV income
Flashbots Ethical MEV Private mempool, bundle auctions

Common Errors and Misunderstandings

1. Confusing MEV with Front-Running

MEV includes all value extraction from transaction ordering, not just front-running. Arbitrage and liquidations are also MEV, and some are beneficial for market efficiency.

2. Assuming Only Miners Extract MEV

With PoS, validators extract MEV. MEV-Boost enables specialized builders to compete for block construction, with validators selecting the most profitable block.

3. Thinking Slippage Settings Fully Protect

Slippage protects against sandwich attacks but not against all MEV. Even with 0.5% slippage, MEV bots capture that 0.5% unless you use private mempools.

4. Believing MEV Is Always Bad

Arbitrage MEV makes markets efficient by equalizing prices across DEXes. Liquidation MEV keeps lending protocols healthy. Only predatory MEV (sandwich) is clearly harmful.

5. Ignoring Cross-Chain MEV

MEV is not limited to one chain. Cross-chain arbitrage and sandwich attacks exist across L2s and sidechains, often via sequencer MEV.

Practice Questions

  1. What is MEV? Maximal Extractable Value is the profit block proposers can extract by controlling transaction ordering within a block. It includes front-running, sandwich attacks, arbitrage, and liquidations.

  2. How does a sandwich attack work? Buy before the victim's transaction (drives price up), let the victim buy at the inflated price, then sell immediately after (capturing the spread). The victim gets a worse price.

  3. What is MEV-Boost? MEV-Boost is middleware that connects Ethereum validators to a competitive block builder market. Validators outsource block construction to specialized builders who bid for the right to propose blocks.

  4. How do private mempools prevent MEV? Private mempools (Flashbots, Eden, SecureRPC) send transactions directly to validators/builders without public broadcast. The transactions are invisible to MEV bots, preventing front-running.

  5. What is the difference between beneficial and predatory MEV? Beneficial MEV includes arbitrage (market efficiency) and liquidations (protocol health). Predatory MEV includes sandwich attacks and front-running trades that harm users without providing economic benefits.

Challenge

Build a Flashbots searcher bot using Node.js and ethers.js that identifies profitable atomic arbitrage opportunities between Uniswap V2 and Sushiswap, constructs a bundle with the arbitrage transaction, simulates it against a local Hardhat fork, and submits it via the Flashbots relay. Include failure handling and profit tracking.

Real-World Task

Create a MEV protection middleware for a DeFi protocol using Solidity that implements commit-reveal for large swaps, integrates with Flashbots for private transaction submission, uses TWAP oracles for price calculation to reduce slippage manipulation, and monitors mempool for sandwich attempts using TypeScript.

Frequently Asked Questions

Can MEV be completely eliminated?

No. MEV is inherent to blockchain design where block proposers control transaction ordering. The goal is to minimize harmful MEV and redistribute MEV value to users. Solutions include PBS, encrypted mempools (Shutter), and batch auctions (CoW Protocol).

How much MEV is extracted daily?

Approximately $5-15 million per day on Ethereum, with peaks up to $30M during high activity. Flashbots alone processes over 90% of Ethereum blocks, with total MEV extracted exceeding $1.5 billion since 2020.

Is MEV legal?

Transaction ordering manipulation is not illegal in most jurisdictions, but it raises ethical and regulatory questions. Some forms of MEV (like sandwich attacks on retail traders) are being investigated by regulators as potential market manipulation.

Next Steps

After understanding MEV, explore zk-Rollups where sequencer MEV differs from L1, then dive into Wallet Development with built-in MEV protection.

Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro