Skip to main content

foundry_cli/opts/
evm.rs

1//! CLI arguments for configuring the EVM settings.
2
3use crate::opts::RpcCommonOpts;
4use alloy_primitives::{Address, B256, U256};
5use clap::Parser;
6use foundry_common::shell;
7use foundry_config::{
8    Chain, Config, FoundryHardfork,
9    figment::{
10        self, Metadata, Profile, Provider,
11        error::Kind::InvalidType,
12        value::{Dict, Map, Value},
13    },
14};
15use foundry_evm_networks::NetworkConfigs;
16use serde::Serialize;
17
18/// `EvmArgs` and `EnvArgs` take the highest precedence in the Config/Figment hierarchy.
19///
20/// All vars are opt-in, their default values are expected to be set by the
21/// [`foundry_config::Config`], and are always present ([`foundry_config::Config::default`])
22///
23/// Both have corresponding types in the `evm_adapters` crate which have mandatory fields.
24/// The expected workflow is
25///   1. load the [`foundry_config::Config`]
26///   2. merge with `EvmArgs` into a `figment::Figment`
27///   3. extract `evm_adapters::Opts` from the merged `Figment`
28///
29/// # Example
30///
31/// ```ignore
32/// use foundry_config::Config;
33/// use forge::executor::opts::EvmOpts;
34/// use foundry_cli::opts::EvmArgs;
35/// # fn t(args: EvmArgs) {
36/// let figment = Config::figment_with_root(".").merge(args);
37/// let opts = figment.extract::<EvmOpts>().unwrap();
38/// # }
39/// ```
40#[derive(Clone, Debug, Default, Serialize, Parser)]
41#[command(next_help_heading = "EVM options", about = None, long_about = None)] // override doc
42pub struct EvmArgs {
43    /// Common RPC options (URL, timeout, rate limiting, etc.).
44    #[command(flatten)]
45    #[serde(flatten)]
46    pub rpc: RpcCommonOpts,
47
48    /// Fetch state from a specific block number over a remote endpoint.
49    ///
50    /// See --rpc-url.
51    #[arg(long, requires = "rpc_url", value_name = "BLOCK")]
52    #[serde(skip_serializing_if = "Option::is_none")]
53    pub fork_block_number: Option<u64>,
54
55    /// Fetch fork state by block number instead of hash.
56    ///
57    /// Use for RPC endpoints that cannot serve state by block hash. Number-based reads
58    /// cannot guarantee a consistent snapshot if the remote chain reorganizes and do not
59    /// use the disk state cache. Transaction replay still requires hash-addressed state.
60    #[arg(long)]
61    #[serde(skip)]
62    pub fork_state_by_number: bool,
63
64    /// Number of retries.
65    ///
66    /// Applies to the fork created by --rpc-url, and to forks created by cheatcodes unless their
67    /// `rpc_endpoints` entry sets `retries`.
68    #[arg(long, value_name = "RETRIES")]
69    #[serde(skip_serializing_if = "Option::is_none")]
70    pub fork_retries: Option<u32>,
71
72    /// Initial retry backoff on encountering errors.
73    ///
74    /// Applies to the fork created by --rpc-url, and to forks created by cheatcodes unless their
75    /// `rpc_endpoints` entry sets `retry_backoff`.
76    #[arg(long, value_name = "BACKOFF")]
77    #[serde(skip_serializing_if = "Option::is_none")]
78    pub fork_retry_backoff: Option<u64>,
79
80    /// Explicitly disables the use of RPC caching.
81    ///
82    /// All storage slots are read entirely from the endpoint.
83    ///
84    /// This flag overrides the project's configuration file.
85    ///
86    /// See --rpc-url.
87    #[arg(long)]
88    #[serde(skip)]
89    pub no_storage_caching: bool,
90
91    /// Disable parent-block BAL cache prewarming for transaction-hash fork cheatcodes.
92    ///
93    /// Preceding transactions are still replayed when prewarming is enabled.
94    #[arg(long)]
95    #[serde(skip)]
96    pub no_fork_bal: bool,
97
98    /// Prefetch remote fork state before the EVM reads it.
99    ///
100    /// While reads miss the cache, each call into a fork contract is simulated on the endpoint
101    /// with `eth_createAccessList` and the state it touches is fetched in batches. With
102    /// storage caching, a new fork block also fetches the keys cached for an older block on
103    /// the same chain.
104    #[arg(long)]
105    #[serde(skip)]
106    pub fork_prefetch: bool,
107
108    /// The initial balance of deployed test contracts.
109    #[arg(long, value_name = "BALANCE")]
110    #[serde(skip_serializing_if = "Option::is_none")]
111    pub initial_balance: Option<U256>,
112
113    /// The address which will be executing tests/scripts.
114    #[arg(long, value_name = "ADDRESS")]
115    #[serde(skip_serializing_if = "Option::is_none")]
116    pub sender: Option<Address>,
117
118    /// Enable the FFI cheatcode.
119    #[arg(long)]
120    #[serde(skip)]
121    pub ffi: bool,
122
123    /// Whether to show `console.log` outputs in realtime during script/test execution.
124    ///
125    /// Ignored when `--json` or `--junit` writes a report to stdout. Otherwise, logs print live
126    /// instead of being captured, so `forge test --json-file` does not include them.
127    #[arg(long)]
128    #[serde(skip)]
129    pub live_logs: bool,
130
131    /// Use the create 2 factory in all cases including tests and non-broadcasting scripts.
132    #[arg(long)]
133    #[serde(skip)]
134    pub always_use_create_2_factory: bool,
135
136    /// The CREATE2 deployer address to use, this will override the one in the config.
137    #[arg(long, value_name = "ADDRESS")]
138    #[serde(skip_serializing_if = "Option::is_none")]
139    pub create2_deployer: Option<Address>,
140
141    /// All ethereum environment related arguments
142    #[command(flatten)]
143    #[serde(flatten)]
144    pub env: EnvArgs,
145
146    /// Whether to enable isolation of calls.
147    /// In isolation mode all top-level calls are executed as a separate transaction in a separate
148    /// EVM context, enabling more precise gas accounting and transaction state changes.
149    #[arg(long)]
150    #[serde(skip)]
151    pub isolate: bool,
152
153    /// Whether to disable isolation of calls.
154    #[arg(long, conflicts_with = "isolate")]
155    #[serde(skip)]
156    pub no_isolate: bool,
157
158    /// The runtime EVM hardfork to use.
159    ///
160    /// Network-specific hardforks must be namespaced, for example `tempo:T5`.
161    #[arg(long, value_name = "HARDFORK")]
162    #[serde(skip_serializing_if = "Option::is_none")]
163    pub hardfork: Option<FoundryHardfork>,
164
165    /// Network selection.
166    #[command(flatten)]
167    #[serde(skip)]
168    pub networks: NetworkConfigs,
169}
170
171// Make this set of options a `figment::Provider` so that it can be merged into the `Config`
172impl Provider for EvmArgs {
173    fn metadata(&self) -> Metadata {
174        Metadata::named("Evm Opts Provider")
175    }
176
177    fn data(&self) -> Result<Map<Profile, Dict>, figment::Error> {
178        let value = Value::serialize(self)?;
179        let error = InvalidType(value.to_actual(), "map".into());
180        let mut dict = value.into_dict().ok_or(error)?;
181
182        if shell::verbosity() > 0 {
183            // need to merge that manually otherwise `from_occurrences` does not work
184            let verbosity = shell::verbosity();
185            dict.insert("verbosity".to_string(), verbosity.into());
186        }
187
188        if self.ffi {
189            dict.insert("ffi".to_string(), self.ffi.into());
190        }
191
192        if self.live_logs {
193            dict.insert("live_logs".to_string(), self.live_logs.into());
194        }
195
196        if self.no_isolate {
197            dict.insert("isolate".to_string(), false.into());
198        } else if self.isolate {
199            dict.insert("isolate".to_string(), self.isolate.into());
200        }
201
202        if self.always_use_create_2_factory {
203            dict.insert(
204                "always_use_create_2_factory".to_string(),
205                self.always_use_create_2_factory.into(),
206            );
207        }
208
209        if self.no_storage_caching {
210            dict.insert("no_storage_caching".to_string(), self.no_storage_caching.into());
211        }
212
213        // Merge serde-skipped fields from the common RPC options.
214        if self.rpc.no_rpc_rate_limit {
215            dict.insert("no_rpc_rate_limit".to_string(), true.into());
216        }
217        if self.rpc.accept_invalid_certs {
218            dict.insert("eth_rpc_accept_invalid_certs".to_string(), true.into());
219        }
220        if self.rpc.no_proxy {
221            dict.insert("eth_rpc_no_proxy".to_string(), true.into());
222        }
223
224        // Only insert network flags when explicitly set via CLI to avoid overriding
225        // values from foundry.toml (NetworkConfigs is flattened in Config).
226        if let Some(network) = self.networks.resolved_network() {
227            dict.insert("network".to_string(), network.name().into());
228        }
229        if self.networks.is_celo() {
230            dict.insert("celo".to_string(), true.into());
231        }
232
233        let mut data = Map::from([(Config::selected_profile(), dict)]);
234        if self.fork_state_by_number {
235            data.entry(Profile::Global)
236                .or_default()
237                .insert("fork_state_by_number".to_string(), true.into());
238        }
239        if self.no_fork_bal {
240            // Environment values use the global profile, which overrides the selected profile.
241            data.entry(Profile::Global).or_default().insert("no_fork_bal".to_string(), true.into());
242        }
243        if self.fork_prefetch {
244            data.entry(Profile::Global)
245                .or_default()
246                .insert("fork_prefetch".to_string(), true.into());
247        }
248        Ok(data)
249    }
250}
251
252/// Configures the executor environment during tests.
253#[derive(Clone, Debug, Default, Serialize, Parser)]
254#[command(next_help_heading = "Executor environment config")]
255pub struct EnvArgs {
256    /// EIP-170: Contract code size limit in bytes. Useful to increase this because of tests. By
257    /// default, it is 0x6000 (~25kb).
258    #[arg(long, value_name = "CODE_SIZE")]
259    #[serde(skip_serializing_if = "Option::is_none")]
260    pub code_size_limit: Option<usize>,
261
262    /// The chain name or EIP-155 chain ID.
263    #[arg(long, visible_alias = "chain-id", value_name = "CHAIN")]
264    #[serde(rename = "chain_id", skip_serializing_if = "Option::is_none", serialize_with = "id")]
265    pub chain: Option<Chain>,
266
267    /// The gas price.
268    #[arg(long, value_name = "GAS_PRICE")]
269    #[serde(skip_serializing_if = "Option::is_none")]
270    pub gas_price: Option<u64>,
271
272    /// The base fee in a block.
273    #[arg(long, visible_alias = "base-fee", value_name = "FEE")]
274    #[serde(skip_serializing_if = "Option::is_none")]
275    pub block_base_fee_per_gas: Option<u64>,
276
277    /// The transaction origin.
278    #[arg(long, value_name = "ADDRESS")]
279    #[serde(skip_serializing_if = "Option::is_none")]
280    pub tx_origin: Option<Address>,
281
282    /// The coinbase of the block.
283    #[arg(long, value_name = "ADDRESS")]
284    #[serde(skip_serializing_if = "Option::is_none")]
285    pub block_coinbase: Option<Address>,
286
287    /// The timestamp of the block.
288    #[arg(long, value_name = "TIMESTAMP")]
289    #[serde(skip_serializing_if = "Option::is_none")]
290    pub block_timestamp: Option<u64>,
291
292    /// The block number.
293    #[arg(long, value_name = "BLOCK")]
294    #[serde(skip_serializing_if = "Option::is_none")]
295    pub block_number: Option<u64>,
296
297    /// The block difficulty.
298    #[arg(long, value_name = "DIFFICULTY")]
299    #[serde(skip_serializing_if = "Option::is_none")]
300    pub block_difficulty: Option<u64>,
301
302    /// The block prevrandao value. NOTE: Before merge this field was mix_hash.
303    #[arg(long, value_name = "PREVRANDAO")]
304    #[serde(skip_serializing_if = "Option::is_none")]
305    pub block_prevrandao: Option<B256>,
306
307    /// The block gas limit.
308    #[arg(long, visible_alias = "gas-limit", value_name = "BLOCK_GAS_LIMIT")]
309    #[serde(skip_serializing_if = "Option::is_none")]
310    pub block_gas_limit: Option<u64>,
311
312    /// The memory limit per EVM execution in bytes.
313    /// If this limit is exceeded, a `MemoryLimitOOG` result is thrown.
314    ///
315    /// The default is 128MiB.
316    #[arg(long, value_name = "MEMORY_LIMIT")]
317    #[serde(skip_serializing_if = "Option::is_none")]
318    pub memory_limit: Option<u64>,
319
320    /// Whether to disable the block gas limit checks.
321    #[arg(long, visible_aliases = &["no-block-gas-limit", "no-gas-limit"])]
322    #[serde(skip_serializing_if = "std::ops::Not::not")]
323    pub disable_block_gas_limit: bool,
324
325    /// Whether to enable tx gas limit checks as imposed by Osaka (EIP-7825) and
326    /// Amsterdam (EIP-8037).
327    #[arg(long, visible_alias = "tx-gas-limit")]
328    #[serde(skip_serializing_if = "std::ops::Not::not")]
329    pub enable_tx_gas_limit: bool,
330}
331
332/// We have to serialize chain IDs and not names because when extracting an EVM `Env`, it expects
333/// `chain_id` to be `u64`.
334fn id<S: serde::Serializer>(chain: &Option<Chain>, s: S) -> Result<S::Ok, S::Error> {
335    if let Some(chain) = chain {
336        s.serialize_u64(chain.id())
337    } else {
338        // skip_serializing_if = "Option::is_none" should prevent this branch from being taken
339        unreachable!()
340    }
341}
342
343#[cfg(test)]
344mod tests {
345    use super::*;
346    use clap::CommandFactory;
347    use foundry_config::{
348        NamedChain,
349        figment::{Figment, providers::Serialized},
350    };
351
352    #[test]
353    fn fork_state_by_number_cli_preserves_config_unless_explicit() {
354        for profile in ["default", "ci"] {
355            for configured in [false, true] {
356                for environment in [None, Some(false), Some(true)] {
357                    for flag in [false, true] {
358                        let config =
359                            Config { fork_state_by_number: configured, ..Default::default() };
360                        let mut figment =
361                            Figment::from(Serialized::defaults(config).profile(profile))
362                                .select(profile);
363                        if let Some(environment) = environment {
364                            figment = figment
365                                .merge(Serialized::global("fork_state_by_number", environment));
366                        }
367                        let args = EvmArgs::parse_from(
368                            ["foundry-cli"]
369                                .into_iter()
370                                .chain(flag.then_some("--fork-state-by-number")),
371                        );
372                        let merged = Config::from_provider(figment.merge(args)).unwrap();
373                        assert_eq!(
374                            merged.fork_state_by_number,
375                            flag || environment.unwrap_or(configured),
376                            "profile={profile}, configured={configured}, environment={environment:?}, flag={flag}",
377                        );
378                    }
379                }
380            }
381        }
382    }
383
384    #[test]
385    fn fork_bal_cli_preserves_config_unless_explicit() {
386        for profile in ["default", "ci"] {
387            for configured in [false, true] {
388                for environment in [None, Some(false), Some(true)] {
389                    for flag in [false, true] {
390                        let config = Config { no_fork_bal: configured, ..Default::default() };
391                        let mut figment =
392                            Figment::from(Serialized::defaults(config).profile(profile))
393                                .select(profile);
394                        if let Some(environment) = environment {
395                            figment = figment.merge(Serialized::global("no_fork_bal", environment));
396                        }
397                        let args = EvmArgs::parse_from(
398                            ["foundry-cli"].into_iter().chain(flag.then_some("--no-fork-bal")),
399                        );
400                        let merged = Config::from_provider(figment.merge(args)).unwrap();
401                        assert_eq!(
402                            merged.no_fork_bal,
403                            flag || environment.unwrap_or(configured),
404                            "profile={profile}, configured={configured}, environment={environment:?}, flag={flag}",
405                        );
406                    }
407                }
408            }
409        }
410    }
411
412    #[test]
413    fn fork_prefetch_cli_preserves_config_unless_explicit() {
414        for profile in ["default", "ci"] {
415            for configured in [false, true] {
416                for flag in [false, true] {
417                    let config = Config { fork_prefetch: configured, ..Default::default() };
418                    let figment = Figment::from(Serialized::defaults(config).profile(profile))
419                        .select(profile);
420                    let args = EvmArgs::parse_from(
421                        ["foundry-cli"].into_iter().chain(flag.then_some("--fork-prefetch")),
422                    );
423                    let merged = Config::from_provider(figment.merge(args)).unwrap();
424                    assert_eq!(
425                        merged.fork_prefetch,
426                        flag || configured,
427                        "profile={profile}, configured={configured}, flag={flag}",
428                    );
429                }
430            }
431        }
432    }
433
434    #[test]
435    fn compute_units_per_second_skips_when_none() {
436        let args = EvmArgs::default();
437        let data = args.data().expect("provider data");
438        let dict = data.get(&Config::selected_profile()).expect("profile dict");
439        assert!(
440            !dict.contains_key("compute_units_per_second"),
441            "compute_units_per_second should be skipped when None"
442        );
443    }
444
445    #[test]
446    fn compute_units_per_second_present_when_some() {
447        let args = EvmArgs {
448            rpc: RpcCommonOpts { compute_units_per_second: Some(1000), ..Default::default() },
449            ..Default::default()
450        };
451        let data = args.data().expect("provider data");
452        let dict = data.get(&Config::selected_profile()).expect("profile dict");
453        let val = dict.get("compute_units_per_second").expect("cups present");
454        assert_eq!(val, &Value::from(1000u64));
455    }
456
457    #[test]
458    fn celo_network_is_included_in_provider_data() {
459        let args = EvmArgs { networks: NetworkConfigs::with_celo(), ..Default::default() };
460        let data = args.data().expect("provider data");
461        let dict = data.get(&Config::selected_profile()).expect("profile dict");
462
463        assert_eq!(dict.get("celo"), Some(&Value::from(true)));
464        assert!(!dict.contains_key("network"));
465    }
466
467    #[test]
468    fn explicit_ethereum_network_is_included_in_provider_data() {
469        let args = EvmArgs { networks: NetworkConfigs::with_ethereum(), ..Default::default() };
470        let data = args.data().expect("provider data");
471        let dict = data.get(&Config::selected_profile()).expect("profile dict");
472
473        assert_eq!(dict.get("network"), Some(&Value::from("ethereum")));
474        assert!(!dict.contains_key("celo"));
475    }
476
477    #[test]
478    fn rpc_url_arg_does_not_read_eth_rpc_url_env() {
479        let command = EvmArgs::command();
480        let rpc_url =
481            command.get_arguments().find(|arg| arg.get_id() == "rpc_url").expect("rpc_url arg");
482
483        assert!(rpc_url.get_env().is_none());
484    }
485
486    #[test]
487    fn can_parse_chain_id() {
488        let args = EvmArgs {
489            env: EnvArgs { chain: Some(NamedChain::Mainnet.into()), ..Default::default() },
490            ..Default::default()
491        };
492        let config = Config::from_provider(Config::figment().merge(args)).unwrap();
493        assert_eq!(config.chain, Some(NamedChain::Mainnet.into()));
494
495        let env = EnvArgs::parse_from(["foundry-cli", "--chain-id", "goerli"]);
496        assert_eq!(env.chain, Some(NamedChain::Goerli.into()));
497    }
498
499    #[cfg(feature = "base")]
500    #[test]
501    fn can_parse_namespaced_base_hardfork() {
502        let args = EvmArgs::parse_from(["foundry-cli", "--hardfork", "base:Beryl"]);
503        assert_eq!(args.hardfork.map(String::from).as_deref(), Some("base:Beryl"));
504
505        let config = Config::from_provider(Config::figment().merge(args)).unwrap();
506        assert!(config.networks.is_base());
507        assert_eq!(config.hardfork.map(String::from).as_deref(), Some("base:Beryl"));
508    }
509
510    #[test]
511    fn hardfork_arg_selects_network() {
512        let args = EvmArgs::parse_from(["foundry-cli", "--hardfork", "tempo:T5"]);
513        let hardfork = "tempo:T5".parse::<FoundryHardfork>().unwrap();
514        assert_eq!(args.hardfork, Some(hardfork));
515
516        let config = Config::from_provider(Config::figment().merge(args)).unwrap();
517        assert_eq!(config.hardfork, Some(hardfork));
518        assert!(config.networks.is_tempo());
519    }
520
521    #[test]
522    fn test_memory_limit() {
523        let args = EvmArgs {
524            env: EnvArgs { chain: Some(NamedChain::Mainnet.into()), ..Default::default() },
525            ..Default::default()
526        };
527        let config = Config::from_provider(Config::figment().merge(args)).unwrap();
528        assert_eq!(config.memory_limit, Config::default().memory_limit);
529
530        let env = EnvArgs::parse_from(["foundry-cli", "--memory-limit", "100"]);
531        assert_eq!(env.memory_limit, Some(100));
532    }
533
534    #[test]
535    fn test_chain_id() {
536        let env = EnvArgs::parse_from(["foundry-cli", "--chain-id", "1"]);
537        assert_eq!(env.chain, Some(Chain::mainnet()));
538
539        let env = EnvArgs::parse_from(["foundry-cli", "--chain-id", "mainnet"]);
540        assert_eq!(env.chain, Some(Chain::mainnet()));
541        let args = EvmArgs { env, ..Default::default() };
542        let config = Config::from_provider(Config::figment().merge(args)).unwrap();
543        assert_eq!(config.chain, Some(Chain::mainnet()));
544    }
545}