1use alloy_consensus::Transaction;
2use alloy_network::{AnyNetwork, TransactionResponse};
3use alloy_primitives::{
4 Address, Bytes, U256,
5 map::{HashMap, HashSet},
6};
7use alloy_provider::{Provider, RootProvider};
8use alloy_rpc_types::BlockTransactions;
9use clap::Parser;
10use eyre::{Result, WrapErr};
11use foundry_cli::{
12 opts::{EtherscanOpts, RpcOpts},
13 utils::{TraceResult, handle_traces, init_progress},
14};
15use foundry_common::{SYSTEM_TRANSACTION_TYPE, is_impersonated_tx, is_known_system_sender, shell};
16use foundry_compilers::artifacts::EvmVersion;
17use foundry_config::{
18 Config,
19 figment::{
20 self, Figment, Metadata, Profile,
21 value::{Dict, Map},
22 },
23};
24use foundry_evm::{
25 Env,
26 executors::{EvmError, TracingExecutor},
27 opts::EvmOpts,
28 traces::{InternalTraceMode, TraceMode, Traces},
29 utils::configure_tx_env,
30};
31use foundry_evm_core::env::AsEnvMut;
32
33use crate::utils::apply_chain_and_block_specific_env_changes;
34
35#[derive(Clone, Debug, Parser)]
37pub struct RunArgs {
38 tx_hash: String,
40
41 #[arg(long, short)]
43 debug: bool,
44
45 #[arg(long)]
47 decode_internal: bool,
48
49 #[arg(long, short)]
51 trace_printer: bool,
52
53 #[arg(long)]
57 quick: bool,
58
59 #[arg(long, default_value_t = false)]
61 disable_labels: bool,
62
63 #[arg(long, short)]
67 label: Vec<String>,
68
69 #[command(flatten)]
70 etherscan: EtherscanOpts,
71
72 #[command(flatten)]
73 rpc: RpcOpts,
74
75 #[arg(long)]
79 evm_version: Option<EvmVersion>,
80
81 #[arg(long, alias = "cups", value_name = "CUPS")]
87 pub compute_units_per_second: Option<u64>,
88
89 #[arg(long, value_name = "NO_RATE_LIMITS", visible_alias = "no-rpc-rate-limit")]
95 pub no_rate_limit: bool,
96
97 #[arg(long, alias = "alphanet")]
99 pub odyssey: bool,
100
101 #[arg(long, visible_alias = "la")]
103 pub with_local_artifacts: bool,
104
105 #[arg(long)]
107 pub disable_block_gas_limit: bool,
108}
109
110impl RunArgs {
111 pub async fn run(self) -> Result<()> {
117 let figment = Into::<Figment>::into(&self.rpc).merge(&self);
118 let evm_opts = figment.extract::<EvmOpts>()?;
119 let mut config = Config::from_provider(figment)?.sanitized();
120
121 let compute_units_per_second =
122 if self.no_rate_limit { Some(u64::MAX) } else { self.compute_units_per_second };
123
124 let provider = foundry_cli::utils::get_provider_builder(&config)?
125 .compute_units_per_second_opt(compute_units_per_second)
126 .build()?;
127
128 let tx_hash = self.tx_hash.parse().wrap_err("invalid tx hash")?;
129 let tx = provider
130 .get_transaction_by_hash(tx_hash)
131 .await
132 .wrap_err_with(|| format!("tx not found: {tx_hash:?}"))?
133 .ok_or_else(|| eyre::eyre!("tx not found: {:?}", tx_hash))?;
134
135 if is_known_system_sender(tx.from())
137 || tx.transaction_type() == Some(SYSTEM_TRANSACTION_TYPE)
138 {
139 return Err(eyre::eyre!(
140 "{:?} is a system transaction.\nReplaying system transactions is currently not supported.",
141 tx.tx_hash()
142 ));
143 }
144
145 let tx_block_number =
146 tx.block_number.ok_or_else(|| eyre::eyre!("tx may still be pending: {:?}", tx_hash))?;
147
148 let block = provider.get_block(tx_block_number.into()).full().await?;
150
151 config.fork_block_number = Some(tx_block_number - 1);
153
154 let create2_deployer = evm_opts.create2_deployer;
155 let (mut env, fork, chain, odyssey) =
156 TracingExecutor::get_fork_material(&config, evm_opts).await?;
157 let mut evm_version = self.evm_version;
158
159 env.evm_env.cfg_env.disable_block_gas_limit = self.disable_block_gas_limit;
160 env.evm_env.block_env.number = U256::from(tx_block_number);
161
162 if let Some(block) = &block {
163 env.evm_env.block_env.timestamp = U256::from(block.header.timestamp);
164 env.evm_env.block_env.beneficiary = block.header.beneficiary;
165 env.evm_env.block_env.difficulty = block.header.difficulty;
166 env.evm_env.block_env.prevrandao = Some(block.header.mix_hash.unwrap_or_default());
167 env.evm_env.block_env.basefee = block.header.base_fee_per_gas.unwrap_or_default();
168 env.evm_env.block_env.gas_limit = block.header.gas_limit;
169
170 if evm_version.is_none() {
173 if block.header.excess_blob_gas.is_some() {
175 evm_version = Some(EvmVersion::Prague);
176 }
177 }
178 apply_chain_and_block_specific_env_changes::<AnyNetwork>(env.as_env_mut(), block);
179 }
180
181 let trace_mode = TraceMode::Call
182 .with_debug(self.debug)
183 .with_decode_internal(if self.decode_internal {
184 InternalTraceMode::Full
185 } else {
186 InternalTraceMode::None
187 })
188 .with_state_changes(shell::verbosity() > 4);
189 let mut executor = TracingExecutor::new(
190 env.clone(),
191 fork,
192 evm_version,
193 trace_mode,
194 odyssey,
195 create2_deployer,
196 None,
197 )?;
198 let mut env = Env::new_with_spec_id(
199 env.evm_env.cfg_env.clone(),
200 env.evm_env.block_env.clone(),
201 env.tx.clone(),
202 executor.spec_id(),
203 );
204
205 if !self.quick {
207 if !shell::is_json() {
208 sh_println!("Executing previous transactions from the block.")?;
209 }
210
211 if let Some(block) = block {
212 let pb = init_progress(block.transactions.len() as u64, "tx");
213 pb.set_position(0);
214
215 let BlockTransactions::Full(ref txs) = block.transactions else {
216 return Err(eyre::eyre!("Could not get block txs"));
217 };
218
219 for (index, tx) in txs.iter().enumerate() {
220 if is_known_system_sender(tx.from())
224 || tx.transaction_type() == Some(SYSTEM_TRANSACTION_TYPE)
225 {
226 pb.set_position((index + 1) as u64);
227 continue;
228 }
229 if tx.tx_hash() == tx_hash {
230 break;
231 }
232
233 configure_tx_env(&mut env.as_env_mut(), &tx.inner);
234
235 env.evm_env.cfg_env.disable_balance_check = true;
236
237 if let Some(to) = Transaction::to(tx) {
238 trace!(tx=?tx.tx_hash(),?to, "executing previous call transaction");
239 executor.transact_with_env(env.clone()).wrap_err_with(|| {
240 format!(
241 "Failed to execute transaction: {:?} in block {}",
242 tx.tx_hash(),
243 env.evm_env.block_env.number
244 )
245 })?;
246 } else {
247 trace!(tx=?tx.tx_hash(), "executing previous create transaction");
248 if let Err(error) = executor.deploy_with_env(env.clone(), None) {
249 match error {
250 EvmError::Execution(_) => (),
252 error => {
253 return Err(error).wrap_err_with(|| {
254 format!(
255 "Failed to deploy transaction: {:?} in block {}",
256 tx.tx_hash(),
257 env.evm_env.block_env.number
258 )
259 });
260 }
261 }
262 }
263 }
264
265 pb.set_position((index + 1) as u64);
266 }
267 }
268 }
269
270 let result = {
272 executor.set_trace_printer(self.trace_printer);
273
274 configure_tx_env(&mut env.as_env_mut(), &tx.inner);
275 if is_impersonated_tx(tx.inner.inner.inner()) {
276 env.evm_env.cfg_env.disable_balance_check = true;
277 }
278
279 if let Some(to) = Transaction::to(&tx) {
280 trace!(tx=?tx.tx_hash(), to=?to, "executing call transaction");
281 TraceResult::try_from(executor.transact_with_env(env))?
282 } else {
283 trace!(tx=?tx.tx_hash(), "executing create transaction");
284 TraceResult::try_from(executor.deploy_with_env(env, None))?
285 }
286 };
287
288 let contracts_bytecode = fetch_contracts_bytecode_from_trace(&provider, &result).await?;
289 handle_traces(
290 result,
291 &config,
292 chain,
293 &contracts_bytecode,
294 self.label,
295 self.with_local_artifacts,
296 self.debug,
297 self.decode_internal,
298 self.disable_labels,
299 )
300 .await?;
301
302 Ok(())
303 }
304}
305
306pub async fn fetch_contracts_bytecode_from_trace(
307 provider: &RootProvider<AnyNetwork>,
308 result: &TraceResult,
309) -> Result<HashMap<Address, Bytes>> {
310 let mut contracts_bytecode = HashMap::default();
311 if let Some(ref traces) = result.traces {
312 let addresses = gather_trace_addresses(traces);
313 let results = futures::future::join_all(addresses.into_iter().map(async |a| {
314 (
315 a,
316 provider.get_code_at(a).await.unwrap_or_else(|e| {
317 sh_warn!("Failed to fetch code for {a:?}: {e:?}").ok();
318 Bytes::new()
319 }),
320 )
321 }))
322 .await;
323 for (address, code) in results {
324 if !code.is_empty() {
325 contracts_bytecode.insert(address, code);
326 }
327 }
328 }
329 Ok(contracts_bytecode)
330}
331
332fn gather_trace_addresses(traces: &Traces) -> HashSet<Address> {
333 let mut addresses = HashSet::default();
334 for (_, trace) in traces {
335 for node in trace.arena.nodes() {
336 if !node.trace.address.is_zero() {
337 addresses.insert(node.trace.address);
338 }
339 if !node.trace.caller.is_zero() {
340 addresses.insert(node.trace.caller);
341 }
342 }
343 }
344 addresses
345}
346
347impl figment::Provider for RunArgs {
348 fn metadata(&self) -> Metadata {
349 Metadata::named("RunArgs")
350 }
351
352 fn data(&self) -> Result<Map<Profile, Dict>, figment::Error> {
353 let mut map = Map::new();
354
355 if self.odyssey {
356 map.insert("odyssey".into(), self.odyssey.into());
357 }
358
359 if let Some(api_key) = &self.etherscan.key {
360 map.insert("etherscan_api_key".into(), api_key.as_str().into());
361 }
362
363 if let Some(api_version) = &self.etherscan.api_version {
364 map.insert("etherscan_api_version".into(), api_version.to_string().into());
365 }
366
367 if let Some(evm_version) = self.evm_version {
368 map.insert("evm_version".into(), figment::value::Value::serialize(evm_version)?);
369 }
370
371 Ok(Map::from([(Config::selected_profile(), map)]))
372 }
373}