Sandwich Attacks in Crypto: How To Protect Yourself

A sandwich attack is a type of market manipulation that targets the decentralised finance market.

Sandwich Attacks in Crypto: How To Protect Yourself
💡
This article was originally published here by Cyberscope.

In 2022, researchers analyzed the transaction data of Uniswap V2 and Sushiswap. They found that in April 2021, the monthly number of sandwich attacks reached 84,000.

Exciting opportunities and ideas are always around the corner in the cryptocurrency world, but these innovations also come with hidden dangers.

One of these dangers is the mysterious "Sandwich Attack." Sandwich Attacks can create significant issues within decentralized finance (DeFi).

Even the Ethereum guru, Vitalik Buterin, way back in 2018, waved his crypto wand of caution about these sneaky manoeuvres.

In this guide, you’ll learn all about Sandwich Attacks.

Let’s delve into how these attacks work, share real-life stories, and provide straightforward strategies to ensure the safety of your crypto investments.

Understanding Sandwich Attacks

At its heart, a sandwich attack is like the ultimate sneak-peek maneuver in decentralized finance (DeFi). It's all about targeting those DeFi protocols and services with a mischievous grin.

So, how does this sandwich attack work? Well, imagine a mischievous trader, let's call them 'The Crypto Trickster,' roaming the vast network, say, Ethereum. They're on the lookout for a pending transaction, like a detective hot on the trail.

Now, here's where the sandwiching action comes into play.

The Crypto Trickster goes for a double whammy - they place an order right before the target trade and another right after it. It's like they're front-running and back-running all at once, trapping the innocent pending transaction right in the middle.

But what's their devious plan, you ask? It's all about playing with asset prices!

First, our Crypto Trickster decides to buy the asset the unsuspecting user is swapping to - let's say it's LINK turning into ETH. They know ETH's price is about to rise, so they grab some.

Here's the twist: they buy ETH again, but this time at a lower price. Why? To make the victim pay a higher price when they make their purchase. Sneaky, right? Then, our sly trickster sells ETH at that higher price, pocketing the profit.

What's the outcome of this cryptic dance? The initial user ends up with a different amount of ETH than expected. The culprit managed to fill the order at their chosen price, making the next trade more expensive.

And that's when the ETH price takes a little jump, thanks to our sandwich maestro. It's a whirlwind of front-running, back-running, and creating a fancy fake price surge.

Visual Example of a Sandwich Attack | Image Source: Hackless
Visual Example of a Sandwich Attack | Image Source: Hackless

Various Factors to Consider in Sandwich Attacks

Now, let's dive into the fascinating complexities that make sandwich attacks more than just a walk in the crypto park. While it might seem like child's play from our previous explanation, the reality is executing a sandwich attack requires some serious preparation. It's like a heist in the world of decentralized finance, and you've got to be ready.

You see, most sandwich attacks occur in the realm of Automated Market Makers (AMMs). Think of them as the bustling bazaars of crypto, where trades happen round the clock.

Famous names like Uniswap, PancakeSwap, and SushiSwap are the stars of this crypto show. These nifty pricing algorithms keep liquidity in high demand and trades happening non-stop. But wait, there's a catch.

Enter 'Price Slippage.' It's like the quicksand of crypto. Price slippage creeps in when the volume and liquidity of an asset start dancing to a different tune.

Now, here's where it gets interesting. When our clever trickster is plotting a sandwich attack, they need to consider a trio of factors - the expected execution price, the actual execution price, and the unexpected slippage rate. It's like a triple twist in a high-stakes game.

These factors can juggle around the rates at which trades occur. Think of it as trading your shiny gem for someone else's rare artifact, but the value can change mid-swap.

Plus, let's not forget the delightful world of blockchain, where transactions can sometimes take a nap before waking up. And as they snooze, the exchange rates of assets might throw a wild party, leading to even more unexpected price slippage.

So, you see, it's not just about making a sandwich but navigating this rollercoaster of variables in the crypto circus. It's a challenge for even the sneakiest of tricksters!

How Do Sandwich Attacks Work?

Let's make this step-by-step example come alive with a touch of storytelling.

Step 1: Emily's Crypto Adventure

Our heroine, Emily, sets out on a crypto quest. She's got some ETH and a desire for DOGE tokens. So, she heads over to the magical realm of a decentralized exchange, like Uniswap, to make her dreams come true. Emily is eyeing those 2,900 DOGE tokens; she knows it should cost her around 1 ETH.

So, Emily decides to play it safe and sets a 10% slippage tolerance. This means she's ready to part with up to 1.1 ETH for her precious 2,900 DOGE.

Step 2: The Crypto Searcher's Cunning Move

As Emily's trade waits in the Ethereum mempool (the pending order queue), like a brave knight ready for battle, a crypto detective appears on the scene. This searcher has a keen eye for opportunities and springs into action.

They place a trade just before Emily's, and it's clever. They buy 2,900 DOGE for exactly 1 ETH. Now, here's the twist - because of the price impact of this first trade, the cost of Emily's 2,900 DOGE has climbed to 1.1 ETH, hitting her slippage tolerance.

Step 3: Emily's Bittersweet Victory

Finally, the moment arrives. Emily's transaction gets the green light, and she's now the proud owner of 2,900 DOGE, but it comes at 1.1 ETH, as per her slippage limit. But wait, our cunning searcher is not done yet. They seize the opportunity and sell their original 2,900 DOGE at this new rate - 2,900 DOGE coins for 1.1 ETH.

The result? The searcher bought 2,900 DOGE for 1 ETH and sold it for 1.1 ETH, earning a profit of 0.1 ETH (before accounting for gas and fees). Not bad for a day's work in the crypto realm!

Sandwich Attack Result Example | Image Source: Dextools
Sandwich Attack Result Example | Image Source: Dextools

It's easy to see how these sandwich attacks can become profitable adventures for the clever crypto searcher. But for Emily, well, it's a bit of a mixed bag. She got her DOGE, but her slippage tolerance left the door open for a sandwich attack, making her pay an extra 10% for her crypto dream.

Two Possible Scenarios for Sandwich Attacks

Scenario 1: Liquidity Taker vs. Market Taker

Now, let's talk about the showdown between the liquidity takers.

Imagine this: A regular market taker just going about their business with a pending AMM transaction hanging in the blockchain. But wait, here comes the troublemaker, our culprit. They decide to play the front-runner and back-runner game for their financial gain.

Here's the twist - the liquidity pool and asset pair have not one, not two, but three pending transactions in the queue. It's like a traffic jam; the miners are the traffic cops deciding who gets the green light first.

Now, what does our sly culprit do? They whip out their secret weapon - they pay a higher transaction cost than the other person. It's like saying, 'I'll pay more for this highway toll.' And guess what? There's a bigger chance their mischievous transaction gets the thumbs-up first. It's not a guaranteed win, but it showcases how tempting and easy it can be to try a sandwich attack.

Scenario 2: Liquidity Provider vs. Taker

Now, let's switch gears to the tale of a liquidity provider taking on a liquidity taker. The stage is set, and the initial setup is pretty much the same. But our bad actor has a trifecta of actions planned this time.

First, they pull a sneaky move - they remove liquidity, like a magician pulling a rabbit out of a hat, to mess with the victim's slippage. Then, they play the back-runner card by re-adding liquidity, restoring the pool balance to its original form. And finally, they swap asset Y for X to bring the asset balance back to where it started.

But here's the kicker - withdrawing their liquidity before the victim's transaction gets through cancels out the commission fee for that transaction. Imagine a toll booth collector deciding not to collect a fee - that's the financial harm they can cause to the taker. But, of course, it comes at the cost of the collector's commission.

Sandwich Attack Statistics | Image Source: Dune
Sandwich Attack Statistics | Image Source: Dune

How to Protect Yourself from Sandwich Attacks

Let's delve into the steps to shield yourself from sandwich attacks:

1. Set a Low Slippage

Slippage refers to the difference between the expected and actual transaction prices in fast-moving crypto markets. Imagine it as a rollercoaster ride where prices can change rapidly. Setting a low slippage means your transaction will only proceed if the token price stays within a narrow range. If an attacker tries to manipulate the price beyond your tolerance, your order gets canceled, keeping your tokens safe.

2. Use Larger Liquidity Pools

Opt for larger liquidity pools when making transactions. These pools provide stability in trading by minimizing price fluctuations from individual trades. Attacking a large liquidity pool requires significant capital, acting as a deterrent against manipulation.

3. Pay Higher Gas Fees

Consider using higher gas fees for larger trades. While it may cost more, it speeds up your transaction and makes it costly for attackers to front-run it. This added layer of security can safeguard your assets.

4. Utilize Telegram Bots

Telegram crypto bots can automate and execute trades swiftly. Some bots offer features to protect against sandwich attacks. They can hide transaction details until execution, preventing front-running by malicious bots. However, be cautious, as bots also have access to your private keys, posing security risks.

5. Use a Private RPC Network

A private RPC network hides your pending transactions from prying eyes. This prevents attackers from scanning the mempool for targets. It adds an extra layer of confidentiality to your trades.

6. Run Your Node

Running your node gives you more control over transactions, reducing dependencies on external platforms. You can submit transactions directly and control their timing and processing.

7. MEVblocker

MEV Blocker is a free RPC endpoint that protects your trades against MEV. It sends your transaction to a network of searchers who scan for back-running but can't front-run your trades. Add MEV Blocker to your wallet, such as MetaMask, for added protection.

8. Flashbots

Flashbots is a research organization focused on fair trading practices. You can integrate 'Flashbots Protect' into your wallet, like MetaMask. It shields you from front-running by MEV bots and offers features like transaction prevention.

Consequences of Sandwich Attacks?

Sandwich attacks in DeFi can cause a lot of problems:

  • Losing Money: People who get caught in these attacks can lose their money. They don't get as much as they should from their trades, so they miss out on making a profit.
  • Trust Issues: DeFi is like a new kind of money system, but when sandwich attacks keep happening, people lose trust in it. If you played a game and someone kept cheating – you wouldn't want to play anymore.
  • Rules Getting Tougher: Because of these attacks, some people might say, "We need more rules!" That means they might make stricter laws for how DeFi works. This could make it harder for people to use DeFi.

Are Sandwich Attacks Worth It?

Now, you might wonder, "Is it even worth it for attackers to do sandwich attacks?" Well, not always! Doing these tricky sandwich attacks can cost the attackers a lot of money. They have to pay fees for each action they take, and on the Ethereum network, those fees can add up quickly.

But here's the catch: If the money they make from these attacks (like the commission they earn) is more than what they spend on fees, it can still be profitable.

So, it's like a game where attackers have to be really smart with their moves to make it worth their while.

Final Thoughts

Sandwich bots and MEV, while morally ambiguous, shed light on the transparency of Web3. They showcase the open nature of blockchain technology, where all transactions are on display. Think of the crypto world as a big puzzle with many hidden surprises.

But don't worry; there are clever people who are always finding ways to make the crypto world safer. They develop new tricks to protect your money from the tricky bots and puzzle pieces. The important thing is to keep learning about these tricks and how to stay safe. It's like learning to spot a sneaky magician's tricks so they can't fool you.

So, here's a big question: Is it better to have lots of freedom in the crypto world, even if tricky things can happen? Or should we make it super safe, even if it's not as free?


Disclaimer: This article was written by the writer to provide guidance and understanding of web3/blockchain/cryptocurrency. It is not an exhaustive article and should not be taken as financial advice. Obiex will not be held liable for your investment decisions.


💡
Are you interested in having your guest posts featured on our blog? Email [email protected] with your name and a sample of the article, opinion piece, or listicle you want featured.