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 MEV Simulation Environment for Testing

A developer guide for building a local or testnet environment to simulate MEV extraction attacks, test protocol resilience, and evaluate mitigation strategies before mainnet deployment.
Chainscore © 2026
introduction
INTRODUCTION

Setting Up a MEV Simulation Environment for Testing

A robust local simulation environment is essential for developing and testing MEV strategies without risking real funds or interacting with live networks.

MEV, or Maximal Extractable Value, refers to profit extracted by reordering, including, or censoring transactions within blocks. To safely research and prototype strategies—like arbitrage, liquidations, or sandwich attacks—you need a controlled testing ground. A simulation environment replicates core blockchain components, allowing you to execute transactions against a local mempool and state without the cost or finality of mainnet. Popular frameworks for this include Foundry and Hardhat, which provide EVM-compatible local networks and testing utilities.

The core of your setup will be a local Ethereum node, such as the one provided by Ganache or Hardhat Network. You will seed this node with simulated blockchain state, including token balances for test accounts and deployed copies of major protocols like Uniswap V3 or Aave. Tools like Anvil (from Foundry) are particularly useful as they offer advanced features for manipulating the chain, such as impersonating accounts, setting specific block timestamps, and mining transactions on-demand. This control is critical for testing time-sensitive MEV opportunities.

To simulate the mempool and transaction propagation, you can use a local mempool simulator or work directly with your node's transaction pool. You'll write and deploy smart contracts representing your searcher logic, often called "searcher contracts" or "bundles". Your testing scripts will send these transactions to your local node, where you can observe their execution, gas usage, and profitability. It's crucial to include failed transaction scenarios and revert handling in your tests to ensure robustness.

For more advanced simulation, particularly around block building, integrate with a block simulator like Ethereum Execution Simulator (EELS) or mev-rs. These tools allow you to construct entire blocks from a set of pending transactions, applying your preferred ordering to calculate potential extractable value. This step moves beyond single-transaction tests to model the competitive environment of real block production, where multiple searchers submit bundles to validators.

Finally, instrument your environment for data collection. Log key metrics such as profit per bundle, success rate, gas costs, and simulated validator payments (e.g., to Flashbots' mev-share). This data validates your strategy's economic viability. Remember, a comprehensive simulation suite is your first defense against costly errors on mainnet. Start with simple arbitrage on a forked Uniswap pool, then gradually increase complexity by adding more actors and adversarial conditions.

prerequisites
PREREQUISITES

Setting Up a MEV Simulation Environment for Testing

Before you can simulate and analyze MEV strategies, you need a controlled, local environment that mimics the live blockchain. This guide covers the essential tools and configurations.

A robust MEV simulation environment requires three core components: a local blockchain, a transaction execution client, and a block builder. The most common setup uses Foundry's Anvil as the local EVM chain, Geth or Reth for execution, and a custom builder like mev-rs or Flashbots SUAVE. This stack allows you to fork mainnet state, simulate complex transaction bundles, and test strategies without spending real ETH or interacting with public mempools. You'll also need a basic understanding of Ethereum's transaction lifecycle and the JSON-RPC interface.

Start by installing the foundational tools. Use Foundry for its anvil command to spin up a local chain: anvil --fork-url $RPC_URL. This creates a local node that mirrors the state of a live network at a specific block. For a more realistic block building simulation, you'll need an execution client. You can run Geth in dev mode with geth --dev or use the newer Reth for its performance. These clients process transactions and manage the state trie, which is critical for accurate gas and state change simulations.

Next, integrate a block builder to simulate the auction process. The mev-rs library in Rust provides a modular builder and relay for local testing. Alternatively, you can use the Flashbots SUAVE testnet devnet for a more integrated environment. Configure your builder to connect to your local execution client via its RPC endpoint (typically http://localhost:8545). This setup lets you submit private bundles and observe how they are ordered and included in a simulated block, revealing potential frontrunning or sandwiching opportunities.

Your simulation environment must be seeded with realistic data. When forking mainnet, use a recent block number and a reliable RPC provider like Alchemy or Infura. Fund test accounts using Anvil's --accounts flag or by impersonating known whales via anvil_impersonateAccount. You'll also need test ERC-20 tokens; you can deploy common ones like WETH and USDC from their verified source code using Foundry's forge create command. Accurate state is non-negotiable for testing arbitrage or liquidation strategies.

Finally, instrument your environment for observability. Enable verbose logging in your execution client and builder. Use tools like Ethers.js or Viem in a separate script to send test transactions and monitor the mempool. The goal is to create a feedback loop where you can deploy a smart contract, execute a bundle, and analyze the resulting block and state diff. This local sandbox is where you validate the profitability and correctness of your MEV strategies before any real-world deployment.

environment-setup-options
FOUNDATIONS

Choosing Your Simulation Environment

Selecting the right simulation environment is the first critical step in MEV research and strategy development. This guide compares the leading options.

A MEV simulation environment is a sandboxed system that mimics the behavior of a live blockchain. It allows you to test transaction ordering, bundle construction, and strategy logic without spending real gas or risking funds. The core components you need are a local Ethereum execution client (like Geth or Erigon), a consensus client, and a block builder that can be instrumented for analysis. Setting this up from scratch is complex, which is why pre-packaged solutions have become the standard for developers.

For most researchers, Foundry's Anvil is the recommended starting point. It's a local Ethereum node written in Rust that's part of the Foundry toolkit. You can fork mainnet at a specific block, giving you a complete state with real contracts and token balances to test against. Use anvil --fork-url <RPC_URL> to start. Its speed and integration with Foundry's testing framework make it ideal for rapid iteration on smart contract interactions and simple arbitrage logic.

For more advanced scenarios involving searcher competition or validator behavior, you need a dedicated simulation framework. Ethereum Execution Simulator (EES) and Flashbots SUAVE are two leading choices. EES provides a high-fidelity, deterministic simulation of the Ethereum network, perfect for backtesting strategies against historical data. The Flashbots MEV-Share and MEV-Boost testnets, along with the SUAVE development environment, allow you to test in an ecosystem that mirrors the real proposer-builder-separated (PBS) landscape.

Your choice depends on your testing goals. Use Anvil for unit tests of your strategy's core logic. Use EES for rigorous, repeatable backtesting against historical chain data to validate profitability. Use the SUAVE devnet for integration testing where your strategy must interact with a real relay, builder, and other searchers in a competitive environment. Always start simple and increase fidelity as needed; simulating an entire blockchain is computationally expensive.

Regardless of your chosen tool, structure your simulation to be deterministic and reproducible. Seed your random number generators, record initial chain state and input transactions, and log all results. This allows you to debug failures and verify that strategy improvements are genuine. The Flashbots Research GitHub and EES documentation are essential resources for advanced setup configurations and example simulations.

TOOL SELECTION

MEV Simulation Tools Comparison

Key specifications and capabilities of major tools for simulating and analyzing MEV strategies.

FeatureFoundry (Anvil)GanacheHardhat NetworkTenderly

Local Node Emulation

Fork Mainnet

Custom Transaction Ordering

Mempool Simulation

Gas Price Manipulation

Time Warping / Block Mining

State Snapshots & Reverts

Simulation Speed

< 100ms

~500ms

< 200ms

2-5 sec

Primary Use Case

Strategy Dev & Unit Tests

DApp Testing

Smart Contract Dev

Debug & Analysis

step-1-fork-mainnet-with-foundry
SETUP

Step 1: Fork Mainnet with Foundry

Learn how to create a local fork of Ethereum mainnet using Foundry's Anvil, the essential first step for simulating and testing MEV strategies in a realistic environment.

A mainnet fork is a local, isolated copy of the Ethereum blockchain state at a specific block. Using Foundry's anvil command, you can spin up a local node that mirrors the live network, including all deployed contracts, token balances, and current prices. This allows you to test MEV strategies—like arbitrage, liquidations, or sandwich attacks—against real-world conditions without spending real ETH or risking your funds on a public testnet. The forked environment provides a sandbox where transactions are executed deterministically, enabling reproducible testing and debugging.

To start, ensure you have Foundry installed. If not, run curl -L https://foundry.paradigm.xyz | bash and then foundryup. Once installed, forking mainnet is a single command: anvil --fork-url https://eth-mainnet.g.alchemy.com/v2/YOUR_API_KEY. Replace the URL with your preferred RPC provider endpoint from services like Alchemy, Infura, or a public node. The --fork-block-number flag is optional but recommended; specifying a block (e.g., --fork-block-number 20000000) pins your fork to a historical state, ensuring your experiments remain consistent across sessions.

When the fork starts, Anvil outputs critical information: a list of 10 test accounts with 10,000 ETH each (private keys included), the local RPC URL (typically http://127.0.0.1:8545), and the chain ID (usually 1 or 31337). You can now interact with this forked chain using tools like cast or forge, or connect your script or bot to the local RPC. Any transactions you send will only affect your local state. This setup is perfect for simulating the mempool, testing contract interactions with protocols like Uniswap or Aave, and observing how your MEV actions impact the blockchain state before deploying them live.

step-2-simulate-mev-bundles
DEVELOPER TUTORIAL

Step 2: Simulate MEV Bundles and Arbitrage

Learn how to set up a local environment to safely test MEV strategies by simulating bundle execution and arbitrage opportunities before deploying to mainnet.

Before committing capital on-chain, you must validate your MEV strategy's profitability and safety in a simulated environment. A simulation environment uses a forked version of a live blockchain (like Ethereum mainnet) to execute your bundles against the exact same state, but without spending real gas or risking funds. This allows you to test for frontrunning, sandwich attacks, arbitrage loops, and revert conditions in a risk-free setting. Tools like Foundry's anvil and Tenderly are essential for creating these local forks.

To begin, fork the mainnet using Foundry. Install Foundry and run anvil --fork-url <YOUR_RPC_ENDPOINT>. This command spins up a local Ethereum node that mirrors the latest mainnet state. You can specify a block number to fork from a specific historical point, which is crucial for backtesting strategies. Your RPC provider (Alchemy, Infura, QuickNode) must support archive data for this to work. Once running, anvil provides a local RPC URL (typically http://127.0.0.1:8545) and a set of pre-funded test accounts.

Next, craft and send your transaction bundle for simulation. Using the eth_sendBundle JSON-RPC method, you submit a bundle containing your target transaction(s) and any surrounding transactions you wish to simulate alongside it. The key is to set the simulationBlock and simulationTimestamp parameters to match your forked chain's state. You can use a library like flashbots/builder or a direct RPC call. The simulator will execute the bundle and return a detailed report showing gas used, state changes, and most importantly, whether the bundle reverts or is profitable.

For arbitrage simulation, your bundle typically contains two transactions: a flash loan acquisition from a protocol like Aave or Uniswap V3, followed by your arbitrage swap across DEXs. The simulation will calculate the final token balance after repaying the loan. A successful simulation must show a net positive ETH balance for the searcher's address after all gas costs are accounted for. Always simulate with competitive gas prices to ensure your strategy remains viable under real network conditions.

Analyze the simulation results thoroughly. Look beyond simple profit/loss. Check for unexpected slippage, price impact on smaller pools, and interactions with other pending mempool transactions you included in the simulation. A common practice is to simulate your bundle both in isolation and alongside recent real transactions from the public mempool to test for competitiveness. This step helps you avoid negative externalities and revert griefing from other searchers.

Finally, integrate simulation into your CI/CD pipeline. Automate the process of forking a recent block, running your strategy logic, and asserting profitability thresholds. This ensures your MEV bots don't degrade over time as protocol logic or market conditions change. Remember, simulation is not a guarantee of mainnet success due to latency and real-time competition, but it is the most effective method for eliminating logical errors and unprofitable strategies before they cost you real ETH.

step-3-test-protocol-mitigations
SIMULATION

Step 3: Test Protocol Mitigations

This step details how to configure a local MEV simulation environment to test the effectiveness of your proposed mitigations against identified attack vectors.

After identifying potential MEV vulnerabilities, you must validate your countermeasures in a controlled environment before deploying to mainnet. A local simulation environment replicates blockchain state and validator behavior, allowing you to inject malicious bundles or transactions to test your protocol's resilience. Tools like Foundry's Anvil or Hardhat Network are ideal for this, as they provide a fork of a live network (e.g., Ethereum mainnet) with programmable RPC endpoints. You can simulate specific block conditions, such as high gas prices or pending transaction pools, to create realistic attack scenarios.

To begin, fork the target network at a recent block number. This creates a local chain with the exact state, including token balances and contract deployments, of the live network. Using this fork, you deploy your protocol's smart contracts or, if testing an existing protocol, interact with its already-deployed instances. The key is to then write and execute simulation scripts that mimic attacker behavior. For example, a script might front-run a user's swap transaction by crafting a bundle with a higher gas price, sending it via eth_sendBundle to a local MEV-Boost relay simulator like mev-boost-testnet.

Your simulation should measure key outcomes: did the malicious bundle get included? Was user transaction ordering or execution outcome negatively impacted? Did your mitigation (e.g., a commit-reveal scheme, a modified fee structure, or a private mempool integration) successfully neutralize the attack? Log these results and compare them against a baseline run without your mitigations. It's critical to test across multiple block heights and network conditions to ensure robustness. This iterative testing cycle helps refine your mitigation strategy before it faces real economic incentives on a public network.

step-4-integrate-with-hardhat
DEVELOPER TUTORIAL

Step 4: Integrate MEV Tests into Hardhat

This guide walks through configuring a Hardhat project to simulate and test for MEV vulnerabilities using the `@flashbots/hardhat` plugin and a local Anvil fork.

To test for MEV vulnerabilities, you need a realistic simulation environment. The most effective method is to fork a live network like Ethereum Mainnet using a local node such as Anvil from Foundry. This gives your tests access to real contract states, token balances, and current market prices. Install the necessary dependencies: @nomicfoundation/hardhat-toolbox, @flashbots/hardhat, and @nomicfoundation/hardhat-network-helpers. Configure your hardhat.config.js to use the Flashbots plugin and set up a forked network endpoint, typically pointing to a local Anvil instance running on http://127.0.0.1:8545.

With the environment configured, you can write tests that simulate common MEV attack vectors. A core pattern is the sandwich attack simulation. Your test should: 1) Fork the mainnet at a specific block, 2) Impersonate an attacker account using hardhat_impersonateAccount, 3) Simulate a victim's pending swap transaction on a DEX like Uniswap V3, 4) Have the attacker front-run it with a large buy, and 5) Back-run it with a sell. The @flashbots/hardhat plugin provides utilities like getPendingTransactions to fetch mempool state from your local node, making this simulation possible.

Beyond sandwich attacks, test for liquidity sniping on new pool deployments and arbitrage between decentralized exchanges. Use hardhat_setStorageAt to manipulate contract states and simulate specific conditions, such as a mispriced asset. Always assert expected outcomes: verify the attacker's profit in ETH or USDC, and confirm the victim received worse execution (higher slippage). These integration tests should run in your CI/CD pipeline. By automating MEV simulations, you can proactively identify and mitigate extractable value in your protocol's transaction flows before deployment.

MEV SIMULATION

Frequently Asked Questions

Common questions and solutions for developers building and testing MEV strategies in a simulated environment.

An MEV simulation environment is a local or testnet sandbox that replicates blockchain state, mempool dynamics, and validator behavior to test extraction strategies without risking real funds. You need one to:

  • Safely prototype strategies like arbitrage, liquidations, or sandwich attacks.
  • Benchmark performance by simulating network latency and gas competition.
  • Audit security and economic impacts before deploying on mainnet.

Tools like Foundry's Anvil, Ganache, or specialized frameworks like Flashbots SUAVE and Eden Network's testnet provide the necessary components: a local EVM, transaction pool simulation, and block builder logic.

conclusion-next-steps
NEXT STEPS

Conclusion and Next Steps

You have now configured a local MEV simulation environment. This guide covered the essential setup, but the real work begins with active experimentation and integration.

Your local simulation environment is a foundational tool for developing and testing MEV strategies without financial risk. You can now experiment with building searcher bots that identify profitable opportunities, such as arbitrage or liquidations, by analyzing the simulated mempool. Use the anvil forked state to test against real mainnet conditions, and leverage mev-rs or mev-inspect-rs to understand transaction ordering and block construction. This sandbox is crucial for stress-testing your logic against edge cases and network congestion.

To deepen your understanding, integrate with a block builder simulator like mev-boost's test relays or the flashbots/builder specification. This allows you to practice submitting bundles and simulating the PBS (Proposer-Builder Separation) auction. Explore how different strategies perform under varying gas prices and block space constraints. Document your findings and iterate on your bot's logic; successful simulation often involves running thousands of test transactions to refine profitability and reliability.

The next logical step is to connect to a testnet. Deploy your tested strategies on networks like Goerli, Sepolia, or Holesky, which offer a more realistic environment with public mempools and active searchers. Use services like the Flashbots Testnet Explorer to monitor your bundle submissions. Remember, moving to mainnet requires extreme caution: start with minimal capital, implement robust error handling, and consider the ethical implications of your MEV extraction methods.

Continue your education by studying advanced topics. Research PGA (Priority Gas Auctions), time-bandit attacks, and CFMM (Constant Function Market Maker) arbitrage mechanics. Engage with the community through repositories like flashbots/pm and eth-educators/mev-resources. The MEV landscape evolves rapidly with each network upgrade, so staying updated on EIPs and client changes is essential for maintaining a competitive and compliant strategy.

How to Set Up a MEV Simulation Environment for Testing | ChainScore Guides