By Saylık SeherandMalanii Oleh
In traditional finance, front-running, a practice where brokers exploit advance knowledge of clients’ orders, has plagued the integrity 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 crypto goes deeper than you think. 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. Front-running bots are smart contracts programmed to scan and capitalize on impending transactions, e.g., by altering the order for pending transactions in the mempool.
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.
Parallax is a platform that enables various compounding strategies. The strategy CurveSorbetteriesStrategy, allows users to deposit funds into the USDC-USDT-MIM liquidity pool on Curve and automatically compound the rewards. When a user initiates a position, they receive an ERC721 token, which is subsequently burned upon a complete withdrawal.
In contrast to the initial example, their swapping system included a check for the minimum swap amount, but it relied on off-chain data and could be manipulated. This vulnerability opens the door to potential front-running attacks on SPELL – MIM swaps, which can even be executed in a single transaction without the need to monitor the mempool. An attacker could initiate such an attack by directly calling the compound function.
function compound(
uint256[] memory amountsOutMin
) public onlyParallax returns (uint256) {
// Harvest SPELL tokens and swap to MIM tokens
uint256 receivedMim = _harvest(amountsOutMin[0]);
if (receivedMim != 0) {
// Swap one third of MIM tokens for USDC and another third for USDT
(
uint256 receivedUsdc,
uint256 receivedUsdt,
uint256 remainingMim
) = _swapThirdOfMimToUsdcAndThirdToUsdt(
receivedMim,
amountsOutMin[1],
amountsOutMin[2]
);
// Reinvest swapped tokens (earned rewards)
return
_deposit(
DepositParams({
usdcAmount: receivedUsdc,
usdtAmount: receivedUsdt,
mimAmount: remainingMim,
usdcUsdtLPsAmountOutMin: amountsOutMin[3],
mimUsdcUsdtLPsAmountOutMin: amountsOutMin[4]
})
);
}
return 0;
}
function _harvest(
uint256 swapMimAmountOutMin
) private returns (uint256 receivedMim) {
// Harvest rewards from the Sorbettiere (in SPELL tokens)
_sorbettiereDeposit(0);
uint256 spellBalance = IERC20Upgradeable(SPELL).balanceOf(
address(this)
);
// Swap Sorbettiere rewards (SPELL tokens) for MIM tokens
if (spellBalance >= compoundMinAmount) {
receivedMim = _swapTokensForTokens(
SPELL,
spellBalance,
swapMimAmountOutMin,
_toDynamicArray([SPELL, MIM])
);
}
}
After the remediations, they fixed the issue and ensured that the swap operations were protected from front-running attacks.
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 rate, 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 proxy contracts, sending non-standard gas prices, performing transactions during off-peak periods, and choosing secure DEXs.
Subscribe to our newsletter
Enter your email address to subscribe to Hacken Reseach and receive notifications of new posts by email.