A Comprehensive Analysis of MEV Sandwich Attacks: The Fatal Chain from Ordering to Flash Swaps

金色财经_
UNI-5.72%

Author: Daii Source: mirror

Last Wednesday (March 12), a crypto trader lost $215,000 in a single MEV attack, which went viral.

d40IzkNmiRRIQY5uP5wMz1zpFo0cMqNwhmogZmhk.png

In simple terms, this user intended to exchange $220,800 worth of USDC stablecoin for an equivalent amount of USDT in the Uniswap v3 trading pool, but ended up receiving only 5,272 USDT, resulting in an asset evaporation of $215,700 in just a few seconds, as shown in the picture below.

yDgyTJBzWhnGWbbjWdCfwzNHy2RWfixeFPAhUl16.png

The image above is a screenshot of the on-chain record of this transaction. The fundamental reason for this tragedy is the infamous “Sandwich Attack” in the blockchain world.

kf5CcjkRVjOcv2Tj5LM63tYSNd150MXNqxzlLXgj.png

The first to disclose this MEV attack was Michael (see the image above), who explained that:

An MEV bot front-ran the tx by swapping all the USDC liquidity out. After the transaction executed, they put back the liquidity. The attacker tipped a block builder (bobTheBuilder) $200k and profited $8k from this transaction.

Translation: MEV bots front-run tx by swapping out all USDC liquidity. After the trade is executed, they put the liquidity back. The attacker tipped the block builder (bobTheBuilder) $200,000 and made a profit of $8,000 from this trade.

There is a typo in the above content; the MEV attack robot exchanged a large amount of USDT, not USDC.

However, after reading his explanation and news reports, you might still be confused because there are too many new terms, such as Sandwich Attack, front-ran the tx, put back the liquidity, tipped a block builder, etc.

Today, we will take this MEV attack as an example to dissect the entire process and give you a glimpse into the dark world of MEV.

First, we need to explain what MEV is.

1. What is MEV?

MEV was originally called Miner Extractable Value, which refers to the additional profit that miners can make by reordering, inserting, or excluding transactions in blockchain blocks. This may result in higher costs for the average user, or a more unfavorable transaction price.

As blockchain networks like Ethereum shift from the Proof-of-Work (PoW) consensus mechanism to the Proof-of-Stake (PoS) consensus mechanism, the power to control transaction ordering has shifted from miners to validators. Consequently, the term has correspondingly evolved from “Miner Extractable Value” to “Maximal Extractable Value.”

Although the name has changed, the core concept of extracting value by manipulating the order of trades remains the same.

The content above is still a bit technical, you just need to remember: MEV exists because previous miners and current validators have the right to sort the transactions in the mempool. This sorting occurs within a block, and currently, Ethereum produces a block approximately every 11 seconds, which means this right is exercised every 11 seconds. Similarly, this MEV attack was also achieved through the sorting by validators.

Click on this link, and you will see the transaction details included in the block numbered 22029771 related to this attack, as shown in the figure below.

gOBtJtdKthPSTi4uxT3qT8ZxgrXMXxlFAbOEp7RC.png

Please note that the transactions in the above figures 1, 2, and 3 are the MEV attack mentioned at the beginning of this article, and this order is arranged by the validator (bobTheBuilder). Why can this happen?

2. The Principle of MEV

To understand how MEV works, we first need to understand how blockchain records and updates information.

2.1 Blockchain State Update Mechanism

Blockchain can be seen as a continually growing ledger that records all transactions that occur. The state of this ledger, such as the balance of each account and the reserves of various tokens in the Uniswap trading pool, is determined by previous transactions.

When a new block is added to the blockchain, all transactions contained in that block are executed one by one in the order they appear in the block. With each transaction executed, the global state of the blockchain changes accordingly.

In other words, it’s not just the order of the blocks that is important, but also the order of transactions within the blocks. So how is the order of transactions in a block determined?

2.2 Validator decides transaction order

When a user initiates a transaction on the blockchain network, such as the transaction that converts USDC to USDT through Uniswap, it is first broadcasted to the nodes in the network. After preliminary validation, the transaction enters an area known as the “mempool.” The mempool acts like a waiting area where transactions have not yet been confirmed and added to the next block of the blockchain.

Previous miners (in PoW systems) are now validators (in PoS systems) who have the right to select transactions from the memory pool and decide the order of these transactions in the next block.

The order of transactions in a block is crucial. Before a block is finalized and added to the blockchain, the transactions within that block are executed in the order determined by the validator (such as bobTheBuilder). This means that if a block contains multiple transactions interacting with the same transaction pool, the execution order of these transactions will directly affect the outcome of each transaction.

This capability allows validators to prioritize specific transactions, delay or exclude others, and even insert their own transactions to maximize profits.

The ordering of this transaction is equally important; even a slight mistake can lead to a failed attack.

2.3 The transaction ordering of this MEV attack

Let’s first briefly understand the 3 transactions related to this MEV attack:

dOFw7Sh0V9EIVxqeuCZIDFbCHSXZ7Sl9JXeXJUue.png

  • Trade 1 (the attacker’s first trade): Executed before the victim’s transaction. The purpose of this trade is usually to drive up the price of the token that the victim wants to trade.
  • Transaction 2 (Victim’s Transaction): Executed after the attacker’s first transaction. Due to the attacker’s previous actions, the price in the transaction pool is unfavorable for the victim at this time; he has to pay more USDC to exchange for an equivalent amount of USDT, or he can only exchange for less USDT.
  • Transaction 3 (Attacker’s Second Transaction): Executed after the victim’s transaction. The purpose of this transaction is usually to profit from the new price fluctuations caused by the victim’s transaction.

This time, the validator of the MEV attack is bob-The-Builder.eth, who is responsible for arranging the transactions in the order of 1, 2, 3. Of course, bobTheBuilder didn’t do this for free; he earned more than 100 ETH from this sorting, while the initiator of the MEV attack only had an income of 8000 USD. Their income comes from the victim’s second transaction.

In short, the attacker (MEV bot) colluded with the validator (bobTheBuilder) to cause the victim of the second transaction to lose $215,000, with the attacker receiving $8,000 and the validator receiving $200,000 (over 100 ETH).

The attack method they use has a vivid name - sandwich attack. Below, we will explain it trade by trade, so you can thoroughly understand how the relatively complex MEV sandwich attack works.

3. Full Analysis of Sandwich Attacks

The reason it is called a Sandwich Attack is that the attacker’s two transactions (Transaction 1 and Transaction 3) are placed before and after the victim’s transaction (Transaction 2), making the entire transaction sequence resemble the structure of a sandwich (see the image above).

Transaction 1 and Transaction 3 serve different functions. In simple terms, Transaction 1 is responsible for the crime, while Transaction 3 is responsible for dividing the spoils. Specifically, the entire process is as follows:

3.1 Transaction 1, responsible for increasing the price of USDT

Click on the link for transaction number 1 in the image above, and you will see the detailed content of transaction number 1. The attacker directly raised the price of USDT by exchanging all 17.58 million USDT with 18.65 million USDC, as shown in the image below.

vi4i8ramCtgyZuTSNZLLVLsqry8MONxhGPRUVOsC.png

At this time, the remaining assets in the liquidity pool are a large amount of USDC and a small amount of USDT. According to news reports, before the attack, Uniswap had approximately 19.8 million USDC and USDT in its liquidity. After executing the trade, only 2.22 million USDT remains in the pool (=1980-1758), while the USDC balance increases to about 38.45 million (=1980+1865).

At this point, the exchange rate between USDC and USDT in this pool is no longer 1:1, but 1:17, which means that it takes 17 USDC to exchange for 1 USDT. However, this ratio is only approximate because this pool is V3, and the liquidity inside is not evenly distributed.

There is one more thing I want to tell you. In fact, the attacker did not use 18.65 million USDC all at once; the actual amount of USDC used was 1.09 million, which is less than 6%. How did he do it? We will explain it in detail after we finish discussing the attack.

3.2 Transaction 2, execute 220,000 USDC to exchange for USDT

Clicking the link of trade 2 in the above image will show the following image.

x3kBJKcYVyM44HJSUHuIxVQ1ScIutWsoZ6JuRvM7.png

As shown in the figure above, the victim’s transaction 2 was affected by transaction 1, resulting in only 5272 USDT for 220,000 USDC, unknowingly incurring a loss of 170,000 USDT. Why is it said to be unknowingly? Because if the victim was trading through Uniswap, the interface they would see when submitting the transaction would be as follows.

rqLjmsxfcI06dN56OvKVyTctzoiWpvUPvCyEWYom.png

From the above image, you will find that the victims should at least receive 220,000, which should be guaranteed. The reason the victims ultimately only received over 5,000 USDT is due to a huge slippage, reaching over 90%. However, Uniswap has a default maximum slippage limit of 5.5%, as shown in the image below.

Qlpu7GNLheCyBJtsy2LEgpo0vVP2oENI4sGcSiiW.png

In other words, if the victim traded through the Uniswap frontend, then they should have received at least 208381 USDT (= 220510 * 94.5%). You may wonder why the blockchain record above shows that this transaction took place on “Uniswap V3”.

Because the front end and back end of blockchain transactions are separate. The “Uniswap V3” mentioned above refers to the USDC-USDT liquidity pool of Uniswap, which is public, allowing any front end of a transaction to trade through this pool.

It is precisely because of this that some people suspect that the victim is not simple, not an ordinary person; otherwise, there wouldn’t be such a large slippage. It may be a case of using MEV attacks for money laundering. We’ll talk about this later.

3.3 Transaction 3, Harvesting + Dividing the spoils

hco4wljEJ9HngbaT8S3asZcEGGNpt9HjUPoAA1ka.png

Click on the link to view the details of transaction 3, as shown in the above image. Let’s discuss transactions A, B, and C separately.

In transaction A, the liquidity in the pool was restored to normal, and 17.32 million USDT was exchanged back for 18.60 million USDC.

Transaction B, preparing for profit distribution, exchanging part of the earnings——204,000 USDC for 105 ETH;

Transaction C, distribute the loot, pay 100.558 ETH to the validator bob-The-Builder.eth.

The sandwich attack has ended.

Now let’s address a very important question mentioned above: how did the attacker achieve an attack of 18 million with 1.09 million USDC?

4. How the attacker executed a pool attack of 18 million USDC

The reason the attacker was able to carry out an attack worth 18 million dollars with only 1.09 million USDC in principal is due to a magical and special mechanism in the blockchain world—Uniswap V3’s Flash Swap.

4.1 What is Flash Swap?

In simple terms:

Lightning Exchange allows users to withdraw assets from the Uniswap pool in the same transaction and then repay with another asset (or the same asset plus a fee).

Uniswap allows this “take first, pay later” behavior as long as the entire operation is completed within the same transaction. Please note that it must be completed within the same transaction. This design is intended to ensure the security of the Uniswap platform itself:

  • Zero-risk borrowing: Uniswap allows users to withdraw funds from the pool temporarily without collateral (similar to borrowing), but must be repaid immediately at the end of the transaction.
  • Atomicity: The entire operation must be atomic, either completely successful (funds returned) or completely failed (transaction rolled back).

The original intention of the design of lightning exchange was to facilitate more effective on-chain arbitrage, but unfortunately, it has been exploited by MEV attackers, becoming a tool for market manipulation.

How does 4.2 Lightning Exchange assist?

Let’s take a look at the picture and see how the lightning exchange of this attack was achieved step by step, as shown in the figure below.

S6eRIwZXTXtWBU7tUaAjr9bvAm2RIPpdoyjiHnhn.png

  • F1 attacker borrowed 1.09 million USDC from AAVE using their own 701 WETH;
  • The attacker initiates a lightning exchange request on F2, first withdrawing 17.58 million USDT from the Uniswap pool (no payment is required at this time), temporarily increasing the attacker’s account by 17.58 million USDT;
  • The attacker quickly deposited 17.58 million USDT into the Curve pool and exchanged it for 17.55 million USDC. The attacker’s USDT decreased by 17.58 million, while USDC increased by 17.55 million. From the chart below, you will find that the attacker chose Curve because there is ample liquidity here, with over 70.54 million USDT and 50.71 million USDC, resulting in relatively low slippage.

o1LnGSaUlzRjt7vqs5YOy0wqTRznOxzRkjVHSdEw.png

  • The F4 attacker then returned the 17.55 million USDC obtained from Curve, along with the originally prepared 1.09 million USDC (from Aave lending), totaling 18.64 million USDC, to Uniswap in one go, completing the flash swap;

After this transaction (Transaction 1), the attacker’s account balance decreased by 1.09 million USDC, because out of the 18.64 million USDC returned to Uniswap, only 17.55 million USDC was exchanged from Curve, while the remaining 1.09 million USDC was the attacker’s own funds.

You should have noticed that this transaction actually caused the attacker a loss of 1.09 million. However, in the subsequent transaction 3, which also used the method of lightning swapping, not only did it recover the 1.09 million USDC, but it also earned over 200,000.

oKE3vvGoW8lIISTane5LmOrh3BrDYyLV5PxHLXkM.png

Next, let’s analyze the data of Transaction 3 step by step.

  • K1 attacker withdrew 18.6 million USDC from Uniswap using a flash swap;
  • K2 attacker swapped 17.3 million USDC, which was just withdrawn from Uniswap, for 17.32 million USDT.
  • The attacker K1 returned the 17.32 million USDT obtained from Curve back to Uniswap. The flash swap is complete. It’s important to note that the attacker only spent 17.3 million USDC through K2 to acquire 17.32 million USDT. Of the remaining 1.3 million (= 1.86 million - 1.73 million) USDC, 1.09 million is their own funds, while the remaining 210,000 USDC is the profit from this attack.
  • K3 attacker returned the principal to AAVE, took away 701 WETH, exchanged 200,000 USDC for 105 ETH, and sent 100.558 ETH to the validator as a tip (approximately 200,000 USD), keeping less than 10,000 USD in profit for themselves.

You might be surprised why attackers are willing to hand over profits of up to $200,000 to validators?

4.3 Why give a “tip” of 200,000 dollars?

Actually, this is not generosity, but a necessary condition for a successful MEV attack like a sandwich attack:

  • The key to a successful attack is the precise control of transaction order, and it is the validator (bobTheBuilder) who controls the transaction order.
  • Validators not only help attackers ensure that the victim’s transactions are between the attacking transactions, but more importantly, validators can ensure that other competing MEV bots cannot queue jump or interfere with the smooth completion of the attack.

Therefore, attackers would rather sacrifice the majority of their profits to ensure the success of the attack, while keeping a certain amount of profit for themselves.

It is important to note that MEV attacks also have costs. There are costs associated with flash swaps on Uniswap and costs in Curve trading as well. However, due to the relatively low fee rates of approximately 0.01% to 0.05%, these costs are negligible compared to the gains from the attack.

Finally, let me remind you that defending against MEV attacks is actually quite simple. You just need to: set your slippage tolerance, not to exceed 1%; execute large trades in several smaller transactions. So, you don’t have to stop trading on DEX (decentralized exchanges) out of fear.

Conclusion: Warnings and Insights from the Dark Forest

The $215,000 MEV attack incident is undoubtedly another brutal demonstration of the “dark forest” principle in the blockchain world. It vividly reveals the complex game of exploiting mechanism loopholes to gain benefits in a decentralized, permissionless environment.

From a higher perspective, the emergence of MEV is a reflection of the double-edged sword effect of blockchain transparency and programmability.

  • On one hand, all transaction records are publicly accessible, making it possible to track and analyze attack behaviors;
  • On the other hand, the complex logic of smart contracts and the determinism of transaction execution also provide savvy participants with opportunities.

This is not simply a hacking act, but a profound understanding and utilization of the underlying mechanisms of blockchain. It tests the robustness of protocol design and challenges the risk awareness of participants.

Understanding MEV and recognizing its risks is essential for navigating this digital world filled with opportunities yet also hidden crises. Remember, in the “dark forest” of blockchain, only by respecting the rules and enhancing awareness can one avoid becoming the next prey to be devoured.

This is also the effect I want to achieve through this article.

View Original
Disclaimer: The information on this page may come from third parties and does not represent the views or opinions of Gate. The content displayed on this page is for reference only and does not constitute any financial, investment, or legal advice. Gate does not guarantee the accuracy or completeness of the information and shall not be liable for any losses arising from the use of this information. Virtual asset investments carry high risks and are subject to significant price volatility. You may lose all of your invested principal. Please fully understand the relevant risks and make prudent decisions based on your own financial situation and risk tolerance. For details, please refer to Disclaimer.
Comment
0/400
No comments
Trade Crypto Anywhere Anytime
qrCode
Scan to download Gate App
Community
English
  • 简体中文
  • English
  • Tiếng Việt
  • 繁體中文
  • Español
  • Русский
  • Français (Afrique)
  • Português (Portugal)
  • Bahasa Indonesia
  • 日本語
  • بالعربية
  • Українська
  • Português (Brasil)