Skip to main content

forge_verify/etherscan/
mod.rs

1use crate::{
2    VerifierArgs,
3    provider::{
4        ExternalVerificationContext, VerificationContext, VerificationProvider,
5        VerificationProviderType,
6    },
7    utils::ensure_solc_build_metadata,
8    verify::{ContractLanguage, VerifyArgs, VerifyCheckArgs},
9};
10use alloy_dyn_abi::JsonAbiExt;
11use alloy_primitives::hex;
12use alloy_provider::Provider;
13use alloy_rpc_types::TransactionTrait;
14use eyre::{Context, OptionExt, Result, eyre};
15use foundry_block_explorers::{
16    Client,
17    errors::EtherscanError,
18    verify::{CodeFormat, VerifyContract},
19};
20use foundry_cli::{
21    opts::EtherscanOpts,
22    utils::{LoadConfig, get_provider, read_constructor_args_file},
23};
24use foundry_common::{abi::encode_args, retry::RetryError};
25use foundry_compilers::{Artifact, artifacts::BytecodeObject};
26use foundry_config::Config;
27use foundry_evm::constants::DEFAULT_CREATE2_DEPLOYER;
28use regex::Regex;
29use semver::BuildMetadata;
30use std::{fmt::Debug, future::Future as StdFuture, pin::Pin, sync::LazyLock, time::Duration};
31
32mod flatten;
33
34mod standard_json;
35
36pub static RE_BUILD_COMMIT: LazyLock<Regex> =
37    LazyLock::new(|| Regex::new(r"(?P<commit>commit\.[0-9,a-f]{8})").unwrap());
38
39#[derive(Clone, Debug, Default)]
40#[non_exhaustive]
41pub struct EtherscanVerificationProvider;
42
43/// The contract source provider for [EtherscanVerificationProvider]
44///
45/// Returns source, contract_name and the source [CodeFormat]
46trait EtherscanSourceProvider: Send + Sync + Debug {
47    fn source(
48        &self,
49        args: &VerifyArgs,
50        context: &VerificationContext,
51    ) -> Result<(String, String, CodeFormat)>;
52}
53
54#[async_trait::async_trait]
55impl VerificationProvider for EtherscanVerificationProvider {
56    fn provider_type(&self) -> VerificationProviderType {
57        VerificationProviderType::Etherscan
58    }
59
60    async fn preflight_verify_check(
61        &mut self,
62        args: VerifyArgs,
63        context: VerificationContext,
64    ) -> Result<()> {
65        let _ = self.prepare_verify_request(&args, &context).await?;
66        Ok(())
67    }
68
69    async fn submit(
70        &mut self,
71        args: VerifyArgs,
72        context: VerificationContext,
73    ) -> Result<Option<VerifyCheckArgs>> {
74        let (etherscan, verify_args) = self.prepare_verify_request(&args, &context).await?;
75        self.submit_verify_request(args, etherscan, verify_args).await
76    }
77
78    fn submit_external(
79        &mut self,
80        args: VerifyArgs,
81        context: ExternalVerificationContext,
82    ) -> Pin<Box<dyn StdFuture<Output = Result<Option<VerifyCheckArgs>>> + '_>> {
83        Box::pin(async move {
84            let etherscan = self.client(&args.etherscan, &args.verifier, &context.config)?;
85            let verify_args = self.create_external_verify_request(&args, &context)?;
86            self.submit_verify_request(args, etherscan, verify_args).await
87        })
88    }
89
90    /// Executes the command to check verification status on Etherscan
91    async fn check(&self, args: VerifyCheckArgs) -> Result<()> {
92        let config = args.load_config()?;
93        let etherscan = self.client(&args.etherscan, &args.verifier, &config)?;
94        args.retry
95            .into_retry()
96            .run_async_until_break(|| async {
97                let resp = etherscan
98                    .check_contract_verification_status(args.id.clone())
99                    .await
100                    .wrap_err("Failed to request verification status")
101                    .map_err(RetryError::Retry)?;
102
103                trace!(status = %resp.status, "Received Etherscan verification response");
104
105                let _ = sh_status!(
106                    "Contract verification status:\nResponse: `{}`\nDetails: `{}`",
107                    sanitize_remote_message(&resp.message),
108                    sanitize_remote_message(&resp.result)
109                );
110
111                match VerificationCheckStatus::classify(&resp.status, &resp.result) {
112                    VerificationCheckStatus::Pending => {
113                        Err(RetryError::Retry(eyre!("Verification is still pending...")))
114                    }
115                    VerificationCheckStatus::UnableToVerify => {
116                        Err(RetryError::Retry(eyre!("Unable to verify.")))
117                    }
118                    VerificationCheckStatus::AlreadyVerified => {
119                        let _ = sh_status!("Contract source code already verified");
120                        Ok(())
121                    }
122                    VerificationCheckStatus::Failed => Err(RetryError::Break(eyre!(
123                        "Contract verification failed:\nStatus: `{}`\nResult: `{}`",
124                        resp.status,
125                        sanitize_remote_message(&resp.result)
126                    ))),
127                    VerificationCheckStatus::Verified => {
128                        let _ = sh_status!("Contract successfully verified");
129                        Ok(())
130                    }
131                    VerificationCheckStatus::Finished => Ok(()),
132                }
133            })
134            .await
135            .wrap_err("Checking verification result failed")
136    }
137}
138
139/// The state of an Etherscan verification job, as reported by its status check.
140#[derive(Clone, Copy, Debug, PartialEq, Eq)]
141enum VerificationCheckStatus {
142    /// The job is queued, or the explorer has not indexed the contract yet; check again.
143    Pending,
144    /// The explorer could not verify the contract yet; check again.
145    UnableToVerify,
146    /// The contract was verified before this job.
147    AlreadyVerified,
148    /// The job failed (status `0`).
149    Failed,
150    /// The job verified the contract.
151    Verified,
152    /// The job finished with a result this client does not recognize.
153    Finished,
154}
155
156impl VerificationCheckStatus {
157    /// Classifies a verification status response from its `status` and `result` fields.
158    ///
159    /// The order matters: explorers report pending and retryable jobs with status `0`.
160    fn classify(status: &str, result: &str) -> Self {
161        if result == "Pending in queue" || result.starts_with("Error: contract does not exist") {
162            Self::Pending
163        } else if result == "Unable to verify" {
164            Self::UnableToVerify
165        } else if result == "Already Verified" {
166            Self::AlreadyVerified
167        } else if status == "0" {
168            Self::Failed
169        } else if result == "Pass - Verified" {
170            Self::Verified
171        } else {
172            Self::Finished
173        }
174    }
175}
176
177impl EtherscanVerificationProvider {
178    async fn submit_verify_request(
179        &self,
180        args: VerifyArgs,
181        etherscan: Client,
182        verify_args: VerifyContract,
183    ) -> Result<Option<VerifyCheckArgs>> {
184        if !args.skip_is_verified_check
185            && self.is_contract_verified(&etherscan, &verify_args).await?
186        {
187            sh_status!(
188                "Contract [{}] {:?} is already verified. Skipping verification.",
189                verify_args.contract_name,
190                verify_args.address.to_checksum(None)
191            )?;
192
193            return Ok(None);
194        }
195
196        trace!(
197            provider = "Etherscan",
198            address = %verify_args.address,
199            target = %verify_args.contract_name,
200            "submitting verification request"
201        );
202
203        let resp = args
204            .retry
205            .into_retry()
206            .run_async(|| async {
207                sh_status!(
208                    "Submitting verification for [{}] {}.",
209                    verify_args.contract_name,
210                    verify_args.address
211                )?;
212                let resp = etherscan
213                    .submit_contract_verification(&verify_args)
214                    .await
215                    .wrap_err("Failed to submit Etherscan contract verification")?;
216
217                trace!(status = %resp.status, "Received Etherscan verification response");
218
219                if resp.status == "0" {
220                    if resp.result == "Contract source code already verified"
221                        // specific for blockscout response
222                        || resp.result == "Smart-contract already verified."
223                    {
224                        return Ok(None);
225                    }
226
227                    if resp.result.starts_with("Unable to locate ContractCode at")
228                        || resp.result.starts_with("The address is not a smart contract")
229                        || resp.result.starts_with("Address is not a smart-contract")
230                    {
231                        warn!("{}", sanitize_remote_message(&resp.result));
232                        return Err(eyre!(
233                            "Could not detect deployment: {}",
234                            sanitize_remote_message(&resp.result)
235                        ));
236                    }
237
238                    warn!(status = %resp.status, "Etherscan verification submission failed");
239                    eyre::bail!(
240                        "Encountered an error verifying this contract:\nResponse: `{}`\nDetails: `{}`",
241                        sanitize_remote_message(&resp.message),
242                        sanitize_remote_message(&resp.result)
243                    );
244                }
245
246                Ok(Some(resp))
247            })
248            .await?;
249
250        if let Some(resp) = resp {
251            let url = etherscan.address_url(args.address);
252            let display_id = sanitize_remote_message(&resp.result);
253            sh_status!(
254                "Submitted contract for verification:\n\tResponse: `{}`\n\tGUID: `{}`\n\tURL: {}",
255                sanitize_remote_message(&resp.message),
256                display_id,
257                url
258            )?;
259            if args.print_submission_result_to_stdout {
260                sh_println!("{}\t{}", display_id, url)?;
261            }
262            Ok(Some(VerifyCheckArgs {
263                id: resp.result,
264                etherscan: args.etherscan,
265                retry: args.retry,
266                verifier: args.verifier,
267            }))
268        } else {
269            sh_status!("Contract source code already verified")?;
270            Ok(None)
271        }
272    }
273
274    fn create_external_verify_request(
275        &self,
276        args: &VerifyArgs,
277        context: &ExternalVerificationContext,
278    ) -> Result<VerifyContract> {
279        let source = serde_json::to_string(&context.standard_json_input)
280            .wrap_err("Failed to serialize standard json input")?;
281        let compiler_version = format!("v{}", context.compiler_version);
282        let mut request =
283            VerifyContract::new(args.address, context.target.clone(), source, compiler_version)
284                .constructor_arguments(args.constructor_args.clone())
285                .code_format(CodeFormat::StandardJsonInput);
286        apply_license_type(&mut request, args.license_type.as_deref());
287        Ok(request)
288    }
289
290    /// Create a source provider
291    fn source_provider(&self, args: &VerifyArgs) -> Box<dyn EtherscanSourceProvider> {
292        if args.flatten {
293            Box::new(flatten::EtherscanFlattenedSource)
294        } else {
295            Box::new(standard_json::EtherscanStandardJsonSource)
296        }
297    }
298
299    /// Configures the API request to the Etherscan API using the given [`VerifyArgs`].
300    async fn prepare_verify_request(
301        &mut self,
302        args: &VerifyArgs,
303        context: &VerificationContext,
304    ) -> Result<(Client, VerifyContract)> {
305        let config = args.load_config()?;
306        let etherscan = self.client(&args.etherscan, &args.verifier, &config)?;
307        let verify_args = self.create_verify_request(args, context).await?;
308
309        Ok((etherscan, verify_args))
310    }
311
312    /// Queries the Etherscan API to verify if the contract is already verified.
313    async fn is_contract_verified(
314        &self,
315        etherscan: &Client,
316        verify_contract: &VerifyContract,
317    ) -> Result<bool> {
318        let check = etherscan.contract_abi(verify_contract.address).await;
319
320        if let Err(err) = check {
321            return match err {
322                EtherscanError::ContractCodeNotVerified(_) => Ok(false),
323                error => Err(error).wrap_err_with(|| {
324                    format!("Failed to obtain contract ABI for {}", verify_contract.address)
325                }),
326            };
327        }
328
329        Ok(true)
330    }
331
332    /// Create an Etherscan client.
333    pub(crate) fn client(
334        &self,
335        etherscan_opts: &EtherscanOpts,
336        verifier_args: &VerifierArgs,
337        config: &Config,
338    ) -> Result<Client> {
339        let chain = etherscan_opts.chain.unwrap_or_default();
340        let etherscan_key = etherscan_opts.key();
341        let verifier_type = verifier_args.effective_type();
342        let verifier_url = verifier_args.verifier_url.as_deref();
343
344        // Verifier is etherscan if explicitly set or if no verifier set (default sourcify) but
345        // API key passed.
346        let is_etherscan = verifier_type.is_etherscan()
347            || (verifier_type.is_sourcify() && etherscan_key.is_some());
348        let etherscan_config = match config.get_etherscan_config_with_chain(Some(chain)) {
349            Ok(config) => config,
350            // The selected URL is authoritative, so an invalid lower-priority endpoint must not
351            // prevent creating the client.
352            Err(_) if verifier_url.is_some() => None,
353            Err(err) => return Err(err.into()),
354        };
355
356        let api_url =
357            verifier_url.or_else(|| etherscan_config.as_ref().map(|c| c.api_url.as_str()));
358        let base_url = etherscan_config
359            .as_ref()
360            .and_then(|c| c.browser_url.as_deref())
361            .or_else(|| chain.etherscan_urls().map(|(_, url)| url));
362        let etherscan_key =
363            etherscan_key.or_else(|| etherscan_config.as_ref().map(|c| c.key.clone()));
364
365        let mut builder = Client::builder();
366
367        builder = if let Some(api_url) = api_url {
368            // we don't want any trailing slashes because this can cause cloudflare issues: <https://github.com/foundry-rs/foundry/pull/6079>
369            let api_url = api_url.trim_end_matches('/');
370            let base_url = if is_etherscan {
371                base_url.unwrap_or(api_url)
372            } else {
373                // If verifier is not Etherscan then set base url as api url without /api suffix.
374                api_url.strip_suffix("/api").unwrap_or(api_url)
375            };
376            builder.with_api_url(api_url)?.with_url(base_url)?
377        } else {
378            builder.chain(chain)?
379        };
380
381        let http = reqwest::Client::builder()
382            .timeout(Duration::from_secs(30))
383            .connect_timeout(Duration::from_secs(10))
384            .build()
385            .wrap_err("Failed to create Etherscan HTTP client")?;
386        builder
387            .with_client(http)
388            .with_api_key(etherscan_key.unwrap_or_default())
389            .build()
390            .wrap_err("Failed to create Etherscan client")
391    }
392
393    /// Creates the `VerifyContract` Etherscan request in order to verify the contract
394    ///
395    /// If `--flatten` is set to `true` then this will send with [`CodeFormat::SingleFile`]
396    /// otherwise this will use the [`CodeFormat::StandardJsonInput`]
397    pub async fn create_verify_request(
398        &mut self,
399        args: &VerifyArgs,
400        context: &VerificationContext,
401    ) -> Result<VerifyContract> {
402        let (source, contract_name, code_format) =
403            self.source_provider(args).source(args, context)?;
404
405        let lang = args.detect_language(context);
406
407        let mut compiler_version = context.compiler_version.clone();
408        compiler_version.build = match RE_BUILD_COMMIT.captures(compiler_version.build.as_str()) {
409            Some(cap) => BuildMetadata::new(cap.name("commit").unwrap().as_str())?,
410            _ => BuildMetadata::EMPTY,
411        };
412
413        let compiler_version = if matches!(lang, ContractLanguage::Vyper) {
414            format!("vyper:{}", compiler_version.to_string().split('+').next().unwrap_or("0.0.0"))
415        } else {
416            format!("v{}", ensure_solc_build_metadata(context.compiler_version.clone()).await?)
417        };
418
419        let constructor_args = self.constructor_args(args, context).await?;
420        let mut verify_args =
421            VerifyContract::new(args.address, contract_name, source, compiler_version)
422                .constructor_arguments(constructor_args)
423                .code_format(code_format);
424
425        if args.via_ir {
426            // we explicitly set this __undocumented__ argument to true if provided by the user,
427            // though this info is also available in the compiler settings of the standard json
428            // object if standard json is used
429            // unclear how Etherscan interprets this field in standard-json mode
430            verify_args = verify_args.via_ir(true);
431        }
432
433        apply_license_type(&mut verify_args, args.license_type.as_deref());
434
435        if code_format == CodeFormat::SingleFile {
436            verify_args = if let Some(optimizations) = args.num_of_optimizations {
437                verify_args.optimized().runs(optimizations as u32)
438            } else if context.config.optimizer == Some(true) {
439                verify_args
440                    .optimized()
441                    .runs(context.config.optimizer_runs.unwrap_or(200).try_into()?)
442            } else {
443                verify_args.not_optimized()
444            };
445        }
446
447        if code_format == CodeFormat::VyperJson {
448            verify_args =
449                if args.num_of_optimizations.is_some() || context.config.optimizer == Some(true) {
450                    verify_args.optimized().runs(1)
451                } else {
452                    verify_args.not_optimized().runs(0)
453                }
454        }
455
456        Ok(verify_args)
457    }
458
459    /// Return the optional encoded constructor arguments. If the path to
460    /// constructor arguments was provided, read them and encode. Otherwise,
461    /// return whatever was set in the [VerifyArgs] args.
462    async fn constructor_args(
463        &mut self,
464        args: &VerifyArgs,
465        context: &VerificationContext,
466    ) -> Result<Option<String>> {
467        if let Some(constructor_args_path) = &args.constructor_args_path {
468            let abi = context.get_target_abi()?;
469            let constructor = abi
470                .constructor()
471                .ok_or_else(|| eyre!("Can't retrieve constructor info from artifact ABI."))?;
472            let values = encode_args(
473                &constructor.inputs,
474                read_constructor_args_file(constructor_args_path.clone())?,
475            )?;
476            return Ok(Some(hex::encode(constructor.abi_encode_input(&values)?)));
477        }
478        if args.guess_constructor_args {
479            return Ok(Some(self.guess_constructor_args(args, context).await?));
480        }
481
482        Ok(args.constructor_args.clone())
483    }
484
485    /// Uses Etherscan API to fetch contract creation transaction.
486    /// If transaction is a create transaction or a invocation of default CREATE2 deployer, tries to
487    /// match provided creation code with local bytecode of the target contract.
488    /// If bytecode match, returns latest bytes of on-chain creation code as constructor arguments.
489    async fn guess_constructor_args(
490        &mut self,
491        args: &VerifyArgs,
492        context: &VerificationContext,
493    ) -> Result<String> {
494        let provider = get_provider(&context.config)?;
495        let client = self.client(&args.etherscan, &args.verifier, &context.config)?;
496
497        let creation_data = client.contract_creation_data(args.address).await?;
498        let transaction = provider
499            .get_transaction_by_hash(creation_data.transaction_hash)
500            .await?
501            .ok_or_eyre("Transaction not found")?;
502        let receipt = provider
503            .get_transaction_receipt(creation_data.transaction_hash)
504            .await?
505            .ok_or_eyre("Couldn't fetch transaction receipt from RPC")?;
506
507        let maybe_creation_code = if receipt.contract_address == Some(args.address) {
508            transaction.input()
509        } else if transaction.to() == Some(DEFAULT_CREATE2_DEPLOYER) {
510            &transaction.input()[32..]
511        } else {
512            eyre::bail!(
513                "Fetching of constructor arguments is not supported for contracts created by contracts"
514            );
515        };
516
517        let output = context.project.compile_file(&context.target_path)?;
518        let artifact = output
519            .find(&context.target_path, &context.target_name)
520            .ok_or_eyre("Contract artifact wasn't found locally")?;
521        let bytecode = artifact
522            .get_bytecode_object()
523            .ok_or_eyre("Contract artifact does not contain bytecode")?;
524
525        let bytecode = match bytecode.as_ref() {
526            BytecodeObject::Bytecode(bytes) => Ok(bytes),
527            BytecodeObject::Unlinked(_) => {
528                Err(eyre!("You have to provide correct libraries to use --guess-constructor-args"))
529            }
530        }?;
531
532        if maybe_creation_code.starts_with(bytecode) {
533            let constructor_args = &maybe_creation_code[bytecode.len()..];
534            let constructor_args = hex::encode(constructor_args);
535            sh_status!("Identified constructor arguments: {constructor_args}")?;
536            Ok(constructor_args)
537        } else {
538            eyre::bail!("Local bytecode doesn't match on-chain bytecode");
539        }
540    }
541}
542
543fn sanitize_remote_message(message: &str) -> String {
544    message.chars().map(|ch| if ch.is_control() { ' ' } else { ch }).take(512).collect()
545}
546
547fn apply_license_type(verify_args: &mut VerifyContract, license_type: Option<&str>) {
548    if let Some(license_type) = license_type {
549        verify_args.other.insert("licenseType".to_string(), license_type.to_string());
550    }
551}
552
553#[cfg(test)]
554mod tests {
555    use super::*;
556    use clap::Parser;
557    use foundry_common::fs;
558    use foundry_test_utils::{forgetest, str, util::SOLC_VERSION};
559    use tempfile::tempdir;
560
561    #[test]
562    fn classifies_verification_check_status() {
563        use VerificationCheckStatus::*;
564        let cases = [
565            ("0", "Pending in queue", Pending),
566            ("0", "Error: contract does not exist", Pending),
567            ("0", "Unable to verify", UnableToVerify),
568            ("1", "Already Verified", AlreadyVerified),
569            ("0", "Fail - Unable to verify", Failed),
570            ("1", "Pass - Verified", Verified),
571            ("1", "Something else", Finished),
572        ];
573        for (status, result, expected) in cases {
574            assert_eq!(VerificationCheckStatus::classify(status, result), expected, "{result}");
575        }
576    }
577
578    #[test]
579    fn external_request_preserves_raw_input_and_target() {
580        let args =
581            VerifyArgs::parse_from(["foundry-cli", "0xd8509bee9c9bf012282ad33aba0d87241baf5064"]);
582        let input = serde_json::json!({
583            "language": "Solidity",
584            "settings": { "unknownSetting": { "futureField": true } },
585            "unknownTopLevel": [1, 2, 3]
586        });
587        let context = ExternalVerificationContext {
588            config: Config::default(),
589            compiler_version: "0.8.30+commit.73712a01".parse().unwrap(),
590            standard_json_input: std::sync::Arc::new(input.clone()),
591            target: "contracts/Unknown.sol:ExactTarget".to_string(),
592        };
593
594        let request =
595            EtherscanVerificationProvider.create_external_verify_request(&args, &context).unwrap();
596        assert_eq!(serde_json::from_str::<serde_json::Value>(&request.source).unwrap(), input);
597        assert_eq!(request.contract_name, "contracts/Unknown.sol:ExactTarget");
598        assert_eq!(request.compiler_version, "v0.8.30+commit.73712a01");
599    }
600
601    #[test]
602    fn applies_license_type_to_verify_request() {
603        let mut verify_args = VerifyContract::new(
604            Default::default(),
605            "Counter".to_string(),
606            "contract Counter {}".to_string(),
607            "v0.8.23+commit.f704f362".to_string(),
608        );
609
610        apply_license_type(&mut verify_args, Some("13"));
611
612        assert_eq!(verify_args.other.get("licenseType").map(String::as_str), Some("13"));
613    }
614
615    #[test]
616    fn can_extract_etherscan_verify_config() {
617        let temp = tempdir().unwrap();
618        let root = temp.path();
619
620        let config = r#"
621                [profile.default]
622
623                [etherscan]
624                amoy = { key = "dummykey", chain = 80002, url = "https://amoy.polygonscan.com/" }
625            "#;
626
627        let toml_file = root.join(Config::FILE_NAME);
628        fs::write(toml_file, config).unwrap();
629
630        let args: VerifyArgs = VerifyArgs::parse_from([
631            "foundry-cli",
632            "0xd8509bee9c9bf012282ad33aba0d87241baf5064",
633            "src/Counter.sol:Counter",
634            "--chain",
635            "amoy",
636            "--root",
637            root.as_os_str().to_str().unwrap(),
638        ]);
639
640        let config = args.load_config().unwrap();
641
642        let etherscan = EtherscanVerificationProvider::default();
643        let client = etherscan.client(&args.etherscan, &args.verifier, &config).unwrap();
644        // Custom URL from foundry.toml should be used
645        assert_eq!(client.etherscan_api_url().as_str(), "https://amoy.polygonscan.com/");
646
647        assert!(format!("{client:?}").contains("dummykey"));
648
649        let args: VerifyArgs = VerifyArgs::parse_from([
650            "foundry-cli",
651            "0xd8509bee9c9bf012282ad33aba0d87241baf5064",
652            "src/Counter.sol:Counter",
653            "--chain",
654            "amoy",
655            "--verifier-url",
656            "https://verifier-url.com/",
657            "--root",
658            root.as_os_str().to_str().unwrap(),
659        ]);
660
661        let config = args.load_config().unwrap();
662
663        let etherscan = EtherscanVerificationProvider::default();
664        let client = etherscan.client(&args.etherscan, &args.verifier, &config).unwrap();
665        assert_eq!(client.etherscan_api_url().as_str(), "https://verifier-url.com/");
666        assert!(format!("{client:?}").contains("dummykey"));
667    }
668
669    #[test]
670    fn can_extract_etherscan_v2_verify_config() {
671        let temp = tempdir().unwrap();
672        let root = temp.path();
673
674        let config = r#"
675                [profile.default]
676
677                [etherscan]
678                amoy = { key = "dummykey", chain = 80002, url = "https://amoy.polygonscan.com/" }
679            "#;
680
681        let toml_file = root.join(Config::FILE_NAME);
682        fs::write(toml_file, config).unwrap();
683
684        let args: VerifyArgs = VerifyArgs::parse_from([
685            "foundry-cli",
686            "0xd8509bee9c9bf012282ad33aba0d87241baf5064",
687            "src/Counter.sol:Counter",
688            "--verifier",
689            "etherscan",
690            "--chain",
691            "amoy",
692            "--root",
693            root.as_os_str().to_str().unwrap(),
694        ]);
695
696        let config = args.load_config().unwrap();
697
698        let etherscan = EtherscanVerificationProvider::default();
699
700        let client = etherscan.client(&args.etherscan, &args.verifier, &config).unwrap();
701
702        // Custom URL from foundry.toml should be used
703        assert_eq!(client.etherscan_api_url().as_str(), "https://amoy.polygonscan.com/");
704        assert!(format!("{client:?}").contains("dummykey"));
705
706        let args: VerifyArgs = VerifyArgs::parse_from([
707            "foundry-cli",
708            "0xd8509bee9c9bf012282ad33aba0d87241baf5064",
709            "src/Counter.sol:Counter",
710            "--verifier",
711            "etherscan",
712            "--chain",
713            "amoy",
714            "--verifier-url",
715            "https://verifier-url.com/",
716            "--root",
717            root.as_os_str().to_str().unwrap(),
718        ]);
719
720        let config = args.load_config().unwrap();
721
722        assert_eq!(args.verifier.effective_type(), VerificationProviderType::Etherscan);
723
724        let etherscan = EtherscanVerificationProvider::default();
725        let client = etherscan.client(&args.etherscan, &args.verifier, &config).unwrap();
726        assert_eq!(client.etherscan_api_url().as_str(), "https://verifier-url.com/");
727        assert!(format!("{client:?}").contains("dummykey"));
728    }
729
730    #[tokio::test(flavor = "multi_thread")]
731    async fn fails_on_disabled_cache_and_missing_info() {
732        let temp = tempdir().unwrap();
733        let root = temp.path();
734        let root_path = root.as_os_str().to_str().unwrap();
735
736        let config = r"
737                [profile.default]
738                cache = false
739            ";
740
741        let toml_file = root.join(Config::FILE_NAME);
742        fs::write(toml_file, config).unwrap();
743
744        let address = "0xd8509bee9c9bf012282ad33aba0d87241baf5064";
745        let contract_name = "Counter";
746        let src_dir = "src";
747        fs::create_dir_all(root.join(src_dir)).unwrap();
748        let contract_path = format!("{src_dir}/Counter.sol");
749        fs::write(root.join(&contract_path), "").unwrap();
750
751        // No compiler argument
752        let args = VerifyArgs::parse_from([
753            "foundry-cli",
754            address,
755            &format!("{contract_path}:{contract_name}"),
756            "--root",
757            root_path,
758        ]);
759        let result = args.resolve_context().await;
760        assert!(result.is_err());
761        assert_eq!(
762            result.unwrap_err().to_string(),
763            "If cache is disabled, compiler version must be either provided with `--compiler-version` option or set in foundry.toml"
764        );
765    }
766
767    #[forgetest]
768    async fn respects_path_for_duplicate(prj: _, cmd: _) {
769        prj.add_source("Counter1", "contract Counter {}");
770        prj.add_source("Counter2", "contract Counter {}");
771
772        cmd.args(["build", "--force"]).assert_success().stdout_eq(str![[r#"
773[COMPILING_FILES] with [SOLC_VERSION]
774...
775[SOLC_VERSION] [ELAPSED]
776Compiler run successful!
777
778"#]]);
779
780        let args = VerifyArgs::parse_from([
781            "foundry-cli",
782            "0x0000000000000000000000000000000000000000",
783            "src/Counter1.sol:Counter",
784            "--root",
785            &prj.root().to_string_lossy(),
786        ]);
787        let context = args.resolve_context().await.unwrap();
788
789        let mut etherscan = EtherscanVerificationProvider::default();
790        etherscan.preflight_verify_check(args, context).await.unwrap();
791    }
792
793    #[forgetest]
794    async fn encodes_constructor_args_from_file(prj: _) {
795        let args_path = prj.root().join("constructor-args.json");
796        for (name, source, input, expected) in [
797            (
798                "Mixed",
799                "contract Mixed { constructor(uint256, string memory, uint256[] memory) {} }",
800                r#"["7", "hello", "[1,2]"]"#,
801                concat!(
802                    "0000000000000000000000000000000000000000000000000000000000000007",
803                    "0000000000000000000000000000000000000000000000000000000000000060",
804                    "00000000000000000000000000000000000000000000000000000000000000a0",
805                    "0000000000000000000000000000000000000000000000000000000000000005",
806                    "68656c6c6f000000000000000000000000000000000000000000000000000000",
807                    "0000000000000000000000000000000000000000000000000000000000000002",
808                    "0000000000000000000000000000000000000000000000000000000000000001",
809                    "0000000000000000000000000000000000000000000000000000000000000002",
810                ),
811            ),
812            ("Empty", "contract Empty { constructor() {} }", "[]", ""),
813        ] {
814            prj.add_source(name, source);
815            fs::write(&args_path, input).unwrap();
816            let args = VerifyArgs::parse_from([
817                "foundry-cli",
818                "0x0000000000000000000000000000000000000000",
819                &format!("src/{name}.sol:{name}"),
820                "--root",
821                &prj.root().to_string_lossy(),
822                "--constructor-args-path",
823                &args_path.to_string_lossy(),
824                "--compiler-version",
825                SOLC_VERSION,
826            ]);
827            let context = args.resolve_context().await.unwrap();
828            let mut etherscan = EtherscanVerificationProvider::default();
829            let encoded = etherscan.constructor_args(&args, &context).await.unwrap();
830            assert_eq!(encoded.as_deref(), Some(expected));
831
832            if name == "Mixed" {
833                fs::write(&args_path, r#"["7"]"#).unwrap();
834                let error = etherscan.constructor_args(&args, &context).await.unwrap_err();
835                assert_eq!(error.to_string(), "encode length mismatch: expected 3 types, got 1");
836            }
837        }
838    }
839}