Building MEV Bots: Arbitrage & Sandwich

Learning Goal:
This curriculum is designed to guide you from blockchain fundamentals to the engineering of high-performance Maximum Extractable Value (MEV) searcher bots. By the end of this course, you will be able to monitor the Ethereum mempool via WebSockets, identify arbitrage and sandwich opportunities, write gas-optimized execution smart contracts in Solidity and Yul, and privately submit transaction bundles using Flashbots.

  • Prerequisites: Intermediate programming experience (JavaScript/Node.js or Python) and basic familiarity with terminal commands. Prior exposure to web development or financial concepts is helpful but not required.
  • Estimated Total Study Time: 38 Hours

Module 1: Blockchain & Ethereum Foundations

This module introduces the underlying architecture of the Ethereum blockchain. You will learn how peer-to-peer state machines record transactions, how block-building mechanics function, and how the critical concept of "gas" acts as both a system resource and an execution priority fee.

Recommended Videos

  • Why this video: This video provides a direct, accessible high-level visualization of Ethereum as a decentralized global computer. It establishes the baseline concept of smart contracts—applications that execute autonomously exactly as programmed—which are the building blocks of decentralized finance (DeFi) systems.

  • Why this video: A deeper structural dive into the mechanics of Ethereum. It contrasts the platform with Bitcoin's transactional model and breaks down how decentralized applications (dApps) execute on the Ethereum Virtual Machine (EVM).

  • Why this video: Understanding gas is paramount for MEV searchers. This video explains how transactions are sent to the mempool—the pending holding area—and how block builders (miners/validators) pick transactions based on who pays the highest gas fee. This sets up the conceptual groundwork for bid-wars and transaction ordering.

Knowledge Checkpoint

  • Understand the role of the Ethereum Virtual Machine (EVM) in processing smart contract bytecode.
  • Differentiate between Base Fee, Max Fee, and Priority Fee (EIP-1559).
  • Explain how a transaction moves from a local wallet, through the public peer-to-peer mempool, and into an on-chain block.
  • Identify how high network congestion affects gas prices and execution priority.

Module 2: Smart Contracts & Decentralized Exchanges (AMMs)

To extract value, searchers must understand where it resides: Decentralized Exchanges (DEXs) operating as Automated Market Makers (AMMs). This module covers the programming of Ethereum smart contracts in Solidity and the mathematical invariants (like the constant product formula xy=kx \cdot y = k) that govern pools like Uniswap V2 and V3.

Recommended Videos

  • Why this video: A highly structured, developer-focused introduction to Solidity, contract compilation, deployment, and execution within the EVM sandbox. It bypasses superficial hand-waving and shows you how smart contract state is declared and modified.

  • Why this video: This video walks through the exact constant product math model (xy=kx \cdot y = k) that dictates trade pricing, slippage, and liquidity on Uniswap V2 and clone exchanges. A firm grasp of this formula is vital for calculating arbitrage profits.

  • Why this video: A practical explanation of how token pricing scales with shifts in reserves. It details how trades mathematically push prices up or down, laying the groundwork for identifying mispriced liquidity pools.

  • Why this video: A solid introduction to the smart contract architecture of Uniswap. It explains the relationship between the Factory contracts (which deploy pools) and Router contracts (which handle swap execution pathways), demonstrating how developers programmatically route trades.

Knowledge Checkpoint

  • Write, compile, and deploy a simple Solidity contract using Remix IDE.
  • Calculate the expected output of a trade using the formula: y=rΔxyx+rΔxy = \frac{r \cdot \Delta x \cdot y}{x + r \cdot \Delta x} (where rr is fee adjustment, e.g., 0.9970.997).
  • Understand the difference between Uniswap V2 (infinite liquidity curves) and Uniswap V3 (concentrated liquidity ticks).
  • Define slippage tolerance and explain how it creates trade vulnerabilities.

Module 3: Introduction to MEV & Mempool Monitoring

This module moves into the "Dark Forest" of Ethereum. You will study how Maximal Extractable Value is created by transaction ordering. Additionally, you will build your first tooling component: a real-time pending-transaction tracker that connects to a node provider using WebSockets.

Recommended Videos

  • Why this video: A masterclass on the concept of MEV. It details frontrunning, backrunning, sandwich attacks, and liquidations. It explains how miners and searchers extract profit directly from the flexibility of block creation.

  • Why this video: A documentary-style investigation into the competitive world of searchers. It introduces the "Dark Forest" concept (based on the paradigm-defining Paradigm article) and highlights how public mempool transactions are scanned and frontrun by generalized predators.

  • Why this video: This is a crucial technical guide. It walks you through setting up a WebSocket connection using Ethers.js to subscribe to and stream pending transactions directly from the mempool. This is the sensory organ of your MEV bot.

  • Why this video: A technical visualization of how a sandwich attack is constructed: detecting a high-slippage victim transaction, frontrunning it (paying higher gas to buy first), and backrunning it (paying normal gas to sell immediately after the price has been pushed up).

Knowledge Checkpoint

  • Draw a visual sequence diagram showing the step-by-step transaction flow of a sandwich attack.
  • Write a script in JavaScript/TypeScript using Ethers.js to listen to pending transactions and filter transactions targeting known AMM Router addresses.
  • Understand why public mempool frontrunning is highly vulnerable to "sandwiching the sandwicher" traps (poison tokens).

Module 4: Flashbots & Private Transaction Submission

Submitting transactions to the public mempool makes you prey to other searchers. This module introduces Flashbots and MEV-Boost. You will learn how to bypass the public mempool entirely by constructing and submitting private transaction "bundles" directly to block builders.

Recommended Videos

  • Why this video: An educational talk from ETHGlobal detailing Flashbots' core goals: mitigating negative externalities of MEV, democratizing extraction, and explaining how searchers interact with the Flashbots builder network.

  • Why this video: A developer-focused walkthrough on how to structure a transaction bundle. It explains the mechanics of setting up the Ethers.js Flashbots provider, formatting multiple transactions to execute in strict consecutive order, and ensuring atomic execution.

  • Why this video: A practical demonstration of using Flashbots bundles in high-demand, competitive situations. While the context here is an NFT mint, the technical implementation of bundle construction, signing, and gas/priority bidding matches what arbitrage bots use.

Knowledge Checkpoint

  • Explain how a Flashbots bundle achieves "all-or-nothing" (atomic) execution guarantees.
  • Understand why submitting a transaction via Flashbots protects it from being frontrun in the public mempool.
  • Describe the bribe mechanism (direct contract transfer to block.coinbase) used to pay builders without using public gas auctions.

Module 5: Coding Arbitrage & Sandwich Bots

This module is the practical engine of the curriculum. You will analyze production-grade searcher templates, study Uniswap V3 flash swap logic, and work through mathematical optimizations for price discrepancies.

🚨 Critical Developer Warning: The YouTube ecosystem is flooded with "Passive Income MEV Bot" scams (frequently using clickbait titles like "AI Arbitrage Bot", "1k Per Day", or "Remix Solidity copy-paste").

These videos are phishing scams designed to steal your funds. They prompt you to copy obfuscated Solidity code into Remix and fund it with ETH. Once funded, the contract transfers your assets directly to the scammer's wallet.

Never run code you do not fully understand. Always audit external smart contracts line-by-line. Real MEV bots require custom off-chain searcher code paired with custom on-chain execution contracts.

Recommended Videos

  • Why this video: This is a comprehensive, production-grade guide hosted by Flashbots product lead Robert Miller. This code walkthrough examines the architecture of a real, open-source Flashbots arbitrage bot. It explains the mechanics of state scanning, calculation of price differentials across pools, and bundle packaging.

  • Why this video: A structured step-by-step Solidity tutorial showcasing how to perform a flash swap arbitrage between Uniswap V3 pools. It shows you how to borrow from one pool, swap through another pool, repay the loan, and keep the price difference—all within a single atomic transaction.

  • Why this video: An exploration of the mathematical algorithms required to capture arbitrage value when pricing ranges are disjoint or overlapping. It teaches you how to calculate the optimal trade input size to maximize arbitrage yields rather than over-slipping yourself.

  • Why this video: This video covers the integration of a JS/TS searcher engine with Uniswap V3 smart contracts, demonstrating the implementation of the exactInputSingleSwap execution flow.

Knowledge Checkpoint

  • Set up a local test environment (Hardhat or Foundry) to fork Ethereum mainnet.
  • Build an execution contract that accepts flash loans or flash swaps to execute multi-pool arbitrage.
  • Implement mathematical calculations in your searcher script to find the optimal trade size (SoptS_{\text{opt}}) for an arbitrage pathway.
  • Audit all execution contracts line-by-line to guarantee they contain no hardcoded backdoors, malicious libraries, or unexpected transfer calls.

Module 6: Gas Optimization & Advanced Execution

In the MEV world, a single extra gas unit can make your bid uncompetitive. This final module details advanced Solidity optimization techniques, low-level EVM assembly (Yul), and real-world considerations for navigating competitive searcher markets.

Recommended Videos

  • Why this video: A comprehensive tutorial on reducing gas footprint. It focuses on EVM storage layout, memory caching, optimization of variables, and avoiding redundant execution operations. These techniques are vital for reducing the execution cost of your MEV smart contracts.

  • Why this video: Real-world MEV executors are rarely written in vanilla, high-level Solidity. This video introduces Yul, the low-level intermediate assembly language for the EVM. Writing in Yul lets you bypass high-level compiler overhead, manually manage memory offsets, and execute hyper-optimized calls.

Gap Analysis & Independent Research

Because MEV strategies are highly competitive, advanced searchers keep their gas-optimization techniques proprietary. To optimize your contracts to a professional level, supplement this video material with independent study of the following concepts:

  • Huff Language: Learn the Huff assembly framework, which lets you write smart contracts directly in EVM opcodes for maximum gas savings.
  • Custom Router Bypass: Analyze how to call token pools directly using UniswapV2Pair.swap() instead of routing through standard Router contracts to bypass unnecessary storage reads and logic branches.
  • Cold vs. Warm Storage: Study the gas cost changes introduced in EIP-2929 to understand how reading state multiple times in a transaction affects your gas usage.

Knowledge Checkpoint

  • Understand the gas cost difference between sstor (modifying state variables) and memory-based operations.
  • Write a basic Yul block inside a Solidity function to perform a low-level, gas-optimized function call.
  • Explain how gas optimization impacts the price-competitiveness of a Flashbots bundle bid.
  • Identify and eliminate redundant state checks (such as using unchecked math for increments) inside your contract execution code.

Course Map

This visual diagram outlines the progression of concepts throughout this curriculum:


Key People Index

  • Vitalik Buterin: Co-founder of Ethereum. His original designs for the EVM and subsequent work on scalability (and gas structures) shape the current MEV landscape.
  • Tomasz K. Stańczak: Founder of Nethermind and active MEV/Flashbots researcher. Known for his work analyzing on-chain transaction flows and client execution efficiency.
  • Robert Miller: Product Lead at Flashbots. A prominent researcher on MEV mechanics, known for writing detailed analyses of block-building and walking developers through searcher repositories.
  • Andreas M. Antonopoulos: Renowned computer scientist and author of Mastering Ethereum. His educational series on mempool dynamics and peer-to-peer systems remains a foundational resource for the industry.

Final Self-Assessment

Review this list of core skills to assess your knowledge of MEV development:

  • Explain the step-by-step path of a pending transaction from the public mempool to its inclusion in a block.
  • Calculate pool exchange outputs mathematically using the constant product formula (xy=kx \cdot y = k) for a given trade input.
  • Set up a live Node.js/Rust script that connects to an Ethereum node provider via WebSockets and listens to pending mempool transactions.
  • Set up, configure, and sign a private Flashbots bundle consisting of a frontrun, victim, and backrun transaction.
  • Explain the mechanism of flash loans and build an execution smart contract capable of executing an atomic flash-swap arbitrage.
  • Successfully run unit tests on a mainnet fork (e.g., Hardhat/Foundry) demonstrating a complete arbitrage cycle.
  • Identify and explain at least three standard Solidity gas-optimization techniques (e.g., storage slot packing, memory caching, using unchecked).
  • Audit an unfamiliar solidity contract to ensure it contains no malicious fallback loops, fee-on-transfer traps, or backdoor balance-draining mechanisms.
Explore Further

Related Blockchain & Crypto Roadmaps

View All