forge_script/
verify.rs

1use crate::{
2    build::LinkedBuildData,
3    sequence::{get_commit_hash, ScriptSequenceKind},
4    ScriptArgs, ScriptConfig,
5};
6use alloy_primitives::{hex, Address};
7use eyre::{eyre, Result};
8use forge_script_sequence::{AdditionalContract, ScriptSequence};
9use forge_verify::{provider::VerificationProviderType, RetryArgs, VerifierArgs, VerifyArgs};
10use foundry_cli::opts::{EtherscanOpts, ProjectPathOpts};
11use foundry_common::ContractsByArtifact;
12use foundry_compilers::{artifacts::EvmVersion, info::ContractInfo, Project};
13use foundry_config::{Chain, Config};
14use semver::Version;
15
16/// State after we have broadcasted the script.
17/// It is assumed that at this point [BroadcastedState::sequence] contains receipts for all
18/// broadcasted transactions.
19pub struct BroadcastedState {
20    pub args: ScriptArgs,
21    pub script_config: ScriptConfig,
22    pub build_data: LinkedBuildData,
23    pub sequence: ScriptSequenceKind,
24}
25
26impl BroadcastedState {
27    pub async fn verify(self) -> Result<()> {
28        let Self { args, script_config, build_data, mut sequence, .. } = self;
29
30        let verify = VerifyBundle::new(
31            &script_config.config.project()?,
32            &script_config.config,
33            build_data.known_contracts,
34            args.retry,
35            args.verifier,
36        );
37
38        for sequence in sequence.sequences_mut() {
39            verify_contracts(sequence, &script_config.config, verify.clone()).await?;
40        }
41
42        Ok(())
43    }
44}
45
46/// Data struct to help `ScriptSequence` verify contracts on `etherscan`.
47#[derive(Clone)]
48pub struct VerifyBundle {
49    pub num_of_optimizations: Option<usize>,
50    pub known_contracts: ContractsByArtifact,
51    pub project_paths: ProjectPathOpts,
52    pub etherscan: EtherscanOpts,
53    pub retry: RetryArgs,
54    pub verifier: VerifierArgs,
55    pub via_ir: bool,
56}
57
58impl VerifyBundle {
59    pub fn new(
60        project: &Project,
61        config: &Config,
62        known_contracts: ContractsByArtifact,
63        retry: RetryArgs,
64        verifier: VerifierArgs,
65    ) -> Self {
66        let num_of_optimizations =
67            if config.optimizer == Some(true) { config.optimizer_runs } else { None };
68
69        let config_path = config.get_config_path();
70
71        let project_paths = ProjectPathOpts {
72            root: Some(project.paths.root.clone()),
73            contracts: Some(project.paths.sources.clone()),
74            remappings: project.paths.remappings.clone(),
75            remappings_env: None,
76            cache_path: Some(project.paths.cache.clone()),
77            lib_paths: project.paths.libraries.clone(),
78            hardhat: config.profile == Config::HARDHAT_PROFILE,
79            config_path: if config_path.exists() { Some(config_path) } else { None },
80        };
81
82        let via_ir = config.via_ir;
83
84        Self {
85            num_of_optimizations,
86            known_contracts,
87            etherscan: Default::default(),
88            project_paths,
89            retry,
90            verifier,
91            via_ir,
92        }
93    }
94
95    /// Configures the chain and sets the etherscan key, if available
96    pub fn set_chain(&mut self, config: &Config, chain: Chain) {
97        // If dealing with multiple chains, we need to be able to change in between the config
98        // chain_id.
99        self.etherscan.key = config.get_etherscan_api_key(Some(chain));
100        self.etherscan.chain = Some(chain);
101    }
102
103    /// Given a `VerifyBundle` and contract details, it tries to generate a valid `VerifyArgs` to
104    /// use against the `contract_address`.
105    pub fn get_verify_args(
106        &self,
107        contract_address: Address,
108        create2_offset: usize,
109        data: &[u8],
110        libraries: &[String],
111        evm_version: EvmVersion,
112    ) -> Option<VerifyArgs> {
113        for (artifact, contract) in self.known_contracts.iter() {
114            let Some(bytecode) = contract.bytecode() else { continue };
115            // If it's a CREATE2, the tx.data comes with a 32-byte salt in the beginning
116            // of the transaction
117            if data.split_at(create2_offset).1.starts_with(bytecode) {
118                let constructor_args = data.split_at(create2_offset + bytecode.len()).1.to_vec();
119
120                if artifact.source.extension().is_some_and(|e| e.to_str() == Some("vy")) {
121                    warn!("Skipping verification of Vyper contract: {}", artifact.name);
122                }
123
124                // Strip artifact profile from contract name when creating contract info.
125                let contract = ContractInfo {
126                    path: Some(artifact.source.to_string_lossy().to_string()),
127                    name: artifact
128                        .name
129                        .strip_suffix(&format!(".{}", &artifact.profile))
130                        .unwrap_or_else(|| &artifact.name)
131                        .to_string(),
132                };
133
134                // We strip the build metadadata information, since it can lead to
135                // etherscan not identifying it correctly. eg:
136                // `v0.8.10+commit.fc410830.Linux.gcc` != `v0.8.10+commit.fc410830`
137                let version = Version::new(
138                    artifact.version.major,
139                    artifact.version.minor,
140                    artifact.version.patch,
141                );
142
143                let verify = VerifyArgs {
144                    address: contract_address,
145                    contract: Some(contract),
146                    compiler_version: Some(version.to_string()),
147                    constructor_args: Some(hex::encode(constructor_args)),
148                    constructor_args_path: None,
149                    num_of_optimizations: self.num_of_optimizations,
150                    etherscan: self.etherscan.clone(),
151                    rpc: Default::default(),
152                    flatten: false,
153                    force: false,
154                    skip_is_verified_check: true,
155                    watch: true,
156                    retry: self.retry,
157                    libraries: libraries.to_vec(),
158                    root: None,
159                    verifier: self.verifier.clone(),
160                    via_ir: self.via_ir,
161                    evm_version: Some(evm_version),
162                    show_standard_json_input: false,
163                    guess_constructor_args: false,
164                    compilation_profile: Some(artifact.profile.to_string()),
165                };
166
167                return Some(verify)
168            }
169        }
170        None
171    }
172}
173
174/// Given the broadcast log, it matches transactions with receipts, and tries to verify any
175/// created contract on etherscan.
176async fn verify_contracts(
177    sequence: &mut ScriptSequence,
178    config: &Config,
179    mut verify: VerifyBundle,
180) -> Result<()> {
181    trace!(target: "script", "verifying {} contracts [{}]", verify.known_contracts.len(), sequence.chain);
182
183    verify.set_chain(config, sequence.chain.into());
184
185    if verify.etherscan.has_key() || verify.verifier.verifier != VerificationProviderType::Etherscan
186    {
187        trace!(target: "script", "prepare future verifications");
188
189        let mut future_verifications = Vec::with_capacity(sequence.receipts.len());
190        let mut unverifiable_contracts = vec![];
191
192        // Make sure the receipts have the right order first.
193        sequence.sort_receipts();
194
195        for (receipt, tx) in sequence.receipts.iter_mut().zip(sequence.transactions.iter()) {
196            // create2 hash offset
197            let mut offset = 0;
198
199            if tx.is_create2() {
200                receipt.contract_address = tx.contract_address;
201                offset = 32;
202            }
203
204            // Verify contract created directly from the transaction
205            if let (Some(address), Some(data)) = (receipt.contract_address, tx.tx().input()) {
206                match verify.get_verify_args(
207                    address,
208                    offset,
209                    data,
210                    &sequence.libraries,
211                    config.evm_version,
212                ) {
213                    Some(verify) => future_verifications.push(verify.run()),
214                    None => unverifiable_contracts.push(address),
215                };
216            }
217
218            // Verify potential contracts created during the transaction execution
219            for AdditionalContract { address, init_code, .. } in &tx.additional_contracts {
220                match verify.get_verify_args(
221                    *address,
222                    0,
223                    init_code.as_ref(),
224                    &sequence.libraries,
225                    config.evm_version,
226                ) {
227                    Some(verify) => future_verifications.push(verify.run()),
228                    None => unverifiable_contracts.push(*address),
229                };
230            }
231        }
232
233        trace!(target: "script", "collected {} verification jobs and {} unverifiable contracts", future_verifications.len(), unverifiable_contracts.len());
234
235        check_unverified(sequence, unverifiable_contracts, verify);
236
237        let num_verifications = future_verifications.len();
238        let mut num_of_successful_verifications = 0;
239        sh_println!("##\nStart verification for ({num_verifications}) contracts")?;
240        for verification in future_verifications {
241            match verification.await {
242                Ok(_) => {
243                    num_of_successful_verifications += 1;
244                }
245                Err(err) => {
246                    sh_err!("Failed to verify contract: {err:#}")?;
247                }
248            }
249        }
250
251        if num_of_successful_verifications < num_verifications {
252            return Err(eyre!("Not all ({num_of_successful_verifications} / {num_verifications}) contracts were verified!"))
253        }
254
255        sh_println!("All ({num_verifications}) contracts were verified!")?;
256    }
257
258    Ok(())
259}
260
261fn check_unverified(
262    sequence: &ScriptSequence,
263    unverifiable_contracts: Vec<Address>,
264    verify: VerifyBundle,
265) {
266    if !unverifiable_contracts.is_empty() {
267        let _ = sh_warn!(
268            "We haven't found any matching bytecode for the following contracts: {:?}.\n\nThis may occur when resuming a verification, but the underlying source code or compiler version has changed.",
269            unverifiable_contracts
270        );
271
272        if let Some(commit) = &sequence.commit {
273            let current_commit = verify
274                .project_paths
275                .root
276                .map(|root| get_commit_hash(&root).unwrap_or_default())
277                .unwrap_or_default();
278
279            if &current_commit != commit {
280                let _ = sh_warn!(
281                    "Script was broadcasted on commit `{commit}`, but we are at `{current_commit}`."
282                );
283            }
284        }
285    }
286}