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

Written by: Daii

Last Wednesday (March 12), a cryptocurrency trader was hit by an MEV attack and lost $215,000 in a single instance.

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

The above image 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.

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.

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

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

Today, we will take this MEV attack as an example, dismantle the whole process, and take you through the dark world of MEV.

First, we need to explain what MEV is.

  1. What is MEV?

MEV, originally known as Miner Extractable Value, refers to the additional profit that miners can obtain by reordering, inserting, or excluding transactions within a blockchain block. Such actions may cause ordinary users to incur higher costs or receive less favorable transaction prices.

As blockchain networks like Ethereum transition from Proof-of-Work (PoW) consensus mechanisms to Proof-of-Stake (PoS) consensus mechanisms, the power to control transaction ordering has shifted from miners to validators. As a result, the terminology has accordingly 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 the miners of the past and the validators of the present have the right to sort transactions in the memory pool (mempool). This sorting occurs within a block, and currently, Ethereum generates a block approximately every 11 seconds, which means that such a power exercise happens every 11 seconds. Similarly, this MEV attack was also implemented through the sorting of the validators.

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

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

  1. The principle of MEV

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

2.1 Blockchain Status Update Mechanism

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

When a new block is added to the blockchain, all transactions included 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 is accordingly changed.

In other words, not only is the order of the blocks important, but the order of the transactions within the blocks is also crucial. So how is the order of transactions within a block determined?

2.2 The validator determines the order of transactions

When a user initiates a transaction on the blockchain network, such as a transaction that converts USDC to USDT via Uniswap, it is first broadcasted to the nodes in the network. After preliminary verification, the transaction enters an area called 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 determine 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 (for example, 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 certain transactions, delay or exclude others, and even insert their own transactions to maximize profits.

The order of this transaction is equally important; any slight mistake could lead to a failed attack.

2.3 The transaction sorting of this MEV attack

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

Transaction 1 (Attacker's First Transaction): Executed before the victim's transaction. The purpose of this transaction 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 point, and he needs to pay more USDC to exchange for an equivalent amount of USDT, or 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 movements caused by the victim's transaction.

This time, the validator of the MEV attack is bob-The-Builder.eth, who is responsible for ordering the transactions in the sequence of 1, 2, 3. Of course, bobTheBuilder is not doing this for free; he earned over 100 ETH from this sorting, while the initiator of the MEV attack only made $8,000. Their income comes from the victims' second transaction.

In a nutshell, the attacker (MEV bot) colluded with the validator (bobTheBuilder), causing the victim of the second transaction to lose $215,000, of which the attacker received $8,000 and the validator received $200,000 (over 100 ETH).

The attack method they use has a vivid name - sandwich attack. Next, let's explain it transaction by transaction, so you can thoroughly understand how the relatively complex MEV sandwich attack works.

  1. A Comprehensive 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 above image).

Transaction 1 and Transaction 3 serve different functions. To put it simply, Transaction 1 is responsible for the act, while Transaction 3 is responsible for the distribution of the proceeds. Specifically, the entire process is as follows:

3.1 Trade 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 information of transaction number 1. The attacker raised the price of USDT quite directly by exchanging all of the 17.58 million USDT inside with 18.65 million USDC, as shown in the image below.

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's liquidity had approximately 19.8 million USDC and USDT respectively. After executing transaction 1, there would only be 2.22 million USDT left in the pool (=1980-1758), while the USDC balance would increase to about 38.45 million (=1980+1865).

At this time, the exchange rate between USDC and USDT in this pool is no longer 1:1, but rather 1:17. This means that it takes 17 USDC to exchange for 1 USDT. However, this ratio is just an approximation because this pool is V3, and its liquidity is not evenly distributed.

One more thing, I'm going to tell you. In fact, the attacker did not use 18.65 million USDC at one time, and the actual USDC used was 1.09 million, which is less than 6%. How did he do it? We'll talk about it in more detail when we're done with the attack.

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

Clicking the link of Transaction 2 in the above image will show the image below.

As shown in the figure above, the victim's transaction 2 was affected by transaction 1, resulting in only 5,272 USDT for 220,000 USDC, leading to an unnoticed loss of 170,000 USDT. Why do we say it was unnoticed? Because if the victim was trading through Uniswap, the interface they would see when submitting the transaction would be as follows.

From the above figure, you will find that the victims should have at least received 220,000 in guaranteed funds. The reason the victims only received a little over 5,000 USDT in the end was due to a massive slippage, exceeding 90%. However, Uniswap has a default maximum slippage limit of 5.5%, as seen in the figure below.

In other words, if the victim was trading through the Uniswap frontend, then he should receive at least 208381 USDT (= 220510 * 94.5%). You might be wondering why the blockchain record above shows that this transaction was conducted 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 and can be accessed by any front-end for trading.

Also because of this, 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 using MEV attacks for money laundering. We will discuss this later.

3.3 Transaction 3, Harvesting + Distribution

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

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

Trade B, prepare for the distribution of loot, exchange 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.

At this point, the sandwich attack is over.

Now let's address a very important question mentioned above: how did the attacker achieve an attack of 18 million using 1.09 million USDC.

  1. How did the attacker execute the pool attack of 18 million USDC?

The reason the attacker was able to execute an attack worth $18 million using only $1.09 million in USDC principal is because there exists 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 first withdraw assets from the Uniswap pool in a single transaction, and then repay with another asset (or the same asset plus fees).

As long as the entire operation is completed within the same transaction, Uniswap allows this "take first, pay later" behavior. Please note, it must be completed within the same transaction. This design is aimed at ensuring the security of the Uniswap platform itself:

Zero-risk lending: Uniswap allows users to temporarily withdraw funds from the pool without collateral (similar to lending), but must repay immediately at the end of the transaction.

Atomicity: The entire operation must be atomic; it must either succeed completely (funds returned) or fail entirely (transaction rolled back).

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

4.2 How does 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.

F1 attacker borrowed 1.09 million USDC from AAVE using their own 701 WETH;

F2 attackers initiated a flash swap request, first withdrawing 17.58 million USDT from the Uniswap pool (no prior payment is needed at this moment), temporarily increasing the attacker’s account by 17.58 million USDT;

F3 attackers quickly deposited 17.58 million USDT into the Curve pool, exchanging it back for 17.55 million USDC. The attacker's USDT decreased by 17.58 million, while USDC increased by 17.55 million. As you can see in the chart below, the reason the attackers chose Curve is because there is ample liquidity here, with over 70.54 million USDT and 50.71 million USDC, resulting in relatively low slippage.

F4 attackers then returned the 17.55 million USDC exchanged from Curve, plus the 1.09 million USDC they originally prepared (from Aave lending), totaling 18.64 million USDC, completing the flash swap with Uniswap.

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, and 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 following transaction 3, using the same flash swap method, not only did they recover the 1.09 million USDC, but they also made over 200,000.

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

K1 attacker withdrew 18.6 million USDC using a flash swap on Uniswap;

The K2 attacker exchanged 17.3 million USDC, which was just withdrawn from Uniswap, for 17.32 million USDT.

The attacker K1 returned the 17.32 million USDT converted from Curve back to Uniswap. The flash swap was completed. It is important to note that the attacker obtained 17.32 million USDT by spending only 17.30 million USDC through K2. Of the remaining 1.3 million (= 1.86 million - 1.73 million) USDC, 1.09 million came from their own funds, while the remaining 210,000 USDC was 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 (about 200,000 USD), leaving himself with less than 10,000 USD in profit.

You may be surprised as to 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 validators (bobTheBuilder) who control the transaction order.

Validators not only help attackers ensure that the victim's transactions are between the attacking transactions, but more crucially, validators can ensure that other competing MEV bots cannot front-run or interfere with the smooth execution of the attack.

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

It should be noted that MEV attacks also come with costs. There are costs associated with flash swaps on Uniswap and costs when trading on Curve. However, due to the relatively low fees, which are around 0.01% to 0.05%, they can be considered negligible compared to the gains from the attacks.

Finally, a reminder that defending against MEV attacks is actually quite simple. You just need to: set your slippage tolerance properly, not exceeding 1%; execute large trades in multiple smaller orders. Therefore, you don’t have to avoid 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 manifestation of the "dark forest" principle in the blockchain world. It vividly reveals the complex game of exploiting mechanism loopholes for profit in a decentralized, permissionless environment.

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

On one hand, all transaction records are publicly accessible, allowing for tracking and analysis of attack behaviors.

On the other hand, the complex logic of smart contracts and the determinism of transaction execution provide savvy participants with opportunities to exploit.

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

Understanding MEV and recognizing its risks is essential for navigating this digital world that is full of opportunities but also harbors hidden dangers. Remember, in the "dark forest" of blockchain, only by respecting the rules and enhancing our awareness can we avoid becoming the next prey to be devoured.

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

View Original
The content is for reference only, not a solicitation or offer. No investment, tax, or legal advice provided. See Disclaimer for more risks disclosure.
  • Reward
  • Comment
  • Share
Comment
0/400
No comments