Frontrun or Be Frontrun
Season 2: PROTOCOL ZERO, Chapter 2 | Transaction Ordering Manipulation
Frontrun or Be Frontrun
Season 2: PROTOCOL ZERO, Chapter 2 | Transaction Ordering Manipulation
The oldest MEV strategy isn’t sophisticated. It’s just faster and meaner than you.
Previously in PROTOCOL ZERO…
In Chapter 1, we tore the polite mask off the mempool. We proved it isn’t a quiet waiting room where your transaction sits patiently for the next block. It’s a public, adversarial auction — a screaming pit floor where every pending trade you broadcast is visible to thousands of unblinking bots before it’s ever confirmed. You hit “Swap.” You thought you whispered. You actually shouted into a room full of predators.
This chapter is about what those predators do with the sound of your voice.
Let me paint you the scene.
You’re new. You found a token. The chart looks like a staircase to heaven. You open Uniswap, type in your amount, and click Swap. A little spinner appears. Pending. You lean back, sip your coffee, and feel the warm glow of a man who is about to be early.
Forty milliseconds later — before your coffee cup even reaches the saucer — three bots have already read your transaction, done the math, decided exactly how much money to steal from you, executed two trades around yours, and gone back to scanning for the next sucker.
You weren’t early. You were lunch.
This is the Dark Forest. And in the Dark Forest, there is one law older than smart contracts, older than DeFi, older than Ethereum itself: be faster, or be food.
1. The Auction You Didn’t Know You Entered: The Priority Gas Auction (PGA)
Here’s the thing nobody tells beginners: on Ethereum, gas price is a bribe.
That’s it. That’s the whole trick. When you attach a fee to your transaction, you’re not paying a toll — you’re slipping the bouncer a tip to get in front of the line. The block producer is a greedy, rational animal: it sorts pending transactions by who’s paying the biggest tip and stuffs the fattest bribes in first.
The bots understand this in their bones. So when a bot sees a juicy transaction in the mempool, it doesn’t replace you — it just outbids you. The logic is almost insultingly simple:
attacker.tip = your.tip + ε
Where ε (epsilon) is the tiniest possible amount needed to leapfrog you. One wei more, if that's all it takes. Just enough to make the block producer place the attacker's transaction one slot above yours.
And when two bots both spot the same lunch? They don’t fight with fists. They fight with bribes, in real time, racing each other’s gas price upward in microseconds. This frantic bidding war is the Priority Gas Auction — the PGA. Picture two seagulls screaming over the same chip, except the seagulls are running on co-located servers and the chip is your retirement.
The brutal punchline: most of your “high gas fees” on a busy day aren’t congestion. They’re the wake left behind by bots screaming at each other over your money.
2. Two Flavors of Theft: Displacement vs. Generalized Frontrunning
Not all frontrunning is created equal. There are two species of predator here, and they hunt differently.
Displacement is the simple one. The bot sees an opportunity that only one person can take — an arbitrage gap, a profitable liquidation, a mispriced mint. There’s exactly one prize, and it goes to whoever lands first. So the bot copies your intent, fires it with a higher tip, grabs the prize, and your transaction lands a slot later only to revert with a sad little INSUFFICIENT_OUTPUT_AMOUNT. The opportunity is gone. It didn't share the loot. It displaced you entirely. You're not robbed — you're simply erased.
Generalized Frontrunning is where it gets genuinely creepy. This bot is dumb on purpose. It doesn’t understand your transaction. It doesn’t know if you’re swapping, claiming an airdrop, or minting an NFT. It doesn’t care.
What it does is this: it grabs your raw calldata — the exact bytes of your transaction — copies them verbatim, swaps in its own address, and runs the whole thing in a private simulation (eth_call) against the current state of the chain. Then it asks one single question:
“If I run this exact transaction instead of this person… do I end up richer?”
If the simulation says yes — even by a dollar — the bot fires the cloned transaction with a higher tip and steals an opportunity it doesn’t even comprehend. It’s a parasite with no eyes, no brain, and a perfect nose for profit. It found a $100 bill on the sidewalk by blindly copying the footsteps of the guy who was bending down to pick it up.
3. The Main Event: The Sandwich Attack 🥪
This is the masterpiece. The displacement attack just steals your opportunity. The sandwich attack is more elegant, more cruel: it lets your transaction succeed — it needs your transaction to succeed — and it bleeds you anyway.
To understand it, you need exactly one piece of math. Stay with me, non-coder. This is easier than splitting a dinner bill.
The One Equation That Runs DeFi
A Uniswap V2 pool is just two piles of tokens — say, ETH and USDC. The pool obeys one stubborn rule, the constant-product invariant:
x⋅y=k
x is the amount of ETH in the pool. y is the amount of USDC. And k is a number that must never change during a trade. That's the whole religion. The price of the token is simply the ratio between the two piles.
Here’s the consequence that makes sandwiches possible: the bigger your trade relative to the pool, the worse your price gets. Buy a lot of ETH, and you drain the ETH pile, making the remaining ETH more expensive for the very trade you’re making. This self-inflicted price damage is called slippage.
And because you know slippage exists, your wallet does something fatal: it publishes a parameter called amountOutMin.
*amountOutMinis you saying, out loud, in public: **"I'll accept this trade as long as I get at least THIS much back."***
You think you’re protecting yourself. You’re actually handing the attacker the exact dimensions of how hard they’re allowed to squeeze you before you’ll cancel. You drew them a box and said, “feel free to rob me up to this line.” The bot will rob you to the micron of that line and not a wei further.
The Three-Slice Execution
The attacker wraps your transaction in two of their own. The block ordering is the entire weapon:
TX1 — The Front Slice (BUY): The bot buys the same token you’re about to buy, right before you. This pushes the price up (it ate some of the cheap supply). It paid a fair-ish price.
TX2 — The Victim Swap (YOU): Your transaction now executes against the worse price the bot just created. You still get at least your
amountOutMin— so your trade doesn't revert — but you get the worst legal price possible. Your own buy shoves the price even higher.
TX3 — The Back Slice (SELL): The bot immediately sells the token it bought in TX1, now at the inflated price your trade helped create. It dumps back into the pool, pockets the spread, and vanishes.
The bot bought low, you bought high, the bot sold high. You were the cream in the middle. You provided the price movement; the bot harvested it. And the most diabolical part? Your transaction succeeded. You’ll look at your wallet, see your tokens, and have no idea you were just digested.

4. The Predator’s Weapon, Up Close: The Front Slice Contract
People imagine MEV bots as bloated, complex monsters. They’re the opposite. A front-slice contract is brutally lean, because in a gas auction every wasted opcode is money handed to a competitor. Here’s the conceptual skeleton — stripped of the production paranoia, but honest about the shape:
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
interface IUniswapV2Pair {
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;
}
contract FrontSlice {
address private immutable owner;
constructor() { owner = msg.sender; }
// Called by the bot for TX1 (buy) and TX3 (sell).
// Direct pair.swap() - NO router, NO extra hops, NO mercy.
function strike(
address pair,
uint amount0Out,
uint amount1Out
) external {
require(msg.sender == owner); // 1 SLOAD. that's the only check it can afford.
IUniswapV2Pair(pair).swap(
amount0Out,
amount1Out,
address(this),
new bytes(0) // empty = optimistic, gas-minimal swap
);
}
}
Notice what’s missing. No slippage protection. No deadline. No SafeERC20. No router. The bot doesn’t need a router — routers are for humans who want safety, and safety costs gas. The bot calls the pool directly, because it has already simulated the exact outcome off-chain and knows down to the wei what it will receive. It doesn’t hope. It knows. That single require is the only luxury it permits itself. Everything else is shaved to the bone, because in the PGA, the leaner contract bids higher and lands first.
That’s the asymmetry of the Dark Forest in one code block: you are protected and slow. The bot is naked and instant.
5. Auditor’s Fix / Defense Architecture
So how do you survive a forest where the predators are faster, leaner, and watching your every broadcast? You don’t outrun them. You stop broadcasting where they can hear you, and you shrink the box you draw for them.
Defense 1 — Go dark. Route through Private Relays.
The sandwich attack has a single point of failure: the bot must see your transaction in the public mempool before it lands. No visibility, no sandwich. So don’t send your transaction to the public mempool at all.
Services like Flashbots Protect route your transaction through a private channel directly to block builders. It never touches the public auction floor. The predators are scanning an empty room. You walked through the forest in a cloaking field — they can’t clamp what they can’t see. This is the single most effective defense in existence, and it’s a one-time RPC change in your wallet.
// The cloak is a single RPC endpoint swap. That's it.
Network Name: Flashbots Protect
RPC URL: https://rpc.flashbots.net
Chain ID: 1
Defense 2 — Tighten your slippage. Shrink the box.
Remember: amountOutMin is the line the bot squeezes you to. A sandwich is only worth executing if the profit margin clears the bot's gas and risk. So shrink the margin. A 0.1%–0.5% slippage tolerance leaves so little room between your expected price and your minimum that there's no meat left on the bone — the attack costs the bot more in gas than it can extract. The trade-off: too tight, and legitimate price movement makes your trade revert. The art is finding the floor where you're protected but still executable. Default 5% slippage on a thin pool isn't a setting — it's a donation.
Defense 3 — Architectural, for protocol builders. If you’re writing the contract, don’t trust user-supplied amountOutMin as your only shield. Consider on-chain TWAP oracles for sanity bounds, commit-reveal schemes to hide intent until execution, or batch auction settlement (à la CoW Protocol) that eliminates intra-block ordering as an attack surface entirely. The endgame is to remove ordering itself as a thing money can be extracted from.
The Takeaway
Frontrunning isn’t a bug. It’s not a hack. Nobody is breaking the rules — the predators are following them perfectly, just faster than you can. That’s what makes it the oldest and most permanent strategy in the Dark Forest.
Burn these four into memory:
- Gas is a bribe, and the Priority Gas Auction is a real-time bidding war fought in microseconds over your transaction —
attacker.tip = your.tip + ε. - Displacement erases you; Generalized Frontrunning clones you — sometimes blindly, by copying raw calldata and simulating profit without even understanding what your transaction does.
- The sandwich weaponizes your own
amountOutMin. The slippage parameter you set to protect yourself is the exact map the attacker uses to rob you to the legal limit — while letting your trade succeed so you never notice. - You survive by going invisible (private relays) and shrinking the box (tight slippage). You cannot win the speed war. You can only refuse to fight it in the open.
The public mempool is not your friend. It never was. In the Dark Forest, the loudest transaction gets eaten first — and until now, you’ve been screaming.
Next chapter, we go deeper. Because frontrunning is the honest predator. The ones that hide inside the contract you trusted? Those are the Shadow Contracts.
🔌 Let’s Connect
PROTOCOL ZERO is a hands-on Web3 security masterclass for engineers, auditors, and searchers who refuse to be the merchandise. If this chapter sharpened your threat model, follow along — Season 2 only goes deeper.
👏 Clap to boost visibility for fellow builders. 🔖 Bookmark the series — Chapter 3 drops next. 💬 Drop your war stories in the comments. The best mempool horror story gets dissected live. 🛰️ Find me across the security research community — I respond to every serious technical question.
Stay paranoid. Stay precise. The auction never sleeps.
메타데이터
- post_id
- ef8b11dc75db
- slug
- frontrun-or-be-frontrun-ef8b11dc75db
- url
- https://blog.blockmagnates.com/frontrun-or-be-frontrun-ef8b11dc75db
- canonical_url
- https://blog.blockmagnates.com/frontrun-or-be-frontrun-ef8b11dc75db
- author_url
- https://medium.com/@hunterx461
- status
- ok
- fetched_at
- 2026-07-09 03:40:04