Maximal Extractable Value (MEV)
Deconstructing MEV: How Searchers Execute Arbitrage and Sandwich Attacks
Master the technical patterns of arbitrage and sandwich attacks to understand how searchers extract value from the public mempool.
In this article
The Architecture of the Public Mempool
In a decentralized network, transactions do not immediately move from a user's wallet to the blockchain state. Instead, they enter a peer-to-peer gossip layer known as the mempool, where they wait for a validator to select them for inclusion in the next block. This intermediate state is entirely public, meaning any node on the network can see the details of every pending transaction before it is finalized.
The transparent nature of the mempool creates a unique environment where sophisticated bots, known as searchers, monitor the flow of data for profit opportunities. Because validators typically order transactions based on the gas price offered, searchers can influence the sequence of execution by adjusting their priority fees. This ability to reorder, include, or exclude transactions is the core mechanic of Maximal Extractable Value.
To understand MEV, you must view the blockchain not as a simple ledger but as a state machine with a highly visible transition queue. Every pending swap on a decentralized exchange or every liquidation threshold reached on a lending platform is a signal to searchers. They leverage this information to construct bundles of transactions that guarantee their own profit while the network processes the block.
- Mempool visibility allows searchers to simulate transactions before they land on-chain
- Priority fees act as a bidding mechanism for transaction placement within a block
- Gas Price Auctions (GPAs) are the primary way searchers compete for the top of the block
While MEV is often associated with negative externalities like high gas prices, it also plays a functional role in the ecosystem. Arbitrageurs ensure that asset prices remain consistent across different trading venues, and liquidators protect the solvency of lending protocols. However, the technical implementation of these strategies requires a deep understanding of network latency and smart contract interaction patterns.
Transaction Propagation and Latency
When a user signs a transaction and broadcasts it through a provider, it propagates through a network of nodes using the gossip protocol. Different geographic regions and node configurations can lead to slight variations in when a searcher sees a specific transaction. Searchers often run their own high-performance nodes in multiple data centers to reduce the time between transaction broadcast and detection.
Minimal latency is critical because MEV opportunities are usually winner-take-all scenarios where only the first person to execute the trade captures the profit. If two searchers identify the same arbitrage opportunity, the one who propagates their transaction to the block builder first, or offers the higher fee, will succeed. This has led to a technological arms race involving optimized networking stacks and specialized hardware.
Mastering Atomic Arbitrage Patterns
Atomic arbitrage is the most common form of MEV and involves exploiting price discrepancies between two or more decentralized exchanges. For example, if the price of an asset is lower on Uniswap than it is on Sushiswap, a searcher can buy the asset on the first exchange and sell it on the second in a single transaction. This operation is considered atomic because if any part of the trade fails, the entire transaction reverts, protecting the searcher from loss.
The logic of an arbitrage bot involves constant monitoring of liquidity pool reserves to calculate the optimal trade size. Because decentralized exchanges use automated market maker formulas like x times y equals k, every trade impacts the price of the underlying assets. A searcher must calculate exactly how much of an asset to swap to maximize profit after accounting for slippage and gas costs.
1// This contract executes a cross-exchange arbitrage trade in a single transaction
2pragma solidity ^0.8.0;
3
4interface IUniswapV2Pair {
5 function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;
6}
7
8contract ArbExecutor {
9 address public owner;
10
11 constructor() {
12 owner = msg.sender;
13 }
14
15 // The execute function takes addresses of two pools and the amount to trade
16 function executeArb(address poolA, address poolB, uint amountIn) external {
17 require(msg.sender == owner, "Unauthorized");
18
19 // Step 1: Logic to pull tokens or use flash loan would go here
20 // Step 2: Swap on Pool A to get intermediate tokens
21 // Step 3: Swap on Pool B to return to original asset
22
23 // The transaction reverts if the final balance is not greater than the initial balance
24 uint finalBalance = address(this).balance;
25 require(finalBalance > amountIn, "No profit detected");
26 }
27}The code above illustrates the basic structure of an executor contract used by searchers. Instead of interacting with decentralized exchanges directly through a wallet, searchers use custom smart contracts to ensure atomicity and reduce the number of external calls. This efficiency is necessary to keep gas costs low enough to maintain a healthy profit margin across different market conditions.
Calculating Optimal Input for AMMs
To maximize profit, searchers use calculus to determine the exact amount of tokens to swap between two pools. Since the price on an AMM shifts as you trade against it, there is a point of diminishing returns where the slippage on the second exchange outweighs the price difference. Solving for the derivative of the profit function relative to the input amount allows a searcher to find the peak of the profit curve.
In practice, this calculation must be performed in milliseconds as new blocks are produced. Searchers often pre-calculate these values for various price points or use highly optimized off-chain simulators written in languages like Rust or C++ to find opportunities. This allows them to submit their transactions the moment a price discrepancy is detected in the mempool.
The Mechanics of Sandwich Attacks
A sandwich attack is a more controversial MEV strategy that targets users who have set a high slippage tolerance on their trades. When a searcher sees a large pending buy order in the mempool, they place their own buy order immediately before the user and a sell order immediately after. This effectively forces the user to buy at the highest price their slippage tolerance allows, with the searcher pocketing the difference.
This strategy consists of three distinct parts: the frontrun, the victim's trade, and the backrun. The searcher's first transaction increases the price of the asset, the user's transaction increases it further, and the searcher's final transaction sells the asset at the newly inflated price. This can only be executed reliably if the searcher can guarantee the order of these three transactions within a single block.
Sandwiching relies on the predictable behavior of automated market makers and the user's willingness to accept a range of execution prices. It represents a direct transfer of value from the retail trader to the searcher, highlighting the importance of slippage management in decentralized finance.
Detecting a potential sandwich opportunity requires parsing the transaction data in the mempool to identify swaps on supported decentralized exchanges. The searcher's bot must decode the function arguments to find the minimum output amount the user is willing to accept. If the gap between the current price and the user's minimum is large enough to cover gas fees and yield a profit, the attack is initiated.
1from web3 import Web3
2
3# Connect to a high-speed node provider
4w3 = Web3(Web3.HTTPProvider('https://mainnet.infura.io/v3/YOUR_KEY'))
5
6def monitor_mempool():
7 # Use a filter to listen for pending transactions
8 pending_filter = w3.eth.filter('pending')
9
10 while True:
11 for tx_hash in pending_filter.get_new_entries():
12 tx = w3.eth.get_transaction(tx_hash)
13
14 # Check if the transaction is interacting with a known DEX
15 if tx['to'] == '0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D': # Uniswap V2
16 # Decode the input data to check for trade size and slippage
17 print(f"Analyzing potential opportunity in tx: {tx_hash.hex()}")
18 # Detailed logic for slippage analysis would be implemented hereThe Python snippet demonstrates how a searcher might start the process of identifying victims. By filtering for the Uniswap router address, the bot can isolate trades that are likely to move the price. Real-world implementations would also check the gas price of the pending transaction to ensure the frontrun can successfully leapfrog it in the block order.
Risks and Countermeasures for Searchers
Sandwiching is not without risk, as searchers can be counter-attacked through a technique known as a salmonella attack. In this scenario, a developer creates a bait token with custom logic that detects when it is being bought and sold in a sandwich pattern. The token contract can then trigger a revert or a fee on the second half of the sandwich, causing the searcher to lose their initial investment.
To mitigate these risks, sophisticated searchers use simulation engines to dry-run their bundles against the current state of the blockchain. If the simulation shows any unexpected behavior or failing calls, the searcher will discard the opportunity. This level of defensive programming is what separates professional searcher operations from simple hobbyist scripts.
Evolution of Extraction: From PGAs to MEV-Boost
In the early days of MEV, searchers competed in Priority Gas Auctions by repeatedly outbidding each other with higher gas prices. This led to massive congestion on the network and unpredictable gas fees for regular users. To solve this, the community introduced specialized relay services that allow searchers to submit bundles of transactions directly to block builders off-chain.
The most prominent of these solutions is Flashbots, which provides a private communication channel between searchers and validators. Instead of broadcasting their transactions to the public mempool where they could be frontrun, searchers send them as bundles. These bundles are either included in a block in their entirety or not included at all, providing a level of execution certainty and privacy.
This architecture has shifted the MEV landscape toward a more formal auction process called the Builder-Proposer Separation. In this model, specialized builders aggregate bundles from many searchers to create the most profitable block possible. The validator then simply chooses the highest-value block header without seeing the individual transactions inside until the block is proposed.
While these systems reduce network congestion and protect searchers from being frontrun themselves, they also centralize certain aspects of block production. Developers must understand how to interact with these private RPCs to protect their users' transactions. By using services like Flashbots Protect, users can bypass the public mempool entirely and avoid falling victim to sandwich attacks.
The Role of Searcher Bundles
A bundle is a group of transactions that are executed sequentially and atomically in the order provided by the searcher. A typical bundle might contain a user's transaction that the searcher is backrunning to capture an arbitrage opportunity. The searcher pays the validator through a direct transfer of ether within the transaction or via a high gas price, ensuring the validator is incentivized to include the bundle.
Bundles are powerful because they allow searchers to express complex preferences about transaction ordering that are impossible in the public mempool. For instance, a searcher can specify that their transaction must be the very first one in a block. This granular control is what enables advanced MEV strategies while keeping the public network free from bidding war spam.
