Skip to content

Commit

Permalink
refactor(cli): move resolving logic out of verify
Browse files Browse the repository at this point in the history
  • Loading branch information
julio4 committed Jul 4, 2024
1 parent dd305c7 commit 751ad56
Show file tree
Hide file tree
Showing 6 changed files with 67 additions and 52 deletions.
5 changes: 3 additions & 2 deletions crates/cli/src/api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -128,6 +128,7 @@ pub struct VerificationJobDispatch {
job_id: String,
}

#[allow(dead_code)]
#[derive(Debug, serde::Deserialize)]
pub struct VerificationJob {
job_id: String,
Expand Down Expand Up @@ -173,7 +174,7 @@ pub struct ProjectMetadataInfo {
}

pub fn dispatch_class_verification_job(
api_key: &str,
_api_key: &str,
network: Network,
address: &str,
license: &str,
Expand Down Expand Up @@ -240,7 +241,7 @@ pub fn dispatch_class_verification_job(
}

pub fn poll_verification_status(
api_key: &str,
_api_key: &str,
network: Network,
job_id: &str,
max_retries: u32,
Expand Down
61 changes: 57 additions & 4 deletions crates/cli/src/cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,17 +8,27 @@ mod verify;
use crate::license::LicenseType;
use crate::utils::detect_local_tools;
use camino::Utf8PathBuf;
use console::{style, Emoji};
use dialoguer::{theme::ColorfulTheme, Confirm, Input, Select};
use std::env;
use indicatif::{HumanDuration, ProgressStyle};
use regex::Regex;
use std::{env, time::Instant};
use strum::IntoEnumIterator;
use verify::VerifyProjectArgs;

#[allow(dead_code)]
enum TargetType {
ScarbProject,
File,
}

fn main() -> anyhow::Result<()> {
println!(
"{} {} Getting project information...",
style("[1/3]").bold().dim(),
Emoji("📝", "")
);

// Network selection
let is_debug_network = env::var("DEBUG_NETWORK").is_ok();
let network_items = if is_debug_network {
Expand All @@ -36,7 +46,6 @@ fn main() -> anyhow::Result<()> {

// Project type + Path entry
let target_type = TargetType::ScarbProject; // by default we assume the user is in a scarb project

let is_current_dir_scarb = env::current_dir()?.join("scarb.toml").exists();
let path = if is_current_dir_scarb {
env::current_dir()?.to_str().unwrap().trim().to_string()
Expand All @@ -54,6 +63,17 @@ fn main() -> anyhow::Result<()> {
panic!("Path does not exist");
}

// Start the whole process
let _spinner_style = ProgressStyle::with_template("{prefix:.bold.dim} {spinner} {wide_msg}")
.unwrap()
.tick_chars("⠁⠂⠄⡀⢀⠠⠐⠈");

println!(
"{} {} Resolving project...",
style("[2/3]").bold().dim(),
Emoji("🔗", "")
);

// Resolve project
let (project_files, project_metadata) = match target_type {
TargetType::File => {
Expand All @@ -69,6 +89,11 @@ fn main() -> anyhow::Result<()> {
};

// TODO: try to calculate the class hash automatically later after contract selection?
// println!(
// "{} {} Calculating class hash...",
// style("[x/x]").bold().dim(),
// Emoji("🔍 ", "")
// );
let re = Regex::new(r"^0x[a-fA-F0-9]{64}$").unwrap();
let class_hash: String = Input::with_theme(&ColorfulTheme::default())
.with_prompt("Input class hash to verify : ")
Expand Down Expand Up @@ -98,6 +123,11 @@ fn main() -> anyhow::Result<()> {

// Check if account contract
// TODO: Is there a way to detect this automatically?
// println!(
// "{} {} Checking if account contract...",
// style("[x/x]").bold().dim(),
// Emoji("📃 ", "")
// );
let is_account_contract: bool = Confirm::with_theme(&ColorfulTheme::default())
.with_prompt("Is this an Account Class?")
.interact()?;
Expand All @@ -112,6 +142,13 @@ fn main() -> anyhow::Result<()> {
.expect("Aborted at license version selection, terminating...")
.expect("Aborted at license version selection, terminating...");

let verification_start = Instant::now();
println!(
"{} {} Verifying project...",
style("[3/3]").bold().dim(),
Emoji("🔍", "")
);

// Parse args into VerifyProjectArgs
let verify_args = VerifyProjectArgs {
network: network_items[network_index].to_string(),
Expand All @@ -121,13 +158,29 @@ fn main() -> anyhow::Result<()> {
is_account_contract: Some(is_account_contract),
max_retries: Some(10),
api_key: "".to_string(),
path: utf8_path
path: utf8_path,
};

match target_type {
let verification_result = match target_type {
TargetType::ScarbProject => {
verify::verify_project(verify_args, project_metadata, project_files)
}
TargetType::File => panic!("Single contract file verification is not yet implemented"),
};

match verification_result {
Ok(_) => {
println!(
"{} Successfully verified in {}",
Emoji("✅", ""),
HumanDuration(verification_start.elapsed())
);
Ok(())
}
Err(e) => Err(anyhow::anyhow!(
"verification failed {} {}",
Emoji("❌", ""),
e
)),
}
}
21 changes: 1 addition & 20 deletions crates/cli/src/resolver.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
use camino::Utf8PathBuf;
use console::{style, Emoji};
use indicatif::ProgressStyle;
use serde::{Deserialize, Serialize};
use std::{fs, time::Instant};
use std::fs;
use walkdir::{DirEntry, WalkDir};

use crate::api::{FileInfo, ProjectMetadataInfo};
Expand Down Expand Up @@ -32,17 +30,6 @@ pub fn resolve_scarb(
cairo_version: SupportedCairoVersions,
scarb_version: SupportedScarbVersions,
) -> anyhow::Result<(Vec<FileInfo>, ProjectMetadataInfo)> {
// Start a spinner for the resolving process
let started = Instant::now();
let spinner_style = ProgressStyle::with_template("{prefix:.bold.dim} {spinner} {wide_msg}")
.unwrap()
.tick_chars("⠁⠂⠄⡀⢀⠠⠐⠈");

println!(
"{} {} Resolving contract: Extracting files from the Scarb project...",
style("[1/3]").bold().dim(),
Emoji("📃 ", "")
);
// Extract necessary files from the Scarb project for the verified contract
let source_dir = if path.is_absolute() {
path
Expand All @@ -66,12 +53,6 @@ pub fn resolve_scarb(
));
}

println!(
"{} {}Resolving contract: minimizing dependencies...",
style("[2/3]").bold().dim(),
Emoji("🔗 ", "")
);

// Read the scarb metadata to get more information
// TODO: switch this to using scarb-metadata
let scarb_toml_content = fs::read_to_string(source_dir.join("Scarb.toml"))?;
Expand Down
27 changes: 3 additions & 24 deletions crates/cli/src/verify.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,8 @@
use std::{env::current_dir, fs, str::FromStr, time::Instant};
use std::{env::current_dir, str::FromStr};

use anyhow::Result;
use camino::Utf8PathBuf;
use clap::{arg, Args};
use console::Emoji;
use indicatif::{HumanDuration, ProgressStyle};

use dyn_compiler::dyn_compiler::SupportedCairoVersions;

Expand Down Expand Up @@ -58,18 +56,6 @@ pub fn verify_project(
metadata: ProjectMetadataInfo,
files: Vec<FileInfo>,
) -> Result<()> {
// Start a spinner for the verification process
let started = Instant::now();
let spinner_style = ProgressStyle::with_template("{prefix:.bold.dim} {spinner} {wide_msg}")
.unwrap()
.tick_chars("⠁⠂⠄⡀⢀⠠⠐⠈");

// println!(
// "{} {}Checking if the class is already declared...",
// style("[2/4]").bold().dim(),
// Emoji("🔍 ", "")
// );

// Check if the class exists on the network
let network_enum = Network::from_str(args.network.as_str())?;
match does_class_exist(network_enum.clone(), &args.hash) {
Expand Down Expand Up @@ -113,22 +99,15 @@ pub fn verify_project(
);

match poll_result {
Ok(_response) => {
println!(
"{} Successfully verified in {}",
Emoji("✅ ", ""),
HumanDuration(started.elapsed())
);
Ok(())
}
Ok(_response) => Ok(()),
Err(e) => Err(anyhow::anyhow!(
"Error while polling verification status: {}",
e
)),
}
}

pub fn verify_file(args: VerifyFileArgs, cairo_version: SupportedCairoVersions) -> Result<()> {
pub fn _verify_file(args: VerifyFileArgs, cairo_version: SupportedCairoVersions) -> Result<()> {
let file_dir: Utf8PathBuf = match args.path.is_absolute() {
true => args.path.clone(),
false => {
Expand Down
2 changes: 1 addition & 1 deletion crates/voyager-resolver-cairo/src/compiler/scarb_utils.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use anyhow::{anyhow, ensure, Context, Result};
use scarb::flock::Filesystem;
use serde::{Deserialize, Serialize};
use serde::Deserialize;
use std::fs;
use std::path::{Path, PathBuf};
use std::str::FromStr;
Expand Down
3 changes: 2 additions & 1 deletion crates/voyager-resolver-cairo/src/graph/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ pub fn create_graph(modules: &Vec<CairoModule>) -> Graph<ModulePath, EdgeWeight>
graph
}

pub fn display_graphviz(graph: &Graph<ModulePath, EdgeWeight>) {
pub fn _display_graphviz(graph: &Graph<ModulePath, EdgeWeight>) {
println!("{:#?}", Dot::with_config(&graph, &[Config::EdgeNoLabel]));
}

Expand All @@ -80,6 +80,7 @@ pub fn display_graphviz(graph: &Graph<ModulePath, EdgeWeight>) {
/// # Returns
///
/// A vector of unique `String` node labels representing the required files for compilation.
#[allow(dead_code)]
pub fn get_required_project_modules(
graph: &Graph<ModulePath, EdgeWeight>,
) -> Result<Vec<ModulePath>> {
Expand Down

0 comments on commit 751ad56

Please sign in to comment.