QTube LearnDeFi and markets Advanced
What Is a Sandwich Attack?
A sandwich is an ordering-based form of MEV: an attacker places one transaction before a target and another after it. The common example is a visible exact-input AMM swap.
In brief
- A sandwich is an ordering-based form of MEV: an attacker places one transaction before a target and another after it.
- The common example is a visible exact-input AMM swap. The attacker uses the victim’s price impact and remaining slippage tolerance to seek a profit.
- The victim receives fewer output tokens than the pre-submission quote, but no line item says “sandwich fee.”
- A minimum-output or maximum-input check can reject execution beyond the user’s bound. The check limits damage; it does not promise a good price or successful inclusion.
- Private submission, deeper routes, RFQ or intent systems and batch auctions change what attackers can see or how trades are ordered. Each introduces its own assumptions and failure modes.
- The classic pattern is associated with public transaction visibility, but sandwiching is not unique to Ethereum, AMMs or public mempools.
This article explains recognition and defense. It deliberately omits profit equations, bot construction, bidding tactics and executable transaction sequences.
How the classic AMM sandwich works
Take a wallet that quotes an exact-input swap: spend a fixed amount of token A and receive an estimated amount of token B. The transaction includes a minimum acceptable B output.
At a defensive level, the sequence is:
- The wallet simulates current pool reserves and displays an expected output.
- The user signs a swap with a minimum-output condition and broadcasts or privately submits it.
- A searcher with pre-execution visibility identifies that the swap will materially move the pool price.
- The searcher’s first trade executes ahead of the user in the same direction, making B more expensive.
- The user’s trade executes against the changed reserves, receiving less B but still at or above the authorized minimum.
- The searcher’s second trade executes after the user, reducing its temporary inventory and attempting to capture the price movement, after fees and other costs.
The attacker cannot simply take the whole input. The victim’s own signed transaction still enforces token amounts and contract rules. The loss is the difference between the execution the user expected and the worse execution the transaction allowed.
The strategy is risky for the attacker. Competing searchers, another intervening trade, a reverted victim transaction, changed ordering, fees or a token with unexpected behavior can make one or both legs unprofitable. Ethereum.org uses “salmonella” contracts as an example of why copying or sandwiching apparent opportunities can backfire. This is not a guarantee that hostile flow is safely punished.
Price impact, slippage and tolerance
These terms should remain separate:
- Price impact is the expected movement caused by trade size relative to available liquidity.
- Slippage, in this corpus’s strict usage, is the gap between the size-adjusted expected execution at submission and the actual fill after intervening movement or ordering.
- Slippage tolerance is the boundary encoded into the transaction.
- Swap fees and gas are separate costs.
A sandwich uses both impact and tolerance. The victim’s trade is large enough to move the pool, creating a potential backrun. The attacker’s first trade consumes some of the victim’s tolerance by moving the starting state in an unfavorable direction.
For a typical exact-input Uniswap-style router, output below amountOutMinimum causes a revert. If that reverting transaction is included on Ethereum, state changes are rolled back but gas is still consumed. A private service may instead simulate and withhold a reverting transaction, so “every failed swap pays gas” is not universal.
Exact-output swaps reverse the control: the user specifies the output and caps the maximum input. Other routers can use deadlines, price limits or signed intents. The durable defense is a transaction-enforced economic bound, not one particular parameter name.
Why a wide limit is dangerous
A slippage limit is a reservation boundary. Setting it very wide says the transaction may execute even after a large adverse state change. That can leave more room for a sandwich, ordinary volatility or stale routing.
Setting it extremely tight has a different cost. Harmless market movement or another user’s trade may cause a revert or delayed inclusion. Research by Heimbach and Wattenhofer shows why one fixed default cannot fit every pool, trade size and market condition.
There is no defensible universal percentage. A reasonable limit depends on:
- expected price impact for the trade size;
- pool depth across the route, including concentrated-liquidity ticks;
- volatility and quote age;
- whether the quote is firm, indicative or simulated;
- network and submission path;
- the user’s willingness to accept failure instead of a worse fill.
“Raise slippage until it goes through” is not a security strategy.
Related ordering patterns
Frontrunning is the broad act of placing a transaction ahead of a known target to gain an advantage. Copying a mint or arbitrage without a later unwind may be a frontrun but not a sandwich.
Backrunning places a transaction immediately after a state-changing transaction. Arbitraging the price difference created by a swap can be a backrun without worsening the user’s pre-trade execution.
Sandwiching combines before-and-after trades around a target. The first leg changes the victim’s execution; that adverse effect distinguishes the classic attack from a pure backrun.
Just-in-time liquidity and other ordering strategies can also surround a swap but have different mechanics and distributional effects. Similar-looking block traces should not be labeled without examining asset flow and prices.
MEV is the umbrella concept. A sandwich is one predatory ordering pattern within it.
Where sandwiches occur
Public-mempool AMMs
Ethereum’s public peer-to-peer transaction pool is the familiar setting: a pending swap is visible before a builder orders it. Visibility alone is not sufficient; the route must have enough price impact and tolerance for the surrounding trades to cover fees and risk.
Private order flow
A transaction hidden from the public mempool can still be visible to the RPC, builder, relay or permitted searchers. Flashbots Protect explicitly says users trust builders not to frontrun or disclose transactions. Private therefore means restricted visibility, not “nobody can see it.”
Solana and other chains
Solana does not use Ethereum’s public-mempool and MEV-Boost pipeline. Leaders, low-latency feeds and Jito bundle infrastructure create different routes for pre-execution information and ordering. Recent academic measurement has identified sandwich-like patterns in Jito-related Solana activity, so “no public Ethereum mempool” does not imply “no sandwiches.”
Order-book and hybrid venues can also expose predictable marketable orders to before-and-after trading. Matching rules, partial fills and cancellation behavior differ from an AMM, so the constant-product explanation does not transfer unchanged.
Defensive mitigations, with limits
Enforce an economic bound
Review the minimum received or maximum spent, not only a percentage label. A bound limits how badly the transaction may execute. It cannot stop execution near that boundary, guarantee inclusion or distinguish a sandwich from ordinary movement.
Reduce avoidable price impact
A smaller trade relative to available depth presents less movement to capture. A router may split across deeper pools or different venues. Splitting manually can add fees, market exposure and more transactions, so it is not automatically better.
Use private submission carefully
Private RPCs can hide a transaction from the public pool. Check who receives full transaction data, whether it may be forwarded to multiple builders or searchers, how long it remains pending, and whether a wallet can rebroadcast it publicly. The mitigation replaces broad visibility with intermediary trust.
Consider alternative execution designs
RFQ systems can provide a signed quote; intent systems can let solvers compete for a result; batch auctions can execute orders at a common clearing rule. Research on function-maximizing AMMs shows that batching can eliminate sandwich incentives inside its model. Production systems still have solver, auction, oracle, censorship, settlement and implementation assumptions.
Treat labels as claims, not proofs
“MEV protected,” “private,” “zero slippage” and “fair ordering” need precise definitions. Simulation checks the state used by the simulator; it cannot guarantee no later state or ordering change. Confirmation count also does not prevent a sandwich because the ordering occurs inside the block that first includes the swap.
What a user can verify after a swap
A block explorer or analytics tool may show:
- a trade in the same pool immediately before the user;
- the user’s fill at a worse price than the earlier quote or pre-trade state;
- a related reverse trade shortly after;
- linked asset flows or payments among searcher and block-building addresses.
Those clues are not individually conclusive. Arbitrage and unrelated trades can bracket a swap by chance, routers can use several pools, and addresses can change. Reliable attribution reconstructs the route, token amounts, pool states, transaction order and fees.
Sources & further reading
-
Maximal extractable value (MEV)
Primary · Documentation
Sandwich definition, ordering, non-guaranteed execution and defensive context
-
Glossary
Primary · Documentation
Price impact, slippage, swap fees and AMM terminology
-
How Uniswap Works
Primary · Documentation
Reserve-based price movement and pool-depth mechanics
-
Multi-hop Swapping
Primary · Documentation
Direct router documentation that an exact-input swap reverts below amountOutMinimum
-
Quick Start (Flashbots Protect)
Primary · Documentation
Private submission, builder trust, rebroadcast warning and non-inclusion of reverting transactions
-
High-Frequency Trading on Decentralized On-Chain Exchanges
Primary · Paper
Academic formalization and empirical study of AMM sandwich attacks and competing adversaries
-
Eliminating Sandwich Attacks with the Help of Game Theory
Primary · Paper
Analysis of slippage-setting tradeoffs and why constant defaults are inadequate
-
Arbitrageurs’ Profits, LVR, and Sandwich Attacks: Batch Trading as an AMM Design Response
Primary · Paper
Model of batch execution as a response to ordering-based extraction
-
EEA DeFi Risk Assessment Guidelines — Version 1
Primary · Standard
Independent taxonomy of sandwiching and mitigation classes
-
Quantifying the Threat of Sandwiching MEV on Jito: A Measurement of Solana’s Leading Validator Client
Secondary · Analysis
Chain-specific evidence that sandwich-like activity is not limited to Ethereum’s public mempool