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

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

10 minutes

By Saylık SeherandMalanii Oleh

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.

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 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.

Three Ways Front-Running Attacks Work


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

  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 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);
            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

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.

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: When 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)


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.

to our newsletter

Be the first to receive our latest company updates, Web3 security insights, and exclusive content curated for the blockchain enthusiast.в

Speaker Img

Table of contents

  • What Is Front-Running?
  • Three Ways Front-Running Attacks Work
  • Front-Running In Hacken Experience
  • Front-Running Triggers

Tell us about your project

Follow Us

Read next:

More related
  • Blog image
    What is DePIN? Exploring Decentralized Physical Infrastructure Networks

    7 min read


  • Blog image
  • Blog image
More related →

Trusted Web3 Security Partner