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_consensus::BlockHeader;
18use alloy_eips::{eip1559::BaseFeeParams, eip7840::BlobParams};
19use alloy_evm::EvmEnv;
20use alloy_genesis::Genesis;
21use alloy_network::{AnyNetwork, TransactionResponse};
22use alloy_primitives::{BlockNumber, TxHash, U256, hex, map::HashMap, utils::Unit};
23use alloy_provider::Provider;
24use alloy_rpc_types::{Block, BlockNumberOrTag};
25use alloy_signer::Signer;
26use alloy_signer_local::{
27 MnemonicBuilder, PrivateKeySigner,
28 coins_bip39::{English, Mnemonic},
29};
30use alloy_transport::TransportError;
31use anvil_server::ServerConfig;
32use eyre::{Context, Result};
33use foundry_common::{
34 ALCHEMY_FREE_TIER_CUPS, NON_ARCHIVE_NODE_WARNING, REQUEST_TIMEOUT,
35 provider::{ProviderBuilder, RetryProvider},
36};
37use foundry_config::Config;
38use foundry_evm::{
39 backend::{BlockchainDb, BlockchainDbMeta, SharedBackend},
40 constants::DEFAULT_CREATE2_DEPLOYER,
41 core::AsEnvMut,
42 hardfork::{
43 FoundryHardfork, OpHardfork, ethereum_hardfork_from_block_tag,
44 spec_id_from_ethereum_hardfork,
45 },
46 utils::{apply_chain_and_block_specific_env_changes, get_blob_base_fee_update_fraction},
47};
48use itertools::Itertools;
49use op_revm::OpTransaction;
50use parking_lot::RwLock;
51use rand_08::thread_rng;
52use revm::{
53 context::{BlockEnv, CfgEnv, TxEnv},
54 context_interface::block::BlobExcessGasAndPrice,
55 primitives::hardfork::SpecId,
56};
57use serde_json::{Value, json};
58use std::{
59 fmt::Write as FmtWrite,
60 fs::File,
61 io,
62 net::{IpAddr, Ipv4Addr},
63 path::PathBuf,
64 sync::Arc,
65 time::Duration,
66};
67use tokio::sync::RwLock as TokioRwLock;
68use yansi::Paint;
69
70pub use foundry_common::version::SHORT_VERSION as VERSION_MESSAGE;
71use foundry_evm::{
72 traces::{CallTraceDecoderBuilder, identifier::SignaturesIdentifier},
73 utils::get_blob_params,
74};
75use foundry_evm_networks::NetworkConfigs;
76
77pub const NODE_PORT: u16 = 8545;
79pub const CHAIN_ID: u64 = 31337;
81pub const DEFAULT_GAS_LIMIT: u64 = 30_000_000;
83pub const DEFAULT_MNEMONIC: &str = "test test test test test test test test test test test junk";
85
86pub const DEFAULT_IPC_ENDPOINT: &str =
88 if cfg!(unix) { "/tmp/anvil.ipc" } else { r"\\.\pipe\anvil.ipc" };
89
90const BANNER: &str = r"
91 _ _
92 (_) | |
93 __ _ _ __ __ __ _ | |
94 / _` | | '_ \ \ \ / / | | | |
95 | (_| | | | | | \ V / | | | |
96 \__,_| |_| |_| \_/ |_| |_|
97";
98
99#[derive(Clone, Debug)]
101pub struct NodeConfig {
102 pub chain_id: Option<u64>,
104 pub gas_limit: Option<u64>,
106 pub disable_block_gas_limit: bool,
108 pub enable_tx_gas_limit: bool,
110 pub gas_price: Option<u128>,
112 pub base_fee: Option<u64>,
114 pub disable_min_priority_fee: bool,
116 pub blob_excess_gas_and_price: Option<BlobExcessGasAndPrice>,
118 pub hardfork: Option<FoundryHardfork>,
120 pub genesis_accounts: Vec<PrivateKeySigner>,
122 pub genesis_balance: U256,
124 pub genesis_timestamp: Option<u64>,
126 pub genesis_block_number: Option<u64>,
128 pub signer_accounts: Vec<PrivateKeySigner>,
130 pub block_time: Option<Duration>,
132 pub no_mining: bool,
134 pub mixed_mining: bool,
136 pub port: u16,
138 pub max_transactions: usize,
140 pub eth_rpc_url: Option<String>,
142 pub fork_choice: Option<ForkChoice>,
144 pub fork_headers: Vec<String>,
146 pub fork_chain_id: Option<U256>,
148 pub account_generator: Option<AccountGenerator>,
150 pub enable_tracing: bool,
152 pub no_storage_caching: bool,
154 pub server_config: ServerConfig,
156 pub host: Vec<IpAddr>,
158 pub transaction_order: TransactionOrder,
160 pub config_out: Option<PathBuf>,
162 pub genesis: Option<Genesis>,
164 pub fork_request_timeout: Duration,
166 pub fork_request_retries: u32,
168 pub fork_retry_backoff: Duration,
170 pub compute_units_per_second: u64,
172 pub ipc_path: Option<Option<String>>,
174 pub enable_steps_tracing: bool,
176 pub print_logs: bool,
178 pub print_traces: bool,
180 pub enable_auto_impersonate: bool,
182 pub code_size_limit: Option<usize>,
184 pub prune_history: PruneStateHistoryConfig,
188 pub max_persisted_states: Option<usize>,
190 pub init_state: Option<SerializableState>,
192 pub transaction_block_keeper: Option<usize>,
194 pub disable_default_create2_deployer: bool,
196 pub disable_pool_balance_checks: bool,
198 pub slots_in_an_epoch: u64,
200 pub memory_limit: Option<u64>,
202 pub precompile_factory: Option<Arc<dyn PrecompileFactory>>,
204 pub networks: NetworkConfigs,
206 pub silent: bool,
208 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 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 #[doc(hidden)]
426 pub fn test() -> Self {
427 Self { enable_tracing: true, port: 0, silent: true, ..Default::default() }
428 }
429
430 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 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 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 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 #[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 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 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.get_chain_id(),
537 self.get_genesis_timestamp(),
538 ),
539 )
540 }
541 }
542
543 pub fn get_blob_params(&self) -> BlobParams {
545 get_blob_params(self.get_chain_id(), self.get_genesis_timestamp())
546 }
547
548 pub fn get_hardfork(&self) -> FoundryHardfork {
550 if let Some(hardfork) = self.hardfork {
551 return hardfork;
552 }
553 if self.networks.is_optimism() {
554 return OpHardfork::default().into();
555 }
556 EthereumHardfork::default().into()
557 }
558
559 #[must_use]
561 pub fn with_code_size_limit(mut self, code_size_limit: Option<usize>) -> Self {
562 self.code_size_limit = code_size_limit;
563 self
564 }
565 #[must_use]
567 pub fn disable_code_size_limit(mut self, disable_code_size_limit: bool) -> Self {
568 if disable_code_size_limit {
569 self.code_size_limit = Some(usize::MAX);
570 }
571 self
572 }
573
574 #[must_use]
576 pub fn with_init_state(mut self, init_state: Option<SerializableState>) -> Self {
577 self.init_state = init_state;
578 self
579 }
580
581 #[must_use]
583 #[cfg(feature = "cmd")]
584 pub fn with_init_state_path(mut self, path: impl AsRef<std::path::Path>) -> Self {
585 self.init_state = crate::cmd::StateFile::parse_path(path).ok().and_then(|file| file.state);
586 self
587 }
588
589 #[must_use]
591 pub fn with_chain_id<U: Into<u64>>(mut self, chain_id: Option<U>) -> Self {
592 self.set_chain_id(chain_id);
593 self
594 }
595
596 pub fn get_chain_id(&self) -> u64 {
598 self.chain_id
599 .or_else(|| self.genesis.as_ref().map(|g| g.config.chain_id))
600 .unwrap_or(CHAIN_ID)
601 }
602
603 pub fn set_chain_id(&mut self, chain_id: Option<impl Into<u64>>) {
605 self.chain_id = chain_id.map(Into::into);
606 let chain_id = self.get_chain_id();
607 self.networks.with_chain_id(chain_id);
608 self.genesis_accounts.iter_mut().for_each(|wallet| {
609 *wallet = wallet.clone().with_chain_id(Some(chain_id));
610 });
611 self.signer_accounts.iter_mut().for_each(|wallet| {
612 *wallet = wallet.clone().with_chain_id(Some(chain_id));
613 })
614 }
615
616 #[must_use]
618 pub fn with_gas_limit(mut self, gas_limit: Option<u64>) -> Self {
619 self.gas_limit = gas_limit;
620 self
621 }
622
623 #[must_use]
627 pub fn disable_block_gas_limit(mut self, disable_block_gas_limit: bool) -> Self {
628 self.disable_block_gas_limit = disable_block_gas_limit;
629 self
630 }
631
632 #[must_use]
636 pub fn enable_tx_gas_limit(mut self, enable_tx_gas_limit: bool) -> Self {
637 self.enable_tx_gas_limit = enable_tx_gas_limit;
638 self
639 }
640
641 #[must_use]
643 pub fn with_gas_price(mut self, gas_price: Option<u128>) -> Self {
644 self.gas_price = gas_price;
645 self
646 }
647
648 #[must_use]
650 pub fn set_pruned_history(mut self, prune_history: Option<Option<usize>>) -> Self {
651 self.prune_history = PruneStateHistoryConfig::from_args(prune_history);
652 self
653 }
654
655 #[must_use]
657 pub fn with_max_persisted_states<U: Into<usize>>(
658 mut self,
659 max_persisted_states: Option<U>,
660 ) -> Self {
661 self.max_persisted_states = max_persisted_states.map(Into::into);
662 self
663 }
664
665 #[must_use]
667 pub fn with_transaction_block_keeper<U: Into<usize>>(
668 mut self,
669 transaction_block_keeper: Option<U>,
670 ) -> Self {
671 self.transaction_block_keeper = transaction_block_keeper.map(Into::into);
672 self
673 }
674
675 #[must_use]
677 pub fn with_base_fee(mut self, base_fee: Option<u64>) -> Self {
678 self.base_fee = base_fee;
679 self
680 }
681
682 #[must_use]
684 pub fn disable_min_priority_fee(mut self, disable_min_priority_fee: bool) -> Self {
685 self.disable_min_priority_fee = disable_min_priority_fee;
686 self
687 }
688
689 #[must_use]
691 pub fn with_genesis(mut self, genesis: Option<Genesis>) -> Self {
692 self.genesis = genesis;
693 self
694 }
695
696 pub fn get_genesis_timestamp(&self) -> u64 {
698 self.genesis_timestamp
699 .or_else(|| self.genesis.as_ref().map(|g| g.timestamp))
700 .unwrap_or_else(|| duration_since_unix_epoch().as_secs())
701 }
702
703 #[must_use]
705 pub fn with_genesis_timestamp<U: Into<u64>>(mut self, timestamp: Option<U>) -> Self {
706 if let Some(timestamp) = timestamp {
707 self.genesis_timestamp = Some(timestamp.into());
708 }
709 self
710 }
711
712 #[must_use]
714 pub fn with_genesis_block_number<U: Into<u64>>(mut self, number: Option<U>) -> Self {
715 if let Some(number) = number {
716 self.genesis_block_number = Some(number.into());
717 }
718 self
719 }
720
721 pub fn get_genesis_number(&self) -> u64 {
723 self.genesis_block_number
724 .or_else(|| self.genesis.as_ref().and_then(|g| g.number))
725 .unwrap_or(0)
726 }
727
728 #[must_use]
730 pub fn with_hardfork(mut self, hardfork: Option<FoundryHardfork>) -> Self {
731 self.hardfork = hardfork;
732 self
733 }
734
735 #[must_use]
737 pub fn with_genesis_accounts(mut self, accounts: Vec<PrivateKeySigner>) -> Self {
738 self.genesis_accounts = accounts;
739 self
740 }
741
742 #[must_use]
744 pub fn with_signer_accounts(mut self, accounts: Vec<PrivateKeySigner>) -> Self {
745 self.signer_accounts = accounts;
746 self
747 }
748
749 pub fn with_account_generator(mut self, generator: AccountGenerator) -> eyre::Result<Self> {
752 let accounts = generator.generate()?;
753 self.account_generator = Some(generator);
754 Ok(self.with_signer_accounts(accounts.clone()).with_genesis_accounts(accounts))
755 }
756
757 #[must_use]
759 pub fn with_genesis_balance<U: Into<U256>>(mut self, balance: U) -> Self {
760 self.genesis_balance = balance.into();
761 self
762 }
763
764 #[must_use]
766 pub fn with_blocktime<D: Into<Duration>>(mut self, block_time: Option<D>) -> Self {
767 self.block_time = block_time.map(Into::into);
768 self
769 }
770
771 #[must_use]
772 pub fn with_mixed_mining<D: Into<Duration>>(
773 mut self,
774 mixed_mining: bool,
775 block_time: Option<D>,
776 ) -> Self {
777 self.block_time = block_time.map(Into::into);
778 self.mixed_mining = mixed_mining;
779 self
780 }
781
782 #[must_use]
784 pub fn with_no_mining(mut self, no_mining: bool) -> Self {
785 self.no_mining = no_mining;
786 self
787 }
788
789 #[must_use]
791 pub fn with_slots_in_an_epoch(mut self, slots_in_an_epoch: u64) -> Self {
792 self.slots_in_an_epoch = slots_in_an_epoch;
793 self
794 }
795
796 #[must_use]
798 pub fn with_port(mut self, port: u16) -> Self {
799 self.port = port;
800 self
801 }
802
803 #[must_use]
810 pub fn with_ipc(mut self, ipc_path: Option<Option<String>>) -> Self {
811 self.ipc_path = ipc_path;
812 self
813 }
814
815 #[must_use]
817 pub fn set_config_out(mut self, config_out: Option<PathBuf>) -> Self {
818 self.config_out = config_out;
819 self
820 }
821
822 #[must_use]
824 pub fn no_storage_caching(self) -> Self {
825 self.with_storage_caching(true)
826 }
827
828 #[must_use]
829 pub fn with_storage_caching(mut self, storage_caching: bool) -> Self {
830 self.no_storage_caching = storage_caching;
831 self
832 }
833
834 #[must_use]
836 pub fn with_eth_rpc_url<U: Into<String>>(mut self, eth_rpc_url: Option<U>) -> Self {
837 self.eth_rpc_url = eth_rpc_url.map(Into::into);
838 self
839 }
840
841 #[must_use]
843 pub fn with_fork_block_number<U: Into<u64>>(self, fork_block_number: Option<U>) -> Self {
844 self.with_fork_choice(fork_block_number.map(Into::into))
845 }
846
847 #[must_use]
849 pub fn with_fork_transaction_hash<U: Into<TxHash>>(
850 self,
851 fork_transaction_hash: Option<U>,
852 ) -> Self {
853 self.with_fork_choice(fork_transaction_hash.map(Into::into))
854 }
855
856 #[must_use]
858 pub fn with_fork_choice<U: Into<ForkChoice>>(mut self, fork_choice: Option<U>) -> Self {
859 self.fork_choice = fork_choice.map(Into::into);
860 self
861 }
862
863 #[must_use]
865 pub fn with_fork_chain_id(mut self, fork_chain_id: Option<U256>) -> Self {
866 self.fork_chain_id = fork_chain_id;
867 self
868 }
869
870 #[must_use]
872 pub fn with_fork_headers(mut self, headers: Vec<String>) -> Self {
873 self.fork_headers = headers;
874 self
875 }
876
877 #[must_use]
879 pub fn fork_request_timeout(mut self, fork_request_timeout: Option<Duration>) -> Self {
880 if let Some(fork_request_timeout) = fork_request_timeout {
881 self.fork_request_timeout = fork_request_timeout;
882 }
883 self
884 }
885
886 #[must_use]
888 pub fn fork_request_retries(mut self, fork_request_retries: Option<u32>) -> Self {
889 if let Some(fork_request_retries) = fork_request_retries {
890 self.fork_request_retries = fork_request_retries;
891 }
892 self
893 }
894
895 #[must_use]
897 pub fn fork_retry_backoff(mut self, fork_retry_backoff: Option<Duration>) -> Self {
898 if let Some(fork_retry_backoff) = fork_retry_backoff {
899 self.fork_retry_backoff = fork_retry_backoff;
900 }
901 self
902 }
903
904 #[must_use]
908 pub fn fork_compute_units_per_second(mut self, compute_units_per_second: Option<u64>) -> Self {
909 if let Some(compute_units_per_second) = compute_units_per_second {
910 self.compute_units_per_second = compute_units_per_second;
911 }
912 self
913 }
914
915 #[must_use]
917 pub fn with_tracing(mut self, enable_tracing: bool) -> Self {
918 self.enable_tracing = enable_tracing;
919 self
920 }
921
922 #[must_use]
924 pub fn with_steps_tracing(mut self, enable_steps_tracing: bool) -> Self {
925 self.enable_steps_tracing = enable_steps_tracing;
926 self
927 }
928
929 #[must_use]
931 pub fn with_print_logs(mut self, print_logs: bool) -> Self {
932 self.print_logs = print_logs;
933 self
934 }
935
936 #[must_use]
938 pub fn with_print_traces(mut self, print_traces: bool) -> Self {
939 self.print_traces = print_traces;
940 self
941 }
942
943 #[must_use]
945 pub fn with_auto_impersonate(mut self, enable_auto_impersonate: bool) -> Self {
946 self.enable_auto_impersonate = enable_auto_impersonate;
947 self
948 }
949
950 #[must_use]
951 pub fn with_server_config(mut self, config: ServerConfig) -> Self {
952 self.server_config = config;
953 self
954 }
955
956 #[must_use]
958 pub fn with_host(mut self, host: Vec<IpAddr>) -> Self {
959 self.host = if host.is_empty() { vec![IpAddr::V4(Ipv4Addr::LOCALHOST)] } else { host };
960 self
961 }
962
963 #[must_use]
964 pub fn with_transaction_order(mut self, transaction_order: TransactionOrder) -> Self {
965 self.transaction_order = transaction_order;
966 self
967 }
968
969 pub fn get_ipc_path(&self) -> Option<String> {
971 match &self.ipc_path {
972 Some(path) => path.clone().or_else(|| Some(DEFAULT_IPC_ENDPOINT.to_string())),
973 None => None,
974 }
975 }
976
977 pub fn print(&self, fork: Option<&ClientFork>) -> Result<()> {
979 if let Some(path) = &self.config_out {
980 let file = io::BufWriter::new(
981 File::create(path).wrap_err("unable to create anvil config description file")?,
982 );
983 let value = self.as_json(fork);
984 serde_json::to_writer(file, &value).wrap_err("failed writing JSON")?;
985 }
986 if !self.silent {
987 sh_println!("{}", self.as_string(fork))?;
988 }
989 Ok(())
990 }
991
992 pub fn block_cache_path(&self, block: u64) -> Option<PathBuf> {
996 if self.no_storage_caching || self.eth_rpc_url.is_none() {
997 return None;
998 }
999 let chain_id = self.get_chain_id();
1000
1001 Config::foundry_block_cache_file(chain_id, block)
1002 }
1003
1004 #[must_use]
1006 pub fn with_disable_default_create2_deployer(mut self, yes: bool) -> Self {
1007 self.disable_default_create2_deployer = yes;
1008 self
1009 }
1010
1011 #[must_use]
1013 pub fn with_disable_pool_balance_checks(mut self, yes: bool) -> Self {
1014 self.disable_pool_balance_checks = yes;
1015 self
1016 }
1017
1018 #[must_use]
1020 pub fn with_precompile_factory(mut self, factory: impl PrecompileFactory + 'static) -> Self {
1021 self.precompile_factory = Some(Arc::new(factory));
1022 self
1023 }
1024
1025 #[must_use]
1027 pub fn with_networks(mut self, networks: NetworkConfigs) -> Self {
1028 self.networks = networks;
1029 self
1030 }
1031
1032 #[must_use]
1034 pub fn silent(self) -> Self {
1035 self.set_silent(true)
1036 }
1037
1038 #[must_use]
1039 pub fn set_silent(mut self, silent: bool) -> Self {
1040 self.silent = silent;
1041 self
1042 }
1043
1044 #[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 pub(crate) async fn setup(&mut self) -> Result<mem::Backend> {
1059 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 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 base_fee_params: BaseFeeParams =
1098 self.networks.base_fee_params(self.get_genesis_timestamp());
1099
1100 let fees = FeeManager::new(
1101 spec_id,
1102 self.get_base_fee(),
1103 !self.disable_min_priority_fee,
1104 self.get_gas_price(),
1105 self.get_blob_excess_gas_and_price(),
1106 self.get_blob_params(),
1107 base_fee_params,
1108 );
1109
1110 let (db, fork): (Arc<TokioRwLock<Box<dyn Db>>>, Option<ClientFork>) =
1111 if let Some(eth_rpc_url) = self.eth_rpc_url.clone() {
1112 self.setup_fork_db(eth_rpc_url, &mut env, &fees).await?
1113 } else {
1114 (Arc::new(TokioRwLock::new(Box::<MemDb>::default())), None)
1115 };
1116
1117 if let Some(ref genesis) = self.genesis {
1119 if self.chain_id.is_none() {
1122 env.evm_env.cfg_env.chain_id = genesis.config.chain_id;
1123 }
1124 env.evm_env.block_env.timestamp = U256::from(genesis.timestamp);
1125 if let Some(base_fee) = genesis.base_fee_per_gas {
1126 env.evm_env.block_env.basefee = base_fee.try_into()?;
1127 }
1128 if let Some(number) = genesis.number {
1129 env.evm_env.block_env.number = U256::from(number);
1130 }
1131 env.evm_env.block_env.beneficiary = genesis.coinbase;
1132 }
1133
1134 let genesis = GenesisConfig {
1135 number: self.get_genesis_number(),
1136 timestamp: self.get_genesis_timestamp(),
1137 balance: self.genesis_balance,
1138 accounts: self.genesis_accounts.iter().map(|acc| acc.address()).collect(),
1139 genesis_init: self.genesis.clone(),
1140 };
1141
1142 let mut decoder_builder = CallTraceDecoderBuilder::new();
1143 if self.print_traces {
1144 if let Ok(identifier) = SignaturesIdentifier::new(false) {
1146 debug!(target: "node", "using signature identifier");
1147 decoder_builder = decoder_builder.with_signature_identifier(identifier);
1148 }
1149 }
1150
1151 let backend = mem::Backend::with_genesis(
1153 db,
1154 Arc::new(RwLock::new(env)),
1155 genesis,
1156 fees,
1157 Arc::new(RwLock::new(fork)),
1158 self.enable_steps_tracing,
1159 self.print_logs,
1160 self.print_traces,
1161 Arc::new(decoder_builder.build()),
1162 self.prune_history,
1163 self.max_persisted_states,
1164 self.transaction_block_keeper,
1165 self.block_time,
1166 self.cache_path.clone(),
1167 Arc::new(TokioRwLock::new(self.clone())),
1168 )
1169 .await?;
1170
1171 if !self.disable_default_create2_deployer && self.eth_rpc_url.is_none() {
1174 backend
1175 .set_create2_deployer(DEFAULT_CREATE2_DEPLOYER)
1176 .await
1177 .wrap_err("failed to create default create2 deployer")?;
1178 }
1179
1180 if let Some(state) = self.init_state.clone() {
1181 backend.load_state(state).await.wrap_err("failed to load init state")?;
1182 }
1183
1184 Ok(backend)
1185 }
1186
1187 pub async fn setup_fork_db(
1194 &mut self,
1195 eth_rpc_url: String,
1196 env: &mut Env,
1197 fees: &FeeManager,
1198 ) -> Result<(Arc<TokioRwLock<Box<dyn Db>>>, Option<ClientFork>)> {
1199 let (db, config) = self.setup_fork_db_config(eth_rpc_url, env, fees).await?;
1200 let db: Arc<TokioRwLock<Box<dyn Db>>> = Arc::new(TokioRwLock::new(Box::new(db)));
1201 let fork = ClientFork::new(config, Arc::clone(&db));
1202 Ok((db, Some(fork)))
1203 }
1204
1205 pub async fn setup_fork_db_config(
1211 &mut self,
1212 eth_rpc_url: String,
1213 env: &mut Env,
1214 fees: &FeeManager,
1215 ) -> Result<(ForkedDatabase, ClientForkConfig)> {
1216 debug!(target: "node", ?eth_rpc_url, "setting up fork db");
1217 let provider = Arc::new(
1218 ProviderBuilder::new(ð_rpc_url)
1219 .timeout(self.fork_request_timeout)
1220 .initial_backoff(self.fork_retry_backoff.as_millis() as u64)
1221 .compute_units_per_second(self.compute_units_per_second)
1222 .max_retry(self.fork_request_retries)
1223 .headers(self.fork_headers.clone())
1224 .build()
1225 .wrap_err("failed to establish provider to fork url")?,
1226 );
1227
1228 let (fork_block_number, fork_chain_id, force_transactions) = if let Some(fork_choice) =
1229 &self.fork_choice
1230 {
1231 let (fork_block_number, force_transactions) =
1232 derive_block_and_transactions(fork_choice, &provider).await.wrap_err(
1233 "failed to derive fork block number and force transactions from fork choice",
1234 )?;
1235 let chain_id = if let Some(chain_id) = self.fork_chain_id {
1236 Some(chain_id)
1237 } else if self.hardfork.is_none() {
1238 let chain_id =
1240 provider.get_chain_id().await.wrap_err("failed to fetch network chain ID")?;
1241 if alloy_chains::NamedChain::Mainnet == chain_id {
1242 let hardfork: EthereumHardfork =
1243 ethereum_hardfork_from_block_tag(fork_block_number);
1244
1245 env.evm_env.cfg_env.spec = spec_id_from_ethereum_hardfork(hardfork);
1246 self.hardfork = Some(FoundryHardfork::Ethereum(hardfork));
1247 }
1248 Some(U256::from(chain_id))
1249 } else {
1250 None
1251 };
1252
1253 (fork_block_number, chain_id, force_transactions)
1254 } else {
1255 let bn = find_latest_fork_block(&provider)
1257 .await
1258 .wrap_err("failed to get fork block number")?;
1259 (bn, None, None)
1260 };
1261
1262 let block = provider
1263 .get_block(BlockNumberOrTag::Number(fork_block_number).into())
1264 .await
1265 .wrap_err("failed to get fork block")?;
1266
1267 let block = if let Some(block) = block {
1268 block
1269 } else {
1270 if let Ok(latest_block) = provider.get_block_number().await {
1271 let mut message = format!(
1272 "Failed to get block for block number: {fork_block_number}\n\
1273latest block number: {latest_block}"
1274 );
1275 if fork_block_number <= latest_block {
1279 message.push_str(&format!("\n{NON_ARCHIVE_NODE_WARNING}"));
1280 }
1281 eyre::bail!("{message}");
1282 }
1283 eyre::bail!("failed to get block for block number: {fork_block_number}")
1284 };
1285
1286 let gas_limit = self.fork_gas_limit(&block);
1287 self.gas_limit = Some(gas_limit);
1288
1289 env.evm_env.block_env = BlockEnv {
1290 number: U256::from(fork_block_number),
1291 timestamp: U256::from(block.header.timestamp),
1292 difficulty: block.header.difficulty,
1293 prevrandao: Some(block.header.mix_hash.unwrap_or_default()),
1295 gas_limit,
1296 beneficiary: env.evm_env.block_env.beneficiary,
1298 basefee: env.evm_env.block_env.basefee,
1299 ..Default::default()
1300 };
1301
1302 let chain_id = if let Some(chain_id) = self.chain_id {
1304 chain_id
1305 } else {
1306 let chain_id = if let Some(fork_chain_id) = fork_chain_id {
1307 fork_chain_id.to()
1308 } else {
1309 provider.get_chain_id().await.wrap_err("failed to fetch network chain ID")?
1310 };
1311
1312 self.set_chain_id(Some(chain_id));
1314 env.evm_env.cfg_env.chain_id = chain_id;
1315 env.tx.base.chain_id = chain_id.into();
1316 chain_id
1317 };
1318
1319 if self.base_fee.is_none() {
1321 if let Some(base_fee) = block.header.base_fee_per_gas {
1322 self.base_fee = Some(base_fee);
1323 env.evm_env.block_env.basefee = base_fee;
1324 let next_block_base_fee = fees.get_next_block_base_fee_per_gas(
1327 block.header.gas_used,
1328 gas_limit,
1329 block.header.base_fee_per_gas.unwrap_or_default(),
1330 );
1331
1332 fees.set_base_fee(next_block_base_fee);
1334 }
1335 if let (Some(blob_excess_gas), Some(blob_gas_used)) =
1336 (block.header.excess_blob_gas, block.header.blob_gas_used)
1337 {
1338 let blob_params = get_blob_params(chain_id, block.header.timestamp);
1340
1341 env.evm_env.block_env.blob_excess_gas_and_price = Some(BlobExcessGasAndPrice::new(
1342 blob_excess_gas,
1343 blob_params.update_fraction as u64,
1344 ));
1345
1346 fees.set_blob_params(blob_params);
1347
1348 let next_block_blob_excess_gas =
1349 fees.get_next_block_blob_excess_gas(blob_excess_gas, blob_gas_used);
1350 fees.set_blob_excess_gas_and_price(BlobExcessGasAndPrice::new(
1351 next_block_blob_excess_gas,
1352 blob_params.update_fraction as u64,
1353 ));
1354 }
1355 }
1356
1357 if self.gas_price.is_none()
1359 && let Ok(gas_price) = provider.get_gas_price().await
1360 {
1361 self.gas_price = Some(gas_price);
1362 fees.set_gas_price(gas_price);
1363 }
1364
1365 let block_hash = block.header.hash;
1366
1367 let override_chain_id = self.chain_id;
1368 apply_chain_and_block_specific_env_changes::<AnyNetwork>(
1370 env.as_env_mut(),
1371 &block,
1372 self.networks,
1373 );
1374
1375 let meta = BlockchainDbMeta::new(env.evm_env.block_env.clone(), eth_rpc_url.clone());
1376 let block_chain_db = if self.fork_chain_id.is_some() {
1377 BlockchainDb::new_skip_check(meta, self.block_cache_path(fork_block_number))
1378 } else {
1379 BlockchainDb::new(meta, self.block_cache_path(fork_block_number))
1380 };
1381
1382 let backend = SharedBackend::spawn_backend(
1385 Arc::clone(&provider),
1386 block_chain_db.clone(),
1387 Some(fork_block_number.into()),
1388 )
1389 .await;
1390
1391 let config = ClientForkConfig {
1392 eth_rpc_url,
1393 block_number: fork_block_number,
1394 block_hash,
1395 transaction_hash: self.fork_choice.and_then(|fc| fc.transaction_hash()),
1396 provider,
1397 chain_id,
1398 override_chain_id,
1399 timestamp: block.header.timestamp,
1400 base_fee: block.header.base_fee_per_gas.map(|g| g as u128),
1401 timeout: self.fork_request_timeout,
1402 retries: self.fork_request_retries,
1403 backoff: self.fork_retry_backoff,
1404 compute_units_per_second: self.compute_units_per_second,
1405 total_difficulty: block.header.total_difficulty.unwrap_or_default(),
1406 blob_gas_used: block.header.blob_gas_used.map(|g| g as u128),
1407 blob_excess_gas_and_price: env.evm_env.block_env.blob_excess_gas_and_price,
1408 force_transactions,
1409 };
1410
1411 debug!(target: "node", fork_number=config.block_number, fork_hash=%config.block_hash, "set up fork db");
1412
1413 let mut db = ForkedDatabase::new(backend, block_chain_db);
1414
1415 db.insert_block_hash(U256::from(config.block_number), config.block_hash);
1417
1418 Ok((db, config))
1419 }
1420
1421 pub(crate) fn fork_gas_limit<T: TransactionResponse, H: BlockHeader>(
1425 &self,
1426 block: &Block<T, H>,
1427 ) -> u64 {
1428 if !self.disable_block_gas_limit {
1429 if let Some(gas_limit) = self.gas_limit {
1430 return gas_limit;
1431 } else if block.header.gas_limit() > 0 {
1432 return block.header.gas_limit();
1433 }
1434 }
1435
1436 u64::MAX
1437 }
1438
1439 pub(crate) fn gas_limit(&self) -> u64 {
1443 if self.disable_block_gas_limit {
1444 return u64::MAX;
1445 }
1446
1447 self.gas_limit.unwrap_or(DEFAULT_GAS_LIMIT)
1448 }
1449}
1450
1451async fn derive_block_and_transactions(
1456 fork_choice: &ForkChoice,
1457 provider: &Arc<RetryProvider>,
1458) -> eyre::Result<(BlockNumber, Option<Vec<PoolTransaction>>)> {
1459 match fork_choice {
1460 ForkChoice::Block(block_number) => {
1461 let block_number = *block_number;
1462 if block_number >= 0 {
1463 return Ok((block_number as u64, None));
1464 }
1465 let latest = provider.get_block_number().await?;
1467
1468 Ok((block_number.saturating_add(latest as i128) as u64, None))
1469 }
1470 ForkChoice::Transaction(transaction_hash) => {
1471 let transaction = provider
1473 .get_transaction_by_hash(transaction_hash.0.into())
1474 .await?
1475 .ok_or_else(|| eyre::eyre!("failed to get fork transaction by hash"))?;
1476 let transaction_block_number = transaction.block_number.ok_or_else(|| {
1477 eyre::eyre!("fork transaction is not mined yet (no block number)")
1478 })?;
1479
1480 let transaction_block = provider
1482 .get_block_by_number(transaction_block_number.into())
1483 .full()
1484 .await?
1485 .ok_or_else(|| eyre::eyre!("failed to get fork block by number"))?;
1486
1487 let filtered_transactions = transaction_block
1489 .transactions
1490 .as_transactions()
1491 .ok_or_else(|| eyre::eyre!("failed to get transactions from full fork block"))?
1492 .iter()
1493 .take_while_inclusive(|&transaction| transaction.tx_hash() != transaction_hash.0)
1494 .collect::<Vec<_>>();
1495
1496 let force_transactions = filtered_transactions
1498 .iter()
1499 .map(|&transaction| PoolTransaction::try_from(transaction.clone()))
1500 .collect::<Result<Vec<_>, _>>()
1501 .map_err(|e| eyre::eyre!("Err converting to pool transactions {e}"))?;
1502 Ok((transaction_block_number.saturating_sub(1), Some(force_transactions)))
1503 }
1504 }
1505}
1506
1507#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1509pub enum ForkChoice {
1510 Block(i128),
1514 Transaction(TxHash),
1516}
1517
1518impl ForkChoice {
1519 pub fn block_number(&self) -> Option<i128> {
1521 match self {
1522 Self::Block(block_number) => Some(*block_number),
1523 Self::Transaction(_) => None,
1524 }
1525 }
1526
1527 pub fn transaction_hash(&self) -> Option<TxHash> {
1529 match self {
1530 Self::Block(_) => None,
1531 Self::Transaction(transaction_hash) => Some(*transaction_hash),
1532 }
1533 }
1534}
1535
1536impl From<TxHash> for ForkChoice {
1538 fn from(tx_hash: TxHash) -> Self {
1539 Self::Transaction(tx_hash)
1540 }
1541}
1542
1543impl From<u64> for ForkChoice {
1545 fn from(block: u64) -> Self {
1546 Self::Block(block as i128)
1547 }
1548}
1549
1550#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
1551pub struct PruneStateHistoryConfig {
1552 pub enabled: bool,
1553 pub max_memory_history: Option<usize>,
1554}
1555
1556impl PruneStateHistoryConfig {
1557 pub fn is_state_history_supported(&self) -> bool {
1559 !self.enabled || self.max_memory_history.is_some()
1560 }
1561
1562 pub fn is_config_enabled(&self) -> bool {
1564 self.enabled
1565 }
1566
1567 pub fn from_args(val: Option<Option<usize>>) -> Self {
1568 val.map(|max_memory_history| Self { enabled: true, max_memory_history }).unwrap_or_default()
1569 }
1570}
1571
1572#[derive(Clone, Debug)]
1574pub struct AccountGenerator {
1575 chain_id: u64,
1576 amount: usize,
1577 phrase: String,
1578 derivation_path: Option<String>,
1579}
1580
1581impl AccountGenerator {
1582 pub fn new(amount: usize) -> Self {
1583 Self {
1584 chain_id: CHAIN_ID,
1585 amount,
1586 phrase: Mnemonic::<English>::new(&mut thread_rng()).to_phrase(),
1587 derivation_path: None,
1588 }
1589 }
1590
1591 #[must_use]
1592 pub fn phrase(mut self, phrase: impl Into<String>) -> Self {
1593 self.phrase = phrase.into();
1594 self
1595 }
1596
1597 fn get_phrase(&self) -> &str {
1598 &self.phrase
1599 }
1600
1601 #[must_use]
1602 pub fn chain_id(mut self, chain_id: impl Into<u64>) -> Self {
1603 self.chain_id = chain_id.into();
1604 self
1605 }
1606
1607 #[must_use]
1608 pub fn derivation_path(mut self, derivation_path: impl Into<String>) -> Self {
1609 let mut derivation_path = derivation_path.into();
1610 if !derivation_path.ends_with('/') {
1611 derivation_path.push('/');
1612 }
1613 self.derivation_path = Some(derivation_path);
1614 self
1615 }
1616
1617 fn get_derivation_path(&self) -> &str {
1618 self.derivation_path.as_deref().unwrap_or("m/44'/60'/0'/0/")
1619 }
1620}
1621
1622impl AccountGenerator {
1623 pub fn generate(&self) -> eyre::Result<Vec<PrivateKeySigner>> {
1624 let builder = MnemonicBuilder::<English>::default().phrase(self.phrase.as_str());
1625
1626 let derivation_path = self.get_derivation_path();
1628
1629 let mut wallets = Vec::with_capacity(self.amount);
1630 for idx in 0..self.amount {
1631 let builder =
1632 builder.clone().derivation_path(format!("{derivation_path}{idx}")).unwrap();
1633 let wallet = builder.build()?.with_chain_id(Some(self.chain_id));
1634 wallets.push(wallet)
1635 }
1636 Ok(wallets)
1637 }
1638}
1639
1640pub fn anvil_dir() -> Option<PathBuf> {
1642 Config::foundry_dir().map(|p| p.join("anvil"))
1643}
1644
1645pub fn anvil_tmp_dir() -> Option<PathBuf> {
1647 anvil_dir().map(|p| p.join("tmp"))
1648}
1649
1650async fn find_latest_fork_block<P: Provider<AnyNetwork>>(
1655 provider: P,
1656) -> Result<u64, TransportError> {
1657 let mut num = provider.get_block_number().await?;
1658
1659 for _ in 0..2 {
1662 if let Some(block) = provider.get_block(num.into()).await?
1663 && !block.header.hash.is_zero()
1664 {
1665 break;
1666 }
1667 num = num.saturating_sub(1)
1669 }
1670
1671 Ok(num)
1672}
1673
1674#[cfg(test)]
1675mod tests {
1676 use super::*;
1677
1678 #[test]
1679 fn test_prune_history() {
1680 let config = PruneStateHistoryConfig::default();
1681 assert!(config.is_state_history_supported());
1682 let config = PruneStateHistoryConfig::from_args(Some(None));
1683 assert!(!config.is_state_history_supported());
1684 let config = PruneStateHistoryConfig::from_args(Some(Some(10)));
1685 assert!(config.is_state_history_supported());
1686 }
1687}