Hashtag Web3 Logo

Sandwich Attack in DEX Explained

Learn how sandwich attacks work on decentralized exchanges (DEXs), how they exploit DeFi traders, and what strategies you can use to protect your trades from this common MEV tactic.

Sandwich Attack in DEX Explained - Hashtag Web3 article cover

What is a Sandwich Attack in DeFi? A Complete Guide

A sandwich attack is one of the most common and predatory forms of front-running in Decentralized Finance (DeFi). It occurs when an attacker sees a user's pending trade on a Decentralized Exchange (DEX) and "sandwiches" it between two of their own trades to extract a profit. The attacker's two trades form the "bread," and the victim's trade is the "filling" in the middle.

This exploitative strategy takes advantage of the transparent nature of blockchain mempools and the mechanics of Automated Market Makers (AMMs). The profit generated by the attacker comes directly at the expense of the victim, who ends up with a worse execution price for their trade than they should have.

This guide will walk you through the mechanics of a sandwich attack, explain why they are possible, and detail the steps you can take to protect yourself.

Key Insights

  • Core Concept: A sandwich attack is a three-step front-running strategy: buy, let the victim buy, then sell.
  • The Victim: Any user submitting a sufficiently large trade on a DEX with a loose slippage tolerance is a potential target.
  • The Attacker: Sophisticated bots that constantly monitor the public mempool for profitable sandwiching opportunities.
  • The Result: The attacker makes a near risk-free profit. The victim receives fewer tokens than they expected, effectively having the value extracted by the attacker.
  • Mitigation: Using tight slippage tolerance and MEV (Maximal Extractable Value) protection services are the most effective defenses.

The Anatomy of a Sandwich Attack

Let's break down the attack into its three main steps. Imagine a user, Bob, wants to swap 100 ETH for a token called "CAT" on a DEX like Uniswap.

Step 1: The Front-Run (The First Slice of Bread)

  1. Bob's Transaction: Bob submits his trade to the Ethereum mempool. The mempool is a public waiting area where transactions sit before being included in a block by a miner or validator.
  2. The Bot Scans the Mempool: An attacker's bot constantly scans the mempool for large, profitable trades. It sees Bob's 100 ETH buy order for CAT.
  3. The Bot Places an Order: The bot calculates that Bob's trade will push the price of CAT up. To profit from this, the bot immediately submits its own transaction to buy CAT. To ensure its trade is executed before Bob's, the bot sets a higher gas fee (a "priority fee"). Miners are incentivized to process transactions with higher fees first.

The block is now being formed with the bot's transaction placed just before Bob's.

Step 2: The Victim's Trade (The Filling)

  1. The Bot's Trade Executes: The block is mined. The bot's buy order goes through first, slightly increasing the price of CAT.
  2. Bob's Trade Executes: Bob's trade for 100 ETH now executes, but at a slightly higher average price than he would have gotten originally. Because his trade is large, it significantly pushes up the price of CAT.

Step 3: The Back-Run (The Second Slice of Bread)

  1. The Bot Sells: The attacker's bot had already submitted a second transaction to sell the CAT tokens it bought in Step 1. It sets the gas fee for this transaction to be just high enough to ensure it is included in the same block, immediately after Bob's trade.
  2. The Bot Realizes a Profit: The bot sells its CAT tokens at the new, higher price created by Bob's large purchase.

The Result:

  • Bob received fewer CAT tokens for his 100 ETH because the bot's initial trade pushed the price up, and he was forced to buy at a worse rate. The difference between what he should have received and what he got is his slippage.
  • The attacker's bot made a near risk-free profit by capturing this slippage. Bob's trade was perfectly "sandwiched."

Why Are Sandwich Attacks Possible?

This form of MEV is enabled by the inherent properties of most public blockchains:

  • Public Mempool: All transaction intentions are public knowledge before they are confirmed.
  • AMM Mechanics: The price on an AMM is deterministic. Bots can perfectly predict the price impact of a trade.
  • Gas Price Auctions: Transaction ordering within a block is largely determined by the gas fees paid. Bots can simply outbid a user's gas price to get priority.

How to Protect Yourself from Sandwich Attacks

As a DeFi user, you are not helpless. You can take several steps to avoid becoming a victim.

  1. Set Low Slippage Tolerance: This is the most effective defense. Slippage is the percentage of price movement you are willing to accept for your trade to go through. By default, many DEX interfaces set this to 1-3%, which is an open invitation for sandwich bots. Manually set your slippage to a lower value, like 0.5% or 0.1%. If a bot tries to sandwich you and moves the price by more than your slippage tolerance, your transaction will simply fail (you will still pay gas, but you won't lose the value to the bot).

  2. Use MEV Protection Services:

    • Flashbots: Services like Flashbots allow you to send your transaction to a private relay directly to miners, bypassing the public mempool. If bots can't see your transaction, they can't front-run it. Many popular wallets (like MetaMask) and DEX aggregators have integrated Flashbots or similar MEV protection RPCs.
    • DEX Aggregators: Services like 1inch or CowSwap have built-in mechanisms to prevent sandwich attacks by routing trades through private liquidity or using batch auctions.
  3. Trade on Low-Liquidity or Less Common DEXs: Bots tend to focus on the most popular, high-liquidity pairs on major DEXs like Uniswap. Trading on less popular exchanges can sometimes help you avoid their attention, though this may come with its own risks and higher fees.

  4. Split Your Trades: Instead of making one very large trade, break it into several smaller ones. Smaller trades have less price impact and are less likely to be profitable targets for sandwich bots.

Frequently Asked Questions (FAQ)

Q: Am I at risk if I'm making a small trade? A: Generally, no. Sandwich bots are looking for trades that are large enough to move the price sufficiently to cover their gas costs (for two transactions) and still leave a profit. Small retail trades are usually not profitable targets.

Q: Is there a way to guarantee my trade won't be sandwiched? A: Using an MEV protection service like Flashbots is the closest you can get to a guarantee, as it completely hides your transaction from the public mempool where bots operate.

Q_ Do I lose all my money in a sandwich attack? A: No. You don't lose your principal investment. What you lose is the value extracted through slippage. For example, instead of receiving 1000 CAT tokens, you might receive 980 CAT tokens. The value of those missing 20 tokens is the profit captured by the bot.

Q: Why don't DEXs build in protection by default? A: Some are starting to. Protocols like CowSwap use batch auctions to prevent this. However, for a standard AMM like Uniswap, the permissionless nature of the blockchain makes it difficult to prevent MEV at the protocol level without significant architectural trade-offs.


Internally, this article links to: what-is-frontrunning-in-defi-trading, what-is-price-impact-in-dex-trading

Looking for a Web3 Job?

Get the best Web3, crypto, and blockchain jobs delivered directly to you. Join our Telegram channel with over 58,000 subscribers.