In traditional finance, front-running, a practice where brokers leverage early access to clients’ trade orders to their advantage, has undermined the trustworthiness of stock markets for decades. On Wall Street, front running is illegal under SEC Rule 17(j)-1.
The practice has also made its way into DeFi. It works differently, but the logic is the same: exploit a genuine transaction to your advantage. The scale of front-running in crypto is massive.
Since June 2020, MEV bots have made at least $1 billion in profits across Ethereum, BSC, and Solana, usually at the expense of retail investors. In addition to funds safety, front-running also raises the issues of market fairness and transparency.
Yet, the seemingly unethical practice can also be used for a good cause. For example, white hat hackers front-run malicious transactions to recover assets stolen by hackers, but more on that later.
In traditional markets, front-running involves a broker who, knowing a client’s major order is about to be placed, quickly makes their own trade, benefiting from the anticipated price movement.
In the context of crypto, front-running attacks take on a more sophisticated form. With knowledge of the transaction queue (or the “mempool”), validators who run software to approve transactions on the network can reorder, include, or omit transactions in ways that benefit them financially.
For example, if a miner notices a large buy order for a particular cryptocurrency token, they might insert their own buy order first, then validate the larger buy order, and subsequently net an arbitrage.
Front-running in cryptocurrency goes deeper than it first appears. In addition to validators who get the highest share of front-running gains, there is also a vast network of Maximum Extractable Value (MEV) traders operating bots to profit from blockchain’s complicated nature.
According to Ryan Zurrer, around 50 teams are actively involved in MEV, with roughly 10 dominating the scene. The best teams earn monthly profits in the “high five to mid-six figures” range and have made millions in optimal market conditions.
In a public blockchain, transaction data is accessible to all. And since there are no SEC cybersecurity rules for them, most front-running activity happens on DEXs. Hence, the DeFi world is full of smart traders who operate MEV front-running bots scavenging the on-chain landscape for prey.
In this type of attack, the perpetrator uses a higher gas price to guarantee their transaction is processed before the impending transactions. Here, outbidding ensures priority processing.
In this method, attackers use the sheer volume of transactions to their advantage. They create a barrage of transactions, all with significantly higher gas prices, known as a “suppression cluster”. The result? The victim’s transaction struggles to find space in the same block due to the overwhelming number of high-priority transactions.
The insertion tactic is more complex and is reminiscent of a sandwich attack – front-running and back-running a transaction. Here, the attacker places the victim’s TX in the so-called sandwich. The first has a higher gas price, and the second a lower one. This attack is particularly prevalent in decentralized exchanges, allowing attackers to take advantage of large-scale trades, often referred to as “whale transactions”, thus enabling them to derive substantial profits.
Sandwich Attack Example
In this section, we present smart contract vulnerabilities that could enable front-running attacks. All issues have been resolved during the Hacken Smart Contract Audit.
Catgirl is an NFT Marketplace that allows users to list, buy, sell, and cancel orders.
The function below allows users to swap their Catgirl NFTs via BNB tokens and is currently exposed to potential front-running manipulations due to the absence of a minimum output value enforcement mechanism during the swap operation. When a significantly large swap transaction occurs, malicious users may step in with a higher gas fee to preempt the transaction, causing the buyer to purchase at a much higher price
This vulnerability makes it susceptible to front-running tactics whenever the function is executed, as it lacks proper slippage checks.
function swapBNBForCatgirl(uint256 amount) private {
address[] memory path = new address[](2);
path[0] = pancakeRouter.WETH();
path[1] = address(uCatgirlToken);
pancakeRouter.swapExactETHForTokensSupportingFeeOnTransferTokens{
value: amount
}(0, path, address(this), block.timestamp);
}
Fortunately, they resolved the issue and introduced a slippage check. The swap function is currently safeguarded regarding front-running attacks.
Diverse Solutions operates as a staking pool utilizing a modified Automated Market Maker (AMM) mechanism. The exchange rate between ARDM and XARDM is determined by the ratio of the total supply of XARDM to the total amount of ARDM held within the exchange contract.
In their first audit review, on 24 April 2023, Hacken audit team detected a front-running vulnerability in their code. The heart of the problem lies within the deposit()
function, where a seemingly innocent equation governs the minting of shares. Here, we have two main functions: deposit()
function is to swap your ARDM tokens to xARDM tokens, and the withdraw()
function is to swap your xARDM tokens to ARDM tokens.
function deposit(uint256 _amount) external nonReentrant onlyEOA whenDepositNotPaused {
require(_amount > 0, "AMOUNT ZERO");
uint256 totalARDM = ARDM.balanceOf(address(this);
uint256 totalxARDM = xARDM.totalSupply();
if (totalxARDM == 0 || totalARDM == 0) {
xARDM.mint(msg.sender, _amount);
emit Deposit(msg.sender, _amount, _amount);
} else {
// This equation calculates the number of shares a user should receive based on their deposited amount and the total assets and total shares in the vault. However, beneath the surface, a critical flaw exists. This flaw allows malicious actors to manipulate the denominator, leading to outcomes that can be detrimental to other users.
uint256 mintAmount = (_amount * totalxARDM) / totalARDM;
xARDM.mint(msg.sender, mintAmount);
emit Deposit(msg.sender, _amount, mintAmount);
}
ARDM.transferFrom(msg.sender, address(this), _amount);
if (penaltyFeePaused == false) {
_userDeadline[msg.sender] = block.timestamp;
}
}
function withdraw(uint256 _amount) external nonReentrant onlyEOA whenWithdrawNotPaused {
require(_amount > 0, "AMOUNT ZERO");
uint256 totalARDM = ARDM.balanceOf(address(this));
uint256 totalxARDM = xARDM.totalSupply();
uint256 transferAmount = (_amount * totalARDM) / totalxARDM;
if (
penaltyFeePaused == false &&
_userDeadline[msg.sender] + penaltyDeadline > block.timestamp
) {
uint256 fee = (transferAmount * penaltyFee) / 100000000000000000000;
uint256 transferAmountMinusFee = transferAmount - fee;
xARDM.burnFrom(msg.sender, _amount);
ARDM.transfer(msg.sender, transferAmountMinusFee);
ARDM.transfer(treasuryAddress, fee);
emit PenaltyFeeSent(treasuryAddress, fee);
} else {
xARDM.burnFrom(msg.sender, _amount);
ARDM.transfer(msg.sender, transferAmount);
}
emit Withdraw(msg.sender, transferAmount, _amount);
}
The attack scenario explained in the report is as follows:
Initially, an attacker initiates the staking pool by making the first deposit and mints a small fraction of share (XARDM), equivalent to one wei. This operation is represented as deposit(1)
, and it results in a state where the pool’s total assets are 1 ARDM, and the total supply of XARDM is also 1.
The attacker, with malicious intent, anticipates another user’s deposit action and decides to front-run their transaction. The victim intends to deposit a substantial amount, specifically 20,000 ARDM, into the pool.
To manipulate the situation in their favor, the attacker swiftly inflates the denominator of the share calculation just as the victim initiates their deposit. The attacker executes the command “ardm.transfer(20,000e18),” which transfers a large quantity of ARDM to the pool. Consequently, the total assets of the pool increase significantly to 20,000e18 ARDM, while the total supply of XARDM remains at 1.
Due to the rapid inflation of the pool’s assets, when the victim’s deposit transaction is eventually processed, they receive a minimal share of XARDM. This calculation is performed as follows: (1 * 20,000e18) / (20,000e18 + 1)
, which results in almost zero shares of XARDM for the victim.
Ultimately, the attacker capitalizes on the situation by burning their share of XARDM. This action effectively grants them ownership of all the ARDM in the pool, leaving the victim with no shares and no stake in the pool’s assets.
In this scenario, the attacker exploits the timing of transactions and the calculation of shares to manipulate the pool’s state and deprive the victim of their intended stake in the pool, ultimately gaining control over all the deposited ARDM.
Resolution of the issue
The customer has successfully resolved the front-running issue and obtained a sufficient score from the audit.
In the comparison above, significant changes have been illustrated. The function now exclusively considers the ARDM amount transferred via the deposit()
function rather than the total ARDM balance of the contract. The client has taken measures to prevent external transfers of ARDM tokens, as they were impacting the price ratio of ARDM/xARDM and mitigated associated risks.
As the DeFi ecosystem continues to mature, so does the creativity of those trying to exploit it.
Protection against front-running attacks requires measures from both the platforms that host transactions and the individual users who conduct them. Let’s delve into strategies for each:
In a unique crypto incident, a hacker executed a $69M liquidity pool hack of Curve Finance, but 70% of lost funds were returned thanks to front-running. The theft was partially foiled by MEV bots operated by white hat hackers, including Coffeebabe. Successfully intercepting the hacker’s transaction, coffeebabe.eth returned the rescued funds to Curve.
This event underscores the potential of MEV bots and the white-hat community in counteracting malicious activities, with this intervention recovering 70% of the lost assets. Such dynamics exemplify the importance of crowdsourced solutions for DeFi security.
Follow @hackenclub on 𝕏 (Twitter)
In the crypto realm, front-running is an operation where validators and MEV bots manipulate genuine transactions for financial gain through displacement, suppression, or insertion.
As the tactics of front-runners evolve, so must the strategies to address them.
DeFi platforms are responsible for implementing minimal slippage rates, commit-reveal schemes, batch transactions, smart contract audits, rate limiting, priority gas auctions, off-chain order relays, randomized transaction ordering, time-lock contracts, and sliding windows.
Users can protect their assets from front-running risks by protecting their privacy, using Layer 2 solutions, sending non-standard gas prices, performing transactions during off-peak periods, choosing secure DEXs, and, most importantly, staying informed.
Be the first to receive our latest company updates, Web3 security insights, and exclusive content curated for the blockchain enthusiasts.
Table of contents
Tell us about your project
14 min read
Discover
10 min read
Discover
13 min read
Discover