I built a MEV bot on Solana a while back. It worked. I made money. But then I wanted to see it from the other side. The victim’s side.

I kept noticing my swaps getting worse fills than what the quote said. Just a little bit worse. Consistently. I suspected something, but suspicion isn’t proof. I wanted to look at the raw blocks and see if the sandwich pattern was actually there.

So I wrote a script. It’s not fancy. It doesn’t need an indexer or a database. It just looks at one block at a time.

Here is how I do it.


What you are looking for

A sandwich attack has a specific shape in the block data.

An attacker buys Token X right before your swap. Then you buy Token X at a worse price because the pool shifted. Then the attacker sells Token X immediately after you, locking in their profit.

Three transactions. Same pool. The attacker signs both the first and third transaction. You sign the middle one.

On Solana, these usually land together because the attacker sends them as a Jito bundle. That means they sit next to each other in the block. No gaps. No noise. Just three lines that tell the whole story.


Step 1: Fetch the block

You need the full transaction details. The default fetch doesn’t give you token balances.

const block = await connection.getBlock(slot, {
  maxSupportedTransactionVersion: 0,
  transactionDetails: 'full',
  rewards: false,
  commitment: 'confirmed'
})

That maxSupportedTransactionVersion: 0 part is important. If you skip it, versioned transactions throw errors. I used to debug that for an hour before I realized the option was missing. Don’t be me.

The commitment: 'confirmed' flag matters too. The default is finalized, which lags the tip by several seconds. If you’re watching live, you want confirmed.


Step 2: Extract token changes

For each transaction, I need to know who paid the fee and how their token balances changed.

The fee payer is always the first account key in the transaction message. The token changes are in meta.preTokenBalances and meta.postTokenBalances.

I wrote a helper that compares the two and returns a map of mint to delta for a specific owner. Keep it simple. You don’t need a full accounting engine.

import type { VersionedBlockResponse } from '@solana/web3.js'

type BlockTx = VersionedBlockResponse['transactions'][number]

function getTokenDeltas(tx: BlockTx, owner: string): Map<string, number> {
  const deltas = new Map<string, number>()
  if (!tx.meta) return deltas

  const preBalances = tx.meta.preTokenBalances ?? []
  const postBalances = tx.meta.postTokenBalances ?? []

  for (const post of postBalances) {
    if (post.owner !== owner) continue
    const mint = post.mint
    const pre = preBalances.find(p => p.mint === mint && p.owner === owner)
    const preAmount = pre?.uiTokenAmount?.uiAmount ?? 0
    const postAmount = post.uiTokenAmount?.uiAmount ?? 0
    const delta = postAmount - preAmount
    deltas.set(mint, delta)
  }
  return deltas
}

This gives you the net change for any token the owner touched. If they bought, it’s positive. If they sold, it’s negative.


Step 3: Slide a window of three

Now you look at the block’s transactions in order. You slide a window of three across them.

You flag a potential sandwich when:

  • Transaction i and transaction i+2 have the same fee payer.
  • Transaction i+1 has a different fee payer.
  • All three touch the same mint.
  • The first leg gains that token.
  • The last leg loses that token.
const txs = block.transactions
for (let i = 0; i < txs.length - 2; i++) {
  const t1 = txs[i]
  const t2 = txs[i + 1]
  const t3 = txs[i + 2]

  if (!t1.meta || !t2.meta || !t3.meta) continue
  if (t1.meta.err || t2.meta.err || t3.meta.err) continue

  const payer1 = t1.transaction.message.staticAccountKeys[0].toBase58()
  const payer2 = t2.transaction.message.staticAccountKeys[0].toBase58()
  const payer3 = t3.transaction.message.staticAccountKeys[0].toBase58()

  if (payer1 !== payer3 || payer1 === payer2) continue

  const deltas1 = getTokenDeltas(t1, payer1)
  const deltas2 = getTokenDeltas(t2, payer2)
  const deltas3 = getTokenDeltas(t3, payer1)

  for (const [mint, d1] of deltas1) {
    if (d1 <= 0) continue
    const d2 = deltas2.get(mint)
    const d3 = deltas3.get(mint)
    if (d2 === undefined || d3 === undefined) continue
    if (d2 > 0 && d3 < 0) {
      console.log(`Sandwich detected at slot ${slot}, txs ${i}, ${i+1}, ${i+2}`)
      console.log(`Attacker: ${payer1}`)
      console.log(`Victim: ${payer2}`)
      console.log(`Mint: ${mint}`)
    }
  }
}

This loop is the core. It’s brute force, but it works. You’re scanning a block of over a thousand transactions. That’s still cheap.


Step 4: Estimate profit

You want to know if the attacker actually made money. The easiest way is to look at their SOL or WSOL delta across the front and back legs.

WSOL mint is So11111111111111111111111111111111111111112. If they started with X SOL and ended with Y SOL, the difference is their profit minus fees.

I don’t calculate gas fees perfectly here. I just look at the net SOL change for the attacker across both legs. If it’s positive, they likely profited.

You can refine this later. For spotting patterns, this is enough.


Gotchas you will hit

First, failed transactions. If meta.err is not null, skip it. A sandwich where the middle leg fails is just noise. It looks like a sandwich but nobody lost money except maybe some slippage on the front leg.

Second, multi-hop routes. Aggregators sometimes split your swap across multiple pools. This makes the “same mint” check noisy because you might see different mints involved in what feels like one logical trade. I accept this noise. It’s for spotting patterns, not court evidence.

Third, false positives from normal arbitrage bots. Sometimes two different arbitrageurs happen to touch the same pool in close succession. The fee payer match is strong evidence, but not perfect. I look at a handful of these before I believe it’s a real sandwich.


Running it live

You don’t need to poll every slot if you’re just learning. But if you want to watch it happen in real time, subscribe to slot changes.

connection.onSlotChange((info) => {
  // delay because confirmed commitment lags the tip
  setTimeout(() => {
    fetchAndAnalyzeBlock(info.slot)
  }, 2000)
})

That 2 second delay saves you from race conditions. The RPC might not have the full block data ready the instant the slot lands.

Don’t hammer the RPC. If you’re checking every slot, you’re making a lot of calls. Use the batching techniques I wrote about in my rate limiting post. You don’t need to upgrade your plan if your code is efficient.


How to protect yourself

If you’re on the receiving end, two things help.

Tighten your slippage tolerance. If you set it to 1%, you’re giving the attacker more room. Set it as low as you can afford without failing the trade.

Use a private or protected route. A normal RPC send exposes your transaction to whoever sees it before it lands. Sending through an RPC with MEV protection is the fix.

You don’t need to switch DEXs. You just need to control where your transaction goes before it’s public.


One block is enough

I used to think I needed a fancy indexer to see MEV. I thought I had to build a big pipeline, store history, run complex queries.

I was wrong.

One block and a three-transaction window gets you most of the way there. You can see the attacker, the victim, the mint, and the profit direction in plain text.

It’s not perfect. It misses edge cases. It has noise. But it tells the story clearly enough to understand what’s happening to your funds.

And that’s all I wanted. Proof.