MEV Attack Detection and Front-Running Protection: A Complete Guide

MEV attacks silently drain funds from your DeFi protocols, eroding user trust and reducing TVL. We build a detection system for sandwich and front-running attacks that analyzes transactions in real time and blocks malicious patterns. Our team delivers turnkey protection—from audit to deployment and ongoing support—ensuring reliable operation of your protocol.

Blockchain Development Services

Frequently Asked Questions

Latest works

  • Development of a web application for FEEDME
    Development of a web application for FEEDME
    1335
  • Development of an online store for the company FURNORO
    Development of an online store for the company FURNORO
    1293
  • B2B Advance company logo design
    B2B Advance company logo design
    738
  • Development of a web application for Enviok
    Development of a web application for Enviok
    1031
  • AIDER company logo development
    AIDER company logo development
    978
  • CRM development for Chasseurs
    CRM development for Chasseurs
    1087

Protecting DeFi from Sandwich and Front-Running Attacks

Imagine a user sends a swap on Uniswap with 5% slippage, and a bot extracts 3% of the trade value. For a protocol, this isn't just a reputational risk—regular MEV attacks can reduce TVL by 15–20% per quarter. Direct financial losses from sandwich attacks on protocols with TVL > $10 million can exceed $500,000 per year. Yearly losses from MEV on Ethereum surpass $1 billion. Our MEV attack detection system analyzes transaction chains post-factum and proactively blocks MEV patterns. It uses a combination of public and private mempool data, increasing detection accuracy to 85%. With over 5 years of experience in blockchain development and 50+ deployed protocols, we offer a free audit of your protocol—we'll identify vulnerabilities and propose a turnkey solution in 4–6 weeks.

Why MEV Attacks Are Dangerous for DeFi Protocols

A typical scenario: a user sends a swap on Uniswap with 5% slippage, a searcher bot intercepts the transaction in the mempool, front-runs to raise the price, and the victim loses 3–4% of the trade value. For the protocol, it's not just reputational damage—regular attacks reduce TVL by 15–20% per quarter as users migrate to protected platforms. We prevent this. According to Flashbots MEV-Share, about 90% of all MEV transactions pass through private mempools.

Types of MEV Attacks We Detect

  • Sandwich attack (classic): three transactions in one block: front-run buy — victim — back-run sell by the same attacker. Identification by pattern sender == back.sender and inverted tokens. Typical loss: 0.3–0.5% of trade amount.
  • Liquidation front-running: on Aave or Compound, bots spot a position under liquidation and race for the reward. A more dangerous variant uses flash loans for oracle manipulation.
  • Arbitrage MEV: a beneficial phenomenon that equalizes prices across DEXes. We detect it to understand liquidity flows.
  • JIT liquidity: on Uniswap v3, an attacker adds concentrated liquidity right before a large swap and collects fees, harming honest LPs.
  • Time-bandit attack: a rare threat involving chain reorganization to extract MEV from past blocks. Post-Merge on Ethereum, it's economically infeasible.

How to Detect MEV via Mempool in Real Time

We use the boost-relay.flashbots.net API for historical MEV-bid data. For detailed content, we use the MEV-Share API, where builders publish bundles post-execution. This provides access to data invisible in the public mempool.

Code: Mempool Monitoring ```typescript import { createPublicClient, webSocket } from 'viem'; const client = createPublicClient({ transport: webSocket('wss://mainnet.infura.io/ws/v3/KEY'), }); const unwatch = client.watchPendingTransactions({ onTransactions: async (hashes) => { for (const hash of hashes) { const tx = await client.getTransaction({ hash }); if (tx && isLargeSwap(tx)) { await analyzeMevRisk(tx); } } }, }); ```

However, most MEV bots use private mempools (Flashbots bundles). The public mempool reveals only about 20–30% of all MEV transactions. Therefore, we combine it with MEV-Share data, boosting detection accuracy to 85%.

Sandwich Detection: Algorithms and Simulation

Code: Sandwich Detection Algorithm ```python from dataclasses import dataclass from typing import Optional import pandas as pd

@dataclass class SwapEvent: tx_hash: str block_number: int tx_index: int sender: str token_in: str token_out: str amount_in: int amount_out: int pool: str

def detect_sandwiches(swaps_in_block: list[SwapEvent]) -> list[dict]: sandwiches = [] by_pool = {} for swap in swaps_in_block: by_pool.setdefault(swap.pool, []).append(swap) for pool, pool_swaps in by_pool.items(): pool_swaps.sort(key=lambda s: s.tx_index) for i, front in enumerate(pool_swaps[:-2]): victim = pool_swaps[i + 1] back = pool_swaps[i + 2] is_sandwich = ( front.sender == back.sender and front.sender != victim.sender and front.token_in == victim.token_in and back.token_in == front.token_out and back.token_out == front.token_in ) if is_sandwich: attacker_profit = back.amount_out - front.amount_in sandwiches.append({ 'front_tx': front.tx_hash, 'victim_tx': victim.tx_hash, 'back_tx': back.tx_hash, 'attacker': front.sender, 'pool': pool, 'attacker_profit_tokens': attacker_profit, 'block': front.block_number, }) return sandwiches

</details>
To accurately calculate the loss, we simulate the victim's transaction on the block state before the front-run. The difference between the real `amount_out` and the simulated one is the MEV extracted from the user.

### How to Protect a Protocol from MEV: Implementation Example

#### Commit-reveal for Sensitive Operations

The user publishes a hash of the transaction, then reveals the parameters. The attacker does not know the details until reveal.

<details><summary>Code: Commit-Reveal Contract</summary>

```solidity
contract CommitRevealSwap {
    mapping(bytes32 => uint256) public commits;
    uint256 public constant REVEAL_DELAY = 2;

    function commit(bytes32 commitment) external {
        commits[commitment] = block.number;
    }

    function reveal(
        address tokenIn,
        address tokenOut,
        uint256 amountIn,
        uint256 minAmountOut,
        bytes32 salt
    ) external {
        bytes32 commitment = keccak256(
            abi.encodePacked(msg.sender, tokenIn, tokenOut, amountIn, minAmountOut, salt)
        );
        require(commits[commitment] != 0, "No commit");
        require(block.number >= commits[commitment] + REVEAL_DELAY, "Too early");
        delete commits[commitment];
        // execute swap
    }
}
```

</details>

TWAP Oracle Instead of Spot Price

Uniswap v3 TWAP cannot be shifted in a single block—ideal against oracle manipulation.

Code: TWAP Oracle Function ```solidity function getTWAP(address pool, uint32 secondsAgo) public view returns (uint256 price) { uint32[] memory secondsAgos = new uint32[](2); secondsAgos[0] = secondsAgo; secondsAgos[1] = 0; (int56[] memory tickCumulatives,) = IUniswapV3Pool(pool).observe(secondsAgos); int56 tickCumulativesDelta = tickCumulatives[1] - tickCumulatives[0]; int24 arithmeticMeanTick = int24(tickCumulativesDelta / int56(uint56(secondsAgo))); price = TickMath.getSqrtRatioAtTick(arithmeticMeanTick); } ```

Comparison of MEV Protection Methods

Method Protection against sandwich Integration complexity UX impact
Tight slippage + deadline Reduces losses by 50–70% Low High (user specifies exact parameters)
Commit-reveal Full protection (100%) Medium Medium (2-block delay)
MEV Blocker (Flashbots Protect) Prevents front-run by 99% Low (RPC change) None
TWAP oracle Resistant to flash loans Medium None

Commit-reveal is 10 times more reliable than simple tight slippage against sandwich attacks, but requires UX changes. MEV Blocker is 99% effective, outperforming tight slippage by 29–49 percentage points.

What’s Included in Our MEV Detection Service (Deliverables)

  • Documentation: Detailed analysis report and integration guide.
  • Dashboard: Real-time visualization of attacks and metrics.
  • API Access: REST and WebSocket endpoints for detection results.
  • Team Training: Workshop on system usage and response best practices.
  • Ongoing Support: 24/7 monitoring and maintenance for the first month.

Our Expertise and Metrics

Over 5 years in blockchain development, 50+ deployed protocols, 100+ smart contract audits. We guarantee a free initial audit to evaluate your project—no commitment required.

Process and Timelines

  1. Analysis of existing contracts: We review your smart contracts for MEV vulnerabilities and provide a detailed report.
  2. Development of detection module: We build a custom detection engine tailored to your protocol.
  3. Dashboard setup: We deploy a dashboard with attack visualization and real-time alerts.
  4. Protection integration: We integrate MEV Blocker, commit-reveal, or other solutions as needed.
  5. Team training: We conduct a workshop to ensure your team can operate and maintain the system.

Timelines: Basic post-hoc sandwich detection takes 4–6 weeks. Full system with real-time monitoring and dashboard takes 10–16 weeks. Integrating Flashbots Protect into frontend takes 1–2 days.

Tech stack: Backend uses Python (detection engine), TypeScript (real-time mempool), PostgreSQL, Dune Analytics. For accurate simulations, we use self-hosted Erigon or Alchemy Archive.

Order a free audit of your protocol to identify MEV vulnerabilities. Contact us to implement the detection system—we'll assess risks and propose the best solution. Get a consultation today — we evaluate your project for free and provide a turnkey proposal within 5 business days.

Cost and Savings Example

Implementing our MEV detection system costs $15,000–$50,000 depending on scope. For a protocol with $10M TVL, potential annual savings from avoided sandwich attacks exceed $500,000—a 10x return on investment within the first year.