Skip to main content

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