forge_verify/
sourcify.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
use crate::{
    provider::{VerificationContext, VerificationProvider},
    verify::{VerifyArgs, VerifyCheckArgs},
};
use alloy_primitives::map::HashMap;
use async_trait::async_trait;
use eyre::Result;
use foundry_common::{fs, retry::Retry};
use futures::FutureExt;
use reqwest::Url;
use serde::{Deserialize, Serialize};
use std::str::FromStr;

pub static SOURCIFY_URL: &str = "https://sourcify.dev/server/";

/// The type that can verify a contract on `sourcify`
#[derive(Clone, Debug, Default)]
#[non_exhaustive]
pub struct SourcifyVerificationProvider;

#[async_trait]
impl VerificationProvider for SourcifyVerificationProvider {
    async fn preflight_verify_check(
        &mut self,
        args: VerifyArgs,
        context: VerificationContext,
    ) -> Result<()> {
        let _ = self.prepare_request(&args, &context)?;
        Ok(())
    }

    async fn verify(&mut self, args: VerifyArgs, context: VerificationContext) -> Result<()> {
        let body = self.prepare_request(&args, &context)?;

        trace!("submitting verification request {:?}", body);

        let client = reqwest::Client::new();

        let retry: Retry = args.retry.into();
        let resp = retry
            .run_async(|| {
                async {
                    sh_println!(
                        "\nSubmitting verification for [{}] {:?}.",
                        context.target_name,
                        args.address.to_string()
                    )?;
                    let response = client
                        .post(args.verifier.verifier_url.as_deref().unwrap_or(SOURCIFY_URL))
                        .header("Content-Type", "application/json")
                        .body(serde_json::to_string(&body)?)
                        .send()
                        .await?;

                    let status = response.status();
                    if !status.is_success() {
                        let error: serde_json::Value = response.json().await?;
                        eyre::bail!(
                            "Sourcify verification request for address ({}) failed with status code {status}\nDetails: {error:#}",
                            args.address,
                        );
                    }

                    let text = response.text().await?;
                    Ok(Some(serde_json::from_str::<SourcifyVerificationResponse>(&text)?))
                }
                .boxed()
            })
            .await?;

        self.process_sourcify_response(resp.map(|r| r.result))
    }

    async fn check(&self, args: VerifyCheckArgs) -> Result<()> {
        let retry: Retry = args.retry.into();
        let resp = retry
            .run_async(|| {
                async {
                    let url = Url::from_str(
                        args.verifier.verifier_url.as_deref().unwrap_or(SOURCIFY_URL),
                    )?;
                    let query = format!(
                        "check-by-addresses?addresses={}&chainIds={}",
                        args.id,
                        args.etherscan.chain.unwrap_or_default().id(),
                    );
                    let url = url.join(&query)?;
                    let response = reqwest::get(url).await?;
                    if !response.status().is_success() {
                        eyre::bail!(
                            "Failed to request verification status with status code {}",
                            response.status()
                        );
                    };

                    Ok(Some(response.json::<Vec<SourcifyResponseElement>>().await?))
                }
                .boxed()
            })
            .await?;

        self.process_sourcify_response(resp)
    }
}

impl SourcifyVerificationProvider {
    /// Configures the API request to the sourcify API using the given [`VerifyArgs`].
    fn prepare_request(
        &self,
        args: &VerifyArgs,
        context: &VerificationContext,
    ) -> Result<SourcifyVerifyRequest> {
        let metadata = context.get_target_metadata()?;
        let imports = context.get_target_imports()?;

        let mut files = HashMap::with_capacity_and_hasher(2 + imports.len(), Default::default());

        let metadata = serde_json::to_string_pretty(&metadata)?;
        files.insert("metadata.json".to_string(), metadata);

        let contract_path = context.target_path.clone();
        let filename = contract_path.file_name().unwrap().to_string_lossy().to_string();
        files.insert(filename, fs::read_to_string(&contract_path)?);

        for import in imports {
            let import_entry = format!("{}", import.display());
            files.insert(import_entry, fs::read_to_string(&import)?);
        }

        let req = SourcifyVerifyRequest {
            address: args.address.to_string(),
            chain: args.etherscan.chain.unwrap_or_default().id().to_string(),
            files,
            chosen_contract: None,
        };

        Ok(req)
    }

    fn process_sourcify_response(
        &self,
        response: Option<Vec<SourcifyResponseElement>>,
    ) -> Result<()> {
        let Some([response, ..]) = response.as_deref() else { return Ok(()) };
        match response.status.as_str() {
            "perfect" => {
                if let Some(ts) = &response.storage_timestamp {
                    sh_println!("Contract source code already verified. Storage Timestamp: {ts}")?;
                } else {
                    sh_println!("Contract successfully verified")?;
                }
            }
            "partial" => {
                sh_println!("The recompiled contract partially matches the deployed version")?;
            }
            "false" => sh_println!("Contract source code is not verified")?,
            s => eyre::bail!("Unknown status from sourcify. Status: {s:?}"),
        }
        Ok(())
    }
}

#[derive(Debug, Serialize)]
pub struct SourcifyVerifyRequest {
    address: String,
    chain: String,
    files: HashMap<String, String>,
    #[serde(rename = "chosenContract", skip_serializing_if = "Option::is_none")]
    chosen_contract: Option<String>,
}

#[derive(Debug, Deserialize)]
pub struct SourcifyVerificationResponse {
    result: Vec<SourcifyResponseElement>,
}

#[derive(Debug, Deserialize)]
pub struct SourcifyResponseElement {
    status: String,
    #[serde(rename = "storageTimestamp")]
    storage_timestamp: Option<String>,
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_check_addresses_url() {
        let url = Url::from_str("https://server-verify.hashscan.io").unwrap();
        let url = url.join("check-by-addresses?addresses=0x1234&chainIds=1").unwrap();
        assert_eq!(
            url.as_str(),
            "https://server-verify.hashscan.io/check-by-addresses?addresses=0x1234&chainIds=1"
        );
    }
}