Sandwich Attack on a DEX

Sandwich attacks front-run your DEX trade in the public mempool, inflating the price by several percent before your order fills.

SECURITY5 min readBy AlgoSys Editorial TeamPublished Apr 24, 2026Updated Jun 26, 2026
Contents

A sandwich attack is a form of front-running in which an attacker profits from the very ordering of transactions in a blockchain's mempool. The mempool is the queue of unconfirmed transactions waiting to be included in a block, and it is public: anyone can look inside. These attacks are most common on decentralized exchanges (DEX) that run on automated market makers (AMM), meaning on a formula where the price of a token depends on the ratio of assets in the liquidity pool.

The idea itself is simple. The attacker watches the mempool for a large buy order. Once they find such a trade, they place their own buy directly before the victim's transaction and their sell immediately after it. The victim ends up "sandwiched" between two orders, like the filling in a sandwich: their trade executes at a worse price, and the attacker pockets the difference.

Notable cases include widespread DEX exploitation during periods of high volatility that affected many users. Attributing a specific incident exclusively to a sandwich attack without deep forensic analysis is difficult, but the mechanism itself has been a persistent threat since the dawn of DeFi. The Lazarus Group has also been observed employing various transaction manipulation tactics.

MECHANICS

Everything starts with observation. The attacker monitors the mempool for pending transactions, especially large buys on AMM-based DEXs. They identify a target, such as a user trying to buy a large amount of some token, because it is precisely a large order that will noticeably move the price in the pool.

Next comes the first slice of "bread." The attacker submits their own buy of the same token and sets a higher gas price (the fee paid to the validator for priority) so their transaction lands in the block before the victim's. This buy pushes the token's price up before the victim's trade executes.

Immediately after that, the second slice goes in. The attacker submits a second transaction to sell the token they just bought, again with a high gas price, but timed to land in the block right after the victim's transaction. This sale captures the profit from the price spike that the victim's own purchase caused.

In the end, the victim's trade executes at a price inflated by the attacker's initial buy, and the attacker earns the difference between their buy and sell. The victim experiences significant slippage, paying more for the tokens than they expected when they submitted the order.

To see this in numbers, imagine a pool where a token costs 100 dollars and you want to buy a large amount with a 5 percent slippage tolerance:

Step Action Token price
1 Bot buys before you 100 → 103
2 Your buy executes 103 → 105
3 Bot sells right after you 105 → 100

You expected to pay 100 but paid around 105, giving away an extra 5 percent essentially for nothing. That money stayed with the bot as the profit between its buy at 103 and its sell at 105. If your slippage tolerance had been 1 percent instead of 5, the trade would simply have been cancelled at step 2 and the attack would not have worked.

RED FLAGS

The primary signal is an execution price noticeably worse than what you saw when you submitted. If your DEX trades regularly show higher-than-expected slippage, it is worth inspecting the transaction details in a blockchain explorer. Pay attention to unusually high gas fees on neighboring transactions, to repeated rapid buy-and-sell pairs for the same token, and to bots that consistently execute trades just before or right after yours.

Specific warning signs look like this:

  • Your trade's execution price is significantly worse than the quoted price at the time of submission.
  • The preceding and following transactions in the block involve the same token and show a rapid buy-and-sell pair.
  • The gas on your transaction is noticeably above average, or you see neighboring transactions with extremely high gas.
  • The smart contract has a history of being targeted by MEV bots.
  • The same address consistently makes small, profitable trades just before and after yours.
  • The token price spikes sharply upward and then drops back around the confirmation of your transaction.

PROTECTION

The most practical measure is removing your transaction from the bots' view. Private transaction services and mempool-obscuring tools prevent attackers from seeing your trade before it enters a block, and if the trade is invisible it cannot be front-run. This includes Flashbots Protect and similar initiatives that bundle transactions privately. At the same time, set a realistic slippage tolerance in your wallet or exchange interface: a tight tolerance will automatically reject the trade if the price moves too far, making the attack pointless. DEX aggregators that split a trade across multiple liquidity pools also help, because they reduce slippage and obscure the transaction's intent.

It pays to understand the underlying problem. MEV (Maximal Extractable Value) is the profit that miners or validators can extract by reordering transactions inside a block, and it is what feeds sandwich bots. Where possible, using limit orders (orders to execute at a specified price) on centralized exchanges or on DEXs that support them makes sense, since such orders are not publicly visible in the mempool before they fill.

If you are running your own DeFi application, protection shifts to the code level. Conduct thorough smart contract audits to identify vulnerabilities that could be exploited for sandwich attacks. Implement circuit breakers and monitoring that pause trading during anomalous price movements or slippage. Partnering with blockchain security firms provides proactive threat intelligence and a ready-made incident response plan.

AFTERMATH

If you suspect a sandwich attack, the first step is to stop any further trading on the affected platform to avoid additional losses. Then document everything you can: the transaction hash, addresses involved, token amounts, gas prices, and execution times. Preserve evidence of price discrepancies and slippage, as you will need it for any proceedings.

Next, report the incident to the DEX or platform where the trade occurred, attaching the evidence you collected. Notify analytics firms like Chainalysis, TRM Labs, or PeckShield: they can trace the flow of funds and identify attacker addresses. If significant amounts were lost, it is worth contacting specialized cybercrime authorities such as Interpol or national agencies.

Be realistic about recovery prospects. Because blockchain transactions are immutable, recovery options are limited, so the main focus should be on preventing future trades and strengthening security protocols. Participating in security communities and forums helps you stay on top of current threats and mitigation strategies.

FAQ

Why did I become a victim of a sandwich attack rather than someone else?

It is not a personal hunt, it is about trade size. Bots scan the mempool (the queue of unconfirmed transactions) and pick any large buy that will noticeably move the price in the pool. The larger your order and the higher your slippage tolerance, the more attractive it is to the attacker. Small trades usually do not cover the gas the bot spends on the wrap.

Does a high slippage tolerance protect me, or does a low one?

A low, realistic tolerance protects you. Slippage tolerance sets the maximum price deviation you are willing to accept. If you set it high (say, 5 percent or more), you are effectively allowing the bot to move the price almost that far and pocket the difference. A tight tolerance simply causes your trade to cancel if the price moves too far, and the attack loses its point.

Can I get my money back after a sandwich attack?

Direct recovery is almost impossible because blockchain transactions are immutable and cannot be cancelled or reversed. The realistic goal after an incident is to document evidence, report to the platform and analytics firms, and close the gap so it does not happen again. Recovery of funds is only possible in rare cases through investigation and law enforcement when losses are large.

Does Flashbots Protect help, and what is it for?

Yes, it is one of the most effective methods. Flashbots Protect and similar services accept your transaction privately, bypassing the public mempool, so the bot simply cannot see it before it lands in a block. No visibility, no front-running. Private relays and mempool-obscuring tools achieve the same effect.

How is a sandwich attack different from ordinary slippage?

Ordinary slippage arises on its own due to market movement or insufficient liquidity between the moment you submit and the moment your order is filled. A sandwich creates artificial slippage: the attacker deliberately buys before you to push the price up, then sells immediately after. You can tell the difference by looking at neighboring transactions in the block, where the same address makes a quick buy before your trade and sells the same token right after it.

Put this to work in the terminal

Live charts, derivatives, on-chain and macro data, free.

Open terminal →