TL;DR Today we’ll explore a very artful and clever DeFi exploit, to say the least. Specifically, we will take a look at the “sandwich” exploit. This technique applies to Automated market makers such as Uniswap. This process consists of an MEV bot taking advantage of small differences in price when an order is placed. The bot then goes and front-runs the transaction before the execution of the legitimate order, causing a shift in price which then the bot takes advantage of this difference and siphons off profits. In this article, we’ll break down how this works and how this impacts the future of DeFi. What are some things we can do to protect ourselves from this?
Sandwich Anatomy?
This attack starts off with any individual placing an order for asset Y. The moment the transaction appears in the mempool–it’s fair play for the bots to start scanning the pool for profits. This particular exploit is quite unique: the order in which the transaction gets executed is critical for this to work properly. Firstly, after a genuine order appears in the network, MEV bots will check out the transaction and front-run the target by placing an order moments before the legit purchase is approved. This large order will cause a huge price-impact. The bot immediately will sell the assets at a higher price to the aforementioned buyer— extracting as much profits from the target as possible.
As we can see the general overview of the exploit is colorless yet artful in many ways. The basic idea really consists of:
Look for a profitable target
Front-run the target
The target will undergo higher slippage causing the victim to buy assets at a higher price.
Finally, sell and take profits.
The Map
It is important to note how the transaction map flows in order to know how to execute this exploit. Where and how this is done.
The first step begins with a user – the victim in this case – just placing a buy order. Once the transaction is broadcasted to the network as shown by the diagram above. The transaction then sits in the miner memory pool while it gets picked up by the miner. This is where the malicious user in this case the bot comes into play. Via a spy node, which is connected to the network it starts scanning for profitable transactions in the memory pool. Slippage of the orders is provided in the transaction details, that is how the bot is clever enough to know which victims they should attack and which ones they should avoid.
After the bot has found a target the next step would be front-running the target. The bot in this case will place a buy order. The only difference is that it’ll significantly pay a higher gas price to make sure their transaction gets executed first. The diagram below shows how this would look on the network.
The final step ideally would be to sell the assets immediately after the order is executed to take advantage of the shift in price. Note that in the final step the bot would pay less gas for the sell order but also pay enough gas to make sure the transaction is executed within the same block. As we can see, the anatomy of this process ends up with the victim being in the middle of the attack hence the name ‘sandwich’. Overall this is a clever way to squeeze profits based on how much slippage the victim is willing to endure.
How to avoid getting sandwich
As mentioned earlier these bots can see transactions that are in the mempool and calculate profits based on that information. Now let’s say the victim instead of sending the transaction straight to the network it uses the Flashbot relayer to hide information and avoid getting sandwiched by the bots. Let’s go over a simple script that will send the transaction over to the Flashbot relayer.
Essentially you can build your project as you normally would but you would need the following packages and libraries:
"dependencies": { "@flashbots/ethers-provider-bundle": "^0.4.3", "ethers": "^5.5.2" },
"devDependencies": { "@types/node": "^17.0.0", "ts-node": "^10.4.0", "tslib": "^2.3.1", "typescript": "^4.5.4" }
After you have imported your environment variables and created your contracts, you can connect to the flashbots relayer. Then start sending the transactions by initializing a flashbot by providing the following params (provider, signer, Flashbot_endpoint).
After that is done you can then go ahead and start using flashbot.sendRawBundle
function to send transactions and defend yourself against these attacks. For example:
const signedTx = await flashbot.signBundle([ {
signer: wallet,
transaction: { chainId: CHAIN_ID, // EIP 1559 transaction
type: 2, value: 0, data: "0x",
maxFeePerGas: GWEI * 3n,
maxPriorityFeePerGas: GWEI * 2n, gasLimit: 1000000,
to: "0x26C4ca34f722BD8fD23D58f34576d8718c883A80",
}, }, ]);
const res = await flashbot.sendRawBundle(signedTx, targetBlock);
if ("error" in res) { throw new Error(res.error.message); }
This is just a brief overview but if executed successfully then you have protected the transaction against MEV bots and sandwich attacks. Again this works because flashbots have a mempool that is private thus protecting your transaction data. The full code and details of this script can be found up on my GitHub if interested.
The Future Of MEV
Overall one might have ethical dilemmas with the concept of MEV, but due to the nature of the network this is bound to happen. All of the data that these actors and malicious users are able to collect is publicly available. The network is untenable against these types of attacks. But one should not get discouraged by this phenomenon. New solutions and projects dedicated to reduce MEV across all chain are in the making as we speak. The more people are aware of this the harder it is to extract MEV but will MEV die out or will we just see more creative and complex strategies ?
Resources:
https://docs.flashbots.net/
https://arxiv.org/abs/2009.14021
Author is a Software Engineer intern at Polygon, interested in MEV, ZK-Proofs, distributed systems and blockchain applicability in the real world. They’re a student at Queen’s college, studying Computer Science and Math. Interest outside of Web3 involve hiking, eating out and exploring NYC.
Very cool and very interesting
Well written piece would read again!!!