Sandwich Attack

A sandwich attack is when a bot spots a pending swap on a decentralized exchange, buys just before it to push the price up, and sells just after it, taking value from the user's trade.

On a public blockchain, a swap waits in the mempool before it is included in a block, where anyone can see it. A sandwich attack exploits that window: a bot places one trade before the victim’s swap and another right after, so the victim buys at a worse price and the bot pockets the difference.1 It is one of the best-known forms of maximal extractable value, or MEV. This entry walks through the mechanics with numbers, shows how slippage tolerance caps the damage, and explains how private transaction routes keep swaps out of view.

Category
Cryptocurrency and Blockchain
Reading time
7 min
Also called
Front-run and back-run, Sandwich trading, Sandwich bot
Updated

Sandwich attacks in plain words

Picture announcing loudly in a market that you are about to buy a large amount of apples. Someone quicker buys first, the price goes up, you pay more, and they sell their apples to you or the next buyer at the higher price. On a DEX, a searcher watches the mempool for a large swap, buys the same token just before it and sells just after it.1

The attack works because DEX prices move with each trade and because transaction order inside a block can be bought with higher fees.2 The user’s main defences are a tight slippage tolerance and sending swaps through a private route that bots cannot see.3

How a sandwich attack works, step by step

  1. The victim signs a swap

    A user submits a DEX swap with a slippage tolerance, the margin of price movement they will accept before the swap fails.4

  2. A bot spots it in the mempool

    Searchers run bots that scan pending transactions for large swaps that will move the price.1

  3. Front-run

    The bot buys the same token first, ordered ahead of the victim, often by paying a higher fee. This pushes the pool price up.2

  4. The victim’s swap executes at a worse price

    The user still trades, as long as the price stays within their slippage tolerance, but receives fewer tokens than quoted.4

  5. Back-run

    Right after the victim’s trade, the bot sells the tokens it bought at the now higher price and keeps the difference.1

  6. Costs and risks for the bot

    The bot pays gas and pool fees, and because the sandwich spans separate transactions it is riskier than a single atomic arbitrage.1

Worked examples

Example 1 — What the victim loses

Victim

A hypothetical pool holds 1,000 ETH and 2,000,000 USDC (price $2,000) and follows the constant-product rule, ignoring pool fees. A user swaps 100,000 USDC for ETH. A bot front-runs with 50,000 USDC.

Example 1 — What the victim loses — calculation
ETH received, no attack≈ 47.62 ETH
ETH received, sandwiched≈ 45.38 ETH
ETH lost to the sandwich47.62 − 45.38 = 2.24 ETH
As a share of the quote2.24 ÷ 47.62 ≈ 4.7%

The front-run moved the price before the user’s trade, so the same 100,000 USDC bought about 2.24 ETH less. The swap only went through because the user’s slippage tolerance was at least 4.7%.

Example 2 — What the bot earns

Attacker

Same hypothetical pool. The bot buys before the victim and sells right after, at the price the victim’s trade pushed up.

Example 2 — What the bot earns — calculation
Front-run: 50,000 USDC buys≈ 24.39 ETH
Back-run: 24.39 ETH sells for≈ 54,931.67 USDC
Gross profit54,931.67 − 50,000 = 4,931.67
Then subtractGas and pool fees

The bot’s gross profit of about 4,932 USDC comes largely out of the victim’s trade. In competitive markets, searchers may hand most of such profit to validators as fees to win the ordering.1

Example 3 — A 0.5% slippage tolerance

Defence

The user instead sets a 0.5% slippage tolerance on the quoted 47.62 ETH. Any execution below the minimum makes the swap fail.4

Example 3 — A 0.5% slippage tolerance — calculation
Minimum accepted47.62 × 0.995 ≈ 47.38 ETH
Output under a 50,000 USDC sandwich≈ 45.38 ETH
Result of that sandwichSwap reverts
Largest front-run that still fits≈ 5,141 USDC
Bot’s gross profit then≈ 525 USDC

A tight tolerance cuts the attack’s room from about 4,932 USDC to about 525 USDC before gas and fees, which often makes it unprofitable. The trade-off is that the swap fails more often in fast markets.

Sandwich attack, front-running and arbitrage

AspectWho is hurtTypical defence
Sandwich attackThe swapper, through worse execution1Tight slippage, private routing
Traditional front-runningClients whose orders a firm trades ahead ofBroker rules and supervision; see Front Running
DEX arbitrageNo single user; it aligns prices across venues1None needed

Why sandwich attacks matter to traders

  • Hidden trading cost

    Sandwiched users face more slippage and worse execution, a cost that never shows as a separate fee.1 See Slippage.

  • Setting slippage tolerance

    A tolerance just wide enough to fill limits what a bot can take. See Slippage Tolerance.4

  • Choosing a transaction route

    Private RPC endpoints such as Flashbots Protect send swaps to a private mempool, out of sight of sandwich bots.3

  • Understanding MEV

    Sandwiches are one MEV strategy alongside arbitrage and liquidations. See Maximal Extractable Value.1

Advantages and disadvantages

Advantages

  • Knowing the mechanics helps traders set sensible slippage limits.
  • The damage can be capped with settings any user controls.
  • Private routing tools are free or cheap and widely available.
  • Breaking large swaps into smaller ones reduces the bot’s potential profit.

Disadvantages

  • The loss is invisible unless you compare the fill with the quote.
  • Large swaps in thin pools are the easiest targets.
  • Very tight slippage settings cause failed swaps and wasted gas.
  • Private routes involve trusting a third-party service.

Going deeper

Read as far as you need. Each level builds on the one before it.

Why the mempool is the weak spot

Beginner

Pending swaps are public before they are confirmed, and gas fees help decide transaction order.4 Anyone who sees your trade first and can pay to go ahead of it can profit from the price move you are about to cause. See Mempool.

From gas auctions to block builders

Intermediate

The 2019 research paper Flash Boys 2.0 documented bots competing in priority gas auctions to get their transactions ordered first on decentralized exchanges, and named the resulting profits miner extractable value.2 After Ethereum moved to proof of stake, the term became maximal extractable value.1

Today much MEV flows through specialised block builders and MEV-Boost relays, which let validators pick the highest-paying block from outside builders.1

Private routing and refunds

Advanced

Flashbots Protect sends transactions to a private mempool so bots cannot see them before inclusion, and only includes transactions that will not revert, so failed swaps cost no gas.3

Through MEV-Share, users can get back part of the value their transaction creates, with the rest split among searchers and validators; privacy settings decide how much information searchers see and therefore how large the refund can be.5

Common mistakes

  1. Leaving slippage on a wide default

    A 3–5% tolerance on a large swap is an open invitation. Set it as tight as the market allows.4

  2. Swapping large size in a thin pool

    Big trades in shallow liquidity move the price most, which is exactly what makes a sandwich profitable. Check Liquidity first or use a DEX Aggregator.

  3. Blaming the DEX fee for a bad fill

    Compare your executed amount with the quote. A gap well beyond price impact and fees may be a sandwich.

  4. Setting slippage to near zero

    Too tight a setting makes ordinary swaps fail, wasting gas. Aim for the smallest tolerance that reliably fills.

Check your understanding

Test yourself before moving on. Each answer comes with an explanation.

Q1You are quoted 10.00 ETH with a 1% slippage tolerance. What is the least ETH your swap can deliver without failing?
Q2Which step completes a sandwich attack?

Key points to remember

  1. A sandwich attack places a buy before and a sell after a victim’s DEX swap.
  2. It works because pending swaps are public and ordering can be bought.
  3. Slippage tolerance caps how much a bot can take; wide settings invite attacks.
  4. Private routes such as Flashbots Protect keep swaps out of the public mempool.
  5. Sandwiching is one form of MEV, alongside arbitrage and liquidations.

Frequently asked questions

Is a sandwich attack illegal?

It depends on the jurisdiction and is largely untested. It resembles front-running in traditional markets, but DEX trades usually lack a broker with duties to the user. Treat it as a cost to manage rather than something you can recover.

How do I know if I was sandwiched?

Look up your swap on a block explorer and check the transactions immediately before and after it in the same block. A buy of the same token just before and a sell just after, from the same address, is the typical pattern.

Do private RPCs stop sandwich attacks completely?

They remove the main attack route by keeping your transaction out of the public mempool until it is included.3 You still rely on the service working as described, and a sensible slippage setting remains a good backstop.

Further learning

Sources

This article is written in our own words. The sources below support the specific facts, rules and figures marked with a number in the text. Links open the original publisher’s page.

  1. ethereum.org. Maximal extractable value (MEV) (opens in a new tab) Checked .
  2. arXiv (Daian et al.). Flash Boys 2.0: Frontrunning, Transaction Reordering, and Consensus Instability in Decentralized Exchanges (opens in a new tab) Checked .
  3. Flashbots Docs. Flashbots Protect overview (opens in a new tab) Checked .
  4. Uniswap Docs. Swaps (opens in a new tab) Checked .
  5. Flashbots Docs. MEV refunds (opens in a new tab) Checked .

Educational content, not financial advice. Examples use hypothetical prices and simplified costs; actual fees, margin rules and regulations vary by broker, market and country. We are not affiliated with any publisher linked above. Last reviewed . Report an error or request a source credit.