Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(sozo): add --stats flag to output stats of the build artifacts #1799

Merged
Merged
Show file tree
Hide file tree
Changes from 6 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions bin/sozo/resources/starknet_constants.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
{
"max_contract_bytecode_size": 81290,
"max_contract_class_size": 4089446
}
65 changes: 62 additions & 3 deletions bin/sozo/src/commands/build.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,23 @@
use std::fs::File;

use anyhow::Result;
use clap::Args;
use dojo_bindgen::{BuiltinPlugins, PluginManager};
use dojo_lang::scarb_internal::compile_workspace;
use scarb::core::{Config, TargetKind};
use scarb::ops::CompileOpts;

use super::options::statistics::{ContractStatistics, Stats};
use crate::commands::options::statistics::{
compare_against_limit, get_contract_statistics_for_dir,
};

#[derive(Debug, serde::Deserialize)]
pub struct StarknetConstants {
max_contract_bytecode_size: u64,
max_contract_class_size: u64,
}

#[derive(Args, Debug)]
pub struct BuildArgs {
#[arg(long)]
Expand All @@ -18,11 +31,14 @@ pub struct BuildArgs {
#[arg(long)]
#[arg(help = "Output directory.", default_value = "bindings")]
pub bindings_output: String,

#[command(flatten)]
pub stats: Stats,
fabrobles92 marked this conversation as resolved.
Show resolved Hide resolved
}

impl BuildArgs {
pub fn run(self, config: &Config) -> Result<()> {
let compile_info = compile_workspace(
let compile_info: dojo_lang::scarb_internal::CompileInfo = compile_workspace(
fabrobles92 marked this conversation as resolved.
Show resolved Hide resolved
config,
CompileOpts { include_targets: vec![], exclude_targets: vec![TargetKind::TEST] },
)?;
Expand All @@ -36,6 +52,22 @@ impl BuildArgs {
builtin_plugins.push(BuiltinPlugins::Unity);
}

if self.stats.stats || self.stats.stats_limits.is_some() {
const STARKNET_CONSTANTS_JSON: &str = "resources/starknet_constants.json";
let json_consts_path = match &self.stats.stats_limits {
Some(path) => path.clone(),
None => String::from(STARKNET_CONSTANTS_JSON),
};

let file = File::open(json_consts_path)?;
let limits: StarknetConstants = serde_json::from_reader(&file)?;
let contracts_statistics = get_contract_statistics_for_dir(&compile_info.target_dir);

for contract_stats in contracts_statistics {
print_stats(contract_stats, &limits);
}
}

// Custom plugins are always empty for now.
let bindgen = PluginManager {
profile_name: compile_info.profile_name,
Expand All @@ -57,18 +89,45 @@ impl BuildArgs {
}
}

pub fn print_stats(contract_statistic: ContractStatistics, limits: &StarknetConstants) {
println!(
"---------------Contract Stats for {}---------------",
contract_statistic.contract_name
);

print!(
"- Contract bytecode size (Number of felts in the program): {} ",
contract_statistic.number_felts,
);
println!(
"{}",
compare_against_limit(contract_statistic.number_felts, limits.max_contract_bytecode_size)
);

print!("- Contract Class size: {} bytes ", contract_statistic.file_size);
println!(
"{}",
compare_against_limit(contract_statistic.file_size, limits.max_contract_class_size)
);
}

#[cfg(test)]
mod tests {
use dojo_test_utils::compiler::build_test_config;

use super::BuildArgs;
use crate::commands::options::statistics::Stats;

#[test]
fn build_example_with_typescript_and_unity_bindings() {
let config = build_test_config("../../examples/spawn-and-move/Scarb.toml").unwrap();

let build_args =
BuildArgs { bindings_output: "generated".to_string(), typescript: true, unity: true };
let build_args = BuildArgs {
bindings_output: "generated".to_string(),
typescript: true,
unity: true,
stats: Stats { stats: false, stats_limits: None },
};
let result = build_args.run(&config);
assert!(result.is_ok());
}
Expand Down
1 change: 1 addition & 0 deletions bin/sozo/src/commands/options/mod.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
pub mod account;
pub mod starknet;
pub mod statistics;
pub mod transaction;
pub mod world;

Expand Down
106 changes: 106 additions & 0 deletions bin/sozo/src/commands/options/statistics.rs
fabrobles92 marked this conversation as resolved.
Show resolved Hide resolved
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
use std::fs::{self, File};
use std::path::PathBuf;

use anyhow::Result;
use camino::Utf8PathBuf;
use clap::Args;
use starknet::core::types::contract::SierraClass;
use starknet::core::types::FlattenedSierraClass;

pub struct ContractStatistics {
pub contract_name: String,
pub number_felts: u64,
pub file_size: u64,
}

#[derive(Debug, Args)]
#[group(required = false, multiple = false)]
pub struct Stats {
#[arg(long, help = "Display statistics")]
pub stats: bool,

#[arg(
long,
value_name = "FILE",
help = "Specify a JSON file with custom limits for statistics"
)]
pub stats_limits: Option<String>,
}

pub fn read_sierra_json_program(file: &File) -> Result<FlattenedSierraClass> {
let contract_artifact: SierraClass = serde_json::from_reader(file)?;
let contract_artifact: FlattenedSierraClass = contract_artifact.flatten()?;

Ok(contract_artifact)
}

pub fn compute_contract_byte_code_size(contract_artifact: FlattenedSierraClass) -> usize {
contract_artifact.sierra_program.len()
}

pub fn get_file_size_in_bytes(file: File) -> u64 {
file.metadata().unwrap().len()
}

pub fn get_contract_statistics_for_file(
file_name: String,
sierra_json_file: File,
contract_artifact: FlattenedSierraClass,
) -> ContractStatistics {
ContractStatistics {
contract_name: file_name,
number_felts: compute_contract_byte_code_size(contract_artifact) as u64,
file_size: get_file_size_in_bytes(sierra_json_file),
}
}

pub fn get_contract_statistics_for_dir(target_directory: &Utf8PathBuf) -> Vec<ContractStatistics> {
let mut contract_statistics = Vec::new();
let built_contract_paths: fs::ReadDir = fs::read_dir(target_directory.as_str()).unwrap();
for sierra_json_path in built_contract_paths {
let sierra_json_path: PathBuf = sierra_json_path.unwrap().path();

let sierra_json_file: File = match File::open(&sierra_json_path) {
Ok(file) => file,
Err(_) => {
println!("Error opening Sierra JSON file: {}", sierra_json_path.display());
continue; // Skip this file and proceed with the next one
}
};

let contract_artifact: FlattenedSierraClass =
match read_sierra_json_program(&sierra_json_file) {
Ok(artifact) => artifact,
Err(_) => {
println!("Error reading Sierra JSON program: {}", sierra_json_path.display());
continue; // Skip this file and proceed with the next one
}
};

let filename = sierra_json_path.file_name().unwrap();
contract_statistics.push(get_contract_statistics_for_file(
filename.to_string_lossy().to_string(),
sierra_json_file,
contract_artifact,
));
}
contract_statistics
}

pub fn compare_against_limit(num1: u64, limit: u64) -> String {
let warning_threshold = (limit as f64 * 0.8) as u64;
let mut buffer = String::new();

if num1 > limit {
buffer.push_str("\x1b[0;31mDANGER\x1b[0m"); // Red color
buffer.push_str(&format!("! You have passed the starknet limit of {}", limit));
} else if num1 > warning_threshold {
buffer.push_str("\x1b[0;33mWARNING\x1b[0m"); // Yellow color
buffer.push_str(&format!("! You have reached 80% of the starknet limit of {}", limit));
} else {
buffer.push_str("\x1b[0;32mOK\x1b[0m"); // Green color
buffer.push_str(" No warnings.");
}

buffer
}
Loading