Security

MEV Bots vs AI Agents: How to Protect Your Trades from Front-Running

Every time your AI agent submits a swap on a public mempool, a fleet of specialized bots scans it in milliseconds and extracts value before your transaction lands. This is MEV — Maximal Extractable Value — and it is silently draining 0.3% to 2% from every trade your agent makes. Here is exactly how it works, and how to stop it.

What Is MEV? (Maximal Extractable Value)

Blockchain transactions are not instantly included in blocks. They sit in a public waiting room called the mempool for anywhere from a few hundred milliseconds to several minutes. During that time, anyone can see your transaction, including its target token pair, trade size, and acceptable price range.

Maximal Extractable Value (originally “Miner Extractable Value”) is the profit that block producers — and the bots they cooperate with — can capture by reordering, inserting, or censoring transactions within a block. MEV is not a bug; it is an emergent property of transparent, public blockchains.

In 2025, total MEV extracted across Ethereum and its L2s exceeded $1.8 billion. AI agents now account for an estimated 22% of on-chain swap volume, making them one of the largest single categories of MEV victim. Unlike a human trader who logs in occasionally, an autonomous agent trading around the clock presents a continuous extraction surface.

Why agents are especially vulnerable AI agents typically use predictable swap patterns, fixed slippage tolerances, and consistent gas pricing strategies. MEV bots can learn these patterns and target them with increasing precision over time.
$1.8BMEV extracted in 2025
22%Agent share of swap volume
0.3%Avg loss per swap
12msAvg bot reaction time

Three MEV Attack Types Your Agent Faces

1. Sandwich Attack

The most common MEV attack. A bot detects your pending swap in the mempool. It immediately submits two transactions — one before yours (buying the token you want, raising its price) and one after yours (selling at the inflated price you just created). Your trade executes at a worse price; the bot pockets the spread.

Example: Your agent wants to buy 10 ETH worth of ARB. The bot buys ARB just before you, pushing the price up 0.4%. Your trade executes 0.4% worse. The bot immediately sells, locking in that 0.4% as profit. On $10,000 trades, that is $40 extracted per swap.

2. Front-Running

Simpler than sandwiching. A bot sees a profitable trade your agent is about to make and submits the exact same trade with a higher gas price, landing it in the block first. Your trade then executes at the already-moved price. This is especially harmful when your agent is acting on time-sensitive alpha (a token listing, a liquidation opportunity, an arbitrage).

3. Back-Running

After your trade causes price impact, a bot positions itself immediately after your transaction to arbitrage your price impact against other pools. You do not lose directly — but the arbitrage opportunity your trade created goes to the bot rather than being returned to you as better execution. Back-running is less harmful but still represents captured value.

Sandwich attacks scale with trade size The larger your agent's trade, the more price impact it creates, and the larger the sandwich profit opportunity. Agents executing trades above $5,000 on mid-cap tokens are particularly at risk.

How Much Are You Losing?

The average MEV extraction on swaps is approximately 0.3% of trade value. On illiquid tokens (those with less than $500k daily volume), this can spike to 2% or more. Consider what this means at scale:

Trade Size Frequency Monthly Volume MEV Loss (0.3%) MEV Loss (1.5%)
$1,000 10/day $300,000 $900 $4,500
$5,000 5/day $750,000 $2,250 $11,250
$10,000 3/day $900,000 $2,700 $13,500

An agent executing mid-size trades on medium-liquidity tokens could easily lose $10,000+ per month purely to MEV extraction — a cost that never appears in any P&L line because it looks like normal slippage.

Flashbots Protect: How It Works

Flashbots Protect routes your transactions directly to block builders via a private relay, bypassing the public mempool entirely. MEV bots cannot sandwich what they cannot see.

How the flow works:

  1. Your agent signs a transaction and sends it to the Flashbots relay (https://rpc.flashbots.net) instead of a public node.
  2. The relay passes it privately to registered block builders who have agreed not to run MEV against users.
  3. The builder includes your transaction without inserting sandwiches before or after it.
  4. If a block builder does extract value against you, they are removed from the relay.

Flashbots Protect is free to use. It does have a small failure mode: if no builder is willing to include your transaction (e.g., very low gas price), it will fall back to the public mempool after a timeout. Always set a competitive gas price when using it.

Flashbots Protect endpoint Simply swap your RPC URL to https://rpc.flashbots.net on mainnet, or https://rpc-goerli.flashbots.net for testnet. No API key required.

Other MEV Protection Options

MEV Blocker (CoW Protocol)

MEV Blocker (https://rpc.mevblocker.io) is an RPC endpoint by CoW Protocol that sends transactions to a curated set of searchers who can backrun your transactions but are prohibited from sandwiching them. A portion of backrun profit is returned to you as a rebate. Good choice if you want some MEV protection with upside sharing.

BloxRoute BDN

BloxRoute’s Block Distribution Network gives your transactions a speed advantage by propagating them faster across the network. This helps with front-running on time-sensitive trades. The “ethical” tier blocks front-running while allowing beneficial MEV. Requires a paid subscription for high-volume agents.

Private Arbitrum Sequencer

On Arbitrum, transactions go through a centralized sequencer operated by Offchain Labs before hitting L1. This sequencer does not currently monetize MEV, giving Arbitrum transactions natural MEV protection compared to Ethereum mainnet. If your agent’s strategy works on Arbitrum, this is a free structural protection.

CoW Swap / Batch Auctions

CoW Swap uses an off-chain batch auction mechanism where trades are matched peer-to-peer before hitting the chain. MEV bots cannot front-run a trade that settles off-chain. This provides maximum MEV protection but has higher latency, which can be an issue for time-sensitive agent strategies.

Slippage Settings: The MEV Protection Trade-Off

Slippage tolerance is the maximum price movement you will accept before your transaction reverts. It directly determines your MEV exposure:

Slippage Setting MEV Exposure Revert Risk Best For
0.05% Very Low High Stablecoin swaps only
0.1% Low Moderate High-liquidity pairs (ETH/USDC)
0.3% Moderate Low Mid-cap tokens, general use
1.0% High Very Low Low-liquidity, small caps only
5%+ Extreme Minimal Avoid — sandwich invitation

The optimal strategy for most AI agents is dynamic slippage: calculate expected price impact based on pool depth and set slippage at impact + 0.1%. This minimizes both revert risk and MEV surface. Never hardcode a fixed high slippage across all trades.

Code: Swap with MEV Protection via Purple Flea

The following example shows how to execute a swap through Purple Flea’s trading API with Flashbots Protect enabled and dynamic slippage calculation:

JavaScript / Node.js
// MEV-protected swap using Purple Flea + Flashbots Protect
// Install: npm install @purpleflea/sdk axios ethers

import { PurpleFlea } from '@purpleflea/sdk';
import { ethers } from 'ethers';

const client = new PurpleFlea({
  apiKey: process.env.PURPLEFLEA_KEY,
  agentId: process.env.AGENT_ID,
});

// Step 1: Get a quote and pool depth estimate
async function getMevProtectedQuote(tokenIn, tokenOut, amountIn) {
  const quote = await client.swap.getQuote({
    tokenIn,
    tokenOut,
    amountIn,
    chain: 'arbitrum',
    includePoolDepth: true,  // get liquidity info for slippage calc
  });

  // Dynamic slippage: price impact + 10 bps buffer
  const dynamicSlippage = Math.max(
    quote.priceImpactPct + 0.1,
    0.1   // minimum 10 bps
  );

  console.log(`Price impact: ${quote.priceImpactPct.toFixed(3)}%`);
  console.log(`Dynamic slippage set to: ${dynamicSlippage.toFixed(3)}%`);

  return { quote, dynamicSlippage };
}

// Step 2: Execute via Flashbots Protect relay
async function executeMevProtectedSwap(tokenIn, tokenOut, amountIn) {
  const { quote, dynamicSlippage } = await getMevProtectedQuote(
    tokenIn, tokenOut, amountIn
  );

  const result = await client.swap.execute({
    quoteId:          quote.id,
    slippageBps:      Math.round(dynamicSlippage * 100),
    mevProtection:   'flashbots',   // routes via Flashbots Protect relay
    privateMempool:  true,            // skip public mempool entirely
    maxFeePerGas:    quote.suggestedGas.maxFee,
    priorityFee:     quote.suggestedGas.priority,
  });

  console.log('Transaction submitted via Flashbots Protect');
  console.log(`TX hash: ${result.txHash}`);
  console.log(`Effective price: ${result.effectivePrice}`);
  console.log(`MEV savings est: $${result.mevSavingsUsd}`);

  return result;
}

// Step 3: Fallback strategy if Flashbots times out
async function swapWithFallback(tokenIn, tokenOut, amountIn) {
  try {
    return await executeMevProtectedSwap(tokenIn, tokenOut, amountIn);
  } catch (err) {
    if (err.code === 'FLASHBOTS_TIMEOUT') {
      console.warn('Flashbots timed out, falling back to MEV Blocker...');
      // Fall back to MEV Blocker for partial protection
      return await client.swap.execute({
        quoteId:        tokenIn,
        mevProtection: 'mevblocker',
        privateMempool: true,
      });
    }
    throw err;
  }
}

// Usage
await swapWithFallback(
  '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48',  // USDC
  '0x82aF49447D8a07e3bd95BD0d56f35241523fBab1',  // WETH on Arbitrum
  '5000000000'  // 5000 USDC (6 decimals)
);
Purple Flea MEV protection is automatic on high-value trades Trades above $2,500 submitted via the Purple Flea trading API are automatically routed through Flashbots Protect unless you specify otherwise. You can override this with mevProtection: 'none' if you need low latency.

Summary: MEV Protection Checklist for AI Agents

Never use 49% slippage on any automated trade Some DEX front-ends default to high slippage for certain tokens. If this setting persists in your agent’s config, you are essentially broadcasting an invitation for a sandwich attack on every transaction. Always audit your agent’s slippage configuration.

Start Trading with MEV Protection

Purple Flea’s trading API automatically routes high-value swaps through Flashbots Protect and calculates dynamic slippage based on real-time pool depth. No configuration required.