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::{
20    AnyNetwork, BlockResponse, Ethereum, TransactionBuilder, primitives::HeaderResponse,
21};
22use alloy_primitives::{B256, Bytes, TxKind, U256, hex, map::AddressHashMap};
23use alloy_provider::{Provider, ext::DebugApi};
24use alloy_rpc_types::{
25    BlockId, BlockNumberOrTag, TransactionInput, TransactionRequest,
26    trace::geth::{GethDebugTracingCallOptions, GethDebugTracingOptions},
27};
28use clap::Parser;
29use evm2::EvmFeatures;
30use eyre::{Result, WrapErr};
31use foundry_cli::{
32    opts::{ChainValueParser, RpcOpts, TracingArgs, TransactionOpts},
33    utils::{TraceResult, load_config_from_provider, parse_ether_value},
34};
35use foundry_common::{
36    abi::{encode_function_args, get_func},
37    fmt::{format_token, serialize_value_as_json},
38    provider::{ProviderBuilder, curl_transport::generate_curl_command},
39    sh_println, shell,
40};
41use foundry_compilers::artifacts::EvmVersion;
42use foundry_config::{
43    Chain, Config, TracingConfig,
44    figment::{
45        self, Metadata, Profile,
46        value::{Dict, Map},
47    },
48};
49use foundry_evm::{
50    core::{
51        decode::RevertDecoder,
52        evm::{
53            BlockContext, ChainFor, EthEvmNetwork, EvmEnvFor, EvmFactoryFor, FoundryEvmFactory,
54            FoundryEvmNetwork, FoundryTxConversion, TempoEvmNetwork, TxFor, TypesFor,
55        },
56    },
57    executors::{Executor, ExecutorBuilder, TracingExecutor},
58    opts::EvmOpts,
59    traces::{InternalTraceMode, SparsedTraceArena, TraceContext, TraceRequirements},
60};
61use foundry_evm_networks::{NetworkConfigs, NetworkVariant};
62use foundry_wallets::{BrowserWalletOpts, WalletOpts};
63use std::str::FromStr;
64
65#[cfg(feature = "base")]
66use foundry_evm::core::evm::BaseEvmNetwork;
67
68#[cfg(feature = "monad")]
69use foundry_evm::core::evm::MonadEvmNetwork;
70
71#[cfg(feature = "optimism")]
72use foundry_evm::core::evm::OpEvmNetwork;
73
74/// CLI arguments for `cast call`.
75///
76/// ## State Override Flags
77///
78/// The following flags can be used to override the state for the call:
79///
80/// * `--override-balance <address>:<balance>` - Override the balance of an account
81/// * `--override-nonce <address>:<nonce>` - Override the nonce of an account
82/// * `--override-code <address>:<code>` - Override the code of an account
83/// * `--override-state <address>:<slot>:<value>` - Override a storage slot of an account
84///
85/// Multiple overrides can be specified for the same account. For example:
86///
87/// ```bash
88/// cast call 0x... "transfer(address,uint256)" 0x... 100 \
89///   --override-balance 0x0000000000000000000000000000000000000001:0x1234 \
90///   --override-nonce 0x0000000000000000000000000000000000000001:1 \
91///   --override-code 0x0000000000000000000000000000000000000001:0x1234 \
92///   --override-state 0x0000000000000000000000000000000000000001:0x1:0x1234 \
93///   --override-state-diff 0x0000000000000000000000000000000000000001:0x1:0x1234
94/// ```
95///
96/// `--delegate` builds on the same mechanism: it overrides the code of the `--from` address with
97/// the destination's code so the call runs as a `delegatecall`.
98#[derive(Debug, Parser)]
99pub struct CallArgs {
100    /// The destination of the transaction.
101    #[arg(value_parser = NameOrAddress::from_str)]
102    to: Option<NameOrAddress>,
103
104    /// The signature of the function to call.
105    sig: Option<String>,
106
107    /// The arguments of the function to call.
108    #[arg(allow_negative_numbers = true)]
109    args: Vec<String>,
110
111    /// Raw hex-encoded data for the transaction. Used instead of `SIG` and `ARGS`.
112    #[arg(
113        long,
114        conflicts_with_all = &["sig", "args"]
115    )]
116    data: Option<String>,
117
118    /// Forks the remote rpc, executes the transaction locally and prints a trace
119    #[arg(long, default_value_t = false)]
120    trace: bool,
121
122    /// Simulate the call as a `delegatecall` from the `--from` address.
123    ///
124    /// The destination's runtime code is applied as a code override on the `--from` address and
125    /// the call is then made to that address, so the destination's code runs in the caller's
126    /// storage context, like an on-chain `delegatecall`.
127    ///
128    /// Note that the executed code observes `msg.sender` (and `tx.origin`) equal to the `--from`
129    /// address itself, whereas in an on-chain `delegatecall` `msg.sender` is preserved from the
130    /// delegating contract's own caller.
131    #[arg(long, requires = "from", conflicts_with = "browser")]
132    delegate: bool,
133
134    /// Fetch the call trace from the node via `debug_traceCall` (callTracer) and render it,
135    /// instead of re-executing the call locally like `--trace`.
136    ///
137    /// This is a call-tree view: nested calls, value, gas, emitted logs and revert data. It does
138    /// not provide the opcode / struct-log level detail of a local `--trace` / `--debug` run.
139    ///
140    /// The local-execution-only trace flags (`--debug`, `--decode-internal`, `--evm-version`) do
141    /// not apply, since the trace comes from the node rather than a local run.
142    #[arg(
143        long = "debug-trace-call",
144        default_value_t = false,
145        conflicts_with_all = ["trace", "debug", "decode_internal", "evm_version"]
146    )]
147    debug_trace_call: bool,
148
149    /// Opens an interactive debugger.
150    /// Can only be used with `--trace`.
151    #[arg(long, requires = "trace")]
152    debug: bool,
153
154    #[command(flatten)]
155    tracing: TracingArgs,
156
157    /// The EVM Version to use.
158    /// Can only be used with `--trace`.
159    #[arg(long, requires = "trace")]
160    evm_version: Option<EvmVersion>,
161
162    /// The block height to query at.
163    ///
164    /// Can also be the tags earliest, finalized, safe, latest, or pending.
165    #[arg(long, short)]
166    block: Option<BlockId>,
167
168    #[command(subcommand)]
169    command: Option<CallSubcommands>,
170
171    #[command(flatten)]
172    tx: TransactionOpts,
173
174    /// Skip the EIP-7702 authorization disclosure confirmation.
175    #[arg(long)]
176    force: bool,
177
178    #[command(flatten)]
179    rpc: RpcOpts,
180
181    #[command(flatten)]
182    wallet: WalletOpts,
183
184    #[command(flatten)]
185    browser: BrowserWalletOpts,
186
187    #[arg(
188        short,
189        long,
190        alias = "chain-id",
191        env = "CHAIN",
192        value_parser = ChainValueParser::default(),
193    )]
194    pub chain: Option<Chain>,
195
196    /// Use current project artifacts for trace decoding.
197    #[arg(long, visible_alias = "la")]
198    pub with_local_artifacts: bool,
199
200    #[command(flatten)]
201    pub overrides: CallOverrideOpts,
202}
203
204#[derive(Debug, Parser)]
205pub enum CallSubcommands {
206    /// ignores the address field and simulates creating a contract
207    #[command(name = "--create")]
208    Create {
209        /// Bytecode of contract.
210        code: String,
211
212        /// The signature of the constructor.
213        sig: Option<String>,
214
215        /// The arguments of the constructor.
216        #[arg(allow_negative_numbers = true)]
217        args: Vec<String>,
218
219        /// Ether to send in the transaction.
220        ///
221        /// Either specified in wei, or as a string with a unit type.
222        ///
223        /// Examples: 1ether, 10gwei, 0.01ether
224        #[arg(long, value_parser = parse_ether_value)]
225        value: Option<U256>,
226    },
227}
228
229/// The `callTracer` options shared by `--debug-trace-call` and its `--curl` rendering.
230fn call_tracer_options() -> GethDebugTracingCallOptions {
231    GethDebugTracingCallOptions::default()
232        .with_tracing_options(GethDebugTracingOptions::call_tracer(call_tracer_config()))
233}
234
235impl CallArgs {
236    fn resolve_tracing(&self, config: &TracingConfig, verbosity: u8) -> TracingConfig {
237        if self.debug_trace_call {
238            self.tracing.resolve_call_tracer(config, verbosity)
239        } else {
240            self.tracing.resolve(config, verbosity)
241        }
242    }
243
244    pub async fn run(mut self) -> Result<()> {
245        self.validate_trace_args()?;
246
247        // Handle --curl mode early, before any provider interaction
248        if self.rpc.curl {
249            if self.trace {
250                eyre::bail!(
251                    "--trace cannot be combined with --curl; use --debug-trace-call --curl instead"
252                );
253            }
254            if self.browser.browser {
255                eyre::bail!("--browser cannot be combined with --curl; use --from <ADDRESS>");
256            }
257            if self.delegate {
258                // The code override that makes the call a `delegatecall` is read from the node,
259                // which `--curl` deliberately never contacts.
260                eyre::bail!("--delegate cannot be combined with --curl");
261            }
262            if !self.tx.auth.is_empty() {
263                eyre::bail!("--auth cannot be combined with --curl");
264            }
265            if self.command.is_some() {
266                eyre::bail!("--create cannot be combined with --curl");
267            }
268            return self.run_curl().await;
269        }
270
271        let figment = self.rpc.clone().into_figment(self.with_local_artifacts).merge(&self);
272        let (mut config, mut evm_opts) = super::load_cast_config_and_evm_opts(figment)?;
273        evm_opts.fork_url = Some(config.get_rpc_url_or_localhost_http()?.into_owned());
274        let has_tempo_session = self.tx.tempo.session_id()?.is_some();
275        let requires_tempo = self.tx.tempo.is_tempo() || has_tempo_session;
276        super::validate_tempo_network(&config, requires_tempo)?;
277        if requires_tempo {
278            evm_opts.networks = NetworkConfigs::with_tempo();
279        } else if !evm_opts.networks.has_network_selection()
280            && let Some(chain) = config.chain
281        {
282            evm_opts.networks =
283                evm_opts.networks.try_with_chain_id(chain.id()).map_err(eyre::Report::msg)?;
284        }
285        if has_tempo_session && self.will_disclose_auth() {
286            eyre::bail!("Tempo sessions cannot be combined with EIP-7702 authorizations");
287        }
288        let Some(auth_preflight) = self.preflight_auth_disclosure().await? else {
289            return Ok(());
290        };
291        evm_opts.infer_network_from_fork().await?;
292        if self.chain.is_none()
293            && let Some(chain_id) = evm_opts.env.chain_id
294        {
295            let chain = Chain::from_id(chain_id);
296            self.chain = Some(chain);
297            config.chain = Some(chain);
298        }
299
300        match evm_opts.networks.execution_network() {
301            NetworkVariant::Tempo => {
302                self.run_with_network_and_opts::<TempoEvmNetwork>(
303                    config,
304                    evm_opts,
305                    auth_preflight,
306                    ExecutorBuilder::<TempoEvmNetwork>::new(),
307                )
308                .await
309            }
310            #[cfg(feature = "base")]
311            NetworkVariant::Base => {
312                super::validate_base_transaction_options(&self.tx)?;
313                self.run_with_network_and_opts::<BaseEvmNetwork>(
314                    config,
315                    evm_opts,
316                    auth_preflight,
317                    ExecutorBuilder::<BaseEvmNetwork>::new(),
318                )
319                .await
320            }
321            #[cfg(feature = "monad")]
322            NetworkVariant::Monad => {
323                self.run_with_network_and_opts::<MonadEvmNetwork>(
324                    config,
325                    evm_opts,
326                    auth_preflight,
327                    ExecutorBuilder::<MonadEvmNetwork>::new(),
328                )
329                .await
330            }
331            #[cfg(feature = "optimism")]
332            NetworkVariant::Optimism => {
333                self.run_with_network_and_opts::<OpEvmNetwork>(
334                    config,
335                    evm_opts,
336                    auth_preflight,
337                    ExecutorBuilder::<OpEvmNetwork>::new(),
338                )
339                .await
340            }
341            NetworkVariant::Ethereum => {
342                self.run_with_network_and_opts::<EthEvmNetwork>(
343                    config,
344                    evm_opts,
345                    auth_preflight,
346                    ExecutorBuilder::<EthEvmNetwork>::new(),
347                )
348                .await
349            }
350        }
351    }
352
353    /// Returns whether resolving this call can disclose an authorization before the transaction
354    /// builder exists. This mirrors the builder's disclosure check after applying `.raw()`.
355    const fn will_disclose_auth(&self) -> bool {
356        !self.tx.auth.is_empty() && (!self.trace || matches!(self.tx.access_list, Some(None)))
357    }
358
359    /// Confirms the authorization disclosure before the network is resolved.
360    ///
361    /// Returns `None` when the user declined, otherwise whether the disclosure was confirmed
362    /// along with the sender resolved for it (absent for browser wallets).
363    async fn preflight_auth_disclosure(
364        &self,
365    ) -> Result<Option<(bool, Option<SenderKind<'static>>)>> {
366        if !self.will_disclose_auth() {
367            return Ok(Some((false, None)));
368        }
369
370        let sender = if self.browser.browser {
371            None
372        } else {
373            Some(SenderKind::from_wallet_opts(self.wallet.clone(), &self.tx.auth).await?)
374        };
375        let browser_sender = SenderKind::from(self.wallet.from.unwrap_or_default());
376        let validation_sender = sender.as_ref().unwrap_or(&browser_sender);
377        if !confirm_auth_rpc_disclosure_before_network_resolution(
378            &self.tx.auth,
379            validation_sender,
380            self.force,
381        )? {
382            return Ok(None);
383        }
384
385        Ok(Some((true, sender)))
386    }
387
388    fn validate_trace_args(&self) -> Result<()> {
389        if !self.trace
390            && !self.debug_trace_call
391            && (self.tracing.disable_labels
392                || self.tracing.compact_labels
393                || !self.tracing.labels.is_empty()
394                || self.tracing.trace_depth.is_some())
395        {
396            eyre::bail!("trace rendering options require `--trace` or `--debug-trace-call`");
397        }
398
399        if self.tracing.decode_internal && !self.trace {
400            eyre::bail!("`--decode-internal` requires `--trace`");
401        }
402
403        Ok(())
404    }
405
406    async fn run_with_network_and_opts<FEN: FoundryEvmNetwork>(
407        self,
408        mut config: Box<Config>,
409        evm_opts: EvmOpts,
410        (auth_confirmed, auth_sender): (bool, Option<SenderKind<'static>>),
411        executor_builder: ExecutorBuilder<FEN>,
412    ) -> Result<()> {
413        config.networks = evm_opts.networks;
414        let mut state_overrides = self.overrides.get_state_overrides()?;
415        let block_overrides = self.overrides.get_block_overrides()?;
416        config.tracing = self.resolve_tracing(&config.tracing, shell::verbosity());
417        let tracing = config.tracing.clone();
418
419        let Self {
420            mut to,
421            mut sig,
422            mut args,
423            mut tx,
424            command,
425            block,
426            trace,
427            debug_trace_call,
428            evm_version,
429            debug,
430            data,
431            with_local_artifacts,
432            wallet,
433            browser,
434            force,
435            delegate,
436            ..
437        } = self;
438
439        if let Some(data) = data {
440            sig = Some(data);
441        }
442
443        let provider = ProviderBuilder::<FEN::Network>::from_config(&config)?.build()?;
444        let endpoint_identity =
445            if debug_trace_call { Some(evm_opts.fork_endpoint_identity().await?) } else { None };
446        let sender = match auth_sender {
447            Some(sender) => sender,
448            None => {
449                let chain_id = match config.chain {
450                    Some(chain) => chain.id(),
451                    None => provider.get_chain_id().await?,
452                };
453                read_only_sender::<FEN::Network>(&browser, wallet, &tx, chain_id).await?.0
454            }
455        };
456        let from = sender.address();
457
458        // A `delegatecall` runs the destination's code against the caller's storage, which
459        // `eth_call` cannot express. Overriding the caller's code with the destination's and
460        // then calling the caller reproduces that context. The retarget to the caller happens
461        // after the transaction is built, so calldata encoding and function resolution still
462        // see the destination.
463        if delegate {
464            if command.is_some() {
465                eyre::bail!("`--delegate` cannot be combined with `--create`");
466            }
467            let Some(target) = to else {
468                eyre::bail!("`--delegate` requires a destination address");
469            };
470            let target = target.resolve(&provider).await?;
471            let overrides = state_overrides.get_or_insert_with(Default::default);
472            if overrides.get(&from).is_some_and(|account| account.code.is_some()) {
473                eyre::bail!("`--delegate` conflicts with `--override-code` for the sender {from}");
474            }
475            // A code override for the destination is the state this call runs against, so it
476            // takes precedence over the deployed code.
477            let code = match overrides.get(&target).and_then(|account| account.code.clone()) {
478                Some(code) => code,
479                None => provider.get_code_at(target).block_id(block.unwrap_or_default()).await?,
480            };
481            if code.is_empty() {
482                eyre::bail!("`--delegate` destination {target} has no code to delegate to");
483            }
484            overrides.entry(from).or_default().code = Some(code);
485            to = Some(NameOrAddress::Address(target));
486        }
487
488        let code = if let Some(CallSubcommands::Create {
489            code,
490            sig: create_sig,
491            args: create_args,
492            value,
493        }) = command
494        {
495            sig = create_sig;
496            args = create_args;
497            if let Some(value) = value {
498                tx.value = Some(value);
499            }
500            Some(code)
501        } else {
502            None
503        };
504
505        let builder = CastTxBuilder::new(&provider, tx, &config)
506            .await?
507            .with_to(to)
508            .await?
509            .with_code_sig_and_args(code, sig, args)
510            .await?
511            .raw();
512        let will_disclose =
513            (!trace && builder.has_auth()) || builder.will_disclose_auth_during_build();
514        if will_disclose
515            && !auth_confirmed
516            && !confirm_auth_rpc_disclosure(&builder, &sender, force)?
517        {
518            return Ok(());
519        }
520        let (mut tx, func) = builder.build(sender).await?;
521
522        // The delegate override put the destination's code on the sender, so the built call is
523        // aimed at the sender; the calldata above was still encoded against the destination.
524        if delegate {
525            tx.set_to(from);
526        }
527
528        if debug_trace_call {
529            let endpoint_identity = endpoint_identity
530                .ok_or_else(|| eyre::eyre!("remote trace endpoint identity was not captured"))?;
531            let requested_block = block.unwrap_or(BlockId::latest());
532            let fetched_block = provider.get_block(requested_block).await?;
533            let resolved_canonical_block =
534                if matches!(requested_block, BlockId::Number(_)) && !requested_block.is_pending() {
535                    fetched_block.as_ref().map(block_num_hash)
536                } else {
537                    None
538                };
539            let block = pin_remote_trace_block(
540                requested_block,
541                fetched_block.as_ref().map(|block| block.header().hash()),
542            )?;
543            let block_time_override = block_overrides.as_ref().and_then(|overrides| overrides.time);
544            let mut call_options = call_tracer_options();
545            // A contract that only exists through a `--override-code` entry has no on-chain
546            // code to fetch for local-artifact matching, so remember the override code before
547            // handing the overrides to `debug_traceCall`.
548            let mut override_bytecode = AddressHashMap::<Bytes>::default();
549            if with_local_artifacts && let Some(overrides) = &state_overrides {
550                for (address, account) in overrides {
551                    if let Some(code) = &account.code {
552                        override_bytecode.insert(*address, code.clone());
553                    }
554                }
555            }
556
557            // Honour the same state / block overrides as the local `--trace` path.
558            if let Some(state_overrides) = state_overrides {
559                call_options = call_options.with_state_overrides(state_overrides);
560            }
561            if let Some(block_overrides) = block_overrides {
562                call_options = call_options.with_block_overrides(block_overrides);
563            }
564
565            let frame = call_tracer_frame(
566                provider.debug_trace_call(tx, block, call_options).await,
567                "debug_traceCall",
568                "drop `--debug-trace-call` to run the call locally with `--trace`",
569                "the requested block; use an archive endpoint, or target a more recent block with `--block`",
570            )?;
571
572            let arena = SparsedTraceArena {
573                arena: call_frame_to_arena(&frame, None),
574                ignored: Default::default(),
575                diagnostics: Default::default(),
576                debug_steps: None,
577            };
578            let result = TraceResult {
579                success: frame.error.is_none() && frame.revert_reason.is_none(),
580                traces: Some(vec![(TraceKind::Execution, arena)]),
581                gas_used: frame.gas_used.saturating_to(),
582            };
583
584            // Local-artifact labeling matches deployed runtime bytecode against the
585            // project artifacts. There is no local executor on this path, so fetch the code
586            // over RPC for the addresses in the trace. Skip the extra round-trips unless
587            // local artifacts were requested.
588            let contracts_bytecode = if with_local_artifacts {
589                let mut contracts_bytecode =
590                    fetch_code_via_rpc(&provider, trace_addresses(&result), block).await;
591                // The trace ran the override code, not the on-chain code, so the override
592                // wins for artifact matching.
593                contracts_bytecode.extend(override_bytecode);
594                contracts_bytecode
595            } else {
596                Default::default()
597            };
598            let final_endpoint_identity = evm_opts.fork_endpoint_identity().await?;
599            ensure_remote_trace_context_unchanged(&endpoint_identity, &final_endpoint_identity)?;
600
601            // The remote node executed this trace, so its reported family is authoritative for
602            // decoding even when the caller selected a compatible local EVM implementation.
603            let chain = alloy_chains::Chain::from_id(endpoint_identity.source_chain_id);
604            let block_timestamp = block_time_override
605                .or_else(|| fetched_block.as_ref().map(|block| block.header().timestamp()));
606            let resolved_hardfork =
607                resolve_remote_trace_hardfork(config.hardfork, &endpoint_identity, block_timestamp);
608            if let Some(resolved_block) = resolved_canonical_block {
609                let canonical_block =
610                    provider.get_block_by_number(resolved_block.number.into()).await?;
611                ensure_remote_trace_block_is_canonical(
612                    resolved_block,
613                    canonical_block.as_ref().map(block_num_hash),
614                )?;
615            }
616            return handle_traces(
617                result,
618                &config,
619                {
620                    let context = TraceContext::new(
621                        chain,
622                        endpoint_identity.network_profile,
623                        resolved_hardfork,
624                    );
625                    context.with_hardfork(context.decoding_hardfork(&config))
626                },
627                &contracts_bytecode,
628                &tracing,
629                with_local_artifacts,
630                false,
631            )
632            .await;
633        }
634
635        if trace {
636            if let Some(BlockId::Number(BlockNumberOrTag::Number(block_number))) = block {
637                // Override Config `fork_block_number` (if set) with CLI value.
638                config.fork_block_number = Some(block_number);
639            }
640
641            let create2_deployer = evm_opts.create2_deployer;
642            let mut fork = TracingExecutor::<FEN>::get_fork(&mut config, evm_opts).await?;
643            // Modify settings usually set in eth_call while keeping execution gas bounded.
644            fork.evm_env.set_feature(EvmFeatures::BLOCK_GAS_LIMIT_CHECK, false);
645            fork.evm_env.version.tx_gas_limit_cap = u64::MAX;
646
647            if let Some(block_overrides) = block_overrides {
648                if let Some(number) = block_overrides.number {
649                    fork.evm_env.block.number = number.to();
650                }
651                if let Some(time) = block_overrides.time {
652                    fork.evm_env.block.timestamp = U256::from(time);
653                }
654            }
655            fork.resolve_spec(&config, evm_version);
656            fork.extend_precompile_labels(&mut config);
657            let context = fork.context();
658
659            let trace_requirements = TraceRequirements::none()
660                .with_calls(true)
661                .with_debug_recording(debug)
662                .with_decode_internal(if tracing.decode_internal {
663                    InternalTraceMode::Full
664                } else {
665                    InternalTraceMode::None
666                })
667                .with_state_changes(tracing.verbosity > 4);
668            let mut executor = fork.into_executor(
669                executor_builder,
670                trace_requirements,
671                create2_deployer,
672                state_overrides,
673            )?;
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 = ProviderBuilder::<AnyNetwork>::from_config(config)?.build()?;
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}