anvil/
cmd.rs

1use crate::{
2    AccountGenerator, CHAIN_ID, EthereumHardfork, NodeConfig,
3    config::{DEFAULT_MNEMONIC, ForkChoice},
4    eth::{EthApi, backend::db::SerializableState, pool::transactions::TransactionOrder},
5};
6use alloy_genesis::Genesis;
7use alloy_op_hardforks::OpHardfork;
8use alloy_primitives::{B256, U256, utils::Unit};
9use alloy_signer_local::coins_bip39::{English, Mnemonic};
10use anvil_server::ServerConfig;
11use clap::Parser;
12use core::fmt;
13use foundry_common::shell;
14use foundry_config::{Chain, Config, FigmentProviders};
15use foundry_evm_networks::NetworkConfigs;
16use futures::FutureExt;
17use rand_08::{SeedableRng, rngs::StdRng};
18use std::{
19    net::IpAddr,
20    path::{Path, PathBuf},
21    pin::Pin,
22    str::FromStr,
23    sync::{
24        Arc,
25        atomic::{AtomicUsize, Ordering},
26    },
27    task::{Context, Poll},
28    time::Duration,
29};
30use tokio::time::{Instant, Interval};
31
32#[derive(Clone, Debug, Parser)]
33pub struct NodeArgs {
34    /// Port number to listen on.
35    #[arg(long, short, default_value = "8545", value_name = "NUM")]
36    pub port: u16,
37
38    /// Number of dev accounts to generate and configure.
39    #[arg(long, short, default_value = "10", value_name = "NUM")]
40    pub accounts: u64,
41
42    /// The balance of every dev account in Ether.
43    #[arg(long, default_value = "10000", value_name = "NUM")]
44    pub balance: u64,
45
46    /// The timestamp of the genesis block.
47    #[arg(long, value_name = "NUM")]
48    pub timestamp: Option<u64>,
49
50    /// The number of the genesis block.
51    #[arg(long, value_name = "NUM")]
52    pub number: Option<u64>,
53
54    /// BIP39 mnemonic phrase used for generating accounts.
55    /// Cannot be used if `mnemonic_random` or `mnemonic_seed` are used.
56    #[arg(long, short, conflicts_with_all = &["mnemonic_seed", "mnemonic_random"])]
57    pub mnemonic: Option<String>,
58
59    /// Automatically generates a BIP39 mnemonic phrase, and derives accounts from it.
60    /// Cannot be used with other `mnemonic` options.
61    /// You can specify the number of words you want in the mnemonic.
62    /// [default: 12]
63    #[arg(long, conflicts_with_all = &["mnemonic", "mnemonic_seed"], default_missing_value = "12", num_args(0..=1))]
64    pub mnemonic_random: Option<usize>,
65
66    /// Generates a BIP39 mnemonic phrase from a given seed
67    /// Cannot be used with other `mnemonic` options.
68    ///
69    /// CAREFUL: This is NOT SAFE and should only be used for testing.
70    /// Never use the private keys generated in production.
71    #[arg(long = "mnemonic-seed-unsafe", conflicts_with_all = &["mnemonic", "mnemonic_random"])]
72    pub mnemonic_seed: Option<u64>,
73
74    /// Sets the derivation path of the child key to be derived.
75    ///
76    /// [default: m/44'/60'/0'/0/]
77    #[arg(long)]
78    pub derivation_path: Option<String>,
79
80    /// The EVM hardfork to use.
81    ///
82    /// Choose the hardfork by name, e.g. `prague`, `cancun`, `shanghai`, `paris`, `london`, etc...
83    /// [default: latest]
84    #[arg(long)]
85    pub hardfork: Option<String>,
86
87    /// Block time in seconds for interval mining.
88    #[arg(short, long, visible_alias = "blockTime", value_name = "SECONDS", value_parser = duration_from_secs_f64)]
89    pub block_time: Option<Duration>,
90
91    /// Slots in an epoch
92    #[arg(long, value_name = "SLOTS_IN_AN_EPOCH", default_value_t = 32)]
93    pub slots_in_an_epoch: u64,
94
95    /// Writes output of `anvil` as json to user-specified file.
96    #[arg(long, value_name = "FILE", value_hint = clap::ValueHint::FilePath)]
97    pub config_out: Option<PathBuf>,
98
99    /// Disable auto and interval mining, and mine on demand instead.
100    #[arg(long, visible_alias = "no-mine", conflicts_with = "block_time")]
101    pub no_mining: bool,
102
103    #[arg(long, visible_alias = "mixed-mining", requires = "block_time")]
104    pub mixed_mining: bool,
105
106    /// The hosts the server will listen on.
107    #[arg(
108        long,
109        value_name = "IP_ADDR",
110        env = "ANVIL_IP_ADDR",
111        default_value = "127.0.0.1",
112        help_heading = "Server options",
113        value_delimiter = ','
114    )]
115    pub host: Vec<IpAddr>,
116
117    /// How transactions are sorted in the mempool.
118    #[arg(long, default_value = "fees")]
119    pub order: TransactionOrder,
120
121    /// Initialize the genesis block with the given `genesis.json` file.
122    #[arg(long, value_name = "PATH", value_parser= read_genesis_file)]
123    pub init: Option<Genesis>,
124
125    /// This is an alias for both --load-state and --dump-state.
126    ///
127    /// It initializes the chain with the state and block environment stored at the file, if it
128    /// exists, and dumps the chain's state on exit.
129    #[arg(
130        long,
131        value_name = "PATH",
132        value_parser = StateFile::parse,
133        conflicts_with_all = &[
134            "init",
135            "dump_state",
136            "load_state"
137        ]
138    )]
139    pub state: Option<StateFile>,
140
141    /// Interval in seconds at which the state and block environment is to be dumped to disk.
142    ///
143    /// See --state and --dump-state
144    #[arg(short, long, value_name = "SECONDS")]
145    pub state_interval: Option<u64>,
146
147    /// Dump the state and block environment of chain on exit to the given file.
148    ///
149    /// If the value is a directory, the state will be written to `<VALUE>/state.json`.
150    #[arg(long, value_name = "PATH", conflicts_with = "init")]
151    pub dump_state: Option<PathBuf>,
152
153    /// Preserve historical state snapshots when dumping the state.
154    ///
155    /// This will save the in-memory states of the chain at particular block hashes.
156    ///
157    /// These historical states will be loaded into the memory when `--load-state` / `--state`, and
158    /// aids in RPC calls beyond the block at which state was dumped.
159    #[arg(long, conflicts_with = "init", default_value = "false")]
160    pub preserve_historical_states: bool,
161
162    /// Initialize the chain from a previously saved state snapshot.
163    #[arg(
164        long,
165        value_name = "PATH",
166        value_parser = SerializableState::parse,
167        conflicts_with = "init"
168    )]
169    pub load_state: Option<SerializableState>,
170
171    #[arg(long, help = IPC_HELP, value_name = "PATH", visible_alias = "ipcpath")]
172    pub ipc: Option<Option<String>>,
173
174    /// Don't keep full chain history.
175    /// If a number argument is specified, at most this number of states is kept in memory.
176    ///
177    /// If enabled, no state will be persisted on disk, so `max_persisted_states` will be 0.
178    #[arg(long)]
179    pub prune_history: Option<Option<usize>>,
180
181    /// Max number of states to persist on disk.
182    ///
183    /// Note that `prune_history` will overwrite `max_persisted_states` to 0.
184    #[arg(long, conflicts_with = "prune_history")]
185    pub max_persisted_states: Option<usize>,
186
187    /// Number of blocks with transactions to keep in memory.
188    #[arg(long)]
189    pub transaction_block_keeper: Option<usize>,
190
191    #[command(flatten)]
192    pub evm: AnvilEvmArgs,
193
194    #[command(flatten)]
195    pub server_config: ServerConfig,
196
197    /// Path to the cache directory where states are stored.    
198    #[arg(long, value_name = "PATH")]
199    pub cache_path: Option<PathBuf>,
200}
201
202#[cfg(windows)]
203const IPC_HELP: &str =
204    "Launch an ipc server at the given path or default path = `\\.\\pipe\\anvil.ipc`";
205
206/// The default IPC endpoint
207#[cfg(not(windows))]
208const IPC_HELP: &str = "Launch an ipc server at the given path or default path = `/tmp/anvil.ipc`";
209
210/// Default interval for periodically dumping the state.
211const DEFAULT_DUMP_INTERVAL: Duration = Duration::from_secs(60);
212
213impl NodeArgs {
214    pub fn into_node_config(self) -> eyre::Result<NodeConfig> {
215        let genesis_balance = Unit::ETHER.wei().saturating_mul(U256::from(self.balance));
216        let compute_units_per_second =
217            if self.evm.no_rate_limit { Some(u64::MAX) } else { self.evm.compute_units_per_second };
218
219        let hardfork = match &self.hardfork {
220            Some(hf) => {
221                if self.evm.networks.optimism {
222                    Some(OpHardfork::from_str(hf)?.into())
223                } else {
224                    Some(EthereumHardfork::from_str(hf)?.into())
225                }
226            }
227            None => None,
228        };
229
230        Ok(NodeConfig::default()
231            .with_gas_limit(self.evm.gas_limit)
232            .disable_block_gas_limit(self.evm.disable_block_gas_limit)
233            .with_gas_price(self.evm.gas_price)
234            .with_hardfork(hardfork)
235            .with_blocktime(self.block_time)
236            .with_no_mining(self.no_mining)
237            .with_mixed_mining(self.mixed_mining, self.block_time)
238            .with_account_generator(self.account_generator())?
239            .with_genesis_balance(genesis_balance)
240            .with_genesis_timestamp(self.timestamp)
241            .with_genesis_block_number(self.number)
242            .with_port(self.port)
243            .with_fork_choice(match (self.evm.fork_block_number, self.evm.fork_transaction_hash) {
244                (Some(block), None) => Some(ForkChoice::Block(block)),
245                (None, Some(hash)) => Some(ForkChoice::Transaction(hash)),
246                _ => self
247                    .evm
248                    .fork_url
249                    .as_ref()
250                    .and_then(|f| f.block)
251                    .map(|num| ForkChoice::Block(num as i128)),
252            })
253            .with_fork_headers(self.evm.fork_headers)
254            .with_fork_chain_id(self.evm.fork_chain_id.map(u64::from).map(U256::from))
255            .fork_request_timeout(self.evm.fork_request_timeout.map(Duration::from_millis))
256            .fork_request_retries(self.evm.fork_request_retries)
257            .fork_retry_backoff(self.evm.fork_retry_backoff.map(Duration::from_millis))
258            .fork_compute_units_per_second(compute_units_per_second)
259            .with_eth_rpc_url(self.evm.fork_url.map(|fork| fork.url))
260            .with_base_fee(self.evm.block_base_fee_per_gas)
261            .disable_min_priority_fee(self.evm.disable_min_priority_fee)
262            .with_storage_caching(self.evm.no_storage_caching)
263            .with_server_config(self.server_config)
264            .with_host(self.host)
265            .set_silent(shell::is_quiet())
266            .set_config_out(self.config_out)
267            .with_chain_id(self.evm.chain_id)
268            .with_transaction_order(self.order)
269            .with_genesis(self.init)
270            .with_steps_tracing(self.evm.steps_tracing)
271            .with_print_logs(!self.evm.disable_console_log)
272            .with_print_traces(self.evm.print_traces)
273            .with_auto_impersonate(self.evm.auto_impersonate)
274            .with_ipc(self.ipc)
275            .with_code_size_limit(self.evm.code_size_limit)
276            .disable_code_size_limit(self.evm.disable_code_size_limit)
277            .set_pruned_history(self.prune_history)
278            .with_init_state(self.load_state.or_else(|| self.state.and_then(|s| s.state)))
279            .with_transaction_block_keeper(self.transaction_block_keeper)
280            .with_max_persisted_states(self.max_persisted_states)
281            .with_networks(self.evm.networks)
282            .with_disable_default_create2_deployer(self.evm.disable_default_create2_deployer)
283            .with_disable_pool_balance_checks(self.evm.disable_pool_balance_checks)
284            .with_slots_in_an_epoch(self.slots_in_an_epoch)
285            .with_memory_limit(self.evm.memory_limit)
286            .with_cache_path(self.cache_path))
287    }
288
289    fn account_generator(&self) -> AccountGenerator {
290        let mut generator = AccountGenerator::new(self.accounts as usize)
291            .phrase(DEFAULT_MNEMONIC)
292            .chain_id(self.evm.chain_id.unwrap_or(CHAIN_ID.into()));
293        if let Some(ref mnemonic) = self.mnemonic {
294            generator = generator.phrase(mnemonic);
295        } else if let Some(count) = self.mnemonic_random {
296            let mut rng = rand_08::thread_rng();
297            let mnemonic = match Mnemonic::<English>::new_with_count(&mut rng, count) {
298                Ok(mnemonic) => mnemonic.to_phrase(),
299                Err(err) => {
300                    warn!(target: "node", ?count, %err, "failed to generate mnemonic, falling back to 12-word random mnemonic");
301                    // Fallback: generate a valid 12-word random mnemonic instead of using
302                    // DEFAULT_MNEMONIC
303                    Mnemonic::<English>::new_with_count(&mut rng, 12)
304                        .expect("valid default word count")
305                        .to_phrase()
306                }
307            };
308            generator = generator.phrase(mnemonic);
309        } else if let Some(seed) = self.mnemonic_seed {
310            let mut seed = StdRng::seed_from_u64(seed);
311            let mnemonic = Mnemonic::<English>::new(&mut seed).to_phrase();
312            generator = generator.phrase(mnemonic);
313        }
314        if let Some(ref derivation) = self.derivation_path {
315            generator = generator.derivation_path(derivation);
316        }
317        generator
318    }
319
320    /// Returns the location where to dump the state to.
321    fn dump_state_path(&self) -> Option<PathBuf> {
322        self.dump_state.as_ref().or_else(|| self.state.as_ref().map(|s| &s.path)).cloned()
323    }
324
325    /// Starts the node
326    ///
327    /// See also [crate::spawn()]
328    pub async fn run(self) -> eyre::Result<()> {
329        let dump_state = self.dump_state_path();
330        let dump_interval =
331            self.state_interval.map(Duration::from_secs).unwrap_or(DEFAULT_DUMP_INTERVAL);
332        let preserve_historical_states = self.preserve_historical_states;
333
334        let (api, mut handle) = crate::try_spawn(self.into_node_config()?).await?;
335
336        // sets the signal handler to gracefully shutdown.
337        let mut fork = api.get_fork();
338        let running = Arc::new(AtomicUsize::new(0));
339
340        // handle for the currently running rt, this must be obtained before setting the crtlc
341        // handler, See [Handle::current]
342        let mut signal = handle.shutdown_signal_mut().take();
343
344        let task_manager = handle.task_manager();
345        let mut on_shutdown = task_manager.on_shutdown();
346
347        let mut state_dumper =
348            PeriodicStateDumper::new(api, dump_state, dump_interval, preserve_historical_states);
349
350        task_manager.spawn(async move {
351            // wait for the SIGTERM signal on unix systems
352            #[cfg(unix)]
353            let mut sigterm = Box::pin(async {
354                if let Ok(mut stream) =
355                    tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate())
356                {
357                    stream.recv().await;
358                } else {
359                    futures::future::pending::<()>().await;
360                }
361            });
362
363            // On windows, this will never fire.
364            #[cfg(not(unix))]
365            let mut sigterm = Box::pin(futures::future::pending::<()>());
366
367            // await shutdown signal but also periodically flush state
368            tokio::select! {
369                 _ = &mut sigterm => {
370                    trace!("received sigterm signal, shutting down");
371                }
372                _ = &mut on_shutdown => {}
373                _ = &mut state_dumper => {}
374            }
375
376            // shutdown received
377            state_dumper.dump().await;
378
379            // cleaning up and shutting down
380            // this will make sure that the fork RPC cache is flushed if caching is configured
381            if let Some(fork) = fork.take() {
382                trace!("flushing cache on shutdown");
383                fork.database
384                    .read()
385                    .await
386                    .maybe_flush_cache()
387                    .expect("Could not flush cache on fork DB");
388                // cleaning up and shutting down
389                // this will make sure that the fork RPC cache is flushed if caching is configured
390            }
391            std::process::exit(0);
392        });
393
394        ctrlc::set_handler(move || {
395            let prev = running.fetch_add(1, Ordering::SeqCst);
396            if prev == 0 {
397                trace!("received shutdown signal, shutting down");
398                let _ = signal.take();
399            }
400        })
401        .expect("Error setting Ctrl-C handler");
402
403        Ok(handle.await??)
404    }
405}
406
407/// Anvil's EVM related arguments.
408#[derive(Clone, Debug, Parser)]
409#[command(next_help_heading = "EVM options")]
410pub struct AnvilEvmArgs {
411    /// Fetch state over a remote endpoint instead of starting from an empty state.
412    ///
413    /// If you want to fetch state from a specific block number, add a block number like `http://localhost:8545@1400000` or use the `--fork-block-number` argument.
414    #[arg(
415        long,
416        short,
417        visible_alias = "rpc-url",
418        value_name = "URL",
419        help_heading = "Fork config"
420    )]
421    pub fork_url: Option<ForkUrl>,
422
423    /// Headers to use for the rpc client, e.g. "User-Agent: test-agent"
424    ///
425    /// See --fork-url.
426    #[arg(
427        long = "fork-header",
428        value_name = "HEADERS",
429        help_heading = "Fork config",
430        requires = "fork_url"
431    )]
432    pub fork_headers: Vec<String>,
433
434    /// Timeout in ms for requests sent to remote JSON-RPC server in forking mode.
435    ///
436    /// Default value 45000
437    #[arg(id = "timeout", long = "timeout", help_heading = "Fork config", requires = "fork_url")]
438    pub fork_request_timeout: Option<u64>,
439
440    /// Number of retry requests for spurious networks (timed out requests)
441    ///
442    /// Default value 5
443    #[arg(id = "retries", long = "retries", help_heading = "Fork config", requires = "fork_url")]
444    pub fork_request_retries: Option<u32>,
445
446    /// Fetch state from a specific block number over a remote endpoint.
447    ///
448    /// If negative, the given value is subtracted from the `latest` block number.
449    ///
450    /// See --fork-url.
451    #[arg(
452        long,
453        requires = "fork_url",
454        value_name = "BLOCK",
455        help_heading = "Fork config",
456        allow_hyphen_values = true
457    )]
458    pub fork_block_number: Option<i128>,
459
460    /// Fetch state from after a specific transaction hash has been applied over a remote endpoint.
461    ///
462    /// See --fork-url.
463    #[arg(
464        long,
465        requires = "fork_url",
466        value_name = "TRANSACTION",
467        help_heading = "Fork config",
468        conflicts_with = "fork_block_number"
469    )]
470    pub fork_transaction_hash: Option<B256>,
471
472    /// Initial retry backoff on encountering errors.
473    ///
474    /// See --fork-url.
475    #[arg(long, requires = "fork_url", value_name = "BACKOFF", help_heading = "Fork config")]
476    pub fork_retry_backoff: Option<u64>,
477
478    /// Specify chain id to skip fetching it from remote endpoint. This enables offline-start mode.
479    ///
480    /// You still must pass both `--fork-url` and `--fork-block-number`, and already have your
481    /// required state cached on disk, anything missing locally would be fetched from the
482    /// remote.
483    #[arg(
484        long,
485        help_heading = "Fork config",
486        value_name = "CHAIN",
487        requires = "fork_block_number"
488    )]
489    pub fork_chain_id: Option<Chain>,
490
491    /// Sets the number of assumed available compute units per second for this provider
492    ///
493    /// default value: 330
494    ///
495    /// See also --fork-url and <https://docs.alchemy.com/reference/compute-units#what-are-cups-compute-units-per-second>
496    #[arg(
497        long,
498        requires = "fork_url",
499        alias = "cups",
500        value_name = "CUPS",
501        help_heading = "Fork config"
502    )]
503    pub compute_units_per_second: Option<u64>,
504
505    /// Disables rate limiting for this node's provider.
506    ///
507    /// default value: false
508    ///
509    /// See also --fork-url and <https://docs.alchemy.com/reference/compute-units#what-are-cups-compute-units-per-second>
510    #[arg(
511        long,
512        requires = "fork_url",
513        value_name = "NO_RATE_LIMITS",
514        help_heading = "Fork config",
515        visible_alias = "no-rpc-rate-limit"
516    )]
517    pub no_rate_limit: bool,
518
519    /// Explicitly disables the use of RPC caching.
520    ///
521    /// All storage slots are read entirely from the endpoint.
522    ///
523    /// This flag overrides the project's configuration file.
524    ///
525    /// See --fork-url.
526    #[arg(long, requires = "fork_url", help_heading = "Fork config")]
527    pub no_storage_caching: bool,
528
529    /// The block gas limit.
530    #[arg(long, alias = "block-gas-limit", help_heading = "Environment config")]
531    pub gas_limit: Option<u64>,
532
533    /// Disable the `call.gas_limit <= block.gas_limit` constraint.
534    #[arg(
535        long,
536        value_name = "DISABLE_GAS_LIMIT",
537        help_heading = "Environment config",
538        alias = "disable-gas-limit",
539        conflicts_with = "gas_limit"
540    )]
541    pub disable_block_gas_limit: bool,
542
543    /// EIP-170: Contract code size limit in bytes. Useful to increase this because of tests. To
544    /// disable entirely, use `--disable-code-size-limit`. By default, it is 0x6000 (~25kb).
545    #[arg(long, value_name = "CODE_SIZE", help_heading = "Environment config")]
546    pub code_size_limit: Option<usize>,
547
548    /// Disable EIP-170: Contract code size limit.
549    #[arg(
550        long,
551        value_name = "DISABLE_CODE_SIZE_LIMIT",
552        conflicts_with = "code_size_limit",
553        help_heading = "Environment config"
554    )]
555    pub disable_code_size_limit: bool,
556
557    /// The gas price.
558    #[arg(long, help_heading = "Environment config")]
559    pub gas_price: Option<u128>,
560
561    /// The base fee in a block.
562    #[arg(
563        long,
564        visible_alias = "base-fee",
565        value_name = "FEE",
566        help_heading = "Environment config"
567    )]
568    pub block_base_fee_per_gas: Option<u64>,
569
570    /// Disable the enforcement of a minimum suggested priority fee.
571    #[arg(long, visible_alias = "no-priority-fee", help_heading = "Environment config")]
572    pub disable_min_priority_fee: bool,
573
574    /// The chain ID.
575    #[arg(long, alias = "chain", help_heading = "Environment config")]
576    pub chain_id: Option<Chain>,
577
578    /// Enable steps tracing used for debug calls returning geth-style traces
579    #[arg(long, visible_alias = "tracing")]
580    pub steps_tracing: bool,
581
582    /// Disable printing of `console.log` invocations to stdout.
583    #[arg(long, visible_alias = "no-console-log")]
584    pub disable_console_log: bool,
585
586    /// Enable printing of traces for executed transactions and `eth_call` to stdout.
587    #[arg(long, visible_alias = "enable-trace-printing")]
588    pub print_traces: bool,
589
590    /// Enables automatic impersonation on startup. This allows any transaction sender to be
591    /// simulated as different accounts, which is useful for testing contract behavior.
592    #[arg(long, visible_alias = "auto-unlock")]
593    pub auto_impersonate: bool,
594
595    /// Disable the default create2 deployer
596    #[arg(long, visible_alias = "no-create2")]
597    pub disable_default_create2_deployer: bool,
598
599    /// Disable pool balance checks
600    #[arg(long)]
601    pub disable_pool_balance_checks: bool,
602
603    /// The memory limit per EVM execution in bytes.
604    #[arg(long)]
605    pub memory_limit: Option<u64>,
606
607    #[command(flatten)]
608    pub networks: NetworkConfigs,
609}
610
611/// Resolves an alias passed as fork-url to the matching url defined in the rpc_endpoints section
612/// of the project configuration file.
613/// Does nothing if the fork-url is not a configured alias.
614impl AnvilEvmArgs {
615    pub fn resolve_rpc_alias(&mut self) {
616        if let Some(fork_url) = &self.fork_url
617            && let Ok(config) = Config::load_with_providers(FigmentProviders::Anvil)
618            && let Some(Ok(url)) = config.get_rpc_url_with_alias(&fork_url.url)
619        {
620            self.fork_url = Some(ForkUrl { url: url.to_string(), block: fork_url.block });
621        }
622    }
623}
624
625/// Helper type to periodically dump the state of the chain to disk
626struct PeriodicStateDumper {
627    in_progress_dump: Option<Pin<Box<dyn Future<Output = ()> + Send + Sync + 'static>>>,
628    api: EthApi,
629    dump_state: Option<PathBuf>,
630    preserve_historical_states: bool,
631    interval: Interval,
632}
633
634impl PeriodicStateDumper {
635    fn new(
636        api: EthApi,
637        dump_state: Option<PathBuf>,
638        interval: Duration,
639        preserve_historical_states: bool,
640    ) -> Self {
641        let dump_state = dump_state.map(|mut dump_state| {
642            if dump_state.is_dir() {
643                dump_state = dump_state.join("state.json");
644            }
645            dump_state
646        });
647
648        // periodically flush the state
649        let interval = tokio::time::interval_at(Instant::now() + interval, interval);
650        Self { in_progress_dump: None, api, dump_state, preserve_historical_states, interval }
651    }
652
653    async fn dump(&self) {
654        if let Some(state) = self.dump_state.clone() {
655            Self::dump_state(self.api.clone(), state, self.preserve_historical_states).await
656        }
657    }
658
659    /// Infallible state dump
660    async fn dump_state(api: EthApi, dump_state: PathBuf, preserve_historical_states: bool) {
661        trace!(path=?dump_state, "Dumping state on shutdown");
662        match api.serialized_state(preserve_historical_states).await {
663            Ok(state) => {
664                if let Err(err) = foundry_common::fs::write_json_file(&dump_state, &state) {
665                    error!(?err, "Failed to dump state");
666                } else {
667                    trace!(path=?dump_state, "Dumped state on shutdown");
668                }
669            }
670            Err(err) => {
671                error!(?err, "Failed to extract state");
672            }
673        }
674    }
675}
676
677// An endless future that periodically dumps the state to disk if configured.
678impl Future for PeriodicStateDumper {
679    type Output = ();
680
681    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
682        let this = self.get_mut();
683        if this.dump_state.is_none() {
684            return Poll::Pending;
685        }
686
687        loop {
688            if let Some(mut flush) = this.in_progress_dump.take() {
689                match flush.poll_unpin(cx) {
690                    Poll::Ready(_) => {
691                        this.interval.reset();
692                    }
693                    Poll::Pending => {
694                        this.in_progress_dump = Some(flush);
695                        return Poll::Pending;
696                    }
697                }
698            }
699
700            if this.interval.poll_tick(cx).is_ready() {
701                let api = this.api.clone();
702                let path = this.dump_state.clone().expect("exists; see above");
703                this.in_progress_dump =
704                    Some(Box::pin(Self::dump_state(api, path, this.preserve_historical_states)));
705            } else {
706                break;
707            }
708        }
709
710        Poll::Pending
711    }
712}
713
714/// Represents the --state flag and where to load from, or dump the state to
715#[derive(Clone, Debug)]
716pub struct StateFile {
717    pub path: PathBuf,
718    pub state: Option<SerializableState>,
719}
720
721impl StateFile {
722    /// This is used as the clap `value_parser` implementation to parse from file but only if it
723    /// exists
724    fn parse(path: &str) -> Result<Self, String> {
725        Self::parse_path(path)
726    }
727
728    /// Parse from file but only if it exists
729    pub fn parse_path(path: impl AsRef<Path>) -> Result<Self, String> {
730        let mut path = path.as_ref().to_path_buf();
731        if path.is_dir() {
732            path = path.join("state.json");
733        }
734        let mut state = Self { path, state: None };
735        if !state.path.exists() {
736            return Ok(state);
737        }
738
739        state.state = Some(SerializableState::load(&state.path).map_err(|err| err.to_string())?);
740
741        Ok(state)
742    }
743}
744
745/// Represents the input URL for a fork with an optional trailing block number:
746/// `http://localhost:8545@1000000`
747#[derive(Clone, Debug, PartialEq, Eq)]
748pub struct ForkUrl {
749    /// The endpoint url
750    pub url: String,
751    /// Optional trailing block
752    pub block: Option<u64>,
753}
754
755impl fmt::Display for ForkUrl {
756    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
757        self.url.fmt(f)?;
758        if let Some(block) = self.block {
759            write!(f, "@{block}")?;
760        }
761        Ok(())
762    }
763}
764
765impl FromStr for ForkUrl {
766    type Err = String;
767
768    fn from_str(s: &str) -> Result<Self, Self::Err> {
769        if let Some((url, block)) = s.rsplit_once('@') {
770            if block == "latest" {
771                return Ok(Self { url: url.to_string(), block: None });
772            }
773            // this will prevent false positives for auths `user:password@example.com`
774            if !block.is_empty() && !block.contains(':') && !block.contains('.') {
775                let block: u64 = block
776                    .parse()
777                    .map_err(|_| format!("Failed to parse block number: `{block}`"))?;
778                return Ok(Self { url: url.to_string(), block: Some(block) });
779            }
780        }
781        Ok(Self { url: s.to_string(), block: None })
782    }
783}
784
785/// Clap's value parser for genesis. Loads a genesis.json file.
786fn read_genesis_file(path: &str) -> Result<Genesis, String> {
787    foundry_common::fs::read_json_file(path.as_ref()).map_err(|err| err.to_string())
788}
789
790fn duration_from_secs_f64(s: &str) -> Result<Duration, String> {
791    let s = s.parse::<f64>().map_err(|e| e.to_string())?;
792    if s == 0.0 {
793        return Err("Duration must be greater than 0".to_string());
794    }
795    Duration::try_from_secs_f64(s).map_err(|e| e.to_string())
796}
797
798#[cfg(test)]
799mod tests {
800    use super::*;
801    use std::{env, net::Ipv4Addr};
802
803    #[test]
804    fn test_parse_fork_url() {
805        let fork: ForkUrl = "http://localhost:8545@1000000".parse().unwrap();
806        assert_eq!(
807            fork,
808            ForkUrl { url: "http://localhost:8545".to_string(), block: Some(1000000) }
809        );
810
811        let fork: ForkUrl = "http://localhost:8545".parse().unwrap();
812        assert_eq!(fork, ForkUrl { url: "http://localhost:8545".to_string(), block: None });
813
814        let fork: ForkUrl = "wss://user:password@example.com/".parse().unwrap();
815        assert_eq!(
816            fork,
817            ForkUrl { url: "wss://user:password@example.com/".to_string(), block: None }
818        );
819
820        let fork: ForkUrl = "wss://user:password@example.com/@latest".parse().unwrap();
821        assert_eq!(
822            fork,
823            ForkUrl { url: "wss://user:password@example.com/".to_string(), block: None }
824        );
825
826        let fork: ForkUrl = "wss://user:password@example.com/@100000".parse().unwrap();
827        assert_eq!(
828            fork,
829            ForkUrl { url: "wss://user:password@example.com/".to_string(), block: Some(100000) }
830        );
831    }
832
833    #[test]
834    fn can_parse_ethereum_hardfork() {
835        let args: NodeArgs = NodeArgs::parse_from(["anvil", "--hardfork", "berlin"]);
836        let config = args.into_node_config().unwrap();
837        assert_eq!(config.hardfork, Some(EthereumHardfork::Berlin.into()));
838    }
839
840    #[test]
841    fn can_parse_optimism_hardfork() {
842        let args: NodeArgs =
843            NodeArgs::parse_from(["anvil", "--optimism", "--hardfork", "Regolith"]);
844        let config = args.into_node_config().unwrap();
845        assert_eq!(config.hardfork, Some(OpHardfork::Regolith.into()));
846    }
847
848    #[test]
849    fn cant_parse_invalid_hardfork() {
850        let args: NodeArgs = NodeArgs::parse_from(["anvil", "--hardfork", "Regolith"]);
851        let config = args.into_node_config();
852        assert!(config.is_err());
853    }
854
855    #[test]
856    fn can_parse_fork_headers() {
857        let args: NodeArgs = NodeArgs::parse_from([
858            "anvil",
859            "--fork-url",
860            "http,://localhost:8545",
861            "--fork-header",
862            "User-Agent: test-agent",
863            "--fork-header",
864            "Referrer: example.com",
865        ]);
866        assert_eq!(args.evm.fork_headers, vec!["User-Agent: test-agent", "Referrer: example.com"]);
867    }
868
869    #[test]
870    fn can_parse_prune_config() {
871        let args: NodeArgs = NodeArgs::parse_from(["anvil", "--prune-history"]);
872        assert!(args.prune_history.is_some());
873
874        let args: NodeArgs = NodeArgs::parse_from(["anvil", "--prune-history", "100"]);
875        assert_eq!(args.prune_history, Some(Some(100)));
876    }
877
878    #[test]
879    fn can_parse_max_persisted_states_config() {
880        let args: NodeArgs = NodeArgs::parse_from(["anvil", "--max-persisted-states", "500"]);
881        assert_eq!(args.max_persisted_states, (Some(500)));
882    }
883
884    #[test]
885    fn can_parse_disable_block_gas_limit() {
886        let args: NodeArgs = NodeArgs::parse_from(["anvil", "--disable-block-gas-limit"]);
887        assert!(args.evm.disable_block_gas_limit);
888
889        let args =
890            NodeArgs::try_parse_from(["anvil", "--disable-block-gas-limit", "--gas-limit", "100"]);
891        assert!(args.is_err());
892    }
893
894    #[test]
895    fn can_parse_disable_code_size_limit() {
896        let args: NodeArgs = NodeArgs::parse_from(["anvil", "--disable-code-size-limit"]);
897        assert!(args.evm.disable_code_size_limit);
898
899        let args = NodeArgs::try_parse_from([
900            "anvil",
901            "--disable-code-size-limit",
902            "--code-size-limit",
903            "100",
904        ]);
905        // can't be used together
906        assert!(args.is_err());
907    }
908
909    #[test]
910    fn can_parse_host() {
911        let args = NodeArgs::parse_from(["anvil"]);
912        assert_eq!(args.host, vec![IpAddr::V4(Ipv4Addr::LOCALHOST)]);
913
914        let args = NodeArgs::parse_from([
915            "anvil", "--host", "::1", "--host", "1.1.1.1", "--host", "2.2.2.2",
916        ]);
917        assert_eq!(
918            args.host,
919            ["::1", "1.1.1.1", "2.2.2.2"].map(|ip| ip.parse::<IpAddr>().unwrap()).to_vec()
920        );
921
922        let args = NodeArgs::parse_from(["anvil", "--host", "::1,1.1.1.1,2.2.2.2"]);
923        assert_eq!(
924            args.host,
925            ["::1", "1.1.1.1", "2.2.2.2"].map(|ip| ip.parse::<IpAddr>().unwrap()).to_vec()
926        );
927
928        unsafe { env::set_var("ANVIL_IP_ADDR", "1.1.1.1") };
929        let args = NodeArgs::parse_from(["anvil"]);
930        assert_eq!(args.host, vec!["1.1.1.1".parse::<IpAddr>().unwrap()]);
931
932        unsafe { env::set_var("ANVIL_IP_ADDR", "::1,1.1.1.1,2.2.2.2") };
933        let args = NodeArgs::parse_from(["anvil"]);
934        assert_eq!(
935            args.host,
936            ["::1", "1.1.1.1", "2.2.2.2"].map(|ip| ip.parse::<IpAddr>().unwrap()).to_vec()
937        );
938    }
939}