Crypto Bots

How to Build a MEV Bot on Ethereum: The Complete 2026 Guide

MEV (Maximal Extractable Value) bots extract profit from Ethereum block ordering. This guide explains how MEV works, the types of MEV strategies, and how to build a basic sandwich bot with Flashbots.

A
AI Agents Hubยท2026-03-24ยท4 min readยท732 words

Builder of AI agents, crypto trading bots, and open-source automation tools. Sharing practical guides on how to build, deploy, and profit from AI and DeFi technology.

What Is MEV and Why Does It Matter?

Maximal Extractable Value (MEV) is the profit miners and validators can capture by reordering, inserting, or censoring transactions within blocks they produce. Since Ethereum's merge to Proof of Stake, validators have taken over this role from miners โ€” but the opportunity is the same.

In 2025, over $1.5 billion in MEV was extracted on Ethereum alone. MEV bots operate in a dark forest where milliseconds matter and every pending transaction is a potential profit opportunity.

Types of MEV Strategies

1. Sandwich Attacks

The most common MEV strategy. A bot:

  1. Detects a large pending swap in the mempool
  2. Inserts a buy transaction before the target (front-run)
  3. Lets the target execute, moving the price up
  4. Inserts a sell transaction after (back-run)

Net result: profit from the price impact caused by the target's trade.

2. Arbitrage MEV

Pure arbitrage between DEXs within a single block. No front-running required. A bot spots a price discrepancy between Uniswap V3 and Curve, then executes both sides atomically.

3. Liquidation MEV

DeFi protocols like Aave and Compound allow anyone to liquidate undercollateralized positions for a bonus. MEV bots monitor health factors and race to trigger liquidations first.

4. JIT (Just-in-Time) Liquidity

Provide liquidity to a Uniswap V3 pool just before a large swap, capture the trading fees, then remove liquidity immediately after. Requires precise block-level timing.

Setting Up Flashbots

Flashbots created a private transaction relay that lets you submit "bundles" directly to validators โ€” bypassing the public mempool and avoiding front-runners front-running you.

npm install @flashbots/ethers-provider-bundle ethers
import { FlashbotsBundleProvider } from '@flashbots/ethers-provider-bundle'
import { ethers } from 'ethers'

const FLASHBOTS_RELAY = 'https://relay.flashbots.net'

async function setupFlashbots() {
  const provider = new ethers.JsonRpcProvider(process.env.ETH_RPC_URL)
  const authSigner = new ethers.Wallet(process.env.FLASHBOTS_AUTH_KEY!, provider)
  
  const flashbotsProvider = await FlashbotsBundleProvider.create(
    provider,
    authSigner,
    FLASHBOTS_RELAY
  )
  
  return flashbotsProvider
}

Building a Basic Arbitrage MEV Bot

import { ethers, Contract } from 'ethers'

const UNISWAP_V2_ROUTER = '0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D'
const SUSHISWAP_ROUTER = '0xd9e1cE17f2641f24aE83637ab66a2cca9C378B9F'

interface PriceQuote {
  price: bigint
  path: string[]
}

async function checkArbitrage(
  tokenA: string,
  tokenB: string,
  amountIn: bigint
): Promise<{ profit: bigint; route: string } | null> {
  
  const uniPrice = await getQuote(UNISWAP_V2_ROUTER, tokenA, tokenB, amountIn)
  const sushiPrice = await getQuote(SUSHISWAP_ROUTER, tokenA, tokenB, amountIn)
  
  // Buy on cheaper DEX, sell on more expensive
  if (uniPrice.price > sushiPrice.price) {
    const profit = uniPrice.price - amountIn - estimateGasCost()
    if (profit > 0n) {
      return { profit, route: 'buy-sushi-sell-uni' }
    }
  }
  
  return null
}

Mempool Monitoring

To detect sandwich opportunities, you need to monitor pending transactions:

const provider = new ethers.WebSocketProvider(process.env.WS_RPC_URL!)

provider.on('pending', async (txHash: string) => {
  const tx = await provider.getTransaction(txHash)
  if (!tx) return
  
  // Check if this is a Uniswap swap
  if (tx.to?.toLowerCase() === UNISWAP_V3_ROUTER.toLowerCase()) {
    const decoded = decodeSwapCalldata(tx.data)
    if (decoded && decoded.amountIn > MIN_SANDWICH_SIZE) {
      await attemptSandwich(tx, decoded)
    }
  }
})

Gas Optimization: The Key to MEV Profitability

MEV is a gas war. Your bot must:

  1. Use private mempools (Flashbots, Eden Network) to avoid failed transactions eating gas
  2. Simulate transactions before submitting โ€” never pay gas on a failed arb
  3. Set priority fees dynamically โ€” use eth_maxPriorityFeePerGas and add a small premium
async function getOptimalGasPrice(competitiveness: number): Promise<bigint> {
  const feeData = await provider.getFeeData()
  const baseFee = feeData.maxFeePerGas!
  
  // Add 10-20% premium based on how competitive this opportunity is
  const premium = BigInt(Math.floor(Number(baseFee) * competitiveness))
  return baseFee + premium
}

Is MEV Still Profitable in 2026?

Yes โ€” but it's increasingly competitive. The "dark forest" is crowded with sophisticated bots. Profitable MEV today requires:

  • Low-latency RPC nodes (Alchemy, QuickNode, or your own geth/reth instance)
  • Flashbots or private mempools for atomic bundle submission
  • Fast simulation (use Tenderly or local forked state)
  • Capital efficiency โ€” MEV bots need ETH/WETH float to execute trades

Beginners can still find opportunities in long-tail token pairs and smaller DEXs where competition is lower. Focus on Uniswap V3 pools with low liquidity and high volume.

Ethical Considerations

Sandwich attacks are controversial โ€” they directly harm retail traders by increasing their slippage. Many in the DeFi community consider them predatory. If you're building MEV strategies, consider focusing on pure arbitrage (which improves price efficiency) rather than sandwiching retail users.

Further Reading

Related Articles