forge_script/
verify.rs

1use crate::{
2    ScriptArgs, ScriptConfig,
3    build::LinkedBuildData,
4    sequence::{ScriptSequenceKind, get_commit_hash},
5};
6use alloy_primitives::{Address, hex};
7use eyre::{Result, eyre};
8use forge_script_sequence::{AdditionalContract, ScriptSequence};
9use forge_verify::{RetryArgs, VerifierArgs, VerifyArgs, provider::VerificationProviderType};
10use foundry_cli::opts::{EtherscanOpts, ProjectPathOpts};
11use foundry_common::ContractsByArtifact;
12use foundry_compilers::{Project, artifacts::EvmVersion, info::ContractInfo};
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                    language: None,
166                };
167
168                return Some(verify);
169            }
170        }
171        None
172    }
173}
174
175/// Given the broadcast log, it matches transactions with receipts, and tries to verify any
176/// created contract on etherscan.
177async fn verify_contracts(
178    sequence: &mut ScriptSequence,
179    config: &Config,
180    mut verify: VerifyBundle,
181) -> Result<()> {
182    trace!(target: "script", "verifying {} contracts [{}]", verify.known_contracts.len(), sequence.chain);
183
184    verify.set_chain(config, sequence.chain.into());
185
186    if verify.etherscan.has_key() || verify.verifier.verifier != VerificationProviderType::Etherscan
187    {
188        trace!(target: "script", "prepare future verifications");
189
190        let mut future_verifications = Vec::with_capacity(sequence.receipts.len());
191        let mut unverifiable_contracts = vec![];
192
193        // Make sure the receipts have the right order first.
194        sequence.sort_receipts();
195
196        for (receipt, tx) in sequence.receipts.iter_mut().zip(sequence.transactions.iter()) {
197            // create2 hash offset
198            let mut offset = 0;
199
200            if tx.is_create2() {
201                receipt.contract_address = tx.contract_address;
202                offset = 32;
203            }
204
205            // Verify contract created directly from the transaction
206            if let (Some(address), Some(data)) = (receipt.contract_address, tx.tx().input()) {
207                match verify.get_verify_args(
208                    address,
209                    offset,
210                    data,
211                    &sequence.libraries,
212                    config.evm_version,
213                ) {
214                    Some(verify) => future_verifications.push(verify.run()),
215                    None => unverifiable_contracts.push(address),
216                };
217            }
218
219            // Verify potential contracts created during the transaction execution
220            for AdditionalContract { address, init_code, .. } in &tx.additional_contracts {
221                match verify.get_verify_args(
222                    *address,
223                    0,
224                    init_code.as_ref(),
225                    &sequence.libraries,
226                    config.evm_version,
227                ) {
228                    Some(verify) => future_verifications.push(verify.run()),
229                    None => unverifiable_contracts.push(*address),
230                };
231            }
232        }
233
234        trace!(target: "script", "collected {} verification jobs and {} unverifiable contracts", future_verifications.len(), unverifiable_contracts.len());
235
236        check_unverified(sequence, unverifiable_contracts, verify);
237
238        let num_verifications = future_verifications.len();
239        let mut num_of_successful_verifications = 0;
240        sh_println!("##\nStart verification for ({num_verifications}) contracts")?;
241        for verification in future_verifications {
242            match verification.await {
243                Ok(_) => {
244                    num_of_successful_verifications += 1;
245                }
246                Err(err) => {
247                    sh_err!("Failed to verify contract: {err:#}")?;
248                }
249            }
250        }
251
252        if num_of_successful_verifications < num_verifications {
253            return Err(eyre!(
254                "Not all ({num_of_successful_verifications} / {num_verifications}) contracts were verified!"
255            ));
256        }
257
258        sh_println!("All ({num_verifications}) contracts were verified!")?;
259    }
260
261    Ok(())
262}
263
264fn check_unverified(
265    sequence: &ScriptSequence,
266    unverifiable_contracts: Vec<Address>,
267    verify: VerifyBundle,
268) {
269    if !unverifiable_contracts.is_empty() {
270        let _ = sh_warn!(
271            "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.",
272            unverifiable_contracts
273        );
274
275        if let Some(commit) = &sequence.commit {
276            let current_commit = verify
277                .project_paths
278                .root
279                .map(|root| get_commit_hash(&root).unwrap_or_default())
280                .unwrap_or_default();
281
282            if &current_commit != commit {
283                let _ = sh_warn!(
284                    "Script was broadcasted on commit `{commit}`, but we are at `{current_commit}`."
285                );
286            }
287        }
288    }
289}