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 8 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
52 changes: 48 additions & 4 deletions bin/sozo/src/commands/build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@
use scarb::core::{Config, TargetKind};
use scarb::ops::CompileOpts;

use super::options::statistics::{ContractStatistics, Stats};
use crate::commands::options::statistics::get_contract_statistics_for_dir;
#[derive(Args, Debug)]
pub struct BuildArgs {
#[arg(long)]
Expand All @@ -18,11 +20,14 @@
#[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 +41,14 @@
builtin_plugins.push(BuiltinPlugins::Unity);
}

if self.stats.stats {
let contracts_statistics = get_contract_statistics_for_dir(&compile_info.target_dir);

Check warning on line 45 in bin/sozo/src/commands/build.rs

View check run for this annotation

Codecov / codecov/patch

bin/sozo/src/commands/build.rs#L45

Added line #L45 was not covered by tests

for contract_stats in contracts_statistics {
print_stats(contract_stats);
}

Check warning on line 49 in bin/sozo/src/commands/build.rs

View check run for this annotation

Codecov / codecov/patch

bin/sozo/src/commands/build.rs#L47-L49

Added lines #L47 - L49 were not covered by tests
}

// Custom plugins are always empty for now.
let bindgen = PluginManager {
profile_name: compile_info.profile_name,
Expand All @@ -57,19 +70,50 @@
}
}

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

println!(
"- Contract bytecode size (Number of felts in the program): {}\n",
contract_statistic.number_felts,
);

println!("- Contract Class size: {} bytes\n", contract_statistic.file_size);
fabrobles92 marked this conversation as resolved.
Show resolved Hide resolved
}

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

use super::BuildArgs;
use super::{print_stats, BuildArgs};
use crate::commands::options::statistics::{ContractStatistics, 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 },
};
let result = build_args.run(&config);
assert!(result.is_ok());
}

#[test]
fn test_print_stats() {
// Arrange
fabrobles92 marked this conversation as resolved.
Show resolved Hide resolved
let contract_statistic = ContractStatistics {
contract_name: String::from("SampleContract"),
number_felts: 100,
file_size: 1024,
};
// Act
fabrobles92 marked this conversation as resolved.
Show resolved Hide resolved
print_stats(contract_statistic);
}
}
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
182 changes: 182 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,182 @@
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;

#[derive(Debug, PartialEq)]
pub struct ContractStatistics {
pub contract_name: String,
pub number_felts: u64,
pub file_size: u64,
}

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

Check warning on line 20 in bin/sozo/src/commands/options/statistics.rs

View check run for this annotation

Codecov / codecov/patch

bin/sozo/src/commands/options/statistics.rs#L20

Added line #L20 was not covered by tests
}

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

Check warning on line 60 in bin/sozo/src/commands/options/statistics.rs

View check run for this annotation

Codecov / codecov/patch

bin/sozo/src/commands/options/statistics.rs#L59-L60

Added lines #L59 - L60 were not covered by tests
}
};

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

Check warning on line 69 in bin/sozo/src/commands/options/statistics.rs

View check run for this annotation

Codecov / codecov/patch

bin/sozo/src/commands/options/statistics.rs#L68-L69

Added lines #L68 - L69 were not covered by tests
}
};

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
}

#[cfg(test)]
mod tests {
use std::fs::File;
use std::path::Path;

use camino::Utf8PathBuf;

use super::{
compute_contract_byte_code_size, get_contract_statistics_for_dir,
get_contract_statistics_for_file, get_file_size_in_bytes, read_sierra_json_program,
ContractStatistics,
};

const TEST_SIERRA_JSON_CONTRACT: &str =
"tests/test_data/sierra_compiled_contracts/contracts_test.contract_class.json";
const TEST_SIERRA_FOLDER_CONTRACTS: &str = "tests/test_data/sierra_compiled_contracts/";

#[test]
fn compute_contract_byte_code_size_returns_correct_size() {
// Arrange
let sierra_json_file = File::open(TEST_SIERRA_JSON_CONTRACT)
.unwrap_or_else(|err| panic!("Failed to open file: {}", err));
let flattened_sierra_class = read_sierra_json_program(&sierra_json_file)
.unwrap_or_else(|err| panic!("Failed to read JSON program: {}", err));
let expected_number_of_felts: usize = 448;

// Act
let number_of_felts = compute_contract_byte_code_size(flattened_sierra_class);

// Assert
assert_eq!(
number_of_felts, expected_number_of_felts,
"Number of felts mismatch. Expected {}, got {}",

Check warning on line 115 in bin/sozo/src/commands/options/statistics.rs

View check run for this annotation

Codecov / codecov/patch

bin/sozo/src/commands/options/statistics.rs#L115

Added line #L115 was not covered by tests
expected_number_of_felts, number_of_felts
);
}

#[test]
fn get_contract_statistics_for_file_returns_correct_statistics() {
// Arrange
let sierra_json_file = File::open(TEST_SIERRA_JSON_CONTRACT)
.unwrap_or_else(|err| panic!("Failed to open file: {}", err));
let contract_artifact = read_sierra_json_program(&sierra_json_file)
.unwrap_or_else(|err| panic!("Failed to read JSON program: {}", err));
let filename =
Path::new(TEST_SIERRA_JSON_CONTRACT).file_name().unwrap().to_string_lossy().to_string();
let expected_contract_statistics: ContractStatistics = ContractStatistics {
contract_name: String::from("contracts_test.contract_class.json"),
number_felts: 448,
file_size: 38384,
};

// Act
let statistics =
get_contract_statistics_for_file(filename.clone(), sierra_json_file, contract_artifact);

// Assert
assert_eq!(statistics, expected_contract_statistics);
}

#[test]
fn get_contract_statistics_for_dir_returns_correct_statistics() {
// Arrange
let path_full_of_built_sierra_contracts = Utf8PathBuf::from(TEST_SIERRA_FOLDER_CONTRACTS);

// Act
let contract_statistics =
get_contract_statistics_for_dir(&path_full_of_built_sierra_contracts);

// Assert
assert_eq!(contract_statistics.len(), 1, "Mismatch number of contract statistics");
}

#[test]
fn get_file_size_in_bytes_returns_correct_size() {
// Arrange
let sierra_json_file = File::open(TEST_SIERRA_JSON_CONTRACT)
.unwrap_or_else(|err| panic!("Failed to open file: {}", err));
const EXPECTED_SIZE: u64 = 38384;

// Act
let file_size = get_file_size_in_bytes(sierra_json_file);

// Assert
assert_eq!(file_size, EXPECTED_SIZE, "File size mismatch");
}

#[test]
fn read_sierra_json_program_returns_ok_when_successful() {
// Arrange
let sierra_json_file = File::open(TEST_SIERRA_JSON_CONTRACT)
.unwrap_or_else(|err| panic!("Failed to open file: {}", err));

// Act
let result = read_sierra_json_program(&sierra_json_file);

// Assert
assert!(result.is_ok(), "Expected Ok result");
}
}
Loading
Loading