• Hacken
  • Blog
  • Discover
  • Front-Running In Blockchain: Real-Life Examples & Prevention

Front-Running In Blockchain: Real-Life Examples & Prevention

By Saylık SeherandMalanii Oleh

Share via:

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.

What Is Front-Running?

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.

The Big Problem Of MEV Bots

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.

Three Ways Front-Running Attacks Work

Displacement

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. 

Suppression

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.

Insertion

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

  1. An unsuspecting big investor places an order to buy 1000 ETH at the current market rate of $1,620.
  2. MEV bot spots this substantial transaction in the public transaction pool. Acting swiftly, the bot moves first, snapping up ETH at $1,620.
  3. Due to immediate market effects, the trader’s purchase is executed at an elevated price, landing at $1,625.
  4. Capitalizing on this brief surge, the bot promptly offloads its 500 ETH.
  5. This play guarantees the bot a quick gain of $5 for each ETH, resulting in a total profit of $5,000.

Front-Running In Hacken Experience

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

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

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.

Front-Running Triggers

  • Pending transactions in mempool: The mempool, a sort of “waiting room” for transactions, is a goldmine of information. Attackers can spot potentially profitable transactions here before they are confirmed.
  • Large orders: Big trades or “whale” activities can cause significant market movement. Front-runners watch out for these as they can be easily exploited for sizable gains.
  • API and oracle updates: APIs and oracles feed external data to smart contracts. Changes or updates here can influence contract outcomes and become a potential target for front-running.
  • Liquidity pool changes: When liquidity is added or removed from a DeFi pool, it can lead to substantial price changes, making it a tempting target for front-runners.
  • Token listings: The moment a new token is listed on a decentralized exchange, there’s often a rush to buy, presenting ample opportunities for front-running.
  • Governance proposals: Major governance decisions or proposals can impact token values, especially if they relate to protocol changes, fee structures, or partnerships.
  • Migratory activities: These can be front-running hotspots when funds migrate from one protocol to another, especially during protocol upgrades or yield farming shifts.
  • Arbitrage opportunities: Price discrepancies between different exchanges or tokens can be exploited by attackers who front-run these arbitrage trades.
  • Flash loans: These are uncollateralized loan operations that happen within a single transaction. The initiation or presence of a flash loan can be a signal for potential price manipulation and front-running.
  • Order book analysis: On some decentralized exchanges, observing the orderbook can provide insights into impending trades, making it a goldmine for front-runners.
  • Vault or Strategy Changes in Yield Protocols: When a DeFi protocol announces a new yield strategy or vault changes, users may rush to deposit funds, creating front-running opportunities.

As the DeFi ecosystem continues to mature, so does the creativity of those trying to exploit it. 

How To Prevent Front-Running Attack?

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:

For Platforms:

  • Minimal Slippage Rate:  To protect DeFi applications that allow swapping, a slippage restriction should be implemented, and the slippage percentage (%) should be set to be between 0.1% and 5%, depending on the network fee and swap size, designed to give you the best swap outcome. This deliberate effort to minimize slippage serves as a robust defense against opportunistic front-runners who thrive on exploiting higher slippage rates. By adhering to this strategy, you can help safeguard your trading activities and reduce the risks associated with predatory trading practices.
  • Implement Commit-Reveal Schemes: This involves a two-step process where users first commit to a specific action without revealing the details and then later disclose the exact information. This makes it more challenging for attackers to determine and anticipate user actions.
  • Batch Transactions: By bundling several transactions together and processing them as one unit, it becomes more difficult for attackers to single out and exploit individual trades.
  • Monitor for Bots: Continual surveillance for automated bots and scripts that might be looking to exploit front-running opportunities can help in early detection and mitigation.
  • Smart Contract Audit: Regular audits by reputable firms can identify vulnerabilities in smart contracts that might be prone to front-running or other malicious activities.
  • Rate Limiting: Implementing restrictions on the frequency of transactions from a single address can deter front-runners who often operate by flooding the network with rapid, successive transactions.
  • Priority Gas Auctions (PGA): This is a mechanism where users bid not on the transaction fee (or gas), but on their transaction’s priority. This can help in restructuring the incentive and making front-running more expensive and thus less viable for attackers.
  • Off-Chain Order Relays: Use off-chain systems to match trades and then batch and execute them on-chain. This way, the exact details remain hidden until the last moment, reducing the window of opportunity for front-runners.
  • Randomized Transaction Ordering: Randomly ordering transactions within a block can make it challenging for front-runners to predict their placement, thus reducing their edge.
  • Time-Lock Contracts: By setting specific time constraints on transactions, platforms can prevent sudden and opportunistic trades, making front-running harder.
  • Implement Sliding Windows: Rather than executing orders immediately, a platform could use a sliding window mechanism, where orders are collected and executed in batches, making it difficult to pinpoint any single transaction.

For Users:

  • Privacy Transactions: Leveraging privacy tools or platforms that offer shielded or confidential transactions can help mask user activity, making front-running more challenging.
  • Don’t Brag About Large Trades: Publicizing a significant trade, especially on social platforms, can attract front-runners. It’s always best to keep trading intentions discreet.
  • Stay Updated: Regularly updating oneself on the latest security measures, patches, or platform changes can help users be one step ahead of potential front-runners.
  • Use Platforms with Front-Running Protections: Opt for exchanges or DeFi platforms that have inbuilt measures to prevent front-running or prioritize user security.
  • Proxy Contracts: Use intermediary contracts that can obscure the original intent of the transaction until it’s executed. This adds a layer of complexity and unpredictability.
  • Setting Non-Standard Gas Prices: By avoiding rounded numbers and common gas price patterns, users can make their transactions less predictable and thus less prone to front-running.
  • Avoiding Peak Transaction Times: Performing transactions during off-peak times can reduce the chances of being targeted, as front-runners are more active during high-activity periods.
  • Educate and Collaborate: Engage with communities, forums, and platforms to stay updated on the latest front-running techniques and the measures to counteract them.
  • Use Layer 2 Solutions: Many Layer 2 scaling solutions, like rollups or state channels, can help reduce the front-running risk by processing transactions off the main chain, where they’re less visible and thus less susceptible.
  • Beware Of Front-Running Bot Scams: There’s been a surge in a particular crypto scam cropping up on YouTube and social media. At the core of this scam is a tantalizing offer: a Solidity bot that claims to leverage the front-running technique, promising daily returns in the hundreds. In reality, scammers get access to your wallets.

Front-Running Used For Good

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)

Wrap-Up

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 image
promotion image
IMPORTANT

Subscribe to our newsletter

Enter your email address to subscribe to Hacken Reseach and receive notifications of new posts by email.

Read next:

More related
  • Blog image
    DISCOVER
    Telegram Crypto Trading Bots: Convenience vs. Security Risks Hacken
  • Blog image
  • Blog image
    DISCOVER
    Fintoch Rug Pull Explained Hacker H.
  • Blog image
  • Blog image
  • Blog image
  • Blog image
  • Blog image
  • Blog image
  • Blog image
    DISCOVER
    51% Attack: The Concept, Risks & Prevention HackenBarwikowski B.

Get our latest updates and expert insights on Web3 security