Services Approach Projects Research About All Research
MEV & Infra

Anatomy of a Sandwich Attack

A sandwich attack is a value-extraction primitive hiding in plain sight: here is the full mechanism, the math, and the defenses that actually hold.

Advanced MEV 9 min read Jul 8, 2026

Every swap you broadcast to a public mempool is a confession. It announces, in cleartext, exactly what you intend to buy, how much, and the worst price you will accept. To you this is invisible plumbing. To a searcher running a sandwich bot, it is an offer, and the offer is to pay them.

This is a security piece, not a tutorial. We dissect the sandwich because the only way to defend a thing is to understand precisely how it dies. The attack is not exotic. It is arithmetic plus a privileged view of transaction ordering. Once you see the mechanism clearly, the defenses stop being folklore and start being engineering.

What a Sandwich Actually Is

A sandwich attack is a form of Maximal Extractable Value (MEV) in which an attacker brackets your trade with two of their own. They place one transaction immediately before yours (the frontrun) and one immediately after (the backrun). Your own trade moves the market in between, and the attacker harvests the difference.

It works because of two properties that hold on most automated market makers (AMMs):

  1. Price impact is deterministic. On a constant-product AMM, the price a trade receives is a closed-form function of the pool's reserves. Anyone who can read the pool state can compute the exact slippage a pending swap will cause.
  2. Ordering is for sale. Whoever decides the order of transactions inside a block (a block proposer, a sequencer, or a searcher bidding for placement) can insert their own transactions around yours. Ordering is the scarce resource, and MEV is the rent it commands.

You are never tricked into a bad contract. You get exactly the trade you asked for, at the worst price your slippage tolerance permitted. That is the cruelty of it: the attack lives entirely inside the slack you yourself authorized.

The Constant-Product Math

Consider a Uniswap-v2-style pool holding reserves of two tokens, x (say WETH) and y (a token TKN). The invariant is:

invariant
x * y = k

k is held constant across a swap (ignoring fees for a moment). When a trader sells Δx of WETH into the pool, the amount of TKN they receive, Δy, is whatever keeps the product constant:

output for a swap of Δx
(x + Δx) * (y - Δy) = k = x * y Δy = y - (x * y) / (x + Δx)

The marginal price y/x worsens as the trade grows: larger swaps eat deeper into the curve. That curvature is the surface the attacker exploits.

A Worked Example

Start with a pool: x = 100 WETH, y = 200,000 TKN, so k = 20,000,000. The spot price is 2,000 TKN per WETH.

Step 0: The victim broadcasts. Alice wants to buy TKN with 10 WETH. She signs a swap and sends it to the public mempool. Her wallet sets a slippage tolerance of 1%, encoding a minimum output (amountOutMin). At the current state, 10 WETH would yield:

step 0: ideal fill
Δy = 200,000 - (20,000,000) / (100 + 10) = 200,000 - 181,818.18 = 18,181.82 TKN

Her wallet computes amountOutMin as roughly 1% below that ideal: about 18,000 TKN. Anything worse, and her transaction reverts. The attacker now knows the exact floor she will tolerate.

Step 1: The frontrun. The searcher sees Alice's pending swap and inserts a buy of their own first. Suppose they push 15 WETH into the pool:

step 1: frontrun (15 WETH in)
Δy_attacker = 200,000 - (20,000,000) / (100 + 15) = 200,000 - 173,913.04 = 26,086.96 TKN

The attacker now holds 26,086.96 TKN. The pool reserves update to x = 115 WETH, y = 173,913.04 TKN. The price of TKN has risen, exactly what the attacker wants before Alice trades.

Step 2: The victim executes into a poisoned pool. Alice's 10 WETH now hits the worsened state:

step 2: victim fill (poisoned)
Δy_alice = 173,913.04 - (115 * 173,913.04) / (115 + 10) = 173,913.04 - (20,000,000) / 125 = 173,913.04 - 160,000 = 13,913.04 TKN

Alice receives only 13,913 TKN, far below the 18,181 she would have gotten in an empty mempool. Notice this is below her 18,000 amountOutMin. With a tight 1% tolerance, her transaction reverts here: the attack fails and costs the attacker gas. A profitable sandwich requires that your slippage tolerance be loose enough to survive the frontrun. Bots size the frontrun precisely to push you to the edge of amountOutMin without tipping over it. Had Alice set a lax 10% tolerance (amountOutMin ≈ 16,363), the attacker would size the frontrun to land her fill just above that floor and extract the maximum the curve allows. The lesson is already in the math: your slippage tolerance is the attacker's budget.

Step 3: The backrun. Assume Alice's lax tolerance let the trade clear. After her swap the pool sits at x = 125 WETH, y = 160,000 TKN. The attacker now sells back the TKN they bought in Step 1. Selling 26,086.96 TKN into this richer pool:

step 3: backrun (sell 26,086.96 TKN)
Δx_out = 125 - (125 * 160,000) / (160,000 + 26,086.96) = 125 - (20,000,000) / 186,086.96 = 125 - 107.48 = 17.52 WETH

The attacker spent 15 WETH in the frontrun and recovered roughly 17.52 WETH in the backrun, a gross profit on the order of ~2.5 WETH before fees and gas, conjured from Alice's slippage. The exact numbers shift once you fold in the 0.3% swap fee on each leg and the gas cost of two transactions; the fee actually erodes attacker margin, which is part of why very small victim trades are not worth sandwiching. But the shape holds: buy pressure in, let the victim push the price, sell into the wake.

Where It Happens

The math is chain-agnostic. What differs is the ordering market: where the attacker gets their privileged view and their placement.

Ethereum: The Public Mempool and Proposer-Builder Separation

On Ethereum L1, the classic attack surface is the public mempool. Pending transactions propagate openly before inclusion, giving searchers a window to simulate and react. Since The Merge and the rise of proposer-builder separation (PBS), most blocks are assembled by specialized builders who order transactions to maximize value, then sold to proposers via relays (the MEV-Boost pipeline). A searcher constructs a sandwich bundle (frontrun, victim, backrun as an atomic, ordered unit) and submits it to builders, bidding a priority fee or a direct payment for the privilege of that exact ordering. Bundles either land intact or not at all, which removes the attacker's risk of being partially filled.

The defensive implication is sharp: if your transaction never touches the public mempool, the searcher loses their target. That single fact underwrites most real Ethereum defenses.

Solana and Jito: No Mempool, But Orderflow Still Leaks

Solana has no global mempool in the Ethereum sense; transactions are forwarded to the current leader (the validator producing the slot). That does not eliminate sandwiching; it relocates it. Jito's block engine runs an auction in which searchers submit bundles and bid for placement within the leader's block, analogous to Ethereum's builder auction. Sandwiching on Solana has historically depended on searchers gaining early sight of orderflow: through bundle simulation, through mempool-like forwarding services, or through validators that share pending transactions. The threat model is the same primitive (ordering as a sellable resource) wearing different infrastructure. Jito has at times moved to curb the most blatant mempool-style sandwiching, but the economic gravity that creates the attack does not disappear. It migrates to wherever orderflow can be observed before finalization.

The general principle across both ecosystems: a sandwich requires (a) pre-execution visibility into your trade and (b) the ability to control ordering around it. Remove either and the attack collapses.

How to Defend

Defense means attacking those two prerequisites (visibility and ordering) or shrinking the slack the math feeds on.

  • Tighten slippage, but understand its limits. A tight amountOutMin shrinks the attacker's budget and can force their sandwich to revert your trade rather than profit from it. But tight slippage on a volatile or thin pool causes legitimate failed transactions, and a determined searcher will simply target trades whose tolerance leaves room. Slippage control is necessary, not sufficient. Set it deliberately per-pool, not as a global 0.5% you stop thinking about.
  • Use private orderflow. This is the strongest single defense on Ethereum. Services such as Flashbots Protect and other private RPC endpoints route your transaction directly to builders without ever broadcasting it to the public mempool. If the searcher cannot see your swap before it is mined, they cannot bracket it. Many such RPCs also offer revert protection and MEV refunds, returning some of the backrun value to you. The trade-off is a trust assumption in the RPC provider and occasionally slower inclusion.
  • Route with MEV awareness. Aggregators and routers can split a large order across pools, across blocks, or through paths with deeper liquidity, reducing the price impact any single fill creates, and price impact is the raw material of the sandwich. Smaller, deeper, fragmented fills are less profitable to attack. Some routers also natively submit through private channels.
  • Prefer commit-reveal and batch-auction venues where they exist. Designs that hide trade contents until execution attack visibility at the protocol level. CoW Protocol-style batch auctions settle many orders at a single uniform clearing price, so there is zero intra-batch ordering for an attacker to exploit and no exposed amountOutMin to lean on. Commit-reveal schemes have you commit to a hashed order first and reveal it only once ordering is fixed, denying the searcher the pre-execution view the attack depends on. These are structural defenses: they change the game rather than playing it more carefully.
  • For builders of protocols and infrastructure: treat orderflow as sensitive material. Encrypted mempools, threshold-decrypted ordering, and fair-ordering research all target the visibility prerequisite at the base layer. The endgame is making the pre-execution view impossible to obtain, not merely expensive.

Securing the Unseen

The sandwich endures because it is honest about what blockchains are: ordered ledgers where the right to order is worth money. It is not a bug in any one contract; it is a property of transparent execution meeting deterministic pricing. You do not patch it, you deny it.

At 0xhades we investigate mempools and orderflow the way an attacker does, because that is the only vantage from which a defense can be proven rather than asserted. We map the extractable surface of a protocol before someone else prices it.

We map the extractable surface before someone else prices it.

0xhades investigates mempools and orderflow from the attacker's vantage: the only place a defense can be proven rather than asserted. If your protocol handles ordering-sensitive value, let's talk before you ship.

Request an Engagement