Skip to main content
← Back to Learn

Sandwich Attack Anatomy: How MEV Bots Exploit the Mempool

A step-by-step breakdown of how sandwich attacks work in the public mempool, how MEV bots detect targets, and why slippage tolerance alone doesn't protect you.

Every time you submit a swap on a decentralized exchange, your transaction sits in the public mempool before it is mined. While it sits there, anyone can see it. MEV bots watch that mempool in real time, parse pending transactions, and when they spot a profitable opportunity, they front-run and back-run your trade. This is called a sandwich attack. It is one of the most common forms of maximal extractable value extraction on Ethereum and other EVM chains.

This article explains how sandwich attacks work at a mechanical level. We will cover the mempool, how bots detect targets, the exact sequence of transactions in a sandwich, why slippage tolerance does not protect you, and what public tools exist for detecting whether your transaction was sandwiched. Everything here is public knowledge. Sandwich attacks are a well-documented phenomenon studied by researchers, discussed in Ethereum improvement proposals, and visible on public block explorers.

What Is the Mempool

The mempool is the staging area for pending transactions. When you submit a transaction to an Ethereum node, the node does not mine it immediately. It adds the transaction to its mempool, a local list of pending transactions, and broadcasts it to other nodes. Validators and miners eventually select transactions from the mempool, order them, and include them in blocks.

The mempool is public. Anyone running a node can see every pending transaction. There are also specialized mempool monitoring services that provide real-time streaming of pending transactions via WebSocket APIs. Flashbots, MEV-Share, and other public infrastructure projects provide access to this data.

This transparency is the foundation of MEV. Because transactions are visible before they are mined, bots can analyze them, predict their market impact, and submit competing transactions that exploit the predictable price movement.

What Is a Sandwich Attack

A sandwich attack is a three-transaction pattern. The victim submits a swap that moves the price of a token. The attacker sees this pending swap and inserts two transactions around it.

Transaction 1, the front-run. The attacker buys the same token the victim is buying. This pushes the price up before the victim's transaction executes.

Transaction 2, the victim's swap. The victim's transaction executes at the inflated price. The victim pays more than they would have if the attacker had not front-run them.

Transaction 3, the back-run. The attacker sells the token they just bought. Because the victim's swap pushed the price up further, the attacker sells at a higher price than they bought.

The attacker profits from the price difference. The victim pays a worse price. The attacker's profit is extracted directly from the victim's trade.

The Mechanics, Step by Step

Let's walk through a concrete example using a constant product automated market maker, the model used by Uniswap V2 and many other DEXes. The invariant is x * y = k, where x and y are the reserves of two tokens and k is a constant. The price of token A in terms of token B is y / x.

Suppose a liquidity pool has 1000 ETH and 2,000,000 USDC. The price of ETH is 2,000 USDC. A user submits a transaction to buy 10 ETH with USDC. Using the constant product formula, this trade would move the price to approximately 2,040 USDC per ETH. The user expects to pay around 20,400 USDC for 10 ETH, accounting for slippage.

Now the attacker steps in.

The attacker sees the pending transaction in the mempool. The attacker calculates that the victim's 10 ETH buy will move the price from 2,000 to 2,040. The attacker submits a front-run transaction buying, say, 5 ETH. This moves the price to approximately 2,010. The attacker pays around 10,100 USDC.

The attacker's transaction is submitted with a higher gas price, or through a private relay that prioritizes ordering, so it is included in the block before the victim's transaction.

Now the victim's transaction executes. The pool is now at a price of 2,010, not 2,000. The victim's 10 ETH buy moves the price from 2,010 to approximately 2,051. The victim pays around 20,510 USDC instead of 20,400 USDC. The victim gets a worse price because the attacker's front-run moved the starting price up.

Then the attacker's back-run executes. The attacker sells 5 ETH. The pool is at 2,051 after the victim's trade. The attacker sells into this higher price, receiving around 10,255 USDC. The attacker paid 10,100 USDC and received 10,255 USDC. Profit is approximately 155 USDC, minus gas costs.

The victim lost approximately 110 USDC to the sandwich. That value was transferred to the attacker.

How MEV Bots Detect Targets

MEV bots do not attack every transaction. They scan the mempool and filter for transactions that are profitable to sandwich. The detection logic is straightforward in principle.

First, the bot monitors pending transactions. It connects to one or more Ethereum nodes or mempool services and receives a stream of pending transactions in real time.

Second, it decodes each transaction. Using the transaction's to address and calldata, the bot identifies the function being called and the parameters. For a Uniswap V2 swap, the calldata encodes the path, the amount in, the amount out minimum, and the recipient. The bot parses these fields.

Third, it simulates the transaction. The bot runs the transaction against a local copy of the blockchain state, using a fork of the current block. This simulation tells the bot exactly how the pool reserves will change and what price the victim will receive.

Fourth, it calculates profitability. The bot determines whether inserting a front-run and back-run around the victim's transaction would be profitable after gas costs. This involves simulating the front-run, then the victim's transaction on top of the front-run, then the back-run. If the net profit after gas is positive, the bot proceeds.

Fifth, it submits the sandwich. The bot submits the front-run and back-run transactions, either through the public mempool with higher gas prices or through a private relay like Flashbots that allows precise transaction ordering within a block.

This entire process happens in milliseconds. The bot sees the pending transaction, simulates it, and submits the sandwich before the next block is mined. On Ethereum, where blocks are approximately 12 seconds apart, the bot has a window of a few seconds to act.

Why Slippage Tolerance Does Not Protect You

Most DEX interfaces let you set a slippage tolerance, typically 0.5% to 1%. This sets the minimum amount out you are willing to accept. If the executed amount falls below this threshold, the transaction reverts.

Many users believe slippage tolerance protects them from sandwich attacks. It does not. Here is why.

A sandwich attacker specifically targets transactions with slippage tolerance high enough to absorb the sandwich. The attacker's front-run pushes the price up. The victim's transaction then executes at the inflated price. If the victim's slippage tolerance is high enough to accept the inflated price, the transaction goes through and the attacker profits.

If the slippage tolerance is too low, the victim's transaction reverts. The attacker's front-run still executes, but without the victim's transaction in the middle, the back-run sells at the same price the front-run bought at. The attacker loses gas fees with no profit. So attackers simply skip transactions with low slippage tolerance.

This means slippage tolerance acts as a threshold, not a shield. Set it too high, and you are an easy target. Set it low enough, and the attacker skips you. But setting it too low means your transaction may revert due to normal price movement, costing you gas with no swap.

The optimal slippage tolerance is a tradeoff. You want it low enough to deter most sandwich attacks but high enough to survive normal price movement and network latency. For most liquid pools, 0.5% is a reasonable starting point. For illiquid pools, you may need higher tolerance, which makes you more vulnerable.

Real-World Examples on Etherscan

Sandwich attacks are visible on public block explorers. You can find them by looking for the three-transaction pattern in a single block: a buy, followed by the victim's swap, followed by a sell, all on the same liquidity pool.

A common way to find examples is to look at the MEV transaction labels on Etherscan. Etherscan tags some addresses as MEV bots. If you look at the transaction history of these addresses, you will see patterns of buying and selling the same token in the same block, always paired with a third-party swap in between.

Another approach is to use public MEV dashboards. Flashbots maintains MEV-Explore, a public dashboard that lists extracted MEV by type, including sandwich attacks. Each entry links to the relevant transactions on Etherscan. EigenPhi and other public analytics tools also provide sandwich attack data with transaction hashes.

When you examine a sandwich on Etherscan, look at the block. You will see the attacker's front-run transaction at a lower transaction index, the victim's transaction at a higher index, and the attacker's back-run at the highest index. The ordering within the block is what makes the sandwich work. The attacker ensures their transactions bracket the victim's.

The Economics of Sandwiching

Sandwich attacks are not free for the attacker. The attacker pays gas for two transactions, the front-run and the back-run. The attacker also pays a priority fee or a bribe to the validator to ensure their transactions are ordered correctly.

The attacker's profit is the difference between what they paid in the front-run and what they received in the back-run, minus gas costs and validator bribes. For the attack to be worthwhile, this profit must be positive.

This means small trades are generally not worth sandwiching. The gas cost of two transactions plus the validator bribe creates a minimum profit threshold. On Ethereum mainnet, this threshold is relatively high. On L2s with lower gas costs, the threshold is lower, which means smaller trades are vulnerable.

The attacker also faces competition. Multiple MEV bots monitor the same mempool. When a profitable opportunity appears, they race to submit the best sandwich. This competition is resolved through a priority gas auction. The bot that pays the highest priority fee or validator bribe wins. This competition erodes the attacker's profit margin, with more of the extracted value going to the validator.

How to Detect If You Were Sandwiched

If you want to check whether your transaction was sandwiched, you can do so using public tools, as described in our forensic DEX settlement auditing methodology.

Method 1. Check the block for related transactions. Find your transaction on Etherscan. Note the block number and the pool address. Look at all transactions in that block that interact with the same pool. If you see a buy immediately before your transaction and a sell immediately after, both from the same address, you were likely sandwiched.

Method 2. Compare quoted vs executed price. Before your transaction, query the pool reserves. Calculate the expected output for your input amount. Then check the actual output from your transaction's receipt. If the actual output is significantly worse than the expected output, and there is no other obvious explanation like a large trade immediately before yours, a sandwich is likely.

Method 3. Use MEV analytics tools. EigenPhi, Flashbots MEV-Explore, and other public dashboards list sandwich attacks with victim transaction hashes. Search for your transaction hash in these tools.

Method 4. Use the eth_getBlockReceipts RPC method to fetch all receipts for the block containing your transaction. Parse the logs for the pool address. Look for Swap events from other addresses in the same block. This is the programmatic approach for building your own detection tool.

Here is a generic example of fetching block receipts and filtering for swap events:

const blockReceipts = await provider.send("eth_getBlockReceipts", [
  blockHash,
]);

const swapsInBlock = blockReceipts.filter((receipt) =>
  receipt.logs.some(
    (log) =>
      log.address.toLowerCase() === poolAddress.toLowerCase() &&
      log.topics[0] === SWAP_EVENT_TOPIC
  )
);

const sandwichPattern = findSandwichPattern(swapsInBlock, yourTxHash);

The findSandwichPattern function would check for a swap from the same address before and after your transaction, with opposite directions.

Mempool Privacy and Alternative Solutions

The root cause of sandwich attacks is mempool transparency. If transactions were not visible before execution, bots could not front-run them. Several approaches address this at the protocol level.

Private transaction relays. Services like Flashbots Protect and MEV-Share route transactions through private channels that bypass the public mempool, similar to how Permit2 signature relay keeps approval signatures off the public mempool. Instead of broadcasting to all nodes, the transaction is sent directly to builders who include it in a block. This is conceptually similar to the gasless signature relay pattern where the user's signature never touches the public mempool. The transaction is not visible in the public mempool, so sandwich bots cannot see it. This is a widely used public service.

Batch auctions. Some DEX designs batch all transactions in a block and settle them at a single clearing price. This eliminates the ordering advantage that sandwich attacks rely on. CoWSwap uses this model, settling trades through a batch auction mechanism.

Commit-reveal schemes. These require users to commit a hash of their intended trade first, then reveal the trade details after the commit is finalized. This prevents front-running because the trade details are hidden until it is too late to front-run. The tradeoff is additional latency and complexity.

Threshold encryption. Some research proposals encrypt mempool transactions and only decrypt them after ordering is finalized. This would prevent any mempool monitoring, but it requires changes at the protocol level and is not yet deployed on Ethereum.

Each of these approaches is public and documented. None of them are specific to any single product or company.

The Broader MEV Landscape

Sandwich attacks are one form of MEV, but not the only form. Other common types include arbitrage, where bots exploit price differences between pools, and liquidations, where bots compete to liquidate undercollateralized positions.

Arbitrage is generally considered benign or even beneficial, as it aligns prices across markets. Liquidations are a necessary function of lending protocols. Sandwich attacks are more controversial because they extract value from ordinary users without providing any corresponding service.

The Ethereum community has invested significant effort in addressing MEV. Proposals like PBS, proposer-builder separation, aim to make block building more competitive and fair. MEV-Share and MEV-Blocker allow users to capture some of the MEV generated by their own transactions. These are all public initiatives with open documentation.

Practical Takeaways for Developers

If you are building a DEX integration or a trading bot, understanding sandwich attacks is essential.

First, always set slippage tolerance carefully. Do not use high slippage tolerances by default. 0.5% is a reasonable starting point for liquid pools. For large trades relative to pool size, consider splitting the trade across multiple transactions or multiple pools.

Second, consider routing transactions through a private relay. Flashbots Protect and similar services are free to use and prevent your transactions from appearing in the public mempool. This eliminates the vast majority of sandwich attacks.

Third, if you are building a trading bot, simulate your transactions before submitting them. Use a local fork of the current block state to estimate the expected output. After execution, compare the actual output to the expected output. Large discrepancies indicate MEV extraction.

Fourth, monitor the blocks containing your transactions. If you see suspicious trading patterns around your transactions, investigate. Building a simple sandwich detection tool using the eth_getBlockReceipts method is straightforward and can alert you to extraction, forming the basis of a full settlement audit.

Where to Learn More

The Flashbots documentation provides detailed information on MEV extraction, private relays, and the builder ecosystem. The Ethereum Foundation's MEV research page collects academic papers and EIPs related to MEV. EigenPhi's public dashboard provides real-time MEV data with transaction-level detail.

The Uniswap V2 and V3 contracts are open source, and the constant product formula is well documented. Understanding the math behind AMMs is essential for understanding why sandwich attacks work.

For detecting sandwich attacks programmatically, the eth_getBlockReceipts RPC method is available on most Ethereum node providers. Etherscan's API provides transaction and block data. These are all public, free or freemium resources.

Summary

Sandwich attacks exploit the public mempool to extract value from DEX swaps. A bot sees your pending transaction, front-runs it to push the price up, lets your transaction execute at the inflated price, then back-runs to sell at the higher price. The bot profits, you lose.

Slippage tolerance does not protect you. It acts as a threshold that determines whether you are worth attacking. Set it too high and you are a target. Set it low and you risk reverts from normal price movement.

The most effective defense is mempool privacy. Routing transactions through private relays prevents bots from seeing them in the first place. This is a free, public service available to anyone.

Sandwich attacks are a structural consequence of how Ethereum orders transactions. They are not a bug in any specific protocol. They are an economic arbitrage that exists because pending transactions are public and block ordering is flexible. Understanding the mechanics is the first step to protecting your users.

Frequently Asked Questions

What is a sandwich attack?

A sandwich attack is a form of maximal extractable value (MEV) exploitation where a bot places two transactions around a victim's pending swap to profit from the price movement it causes. The bot first submits a buy transaction that pushes the price up, then the victim's swap executes at the worse price, and finally the bot sells at the inflated price for a profit. The victim pays a higher effective price because the bot's front-run transaction moved the pool against them. Sandwich attacks are possible whenever a transaction's price impact is visible before execution.

How do MEV bots detect transactions?

MEV bots monitor pending transactions before they are included in a block by subscribing to the public mempool through node RPCs or specialized relay services. They decode the calldata of each transaction, simulate its execution against current pool state, and compute the price impact and potential profit from front-running or back-running. If the simulated profit exceeds the gas cost, the bot submits competing transactions with higher gas prices to be ordered favorably. Detection happens in milliseconds and is fully automated.

What is the public mempool?

The public mempool is the set of pending, unconfirmed transactions that nodes broadcast to each other before a validator or miner includes them in a block. Transactions in the mempool are visible to anyone running a full node or connected to a mempool feed, which is how MEV bots observe them. Not all transactions pass through the public mempool; private order flow and direct-to-builder submission can bypass it. The mempool is a gossip network, not a single canonical queue, so different nodes may see different subsets of pending transactions.

How fast do MEV bots react?

MEV bots typically react within tens to hundreds of milliseconds of observing a target transaction in the mempool. The bottleneck is simulation and transaction submission, not detection, since bots run hot loops that continuously evaluate incoming transactions. On networks like Ethereum, the bot must outbid the victim on gas price or use direct builder submission to ensure profitable ordering. Sub-block latency is the norm, and competition among bots has driven reaction times close to the network's propagation delay.

Can sandwich attacks be prevented?

Sandwich attacks cannot be fully prevented at the protocol level as long as transactions are visible before execution, but several mitigations reduce exposure. Submitting transactions through private order flow or direct-to-builder relays keeps them out of the public mempool where bots observe them. Using slippage tolerance limits caps the maximum acceptable price movement, causing the swap to revert if the front-run pushes the price beyond the limit. Automated router-level MEV protection and batching auctions also reduce the profitability and feasibility of sandwiching.

Orkid routes swaps through a private solver rather than the public mempool, which removes the visibility window sandwich bots need. Swap MEV-protected — or compare against CoW Swap, which mitigates it differently.

Put it to work

The research above powers the product — try it or compare it: