forge_verify/etherscan/
mod.rs

1use crate::{
2    VerifierArgs,
3    provider::{VerificationContext, VerificationProvider},
4    retry::RETRY_CHECK_ON_VERIFY,
5    verify::{ContractLanguage, VerifyArgs, VerifyCheckArgs},
6};
7use alloy_json_abi::Function;
8use alloy_primitives::hex;
9use alloy_provider::Provider;
10use alloy_rpc_types::TransactionTrait;
11use eyre::{Context, OptionExt, Result, eyre};
12use foundry_block_explorers::{
13    Client, EtherscanApiVersion,
14    errors::EtherscanError,
15    utils::lookup_compiler_version,
16    verify::{CodeFormat, VerifyContract},
17};
18use foundry_cli::{
19    opts::EtherscanOpts,
20    utils::{LoadConfig, get_provider, read_constructor_args_file},
21};
22use foundry_common::{abi::encode_function_args, retry::RetryError};
23use foundry_compilers::{Artifact, artifacts::BytecodeObject};
24use foundry_config::Config;
25use foundry_evm::constants::DEFAULT_CREATE2_DEPLOYER;
26use regex::Regex;
27use semver::{BuildMetadata, Version};
28use std::{fmt::Debug, sync::LazyLock};
29
30mod flatten;
31
32mod standard_json;
33
34pub static RE_BUILD_COMMIT: LazyLock<Regex> =
35    LazyLock::new(|| Regex::new(r"(?P<commit>commit\.[0-9,a-f]{8})").unwrap());
36
37#[derive(Clone, Debug, Default)]
38#[non_exhaustive]
39pub struct EtherscanVerificationProvider;
40
41/// The contract source provider for [EtherscanVerificationProvider]
42///
43/// Returns source, contract_name and the source [CodeFormat]
44trait EtherscanSourceProvider: Send + Sync + Debug {
45    fn source(
46        &self,
47        args: &VerifyArgs,
48        context: &VerificationContext,
49    ) -> Result<(String, String, CodeFormat)>;
50}
51
52#[async_trait::async_trait]
53impl VerificationProvider for EtherscanVerificationProvider {
54    async fn preflight_verify_check(
55        &mut self,
56        args: VerifyArgs,
57        context: VerificationContext,
58    ) -> Result<()> {
59        let _ = self.prepare_verify_request(&args, &context).await?;
60        Ok(())
61    }
62
63    async fn verify(&mut self, args: VerifyArgs, context: VerificationContext) -> Result<()> {
64        let (etherscan, verify_args) = self.prepare_verify_request(&args, &context).await?;
65
66        if !args.skip_is_verified_check
67            && self.is_contract_verified(&etherscan, &verify_args).await?
68        {
69            sh_println!(
70                "\nContract [{}] {:?} is already verified. Skipping verification.",
71                verify_args.contract_name,
72                verify_args.address.to_checksum(None)
73            )?;
74
75            return Ok(());
76        }
77
78        trace!(?verify_args, "submitting verification request");
79
80        let resp = args
81            .retry
82            .into_retry()
83            .run_async(|| async {
84                sh_println!(
85                    "\nSubmitting verification for [{}] {}.",
86                    verify_args.contract_name,
87                    verify_args.address
88                )?;
89                let resp = etherscan
90                    .submit_contract_verification(&verify_args)
91                    .await
92                    .wrap_err_with(|| {
93                        // valid json
94                        let args = serde_json::to_string(&verify_args).unwrap();
95                        error!(?args, "Failed to submit verification");
96                        format!("Failed to submit contract verification, payload:\n{args}")
97                    })?;
98
99                trace!(?resp, "Received verification response");
100
101                if resp.status == "0" {
102                    if resp.result == "Contract source code already verified"
103                        // specific for blockscout response
104                        || resp.result == "Smart-contract already verified."
105                    {
106                        return Ok(None);
107                    }
108
109                    if resp.result.starts_with("Unable to locate ContractCode at")
110                        || resp.result.starts_with("The address is not a smart contract")
111                    {
112                        warn!("{}", resp.result);
113                        return Err(eyre!("Could not detect the deployment."));
114                    }
115
116                    warn!("Failed verify submission: {:?}", resp);
117                    sh_err!(
118                        "Encountered an error verifying this contract:\nResponse: `{}`\nDetails:
119                        `{}`",
120                        resp.message,
121                        resp.result
122                    )?;
123                    std::process::exit(1);
124                }
125
126                Ok(Some(resp))
127            })
128            .await?;
129
130        if let Some(resp) = resp {
131            sh_println!(
132                "Submitted contract for verification:\n\tResponse: `{}`\n\tGUID: `{}`\n\tURL: {}",
133                resp.message,
134                resp.result,
135                etherscan.address_url(args.address)
136            )?;
137
138            if args.watch {
139                let check_args = VerifyCheckArgs {
140                    id: resp.result,
141                    etherscan: args.etherscan,
142                    retry: RETRY_CHECK_ON_VERIFY,
143                    verifier: args.verifier,
144                };
145                return self.check(check_args).await;
146            }
147        } else {
148            sh_println!("Contract source code already verified")?;
149        }
150
151        Ok(())
152    }
153
154    /// Executes the command to check verification status on Etherscan
155    async fn check(&self, args: VerifyCheckArgs) -> Result<()> {
156        let config = args.load_config()?;
157        let etherscan = self.client(&args.etherscan, &args.verifier, &config)?;
158        args.retry
159            .into_retry()
160            .run_async_until_break(|| async {
161                let resp = etherscan
162                    .check_contract_verification_status(args.id.clone())
163                    .await
164                    .wrap_err("Failed to request verification status")
165                    .map_err(RetryError::Retry)?;
166
167                trace!(?resp, "Received verification response");
168
169                let _ = sh_println!(
170                    "Contract verification status:\nResponse: `{}`\nDetails: `{}`",
171                    resp.message,
172                    resp.result
173                );
174
175                if resp.result == "Pending in queue" {
176                    return Err(RetryError::Retry(eyre!("Verification is still pending...")));
177                }
178
179                if resp.result == "Unable to verify" {
180                    return Err(RetryError::Retry(eyre!("Unable to verify.")));
181                }
182
183                if resp.result == "Already Verified" {
184                    let _ = sh_println!("Contract source code already verified");
185                    return Ok(());
186                }
187
188                if resp.status == "0" {
189                    return Err(RetryError::Break(eyre!("Contract failed to verify.")));
190                }
191
192                if resp.result == "Pass - Verified" {
193                    let _ = sh_println!("Contract successfully verified");
194                }
195
196                Ok(())
197            })
198            .await
199            .wrap_err("Checking verification result failed")
200    }
201}
202
203impl EtherscanVerificationProvider {
204    /// Create a source provider
205    fn source_provider(&self, args: &VerifyArgs) -> Box<dyn EtherscanSourceProvider> {
206        if args.flatten {
207            Box::new(flatten::EtherscanFlattenedSource)
208        } else {
209            Box::new(standard_json::EtherscanStandardJsonSource)
210        }
211    }
212
213    /// Configures the API request to the Etherscan API using the given [`VerifyArgs`].
214    async fn prepare_verify_request(
215        &mut self,
216        args: &VerifyArgs,
217        context: &VerificationContext,
218    ) -> Result<(Client, VerifyContract)> {
219        let config = args.load_config()?;
220        let etherscan = self.client(&args.etherscan, &args.verifier, &config)?;
221        let verify_args = self.create_verify_request(args, context).await?;
222
223        Ok((etherscan, verify_args))
224    }
225
226    /// Queries the Etherscan API to verify if the contract is already verified.
227    async fn is_contract_verified(
228        &self,
229        etherscan: &Client,
230        verify_contract: &VerifyContract,
231    ) -> Result<bool> {
232        let check = etherscan.contract_abi(verify_contract.address).await;
233
234        if let Err(err) = check {
235            return match err {
236                EtherscanError::ContractCodeNotVerified(_) => Ok(false),
237                error => Err(error).wrap_err_with(|| {
238                    format!("Failed to obtain contract ABI for {}", verify_contract.address)
239                }),
240            };
241        }
242
243        Ok(true)
244    }
245
246    /// Create an Etherscan client.
247    pub(crate) fn client(
248        &self,
249        etherscan_opts: &EtherscanOpts,
250        verifier_args: &VerifierArgs,
251        config: &Config,
252    ) -> Result<Client> {
253        let chain = etherscan_opts.chain.unwrap_or_default();
254        let etherscan_key = etherscan_opts.key();
255        let verifier_type = &verifier_args.verifier;
256        let verifier_url = verifier_args.verifier_url.as_deref();
257
258        // Verifier is etherscan if explicitly set or if no verifier set (default sourcify) but
259        // API key passed.
260        let is_etherscan = verifier_type.is_etherscan()
261            || (verifier_type.is_sourcify() && etherscan_key.is_some());
262        let etherscan_config = config.get_etherscan_config_with_chain(Some(chain))?;
263
264        let api_version = verifier_args.verifier_api_version.unwrap_or_else(|| {
265            if is_etherscan {
266                etherscan_config.as_ref().map(|c| c.api_version).unwrap_or_default()
267            } else {
268                EtherscanApiVersion::V1
269            }
270        });
271
272        let etherscan_api_url = verifier_url
273            .or_else(|| {
274                if api_version == EtherscanApiVersion::V2 {
275                    None
276                } else {
277                    etherscan_config.as_ref().map(|c| c.api_url.as_str())
278                }
279            })
280            .map(str::to_owned);
281
282        let api_url = etherscan_api_url.as_deref();
283        let base_url = etherscan_config
284            .as_ref()
285            .and_then(|c| c.browser_url.as_deref())
286            .or_else(|| chain.etherscan_urls().map(|(_, url)| url));
287        let etherscan_key =
288            etherscan_key.or_else(|| etherscan_config.as_ref().map(|c| c.key.clone()));
289
290        let mut builder = Client::builder().with_api_version(api_version);
291
292        builder = if let Some(api_url) = api_url {
293            // we don't want any trailing slashes because this can cause cloudflare issues: <https://github.com/foundry-rs/foundry/pull/6079>
294            let api_url = api_url.trim_end_matches('/');
295            let base_url = if !is_etherscan {
296                // If verifier is not Etherscan then set base url as api url without /api suffix.
297                api_url.strip_prefix("/api").unwrap_or(api_url)
298            } else {
299                base_url.unwrap_or(api_url)
300            };
301            builder.with_chain_id(chain).with_api_url(api_url)?.with_url(base_url)?
302        } else {
303            builder.chain(chain)?
304        };
305
306        builder
307            .with_api_key(etherscan_key.unwrap_or_default())
308            .build()
309            .wrap_err("Failed to create Etherscan client")
310    }
311
312    /// Creates the `VerifyContract` Etherscan request in order to verify the contract
313    ///
314    /// If `--flatten` is set to `true` then this will send with [`CodeFormat::SingleFile`]
315    /// otherwise this will use the [`CodeFormat::StandardJsonInput`]
316    pub async fn create_verify_request(
317        &mut self,
318        args: &VerifyArgs,
319        context: &VerificationContext,
320    ) -> Result<VerifyContract> {
321        let (source, contract_name, code_format) =
322            self.source_provider(args).source(args, context)?;
323
324        let lang = args.detect_language(context);
325
326        let mut compiler_version = context.compiler_version.clone();
327        compiler_version.build = match RE_BUILD_COMMIT.captures(compiler_version.build.as_str()) {
328            Some(cap) => BuildMetadata::new(cap.name("commit").unwrap().as_str())?,
329            _ => BuildMetadata::EMPTY,
330        };
331
332        let compiler_version = if matches!(lang, ContractLanguage::Vyper) {
333            format!("vyper:{}", compiler_version.to_string().split('+').next().unwrap_or("0.0.0"))
334        } else {
335            format!("v{}", ensure_solc_build_metadata(context.compiler_version.clone()).await?)
336        };
337
338        let constructor_args = self.constructor_args(args, context).await?;
339        let mut verify_args =
340            VerifyContract::new(args.address, contract_name, source, compiler_version)
341                .constructor_arguments(constructor_args)
342                .code_format(code_format);
343
344        if args.via_ir {
345            // we explicitly set this __undocumented__ argument to true if provided by the user,
346            // though this info is also available in the compiler settings of the standard json
347            // object if standard json is used
348            // unclear how Etherscan interprets this field in standard-json mode
349            verify_args = verify_args.via_ir(true);
350        }
351
352        if code_format == CodeFormat::SingleFile {
353            verify_args = if let Some(optimizations) = args.num_of_optimizations {
354                verify_args.optimized().runs(optimizations as u32)
355            } else if context.config.optimizer == Some(true) {
356                verify_args
357                    .optimized()
358                    .runs(context.config.optimizer_runs.unwrap_or(200).try_into()?)
359            } else {
360                verify_args.not_optimized()
361            };
362        }
363
364        if code_format == CodeFormat::VyperJson {
365            verify_args =
366                if args.num_of_optimizations.is_some() || context.config.optimizer == Some(true) {
367                    verify_args.optimized().runs(1)
368                } else {
369                    verify_args.not_optimized().runs(0)
370                }
371        }
372
373        Ok(verify_args)
374    }
375
376    /// Return the optional encoded constructor arguments. If the path to
377    /// constructor arguments was provided, read them and encode. Otherwise,
378    /// return whatever was set in the [VerifyArgs] args.
379    async fn constructor_args(
380        &mut self,
381        args: &VerifyArgs,
382        context: &VerificationContext,
383    ) -> Result<Option<String>> {
384        if let Some(ref constructor_args_path) = args.constructor_args_path {
385            let abi = context.get_target_abi()?;
386            let constructor = abi
387                .constructor()
388                .ok_or_else(|| eyre!("Can't retrieve constructor info from artifact ABI."))?;
389            let func = Function {
390                name: "constructor".to_string(),
391                inputs: constructor.inputs.clone(),
392                outputs: vec![],
393                state_mutability: alloy_json_abi::StateMutability::NonPayable,
394            };
395            let encoded_args = encode_function_args(
396                &func,
397                read_constructor_args_file(constructor_args_path.to_path_buf())?,
398            )?;
399            let encoded_args = hex::encode(encoded_args);
400            return Ok(Some(encoded_args[8..].into()));
401        }
402        if args.guess_constructor_args {
403            return Ok(Some(self.guess_constructor_args(args, context).await?));
404        }
405
406        Ok(args.constructor_args.clone())
407    }
408
409    /// Uses Etherscan API to fetch contract creation transaction.
410    /// If transaction is a create transaction or a invocation of default CREATE2 deployer, tries to
411    /// match provided creation code with local bytecode of the target contract.
412    /// If bytecode match, returns latest bytes of on-chain creation code as constructor arguments.
413    async fn guess_constructor_args(
414        &mut self,
415        args: &VerifyArgs,
416        context: &VerificationContext,
417    ) -> Result<String> {
418        let provider = get_provider(&context.config)?;
419        let client = self.client(&args.etherscan, &args.verifier, &context.config)?;
420
421        let creation_data = client.contract_creation_data(args.address).await?;
422        let transaction = provider
423            .get_transaction_by_hash(creation_data.transaction_hash)
424            .await?
425            .ok_or_eyre("Transaction not found")?;
426        let receipt = provider
427            .get_transaction_receipt(creation_data.transaction_hash)
428            .await?
429            .ok_or_eyre("Couldn't fetch transaction receipt from RPC")?;
430
431        let maybe_creation_code = if receipt.contract_address == Some(args.address) {
432            transaction.inner.inner.input()
433        } else if transaction.to() == Some(DEFAULT_CREATE2_DEPLOYER) {
434            &transaction.inner.inner.input()[32..]
435        } else {
436            eyre::bail!(
437                "Fetching of constructor arguments is not supported for contracts created by contracts"
438            )
439        };
440
441        let output = context.project.compile_file(&context.target_path)?;
442        let artifact = output
443            .find(&context.target_path, &context.target_name)
444            .ok_or_eyre("Contract artifact wasn't found locally")?;
445        let bytecode = artifact
446            .get_bytecode_object()
447            .ok_or_eyre("Contract artifact does not contain bytecode")?;
448
449        let bytecode = match bytecode.as_ref() {
450            BytecodeObject::Bytecode(bytes) => Ok(bytes),
451            BytecodeObject::Unlinked(_) => {
452                Err(eyre!("You have to provide correct libraries to use --guess-constructor-args"))
453            }
454        }?;
455
456        if maybe_creation_code.starts_with(bytecode) {
457            let constructor_args = &maybe_creation_code[bytecode.len()..];
458            let constructor_args = hex::encode(constructor_args);
459            sh_println!("Identified constructor arguments: {constructor_args}")?;
460            Ok(constructor_args)
461        } else {
462            eyre::bail!("Local bytecode doesn't match on-chain bytecode")
463        }
464    }
465}
466
467/// Given any solc [Version] return a [Version] with build metadata
468///
469/// # Example
470///
471/// ```ignore
472/// use semver::{BuildMetadata, Version};
473/// let version = Version::new(1, 2, 3);
474/// let version = ensure_solc_build_metadata(version).await?;
475/// assert_ne!(version.build, BuildMetadata::EMPTY);
476/// ```
477async fn ensure_solc_build_metadata(version: Version) -> Result<Version> {
478    if version.build != BuildMetadata::EMPTY {
479        Ok(version)
480    } else {
481        Ok(lookup_compiler_version(&version).await?)
482    }
483}
484
485#[cfg(test)]
486mod tests {
487    use super::*;
488    use crate::provider::VerificationProviderType;
489    use clap::Parser;
490    use foundry_common::fs;
491    use foundry_test_utils::{forgetest_async, str};
492    use tempfile::tempdir;
493
494    #[test]
495    fn can_extract_etherscan_verify_config() {
496        let temp = tempdir().unwrap();
497        let root = temp.path();
498
499        let config = r#"
500                [profile.default]
501
502                [etherscan]
503                mumbai = { key = "dummykey", chain = 80001, url = "https://api-testnet.polygonscan.com/" }
504            "#;
505
506        let toml_file = root.join(Config::FILE_NAME);
507        fs::write(toml_file, config).unwrap();
508
509        let args: VerifyArgs = VerifyArgs::parse_from([
510            "foundry-cli",
511            "0xd8509bee9c9bf012282ad33aba0d87241baf5064",
512            "src/Counter.sol:Counter",
513            "--chain",
514            "mumbai",
515            "--root",
516            root.as_os_str().to_str().unwrap(),
517        ]);
518
519        let config = args.load_config().unwrap();
520
521        let etherscan = EtherscanVerificationProvider::default();
522        let client = etherscan.client(&args.etherscan, &args.verifier, &config).unwrap();
523        assert_eq!(client.etherscan_api_url().as_str(), "https://api-testnet.polygonscan.com/");
524
525        assert!(format!("{client:?}").contains("dummykey"));
526
527        let args: VerifyArgs = VerifyArgs::parse_from([
528            "foundry-cli",
529            "0xd8509bee9c9bf012282ad33aba0d87241baf5064",
530            "src/Counter.sol:Counter",
531            "--chain",
532            "mumbai",
533            "--verifier-url",
534            "https://verifier-url.com/",
535            "--root",
536            root.as_os_str().to_str().unwrap(),
537        ]);
538
539        let config = args.load_config().unwrap();
540
541        let etherscan = EtherscanVerificationProvider::default();
542        let client = etherscan.client(&args.etherscan, &args.verifier, &config).unwrap();
543        assert_eq!(client.etherscan_api_url().as_str(), "https://verifier-url.com/");
544        assert!(format!("{client:?}").contains("dummykey"));
545    }
546
547    #[test]
548    fn can_extract_etherscan_v2_verify_config() {
549        let temp = tempdir().unwrap();
550        let root = temp.path();
551
552        let config = r#"
553                [profile.default]
554
555                [etherscan]
556                mumbai = { key = "dummykey", chain = 80001, url = "https://api-testnet.polygonscan.com/" }
557            "#;
558
559        let toml_file = root.join(Config::FILE_NAME);
560        fs::write(toml_file, config).unwrap();
561
562        let args: VerifyArgs = VerifyArgs::parse_from([
563            "foundry-cli",
564            "0xd8509bee9c9bf012282ad33aba0d87241baf5064",
565            "src/Counter.sol:Counter",
566            "--verifier",
567            "etherscan",
568            "--chain",
569            "mumbai",
570            "--root",
571            root.as_os_str().to_str().unwrap(),
572        ]);
573
574        let config = args.load_config().unwrap();
575
576        let etherscan = EtherscanVerificationProvider::default();
577
578        let client = etherscan.client(&args.etherscan, &args.verifier, &config).unwrap();
579
580        assert_eq!(client.etherscan_api_url().as_str(), "https://api.etherscan.io/v2/api");
581        assert!(format!("{client:?}").contains("dummykey"));
582
583        let args: VerifyArgs = VerifyArgs::parse_from([
584            "foundry-cli",
585            "0xd8509bee9c9bf012282ad33aba0d87241baf5064",
586            "src/Counter.sol:Counter",
587            "--verifier",
588            "etherscan",
589            "--chain",
590            "mumbai",
591            "--verifier-url",
592            "https://verifier-url.com/",
593            "--root",
594            root.as_os_str().to_str().unwrap(),
595        ]);
596
597        let config = args.load_config().unwrap();
598
599        assert_eq!(args.verifier.verifier, VerificationProviderType::Etherscan);
600
601        let etherscan = EtherscanVerificationProvider::default();
602        let client = etherscan.client(&args.etherscan, &args.verifier, &config).unwrap();
603        assert_eq!(client.etherscan_api_url().as_str(), "https://verifier-url.com/");
604        assert_eq!(*client.etherscan_api_version(), EtherscanApiVersion::V2);
605        assert!(format!("{client:?}").contains("dummykey"));
606    }
607
608    #[tokio::test(flavor = "multi_thread")]
609    async fn fails_on_disabled_cache_and_missing_info() {
610        let temp = tempdir().unwrap();
611        let root = temp.path();
612        let root_path = root.as_os_str().to_str().unwrap();
613
614        let config = r"
615                [profile.default]
616                cache = false
617            ";
618
619        let toml_file = root.join(Config::FILE_NAME);
620        fs::write(toml_file, config).unwrap();
621
622        let address = "0xd8509bee9c9bf012282ad33aba0d87241baf5064";
623        let contract_name = "Counter";
624        let src_dir = "src";
625        fs::create_dir_all(root.join(src_dir)).unwrap();
626        let contract_path = format!("{src_dir}/Counter.sol");
627        fs::write(root.join(&contract_path), "").unwrap();
628
629        // No compiler argument
630        let args = VerifyArgs::parse_from([
631            "foundry-cli",
632            address,
633            &format!("{contract_path}:{contract_name}"),
634            "--root",
635            root_path,
636        ]);
637        let result = args.resolve_context().await;
638        assert!(result.is_err());
639        assert_eq!(
640            result.unwrap_err().to_string(),
641            "If cache is disabled, compiler version must be either provided with `--compiler-version` option or set in foundry.toml"
642        );
643    }
644
645    forgetest_async!(respects_path_for_duplicate, |prj, cmd| {
646        prj.add_source("Counter1", "contract Counter {}").unwrap();
647        prj.add_source("Counter2", "contract Counter {}").unwrap();
648
649        cmd.args(["build", "--force"]).assert_success().stdout_eq(str![[r#"
650[COMPILING_FILES] with [SOLC_VERSION]
651...
652[SOLC_VERSION] [ELAPSED]
653Compiler run successful!
654
655"#]]);
656
657        let args = VerifyArgs::parse_from([
658            "foundry-cli",
659            "0x0000000000000000000000000000000000000000",
660            "src/Counter1.sol:Counter",
661            "--root",
662            &prj.root().to_string_lossy(),
663        ]);
664        let context = args.resolve_context().await.unwrap();
665
666        let mut etherscan = EtherscanVerificationProvider::default();
667        etherscan.preflight_verify_check(args, context).await.unwrap();
668    });
669}