DeFi

What Is a Sandwich Attack in Crypto and How to Protect Against It

Intermediate
DeFi
2024年9月30日

Decentralized exchanges (DEXs) offer crypto traders numerous opportunities and distinct advantages. At the same time, these platforms often attract malicious actors intent on causing harm and deriving profit at the expense of unsuspecting fellow traders. While rug pulls and flash loan attacks are often mentioned when discussing the unique threats on decentralized trading platforms, another type of malicious attack — a sandwich attack — gets far less attention.

In the most standard form of sandwich attack, a trader with sinister motives identifies a pending swap transaction on a blockchain and places two orders — one before and one after the targeted transaction — to manipulate the asset price. The culprit's goal is to buy the asset before the expected price increase, and then quickly sell it after the price inflation. The victim of the attack ends up purchasing the asset at the inflated price and then watches helplessly as its price plummets afterward.

Sandwich attacks — while less publicized than some other security vulnerabilities in the world of decentralized finance (DeFi) — can still be devastating for traders who fall victim to these exploits. A trader unaware of being targeted by such an attack may quickly lose significant funds and get wiped out, especially if they actively place orders during the attack phase. 

The good news is that there are several measures that traders can implement to minimize the probability of becoming “filling” for the attacker's breakfast sandwich. In this article, we’re taking a closer look at sandwich attacks, their two main varieties and the key ways to avoid them.

Key Takeaways:

  • A sandwich attack is a common exploit on DEX platforms, in which an attacker places two (and in one variation, three) transactions around a victim's swap order, intending to manipulate asset prices and profit at the expense of the victim.

  • Key ways to protect yourself from sandwich attacks include controlling your acceptable slippage rates, using larger swap pools, paying higher gas fees and using centralized exchange (CEX) platforms.

EN_2409-T35020_Learn_Read_to_Earn_728x90.png

What Is a Sandwich Attack in Crypto?

A sandwich attack is a type of malicious transaction on DEX platforms whereby the attacker identifies a pending swap operation and places one order before and another right after the targeted transaction in order to manipulate the asset's price. The malicious trader "sandwiches" the pending transaction by simultaneously front-running and back-running it, hence the name. Their goal is to buy the asset chosen by the unsuspecting trader at a lower price, and then sell it immediately after their back-running transaction.

As a result of the sandwich attack, the victim buys the asset at an inflated price as compared to the expected execution price. After the back-run transaction, the asset price declines, and the victim ends up with an asset valued lower than what they paid for it. Depending upon the victim's trading volume and activity, losses from a sandwich attack — or a series of them — can be devastating. These attacks are pretty common on DEXs, although they receive less coverage than other forms of exploit, such as flash loan attacks.

Sandwich attacks can be considered a form of arbitrage trading. However, unlike some other forms of arbitrage, these attacks directly harm traders who fall victim to them. The sandwich attacker intentionally manipulates the price — both before and after the victim's transaction — in order to profit at the victim's expense. As such, these attacks are nothing other than malicious market manipulation, and are widely condemned in the DeFi community.

Technically speaking, sandwich attacks are possible on decentralized trading platforms due to the public nature of blockchains. Every public blockchain keeps its pending transactions in the mempool area, a waiting room for transactions before they’re finally written to the blockchain's permanent ledger of records. Attackers are actively looking in the mempool for transactions that provide good potential for these exploits.

How Does a Sandwich Attack Work?

Let's consider how a typical sandwich attack might occur in practice. 

Let’s say a trader decides to place a swap order on an automated market maker (AMM)–based DEX, exchanging USDT for ETH. A sandwich attacker spots the victim's transaction in the pending list, and quickly places a buy order for ETH, trying to get their own front-running transaction executed first. Due to the nature of blockchain technology, there are ways for the attacker to achieve this (for example by paying a higher gas fee to raise their own transaction's priority). By having their own transaction executed first, the attacker takes advantage of ETH's lower price. As a result of the buy order, the price of ETH in the trading pool increases.

Therefore, when the victim's order for swapping USDT for ETH goes through, the actual execution price differs from what they had hoped for — and ETH now costs more, so the victim receives the asset at an inflated price. The culprit also schedules another transaction, to be executed quickly after the victim's transaction. In this back-running transaction, the culprit sells ETH at the inflated price and pockets the profit. As a result of the sell transaction, ETH's price drops, and the victim now owns an asset valued lower than what they paid for it.

Types of Sandwich Attacks

Liquidity Taker vs. Taker

There are two main types of sandwich attacks. The most common one is the taker vs. taker scenario. Typically, sandwich attackers use liquidity pools at AMMs to carry out their attacks. In the taker vs. taker scenario, swap operations are executed against the pool and the setup is as described above, with the malicious taker trying to manipulate asset prices by placing both a front-running transaction and a back-running transaction around the victim's order.

Liquidity Provider vs. Taker

Attackers also use a modification of the standard sandwich attack by acting as liquidity providers. While liquidity takers attack using two transactions, attackers execute three orders in the liquidity provider vs. taker mode. 

In the first order, the culprit removes liquidity from the swap pool as a front-running method, increasing the slippage rates for the victim's order. In the second transaction, they execute the back-running method by adding the liquidity back to restore the initial pool balance. Finally, they swap the targeted asset — in our example above, ETH for the original asset, and USDT to restore the asset balance in the pool to the way it was before the attack.

By removing liquidity before the taker's trade, the liquidity provider avoids paying a commission fee (which is normally shared between all liquidity providers). This means the taker has to pay more, due to increased slippage, while the liquidity provider keeps their cut of the commission.

Skinny_Banner-1600x400.webp

Protecting Against Sandwich Attacks

Some DEX platforms (such as 1inch) are taking protective measures against sandwich attacks by introducing transactions that aren't visible in the mempool. Some platforms also protect users against MEV (maximal extractable value) bots, a type of bot frequently used in sandwich attacks. However, any DeFi trader should also take their own precautionary measures to minimize the risk of falling victim to these attacks. Below, we list some proactive ways you can use to avoid your funds becoming a succulent sandwich filling in a malicious attack.

Set a Low Slippage

Slippage rates are the difference between the expected and actual cost of a swap transaction on decentralized protocols. Many DEX platforms allow you to set acceptable slippage rates for your swap trades. Use this option actively, as the price slippage aspect features prominently in sandwich attacks (particularly in the liquidity provider vs. taker variation).

Use Larger Liquidity Pools

Larger liquidity pools are less affected by sandwich attacks, thanks to their having ample funds floating around. The smaller the pool you use, the more pronounced the price swings caused by sandwich attacks — and more extreme price swings will mean one very unpleasant thing: larger losses from these attacks. 

Note, however, that sandwich attackers are most active on large DEXs, such as Uniswap (UNI) and SushiSwap (SUSHI). Therefore, it's less about the size of the platform and more about liquidity volumes in a specific pool. Sandwich attackers love low-liquidity pools at large DEXs. Thus, don't be deceived by a platform's large industry footprint or reputation. Pay close attention to the actual liquidity levels typically available in the pool you're interested in.

DEX aggregators may be helpful, as they distribute a single trade across multiple liquidity pools, which can mitigate the impact of sandwich attacks by reducing the likelihood that a single pool is targeted. Additionally, as DEX aggregators aim to execute more efficient trades, you’re more likely to experience lower slippage when using them.

Pay Higher Gas Fees

One of the key ways sandwich attackers carry out their sinister trade is by paying higher gas fees on a blockchain. By doing so, they often ensure (though never guarantee) that their front-running transaction will be executed before the victim's trade. You can reduce your vulnerability to these attacks by paying a higher gas fee to have your transaction processed by miners before the malicious front-running order is executed.

Use Centralized Exchanges

Centralized exchanges (CEXs), including Bybit, are immune from sandwich attacks, as this type of attack is unique to DEXs. While the measures above may minimize (though never eliminate) the risk of such attacks, conducting your trades on a CEX is the only reliable way to completely avoid the possibility of becoming prey to sandwich attackers.

Closing Thoughts

Sandwich attacks exploit the inherently asynchronous nature of transaction ordering on blockchain. While not as high-profile as prominent flash loan attacks, they are ubiquitous on DEXs and cost traders dearly. Luckily, there are several ways to minimize the potential threat from these attacks. By tightly controlling your slippage rates, using larger liquidity pools, paying higher gas fees to elevate the priority of your orders and using CEX platforms, you can significantly reduce the risk of falling victim to sandwich attacks.

#LearnWithBybit