Front-running attacks are at the forefront of various types of attacks in the blockchain world. In traditional stock markets, front-running involves intermediaries like brokers or traders using their clients’ trading information against them, a practice that’s illegal, unethical, and hard to prove unless done naively.
In decentralized finance, front running refers to a malicious practice where a miner, as well as non-miners, can mount this type of attack. They take advantage by exploiting advanced knowledge of pending transactions to gain an upper hand over other participants in the network.
Reported in 2022, over 2.5 years, more than USD $500 million was extracted from the Ethereum blockchain due to front-running activities, including sandwich attacks, liquidations, and arbitrage opportunities. To date, the reports show a rapid increase in these statistics.
Let’s quickly delve into the basics of front-running attacks, walk through the taxonomy of front-running attacks, understand the factors triggering front-running and briefly discuss the role of MEV bots in front-running attacks and preventive measures.
What is a Front-Running Attack?
As the name suggests, front-running refers to the practice of someone overtaking or jumping ahead to gain an advantage. Someone might argue that it is just another form of competition, similar to how businesses compete in the real world. Let’s quickly go through a simple scenario to see how front-running occurs and why it is an unethical practice.
Alice and Bob participate in a Quiz game. Alice solves the problem and submits her answer to the blockchain with a 15 gwei gas fee. Her transaction enters the mempool, waiting to be processed. Bob, who hadn’t solved the problem, was watching the mempool closely.
Spotting Alice’s transaction, he quickly copies her answer and submits his own transaction with a higher gas fee of 50 gwei. Because miners prioritize higher fees, Bob’s transaction was processed first, and he claimed the reward before Alice, despite her submitting the correct answer first.
Now, do you spot where the issue is? It is about exploiting insider knowledge or privileged access to information that others do not have.
Taxonomy of Front-Running Attacks
There are three different variants of how an attack can be performed: Displacement, suppression, and Insertion. We’ll understand each type of attack by short stories featuring Alice and Bob.
Displacement
In a displacement attack, just like the quiz example, the perpetrator uses a higher gas price to ensure their transaction is processed before a pending transaction, outbidding others to secure priority processing.
Alice submits a transaction to buy a rare NFT with a reasonable gas fee. Bob, noticing Alice’s pending transaction, submits his own transaction with a higher gas fee to purchase the same NFT. Bob’s transaction is prioritized and executed first, causing Alice’s transaction to fail as the NFT is no longer available.
Insertion
Insertion attacks, also known as sandwich attacks, place a victim’s transaction between two of the transactions, one before with a higher gas fee and one after with a lower fee, allowing the attacks to profit from price changes.
This tactic is well-known as arbitraging on decentralized exchanges, where an attacker observes a large trade, also known as a whale, and sends a buy transaction before the trade, and a sell transaction after the trade.
Alice submits a large trade on a decentralized exchange. Bob, spotting this transaction, quickly places a buy order with a higher gas fee, driving up the asset’s price. Alice’s trade then executes at this elevated price, resulting in her paying more. Afterward, Bob sells the asset at a higher price, making a profit from the price increase he triggered.
Suppression
A suppression attack, also known as block stuffing, means that attackers overwhelm the network by flooding it with transactions carrying high gas prices, creating a “suppression cluster” that fills the block and leaves little room for the victim’s transaction.
Alice tries to enter a blockchain lottery where the last ticket purchase wins. Just before the deadline, Bob submits a flood of high-fee transactions, filling up the block and delaying Alice’s transaction until after the deadline. Bob’s strategy wins him the lottery prize, while Alice’s transaction is effectively blocked.
Disclaimer: Don’t be like Bob, lurking in the mempool and disrupting Alice’s plans. You have a choice—be like Alice, who, despite good intentions, faces trouble due to naivety and lack of awareness, or be like Charlie, who stays informed and secure. Ensure your Web3 journey is safe and savvy—be like Charlie!
Which Factors are Responsible for Triggering Front-Running Attacks?
The ideal approach for detecting possibilities of front-running attacks focuses on identifying important triggers for front-running. Here is an outline of the notable triggers which can lead to front-running attacks.
-
Large transactions
When a large trade or ‘whale’ trade is initiated, it can cause significant price shifts. Hackers monitor such trades closely to front-run and profit. GMX attack in 2022 fits the example of these whale transactions.
-
Pending Transactions
The mempool, where pending transactions wait for processing is a common target for front running. As seen in Alice-Bob scenario, Attackers can spot profitable pending transactions and submit their own with higher gas fees.
-
Liquidity Pool Transactions
Adding or removing liquidity from DeFi pools can cause drastic fluctuations in price. Front-runners target such changes to exploit price discrepancies. In DeFi, liquidity pool fluctuations on platforms like Curve and Uniswap have been exploited by MEV bots that front-run liquidy shifts.
-
Arbitrage Opportunities and Flash loans
Arbitrage attacks have become more prevalent across decentralized exchanges, particularly with bots exploiting price discrepancies in 2022. Arbitrage occurs when the same asset is priced differently on different exchanges, allowing attackers to buy at a lower price on one platform and sell at a higher price on another, all within the same transaction.
These attacks leverage the lack of synchronization between markets, extracting profits without risk. They are similar to flash loan attacks in how they take advantage of price differences.
-
New token Listings
When new tokens are listed on DEX, a rush to buy them follows. This is usually seen during the launch of new tokens, bots often buy tokens first or attack front-run buy orders by submitting transactions with a higher gas fee, thus inflating the price before retail investors can act.
-
Updates for Oracles and APIs
Oracles and APIs provide external data to smart contracts. Updates to this data can change the outcome of contracts. Attackers can front-run these updates by using prior knowledge.
-
Governance Proposals
If a governance proposal is submitted to reduce token supply, it can impact token prices, an attacker could front-run by buying the token before the price rises following approval. Such governance changes in blockchain protocols can impact fee structures. Governance proposals in blockchain protocols can affect various aspects, including fee structures, token distribution, and protocol upgrades
-
Order Book Review
On decentralized exchanges using order books, attackers can review pending orders to identify profitable front-running opportunities. If Alice places an order to buy tokens, Bob can review the order book and place his buy order with higher priority, front-running Alice’s transaction.
What is the role of MEV bots in front-running attacks?
MEV (Maximum Extractable Value) bots play a significant role in front-running attacks by exploiting their ability to reorder, insert or exclude transactions in the mempool. These bots, powered by smart contracts, scan pending transactions and act swiftly to capitalize on profitable opportunities.
For instance, in 2023, MEV bots preying on liquidity providers caused losses of over $500 million, with a large percentage of these attacks targeting smaller transactions. Data from analyst Lekos revealed that 75% of these losses stemmed from transactions under $20,000, demonstrating how MEV bots exploit even smaller-scale traders for substantial profits. Their ability to manipulate transaction order in DEX has created a significant challenge for security DeFi ecosystems.
Front-Running In BlockApex Experience
In this section, we present one of the smart contract vulnerabilities that could have enabled front-running attacks. All issues have been resolved during the BlockApex Smart Contract Audit.
Axone Audit Overview
The Objectarium contract, built on the CosmWasm framework, serves as a decentralized data storage solution within the OKP4 ecosystem. It supports diverse unstructured data, essential for dApps that manage both simple and complex data types.
In this code snippet, the red section represents the vulnerable implementation, while the green section shows the updated, audited code that resolves the issue.
Vulnerability: DoS via Front-Running
- Front-Running Vulnerability: The core issue is that if an object already exists, the code simply returns an error (ObjectAlreadyStored), preventing Law Stone initialization if an attacker preemptively stores the same data.
- DoS Attack: Attackers can monitor the mempool for incoming transactions, extract the data, and front-run the transaction by storing the same object first. This would cause the legitimate transaction to fail, leading to a denial of service (DoS) for Law Stone’s initialization.
Resolution:
BlockApex identified and recommended strict checks to ensure Objectarium only accepts transactions from the expected contract, fixing the vulnerability in a subsequent update.
- No-Op for Existing Object: The fixed version removes the error when an object is already stored. Instead, if the object exists, it will still manage the pinning operation if needed, but it will not fail the entire transaction.
- Prevent DoS: This change ensures that even if an attacker has stored the same data first, the legitimate transaction will not fail. The Law Stone initialization can proceed without getting blocked by the ObjectAlreadyStored error.
Mitigation Techniques
Preventing front-running attacks in protocols involves addressing two main issues, one is lack of transaction confidentiality, the transparent nature of blockchain allows transaction details to be visible to all participants. Another apparent issue is the way miners order transactions, which are often ordered by gas fees.
We have separated developer end mitigation techniques, implemented by smart contract developers within DApps or smart contracts. On the other hand architectural mitigation which is mostly implemented by platforms, operates at the infrastructural level of blockchains.
Both layers of mitigation have their trade-offs. Architectural solutions can reduce the need for developer-end mitigations, but for many protocols, especially in decentralized finance (DeFi), a combination of both is necessary for comprehensive front-running protection. Here are some mitigation techniques for front-running attacks:
Architectural Mitigation
-
Disallowing Mempool Manipulation
Prevents miners or validators from reordering transactions based on visibility in the mempool to reduce front-running. In Ethereum 2.0, the shift to Proof of Stake (PoS) aims to mitigate the miner’s control over transaction sequencing.
A drawback would be that validators in PoS can reorder transactions based on other incentives, making complete prevention challenging.
-
Off-chain ordering
Transactions are sequenced off-chain before being settled on-chain, reducing visibility and front-running risk. Many layer 2 solutions, one of them being StarkEx order transactions off-chain before committing them to Ethereum.
The risk here is that this paves the way for centralization and reduces transparency for users, as transaction order is decided off-chain.
Developer-End Mitigations
-
Commit and Reveal
This method involves splitting a transaction into two parts: a commitment phase (where a hash of the transaction is submitted) and a reveal phase (where the actual transaction details are revealed).
During the commit phase, the data remains hidden from the public, preventing front-runners from exploiting it. However, this approach adds significant overhead due to additional transactions, making it less scalable for fast-paced DeFi activities.
-
Slippage Control
This mitigation requires users to set a minimum expected value for their transaction, typically by controlling the allowable price slippage in trades. This prevents front-runners from exploiting arbitrage opportunities.
This approach is effective for price-based or order-based front-running. However, manual configuration negatively impacts user experience, making the platform less user-friendly. Additionally, predicting the best prices in advance is challenging, making it difficult to calculate the optimal slippage amount for a trade
For users, we would say that the world is full of people like Bob, who take advantage of your naiveness so being vigilant of their tactics, taking the right preventive measures such as using privacy tools to mask user activity, not bragging about large trades on social platforms, opting for secure DeFi platforms, setting non-standard gas prices to make transactions less predictable, avoiding peak times, all of this and lastly educate yourself and stay informed on security updates.
Conclusion
Front-running attacks exploit the transparency and inefficiencies of blockchain networks to gain unfair advantages, often at significant financial costs. By understanding the various attack vectors—displacement, insertion, and suppression—and implementing robust mitigation strategies, both developers and users can better protect themselves from these threats.
BlockApex is at the forefront of security and innovation, we aim for the highest level of security by not only preventing front-running but all potential attacks. Our audit services can eliminate critical bugs, protect your assets, and most importantly keep pesky issues like Bob at bay. Reach out to us today.