Skip to main content

anvil/
cmd.rs

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