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        // Authorize linked libraries before the script constructor can call them. Configured
170        // libraries already present on a fork are not in `predeploy_libraries`.
171        for address in
172            self.build_data.libraries.libs.values().flat_map(|libraries| libraries.values())
173        {
174            runner.executor.backend_mut().allow_cheatcode_access(address.parse()?);
175        }
176
177        let (address, mut setup_result) = runner.setup(
178            &self.build_data.predeploy_libraries,
179            self.execution_data.bytecode.clone(),
180            needs_setup(&self.execution_data.abi),
181            &self.script_config,
182            self.args.broadcast,
183        )?;
184
185        if setup_result.success {
186            let script_result = runner.script(address, self.execution_data.calldata.clone())?;
187
188            setup_result.success &= script_result.success;
189            setup_result.gas_used = script_result.gas_used;
190            setup_result.logs.extend(script_result.logs);
191            setup_result.traces.extend(script_result.traces);
192            setup_result.labeled_addresses.extend(script_result.labeled_addresses);
193            setup_result.debug_bytecodes.extend(script_result.debug_bytecodes);
194            setup_result.returned = script_result.returned;
195            setup_result.exit_reason = script_result.exit_reason;
196            setup_result.breakpoints = script_result.breakpoints;
197
198            match (&mut setup_result.transactions, script_result.transactions) {
199                (Some(txs), Some(new_txs)) => {
200                    txs.extend(new_txs);
201                }
202                (None, Some(new_txs)) => {
203                    setup_result.transactions = Some(new_txs);
204                }
205                _ => {}
206            }
207        }
208
209        Ok(setup_result)
210    }
211
212    /// It finds the deployer from the running script and uses it to predeploy libraries.
213    ///
214    /// If there are multiple candidate addresses, it skips everything and lets `--sender` deploy
215    /// them instead.
216    fn maybe_new_sender(
217        &self,
218        transactions: Option<&BroadcastableTransactions<FEN::Network>>,
219    ) -> Result<Option<Address>> {
220        let mut new_sender = None;
221
222        if let Some(txs) = transactions {
223            // If the user passed a `--sender` don't check anything.
224            if self.build_data.predeploy_libraries.libraries_count() > 0
225                && self.args.evm.sender.is_none()
226            {
227                for tx in txs {
228                    if tx.transaction.to().is_none() {
229                        let sender = tx.transaction.from().expect("no sender");
230                        if let Some(ns) = new_sender {
231                            if sender != ns {
232                                sh_warn!(
233                                    "You have more than one deployer who could predeploy libraries. Using `--sender` instead."
234                                )?;
235                                return Ok(None);
236                            }
237                        } else if sender != self.script_config.evm_opts.sender {
238                            new_sender = Some(sender);
239                        }
240                    }
241                }
242            }
243        }
244        Ok(new_sender)
245    }
246}
247
248/// Container for information about RPC-endpoints used during script execution.
249pub struct RpcData {
250    /// Unique list of rpc urls present.
251    pub total_rpcs: HashSet<String>,
252    /// If true, one of the transactions did not have a rpc.
253    pub missing_rpc: bool,
254    /// Chain IDs already fetched for each RPC URL.
255    pub(crate) chain_ids: HashMap<String, u64>,
256}
257
258impl RpcData {
259    /// Iterates over script transactions and collects RPC urls.
260    fn from_transactions<N: Network>(txs: &BroadcastableTransactions<N>) -> Self {
261        let missing_rpc = txs.iter().any(|tx| tx.rpc.is_none());
262        let total_rpcs = txs.iter().filter_map(|tx| tx.rpc.clone()).collect::<HashSet<_>>();
263
264        Self { total_rpcs, missing_rpc, chain_ids: HashMap::default() }
265    }
266
267    /// Returns true if script might be multi-chain.
268    /// Returns false positive in case when missing rpc is the same as the only rpc present.
269    pub fn is_multi_chain(&self) -> bool {
270        self.total_rpcs.len() > 1 || (self.missing_rpc && !self.total_rpcs.is_empty())
271    }
272
273    /// Checks if all RPCs support EIP-3855. Prints a warning if not.
274    async fn check_shanghai_support(&mut self) -> Result<()> {
275        let chain_ids =
276            self.total_rpcs.iter().filter(|rpc| !self.chain_ids.contains_key(*rpc)).map(
277                |rpc| async move {
278                    let provider = ProviderBuilder::<AnyNetwork>::new(rpc).build().ok()?;
279                    Some((rpc.clone(), provider.get_chain_id().await.ok()?))
280                },
281            );
282
283        self.chain_ids.extend(join_all(chain_ids).await.into_iter().flatten());
284        let iter = self
285            .chain_ids
286            .values()
287            .filter_map(|id| NamedChain::try_from(*id).ok())
288            .map(|chain| (chain.supports_shanghai(), chain));
289        if iter.clone().any(|(s, _)| !s) {
290            let msg = format!(
291                "\
292EIP-3855 is not supported in one or more of the RPCs used.
293Unsupported Chain IDs: {}.
294Contracts deployed with a Solidity version equal or higher than 0.8.20 might not work properly.
295For more information, please see https://eips.ethereum.org/EIPS/eip-3855",
296                iter.filter(|(supported, _)| !supported)
297                    .map(|(_, chain)| chain as u64)
298                    .format(", ")
299            );
300            sh_warn!("{msg}")?;
301        }
302        Ok(())
303    }
304}
305
306/// Container for data being collected after execution.
307pub struct ExecutionArtifacts {
308    /// Trace decoder used to decode traces.
309    pub decoder: CallTraceDecoder,
310    /// Return values from the execution result.
311    pub returns: HashMap<String, NestedValue>,
312    /// Information about RPC endpoints used during script execution.
313    pub rpc_data: RpcData,
314}
315
316/// State after the script has been executed.
317pub struct ExecutedState<FEN: FoundryEvmNetwork> {
318    pub args: ScriptArgs,
319    pub script_config: ScriptConfig<FEN>,
320    pub script_wallets: Wallets,
321    pub browser_wallet: Option<BrowserSigner<FEN::Network>>,
322    pub build_data: LinkedBuildData,
323    pub execution_data: ExecutionData,
324    pub execution_result: ScriptResult<FEN::Network>,
325}
326
327impl<FEN: FoundryEvmNetwork> ExecutedState<FEN> {
328    /// Collects the data we need for simulation and various post-execution tasks.
329    pub async fn prepare_simulation(self) -> Result<PreSimulationState<FEN>> {
330        self.prepare_simulation_inner(false).await
331    }
332
333    /// Collects simulation data without emitting warnings for an optimization candidate that may
334    /// be discarded.
335    pub(crate) async fn prepare_simulation_silent(self) -> Result<PreSimulationState<FEN>> {
336        self.prepare_simulation_inner(true).await
337    }
338
339    async fn prepare_simulation_inner(self, silent: bool) -> Result<PreSimulationState<FEN>> {
340        let returns = self.get_returns()?;
341
342        let mut rpc_data = RpcData::from_transactions(
343            self.execution_result.transactions.as_ref().unwrap_or(&Default::default()),
344        );
345        if let Some(identity) = &self.script_config.evm_opts.fork_endpoint
346            && rpc_data.total_rpcs.contains(&identity.endpoint)
347        {
348            rpc_data.chain_ids.insert(identity.endpoint.clone(), identity.execution_chain_id);
349        }
350
351        if rpc_data.is_multi_chain() && !silent {
352            sh_warn!("Multi chain deployment is still under development. Use with caution.")?;
353            if !self.build_data.libraries.is_empty() {
354                eyre::bail!(
355                    "Multi chain deployment does not support library linking at the moment."
356                );
357            }
358        }
359        if !silent {
360            rpc_data.check_shanghai_support().await?;
361        }
362
363        let decoder = self.build_trace_decoder(&rpc_data).await?;
364
365        Ok(PreSimulationState {
366            args: self.args,
367            script_config: self.script_config,
368            script_wallets: self.script_wallets,
369            browser_wallet: self.browser_wallet,
370            build_data: self.build_data,
371            execution_data: self.execution_data,
372            execution_result: self.execution_result,
373            execution_artifacts: ExecutionArtifacts { decoder, returns, rpc_data },
374        })
375    }
376
377    /// Builds [CallTraceDecoder] from the execution result and known contracts.
378    async fn build_trace_decoder(&self, rpc_data: &RpcData) -> Result<CallTraceDecoder> {
379        let chain_id = self.script_config.source_chain_id.map(Chain::from).or_else(|| {
380            self.script_config
381                .evm_opts
382                .fork_url
383                .as_ref()
384                .and_then(|url| rpc_data.chain_ids.get(url))
385                .map(|chain_id| (*chain_id).into())
386        });
387        let chain_id = match chain_id {
388            Some(chain_id) => Some(chain_id),
389            None => self.script_config.evm_opts.get_remote_chain_id().await,
390        };
391        build_trace_decoder_for_context(
392            &self.args,
393            &self.script_config,
394            &self.build_data.known_contracts,
395            &self.build_data.sources,
396            &self.execution_result,
397            chain_id,
398        )
399    }
400
401    /// Collects the return values from the execution result.
402    fn get_returns(&self) -> Result<HashMap<String, NestedValue>> {
403        let mut returns = HashMap::default();
404        let returned = &self.execution_result.returned;
405        let func = &self.execution_data.func;
406
407        match func.abi_decode_output(returned) {
408            Ok(decoded) => {
409                for (index, (token, output)) in decoded.iter().zip(&func.outputs).enumerate() {
410                    let internal_type =
411                        output.internal_type.clone().unwrap_or(InternalType::Other {
412                            contract: None,
413                            ty: "unknown".to_string(),
414                        });
415
416                    let label = if output.name.is_empty() {
417                        index.to_string()
418                    } else {
419                        output.name.clone()
420                    };
421
422                    returns.insert(
423                        label,
424                        NestedValue {
425                            internal_type: internal_type.to_string(),
426                            value: format_token_raw(token),
427                        },
428                    );
429                }
430            }
431            Err(_) => {
432                sh_err!("Failed to decode return value: {:x?}", returned)?;
433            }
434        }
435
436        Ok(returns)
437    }
438}
439
440/// Builds a trace decoder for the exact execution context of a script runner.
441pub(crate) fn build_trace_decoder_for_context<FEN: FoundryEvmNetwork>(
442    args: &ScriptArgs,
443    script_config: &ScriptConfig<FEN>,
444    known_contracts: &ContractsByArtifact,
445    sources: &ContractSources,
446    execution_result: &ScriptResult<FEN::Network>,
447    chain_id: Option<Chain>,
448) -> Result<CallTraceDecoder> {
449    let resolved_hardfork = script_config.hardfork;
450    let mut tracing = script_config.config.tracing.clone();
451    tracing.labels.extend(execution_result.labeled_addresses.clone());
452
453    let builder = CallTraceDecoderBuilder::new()
454        .with_tracing_config(&tracing)
455        .with_known_contracts(known_contracts)
456        .with_signature_identifier(SignaturesIdentifier::from_config(&script_config.config)?)
457        .with_networks(script_config.config.networks)
458        .with_chain_id(chain_id.map(|chain| chain.id()))
459        .with_hardfork(resolved_hardfork);
460    let mut decoder = builder.build();
461
462    // The debugger resolves frame identities before decoding internal calls.
463    if tracing.decode_internal && !args.debug {
464        decoder.debug_identifier = Some(DebugTraceIdentifier::new(sources.clone()));
465    }
466
467    let use_debug_bytecodes = args.debug && !execution_result.debug_bytecodes.is_empty();
468    let mut identifier = if use_debug_bytecodes {
469        TraceIdentifiers::new()
470            .with_local_and_bytecodes(known_contracts, &execution_result.debug_bytecodes)
471    } else {
472        TraceIdentifiers::new().with_local(known_contracts)
473    }
474    .with_external(&script_config.config, chain_id)?;
475
476    for (_, trace) in &execution_result.traces {
477        decoder.identify(trace, &mut identifier);
478    }
479
480    Ok(decoder)
481}
482
483impl<FEN: FoundryEvmNetwork> PreSimulationState<FEN> {
484    pub async fn show_json(&self) -> Result<()> {
485        let mut result = self.execution_result.clone();
486        let trace_depth = self.script_config.config.tracing.trace_depth;
487
488        for (_, trace) in &mut result.traces {
489            decode_trace_arena(trace, &self.execution_artifacts.decoder).await;
490            if let Some(trace_depth) = trace_depth {
491                *trace = trace_arena_at_depth(trace, trace_depth);
492            }
493        }
494
495        let json_result = JsonResult {
496            logs: decode_console_logs(&result.logs),
497            returns: &self.execution_artifacts.returns,
498            result: &result,
499        };
500        let json = serde_json::to_string(&json_result)?;
501
502        sh_println!("{json}")?;
503
504        if !self.execution_result.success {
505            return Err(eyre::eyre!(
506                "script failed: {}",
507                &self
508                    .execution_artifacts
509                    .decoder
510                    .revert_decoder
511                    .decode(&result.returned[..], result.exit_reason)
512            ));
513        }
514
515        Ok(())
516    }
517
518    pub async fn show_traces(&self) -> Result<()> {
519        let tracing = &self.script_config.config.tracing;
520        let verbosity = tracing.verbosity;
521        let func = &self.execution_data.func;
522        let result = &self.execution_result;
523        let decoder = &self.execution_artifacts.decoder;
524
525        if !result.success || verbosity > 3 {
526            if result.traces.is_empty() {
527                warn!(verbosity, "no traces");
528            }
529
530            sh_println!("Traces:")?;
531            for (kind, trace) in &result.traces {
532                let should_include = match kind {
533                    TraceKind::Setup => verbosity >= 5,
534                    TraceKind::Execution => verbosity > 3,
535                    _ => false,
536                } || !result.success;
537
538                if should_include {
539                    let mut trace = trace.clone();
540                    decode_trace_arena(&mut trace, decoder).await;
541                    if let Some(trace_depth) = tracing.trace_depth {
542                        prune_trace_depth(&mut trace, trace_depth);
543                    }
544                    sh_println!("{}", render_trace_arena_inner(&trace, false, verbosity > 4))?;
545                }
546            }
547            sh_println!()?;
548        }
549
550        if result.success {
551            sh_println!("{}", "Script ran successfully.".green())?;
552        }
553
554        if self.script_config.evm_opts.fork_url.is_none() {
555            sh_println!("Gas used: {}", result.gas_used)?;
556        }
557
558        if result.success && !result.returned.is_empty() {
559            sh_println!("\n== Return ==")?;
560            match func.abi_decode_output(&result.returned) {
561                Ok(decoded) => {
562                    for (index, (token, output)) in decoded.iter().zip(&func.outputs).enumerate() {
563                        let internal_type =
564                            output.internal_type.clone().unwrap_or(InternalType::Other {
565                                contract: None,
566                                ty: "unknown".to_string(),
567                            });
568
569                        let label = if output.name.is_empty() {
570                            index.to_string()
571                        } else {
572                            output.name.clone()
573                        };
574                        sh_println!(
575                            "{label}: {internal_type} {value}",
576                            label = label.trim_end(),
577                            value = format_token(token)
578                        )?;
579                    }
580                }
581                Err(_) => {
582                    sh_err!("{:x?}", (&result.returned))?;
583                }
584            }
585        }
586
587        let console_logs = decode_console_logs(&result.logs);
588        if !console_logs.is_empty() {
589            sh_println!("\n== Logs ==")?;
590            for log in console_logs {
591                sh_println!("  {log}")?;
592            }
593        }
594
595        if !result.success {
596            return Err(eyre::eyre!(
597                "script failed: {}",
598                &self
599                    .execution_artifacts
600                    .decoder
601                    .revert_decoder
602                    .decode(&result.returned[..], result.exit_reason)
603            ));
604        }
605
606        Ok(())
607    }
608
609    pub fn run_debugger(self) -> Result<()> {
610        self.create_debugger()?.run(None)
611    }
612
613    pub fn dump_debugger(self, path: &Path) -> Result<()> {
614        self.create_debugger()?.run(Some(path))
615    }
616
617    fn create_debugger(self) -> Result<DebuggerBuilder> {
618        let mut sources = self.build_data.sources;
619        sources.insert_compiled_sources(
620            &self.script_config.config.project_paths::<MultiCompilerLanguage>().build_infos,
621        );
622        Ok(DebuggerBuilder::new()
623            .traces(self.execution_result.traces)
624            .decoder(&self.execution_artifacts.decoder)
625            .known_contracts(&self.build_data.known_contracts)
626            .sources(sources)
627            .breakpoints(self.execution_result.breakpoints))
628    }
629}