forge_verify/etherscan/
mod.rs

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