Frontrunning & Sandwich Attacks

Smart Contract Vulnerability Deep Dive

JohnnyTime
JohnnyTime · Updated June 24, 2026
26 min read
Total Stolen $12,429,900
Last Attack Dec 28, 2025
Latest Victim MSCST

Summarize with AI

Frontrunning & Sandwich Attacks: Complete Guide to Detection and Prevention

Frontrunning attacks exploit the transparent nature of blockchain mempools to steal value from unsuspecting users. Imagine playing a game of poker where everyone can see your cards before you even place a bet. That’s essentially what happens on public blockchains every second of every day. With over $1.2 billion extracted through MEV (Maximal Extractable Value) and frontrunning on Ethereum alone, and sandwich attacks accounting for 51% of all MEV volume in 2025, this is one of the most profitable - and persistent - threats in DeFi.

Whether you're a smart contract auditor looking to secure protocols or a Web3 developer building the next big DEX, understanding how these predatory bots operate is non-negotiable.

This comprehensive guide covers everything from basic mempool sniping to the sophisticated sandwich attacks that systematically drain millions from DEX traders every single month. Let's dive into the dark forest of the mempool.


What Is a Frontrunning Attack?

A frontrunning attack occurs when a malicious actor (usually an automated bot) monitors the blockchain's public pending transaction pool (the mempool). When it spots a profitable transaction waiting to be processed, the bot submits its own identical or counter-transaction with a significantly higher gas fee. This bribes the network validators to execute the attacker's transaction before the victim's.

By exploiting this advance knowledge of a transaction that will change the blockchain's state, the attacker steals the opportunity. This usually means buying an asset right before a large purchase pushes its price up, or sniping a lucrative protocol reward before the legitimate user can claim it.

The Stock Market Analogy

Imagine a shady stockbroker who receives a client's order to buy 1 million shares of a tech company. The broker knows this massive buy order will instantly drive the stock price up. Before executing the client's order, the broker secretly buys a chunk of shares for themselves at the current low price. The client’s massive order goes through, pumping the price, and the broker immediately dumps their shares at the inflated price for a risk-free profit.

That's frontrunning. It's highly illegal and heavily penalized in traditional finance (TradFi). But on a public blockchain? Every pending transaction is visible to anyone running a node, and there's no SEC regulator to stop it from happening. It’s strictly a battle of code and gas fees.

The Mempool (Memory Pool): On Ethereum, the mempool is essentially a waiting room that holds all unconfirmed transactions in plain sight. Specialized MEV bots monitor this pool 24/7, relentlessly scanning for profitable opportunities to exploit in milliseconds.


Why Frontrunning Attacks Are So Dangerous

Frontrunning and MEV extraction have caused staggering cumulative losses across DeFi:

$0M+
Cumulative MEV Extracted
$0M
Sandwich Attacks (2025)
2020–2025
Active Threat Period
Attack Year Impact
MIT Brothers MEV Exploit 2023 $25M stolen in 12 seconds
jaredfromsubway.eth Bot 2023–2024 $22M+ profit from sandwich attacks
Rogue Validator Attack 2023 $25M stolen from MEV bots
Bancor Frontrunning 2020 $135K stolen during rescue operation

Frontrunning is one of the OWASP Smart Contract Top 10 vulnerabilities and accounts for over half of all MEV extraction on Ethereum.

Types of Frontrunning

1
Displacement
"Attacker copies and replaces the victim's transaction entirely, claiming the reward first"
Complexity: Low | Classic reward sniping
2
Insertion (Sandwich)
"Attacker places two transactions around the victim - buying before and selling after"
Complexity: Medium | DEX trade exploitation
3
Suppression
"Attacker floods the network with high-gas transactions to delay the victim's transaction"
Complexity: High | Block stuffing attack

Real-World Frontrunning Exploits

The MIT Brothers: $25 Million in 12 Seconds (April 2023)

In what became the first U.S. criminal prosecution of blockchain frontrunning, two MIT-educated brothers - Anton (24) and James (28) Peraire-Bueno - exploited a vulnerability in MEV-boost relay software.

How they did it:

  1. Deployed "bait transactions" to lure MEV sandwich bots

  2. Exploited a flaw in MEV-boost that let their validator reorder transactions within a block

  3. Stole $25 million in just 12 seconds by intercepting the sandwich bots' own strategy

  4. Used shell companies and concealed identities to launder the proceeds

The brothers were charged with wire fraud and conspiracy, each facing up to 20 years in prison. This case proved that MEV exploitation can cross the line from "gray area" into criminal activity.

jaredfromsubway.eth: The Most Notorious MEV Bot (2023–2024)

The most famous sandwich bot in Ethereum history, jaredfromsubway.eth earned over $22 million in profit since March 2023.

At its peak during the PEPE/WOJAK meme coin frenzy, this single bot consumed 7% of all Ethereum gas in a 24-hour period. In one week alone after April 17, 2023, it netted $2.7 million.

In 2024, the operator returned with "Jared 2.0" - an upgraded bot targeting Ethena (ENA) traders.

A single sandwich attack in January 2025 generated over $800,000 in profit - demonstrating the massive scale of MEV extraction.

The Bancor Rescue Race (June 2020)

When the 1inch Exchange team discovered a critical vulnerability in Bancor's smart contracts, a frontrunning race ensued:

Actor Action Result
Bancor Team Began rescuing funds at 03:06 AM UTC via 62 transactions Saved $409,656
Frontrunner Bot Detected the rescue, copied transactions within 3 minutes Stole $131,889
Second Bot Joined at 03:09 AM UTC Grabbed $3,340

Total damage: $545,423 in user funds drained - including $135,229 stolen by automated frontrunning bots that simply copied Bancor's own rescue transactions.

The "Salmonella" Counter-Attack (March 2021)

In a creative reversal, developer Nathan Worsley deployed a poisoned ERC20 token called "Salmonella" that appeared normal but secretly returned only 10% of expected tokens to anyone other than the owner.

He created bait transactions with low fees and high slippage to lure sandwich bots. Ethermine's frontrunning bots fell into the trap, losing 103 ETH (~$250,000). It was a rare case of a victim turning the tables on frontrunners.


Want to execute frontrunning attacks yourself in a safe lab? The Smart Contract Hacking course includes hands-on MEV and frontrunning exercises where you'll exploit vulnerable contracts - exactly like real security researchers do.


How Frontrunning Attacks Work: Step-by-Step

Understanding the mempool and transaction ordering is crucial. Here's how a basic displacement frontrunning attack unfolds.

The Mempool: A Transparent Waiting Room

When you submit a transaction on Ethereum, it doesn't execute immediately. Instead:

  1. Your transaction enters the public mempool - visible to anyone running a node

  2. It propagates to ~99% of network nodes within seconds via gossip protocol

  3. A block builder selects transactions to include in the next block

  4. Transactions with higher priority fees (tips) are included first

This 12-second window between submission and block inclusion is the attack surface.

The Attack Flow

Step What Happens Who Benefits
1 Victim submits transaction to mempool -
2 Attacker's bot detects the pending transaction Attacker
3 Attacker decodes calldata to understand the action Attacker
4 Attacker simulates the transaction for profitability Attacker
5 Attacker submits identical transaction with higher gas Attacker
6 Attacker's transaction executes first in the block Attacker
7 Victim's transaction reverts or executes at a loss Nobody
Front-running attack diagram - Same block, reordered by gas - the bot brackets the victim's swap
Same block, reordered by gas - the bot brackets the victim's swap

The Attack Phases

1
Tap to reveal
Mempool Monitoring

The attacker runs a full node or uses mempool monitoring services to scan every pending transaction in real-time. They decode the calldata to understand what function is being called and with what parameters.

2
Tap to reveal
Profitability Simulation

The bot simulates the victim's transaction locally to calculate the exact profit available. For sandwich attacks, it calculates the optimal front-run amount based on pool reserves and the victim's slippage tolerance.

3
Tap to reveal
Transaction Submission

The attacker submits their transaction with a strategically higher gas price (priority fee). Under EIP-1559, the effective tip - min(maxPriorityFee, maxFee - baseFee) - determines ordering priority within a block.

4
Tap to reveal
Profit Extraction

The attacker's transaction executes first. For displacement attacks, the attacker claims the reward. For sandwich attacks, the attacker sells the inflated tokens immediately after the victim's trade for a risk-free profit.

"If your transaction's outcome is visible in the mempool, someone will exploit it."
This is the fundamental problem. Any transaction where the profit is publicly observable before execution is a prime frontrunning target. Always design your contracts to hide or protect sensitive information.

Frontrunning Vulnerable Code Example

Let's examine the classic displacement frontrunning vulnerability - a contract that rewards whoever solves a digital puzzle first. It sounds fun, but on a public blockchain, it's a disaster waiting to happen.

🚨 Warning: This contract is intentionally vulnerable. Never use this pattern in production!

The Vulnerable Reward Contract

// VULNERABLE CONTRACT - DO NOT USE IN PRODUCTION
pragma solidity ^0.8.20;

contract VulnerableReward {
    bytes32 public constant targetHash =
        0x564ccaf7594d66b1eaaea24fe01f0585bf52ee70852af4eac0cc4b04711cd0e2;

    constructor() payable {}

    // VULNERABILITY: Solution is visible in the mempool before execution
    function solve(string memory solution) public {
        require(
            keccak256(abi.encodePacked(solution)) == targetHash,
            "Wrong answer"
        );

        // Winner takes the entire reward
        (bool sent, ) = msg.sender.call{value: 10 ether}("");
        require(sent, "Transfer failed");
    }
}

Why Is This Vulnerable?

The core issue here is transparency:

  1. Alice desperately works to find the solution, discovers it is "Ethereum", and calls solve("Ethereum").

  2. Her transaction enters the public mempool with the plaintext solution completely visible in the calldata.

  3. An attacker's bot instantly decodes the calldata and spots the string "Ethereum".

  4. The bot immediately submits its own solve("Ethereum") transaction with a 10x higher gas price.

  5. The miners/validators (greedy for the higher fee) execute the attacker's transaction first, handing them the 10 ETH reward.

  6. Alice's legitimate transaction finally executes but reverts, because the contract balance has already been drained.

The victim did everything right. They solved the puzzle and submitted the valid transaction. But the transparent nature of the mempool allowed a sniper bot to swoop in and steal their hard-earned reward.


The Sandwich Attack: Advanced Frontrunning Example

Sandwich attacks are the bread and butter (pun intended) of frontrunning on Decentralized Exchanges (DEXes). Here's exactly how they drain traders.

Vulnerable DEX Swap (No Slippage Protection)

// VULNERABLE CONTRACT - DO NOT USE IN PRODUCTION
pragma solidity ^0.8.20;

contract VulnerableSwap {
    uint256 public reserveA;
    uint256 public reserveB;

    // Constant product AMM: reserveA * reserveB = k
    function swapAforB(uint256 amountA) external returns (uint256 amountB) {
        uint256 amountInWithFee = amountA * 997; // 0.3% fee
        amountB = (amountInWithFee * reserveB) /
            (reserveA * 1000 + amountInWithFee);

        // VULNERABILITY: No minimum output check! (Slippage protection missing)
        // Attacker can manipulate reserves before this executes
        // Transfer tokens...
    }
}

The Sandwich Attack Flow

Step Transaction Effect on Price
1 Attacker buys Token B (front-run) Price of B artificially pumps
2 Victim swaps A for B at the inflated price Victim gets heavily short-changed
3 Attacker sells Token B (back-run) Attacker pockets the risk-free profit
{
  "title": "🥪 The sandwich: watch the bot bracket Alice's swap",
  "stage": { "width": 920, "height": 440 },
  "nodes": [
    { "id": "mempool", "label": "Public Mempool", "role": "pending txs are visible", "emoji": "📡", "x": 360, "y": 40, "color": "slate" },
    { "id": "victim", "label": "Alice (Victim)", "role": "swaps 40 ETH", "emoji": "🧑", "x": 60, "y": 300, "color": "cyan" },
    { "id": "pool", "label": "DEX Pool", "role": "1,000 ETH / 2,000,000 USDC", "emoji": "🏊", "x": 380, "y": 300, "color": "purple" },
    { "id": "attacker", "label": "Attacker Bot", "role": "front-run + back-run", "emoji": "🤖", "x": 720, "y": 300, "color": "red" }
  ],
  "links": [
    { "from": "victim", "to": "mempool" },
    { "from": "mempool", "to": "attacker" },
    { "from": "attacker", "to": "pool" },
    { "from": "victim", "to": "pool" }
  ],
  "nets": [
    { "id": "atk", "label": "Attacker Net" },
    { "id": "victim", "label": "Alice vs fair price" }
  ],
  "legend": [
    { "cls": "call", "label": "observe / call" },
    { "cls": "token", "label": "token swap" },
    { "cls": "sig", "label": "slippage guard" },
    { "cls": "fail", "label": "reverted / blocked" }
  ],
  "scenarios": {
    "Vulnerable (no slippage)": [
      { "note": "Alice broadcasts a swap: <b>40 ETH</b>, expecting ~78,431 USDC at the fair price. The transaction sits in the public mempool first.", "hi": ["victim","mempool"], "bal": { "victim": "40 ETH", "pool": "fair price", "attacker": "watching" }, "net": { "atk": "$0", "victim": "fair: 78,431" }, "chip": { "from": "victim", "to": "mempool", "label": "📢 swap 40 ETH", "cls": "call" } },
      { "note": "The bot spots the pending swap and copies it with <b>higher gas</b> so its own transactions mine first and last.", "hi": ["mempool","attacker"], "chip": { "from": "mempool", "to": "attacker", "label": "👀 sees pending tx", "cls": "call" } },
      { "note": "<b>Front-run:</b> the bot buys first - 18.59 ETH in - pushing ETH's price along the curve before Alice trades.", "tone": "bad", "hi": ["attacker","pool"], "bal": { "pool": "price skewed ↑" }, "net": { "atk": "-18.59 ETH" }, "chip": { "from": "attacker", "to": "pool", "label": "① buy 18.59 ETH", "cls": "token" } },
      { "note": "Alice's swap now fills on the worse price: 40 ETH for only <b>76,712 USDC</b> - she is short 1,719 USDC versus the fair quote.", "tone": "bad", "hi": ["victim","pool"], "bal": { "victim": "76,712 USDC" }, "net": { "victim": "-1,719 USDC" }, "chip": { "from": "victim", "to": "pool", "label": "② swap 40 ETH", "cls": "token" } },
      { "note": "<b>Back-run:</b> the bot immediately sells the USDC it just bought back into the pool, receiving 19.45 ETH.", "hi": ["attacker","pool"], "chip": { "from": "attacker", "to": "pool", "label": "③ sell back", "cls": "token" }, "net": { "atk": "+0.86 ETH" } },
      { "note": "The sandwich closes: the bot nets <b>~0.86 ETH</b> at zero market risk, and Alice silently ate the 1,719 USDC of slippage.", "tone": "bad", "hi": ["attacker","victim"], "bal": { "attacker": "+0.86 ETH", "victim": "lost 1,719 USDC" }, "net": { "atk": "+0.86 ETH", "victim": "-1,719 USDC" } }
    ],
    "Fixed (slippage protection)": [
      { "note": "Alice sends the same 40 ETH swap, but now with <b>minOut = 78,000 USDC</b> - a slippage guard that reverts if she would receive less.", "hi": ["victim","mempool"], "bal": { "victim": "40 ETH", "attacker": "watching" }, "chip": { "from": "victim", "to": "mempool", "label": "📢 swap + minOut", "cls": "sig" } },
      { "note": "The bot front-runs exactly as before, buying first to skew the price.", "hi": ["attacker","pool"], "chip": { "from": "attacker", "to": "pool", "label": "① front-run buy", "cls": "token" }, "net": { "atk": "-18.59 ETH" } },
      { "note": "Alice's swap would now return only 76,712 USDC - below her 78,000 minimum - so the swap <b>reverts</b>. She loses nothing but gas.", "tone": "ok", "hi": ["victim","pool"], "bal": { "victim": "40 ETH (kept)" }, "net": { "victim": "no loss" }, "chip": { "from": "victim", "to": "pool", "label": "② revert < minOut", "cls": "fail" } },
      { "note": "The bot is now stuck holding USDC it overpaid for, and unwinding only burns gas. With slippage limits, the sandwich stops being profitable.", "tone": "ok", "hi": ["attacker"], "bal": { "attacker": "stuck inventory" }, "net": { "atk": "≤ 0 (gas lost)" } }
    ]
  }
}

Real Sandwich Attack Example

Let's look at a Uniswap pool containing 1,000 ETH and 2,000,000 USDC.

The innocent scenario (no attack):

  • Alice swaps 40 ETH → receives an expected ~78,431 USDC.

The nightmare scenario (with sandwich attack):

  1. The attacker front-runs Alice: swaps 18.59 ETH → receives ~36,320 USDC (pumping the price of USDC).

  2. Alice's original swap executes: 40 ETH → receives only ~76,712 USDC (she lost 1,719 USDC!).

  3. The attacker back-runs Alice: sells the 36,320 USDC back to the pool → receives ~19.45 ETH.

  4. Attacker's net profit: ~0.86 ETH (≈1,719 USDC) for literally zero market risk.

In real-world testing, victims routinely lose dozens of tokens per trade while attacker bots rake in the difference. What's worse? These bots execute thousands of attacks every single day.

Front-running attack diagram - Why the sandwich victim overpays: the price-impact gap
Why the sandwich victim overpays: the price-impact gap

A Protocol-Level Vulnerable Pattern

This isn't just theory. Here is a pattern taken straight from real audit findings (like Sherlock and Code4Rena) demonstrating how protocols inadvertently enable sandwich attacks:

// VULNERABLE - From a real Sherlock audit finding (2024)
// Missing slippage protection on a Uniswap Router call
IUniswapRouterV2(SUSHI_ROUTER).swapExactTokensForTokens(
    toSwap,
    0,                    // 🚨 VULNERABLE: accepts ANY output amount!
    path,
    address(this),
    type(uint256).max     // 🚨 VULNERABLE: no deadline!
);

The two critical, fatal flaws here:

  • amountOutMin = 0 means the swap will passively accept any output amount - even just 1 wei!

  • deadline = type(uint256).max means the transaction never expires, allowing a malicious miner or bot to hold it and execute it at the most mathematically destructive moment.


Ready to write exploits like this yourself and learn how to defend against them? The Smart Contract Hacking course covers frontrunning, sandwich attacks, and MEV in-depth with hands-on, real-world scenarios. Learn directly from JohnnyTime (12+ years in cybersecurity) and Trust (#1 Code4rena warden).


How to Prevent Frontrunning Attacks

Preventing frontrunning requires a layered defense approach. You must combine smart contract design patterns, robust infrastructure solutions, and operational awareness.

Prevention Effectiveness Comparison

Effectiveness95/100

What it does: Splits the action into two transactions - first commit a hidden hash, then reveal the actual data. The hash includes msg.sender, preventing attackers from copying the reveal.

When to use: Puzzles, auctions, voting, any on-chain secret submission.

Limitation: Requires two transactions (higher gas cost) and a waiting period between commit and reveal phases.

Effectiveness90/100

What it does: Allows users to specify the minimum acceptable output for a swap. If price moves beyond tolerance, the transaction reverts - making the sandwich unprofitable.

When to use: Every DEX swap, liquidity provision, and token exchange function.

Limitation: Users must set appropriate slippage values. Too high (>5%) still allows extraction. Too low causes frequent reverts.

Effectiveness85/100

What it does: Bypasses the public mempool entirely. Transactions go directly to block builders via private channels, invisible to frontrunning bots.

When to use: Any high-value DeFi transaction. Flashbots Protect has served 2.1 million unique accounts and protected $43 billion in DEX volume.

Limitation: Relies on trusted infrastructure. Users must configure private RPC endpoints in their wallets. Not available on all chains.

Effectiveness80/100

What it does: Groups multiple trades into batches executed at a uniform clearing price. Since all orders in a batch get the same price, there's no ordering advantage to exploit.

When to use: DEX aggregation and high-value swaps where MEV protection is critical.

Limitation: Adds latency (batch settlement windows). Only works with protocols that support the batch auction model.


Frontrunning Secure Code Examples

Secure Pattern 1: Commit-Reveal for Reward Contracts

// SECURE CONTRACT - Production-ready
pragma solidity ^0.8.20;

contract SecureReward {
    struct Commit {
        bytes32 solutionHash;
        uint256 commitTime;
        bool revealed;
    }

    bytes32 public targetHash =
        0x564ccaf7594d66b1eaaea24fe01f0585bf52ee70852af4eac0cc4b04711cd0e2;
    address public winner;
    bool public ended;
    mapping(address => Commit) public commits;

    event SolutionCommitted(address indexed solver);
    event SolutionRevealed(address indexed solver);
    event RewardClaimed(address indexed winner, uint256 amount);

    constructor() payable {}

    // STEP 1: Commit a hash that includes msg.sender
    function commitSolution(bytes32 _solutionHash) external {
        require(!ended, "Already solved");
        require(commits[msg.sender].commitTime == 0, "Already committed");

        commits[msg.sender] = Commit({
            solutionHash: _solutionHash,
            commitTime: block.timestamp,
            revealed: false
        });
        emit SolutionCommitted(msg.sender);
    }

    // STEP 2: Reveal the solution (must be a different block)
    function revealSolution(
        string memory _solution,
        string memory _secret
    ) external {
        require(!ended, "Already solved");
        Commit storage commit = commits[msg.sender];
        require(commit.commitTime != 0, "Not committed");
        require(commit.commitTime < block.timestamp, "Same block");
        require(!commit.revealed, "Already revealed");

        // Hash includes msg.sender - attacker can't copy this
        bytes32 solutionHash = keccak256(
            abi.encodePacked(msg.sender, _solution, _secret)
        );
        require(solutionHash == commit.solutionHash, "Hash mismatch");
        require(
            keccak256(abi.encodePacked(_solution)) == targetHash,
            "Wrong answer"
        );

        commit.revealed = true;
        winner = msg.sender;
        ended = true;

        (bool sent, ) = payable(msg.sender).call{value: address(this).balance}("");
        require(sent, "Transfer failed");
        emit RewardClaimed(msg.sender, address(this).balance);
    }
}

Security Features at a Glance

Feature Protection
Two-phase commit-reveal Hides solution until committed on-chain
msg.sender in hash Prevents attacker from copying reveal tx
commitTime < block.timestamp Forces different-block reveal
Events Transparency and monitoring

Secure Pattern 2: DEX Swap with Slippage Protection

// SECURE CONTRACT - Production-ready
pragma solidity ^0.8.20;

contract SecureSwap {
    uint256 public reserveA;
    uint256 public reserveB;

    event Swap(
        address indexed user,
        uint256 amountIn,
        uint256 amountOut,
        uint256 deadline
    );

    function swapAforB(
        uint256 amountA,
        uint256 minAmountB,   // PROTECTION: User sets minimum output
        uint256 deadline       // PROTECTION: Transaction expiration
    ) external returns (uint256 amountB) {
        // STEP 1: CHECKS
        require(block.timestamp <= deadline, "Transaction expired");
        require(amountA > 0, "Invalid input amount");
        require(minAmountB > 0, "Set a minimum output");

        // STEP 2: Calculate output
        uint256 amountInWithFee = amountA * 997;
        amountB = (amountInWithFee * reserveB) /
            (reserveA * 1000 + amountInWithFee);

        // STEP 3: Enforce slippage protection
        require(amountB >= minAmountB, "Slippage tolerance exceeded");

        // STEP 4: Execute transfer...
        emit Swap(msg.sender, amountA, amountB, deadline);
    }
}

The require(amountB >= minAmountB) check is the critical defense. If a sandwich attacker front-runs and moves the price, the victim's swap will revert because the output falls below slippage tolerance - making the sandwich attack unprofitable.


Advanced Frontrunning Variations

As the MEV ecosystem has matured, attackers have developed increasingly sophisticated techniques beyond basic displacement.

Comparing Advanced Attack Types

High Impact

Generalized Frontrunners

Bots that copy any profitable pending transaction, replace the sender address with their own, and resubmit with higher gas. They don't need to understand the contract - they simply replicate profitable calldata.

Growing Threat

Cross-Domain MEV

Attacks that span L1 and L2 rollups. An attacker can route a victim's L2 transaction through a bridge and coordinate timing on L1 to sandwich the trade across two domains. Estimated to yield up to $2 million in profit.

Protocol Risk

Liquidation Frontrunning

Bots race to liquidate undercollateralized positions on lending protocols like Aave and Compound. While this keeps protocols solvent, the competition drives up gas costs and can cause cascading liquidations during market crashes.

Real Audit Findings (2024)

Frontrunning vulnerabilities continue to appear in production protocols. Here are findings from Sherlock and Code4rena audits:

Protocol Finding Severity
Optimism Smart wallet bond theft via tx.origin frontrunning Medium
Sentiment V2 Vault inflation attack - attacker frontrunns deposits to steal 100% of new depositors' funds High
Axion Missing slippage protection in _unfarmBuyBurn enables sandwich attacks Medium
Mellow Batch withdrawal sandwich - attackers steal value from withdrawal queues Medium
Flayer Fee donation sandwich - attackers recover tax via sandwiching fee distributions Medium

The ERC-20 Approve Race Condition

A lesser-known but critical frontrunning vector exists in the standard approve() function:

// User wants to change approval from 100 to 50
token.approve(spender, 50);

The attack:

  1. Spender sees the approve(50) transaction in the mempool

  2. Spender front-runs with transferFrom() for the current 100 allowance

  3. After victim's approve(50) executes, spender calls transferFrom() again for 50

  4. Result: Spender extracts 150 tokens instead of the intended 50

Prevention: Use increaseAllowance() / decreaseAllowance() from OpenZeppelin, or reset approval to 0 before setting the new value.

The MEV Supply Chain

Understanding who profits from frontrunning reveals the full ecosystem:

Role What They Do Revenue Share
Searchers Find MEV opportunities, build bundles Pay up to 100% of MEV as fees
Block Builders Order transactions optimally Keep builder tips
Validators Select highest-paying block 30-40% of revenue from MEV

~90% of Ethereum validators use MEV-Boost to outsource block construction. This means most blocks are built by specialized builders who maximize MEV extraction.


These advanced patterns separate junior auditors from senior researchers. The Smart Contract Hacking course covers frontrunning, sandwich attacks, and MEV alongside flash loans, oracle manipulation, and more. Join 2,000+ security researchers in our Discord community.


Common Misconceptions

?

"EIP-1559 solved the frontrunning problem."

Tap to reveal
MYTH

EIP-1559 improved fee estimation but left frontrunning unresolved. It eliminated zero-gas transactions used by some MEV protection services. Analysis shows MEV extraction actually increased post-1559 as miners sought new revenue sources.

?

"Frontrunning only affects DEX swaps."

Tap to reveal
MYTH

Frontrunning affects auctions, NFT mints, puzzle rewards, governance proposals, token approvals, liquidations, oracle updates, and any transaction where the outcome is publicly observable before execution.

?

"Setting low slippage tolerance completely prevents sandwich attacks."

Tap to reveal
MYTH

Low slippage reduces profitability but doesn't eliminate the attack. Sophisticated bots can still extract value within your tolerance. For full protection, combine slippage limits with private mempools (Flashbots Protect or MEV Blocker).

?

"Private mempools make over 50% of Ethereum transactions invisible to frontrunners."

Tap to reveal
FACT

Private transactions now account for over 50% of all gas on Ethereum. Flashbots Protect alone serves 2.1 million unique accounts. MEV Blocker covers 60%+ of Ethereum blocks and stops roughly 80% of sandwich attacks.


Frontrunning attacks are deeply connected to other smart contract vulnerability classes. Flash loan attacks often combine with frontrunning strategies - attackers use flash-borrowed capital to execute massive sandwich attacks that would otherwise require millions in upfront capital, making MEV extraction accessible to anyone.

Frontrunning also shares common ground with oracle manipulation attacks. When protocols rely on spot prices from AMM pools, a frontrunner can manipulate the price just before an oracle read, causing the protocol to act on incorrect data. Using time-weighted average prices (TWAP) over longer intervals helps defend against both single-block price manipulation and frontrunning-based oracle attacks.


Test Your Frontrunning Knowledge

5 questions - How well do you really know this attack?

Question 1 of 5

Frequently Asked Questions About Frontrunning Attacks

Frontrunning in crypto is when someone sees your pending transaction on the blockchain, then submits their own transaction first (by paying a higher gas fee) to profit at your expense. It's like someone cutting in line at a store because they saw what you were about to buy and wanted to buy it first to resell to you at a higher price.

A sandwich attack is when an attacker places two transactions around yours on a DEX - buying the token before you (pushing the price up) and selling it right after (at the inflated price). Your trade gets "sandwiched" between these two transactions, causing you to receive fewer tokens than expected while the attacker pockets the difference.

Use private RPC endpoints like Flashbots Protect or MEV Blocker - these bypass the public mempool so bots can't see your transaction. Set low slippage tolerance (0.5%-1%) on DEX swaps. For large trades, use batch auction protocols like CoW Swap. You can also split large trades into smaller ones to reduce the frontrunning incentive.

The legal status is evolving. In May 2024, the U.S. Department of Justice charged two MIT graduates with wire fraud for a $25 million MEV exploit - the first criminal prosecution of its kind. While traditional frontrunning is illegal in stock markets, the regulatory framework for blockchain MEV is still developing. Some forms of MEV extraction (like DEX arbitrage) are considered legitimate, while sandwich attacks that directly harm users are increasingly scrutinized.

Yes! Developers should implement commit-reveal schemes for sensitive submissions, enforce slippage protection with minAmountOut parameters on all swaps, add transaction deadlines to prevent stale execution, and consider integrating with batch auction systems. For maximum protection, encourage users to submit transactions through private RPCs.

Traditional mempool frontrunning is rare on L2s because most rollups (Arbitrum, Optimism) use a centralized sequencer with a private mempool. However, a new threat called cross-domain MEV has emerged - attackers can coordinate attacks across L1 and L2 by exploiting bridge message timing. The L1-L2 settlement gap creates unique attack vectors that researchers have shown can yield up to $2 million in profit.


Quick Reference: Frontrunning Prevention Checklist

Before deploying any contract with publicly observable valuable transactions:

  • Add slippage protection (minAmountOut) to every swap and exchange function

  • Set transaction deadlines to prevent stale execution at unfavorable prices

  • Use commit-reveal schemes for puzzles, auctions, and secret submissions

  • Never hardcode amountOutMin = 0 in protocol-level swap calls

  • Use increaseAllowance() instead of approve() to prevent the approval race condition

  • Recommend private RPCs (Flashbots Protect, MEV Blocker) to your users

  • Consider batch auction integration (CoW Protocol) for high-value swap functionality

  • Audit for frontrunning vectors - check every function where transaction ordering matters

  • Monitor for sandwich attacks on your protocol's pools post-deployment

  • Test MEV scenarios in your test suite with simulated mempool adversaries


Conclusion: The Invisible Tax on Every DeFi User

Frontrunning isn't just a technical curiosity - it's an invisible tax that extracts billions from DeFi users every year:

  • $1.2 billion+ extracted through MEV on Ethereum

  • $290 million in sandwich attacks in 2025 alone

  • 60,000–90,000 sandwich attacks every month

The good news? Frontrunning is increasingly preventable.

Use commit-reveal schemes for sensitive transactions. Enforce slippage protection in your smart contracts. Route transactions through private mempools. The tools exist - you just need to use them.

Don't let your protocol become the next data point in MEV extraction statistics.


Take Your Security Skills to the Next Level

Understanding frontrunning is just the beginning. To become a professional smart contract auditor, you need hands-on experience with real exploit scenarios.

The Smart Contract Hacking course delivers:

  • 320+ videos covering frontrunning, flash loans, oracle manipulation, and more

  • 40+ hands-on exercises exploiting and securing real contracts

  • Expert instruction from JohnnyTime, Trust (#1 Code4rena warden), and Pashov

  • 2,000+ member Discord for support and job opportunities

  • SSCH Certification to validate your expertise

Our students win audit contests, land security jobs, and earn significant bug bounties. See their success stories.

Start Your Security Researcher Journey

Curious what's covered? Browse the full course curriculum or try a free lesson first.

Sources and editorial notes

Reviewed by JohnnyTime. Last updated .

Incident database

Real Frontrunning & Sandwich Attacks hacks to study

A stable selection of high-signal incidents linked to this attack class, ordered by reported loss and recency.

Master Frontrunning & Sandwich Attacks in a safe lab

Practice the exploit path, debug the vulnerable code, and learn the prevention workflow auditors use in real reviews.

Exploit setup Root-cause tracing Patch review
Practice Frontrunning & Sandwich Attacks Free Trial