Skip to main content

forge_verify/
sourcify.rs

1use crate::{
2    provider::{
3        ExternalVerificationContext, VerificationContext, VerificationProvider,
4        VerificationProviderType,
5    },
6    utils::ensure_solc_build_metadata,
7    verify::{ContractLanguage, VerifyArgs, VerifyCheckArgs, parse_http_verifier_url},
8};
9use alloy_primitives::Address;
10use async_trait::async_trait;
11use eyre::{Context, Result, eyre};
12use foundry_common::retry::RetryError;
13use futures::{FutureExt, StreamExt};
14use reqwest::StatusCode;
15use serde::{Deserialize, Serialize};
16use std::{future::Future as StdFuture, pin::Pin, time::Duration};
17use url::Url;
18
19pub static SOURCIFY_URL: &str = "https://sourcify.dev/server/";
20
21/// The type that can verify a contract on `sourcify`
22#[derive(Clone, Debug, Default)]
23#[non_exhaustive]
24pub struct SourcifyVerificationProvider;
25
26#[async_trait]
27impl VerificationProvider for SourcifyVerificationProvider {
28    fn provider_type(&self) -> VerificationProviderType {
29        VerificationProviderType::Sourcify
30    }
31
32    async fn preflight_verify_check(
33        &mut self,
34        args: VerifyArgs,
35        context: VerificationContext,
36    ) -> Result<()> {
37        let _ = self.prepare_verify_request(&args, &context).await?;
38        Ok(())
39    }
40
41    async fn submit(
42        &mut self,
43        args: VerifyArgs,
44        context: VerificationContext,
45    ) -> Result<Option<VerifyCheckArgs>> {
46        let body = self.prepare_verify_request(&args, &context).await?;
47        self.submit_verify_request(args, body, &context.target_name).await
48    }
49
50    fn submit_external(
51        &mut self,
52        args: VerifyArgs,
53        context: ExternalVerificationContext,
54    ) -> Pin<Box<dyn StdFuture<Output = Result<Option<VerifyCheckArgs>>> + '_>> {
55        Box::pin(async move {
56            let target = context.target.clone();
57            let body = Self::prepare_external_verify_request(&args, context);
58            self.submit_verify_request(args, body, &target).await
59        })
60    }
61
62    async fn check(&self, args: VerifyCheckArgs) -> Result<()> {
63        let url = Self::get_job_status_url(args.verifier.verifier_url.as_deref(), args.id.clone())?;
64
65        args.retry
66            .into_retry()
67            .run_async_until_break(|| async {
68                let response = verification_client()
69                    .map_err(RetryError::Break)?
70                    .get(&url)
71                    .send()
72                    .await
73                    .wrap_err("Failed to request verification status")
74                    .map_err(RetryError::Retry)?;
75
76                if response.status() == StatusCode::NOT_FOUND {
77                    return Err(RetryError::Break(eyre!(
78                        "No verification job found for ID {}",
79                        sanitize_remote_message(&args.id)
80                    )));
81                }
82
83                if !response.status().is_success() {
84                    return Err(RetryError::Retry(eyre!(
85                        "Failed to request verification status with status code {}",
86                        response.status()
87                    )));
88                }
89
90                let job_response: SourcifyJobResponse = serde_json::from_slice(
91                    &read_capped_body(response).await.map_err(RetryError::Retry)?,
92                )
93                .wrap_err("Failed to parse job response")
94                .map_err(RetryError::Retry)?;
95
96                match job_response.into_status() {
97                    SourcifyJobStatus::Pending => {
98                        Err(RetryError::Retry(eyre!("Verification is still pending...")))
99                    }
100                    SourcifyJobStatus::AlreadyVerified => {
101                        let _ = sh_status!("Contract source code already verified");
102                        Ok(())
103                    }
104                    SourcifyJobStatus::Failed(error) => Err(RetryError::Break(eyre!(
105                        "Verification job failed:\nError Code: `{}`\nMessage: `{}`",
106                        sanitize_remote_message(&error.custom_code),
107                        sanitize_remote_message(&error.message)
108                    ))),
109                    SourcifyJobStatus::Verified { match_status } => {
110                        if let Some(contract_status) = match_status {
111                            let _ = sh_status!(
112                                "Contract successfully verified:\nStatus: `{}`",
113                                sanitize_remote_message(&contract_status),
114                            );
115                        }
116                        Ok(())
117                    }
118                }
119            })
120            .await
121            .wrap_err("Checking verification result failed")
122    }
123}
124
125fn sanitize_remote_message(message: &str) -> String {
126    message.chars().map(|ch| if ch.is_control() { ' ' } else { ch }).take(512).collect()
127}
128
129const MAX_RESPONSE_BODY: usize = 1024 * 1024;
130
131fn verification_client() -> Result<reqwest::Client> {
132    reqwest::Client::builder()
133        .user_agent(foundry_common::DEFAULT_USER_AGENT)
134        .timeout(Duration::from_secs(30))
135        .connect_timeout(Duration::from_secs(10))
136        .build()
137        .wrap_err("Failed to create Sourcify HTTP client")
138}
139
140async fn read_capped_body(response: reqwest::Response) -> Result<Vec<u8>> {
141    let mut body = Vec::new();
142    let mut stream = response.bytes_stream();
143    while let Some(chunk) = stream.next().await {
144        let chunk = chunk?;
145        eyre::ensure!(
146            body.len().saturating_add(chunk.len()) <= MAX_RESPONSE_BODY,
147            "Sourcify response body exceeds 1 MiB"
148        );
149        body.extend_from_slice(&chunk);
150    }
151    Ok(body)
152}
153
154impl SourcifyVerificationProvider {
155    fn prepare_external_verify_request(
156        args: &VerifyArgs,
157        context: ExternalVerificationContext,
158    ) -> SourcifyVerifyRequest {
159        SourcifyVerifyRequest {
160            std_json_input: (*context.standard_json_input).clone(),
161            compiler_version: context.compiler_version.to_string(),
162            contract_identifier: context.target,
163            creation_transaction_hash: args.creation_transaction_hash.map(|hash| hash.to_string()),
164        }
165    }
166
167    async fn submit_verify_request(
168        &self,
169        args: VerifyArgs,
170        body: SourcifyVerifyRequest,
171        target: &str,
172    ) -> Result<Option<VerifyCheckArgs>> {
173        if !args.skip_is_verified_check && self.is_contract_verified(&args).await? {
174            sh_status!(
175                "Contract [{}] {:?} is already verified. Skipping verification.",
176                target,
177                args.address.to_string()
178            )?;
179
180            return Ok(None);
181        }
182
183        trace!(provider = "Sourcify", address = %args.address, target, "submitting verification request");
184
185        let chain_id = args.etherscan.chain.unwrap_or_default().id();
186        let url =
187            Self::get_verify_url(args.verifier.verifier_url.as_deref(), chain_id, args.address)?;
188        let client = verification_client()?;
189
190        let resp = args
191            .retry
192            .into_retry()
193            .run_async(|| {
194                async {
195                    sh_status!("Submitting verification for [{}] {}.", target, args.address)?;
196                    let response = client
197                        .post(&url)
198                        .header("Content-Type", "application/json")
199                        .body(serde_json::to_string(&body)?)
200                        .send()
201                        .await?;
202
203                    let status = response.status();
204                    match status {
205                        StatusCode::CONFLICT => {
206                            sh_status!("Contract source code already fully verified")?;
207                            Ok(None)
208                        }
209                        StatusCode::ACCEPTED => {
210                            let text = read_capped_body(response).await?;
211                            let verify_response: SourcifyVerificationResponse =
212                                serde_json::from_slice(&text)
213                                    .wrap_err("Failed to parse Sourcify verification response")?;
214                            Ok(Some(verify_response))
215                        }
216                        _ => {
217                            eyre::bail!(
218                                "Sourcify verification request for address ({}) failed with status code {status}",
219                                args.address,
220                            );
221                        }
222                    }
223                }
224                .boxed()
225            })
226            .await?;
227
228        if let Some(resp) = resp {
229            eyre::ensure!(
230                !resp.verification_id.is_empty()
231                    && resp.verification_id.len() <= 512
232                    && !matches!(resp.verification_id.as_str(), "." | ".."),
233                "Sourcify returned an invalid verification job ID"
234            );
235            let display_id = sanitize_remote_message(&resp.verification_id);
236            let job_url = Self::get_job_ui_url(
237                args.verifier.verifier_url.as_deref(),
238                resp.verification_id.clone(),
239            )?;
240            sh_status!(
241                "Submitted contract for verification:\n\tVerification Job ID: `{}`\n\tURL: {}",
242                display_id,
243                job_url
244            )?;
245            if args.print_submission_result_to_stdout {
246                sh_println!("{}\t{}", display_id, job_url)?;
247            }
248            Ok(Some(VerifyCheckArgs {
249                id: resp.verification_id,
250                etherscan: args.etherscan,
251                retry: args.retry,
252                verifier: args.verifier,
253            }))
254        } else {
255            Ok(None)
256        }
257    }
258
259    /// Returns the Sourcify base URL, failing on an invalid explicit URL instead of falling back
260    /// to the public endpoint.
261    fn get_base_url(verifier_url: Option<&str>) -> Result<Url> {
262        let mut url = parse_http_verifier_url(verifier_url.unwrap_or(SOURCIFY_URL), "Sourcify")?;
263        if !url.path().ends_with('/') {
264            url.set_path(&format!("{}/", url.path()));
265        }
266        Ok(url)
267    }
268
269    fn get_verify_url(
270        verifier_url: Option<&str>,
271        chain_id: u64,
272        contract_address: Address,
273    ) -> Result<String> {
274        let base_url = Self::get_base_url(verifier_url)?;
275        Ok(format!("{base_url}v2/verify/{chain_id}/{contract_address}"))
276    }
277
278    fn get_job_status_url(verifier_url: Option<&str>, job_id: String) -> Result<String> {
279        Self::get_job_url(verifier_url, &["v2", "verify"], &job_id)
280    }
281
282    fn get_job_ui_url(verifier_url: Option<&str>, job_id: String) -> Result<String> {
283        Self::get_job_url(verifier_url, &["verify-ui", "jobs"], &job_id)
284    }
285
286    fn get_job_url(verifier_url: Option<&str>, path: &[&str], job_id: &str) -> Result<String> {
287        let base_url = Self::get_base_url(verifier_url)?;
288        let job_id = encode_path_segment(job_id);
289        Ok(format!("{base_url}{}/{job_id}", path.join("/")))
290    }
291
292    fn get_lookup_url(
293        verifier_url: Option<&str>,
294        chain_id: u64,
295        contract_address: Address,
296    ) -> Result<String> {
297        let base_url = Self::get_base_url(verifier_url)?;
298        Ok(format!("{base_url}v2/contract/{chain_id}/{contract_address}"))
299    }
300
301    /// Configures the API request to the sourcify API using the given [`VerifyArgs`].
302    async fn prepare_verify_request(
303        &self,
304        args: &VerifyArgs,
305        context: &VerificationContext,
306    ) -> Result<SourcifyVerifyRequest> {
307        // Reject an invalid explicit URL before preparing any source.
308        Self::get_base_url(args.verifier.verifier_url.as_deref())?;
309        let lang = args.detect_language(context);
310        let contract_identifier = format!(
311            "{}:{}",
312            context
313                .target_path
314                .strip_prefix(context.project.root())
315                .unwrap_or(context.target_path.as_path())
316                .display(),
317            context.target_name
318        );
319        let creation_transaction_hash = args.creation_transaction_hash.map(|h| h.to_string());
320
321        match lang {
322            ContractLanguage::Solidity => {
323                let input = context.get_solc_standard_json_input()?;
324
325                let std_json_input = serde_json::to_value(&input)
326                    .wrap_err("Failed to serialize standard json input")?;
327                let compiler_version =
328                    ensure_solc_build_metadata(context.compiler_version.clone()).await?.to_string();
329
330                Ok(SourcifyVerifyRequest {
331                    std_json_input,
332                    compiler_version,
333                    contract_identifier,
334                    creation_transaction_hash,
335                })
336            }
337            ContractLanguage::Vyper => {
338                let input = context.get_vyper_standard_json_input()?;
339                let std_json_input = serde_json::to_value(&input)
340                    .wrap_err("Failed to serialize vyper json input")?;
341
342                let compiler_version = context.compiler_version.to_string();
343
344                Ok(SourcifyVerifyRequest {
345                    std_json_input,
346                    compiler_version,
347                    contract_identifier,
348                    creation_transaction_hash,
349                })
350            }
351        }
352    }
353
354    async fn is_contract_verified(&self, args: &VerifyArgs) -> Result<bool> {
355        let chain_id = args.etherscan.chain.unwrap_or_default().id();
356        let url =
357            Self::get_lookup_url(args.verifier.verifier_url.as_deref(), chain_id, args.address)?;
358
359        match verification_client()?.get(&url).send().await {
360            Ok(response) => {
361                if response.status().is_success() {
362                    let contract_response: SourcifyContractResponse =
363                        serde_json::from_slice(&read_capped_body(response).await?)
364                            .wrap_err("Failed to parse contract response")?;
365
366                    let creation_exact = contract_response
367                        .creation_match
368                        .as_ref()
369                        .is_some_and(|s| s == "exact_match");
370
371                    let runtime_exact = contract_response
372                        .runtime_match
373                        .as_ref()
374                        .is_some_and(|s| s == "exact_match");
375
376                    Ok(creation_exact && runtime_exact)
377                } else {
378                    Ok(false)
379                }
380            }
381            Err(error) => Err(error).wrap_err_with(|| {
382                format!("Failed to query verification status for {}", args.address)
383            }),
384        }
385    }
386}
387
388fn encode_path_segment(value: &str) -> String {
389    const HEX: &[u8; 16] = b"0123456789ABCDEF";
390    let mut encoded = String::with_capacity(value.len());
391    for byte in value.bytes() {
392        if byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_' | b'~') {
393            encoded.push(char::from(byte));
394        } else {
395            encoded.push('%');
396            encoded.push(char::from(HEX[(byte >> 4) as usize]));
397            encoded.push(char::from(HEX[(byte & 0x0f) as usize]));
398        }
399    }
400    encoded
401}
402
403#[derive(Debug, Serialize)]
404#[serde(rename_all = "camelCase")]
405pub struct SourcifyVerifyRequest {
406    std_json_input: serde_json::Value,
407    compiler_version: String,
408    contract_identifier: String,
409    #[serde(skip_serializing_if = "Option::is_none")]
410    creation_transaction_hash: Option<String>,
411}
412
413#[derive(Debug, Deserialize)]
414#[serde(rename_all = "camelCase")]
415pub struct SourcifyVerificationResponse {
416    verification_id: String,
417}
418
419#[derive(Debug, Deserialize)]
420#[serde(rename_all = "camelCase")]
421pub struct SourcifyJobResponse {
422    is_job_completed: bool,
423    contract: Option<SourcifyContractResponse>,
424    error: Option<SourcifyErrorResponse>,
425}
426
427impl SourcifyJobResponse {
428    /// Resolves the job's state from its completion flag, error and contract fields.
429    fn into_status(self) -> SourcifyJobStatus {
430        if !self.is_job_completed {
431            return SourcifyJobStatus::Pending;
432        }
433        match self.error {
434            Some(error) if error.custom_code == "already_verified" => {
435                SourcifyJobStatus::AlreadyVerified
436            }
437            Some(error) => SourcifyJobStatus::Failed(error),
438            None => SourcifyJobStatus::Verified {
439                match_status: self.contract.and_then(|contract| contract.match_status),
440            },
441        }
442    }
443}
444
445/// The state of a Sourcify verification job.
446#[derive(Debug)]
447enum SourcifyJobStatus {
448    /// The job has not completed yet; check again.
449    Pending,
450    /// The job completed because the contract was already verified.
451    AlreadyVerified,
452    /// The job completed with an error.
453    Failed(SourcifyErrorResponse),
454    /// The job completed without an error, with the match Sourcify reported, if any.
455    Verified { match_status: Option<String> },
456}
457
458#[derive(Debug, Deserialize)]
459#[serde(rename_all = "camelCase")]
460pub struct SourcifyContractResponse {
461    #[serde(rename = "match")]
462    match_status: Option<String>,
463    creation_match: Option<String>,
464    runtime_match: Option<String>,
465}
466
467#[derive(Debug, Deserialize)]
468#[serde(rename_all = "camelCase")]
469pub struct SourcifyErrorResponse {
470    custom_code: String,
471    message: String,
472}
473
474#[cfg(test)]
475mod tests {
476    use super::*;
477    use clap::Parser;
478    use foundry_cli::utils::LoadConfig;
479    use foundry_common::compile::ProjectCompiler;
480    use foundry_config::Config;
481    use foundry_test_utils::{forgetest, util::SOLC_VERSION};
482    use serde_json::json;
483    use std::{
484        io::{Read, Write},
485        net::TcpListener,
486        thread,
487    };
488
489    #[test]
490    fn external_request_preserves_raw_input_and_target() {
491        let args =
492            VerifyArgs::parse_from(["foundry-cli", "0xd8509bee9c9bf012282ad33aba0d87241baf5064"]);
493        let input = json!({
494            "language": "Solidity",
495            "settings": { "unknownSetting": { "futureField": true } },
496            "unknownTopLevel": [1, 2, 3]
497        });
498        let context = ExternalVerificationContext {
499            config: Config::default(),
500            compiler_version: "0.8.30+commit.73712a01".parse().unwrap(),
501            standard_json_input: std::sync::Arc::new(input.clone()),
502            target: "contracts/Unknown.sol:ExactTarget".to_string(),
503        };
504
505        let request = SourcifyVerificationProvider::prepare_external_verify_request(&args, context);
506        assert_eq!(request.std_json_input, input);
507        assert_eq!(request.contract_identifier, "contracts/Unknown.sol:ExactTarget");
508        assert_eq!(request.compiler_version, "0.8.30+commit.73712a01");
509    }
510
511    #[test]
512    fn job_response_status() {
513        let status = |body: serde_json::Value| {
514            serde_json::from_value::<SourcifyJobResponse>(body).unwrap().into_status()
515        };
516        assert!(matches!(
517            status(json!({ "isJobCompleted": false, "contract": null, "error": null })),
518            SourcifyJobStatus::Pending
519        ));
520        assert!(matches!(
521            status(json!({
522                "isJobCompleted": true,
523                "error": { "customCode": "already_verified", "message": "" }
524            })),
525            SourcifyJobStatus::AlreadyVerified
526        ));
527        assert!(matches!(
528            status(json!({
529                "isJobCompleted": true,
530                "contract": { "match": "match" },
531                "error": { "customCode": "internal_error", "message": "boom" }
532            })),
533            SourcifyJobStatus::Failed(error) if error.custom_code == "internal_error"
534        ));
535        assert!(matches!(
536            status(json!({ "isJobCompleted": true, "contract": { "match": "exact_match" } })),
537            SourcifyJobStatus::Verified { match_status: Some(m) } if m == "exact_match"
538        ));
539        assert!(matches!(
540            status(json!({ "isJobCompleted": true, "contract": null })),
541            SourcifyJobStatus::Verified { match_status: None }
542        ));
543    }
544
545    #[test]
546    fn job_urls_encode_opaque_ids_as_one_path_segment() {
547        let id = "job a+b/part?query#fragment\n".to_string();
548        let status = SourcifyVerificationProvider::get_job_status_url(None, id.clone()).unwrap();
549        let ui = SourcifyVerificationProvider::get_job_ui_url(None, id).unwrap();
550        let encoded = "job%20a%2Bb%2Fpart%3Fquery%23fragment%0A";
551        assert!(status.ends_with(&format!("v2/verify/{encoded}")), "{status}");
552        assert!(ui.ends_with(&format!("verify-ui/jobs/{encoded}")), "{ui}");
553        assert_eq!(encode_path_segment("."), "%2E");
554        assert_eq!(encode_path_segment(".."), "%2E%2E");
555    }
556
557    #[tokio::test]
558    async fn check_reports_error_with_null_contract() {
559        let body = json!({
560            "isJobCompleted": true,
561            "contract": null,
562            "error": {
563                "customCode": "internal_error",
564                "message": "too many connections from this IP"
565            }
566        })
567        .to_string();
568        let server = TcpListener::bind("127.0.0.1:0").unwrap();
569        let server_url = format!("http://{}/server", server.local_addr().unwrap());
570        let server_thread = thread::spawn(move || {
571            let (mut socket, _) = server.accept().unwrap();
572            let mut request = [0; 4096];
573            let bytes_read = socket.read(&mut request).unwrap();
574            assert!(
575                std::str::from_utf8(&request[..bytes_read])
576                    .unwrap()
577                    .starts_with("GET /server/v2/verify/job-id ")
578            );
579            socket
580                .write_all(
581                    format!(
582                        "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
583                        body.len()
584                    )
585                    .as_bytes(),
586                )
587                .unwrap();
588        });
589
590        let args = VerifyCheckArgs::parse_from([
591            "foundry-cli",
592            "job-id",
593            "--verifier-url",
594            &server_url,
595            "--retries",
596            "1",
597            "--delay",
598            "0",
599        ]);
600        let error = SourcifyVerificationProvider::default().check(args).await.unwrap_err();
601        server_thread.join().unwrap();
602
603        let error = format!("{error:?}");
604        assert!(error.contains("Error Code: `internal_error`"), "{error}");
605        assert!(error.contains("Message: `too many connections from this IP`"), "{error}");
606    }
607
608    #[tokio::test]
609    async fn check_rejects_invalid_explicit_url_instead_of_public_fallback() {
610        for (verifier_url, expected) in [
611            ("127.0.0.1:5555", "invalid Sourcify URL: relative URL without a base"),
612            ("", "invalid Sourcify URL: relative URL without a base"),
613            (
614                "https://user:password-secret@example.invalid:bad/server?api_key=query-secret",
615                "invalid Sourcify URL: invalid port number",
616            ),
617            (
618                "ftp://user:password-secret@example.invalid/server?api_key=query-secret",
619                "invalid Sourcify URL: URL scheme must be http or https",
620            ),
621        ] {
622            let args = VerifyCheckArgs::parse_from([
623                "foundry-cli",
624                "job-id",
625                "--verifier-url",
626                verifier_url,
627                "--retries",
628                "1",
629                "--delay",
630                "0",
631            ]);
632            let error = SourcifyVerificationProvider::default().check(args).await.unwrap_err();
633            assert_eq!(format!("{error:#}"), expected);
634        }
635    }
636
637    #[tokio::test]
638    async fn verification_client_follows_redirects() {
639        let target = TcpListener::bind("127.0.0.1:0").unwrap();
640        let target_url = format!("http://{}", target.local_addr().unwrap());
641        let target_thread = thread::spawn(move || {
642            let (mut socket, _) = target.accept().unwrap();
643            let mut request = [0; 4096];
644            let bytes_read = socket.read(&mut request).unwrap();
645            assert!(std::str::from_utf8(&request[..bytes_read]).unwrap().starts_with("GET "));
646            socket
647                .write_all(
648                    b"HTTP/1.1 200 OK\r\nContent-Length: 10\r\nConnection: close\r\n\r\nredirected",
649                )
650                .unwrap();
651        });
652
653        let source = TcpListener::bind("127.0.0.1:0").unwrap();
654        let source_url = format!("http://{}", source.local_addr().unwrap());
655        let source_thread = thread::spawn(move || {
656            let (mut socket, _) = source.accept().unwrap();
657            let mut request = [0; 4096];
658            let bytes_read = socket.read(&mut request).unwrap();
659            assert!(bytes_read > 0);
660            socket
661                .write_all(
662                    format!(
663                        "HTTP/1.1 307 Temporary Redirect\r\nLocation: {target_url}\r\nContent-Length: 0\r\nConnection: close\r\n\r\n"
664                    )
665                    .as_bytes(),
666                )
667                .unwrap();
668        });
669
670        let response = verification_client()
671            .unwrap()
672            .get(source_url)
673            .send()
674            .await
675            .unwrap()
676            .text()
677            .await
678            .unwrap();
679        source_thread.join().unwrap();
680        target_thread.join().unwrap();
681        assert_eq!(response, "redirected");
682    }
683
684    #[forgetest]
685    async fn creates_correct_verify_request_body(prj: _) {
686        prj.add_source("Counter", "contract Counter {}");
687
688        let args = VerifyArgs::parse_from([
689            "foundry-cli",
690            "0xd8509bee9c9bf012282ad33aba0d87241baf5064",
691            "src/Counter.sol:Counter",
692            "--compiler-version",
693            SOLC_VERSION,
694            "--root",
695            &prj.root().to_string_lossy(),
696        ]);
697
698        let context = args.resolve_context().await.unwrap();
699        let provider = SourcifyVerificationProvider::default();
700        let request = provider.prepare_verify_request(&args, &context).await.unwrap();
701
702        assert_eq!(request.compiler_version, "0.8.38+commit.1835d247");
703        assert_eq!(request.contract_identifier, "src/Counter.sol:Counter");
704        assert!(request.creation_transaction_hash.is_none());
705
706        assert!(request.std_json_input.is_object());
707        let json_obj = request.std_json_input.as_object().unwrap();
708        assert!(json_obj.contains_key("sources"));
709        assert!(json_obj.contains_key("settings"));
710
711        let sources = json_obj.get("sources").unwrap().as_object().unwrap();
712        assert!(sources.contains_key("src/Counter.sol"));
713        let counter_source = sources.get("src/Counter.sol").unwrap().as_object().unwrap();
714        let content = counter_source.get("content").unwrap().as_str().unwrap();
715        assert!(content.contains("contract Counter {}"));
716    }
717
718    #[forgetest]
719    async fn keeps_solar_compiler_version(prj: _) {
720        prj.add_source("Counter", "contract Counter {}");
721
722        let solar_version = format!("{SOLC_VERSION}+commit.d9f23fb.solar.0.2.0");
723        let args = VerifyArgs::parse_from([
724            "foundry-cli",
725            "0xd8509bee9c9bf012282ad33aba0d87241baf5064",
726            "src/Counter.sol:Counter",
727            "--compiler-version",
728            &solar_version,
729            "--root",
730            &prj.root().to_string_lossy(),
731        ]);
732
733        // Cache the artifacts under the plain version, as for a Solar build.
734        let mut config = args.load_config().unwrap();
735        config.solc = Some(SOLC_VERSION.into());
736        ProjectCompiler::new().quiet(true).compile(&config.project().unwrap()).unwrap();
737
738        let context = args.resolve_context().await.unwrap();
739        let provider = SourcifyVerificationProvider::default();
740        let request = provider.prepare_verify_request(&args, &context).await.unwrap();
741
742        assert_eq!(request.compiler_version, solar_version);
743    }
744}