Free 30-min Web3 Consultation
Book Consultation
Smart Contract Security Audits
View Audit Services
Custom DeFi Protocol Development
Explore DeFi
Full-Stack Web3 dApp Development
View App Services
Free 30-min Web3 Consultation
Book Consultation
Smart Contract Security Audits
View Audit Services
Custom DeFi Protocol Development
Explore DeFi
Full-Stack Web3 dApp Development
View App Services
Free 30-min Web3 Consultation
Book Consultation
Smart Contract Security Audits
View Audit Services
Custom DeFi Protocol Development
Explore DeFi
Full-Stack Web3 dApp Development
View App Services
Free 30-min Web3 Consultation
Book Consultation
Smart Contract Security Audits
View Audit Services
Custom DeFi Protocol Development
Explore DeFi
Full-Stack Web3 dApp Development
View App Services
LABS
Guides

Setting Up a Simulation Lab for Testing MEV Attack Vectors

A technical guide for developers to build a controlled, forked environment to simulate, analyze, and defend against MEV attacks like front-running and arbitrage before mainnet deployment.
Chainscore © 2026
introduction
INTRODUCTION

Setting Up a Simulation Lab for Testing MEV Attack Vectors

A practical guide to building a controlled environment for analyzing and understanding Maximal Extractable Value (MEV) risks.

Maximal Extractable Value (MEV) represents the profit that can be extracted by reordering, including, or censoring transactions within a block. To study these complex attack vectors—like sandwich attacks, arbitrage, or time-bandit attacks—in a safe and reproducible manner, you need a dedicated simulation lab. This environment allows you to replay historical mainnet states, deploy custom smart contracts, and script malicious searcher bots without risking real funds or impacting live networks. Tools like Foundry, Hardhat, and Ganache form the foundation of such a lab.

The core of your MEV simulation setup is a local Ethereum node that can be forked from a specific block. Using Foundry's anvil command (anvil --fork-url <RPC_URL> --fork-block-number <BLOCK>) creates a local testnet identical to mainnet at that point in time. This gives you a sandbox with real contract addresses, token balances, and mempool dynamics. You can then write and deploy attacker contracts in Solidity using Foundry's forge to simulate frontrunning logic or analyze the profitability of a specific arbitrage opportunity observed on-chain.

To simulate the broader MEV supply chain, you'll need to model key actors: searchers (who find opportunities), builders (who construct blocks), and relays (who facilitate communication). You can use the mev-inspect-py library to parse historical blocks and identify past MEV transactions. For simulating builder behavior, tools like Flashbots' mev-boost-relay can be run locally. Scripting the interaction between these components in Python or TypeScript allows you to test how changes to transaction ordering or block construction algorithms affect extractable value.

A critical step is creating reproducible attack scenarios. Start by forking from a block number where a known MEV event occurred, such as a large DEX swap vulnerable to a sandwich. Write a searcher bot that monitors the local mempool (via anvil's RPC), calculates a profitable frontrun, and submits a bundle. Use Foundry's forge scripts to automate this process and forge test to assert the financial outcome. This method turns abstract MEV concepts into tangible, executable code, providing deep insight into the economic incentives and technical execution of these strategies.

Finally, your lab should include analysis and visualization tools. After running simulations, use Ethers.js or Viem to query transaction traces and calculate profit in USD. Libraries like Pandas can help analyze data across multiple simulation runs. The goal is to move from observing MEV to understanding its precise mechanics and, ultimately, designing more robust systems—like fair ordering protocols or SUAVE—that can mitigate its negative externalities. This hands-on approach is essential for developers and researchers aiming to secure the next generation of decentralized applications.

prerequisites
PREREQUISITES AND SETUP

Setting Up a Simulation Lab for Testing MEV Attack Vectors

A controlled, isolated environment is essential for safely analyzing and understanding MEV attack vectors like sandwich attacks, arbitrage, and time-bandit attacks.

Before simulating any MEV attack, you need a foundational software stack. This includes Node.js (v18+), Python (v3.10+), and a package manager like npm or yarn. You will also need Git for cloning repositories and a code editor such as VS Code. For blockchain interaction, install the Foundry toolkit, which provides forge, cast, and anvil—essential tools for compiling, testing, and deploying smart contracts on a local network. Anvil, Foundry's local testnet node, will be the core of your simulation lab.

The next step is to set up your primary simulation environment. Clone the Foundry repository and install it using the foundryup command. Once installed, start an Anvil instance with anvil. This spins up a local Ethereum node with deterministic accounts pre-funded with test ETH, perfect for replaying transactions. You should also install Ganache as an alternative for more GUI-focused testing and Hardhat if you plan to work with more complex development environments. Configure your environment variables, such as RPC_URL (pointing to http://localhost:8545) and PRIVATE_KEY (using one of Anvil's provided keys).

To simulate real-world conditions, you need access to historical blockchain data. Use services like Alchemy or Infura to get archive node access via their free tiers, or run a local Erigon or Geth node with full archival data. For MEV-specific data, query the Flashbots MEV-Share API or the EigenPhi dashboard to analyze past attack transactions. You can also use the cast command from Foundry to fork mainnet state directly into your Anvil instance with anvil --fork-url $MAINNET_RPC_URL, allowing you to replay historical blocks and transactions in your sandbox.

Your simulation lab needs monitoring and analysis tools. Install Tenderly for advanced transaction simulation and debugging, or use Etherscan's testnet explorers for basic verification. For analyzing mempool data—critical for frontrunning and sandwich attacks—set up a Geth node with txpool APIs enabled or use a service like Blocknative. Implement simple Python scripts using the web3.py library or Node.js scripts with ethers.js to listen for pending transactions and simulate attack logic. Always start by forking a block number before a known MEV event to test your detection and exploitation code in a safe, reproducible manner.

Finally, establish a rigorous testing workflow. Create separate directories for different attack vector simulations (e.g., /sandwich, /arbitrage). Write Foundry test scripts in Solidity (*.t.sol) to formalize your attack simulations and assertions. Use forge test --fork-url $RPC_URL to run these tests against a forked network. Incorporate Slither or Mythril for static analysis of target smart contracts to identify vulnerabilities. Remember, the goal of this lab is analysis and education; never run these simulations on mainnet or public testnets without explicit permission, as they can constitute actual attacks on live systems.

lab-components
MEV SIMULATION LAB

Core Lab Components

Essential tools and frameworks for building a controlled environment to analyze and test MEV strategies, from sandwich attacks to arbitrage.

06

Lab Security & Isolation

Never test live. Isolate your simulation environment completely.

  • Use separate wallets & RPC endpoints with zero real funds.
  • Run Anvil and bots in Docker containers or dedicated VMs.
  • Key Principle: Your lab should be able to simulate a failed attack that loses all gas without any real financial cost. This isolation is non-negotiable for safe research.
forking-environment
SETUP

Step 1: Forking a Live Network with Anvil

Learn how to create a local, fork-based simulation environment to safely test MEV strategies and smart contract interactions against real-world state.

Forking a live blockchain with Anvil, part of the Foundry development suite, creates a local Ethereum Virtual Machine (EVM) instance that mirrors the exact state of a mainnet or testnet at a specific block. This is the foundational step for any MEV research or testing lab. Instead of deploying complex contracts and seeding them with assets, you interact with a perfect replica of the live network, including all existing contracts, token balances, and liquidity pool states. This allows for realistic simulation of transactions, sandwich attacks, or arbitrage opportunities without spending real funds or risking mainnet deployment.

To start, ensure Foundry is installed. The core command is anvil --fork-url <RPC_URL>. For example, using a service like Alchemy or Infura: anvil --fork-url https://eth-mainnet.g.alchemy.com/v2/YOUR_KEY. By default, this forks the chain at the latest block. For reproducible tests, specify a block number with --fork-block-number. Anvil spins up a local RPC endpoint (typically http://127.0.0.1:8545) and provides 10 prefunded accounts, each with 10,000 test ETH, giving you immediate capital to simulate transactions.

The power of a forked environment lies in its state manipulation capabilities. You can impersonate any account using anvil_impersonateAccount, allowing you to send transactions from contracts or externally owned accounts you don't own the private key for. This is essential for testing how your MEV bot interacts with, or exploits, existing smart contracts. Furthermore, you can modify blockchain state directly—for instance, setting an account's balance with anvil_setBalance or changing storage slots with anvil_setStorageAt—to create specific, adversarial conditions for your tests.

When testing MEV vectors, forking at a historical block where a known arbitrage or liquidation opportunity existed is a common practice. You can replay the mempool transactions leading up to that block and insert your own transaction to see if your strategy would have succeeded. Tools like Foundry's cast can be used alongside Anvil to query state (cast call), send transactions (cast send), and decode logs, creating a complete command-line testing workflow. This setup provides a sandbox identical to mainnet, making it the most accurate environment for pre-deployment validation.

deploy-and-configure
SIMULATION LAB

Setting Up a Simulation Lab for Testing MEV Attack Vectors

A controlled simulation environment is essential for safely identifying and mitigating MEV vulnerabilities before mainnet deployment. This guide details how to configure a local testnet with tools like Foundry and Anvil to replicate real-world conditions.

Begin by establishing a local blockchain environment using Foundry's Anvil. Anvil provides a deterministic, forkable Ethereum node ideal for MEV simulation. Install Foundry and start a local chain with a specific block number to create a consistent testing baseline. Use the command anvil --fork-url <RPC_URL> --fork-block-number <BLOCK_NUMBER> to fork a recent mainnet state. This allows you to simulate transactions against real smart contracts and liquidity pools, capturing the complex state dependencies that MEV bots exploit.

Next, configure your simulation to replicate common MEV attack vectors. Key scenarios to model include sandwich attacks on DEX trades, liquidations in lending protocols, and arbitrage opportunities across pools. Write Foundry test scripts (forge test) that deploy a mock searcher bot. This bot should use Flashbots' eth_sendBundle RPC via a local mev-geth or mev-boost relay to simulate the bundling and ordering of transactions, which is the core mechanic behind most MEV extraction.

Instrument your simulation to collect critical data. Log metrics such as extractable value per block, gas costs for front-running transactions, and the success rate of attack bundles. Use tools like Tenderly or custom event logging to trace state changes and profit calculations. Analyzing this data helps you quantify the financial impact of specific vulnerabilities, such as the slippage tolerance in a DEX router or the latency in an oracle price update, providing concrete evidence for protocol adjustments.

Finally, implement and test mitigation strategies within your simulation. Common defenses include transaction deadline enforcement, slippage protection (e.g., using TWAP oracles), and private transaction pools like Flashbots Protect. Modify your protocol's smart contracts in the forked environment and re-run the attacker bot scripts to measure the reduction in extractable value. This iterative process of attack simulation and defense implementation is the most effective method for hardening your protocol against economic exploits before real funds are at risk.

scripting-attacks
HANDS-ON LAB

Step 3: Scripting Common MEV Attack Vectors

This guide walks through setting up a local simulation environment to safely test and understand the mechanics of common MEV strategies using Foundry and Anvil.

A controlled simulation lab is essential for studying MEV. It allows you to replay historical blocks, fork mainnet state, and execute transactions without spending real ETH or risking funds. The core tooling for this is Foundry, specifically its forge command-line tool and the anvil local node. Anvil lets you fork any Ethereum network at a specific block, creating a sandboxed, deterministic environment. You can then use cast to send transactions and forge to write and run Solidity test scripts that simulate attack vectors.

Start by forking mainnet. Run anvil --fork-url <YOUR_RPC_URL> --fork-block-number 19000000. This creates a local node with the state of mainnet at block 19,000,000. Your scripts will interact with this forked chain. You'll need an RPC URL from a service like Alchemy or Infura. Next, fund a test account. Anvil provides 10 pre-funded accounts; you can use their private keys in your scripts. To simulate a more realistic scenario, you can also impersonate any account (like a large DEX contract) using vm.prank in Foundry tests.

Let's script a simple sandwich attack simulation. The goal is to identify a pending victim swap on a DEX like Uniswap V2, front-run it with a large buy to move the price, and back-run it with a sell. In Foundry, you write a test in Solidity. First, use the IWETH and IUniswapV2Router interfaces. Your script will: 1) Impersonate the attacker account with vm.startPrank(attacker), 2) Use cast or direct calls to monitor the mempool (simulated by broadcasting a victim tx in your test), 3) Execute the front-run swap, 4) Let the victim swap execute, 5) Execute the back-run swap. Calculate profitability by comparing WETH balances before and after.

For liquidations, you can simulate a position becoming undercollateralized. Fork mainnet with a protocol like Aave or Compound. Use vm.roll to simulate a price oracle update that drops the collateral value. Your script then calls the liquidationCall function, paying the debt and receiving the collateral, factoring in the liquidation bonus. This lets you analyze the gas costs and profit margins under different conditions. You can also test arbitrage between two forked DEXes on the same local chain.

Always validate your simulations. Compare your script's profit calculations with theoretical models. Use console.log to output key state variables: token balances, pool reserves, and gas used. Foundry's forge test --fork-url <RPC> --match-path test/MEVSimulation.t.sol -vvv provides verbose output for debugging. Remember, these are simulations; real-world MEV involves network latency, gas competition, and private transaction propagation through services like Flashbots.

This lab setup is the foundation for research. You can extend it to test bundle construction with flashbots RPC endpoints, analyze the impact of different block builders, or experiment with PBS (Proposer-Builder Separation) concepts. The code and methodology from Flashbots' mev-inspect-rs and Foundry Book are excellent references for deepening your understanding.

SIMULATION LAB FOCUS

MEV Attack Vector Analysis

Comparison of common MEV attack vectors, their mechanisms, and required lab setup for simulation.

Attack VectorPrimary MechanismSimulation ComplexityLab Setup RequiredRisk Level

Sandwich Attack

Frontrun user tx, backrun with own

Medium

High

Time-Bandit Attack

Reorg chain to steal finalized blocks

High

Critical

Liquidator Frontrunning

Outbid public mempool liquidations

Low

Medium

Arbitrage (DEX)

Exploit price differences across pools

Low

Low

NFT Sniping

Monitor pending mints, frontrun purchase

Low

Medium

Long-tail Reorg

Orchestrate deep chain reorganizations

Very High

Critical

Oracle Manipulation

Delay or spoof price feed updates

Medium

High

testing-defenses
LAB SETUP

Step 4: Implementing and Stress-Testing Defenses

A controlled simulation environment is essential for safely testing MEV attack vectors and validating defensive strategies before deployment on mainnet.

The core of a MEV simulation lab is a local blockchain testnet. Using tools like Ganache or a local Hardhat node provides a sandboxed environment where you control all variables. You can fork a specific mainnet block state using hardhat node --fork <ALCHEMY_URL>, allowing you to replay historical transactions or simulate new ones. This setup is critical for testing without spending real ETH or risking funds. Essential components include a local RPC endpoint (e.g., http://localhost:8545), funded test accounts, and the ability to manipulate block parameters like gas price and miner behavior.

To simulate MEV attacks, you need to script the attack vectors you intend to test. For a sandwich attack, write a bot that monitors the mempool for a target DEX trade, then programmatically submits a front-running and back-running transaction. Use a library like ethers.js or web3.py to build and broadcast these transactions. For time-bandit attacks, you need to simulate a malicious validator who can reorg the chain; this can be approximated by forking the chain at a past block and building an alternative block sequence. Testing these scripts in isolation helps you understand their precise mechanics and failure modes.

Equally important is implementing and testing defenses. If you are building a DApp, integrate and configure a MEV protection RPC like Flashbots Protect or BloXroute's Private Transactions. In your lab, verify that transactions sent via these services are not visible in the public mempool of your local node. For smart contract developers, test commit-reveal schemes or threshold encryption (e.g., using the Shutter Network) to obfuscate transaction intent. Use your attack scripts to attempt to front-run these protected transactions and confirm the defenses hold.

Stress-testing involves pushing the system under adversarial conditions. Create load by simulating high network congestion, spamming the mempool with decoy transactions, or manipulating gas prices. Use tools like Hardhat's network helpers to mine blocks on demand or adjust block gas limits. The goal is to answer specific questions: At what load does a protection mechanism fail? Does a fair ordering protocol maintain its guarantees under a Sybil attack? Document the conditions, transaction success rates, and any observed leakage of transaction data to refine your defensive parameters.

Finally, establish a validation and iteration loop. After each test, analyze the blockchain state and transaction logs to verify outcomes. Compare the results against your security hypotheses. Tools like Tenderly's forked simulation or Foundry's forge test with a mainnet fork can automate this analysis. Continuously update your attack scripts to emulate evolving tactics and retest your defenses. This rigorous, repeatable process in a controlled lab is the only reliable method to build confidence in your MEV mitigation strategies before they guard real user funds.

MEV SIMULATION LAB

Frequently Asked Questions

Common questions and troubleshooting for developers building a controlled environment to test MEV strategies, bot behavior, and network security.

A local MEV simulation lab creates a controlled, isolated environment to test Maximum Extractable Value (MEV) strategies and their impact without risking real funds or interacting with live networks. Its core purposes are:

  • Strategy Development & Backtesting: Test the profitability and logic of searcher bots (e.g., for arbitrage, liquidations) against historical or synthetic block data.
  • Security Research: Analyze how different MEV strategies (like sandwich attacks) affect user transactions and protocol health in a safe setting.
  • Validator/Builder Simulation: Experiment with block building algorithms and order flow auctions (OFAs) to understand their role in MEV distribution.
  • Protocol Testing: Assess how new DeFi protocols or smart contracts might be exploited by MEV, enabling proactive mitigation.

Using tools like Foundry's Anvil or Hardhat Network, you can fork mainnet state and simulate transactions with precise control over block timing and ordering.

conclusion-next-steps
SIMULATION LAB

Conclusion and Next Steps

You have configured a controlled environment for analyzing MEV. This is a critical foundation for security research and protocol development.

Your simulation lab is now a powerful tool for proactive security. You can use it to stress-test your own protocols, validate the effectiveness of new MEV mitigations like fair ordering or encrypted mempools, and benchmark the performance of different validators or searcher strategies. This hands-on approach moves beyond theoretical analysis, allowing you to observe attack vectors like sandwich attacks and time-bandit attacks in a safe, reproducible environment before they impact mainnet users and funds.

To deepen your analysis, integrate advanced tooling. Connect your forked network to MEV-Inspect or EigenPhi to automatically detect and classify MEV transactions. Use Tenderly or a custom Geth/Prysm trace to visualize transaction ordering and gas price wars within a block. For more complex scenarios, consider writing custom Foundry scripts or Python bots that simulate adversarial searcher behavior, allowing you to measure the extractable value under different network conditions and protocol parameters.

The next logical step is to explore cross-chain MEV. Set up a local testnet of a second chain (e.g., a fork of Polygon or Arbitrum) and bridge assets between them using a forked version of a canonical bridge. This lets you study cross-domain MEV opportunities and risks, such as arbitrage between DEXes on different L2s or latency attacks on bridge finality. Tools like Chainlink CCIP local nodes or the Axelar local devnet can facilitate these experiments.

Finally, contribute your findings. Reproducible research strengthens the entire ecosystem. Consider publishing attack PoCs (as scripts, not live exploits) on GitHub, writing detailed post-mortems of simulated attacks, or sharing configuration templates for your lab setup. Engaging with communities like the Flashbots Collective or ETH R&D channels can provide peer review and help standardize testing methodologies, pushing forward the state of MEV research and mitigation.

How to Set Up a MEV Attack Simulation Lab | ChainScore Guides