DeFi Security Lecture 8 — Front Running Attack

Beaver Finance
beaver-smartcontract-security
12 min readJan 20, 2022

Front-running attacks have knowingly or unknowingly impacted many users swapping tokens on automated market maker (AMM) exchanges.

What is front-running?

In general, front-running refers to the act of jumping in the execution queue to redeem a transaction before a known future transaction occurs. These front-running robots can analyze smart contract instructions and functions they have never used in a smart contract before to extract potential gains and cut off funds.

A front-running attack occurs when a malicious user observes a swap transaction after it is broadcast but before it is finalized and reorders transactions to benefit themselves. Commonly, a miner or bot will place their own transaction immediately in front of the pending transaction.

Front-Running is the process of waiting for a normal transaction to be packaged. The front-running robot preemptively completes the attack transaction by setting a higher gas fee to seize the user’s interests. Mempool is a group of Ethereum transactions that have been broadcasted to the network and are waiting to be packaged into blocks.

It is the premise that Front-Running can be implemented. The front-running robot analyzes and finds attackable targets by continuously scanning the transactions in the Mempool.

On the Mempool browser, you can subscribe to transactions in Mempool by setting various filters and viewing the full details of these transactions.

How to arbitrage through front-running?

A simple example of front-running is an exchange bid. Suppose someone is about to buy a lot of ETH on Uniswap, enough to push the price of ETH up. One way to benefit from this scenario is to snap up ETH in the moments before this massive ETH purchase when prices are still low. Then, immediately after the ETH price surges, sell to lock in profits.

When the chain detects that you have a buying behavior, it will immediately buy your ETH. Plus, since the gas is higher, and you confirm the transaction one step faster, your overall transaction price will be higher because DEX has slippage, so you will still be at a vantage point. The price of one point is filled, and the price is pushed up a little more. At this time, the chain sells again, completing an arbitrage.

In addition to this example of arbitrage trading, there are many ways to use front-running to extract value, including liquidation, buying rare NFTs, or simply creating user errors. (The extractable value of a transaction or order of deals is called “Miner Extractable Value MEV”).

In the Ethereum Mempool (a set of pending, unconfirmed transactions), these hackers take the form of ‘arbitrage bots.’ Arbitrage bots monitor pending trades and try to exploit them to create profit opportunities. Arbitrage bots typically look for specific types of trades in the Mempool (like DEX trades or oracle updates) and try to front-run trades according to a predetermined algorithm. Generic frontrunners look for any transactions that make a profit by copying and replacing them with their own addresses.

The most typical and harmful among these front-running attacks is a Sandwich Attack against AMM transactions. In addition, there are also front-running attacks against arbitrage, clearing transactions, flash loans, etc. that exploit system loopholes to make profits. With automated script control, there is almost no chance of being spared.

In order to better explain the attack principle, we are adding some background knowledge.

We know that today’s mainstream DEXs, such as Uniswap, all use the AMM (Automated Market Maker) mechanism, and their prices follow a constant product formula. For example, if a liquidity pool of A token and ETH is established in Uniswap, the quantity of A is 1000, and the quantity of ETH is 100, then the product of the two quantities is 100000, and the current price of A is 0.1ETH. When Alice tries to use 10 ETH to buy token A in the pool, the amount X of A she gets can be deduced by the following formula (Note: To simplify the calculation, the handling fee is not considered below):

(1000-X)\(100+10)= 100000,X = 90.9

In this transaction, token A’s price is 10/90.9 = 0.11, and the price slippage compared to the original A’s price is:

(0.11–0.1)/0.1 * 100% = 10%

A single transaction caused a 10% slippage in the currency price. It can be seen that the more illiquid the pool, the more likely it is to generate slippage when encountering large transactions. And if, before the user’s normal large-value transaction (the transaction is expected to have a large slippage), they can buy token A first, and then after the user’s normal transaction, sell the bought token A, to derive a significant amount of profit.

Following the previous example, suppose that before Alice’s transaction, Bob spends 5 ETH on buying token A first, and then after Alice’s transaction is completed, Bob sells the previously bought token A, let’s see what the result will be:

The first is Bob’s front-running transaction:

(1000-X)\(100+5) = 100000, X = 47.62

That is, Bob buys 47.62 A for 5 ETH

Next is Alice’s normal transaction. Note that the number of A in the liquidity pool becomes 952.38 and the number of ETH becomes 105:

(952.38-X) \ (105+10) = 100000, X = 82.81

Finally, Bob sells 47.62 token A’s transactions, at this time, the amount of A in the liquidity is 869.57, and the amount of ETH is 115:

(869.57+47.62)\*(115-Y)= 100000,Y = 5.97

Bob nets 5.97–5 = 0.97 ETH through this front-running attack, while Alice’s net loss is 90.9–82.81 = 8.09 A. Bob gets his own gain by making Alice suffer a larger slippage loss!

Of course, the actual front-running attack will be more complicated, and the attacker needs to perform more sophisticated calculations in order to achieve the following two goals:

  1. Let the user’s transaction result infinitely approach the maximum slippage (max_slippage) set by the user themself in order to achieve the theoretical maximum arbitrage space
  2. Striking a balance between fee competitiveness and income, and try to win the competition with other robots as much as possible

We use the graph above to better describe this process:

  1. At point A, the user intends to invest in_amount(user) USDT to buy ETH, this transaction will normally push the current state to B, and the user sets the maximum slippage as B(max_slippage);
  2. The preemptive robot detects this transaction, and before the user’s transaction, it conducts a buy transaction of in_amount(robot) USDT, and pushes the current state to A’;
  3. The user’s transaction is subsequently executed, reaching the maximum slippage B (max_slippage) set by it;
  4. The preemptive robot sells the ETH bought in step 2, the status reaches point C, and gets out_amount(robot) USDT
  5. Run the robot to get the profit out_amount(robot) — in_amount(robot) — handling fee

How does the front-running bot work?

Building a generalized front-running bot usually requires two components:

  • The first component is an Ethereum account, with or without a smart wallet agent, to which their tampered transactions will be sent.
  • The second is the “backend,” the brain of the operation, which usually occurs off-chain.

The operators of these bots use specific techniques to scan each trade in the trading pool, parse it, replace its parameters (for example, the trade caller), and determine whether it is profitable to cut it. Instead of using services like Infura or even private nodes, the transaction layer sends transactions directly to miners, who promise not to broadcast them to the rest of the network, ensuring that transactions stay off the radar of predators. Miners started manipulating front-running bots while only providing a safe channel for traders who paid extra.

Front-End front-running Workflow

Rational bots will not attack transactions where the transaction fee exceeds the potential profit. Total transaction fees can be high, especially when gas prices are high, so a certain minimum profit is required for front-running bots to attack decoy transactions.

Also, time is important since the bot needs to analyze every transaction in the transaction pool (of which there are many transactions). Ethereum takes an average of 12 seconds to produce a block. If the gas price of a transaction is high enough, it must be analyzed and replaced quickly enough before the next block is produced.

This is a probabilistic process. After the transaction is broadcast, it is possible that a block will be mined immediately, so that the robot does not have time to successfully analyze the transaction and broadcast a preemptive transaction.

Examples of real-world Front Running Attacks

On January 14th, 2022, the airdrop of WTF began at 0:00 on Friday. But the WTF airdrop was nothing short of carnage. Although not a rug-pull, some MEV bots have swept away more than $100,000 in profits like bandits due to mishandling by the team. Fees.wtf is a dApp that, after connecting it to your Ethereum wallet, tells you how much you spend on Ethereum gas fees.

When WTF is released, developers add a certain amount of WTF liquidity to the pool. Specifically, they added 2211.46 WTF, the first interaction with the Uniswap pool was a user adding a very low/sloping liquidity ratio, however, the team added almost no WETH (0.00001 ETH).

https://etherscan.io/tx/0xec34f30b96707bf76f4d65ae3124d94124e6879c01aca3f39d2cba67799546f8

Immediately after that, the bots that intend to drain the liquidity pool started running, and one bot bought 2211.45 WTFs from the pool at the price of 2 ETH. This caused the price of WTF to skyrocket, while other addresses trying to buy the remaining 0.01 WTF were paying more and more.

https://etherscan.io/token/0xa68dd8cb83097765263adad881af6eed479c4a33?a=0xefa3254af4ea456d69bc2326e0dbb6fc89bedfac

By this time, the WETH-WTF trading pair had accumulated dozens of ETH due to bot purchases, and there was almost no WTF left in the pool, which meant that selling any amount of WTF would be a huge profit.

We can look at the details of this process in detail:

An address first bought “a little” WTF (worth 10 ETH at the time).

https://etherscan.io/tx/0x0c9073f079aba98c5930f6c9e7b7d9196bc00af7e29d638fadc94f55e351b8eb

Then, after the front-running robot detected this profitable transaction, it immediately launched an attack and launched a buy transaction. This address sent an ultra-fast transaction at a speed of 3000 gwei in the next block.

The Gas competition mechanism Successfully preempted the user’s normal transaction, sold their previously purchased WTF at a price nearly 6 times higher than the original price, and successfully withdrew 58 ETH of liquidity from the WETH-WTF pool.

https://etherscan.io/tx/0x1cfac232b226dd81c90f4925716b025d471ea5c16d656b68127a126cae51f8f0

Eventually, the liquidity pool becomes fully tilted. While the bots are sniping liquidity, some speculative users are still spending a lot of ETH to buy WTF in smaller and smaller quantities.

For example, at this address, it took 22 ETH to buy only 2.34 WTF.

https://etherscan.io/tx/0x48699a888f73bf71290615297e6a5929460ddcd5a3dcb4bea0240066ae1e2f9d

Subsequently, more liquidity was added to the pool, and MEV bots (specifically MEV Bot: 0x000…B40) started attacking thousands of users at once.

https://etherscan.io/token/0xa68dd8cb83097765263adad881af6eed479c4a33?a=0x00000000003b3cc22af3ae1eac0440bcee416b40

For example, a bot used a $2.7 million flash loan to extract $2,000 from an address through a sandwich attack. In the end, the address only acquired about 0.0000000019 WTF (the user’s unit price of WTF was nearly $1.04 billion).

https://etherscan.io/tx/0xde78fe4a45109823845dc47c9030aac4c3efd3e5c540e229984d6f7b5eb4ec83

And as of now, the price of WTF is hovering around $0.20. This is all caused by MEV bots, each trying to drain the nascent liquidity pool as fast as possible, and the bot wins.

How to prevent front-running?

Now that we’ve seen the dramatically negative after-effects of Front-Running, what can we do to stop a front-running attack?

As a general user, there are several ways to deal with Front-Running:

1. Set a low transaction slippage, such as 0.1%, which will make the front-running robot less profitable.

Disadvantages: The slippage is too low, which makes large transactions very easy to fail, and the failed transactions still need to pay high fees.

2. Increase the gas cost, which will increase the attack cost of the robot.

Disadvantage: This also increases the transaction costs.

It can be seen that the above solutions come with their own shortcomings, making them less efficient. Let’s look at some more constructive solutions that have been proposed throughout the history of DeFi.

First, by analyzing the whole process of hunting, we can conclude that to achieve front-Running, several elements are required:

  • Transaction publicity: Transaction details can be obtained in the Mempool.

Ethereum transaction execution mechanism: the transaction can be preemptively completed through gas competition;

  • AMM Trading Curve Mechanism: Constant Product Mechanism Can Cause Large Slippage.

Our countermeasure to front running lies in these two elements.

Transaction publicity

Since the robot decides whether to launch an attack by analyzing the transactions in the Mempool, then can we directly encrypt the transaction information so that the robot cannot see or understand it!?

Some leaders in the community propose to use the zero-knowledge proof technology zk-SNARKs to achieve the above goals, that is, to use zk-SNARKs to encrypt and hide the information of each transaction so that the robot can not start.

However, at present, the solution is too nascent, and there are defects in its designs including high gas consumption to block attacks resulting in systematic overall liveness.

Ethereum transaction execution mechanism

The current Ethereum transaction execution mechanism is completed through gas competition, that is, whoever pays the highest gas fee, the miner will package the transaction first, then if we bypass this mechanism and send the transaction to the miner to be packaged directly, It eliminates the possibility of the rushing robot attacking in the middle.

Therefore, a scheme similar to Layer 0 has also been applied, such as the Taichi service of Spark Pool. Users can directly set up Taichi’s Ethereum node in MetaMask so that transactions are directly packaged without appearing in Mempool. However, the disadvantage is that there is a certain uncertainty in the timeliness of being packaged.

In addition, solutions with similar concepts such as ArcherSwap build a bridge between traders and miners.

Traders can let miners directly package their own transactions in the form of rewards, which avoids the possibility of being Front-Running. Although there is such a feeling of paying protection fees to avoid being attacked, it also reduces the cost of traders and has the advantage of not charging transaction failure fees.

AMM Algorithm Optimization

Under the AMM mechanism, large-value transactions generate excessive price slippage (which can be understood as a temporary wrong price), which is the profit margin of Front-Running. If there is an AMM mechanism that can reduce the impact of large-value transactions on subsequent transaction price, it can effectively prevent Front-Running attacks.

As early as 2018, Vitalik provided a solution in the Ethereum technical community. When a swap transaction occurs, the transaction pool price will not immediately be adjusted to the real price. Still, it will slowly tend to the real price within a few minutes, which imitates a scenario like there is a lot of liquidity in the trading pool out of thin air. This technology was named as the Virtual Balance technology.

This new mechanism can greatly compress the profit margins of arbitrageurs, effectively defend against Front-Running attacks, and at the same time increase the income of liquidity market makers.

Increase Liquidity

In addition, there is another way of thinking, which is to increase the liquidity of a specific price range in the trading pool as much as possible. The greater the liquidity, the smaller the slippage.

The preemptive robot will lose profits when the liquidity reaches a certain level. Space, the liquidity-focused feature of Uniswap’s V3 release, is an effort in this regard.

Summing up

Front-running transactions in Ethereum can be achieved by paying a slightly higher gas price than normal. In this way, miners are encouraged to prioritize their transactions when building blocks. The higher the transaction fee, the higher the order of execution.

Therefore, if both transactions profit from the same instruction calling the smart contract in the same block, only the transaction that fills first will ultimately profit.

Beaver Finance team up with experienced security experts on building our system and would continuously share our findings on DeFi security topics.

Stay Alert, Stay Safe!

Reference

1,https://twitter.com/WazzCrypto/status/1481810591618637827

2,http://www.finacerun.com/home/news/detail/article_id/70535.html

--

--

Beaver Finance
beaver-smartcontract-security

Beaver Finance is a Single-Asset Intelligent Yield Enhancing platform with the Option-based cutting-edge hedging solution for Impermanent Loss.