anvil/
config.rs

1use crate::{
2    EthereumHardfork, FeeManager, PrecompileFactory,
3    eth::{
4        backend::{
5            db::{Db, SerializableState},
6            env::Env,
7            fork::{ClientFork, ClientForkConfig},
8            genesis::GenesisConfig,
9            mem::fork_db::ForkedDatabase,
10            time::duration_since_unix_epoch,
11        },
12        fees::{INITIAL_BASE_FEE, INITIAL_GAS_PRICE},
13        pool::transactions::{PoolTransaction, TransactionOrder},
14    },
15    mem::{self, in_memory_db::MemDb},
16};
17use alloy_chains::Chain;
18use alloy_consensus::BlockHeader;
19use alloy_eips::eip7840::BlobParams;
20use alloy_evm::EvmEnv;
21use alloy_genesis::Genesis;
22use alloy_network::{AnyNetwork, TransactionResponse};
23use alloy_primitives::{BlockNumber, TxHash, U256, hex, map::HashMap, utils::Unit};
24use alloy_provider::Provider;
25use alloy_rpc_types::{Block, BlockNumberOrTag};
26use alloy_signer::Signer;
27use alloy_signer_local::{
28    MnemonicBuilder, PrivateKeySigner,
29    coins_bip39::{English, Mnemonic},
30};
31use alloy_transport::TransportError;
32use anvil_server::ServerConfig;
33use eyre::{Context, Result};
34use foundry_common::{
35    ALCHEMY_FREE_TIER_CUPS, NON_ARCHIVE_NODE_WARNING, REQUEST_TIMEOUT,
36    provider::{ProviderBuilder, RetryProvider},
37};
38use foundry_config::Config;
39use foundry_evm::{
40    backend::{BlockchainDb, BlockchainDbMeta, SharedBackend},
41    constants::DEFAULT_CREATE2_DEPLOYER,
42    core::AsEnvMut,
43    hardfork::{
44        FoundryHardfork, OpHardfork, ethereum_hardfork_from_block_tag,
45        spec_id_from_ethereum_hardfork,
46    },
47    utils::{apply_chain_and_block_specific_env_changes, get_blob_base_fee_update_fraction},
48};
49use itertools::Itertools;
50use op_revm::OpTransaction;
51use parking_lot::RwLock;
52use rand_08::thread_rng;
53use revm::{
54    context::{BlockEnv, CfgEnv, TxEnv},
55    context_interface::block::BlobExcessGasAndPrice,
56    primitives::hardfork::SpecId,
57};
58use serde_json::{Value, json};
59use std::{
60    fmt::Write as FmtWrite,
61    fs::File,
62    io,
63    net::{IpAddr, Ipv4Addr},
64    path::PathBuf,
65    sync::Arc,
66    time::Duration,
67};
68use tokio::sync::RwLock as TokioRwLock;
69use yansi::Paint;
70
71pub use foundry_common::version::SHORT_VERSION as VERSION_MESSAGE;
72use foundry_evm::{
73    traces::{CallTraceDecoderBuilder, identifier::SignaturesIdentifier},
74    utils::get_blob_params,
75};
76use foundry_evm_networks::NetworkConfigs;
77
78/// Default port the rpc will open
79pub const NODE_PORT: u16 = 8545;
80/// Default chain id of the node
81pub const CHAIN_ID: u64 = 31337;
82/// The default gas limit for all transactions
83pub const DEFAULT_GAS_LIMIT: u64 = 30_000_000;
84/// Default mnemonic for dev accounts
85pub const DEFAULT_MNEMONIC: &str = "test test test test test test test test test test test junk";
86
87/// The default IPC endpoint
88pub const DEFAULT_IPC_ENDPOINT: &str =
89    if cfg!(unix) { "/tmp/anvil.ipc" } else { r"\\.\pipe\anvil.ipc" };
90
91const BANNER: &str = r"
92                             _   _
93                            (_) | |
94      __ _   _ __   __   __  _  | |
95     / _` | | '_ \  \ \ / / | | | |
96    | (_| | | | | |  \ V /  | | | |
97     \__,_| |_| |_|   \_/   |_| |_|
98";
99
100/// Configurations of the EVM node
101#[derive(Clone, Debug)]
102pub struct NodeConfig {
103    /// Chain ID of the EVM chain
104    pub chain_id: Option<u64>,
105    /// Default gas limit for all txs
106    pub gas_limit: Option<u64>,
107    /// If set to `true`, disables the block gas limit
108    pub disable_block_gas_limit: bool,
109    /// If set to `true`, enables the tx gas limit as imposed by Osaka (EIP-7825)
110    pub enable_tx_gas_limit: bool,
111    /// Default gas price for all txs
112    pub gas_price: Option<u128>,
113    /// Default base fee
114    pub base_fee: Option<u64>,
115    /// If set to `true`, disables the enforcement of a minimum suggested priority fee
116    pub disable_min_priority_fee: bool,
117    /// Default blob excess gas and price
118    pub blob_excess_gas_and_price: Option<BlobExcessGasAndPrice>,
119    /// The hardfork to use
120    pub hardfork: Option<FoundryHardfork>,
121    /// Signer accounts that will be initialised with `genesis_balance` in the genesis block
122    pub genesis_accounts: Vec<PrivateKeySigner>,
123    /// Native token balance of every genesis account in the genesis block
124    pub genesis_balance: U256,
125    /// Genesis block timestamp
126    pub genesis_timestamp: Option<u64>,
127    /// Genesis block number
128    pub genesis_block_number: Option<u64>,
129    /// Signer accounts that can sign messages/transactions from the EVM node
130    pub signer_accounts: Vec<PrivateKeySigner>,
131    /// Configured block time for the EVM chain. Use `None` to mine a new block for every tx
132    pub block_time: Option<Duration>,
133    /// Disable auto, interval mining mode uns use `MiningMode::None` instead
134    pub no_mining: bool,
135    /// Enables auto and interval mining mode
136    pub mixed_mining: bool,
137    /// port to use for the server
138    pub port: u16,
139    /// maximum number of transactions in a block
140    pub max_transactions: usize,
141    /// url of the rpc server that should be used for any rpc calls
142    pub eth_rpc_url: Option<String>,
143    /// pins the block number or transaction hash for the state fork
144    pub fork_choice: Option<ForkChoice>,
145    /// headers to use with `eth_rpc_url`
146    pub fork_headers: Vec<String>,
147    /// specifies chain id for cache to skip fetching from remote in offline-start mode
148    pub fork_chain_id: Option<U256>,
149    /// The generator used to generate the dev accounts
150    pub account_generator: Option<AccountGenerator>,
151    /// whether to enable tracing
152    pub enable_tracing: bool,
153    /// Explicitly disables the use of RPC caching.
154    pub no_storage_caching: bool,
155    /// How to configure the server
156    pub server_config: ServerConfig,
157    /// The host the server will listen on
158    pub host: Vec<IpAddr>,
159    /// How transactions are sorted in the mempool
160    pub transaction_order: TransactionOrder,
161    /// Filename to write anvil output as json
162    pub config_out: Option<PathBuf>,
163    /// The genesis to use to initialize the node
164    pub genesis: Option<Genesis>,
165    /// Timeout in for requests sent to remote JSON-RPC server in forking mode
166    pub fork_request_timeout: Duration,
167    /// Number of request retries for spurious networks
168    pub fork_request_retries: u32,
169    /// The initial retry backoff
170    pub fork_retry_backoff: Duration,
171    /// available CUPS
172    pub compute_units_per_second: u64,
173    /// The ipc path
174    pub ipc_path: Option<Option<String>>,
175    /// Enable transaction/call steps tracing for debug calls returning geth-style traces
176    pub enable_steps_tracing: bool,
177    /// Enable printing of `console.log` invocations.
178    pub print_logs: bool,
179    /// Enable printing of traces.
180    pub print_traces: bool,
181    /// Enable auto impersonation of accounts on startup
182    pub enable_auto_impersonate: bool,
183    /// Configure the code size limit
184    pub code_size_limit: Option<usize>,
185    /// Configures how to remove historic state.
186    ///
187    /// If set to `Some(num)` keep latest num state in memory only.
188    pub prune_history: PruneStateHistoryConfig,
189    /// Max number of states cached on disk.
190    pub max_persisted_states: Option<usize>,
191    /// The file where to load the state from
192    pub init_state: Option<SerializableState>,
193    /// max number of blocks with transactions in memory
194    pub transaction_block_keeper: Option<usize>,
195    /// Disable the default CREATE2 deployer
196    pub disable_default_create2_deployer: bool,
197    /// Disable pool balance checks
198    pub disable_pool_balance_checks: bool,
199    /// Slots in an epoch
200    pub slots_in_an_epoch: u64,
201    /// The memory limit per EVM execution in bytes.
202    pub memory_limit: Option<u64>,
203    /// Factory used by `anvil` to extend the EVM's precompiles.
204    pub precompile_factory: Option<Arc<dyn PrecompileFactory>>,
205    /// Networks to enable features for.
206    pub networks: NetworkConfigs,
207    /// Do not print log messages.
208    pub silent: bool,
209    /// The path where states are cached.
210    pub cache_path: Option<PathBuf>,
211}
212
213impl NodeConfig {
214    fn as_string(&self, fork: Option<&ClientFork>) -> String {
215        let mut s: String = String::new();
216        let _ = write!(s, "\n{}", BANNER.green());
217        let _ = write!(s, "\n    {VERSION_MESSAGE}");
218        let _ = write!(s, "\n    {}", "https://github.com/foundry-rs/foundry".green());
219
220        let _ = write!(
221            s,
222            r#"
223
224Available Accounts
225==================
226"#
227        );
228        let balance = alloy_primitives::utils::format_ether(self.genesis_balance);
229        for (idx, wallet) in self.genesis_accounts.iter().enumerate() {
230            write!(s, "\n({idx}) {} ({balance} ETH)", wallet.address()).unwrap();
231        }
232
233        let _ = write!(
234            s,
235            r#"
236
237Private Keys
238==================
239"#
240        );
241
242        for (idx, wallet) in self.genesis_accounts.iter().enumerate() {
243            let hex = hex::encode(wallet.credential().to_bytes());
244            let _ = write!(s, "\n({idx}) 0x{hex}");
245        }
246
247        if let Some(generator) = &self.account_generator {
248            let _ = write!(
249                s,
250                r#"
251
252Wallet
253==================
254Mnemonic:          {}
255Derivation path:   {}
256"#,
257                generator.phrase,
258                generator.get_derivation_path()
259            );
260        }
261
262        if let Some(fork) = fork {
263            let _ = write!(
264                s,
265                r#"
266
267Fork
268==================
269Endpoint:       {}
270Block number:   {}
271Block hash:     {:?}
272Chain ID:       {}
273"#,
274                fork.eth_rpc_url(),
275                fork.block_number(),
276                fork.block_hash(),
277                fork.chain_id()
278            );
279
280            if let Some(tx_hash) = fork.transaction_hash() {
281                let _ = writeln!(s, "Transaction hash: {tx_hash}");
282            }
283        } else {
284            let _ = write!(
285                s,
286                r#"
287
288Chain ID
289==================
290
291{}
292"#,
293                self.get_chain_id().green()
294            );
295        }
296
297        if (SpecId::from(self.get_hardfork()) as u8) < (SpecId::LONDON as u8) {
298            let _ = write!(
299                s,
300                r#"
301Gas Price
302==================
303
304{}
305"#,
306                self.get_gas_price().green()
307            );
308        } else {
309            let _ = write!(
310                s,
311                r#"
312Base Fee
313==================
314
315{}
316"#,
317                self.get_base_fee().green()
318            );
319        }
320
321        let _ = write!(
322            s,
323            r#"
324Gas Limit
325==================
326
327{}
328"#,
329            {
330                if self.disable_block_gas_limit {
331                    "Disabled".to_string()
332                } else {
333                    self.gas_limit.map(|l| l.to_string()).unwrap_or_else(|| {
334                        if self.fork_choice.is_some() {
335                            "Forked".to_string()
336                        } else {
337                            DEFAULT_GAS_LIMIT.to_string()
338                        }
339                    })
340                }
341            }
342            .green()
343        );
344
345        let _ = write!(
346            s,
347            r#"
348Genesis Timestamp
349==================
350
351{}
352"#,
353            self.get_genesis_timestamp().green()
354        );
355
356        let _ = write!(
357            s,
358            r#"
359Genesis Number
360==================
361
362{}
363"#,
364            self.get_genesis_number().green()
365        );
366
367        s
368    }
369
370    fn as_json(&self, fork: Option<&ClientFork>) -> Value {
371        let mut wallet_description = HashMap::new();
372        let mut available_accounts = Vec::with_capacity(self.genesis_accounts.len());
373        let mut private_keys = Vec::with_capacity(self.genesis_accounts.len());
374
375        for wallet in &self.genesis_accounts {
376            available_accounts.push(format!("{:?}", wallet.address()));
377            private_keys.push(format!("0x{}", hex::encode(wallet.credential().to_bytes())));
378        }
379
380        if let Some(generator) = &self.account_generator {
381            let phrase = generator.get_phrase().to_string();
382            let derivation_path = generator.get_derivation_path().to_string();
383
384            wallet_description.insert("derivation_path".to_string(), derivation_path);
385            wallet_description.insert("mnemonic".to_string(), phrase);
386        };
387
388        let gas_limit = match self.gas_limit {
389            // if we have a disabled flag we should max out the limit
390            Some(_) | None if self.disable_block_gas_limit => Some(u64::MAX.to_string()),
391            Some(limit) => Some(limit.to_string()),
392            _ => None,
393        };
394
395        if let Some(fork) = fork {
396            json!({
397              "available_accounts": available_accounts,
398              "private_keys": private_keys,
399              "endpoint": fork.eth_rpc_url(),
400              "block_number": fork.block_number(),
401              "block_hash": fork.block_hash(),
402              "chain_id": fork.chain_id(),
403              "wallet": wallet_description,
404              "base_fee": format!("{}", self.get_base_fee()),
405              "gas_price": format!("{}", self.get_gas_price()),
406              "gas_limit": gas_limit,
407            })
408        } else {
409            json!({
410              "available_accounts": available_accounts,
411              "private_keys": private_keys,
412              "wallet": wallet_description,
413              "base_fee": format!("{}", self.get_base_fee()),
414              "gas_price": format!("{}", self.get_gas_price()),
415              "gas_limit": gas_limit,
416              "genesis_timestamp": format!("{}", self.get_genesis_timestamp()),
417            })
418        }
419    }
420}
421
422impl NodeConfig {
423    /// Returns a new config intended to be used in tests, which does not print and binds to a
424    /// random, free port by setting it to `0`
425    #[doc(hidden)]
426    pub fn test() -> Self {
427        Self { enable_tracing: true, port: 0, silent: true, ..Default::default() }
428    }
429
430    /// Returns a new config which does not initialize any accounts on node startup.
431    pub fn empty_state() -> Self {
432        Self {
433            genesis_accounts: vec![],
434            signer_accounts: vec![],
435            disable_default_create2_deployer: true,
436            ..Default::default()
437        }
438    }
439}
440
441impl Default for NodeConfig {
442    fn default() -> Self {
443        // generate some random wallets
444        let genesis_accounts = AccountGenerator::new(10)
445            .phrase(DEFAULT_MNEMONIC)
446            .generate()
447            .expect("Invalid mnemonic.");
448        Self {
449            chain_id: None,
450            gas_limit: None,
451            disable_block_gas_limit: false,
452            enable_tx_gas_limit: false,
453            gas_price: None,
454            hardfork: None,
455            signer_accounts: genesis_accounts.clone(),
456            genesis_timestamp: None,
457            genesis_block_number: None,
458            genesis_accounts,
459            // 100ETH default balance
460            genesis_balance: Unit::ETHER.wei().saturating_mul(U256::from(100u64)),
461            block_time: None,
462            no_mining: false,
463            mixed_mining: false,
464            port: NODE_PORT,
465            max_transactions: 1_000,
466            eth_rpc_url: None,
467            fork_choice: None,
468            account_generator: None,
469            base_fee: None,
470            disable_min_priority_fee: false,
471            blob_excess_gas_and_price: None,
472            enable_tracing: true,
473            enable_steps_tracing: false,
474            print_logs: true,
475            print_traces: false,
476            enable_auto_impersonate: false,
477            no_storage_caching: false,
478            server_config: Default::default(),
479            host: vec![IpAddr::V4(Ipv4Addr::LOCALHOST)],
480            transaction_order: Default::default(),
481            config_out: None,
482            genesis: None,
483            fork_request_timeout: REQUEST_TIMEOUT,
484            fork_headers: vec![],
485            fork_request_retries: 5,
486            fork_retry_backoff: Duration::from_millis(1_000),
487            fork_chain_id: None,
488            // alchemy max cpus <https://docs.alchemy.com/reference/compute-units#what-are-cups-compute-units-per-second>
489            compute_units_per_second: ALCHEMY_FREE_TIER_CUPS,
490            ipc_path: None,
491            code_size_limit: None,
492            prune_history: Default::default(),
493            max_persisted_states: None,
494            init_state: None,
495            transaction_block_keeper: None,
496            disable_default_create2_deployer: false,
497            disable_pool_balance_checks: false,
498            slots_in_an_epoch: 32,
499            memory_limit: None,
500            precompile_factory: None,
501            networks: Default::default(),
502            silent: false,
503            cache_path: None,
504        }
505    }
506}
507
508impl NodeConfig {
509    /// Returns the memory limit of the node
510    #[must_use]
511    pub fn with_memory_limit(mut self, mems_value: Option<u64>) -> Self {
512        self.memory_limit = mems_value;
513        self
514    }
515    /// Returns the base fee to use
516    pub fn get_base_fee(&self) -> u64 {
517        self.base_fee
518            .or_else(|| self.genesis.as_ref().and_then(|g| g.base_fee_per_gas.map(|g| g as u64)))
519            .unwrap_or(INITIAL_BASE_FEE)
520    }
521
522    /// Returns the base fee to use
523    pub fn get_gas_price(&self) -> u128 {
524        self.gas_price.unwrap_or(INITIAL_GAS_PRICE)
525    }
526
527    pub fn get_blob_excess_gas_and_price(&self) -> BlobExcessGasAndPrice {
528        if let Some(value) = self.blob_excess_gas_and_price {
529            value
530        } else {
531            let excess_blob_gas =
532                self.genesis.as_ref().and_then(|g| g.excess_blob_gas).unwrap_or(0);
533            BlobExcessGasAndPrice::new(
534                excess_blob_gas,
535                get_blob_base_fee_update_fraction(
536                    self.chain_id.unwrap_or(Chain::mainnet().id()),
537                    self.get_genesis_timestamp(),
538                ),
539            )
540        }
541    }
542
543    /// Returns the [`BlobParams`] that should be used.
544    pub fn get_blob_params(&self) -> BlobParams {
545        get_blob_params(
546            self.chain_id.unwrap_or(Chain::mainnet().id()),
547            self.get_genesis_timestamp(),
548        )
549    }
550
551    /// Returns the hardfork to use
552    pub fn get_hardfork(&self) -> FoundryHardfork {
553        if let Some(hardfork) = self.hardfork {
554            return hardfork;
555        }
556        if self.networks.is_optimism() {
557            return OpHardfork::default().into();
558        }
559        EthereumHardfork::default().into()
560    }
561
562    /// Sets a custom code size limit
563    #[must_use]
564    pub fn with_code_size_limit(mut self, code_size_limit: Option<usize>) -> Self {
565        self.code_size_limit = code_size_limit;
566        self
567    }
568    /// Disables  code size limit
569    #[must_use]
570    pub fn disable_code_size_limit(mut self, disable_code_size_limit: bool) -> Self {
571        if disable_code_size_limit {
572            self.code_size_limit = Some(usize::MAX);
573        }
574        self
575    }
576
577    /// Sets the init state if any
578    #[must_use]
579    pub fn with_init_state(mut self, init_state: Option<SerializableState>) -> Self {
580        self.init_state = init_state;
581        self
582    }
583
584    /// Loads the init state from a file if it exists
585    #[must_use]
586    #[cfg(feature = "cmd")]
587    pub fn with_init_state_path(mut self, path: impl AsRef<std::path::Path>) -> Self {
588        self.init_state = crate::cmd::StateFile::parse_path(path).ok().and_then(|file| file.state);
589        self
590    }
591
592    /// Sets the chain ID
593    #[must_use]
594    pub fn with_chain_id<U: Into<u64>>(mut self, chain_id: Option<U>) -> Self {
595        self.set_chain_id(chain_id);
596        self
597    }
598
599    /// Returns the chain ID to use
600    pub fn get_chain_id(&self) -> u64 {
601        self.chain_id
602            .or_else(|| self.genesis.as_ref().map(|g| g.config.chain_id))
603            .unwrap_or(CHAIN_ID)
604    }
605
606    /// Sets the chain id and updates all wallets
607    pub fn set_chain_id(&mut self, chain_id: Option<impl Into<u64>>) {
608        self.chain_id = chain_id.map(Into::into);
609        let chain_id = self.get_chain_id();
610        self.networks.with_chain_id(chain_id);
611        self.genesis_accounts.iter_mut().for_each(|wallet| {
612            *wallet = wallet.clone().with_chain_id(Some(chain_id));
613        });
614        self.signer_accounts.iter_mut().for_each(|wallet| {
615            *wallet = wallet.clone().with_chain_id(Some(chain_id));
616        })
617    }
618
619    /// Sets the gas limit
620    #[must_use]
621    pub fn with_gas_limit(mut self, gas_limit: Option<u64>) -> Self {
622        self.gas_limit = gas_limit;
623        self
624    }
625
626    /// Disable block gas limit check
627    ///
628    /// If set to `true` block gas limit will not be enforced
629    #[must_use]
630    pub fn disable_block_gas_limit(mut self, disable_block_gas_limit: bool) -> Self {
631        self.disable_block_gas_limit = disable_block_gas_limit;
632        self
633    }
634
635    /// Enable tx gas limit check
636    ///
637    /// If set to `true`, enables the tx gas limit as imposed by Osaka (EIP-7825)
638    #[must_use]
639    pub fn enable_tx_gas_limit(mut self, enable_tx_gas_limit: bool) -> Self {
640        self.enable_tx_gas_limit = enable_tx_gas_limit;
641        self
642    }
643
644    /// Sets the gas price
645    #[must_use]
646    pub fn with_gas_price(mut self, gas_price: Option<u128>) -> Self {
647        self.gas_price = gas_price;
648        self
649    }
650
651    /// Sets prune history status.
652    #[must_use]
653    pub fn set_pruned_history(mut self, prune_history: Option<Option<usize>>) -> Self {
654        self.prune_history = PruneStateHistoryConfig::from_args(prune_history);
655        self
656    }
657
658    /// Sets max number of states to cache on disk.
659    #[must_use]
660    pub fn with_max_persisted_states<U: Into<usize>>(
661        mut self,
662        max_persisted_states: Option<U>,
663    ) -> Self {
664        self.max_persisted_states = max_persisted_states.map(Into::into);
665        self
666    }
667
668    /// Sets max number of blocks with transactions to keep in memory
669    #[must_use]
670    pub fn with_transaction_block_keeper<U: Into<usize>>(
671        mut self,
672        transaction_block_keeper: Option<U>,
673    ) -> Self {
674        self.transaction_block_keeper = transaction_block_keeper.map(Into::into);
675        self
676    }
677
678    /// Sets the base fee
679    #[must_use]
680    pub fn with_base_fee(mut self, base_fee: Option<u64>) -> Self {
681        self.base_fee = base_fee;
682        self
683    }
684
685    /// Disable the enforcement of a minimum suggested priority fee
686    #[must_use]
687    pub fn disable_min_priority_fee(mut self, disable_min_priority_fee: bool) -> Self {
688        self.disable_min_priority_fee = disable_min_priority_fee;
689        self
690    }
691
692    /// Sets the init genesis (genesis.json)
693    #[must_use]
694    pub fn with_genesis(mut self, genesis: Option<Genesis>) -> Self {
695        self.genesis = genesis;
696        self
697    }
698
699    /// Returns the genesis timestamp to use
700    pub fn get_genesis_timestamp(&self) -> u64 {
701        self.genesis_timestamp
702            .or_else(|| self.genesis.as_ref().map(|g| g.timestamp))
703            .unwrap_or_else(|| duration_since_unix_epoch().as_secs())
704    }
705
706    /// Sets the genesis timestamp
707    #[must_use]
708    pub fn with_genesis_timestamp<U: Into<u64>>(mut self, timestamp: Option<U>) -> Self {
709        if let Some(timestamp) = timestamp {
710            self.genesis_timestamp = Some(timestamp.into());
711        }
712        self
713    }
714
715    /// Sets the genesis number
716    #[must_use]
717    pub fn with_genesis_block_number<U: Into<u64>>(mut self, number: Option<U>) -> Self {
718        if let Some(number) = number {
719            self.genesis_block_number = Some(number.into());
720        }
721        self
722    }
723
724    /// Returns the genesis number
725    pub fn get_genesis_number(&self) -> u64 {
726        self.genesis_block_number
727            .or_else(|| self.genesis.as_ref().and_then(|g| g.number))
728            .unwrap_or(0)
729    }
730
731    /// Sets the hardfork
732    #[must_use]
733    pub fn with_hardfork(mut self, hardfork: Option<FoundryHardfork>) -> Self {
734        self.hardfork = hardfork;
735        self
736    }
737
738    /// Sets the genesis accounts
739    #[must_use]
740    pub fn with_genesis_accounts(mut self, accounts: Vec<PrivateKeySigner>) -> Self {
741        self.genesis_accounts = accounts;
742        self
743    }
744
745    /// Sets the signer accounts
746    #[must_use]
747    pub fn with_signer_accounts(mut self, accounts: Vec<PrivateKeySigner>) -> Self {
748        self.signer_accounts = accounts;
749        self
750    }
751
752    /// Sets both the genesis accounts and the signer accounts
753    /// so that `genesis_accounts == accounts`
754    pub fn with_account_generator(mut self, generator: AccountGenerator) -> eyre::Result<Self> {
755        let accounts = generator.generate()?;
756        self.account_generator = Some(generator);
757        Ok(self.with_signer_accounts(accounts.clone()).with_genesis_accounts(accounts))
758    }
759
760    /// Sets the balance of the genesis accounts in the genesis block
761    #[must_use]
762    pub fn with_genesis_balance<U: Into<U256>>(mut self, balance: U) -> Self {
763        self.genesis_balance = balance.into();
764        self
765    }
766
767    /// Sets the block time to automine blocks
768    #[must_use]
769    pub fn with_blocktime<D: Into<Duration>>(mut self, block_time: Option<D>) -> Self {
770        self.block_time = block_time.map(Into::into);
771        self
772    }
773
774    #[must_use]
775    pub fn with_mixed_mining<D: Into<Duration>>(
776        mut self,
777        mixed_mining: bool,
778        block_time: Option<D>,
779    ) -> Self {
780        self.block_time = block_time.map(Into::into);
781        self.mixed_mining = mixed_mining;
782        self
783    }
784
785    /// If set to `true` auto mining will be disabled
786    #[must_use]
787    pub fn with_no_mining(mut self, no_mining: bool) -> Self {
788        self.no_mining = no_mining;
789        self
790    }
791
792    /// Sets the slots in an epoch
793    #[must_use]
794    pub fn with_slots_in_an_epoch(mut self, slots_in_an_epoch: u64) -> Self {
795        self.slots_in_an_epoch = slots_in_an_epoch;
796        self
797    }
798
799    /// Sets the port to use
800    #[must_use]
801    pub fn with_port(mut self, port: u16) -> Self {
802        self.port = port;
803        self
804    }
805
806    /// Sets the ipc path to use
807    ///
808    /// Note: this is a double Option for
809    ///     - `None` -> no ipc
810    ///     - `Some(None)` -> use default path
811    ///     - `Some(Some(path))` -> use custom path
812    #[must_use]
813    pub fn with_ipc(mut self, ipc_path: Option<Option<String>>) -> Self {
814        self.ipc_path = ipc_path;
815        self
816    }
817
818    /// Sets the file path to write the Anvil node's config info to.
819    #[must_use]
820    pub fn set_config_out(mut self, config_out: Option<PathBuf>) -> Self {
821        self.config_out = config_out;
822        self
823    }
824
825    /// Disables storage caching
826    #[must_use]
827    pub fn no_storage_caching(self) -> Self {
828        self.with_storage_caching(true)
829    }
830
831    #[must_use]
832    pub fn with_storage_caching(mut self, storage_caching: bool) -> Self {
833        self.no_storage_caching = storage_caching;
834        self
835    }
836
837    /// Sets the `eth_rpc_url` to use when forking
838    #[must_use]
839    pub fn with_eth_rpc_url<U: Into<String>>(mut self, eth_rpc_url: Option<U>) -> Self {
840        self.eth_rpc_url = eth_rpc_url.map(Into::into);
841        self
842    }
843
844    /// Sets the `fork_choice` to use to fork off from based on a block number
845    #[must_use]
846    pub fn with_fork_block_number<U: Into<u64>>(self, fork_block_number: Option<U>) -> Self {
847        self.with_fork_choice(fork_block_number.map(Into::into))
848    }
849
850    /// Sets the `fork_choice` to use to fork off from based on a transaction hash
851    #[must_use]
852    pub fn with_fork_transaction_hash<U: Into<TxHash>>(
853        self,
854        fork_transaction_hash: Option<U>,
855    ) -> Self {
856        self.with_fork_choice(fork_transaction_hash.map(Into::into))
857    }
858
859    /// Sets the `fork_choice` to use to fork off from
860    #[must_use]
861    pub fn with_fork_choice<U: Into<ForkChoice>>(mut self, fork_choice: Option<U>) -> Self {
862        self.fork_choice = fork_choice.map(Into::into);
863        self
864    }
865
866    /// Sets the `fork_chain_id` to use to fork off local cache from
867    #[must_use]
868    pub fn with_fork_chain_id(mut self, fork_chain_id: Option<U256>) -> Self {
869        self.fork_chain_id = fork_chain_id;
870        self
871    }
872
873    /// Sets the `fork_headers` to use with `eth_rpc_url`
874    #[must_use]
875    pub fn with_fork_headers(mut self, headers: Vec<String>) -> Self {
876        self.fork_headers = headers;
877        self
878    }
879
880    /// Sets the `fork_request_timeout` to use for requests
881    #[must_use]
882    pub fn fork_request_timeout(mut self, fork_request_timeout: Option<Duration>) -> Self {
883        if let Some(fork_request_timeout) = fork_request_timeout {
884            self.fork_request_timeout = fork_request_timeout;
885        }
886        self
887    }
888
889    /// Sets the `fork_request_retries` to use for spurious networks
890    #[must_use]
891    pub fn fork_request_retries(mut self, fork_request_retries: Option<u32>) -> Self {
892        if let Some(fork_request_retries) = fork_request_retries {
893            self.fork_request_retries = fork_request_retries;
894        }
895        self
896    }
897
898    /// Sets the initial `fork_retry_backoff` for rate limits
899    #[must_use]
900    pub fn fork_retry_backoff(mut self, fork_retry_backoff: Option<Duration>) -> Self {
901        if let Some(fork_retry_backoff) = fork_retry_backoff {
902            self.fork_retry_backoff = fork_retry_backoff;
903        }
904        self
905    }
906
907    /// Sets the number of assumed available compute units per second
908    ///
909    /// See also, <https://docs.alchemy.com/reference/compute-units#what-are-cups-compute-units-per-second>
910    #[must_use]
911    pub fn fork_compute_units_per_second(mut self, compute_units_per_second: Option<u64>) -> Self {
912        if let Some(compute_units_per_second) = compute_units_per_second {
913            self.compute_units_per_second = compute_units_per_second;
914        }
915        self
916    }
917
918    /// Sets whether to enable tracing
919    #[must_use]
920    pub fn with_tracing(mut self, enable_tracing: bool) -> Self {
921        self.enable_tracing = enable_tracing;
922        self
923    }
924
925    /// Sets whether to enable steps tracing
926    #[must_use]
927    pub fn with_steps_tracing(mut self, enable_steps_tracing: bool) -> Self {
928        self.enable_steps_tracing = enable_steps_tracing;
929        self
930    }
931
932    /// Sets whether to print `console.log` invocations to stdout.
933    #[must_use]
934    pub fn with_print_logs(mut self, print_logs: bool) -> Self {
935        self.print_logs = print_logs;
936        self
937    }
938
939    /// Sets whether to print traces to stdout.
940    #[must_use]
941    pub fn with_print_traces(mut self, print_traces: bool) -> Self {
942        self.print_traces = print_traces;
943        self
944    }
945
946    /// Sets whether to enable autoImpersonate
947    #[must_use]
948    pub fn with_auto_impersonate(mut self, enable_auto_impersonate: bool) -> Self {
949        self.enable_auto_impersonate = enable_auto_impersonate;
950        self
951    }
952
953    #[must_use]
954    pub fn with_server_config(mut self, config: ServerConfig) -> Self {
955        self.server_config = config;
956        self
957    }
958
959    /// Sets the host the server will listen on
960    #[must_use]
961    pub fn with_host(mut self, host: Vec<IpAddr>) -> Self {
962        self.host = if host.is_empty() { vec![IpAddr::V4(Ipv4Addr::LOCALHOST)] } else { host };
963        self
964    }
965
966    #[must_use]
967    pub fn with_transaction_order(mut self, transaction_order: TransactionOrder) -> Self {
968        self.transaction_order = transaction_order;
969        self
970    }
971
972    /// Returns the ipc path for the ipc endpoint if any
973    pub fn get_ipc_path(&self) -> Option<String> {
974        match &self.ipc_path {
975            Some(path) => path.clone().or_else(|| Some(DEFAULT_IPC_ENDPOINT.to_string())),
976            None => None,
977        }
978    }
979
980    /// Prints the config info
981    pub fn print(&self, fork: Option<&ClientFork>) -> Result<()> {
982        if let Some(path) = &self.config_out {
983            let file = io::BufWriter::new(
984                File::create(path).wrap_err("unable to create anvil config description file")?,
985            );
986            let value = self.as_json(fork);
987            serde_json::to_writer(file, &value).wrap_err("failed writing JSON")?;
988        }
989        if !self.silent {
990            sh_println!("{}", self.as_string(fork))?;
991        }
992        Ok(())
993    }
994
995    /// Returns the path where the cache file should be stored
996    ///
997    /// See also [ Config::foundry_block_cache_file()]
998    pub fn block_cache_path(&self, block: u64) -> Option<PathBuf> {
999        if self.no_storage_caching || self.eth_rpc_url.is_none() {
1000            return None;
1001        }
1002        let chain_id = self.get_chain_id();
1003
1004        Config::foundry_block_cache_file(chain_id, block)
1005    }
1006
1007    /// Sets whether to disable the default create2 deployer
1008    #[must_use]
1009    pub fn with_disable_default_create2_deployer(mut self, yes: bool) -> Self {
1010        self.disable_default_create2_deployer = yes;
1011        self
1012    }
1013
1014    /// Sets whether to disable pool balance checks
1015    #[must_use]
1016    pub fn with_disable_pool_balance_checks(mut self, yes: bool) -> Self {
1017        self.disable_pool_balance_checks = yes;
1018        self
1019    }
1020
1021    /// Injects precompiles to `anvil`'s EVM.
1022    #[must_use]
1023    pub fn with_precompile_factory(mut self, factory: impl PrecompileFactory + 'static) -> Self {
1024        self.precompile_factory = Some(Arc::new(factory));
1025        self
1026    }
1027
1028    /// Enable features for provided networks.
1029    #[must_use]
1030    pub fn with_networks(mut self, networks: NetworkConfigs) -> Self {
1031        self.networks = networks;
1032        self
1033    }
1034
1035    /// Makes the node silent to not emit anything on stdout
1036    #[must_use]
1037    pub fn silent(self) -> Self {
1038        self.set_silent(true)
1039    }
1040
1041    #[must_use]
1042    pub fn set_silent(mut self, silent: bool) -> Self {
1043        self.silent = silent;
1044        self
1045    }
1046
1047    /// Sets the path where states are cached
1048    #[must_use]
1049    pub fn with_cache_path(mut self, cache_path: Option<PathBuf>) -> Self {
1050        self.cache_path = cache_path;
1051        self
1052    }
1053
1054    /// Configures everything related to env, backend and database and returns the
1055    /// [Backend](mem::Backend)
1056    ///
1057    /// *Note*: only memory based backend for now
1058    pub(crate) async fn setup(&mut self) -> Result<mem::Backend> {
1059        // configure the revm environment
1060
1061        let mut cfg = CfgEnv::default();
1062        cfg.spec = self.get_hardfork().into();
1063
1064        cfg.chain_id = self.get_chain_id();
1065        cfg.limit_contract_code_size = self.code_size_limit;
1066        // EIP-3607 rejects transactions from senders with deployed code.
1067        // If EIP-3607 is enabled it can cause issues during fuzz/invariant tests if the
1068        // caller is a contract. So we disable the check by default.
1069        cfg.disable_eip3607 = true;
1070        cfg.disable_block_gas_limit = self.disable_block_gas_limit;
1071
1072        if !self.enable_tx_gas_limit {
1073            cfg.tx_gas_limit_cap = Some(u64::MAX);
1074        }
1075
1076        if let Some(value) = self.memory_limit {
1077            cfg.memory_limit = value;
1078        }
1079
1080        let spec_id = cfg.spec;
1081        let mut env = Env::new(
1082            EvmEnv::new(
1083                cfg,
1084                BlockEnv {
1085                    gas_limit: self.gas_limit(),
1086                    basefee: self.get_base_fee(),
1087                    ..Default::default()
1088                },
1089            ),
1090            OpTransaction {
1091                base: TxEnv { chain_id: Some(self.get_chain_id()), ..Default::default() },
1092                ..Default::default()
1093            },
1094            self.networks,
1095        );
1096
1097        let fees = FeeManager::new(
1098            spec_id,
1099            self.get_base_fee(),
1100            !self.disable_min_priority_fee,
1101            self.get_gas_price(),
1102            self.get_blob_excess_gas_and_price(),
1103            self.get_blob_params(),
1104        );
1105
1106        let (db, fork): (Arc<TokioRwLock<Box<dyn Db>>>, Option<ClientFork>) =
1107            if let Some(eth_rpc_url) = self.eth_rpc_url.clone() {
1108                self.setup_fork_db(eth_rpc_url, &mut env, &fees).await?
1109            } else {
1110                (Arc::new(TokioRwLock::new(Box::<MemDb>::default())), None)
1111            };
1112
1113        // if provided use all settings of `genesis.json`
1114        if let Some(ref genesis) = self.genesis {
1115            // --chain-id flag gets precedence over the genesis.json chain id
1116            // <https://github.com/foundry-rs/foundry/issues/10059>
1117            if self.chain_id.is_none() {
1118                env.evm_env.cfg_env.chain_id = genesis.config.chain_id;
1119            }
1120            env.evm_env.block_env.timestamp = U256::from(genesis.timestamp);
1121            if let Some(base_fee) = genesis.base_fee_per_gas {
1122                env.evm_env.block_env.basefee = base_fee.try_into()?;
1123            }
1124            if let Some(number) = genesis.number {
1125                env.evm_env.block_env.number = U256::from(number);
1126            }
1127            env.evm_env.block_env.beneficiary = genesis.coinbase;
1128        }
1129
1130        let genesis = GenesisConfig {
1131            number: self.get_genesis_number(),
1132            timestamp: self.get_genesis_timestamp(),
1133            balance: self.genesis_balance,
1134            accounts: self.genesis_accounts.iter().map(|acc| acc.address()).collect(),
1135            genesis_init: self.genesis.clone(),
1136        };
1137
1138        let mut decoder_builder = CallTraceDecoderBuilder::new();
1139        if self.print_traces {
1140            // if traces should get printed we configure the decoder with the signatures cache
1141            if let Ok(identifier) = SignaturesIdentifier::new(false) {
1142                debug!(target: "node", "using signature identifier");
1143                decoder_builder = decoder_builder.with_signature_identifier(identifier);
1144            }
1145        }
1146
1147        // only memory based backend for now
1148        let backend = mem::Backend::with_genesis(
1149            db,
1150            Arc::new(RwLock::new(env)),
1151            genesis,
1152            fees,
1153            Arc::new(RwLock::new(fork)),
1154            self.enable_steps_tracing,
1155            self.print_logs,
1156            self.print_traces,
1157            Arc::new(decoder_builder.build()),
1158            self.prune_history,
1159            self.max_persisted_states,
1160            self.transaction_block_keeper,
1161            self.block_time,
1162            self.cache_path.clone(),
1163            Arc::new(TokioRwLock::new(self.clone())),
1164        )
1165        .await?;
1166
1167        // Writes the default create2 deployer to the backend,
1168        // if the option is not disabled and we are not forking.
1169        if !self.disable_default_create2_deployer && self.eth_rpc_url.is_none() {
1170            backend
1171                .set_create2_deployer(DEFAULT_CREATE2_DEPLOYER)
1172                .await
1173                .wrap_err("failed to create default create2 deployer")?;
1174        }
1175
1176        if let Some(state) = self.init_state.clone() {
1177            backend.load_state(state).await.wrap_err("failed to load init state")?;
1178        }
1179
1180        Ok(backend)
1181    }
1182
1183    /// Configures everything related to forking based on the passed `eth_rpc_url`:
1184    ///  - returning a tuple of a [ForkedDatabase] wrapped in an [Arc] [RwLock](TokioRwLock) and
1185    ///    [ClientFork] wrapped in an [Option] which can be used in a [Backend](mem::Backend) to
1186    ///    fork from.
1187    ///  - modifying some parameters of the passed `env`
1188    ///  - mutating some members of `self`
1189    pub async fn setup_fork_db(
1190        &mut self,
1191        eth_rpc_url: String,
1192        env: &mut Env,
1193        fees: &FeeManager,
1194    ) -> Result<(Arc<TokioRwLock<Box<dyn Db>>>, Option<ClientFork>)> {
1195        let (db, config) = self.setup_fork_db_config(eth_rpc_url, env, fees).await?;
1196        let db: Arc<TokioRwLock<Box<dyn Db>>> = Arc::new(TokioRwLock::new(Box::new(db)));
1197        let fork = ClientFork::new(config, Arc::clone(&db));
1198        Ok((db, Some(fork)))
1199    }
1200
1201    /// Configures everything related to forking based on the passed `eth_rpc_url`:
1202    ///  - returning a tuple of a [ForkedDatabase] and [ClientForkConfig] which can be used to build
1203    ///    a [ClientFork] to fork from.
1204    ///  - modifying some parameters of the passed `env`
1205    ///  - mutating some members of `self`
1206    pub async fn setup_fork_db_config(
1207        &mut self,
1208        eth_rpc_url: String,
1209        env: &mut Env,
1210        fees: &FeeManager,
1211    ) -> Result<(ForkedDatabase, ClientForkConfig)> {
1212        debug!(target: "node", ?eth_rpc_url, "setting up fork db");
1213        let provider = Arc::new(
1214            ProviderBuilder::new(&eth_rpc_url)
1215                .timeout(self.fork_request_timeout)
1216                .initial_backoff(self.fork_retry_backoff.as_millis() as u64)
1217                .compute_units_per_second(self.compute_units_per_second)
1218                .max_retry(self.fork_request_retries)
1219                .headers(self.fork_headers.clone())
1220                .build()
1221                .wrap_err("failed to establish provider to fork url")?,
1222        );
1223
1224        let (fork_block_number, fork_chain_id, force_transactions) = if let Some(fork_choice) =
1225            &self.fork_choice
1226        {
1227            let (fork_block_number, force_transactions) =
1228                derive_block_and_transactions(fork_choice, &provider).await.wrap_err(
1229                    "failed to derive fork block number and force transactions from fork choice",
1230                )?;
1231            let chain_id = if let Some(chain_id) = self.fork_chain_id {
1232                Some(chain_id)
1233            } else if self.hardfork.is_none() {
1234                // Auto-adjust hardfork if not specified, but only if we're forking mainnet.
1235                let chain_id =
1236                    provider.get_chain_id().await.wrap_err("failed to fetch network chain ID")?;
1237                if alloy_chains::NamedChain::Mainnet == chain_id {
1238                    let hardfork: EthereumHardfork =
1239                        ethereum_hardfork_from_block_tag(fork_block_number);
1240
1241                    env.evm_env.cfg_env.spec = spec_id_from_ethereum_hardfork(hardfork);
1242                    self.hardfork = Some(FoundryHardfork::Ethereum(hardfork));
1243                }
1244                Some(U256::from(chain_id))
1245            } else {
1246                None
1247            };
1248
1249            (fork_block_number, chain_id, force_transactions)
1250        } else {
1251            // pick the last block number but also ensure it's not pending anymore
1252            let bn = find_latest_fork_block(&provider)
1253                .await
1254                .wrap_err("failed to get fork block number")?;
1255            (bn, None, None)
1256        };
1257
1258        let block = provider
1259            .get_block(BlockNumberOrTag::Number(fork_block_number).into())
1260            .await
1261            .wrap_err("failed to get fork block")?;
1262
1263        let block = if let Some(block) = block {
1264            block
1265        } else {
1266            if let Ok(latest_block) = provider.get_block_number().await {
1267                let mut message = format!(
1268                    "Failed to get block for block number: {fork_block_number}\n\
1269latest block number: {latest_block}"
1270                );
1271                // If the `eth_getBlockByNumber` call succeeds, but returns null instead of
1272                // the block, and the block number is less than equal the latest block, then
1273                // the user is forking from a non-archive node with an older block number.
1274                if fork_block_number <= latest_block {
1275                    message.push_str(&format!("\n{NON_ARCHIVE_NODE_WARNING}"));
1276                }
1277                eyre::bail!("{message}");
1278            }
1279            eyre::bail!("failed to get block for block number: {fork_block_number}")
1280        };
1281
1282        let gas_limit = self.fork_gas_limit(&block);
1283        self.gas_limit = Some(gas_limit);
1284
1285        env.evm_env.block_env = BlockEnv {
1286            number: U256::from(fork_block_number),
1287            timestamp: U256::from(block.header.timestamp),
1288            difficulty: block.header.difficulty,
1289            // ensures prevrandao is set
1290            prevrandao: Some(block.header.mix_hash.unwrap_or_default()),
1291            gas_limit,
1292            // Keep previous `coinbase` and `basefee` value
1293            beneficiary: env.evm_env.block_env.beneficiary,
1294            basefee: env.evm_env.block_env.basefee,
1295            ..Default::default()
1296        };
1297
1298        // if not set explicitly we use the base fee of the latest block
1299        if self.base_fee.is_none() {
1300            if let Some(base_fee) = block.header.base_fee_per_gas {
1301                self.base_fee = Some(base_fee);
1302                env.evm_env.block_env.basefee = base_fee;
1303                // this is the base fee of the current block, but we need the base fee of
1304                // the next block
1305                let next_block_base_fee = fees.get_next_block_base_fee_per_gas(
1306                    block.header.gas_used,
1307                    gas_limit,
1308                    block.header.base_fee_per_gas.unwrap_or_default(),
1309                );
1310
1311                // update next base fee
1312                fees.set_base_fee(next_block_base_fee);
1313            }
1314            if let (Some(blob_excess_gas), Some(blob_gas_used)) =
1315                (block.header.excess_blob_gas, block.header.blob_gas_used)
1316            {
1317                // derive the blobparams that are active at this timestamp
1318                let blob_params = get_blob_params(
1319                    fork_chain_id
1320                        .unwrap_or_else(|| U256::from(Chain::mainnet().id()))
1321                        .saturating_to(),
1322                    block.header.timestamp,
1323                );
1324
1325                env.evm_env.block_env.blob_excess_gas_and_price = Some(BlobExcessGasAndPrice::new(
1326                    blob_excess_gas,
1327                    blob_params.update_fraction as u64,
1328                ));
1329
1330                fees.set_blob_params(blob_params);
1331
1332                let next_block_blob_excess_gas =
1333                    fees.get_next_block_blob_excess_gas(blob_excess_gas, blob_gas_used);
1334                fees.set_blob_excess_gas_and_price(BlobExcessGasAndPrice::new(
1335                    next_block_blob_excess_gas,
1336                    blob_params.update_fraction as u64,
1337                ));
1338            }
1339        }
1340
1341        // use remote gas price
1342        if self.gas_price.is_none()
1343            && let Ok(gas_price) = provider.get_gas_price().await
1344        {
1345            self.gas_price = Some(gas_price);
1346            fees.set_gas_price(gas_price);
1347        }
1348
1349        let block_hash = block.header.hash;
1350
1351        let chain_id = if let Some(chain_id) = self.chain_id {
1352            chain_id
1353        } else {
1354            let chain_id = if let Some(fork_chain_id) = fork_chain_id {
1355                fork_chain_id.to()
1356            } else {
1357                provider.get_chain_id().await.wrap_err("failed to fetch network chain ID")?
1358            };
1359
1360            // need to update the dev signers and env with the chain id
1361            self.set_chain_id(Some(chain_id));
1362            env.evm_env.cfg_env.chain_id = chain_id;
1363            env.tx.base.chain_id = chain_id.into();
1364            chain_id
1365        };
1366        let override_chain_id = self.chain_id;
1367        // apply changes such as difficulty -> prevrandao and chain specifics for current chain id
1368        apply_chain_and_block_specific_env_changes::<AnyNetwork>(
1369            env.as_env_mut(),
1370            &block,
1371            self.networks,
1372        );
1373
1374        let meta = BlockchainDbMeta::new(env.evm_env.block_env.clone(), eth_rpc_url.clone());
1375        let block_chain_db = if self.fork_chain_id.is_some() {
1376            BlockchainDb::new_skip_check(meta, self.block_cache_path(fork_block_number))
1377        } else {
1378            BlockchainDb::new(meta, self.block_cache_path(fork_block_number))
1379        };
1380
1381        // This will spawn the background thread that will use the provider to fetch
1382        // blockchain data from the other client
1383        let backend = SharedBackend::spawn_backend(
1384            Arc::clone(&provider),
1385            block_chain_db.clone(),
1386            Some(fork_block_number.into()),
1387        )
1388        .await;
1389
1390        let config = ClientForkConfig {
1391            eth_rpc_url,
1392            block_number: fork_block_number,
1393            block_hash,
1394            transaction_hash: self.fork_choice.and_then(|fc| fc.transaction_hash()),
1395            provider,
1396            chain_id,
1397            override_chain_id,
1398            timestamp: block.header.timestamp,
1399            base_fee: block.header.base_fee_per_gas.map(|g| g as u128),
1400            timeout: self.fork_request_timeout,
1401            retries: self.fork_request_retries,
1402            backoff: self.fork_retry_backoff,
1403            compute_units_per_second: self.compute_units_per_second,
1404            total_difficulty: block.header.total_difficulty.unwrap_or_default(),
1405            blob_gas_used: block.header.blob_gas_used.map(|g| g as u128),
1406            blob_excess_gas_and_price: env.evm_env.block_env.blob_excess_gas_and_price,
1407            force_transactions,
1408        };
1409
1410        debug!(target: "node", fork_number=config.block_number, fork_hash=%config.block_hash, "set up fork db");
1411
1412        let mut db = ForkedDatabase::new(backend, block_chain_db);
1413
1414        // need to insert the forked block's hash
1415        db.insert_block_hash(U256::from(config.block_number), config.block_hash);
1416
1417        Ok((db, config))
1418    }
1419
1420    /// we only use the gas limit value of the block if it is non-zero and the block gas
1421    /// limit is enabled, since there are networks where this is not used and is always
1422    /// `0x0` which would inevitably result in `OutOfGas` errors as soon as the evm is about to record gas, See also <https://github.com/foundry-rs/foundry/issues/3247>
1423    pub(crate) fn fork_gas_limit<T: TransactionResponse, H: BlockHeader>(
1424        &self,
1425        block: &Block<T, H>,
1426    ) -> u64 {
1427        if !self.disable_block_gas_limit {
1428            if let Some(gas_limit) = self.gas_limit {
1429                return gas_limit;
1430            } else if block.header.gas_limit() > 0 {
1431                return block.header.gas_limit();
1432            }
1433        }
1434
1435        u64::MAX
1436    }
1437
1438    /// Returns the gas limit for a non forked anvil instance
1439    ///
1440    /// Checks the config for the `disable_block_gas_limit` flag
1441    pub(crate) fn gas_limit(&self) -> u64 {
1442        if self.disable_block_gas_limit {
1443            return u64::MAX;
1444        }
1445
1446        self.gas_limit.unwrap_or(DEFAULT_GAS_LIMIT)
1447    }
1448}
1449
1450/// If the fork choice is a block number, simply return it with an empty list of transactions.
1451/// If the fork choice is a transaction hash, determine the block that the transaction was mined in,
1452/// and return the block number before the fork block along with all transactions in the fork block
1453/// that are before (and including) the fork transaction.
1454async fn derive_block_and_transactions(
1455    fork_choice: &ForkChoice,
1456    provider: &Arc<RetryProvider>,
1457) -> eyre::Result<(BlockNumber, Option<Vec<PoolTransaction>>)> {
1458    match fork_choice {
1459        ForkChoice::Block(block_number) => {
1460            let block_number = *block_number;
1461            if block_number >= 0 {
1462                return Ok((block_number as u64, None));
1463            }
1464            // subtract from latest block number
1465            let latest = provider.get_block_number().await?;
1466
1467            Ok((block_number.saturating_add(latest as i128) as u64, None))
1468        }
1469        ForkChoice::Transaction(transaction_hash) => {
1470            // Determine the block that this transaction was mined in
1471            let transaction = provider
1472                .get_transaction_by_hash(transaction_hash.0.into())
1473                .await?
1474                .ok_or_else(|| eyre::eyre!("failed to get fork transaction by hash"))?;
1475            let transaction_block_number = transaction.block_number.ok_or_else(|| {
1476                eyre::eyre!("fork transaction is not mined yet (no block number)")
1477            })?;
1478
1479            // Get the block pertaining to the fork transaction
1480            let transaction_block = provider
1481                .get_block_by_number(transaction_block_number.into())
1482                .full()
1483                .await?
1484                .ok_or_else(|| eyre::eyre!("failed to get fork block by number"))?;
1485
1486            // Filter out transactions that are after the fork transaction
1487            let filtered_transactions = transaction_block
1488                .transactions
1489                .as_transactions()
1490                .ok_or_else(|| eyre::eyre!("failed to get transactions from full fork block"))?
1491                .iter()
1492                .take_while_inclusive(|&transaction| transaction.tx_hash() != transaction_hash.0)
1493                .collect::<Vec<_>>();
1494
1495            // Convert the transactions to PoolTransactions
1496            let force_transactions = filtered_transactions
1497                .iter()
1498                .map(|&transaction| PoolTransaction::try_from(transaction.clone()))
1499                .collect::<Result<Vec<_>, _>>()
1500                .map_err(|e| eyre::eyre!("Err converting to pool transactions {e}"))?;
1501            Ok((transaction_block_number.saturating_sub(1), Some(force_transactions)))
1502        }
1503    }
1504}
1505
1506/// Fork delimiter used to specify which block or transaction to fork from.
1507#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1508pub enum ForkChoice {
1509    /// Block number to fork from.
1510    ///
1511    /// If negative, the given value is subtracted from the `latest` block number.
1512    Block(i128),
1513    /// Transaction hash to fork from.
1514    Transaction(TxHash),
1515}
1516
1517impl ForkChoice {
1518    /// Returns the block number to fork from
1519    pub fn block_number(&self) -> Option<i128> {
1520        match self {
1521            Self::Block(block_number) => Some(*block_number),
1522            Self::Transaction(_) => None,
1523        }
1524    }
1525
1526    /// Returns the transaction hash to fork from
1527    pub fn transaction_hash(&self) -> Option<TxHash> {
1528        match self {
1529            Self::Block(_) => None,
1530            Self::Transaction(transaction_hash) => Some(*transaction_hash),
1531        }
1532    }
1533}
1534
1535/// Convert a transaction hash into a ForkChoice
1536impl From<TxHash> for ForkChoice {
1537    fn from(tx_hash: TxHash) -> Self {
1538        Self::Transaction(tx_hash)
1539    }
1540}
1541
1542/// Convert a decimal block number into a ForkChoice
1543impl From<u64> for ForkChoice {
1544    fn from(block: u64) -> Self {
1545        Self::Block(block as i128)
1546    }
1547}
1548
1549#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
1550pub struct PruneStateHistoryConfig {
1551    pub enabled: bool,
1552    pub max_memory_history: Option<usize>,
1553}
1554
1555impl PruneStateHistoryConfig {
1556    /// Returns `true` if writing state history is supported
1557    pub fn is_state_history_supported(&self) -> bool {
1558        !self.enabled || self.max_memory_history.is_some()
1559    }
1560
1561    /// Returns true if this setting was enabled.
1562    pub fn is_config_enabled(&self) -> bool {
1563        self.enabled
1564    }
1565
1566    pub fn from_args(val: Option<Option<usize>>) -> Self {
1567        val.map(|max_memory_history| Self { enabled: true, max_memory_history }).unwrap_or_default()
1568    }
1569}
1570
1571/// Can create dev accounts
1572#[derive(Clone, Debug)]
1573pub struct AccountGenerator {
1574    chain_id: u64,
1575    amount: usize,
1576    phrase: String,
1577    derivation_path: Option<String>,
1578}
1579
1580impl AccountGenerator {
1581    pub fn new(amount: usize) -> Self {
1582        Self {
1583            chain_id: CHAIN_ID,
1584            amount,
1585            phrase: Mnemonic::<English>::new(&mut thread_rng()).to_phrase(),
1586            derivation_path: None,
1587        }
1588    }
1589
1590    #[must_use]
1591    pub fn phrase(mut self, phrase: impl Into<String>) -> Self {
1592        self.phrase = phrase.into();
1593        self
1594    }
1595
1596    fn get_phrase(&self) -> &str {
1597        &self.phrase
1598    }
1599
1600    #[must_use]
1601    pub fn chain_id(mut self, chain_id: impl Into<u64>) -> Self {
1602        self.chain_id = chain_id.into();
1603        self
1604    }
1605
1606    #[must_use]
1607    pub fn derivation_path(mut self, derivation_path: impl Into<String>) -> Self {
1608        let mut derivation_path = derivation_path.into();
1609        if !derivation_path.ends_with('/') {
1610            derivation_path.push('/');
1611        }
1612        self.derivation_path = Some(derivation_path);
1613        self
1614    }
1615
1616    fn get_derivation_path(&self) -> &str {
1617        self.derivation_path.as_deref().unwrap_or("m/44'/60'/0'/0/")
1618    }
1619}
1620
1621impl AccountGenerator {
1622    pub fn generate(&self) -> eyre::Result<Vec<PrivateKeySigner>> {
1623        let builder = MnemonicBuilder::<English>::default().phrase(self.phrase.as_str());
1624
1625        // use the derivation path
1626        let derivation_path = self.get_derivation_path();
1627
1628        let mut wallets = Vec::with_capacity(self.amount);
1629        for idx in 0..self.amount {
1630            let builder =
1631                builder.clone().derivation_path(format!("{derivation_path}{idx}")).unwrap();
1632            let wallet = builder.build()?.with_chain_id(Some(self.chain_id));
1633            wallets.push(wallet)
1634        }
1635        Ok(wallets)
1636    }
1637}
1638
1639/// Returns the path to anvil dir `~/.foundry/anvil`
1640pub fn anvil_dir() -> Option<PathBuf> {
1641    Config::foundry_dir().map(|p| p.join("anvil"))
1642}
1643
1644/// Returns the root path to anvil's temporary storage `~/.foundry/anvil/`
1645pub fn anvil_tmp_dir() -> Option<PathBuf> {
1646    anvil_dir().map(|p| p.join("tmp"))
1647}
1648
1649/// Finds the latest appropriate block to fork
1650///
1651/// This fetches the "latest" block and checks whether the `Block` is fully populated (`hash` field
1652/// is present). This prevents edge cases where anvil forks the "latest" block but `eth_getBlockByNumber` still returns a pending block, <https://github.com/foundry-rs/foundry/issues/2036>
1653async fn find_latest_fork_block<P: Provider<AnyNetwork>>(
1654    provider: P,
1655) -> Result<u64, TransportError> {
1656    let mut num = provider.get_block_number().await?;
1657
1658    // walk back from the head of the chain, but at most 2 blocks, which should be more than enough
1659    // leeway
1660    for _ in 0..2 {
1661        if let Some(block) = provider.get_block(num.into()).await?
1662            && !block.header.hash.is_zero()
1663        {
1664            break;
1665        }
1666        // block not actually finalized, so we try the block before
1667        num = num.saturating_sub(1)
1668    }
1669
1670    Ok(num)
1671}
1672
1673#[cfg(test)]
1674mod tests {
1675    use super::*;
1676
1677    #[test]
1678    fn test_prune_history() {
1679        let config = PruneStateHistoryConfig::default();
1680        assert!(config.is_state_history_supported());
1681        let config = PruneStateHistoryConfig::from_args(Some(None));
1682        assert!(!config.is_state_history_supported());
1683        let config = PruneStateHistoryConfig::from_args(Some(Some(10)));
1684        assert!(config.is_state_history_supported());
1685    }
1686}