Skip to main content

forge_script/
simulate.rs

1use super::{
2    multi_sequence::MultiChainSequence,
3    providers::{ProviderInfo, ProvidersManager},
4    recovery::RecoveryStore,
5    runner::ScriptRunner,
6    sequence::{ScriptSequenceKind, SequenceData},
7    transaction::ScriptTransactionBuilder,
8};
9use crate::{
10    ScriptArgs, ScriptConfig, ScriptResult,
11    broadcast::{BundledState, estimate_gas},
12    build::LinkedBuildData,
13    execute::{ExecutionArtifacts, ExecutionData, build_trace_decoder_for_context},
14    sequence::get_commit_hash,
15};
16use alloy_chains::{Chain, NamedChain};
17use alloy_network::{Network, TransactionBuilder};
18use alloy_primitives::{Address, U256, map::HashMap, utils::format_units};
19use alloy_provider::Provider;
20use dialoguer::Confirm;
21use eyre::{Context, Result};
22use forge_script_sequence::{ScriptSequence, TransactionWithMetadata};
23use foundry_cheatcodes::Wallets;
24use foundry_cli::utils::{has_different_gas_calc, now};
25use foundry_common::{
26    ContractData, ContractsByArtifact, provider::fee::resolve_broadcast_eip1559_fees, shell,
27    tempo::known_fee_token_symbol,
28};
29use foundry_evm::{
30    core::evm::FoundryEvmNetwork,
31    traces::{
32        CallTraceDecoder, Traces, debug::ContractSources, decode_trace_arena, prune_trace_depth,
33        render_trace_arena_inner,
34    },
35};
36use foundry_wallets::wallet_browser::signer::BrowserSigner;
37use std::{
38    collections::{BTreeMap, VecDeque},
39    mem,
40};
41
42#[cfg(feature = "monad")]
43mod monad;
44
45/// Same as [ExecutedState](crate::execute::ExecutedState), but also contains [ExecutionArtifacts]
46/// which are obtained from [ScriptResult].
47///
48/// Can be either converted directly to [BundledState] or driven to it through
49/// [FilledTransactionsState].
50pub struct PreSimulationState<FEN: FoundryEvmNetwork> {
51    pub args: ScriptArgs,
52    pub script_config: ScriptConfig<FEN>,
53    pub script_wallets: Wallets,
54    pub browser_wallet: Option<BrowserSigner<FEN::Network>>,
55    pub build_data: LinkedBuildData,
56    pub execution_data: ExecutionData,
57    pub execution_result: ScriptResult<FEN::Network>,
58    pub execution_artifacts: ExecutionArtifacts,
59}
60
61/// The result of simulating one transaction against its RPC.
62struct SimulationOutcome<N: Network> {
63    rpc: String,
64    transaction: SimulatedTransaction<N>,
65    traces: Traces,
66}
67
68/// Whether a simulated transaction executed, and what it became.
69enum SimulatedTransaction<N: Network> {
70    /// Execution failed, which aborts the script once every outcome is reported.
71    Failed,
72    /// Execution succeeded, filling in the transaction's gas and metadata.
73    Succeeded(TransactionWithMetadata<N>),
74    /// Execution succeeded, but the transaction sends no value to an address without code.
75    NoCode(TransactionWithMetadata<N>),
76}
77
78impl<N: Network> SimulatedTransaction<N> {
79    /// Classifies a successful execution of `transaction`.
80    const fn succeeded(transaction: TransactionWithMetadata<N>, no_code: bool) -> Self {
81        if no_code { Self::NoCode(transaction) } else { Self::Succeeded(transaction) }
82    }
83}
84
85struct RpcSimulationContext<R> {
86    runner: R,
87    decoder: CallTraceDecoder,
88}
89
90async fn build_rpc_simulation_context<FEN: FoundryEvmNetwork>(
91    rpc: String,
92    args: &ScriptArgs,
93    script_config: &ScriptConfig<FEN>,
94    known_contracts: &ContractsByArtifact,
95    sources: &ContractSources,
96    execution_result: &ScriptResult<FEN::Network>,
97) -> Result<(String, RpcSimulationContext<ScriptRunner<FEN>>)> {
98    let mut script_config = script_config.clone();
99    script_config.select_rpc(rpc.clone()).await?;
100    let runner = script_config._get_runner(None, false, false).await?;
101    let decoder = build_trace_decoder_for_context(
102        args,
103        &script_config,
104        known_contracts,
105        sources,
106        execution_result,
107        script_config.source_chain_id.map(Chain::from),
108    )?;
109    Ok((rpc, RpcSimulationContext { runner, decoder }))
110}
111
112async fn build_rpc_decoder<FEN: FoundryEvmNetwork>(
113    rpc: String,
114    args: &ScriptArgs,
115    script_config: &ScriptConfig<FEN>,
116    known_contracts: &ContractsByArtifact,
117    sources: &ContractSources,
118    execution_result: &ScriptResult<FEN::Network>,
119) -> Result<(String, CallTraceDecoder)> {
120    let mut script_config = script_config.clone();
121    script_config.resolve_rpc_execution_spec(rpc.clone()).await?;
122    let decoder = build_trace_decoder_for_context(
123        args,
124        &script_config,
125        known_contracts,
126        sources,
127        execution_result,
128        script_config.source_chain_id.map(Chain::from),
129    )?;
130    Ok((rpc, decoder))
131}
132
133impl<FEN: FoundryEvmNetwork> PreSimulationState<FEN> {
134    /// Simulates ordinary transactions against the fork and fills gas estimation and execution
135    /// metadata.
136    ///
137    /// Panics if any transaction has no `rpc` field. Monad simulation has a concrete owner and
138    /// must not use this entry point.
139    pub(crate) async fn fill_ordinary_metadata(self) -> Result<FilledTransactionsState<FEN>> {
140        if self.args.skip_simulation {
141            return self.fill_without_simulation().await;
142        }
143
144        let contexts = self.build_runners().await?.into_iter().collect::<HashMap<_, _>>();
145        let transactions =
146            self.transaction_metadata(|rpc| &contexts.get(rpc).expect("invalid rpc url").decoder)?;
147        let transactions = self.simulate_and_fill_with_contexts(transactions, contexts).await?;
148        Ok(self.into_filled(transactions))
149    }
150
151    /// Fills metadata derived without transaction simulation using each RPC's resolved context.
152    pub(crate) async fn fill_without_simulation(self) -> Result<FilledTransactionsState<FEN>> {
153        let decoders = self.build_rpc_decoders().await?;
154        let transactions =
155            self.transaction_metadata(|rpc| decoders.get(rpc).expect("invalid rpc url"))?;
156        sh_println!("\nSKIPPING ON CHAIN SIMULATION.")?;
157        Ok(self.into_filled(transactions))
158    }
159
160    fn transaction_metadata<'a>(
161        &self,
162        decoder_for_rpc: impl Fn(&str) -> &'a CallTraceDecoder,
163    ) -> Result<VecDeque<TransactionWithMetadata<FEN::Network>>> {
164        let address_to_abi = self.build_address_to_abi_map();
165        let transactions = self
166            .execution_result
167            .transactions
168            .clone()
169            .unwrap_or_default()
170            .into_iter()
171            .map(|tx| {
172                let rpc = tx.rpc.expect("missing broadcastable tx rpc url");
173                let sender = tx.transaction.from().expect("all transactions should have a sender");
174                let nonce = tx.transaction.nonce().expect("all transactions should have a nonce");
175                let to = tx.transaction.to();
176                let decoder = decoder_for_rpc(&rpc);
177
178                let mut builder = ScriptTransactionBuilder::new(tx.transaction, rpc);
179
180                if to.is_some() {
181                    builder.set_call(
182                        &address_to_abi,
183                        &self.build_data.known_contracts,
184                        decoder,
185                        self.script_config.evm_opts.create2_deployer,
186                    )?;
187                } else {
188                    builder.set_create(
189                        false,
190                        tx.contract_address.unwrap_or_else(|| sender.create(nonce)),
191                        &self.build_data.known_contracts,
192                    )?;
193                }
194
195                Ok(builder.build())
196            })
197            .collect::<Result<VecDeque<_>>>()?;
198
199        Ok(transactions)
200    }
201
202    fn into_filled(
203        self,
204        mut transactions: VecDeque<TransactionWithMetadata<FEN::Network>>,
205    ) -> FilledTransactionsState<FEN> {
206        // Use the final script labels, including labels set after a deployment. Additional
207        // contracts are only known after transaction simulation.
208        let labels = &self.execution_result.labeled_addresses;
209        for transaction in &mut transactions {
210            if transaction.call_kind.is_any_create() {
211                transaction.label =
212                    transaction.contract_address.and_then(|address| labels.get(&address)).cloned();
213            }
214            for contract in &mut transaction.additional_contracts {
215                contract.label = labels.get(&contract.address).cloned();
216            }
217        }
218
219        FilledTransactionsState {
220            args: self.args,
221            script_config: self.script_config,
222            script_wallets: self.script_wallets,
223            browser_wallet: self.browser_wallet,
224            build_data: self.build_data,
225            execution_artifacts: self.execution_artifacts,
226            transactions,
227        }
228    }
229
230    /// Executes every transaction in its RPC-specific simulation context and collects gas usage
231    /// and metadata.
232    async fn simulate_and_fill_with_contexts(
233        &self,
234        transactions: VecDeque<TransactionWithMetadata<FEN::Network>>,
235        mut contexts: HashMap<String, RpcSimulationContext<ScriptRunner<FEN>>>,
236    ) -> Result<VecDeque<TransactionWithMetadata<FEN::Network>>> {
237        trace!(target: "script", "executing onchain simulation");
238
239        // Execute in transaction order, retaining all outcomes before reporting failures.
240        self.show_simulation_header()?;
241        let results = transactions
242            .into_iter()
243            .map(|transaction| {
244                let rpc = transaction.rpc.clone();
245                let runner = &mut contexts.get_mut(&rpc).expect("invalid rpc url").runner;
246
247                let tx = transaction.tx();
248                let to = tx.to();
249                let result = runner
250                    .simulate(tx, transaction.is_fixed_gas_limit)
251                    .wrap_err("Internal EVM error during simulation")?;
252
253                if !result.success {
254                    return Ok(SimulationOutcome {
255                        rpc,
256                        transaction: SimulatedTransaction::Failed,
257                        traces: result.traces,
258                    });
259                }
260
261                // Simulate mining the transaction if the user passes `--slow`.
262                if self.args.slow {
263                    runner.executor.evm_env_mut().block.number += U256::ONE;
264                }
265
266                let is_noop_tx = if let Some(to) = to {
267                    runner.executor.is_empty_code(to)? && tx.value().unwrap_or_default().is_zero()
268                } else {
269                    false
270                };
271
272                let transaction = ScriptTransactionBuilder::from(transaction)
273                    .with_execution_result(
274                        &result,
275                        self.args.gas_estimate_multiplier,
276                        &self.build_data,
277                    )?
278                    .build();
279
280                eyre::Ok(SimulationOutcome {
281                    rpc,
282                    transaction: SimulatedTransaction::succeeded(transaction, is_noop_tx),
283                    traces: result.traces,
284                })
285            })
286            .collect::<Vec<_>>();
287
288        self.collect_simulation_results(results, &contexts).await
289    }
290
291    fn show_simulation_header(&self) -> Result<()> {
292        if !shell::is_json() && self.script_config.config.tracing.verbosity > 3 {
293            sh_println!("==========================")?;
294            sh_println!("Simulated On-chain Traces:\n")?;
295        }
296        Ok(())
297    }
298
299    async fn collect_simulation_results<R>(
300        &self,
301        results: Vec<Result<SimulationOutcome<FEN::Network>>>,
302        contexts: &HashMap<String, RpcSimulationContext<R>>,
303    ) -> Result<VecDeque<TransactionWithMetadata<FEN::Network>>> {
304        let mut final_txs = VecDeque::new();
305        let tracing = &self.script_config.config.tracing;
306
307        let mut abort = false;
308        for res in results {
309            let SimulationOutcome { rpc, transaction, mut traces } = res?;
310
311            // Failed executions always show their traces.
312            if !shell::is_json()
313                && (matches!(transaction, SimulatedTransaction::Failed) || tracing.verbosity > 3)
314            {
315                let decoder = &contexts.get(&rpc).expect("invalid rpc url").decoder;
316                for (_, trace) in &mut traces {
317                    decode_trace_arena(trace, decoder).await;
318                    if let Some(trace_depth) = tracing.trace_depth {
319                        prune_trace_depth(trace, trace_depth);
320                    }
321                    sh_println!(
322                        "{}",
323                        render_trace_arena_inner(trace, false, tracing.verbosity > 4)
324                    )?;
325                }
326            }
327
328            match transaction {
329                SimulatedTransaction::Failed => abort = true,
330                SimulatedTransaction::Succeeded(tx) => final_txs.push_back(tx),
331                SimulatedTransaction::NoCode(tx) => {
332                    let to = tx.contract_address.unwrap();
333                    sh_warn!(
334                        "Script contains a transaction to {to} which does not contain any code."
335                    )?;
336
337                    // Only prompt if we're broadcasting and we've not disabled interactivity.
338                    if self.args.should_broadcast() && !self.args.non_interactive {
339                        if !dialoguer::console::Term::stderr().is_term() {
340                            eyre::bail!(
341                                "transaction to {to} has no code; pass --non-interactive to continue without confirmation"
342                            );
343                        }
344                        if !Confirm::new()
345                            .with_prompt("Do you wish to continue?".to_string())
346                            .interact()?
347                        {
348                            eyre::bail!("User canceled the script.");
349                        }
350                    }
351
352                    final_txs.push_back(tx);
353                }
354            }
355        }
356
357        if abort {
358            eyre::bail!("Simulated execution failed.");
359        }
360
361        Ok(final_txs)
362    }
363
364    /// Build mapping from contract address to its ABI, code and contract name.
365    fn build_address_to_abi_map(&self) -> BTreeMap<Address, &ContractData> {
366        self.execution_artifacts
367            .decoder
368            .contracts
369            .iter()
370            .filter_map(move |(addr, contract_id)| {
371                if let Ok(Some((_, data))) =
372                    self.build_data.known_contracts.find_by_name_or_identifier(contract_id)
373                {
374                    return Some((*addr, data));
375                }
376                None
377            })
378            .collect()
379    }
380
381    /// Build [ScriptRunner] forking given RPC for each RPC used in the script.
382    async fn build_runners(
383        &self,
384    ) -> Result<Vec<(String, RpcSimulationContext<ScriptRunner<FEN>>)>> {
385        let rpcs = &self.execution_artifacts.rpc_data.total_rpcs;
386
387        if !shell::is_json() {
388            let n = rpcs.len();
389            let s = if n == 1 { "" } else { "s" };
390            sh_println!("\n## Setting up {n} EVM{s}.")?;
391        }
392
393        // Context construction performs several identity and block probes per endpoint. Resolve
394        // endpoints serially so setup does not create an unbounded cross-endpoint request burst.
395        let mut contexts = Vec::with_capacity(rpcs.len());
396        for rpc in rpcs.iter().cloned() {
397            contexts.push(
398                build_rpc_simulation_context(
399                    rpc,
400                    &self.args,
401                    &self.script_config,
402                    &self.build_data.known_contracts,
403                    &self.build_data.sources,
404                    &self.execution_result,
405                )
406                .await?,
407            );
408        }
409        Ok(contexts)
410    }
411
412    /// Builds one trace decoder for every RPC without constructing simulation runners.
413    async fn build_rpc_decoders(&self) -> Result<HashMap<String, CallTraceDecoder>> {
414        let rpcs = &self.execution_artifacts.rpc_data.total_rpcs;
415        // Decoder construction resolves the same endpoint context as a simulation runner.
416        let mut decoders = HashMap::default();
417        for rpc in rpcs.iter().cloned() {
418            let (rpc, decoder) = build_rpc_decoder(
419                rpc,
420                &self.args,
421                &self.script_config,
422                &self.build_data.known_contracts,
423                &self.build_data.sources,
424                &self.execution_result,
425            )
426            .await?;
427            decoders.insert(rpc, decoder);
428        }
429        Ok(decoders)
430    }
431}
432
433#[cfg(all(test, feature = "monad"))]
434mod tests {
435    use super::*;
436    use alloy_primitives::address;
437    use anvil::{NodeConfig, spawn};
438    use foundry_cli::opts::TempoOpts;
439    use foundry_config::Config;
440    use foundry_evm::{
441        core::{evm::MonadEvmNetwork, opts::EvmOpts},
442        executors::ExecutorBuilder,
443        hardforks::MonadHardfork,
444    };
445    use foundry_evm_networks::NetworkConfigs;
446
447    const RESERVE_BALANCE_ADDRESS: Address = address!("0000000000000000000000000000000000001001");
448
449    #[tokio::test(flavor = "multi_thread")]
450    async fn multi_rpc_fork_selects_trace_decoder_for_source_hardfork() {
451        let (monad_eight_api, monad_eight) = spawn(
452            NodeConfig::test_monad()
453                .with_chain_id(Some(NamedChain::Monad as u64))
454                .with_hardfork(Some(MonadHardfork::MonadEight.into())),
455        )
456        .await;
457        let (monad_nine_api, monad_nine) = spawn(
458            NodeConfig::test_monad()
459                .with_chain_id(Some(NamedChain::Monad as u64))
460                .with_hardfork(Some(MonadHardfork::MonadNine.into())),
461        )
462        .await;
463        monad_eight_api.mine_one().await.unwrap();
464        monad_nine_api.mine_one().await.unwrap();
465        let monad_eight_rpc = monad_eight.http_endpoint();
466        let monad_nine_rpc = monad_nine.http_endpoint();
467
468        let mut evm_opts = EvmOpts {
469            fork_url: Some(monad_eight_rpc.clone()),
470            fork_block_number: Some(0),
471            networks: NetworkConfigs::with_monad(),
472            ..Default::default()
473        };
474        evm_opts.env.chain_id = Some(42);
475        let script_config = ScriptConfig::<MonadEvmNetwork>::new(
476            Config::default(),
477            evm_opts,
478            ExecutorBuilder::<MonadEvmNetwork>::new(),
479            false,
480            TempoOpts::default(),
481            Some(0),
482        )
483        .await
484        .unwrap();
485        let args = ScriptArgs::default();
486        let known_contracts = ContractsByArtifact::default();
487        let sources = ContractSources::default();
488        let execution_result = ScriptResult::default();
489        let contexts = [
490            build_rpc_simulation_context(
491                monad_eight_rpc.clone(),
492                &args,
493                &script_config,
494                &known_contracts,
495                &sources,
496                &execution_result,
497            )
498            .await
499            .unwrap(),
500            build_rpc_simulation_context(
501                monad_nine_rpc.clone(),
502                &args,
503                &script_config,
504                &known_contracts,
505                &sources,
506                &execution_result,
507            )
508            .await
509            .unwrap(),
510        ]
511        .into_iter()
512        .collect::<HashMap<_, _>>();
513
514        let monad_eight = contexts.get(&monad_eight_rpc).unwrap();
515        let monad_eight_runner = &monad_eight.runner;
516        assert_eq!(monad_eight_runner.executor.evm_env().chain_id(), 42);
517        assert_eq!(monad_eight_runner.executor.evm_env().block.number, U256::ZERO);
518        assert_eq!(monad_eight_runner.evm_opts.fork_block_number, Some(0));
519        assert!(!monad_eight_runner.evm_opts.fork_block_number_is_inferred);
520        assert_eq!(monad_eight_runner.evm_opts.networks, NetworkConfigs::with_monad());
521        assert!(!monad_eight_runner.evm_opts.fork_network_is_inferred);
522        assert_eq!(monad_eight.decoder.chain_id, Some(NamedChain::Monad as u64));
523        assert_eq!(monad_eight.decoder.hardfork(), Some(MonadHardfork::MonadEight.into()));
524        assert!(!monad_eight.decoder.precompile_labels().contains_key(&RESERVE_BALANCE_ADDRESS));
525
526        let monad_nine = contexts.get(&monad_nine_rpc).unwrap();
527        let monad_nine_runner = &monad_nine.runner;
528        assert_eq!(monad_nine_runner.executor.evm_env().chain_id(), 42);
529        assert_eq!(monad_nine_runner.executor.evm_env().block.number, U256::ZERO);
530        assert_eq!(monad_nine_runner.evm_opts.fork_block_number, Some(0));
531        assert!(!monad_nine_runner.evm_opts.fork_block_number_is_inferred);
532        assert_eq!(monad_nine_runner.evm_opts.networks, NetworkConfigs::with_monad());
533        assert!(!monad_nine_runner.evm_opts.fork_network_is_inferred);
534        assert_eq!(monad_nine.decoder.chain_id, Some(NamedChain::Monad as u64));
535        assert_eq!(monad_nine.decoder.hardfork(), Some(MonadHardfork::MonadNine.into()));
536        assert_eq!(
537            monad_nine.decoder.precompile_labels().get(&RESERVE_BALANCE_ADDRESS),
538            Some(&"ReserveBalance".to_string())
539        );
540    }
541
542    #[tokio::test(flavor = "multi_thread")]
543    async fn skip_simulation_fork_builds_per_rpc_trace_decoders() {
544        let (monad_eight_api, monad_eight) = spawn(
545            NodeConfig::test_monad()
546                .with_chain_id(Some(NamedChain::Monad as u64))
547                .with_hardfork(Some(MonadHardfork::MonadEight.into())),
548        )
549        .await;
550        let (monad_nine_api, monad_nine) = spawn(
551            NodeConfig::test_monad()
552                .with_chain_id(Some(NamedChain::Monad as u64))
553                .with_hardfork(Some(MonadHardfork::MonadNine.into())),
554        )
555        .await;
556        monad_eight_api.mine_one().await.unwrap();
557        monad_nine_api.mine_one().await.unwrap();
558        let monad_eight_rpc = monad_eight.http_endpoint();
559        let monad_nine_rpc = monad_nine.http_endpoint();
560
561        let script_config = ScriptConfig::<MonadEvmNetwork>::new(
562            Config::default(),
563            EvmOpts {
564                fork_url: Some(monad_eight_rpc.clone()),
565                fork_block_number: Some(0),
566                networks: NetworkConfigs::with_monad(),
567                ..Default::default()
568            },
569            ExecutorBuilder::<MonadEvmNetwork>::new(),
570            false,
571            TempoOpts::default(),
572            Some(0),
573        )
574        .await
575        .unwrap();
576        let args = ScriptArgs { skip_simulation: true, ..Default::default() };
577        let known_contracts = ContractsByArtifact::default();
578        let sources = ContractSources::default();
579        let execution_result = ScriptResult::default();
580        let decoders = [
581            build_rpc_decoder(
582                monad_eight_rpc.clone(),
583                &args,
584                &script_config,
585                &known_contracts,
586                &sources,
587                &execution_result,
588            )
589            .await
590            .unwrap(),
591            build_rpc_decoder(
592                monad_nine_rpc.clone(),
593                &args,
594                &script_config,
595                &known_contracts,
596                &sources,
597                &execution_result,
598            )
599            .await
600            .unwrap(),
601        ]
602        .into_iter()
603        .collect::<HashMap<_, _>>();
604
605        let monad_eight = decoders.get(&monad_eight_rpc).unwrap();
606        assert_eq!(monad_eight.hardfork(), Some(MonadHardfork::MonadEight.into()));
607        assert!(!monad_eight.precompile_labels().contains_key(&RESERVE_BALANCE_ADDRESS));
608
609        let monad_nine = decoders.get(&monad_nine_rpc).unwrap();
610        assert_eq!(monad_nine.hardfork(), Some(MonadHardfork::MonadNine.into()));
611        assert_eq!(
612            monad_nine.precompile_labels().get(&RESERVE_BALANCE_ADDRESS),
613            Some(&"ReserveBalance".to_string())
614        );
615    }
616
617    #[tokio::test(flavor = "multi_thread")]
618    async fn multi_rpc_fork_rejects_inferred_network_change() {
619        let (_monad_api, monad) = spawn(NodeConfig::test_monad()).await;
620        let (_ethereum_api, ethereum) = spawn(NodeConfig::test()).await;
621        let ethereum_rpc = ethereum.http_endpoint();
622        let script_config = ScriptConfig::<MonadEvmNetwork>::new(
623            Config::default(),
624            EvmOpts { fork_url: Some(monad.http_endpoint()), ..Default::default() },
625            ExecutorBuilder::<MonadEvmNetwork>::new(),
626            false,
627            TempoOpts::default(),
628            Some(0),
629        )
630        .await
631        .unwrap();
632        assert!(script_config.evm_opts.fork_network_is_inferred);
633
634        let result = build_rpc_simulation_context(
635            ethereum_rpc.clone(),
636            &ScriptArgs::default(),
637            &script_config,
638            &ContractsByArtifact::default(),
639            &ContractSources::default(),
640            &ScriptResult::default(),
641        )
642        .await;
643        let Err(error) = result else { panic!("inferred cross-network fork should be rejected") };
644        assert!(
645            error
646                .to_string()
647                .contains("fork network `ethereum` is incompatible with the active EVM"),
648            "{error}"
649        );
650
651        let result = build_rpc_decoder(
652            ethereum_rpc,
653            &ScriptArgs { skip_simulation: true, ..Default::default() },
654            &script_config,
655            &ContractsByArtifact::default(),
656            &ContractSources::default(),
657            &ScriptResult::default(),
658        )
659        .await;
660        let Err(error) = result else {
661            panic!("skip-simulation decoder should reject an inferred cross-network fork")
662        };
663        assert!(
664            error
665                .to_string()
666                .contains("fork network `ethereum` is incompatible with the active EVM"),
667            "{error}"
668        );
669    }
670}
671
672/// At this point we have converted transactions collected during script execution to
673/// [TransactionWithMetadata] objects which contain additional metadata needed for broadcasting and
674/// verification.
675pub struct FilledTransactionsState<FEN: FoundryEvmNetwork> {
676    pub args: ScriptArgs,
677    pub script_config: ScriptConfig<FEN>,
678    pub script_wallets: Wallets,
679    pub browser_wallet: Option<BrowserSigner<FEN::Network>>,
680    pub build_data: LinkedBuildData,
681    pub execution_artifacts: ExecutionArtifacts,
682    pub transactions: VecDeque<TransactionWithMetadata<FEN::Network>>,
683}
684
685impl<FEN: FoundryEvmNetwork> FilledTransactionsState<FEN> {
686    /// Bundles all transactions of the [`TransactionWithMetadata`] type in a list of
687    /// [`ScriptSequence`]. List length will be higher than 1, if we're dealing with a multi
688    /// chain deployment.
689    ///
690    /// Each transaction will be added with the correct transaction type and gas estimation.
691    pub async fn bundle(mut self) -> Result<BundledState<FEN>> {
692        let is_multi_deployment = self.execution_artifacts.rpc_data.total_rpcs.len() > 1;
693
694        if is_multi_deployment && !self.build_data.libraries.is_empty() {
695            eyre::bail!("Multi-chain deployment is not supported with libraries.");
696        }
697
698        let mut total_gas_per_rpc: HashMap<String, u128> = HashMap::default();
699
700        // Batches sequence of transactions from different rpcs.
701        let mut new_sequence = VecDeque::new();
702        let mut manager = ProvidersManager::<FEN::Network>::default();
703        let mut sequences = vec![];
704
705        // Peeking is used to check if the next rpc url is different. If so, it creates a
706        // [`ScriptSequence`] from all the collected transactions up to this point.
707        let mut txes_iter = mem::take(&mut self.transactions).into_iter().peekable();
708
709        while let Some(mut tx) = txes_iter.next() {
710            let tx_rpc = tx.rpc.clone();
711            let provider_info = manager
712                .get_or_init_provider(
713                    &tx.rpc,
714                    self.execution_artifacts.rpc_data.chain_ids.get(&tx.rpc).copied(),
715                    self.args.legacy,
716                    self.script_config.config.eip1559_fee_estimate,
717                    &self.script_config.config,
718                )
719                .await?;
720
721            if let Some(tx) = tx.tx_mut().as_unsigned_mut() {
722                // Handles chain specific requirements for unsigned transactions.
723                tx.set_chain_id(provider_info.chain);
724            }
725
726            if !self.args.skip_simulation {
727                let is_fixed_gas_limit = tx.is_fixed_gas_limit;
728                let tx = tx.tx_mut();
729
730                if !is_fixed_gas_limit
731                    && (has_different_gas_calc(provider_info.chain)
732                        || self.script_config.evm_opts.networks.is_tempo())
733                {
734                    // only estimate gas for unsigned transactions
735                    if let Some(tx) = tx.as_unsigned_mut() {
736                        trace!("estimating with different gas calculation");
737                        let gas = tx.gas_limit().expect("gas is set by simulation.");
738
739                        // We are trying to show the user an estimation of the total gas usage.
740                        //
741                        // However, some transactions might depend on previous ones. For
742                        // example, tx1 might deploy a contract that tx2 uses. That
743                        // will result in the following `estimate_gas` call to fail,
744                        // since tx1 hasn't been broadcasted yet.
745                        //
746                        // Not exiting here will not be a problem when actually broadcasting,
747                        // because for chains where `has_different_gas_calc`
748                        // returns true, we await each transaction before
749                        // broadcasting the next one.
750                        if let Err(err) = estimate_gas(
751                            tx,
752                            &provider_info.provider,
753                            self.args.gas_estimate_multiplier,
754                            false,
755                            self.script_config.tempo.is_sponsored(),
756                        )
757                        .await
758                        {
759                            trace!("gas estimation failed: {err}");
760
761                            // Restore gas value, since `estimate_gas` will remove it.
762                            tx.set_gas_limit(gas);
763                        }
764                    }
765                }
766
767                let total_gas = total_gas_per_rpc.entry(tx_rpc.clone()).or_insert(0);
768                *total_gas += tx.gas().expect("gas is set");
769            }
770
771            new_sequence.push_back(tx);
772            // We only create a [`ScriptSequence`] object when we collect all the rpc related
773            // transactions.
774            if let Some(next_tx) = txes_iter.peek()
775                && next_tx.rpc == tx_rpc
776            {
777                continue;
778            }
779
780            let sequence =
781                self.create_sequence(is_multi_deployment, provider_info.chain, new_sequence)?;
782
783            sequences.push(sequence);
784
785            new_sequence = VecDeque::new();
786        }
787
788        if !self.args.skip_simulation {
789            // Present gas information on a per RPC basis.
790            for (rpc, total_gas) in total_gas_per_rpc {
791                let provider_info = manager.get(&rpc).expect("provider is set.");
792
793                self.print_gas_estimate(provider_info, total_gas).await?;
794            }
795        }
796
797        let data = if sequences.len() == 1 {
798            SequenceData::Single(Box::new(sequences.pop().expect("empty sequences")))
799        } else {
800            SequenceData::Multi(MultiChainSequence::new(
801                sequences,
802                &self.args.sig,
803                &self.build_data.build_data.target,
804                &self.script_config.config,
805                !self.args.broadcast,
806            )?)
807        };
808        if self.args.start_fresh {
809            RecoveryStore::<FEN::Network>::archive_unfinished(&data)?;
810        }
811        let sequence =
812            ScriptSequenceKind::create(data, self.args.batch, self.script_config.tempo.sponsor)?;
813
814        Ok(BundledState {
815            args: self.args,
816            script_config: self.script_config,
817            script_wallets: self.script_wallets,
818            browser_wallet: self.browser_wallet,
819            build_data: self.build_data,
820            sequence,
821            resume_script_error: None,
822        })
823    }
824
825    /// Creates a [ScriptSequence] object from the given transactions.
826    fn create_sequence(
827        &self,
828        multi: bool,
829        chain: u64,
830        transactions: VecDeque<TransactionWithMetadata<FEN::Network>>,
831    ) -> Result<ScriptSequence<FEN::Network>> {
832        // Paths are set to None for multi-chain sequences parts, because they don't need to be
833        // saved to a separate file.
834        let paths = if multi {
835            None
836        } else {
837            Some(ScriptSequence::<FEN::Network>::get_paths(
838                &self.script_config.config,
839                &self.args.sig,
840                &self.build_data.build_data.target,
841                chain,
842                !self.args.broadcast,
843            )?)
844        };
845
846        let commit = get_commit_hash(&self.script_config.config.root);
847
848        let local_addresses = match &self.build_data.predeploy_libraries {
849            crate::build::ScriptPredeployLibraries::Default { local, .. }
850            | crate::build::ScriptPredeployLibraries::Create2 { local, .. } => local.as_slice(),
851        };
852        let local_addresses = local_addresses
853            .iter()
854            .map(|library| library.address.to_checksum(None))
855            .collect::<Vec<_>>();
856        let libraries = self
857            .build_data
858            .libraries
859            .libs
860            .iter()
861            .flat_map(|(file, libs)| {
862                libs.iter()
863                    .filter(|(_, address)| !local_addresses.contains(address))
864                    .map(|(name, address)| format!("{}:{name}:{address}", file.to_string_lossy()))
865            })
866            .collect();
867
868        let sequence = ScriptSequence {
869            transactions,
870            returns: self.execution_artifacts.returns.clone(),
871            receipts: vec![],
872            pending: vec![],
873            paths,
874            timestamp: now().as_millis(),
875            libraries,
876            chain,
877            commit,
878            recovery_generation: None,
879            reverted: vec![],
880            awaiting_owners: vec![],
881        };
882        Ok(sequence)
883    }
884
885    /// Prints a gas estimate without changing the fees used for broadcasting.
886    async fn print_gas_estimate(
887        &self,
888        provider_info: &ProviderInfo<FEN::Network>,
889        total_gas: u128,
890    ) -> Result<()> {
891        let token_symbol = if self.script_config.evm_opts.networks.is_tempo() {
892            self.args.tempo.fee_token.map_or_else(
893                || "TIP-20".to_string(),
894                |fee_token| {
895                    known_fee_token_symbol(fee_token)
896                        .map(str::to_string)
897                        .unwrap_or_else(|| fee_token.to_string())
898                },
899            )
900        } else {
901            NamedChain::try_from(provider_info.chain)
902                .unwrap_or_default()
903                .native_currency_symbol()
904                .unwrap_or("ETH")
905                .to_string()
906        };
907
908        // We don't store it in the transactions, since we want the most updated value.
909        // Right before broadcasting.
910        //
911        // Resolve the fees with the same overrides as the broadcast path so the
912        // displayed values match what is sent. Skipped when `--with-gas-price` pins
913        // the max fee directly.
914        let resolved_eip1559_fees = if self.args.with_gas_price.is_none() {
915            if let Some(fees) = provider_info.eip1559_fees().copied() {
916                // `--batch` broadcasts via `broadcast_batch`, which applies no
917                // browser tip, so skip it here too. Best-effort.
918                let browser_suggested_tip = if !self.args.batch && self.browser_wallet.is_some() {
919                    provider_info.provider.get_max_priority_fee_per_gas().await.ok()
920                } else {
921                    None
922                };
923                Some(resolve_broadcast_eip1559_fees(
924                    fees,
925                    None,
926                    self.args.priority_gas_price.map(|p| p.to()),
927                    browser_suggested_tip,
928                )?)
929            } else {
930                None
931            }
932        } else {
933            None
934        };
935
936        // `per_gas` is the legacy gas price or, for EIP-1559, the `maxFeePerGas`
937        // (a base-fee buffer plus the priority fee), which is what the transaction
938        // can pay at most -- not the spot base fee shown by block explorers.
939        let per_gas = if let Some(gas_price) = self.args.with_gas_price {
940            gas_price.to()
941        } else if let Some(fees) = &resolved_eip1559_fees {
942            fees.max_fee_per_gas
943        } else {
944            provider_info.gas_price()?
945        };
946
947        // Format a wei value as a trimmed gwei string.
948        let fmt_gwei = |wei: u128| {
949            let raw = format_units(wei, 9).unwrap_or_else(|_| "[Could not calculate]".to_string());
950            raw.trim_end_matches('0').trim_end_matches('.').to_string()
951        };
952
953        let estimated_gas_price = fmt_gwei(per_gas);
954
955        // (base fee, max priority fee) for the EIP-1559 breakdown.
956        let fee_breakdown = resolved_eip1559_fees
957            .map(|fees| (fmt_gwei(fees.base_fee_per_gas), fmt_gwei(fees.max_priority_fee_per_gas)));
958
959        let estimated_amount_raw = format_units(total_gas.saturating_mul(per_gas), 18)
960            .unwrap_or_else(|_| "[Could not calculate]".to_string());
961        let estimated_amount = estimated_amount_raw.trim_end_matches('0');
962
963        if shell::is_json() {
964            let mut json = serde_json::json!({
965                "chain": provider_info.chain,
966                "estimated_gas_price": estimated_gas_price,
967                "estimated_total_gas_used": total_gas,
968                "estimated_amount_required": estimated_amount,
969                "token_symbol": token_symbol,
970            });
971            if let Some((base_fee, priority_fee)) = &fee_breakdown {
972                json["estimated_max_fee_per_gas"] = serde_json::Value::from(estimated_gas_price);
973                json["estimated_base_fee_per_gas"] = serde_json::Value::from(base_fee.clone());
974                json["estimated_max_priority_fee_per_gas"] =
975                    serde_json::Value::from(priority_fee.clone());
976            }
977            sh_println!("{}", json)?;
978        } else {
979            sh_println!("\n==========================")?;
980            sh_println!("\nChain {}", provider_info.chain)?;
981
982            if let Some((base_fee, priority_fee)) = &fee_breakdown {
983                sh_println!("\nEstimated max fee per gas: {estimated_gas_price} gwei")?;
984                sh_println!("Estimated base fee per gas: {base_fee} gwei")?;
985                sh_println!("Estimated max priority fee per gas: {priority_fee} gwei")?;
986            } else {
987                sh_println!("\nEstimated gas price: {estimated_gas_price} gwei")?;
988            }
989            sh_println!("\nEstimated total gas used for script: {total_gas}")?;
990            sh_println!("\nEstimated amount required: {estimated_amount} {token_symbol}")?;
991            sh_println!("\n==========================")?;
992        }
993        Ok(())
994    }
995}