Skip to main content

foundry_cli/utils/
cmd.rs

1use alloy_dyn_abi::{DynSolValue, Specifier};
2use alloy_json_abi::{Constructor, JsonAbi};
3use eyre::{Result, WrapErr};
4use foundry_common::{
5    TestFunctionExt, fmt::parse_tokens, fs, fs::json_files, selectors::SelectorKind, shell,
6};
7use foundry_compilers::{
8    Artifact, ArtifactId, ProjectCompileOutput, artifacts::CompactBytecode, utils::read_json_file,
9};
10use foundry_config::{
11    Chain, Config, NamedChain,
12    error::ExtractConfigError,
13    figment::{Figment, Provider},
14};
15use foundry_evm::{
16    core::evm::FoundryEvmNetwork,
17    executors::{DeployResult, EvmError, RawCallResult},
18    opts::EvmOpts,
19    traces::{
20        CallTraceDecoder, TraceKind, Traces, decode_trace_arena, identifier::SignaturesCache,
21        prune_trace_depth, render_trace_arena_inner, trace_arena_at_depth,
22    },
23};
24use std::{
25    fmt::Write,
26    path::{Path, PathBuf},
27};
28use yansi::Paint;
29
30/// Given a `Project`'s output, finds the contract by path and name and returns its
31/// ABI, creation bytecode, and `ArtifactId`.
32#[track_caller]
33pub fn find_contract_artifacts(
34    output: ProjectCompileOutput,
35    path: &Path,
36    name: &str,
37) -> Result<(JsonAbi, CompactBytecode, ArtifactId)> {
38    let mut other = Vec::new();
39    let Some((id, contract)) = output.into_artifacts().find_map(|(id, artifact)| {
40        if id.name == name && id.source == path {
41            Some((id, artifact))
42        } else {
43            other.push(id.name);
44            None
45        }
46    }) else {
47        let mut err = format!("could not find artifact: `{name}`");
48        if let Some(suggestion) = super::did_you_mean(name, other).pop()
49            && suggestion != name
50        {
51            err = format!(
52                r#"{err}
53
54        Did you mean `{suggestion}`?"#
55            );
56        }
57        eyre::bail!(err);
58    };
59
60    let abi = contract
61        .get_abi()
62        .ok_or_else(|| eyre::eyre!("contract {} does not contain abi", name))?
63        .into_owned();
64
65    let bin = contract
66        .get_bytecode()
67        .ok_or_else(|| eyre::eyre!("contract {} does not contain bytecode", name))?
68        .into_owned();
69
70    Ok((abi, bin, id))
71}
72
73/// Returns error if constructor has arguments.
74pub fn ensure_clean_constructor(abi: &JsonAbi) -> Result<()> {
75    if let Some(constructor) = &abi.constructor
76        && !constructor.inputs.is_empty()
77    {
78        eyre::bail!(
79            "Contract constructor should have no arguments. Add those arguments to  `run(...)` instead, and call it with `--sig run(...)`."
80        );
81    }
82    Ok(())
83}
84
85pub fn needs_setup(abi: &JsonAbi) -> bool {
86    let setup_fns: Vec<_> = abi.functions().filter(|func| func.name.is_setup()).collect();
87
88    for setup_fn in &setup_fns {
89        if setup_fn.name != "setUp" {
90            let _ = sh_warn!(
91                "Found invalid setup function \"{}\" did you mean \"setUp()\"?",
92                setup_fn.signature()
93            );
94        }
95    }
96
97    setup_fns.len() == 1 && setup_fns[0].name == "setUp"
98}
99
100pub fn eta_key(state: &indicatif::ProgressState, f: &mut dyn Write) {
101    write!(f, "{:.1}s", state.eta().as_secs_f64()).unwrap()
102}
103
104pub fn init_progress(len: u64, label: &str) -> indicatif::ProgressBar {
105    let pb = indicatif::ProgressBar::new(len);
106    let mut template =
107        "{prefix}{spinner:.green} [{elapsed_precise}] [{wide_bar:.cyan/blue}] {pos}/{len} "
108            .to_string();
109    write!(template, "{label}").unwrap();
110    template += " ({eta})";
111    pb.set_style(
112        indicatif::ProgressStyle::with_template(&template)
113            .unwrap()
114            .with_key("eta", crate::utils::eta_key)
115            .progress_chars("#>-"),
116    );
117    pb
118}
119
120/// True if the network calculates gas costs differently.
121pub fn has_different_gas_calc(chain_id: u64) -> bool {
122    let chain = Chain::from(chain_id);
123    if let Some(chain) = chain.named() {
124        return chain.is_tempo()
125            || chain.is_arbitrum()
126            || chain.is_elastic()
127            || matches!(
128                chain,
129                NamedChain::Acala
130                    | NamedChain::AcalaMandalaTestnet
131                    | NamedChain::AcalaTestnet
132                    | NamedChain::Etherlink
133                    | NamedChain::EtherlinkShadownet
134                    | NamedChain::Karura
135                    | NamedChain::KaruraTestnet
136                    | NamedChain::Kusama
137                    | NamedChain::Mantle
138                    | NamedChain::MantleSepolia
139                    | NamedChain::MegaEth
140                    | NamedChain::MegaEthTestnet
141                    | NamedChain::Metis
142                    | NamedChain::Monad
143                    | NamedChain::MonadTestnet
144                    | NamedChain::Moonbase
145                    | NamedChain::Moonbeam
146                    | NamedChain::MoonbeamDev
147                    | NamedChain::Moonriver
148                    | NamedChain::Plume
149                    | NamedChain::PlumeTestnet
150                    | NamedChain::Polkadot
151                    | NamedChain::PolkadotTestnet
152            );
153    }
154    false
155}
156
157/// True if it supports broadcasting in batches.
158pub fn has_batch_support(chain_id: u64) -> bool {
159    if let Some(chain) = Chain::from(chain_id).named() {
160        return !chain.is_arbitrum();
161    }
162    true
163}
164
165/// Helpers for loading configuration.
166///
167/// This is usually implemented through the macros defined in [`foundry_config`]. See
168/// [`foundry_config::impl_figment_convert`] for more details.
169///
170/// By default each function will emit warnings generated during loading, unless the `_no_warnings`
171/// variant is used.
172pub trait LoadConfig {
173    /// Load the [`Config`] based on the options provided in self.
174    fn figment(&self) -> Figment;
175
176    /// Load and sanitize the [`Config`] based on the options provided in self.
177    fn load_config(&self) -> Result<Config, ExtractConfigError> {
178        load_config_from_provider(self.figment())
179    }
180
181    /// Same as [`LoadConfig::load_config`] but does not emit warnings.
182    fn load_config_no_warnings(&self) -> Result<Config, ExtractConfigError> {
183        self.load_config_unsanitized_no_warnings().map(Config::sanitized)
184    }
185
186    /// Load [`Config`] but do not sanitize. See [`Config::sanitized`] for more information.
187    fn load_config_unsanitized(&self) -> Result<Config, ExtractConfigError> {
188        self.load_config_unsanitized_no_warnings().inspect(emit_warnings)
189    }
190
191    /// Same as [`LoadConfig::load_config_unsanitized`] but also emits warnings generated
192    fn load_config_unsanitized_no_warnings(&self) -> Result<Config, ExtractConfigError> {
193        Config::from_provider(self.figment())
194    }
195
196    /// Load and sanitize the [`Config`], as well as extract [`EvmOpts`] from self
197    fn load_config_and_evm_opts(&self) -> Result<(Config, EvmOpts)> {
198        self.load_config_and_evm_opts_no_warnings().inspect(|(config, _)| emit_warnings(config))
199    }
200
201    /// Same as [`LoadConfig::load_config_and_evm_opts`] but also emits warnings generated
202    fn load_config_and_evm_opts_no_warnings(&self) -> Result<(Config, EvmOpts)> {
203        let figment = self.figment();
204
205        let mut evm_opts = figment.extract::<EvmOpts>().map_err(ExtractConfigError::new)?;
206        let config = Config::from_provider(figment)?.sanitized();
207
208        if config.networks != Default::default() {
209            evm_opts.networks = config.networks;
210        }
211
212        // update the fork url if it was an alias
213        if let Some(fork_url) = config.get_rpc_url() {
214            trace!(target: "forge::config", ?fork_url, "Update EvmOpts fork url");
215            evm_opts.fork_url = Some(fork_url?.into_owned());
216        }
217
218        Ok((config, evm_opts))
219    }
220}
221
222/// Loads and sanitizes [`Config`] from a provider and emits generated warnings.
223pub fn load_config_from_provider<T: Provider>(provider: T) -> Result<Config, ExtractConfigError> {
224    Config::from_provider(provider).map(Config::sanitized).inspect(emit_warnings)
225}
226
227impl<T> LoadConfig for T
228where
229    for<'a> Figment: From<&'a T>,
230{
231    fn figment(&self) -> Figment {
232        self.into()
233    }
234}
235
236fn emit_warnings(config: &Config) {
237    for warning in &config.warnings {
238        let _ = sh_warn!("{warning}");
239    }
240}
241
242/// Read contract constructor arguments from the given file.
243pub fn read_constructor_args_file(constructor_args_path: PathBuf) -> Result<Vec<String>> {
244    if !constructor_args_path.exists() {
245        eyre::bail!("Constructor args file \"{}\" not found", constructor_args_path.display());
246    }
247    let args = if constructor_args_path.extension() == Some(std::ffi::OsStr::new("json")) {
248        read_json_file(&constructor_args_path).wrap_err(format!(
249            "Constructor args file \"{}\" must encode a json array",
250            constructor_args_path.display(),
251        ))?
252    } else {
253        fs::read_to_string(constructor_args_path)?.split_whitespace().map(str::to_string).collect()
254    };
255    Ok(args)
256}
257
258/// Parses constructor arguments by matching them against the constructor's input parameters.
259pub fn parse_constructor_args(
260    constructor: &Constructor,
261    constructor_args: &[String],
262) -> Result<Vec<DynSolValue>> {
263    if constructor.inputs.len() != constructor_args.len() {
264        eyre::bail!(
265            "Constructor argument count mismatch: expected {} but got {}",
266            constructor.inputs.len(),
267            constructor_args.len()
268        );
269    }
270
271    let mut params = Vec::with_capacity(constructor.inputs.len());
272    for (input, arg) in constructor.inputs.iter().zip(constructor_args) {
273        let ty = input
274            .resolve()
275            .wrap_err_with(|| format!("Could not resolve constructor arg: input={input}"))?;
276        params.push((ty, arg));
277    }
278    let params = params.iter().map(|(ty, arg)| (ty, arg.as_str()));
279    parse_tokens(params).map_err(Into::into)
280}
281
282/// A slimmed down return from the executor used for returning minimal trace + gas metering info
283#[derive(Debug)]
284pub struct TraceResult {
285    pub success: bool,
286    pub traces: Option<Traces>,
287    pub gas_used: u64,
288}
289
290impl TraceResult {
291    /// Create a new [`TraceResult`] from a [`RawCallResult`].
292    pub fn from_raw<FEN: FoundryEvmNetwork>(
293        raw: RawCallResult<FEN>,
294        trace_kind: TraceKind,
295    ) -> Self {
296        let RawCallResult { gas_used, traces, reverted, .. } = raw;
297        Self { success: !reverted, traces: traces.map(|arena| vec![(trace_kind, arena)]), gas_used }
298    }
299}
300
301impl<FEN: FoundryEvmNetwork> From<DeployResult<FEN>> for TraceResult {
302    fn from(result: DeployResult<FEN>) -> Self {
303        Self::from_raw(result.raw, TraceKind::Deployment)
304    }
305}
306
307impl<FEN: FoundryEvmNetwork> TryFrom<Result<DeployResult<FEN>, EvmError<FEN>>> for TraceResult {
308    type Error = EvmError<FEN>;
309
310    fn try_from(value: Result<DeployResult<FEN>, EvmError<FEN>>) -> Result<Self, Self::Error> {
311        match value {
312            Ok(result) => Ok(Self::from(result)),
313            Err(EvmError::Execution(err)) => Ok(Self::from_raw(err.raw, TraceKind::Deployment)),
314            Err(err) => Err(err),
315        }
316    }
317}
318
319impl<FEN: FoundryEvmNetwork> From<RawCallResult<FEN>> for TraceResult {
320    fn from(result: RawCallResult<FEN>) -> Self {
321        Self::from_raw(result, TraceKind::Execution)
322    }
323}
324
325pub async fn print_traces(
326    result: &mut TraceResult,
327    decoder: &CallTraceDecoder,
328    verbose: bool,
329    state_changes: bool,
330    trace_depth: Option<usize>,
331) -> Result<()> {
332    let traces = result.traces.as_mut().expect("No traces found");
333
334    if !shell::is_json() {
335        sh_println!("Traces:")?;
336    }
337
338    for (_, arena) in traces {
339        decode_trace_arena(arena, decoder).await;
340
341        if shell::is_json()
342            && let Some(trace_depth) = trace_depth
343        {
344            let arena = trace_arena_at_depth(arena, trace_depth);
345            sh_println!("{}", render_trace_arena_inner(&arena, verbose, state_changes))?;
346        } else {
347            if let Some(trace_depth) = trace_depth {
348                prune_trace_depth(arena, trace_depth);
349            }
350            sh_println!("{}", render_trace_arena_inner(arena, verbose, state_changes))?;
351        }
352    }
353
354    if shell::is_json() {
355        return Ok(());
356    }
357
358    sh_println!()?;
359    if result.success {
360        sh_println!("{}", "Transaction successfully executed.".green())?;
361    } else {
362        sh_err!("Transaction failed.")?;
363    }
364    sh_println!("Gas used: {}", result.gas_used)?;
365
366    Ok(())
367}
368
369/// Traverse the artifacts in the project to generate local signatures and merge them into the cache
370/// file.
371pub fn cache_local_signatures(output: &ProjectCompileOutput) -> Result<()> {
372    let Some(cache_dir) = Config::foundry_cache_dir() else {
373        eyre::bail!("Failed to get `cache_dir` to generate local signatures.");
374    };
375    let path = cache_dir.join("signatures");
376    let mut signatures = SignaturesCache::load(&path);
377    for (_, artifact) in output.artifacts() {
378        if let Some(abi) = &artifact.abi {
379            signatures.extend_from_abi(abi);
380        }
381
382        // External libraries don't have functions included in the ABI, but `methodIdentifiers`.
383        if let Some(method_identifiers) = &artifact.method_identifiers {
384            signatures.extend(method_identifiers.iter().filter_map(|(signature, selector)| {
385                Some((SelectorKind::Function(selector.parse().ok()?), signature.clone()))
386            }));
387        }
388    }
389    signatures.save(&path);
390    Ok(())
391}
392
393/// Traverses all files at `folder_path`, parses any JSON ABI files found,
394/// and caches their function/event/error signatures to the local signatures cache.
395pub fn cache_signatures_from_abis(folder_path: impl AsRef<Path>) -> Result<()> {
396    let Some(cache_dir) = Config::foundry_cache_dir() else {
397        eyre::bail!("Failed to get `cache_dir` to generate local signatures.");
398    };
399    let path = cache_dir.join("signatures");
400    let mut signatures = SignaturesCache::load(&path);
401
402    json_files(folder_path.as_ref())
403        .filter_map(|path| std::fs::read_to_string(&path).ok())
404        .filter_map(|content| serde_json::from_str::<JsonAbi>(&content).ok())
405        .for_each(|json_abi| signatures.extend_from_abi(&json_abi));
406
407    signatures.save(&path);
408    Ok(())
409}
410
411#[cfg(test)]
412mod tests {
413    use super::*;
414    use foundry_config::TracingConfig;
415    use std::fs;
416    use tempfile::tempdir;
417
418    struct TracingConfigArgs;
419
420    impl LoadConfig for TracingConfigArgs {
421        fn figment(&self) -> Figment {
422            Config::figment()
423                .merge(("verbosity", 2u8))
424                .merge(("tracing", TracingConfig { verbosity: 4, ..Default::default() }))
425        }
426    }
427
428    #[test]
429    fn tracing_verbosity_is_independent_from_evm_opts() {
430        let (config, evm_opts) = TracingConfigArgs.load_config_and_evm_opts_no_warnings().unwrap();
431
432        assert_eq!(config.verbosity, 2);
433        assert_eq!(config.tracing.verbosity, 4);
434        assert_eq!(evm_opts.verbosity, 2);
435    }
436
437    #[test]
438    fn test_cache_signatures_from_abis() {
439        let temp_dir = tempdir().unwrap();
440        let abi_json = r#"[
441              {
442                  "type": "function",
443                  "name": "myCustomFunction",
444                  "inputs": [{"name": "amount", "type": "uint256"}],
445                  "outputs": [],
446                  "stateMutability": "nonpayable"
447              },
448              {
449                  "type": "event",
450                  "name": "MyCustomEvent",
451                  "inputs": [{"name": "value", "type": "uint256", "indexed": false}],
452                  "anonymous": false
453              },
454              {
455                  "type": "error",
456                  "name": "MyCustomError",
457                  "inputs": [{"name": "code", "type": "uint256"}]
458              }
459          ]"#;
460
461        let abi_path = temp_dir.path().join("test.json");
462        fs::write(&abi_path, abi_json).unwrap();
463
464        cache_signatures_from_abis(temp_dir.path()).unwrap();
465
466        let cache_dir = Config::foundry_cache_dir().unwrap();
467        let cache_path = cache_dir.join("signatures");
468        let cache = SignaturesCache::load(&cache_path);
469
470        let func_selector: alloy_primitives::Selector = "0x2e2dbaf7".parse().unwrap();
471        assert!(cache.contains_key(&SelectorKind::Function(func_selector)));
472
473        let event_selector: alloy_primitives::B256 =
474            "0x8cc20c47f3a2463817352f75dec0dbf43a7a771b5f6817a92bd5724c1f4aa745".parse().unwrap();
475        assert!(cache.contains_key(&SelectorKind::Event(event_selector)));
476
477        let error_selector: alloy_primitives::Selector = "0xd35f45de".parse().unwrap();
478        assert!(cache.contains_key(&SelectorKind::Error(error_selector)));
479    }
480}