starknet-contract-verifier 0.2.2

Contract class verification tool that allows you to verify your starknet classes on a block explorer.
Documentation
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
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
mod args;
use crate::args::{Args, Commands, VerifyArgs};

use camino::{Utf8Path, Utf8PathBuf};
use chrono::{DateTime, Utc};
use clap::Parser;
use colored::*;
use itertools::Itertools;
use log::{debug, info, warn};
use scarb_metadata::PackageMetadata;
use std::collections::HashMap;
use std::time::{Duration, UNIX_EPOCH};
use thiserror::Error;
use verifier::{
    api::{
        poll_verification_status, ApiClient, ApiClientError, FileInfo, ProjectMetadataInfo,
        VerificationJob, VerifyJobStatus,
    },
    class_hash::ClassHash,
    errors, resolver, voyager,
};

#[derive(Debug, Error)]
pub enum CliError {
    #[error(transparent)]
    Api(#[from] ApiClientError),

    #[error(transparent)]
    MissingPackage(#[from] errors::MissingPackage),

    #[error("Class hash {0} is not declared")]
    NotDeclared(ClassHash),

    #[error("Verification dry run")]
    DryRun,

    #[error("No contracts selected for verification. Use --contract-name argument")]
    NoTarget,

    #[error(
        "Only single contract verification is supported. Specify with --contract-name argument"
    )]
    MultipleContracts,

    // TODO: Display suggestions
    #[error(transparent)]
    MissingContract(#[from] errors::MissingContract),

    #[error(transparent)]
    Resolver(#[from] resolver::Error),

    #[error("Couldn't strip {prefix} from {path}")]
    StripPrefix {
        path: Utf8PathBuf,
        prefix: Utf8PathBuf,
    },

    #[error(transparent)]
    Utf8(#[from] camino::FromPathBufError),

    #[error(transparent)]
    Voyager(#[from] voyager::Error),
}

fn display_verification_job_id(job_id: &str) {
    println!();
    println!("verification job id: {}", job_id.green().bold());
    println!();
}

fn main() -> anyhow::Result<()> {
    env_logger::init();
    let Args {
        command: cmd,
        network_url: network,
        network: _,
    } = Args::parse();
    let public = ApiClient::new(network.public)?;
    let private = ApiClient::new(network.private)?;

    match &cmd {
        Commands::Verify(args) => {
            // Check if we can directly access the license from the manifest
            let license_result =
                std::fs::read_to_string(args.path.manifest_path()).map(|toml_content| {
                    if let Some(license_line) = toml_content
                        .lines()
                        .find(|line| line.trim().starts_with("license"))
                    {
                        if let Some(license_value) = license_line.split('=').nth(1) {
                            let license = license_value.trim().trim_matches('"').trim_matches('\'');
                            debug!("Found license in Scarb.toml: {license}");
                            // Accept any license value found
                            return Some(license.to_string());
                        }
                    }
                    None
                });

            let found_license = license_result.unwrap_or(None);

            if args.license.is_none()
                && args.path.get_license().is_none()
                && found_license.is_none()
            {
                warn!(
                    "No license provided via CLI or in Scarb.toml, defaults to All Rights Reserved"
                );
            }

            let job_id = submit(&public, &private, args, found_license)?;
            display_verification_job_id(&job_id);
        }
        Commands::Status { job } => {
            let status = check(&public, job)?;
            info!("{status:?}");
        }
    }
    Ok(())
}

#[allow(clippy::too_many_lines)]
fn submit(
    public: &ApiClient,
    _private: &ApiClient,
    args: &VerifyArgs,
    direct_license: Option<String>,
) -> Result<String, CliError> {
    let metadata = args.path.metadata();

    let mut packages: Vec<PackageMetadata> = vec![];
    resolver::gather_packages(metadata, &mut packages)?;

    // Get raw license string directly if we found it
    let raw_license_str: Option<String> = direct_license;

    // Get license as LicenseId for display purposes
    let license = args.license.or_else(|| args.path.get_license());

    let mut sources: Vec<Utf8PathBuf> = vec![];
    for package in &packages {
        let mut package_sources = resolver::package_sources(package)?;
        sources.append(&mut package_sources);
    }

    let prefix = resolver::biggest_common_prefix(&sources, args.path.root_dir());
    let manifest_path = voyager::manifest_path(metadata);
    let manifest = manifest_path
        .strip_prefix(&prefix)
        .map_err(|_| CliError::StripPrefix {
            path: manifest_path.clone(),
            prefix: prefix.clone(),
        })?;

    let mut files: HashMap<String, Utf8PathBuf> = sources
        .iter()
        .map(|p| -> Result<(String, Utf8PathBuf), CliError> {
            let name = p.strip_prefix(&prefix).map_err(|_| CliError::StripPrefix {
                path: p.clone(),
                prefix: prefix.clone(),
            })?;
            Ok((name.to_string(), p.clone()))
        })
        .try_collect()?;
    files.insert(
        manifest.to_string(),
        voyager::manifest_path(metadata).clone(),
    );

    // Also ensure the workspace root Scarb.toml is included if we're in a workspace
    let workspace_manifest = &metadata.workspace.manifest_path;
    // Check if this is a workspace by comparing normalized paths and checking if workspace has multiple members
    let is_workspace = workspace_manifest != manifest_path && metadata.workspace.members.len() > 1;
    debug!("Workspace manifest: {}", workspace_manifest);
    debug!("Current manifest: {}", manifest_path);
    debug!("Is workspace project: {}", is_workspace);
    debug!("Workspace members: {}", metadata.workspace.members.len());

    if is_workspace {
        let workspace_manifest_rel =
            workspace_manifest
                .strip_prefix(&prefix)
                .map_err(|_| CliError::StripPrefix {
                    path: workspace_manifest.clone(),
                    prefix: prefix.clone(),
                })?;
        debug!("Including workspace root manifest: {}", workspace_manifest);
        files.insert(
            workspace_manifest_rel.to_string(),
            workspace_manifest.clone(),
        );
    }

    // Include Scarb.lock if --lock-file flag is enabled
    if args.lock_file {
        let lock_file_path = args.path.root_dir().join("Scarb.lock");
        if lock_file_path.exists() {
            let lock_file_rel =
                lock_file_path
                    .strip_prefix(&prefix)
                    .map_err(|_| CliError::StripPrefix {
                        path: lock_file_path.clone(),
                        prefix: prefix.clone(),
                    })?;
            debug!("Including Scarb.lock file: {}", lock_file_path);
            files.insert(lock_file_rel.to_string(), lock_file_path.clone());
        } else {
            warn!(
                "--lock-file flag enabled but Scarb.lock not found at {}",
                lock_file_path
            );
        }
    }

    // Filter packages based on the --package argument if provided
    let filtered_packages: Vec<&PackageMetadata> = if let Some(package_id) = &args.package {
        packages.iter().filter(|p| p.name == *package_id).collect()
    } else {
        packages.iter().collect()
    };

    if filtered_packages.is_empty() {
        if let Some(package_id) = &args.package {
            let available_packages: Vec<String> = packages.iter().map(|p| p.name.clone()).collect();
            return Err(CliError::from(errors::MissingContract::new(
                package_id.clone(),
                available_packages,
            )));
        }
    }

    // We need either --package or --contract or both to be specified
    if args.package.is_none() {
        // For workspace projects, package is required
        if is_workspace {
            let available_packages: Vec<String> = packages.iter().map(|p| p.name.clone()).collect();
            return Err(CliError::from(errors::MissingContract::new(
                "Workspace project detected - use --package argument".to_string(),
                available_packages,
            )));
        }
    }

    let cairo_version = metadata.app_version_info.cairo.version.clone();
    let scarb_version = metadata.app_version_info.version.clone();

    // Process the first matching package (or the first one if no package specified)
    let package_meta = filtered_packages
        .first()
        .ok_or_else(|| CliError::NoTarget)?;

    // Use the provided contract name
    let contract_name = &args.contract_name;

    let project_dir_path = args
        .path
        .root_dir()
        .strip_prefix(&prefix)
        .map_err(|_| CliError::StripPrefix {
            path: args.path.root_dir().clone(),
            prefix: prefix.clone(),
        })
        // backend expects this for cwd
        .map(|p| {
            if p == Utf8Path::new("") {
                Utf8Path::new(".")
            } else {
                p
            }
        })?;

    // Find the main source file for the package (conventionally src/lib.cairo or src/main.cairo)
    let possible_main_paths = vec!["src/lib.cairo", "src/main.cairo"];

    let mut contract_file_path = None;

    for path in possible_main_paths {
        let full_path = package_meta.root.join(path);
        if full_path.exists() {
            contract_file_path = Some(full_path);
            break;
        }
    }

    // If we can't find a main file, use the first source file in the package
    if contract_file_path.is_none() {
        // Get all source files from this package
        let package_source_files = sources
            .iter()
            .filter(|path| path.starts_with(&package_meta.root))
            .find(|path| path.extension() == Some("cairo"))
            .cloned();

        contract_file_path = package_source_files;
    }

    let contract_file_path = contract_file_path.ok_or_else(|| CliError::NoTarget)?;

    let contract_file = contract_file_path
        .strip_prefix(prefix.clone())
        .map_err(|_| CliError::StripPrefix {
            path: contract_file_path.clone(),
            prefix,
        })?;

    let project_meta = ProjectMetadataInfo {
        cairo_version: cairo_version.clone(),
        scarb_version: scarb_version.clone(),
        contract_file: contract_file.to_string(),
        project_dir_path: project_dir_path.to_string(),
        package_name: package_meta.name.clone(),
    };

    info!("Verifying contract: {contract_name} from {contract_file}");

    // Format the license display
    let license_display = match &license {
        Some(id) => match id.name {
            // Map common license names to their SPDX identifiers
            "MIT License" => "MIT",
            "Apache License 2.0" => "Apache-2.0",
            "GNU General Public License v3.0 only" => "GPL-3.0-only",
            "BSD 3-Clause License" => "BSD-3-Clause",
            other => other,
        },
        None => {
            if let Some(ref direct) = raw_license_str {
                direct
            } else {
                "NONE"
            }
        }
    };
    info!("licensed with: {license_display}");

    info!("using cairo: {cairo_version} and scarb {scarb_version}");
    info!("These are the files that will be used for verification:");
    for path in files.values() {
        info!("{path}");
    }

    if args.execute {
        return public
            .verify_class(
                &args.class_hash,
                Some(license_display.to_string()),
                contract_name,
                project_meta,
                &files
                    .into_iter()
                    .map(|(name, path)| FileInfo {
                        name,
                        path: path.into_std_path_buf(),
                    })
                    .collect_vec(),
            )
            .map_err(CliError::from);
    }

    info!("Nothing to do, add `--execute` flag to actually verify the contract");
    Err(CliError::DryRun)
}

fn format_timestamp(timestamp: f64) -> String {
    let duration = Duration::from_secs_f64(timestamp);
    if let Some(datetime) = UNIX_EPOCH.checked_add(duration) {
        let datetime: DateTime<Utc> = datetime.into();
        datetime.to_rfc3339()
    } else {
        timestamp.to_string()
    }
}

fn check(public: &ApiClient, job_id: &str) -> Result<VerificationJob, CliError> {
    let status = poll_verification_status(public, job_id).map_err(CliError::from)?;

    match status.status() {
        VerifyJobStatus::Success => {
            println!("\n✅ Verification successful!");
            if let Some(name) = status.name() {
                println!("Contract name: {name}");
            }
            if let Some(file) = status.contract_file() {
                println!("Contract file: {file}");
            }
            if let Some(version) = status.version() {
                println!("Version: {version}");
            }
            if let Some(license) = status.license() {
                println!("License: {license}");
            }
            if let Some(address) = status.address() {
                println!("Contract address: {address}");
            }
            println!("Class hash: {}", status.class_hash());
            if let Some(created) = status.created_timestamp() {
                println!("Created: {}", format_timestamp(created));
            }
            if let Some(updated) = status.updated_timestamp() {
                println!("Last updated: {}", format_timestamp(updated));
            }
            println!("\nThe contract is now verified and visible on Voyager.");
            println!("You can view it by searching for the class hash above.");
        }
        VerifyJobStatus::Fail => {
            println!("\n❌ Verification failed!");
            if let Some(desc) = status.status_description() {
                println!("Reason: {desc}");
            }
            if let Some(created) = status.created_timestamp() {
                println!("Started: {}", format_timestamp(created));
            }
            if let Some(updated) = status.updated_timestamp() {
                println!("Failed: {}", format_timestamp(updated));
            }
        }
        VerifyJobStatus::CompileFailed => {
            println!("\n❌ Compilation failed!");
            if let Some(desc) = status.status_description() {
                println!("Reason: {desc}");
            }
            if let Some(created) = status.created_timestamp() {
                println!("Started: {}", format_timestamp(created));
            }
            if let Some(updated) = status.updated_timestamp() {
                println!("Failed: {}", format_timestamp(updated));
            }
        }
        VerifyJobStatus::Processing => {
            println!("\n⏳ Contract verification is being processed...");
            println!("Job ID: {}", status.job_id());
            println!("Status: Processing");
            if let Some(created) = status.created_timestamp() {
                println!("Started: {}", format_timestamp(created));
            }
            if let Some(updated) = status.updated_timestamp() {
                println!("Last updated: {}", format_timestamp(updated));
            }
            println!("\nUse the same command to check progress later.");
        }
        VerifyJobStatus::Submitted => {
            println!("\n⏳ Verification job submitted and waiting for processing...");
            println!("Job ID: {}", status.job_id());
            println!("Status: Submitted");
            if let Some(created) = status.created_timestamp() {
                println!("Submitted: {}", format_timestamp(created));
            }
            println!("\nUse the same command to check progress later.");
        }
        VerifyJobStatus::Compiled => {
            println!("\n⏳ Contract compiled successfully, verification in progress...");
            println!("Job ID: {}", status.job_id());
            println!("Status: Compiled");
            if let Some(created) = status.created_timestamp() {
                println!("Started: {}", format_timestamp(created));
            }
            if let Some(updated) = status.updated_timestamp() {
                println!("Last updated: {}", format_timestamp(updated));
            }
            println!("\nUse the same command to check progress later.");
        }
        _ => {
            println!("\n⏳ Verification in progress...");
            println!("Job ID: {}", status.job_id());
            println!("Status: {}", status.status());
            if let Some(created) = status.created_timestamp() {
                println!("Started: {}", format_timestamp(created));
            }
            if let Some(updated) = status.updated_timestamp() {
                println!("Last updated: {}", format_timestamp(updated));
            }
            println!("\nUse the same command to check progress later.");
        }
    }

    Ok(status)
}