cast/cmd/
run.rs

1use crate::{debug::handle_traces, utils::apply_chain_and_block_specific_env_changes};
2use alloy_consensus::Transaction;
3use alloy_network::{AnyNetwork, TransactionResponse};
4use alloy_primitives::{
5    Address, Bytes, U256,
6    map::{AddressSet, HashMap},
7};
8use alloy_provider::Provider;
9use alloy_rpc_types::BlockTransactions;
10use clap::Parser;
11use eyre::{Result, WrapErr};
12use foundry_cli::{
13    opts::{EtherscanOpts, RpcOpts},
14    utils::{TraceResult, init_progress},
15};
16use foundry_common::{SYSTEM_TRANSACTION_TYPE, is_impersonated_tx, is_known_system_sender, shell};
17use foundry_compilers::artifacts::EvmVersion;
18use foundry_config::{
19    Config,
20    figment::{
21        self, Metadata, Profile,
22        value::{Dict, Map},
23    },
24};
25use foundry_evm::{
26    Env,
27    core::env::AsEnvMut,
28    executors::{EvmError, Executor, TracingExecutor},
29    opts::EvmOpts,
30    traces::{InternalTraceMode, TraceMode, Traces},
31    utils::configure_tx_env,
32};
33use futures::TryFutureExt;
34use revm::DatabaseRef;
35
36/// CLI arguments for `cast run`.
37#[derive(Clone, Debug, Parser)]
38pub struct RunArgs {
39    /// The transaction hash.
40    tx_hash: String,
41
42    /// Opens the transaction in the debugger.
43    #[arg(long, short)]
44    debug: bool,
45
46    /// Whether to identify internal functions in traces.
47    #[arg(long)]
48    decode_internal: bool,
49
50    /// Print out opcode traces.
51    #[arg(long, short)]
52    trace_printer: bool,
53
54    /// Executes the transaction only with the state from the previous block.
55    ///
56    /// May result in different results than the live execution!
57    #[arg(long)]
58    quick: bool,
59
60    /// Disables the labels in the traces.
61    #[arg(long, default_value_t = false)]
62    disable_labels: bool,
63
64    /// Label addresses in the trace.
65    ///
66    /// Example: 0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045:vitalik.eth
67    #[arg(long, short)]
68    label: Vec<String>,
69
70    #[command(flatten)]
71    etherscan: EtherscanOpts,
72
73    #[command(flatten)]
74    rpc: RpcOpts,
75
76    /// The EVM version to use.
77    ///
78    /// Overrides the version specified in the config.
79    #[arg(long)]
80    evm_version: Option<EvmVersion>,
81
82    /// Sets the number of assumed available compute units per second for this provider
83    ///
84    /// default value: 330
85    ///
86    /// See also, <https://docs.alchemy.com/reference/compute-units#what-are-cups-compute-units-per-second>
87    #[arg(long, alias = "cups", value_name = "CUPS")]
88    pub compute_units_per_second: Option<u64>,
89
90    /// Disables rate limiting for this node's provider.
91    ///
92    /// default value: false
93    ///
94    /// See also, <https://docs.alchemy.com/reference/compute-units#what-are-cups-compute-units-per-second>
95    #[arg(long, value_name = "NO_RATE_LIMITS", visible_alias = "no-rpc-rate-limit")]
96    pub no_rate_limit: bool,
97
98    /// Use current project artifacts for trace decoding.
99    #[arg(long, visible_alias = "la")]
100    pub with_local_artifacts: bool,
101
102    /// Disable block gas limit check.
103    #[arg(long)]
104    pub disable_block_gas_limit: bool,
105
106    /// Enable the tx gas limit checks as imposed by Osaka (EIP-7825).
107    #[arg(long)]
108    pub enable_tx_gas_limit: bool,
109}
110
111impl RunArgs {
112    /// Executes the transaction by replaying it
113    ///
114    /// This replays the entire block the transaction was mined in unless `quick` is set to true
115    ///
116    /// Note: This executes the transaction(s) as is: Cheatcodes are disabled
117    pub async fn run(self) -> Result<()> {
118        let figment = self.rpc.clone().into_figment(self.with_local_artifacts).merge(&self);
119        let evm_opts = figment.extract::<EvmOpts>()?;
120        let mut config = Config::from_provider(figment)?.sanitized();
121
122        let label = self.label;
123        let with_local_artifacts = self.with_local_artifacts;
124        let debug = self.debug;
125        let decode_internal = self.decode_internal;
126        let disable_labels = self.disable_labels;
127        let compute_units_per_second =
128            if self.no_rate_limit { Some(u64::MAX) } else { self.compute_units_per_second };
129
130        let provider = foundry_cli::utils::get_provider_builder(&config)?
131            .compute_units_per_second_opt(compute_units_per_second)
132            .build()?;
133
134        let tx_hash = self.tx_hash.parse().wrap_err("invalid tx hash")?;
135        let tx = provider
136            .get_transaction_by_hash(tx_hash)
137            .await
138            .wrap_err_with(|| format!("tx not found: {tx_hash:?}"))?
139            .ok_or_else(|| eyre::eyre!("tx not found: {:?}", tx_hash))?;
140
141        // check if the tx is a system transaction
142        if is_known_system_sender(tx.from())
143            || tx.transaction_type() == Some(SYSTEM_TRANSACTION_TYPE)
144        {
145            return Err(eyre::eyre!(
146                "{:?} is a system transaction.\nReplaying system transactions is currently not supported.",
147                tx.tx_hash()
148            ));
149        }
150
151        let tx_block_number =
152            tx.block_number.ok_or_else(|| eyre::eyre!("tx may still be pending: {:?}", tx_hash))?;
153
154        // we need to fork off the parent block
155        config.fork_block_number = Some(tx_block_number - 1);
156
157        let create2_deployer = evm_opts.create2_deployer;
158        let (block, (mut env, fork, chain, networks)) = tokio::try_join!(
159            // fetch the block the transaction was mined in
160            provider.get_block(tx_block_number.into()).full().into_future().map_err(Into::into),
161            TracingExecutor::get_fork_material(&mut config, evm_opts)
162        )?;
163
164        let mut evm_version = self.evm_version;
165
166        env.evm_env.cfg_env.disable_block_gas_limit = self.disable_block_gas_limit;
167
168        // By default do not enforce transaction gas limits imposed by Osaka (EIP-7825).
169        // Users can opt-in to enable these limits by setting `enable_tx_gas_limit` to true.
170        if !self.enable_tx_gas_limit {
171            env.evm_env.cfg_env.tx_gas_limit_cap = Some(u64::MAX);
172        }
173
174        env.evm_env.cfg_env.limit_contract_code_size = None;
175        env.evm_env.block_env.number = U256::from(tx_block_number);
176
177        if let Some(block) = &block {
178            env.evm_env.block_env.timestamp = U256::from(block.header.timestamp);
179            env.evm_env.block_env.beneficiary = block.header.beneficiary;
180            env.evm_env.block_env.difficulty = block.header.difficulty;
181            env.evm_env.block_env.prevrandao = Some(block.header.mix_hash.unwrap_or_default());
182            env.evm_env.block_env.basefee = block.header.base_fee_per_gas.unwrap_or_default();
183            env.evm_env.block_env.gas_limit = block.header.gas_limit;
184
185            // TODO: we need a smarter way to map the block to the corresponding evm_version for
186            // commonly used chains
187            if evm_version.is_none() {
188                // if the block has the excess_blob_gas field, we assume it's a Cancun block
189                if block.header.excess_blob_gas.is_some() {
190                    evm_version = Some(EvmVersion::Prague);
191                }
192            }
193            apply_chain_and_block_specific_env_changes::<AnyNetwork>(
194                env.as_env_mut(),
195                block,
196                config.networks,
197            );
198        }
199
200        let trace_mode = TraceMode::Call
201            .with_debug(self.debug)
202            .with_decode_internal(if self.decode_internal {
203                InternalTraceMode::Full
204            } else {
205                InternalTraceMode::None
206            })
207            .with_state_changes(shell::verbosity() > 4);
208        let mut executor = TracingExecutor::new(
209            env.clone(),
210            fork,
211            evm_version,
212            trace_mode,
213            networks,
214            create2_deployer,
215            None,
216        )?;
217        let mut env = Env::new_with_spec_id(
218            env.evm_env.cfg_env.clone(),
219            env.evm_env.block_env.clone(),
220            env.tx.clone(),
221            executor.spec_id(),
222        );
223
224        // Set the state to the moment right before the transaction
225        if !self.quick {
226            if !shell::is_json() {
227                sh_println!("Executing previous transactions from the block.")?;
228            }
229
230            if let Some(block) = block {
231                let pb = init_progress(block.transactions.len() as u64, "tx");
232                pb.set_position(0);
233
234                let BlockTransactions::Full(ref txs) = block.transactions else {
235                    return Err(eyre::eyre!("Could not get block txs"));
236                };
237
238                for (index, tx) in txs.iter().enumerate() {
239                    // System transactions such as on L2s don't contain any pricing info so
240                    // we skip them otherwise this would cause
241                    // reverts
242                    if is_known_system_sender(tx.from())
243                        || tx.transaction_type() == Some(SYSTEM_TRANSACTION_TYPE)
244                    {
245                        pb.set_position((index + 1) as u64);
246                        continue;
247                    }
248                    if tx.tx_hash() == tx_hash {
249                        break;
250                    }
251
252                    configure_tx_env(&mut env.as_env_mut(), &tx.inner);
253
254                    env.evm_env.cfg_env.disable_balance_check = true;
255
256                    if let Some(to) = Transaction::to(tx) {
257                        trace!(tx=?tx.tx_hash(),?to, "executing previous call transaction");
258                        executor.transact_with_env(env.clone()).wrap_err_with(|| {
259                            format!(
260                                "Failed to execute transaction: {:?} in block {}",
261                                tx.tx_hash(),
262                                env.evm_env.block_env.number
263                            )
264                        })?;
265                    } else {
266                        trace!(tx=?tx.tx_hash(), "executing previous create transaction");
267                        if let Err(error) = executor.deploy_with_env(env.clone(), None) {
268                            match error {
269                                // Reverted transactions should be skipped
270                                EvmError::Execution(_) => (),
271                                error => {
272                                    return Err(error).wrap_err_with(|| {
273                                        format!(
274                                            "Failed to deploy transaction: {:?} in block {}",
275                                            tx.tx_hash(),
276                                            env.evm_env.block_env.number
277                                        )
278                                    });
279                                }
280                            }
281                        }
282                    }
283
284                    pb.set_position((index + 1) as u64);
285                }
286            }
287        }
288
289        // Execute our transaction
290        let result = {
291            executor.set_trace_printer(self.trace_printer);
292
293            configure_tx_env(&mut env.as_env_mut(), &tx.inner);
294            if is_impersonated_tx(tx.inner.inner.inner()) {
295                env.evm_env.cfg_env.disable_balance_check = true;
296            }
297
298            if let Some(to) = Transaction::to(&tx) {
299                trace!(tx=?tx.tx_hash(), to=?to, "executing call transaction");
300                TraceResult::try_from(executor.transact_with_env(env))?
301            } else {
302                trace!(tx=?tx.tx_hash(), "executing create transaction");
303                TraceResult::try_from(executor.deploy_with_env(env, None))?
304            }
305        };
306
307        let contracts_bytecode = fetch_contracts_bytecode_from_trace(&executor, &result)?;
308        handle_traces(
309            result,
310            &config,
311            chain,
312            &contracts_bytecode,
313            label,
314            with_local_artifacts,
315            debug,
316            decode_internal,
317            disable_labels,
318        )
319        .await?;
320
321        Ok(())
322    }
323}
324
325pub fn fetch_contracts_bytecode_from_trace(
326    executor: &Executor,
327    result: &TraceResult,
328) -> Result<HashMap<Address, Bytes>> {
329    let mut contracts_bytecode = HashMap::default();
330    if let Some(ref traces) = result.traces {
331        contracts_bytecode.extend(gather_trace_addresses(traces).filter_map(|addr| {
332            // All relevant bytecodes should already be cached in the executor.
333            let code = executor
334                .backend()
335                .basic_ref(addr)
336                .inspect_err(|e| _ = sh_warn!("Failed to fetch code for {addr}: {e}"))
337                .ok()??
338                .code?
339                .bytes();
340            if code.is_empty() {
341                return None;
342            }
343            Some((addr, code))
344        }));
345    }
346    Ok(contracts_bytecode)
347}
348
349fn gather_trace_addresses(traces: &Traces) -> impl Iterator<Item = Address> {
350    let mut addresses = AddressSet::default();
351    for (_, trace) in traces {
352        for node in trace.arena.nodes() {
353            if !node.trace.address.is_zero() {
354                addresses.insert(node.trace.address);
355            }
356            if !node.trace.caller.is_zero() {
357                addresses.insert(node.trace.caller);
358            }
359        }
360    }
361    addresses.into_iter()
362}
363
364impl figment::Provider for RunArgs {
365    fn metadata(&self) -> Metadata {
366        Metadata::named("RunArgs")
367    }
368
369    fn data(&self) -> Result<Map<Profile, Dict>, figment::Error> {
370        let mut map = Map::new();
371
372        if let Some(api_key) = &self.etherscan.key {
373            map.insert("etherscan_api_key".into(), api_key.as_str().into());
374        }
375
376        if let Some(evm_version) = self.evm_version {
377            map.insert("evm_version".into(), figment::value::Value::serialize(evm_version)?);
378        }
379
380        Ok(Map::from([(Config::selected_profile(), map)]))
381    }
382}