Skip to main content

forge_verify/
utils.rs

1use crate::{bytecode::VerifyBytecodeArgs, types::VerificationType};
2use alloy_dyn_abi::{DynSolValue, JsonAbiExt};
3use alloy_network::{AnyNetwork, AnyRpcBlock, TransactionBuilder};
4use alloy_primitives::{Address, B256, Bytes, ChainId, TxKind, U256};
5use alloy_provider::{Provider, network::BlockResponse};
6use alloy_rpc_types::BlockId;
7use clap::ValueEnum;
8use evm2::bytecode::Bytecode;
9use eyre::{OptionExt, Result};
10use foundry_block_explorers::{
11    contract::{ContractCreationData, ContractMetadata, Metadata},
12    errors::EtherscanError,
13    utils::lookup_compiler_version,
14};
15use foundry_cli::utils::LoadConfig;
16use foundry_common::{
17    FoundryTransactionBuilder, abi::encode_args, compile::ProjectCompiler,
18    find_matching_contract_artifact, ignore_metadata_hash, shell,
19};
20use foundry_compilers::{
21    Graph,
22    artifacts::{BytecodeHash, CompactContractBytecode},
23    compilers::ParsedSource,
24    multi::{MultiCompilerLanguage, MultiCompilerParser},
25    utils::canonicalize,
26};
27use foundry_config::Config;
28use foundry_evm::{
29    constants::DEFAULT_CREATE2_DEPLOYER,
30    core::{
31        decode::RevertDecoder,
32        evm::{
33            ChainFor, EvmEnvFor, FoundryEvmNetwork, FoundryTxConversion, TransactionRequestFor,
34            TypesFor,
35        },
36    },
37    executors::{ExecutorBuilder, TracingExecutor},
38    opts::EvmOpts,
39    traces::TraceRequirements,
40    utils::{apply_chain_and_block_specific_env_changes_for_chain, block_env_from_header},
41};
42use foundry_evm_networks::NetworkConfigs;
43use reqwest::Url;
44use semver::{BuildMetadata, Version};
45use serde::{Deserialize, Serialize};
46use yansi::Paint;
47
48#[cfg(all(test, feature = "monad"))]
49use foundry_config::FoundryHardfork;
50
51/// Enum to represent the type of bytecode being verified
52#[derive(Debug, Serialize, Deserialize, Clone, Copy, ValueEnum)]
53pub enum BytecodeType {
54    #[serde(rename = "creation")]
55    Creation,
56    #[serde(rename = "runtime")]
57    Runtime,
58}
59
60impl BytecodeType {
61    /// Check if the bytecode type is creation
62    pub const fn is_creation(&self) -> bool {
63        matches!(self, Self::Creation)
64    }
65
66    /// Check if the bytecode type is runtime
67    pub const fn is_runtime(&self) -> bool {
68        matches!(self, Self::Runtime)
69    }
70}
71
72#[derive(Debug, Serialize, Deserialize)]
73pub struct JsonResult {
74    pub bytecode_type: BytecodeType,
75    pub match_type: Option<VerificationType>,
76    #[serde(skip_serializing_if = "Option::is_none")]
77    pub message: Option<String>,
78}
79
80pub fn match_bytecodes(
81    local_bytecode: &[u8],
82    bytecode: &[u8],
83    constructor_args: &[u8],
84    is_runtime: bool,
85    bytecode_hash: BytecodeHash,
86) -> Option<VerificationType> {
87    // 1. Try full match
88    if local_bytecode == bytecode {
89        // If the bytecode_hash = 'none' in Config. Then it's always a partial match according to
90        // sourcify definitions. Ref: https://docs.sourcify.dev/docs/full-vs-partial-match/.
91        if bytecode_hash == BytecodeHash::None {
92            return Some(VerificationType::Partial);
93        }
94
95        Some(VerificationType::Full)
96    } else {
97        is_partial_match(local_bytecode, bytecode, constructor_args, is_runtime)
98            .then_some(VerificationType::Partial)
99    }
100}
101
102pub fn build_project(
103    args: &VerifyBytecodeArgs,
104    config: &Config,
105) -> Result<CompactContractBytecode> {
106    let project = config.project()?;
107    let compiler = ProjectCompiler::new().quiet(true);
108
109    let target_path = match args.contract.path() {
110        Some(path) => Some(canonicalize(project.root().join(path))?),
111        None => Graph::<MultiCompilerParser>::resolve(&project.paths).ok().and_then(|graph| {
112            if graph
113                .nodes
114                .iter()
115                .any(|node| matches!(node.data.language(), MultiCompilerLanguage::Vyper(_)))
116            {
117                return None;
118            }
119            let mut matches = graph.nodes.iter().filter(|node| {
120                node.data.contract_names().iter().any(|name| name == &args.contract.name)
121            });
122            let target = matches.next()?;
123            (matches.next().is_none()
124                && graph.input_nodes().any(|input| input.path() == target.path()))
125            .then(|| target.path().to_path_buf())
126        }),
127    };
128    if let Some(target_path) = target_path {
129        let mut output = compiler.files([target_path.clone()]).compile(&project)?;
130        let artifact =
131            find_matching_contract_artifact(&mut output, &target_path, Some(&args.contract.name))?;
132        return Ok(artifact.into_contract_bytecode());
133    }
134
135    let mut output = compiler.compile(&project)?;
136
137    let artifact = output
138        .remove_contract(&args.contract)
139        .ok_or_eyre("Build Error: Contract artifact not found locally")?;
140
141    Ok(artifact.into_contract_bytecode())
142}
143
144pub fn print_result(
145    res: Option<VerificationType>,
146    bytecode_type: BytecodeType,
147    json_results: &mut Vec<JsonResult>,
148    etherscan_metadata: Option<&Metadata>,
149    config: &Config,
150) {
151    if let Some(res) = res {
152        if shell::is_json() {
153            let json_res = JsonResult { bytecode_type, match_type: Some(res), message: None };
154            json_results.push(json_res);
155        } else {
156            let _ = sh_println!(
157                "{} with status {}",
158                format!("{bytecode_type:?} code matched").green().bold(),
159                res.green().bold()
160            );
161        }
162    } else if !shell::is_json() {
163        let _ = sh_err!(
164            "{bytecode_type:?} code did not match - this may be due to varying compiler settings"
165        );
166        if let Some(etherscan_metadata) = etherscan_metadata {
167            let mismatches = find_mismatch_in_settings(etherscan_metadata, config);
168            for mismatch in mismatches {
169                let _ = sh_eprintln!("{}", mismatch.red().bold());
170            }
171        }
172    } else {
173        let json_res = JsonResult {
174            bytecode_type,
175            match_type: res,
176            message: Some(format!(
177                "{bytecode_type:?} code did not match - this may be due to varying compiler settings"
178            )),
179        };
180        json_results.push(json_res);
181    }
182}
183
184fn is_partial_match(
185    mut local_bytecode: &[u8],
186    mut bytecode: &[u8],
187    constructor_args: &[u8],
188    is_runtime: bool,
189) -> bool {
190    // 1. Check length of constructor args
191    if constructor_args.is_empty() || is_runtime {
192        // Assume metadata is at the end of the bytecode
193        return try_extract_and_compare_bytecode(local_bytecode, bytecode);
194    }
195
196    // The constructor args are part of what is being verified: the onchain creation code must
197    // actually end with them before they can be stripped, otherwise args of the right length
198    // could never fail the comparison.
199    if !bytecode.ends_with(constructor_args) {
200        return false;
201    }
202
203    // If not runtime, extract constructor args from the end of the bytecode.
204    // The args come from the caller, so neither buffer is known to be that long.
205    let (Some(bytecode_head), Some(local_head)) = (
206        bytecode.len().checked_sub(constructor_args.len()).map(|n| &bytecode[..n]),
207        local_bytecode.len().checked_sub(constructor_args.len()).map(|n| &local_bytecode[..n]),
208    ) else {
209        return false;
210    };
211    bytecode = bytecode_head;
212    local_bytecode = local_head;
213
214    try_extract_and_compare_bytecode(local_bytecode, bytecode)
215}
216
217fn try_extract_and_compare_bytecode(mut local_bytecode: &[u8], mut bytecode: &[u8]) -> bool {
218    local_bytecode = ignore_metadata_hash(local_bytecode);
219    bytecode = ignore_metadata_hash(bytecode);
220
221    // Now compare the local code and bytecode
222    local_bytecode == bytecode
223}
224
225fn find_mismatch_in_settings(
226    etherscan_settings: &Metadata,
227    local_settings: &Config,
228) -> Vec<String> {
229    let mut mismatches: Vec<String> = vec![];
230    if etherscan_settings.evm_version != local_settings.evm_version.to_string().to_lowercase() {
231        let str = format!(
232            "EVM version mismatch: local={}, onchain={}",
233            local_settings.evm_version, etherscan_settings.evm_version
234        );
235        mismatches.push(str);
236    }
237    let local_optimizer: u64 = if local_settings.optimizer == Some(true) { 1 } else { 0 };
238    if etherscan_settings.optimization_used != local_optimizer {
239        let str = format!(
240            "Optimizer mismatch: local={}, onchain={}",
241            local_settings.optimizer.unwrap_or(false),
242            etherscan_settings.optimization_used
243        );
244        mismatches.push(str);
245    }
246    // The only caller reaches this with a `Config` from `load_config`, which has run
247    // `normalize_optimizer_settings`, so `optimizer_runs` is always set by now.
248    if let Some(local_runs) = local_settings.optimizer_runs
249        && etherscan_settings.runs != local_runs as u64
250    {
251        let str = format!(
252            "Optimizer runs mismatch: local={local_runs}, onchain={}",
253            etherscan_settings.runs
254        );
255        mismatches.push(str);
256    }
257
258    mismatches
259}
260
261pub fn maybe_predeploy_contract(
262    creation_data: Result<ContractCreationData, EtherscanError>,
263) -> Result<(Option<ContractCreationData>, bool), eyre::ErrReport> {
264    let mut maybe_predeploy = false;
265    match creation_data {
266        Ok(creation_data) => Ok((Some(creation_data), maybe_predeploy)),
267        // Ref: https://explorer.mode.network/api?module=contract&action=getcontractcreation&contractaddresses=0xC0d3c0d3c0D3c0d3C0D3c0D3C0d3C0D3C0D30010
268        Err(EtherscanError::EmptyResult { status, message })
269            if status == "1" && message == "OK" =>
270        {
271            maybe_predeploy = true;
272            Ok((None, maybe_predeploy))
273        }
274        // Ref: https://api.basescan.org/api?module=contract&action=getcontractcreation&contractaddresses=0xC0d3c0d3c0D3c0d3C0D3c0D3C0d3C0D3C0D30010&apiKey=YourAPIKey
275        Err(EtherscanError::Serde { error: _, content }) if content.contains("GENESIS") => {
276            maybe_predeploy = true;
277            Ok((None, maybe_predeploy))
278        }
279        Err(e) => {
280            eyre::bail!("Error fetching creation data from verifier-url: {:?}", e);
281        }
282    }
283}
284
285pub fn check_and_encode_args(
286    artifact: &CompactContractBytecode,
287    args: Vec<String>,
288) -> Result<Vec<u8>, eyre::ErrReport> {
289    let Some(constructor) = artifact.abi.as_ref().and_then(|abi| abi.constructor()) else {
290        if args.is_empty() {
291            return Ok(Vec::new());
292        }
293        eyre::bail!("Contract has no constructor arguments, but arguments were provided");
294    };
295    if constructor.inputs.len() != args.len() {
296        eyre::bail!(
297            "Mismatch of constructor arguments length. Expected {}, got {}",
298            constructor.inputs.len(),
299            args.len()
300        );
301    }
302    encode_args(&constructor.inputs, &args).map(|args| DynSolValue::Tuple(args).abi_encode_params())
303}
304
305pub fn validate_encoded_constructor_args(
306    artifact: &CompactContractBytecode,
307    args: Vec<u8>,
308) -> Result<Vec<u8>, eyre::ErrReport> {
309    let Some(constructor) = artifact.abi.as_ref().and_then(|abi| abi.constructor()) else {
310        if args.is_empty() {
311            return Ok(args);
312        }
313        eyre::bail!("Contract has no constructor arguments, but encoded arguments were provided");
314    };
315    let values = constructor
316        .abi_decode_input(&args)
317        .map_err(|err| eyre::eyre!("Invalid ABI-encoded constructor arguments: {err}"))?;
318    let encoded = constructor
319        .abi_encode_input(&values)
320        .map_err(|err| eyre::eyre!("Invalid ABI-encoded constructor arguments: {err}"))?;
321    if encoded != args {
322        eyre::bail!("Constructor arguments are not canonically ABI-encoded");
323    }
324    Ok(args)
325}
326
327pub fn check_explorer_args(source_code: &ContractMetadata) -> Result<Bytes, eyre::ErrReport> {
328    if let Some(args) = source_code.items.first() {
329        Ok(args.constructor_arguments.clone())
330    } else {
331        eyre::bail!("No constructor arguments found from block explorer");
332    }
333}
334
335pub fn check_args_len(
336    artifact: &CompactContractBytecode,
337    args: &Bytes,
338) -> Result<(), eyre::ErrReport> {
339    if let Some(constructor) = artifact.abi.as_ref().and_then(|abi| abi.constructor())
340        && !constructor.inputs.is_empty()
341        && args.is_empty()
342    {
343        eyre::bail!(
344            "Contract expects {} constructor argument(s), but none were provided",
345            constructor.inputs.len()
346        );
347    }
348    Ok(())
349}
350
351pub fn load_fork_config_and_evm_opts(config: &Config) -> Result<(Config, EvmOpts)> {
352    let chain = config.chain;
353    let mut fork_config = config.clone();
354    fork_config.chain = None;
355
356    let (mut fork_config, mut evm_opts) = fork_config.load_config_and_evm_opts()?;
357    fork_config.chain = chain;
358    if let Some(chain) = chain {
359        evm_opts.env.chain_id = Some(chain.id());
360    }
361
362    Ok((fork_config, evm_opts))
363}
364
365pub async fn get_tracing_executor<FEN>(
366    fork_config: &mut Config,
367    fork_blk_num: u64,
368    execution_blk_num: u64,
369    execution_block: Option<&AnyRpcBlock>,
370    evm_opts: EvmOpts,
371    executor_builder: ExecutorBuilder<FEN>,
372) -> Result<(EvmEnvFor<FEN>, TracingExecutor<FEN>)>
373where
374    FEN: FoundryEvmNetwork,
375{
376    fork_config.fork_block_number = Some(fork_blk_num);
377
378    let create2_deployer = evm_opts.create2_deployer;
379    let mut fork = TracingExecutor::<FEN>::get_fork(fork_config, evm_opts).await?;
380    let context = fork.context();
381
382    fork.evm_env.block.number = U256::from(execution_blk_num);
383    if let Some(block) = execution_block {
384        configure_env_block::<FEN>(
385            &mut fork.evm_env,
386            block,
387            context.chain().id(),
388            context.networks(),
389        );
390    }
391    fork.resolve_spec(fork_config, None);
392    fork.extend_precompile_labels(fork_config);
393
394    let evm_env = fork.evm_env;
395    let executor = fork.into_executor(
396        executor_builder,
397        TraceRequirements::none().with_calls(true),
398        create2_deployer,
399        None,
400    )?;
401
402    Ok((evm_env, executor))
403}
404
405#[cfg(all(test, feature = "monad"))]
406fn resolve_runtime_spec<FEN>(
407    config: &Config,
408    source_chain_id: ChainId,
409    endpoint_hardfork: Option<FoundryHardfork>,
410    evm_env: &mut EvmEnvFor<FEN>,
411) -> Option<FoundryHardfork>
412where
413    FEN: FoundryEvmNetwork,
414{
415    TracingExecutor::<FEN>::resolve_spec_for_chain(
416        config,
417        source_chain_id,
418        endpoint_hardfork,
419        evm_env,
420        None,
421    )
422}
423
424pub fn configure_env_block<FEN>(
425    evm_env: &mut EvmEnvFor<FEN>,
426    block: &AnyRpcBlock,
427    source_chain_id: ChainId,
428    config: NetworkConfigs,
429) where
430    FEN: FoundryEvmNetwork,
431{
432    let number = evm_env.block.number;
433    evm_env.block = block_env_from_header::<TypesFor<FEN>>(block.header());
434    evm_env.block.number = number;
435    apply_chain_and_block_specific_env_changes_for_chain::<AnyNetwork, _>(
436        evm_env,
437        block,
438        source_chain_id,
439        config,
440    );
441}
442
443/// Executes the creation `tx` (converted from `request`) with `evm_env` and `ext` or extension
444/// state prepared for it, and returns the address of the contract it deployed.
445pub fn deploy_contract<FEN>(
446    executor: &mut TracingExecutor<FEN>,
447    evm_env: &EvmEnvFor<FEN>,
448    request: TransactionRequestFor<FEN>,
449    ext: Option<ChainFor<FEN>>,
450) -> Result<Address, eyre::ErrReport>
451where
452    FEN: FoundryEvmNetwork,
453{
454    // Derive the created address up front: batched transactions return the last call's result,
455    // not the deployment's.
456    let (to, input) = creation_call::<FEN>(&request);
457    let address = if let TxKind::Call(to) = to {
458        if to != DEFAULT_CREATE2_DEPLOYER {
459            eyre::bail!(
460                "Transaction `to` address is not the default create2 deployer i.e the tx is not a contract creation tx."
461            );
462        }
463        let (salt, init_code) = input.split_at(32);
464        DEFAULT_CREATE2_DEPLOYER.create2_from_code(B256::from_slice(salt), init_code)
465    } else {
466        let caller = request.from().unwrap_or_default();
467        caller.create(executor.backend_mut().basic(caller)?.map_or(0, |info| info.nonce))
468    };
469
470    let tx = TypesFor::<FEN>::tx_from_request(request)?;
471    let result = executor.transact_tx(*evm_env, &tx, ext)?;
472    trace!(transact_result = ?result.exit_reason);
473
474    if result.reverted {
475        let decoded_reason = RevertDecoder::new().decode(&result.result, result.exit_reason);
476        eyre::bail!(
477            "Failed to deploy contract on fork at block: {decoded_reason}.\n\
478            This typically happens when your local bytecode differs from what was actually deployed.\n\
479            Common causes:\n\
480            - Your contract source is not at the same commit used during deployment\n\
481            - Cached build artifacts are stale (try `forge clean && forge build`)\n\
482            - Compiler settings (optimizer, evm_version, via_ir) don't match the deployment"
483        );
484    }
485    if !result
486        .state_changeset
487        .account_changes()
488        .any(|account| account.address == address && account.created)
489    {
490        eyre::bail!("Transaction did not deploy a contract at the expected address {address}");
491    }
492
493    Ok(address)
494}
495
496/// Returns the kind and input of the call that deploys the contract: the first call of a Tempo AA
497/// transaction, or the transaction itself.
498pub fn creation_call<FEN: FoundryEvmNetwork>(
499    request: &TransactionRequestFor<FEN>,
500) -> (TxKind, Bytes) {
501    match request.tempo_calls().first() {
502        Some(&(kind, input)) if request.has_tempo_call_list() => {
503            (kind, Bytes::copy_from_slice(input))
504        }
505        _ => {
506            (request.kind().unwrap_or(TxKind::Create), request.input().cloned().unwrap_or_default())
507        }
508    }
509}
510
511pub async fn get_runtime_codes<FEN>(
512    executor: &mut TracingExecutor<FEN>,
513    provider: &impl Provider<AnyNetwork>,
514    address: Address,
515    fork_address: Address,
516    block: Option<u64>,
517) -> Result<(Bytecode, Bytes)>
518where
519    FEN: FoundryEvmNetwork,
520{
521    let fork_runtime_code = executor
522        .backend_mut()
523        .basic(fork_address)?
524        .ok_or_else(|| {
525            eyre::eyre!(
526                "Failed to get runtime code for contract deployed on fork at address {}",
527                fork_address
528            )
529        })?
530        .code
531        .ok_or_else(|| {
532            eyre::eyre!(
533                "Bytecode does not exist for contract deployed on fork at address {}",
534                fork_address
535            )
536        })?;
537
538    let block_id = block.map_or_else(BlockId::latest, BlockId::number);
539    let onchain_runtime_code = provider.get_code_at(address).block_id(block_id).await?;
540
541    Ok((fork_runtime_code, onchain_runtime_code))
542}
543
544/// Returns `true` if the URL only consists of host.
545///
546/// This is used to check user input url for missing /api path
547pub fn is_host_only(url: &Url) -> bool {
548    matches!(url.path(), "/" | "")
549}
550
551/// Wraps a failed verification error with guidance when `--verifier-url` looks misconfigured for
552/// the Etherscan provider. Returns `err` untouched when no hint applies.
553///
554/// The hint only fires when the Etherscan verifier is active: it requires an API endpoint
555/// (typically `/api`). Sourcify, Blockscout, etc. accept host-only URLs, so we leave their
556/// errors alone.
557pub fn wrap_verifier_url_error(
558    err: eyre::Error,
559    verifier_url: Option<&str>,
560    using_etherscan: bool,
561) -> eyre::Error {
562    let Some(verifier_url) = verifier_url else { return err };
563    let url = match Url::parse(verifier_url) {
564        Ok(mut url) => {
565            let _ = url.set_username("");
566            let _ = url.set_password(None);
567            url.set_query(None);
568            url.set_fragment(None);
569            url
570        }
571        Err(url_err) => {
572            return err.wrap_err(format!("Invalid verifier URL provided: {url_err}"));
573        }
574    };
575    if is_host_only(&url) && using_etherscan {
576        return err.wrap_err(format!(
577            "Verifier `etherscan` requires an API endpoint, but `--verifier-url` is host-only: `{url}`.\n\
578             Fixes (pick one):\n\
579             - Append the API path, e.g. `--verifier-url {url}api`\n\
580             - Switch verifier, e.g. `--verifier sourcify` (works with host-only URLs)"
581        ));
582    }
583    err
584}
585
586/// Given any solc [Version] return a [Version] with build metadata
587///
588/// # Example
589///
590/// ```ignore
591/// use semver::{BuildMetadata, Version};
592/// let version = Version::new(1, 2, 3);
593/// let version = ensure_solc_build_metadata(version).await?;
594/// assert_ne!(version.build, BuildMetadata::EMPTY);
595/// ```
596pub async fn ensure_solc_build_metadata(version: Version) -> Result<Version> {
597    if version.build == BuildMetadata::EMPTY {
598        Ok(lookup_compiler_version(&version).await?)
599    } else {
600        Ok(version)
601    }
602}
603
604#[cfg(test)]
605mod tests {
606    use super::*;
607    use crate::verify::VerifierArgs;
608    use alloy_json_abi::JsonAbi;
609    use foundry_cli::opts::EtherscanOpts;
610    use foundry_compilers::PathStyle;
611    use foundry_config::NamedChain;
612    use foundry_test_utils::{TestProject, util::SOLC_VERSION};
613
614    #[cfg(feature = "monad")]
615    use foundry_evm::core::evm::MonadEvmNetwork;
616
617    #[cfg(feature = "monad")]
618    fn monad_env(timestamp: u64) -> EvmEnvFor<MonadEvmNetwork> {
619        let mut env = EvmOpts::default().local_evm_env::<MonadEvmNetwork>();
620        env.set_chain_id(NamedChain::Monad as u64);
621        env.block.timestamp = U256::from(timestamp);
622        env
623    }
624
625    #[test]
626    fn encoded_constructor_args_must_be_canonical() {
627        let artifact = CompactContractBytecode {
628            abi: Some(alloy_json_abi::JsonAbi::parse(["constructor(uint256 value)"]).unwrap()),
629            bytecode: None,
630            deployed_bytecode: None,
631        };
632        let args = artifact
633            .abi
634            .as_ref()
635            .unwrap()
636            .constructor()
637            .unwrap()
638            .abi_encode_input(&[DynSolValue::Uint(U256::ONE, 256)])
639            .unwrap();
640
641        assert_eq!(validate_encoded_constructor_args(&artifact, args.clone()).unwrap(), args);
642
643        // Arbitrary bytes prepended to valid arguments can overlap the creation bytecode's
644        // metadata and must not be accepted as part of the constructor arguments.
645        let overlapping = [alloy_primitives::hex!("a1616101").as_slice(), &args].concat();
646        assert!(validate_encoded_constructor_args(&artifact, overlapping).is_err());
647    }
648
649    #[test]
650    fn typed_constructor_args_require_a_constructor() {
651        let artifact = CompactContractBytecode {
652            abi: Some(JsonAbi::new()),
653            bytecode: None,
654            deployed_bytecode: None,
655        };
656
657        assert!(check_and_encode_args(&artifact, vec!["1".to_string()]).is_err());
658        assert_eq!(check_and_encode_args(&artifact, Vec::new()).unwrap(), Vec::<u8>::new());
659    }
660
661    #[test]
662    fn dynamic_constructor_args_are_encoded_as_top_level_params() {
663        let artifact = CompactContractBytecode {
664            abi: Some(alloy_json_abi::JsonAbi::parse(["constructor(string value)"]).unwrap()),
665            bytecode: None,
666            deployed_bytecode: None,
667        };
668
669        let encoded = check_and_encode_args(&artifact, vec!["hi".to_string()]).unwrap();
670
671        // Constructor arguments are encoded as top-level ABI parameters, so the first word is the
672        // offset to the string payload.
673        let expected = alloy_primitives::hex!(
674            "0000000000000000000000000000000000000000000000000000000000000020"
675            "0000000000000000000000000000000000000000000000000000000000000002"
676            "6869000000000000000000000000000000000000000000000000000000000000"
677        );
678        assert_eq!(encoded, expected);
679    }
680
681    #[test]
682    fn creation_code_must_end_with_constructor_args() {
683        let code = alloy_primitives::hex!("6080604052348015600e575f5ffd5b50607b80601a5f395ff3fe");
684        let real_args = [0x11u8; 32];
685        let wrong_args = [0x22u8; 32];
686
687        let onchain = [code.as_slice(), &real_args].concat();
688
689        // Wrong args of the right length used to report a partial match because the tails were
690        // stripped from both sides without comparing them.
691        let local = [code.as_slice(), &wrong_args].concat();
692        assert_eq!(match_bytecodes(&local, &onchain, &wrong_args, false, BytecodeHash::Ipfs), None);
693
694        let local = [code.as_slice(), &real_args].concat();
695        assert_eq!(
696            match_bytecodes(&local, &onchain, &real_args, false, BytecodeHash::Ipfs),
697            Some(VerificationType::Full)
698        );
699
700        // A valid dynamic encoding can end with another valid encoding. The suffix alone must
701        // not establish that the supplied arguments match.
702        let suffix_args =
703            DynSolValue::Tuple(vec![DynSolValue::Bytes(real_args.to_vec())]).abi_encode();
704        let deployment_args =
705            DynSolValue::Tuple(vec![DynSolValue::Bytes(suffix_args.clone())]).abi_encode();
706        assert!(deployment_args.ends_with(&suffix_args));
707
708        let onchain = [code.as_slice(), deployment_args.as_slice()].concat();
709        let local = [code.as_slice(), suffix_args.as_slice()].concat();
710        assert_eq!(
711            match_bytecodes(&local, &onchain, &suffix_args, false, BytecodeHash::Ipfs),
712            None
713        );
714    }
715
716    #[test]
717    fn build_project_finds_artifact_by_relative_contract_path() {
718        let prj = TestProject::new("verify-bytecode-relative-path", PathStyle::Dapptools);
719        prj.add_source(
720            "Counter.sol",
721            r#"
722pragma solidity ^0.8.0;
723
724contract Counter {
725    uint256 public number;
726}
727"#,
728        );
729        prj.add_source(
730            "Broken.sol",
731            r#"
732pragma solidity ^0.8.0;
733
734contract Broken {
735    this is not valid Solidity
736}
737"#,
738        );
739
740        let mut config = Config::load_with_root(prj.root()).unwrap();
741        config.solc = Some(SOLC_VERSION.into());
742        let args = VerifyBytecodeArgs {
743            address: Address::ZERO,
744            contract: "src/Counter.sol:Counter".parse().unwrap(),
745            block: None,
746            constructor_args: None,
747            encoded_constructor_args: None,
748            constructor_args_path: None,
749            rpc_url: None,
750            network: None,
751            etherscan: EtherscanOpts::default(),
752            verifier: VerifierArgs::default(),
753            libraries: Vec::new(),
754            root: Some(prj.root().to_path_buf()),
755            ignore: None,
756        };
757
758        let artifact = build_project(&args, &config).unwrap();
759
760        assert!(artifact.bytecode.and_then(|bytecode| bytecode.into_bytes()).is_some());
761    }
762
763    #[test]
764    fn load_fork_config_and_evm_opts_serializes_chain_as_id() {
765        let config = Config { chain: Some(NamedChain::Mainnet.into()), ..Default::default() };
766
767        let (fork_config, evm_opts) = load_fork_config_and_evm_opts(&config).unwrap();
768
769        assert_eq!(fork_config.chain, Some(NamedChain::Mainnet.into()));
770        assert_eq!(evm_opts.env.chain_id, Some(1));
771    }
772
773    #[test]
774    #[cfg(feature = "monad")]
775    fn runtime_spec_uses_monad_source_chain_timestamp() {
776        let monad_nine_timestamp = foundry_evm::hardforks::MonadHardfork::MonadNine
777            .mainnet_activation_timestamp()
778            .unwrap();
779
780        let before_config = Config {
781            evm_version: foundry_compilers::artifacts::EvmVersion::Osaka,
782            ..Default::default()
783        };
784        let mut before_env = monad_env(monad_nine_timestamp - 1);
785        before_env.set_chain_id(NamedChain::Mainnet as u64);
786        let before = resolve_runtime_spec::<MonadEvmNetwork>(
787            &before_config,
788            NamedChain::Monad as u64,
789            None,
790            &mut before_env,
791        );
792
793        assert_eq!(
794            before,
795            Some(FoundryHardfork::Monad(foundry_evm::hardforks::MonadHardfork::MonadEight))
796        );
797        assert_eq!(before_env.spec, foundry_evm::hardforks::MonadHardfork::MonadEight);
798        assert_eq!(before_env.chain_id(), NamedChain::Mainnet as u64);
799
800        let after_config = Config {
801            evm_version: foundry_compilers::artifacts::EvmVersion::Prague,
802            ..Default::default()
803        };
804        let mut after_env = monad_env(monad_nine_timestamp);
805        let after = resolve_runtime_spec::<MonadEvmNetwork>(
806            &after_config,
807            NamedChain::Monad as u64,
808            None,
809            &mut after_env,
810        );
811
812        assert_eq!(
813            after,
814            Some(FoundryHardfork::Monad(foundry_evm::hardforks::MonadHardfork::MonadNine))
815        );
816        assert_eq!(after_env.spec, foundry_evm::hardforks::MonadHardfork::MonadNine);
817    }
818
819    #[test]
820    #[cfg(feature = "monad")]
821    fn runtime_spec_and_labels_prefer_explicit_monad_hardfork() {
822        let mut config = Config {
823            hardfork: Some(foundry_evm::hardforks::MonadHardfork::MonadEight.into()),
824            ..Default::default()
825        };
826        let mut env = monad_env(
827            foundry_evm::hardforks::MonadHardfork::MonadNine
828                .mainnet_activation_timestamp()
829                .unwrap(),
830        );
831        let networks = NetworkConfigs::with_monad();
832
833        let resolved = resolve_runtime_spec::<MonadEvmNetwork>(
834            &config,
835            NamedChain::Monad as u64,
836            Some(foundry_evm::hardforks::MonadHardfork::MonadNine.into()),
837            &mut env,
838        );
839        TracingExecutor::<MonadEvmNetwork>::extend_precompile_labels(
840            &mut config,
841            networks,
842            resolved,
843        );
844
845        assert_eq!(
846            resolved,
847            Some(FoundryHardfork::Monad(foundry_evm::hardforks::MonadHardfork::MonadEight))
848        );
849        assert_eq!(env.spec, foundry_evm::hardforks::MonadHardfork::MonadEight);
850        assert!(config.labels.values().any(|label| label == "Staking"));
851        assert!(!config.labels.values().any(|label| label == "ReserveBalance"));
852    }
853
854    #[test]
855    fn test_host_only() {
856        assert!(!is_host_only(&Url::parse("https://blockscout.net/api").unwrap()));
857        assert!(is_host_only(&Url::parse("https://blockscout.net/").unwrap()));
858        assert!(is_host_only(&Url::parse("https://blockscout.net").unwrap()));
859    }
860
861    #[test]
862    fn wrap_verifier_url_error_passes_through_when_no_url() {
863        let err = eyre::eyre!("upstream failure");
864        let wrapped = wrap_verifier_url_error(err, None, true);
865        assert_eq!(wrapped.to_string(), "upstream failure");
866    }
867
868    #[test]
869    fn wrap_verifier_url_error_adds_hint_for_host_only_etherscan_url() {
870        let err = eyre::eyre!("upstream failure");
871        let wrapped = wrap_verifier_url_error(err, Some("https://contracts.tempo.xyz"), true);
872        let msg = format!("{wrapped:#}");
873        assert!(msg.contains("host-only"), "message: {msg}");
874        assert!(msg.contains("--verifier-url https://contracts.tempo.xyz/api"), "message: {msg}");
875        assert!(msg.contains("--verifier sourcify"), "message: {msg}");
876    }
877
878    /// Sourcify and other non-etherscan verifiers accept host-only URLs; we must not emit the
879    /// hint for them, otherwise we would mislead the user into editing a correct URL.
880    #[test]
881    fn wrap_verifier_url_error_does_not_hint_for_non_etherscan_provider() {
882        let err = eyre::eyre!("upstream failure");
883        let wrapped = wrap_verifier_url_error(err, Some("https://contracts.tempo.xyz"), false);
884        assert_eq!(wrapped.to_string(), "upstream failure");
885    }
886
887    #[test]
888    fn wrap_verifier_url_error_reports_invalid_url() {
889        let err = eyre::eyre!("upstream failure");
890        let wrapped = wrap_verifier_url_error(err, Some("not a url"), true);
891        let msg = format!("{wrapped:#}");
892        assert!(msg.contains("Invalid verifier URL"), "message: {msg}");
893        assert!(!msg.contains("not a url"), "message: {msg}");
894    }
895
896    #[test]
897    fn wrap_verifier_url_error_redacts_credentials_and_query() {
898        let err = eyre::eyre!("upstream failure");
899        let wrapped = wrap_verifier_url_error(
900            err,
901            Some("https://user:secret@example.com?api_key=secret"),
902            true,
903        );
904        let msg = format!("{wrapped:#}");
905        assert!(msg.contains("https://example.com/"));
906        assert!(!msg.contains("user"));
907        assert!(!msg.contains("secret"));
908        assert!(!msg.contains("api_key"));
909    }
910
911    /// Args longer than the code at the address leave nothing to strip them from,
912    /// which is a mismatch rather than a crash.
913    #[test]
914    fn match_bytecodes_survives_constructor_args_longer_than_bytecode() {
915        let local = [0x60u8, 0x80, 0x60, 0x40];
916        let onchain = [0x60u8, 0x80];
917        let args = [0x11u8; 32];
918        assert_eq!(match_bytecodes(&local, &onchain, &args, false, BytecodeHash::Ipfs), None);
919
920        // Matching onchain args must not allow stripping past the local buffer.
921        assert_eq!(match_bytecodes(&local, &args, &args, false, BytecodeHash::Ipfs), None);
922    }
923}