A sandwich attack is a market manipulation strategy executed on Automated Market Makers (AMMs) like Uniswap. An attacker, typically a MEV (Maximal Extractable Value) bot, identifies a large, pending user transaction that will move the market price of an asset. The bot then places two of its own transactions around the victim's: one to buy the asset just before, and one to sell it just after. This 'sandwiches' the victim's trade, artificially inflating the price they pay and allowing the attacker to profit from the price difference, known as slippage.
Sandwich Attack
What is a Sandwich Attack?
A sandwich attack is a form of front-running specific to decentralized exchanges where a malicious trader exploits the public nature of pending transactions to profit at the expense of a regular user.
The attack exploits the mempool, where pending transactions are visible before confirmation. By using sophisticated algorithms and paying higher gas fees to ensure their transactions are mined in the correct order, the attacker's initial purchase increases the asset's price on the AMM's bonding curve. The victim's trade then executes at this inflated price. The attacker's immediate sell order capitalizes on the post-trade price, often returning the market close to its original state while extracting value. The victim suffers from worse-than-expected execution, a loss quantified as negative slippage.
Common targets are high-slippage tolerance trades and low-liquidity pools, where a single transaction has a more pronounced price impact. To mitigate risk, traders can use slippage protection, set lower transaction sizes, or utilize DEX aggregators and private transaction services like Flashbots that bypass the public mempool. While sandwich attacks represent a significant challenge in DeFi, they are a direct consequence of the transparent, decentralized nature of blockchain settlement, highlighting the ongoing competition for block space and value extraction.
How a Sandwich Attack Works
A sandwich attack is a form of front-running specific to decentralized finance (DeFi) that exploits the public nature of pending transactions on a blockchain to extract value from a target trade.
A sandwich attack is a type of Maximal Extractable Value (MEV) exploit where a malicious actor, often a bot, manipulates the price of an asset in a decentralized exchange's liquidity pool to profit at the expense of a regular user. The attack is executed by placing two transactions that 'sandwich' the victim's transaction: one placed immediately before to drive the price in an unfavorable direction, and one placed immediately after to profit from the price movement. This is possible because transactions are visible in the public mempool before they are confirmed, allowing attackers to analyze and front-run them.
The attack proceeds in three distinct steps. First, the attacker identifies a large pending trade, typically a swap on an Automated Market Maker (AMM) like Uniswap, that will significantly impact the asset's price. Second, they submit a transaction with a higher gas fee to ensure it is mined before the victim's transaction, buying the same asset and artificially inflating its price. Third, after the victim's trade executes at this worse price, the attacker immediately sells the asset in a follow-up transaction, profiting from the price reversion. The victim is left with slippage and a less favorable exchange rate.
This exploit is fundamentally enabled by the transparency of public blockchains and the design of constant-product AMMs, where large trades create predictable price impacts. Attackers use sophisticated algorithms to calculate the optimal trade size to maximize their profit without causing the attack to fail. Defensive measures include using private transaction relays (like Flashbots Protect), setting lower slippage tolerances, and trading on DEXs that implement mechanisms such as time-weighted average price (TWAP) orders or threshold encryption to obscure transaction details until they are confirmed.
Key Features of a Sandwich Attack
A sandwich attack is a form of frontrunning that exploits the predictable execution of trades on decentralized exchanges (DEXs). It involves three key steps: detection, frontrun, and backrun.
The Three-Transaction Sequence
The attack is defined by a specific, three-step transaction sequence executed by the attacker against a victim's trade.
- Frontrun: The attacker places a buy order for the same asset, driving up its price.
- Victim's Trade: The victim's original, now more expensive, trade executes.
- Backrun: The attacker sells the asset they just bought, profiting from the inflated price caused by the victim's trade.
Dependence on Mempool Visibility
This attack is only possible on blockchains where pending transactions are visible in the public mempool before confirmation. Attackers use bots to monitor for large, profitable trades. This makes Ethereum and other similar chains primary targets, while chains with private mempools or immediate execution (e.g., Solana) are less susceptible.
Exploitation of Slippage Tolerance
The attack capitalizes on the victim's slippage tolerance setting. If the victim sets a high slippage tolerance (e.g., 5%) to ensure their trade goes through, it creates a larger price range for the attacker to manipulate and extract value from. The profit is essentially the difference between the price the victim pays and the market price, captured by the attacker.
Automated Bot Execution
Sandwich attacks are executed entirely by automated MEV (Maximal Extractable Value) bots. These bots:
- Continuously scan the mempool.
- Use gas auction mechanics to ensure their frontrun transaction is mined first.
- Calculate profitability in milliseconds.
- Are responsible for the vast majority of sandwich activity on networks like Ethereum.
Impact on Liquidity Pools
The attack directly impacts the automated market maker (AMM) pool used for the trade. The attacker's rapid buy and sell actions create artificial price movement and increase volatility within the pool. This can lead to temporary loss for liquidity providers and worse execution prices for all subsequent traders until arbitrage corrects the price.
Step-by-Step Attack Mechanism
A detailed breakdown of the sequential steps an attacker takes to execute a sandwich attack against a decentralized exchange (DEX) user.
A sandwich attack is a form of maximal extractable value (MEV) exploitation where an attacker manipulates a victim's DEX transaction by placing two of their own orders around it. The attack unfolds in a specific, automated sequence: first, the attacker front-runs the victim's pending trade by placing a buy order for the same asset, driving its price up; the victim's trade then executes at this inflated price; finally, the attacker back-runs the transaction by immediately selling the acquired asset, profiting from the price discrepancy created by the victim's own trade. This three-step process—front-run, victim execution, back-run—'sandwiches' the target transaction.
The attack is initiated when an attacker, typically a searcher bot, uses specialized software to monitor the mempool for pending transactions with high slippage tolerance. Upon detecting a profitable opportunity, the bot submits its own transaction with a higher gas fee to ensure it is mined first—this is the front-running buy. The core mechanism relies on the predictable price impact of the victim's large trade within an automated market maker (AMM) liquidity pool. The attacker's initial purchase artificially increases the asset's price in the pool before the victim's order executes.
Following the victim's trade, the pool's price is now even more favorable for the attacker's exit. The bot immediately submits a sell transaction (the back-run) to liquidate the assets it purchased in step one. The profit is the difference between the inflated purchase price the victim paid and the price the attacker obtained, minus gas costs. This entire cycle, from detection to final settlement, often occurs within a single block and is executed programmatically by MEV bots competing to capture value from pending transactions.
Key prerequisites for a successful sandwich attack include a transparent mempool, sufficient liquidity in the target pool to absorb the trades, and a victim transaction with a high slippage tolerance that allows execution despite the manipulated price. Defensive measures involve using private transaction relays, setting lower slippage limits, or trading on DEXs with built-in MEV protection. The attack exemplifies how transparent blockchain data can be weaponized for profit at the expense of regular users.
Security Considerations & Risks
A sandwich attack is a form of Maximal Extractable Value (MEV) exploitation where a malicious actor (the attacker) manipulates a pending transaction's execution price by placing their own transactions before and after it in the same block.
Core Attack Mechanism
The attack involves three sequential transactions in a single block:
- Front-run: The attacker places a buy order for an asset, detecting a pending victim's large buy order via the mempool.
- Victim Execution: The victim's buy order executes, but due to the attacker's prior purchase, it now trades at a higher price, pushing the price up further.
- Back-run: The attacker immediately sells the asset they bought in step 1, profiting from the inflated price caused by the victim's trade.
The victim suffers from slippage and pays a worse price than expected.
Key Prerequisites & Attack Vectors
Sandwich attacks require specific conditions to be viable:
- Transparent Mempool: The attacker must see the victim's pending transaction details (e.g., token, amount, slippage tolerance) before it is mined.
- Sufficient Liquidity: The target pool must have enough liquidity for the attacker to move the price and exit.
- High Slippage Tolerance: The victim's transaction must have a high enough slippage setting to not revert when the price worsens.
Attacks are most common on Automated Market Makers (AMMs) like Uniswap, where price is a direct function of the pool's reserves.
Defensive Strategies for Users
Users can mitigate the risk of being sandwiched through several methods:
- Reduce Slippage Tolerance: Setting a very low maximum slippage (e.g., 0.5%) can cause the transaction to revert if front-run, though it may also fail during normal volatility.
- Use Private Transactions: Services like Flashbots Protect or Tornado Cash (for privacy) submit transactions directly to miners/validators, bypassing the public mempool.
- Trade During Low Activity: Executing trades during periods of low network congestion and MEV bot activity reduces visibility.
- Use DEX Aggregators: Aggregators like 1inch often split trades across multiple pools and use private RPCs to obscure intent.
Protocol-Level Mitigations
Blockchain and application developers implement systemic solutions:
- Fair Sequencing Services (FSS): Protocols that reorder transactions to prevent front-running, ensuring a first-seen, first-served order.
- Threshold Encryption: Encrypting transaction content in the mempool until it is included in a block (e.g., Shutter Network).
- Commit-Reveal Schemes: Users submit a commitment hash first and reveal the transaction details later, hiding intent until it's too late to front-run.
- Proposer-Builder Separation (PBS): In Ethereum's roadmap, PBS can help separate block building from proposing, allowing for more transparent and fair block construction markets.
Related MEV Concepts
Sandwich attacks are one specific type of value extraction within the broader MEV landscape:
- Front-running: Generally, any transaction that jumps ahead of another to capitalize on its information.
- Back-running: A transaction that follows another to profit from its state changes (e.g., liquidations).
- Arbitrage: Exploiting price differences between markets, which is often considered "good" or necessary MEV for market efficiency.
- Liquidation Bots: A specific form of back-running that triggers and profits from undercollateralized loan liquidations in protocols like Aave or Compound.
Economic Impact & Measurement
Sandwich attacks represent a direct wealth transfer from regular users to sophisticated bots.
- Quantifying Losses: Research from organizations like Flashbots estimates hundreds of millions of dollars have been extracted via sandwich attacks, though precise measurement is complex.
- Network Effects: These attacks increase gas prices as bots compete to have their transactions ordered first, imposing a negative externality on all network users.
- Ecosystem Cost: Beyond direct losses, they degrade user trust and can make decentralized trading prohibitively expensive for retail participants during high-activity periods.
Mitigation & Prevention Strategies
A sandwich attack is a form of Maximal Extractable Value (MEV) where a malicious actor exploits a pending transaction by placing their own orders both before and after it, manipulating the price to profit at the target's expense. These strategies focus on protecting users from this front-running.
Slippage Tolerance
The primary user-level defense. Setting a low slippage tolerance (e.g., 0.5%) in your transaction prevents it from executing if the price moves beyond that limit, making the attack unprofitable for the bot. However, too low a tolerance can cause legitimate trades to fail in volatile markets.
- Key Concept: A trade parameter defining the maximum acceptable price impact.
- Trade-off: Security vs. transaction success rate.
Limit Orders & TWAP
Using Time-Weighted Average Price (TWAP) strategies or limit orders on DEX aggregators breaks a large trade into many small ones over time. This minimizes price impact per trade, reducing the profit opportunity for a sandwich attack and often making its gas costs prohibitive.
- Example: A $1M swap executed as 100 trades of $10k each over an hour.
- Tool: Commonly available on advanced DeFi platforms and aggregators.
Gas Optimization & Timing
A tactical approach where users submit transactions with higher gas fees (priority fees) to outbid potential attackers, or execute trades during periods of low network congestion and low MEV activity. This reduces the likelihood of being the most profitable target for a bot.
- Strategy: Increase transaction cost for attackers.
- Monitoring: Use tools like EigenPhi to track MEV bot activity.
DEX Design & AMM Innovation
Next-generation Automated Market Makers (AMMs) are being designed with MEV resistance in mind. Features like just-in-time liquidity, discrete batch auctions, and threshold encryption of orders aim to structurally prevent the visibility and arbitrage opportunities that sandwich attacks rely on.
- Innovation: Changing the fundamental market mechanics.
- Future: A long-term, protocol-native solution to the problem.
Comparison with Other MEV Strategies
A feature and risk comparison of common MEV extraction strategies, highlighting the distinct mechanics and impacts of sandwich attacks.
| Feature / Metric | Sandwich Attack | Arbitrage | Liquidations |
|---|---|---|---|
Core Mechanism | Frontrun & backrun a target user transaction | Exploit price differences across DEXs or pools | Execute undercollateralized positions |
Primary Target | Retail traders' market orders | Market inefficiencies (price delta) | Overleveraged borrowers |
Extraction Source | User slippage (value transfer from victim) | Protocol/AMM arbitrage spread | Liquidation bonus (protocol-defined) |
Network Impact | Increases gas prices, worsens user slippage | Improves price efficiency across venues | Maintains protocol solvency |
User Harm | Direct and measurable (slippage loss) | Indirect (minor frontrunning possible) | Targeted (loss of collateral for borrower) |
Detection Difficulty | Moderate (requires pattern analysis) | Low (public on-chain data) | Low (public health factors) |
Mitigation Strategies | Private RPCs, slippage limits, TWAP | Permissionless, often beneficial | Health factor monitoring, keepers |
Real-World Examples & Context
Sandwich attacks are a form of Maximal Extractable Value (MEV) where a bot exploits the public mempool to profit from a user's pending transaction. These examples illustrate how they manifest in practice.
The Classic DEX Swap
This is the most common scenario. A user submits a large swap order on a DEX like Uniswap.
- Step 1: A searcher bot detects the pending buy order for Token A in the mempool.
- Step 2: The bot front-runs the user, buying Token A first, which drives up its price.
- Step 3: The user's transaction executes at the now-higher price.
- Step 4: The bot immediately back-runs the user, selling Token A for a profit, creating slippage for the victim.
Anatomy of Profit & Loss
The attacker's profit is the victim's loss plus gas fees. For example:
- Victim's Order: Wants to buy 100 ETH worth of a token.
- Attack Execution: Bot sandwich causes 2% effective slippage.
- Result: Victim receives ~2% fewer tokens. The bot captures most of this value, minus the cost of its two gas-intensive transactions. The loss is often invisible, buried in the approved 'slippage tolerance'.
Notable Historical Incident
In 2021, a single Ethereum address (known as 'jaredfromsubway.eth') was identified as a prolific sandwich attacker. Analysis by researchers revealed:
- The bot executed hundreds of thousands of attacks.
- It earned over $30M in profit over several months.
- This case study highlighted the scale and automation of MEV extraction, turning it from a theoretical concern into a measurable economic force on the network.
Related MEV Strategies
Sandwich attacks are one component of the broader MEV landscape. Other common strategies include:
- Front-running: Submitting a transaction with a higher gas fee to execute before a known pending transaction.
- Back-running: Submitting a transaction immediately after another to capitalize on the state change (e.g., liquidations).
- Arbitrage: Exploiting price differences for the same asset across different DEXs or liquidity pools.
Frequently Asked Questions (FAQ)
Common questions about the mechanics, prevention, and impact of sandwich attacks in decentralized finance.
A sandwich attack is a type of front-running exploit on a decentralized exchange (DEX) where a malicious actor (the attacker) places two transactions around a victim's pending transaction to profit from the price movement it causes. The attacker first buys the asset the victim is about to buy (the front-run), causing its price to rise. After the victim's transaction executes at the inflated price, the attacker immediately sells the asset (the back-run), profiting from the difference. This attack exploits the public visibility of transactions in the mempool before they are confirmed.
Get In Touch
today.
Our experts will offer a free quote and a 30min call to discuss your project.