← Back to articles
July 17, 2026
5 min read

MEV anatomy: sandwiches, frontrunning, and the dark forest of the mempool

MEV anatomy: sandwiches, frontrunning, and the dark forest of the mempool
#mev
#sandwich attack
#frontrunning
#mempool
#flashbots
#defi
#ethereum

When you sign a swap on a decentralized exchange and broadcast it to a public RPC endpoint, you have not sent a private instruction to a matching engine. You have published a signed, executable statement of intent to a global bulletin board, and you have attached a bounty — the gas price — to whoever agrees to execute it. Everyone can read that statement. No one is obligated to execute it fairly, in order, or at all. The order in which it lands relative to other transactions is not a property of your submission; it is a decision made by a third party who profits from making it against you.

This is the uncomfortable core of trading on-chain. In Statistical Arbitrage and Pairs Trading in Crypto Markets we mentioned, in passing, that moving a position between a CEX and a DEX carries "MEV risk" and left it there as a dangling term. This article pays that debt. It is the front door to a series on the economics of on-chain execution, and its job is to define the vocabulary — mempool, bundle, backrun, sandwich, PBS — precisely enough that the later pieces on atomic arbitrage with flash loans and Uniswap v3 concentrated liquidity for quants can assume you already understand the machine.

MEV — Maximal (or Maximum) Extractable Value — is the profit a party can extract by choosing the inclusion, exclusion, and ordering of transactions within a block, beyond the standard block reward and priority fees. It is not a bug; it is a structural consequence of how permissionless blockchains order transactions. Since the mechanism was formally characterized in 2019, cumulative extracted value has run into the billions of dollars, and a whole industry — searchers, builders, relays, block proposers — has grown up to capture and redistribute it. If you trade on-chain, you are either paying this tax or you have taken deliberate steps not to.

1. The transaction lifecycle: why your intent is public

To see where the value leaks out, follow a transaction from your wallet to a finalized block.

The public mempool

When your wallet signs a transaction and submits it to a standard node's RPC endpoint, the node validates it (signature, nonce, sufficient balance) and, if it passes, gossips it across the peer-to-peer network to other nodes. Each node holds these not-yet-included transactions in a local buffer called the mempool (memory pool). Within a second or two, essentially every node on the network — including nodes operated by parties whose entire business is extracting value from pending transactions — holds a copy of your signed, fully decoded transaction.

"Fully decoded" is the load-bearing phrase. Your transaction is not an opaque blob. It is an ABI-encoded call to a known contract. Anyone watching the mempool can decode it and read, in plain terms: this address is about to swap 40 ETH for USDC on the Uniswap v2 WETH/USDC pool, and it will accept as little as 96,000 USDC. That last clause — the minimum acceptable output — is your slippage tolerance, and it is not a hint. It is a hard parameter compiled into the calldata. We will see shortly that it is also the attacker's budget line.

The mempool is sometimes called the dark forest, after a 2020 essay by Dan Robinson and Georgios Konstantopoulos that borrowed Liu Cixin's metaphor: a space where any visible entity is immediately hunted by predators you cannot see. Broadcast a naive, profitable transaction into the public mempool and it may never reach a block in the form you signed — a bot will have consumed the opportunity and reshaped the surrounding block against you.

Gas price as a priority queue

Ethereum's fee market (post-EIP-1559) splits the gas price into a protocol base fee, which is burned, and a priority fee (the "tip"), which goes to the block proposer. When a block is built, the builder is economically motivated to include the transactions that pay it the most. To a first approximation, the mempool is a priority queue keyed on the tip: higher tip, earlier inclusion.

This is the mechanism that makes ordering purchasable. If I see your pending swap and I want my transaction to execute immediately before yours, I do not need to hack anything. I simply submit a transaction that pays a higher tip. The builder, following its incentive, places mine first. Ordering is not a fairness guarantee the protocol provides; it is an auction the protocol runs, and the lot being auctioned is the right to act on the information in your pending transaction.

Two facts combine into the entire MEV problem:

  1. Pending transactions are visible (public mempool).
  2. Their ordering is for sale (tip-priority auction).

Everything below is a corollary.

Transaction lifecycle from wallet to block: signed tx broadcast to public mempool, visible to searchers, ordered by priority fee into a block by the builder

2. Sandwich mechanics, with the actual math

The sandwich is the canonical toxic MEV strategy against a swapper, and it is worth grinding through the arithmetic because the numbers explain why your slippage setting is the single most important defensive parameter you control.

The constant-product invariant

A Uniswap v2 pool holds reserves xx of token X and yy of token Y, and enforces the invariant

xy=kx \cdot y = k

after every trade (ignoring fees for a moment). If a trader sells Δx\Delta x of token X into the pool, the new X reserve is x+Δxx + \Delta x, and to preserve kk the pool must pay out

Δy=ykx+Δx=yΔxx+Δx.\Delta y = y - \frac{k}{x + \Delta x} = \frac{y \, \Delta x}{x + \Delta x}.

With the 0.3% Uniswap v2 fee, the input is scaled by γ=0.997\gamma = 0.997:

Δy=yγΔxx+γΔx.\Delta y = \frac{y \, \gamma \, \Delta x}{x + \gamma \, \Delta x}.

The key property: the more you buy in one direction, the worse your marginal price. Price impact is convex. This convexity is exactly what the attacker monetizes.

The setup

Take a WETH/USDC pool. To keep the numbers clean, assume reserves that put ETH at roughly 2,500 USDC:

  • x=10,000x = 10{,}000 WETH
  • y=25,000,000y = 25{,}000{,}000 USDC
  • k=2.5×1011k = 2.5 \times 10^{11}

You want to buy USDC with 40 WETH (a sell of WETH into the pool). Ignoring fees for the illustration, an honest fill in an empty block would give you

Δy=25,000,0004010,000+40=1,000,000,00010,04099,601 USDC.\Delta y = \frac{25{,}000{,}000 \cdot 40}{10{,}000 + 40} = \frac{1{,}000{,}000{,}000}{10{,}040} \approx 99{,}601 \text{ USDC}.

The spot price before your trade is 25,000,000/10,000=2,50025{,}000{,}000 / 10{,}000 = 2{,}500 USDC/WETH, so 40 WETH is "worth" 100,000 USDC at the pre-trade mid. You receive 99,601 — the ~399 USDC gap is your own price impact plus fees. Now suppose you set a 1% slippage tolerance. Your transaction's amountOutMin is

99,601×0.9998,605 USDC.99{,}601 \times 0.99 \approx 98{,}605 \text{ USDC}.

That number is now public in the mempool. It tells any observer: this person will accept as little as 98,605 USDC for their 40 WETH. The difference between what you'd get in a clean block (99,601) and your floor (98,605) — about 996 USDC — is the room you have voluntarily handed to whoever front-runs you. This is the attacker's budget.

The attack, step by step

A searcher constructs three transactions and forces them into this order within one block:

1. Front-run (attacker buys first). The attacker sells their own WETH into the pool ahead of you, pushing the price of USDC up (WETH down) so that when your trade lands, you get fewer USDC per WETH. The attacker sizes this so that your transaction still clears your amountOutMin — if it doesn't, your swap reverts and there is no victim to sandwich. The optimal front-run size is the largest one that leaves you exactly at your floor.

Suppose the attacker front-runs with 40 WETH of their own. Pool moves to x=10,040x = 10{,}040, and by the invariant the attacker receives

25,000,0004010,04099,601 USDC out,\frac{25{,}000{,}000 \cdot 40}{10{,}040} \approx 99{,}601 \text{ USDC out},

leaving reserves x=10,040x = 10{,}040 WETH, y24,900,399y \approx 24{,}900{,}399 USDC.

2. Victim (your swap executes into the worsened pool). Your 40 WETH now lands against these reserves:

Δy=24,900,3994010,040+40=996,015,96010,08098,811 USDC.\Delta y = \frac{24{,}900{,}399 \cdot 40}{10{,}040 + 40} = \frac{996{,}015{,}960}{10{,}080} \approx 98{,}811 \text{ USDC}.

Check the constraint: 98,811 > 98,605, so your transaction does not revert — you get filled, just worse. You received 98,811 instead of the 99,601 you'd have gotten in a clean block. You are out roughly 790 USDC, and you have no idea it happened; your swap "succeeded." Pool is now x=10,080x = 10{,}080 WETH, y24,801,588y \approx 24{,}801{,}588 USDC.

3. Back-run (attacker sells back). The attacker now sells the USDC it bought in step 1 back into the pool — or equivalently buys back its WETH — capturing the elevated price your trade created. Buying WETH back with the ~99,601 USDC it holds:

Δx=10,08099,60124,801,588+99,6011,004,010,08024,901,18940.32 WETH.\Delta x = \frac{10{,}080 \cdot 99{,}601}{24{,}801{,}588 + 99{,}601} \approx \frac{1{,}004{,}010{,}080}{24{,}901{,}189} \approx 40.32 \text{ WETH}.

The attacker spent 40 WETH in step 1 and got 40.32 WETH back in step 3 — a profit of about 0.32 WETH (~800 USDC) before gas, extracted almost entirely from your slippage budget. Tighten your slippage and that budget shrinks; the attacker's optimal front-run size falls, and below some threshold the sandwich stops being profitable after gas and the searcher skips you.

The lesson is not "slippage tolerance is bad." You need some tolerance or your transactions revert on ordinary price movement. The lesson is that slippage tolerance is a directly extractable quantity, and setting it to a lazy default like 1% or, worse, "auto" on a thin pool, is equivalent to leaving that much money on the table for anyone watching. On a low-liquidity pool where your own trade moves the price several percent, a default slippage can hand over a shocking fraction of your notional.

A minimal sketch of a searcher's profit condition:

def sandwich_profit(x, y, gamma, victim_dx, victim_min_out, attack_dx, gas_cost):
    out1 = (y * gamma * attack_dx) / (x + gamma * attack_dx)
    x1, y1 = x + attack_dx, y - out1
    vout = (y1 * gamma * victim_dx) / (x1 + gamma * victim_dx)
    if vout < victim_min_out:
        return None  # victim would revert; no sandwich
    x2, y2 = x1 + victim_dx, y1 - vout
    got_back = (x2 * gamma * out1) / (y2 + gamma * out1)
    return got_back - attack_dx - gas_cost  # profit in WETH

The searcher runs a small optimization over attack_dx to find the largest front-run that keeps vout >= victim_min_out. That optimum is where your slippage floor binds — which is another way of saying the attacker's take is capped precisely by the room you left.

3. A taxonomy of MEV: toxic versus benign

"MEV" gets used as a slur, but not all of it is extraction from a victim. It helps to sort strategies by whether someone is made worse off by the ordering.

Frontrunning. Observe a pending profitable transaction, copy or preempt it, and pay a higher tip to execute first. The archetype is seeing a large buy that will move a price and buying ahead of it. Purely toxic: the victim gets a worse price, or their opportunity is stolen outright.

Backrunning. Place your transaction immediately after a target transaction to act on the state it creates. Critically, a pure backrun does not degrade the target's execution — it runs after, so the victim's price is already locked. If your large swap knocks the WETH/USDC pool out of line with Binance, an arbitrageur backruns you to realign it and pockets the difference. You are not harmed; in fact this arbitrage is what keeps on-chain prices tracking the broader market. Backrunning is the benign end of the spectrum, and — as we'll see — modern MEV-protection systems are built precisely to return backrun profit to the user who created it.

Sandwiching. A frontrun and a backrun wrapped around the same victim, as dissected above. Toxic by construction: the frontrun exists only to worsen the victim's fill so the backrun can harvest it.

Atomic arbitrage. A single transaction that buys an asset cheap on one venue and sells it dear on another — say WETH cheaper on Uniswap than on Sushiswap — netting a risk-free profit, all-or-nothing within one transaction (it reverts if unprofitable). No specific victim; it is closing a price discrepancy the market left open. Generally considered benign — it improves cross-venue price consistency — and it is the subject of the atomic arbitrage and flash loans piece in this series, where the "no capital required" property of flash loans makes it especially sharp.

Liquidations. When a lending position (Aave, Compound, Maker) falls below its collateral threshold, the protocol offers a bonus to whoever repays the bad debt and seizes the collateral. Searchers compete to be that liquidator. There is a "victim" — the liquidated borrower — but they are being liquidated by the protocol's rules regardless; MEV competition mostly determines who gets the bonus and, through competition, can shrink it. Call it neutral-to-benign for market health, unpleasant for the borrower.

A rough map:

Strategy Victim harmed? Verdict
Frontrun Yes Toxic
Sandwich Yes Toxic
Backrun (pure) No Benign
Atomic arbitrage No Benign (improves price consistency)
Liquidation Borrower (per protocol rules) Neutral

The toxic/benign line matters because the entire modern MEV-mitigation stack is an attempt to suppress the toxic strategies while preserving — and redistributing — the benign ones. You cannot ban ordering games without also breaking the arbitrage that keeps DEX prices honest. The trick is to route the toxic value back to the person it was taken from.

4. A short history: from gas auctions to Flashbots

Flash Boys 2.0 and priority gas auctions

The phenomenon was named and measured in the 2019 paper "Flash Boys 2.0: Frontrunning, Transaction Reordering, and Consensus Instability in Decentralized Exchanges" by Philip Daian, Steven Goldfeder, Tyler Kell, Yunqi Li, Xueyuan Zhao, Iddo Bentov, Lorenz Breidenbach, and Ari Juels. The paper introduced the term "miner extractable value" (later generalized to maximal extractable value as the industry moved from proof-of-work miners to proof-of-stake proposers) and documented priority gas auctions (PGAs): bots bidding one another up on gas price, in real time, to win the ordering of a profitable opportunity.

PGAs were visibly pathological. Because the only lever bots had was the public gas price, they fought open bidding wars — repeatedly resubmitting with higher and higher tips within the same few seconds — to claim a single arbitrage or liquidation. Two ugly consequences followed. First, this congested the network and inflated gas prices for everyone, MEV-related or not. Second, and more alarming, the paper argued that if the MEV available in a block exceeded the block reward, rational miners would be incentivized to reorganize the chain to steal it, threatening consensus stability itself. MEV was not just a user-fairness problem; it was a threat to the chain.

Flashbots as the response

Flashbots launched in 2020 to defuse the PGA. Its insight: move the ordering auction off the public mempool and into a sealed-bid, off-chain channel. Instead of broadcasting a transaction and fighting a public gas war, a searcher assembles a bundle — an ordered list of transactions to be included atomically, all-or-nothing, in a specific relative order — and submits it privately to a block builder, along with a bid (often paid as a direct transfer to the proposer rather than through the gas price). The builder assembles the most valuable block it can from all the bundles and transactions it receives and offers it to the proposer.

Two things improve at once. Searchers stop spamming the public mempool with failed bids, so the gas-price externality on ordinary users drops. And the winning bundle either lands intact or not at all, eliminating the "failed frontrun" transactions that used to clog blocks. The bidding war still happens — it just happens as a private auction inside the builder rather than a public shouting match on-chain.

PBS: proposer-builder separation

Flashbots' architecture generalized into proposer-builder separation (PBS), the dominant model on Ethereum today. The roles split:

  • Searchers find MEV opportunities and package them into bundles.
  • Builders compete to assemble the single most valuable full block from bundles and public transactions.
  • Relays sit between builders and proposers, receiving full blocks from builders and passing only block headers plus a value bid to the proposer, so the proposer commits to a block before seeing its contents (preventing the proposer from simply stealing the MEV).
  • Proposers (validators) pick the header with the highest bid, sign it, and collect the payment.

This is implemented off-protocol via MEV-Boost, middleware the overwhelming majority of Ethereum validators run — on the order of 80–90% of blocks are built through external builders via MEV-Boost. It works, but it relies on trusted relays. The next step, enshrined PBS (ePBS, EIP-7732), aims to bake proposer-builder separation directly into the Ethereum protocol and remove the trusted-relay dependency. As of mid-2026 it is slated for the Glamsterdam upgrade, targeting a mainnet activation later in 2026, with proponents claiming it can cut MEV losses to users substantially by improving how blocks are committed and by narrowing the window for toxic reordering. Treat the exact numbers as aspirational until it ships, but the direction is clear: the protocol is absorbing the MEV supply chain it spent years pretending didn't exist.

MEV-Share: giving the value back

The most consequential development for ordinary traders is MEV-Share, Flashbots' order-flow auction. The idea inverts the dark forest. Instead of your transaction being visible to every predator, you send it privately to a MEV-Share node, which reveals only partial hints about it (you choose how much) to searchers. Searchers bid to backrun your transaction — remember, a backrun doesn't hurt you — and a large fraction of the resulting profit is refunded to you, with the rest split between the searcher and the proposer to get the bundle included.

The economic reframing is elegant. A large swap creates a backrun opportunity; the question is who captures it. In the dark-forest world, searchers and builders take all of it. Under MEV-Share, the value your own transaction created is largely returned to you. Flashbots' consumer-facing RPC, Flashbots Protect, routes retail transactions through this system, and in 2025 it added gas-fee refunds on top, meaningfully increasing what users get back. This is the "redistribute the benign, suppress the toxic" principle made concrete.

5. Practical defenses for a trader

You do not need to run a searcher to stop being prey. In rough order of impact:

Set slippage deliberately, per pool

Section 2 established that your slippage tolerance is the attacker's budget. Two rules follow. First, size slippage to the pool's actual liquidity and your trade's price impact, not to a habitual 1%. On a deep pool a 0.1–0.3% tolerance may be plenty; on a thin one, either accept that you cannot trade size safely or split into smaller clips. Second, never use "auto"/"unlimited" slippage on a low-liquidity pair — it is a signed blank check. If a swap keeps reverting at a tight tolerance, that is the market telling you your trade is too large for the pool, not a prompt to loosen the floor.

Route through a private RPC

The cleanest structural fix is to keep your transaction out of the public mempool entirely. Point your wallet at a private RPC that forwards transactions directly to builders rather than gossiping them:

  • Flashbots Protect — sends your transaction into the MEV-Share system, so it is never publicly visible to frontrunners, and returns a share of any backrun value plus gas refunds.
  • MEV Blocker (by CoW Protocol and others) — a similar private-RPC service that protects against frontrunning and sandwiching and rebates backrun profit to users, with a free-to-use fee model.

Because a sandwich requires the attacker to see your pending transaction and insert a frontrun before it, removing your transaction from the public mempool removes the frontrun opportunity outright. The backrun opportunity remains, but it is now auctioned back to you rather than stolen. The tradeoff is a little trust in the RPC operator and, occasionally, marginally slower inclusion — usually trivial next to eliminating sandwich risk. (A 2025 benchmark study of private-protection RPCs found their real-world settlement is not always strictly better than public submission, so the effect is strong but not universal; for most retail-sized DEX swaps, private routing is still the correct default.)

Prefer batch-auction and intent-based venues

Some DEX designs remove ordering advantage by construction. CoW Protocol settles trades in batch auctions with a uniform clearing price — every trade in a batch clears at the same price, so there is no "first" and "last" position to exploit, and solvers compete to give you the best execution rather than to reorder around you. Intent-based systems where you sign what you want and let solvers find execution, rather than signing a specific path, similarly deny the sandwich its foothold. If you are doing size, these venues are worth more than any slippage tweak.

Understand why L2s are different

On most Ethereum rollups today (Arbitrum, Optimism, Base), blocks are produced by a single sequencer operated by the rollup team. There is no public mempool of pending transactions for searchers to watch, and there is one trusted party deciding order. In practice most sequencers order transactions first-come-first-served and do not run sandwich attacks against their users, so sandwiching is largely absent on these chains at the protocol layer.

But read the tradeoff precisely: the reason you are safe from decentralized MEV extraction is that you are trusting a centralized orderer not to extract it. The sequencer could frontrun you; it simply chooses (and is reputationally bound) not to. This is a temporary equilibrium. As rollups decentralize their sequencers — shared sequencers, based sequencing, PBS-style auctions on L2 — the same mempool visibility and ordering-for-sale dynamics can re-emerge, and the L2 MEV question becomes an open design problem rather than a solved one. Do not assume "I'm on an L2" means "MEV cannot touch me" indefinitely; it means "one trusted party has promised not to, for now."

What to carry into the rest of the series

Strip the topic to its load-bearing facts:

  1. A public-mempool swap is public intent plus a purchasable ordering slot. That combination, not any single bug, is the whole problem.
  2. On a constant-product AMM, your slippage tolerance is a quantity an attacker can extract, and a sandwich's take is bounded precisely by the room you left. Setting slippage is a security decision, not a convenience toggle.
  3. MEV is not monolithic: frontruns and sandwiches are toxic; backruns and atomic arbitrage are benign and even useful, because they keep on-chain prices consistent. Good mitigation suppresses the former and redistributes the latter.
  4. The industry response ran from PGAs (public gas wars, Flash Boys 2.0, 2019) to Flashbots / bundles / PBS (sealed private auctions) to MEV-Share (return backrun value to the user) and, next, enshrined PBS in the protocol.
  5. As a trader, your defenses are tight per-pool slippage, private RPCs (Flashbots Protect, MEV Blocker), and batch-auction venues — and an awareness that L2 safety is currently a trust assumption in the sequencer, not a law of physics.

The atomic arbitrage and flash loans piece takes the searcher's side of this table — how the benign extraction is built, with borrowed capital and atomic reverts as the safety net. The Uniswap v3 concentrated liquidity piece revisits the constant-product math above and shows how concentrated liquidity reshapes the price-impact curve — and therefore the sandwich budget — we derived here. The mempool is a dark forest. Now you know what is hunting in it.

References

  • Daian, Goldfeder, Kell, Li, Zhao, Bentov, Breidenbach, Juels (2019), Flash Boys 2.0: Frontrunning, Transaction Reordering, and Consensus Instability in Decentralized Exchanges. arXiv:1904.05234.
  • Robinson & Konstantopoulos (2020), Ethereum is a Dark Forest.
  • Flashbots documentation: MEV-Boost, MEV-Share, Flashbots Protect, MEV refunds (docs.flashbots.net).
  • Ethereum PBS / EIP-7732 (enshrined proposer-builder separation), Glamsterdam upgrade materials.
  • MEV Blocker (mevblocker.io); CoW Protocol batch-auction design.
  • Private MEV Protection RPCs: A Benchmark Study (arXiv:2505.19708, 2025).
Disclaimer: The information provided in this article is for educational and informational purposes only and does not constitute financial, investment, or trading advice. Trading cryptocurrencies involves significant risk of loss.

Authors

Eugen Soloviov
Eugen Soloviov

Trading-systems engineer

Trading-systems engineer building bots since 2017: cross-exchange arbitrage (connected up to 30 venues), cointegration-based pairs arbitrage across spot and futures, scalping, news and sentiment-driven strategies, trend algorithms, and portfolio management and balancing algorithms. Also builds sub-millisecond order execution, big-data warehouses, backtesting engines, AI agents, and trading interfaces (incl. open-source profitmaker.cc). Stack: JS/TS, Python, Rust/Zig/Go, DevOps, backend, frontend, architecture.

Newsletter

Stay Ahead of the Market

Subscribe to our newsletter for exclusive AI trading insights, market analysis, and platform updates.

We respect your privacy. Unsubscribe at any time.