Skip to main content

forge_verify/
bytecode.rs

1//! The `forge verify-bytecode` command.
2use crate::{
3    etherscan::EtherscanVerificationProvider,
4    utils::{
5        BytecodeType, JsonResult, check_and_encode_args, check_explorer_args,
6        load_fork_config_and_evm_opts, maybe_predeploy_contract, validate_encoded_constructor_args,
7    },
8    verify::VerifierArgs,
9};
10use alloy_consensus::Transaction as ConsensusTransaction;
11use alloy_network::{AnyNetwork, AnyRpcBlock, AnyRpcTransaction, TransactionBuilder};
12use alloy_primitives::{Address, B256, Bytes, TxKind, U256, hex};
13use alloy_provider::{
14    Provider,
15    ext::TraceApi,
16    network::{BlockResponse, ReceiptResponse, TransactionResponse, primitives::BlockTransactions},
17};
18use alloy_rpc_types::{
19    BlockId, BlockNumberOrTag,
20    trace::parity::{Action, CreateAction, CreateOutput, TraceOutput},
21};
22use clap::{Parser, ValueHint};
23use evm2::evm::AccountInfo;
24use eyre::{Context, OptionExt, Result};
25use foundry_block_explorers::contract::Metadata;
26use foundry_cli::{
27    opts::EtherscanOpts,
28    utils::{self, LoadConfig, read_constructor_args_file},
29};
30use foundry_common::{
31    FoundryTransactionBuilder, SYSTEM_TRANSACTION_TYPE, is_known_system_sender,
32    provider::RetryProvider, shell,
33};
34use foundry_compilers::info::ContractInfo;
35use foundry_config::{Chain, Config, figment, impl_figment_convert};
36use foundry_evm::{
37    constants::DEFAULT_CREATE2_DEPLOYER,
38    core::evm::{
39        BlockContext, ChainFor, EthEvmNetwork, EvmEnvFor, EvmFactoryFor, FoundryEvmExt,
40        FoundryEvmFactory, FoundryEvmNetwork, FoundryTxConversion, TempoEvmNetwork,
41        TransactionRequestFor, TypesFor, eth_envelope_from_any_rpc,
42    },
43    executors::{Executor, ExecutorBuilder, TracingExecutor},
44    opts::{EvmOpts, ForkEndpointIdentity},
45    utils::apply_chain_specific_tx_replay_env_changes_for_chain,
46};
47use foundry_evm_networks::NetworkVariant;
48use std::path::PathBuf;
49
50#[cfg(feature = "base")]
51use foundry_evm::core::evm::BaseEvmNetwork;
52
53#[cfg(feature = "monad")]
54use foundry_evm::core::evm::MonadEvmNetwork;
55
56#[cfg(feature = "optimism")]
57use foundry_evm::core::evm::OpEvmNetwork;
58
59impl_figment_convert!(VerifyBytecodeArgs);
60
61/// CLI arguments for `forge verify-bytecode`.
62#[derive(Clone, Debug, Parser)]
63pub struct VerifyBytecodeArgs {
64    /// The address of the contract to verify.
65    pub address: Address,
66
67    /// The contract identifier in the form `<path>:<contractname>`.
68    pub contract: ContractInfo,
69
70    /// The block at which the bytecode should be verified.
71    #[arg(long, value_name = "BLOCK")]
72    pub block: Option<BlockId>,
73
74    /// The constructor args to generate the creation code.
75    #[arg(
76        long,
77        num_args(1..),
78        conflicts_with_all = &["constructor_args_path", "encoded_constructor_args"],
79        value_name = "ARGS",
80    )]
81    pub constructor_args: Option<Vec<String>>,
82
83    /// The ABI-encoded constructor arguments.
84    #[arg(
85        long,
86        conflicts_with_all = &["constructor_args_path", "constructor_args"],
87        value_name = "HEX",
88    )]
89    pub encoded_constructor_args: Option<String>,
90
91    /// The path to a file containing the constructor arguments.
92    #[arg(
93        long,
94        value_hint = ValueHint::FilePath,
95        value_name = "PATH",
96        conflicts_with_all = &["constructor_args", "encoded_constructor_args"]
97    )]
98    pub constructor_args_path: Option<PathBuf>,
99
100    /// The rpc url to use for verification.
101    #[arg(short = 'r', long, value_name = "RPC_URL", env = "ETH_RPC_URL")]
102    pub rpc_url: Option<String>,
103
104    /// Specify the network for correct encoding.
105    #[arg(long, short, num_args = 1, value_name = "NETWORK")]
106    pub network: Option<NetworkVariant>,
107
108    /// Etherscan options.
109    #[command(flatten)]
110    pub etherscan: EtherscanOpts,
111
112    /// Verifier options.
113    #[command(flatten)]
114    pub verifier: VerifierArgs,
115
116    /// Set pre-linked libraries.
117    #[arg(long, help_heading = "Linker options")]
118    pub libraries: Vec<String>,
119
120    /// The project's root path.
121    ///
122    /// By default root of the Git repository, if in one,
123    /// or the current working directory.
124    #[arg(long, value_hint = ValueHint::DirPath, value_name = "PATH")]
125    pub root: Option<PathBuf>,
126
127    /// Ignore verification for creation or runtime bytecode.
128    #[arg(long, value_name = "BYTECODE_TYPE")]
129    pub ignore: Option<BytecodeType>,
130}
131
132impl figment::Provider for VerifyBytecodeArgs {
133    fn metadata(&self) -> figment::Metadata {
134        figment::Metadata::named("Verify Bytecode Provider")
135    }
136
137    fn data(
138        &self,
139    ) -> Result<figment::value::Map<figment::Profile, figment::value::Dict>, figment::Error> {
140        let mut dict = self.etherscan.dict();
141
142        if let Some(api_key) = &self.verifier.verifier_api_key {
143            dict.insert("etherscan_api_key".into(), api_key.as_str().into());
144        }
145
146        if let Some(block) = &self.block {
147            dict.insert("block".into(), figment::value::Value::serialize(block)?);
148        }
149        if let Some(rpc_url) = &self.rpc_url {
150            dict.insert("eth_rpc_url".into(), rpc_url.clone().into());
151        }
152
153        Ok(figment::value::Map::from([(Config::selected_profile(), dict)]))
154    }
155}
156
157impl VerifyBytecodeArgs {
158    async fn resolve_evm_opts(config: &Config) -> Result<EvmOpts> {
159        let (_, mut evm_opts) = load_fork_config_and_evm_opts(config)?;
160        evm_opts.networks = config.networks;
161        if evm_opts.fork_url.is_none() {
162            evm_opts.fork_url = Some(config.get_rpc_url_or_localhost_http()?.into_owned());
163        }
164        evm_opts.infer_network_from_fork().await?;
165        Ok(evm_opts)
166    }
167
168    async fn ensure_endpoint_identity_unchanged(
169        config: &Config,
170        expected: Option<&ForkEndpointIdentity>,
171    ) -> Result<()> {
172        let Some(expected) = expected else { return Ok(()) };
173        let current = Self::resolve_evm_opts(config).await?.fork_endpoint.ok_or_else(|| {
174            eyre::eyre!("RPC endpoint identity disappeared while verify-bytecode was running")
175        })?;
176        Self::validate_endpoint_identity(expected, &current)
177    }
178
179    fn validate_endpoint_identity(
180        expected: &ForkEndpointIdentity,
181        current: &ForkEndpointIdentity,
182    ) -> Result<()> {
183        if current != expected {
184            eyre::bail!(
185                "RPC endpoint identity changed while verify-bytecode was running; retry against \
186                 a stable endpoint"
187            );
188        }
189        Ok(())
190    }
191
192    fn apply_endpoint_expectation(
193        evm_opts: &mut EvmOpts,
194        endpoint_identity: Option<&ForkEndpointIdentity>,
195        network_was_inferred: bool,
196    ) {
197        if let Some(identity) = endpoint_identity {
198            evm_opts.expect_fork_endpoint(identity.clone(), network_was_inferred);
199        }
200    }
201
202    fn explorer_chain(
203        configured: Option<Chain>,
204        endpoint_identity: Option<&ForkEndpointIdentity>,
205    ) -> Option<Chain> {
206        configured.or_else(|| endpoint_identity.map(|identity| identity.source_chain_id.into()))
207    }
208
209    /// Run the `verify-bytecode` command to verify the bytecode onchain against the locally built
210    /// bytecode.
211    pub async fn run(mut self) -> Result<()> {
212        let mut config = self.load_config_with_dependencies()?;
213        config.libraries.append(&mut self.libraries);
214
215        if let Some(network) = self.network {
216            config.networks = network.into();
217        }
218        let evm_opts = Self::resolve_evm_opts(&config).await?;
219        let network_was_inferred = evm_opts.fork_network_is_inferred;
220        let endpoint_identity = evm_opts.fork_endpoint;
221        config.networks = evm_opts.networks;
222
223        match config.networks.execution_network() {
224            NetworkVariant::Ethereum => {
225                self.run_with_network::<EthEvmNetwork>(
226                    config,
227                    endpoint_identity,
228                    network_was_inferred,
229                    ExecutorBuilder::<EthEvmNetwork>::new(),
230                )
231                .await
232            }
233            #[cfg(feature = "base")]
234            NetworkVariant::Base => {
235                self.run_with_network::<BaseEvmNetwork>(
236                    config,
237                    endpoint_identity,
238                    network_was_inferred,
239                    ExecutorBuilder::<BaseEvmNetwork>::new(),
240                )
241                .await
242            }
243            #[cfg(feature = "optimism")]
244            NetworkVariant::Optimism => {
245                self.run_with_network::<OpEvmNetwork>(
246                    config,
247                    endpoint_identity,
248                    network_was_inferred,
249                    ExecutorBuilder::<OpEvmNetwork>::new(),
250                )
251                .await
252            }
253            NetworkVariant::Tempo => {
254                self.run_with_network::<TempoEvmNetwork>(
255                    config,
256                    endpoint_identity,
257                    network_was_inferred,
258                    ExecutorBuilder::<TempoEvmNetwork>::new(),
259                )
260                .await
261            }
262            #[cfg(feature = "monad")]
263            NetworkVariant::Monad => {
264                let Some(mut verification) = self
265                    .prepare_runtime_verification::<MonadEvmNetwork>(
266                        config,
267                        endpoint_identity,
268                        network_was_inferred,
269                        ExecutorBuilder::<MonadEvmNetwork>::new(),
270                    )
271                    .await?
272                else {
273                    return Ok(());
274                };
275                let context = replay_monad_block_transactions(
276                    &verification.config,
277                    verification.block.as_ref(),
278                    verification.simulation_block,
279                    verification.transaction.tx_hash(),
280                    &mut verification.executor,
281                    &verification.evm_env,
282                )
283                .await?;
284                verification.finish(context).await
285            }
286        }
287    }
288
289    /// Runs verification for networks whose replay does not require block ancestry.
290    async fn run_with_network<FEN: FoundryEvmNetwork>(
291        self,
292        config: Config,
293        endpoint_identity: Option<ForkEndpointIdentity>,
294        network_was_inferred: bool,
295        executor_builder: ExecutorBuilder<FEN>,
296    ) -> Result<()> {
297        let Some(mut verification) = self
298            .prepare_runtime_verification::<FEN>(
299                config,
300                endpoint_identity,
301                network_was_inferred,
302                executor_builder,
303            )
304            .await?
305        else {
306            return Ok(());
307        };
308        let context = replay_block_transactions(
309            verification.block.as_ref(),
310            verification.transaction.tx_hash(),
311            &mut verification.executor,
312            &verification.evm_env,
313            None,
314        )?;
315        verification.finish(context).await
316    }
317
318    async fn prepare_runtime_verification<FEN>(
319        mut self,
320        config: Config,
321        endpoint_identity: Option<ForkEndpointIdentity>,
322        network_was_inferred: bool,
323        executor_builder: ExecutorBuilder<FEN>,
324    ) -> Result<Option<RuntimeVerification<FEN>>>
325    where
326        FEN: FoundryEvmNetwork,
327    {
328        // Setup
329        // `AnyNetwork` rather than `FEN::Network`: chains such as Arbitrum and Celo put
330        // transaction types the strict Ethereum envelope cannot decode into every block, which
331        // would fail the full block fetches below for the whole chain. Execution still uses `FEN`.
332        let provider = utils::get_provider(&config)?;
333
334        // If chain is not set, we try to get it from the RPC.
335        // If RPC is not set, the default chain is used.
336        let chain = match (
337            Self::explorer_chain(config.chain, endpoint_identity.as_ref()),
338            config.get_rpc_url(),
339        ) {
340            (Some(chain), _) => chain,
341            (None, Some(_)) => utils::get_chain::<AnyNetwork, _>(None, &provider).await?,
342            (None, None) => Default::default(),
343        };
344
345        // Set Etherscan options.
346        self.etherscan.chain = Some(chain);
347        self.etherscan.key = config.get_etherscan_config_with_chain(Some(chain))?.map(|c| c.key);
348
349        // Whether a block explorer is configured for this chain. Client setup errors are only
350        // treated as "no explorer available" when no usable verifier, verifier URL, or resolved
351        // API key is configured.
352        let has_explorer_config = self.verifier.verifier.is_some()
353            || self.verifier.verifier_url.is_some()
354            || self.verifier.verifier_api_key.is_some()
355            || self.etherscan.key.is_some();
356
357        // Etherscan client. May be unavailable (e.g. unknown chain, missing configuration), in
358        // which case verification proceeds with local data only.
359        let etherscan = match EtherscanVerificationProvider.client(
360            &self.etherscan,
361            &self.verifier,
362            &config,
363        ) {
364            Ok(client) => Some(client),
365            Err(err) => {
366                if has_explorer_config {
367                    return Err(err);
368                }
369                if !shell::is_json() {
370                    sh_warn!(
371                        "Failed to create a block explorer client: {err}. Continuing with the local project configuration."
372                    )?;
373                }
374                None
375            }
376        };
377
378        // Get the bytecode at the address, bailing if it doesn't exist.
379        let code = provider.get_code_at(self.address).await?;
380        Self::ensure_endpoint_identity_unchanged(&config, endpoint_identity.as_ref()).await?;
381        if code.is_empty() {
382            eyre::bail!("No bytecode found at address {}", self.address);
383        }
384
385        if !shell::is_json() {
386            sh_status!(
387                "Verifying bytecode for contract {} at address {}",
388                self.contract.name,
389                self.address
390            )?;
391        }
392
393        let mut json_results: Vec<JsonResult> = vec![];
394
395        // Get creation tx hash. An unavailable explorer (missing API key, unsupported chain,
396        // unverified contract, etc.) must not prevent verification against a local build: fall
397        // back to verifying the runtime bytecode only.
398        // See <https://github.com/foundry-rs/foundry/issues/13479>.
399        let (creation_data, maybe_predeploy) = match &etherscan {
400            Some(etherscan) => {
401                let creation_data = etherscan.contract_creation_data(self.address).await;
402
403                // Check if contract is a predeploy
404                match maybe_predeploy_contract(creation_data) {
405                    Ok(res) => res,
406                    Err(err) => {
407                        if has_explorer_config {
408                            return Err(err);
409                        }
410                        if !shell::is_json() {
411                            sh_warn!(
412                                "Failed to fetch creation data from the block explorer: {err}"
413                            )?;
414                        }
415                        (None, false)
416                    }
417                }
418            }
419            None => (None, false),
420        };
421
422        trace!(maybe_predeploy = ?maybe_predeploy);
423
424        // Get the constructor args using `source_code` endpoint.
425        let source_code = match &etherscan {
426            Some(etherscan) => match etherscan.contract_source_code(self.address).await {
427                Ok(source_code) => {
428                    if let Some(metadata) = source_code.items.first() {
429                        // Check if the contract name matches.
430                        if metadata.contract_name != self.contract.name {
431                            eyre::bail!("Contract name mismatch");
432                        }
433                        Some(source_code)
434                    } else {
435                        if !shell::is_json() {
436                            sh_warn!(
437                                "Block explorer returned no source metadata. Continuing with the local project configuration; compiler settings mismatches will not be reported."
438                            )?;
439                        }
440                        None
441                    }
442                }
443                Err(err) => {
444                    if has_explorer_config {
445                        return Err(err.into());
446                    }
447                    if !shell::is_json() {
448                        sh_warn!(
449                            "Failed to fetch contract source code from the block explorer: {err}. Continuing with the local project configuration; compiler settings mismatches will not be reported."
450                        )?;
451                    }
452                    None
453                }
454            },
455            None => None,
456        };
457
458        // Obtain Etherscan compilation metadata.
459        let etherscan_metadata = source_code.as_ref().and_then(|source| source.items.first());
460
461        // Obtain local artifact
462        let artifact = crate::utils::build_project(&self, &config)?;
463
464        // Get local bytecode (creation code)
465        let local_bytecode = artifact
466            .bytecode
467            .as_ref()
468            .and_then(|b| b.to_owned().into_bytes())
469            .ok_or_eyre("Unlinked bytecode is not supported for verification")?;
470
471        // Get and encode user provided constructor args
472        let provided_constructor_args = if let Some(encoded) = &self.encoded_constructor_args {
473            Some(validate_encoded_constructor_args(&artifact, hex::decode(encoded)?)?)
474        } else {
475            if let Some(path) = self.constructor_args_path.clone() {
476                // Read from file.
477                Some(read_constructor_args_file(path)?)
478            } else {
479                self.constructor_args.clone()
480            }
481            .map(|args| check_and_encode_args(&artifact, args))
482            .transpose()?
483        };
484
485        let args_from_user = provided_constructor_args.is_some();
486        let mut constructor_args = if let Some(provided) = provided_constructor_args {
487            provided.into()
488        } else if let Some(source_code) = &source_code {
489            // If no constructor args were provided, try to retrieve them from the explorer.
490            check_explorer_args(source_code)?
491        } else {
492            Bytes::new()
493        };
494
495        // This fails only when the contract expects constructor args but NONE were provided OR
496        // retrieved from explorer (in case of predeploys).
497        crate::utils::check_args_len(&artifact, &constructor_args)?;
498
499        // Without creation data (predeploys, or the explorer being unavailable), the creation
500        // code cannot be verified. Verify the runtime bytecode instead by deploying the local
501        // creation code and comparing the resulting runtime code with the onchain one.
502        if creation_data.is_none() {
503            if !shell::is_json() {
504                if maybe_predeploy {
505                    sh_warn!(
506                        "Attempting to verify predeployed contract at {:?}. Ignoring creation code verification.",
507                        self.address
508                    )?;
509                } else {
510                    sh_warn!("Creation data is unavailable. Ignoring creation code verification.")?;
511                }
512            }
513
514            // Without creation data there is nothing else to verify when the runtime bytecode is
515            // ignored.
516            if self.ignore.is_some_and(|b| b.is_runtime()) {
517                if shell::is_json() {
518                    sh_println!("{}", serde_json::to_string(&json_results)?)?;
519                }
520                return Ok(None);
521            }
522
523            let deploy_block = if maybe_predeploy {
524                // Deploy at genesis
525                0_u64
526            } else {
527                match self.block {
528                    Some(BlockId::Number(BlockNumberOrTag::Number(block))) => block,
529                    Some(_) => {
530                        eyre::bail!("Invalid block number");
531                    }
532                    None => provider.get_block_number().await?,
533                }
534            };
535
536            // Append constructor args to the local_bytecode.
537            trace!(%constructor_args);
538            let mut local_bytecode_vec = local_bytecode.to_vec();
539            local_bytecode_vec.extend_from_slice(&constructor_args);
540
541            let deploy_block_info = provider.get_block(deploy_block.into()).full().await?;
542            let (mut fork_config, mut evm_opts) = load_fork_config_and_evm_opts(&config)?;
543            Self::apply_endpoint_expectation(
544                &mut evm_opts,
545                endpoint_identity.as_ref(),
546                network_was_inferred,
547            );
548            let (evm_env, mut executor) = crate::utils::get_tracing_executor::<FEN>(
549                &mut fork_config,
550                deploy_block,
551                deploy_block,
552                deploy_block_info.as_ref(),
553                evm_opts,
554                executor_builder.clone(),
555            )
556            .await?;
557            Self::ensure_endpoint_identity_unchanged(&config, endpoint_identity.as_ref()).await?;
558
559            // Setup the genesis deployment.
560            let deployer = Address::with_last_byte(0x1);
561            let mut tx = TransactionRequestFor::<FEN>::default();
562            tx.set_from(deployer);
563            tx.set_kind(TxKind::Create);
564            tx.set_input(Bytes::from(local_bytecode_vec));
565            tx.set_nonce(0);
566            tx.set_chain_id(evm_env.chain_id());
567            tx.set_gas_limit(evm_env.block.gas_limit.saturating_to());
568            tx.set_gas_price(evm_env.block.basefee.saturating_to());
569
570            // Seed deployer account with funds
571            let account_info =
572                AccountInfo::default().with_balance(U256::from(100 * 10_u128.pow(18)));
573            executor.backend_mut().insert_account_info(deployer, account_info);
574
575            let fork_address = if maybe_predeploy || deploy_block == 0 {
576                crate::utils::deploy_contract::<FEN>(&mut executor, &evm_env, tx, None)?
577            } else {
578                executor.deploy_with_env(evm_env, tx, None)?.address
579            };
580
581            // Compare runtime bytecode. The onchain code is read at `deploy_block` to stay
582            // anchored to the same height as the local fork. Predeploys keep reading at the
583            // latest block: their code is stable and genesis state often isn't served by RPCs.
584            let (deployed_bytecode, onchain_runtime_code) = crate::utils::get_runtime_codes::<FEN>(
585                &mut executor,
586                &provider,
587                self.address,
588                fork_address,
589                (!maybe_predeploy).then_some(deploy_block),
590            )
591            .await?;
592            Self::ensure_endpoint_identity_unchanged(&config, endpoint_identity.as_ref()).await?;
593
594            let match_type = crate::utils::match_bytecodes(
595                deployed_bytecode.original_byte_slice(),
596                &onchain_runtime_code,
597                &constructor_args,
598                true,
599                config.bytecode_hash,
600            );
601
602            crate::utils::print_result(
603                match_type,
604                BytecodeType::Runtime,
605                &mut json_results,
606                etherscan_metadata,
607                &config,
608            );
609
610            if shell::is_json() {
611                sh_println!("{}", serde_json::to_string(&json_results)?)?;
612            }
613
614            return Ok(None);
615        }
616
617        // We can unwrap directly as maybe_predeploy is false
618        let creation_data = creation_data.unwrap();
619        // Get transaction and receipt.
620        trace!(creation_tx_hash = ?creation_data.transaction_hash);
621        let transaction = provider
622            .get_transaction_by_hash(creation_data.transaction_hash)
623            .await
624            .or_else(|e| {
625                eyre::bail!("Couldn't fetch transaction from RPC: {:?}", e);
626            })?
627            .ok_or_else(|| {
628                eyre::eyre!("Transaction not found for hash {}", creation_data.transaction_hash)
629            })?;
630        let receipt = provider
631            .get_transaction_receipt(creation_data.transaction_hash)
632            .await
633            .or_else(|e| {
634                eyre::bail!("Couldn't fetch transaction receipt from RPC: {:?}", e);
635            })?;
636        let receipt = if let Some(receipt) = receipt {
637            receipt
638        } else {
639            eyre::bail!(
640                "Receipt not found for transaction hash {}",
641                creation_data.transaction_hash
642            );
643        };
644
645        let creation_block = transaction.block_number();
646
647        // Extract creation code from creation tx input.
648        let maybe_creation_code = if receipt.to().is_none()
649            && receipt.contract_address() == Some(self.address)
650        {
651            transaction.input().clone()
652        } else if receipt.to() == Some(DEFAULT_CREATE2_DEPLOYER) {
653            Bytes::copy_from_slice(&transaction.input()[32..])
654        } else {
655            // Try to get creation bytecode from tx trace.
656            let traces = provider
657                .trace_transaction(creation_data.transaction_hash)
658                .await
659                .unwrap_or_default();
660
661            let creation_bytecode =
662                traces.iter().find_map(|trace| match (&trace.trace.result, &trace.trace.action) {
663                    (
664                        Some(TraceOutput::Create(CreateOutput { address, .. })),
665                        Action::Create(CreateAction { init, .. }),
666                    ) if *address == self.address => Some(init.clone()),
667                    _ => None,
668                });
669
670            creation_bytecode.ok_or_else(|| {
671                eyre::eyre!(
672                    "Could not extract the creation code for contract at address {}",
673                    self.address
674                )
675            })?
676        };
677        Self::ensure_endpoint_identity_unchanged(&config, endpoint_identity.as_ref()).await?;
678
679        // In some cases, Etherscan will return incorrect constructor arguments. If this
680        // happens, try extracting arguments ourselves. Never replace user-provided arguments.
681        if !args_from_user && !maybe_creation_code.ends_with(&constructor_args) {
682            trace!("mismatch of constructor args with etherscan");
683            if maybe_creation_code.len() >= local_bytecode.len() {
684                // If local bytecode is longer than on-chain one, this is probably not a match.
685                constructor_args = maybe_creation_code.slice(local_bytecode.len()..);
686                trace!(
687                    target: "forge::verify",
688                    "setting constructor args to latest {} bytes of bytecode",
689                    constructor_args.len()
690                );
691            }
692        }
693
694        // Append constructor args to the local_bytecode.
695        trace!(%constructor_args);
696        let mut local_bytecode_vec = local_bytecode.to_vec();
697        local_bytecode_vec.extend_from_slice(&constructor_args);
698
699        // A suffix check alone is insufficient for dynamic ABI values: one valid encoding can
700        // be a suffix of a different valid encoding. Always compare the complete creation code
701        // when arguments came from the user, even if creation output is ignored.
702        let creation_match_type = crate::utils::match_bytecodes(
703            local_bytecode_vec.as_slice(),
704            &maybe_creation_code,
705            &constructor_args,
706            false,
707            config.bytecode_hash,
708        );
709        if args_from_user
710            && creation_match_type.is_none()
711            && self.ignore.is_none_or(|b| !b.is_creation())
712        {
713            let message =
714                "Provided constructor args could not be validated against deployment creation code";
715            if shell::is_json() {
716                json_results.push(JsonResult {
717                    bytecode_type: BytecodeType::Creation,
718                    match_type: None,
719                    message: Some(message.to_string()),
720                });
721                if self.ignore.is_none_or(|b| !b.is_runtime()) {
722                    json_results.push(JsonResult {
723                        bytecode_type: BytecodeType::Runtime,
724                        match_type: None,
725                        message: Some(message.to_string()),
726                    });
727                }
728                sh_println!("{}", serde_json::to_string(&json_results)?)?;
729            } else {
730                sh_warn!("{message}")?;
731                crate::utils::print_result(
732                    None,
733                    BytecodeType::Creation,
734                    &mut json_results,
735                    etherscan_metadata,
736                    &config,
737                );
738                if self.ignore.is_none_or(|b| !b.is_runtime()) {
739                    crate::utils::print_result(
740                        None,
741                        BytecodeType::Runtime,
742                        &mut json_results,
743                        etherscan_metadata,
744                        &config,
745                    );
746                }
747            }
748            return Ok(None);
749        }
750
751        trace!(ignore = ?self.ignore);
752        // Check if `--ignore` is set to `creation`.
753        if self.ignore.is_none_or(|b| !b.is_creation()) {
754            // Compare creation code with locally built bytecode and `maybe_creation_code`.
755            crate::utils::print_result(
756                creation_match_type,
757                BytecodeType::Creation,
758                &mut json_results,
759                etherscan_metadata,
760                &config,
761            );
762
763            // If the creation code does not match, the runtime also won't match. Hence return.
764            if creation_match_type.is_none() {
765                crate::utils::print_result(
766                    None,
767                    BytecodeType::Runtime,
768                    &mut json_results,
769                    etherscan_metadata,
770                    &config,
771                );
772                if shell::is_json() {
773                    sh_println!("{}", serde_json::to_string(&json_results)?)?;
774                }
775                return Ok(None);
776            }
777        }
778
779        if self.ignore.is_none_or(|b| !b.is_runtime()) {
780            // Runtime verification can only re-deploy local bytecode for direct `CREATE` and the
781            // default `CREATE2` deployer, so skip custom factory deployments.
782            if let TxKind::Call(to) = ConsensusTransaction::kind(&transaction)
783                && to != DEFAULT_CREATE2_DEPLOYER
784            {
785                let message = format!(
786                    "Runtime bytecode verification is not supported for this contract: its \
787                     creation transaction calls custom factory {to}. forge can only verify \
788                     runtime bytecode for direct CREATE transactions and calls to the default \
789                     CREATE2 deployer; skipping runtime bytecode verification."
790                );
791                if shell::is_json() {
792                    json_results.push(JsonResult {
793                        bytecode_type: BytecodeType::Runtime,
794                        match_type: None,
795                        message: Some(message),
796                    });
797                    sh_println!("{}", serde_json::to_string(&json_results)?)?;
798                } else {
799                    sh_warn!("{message}")?;
800                }
801                return Ok(None);
802            }
803
804            // Get contract creation block.
805            let simulation_block = match self.block {
806                Some(BlockId::Number(BlockNumberOrTag::Number(block))) => block,
807                Some(_) => {
808                    eyre::bail!("Invalid block number");
809                }
810                None => creation_block.ok_or_else(|| {
811                    eyre::eyre!(
812                        "Failed to get block number of the contract creation tx, specify using the \
813                         --block flag"
814                    )
815                })?,
816            };
817
818            // Fork the chain immediately before `simulation_block`, then execute with the target
819            // block's environment and effective runtime hardfork.
820            let block = provider.get_block(simulation_block.into()).full().await?;
821            let (mut fork_config, mut evm_opts) = load_fork_config_and_evm_opts(&config)?;
822            Self::apply_endpoint_expectation(
823                &mut evm_opts,
824                endpoint_identity.as_ref(),
825                network_was_inferred,
826            );
827            let (mut evm_env, executor) = crate::utils::get_tracing_executor::<FEN>(
828                &mut fork_config,
829                simulation_block - 1, // env.fork_block_number
830                simulation_block,
831                block.as_ref(),
832                evm_opts,
833                executor_builder,
834            )
835            .await?;
836            Self::ensure_endpoint_identity_unchanged(&config, endpoint_identity.as_ref()).await?;
837
838            apply_chain_specific_tx_replay_env_changes_for_chain(&mut evm_env, chain.id());
839            return Ok(Some(RuntimeVerification {
840                address: self.address,
841                config,
842                endpoint_identity,
843                provider,
844                executor,
845                evm_env,
846                block,
847                simulation_block,
848                transaction,
849                local_bytecode_vec,
850                constructor_args,
851                json_results,
852                etherscan_metadata: source_code.and_then(|source| source.items.into_iter().next()),
853            }));
854        }
855        if shell::is_json() {
856            sh_println!("{}", serde_json::to_string(&json_results)?)?;
857        }
858        Ok(None)
859    }
860}
861
862/// Prepared runtime verification, before replaying the creation block's prefix.
863struct RuntimeVerification<FEN: FoundryEvmNetwork> {
864    address: Address,
865    config: Config,
866    endpoint_identity: Option<ForkEndpointIdentity>,
867    provider: RetryProvider,
868    executor: TracingExecutor<FEN>,
869    evm_env: EvmEnvFor<FEN>,
870    block: Option<AnyRpcBlock>,
871    simulation_block: u64,
872    transaction: AnyRpcTransaction,
873    local_bytecode_vec: Vec<u8>,
874    constructor_args: Bytes,
875    json_results: Vec<JsonResult>,
876    etherscan_metadata: Option<Metadata>,
877}
878
879impl<FEN: FoundryEvmNetwork> RuntimeVerification<FEN> {
880    /// Deploys the local creation code in place of the creation transaction's, executing it with
881    /// `ext` or extension state prepared for it, and compares the runtime code.
882    async fn finish(self, ext: Option<ChainFor<FEN>>) -> Result<()> {
883        let Self {
884            address,
885            config,
886            endpoint_identity,
887            provider,
888            mut executor,
889            evm_env,
890            simulation_block,
891            transaction,
892            local_bytecode_vec,
893            constructor_args,
894            mut json_results,
895            etherscan_metadata,
896            ..
897        } = self;
898        // Keep the network-native transaction and replace only its sender and input.
899        let mut tx: TransactionRequestFor<FEN> =
900            TypesFor::<FEN>::envelope_from_any_rpc(&transaction)?.into();
901        // The request conversion drops CREATE's kind. Restore it only for transactions with an
902        // Ethereum envelope, including Celo CIP-64 transactions, preserving native batches.
903        if let Ok(envelope) = eth_envelope_from_any_rpc(&transaction, "Ethereum") {
904            tx.set_kind(ConsensusTransaction::kind(&envelope));
905        }
906        tx.set_from(TransactionResponse::from(&transaction));
907
908        // Replace the `input` with local creation code in the creation tx, which is the first call
909        // of a Tempo AA transaction.
910        let (kind, input) = crate::utils::creation_call::<FEN>(&tx);
911        if let TxKind::Call(to) = kind {
912            if to == DEFAULT_CREATE2_DEPLOYER {
913                let mut input = input[..32].to_vec(); // Salt
914                input.extend_from_slice(&local_bytecode_vec);
915                tx.set_first_call_input(Bytes::from(input));
916
917                // Deploy default CREATE2 deployer
918                executor.deploy_create2_deployer()?;
919            }
920        } else {
921            tx.set_first_call_input(Bytes::from(local_bytecode_vec));
922        }
923
924        let fork_address = crate::utils::deploy_contract::<FEN>(&mut executor, &evm_env, tx, ext)?;
925
926        // State committed using deploy_with_env, now get the runtime bytecode from the db.
927        let (fork_runtime_code, onchain_runtime_code) = crate::utils::get_runtime_codes::<FEN>(
928            &mut executor,
929            &provider,
930            address,
931            fork_address,
932            Some(simulation_block),
933        )
934        .await?;
935        VerifyBytecodeArgs::ensure_endpoint_identity_unchanged(&config, endpoint_identity.as_ref())
936            .await?;
937
938        // Compare the onchain runtime bytecode with the runtime code from the fork.
939        let match_type = crate::utils::match_bytecodes(
940            fork_runtime_code.original_byte_slice(),
941            &onchain_runtime_code,
942            &constructor_args,
943            true,
944            config.bytecode_hash,
945        );
946
947        crate::utils::print_result(
948            match_type,
949            BytecodeType::Runtime,
950            &mut json_results,
951            etherscan_metadata.as_ref(),
952            &config,
953        );
954        if shell::is_json() {
955            sh_println!("{}", serde_json::to_string(&json_results)?)?;
956        }
957        Ok(())
958    }
959}
960
961/// Replays the transactions preceding `target_hash` in `block` and returns the extension state
962/// prepared for the target, positioned in `context` when the network's execution depends on the
963/// block position.
964///
965/// System transactions are skipped, except canonical protocol transactions of the network, such as
966/// Monad's staking syscalls, which replay.
967fn replay_block_transactions<FEN: FoundryEvmNetwork>(
968    block: Option<&AnyRpcBlock>,
969    target_hash: B256,
970    executor: &mut Executor<FEN>,
971    evm_env: &EvmEnvFor<FEN>,
972    context: Option<&BlockContext<FEN>>,
973) -> Result<Option<ChainFor<FEN>>> {
974    let Some(block) = block else { return Ok(None) };
975    let BlockTransactions::Full(txs) = block.transactions() else {
976        return Err(eyre::eyre!("Could not get block txs"));
977    };
978    let target_index = txs
979        .iter()
980        .position(|tx| tx.tx_hash() == target_hash)
981        .ok_or_else(|| eyre::eyre!("transaction {target_hash:?} is missing from its block"))?;
982    let ext_at = |index| {
983        context.map(|context| {
984            let mut ext = EvmFactoryFor::<FEN>::default().evm_ext(evm_env);
985            context.prepare(&mut ext, index);
986            ext
987        })
988    };
989
990    for (index, tx) in txs[..target_index].iter().enumerate() {
991        trace!("replay tx::: {}", tx.tx_hash());
992        if tx.transaction_type() == Some(SYSTEM_TRANSACTION_TYPE) {
993            continue;
994        }
995        let replayed = if is_known_system_sender(tx.from()) {
996            // Only canonical protocol transactions replay; other system envelopes have no native
997            // representation.
998            match TypesFor::<FEN>::tx_from_any_rpc(tx) {
999                Ok(replayed) if ChainFor::<FEN>::is_protocol_transaction(&replayed) => replayed,
1000                _ => continue,
1001            }
1002        } else {
1003            TypesFor::<FEN>::tx_from_any_rpc(tx)?
1004        };
1005        let ext = ext_at(index).map(|mut ext| {
1006            // The canonical block is trusted history, so its protocol transactions replay.
1007            ext.set_protocol_replay(ChainFor::<FEN>::is_protocol_transaction(&replayed));
1008            ext
1009        });
1010
1011        // Transact creations too: batched transactions can mix a creation with calls, so their
1012        // result need not be a deployment. Reverted transactions are committed and replay
1013        // continues.
1014        executor.transact_tx(*evm_env, &replayed, ext).wrap_err_with(|| {
1015            format!(
1016                "Failed to execute transaction: {:?} in block {}",
1017                tx.tx_hash(),
1018                evm_env.block.number
1019            )
1020        })?;
1021    }
1022
1023    Ok(ext_at(target_index))
1024}
1025
1026/// Replays Monad transactions preceding `target_hash` with their ancestry context.
1027#[cfg(feature = "monad")]
1028async fn replay_monad_block_transactions(
1029    config: &Config,
1030    block: Option<&AnyRpcBlock>,
1031    block_number: u64,
1032    target_hash: B256,
1033    executor: &mut Executor<MonadEvmNetwork>,
1034    evm_env: &EvmEnvFor<MonadEvmNetwork>,
1035) -> Result<Option<ChainFor<MonadEvmNetwork>>> {
1036    let block = block.ok_or_else(|| {
1037        eyre::eyre!("block {block_number} is required to reconstruct transaction context")
1038    })?;
1039    let context = monad_block_context(config, block).await?;
1040    replay_block_transactions(Some(block), target_hash, executor, evm_env, Some(&context))
1041}
1042
1043/// Fetches the block context Monad needs to reconstruct replay ordering.
1044#[cfg(feature = "monad")]
1045async fn monad_block_context(
1046    config: &Config,
1047    block: &AnyRpcBlock,
1048) -> Result<BlockContext<MonadEvmNetwork>> {
1049    let provider = utils::get_provider(config)?;
1050    BlockContext::<MonadEvmNetwork>::fetch(&provider, block).await
1051}
1052
1053#[cfg(test)]
1054mod tests {
1055    use super::*;
1056    use alloy_network::{AnyHeader, AnyRpcHeader};
1057    use foundry_evm::core::backend::Backend;
1058    use foundry_evm_networks::NetworkConfigs;
1059    use foundry_test_utils::rpc::{
1060        spawn_rpc_proxy_canned_method, spawn_rpc_proxy_method_not_found_before,
1061    };
1062    use std::sync::atomic::Ordering;
1063
1064    fn replay_block(transactions: Vec<AnyRpcTransaction>) -> AnyRpcBlock {
1065        AnyRpcBlock::new(
1066            alloy_rpc_types::Block::new(
1067                AnyRpcHeader::from_sealed(AnyHeader::default().seal(B256::ZERO)),
1068                BlockTransactions::Full(transactions),
1069            )
1070            .into(),
1071        )
1072    }
1073
1074    fn replay_transaction(
1075        caller: Address,
1076        nonce: u64,
1077        hash: B256,
1078        transaction_type: u8,
1079    ) -> AnyRpcTransaction {
1080        serde_json::from_value(serde_json::json!({
1081            "type": format!("0x{transaction_type:x}"),
1082            "hash": hash, "nonce": format!("0x{nonce:x}"),
1083            "from": caller, "to": Address::with_last_byte(0x43),
1084            "value": "0x7", "gas": "0x5208", "gasPrice": "0x0", "input": "0x",
1085            "v": "0x1b", "r": "0x1", "s": "0x1"
1086        }))
1087        .unwrap()
1088    }
1089
1090    #[test]
1091    fn replay_prefix_excludes_target_and_skips_system_envelopes() {
1092        let caller = Address::with_last_byte(0x42);
1093        let recipient = Address::with_last_byte(0x43);
1094        let target = B256::with_last_byte(2);
1095        let mut env = EvmOpts::default().local_evm_env::<EthEvmNetwork>();
1096        env.block.gas_limit = U256::from(30_000_000);
1097        let mut executor = ExecutorBuilder::<EthEvmNetwork>::new().build(
1098            env,
1099            Default::default(),
1100            Backend::spawn(None, env).unwrap(),
1101            Default::default(),
1102        );
1103        executor.backend_mut().insert_account_info(
1104            caller,
1105            AccountInfo { balance: U256::from(100), ..Default::default() },
1106        );
1107        let block = replay_block(vec![
1108            // Unsupported envelopes from known system senders must be skipped before conversion.
1109            replay_transaction(foundry_common::MONAD_SYSTEM_ADDRESS, 0, B256::ZERO, u8::MAX),
1110            // System transaction types must also be skipped for otherwise ordinary senders.
1111            replay_transaction(caller, 0, B256::with_last_byte(4), SYSTEM_TRANSACTION_TYPE),
1112            replay_transaction(caller, 0, B256::with_last_byte(1), 0),
1113            replay_transaction(caller, 1, target, 0),
1114            replay_transaction(caller, 2, B256::with_last_byte(3), 0),
1115        ]);
1116
1117        replay_block_transactions(Some(&block), target, &mut executor, &env, None).unwrap();
1118
1119        assert_eq!(executor.get_balance(recipient).unwrap(), U256::from(7));
1120        assert_eq!(executor.get_nonce(caller).unwrap(), 1);
1121    }
1122
1123    #[test]
1124    fn replay_missing_target_does_not_execute_prefix() {
1125        let caller = Address::with_last_byte(0x42);
1126        let mut env = EvmOpts::default().local_evm_env::<EthEvmNetwork>();
1127        env.block.gas_limit = U256::from(30_000_000);
1128        let mut executor = ExecutorBuilder::<EthEvmNetwork>::new().build(
1129            env,
1130            Default::default(),
1131            Backend::spawn(None, env).unwrap(),
1132            Default::default(),
1133        );
1134        executor.backend_mut().insert_account_info(
1135            caller,
1136            AccountInfo { balance: U256::from(100), ..Default::default() },
1137        );
1138        let block = replay_block(vec![replay_transaction(caller, 0, B256::ZERO, 0)]);
1139
1140        let error = replay_block_transactions(
1141            Some(&block),
1142            B256::with_last_byte(1),
1143            &mut executor,
1144            &env,
1145            None,
1146        )
1147        .unwrap_err();
1148
1149        assert!(error.to_string().contains("missing from its block"), "{error:?}");
1150        assert_eq!(executor.get_nonce(caller).unwrap(), 0);
1151        assert_eq!(executor.get_balance(caller).unwrap(), U256::from(100));
1152    }
1153
1154    #[test]
1155    #[cfg(feature = "monad")]
1156    fn monad_replay_prefix_replays_canonical_protocol_envelopes() {
1157        let system = foundry_common::MONAD_SYSTEM_ADDRESS;
1158        let staking = alloy_primitives::address!("0x0000000000000000000000000000000000001000");
1159        let target = B256::with_last_byte(3);
1160        let env = EvmOpts::default().local_evm_env::<MonadEvmNetwork>();
1161        let mut executor = ExecutorBuilder::<MonadEvmNetwork>::new().build(
1162            env,
1163            Default::default(),
1164            Backend::spawn(None, env).unwrap(),
1165            Default::default(),
1166        );
1167        // Historical staking state is funded; EIP-161 prunes a touched empty account's storage.
1168        executor.set_balance(staking, U256::ONE).unwrap();
1169        let system_transaction = |nonce: u64, hash: B256, gas: u64| -> AnyRpcTransaction {
1170            serde_json::from_value(serde_json::json!({
1171                "type": "0x0",
1172                "hash": hash, "nonce": format!("0x{nonce:x}"),
1173                "from": system, "to": staking,
1174                "value": "0x0", "gas": format!("0x{gas:x}"), "gasPrice": "0x0",
1175                "input": hex::encode_prefixed(&alloy_primitives::keccak256("syscallSnapshot()")[..4]),
1176                "v": "0x1b", "r": "0x1", "s": "0x1"
1177            }))
1178            .unwrap()
1179        };
1180        let block = replay_block(vec![
1181            // A gas-paying envelope from the system sender is not a protocol system call.
1182            system_transaction(0, B256::with_last_byte(1), 100_000),
1183            system_transaction(0, B256::with_last_byte(2), 0),
1184            system_transaction(1, target, 0),
1185        ]);
1186        let context = BlockContext::new(Vec::new(), Vec::new(), Vec::new());
1187
1188        replay_block_transactions(Some(&block), target, &mut executor, &env, Some(&context))
1189            .unwrap();
1190
1191        // Only the canonical snapshot ran: it advanced the protocol nonce and entered the epoch
1192        // boundary.
1193        assert_eq!(executor.get_nonce(system).unwrap(), 1);
1194        assert_eq!(executor.get_balance(staking).unwrap(), U256::ONE);
1195        assert_eq!(executor.backend().storage(staking, U256::from(2)).unwrap(), U256::ONE << 248);
1196    }
1197
1198    #[test]
1199    fn can_parse_tempo_network() {
1200        let args = VerifyBytecodeArgs::parse_from([
1201            "foundry-cli",
1202            "0x0000000000000000000000000000000000000000",
1203            "src/Counter.sol:Counter",
1204            "--network",
1205            "tempo",
1206        ]);
1207
1208        assert_eq!(args.network, Some(NetworkVariant::Tempo));
1209    }
1210
1211    #[test]
1212    #[cfg(feature = "monad")]
1213    fn can_parse_monad_network() {
1214        let args = VerifyBytecodeArgs::parse_from([
1215            "foundry-cli",
1216            "0x0000000000000000000000000000000000000000",
1217            "src/Counter.sol:Counter",
1218            "--network",
1219            "monad",
1220        ]);
1221
1222        assert_eq!(args.network, Some(NetworkVariant::Monad));
1223    }
1224
1225    #[tokio::test]
1226    async fn fork_resolution_preserves_configured_profiles_and_revalidates() {
1227        for networks in [
1228            NetworkConfigs::default(),
1229            NetworkConfigs::with_ethereum(),
1230            NetworkConfigs::with_celo(),
1231            NetworkConfigs::with_tempo(),
1232            #[cfg(feature = "base")]
1233            NetworkConfigs::with_base(),
1234            #[cfg(feature = "monad")]
1235            NetworkConfigs::with_monad(),
1236            #[cfg(feature = "optimism")]
1237            NetworkConfigs::with_optimism(),
1238        ] {
1239            let (endpoint, chain_requests) = spawn_rpc_proxy_canned_method(
1240                String::new(),
1241                "eth_chainId",
1242                serde_json::json!("0x7a69"),
1243            )
1244            .await;
1245            let endpoint =
1246                spawn_rpc_proxy_method_not_found_before(endpoint, "anvil_nodeInfo", usize::MAX)
1247                    .await;
1248            let config = Config { eth_rpc_url: Some(endpoint), networks, ..Default::default() };
1249            let opts = VerifyBytecodeArgs::resolve_evm_opts(&config).await.unwrap();
1250            assert_eq!(opts.networks.execution_network(), networks.execution_network());
1251            assert_eq!(opts.networks.is_celo(), networks.is_celo());
1252            assert_eq!(opts.fork_network_is_inferred, !networks.has_network_selection());
1253            assert_eq!(opts.fork_endpoint.as_ref().unwrap().source_chain_id, 31337);
1254            assert_eq!(chain_requests.load(Ordering::Relaxed), 1);
1255
1256            let config = Config { networks: opts.networks, ..config };
1257
1258            VerifyBytecodeArgs::ensure_endpoint_identity_unchanged(
1259                &config,
1260                opts.fork_endpoint.as_ref(),
1261            )
1262            .await
1263            .unwrap();
1264            assert_eq!(chain_requests.load(Ordering::Relaxed), 2);
1265        }
1266    }
1267
1268    #[test]
1269    fn verify_bytecode_requires_stable_endpoint_identity() {
1270        let expected = ForkEndpointIdentity {
1271            endpoint: "http://localhost:8545".to_string(),
1272            execution_chain_id: 1,
1273            source_chain_id: 1,
1274            network: NetworkVariant::Ethereum,
1275            network_profile: Default::default(),
1276            reported_hardfork: Some("FutureA".to_string()),
1277            hardfork: None,
1278            instance_id: Some(B256::with_last_byte(1)),
1279            source_fork_block_number: None,
1280            source_fork_block_hash: None,
1281        };
1282
1283        assert!(VerifyBytecodeArgs::validate_endpoint_identity(&expected, &expected).is_ok());
1284
1285        let mut reset = expected.clone();
1286        reset.instance_id = Some(B256::with_last_byte(2));
1287        assert!(VerifyBytecodeArgs::validate_endpoint_identity(&expected, &reset).is_err());
1288
1289        let mut changed_hardfork = expected.clone();
1290        changed_hardfork.reported_hardfork = Some("FutureB".to_string());
1291        assert!(
1292            VerifyBytecodeArgs::validate_endpoint_identity(&expected, &changed_hardfork).is_err()
1293        );
1294
1295        let mut evm_opts = EvmOpts::default();
1296        VerifyBytecodeArgs::apply_endpoint_expectation(&mut evm_opts, Some(&expected), true);
1297        assert_eq!(evm_opts.expected_fork_endpoint, Some(expected));
1298        assert!(evm_opts.fork_network_is_inferred);
1299    }
1300
1301    #[test]
1302    #[cfg(feature = "monad")]
1303    fn nested_endpoint_separates_execution_family_from_explorer_chain() {
1304        let identity = ForkEndpointIdentity {
1305            endpoint: "http://localhost:8545".to_string(),
1306            execution_chain_id: 1,
1307            source_chain_id: 143,
1308            network: NetworkVariant::Monad,
1309            network_profile: NetworkVariant::Monad.into(),
1310            reported_hardfork: None,
1311            hardfork: None,
1312            instance_id: None,
1313            source_fork_block_number: Some(123),
1314            source_fork_block_hash: None,
1315        };
1316
1317        assert_eq!(VerifyBytecodeArgs::explorer_chain(None, Some(&identity)).unwrap().id(), 143);
1318        assert_eq!(
1319            VerifyBytecodeArgs::explorer_chain(Some(Chain::from_id(1)), Some(&identity))
1320                .unwrap()
1321                .id(),
1322            1
1323        );
1324    }
1325}