See More

A Beginner’s Guide to Sandwich Attacks in DeFi

13 mins
Updated by Artyom Gladkov
Join our Trading Community on Telegram

Sandwich attacks in DeFi aren’t uncommon. Less resource-intensive than malware attacks, sandwich attacks are maneuvers whereby malicious actors profit at the expense of other traders.

These malicious attacks mostly plague decentralized exchanges. This guide offers a simplistic breakdown of an attack and explains the role of bots and other resources. Plus, we cover the best strategies to prevent sandwich attacks.

A quick DeFi refresher and how it all adds up

sandwich attack what is defi

Before delving deeper into the world of sandwich attacks, it is appropriate to understand the basics of a standard DeFi ecosystem. 

DeFi, or decentralized finance, has taken financial services to a new level. Powered by smart contracts (pieces of code) and blockchain technology, DeFi cuts out overreliance on intermediaries like financial institutions. But there remains a catch. Where there is code, there remains a chance of sly maneuvers, especially when the boilerplates aren’t properly audited.

Also, in DeFi, it is decentralized exchanges (DEXs) at the center of these attacks. Sandwich attackers exploit the diverse aspects of decentralized exchanges, including slippage rates, liquidity pools, smart contract codes, and more, to initiate a front-running attack. 

DeFi terms to better understand sandwich attacks

And if these are quite a few jargon-like terms to deal with, here is a quick explainer of each:

  1. Smart contracts: Pieces of code that act as self-executing contracts. These contracts come with condition-specific enforceability and are quite popular in DeFi.
  2. Decentralized exchanges (DEXs): Smart contract-powered exchanges that support peer-to-peer trades and direct transactions without the need for centralized intermediaries.
  3. Liquidity pools: Token pools use smart contracts to provide liquidity to specific markets. DEXs rely on liquidity pools for their swappable liquidity. And governing the pricing discovery and movements within the liquidity pools are automated market makers or AMMs.
  4. Slippage: The price difference between an expected and actual trade. Lower market liquidity can cause higher slippage rates. On DEXs, traders must predefine the slippage tolerance preference to initiate safer trades.
  5. Front-running: In DeFi, front-running is like gaining an ethical advantage to trade ahead. Sandwich attackers use this method by gaining knowledge of pending orders, MEVs, and other aspects to manipulate transaction orders and profit in the interim.

Each mentioned terminology, or concept has a role in a sandwich attack. We shall now see how. 

Unpacking sandwich attacks

In a literal sense, a sandwich attack is one where the attacker sandwiches a trade (of the unwitting person) by using two separate transactions. To understand it better, let us first analyze the modus operandi of automated market makers or AMMs. 

A David-Roger example

AMMs are building blocks of DEXs. Say David is trying to swap or trade one crypto for another, but there is no discernible liquidity. In that case, the order might take some time to execute. David can rely on an AMM that connects him to a liquidity pool for the concerned pair (the one he is eyeing). The equivalent price to trade or convert depends on how the AMM evaluates the ratio of the involved assets and the available liquidity.

The attack premise

In a sandwich attack, the attacker (say Roger) will have his eyes on David and will try and front-run David’s transaction to make a profit. Here is how it would go down:

Roger will place two trades: one before and one after David’s transaction. Hence the name sandwich attack.

How Sandwich Attacks work: Medium
How sandwich attacks work: Medium

In the first trade, Roger would buy a significant amount of the crypto that David plans on trading or buying with a swap. Per the image above, Roger’s order would be TA1, trying to front-run David’s Tv.

This would push the price of the crypto higher (due to increased buying pressure), and the AMM processes David’s transaction at a higher price — due to the sudden change in the ratio of assets within the pool. This means David would get fewer assets than he was supposed to due to the prices being pushed higher.

Do note that Roger would already have bought the assets at a lower price and artificially pushed prices higher. 

Once done, Roger would create a sell-side transaction, or TA2, only to sell the assets he previously brought. With the price of the asset being moved higher due to Roger’s buy order and David’s swap or trade, selling it now would return some profit for Roger. Hence, Roger makes a profit at the expense of David.

Let us now better understand this scenario using actual assets and numbers.

Sandwich attacks and the calculations involved

Let us now revisit the actual David-Roger example with real assets. Say David wants to swap 100 ETH for 2000 DAI per ETH on a DEX, using an AMM and its ETH-DAI pool. This means that for the 200000 DAI David swaps, he expects to receive 100 ETH. That would be the ideal scenario.

David raises a transaction request, which moves to the public mempool (as blockchain is transparent) — the storage hub for pending transactions. Roger has already been checking the mempool for possible ideas for front-running, using boots. He notices David’s sizable transaction and the process begins.

Roger immediately places an ETH buy order, 100 ETH for 2000 DAI per ETH, the same as David’s or higher. 

He even offers a higher gas fee to make use of the MEV aspect and get ahead of David’s transaction. This would mean front-running David’s transaction. 

This would inflate the prices of ETH to, say, 2100 DAI per ETH.So now, with ETH’s prices being inflated due to the sudden buy pressure, the exchange rate that David gets for swapping his 100 ETH for DAI is less than what he expected. 

As David is planning to swap ETH for 20000 DAI, he would now only get 95 ETH (approximately). However, David’s buy order would increase the ETH prices again, working in favor of Roger. 

Once David’s loss-making transaction is through, Roger places a sell order (back-running transaction) to get rid of all the 100 ETH he purchased at an inflated price of 2100 DAI per ETH or even higher. This way, he makes a significant profit of 100 DAI per ETH. 

Sandwich attacks and flowchart: Medium
Sandwich attacks and flowchart: Medium

Understanding the exchange rate and slippage

By this time, you might be confused: why does David receive a bad exchange rate, but when Roger sells his 100 ETH, he ends up getting the 2100 DAI per ETH rate or even more? Let us clarify.

When Roger places the buy order, pushing the prices of ETH to 2100 DAI per ETH, the AMM needs to rebalance the exchange rate to maintain liquidity, as the buy order consumes a portion of the pool’s liquidity. 

This is the reason why David receives a poor exchange rate, as the AMM quickly adjusts it once Roger’s order front-runs David’s and gets executed.

However, when Roger ends the attack with a sell order of 100 ETH, he adds more liquidity to the pool, stabilizing the exchange rate and getting him the best ETH-to-DAI price (say 2100 DAI per ETH). Besides, David’s buy order, initiated before Roger’s sell or back-running order, would also have pushed the price of ETH higher, making selling profitable for Roger.

Also, sandwich attackers like Roger execute these sandwiched transactions at warped speeds via sophisticated bots and tools before the AMM can adjust the exchange rates to normal. Something similar happened with the latest flock of memecoins, including the likes of PEPE, CHAD, WOJAK, and more. Let us delve deeper into this.

Sandwich attacks: what’s up with PEPE and other memecoins?

There is a new kid on the memecoin block — PEPE — a token inspired by the Pepe the Frog meme. As of mid-April 2023, PEPE has become a hotbed of sandwich attacks, MEV bots, and every other front-running gig there is.

But first, some perspective.

The Pepe token network wasn’t initially brimming with liquidity. People hardly knew about it. However, things changed when the below tweet surfaced, mentioning how an address named dimethyltryptamine.eth (Milady) saw the PEPE bag worth $250 surge to $1.5 million.

Well, the address didn’t do much. It simply swapped the penny token — 5.9 trillion PEPE tokens — for 0.125 ETH. It was all optimism. As memecoins are driven by hype, a surge in the price of PEPE tokens pushed the bag value higher. But there were other forces at play.

Milady PEPE holdings: Etherscan
Milady PEPE holdings: Etherscan

While the price of PEPE was rising, another address — jaredfromsubway.eth — used the MEV bots to front-run PEPE buying transactions on the network. And as with any other instance of a Sandwich attack, this incessant front-running kept pushing the prices of PEPE higher.

Sandwich attacks with the primary attacker as the top gas spender: Dune Analytics
Sandwich attacks with the primary attacker as the top gas spender: Dune Analytics

Gas Spends data from Dune Analytics places the address as the top “gas” spender over the past week, with the address contributing almost 5.7% of the total gas spend weekly. As front-running can push the prices of the asset higher, the role of the MEV bot-led Sandwich attack in pushing the value of dimethyltryptamine.eth higher can’t be discounted.

Sandwich bots and the price surge at PEPE’s and CHAD’s counter

Sandwich bots’ role in pushing prices isn’t restricted to PEPE tokens. Another project, Chad Coin (CHAD), is up over 51%, day-on-day, (as of April 20, 2022), with sandwich bots pushing the prices higher. As for the specifics, the address jaredfromsubway.eth has spent over $1.28 million in transaction costs or fees over a 24 hour period to front-run the unwitting PEPE and CHAD onlookers.

Sandwich bots as the second highest gas spender: Etherscan
Sandwich bots as the second highest gas spender: Etherscan

The array of sandwich attacks initiated by jaredfromsubway.eth could have amassed profits worth $1.4 million since April 18, 2023, alone — profits at the expense of traders who had to buy PEPE and CHAD at higher prices.

The activity of these Sandwich bots was the highest on April 19, 2022, when the hourly median gas price surged to 119 Gwei at one point.

Hourly median gas hike: Dune Analytics
Hourly median gas hike: Dune Analytics

Experienced Twitter commentators have suggested using MEV blockers to keep sandwich attacks out.

Are there other scenarios in play for sandwich attacks?

While front-running and back-running transactions are part of sandwich attacks, other scenarios can occur. In some cases, attackers do not always front-run transactions using a higher transaction cost or free. Instead, they remove liquidity from the liquidity pool before the victim’s transaction goes through.

Sandwich attacks and the liquidity crunch scenario: Medium
Sandwich attacks and the liquidity crunch scenario: Medium

This makes the victim buy at a higher price, which eventually pushes the prices higher. The adversary or the attacker then reintroduces the liquidity, pushing the prices up even further. Once done, another transaction, the inverse of the victim’s transaction, or a back-running transaction, is initiated to sell or short the assets at a higher price, helping the attacker make profits in the process. 

 transactions gets delayed: Medium
Sandwiched transactions are delayed: Medium

And finally, there can be another scenario with multiple attackers behind the same high-value victim or transaction. This kind of predatory trading scenario lowers the profitability aspect of a sandwich attack. The victim transactions take longer than usual, but the expected profitability also decreases.

What are the consequences of sandwich attacks?

A sandwich attack can harm traders and DeFi exchanges across capacities. Here are some of the most obvious repercussions:

For traders:

  1. High chances of losing money with the fluctuating exchange rate between assets.
  2. Fewer traders then enter the DeFi ecosystem, reducing ecosystem activity and liquidity.

For DeFi ecosystems:

  1. Loss of trust and decreased adoption
  2. A bad reputation for DeFi ecosystems, lowering the capital inflow
  3. Frequent attacks can attract negative regulatory glares

How is a sandwich attack carried out?

Before we plan on stopping these attacks, we need to know how they even function. The example we discussed only tells us what happens. Here is the entire flow of the attack:

Role of bots

Attackers rely on bots to scan the mempool for pending transactions. They usually eye high-value swaps or trades. Once they identify the potential target (pending transaction of choice), they use high-speed trading algorithms to front-run the target transaction and back-run sell orders to exploit the market or pool imbalances created by their buy orders. Front-running PEPE and CHAD buyers is the most recent example of how MEV or Sandwich bots are put to use.

It is important to note that these attackers typically use high-speed internet and infrastructure with low latency to be able to execute trades faster.

Which transactions are vulnerable and why?

Attackers usually eye high-value transactions. And there is a reason behind this choice. But first, let us quickly understand how a liquidity pool powered by an AMM and the pricing algorithms works.

Liquidity pools have specific reserves, say r1 and r2, as ETH and DAI reserves (like the David-Roger example from earlier). Assuming that the fee or transaction cost is 0.3% of the input assets — DAI in the case of David’s trade and ‘a’ is the number of assets to be swapped — the number of assets that one gets as a result of the swap can be determined by the below formula.

product formula amm
Constant product formula for AMM: ETH Zurich

As the assets returned are a function of r1 and r2, the number of assets it is possible to acquire can change between transaction signing and transaction execution. This is the time difference that a sandwich attacker needs to front-run and back-run transactions, changing the value of r1 and r2 to their advantage.

Liquidity is the key

The formula that we saw corresponds to a constant product AMM where the balance between r1 and r2 is always respected. The slippage and exchange rates are offered accordingly. A large buy or even a sell order imbalances r1 and r2 ratio, making the AMM algorithm adjust swap rates to compensate. This is what an attacker wants to make profits.

In most cases, the attacker locates a high-value transaction and simply replicates the same with a higher gas fee. This triggers the MEV aspect of block creation. In a realm where miners want to extract more rewards by letting high gas transactions through first, transactions sandwiched like that of the victim can attract losses. The attacker ends up buying the assets at a low price (something the victim intended but was too slow) and selling the same at a higher price. 

What techniques do attackers use?

Here’s how sandwich attackers bring forth an unexpected slippage rate and the worst-possible exchange rate for unsuspecting victims:

  • Attackers create multiple transactions with higher gas fees, similar to the victims’ transactions. 
  • They use bots to track the mempool (as mentioned earlier)
  • They use a combination of market and limit orders to create an unexpected slippage rate benefiting their trades
  • They even use flash loans to borrow funds to back their liquidity pool, manipulating trades.

As seen, there isn’t much that an unwitting trader like David can do to thwart the efforts of attackers like Roger. But there are a few ways to work around this issue.

Preventing and mitigating a sandwich attack

While some may not consider sandwiched transactions as attacks (instead, thinking of this practice as “making hay while the sun shines”), such actions are unethical. Here are some pointers and insights to help you steer clear of sandwich attacks:

  1. As a trader, you should avoid executing high-value transactions during peak hours, especially when the market volatility is high.
  2. Traders should use slippage detection and protection tools at all times. Note that even if the transactions do not go through due to slippage protection — keeping traders safe — the gas fees or transaction costs must still be paid.
  3. Traders must double-check every aspect of the transaction, including the gas fees, exchange rates, and the amount before trade execution.
  4. Traders must never use unsecured networks while interacting with a liquidity pool. 
  5. DeFi platforms are actively integrating anti-front running strategies like flash bot transactions to connect traders directly to trusted validators to get the transactions through.
  6. Liquidity pools are exploring new MEV blocking solutions, thwarting the concept of sending and validating a transaction validated with higher gas fees.

Some liquidity pools offer “order splitting” as a standard mitigation strategy, as breaking down a large order defeats the purpose of initiating a high-value sandwich attack.

Sandwich attacks from the vault: real incidents

Now that we have explored almost every aspect of sandwich attacks, here is a short explanation of some recent and impactful attacks.

The Uniswap attack

Uniswap’s liquidity pool saw its value cratering at $25.2 million, which could be the crook validators’ handiwork. PeckShield Alert, a blockchain security platform, even tweeted about the perpetrators and how/where the stolen funds were moved. 

The ForceDAO attack

This instance surfaced in April 2021, where attackers used a mix of buy/sell orders and flash loans for market manipulation. This attack on ForceDao — a DeFi project — resulted in a loss of $367,000

The Cream Finance Attack

This February 2021 attack siphoned the Cream Finance project of $37.5 million. Similar to the ForceDAO attack, flash loans and multiple transactions with high transaction costs were used in this case.

A not-so-healthy sandwich

Not every sandwich leaves a great aftertaste. Ever-balancing pricing algorithms (courtesy of smart contracts), the unexpected slippage rate of a DEX, and the visibility of pending transactions all contribute to sandwich attack threats being real and prevalent. All traders should follow the trading practices and security steps outlined in this article in order to mount the best possible defense and stay as secure as possible while interacting with DeFi ecosystems.  

Frequently asked questions

What is a crypto sandwich attack?

How does a sandwich attack work?

How do you stop sandwich bots?

What are the needed conditions for an attacker to launch the sandwich attack successfully?

Top crypto projects in the US | June 2024



In line with the Trust Project guidelines, the educational content on this website is offered in good faith and for general information purposes only. BeInCrypto prioritizes providing high-quality information, taking the time to research and create informative content for readers. While partners may reward the company with commissions for placements in articles, these commissions do not influence the unbiased, honest, and helpful content creation process. Any action taken by the reader based on this information is strictly at their own risk. Please note that our Terms and Conditions, Privacy Policy, and Disclaimers have been updated.

Ananda Banerjee
Ananda Banerjee is a technical copy/content writer specializing in web3, crypto, Blockchain, AI, and SaaS — in a career spanning over 12 years. After completing his M.Tech in Telecommunication engineering from RCCIIT, India, Ananda was quick to pair his technical acumen with content creation in a career that saw him contributing to Towardsdatascience, Hackernoon, Dzone, Elephant Journal, Business2Community, and more. At BIC, Ananda currently contributes long-form content discussing trading,...