● Live On-Chain MEV Data Engineering

Detecting MEV & Sandwich Attacks On-Chain

A practical methodology for separating adversarial extraction from normal execution cost — and why the naive approach gets it badly wrong.

Andrew Maury
Andrew Maury
Case Study
4
Chains covered
~0 bps
CoW MEV exposure
7-day
Rolling detection window

The Challenge

Sandwich attacks are the most common form of on-chain MEV against retail traders. A bot spots a pending swap in the mempool, inserts a frontrun buy just before it and a backrun sell just after — capturing the price impact the victim caused, at the victim's expense. The victim's trade executes at a worse price than expected, and the difference flows to the bot.

The problem for anyone trying to measure this: sandwich attacks are invisible in standard analytics. They look like normal slippage. A $10,000 swap that gets sandwiched shows up in a dashboard as "executed at 42 bps of slippage" — indistinguishable from a large trade in a thin pool. Without a methodology that isolates the adversarial component, every slippage number is a mix of real execution cost and extraction, and you can't act on either.

This matters most to DEX aggregators, L2 foundations, and grant programs that are trying to evaluate which protocols actually protect their users — and which ones quietly route flow into sandwichable positions.

What We Built

ClearTrace's MEV detection layer runs as part of the broader ClearTrace execution-intelligence engine, covering Ethereum, Base, Arbitrum, and Optimism. It identifies victim swaps, quantifies the volume sandwiched over rolling 7-day windows, and reports MEV exposure as a distinct metric — kept separate from the execution quality score so they can be read independently.

The v1 mistake: tx_hash is not execution order

The first cut at sandwich detection tried to reconstruct in-block ordering directly from dex.trades, using tx_hash comparisons as a proxy for sequencer position — treating a lower hash as an earlier transaction. That logic is wrong: tx_hash is a cryptographic hash, not a sequence number. Sorting by hash produces an arbitrary permutation of transactions, not the order they were actually included in the block. A "sandwich" identified this way is noise.

The correct source is Dune's curated dex.sandwiched table, built from Dune's Spellbook detection macro — which uses actual evt_index (on-chain event position) to reconstruct frontrun → victim → backrun triples across every block. Switching to this source eliminated the false positives entirely.

The detection query

The core extraction is direct: pull confirmed victim swaps from dex.sandwiched for the four covered chains, attach per-chain and global 7-day totals as window columns, and return the most recent 500 for the live feed:

WITH victims AS (
    SELECT
        blockchain,
        block_time,
        project,
        token_pair,
        amount_usd,
        tx_hash,
        tx_from
    FROM dex.sandwiched
    WHERE block_time >= NOW() - INTERVAL '7' DAY
      AND blockchain IN ('ethereum', 'base', 'arbitrum', 'optimism')
      AND amount_usd BETWEEN 1 AND 100000000
),
enriched AS (
    SELECT
        v.*,
        COUNT(*) OVER ()                           AS total_attacks_7d,
        SUM(amount_usd) OVER ()                    AS total_sandwiched_usd_7d,
        COUNT(*) OVER (PARTITION BY blockchain)    AS chain_attacks_7d,
        SUM(amount_usd) OVER (PARTITION BY blockchain) AS chain_sandwiched_usd_7d
    FROM victims v
)
SELECT *
FROM enriched
ORDER BY block_time DESC
LIMIT 500;

The window columns mean the 7-day KPIs are accurate across the full dataset — not just the 500-row page — so a per-chain breakdown shows the right totals without a second query.

Separating MEV from slippage in the execution quality score

Slippage and MEV exposure are both costs, but they have different causes and different remedies. ClearTrace scores them separately. Execution quality compares each fill's realized price against a 1-minute VWAP oracle — both the sold leg and the bought leg valued explicitly against prices.usd, avoiding the circular-pricing trap of comparing against Dune's internally derived amount_usd. The MEV score layers on top: it reports sandwich victim counts and sandwiched volume as a distinct column, so a protocol's execution quality score is not contaminated by the MEV it fails to prevent.

The benchmark this produces across major aggregators — using the same $100–$10M notional band and a 2,000 bps junk filter to exclude pricing errors — is the kind of number no aggregator's own dashboard will publish about itself:

Aggregator Median slippage vs VWAP MEV toxicity Revert rate
CoW Swap −0.1 bps Zero 0.0%
1inch −0.4 bps Low 1.2%
Odos −0.6 bps Medium 2.1%

The L2 finding: structural protection vs coverage gap

ClearTrace covers Arbitrum and Optimism, and their sandwich numbers are near-zero compared to Ethereum. This is a fact worth stating carefully, because two very different things can produce near-zero attack counts: the detector runs and finds little (structural protection), or the detector simply has no data for that chain (a coverage gap that would be wrong to call protection).

The verification query checks both: it looks at active_days (how many days in the trailing 30 the chain has data) alongside sandwich_victims_30d. If active_days ≈ 30 and sandwich_victims_30d is tiny, the detector is running and genuinely finding almost nothing — this is the Arbitrum case, consistent with its FCFS (first-come-first-served) private-mempool sequencing that eliminates the pending mempool window bots need to frontrun. A foundation citing "Arbitrum is sandwich-protected" can point to this as the empirical basis.

What It Shows

The ability to detect adversarial extraction in data that's structured to hide it — and to distinguish a real signal (the chain genuinely has fewer attacks) from an absence of data. The v1 → v2 rewrite is the concrete example: the wrong model produced confident-looking numbers that were meaningless; identifying why they were meaningless (hash ≠ sequence) required understanding the underlying data structure deeply enough to know what to use instead.

What It Proves to a Client

That we build measurement infrastructure that holds up to scrutiny. ClearTrace's MEV layer gives L2 foundations, DEX aggregators, and grant programs a neutral, third-party answer to the question their own analytics can't answer honestly: how much of the slippage users are paying is real execution cost, and how much is being extracted by bots? The methodology is auditable — the detection source, the intra-aggregator dedup logic, and the L2 verification approach are all documented and grounded in the actual on-chain data structures.

Have hard data to make useful?

Rantum is a senior data science & ML studio. We turn messy, fragmented, and adversarial data into models, APIs, and products that ship — on-chain and beyond.

Work with us