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