Learn How to Perform a Sandwich Attack
This article was originally published at BuildBear Tutorials.
In this tutorial, we will be using Scaffold-ETH x BuildBear to interactively showcase how to Perform a Sandwich Attack on UniSwapV2 on a fork of the Ethereum Mainnet.
What is Sandwich Attack?
In a sandwich attack scenario, the attacker monitors the mempool (a list of pending transactions) for a target transaction that they want to exploit. Once they identify the target, they submit two transactions — one before and one after the target transaction — surrounding it like the bread in a sandwich.
How does Sandwich Attack Performed?
A Sandwich Attack is orchestrated through a sequence of steps aimed at exploiting price volatility in a decentralized exchange, such as Uniswap. Here’s how the attack is executed:
- Monitoring the Mempool: The attacker begins by closely observing the mempool, which is a pool of pending transactions yet to be confirmed on the blockchain. Within this mempool, the attacker is on the lookout for a specific transaction — the “target” — which they can capitalize on.
- Identifying the Target: The target transaction is one that involves a significant trade, often with a substantial quantity of tokens. This transaction’s pending status in the mempool provides a window of opportunity for the attacker to take advantage of potential price fluctuations.
- Preparing the Sandwich: Once the target transaction is spotted, the attacker quickly acts by submitting two transactions of their own. These transactions are strategically timed to be included in the block before and after the target transaction. This creates a situation where the target transaction is “sandwiched” between the attacker’s transactions.
- Frontrun Transaction: The attacker’s first transaction, known as the frontrun transaction, occurs before the target transaction. In this step, the attacker may perform a token swap, altering the price of the tokens involved in the upcoming target transaction.
- Backrun Transaction: The attacker’s second transaction, called the backrun transaction, occurs after the target transaction. Here, the attacker may execute a reverse token swap, aiming to capitalize on the altered price.
- Manipulating the Price: By executing these two transactions surrounding the target transaction, the attacker’s objective is to manipulate the price of the token. The altered price can lead the user involved in the target transaction to receive a different quantity of tokens than they initially anticipated.
- Profiting from Price Fluctuation: The attacker aims to profit from the price variation caused by their strategic transactions. Depending on whether the price was driven up or down due to the attack, the attacker can gain by either purchasing tokens at a lower price or selling them at a higher price.
By following this tutorial, you will learn how to Perform a Sandwich Attack on UniSwapV2.
Let’s get started!
Getting Started
To begin, navigate to the scaffold-eth x BuildBear repository.
Here’s why we recommend using scaffold-eth x BuildBear:
- It allows you to easily fork EVM-compatible chains (such as Ethereum, Polygon, Binance Smart Chain, Fantom, Optimism, and Arbitrum Mainnet) directly from the CLI. Saving you valuable time that would otherwise be spent searching for working RPCs.
- You can mint native and ERC20 tokens effortlessly using the CLI, eliminating the need to waste time searching for functional faucets.
To get started, click on the “Fork” button to create a copy of the repository on your own GitHub account. Please wait for the forking process to complete before proceeding.
Next, open a terminal and clone the forked repository, which includes all the necessary components for building a decentralized application:
git clone <paste the URL you fork repo>
cd scaffold-eth
To install all the required packages, execute the following command:
yarn install
To execute the Flashloan Arbitrage, we can leverage the existing Aave Protocol and DEXs by forking the Ethereum Mainnet instead of redeploying these protocols.
use the following command:
yarn fork-bb
Deploying the contracts
yarn deploy
🚨 If you are using a Node version < v18 you will need to remove openssl-legacy-provider
from the start
script in package.json
Starting the frontend
yarn start
Once the application is running, you can access it at http://localhost:3000 and you should see the following:
Before diving deeper into the smart contract, let’s start by exploring the functionalities of SandwichAttack. To begin, navigate to the SandwichAttack page.
On the SandwichAttack Page, you have the option to execute three key transactions: the Frontrun transaction, the User transaction, and the Backrun transaction.
Let’s dive deep into the Smart contract
We can find SandwichAttack.sol
contract in packages/hardhat/contracts
:
Let’s break down the key components and functionalities of the contract:
Import and Interface:
- The contract imports the
IERC20
interface from the OpenZeppelin ERC20 library, which provides standard functions for ERC20 tokens. - The contract declares an interface
IUniswapV2Router02
for the UniswapV2 router's swap function. This interface represents the interaction with the UniswapV2 router's swapping functionality.
Frontrun Function:
frontrun
: A function that executes the first step of the sandwich attack. It swapsamount
oftoken0
fortoken1
on UniswapV2.- The function requires that the balances of both
token0
andtoken1
in the contract are higher thanamount
. - The function approves the UniswapV2 router to spend
maxValue
of bothtoken0
andtoken1
. - It sets up the token swap path and parameters, including the minimum amount of
token1
expected (amountOutMin
) and a deadline for the swap (deadline
). - The function executes the token swap and stores the resulting amounts.
Backrun Function:
backrun
: A function that performs the second step of the sandwich attack. It swaps the remaining balance oftoken0
back fortoken1
.- It sets up the token swap path and parameters, including a minimum amount of
token1
expected (which is set to 0) and a deadline for the swap. - The function then executes the token swap and stores the resulting amounts.
Initiating a Sandwich Attack: A Step-by-Step Guide
To truly understand the mechanics of a Sandwich Attack, let’s delve into its execution and intricacies.
1. Preparing the sandwichAttack
Contract:
we need to ensure the sandwichAttack
contract is appropriately funded with the tokens we intend to manipulate. As shown below.
2. Executing the Front-Run Attack:
Our next move involves executing the front-run attack, as shown below :
- User Transactions :
Here, we are swapping 100000000
DAI tokens for UNI Tokens. However, due to the front-run attack, the outcome diverges significantly from expectations. As displayed, the result is a mere 0.062
UNI tokens for the substantial 100000000
DAI tokens.
- Executing the Back-Run Attack:
Here, we are swapping 200000000.0
UNI tokens for 200008627
DAI Tokens.
🎉🎉 Congratulations!
We have successfully executed a Sandwich Attack, effectively altering the token prices within UniswapV2 pools.
If you appreciate what we are doing, please follow us on Twitter, and LinkedIn and Join the Telegram group if you haven’t done yet.
Github Repo : scaffold-eth x BuildBear
About BuildBear:
BuildBear is a platform for testing dApps at scale, for teams. It provides users with their own private Testnet to test their smart contracts and dApps, which can be forked from any EVM chain. It also provides a Faucet, Explorer, and RPC for testing purposes.
BuildBear aims to build an ecosystem of tools for testing dApps at scale for the teams.
Check out the projects we build on scaffold-eth x BuildBear and keep learning :