Skip to main content

cast/cmd/
call.rs

1use super::{
2    auth::{confirm_auth_rpc_disclosure, confirm_auth_rpc_disclosure_before_network_resolution},
3    call_overrides::CallOverrideOpts,
4    fetch_code_via_rpc, print_raw_line,
5    run::{
6        block_num_hash, call_tracer_frame, fetch_contracts_bytecode_from_trace, trace_addresses,
7    },
8};
9use crate::{
10    debug::{ensure_remote_trace_context_unchanged, handle_traces, resolve_remote_trace_hardfork},
11    rpc_trace::{call_frame_to_arena, call_tracer_config},
12    traces::TraceKind,
13    tx::{CastTxBuilder, SenderKind, read_only_sender},
14};
15use alloy_consensus::{BlockHeader, transaction::Recovered};
16use alloy_dyn_abi::FunctionExt;
17use alloy_eips::BlockNumHash;
18use alloy_ens::NameOrAddress;
19use alloy_network::{BlockResponse, Ethereum, TransactionBuilder, primitives::HeaderResponse};
20use alloy_primitives::{B256, Bytes, TxKind, U256, hex, map::AddressHashMap};
21use alloy_provider::{Provider, ext::DebugApi};
22use alloy_rpc_types::{
23    BlockId, BlockNumberOrTag, TransactionInput, TransactionRequest,
24    trace::geth::{GethDebugTracingCallOptions, GethDebugTracingOptions},
25};
26use clap::Parser;
27use evm2::EvmFeatures;
28use eyre::{Result, WrapErr};
29use foundry_cli::{
30    opts::{ChainValueParser, RpcOpts, TracingArgs, TransactionOpts},
31    utils::{TraceResult, get_provider, load_config_from_provider, parse_ether_value},
32};
33use foundry_common::{
34    abi::{encode_function_args, get_func},
35    fmt::{format_token, serialize_value_as_json},
36    provider::{ProviderBuilder, curl_transport::generate_curl_command},
37    sh_println, shell,
38};
39use foundry_compilers::artifacts::EvmVersion;
40use foundry_config::{
41    Chain, Config, TracingConfig,
42    figment::{
43        self, Metadata, Profile,
44        value::{Dict, Map},
45    },
46};
47use foundry_evm::{
48    core::{
49        decode::RevertDecoder,
50        evm::{
51            BlockContext, ChainFor, EthEvmNetwork, EvmEnvFor, EvmFactoryFor, FoundryEvmFactory,
52            FoundryEvmNetwork, FoundryTxConversion, TempoEvmNetwork, TxFor, TypesFor,
53        },
54    },
55    executors::{Executor, ExecutorBuilder, TracingExecutor},
56    opts::EvmOpts,
57    traces::{InternalTraceMode, SparsedTraceArena, TraceContext, TraceRequirements},
58};
59use foundry_evm_networks::{NetworkConfigs, NetworkVariant};
60use foundry_wallets::{BrowserWalletOpts, WalletOpts};
61use std::str::FromStr;
62
63#[cfg(feature = "base")]
64use foundry_evm::core::evm::BaseEvmNetwork;
65
66#[cfg(feature = "monad")]
67use foundry_evm::core::evm::MonadEvmNetwork;
68
69#[cfg(feature = "optimism")]
70use foundry_evm::core::evm::OpEvmNetwork;
71
72/// CLI arguments for `cast call`.
73///
74/// ## State Override Flags
75///
76/// The following flags can be used to override the state for the call:
77///
78/// * `--override-balance <address>:<balance>` - Override the balance of an account
79/// * `--override-nonce <address>:<nonce>` - Override the nonce of an account
80/// * `--override-code <address>:<code>` - Override the code of an account
81/// * `--override-state <address>:<slot>:<value>` - Override a storage slot of an account
82///
83/// Multiple overrides can be specified for the same account. For example:
84///
85/// ```bash
86/// cast call 0x... "transfer(address,uint256)" 0x... 100 \
87///   --override-balance 0x0000000000000000000000000000000000000001:0x1234 \
88///   --override-nonce 0x0000000000000000000000000000000000000001:1 \
89///   --override-code 0x0000000000000000000000000000000000000001:0x1234 \
90///   --override-state 0x0000000000000000000000000000000000000001:0x1:0x1234 \
91///   --override-state-diff 0x0000000000000000000000000000000000000001:0x1:0x1234
92/// ```
93///
94/// `--delegate` builds on the same mechanism: it overrides the code of the `--from` address with
95/// the destination's code so the call runs as a `delegatecall`.
96#[derive(Debug, Parser)]
97pub struct CallArgs {
98    /// The destination of the transaction.
99    #[arg(value_parser = NameOrAddress::from_str)]
100    to: Option<NameOrAddress>,
101
102    /// The signature of the function to call.
103    sig: Option<String>,
104
105    /// The arguments of the function to call.
106    #[arg(allow_negative_numbers = true)]
107    args: Vec<String>,
108
109    /// Raw hex-encoded data for the transaction. Used instead of `SIG` and `ARGS`.
110    #[arg(
111        long,
112        conflicts_with_all = &["sig", "args"]
113    )]
114    data: Option<String>,
115
116    /// Forks the remote rpc, executes the transaction locally and prints a trace
117    #[arg(long, default_value_t = false)]
118    trace: bool,
119
120    /// Simulate the call as a `delegatecall` from the `--from` address.
121    ///
122    /// The destination's runtime code is applied as a code override on the `--from` address and
123    /// the call is then made to that address, so the destination's code runs in the caller's
124    /// storage context, like an on-chain `delegatecall`.
125    ///
126    /// Note that the executed code observes `msg.sender` (and `tx.origin`) equal to the `--from`
127    /// address itself, whereas in an on-chain `delegatecall` `msg.sender` is preserved from the
128    /// delegating contract's own caller.
129    #[arg(long, requires = "from", conflicts_with = "browser")]
130    delegate: bool,
131
132    /// Fetch the call trace from the node via `debug_traceCall` (callTracer) and render it,
133    /// instead of re-executing the call locally like `--trace`.
134    ///
135    /// This is a call-tree view: nested calls, value, gas, emitted logs and revert data. It does
136    /// not provide the opcode / struct-log level detail of a local `--trace` / `--debug` run.
137    ///
138    /// The local-execution-only trace flags (`--debug`, `--decode-internal`, `--evm-version`) do
139    /// not apply, since the trace comes from the node rather than a local run.
140    #[arg(
141        long = "debug-trace-call",
142        default_value_t = false,
143        conflicts_with_all = ["trace", "debug", "decode_internal", "evm_version"]
144    )]
145    debug_trace_call: bool,
146
147    /// Opens an interactive debugger.
148    /// Can only be used with `--trace`.
149    #[arg(long, requires = "trace")]
150    debug: bool,
151
152    #[command(flatten)]
153    tracing: TracingArgs,
154
155    /// The EVM Version to use.
156    /// Can only be used with `--trace`.
157    #[arg(long, requires = "trace")]
158    evm_version: Option<EvmVersion>,
159
160    /// The block height to query at.
161    ///
162    /// Can also be the tags earliest, finalized, safe, latest, or pending.
163    #[arg(long, short)]
164    block: Option<BlockId>,
165
166    #[command(subcommand)]
167    command: Option<CallSubcommands>,
168
169    #[command(flatten)]
170    tx: TransactionOpts,
171
172    /// Skip the EIP-7702 authorization disclosure confirmation.
173    #[arg(long)]
174    force: bool,
175
176    #[command(flatten)]
177    rpc: RpcOpts,
178
179    #[command(flatten)]
180    wallet: WalletOpts,
181
182    #[command(flatten)]
183    browser: BrowserWalletOpts,
184
185    #[arg(
186        short,
187        long,
188        alias = "chain-id",
189        env = "CHAIN",
190        value_parser = ChainValueParser::default(),
191    )]
192    pub chain: Option<Chain>,
193
194    /// Use current project artifacts for trace decoding.
195    #[arg(long, visible_alias = "la")]
196    pub with_local_artifacts: bool,
197
198    #[command(flatten)]
199    pub overrides: CallOverrideOpts,
200}
201
202#[derive(Debug, Parser)]
203pub enum CallSubcommands {
204    /// ignores the address field and simulates creating a contract
205    #[command(name = "--create")]
206    Create {
207        /// Bytecode of contract.
208        code: String,
209
210        /// The signature of the constructor.
211        sig: Option<String>,
212
213        /// The arguments of the constructor.
214        #[arg(allow_negative_numbers = true)]
215        args: Vec<String>,
216
217        /// Ether to send in the transaction.
218        ///
219        /// Either specified in wei, or as a string with a unit type.
220        ///
221        /// Examples: 1ether, 10gwei, 0.01ether
222        #[arg(long, value_parser = parse_ether_value)]
223        value: Option<U256>,
224    },
225}
226
227/// The `callTracer` options shared by `--debug-trace-call` and its `--curl` rendering.
228fn call_tracer_options() -> GethDebugTracingCallOptions {
229    GethDebugTracingCallOptions::default()
230        .with_tracing_options(GethDebugTracingOptions::call_tracer(call_tracer_config()))
231}
232
233impl CallArgs {
234    fn resolve_tracing(&self, config: &TracingConfig, verbosity: u8) -> TracingConfig {
235        if self.debug_trace_call {
236            self.tracing.resolve_call_tracer(config, verbosity)
237        } else {
238            self.tracing.resolve(config, verbosity)
239        }
240    }
241
242    pub async fn run(mut self) -> Result<()> {
243        self.validate_trace_args()?;
244
245        // Handle --curl mode early, before any provider interaction
246        if self.rpc.curl {
247            if self.trace {
248                eyre::bail!(
249                    "--trace cannot be combined with --curl; use --debug-trace-call --curl instead"
250                );
251            }
252            if self.browser.browser {
253                eyre::bail!("--browser cannot be combined with --curl; use --from <ADDRESS>");
254            }
255            if self.delegate {
256                // The code override that makes the call a `delegatecall` is read from the node,
257                // which `--curl` deliberately never contacts.
258                eyre::bail!("--delegate cannot be combined with --curl");
259            }
260            if !self.tx.auth.is_empty() {
261                eyre::bail!("--auth cannot be combined with --curl");
262            }
263            if self.command.is_some() {
264                eyre::bail!("--create cannot be combined with --curl");
265            }
266            return self.run_curl().await;
267        }
268
269        let figment = self.rpc.clone().into_figment(self.with_local_artifacts).merge(&self);
270        let (mut config, mut evm_opts) = super::load_cast_config_and_evm_opts(figment)?;
271        evm_opts.fork_url = Some(config.get_rpc_url_or_localhost_http()?.into_owned());
272        let has_tempo_session = self.tx.tempo.session_id()?.is_some();
273        let requires_tempo = self.tx.tempo.is_tempo() || has_tempo_session;
274        super::validate_tempo_network(&config, requires_tempo)?;
275        if requires_tempo {
276            evm_opts.networks = NetworkConfigs::with_tempo();
277        } else if !evm_opts.networks.has_network_selection()
278            && let Some(chain) = config.chain
279        {
280            evm_opts.networks =
281                evm_opts.networks.try_with_chain_id(chain.id()).map_err(eyre::Report::msg)?;
282        }
283        if has_tempo_session && self.will_disclose_auth() {
284            eyre::bail!("Tempo sessions cannot be combined with EIP-7702 authorizations");
285        }
286        let Some(auth_preflight) = self.preflight_auth_disclosure().await? else {
287            return Ok(());
288        };
289        evm_opts.infer_network_from_fork().await?;
290        if self.chain.is_none()
291            && let Some(chain_id) = evm_opts.env.chain_id
292        {
293            let chain = Chain::from_id(chain_id);
294            self.chain = Some(chain);
295            config.chain = Some(chain);
296        }
297
298        match evm_opts.networks.execution_network() {
299            NetworkVariant::Tempo => {
300                self.run_with_network_and_opts::<TempoEvmNetwork>(
301                    config,
302                    evm_opts,
303                    auth_preflight,
304                    ExecutorBuilder::<TempoEvmNetwork>::new(),
305                )
306                .await
307            }
308            #[cfg(feature = "base")]
309            NetworkVariant::Base => {
310                super::validate_base_transaction_options(&self.tx)?;
311                self.run_with_network_and_opts::<BaseEvmNetwork>(
312                    config,
313                    evm_opts,
314                    auth_preflight,
315                    ExecutorBuilder::<BaseEvmNetwork>::new(),
316                )
317                .await
318            }
319            #[cfg(feature = "monad")]
320            NetworkVariant::Monad => {
321                self.run_with_network_and_opts::<MonadEvmNetwork>(
322                    config,
323                    evm_opts,
324                    auth_preflight,
325                    ExecutorBuilder::<MonadEvmNetwork>::new(),
326                )
327                .await
328            }
329            #[cfg(feature = "optimism")]
330            NetworkVariant::Optimism => {
331                self.run_with_network_and_opts::<OpEvmNetwork>(
332                    config,
333                    evm_opts,
334                    auth_preflight,
335                    ExecutorBuilder::<OpEvmNetwork>::new(),
336                )
337                .await
338            }
339            NetworkVariant::Ethereum => {
340                self.run_with_network_and_opts::<EthEvmNetwork>(
341                    config,
342                    evm_opts,
343                    auth_preflight,
344                    ExecutorBuilder::<EthEvmNetwork>::new(),
345                )
346                .await
347            }
348        }
349    }
350
351    /// Returns whether resolving this call can disclose an authorization before the transaction
352    /// builder exists. This mirrors the builder's disclosure check after applying `.raw()`.
353    const fn will_disclose_auth(&self) -> bool {
354        !self.tx.auth.is_empty() && (!self.trace || matches!(self.tx.access_list, Some(None)))
355    }
356
357    /// Confirms the authorization disclosure before the network is resolved.
358    ///
359    /// Returns `None` when the user declined, otherwise whether the disclosure was confirmed
360    /// along with the sender resolved for it (absent for browser wallets).
361    async fn preflight_auth_disclosure(
362        &self,
363    ) -> Result<Option<(bool, Option<SenderKind<'static>>)>> {
364        if !self.will_disclose_auth() {
365            return Ok(Some((false, None)));
366        }
367
368        let sender = if self.browser.browser {
369            None
370        } else {
371            Some(SenderKind::from_wallet_opts(self.wallet.clone(), &self.tx.auth).await?)
372        };
373        let browser_sender = SenderKind::from(self.wallet.from.unwrap_or_default());
374        let validation_sender = sender.as_ref().unwrap_or(&browser_sender);
375        if !confirm_auth_rpc_disclosure_before_network_resolution(
376            &self.tx.auth,
377            validation_sender,
378            self.force,
379        )? {
380            return Ok(None);
381        }
382
383        Ok(Some((true, sender)))
384    }
385
386    fn validate_trace_args(&self) -> Result<()> {
387        if !self.trace
388            && !self.debug_trace_call
389            && (self.tracing.disable_labels
390                || self.tracing.compact_labels
391                || !self.tracing.labels.is_empty()
392                || self.tracing.trace_depth.is_some())
393        {
394            eyre::bail!("trace rendering options require `--trace` or `--debug-trace-call`");
395        }
396
397        if self.tracing.decode_internal && !self.trace {
398            eyre::bail!("`--decode-internal` requires `--trace`");
399        }
400
401        Ok(())
402    }
403
404    async fn run_with_network_and_opts<FEN: FoundryEvmNetwork>(
405        self,
406        mut config: Box<Config>,
407        evm_opts: EvmOpts,
408        (auth_confirmed, auth_sender): (bool, Option<SenderKind<'static>>),
409        executor_builder: ExecutorBuilder<FEN>,
410    ) -> Result<()> {
411        config.networks = evm_opts.networks;
412        let mut state_overrides = self.overrides.get_state_overrides()?;
413        let block_overrides = self.overrides.get_block_overrides()?;
414        config.tracing = self.resolve_tracing(&config.tracing, shell::verbosity());
415        let tracing = config.tracing.clone();
416
417        let Self {
418            mut to,
419            mut sig,
420            mut args,
421            mut tx,
422            command,
423            block,
424            trace,
425            debug_trace_call,
426            evm_version,
427            debug,
428            data,
429            with_local_artifacts,
430            wallet,
431            browser,
432            force,
433            delegate,
434            ..
435        } = self;
436
437        if let Some(data) = data {
438            sig = Some(data);
439        }
440
441        let provider = ProviderBuilder::<FEN::Network>::from_config(&config)?.build()?;
442        let endpoint_identity =
443            if debug_trace_call { Some(evm_opts.fork_endpoint_identity().await?) } else { None };
444        let sender = match auth_sender {
445            Some(sender) => sender,
446            None => {
447                let chain_id = match config.chain {
448                    Some(chain) => chain.id(),
449                    None => provider.get_chain_id().await?,
450                };
451                read_only_sender::<FEN::Network>(&browser, wallet, &tx, chain_id).await?.0
452            }
453        };
454        let from = sender.address();
455
456        // A `delegatecall` runs the destination's code against the caller's storage, which
457        // `eth_call` cannot express. Overriding the caller's code with the destination's and
458        // then calling the caller reproduces that context. The retarget to the caller happens
459        // after the transaction is built, so calldata encoding and function resolution still
460        // see the destination.
461        if delegate {
462            if command.is_some() {
463                eyre::bail!("`--delegate` cannot be combined with `--create`");
464            }
465            let Some(target) = to else {
466                eyre::bail!("`--delegate` requires a destination address");
467            };
468            let target = target.resolve(&provider).await?;
469            let overrides = state_overrides.get_or_insert_with(Default::default);
470            if overrides.get(&from).is_some_and(|account| account.code.is_some()) {
471                eyre::bail!("`--delegate` conflicts with `--override-code` for the sender {from}");
472            }
473            // A code override for the destination is the state this call runs against, so it
474            // takes precedence over the deployed code.
475            let code = match overrides.get(&target).and_then(|account| account.code.clone()) {
476                Some(code) => code,
477                None => provider.get_code_at(target).block_id(block.unwrap_or_default()).await?,
478            };
479            if code.is_empty() {
480                eyre::bail!("`--delegate` destination {target} has no code to delegate to");
481            }
482            overrides.entry(from).or_default().code = Some(code);
483            to = Some(NameOrAddress::Address(target));
484        }
485
486        let code = if let Some(CallSubcommands::Create {
487            code,
488            sig: create_sig,
489            args: create_args,
490            value,
491        }) = command
492        {
493            sig = create_sig;
494            args = create_args;
495            if let Some(value) = value {
496                tx.value = Some(value);
497            }
498            Some(code)
499        } else {
500            None
501        };
502
503        let builder = CastTxBuilder::new(&provider, tx, &config)
504            .await?
505            .with_to(to)
506            .await?
507            .with_code_sig_and_args(code, sig, args)
508            .await?
509            .raw();
510        let will_disclose =
511            (!trace && builder.has_auth()) || builder.will_disclose_auth_during_build();
512        if will_disclose
513            && !auth_confirmed
514            && !confirm_auth_rpc_disclosure(&builder, &sender, force)?
515        {
516            return Ok(());
517        }
518        let (mut tx, func) = builder.build(sender).await?;
519
520        // The delegate override put the destination's code on the sender, so the built call is
521        // aimed at the sender; the calldata above was still encoded against the destination.
522        if delegate {
523            tx.set_to(from);
524        }
525
526        if debug_trace_call {
527            let endpoint_identity = endpoint_identity
528                .ok_or_else(|| eyre::eyre!("remote trace endpoint identity was not captured"))?;
529            let requested_block = block.unwrap_or_default();
530            let fetched_block = provider.get_block(requested_block).await?;
531            let resolved_canonical_block =
532                if matches!(requested_block, BlockId::Number(_)) && !requested_block.is_pending() {
533                    fetched_block.as_ref().map(block_num_hash)
534                } else {
535                    None
536                };
537            let block = pin_remote_trace_block(
538                requested_block,
539                fetched_block.as_ref().map(|block| block.header().hash()),
540            )?;
541            let block_time_override = block_overrides.as_ref().and_then(|overrides| overrides.time);
542            let mut call_options = call_tracer_options();
543            // A contract that only exists through a `--override-code` entry has no on-chain
544            // code to fetch for local-artifact matching, so remember the override code before
545            // handing the overrides to `debug_traceCall`.
546            let mut override_bytecode = AddressHashMap::<Bytes>::default();
547            if with_local_artifacts && let Some(overrides) = &state_overrides {
548                for (address, account) in overrides {
549                    if let Some(code) = &account.code {
550                        override_bytecode.insert(*address, code.clone());
551                    }
552                }
553            }
554
555            // Honour the same state / block overrides as the local `--trace` path.
556            if let Some(state_overrides) = state_overrides {
557                call_options = call_options.with_state_overrides(state_overrides);
558            }
559            if let Some(block_overrides) = block_overrides {
560                call_options = call_options.with_block_overrides(block_overrides);
561            }
562
563            let frame = call_tracer_frame(
564                provider.debug_trace_call(tx, block, call_options).await,
565                "debug_traceCall",
566                "drop `--debug-trace-call` to run the call locally with `--trace`",
567                "the requested block; use an archive endpoint, or target a more recent block with `--block`",
568            )?;
569
570            let arena = SparsedTraceArena {
571                arena: call_frame_to_arena(&frame, None),
572                ignored: Default::default(),
573                diagnostics: Default::default(),
574                debug_steps: None,
575            };
576            let result = TraceResult {
577                success: frame.error.is_none() && frame.revert_reason.is_none(),
578                traces: Some(vec![(TraceKind::Execution, arena)]),
579                gas_used: frame.gas_used.saturating_to(),
580            };
581
582            // Local-artifact labeling matches deployed runtime bytecode against the
583            // project artifacts. There is no local executor on this path, so fetch the code
584            // over RPC for the addresses in the trace. Skip the extra round-trips unless
585            // local artifacts were requested.
586            let contracts_bytecode = if with_local_artifacts {
587                let mut contracts_bytecode =
588                    fetch_code_via_rpc(&provider, trace_addresses(&result), block).await;
589                // The trace ran the override code, not the on-chain code, so the override
590                // wins for artifact matching.
591                contracts_bytecode.extend(override_bytecode);
592                contracts_bytecode
593            } else {
594                Default::default()
595            };
596            let final_endpoint_identity = evm_opts.fork_endpoint_identity().await?;
597            ensure_remote_trace_context_unchanged(&endpoint_identity, &final_endpoint_identity)?;
598
599            // The remote node executed this trace, so its reported family is authoritative for
600            // decoding even when the caller selected a compatible local EVM implementation.
601            let chain = alloy_chains::Chain::from_id(endpoint_identity.source_chain_id);
602            let block_timestamp = block_time_override
603                .or_else(|| fetched_block.as_ref().map(|block| block.header().timestamp()));
604            let resolved_hardfork =
605                resolve_remote_trace_hardfork(config.hardfork, &endpoint_identity, block_timestamp);
606            if let Some(resolved_block) = resolved_canonical_block {
607                let canonical_block =
608                    provider.get_block_by_number(resolved_block.number.into()).await?;
609                ensure_remote_trace_block_is_canonical(
610                    resolved_block,
611                    canonical_block.as_ref().map(block_num_hash),
612                )?;
613            }
614            return handle_traces(
615                result,
616                &config,
617                {
618                    let context = TraceContext::new(
619                        chain,
620                        endpoint_identity.network_profile,
621                        resolved_hardfork,
622                    );
623                    context.with_hardfork(context.decoding_hardfork(&config))
624                },
625                &contracts_bytecode,
626                &tracing,
627                with_local_artifacts,
628                false,
629            )
630            .await;
631        }
632
633        if trace {
634            if let Some(BlockId::Number(BlockNumberOrTag::Number(block_number))) = block {
635                // Override Config `fork_block_number` (if set) with CLI value.
636                config.fork_block_number = Some(block_number);
637            }
638
639            let create2_deployer = evm_opts.create2_deployer;
640            let fork_prefetch = evm_opts.fork_prefetch;
641            let mut fork = TracingExecutor::<FEN>::get_fork(&mut config, evm_opts).await?;
642            // Modify settings usually set in eth_call while keeping execution gas bounded.
643            fork.evm_env.set_feature(EvmFeatures::BLOCK_GAS_LIMIT_CHECK, false);
644            fork.evm_env.version.tx_gas_limit_cap = u64::MAX;
645
646            if let Some(block_overrides) = block_overrides {
647                if let Some(number) = block_overrides.number {
648                    fork.evm_env.block.number = number.to();
649                }
650                if let Some(time) = block_overrides.time {
651                    fork.evm_env.block.timestamp = U256::from(time);
652                }
653            }
654            fork.resolve_spec(&config, evm_version);
655            fork.extend_precompile_labels(&mut config);
656            let context = fork.context();
657
658            let trace_requirements = TraceRequirements::none()
659                .with_calls(true)
660                .with_debug_recording(debug)
661                .with_decode_internal(if tracing.decode_internal {
662                    InternalTraceMode::Full
663                } else {
664                    InternalTraceMode::None
665                })
666                .with_state_changes(tracing.verbosity > 4);
667            let mut executor = fork.into_executor(
668                executor_builder,
669                trace_requirements,
670                create2_deployer,
671                state_overrides,
672            )?;
673            executor.inspector_mut().fork_prefetch(fork_prefetch);
674
675            let value = tx.value().unwrap_or_default();
676            let input = tx.input().cloned().unwrap_or_default();
677            let tx_kind = tx.kind().expect("set by builder");
678
679            // Apply a user-provided `--gas-limit` to the executor. `prepare_call_env` propagates
680            // the executor's gas limit to the executed call/deploy and the block.
681            if let Some(gas_limit) = tx.gas_limit() {
682                executor.set_gas_limit(gas_limit);
683            }
684
685            // Execute the built request, which keeps the transaction type, fees, nonce, access
686            // and authorization lists of the transaction options, with the executor's gas limit
687            // and chain ID. Like `eth_call`, honour the requested fees without requiring the
688            // caller to afford them. Monad ignores the disabled fee charge, so reject priced
689            // traces there. Zero fees keep the zeroed base fee of `prepare_call_env`, skipping
690            // base fee validation like `eth_call`.
691            let (mut evm_env, call_defaults) =
692                executor.prepare_call_env(from, tx_kind, input, value);
693            let priority_fee = tx.max_priority_fee_per_gas().unwrap_or_default();
694            let gas_price = tx.max_fee_per_gas().or(tx.gas_price()).unwrap_or_default();
695            if gas_price != 0 || priority_fee != 0 {
696                eyre::ensure!(
697                    !config.networks.execution_network().is_monad(),
698                    "Nonzero fees are not supported for local Monad traces; use --debug-trace-call instead"
699                );
700                evm_env.set_feature(EvmFeatures::FEE_CHARGE, false);
701                evm_env.set_feature(EvmFeatures::BALANCE_CHECK, false);
702                evm_env.set_feature(EvmFeatures::BALANCE_TOP_UP, false);
703                evm_env.block.basefee = executor.evm_env().block.basefee;
704            }
705            if tx.gas_price().is_some() {
706                tx.set_gas_price(gas_price);
707            } else {
708                tx.set_max_fee_per_gas(gas_price);
709                tx.set_max_priority_fee_per_gas(priority_fee);
710            }
711            tx.set_from(from);
712            tx.set_chain_id(evm_env.chain_id());
713            if let Some(gas_limit) = call_defaults.gas_limit() {
714                tx.set_gas_limit(gas_limit);
715            }
716            if tx.nonce().is_none()
717                && let Some(nonce) = call_defaults.nonce()
718            {
719                tx.set_nonce(nonce);
720            }
721
722            let trace = if config.networks.execution_network().is_monad() {
723                // Monad's reserve balance depends on the senders of recent blocks, so the call
724                // runs as the first transaction of the block after the fork block.
725                let trace_kind = match tx_kind {
726                    TxKind::Create => TraceKind::Deployment,
727                    TxKind::Call(_) => TraceKind::Execution,
728                };
729                let tx = TypesFor::<FEN>::tx_from_request(tx)?;
730                let ext = next_block_ext(&config, &executor, &evm_env, &tx).await?;
731                TraceResult::from_raw(executor.transact_tx(evm_env, &tx, Some(ext))?, trace_kind)
732            } else {
733                match tx_kind {
734                    TxKind::Create => {
735                        let deploy_result = executor.deploy_with_env(evm_env, tx, None);
736                        TraceResult::try_from(deploy_result)?
737                    }
738                    TxKind::Call(_) => TraceResult::from_raw(
739                        executor.transact_with_env(evm_env, tx)?,
740                        TraceKind::Execution,
741                    ),
742                }
743            };
744
745            let contracts_bytecode = fetch_contracts_bytecode_from_trace(&executor, &trace)?;
746            return handle_traces(
747                trace,
748                &config,
749                context,
750                &contracts_bytecode,
751                &tracing,
752                with_local_artifacts,
753                debug,
754            )
755            .await;
756        }
757
758        let mut call = provider
759            .call(tx.clone())
760            .block(block.unwrap_or_default())
761            .with_block_overrides_opt(block_overrides);
762        if let Some(state_override) = state_overrides {
763            call = call.overrides(state_override)
764        }
765
766        let res = match call.await {
767            Ok(res) => res,
768            Err(err) => {
769                let data = err.as_error_resp().and_then(|payload| payload.as_revert_data());
770                if let Some(data) = data {
771                    let decoded = match RevertDecoder::new().maybe_decode_known(&data) {
772                        Some(decoded) => Some(decoded),
773                        None => crate::tx::decode_custom_error(&data).await.ok().flatten(),
774                    };
775                    if let Some(decoded) = decoded {
776                        return Err(err).wrap_err(format!("execution reverted: {decoded}"));
777                    }
778                }
779                return Err(err.into());
780            }
781        };
782        let decoded = match func.as_ref() {
783            Some(func) => match func.abi_decode_output(res.as_ref()) {
784                Ok(decoded) => decoded,
785                Err(err) => {
786                    // An empty response usually means the recipient is not a contract.
787                    if res.is_empty() {
788                        let Some(addr) = tx.to() else {
789                            eyre::bail!("tx req is a contract deployment");
790                        };
791                        if let Ok(code) =
792                            provider.get_code_at(addr).block_id(block.unwrap_or_default()).await
793                            && code.is_empty()
794                        {
795                            eyre::bail!("contract {addr:?} does not have any code");
796                        }
797                    }
798                    return Err(err).wrap_err(
799                        "could not decode output; did you specify the wrong function return data type?"
800                    );
801                }
802            },
803            None => vec![],
804        };
805
806        // handle case when return type is not specified
807        let response = if decoded.is_empty() {
808            res.to_string()
809        } else if shell::is_json() {
810            let tokens = decoded
811                .into_iter()
812                .map(|value| serialize_value_as_json(value, None, true))
813                .collect::<eyre::Result<Vec<_>>>()?;
814            serde_json::to_string_pretty(&tokens).unwrap()
815        } else {
816            // seth compatible user-friendly return type conversions
817            decoded.iter().map(format_token).collect::<Vec<_>>().join("\n")
818        };
819
820        // With `--delegate` the call targets the sender, whose code comes from the override and
821        // was already checked to be non-empty, so the on-chain code lookup would be misleading.
822        if response == "0x"
823            && !delegate
824            && let Some(contract_address) = tx.to()
825            && provider.get_code_at(contract_address).await?.is_empty()
826        {
827            sh_warn!("Contract code is empty")?;
828        }
829
830        print_raw_line(response)
831    }
832
833    /// Handle --curl mode by generating curl command without any RPC interaction.
834    async fn run_curl(self) -> Result<()> {
835        let figment = self.rpc.clone().into_figment(self.with_local_artifacts).merge(&self);
836        let config = load_config_from_provider(figment)?;
837        let has_tempo_session = self.tx.tempo.session_id()?.is_some();
838        super::validate_tempo_network(&config, self.tx.tempo.is_tempo() || has_tempo_session)?;
839        if has_tempo_session {
840            eyre::bail!("--tempo.session/TEMPO_SESSION_ID cannot be combined with --curl");
841        }
842        let url = config.get_rpc_url_or_localhost_http()?;
843        let jwt = config.get_rpc_jwt_secret()?;
844
845        // Get call data - either from --data or from sig + args
846        let data = if let Some(data) = &self.data {
847            hex::decode(data)?
848        } else if let Some(sig) = &self.sig {
849            // If sig is already hex data, use it directly
850            match hex::decode(sig) {
851                Ok(data) => {
852                    eyre::ensure!(
853                        self.args.is_empty(),
854                        "Arguments cannot be used with raw calldata. Use a function signature to encode arguments, or provide the complete calldata without arguments."
855                    );
856                    data
857                }
858                Err(_) => encode_function_args(&get_func(sig)?, &self.args)?,
859            }
860        } else {
861            Vec::new()
862        };
863
864        // Resolve the destination address (must be a raw address for curl mode)
865        let to = self.to.as_ref().map(|n| match n {
866            NameOrAddress::Address(addr) => Ok(*addr),
867            NameOrAddress::Name(name) => {
868                eyre::bail!("ENS names are not supported with --curl. Please use a raw address instead of '{}'", name);
869            }
870        }).transpose()?;
871
872        // Apply explicit transaction options offline, using the configured chain's fee style
873        // when available. Blob sidecars and authorization lists still require the RPC builder.
874        let legacy = self.tx.legacy
875            || (config.chain.is_some_and(|chain| chain.is_legacy()) && self.tx.auth.is_empty());
876        let mut call_request = TransactionRequest {
877            to: Some(to.map_or(TxKind::Create, TxKind::Call)),
878            from: self.wallet.from,
879            input: TransactionInput::new(data.into()).normalized_data(),
880            ..Default::default()
881        };
882        // Curl currently emits Ethereum-compatible fields only. Keep Tempo options from changing
883        // the nonce without their accompanying network-specific fields.
884        let tx_opts = TransactionOpts { tempo: Default::default(), ..self.tx };
885        tx_opts.apply::<Ethereum>(&mut call_request, legacy);
886
887        let block_param = self
888            .block
889            .map(|b| serde_json::to_value(b).unwrap_or(serde_json::json!("latest")))
890            .unwrap_or(serde_json::json!("latest"));
891
892        // `--debug-trace-call` fetches a callTracer trace of the call instead of executing it,
893        // so the curl payload must target `debug_traceCall` with the same third param as the
894        // non-curl path: the tracer options plus any state / block overrides, so the printed
895        // request traces the same state as the command it represents.
896        let (method, params) = if self.debug_trace_call {
897            let mut call_options = call_tracer_options();
898            if let Some(state_overrides) = self.overrides.get_state_overrides()? {
899                call_options = call_options.with_state_overrides(state_overrides);
900            }
901            if let Some(block_overrides) = self.overrides.get_block_overrides()? {
902                call_options = call_options.with_block_overrides(block_overrides);
903            }
904            ("debug_traceCall", serde_json::json!([call_request, block_param, call_options]))
905        } else {
906            ("eth_call", serde_json::json!([call_request, block_param]))
907        };
908
909        let curl_cmd = generate_curl_command(
910            url.as_ref(),
911            method,
912            params,
913            config.eth_rpc_headers.as_deref(),
914            jwt.as_deref(),
915        )?;
916
917        sh_println!("{}", curl_cmd)?;
918        Ok(())
919    }
920}
921
922fn pin_remote_trace_block(requested: BlockId, fetched_hash: Option<B256>) -> Result<BlockId> {
923    if requested.is_pending() {
924        return Ok(requested);
925    }
926
927    let fetched_hash = fetched_hash.ok_or_else(|| {
928        eyre::eyre!("block {requested:?} was not found while preparing the remote trace")
929    })?;
930    if let BlockId::Hash(requested_hash) = requested {
931        if requested_hash.block_hash != fetched_hash {
932            eyre::bail!(
933                "the RPC endpoint returned block {fetched_hash} for requested block {}; retry the command",
934                requested_hash.block_hash
935            );
936        }
937        // Preserve `requireCanonical` exactly as supplied by the caller.
938        return Ok(requested);
939    }
940
941    Ok(BlockId::hash(fetched_hash))
942}
943
944fn ensure_remote_trace_block_is_canonical(
945    expected: BlockNumHash,
946    actual: Option<BlockNumHash>,
947) -> Result<()> {
948    let Some(actual) = actual else {
949        eyre::bail!(
950            "block {} at {} changed canonicality while collecting its remote trace: the canonical block lookup no longer reports that height; retry the command",
951            expected.hash,
952            expected.number,
953        );
954    };
955    if actual != expected {
956        eyre::bail!(
957            "block {} at {} changed canonicality while collecting its remote trace: the canonical block lookup reported block {} at {}; retry the command",
958            expected.hash,
959            expected.number,
960            actual.hash,
961            actual.number,
962        );
963    }
964
965    Ok(())
966}
967
968impl figment::Provider for CallArgs {
969    fn metadata(&self) -> Metadata {
970        Metadata::named("CallArgs")
971    }
972
973    fn data(&self) -> Result<Map<Profile, Dict>, figment::Error> {
974        let mut map = Map::new();
975
976        if let Some(evm_version) = self.evm_version {
977            map.insert("evm_version".into(), figment::value::Value::serialize(evm_version)?);
978        }
979        if let Some(chain) = self.chain {
980            map.insert("chain_id".into(), chain.id().into());
981        }
982
983        Ok(Map::from([(Config::selected_profile(), map)]))
984    }
985}
986
987/// Returns the network extension state for `tx` executed as the first transaction of the block
988/// after the fork block, which block-position rules such as Monad's reserve balance depend on.
989async fn next_block_ext<FEN: FoundryEvmNetwork>(
990    config: &Config,
991    executor: &Executor<FEN>,
992    evm_env: &EvmEnvFor<FEN>,
993    tx: &Recovered<TxFor<FEN>>,
994) -> Result<ChainFor<FEN>> {
995    let fork = executor.backend().fork().ok_or_else(|| eyre::eyre!("the trace is not forked"))?;
996    let provider = get_provider(config)?;
997    let block = provider
998        .get_block_by_hash(fork.hash())
999        .full()
1000        .await?
1001        .ok_or_else(|| eyre::eyre!("fork block {} not found", fork.hash()))?;
1002    let mut context = BlockContext::<FEN>::fetch(&provider, &block).await?;
1003    context.advance_block();
1004    let mut ext = EvmFactoryFor::<FEN>::default().evm_ext(evm_env);
1005    context.prepare_next(&mut ext, tx);
1006    Ok(ext)
1007}
1008
1009#[cfg(test)]
1010mod tests {
1011    use super::*;
1012    use alloy_eips::RpcBlockHash;
1013
1014    #[test]
1015    fn remote_trace_block_pinning() {
1016        let hash = B256::repeat_byte(0x11);
1017
1018        // Pending stays unpinned; every other block is pinned to the fetched hash.
1019        assert_eq!(pin_remote_trace_block(BlockId::pending(), None).unwrap(), BlockId::pending());
1020        for requested in [
1021            BlockId::number(42),
1022            BlockId::earliest(),
1023            BlockId::latest(),
1024            BlockId::safe(),
1025            BlockId::finalized(),
1026        ] {
1027            assert_eq!(pin_remote_trace_block(requested, Some(hash)).unwrap(), BlockId::hash(hash));
1028        }
1029        let err = pin_remote_trace_block(BlockId::number(42), None).unwrap_err();
1030        assert!(err.to_string().contains("was not found while preparing the remote trace"));
1031
1032        // Hash requests keep `requireCanonical` and must match the response.
1033        for require_canonical in [None, Some(false), Some(true)] {
1034            let requested = BlockId::Hash(RpcBlockHash { block_hash: hash, require_canonical });
1035            assert_eq!(pin_remote_trace_block(requested, Some(hash)).unwrap(), requested);
1036        }
1037        let err = pin_remote_trace_block(
1038            BlockId::hash_canonical(B256::repeat_byte(0x33)),
1039            Some(B256::repeat_byte(0x44)),
1040        )
1041        .unwrap_err();
1042        assert!(err.to_string().contains("returned block"));
1043    }
1044
1045    #[test]
1046    fn remote_trace_block_must_remain_canonical() {
1047        let expected = BlockNumHash::new(42, B256::repeat_byte(0x55));
1048        ensure_remote_trace_block_is_canonical(expected, Some(expected)).unwrap();
1049
1050        let err = ensure_remote_trace_block_is_canonical(expected, None).unwrap_err();
1051        assert!(err.to_string().contains("no longer reports that height"), "{err}");
1052
1053        let reorged = BlockNumHash::new(42, B256::repeat_byte(0x66));
1054        let err = ensure_remote_trace_block_is_canonical(expected, Some(reorged)).unwrap_err();
1055        assert!(err.to_string().contains("changed canonicality"), "{err}");
1056    }
1057
1058    #[test]
1059    fn chain_is_merged_into_config() {
1060        let args = CallArgs::parse_from(["foundry-cli", "--chain", "1"]);
1061        let config = Config::from_provider(Config::figment().merge(&args)).unwrap();
1062
1063        assert_eq!(config.chain, Some(Chain::mainnet()));
1064    }
1065
1066    /// Base chain IDs resolved to Optimism before Base support existed, so a build without the
1067    /// `base` feature — which is what release binaries ship — must keep resolving them that way.
1068    #[test]
1069    #[cfg(all(not(feature = "base"), feature = "optimism"))]
1070    fn chain_id_without_base_still_resolves_to_optimism() {
1071        for chain_id in [8453, 84532] {
1072            let networks = NetworkConfigs::default()
1073                .try_with_chain_id(chain_id)
1074                .unwrap_or_else(|error| panic!("chain ID {chain_id} must still resolve: {error}"));
1075            assert!(networks.is_optimism(), "chain ID {chain_id} must resolve to Optimism");
1076        }
1077    }
1078
1079    #[test]
1080    fn debug_trace_call_ignores_configured_internal_decoding() {
1081        let args = CallArgs::parse_from(["foundry-cli", "--debug-trace-call"]);
1082        let config = TracingConfig { decode_internal: true, ..Default::default() };
1083
1084        assert!(!args.resolve_tracing(&config, 0).decode_internal);
1085    }
1086}