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

We design and develop full-cycle blockchain solutions: from smart contract architecture to launching DeFi protocols, NFT marketplaces and crypto exchanges. Security audits, tokenomics, integration with existing infrastructure.
Showing 1 of 1All 1305 services
MEV Attack Detection and Front-Running Protection: A Complete Guide
Complex
~1-2 weeks
Frequently Asked Questions

Blockchain Development Services

Blockchain Development Stages

Latest works

  • image_website-b2b-advance_0.webp
    B2B ADVANCE company website development
    1349
  • image_web-applications_feedme_466_0.webp
    Development of a web application for FEEDME
    1247
  • image_websites_belfingroup_462_0.webp
    Website development for BELFINGROUP
    949
  • image_ecommerce_furnoro_435_0.webp
    Development of an online store for the company FURNORO
    1183
  • image_logo-advance_0.webp
    B2B Advance company logo design
    642
  • image_crm_enviok_479_0.webp
    Development of a web application for Enviok
    921

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

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.

How Do We Find What the Compiler Misses?

When a protocol loses $197M through a flash loan attack on a function that auditors reviewed live — it's not an accident. It's a systemic gap in methodology. Our experience shows: vulnerabilities live in a contract for over a year, while the compiler remains silent. We restructured the audit process to catch such cases before deployment.

What Static Analysis Won't Find?

Slither is the standard first tool. It finds reentrancy, integer overflow (in older Solidity versions), improper use of tx.origin, variable shadowing, uninitialized storage. On a real project, Slither produces dozens of warnings, of which critical ones are 0‑2. The rest is informational noise.

Slither won't find logical vulnerabilities. If withdraw correctly checks balance and correctly updates state, but business logic allows double deduction through two different code paths — Slither stays silent.

Mythril uses symbolic execution: builds a graph of all possible execution paths and searches for reachable states violating properties. Works well on isolated contracts. On a protocol of 20 contracts with cross‑contract calls — path explosion, analysis hangs or returns false positives.

Both tools are mandatory as a first pass. But they don't replace manual analysis.

Fuzzing: Where Echidna and Foundry Find Real Bugs

Echidna is a property‑based fuzzer from Trail of Bits. The idea: formulate contract invariants as Solidity functions (echidna_invariant), Echidna generates random call sequences and tries to break the invariant.

Example invariant for a lending protocol:

function echidna_total_assets_ge_liabilities() public view returns (bool) {
    return totalAssets() >= totalLiabilities();
}

Echidna will find a sequence deposit → borrow → liquidate → repay that violates this invariant. You can't build such a case manually — too many combinations.

Foundry fuzzing (forge test --fuzz-runs 100000) is easier to integrate if the team is already on Foundry. Supports stateful fuzzing via invariant tests. In a real project: auditing a vault contract, Foundry fuzzed for 40 minutes and found an edge case where maxWithdraw returned a value larger than actual balance at a specific shares/assets ratio after several donations. Hardhat unit tests missed it — they didn't have that combination of parameters.

Medusa (from Trail of Bits, newer than Echidna) supports corpus‑guided fuzzing and runs faster on large contracts. If the codebase exceeds 5000 lines of Solidity — we look at Medusa.

How Invariants Help Identify Critical Vulnerabilities

Formal verification proves that the contract satisfies specifications for all possible inputs — not for N random ones, but mathematically for all. Tools: Certora Prover, K Framework, Halmos.

Certora works with CVL (Certora Verification Language): write rules and invariants, the Prover translates them into SMT formulas and checks via Z3/CVC5. MakerDAO, Aave, Uniswap use Certora in CI/CD pipeline — every PR is automatically verified.

Limitations: doesn't work with unbounded loops, struggles with hash functions and signature verification. For contracts with simple math (AMM, lending) — excellent. For contracts with arbitrary external calls — difficult to write sufficiently complete specifications.

Formal verification makes sense for contracts that: manage over $50M, are rarely updated, have clearly formalizable invariants. For fast‑iterating products — the cost‑benefit ratio doesn't favor verification.

What Attack Vectors Do Junior Auditors Miss?

Storage collision in proxy pattern. Transparent proxy and UUPS use specific slots for implementation address (EIP‑1967). If an implementation accidentally declares a variable in slot 0 that overlaps with proxy storage — we get silent override. Slither won't catch this if proxy and implementation are in different files.

Read‑only reentrancy. Classic reentrancy guard protects against state changes during recursive calls. But if an external contract reads state via a view function mid‑transaction — guard doesn't help. Years ago, Curve pools became an attack vector precisely through this: an external protocol read get_virtual_price during a reentrancy‑vulnerable state of Curve.

Oracle manipulation via TWAP. Spot price is a standard target for flash loan attack. TWAP is harder to manipulate, but not impossible: on low‑liquidity Uniswap v2 pairs, TWAP can be shifted over several blocks with enough capital. Proper protection: use Chainlink as primary oracle with TWAP as fallback, with deviation threshold check.

Gas griefing on unbounded loop. A function iterates over an array of users. Attacker adds thousands of addresses with zero balances — the function's gas cost rises to the gas limit, making it inaccessible. Protection: pull pattern instead of push, limit array lengths, batch processing with position tracking.

Front‑running on MEV. Transaction is visible in mempool before inclusion in block. MEV bot sees addLiquidity for a significant amount, inserts its own swap before it (sandwich attack). For AMM this is part of the model. For protocols with price functions — require minAmountOut / deadline parameter and its mandatory verification.

Structure of a Full Audit

  1. Scope definition and automated analysis (1‑2 days). Fix commit hash, compiler version, list of out‑of‑scope items. Run Slither, Mythril, Aderyn. Triage: separate real critical bugs from false positives. Build contract dependency map.

  2. Manual analysis (5‑15 days). Each contract line by line. Special attention: all external and public functions, all transfer/call/delegatecall, all places where state changes before a check or after an external call, all math operations with user inputs. On average, 95% of found vulnerabilities are logical, not technical.

  3. Fuzzing and testing (2‑5 days). Echidna or Foundry invariant tests for critical invariants. Fork mainnet tests — verify behavior in real environment with real oracles. For example, in 4 days fuzzing finds on average 3 edge cases not covered by unit tests.

  4. Report and mitigation. Report with severity (Critical/High/Medium/Low/Informational), attack vector description, PoC code for Critical/High. Developers fix, auditors perform re‑audit of fixes.

Severity Examples Requires re‑audit?
Critical Drain funds, unauthorized ownership transfer Always
High Manipulation, DoS on key functions Always
Medium Incorrect behavior on edge cases Recommended
Low Gas inefficiency, typos in events Optional

Audit in CI/CD

Common practice for mature protocols: Slither and Aderyn run in GitHub Actions on every PR. Certora Prover — on merge to main. This doesn't replace a full audit before deployment, but catches regressions.

# .github/workflows/audit.yml
- name: Run Slither
  uses: crytic/[email protected]
  with:
    target: 'src/'
    slither-args: '--filter-paths "test|mock|script"'
Checklist of mandatory checks before deployment
  • All external functions have access controls (onlyOwner, onlyRole)
  • Use SafeERC20 for external tokens
  • No delegatecall to unknown addresses
  • Reentrancy check in all functions with external calls
  • Presence of minAmountOut and deadline in AMM functions
  • Use of a trusted oracle (Chainlink) with deviation threshold

Audit Tools Comparison

Tool Type of Analysis What It Finds Limitations
Slither Static Reentrancy, integer overflow, access control Misses logical vulnerabilities
Mythril Symbolic execution Reachable states violating properties Path explosion on large codebases
Echidna Fuzzing (property‑based) Invariant violations Requires writing invariants
Certora Formal verification Mathematical proof of properties Doesn't work with hashes/signatures

Deliverables

  • Full report in PDF with CVSS scores for each vulnerability
  • PoC code for all Critical and High (reproducible in test environment)
  • Remediation recommendations with code examples
  • Re‑audit after fixes (up to two iterations)
  • Brief guide for developers on ongoing operation
  • Post‑deployment support for 30 days (consultations and incident analysis)

Timeline

Audit of a simple token or NFT contract — 3‑5 business days. DeFi protocol with lending/AMM — 2‑4 weeks. Full stack with multiple protocols, cross‑chain, proxy upgrades — 4‑8 weeks. Re‑audit of fixes — 3‑7 days separately.

Our team has 7+ years of experience in smart contract security, having audited over 100 projects. We guarantee we won't miss any known attack vectors — we use licensed versions of Slither and best fuzzer configurations. Assess your project — we will analyze your code for free and provide a commercial offer within 2 days. Order an audit with quality guarantee and get a discount on re‑audit for repeat customers.