Every sandwich attack on Ethereum publishes its own audit trail. The attacker wants it hidden, but the chain doesn’t work that way: a sandwich is two transactions that must sit inside the same block, hit the same pool, swap in opposite directions, and trap someone in between. That shape is impossible to disguise — the pool’s Swap events are public, timestamped, and ordered forever. You don’t need an MEV analytics subscription, a labeled dataset, or an API key to see it. You need ~200 lines of Python and a free public RPC.

I built that scanner and ran it against live mainnet blocks while writing this article. It found a real sandwich in block 26415965, measured the victim’s tax at 12.3 basis points, and — more interestingly — produced an $87,886 “attacker profit” on block 26415926 that turned out to be almost entirely fictional once I traced the flows by hand. That failure mode is the most valuable thing in this article: it’s the same trap that makes most MEV dashboards lie to you, and after reading this you’ll be able to catch it yourself.

What a sandwich actually is, mechanically

A sandwich is an attacker trading around a victim in three moves inside one block:

  1. Front-run: attacker buys the asset the victim is about to buy, pushing the pool price up.
  2. Victim: their swap executes against the moved price. The gap between the pre-attack price and their fill is the tax — paid to the attacker, not to the pool.
  3. Back-run: attacker sells the position the victim’s own price impact just created, capturing the round trip.

The attacker’s net position after legs 1 and 3 nets out to a profit measured in the pool’s tokens. On Uniswap V3 — whose pools alone did roughly $1.33B of the $9.5B in tracked DEX volume on November 14, 2026 per DefiLlama’s live index, the largest single protocol share — every one of those moves emits a Swap event with a fully specified signature. Nothing about the attack is private except the ordering bribe.

Uniswap V3 Swap event layout (topic0 0xc42079f9...a67):

  • topics: [eventSig, sender, recipient, sqrtPriceLimitX96] — all indexed
  • data (ABI-encoded, 160 bytes): amount0 (int256), amount1 (int256), sqrtPriceX96 (uint160), liquidity (uint128), tick (int24)

The signs use pool-balance semantics: positive amount0 means the pool received token0 (the swapper paid it), negative means the pool paid it out. This one convention detail is where half of homemade MEV scripts go wrong, and we’ll see exactly how in a minute.

The scanner

Design principles, in priority order:

  1. Trust nothing but the chain. No exchange APIs, no cached labels, no token lists. Token symbols and decimals are read straight from the contract via eth_call. Prices come from the pool’s own sqrtPriceX96.
  2. Read-only. Every call is eth_blockNumber, eth_getBlockByNumber, eth_getBlockReceipts, or eth_call — the exact method set any free public RPC exposes.
  3. Attribute nothing you can’t net. The naive heuristic — “same sender swaps in and out of one pool with strangers in between = sandwich” — is where this article’s $87,886 mistake lives. We compute it, print it, and then check it against global netting.

The detection loop, verbatim from the script:

V3_SWAP = lc("0xc42079f94a6350d7e6235f29174924f928cc2ac818eb64fed8004e115fbcca67")

The token constants live next to it in the script, all lowercased so they match the addresses RPCs return:

WETH    = lc("0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2")
STABLES = {
    lc("0xdAC17F958D2ee523a2206206994597C13D831ec7"): "USDT",
    lc("0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"): "USDC",
    lc("0x6B175474E89094C44Da98b954EedeAC495271d0F"): "DAI",
}

The ingestion loop, verbatim:

    for b in blocks:
        blk = rpc("eth_getBlockByNumber", [hex(b), True])
        for tx in blk["transactions"]:
            tx_from[(b, tx["hash"].lower())] = tx["from"].lower()
        n_tx += len(blk["transactions"])
        for rec in rpc("eth_getBlockReceipts", [hex(b)]):
            frm = tx_from.get((b, rec["transactionHash"].lower()))
            for lg in rec["logs"]:
                if not lg.get("topics") or lc(lg["topics"][0]) != V3_SWAP:
                    continue
                pool = lc(lg["address"])
                data = bytes.fromhex(lg["data"][2:])
                if len(data) < 160:
                    continue
                a0, a1 = s256(data[0:32]), s256(data[32:64])
                sq = int.from_bytes(data[64:96], "big")
                if pool not in pool_cache:
                    pool_cache[pool] = pool_tokens(pool)
                tk0, tk1 = pool_cache[pool]
                swaps.setdefault((b, pool), {"t0": tk0, "t1": tk1, "list": []})
                swaps[(b, pool)]["list"].append({
                    "logIndex": int(lg["logIndex"], 16), "from": frm,
                    "tx": rec["transactionHash"].lower(),
                    "amount0": a0, "amount1": a1, "sqrtP": sq})
                n_logs += 1

amount0/amount1 are signed pool-balance deltas, so before anything else the script decodes two’s-complement int256:

def s256(raw):
    v = int.from_bytes(raw, "big")
    return v - (1 << 256) if v >= (1 << 255) else v

s256 is two’s-complement decoding for the signed int256 amounts — get this wrong and every buy looks like a sell. The sandwich pattern match, once swaps are grouped per (block, pool) and sorted by logIndex:

        lst = sorted(s["list"], key=lambda x: x["logIndex"])
        if len(lst) < 3:
            continue
        m0, m1 = meta(s["t0"]), meta(s["t1"])
        d0, d1 = m0[1], m1[1]
        used = set()
        for i, a in enumerate(lst):
            if i in used:
                continue
            for j in range(len(lst) - 1, i, -1):
                c = lst[j]
                if j in used or c["from"] != a["from"]:
                    continue
                if (a["amount0"] > 0) == (c["amount0"] > 0):
                    continue  # same direction, not a round trip
                victims = [x for k, x in enumerate(lst) if i < k < j and x["from"] != a["from"]]
                if not victims:
                    continue
                profit0 = -(a["amount0"] + c["amount0"])
                profit1 = -(a["amount1"] + c["amount1"])
                p0h, p1h = profit0 / 10 ** d0, profit1 / 10 ** d1

The profit identity is the elegant part: because the attacker’s two legs are pure pool-balance deltas, their summed delta is their P&L by definition — no external price feed needed to know what the attacker gained or lost in token terms.

Converting sqrtPriceX96 to a human price needs one careful line. sqrtP is the square root of the pool’s raw price — token1-wei per token0-wei:

def price_v3_sqrt(sqrt_p, dec0, dec1):
    """Human price: token1 units per 1 token0."""
    sp = sqrt_p / (1 << 96)
    return (sp * sp) * (10 ** (dec0 - dec1))

For the USDC(6)/WETH(18) pool, token1 units per token0 means WETH per USDC — so the USDC-per-WETH headline number is its reciprocal, 10**12 / (sp/2**96)**2. Skip the decimals correction and you’ll print $0.0006 for ETH, which is exactly the wrong-price bug I hit and fixed mid-build.

Finally, the victim’s tax. The honest way to measure it: compare what the victim actually got against what their trade would have returned at the pre-attack pool state — read via a historical eth_call of slot0() at block N-1 if the front-run is the block’s first swap, otherwise from the previous swap’s ending sqrtP:

SLOT0 = "0x3850c7bd"  # slot0(): (sqrtPriceX96, tick, ..., unlocked)

def pool_sqrtP_at(pool, block):
    """sqrtPriceX96 at the END of `block` via historical eth_call of slot0()."""
    out = rpc("eth_call", [{"to": pool, "data": SLOT0}, hex(block)])
    return int.from_bytes(bytes.fromhex(out[2:])[0:32], "big")

The real catch: a 12 bp tax in block 26415965

The scanner’s live run over 60 consecutive blocks (18,889 transactions, 1,146 V3 swap events decoded, 889 pools) flagged exactly one clean sandwich. Pool: 0xe0554a476a092703abdb3ef35c80e0d76d32939f, USDC/WETH, 0.01% fee tier — the tightest, where sandwiches live because the price moves are cheap to move. Verified on-chain: token0 is canonical USDC 0xa0b8...eb48, token1 is canonical WETH 0xc02a...6cc2.

$ python3 sandwich_scanner.py 60
latest block 26415990, scanning 26415931..26415990 (60 blocks)
transactions: 18889, V3 swap events decoded: 1146, V3 pools touched: 889

candidate sandwiches: 1
  block 26415965 USDC/WETH victims=1
    naive same-pool netting: +0.001324 WETH ($2.36)  <- overstates cross-pool routes
    victim damage: 0.003688 WETH on notional 3.01 WETH (12.3 bp)
    frontrun 0x57c46b5bb4139ee5a7cb03b1bfb7c57a3db73b6c69e5e1d0a1387c558e5aee6b
    backrun  0xcb7004cf555bfeb7ba89b08d4ff5b36216a7e718b4e2dce4ba6389099c457a33

I then hand-decoded every swap in that pool for the block. Here is the entire attack, at prices I derived from each event’s ending sqrtPriceX96:

StepTxActionPrice
pre-attack state—pool mid1,782.03 USDC/WETH
front-run0x57c4...e6bbuys 1.332557 WETH for 2,375.52 USDC1,782.97
victim0x21f8...91b4buys 3.005271 WETH for 5,362.04 USDC1,784.21
back-run0xcb70...a33sells 1.331233 WETH back for 2,375.52 USDC1,784.16

The victim paid 12.26 basis points over the pre-attack mid — $6.57 on a $5,362 order. The attacker grossed 0.001324 WETH ($2.36). And now the number nobody puts in the marketing thread: gas. The front-run cost 169,417 gas at 1.252 gwei (0.000212 ETH); the back-run cost 111,363 gas at 8.891 gwei — 7× the per-unit price, because the attacker had to bid for immediate back-run placement. Total gas: 0.001202 ETH ≈ $2.15 against $2.36 of gross profit. Net for the whole operation: roughly $0.21.

That’s the modern sandwich in one line: thousands of dollars of notional moved, twelve basis points of tax collected, and the profit is one-fifth of a cent per dollar of gas burned — at best. The economics only work because the fixed costs are automatable across thousands of blocks a day, which is exactly why this role is dominated by a handful of industrial searchers and why the “MEV is easy money” framing is five years stale.

The $87,886 lie: when the detector fabricates a sandwich

Eleven blocks earlier — block 26415926, both swaps sharing the same pool pair — my detector’s naive netting flagged this:

block 26415926 WETH/USDT victims=1 profit +24.704269 WETH ($43,939.79)
block 26415926 USDC/WETH victims=1 profit +43946.290843 USDC ($43,946.29)
TOTAL attacker profit (USD-priced): $87,886.08

One wallet, opposite-direction swaps in the same pools, strangers in between. Textbook pattern match. Now the hand audit of that wallet’s actual transactions:

Transaction 0xf7ec...680 (from 0x4958...bb54, to a 9,315-byte contract): pays 13,341.10 USDC into the 5 bp USDC/WETH pool, receives 7.494 WETH; pays those 7.494 WETH into the 30 bp WETH/USDT pool, receives 13,328.29 USDT. Net: −12.81 USD plus 922,845 gas.

Transaction 0x38f7...77e (same wallet, same block): pays 57,182.71 USDT for 32.1983 WETH in the USDT pool; sells those WETH for 57,287.39 USDC in the USDC pool; sweeps a 0.0645 WETH residual for 114.83 USDC. Net: −$115 on the legs plus 814,490 gas ≈ another $3.50.

So the wallet’s global position across the block: roughly −$125, not +$87,886. Where did the detector’s number come from? It netted only the pool-local legs and labeled everything in between — including two other transactions from completely unrelated wallets — as the attacker’s victims. Those “victims” were:

  • 0x1e1c...a50d: a router-executed USDT→WETH→USDC stable-arbitrage that paid 56,731.21 USDT and received 56,949.84 USDC — +$218.63 gross profit on its own arb. The detector booked this wallet’s legs as sandwich revenue for someone else.
  • The spread-capture wallet itself, whose two legs the detector split into “attack” and “profit.”

The global-netting check takes one extra pass — sum every Swap delta for the accused wallet across all pools in the block — and it would have rejected both flags instantly: a real sandwich nets positive; this wallet netted negative. The naive heuristic was off by $88,011 — and, worse, had the sign wrong. This is precisely the error class behind “MEV bots extracted $X” headlines that count router arbitrage as theft: pattern-shaped activity gets booked as predation, and nobody audits the sign.

What this detector is — and honestly isn’t

It is: a working, dependency-free proof that sandwich forensics needs no vendor. Every number in this article came out of this script or my hand-decode of the same raw events. Public RPCs — publicnode, drpc, 0xrpc — served all of it, free, no key.

It isn’t, yet: V2-pool aware (Uniswap V2-fork pairs emit Swap events with non-canonical semantics — I measured “both amounts in” legs on a live MATIC/WETH pair that break naive in/out netting, so I dropped V2 rather than ship wrong numbers), MEV-Boost/private-orderflow aware (private bundles are invisible until inclusion, so same-block detection only), or profitable-strategy-aware (a back-run at 8.9 gwei is a bundle bid, not retail gas).

The business angle. Two audiences pay for this exact capability. Wallet and portfolio tools want per-swap “you were sandwiched” flags with an honest bp number — the $6.57 line item, provable on-chain. And trading desks want the inverse: a live feed of which pools got hit in the last N blocks, because sandwich density is a real-time liquidity-quality signal. Both are thin wrappers around the ~240-line scanner core in this article.

Build notes, if you extend it. Historical slot0() is the whole game for tax measurement — without it your baseline is the attacker’s own front-run, and you’ll measure their markup instead of their theft. And when your detector prints a profit, net the accused wallet globally before you believe it. My $87,886 ghost died in thirty seconds of hand-netting; a dashboards-for-subscriptions business should survive the same audit or not ship.

Every system in this article — the scanner, the historical-price forensics, the victim-tax accounting, or a monitoring feed built on the same core — can be customized for your own data or your own product. If you want that built out, email [email protected] (what we do: /pages/hire-us).