// inside head tag

Frontrunning in Web3 and Understanding MEV

Security

April 30, 2026

Intro

Imagine a trader who spots a good trading opportunity in the market. They sign the transaction, hit confirm, and wait. But when the transaction settles, they notice that they bought the token at a higher price than expected. When trading on a DEX, this isn’t something unusual; they might’ve been the target of an MEV bot.

The public nature of blockchain transactions presents some challenges. While transparency ensures trustworthiness, it also exposes a user's intent before their action is finalized. The time gap between signing a transaction and its inclusion in a block is where frontrunning can occur.

As smart contract security researchers, we see the impact of frontrunning firsthand, particularly within Automated Market Makers (AMMs). Frontrunning other users’ trades is a sophisticated economic operation that drains millions from users and protocols annually.

Frontrunning Explained: The Mempool

To understand the meaning of frontrunning, one must first understand the mempool. When a transaction is sent to the network (for example, a swap transaction on a DEX like Uniswap), the transaction doesn't execute instantly. It enters a “waiting area” called the mempool, where it sits until it is picked up by validator nodes to be confirmed.

Validators select transactions from this pool to build the next block. Validators are financially incentivized to prioritize transactions that pay the highest gas fees.

What Is Frontrunning?

It is the act of spotting a pending transaction in the mempool (i.e., a token swap transaction) and submitting your own transaction with a higher gas fee to ensure it gets processed before the original transaction.

Because the transaction data is visible, sophisticated bots can simulate the trade against the current state of the AMM. If they detect a profit opportunity, they copy the logic, pay a higher “bribe” (gas fee), and get their transactions processed before the original one.

Maximal Extractable Value (MEV) In Crypto

Frontrunning is just one facet of a larger phenomenon known as MEV. Originally, this acronym stood for Miners Extractable Value, referring to the profit miners could extract by processing blockchain transactions.

MEV in crypto has become an industrial-scale operation involving "Searchers" (who run bots) and "Builders" (who bundle transactions). While some MEV is benign, "toxic" MEV, like sandwich attacks, directly harms users.

The Attack Vector: Sandwich Attacks And Slippage

The most notorious form of frontrunning in AMMs is the sandwich attack. This occurs when an MEV bot detects a large swap order pending in the mempool.

In an AMM relying on the constant product formula where x * y = k, a large buy order inevitably pushes the price up. To demonstrate how the attack unfolds, let’s look at some vulnerable code.

AMM Vulnerability Code Example

Frontrunning often exploits poorly constructed slippage checks. Consider this naive swap function that ignores minimum output amounts:

// VULNERABLE CODE EXAMPLE
function naiveSwap(address tokenIn, uint256 amountIn) external {
// assume some checks take place here before the actual swap
    
    // Interaction with the AMM
    IERC20(tokenIn).transferFrom(msg.sender, address(this), amountIn);
    // No minimum amount out specified -> no slippage protection
    AMM.swap(tokenIn, amountIn, 0); 
}

In the code above, the 0 in the swap function represents 100% slippage tolerance. A frontrunning bot sees this and knows they can manipulate the price before this transaction executes, and the trade will still succeed, forcing the victim to swap at a very unfavorable price.

A "Sandwich Attack" Explained

Imagine that Alice calls the naiveSwap function above to swap 10,000 USDC for ETH.

  • Current market price: 1 ETH = 2,000 USDC.
  • Alice’s expectation: she expects to receive approximately 5 ETH.

Figure 1: A sandwich attack executes in three ordered transactions. The bot's frontrun inflates the price; the victim's transaction settles at that inflated price with no slippage floor; the backrun returns the bot to profit.

Here is how the attack unfolds in the mempool:

  1. The setup (frontrun): A bot spots Alice’s transaction. Before her trade executes, the bot pays a higher gas fee to buy a massive amount of ETH from the pool. The bot’s purchase drains the pool's ETH supply, temporarily creating an imbalanced exchange ratio so the new price of 1 ETH = 10,000 USDC.
  2. The victim’s execution: Alice’s naiveSwap transaction executes next.
    • Input: 10,000 USDC.
    • The problem: Because the minimum amount out is set to 0, the contract accepts any price as being valid.
    • Execution: She buys ETH at the new inflated price of 10,000 USDC/ETH.
    • Alice receives: 1 ETH (instead of the 5 ETH she expected).
  3. The payoff (backrun): Immediately after Alice buys (pushing the price even higher), the bot sells all their ETH back to the pool.
    • Bot profit: The bot effectively sold its ETH to Alice at a 400% markup.
    • Alice’s loss: Alice lost 80% of her value ($8,000 worth of ETH) because the naiveSwap function lacked a slippage check.

Fixing The Vulnerability: Enforcing Slippage

To prevent this, smart contracts must enforce strict slippage parameters.

// SECURE CODE EXAMPLE
function secureSwap(
    address tokenIn, 
    uint256 amountIn, 
    uint256 minAmountOut, // Slippage protection
) external {
// assume some checks take place here before the actual swap
    IERC20(tokenIn).transferFrom(msg.sender, address(this), amountIn);
    
    // The transaction will REVERT if the frontrunner pushes 
    // the return amount below minAmountOut
    uint256 actualAmountOut = AMM.swap(tokenIn, amountIn, minAmountOut);
    require(actualAmountOut >= minAmountOut, "Insufficient output amount");
}

By adding a minAmountOut parameter and enforcing that actualAmountOut >= minAmountOut, the user defines the "worst" price they are willing to accept. If a sandwich bot tries to frontrun this transaction to alter the price, the require statement at the end will cause the victim's transaction to revert, protecting their capital. The attacker's strategy fails, and the MEV bot wastes money on gas.

Advanced MEV: Backrunning and Just In Time Liquidity

Not all MEV strategies involve frontrunning. Some happen immediately after.

Backrunning is the practice of submitting a transaction designed to be executed immediately after a target transaction. A common example is arbitrage.

  • Scenario: A user makes a big trade on Uniswap that changes the price of the ETH/USDC pair.
  • The backrun: A bot sees this and immediately buys ETH on Uniswap and sells it on Sushiswap to rebalance the price. This is generally considered "benign" MEV as it makes markets more efficient.

Just In Time (JIT) Liquidity

A more sophisticated form of MEV in concentrated liquidity AMMs (like Uniswap V3) is Just In Time Liquidity.

  1. An LP bot spots a large trade pending in the mempool.
  2. They frontrun the trade by adding massive liquidity concentrated exactly within the price range where the trade is about to be executed (Uniswap’s upper and lower ticks).
  3. The bot earns most of the trading fees from that large swap.
  4. The bot immediately backruns the swap transaction to remove the liquidity.

While JIT liquidity actually gives traders better execution prices (less price impact due to deeper liquidity), it discourages passive liquidity providers (LPs) by stealing their yield since most of the fees from that particular swap will go to the MEV bot instead of going to long-term LP position holders.

JIT Liquidity: A Numerical Example

Let's imagine a USDC/ETH pool with a 0.3% swap fee.

The pre-existing state:

  • LP provider 1 (Bob): Has provided $50,000 worth of liquidity in the active price range.
  • LP provider 2 (Charlie): Has provided $50,000 worth of liquidity in the same active range.
  • Total active liquidity: $100,000.

If a trade happens now, Bob and Charlie would split the swap fees 50/50 because they each own 50% of the active liquidity.

Figure 2: A JIT bot deposits $9.9M in liquidity immediately before a $1M swap executes, capturing 99% of the $3,000 fee generated. Bob and Charlie, each with $50,000 in the pool, receive $15 each rather than the $1,500 they would have earned without the intervention.

The main transaction:

  1. A user submits a transaction to swap $1,000,000 worth of USDC for ETH.
    • Total Fee Generated: $1,000,000 * 0.3% = $3,000
  2. An MEV bot spots the trade.
  3. Alice's MEV bot spots this $1M trade in the mempool. It executes a JIT liquidity strategy.
    • Frontrun the main transaction to add liquidity in the active liquidity range:Alice adds $9,900,000 (9.9 million) of liquidity into the exact tick range where the swap will occur, right before the swap executes.
      • New total liquidity: $100,000 (Bob + Charlie) + $9,900,000 (Alice) = $10,000,000.
      • Alice's share: Alice now owns 99% of the active liquidity in the pool. Bob and Charlie's share has been diluted to just 1% combined.
    • The main transaction executes:
      • The user's $1M trade executes against this new $10M tick range.
      • The fee of $3,000 is distributed pro rata based on liquidity ownership at that exact moment.
    • Fee distribution:
      • Alice (MEV Bot): Takes 99% of the fees -> $2,970.
      • Bob & Charlie (passive LPs): share the remaining 1% -> $30 total ($15 each).
    • Backrun the main transaction to remove the liquidity from the active liquidity range:
      • Alice immediately withdraws her $9.9M liquidity plus her $2,970 in fees.
The end result?

Without Alice, Bob and Charlie would have split the $3,000 fee. Because of the JIT liquidity “attack”, they only earned $15 each. Alice got 99% of the fee from that swap, impacting the yield of the other liquidity providers.

Conclusion

As long as validators choose which transactions to include and in what order, MEV exists. The spectrum runs from benign to damaging: arbitrage bots rebalance prices across markets, JIT liquidity improves execution for traders even while it erodes passive LP yields, and sandwich attacks simply take money from users who left the door open. What separates these outcomes is not the MEV infrastructure itself, but whether the smart contracts being targeted gave attackers anything to exploit.

The mempool is public, and every pending transaction is a statement of intent readable by anyone running a bot. That asymmetry does not go away, but what developers can control is how much that visibility costs their users. A single minAmountOut check is the difference between a trade that reverts safely and one that hands 80% of a user's value to a bot. Assume every transaction is being watched and build accordingly.

Need a smart contract code security review? Contact our security team today for a comprehensive audit.