Skip to main content

forge_script/
execute.rs

1use super::{JsonResult, NestedValue, ScriptResult, runner::ScriptRunner};
2use crate::{
3    ScriptArgs, ScriptConfig,
4    build::{CompiledState, LinkedBuildData},
5    simulate::PreSimulationState,
6};
7use alloy_dyn_abi::FunctionExt;
8use alloy_json_abi::{Function, InternalType, JsonAbi};
9use alloy_network::{AnyNetwork, Network};
10use alloy_primitives::{
11    Address, Bytes,
12    map::{HashMap, HashSet},
13};
14use alloy_provider::Provider;
15use eyre::{OptionExt, Result};
16use foundry_cheatcodes::Wallets;
17use foundry_cli::utils::{ensure_clean_constructor, needs_setup};
18use foundry_common::{
19    ContractsByArtifact,
20    fmt::{format_token, format_token_raw},
21    provider::ProviderBuilder,
22};
23use foundry_compilers::multi::MultiCompilerLanguage;
24use foundry_config::{Chain, NamedChain};
25use foundry_debugger::DebuggerBuilder;
26use foundry_evm::{
27    core::evm::FoundryEvmNetwork,
28    decode::decode_console_logs,
29    inspectors::cheatcodes::BroadcastableTransactions,
30    traces::{
31        CallTraceDecoder, CallTraceDecoderBuilder, DebugTraceIdentifier, TraceKind,
32        debug::ContractSources,
33        decode_trace_arena,
34        identifier::{SignaturesIdentifier, TraceIdentifiers},
35        prune_trace_depth, render_trace_arena_inner, trace_arena_at_depth,
36    },
37};
38use foundry_wallets::wallet_browser::signer::BrowserSigner;
39use futures::future::join_all;
40use itertools::Itertools;
41use std::path::Path;
42use yansi::Paint;
43
44/// State after linking, contains the linked build data along with library addresses and optional
45/// array of libraries that need to be predeployed.
46pub struct LinkedState<FEN: FoundryEvmNetwork> {
47    pub args: ScriptArgs,
48    pub script_config: ScriptConfig<FEN>,
49    pub script_wallets: Wallets,
50    pub browser_wallet: Option<BrowserSigner<FEN::Network>>,
51    pub build_data: LinkedBuildData,
52}
53
54/// Container for data we need for execution which can only be obtained after linking stage.
55#[derive(Debug)]
56pub struct ExecutionData {
57    /// Function to call.
58    pub func: Function,
59    /// Calldata to pass to the target contract.
60    pub calldata: Bytes,
61    /// Bytecode of the target contract.
62    pub bytecode: Bytes,
63    /// ABI of the target contract.
64    pub abi: JsonAbi,
65}
66
67impl<FEN: FoundryEvmNetwork> LinkedState<FEN> {
68    /// Given linked and compiled artifacts, prepares data we need for execution.
69    /// This includes the function to call and the calldata to pass to it.
70    pub async fn prepare_execution(self) -> Result<PreExecutionState<FEN>> {
71        let Self { args, script_config, script_wallets, browser_wallet, build_data } = self;
72
73        let target_contract = build_data.get_target_contract()?;
74
75        let bytecode = target_contract.bytecode().ok_or_eyre("target contract has no bytecode")?;
76
77        let (func, calldata) = args.get_method_and_calldata(&target_contract.abi)?;
78
79        ensure_clean_constructor(&target_contract.abi)?;
80
81        Ok(PreExecutionState {
82            args,
83            script_config,
84            script_wallets,
85            browser_wallet,
86            execution_data: ExecutionData {
87                func,
88                calldata,
89                bytecode: bytecode.clone(),
90                abi: target_contract.abi.clone(),
91            },
92            build_data,
93        })
94    }
95}
96
97/// Same as [LinkedState], but also contains [ExecutionData].
98#[derive(Debug)]
99pub struct PreExecutionState<FEN: FoundryEvmNetwork> {
100    pub args: ScriptArgs,
101    pub script_config: ScriptConfig<FEN>,
102    pub script_wallets: Wallets,
103    pub browser_wallet: Option<BrowserSigner<FEN::Network>>,
104    pub build_data: LinkedBuildData,
105    pub execution_data: ExecutionData,
106}
107
108impl<FEN: FoundryEvmNetwork> PreExecutionState<FEN> {
109    /// Executes the script and returns the state after execution.
110    /// Might require executing script twice in cases when we determine sender from execution.
111    pub async fn execute(self) -> Result<ExecutedState<FEN>> {
112        self.execute_inner(false).await
113    }
114
115    /// Executes an optimization candidate while blocking externally observable cheatcodes.
116    pub(crate) async fn execute_restricted(self) -> Result<ExecutedState<FEN>> {
117        self.execute_inner(true).await
118    }
119
120    async fn execute_inner(mut self, restricted: bool) -> Result<ExecutedState<FEN>> {
121        let mut runner = self
122            .script_config
123            .get_runner_with_cheatcodes(
124                self.build_data.known_contracts.clone(),
125                self.script_wallets.clone(),
126                self.args.debug,
127                self.build_data.build_data.target.clone(),
128                restricted,
129            )
130            .await?;
131        let result = self.execute_with_runner(&mut runner).await?;
132
133        // If we have a new sender from execution, we need to use it to deploy libraries and relink
134        // contracts.
135        if let Some(new_sender) = self.maybe_new_sender(result.transactions.as_ref())? {
136            self.script_config.update_sender(new_sender).await?;
137
138            // Rollback to rerun linking with the new sender.
139            let state = CompiledState {
140                args: self.args,
141                script_config: self.script_config,
142                script_wallets: self.script_wallets,
143                browser_wallet: self.browser_wallet,
144                build_data: self.build_data.build_data,
145            };
146
147            return Box::pin(
148                state.link().await?.prepare_execution().await?.execute_inner(restricted),
149            )
150            .await;
151        }
152
153        Ok(ExecutedState {
154            args: self.args,
155            script_config: self.script_config,
156            script_wallets: self.script_wallets,
157            browser_wallet: self.browser_wallet,
158            build_data: self.build_data,
159            execution_data: self.execution_data,
160            execution_result: result,
161        })
162    }
163
164    /// Executes the script using the provided runner and returns the [ScriptResult].
165    pub async fn execute_with_runner(
166        &self,
167        runner: &mut ScriptRunner<FEN>,
168    ) -> Result<ScriptResult<FEN::Network>> {
169        let (address, mut setup_result) = runner.setup(
170            &self.build_data.predeploy_libraries,
171            self.execution_data.bytecode.clone(),
172            needs_setup(&self.execution_data.abi),
173            &self.script_config,
174            self.args.broadcast,
175        )?;
176
177        if setup_result.success {
178            let script_result = runner.script(address, self.execution_data.calldata.clone())?;
179
180            setup_result.success &= script_result.success;
181            setup_result.gas_used = script_result.gas_used;
182            setup_result.logs.extend(script_result.logs);
183            setup_result.traces.extend(script_result.traces);
184            setup_result.labeled_addresses.extend(script_result.labeled_addresses);
185            setup_result.debug_bytecodes.extend(script_result.debug_bytecodes);
186            setup_result.returned = script_result.returned;
187            setup_result.exit_reason = script_result.exit_reason;
188            setup_result.breakpoints = script_result.breakpoints;
189
190            match (&mut setup_result.transactions, script_result.transactions) {
191                (Some(txs), Some(new_txs)) => {
192                    txs.extend(new_txs);
193                }
194                (None, Some(new_txs)) => {
195                    setup_result.transactions = Some(new_txs);
196                }
197                _ => {}
198            }
199        }
200
201        Ok(setup_result)
202    }
203
204    /// It finds the deployer from the running script and uses it to predeploy libraries.
205    ///
206    /// If there are multiple candidate addresses, it skips everything and lets `--sender` deploy
207    /// them instead.
208    fn maybe_new_sender(
209        &self,
210        transactions: Option<&BroadcastableTransactions<FEN::Network>>,
211    ) -> Result<Option<Address>> {
212        let mut new_sender = None;
213
214        if let Some(txs) = transactions {
215            // If the user passed a `--sender` don't check anything.
216            if self.build_data.predeploy_libraries.libraries_count() > 0
217                && self.args.evm.sender.is_none()
218            {
219                for tx in txs {
220                    if tx.transaction.to().is_none() {
221                        let sender = tx.transaction.from().expect("no sender");
222                        if let Some(ns) = new_sender {
223                            if sender != ns {
224                                sh_warn!(
225                                    "You have more than one deployer who could predeploy libraries. Using `--sender` instead."
226                                )?;
227                                return Ok(None);
228                            }
229                        } else if sender != self.script_config.evm_opts.sender {
230                            new_sender = Some(sender);
231                        }
232                    }
233                }
234            }
235        }
236        Ok(new_sender)
237    }
238}
239
240/// Container for information about RPC-endpoints used during script execution.
241pub struct RpcData {
242    /// Unique list of rpc urls present.
243    pub total_rpcs: HashSet<String>,
244    /// If true, one of the transactions did not have a rpc.
245    pub missing_rpc: bool,
246    /// Chain IDs already fetched for each RPC URL.
247    pub(crate) chain_ids: HashMap<String, u64>,
248}
249
250impl RpcData {
251    /// Iterates over script transactions and collects RPC urls.
252    fn from_transactions<N: Network>(txs: &BroadcastableTransactions<N>) -> Self {
253        let missing_rpc = txs.iter().any(|tx| tx.rpc.is_none());
254        let total_rpcs = txs.iter().filter_map(|tx| tx.rpc.clone()).collect::<HashSet<_>>();
255
256        Self { total_rpcs, missing_rpc, chain_ids: HashMap::default() }
257    }
258
259    /// Returns true if script might be multi-chain.
260    /// Returns false positive in case when missing rpc is the same as the only rpc present.
261    pub fn is_multi_chain(&self) -> bool {
262        self.total_rpcs.len() > 1 || (self.missing_rpc && !self.total_rpcs.is_empty())
263    }
264
265    /// Checks if all RPCs support EIP-3855. Prints a warning if not.
266    async fn check_shanghai_support(&mut self) -> Result<()> {
267        let chain_ids =
268            self.total_rpcs.iter().filter(|rpc| !self.chain_ids.contains_key(*rpc)).map(
269                |rpc| async move {
270                    let provider = ProviderBuilder::<AnyNetwork>::new(rpc).build().ok()?;
271                    Some((rpc.clone(), provider.get_chain_id().await.ok()?))
272                },
273            );
274
275        self.chain_ids.extend(join_all(chain_ids).await.into_iter().flatten());
276        let iter = self
277            .chain_ids
278            .values()
279            .filter_map(|id| NamedChain::try_from(*id).ok())
280            .map(|chain| (chain.supports_shanghai(), chain));
281        if iter.clone().any(|(s, _)| !s) {
282            let msg = format!(
283                "\
284EIP-3855 is not supported in one or more of the RPCs used.
285Unsupported Chain IDs: {}.
286Contracts deployed with a Solidity version equal or higher than 0.8.20 might not work properly.
287For more information, please see https://eips.ethereum.org/EIPS/eip-3855",
288                iter.filter(|(supported, _)| !supported)
289                    .map(|(_, chain)| chain as u64)
290                    .format(", ")
291            );
292            sh_warn!("{msg}")?;
293        }
294        Ok(())
295    }
296}
297
298/// Container for data being collected after execution.
299pub struct ExecutionArtifacts {
300    /// Trace decoder used to decode traces.
301    pub decoder: CallTraceDecoder,
302    /// Return values from the execution result.
303    pub returns: HashMap<String, NestedValue>,
304    /// Information about RPC endpoints used during script execution.
305    pub rpc_data: RpcData,
306}
307
308/// State after the script has been executed.
309pub struct ExecutedState<FEN: FoundryEvmNetwork> {
310    pub args: ScriptArgs,
311    pub script_config: ScriptConfig<FEN>,
312    pub script_wallets: Wallets,
313    pub browser_wallet: Option<BrowserSigner<FEN::Network>>,
314    pub build_data: LinkedBuildData,
315    pub execution_data: ExecutionData,
316    pub execution_result: ScriptResult<FEN::Network>,
317}
318
319impl<FEN: FoundryEvmNetwork> ExecutedState<FEN> {
320    /// Collects the data we need for simulation and various post-execution tasks.
321    pub async fn prepare_simulation(self) -> Result<PreSimulationState<FEN>> {
322        self.prepare_simulation_inner(false).await
323    }
324
325    /// Collects simulation data without emitting warnings for an optimization candidate that may
326    /// be discarded.
327    pub(crate) async fn prepare_simulation_silent(self) -> Result<PreSimulationState<FEN>> {
328        self.prepare_simulation_inner(true).await
329    }
330
331    async fn prepare_simulation_inner(self, silent: bool) -> Result<PreSimulationState<FEN>> {
332        let returns = self.get_returns()?;
333
334        let mut rpc_data = RpcData::from_transactions(
335            self.execution_result.transactions.as_ref().unwrap_or(&Default::default()),
336        );
337        if let Some(identity) = &self.script_config.evm_opts.fork_endpoint
338            && rpc_data.total_rpcs.contains(&identity.endpoint)
339        {
340            rpc_data.chain_ids.insert(identity.endpoint.clone(), identity.execution_chain_id);
341        }
342
343        if rpc_data.is_multi_chain() && !silent {
344            sh_warn!("Multi chain deployment is still under development. Use with caution.")?;
345            if !self.build_data.libraries.is_empty() {
346                eyre::bail!(
347                    "Multi chain deployment does not support library linking at the moment."
348                );
349            }
350        }
351        if !silent {
352            rpc_data.check_shanghai_support().await?;
353        }
354
355        let decoder = self.build_trace_decoder(&rpc_data).await?;
356
357        Ok(PreSimulationState {
358            args: self.args,
359            script_config: self.script_config,
360            script_wallets: self.script_wallets,
361            browser_wallet: self.browser_wallet,
362            build_data: self.build_data,
363            execution_data: self.execution_data,
364            execution_result: self.execution_result,
365            execution_artifacts: ExecutionArtifacts { decoder, returns, rpc_data },
366        })
367    }
368
369    /// Builds [CallTraceDecoder] from the execution result and known contracts.
370    async fn build_trace_decoder(&self, rpc_data: &RpcData) -> Result<CallTraceDecoder> {
371        let chain_id = self.script_config.source_chain_id.map(Chain::from).or_else(|| {
372            self.script_config
373                .evm_opts
374                .fork_url
375                .as_ref()
376                .and_then(|url| rpc_data.chain_ids.get(url))
377                .map(|chain_id| (*chain_id).into())
378        });
379        let chain_id = match chain_id {
380            Some(chain_id) => Some(chain_id),
381            None => self.script_config.evm_opts.get_remote_chain_id().await,
382        };
383        build_trace_decoder_for_context(
384            &self.args,
385            &self.script_config,
386            &self.build_data.known_contracts,
387            &self.build_data.sources,
388            &self.execution_result,
389            chain_id,
390        )
391    }
392
393    /// Collects the return values from the execution result.
394    fn get_returns(&self) -> Result<HashMap<String, NestedValue>> {
395        let mut returns = HashMap::default();
396        let returned = &self.execution_result.returned;
397        let func = &self.execution_data.func;
398
399        match func.abi_decode_output(returned) {
400            Ok(decoded) => {
401                for (index, (token, output)) in decoded.iter().zip(&func.outputs).enumerate() {
402                    let internal_type =
403                        output.internal_type.clone().unwrap_or(InternalType::Other {
404                            contract: None,
405                            ty: "unknown".to_string(),
406                        });
407
408                    let label = if output.name.is_empty() {
409                        index.to_string()
410                    } else {
411                        output.name.clone()
412                    };
413
414                    returns.insert(
415                        label,
416                        NestedValue {
417                            internal_type: internal_type.to_string(),
418                            value: format_token_raw(token),
419                        },
420                    );
421                }
422            }
423            Err(_) => {
424                sh_err!("Failed to decode return value: {:x?}", returned)?;
425            }
426        }
427
428        Ok(returns)
429    }
430}
431
432/// Builds a trace decoder for the exact execution context of a script runner.
433pub(crate) fn build_trace_decoder_for_context<FEN: FoundryEvmNetwork>(
434    args: &ScriptArgs,
435    script_config: &ScriptConfig<FEN>,
436    known_contracts: &ContractsByArtifact,
437    sources: &ContractSources,
438    execution_result: &ScriptResult<FEN::Network>,
439    chain_id: Option<Chain>,
440) -> Result<CallTraceDecoder> {
441    let resolved_hardfork = script_config.hardfork;
442    let mut tracing = script_config.config.tracing.clone();
443    tracing.labels.extend(execution_result.labeled_addresses.clone());
444
445    let builder = CallTraceDecoderBuilder::new()
446        .with_tracing_config(&tracing)
447        .with_known_contracts(known_contracts)
448        .with_signature_identifier(SignaturesIdentifier::from_config(&script_config.config)?)
449        .with_networks(script_config.config.networks)
450        .with_chain_id(chain_id.map(|chain| chain.id()))
451        .with_hardfork(resolved_hardfork);
452    let mut decoder = builder.build();
453
454    // The debugger resolves frame identities before decoding internal calls.
455    if tracing.decode_internal && !args.debug {
456        decoder.debug_identifier = Some(DebugTraceIdentifier::new(sources.clone()));
457    }
458
459    let use_debug_bytecodes = args.debug && !execution_result.debug_bytecodes.is_empty();
460    let mut identifier = if use_debug_bytecodes {
461        TraceIdentifiers::new()
462            .with_local_and_bytecodes(known_contracts, &execution_result.debug_bytecodes)
463    } else {
464        TraceIdentifiers::new().with_local(known_contracts)
465    }
466    .with_external(&script_config.config, chain_id)?;
467
468    for (_, trace) in &execution_result.traces {
469        decoder.identify(trace, &mut identifier);
470    }
471
472    Ok(decoder)
473}
474
475impl<FEN: FoundryEvmNetwork> PreSimulationState<FEN> {
476    pub async fn show_json(&self) -> Result<()> {
477        let mut result = self.execution_result.clone();
478        let trace_depth = self.script_config.config.tracing.trace_depth;
479
480        for (_, trace) in &mut result.traces {
481            decode_trace_arena(trace, &self.execution_artifacts.decoder).await;
482            if let Some(trace_depth) = trace_depth {
483                *trace = trace_arena_at_depth(trace, trace_depth);
484            }
485        }
486
487        let json_result = JsonResult {
488            logs: decode_console_logs(&result.logs),
489            returns: &self.execution_artifacts.returns,
490            result: &result,
491        };
492        let json = serde_json::to_string(&json_result)?;
493
494        sh_println!("{json}")?;
495
496        if !self.execution_result.success {
497            return Err(eyre::eyre!(
498                "script failed: {}",
499                &self
500                    .execution_artifacts
501                    .decoder
502                    .revert_decoder
503                    .decode(&result.returned[..], result.exit_reason)
504            ));
505        }
506
507        Ok(())
508    }
509
510    pub async fn show_traces(&self) -> Result<()> {
511        let tracing = &self.script_config.config.tracing;
512        let verbosity = tracing.verbosity;
513        let func = &self.execution_data.func;
514        let result = &self.execution_result;
515        let decoder = &self.execution_artifacts.decoder;
516
517        if !result.success || verbosity > 3 {
518            if result.traces.is_empty() {
519                warn!(verbosity, "no traces");
520            }
521
522            sh_println!("Traces:")?;
523            for (kind, trace) in &result.traces {
524                let should_include = match kind {
525                    TraceKind::Setup => verbosity >= 5,
526                    TraceKind::Execution => verbosity > 3,
527                    _ => false,
528                } || !result.success;
529
530                if should_include {
531                    let mut trace = trace.clone();
532                    decode_trace_arena(&mut trace, decoder).await;
533                    if let Some(trace_depth) = tracing.trace_depth {
534                        prune_trace_depth(&mut trace, trace_depth);
535                    }
536                    sh_println!("{}", render_trace_arena_inner(&trace, false, verbosity > 4))?;
537                }
538            }
539            sh_println!()?;
540        }
541
542        if result.success {
543            sh_println!("{}", "Script ran successfully.".green())?;
544        }
545
546        if self.script_config.evm_opts.fork_url.is_none() {
547            sh_println!("Gas used: {}", result.gas_used)?;
548        }
549
550        if result.success && !result.returned.is_empty() {
551            sh_println!("\n== Return ==")?;
552            match func.abi_decode_output(&result.returned) {
553                Ok(decoded) => {
554                    for (index, (token, output)) in decoded.iter().zip(&func.outputs).enumerate() {
555                        let internal_type =
556                            output.internal_type.clone().unwrap_or(InternalType::Other {
557                                contract: None,
558                                ty: "unknown".to_string(),
559                            });
560
561                        let label = if output.name.is_empty() {
562                            index.to_string()
563                        } else {
564                            output.name.clone()
565                        };
566                        sh_println!(
567                            "{label}: {internal_type} {value}",
568                            label = label.trim_end(),
569                            value = format_token(token)
570                        )?;
571                    }
572                }
573                Err(_) => {
574                    sh_err!("{:x?}", (&result.returned))?;
575                }
576            }
577        }
578
579        let console_logs = decode_console_logs(&result.logs);
580        if !console_logs.is_empty() {
581            sh_println!("\n== Logs ==")?;
582            for log in console_logs {
583                sh_println!("  {log}")?;
584            }
585        }
586
587        if !result.success {
588            return Err(eyre::eyre!(
589                "script failed: {}",
590                &self
591                    .execution_artifacts
592                    .decoder
593                    .revert_decoder
594                    .decode(&result.returned[..], result.exit_reason)
595            ));
596        }
597
598        Ok(())
599    }
600
601    pub fn run_debugger(self) -> Result<()> {
602        self.create_debugger()?.run(None)
603    }
604
605    pub fn dump_debugger(self, path: &Path) -> Result<()> {
606        self.create_debugger()?.run(Some(path))
607    }
608
609    fn create_debugger(self) -> Result<DebuggerBuilder> {
610        let mut sources = self.build_data.sources;
611        sources.insert_compiled_sources(
612            &self.script_config.config.project_paths::<MultiCompilerLanguage>().build_infos,
613        );
614        Ok(DebuggerBuilder::new()
615            .traces(self.execution_result.traces)
616            .decoder(&self.execution_artifacts.decoder)
617            .known_contracts(&self.build_data.known_contracts)
618            .sources(sources)
619            .breakpoints(self.execution_result.breakpoints))
620    }
621}