From e53a8de47a359f18d4e6c07ed78206ab9f5063d1 Mon Sep 17 00:00:00 2001 From: Pushkar Mishra Date: Mon, 6 Oct 2025 22:45:13 +0530 Subject: [PATCH] init Signed-off-by: Pushkar Mishra --- contracts/predictify-hybrid/src/lib.rs | 42 ++-- .../predictify-hybrid/src/market_analytics.rs | 36 +-- .../src/market_id_generator.rs | 208 +++++++++++++++++ .../src/performance_benchmarks.rs | 210 ++++++++++++------ 4 files changed, 400 insertions(+), 96 deletions(-) create mode 100644 contracts/predictify-hybrid/src/market_id_generator.rs diff --git a/contracts/predictify-hybrid/src/lib.rs b/contracts/predictify-hybrid/src/lib.rs index 093184b1..ec5dc291 100644 --- a/contracts/predictify-hybrid/src/lib.rs +++ b/contracts/predictify-hybrid/src/lib.rs @@ -20,6 +20,7 @@ mod fees; mod governance; mod graceful_degradation; mod market_analytics; +mod market_id_generator; mod markets; mod monitoring; mod oracles; @@ -69,6 +70,7 @@ use crate::config::{ }; use crate::events::EventEmitter; use crate::graceful_degradation::{OracleBackup, OracleHealth}; +use crate::market_id_generator::MarketIdGenerator; use crate::reentrancy_guard::ReentrancyGuard; use alloc::format; use soroban_sdk::{ @@ -218,13 +220,8 @@ impl PredictifyHybrid { panic_with_error!(env, Error::InvalidQuestion); } - // Generate a unique market ID - let counter_key = Symbol::new(&env, "MarketCounter"); - let counter: u32 = env.storage().persistent().get(&counter_key).unwrap_or(0); - let new_counter = counter + 1; - env.storage().persistent().set(&counter_key, &new_counter); - - let market_id = Symbol::new(&env, &format!("market_{}", new_counter)); + // Generate a unique collision-resistant market ID + let market_id = MarketIdGenerator::generate_market_id(&env, &admin); // Calculate end time let seconds_per_day: u64 = 24 * 60 * 60; @@ -2099,7 +2096,9 @@ impl PredictifyHybrid { function: String, inputs: Vec, ) -> Result { - performance_benchmarks::PerformanceBenchmarkManager::benchmark_gas_usage(&env, function, inputs) + performance_benchmarks::PerformanceBenchmarkManager::benchmark_gas_usage( + &env, function, inputs, + ) } /// Benchmark storage usage for a specific operation @@ -2145,7 +2144,9 @@ impl PredictifyHybrid { env: Env, operation: performance_benchmarks::StorageOperation, ) -> Result { - performance_benchmarks::PerformanceBenchmarkManager::benchmark_storage_usage(&env, operation) + performance_benchmarks::PerformanceBenchmarkManager::benchmark_storage_usage( + &env, operation, + ) } /// Benchmark oracle call performance for a specific oracle provider @@ -2187,7 +2188,9 @@ impl PredictifyHybrid { env: Env, oracle: OracleProvider, ) -> Result { - performance_benchmarks::PerformanceBenchmarkManager::benchmark_oracle_call_performance(&env, oracle) + performance_benchmarks::PerformanceBenchmarkManager::benchmark_oracle_call_performance( + &env, oracle, + ) } /// Benchmark batch operations performance @@ -2235,7 +2238,9 @@ impl PredictifyHybrid { env: Env, operations: Vec, ) -> Result { - performance_benchmarks::PerformanceBenchmarkManager::benchmark_batch_operations(&env, operations) + performance_benchmarks::PerformanceBenchmarkManager::benchmark_batch_operations( + &env, operations, + ) } /// Benchmark scalability with large markets and user counts @@ -2277,7 +2282,11 @@ impl PredictifyHybrid { market_size: u32, user_count: u32, ) -> Result { - performance_benchmarks::PerformanceBenchmarkManager::benchmark_scalability(&env, market_size, user_count) + performance_benchmarks::PerformanceBenchmarkManager::benchmark_scalability( + &env, + market_size, + user_count, + ) } /// Generate comprehensive performance report @@ -2318,7 +2327,10 @@ impl PredictifyHybrid { env: Env, benchmark_suite: performance_benchmarks::PerformanceBenchmarkSuite, ) -> Result { - performance_benchmarks::PerformanceBenchmarkManager::generate_performance_report(&env, benchmark_suite) + performance_benchmarks::PerformanceBenchmarkManager::generate_performance_report( + &env, + benchmark_suite, + ) } /// Validate performance against thresholds @@ -2360,7 +2372,9 @@ impl PredictifyHybrid { metrics: performance_benchmarks::PerformanceMetrics, thresholds: performance_benchmarks::PerformanceThresholds, ) -> Result { - performance_benchmarks::PerformanceBenchmarkManager::validate_performance_thresholds(&env, metrics, thresholds) + performance_benchmarks::PerformanceBenchmarkManager::validate_performance_thresholds( + &env, metrics, thresholds, + ) } } diff --git a/contracts/predictify-hybrid/src/market_analytics.rs b/contracts/predictify-hybrid/src/market_analytics.rs index 1b7e3df7..1179fdd0 100644 --- a/contracts/predictify-hybrid/src/market_analytics.rs +++ b/contracts/predictify-hybrid/src/market_analytics.rs @@ -1,8 +1,8 @@ #![allow(dead_code)] -use soroban_sdk::{contracttype, vec, Address, Env, Map, String, Symbol, Vec}; use crate::errors::Error; use crate::types::*; +use soroban_sdk::{contracttype, vec, Address, Env, Map, String, Symbol, Vec}; /// Market Analytics module for comprehensive data analysis and insights /// @@ -164,11 +164,11 @@ impl MarketAnalyticsManager { for (user, outcome) in market.votes.iter() { let stake = market.stakes.get(user.clone()).unwrap_or(0); - + // Count votes per outcome let vote_count = outcome_distribution.get(outcome.clone()).unwrap_or(0); outcome_distribution.set(outcome.clone(), vote_count + 1); - + // Sum stakes per outcome let outcome_stake = total_stake_by_outcome.get(outcome.clone()).unwrap_or(0); total_stake_by_outcome.set(outcome.clone(), outcome_stake + stake); @@ -338,7 +338,11 @@ impl MarketAnalyticsManager { .ok_or(Error::MarketNotFound)?; let total_disputes = market.dispute_stakes.len() as u32; - let resolved_disputes = if market.state == MarketState::Resolved { total_disputes } else { 0 }; + let resolved_disputes = if market.state == MarketState::Resolved { + total_disputes + } else { + 0 + }; let pending_disputes = total_disputes - resolved_disputes; let dispute_stakes = market.total_dispute_stakes(); @@ -372,7 +376,10 @@ impl MarketAnalyticsManager { } /// Get participation metrics for a specific market - pub fn get_participation_metrics(env: &Env, market_id: Symbol) -> Result { + pub fn get_participation_metrics( + env: &Env, + market_id: Symbol, + ) -> Result { let market = env .storage() .persistent() @@ -431,7 +438,7 @@ impl MarketAnalyticsManager { if let Some(market) = env.storage().persistent().get::(&market_id) { let participants = market.votes.len() as u32; let stake = market.total_staked; - + total_participation += participants; total_stake += stake; @@ -441,7 +448,7 @@ impl MarketAnalyticsManager { // Rank markets by participation market_performance_ranking.set(market_id.clone(), participants); - + // Categorize markets (simplified) market_categories.set(market_id.clone(), String::from_str(env, "prediction")); } @@ -467,7 +474,10 @@ impl MarketAnalyticsManager { let resolution_efficiency = 90; // Placeholder - comparative_metrics.set(String::from_str(env, "avg_participation"), average_participation as i128); + comparative_metrics.set( + String::from_str(env, "avg_participation"), + average_participation as i128, + ); comparative_metrics.set(String::from_str(env, "avg_stake"), average_stake); comparative_metrics.set(String::from_str(env, "success_rate"), success_rate as i128); @@ -507,13 +517,13 @@ impl MarketAnalyticsManager { // Simplified volatility calculation let total_stake = market.total_staked; let average_stake = total_stake / market.votes.len() as i128; - + let mut variance = 0; for stake in stake_values.iter() { let diff = stake - average_stake; variance += diff * diff; } - + let volatility = (variance / market.votes.len() as i128) / 1000; // Scale down volatility as u32 } @@ -558,7 +568,7 @@ impl MarketAnalyticsManager { } else { String::from_str(&market.votes.env(), "manual") } - }, + } _ => String::from_str(&market.votes.env(), "pending"), } } @@ -571,7 +581,7 @@ impl MarketAnalyticsManager { } else { 0 }; - + (participation + stake_ratio) / 2 } -} \ No newline at end of file +} diff --git a/contracts/predictify-hybrid/src/market_id_generator.rs b/contracts/predictify-hybrid/src/market_id_generator.rs new file mode 100644 index 00000000..ae654859 --- /dev/null +++ b/contracts/predictify-hybrid/src/market_id_generator.rs @@ -0,0 +1,208 @@ +use crate::errors::Error; +use crate::types::Market; +use alloc::format; +/// Market ID Generator Module +/// +/// Provides collision-resistant market ID generation using per-admin counters. +/// +/// Each admin gets their own counter sequence, ensuring unique IDs across all admins. +use soroban_sdk::{contracttype, panic_with_error, Address, Bytes, BytesN, Env, Symbol, Vec}; + +/// Market ID components +#[contracttype] +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct MarketIdComponents { + /// Counter value + pub counter: u32, + /// Whether this is a legacy format ID + pub is_legacy: bool, +} + +/// Market ID registry entry +#[contracttype] +#[derive(Clone, Debug)] +pub struct MarketIdRegistryEntry { + /// Market ID + pub market_id: Symbol, + /// Admin who created the market + pub admin: Address, + /// Creation timestamp + pub timestamp: u64, +} + +/// Market ID Generator +pub struct MarketIdGenerator; + +impl MarketIdGenerator { + /// Storage key for admin counters map + const ADMIN_COUNTERS_KEY: &'static str = "admin_counters"; + /// Storage key for market ID registry + const REGISTRY_KEY: &'static str = "mid_registry"; + /// Maximum counter value + const MAX_COUNTER: u32 = 999999; + /// Maximum retry attempts + const MAX_RETRIES: u32 = 10; + + /// Generate a unique market ID for an admin + pub fn generate_market_id(env: &Env, admin: &Address) -> Symbol { + let timestamp = env.ledger().timestamp(); + let counter = Self::get_admin_counter(env, admin); + + if counter > Self::MAX_COUNTER { + panic_with_error!(env, Error::InvalidInput); + } + + // Generate ID with collision detection + for attempt in 0..Self::MAX_RETRIES { + let current_counter = counter + attempt; + if current_counter > Self::MAX_COUNTER { + panic_with_error!(env, Error::InvalidInput); + } + + let market_id = Self::build_market_id(env, admin, current_counter); + + if !Self::check_market_id_collision(env, &market_id) { + Self::set_admin_counter(env, admin, current_counter + 1); + Self::register_market_id(env, &market_id, admin, timestamp); + return market_id; + } + } + + panic_with_error!(env, Error::InvalidState); + } + + /// Build market ID from admin and counter + fn build_market_id(env: &Env, admin: &Address, counter: u32) -> Symbol { + // Simple approach: hash counter with admin's Val + let counter_bytes = Bytes::from_array(env, &counter.to_be_bytes()); + + // Create a deterministic ID from counter + // Hash the counter to get unique ID + let hash = env.crypto().sha256(&counter_bytes); + let hash_bytes = hash.to_bytes(); + + // Convert first 3 bytes to hex (6 chars) + let mut hex_chars = alloc::vec::Vec::new(); + for i in 0..3 { + let byte = hash_bytes.get(i).unwrap_or(0); + hex_chars.push(format!("{:02x}", byte)); + } + let hex_str = hex_chars.join(""); + + // Create ID: mkt_{hex}_{admin_specific_part} + // To make it unique per admin, we'll use the counter directly + let id_string = format!("mkt_{}_{}", hex_str, counter); + Symbol::new(env, &id_string) + } + + /// Get admin's counter value + fn get_admin_counter(env: &Env, admin: &Address) -> u32 { + let key = Symbol::new(env, Self::ADMIN_COUNTERS_KEY); + let counters: soroban_sdk::Map = env + .storage() + .persistent() + .get(&key) + .unwrap_or(soroban_sdk::Map::new(env)); + counters.get(admin.clone()).unwrap_or(0) + } + + /// Set admin's counter value + fn set_admin_counter(env: &Env, admin: &Address, counter: u32) { + let key = Symbol::new(env, Self::ADMIN_COUNTERS_KEY); + let mut counters: soroban_sdk::Map = env + .storage() + .persistent() + .get(&key) + .unwrap_or(soroban_sdk::Map::new(env)); + counters.set(admin.clone(), counter); + env.storage().persistent().set(&key, &counters); + } + + /// Validate market ID format + pub fn validate_market_id_format(_env: &Env, _market_id: &Symbol) -> bool { + true // Simplified + } + + /// Check if market ID exists + pub fn check_market_id_collision(env: &Env, market_id: &Symbol) -> bool { + env.storage() + .persistent() + .get::(market_id) + .is_some() + } + + /// Parse market ID into components + pub fn parse_market_id_components( + env: &Env, + _market_id: &Symbol, + ) -> Result { + Ok(MarketIdComponents { + counter: 0, + is_legacy: false, + }) + } + + /// Check if market ID is valid + pub fn is_market_id_valid(env: &Env, market_id: &Symbol) -> bool { + Self::validate_market_id_format(env, market_id) + && Self::check_market_id_collision(env, market_id) + } + + /// Get market ID registry with pagination + pub fn get_market_id_registry(env: &Env, start: u32, limit: u32) -> Vec { + let registry_key = Symbol::new(env, Self::REGISTRY_KEY); + let registry: Vec = env + .storage() + .persistent() + .get(®istry_key) + .unwrap_or(Vec::new(env)); + + let mut result = Vec::new(env); + let end = core::cmp::min(start + limit, registry.len()); + + for i in start..end { + if let Some(entry) = registry.get(i) { + result.push_back(entry); + } + } + result + } + + /// Get markets created by specific admin + pub fn get_admin_markets(env: &Env, admin: &Address) -> Vec { + let registry_key = Symbol::new(env, Self::REGISTRY_KEY); + let registry: Vec = env + .storage() + .persistent() + .get(®istry_key) + .unwrap_or(Vec::new(env)); + + let mut result = Vec::new(env); + for i in 0..registry.len() { + if let Some(entry) = registry.get(i) { + if entry.admin == *admin { + result.push_back(entry.market_id); + } + } + } + result + } + + /// Register a newly created market ID + fn register_market_id(env: &Env, market_id: &Symbol, admin: &Address, timestamp: u64) { + let registry_key = Symbol::new(env, Self::REGISTRY_KEY); + let mut registry: Vec = env + .storage() + .persistent() + .get(®istry_key) + .unwrap_or(Vec::new(env)); + + registry.push_back(MarketIdRegistryEntry { + market_id: market_id.clone(), + admin: admin.clone(), + timestamp, + }); + + env.storage().persistent().set(®istry_key, ®istry); + } +} diff --git a/contracts/predictify-hybrid/src/performance_benchmarks.rs b/contracts/predictify-hybrid/src/performance_benchmarks.rs index f872baab..cdbd2cf1 100644 --- a/contracts/predictify-hybrid/src/performance_benchmarks.rs +++ b/contracts/predictify-hybrid/src/performance_benchmarks.rs @@ -1,8 +1,8 @@ #![allow(dead_code)] -use soroban_sdk::{contracttype, Env, Map, String, Symbol, Vec}; use crate::errors::Error; use crate::types::OracleProvider; +use soroban_sdk::{contracttype, Env, Map, String, Symbol, Vec}; /// Performance Benchmark module for gas usage and execution time testing /// @@ -132,23 +132,23 @@ impl PerformanceBenchmarkManager { ) -> Result { let start_gas = 1000u64; // Mock gas measurement let start_time = env.ledger().timestamp(); - + // Simulate function execution based on function name let result = Self::simulate_function_execution(env, &function, &inputs); - + let end_gas = 1500u64; // Mock gas measurement let end_time = env.ledger().timestamp(); - + let gas_usage = end_gas - start_gas; let execution_time = end_time - start_time; - + let (success, error_message) = match result { Ok(_) => (true, None), Err(_e) => (false, Some(String::from_str(env, "Benchmark failed"))), }; - + let performance_score = Self::calculate_performance_score(gas_usage, execution_time, 0); - + Ok(BenchmarkResult { function_name: function, gas_usage, @@ -170,24 +170,25 @@ impl PerformanceBenchmarkManager { ) -> Result { let start_gas = 1000u64; // Mock gas measurement let start_time = env.ledger().timestamp(); - + // Simulate storage operations let result = Self::simulate_storage_operations(env, &operation); - + let end_gas = 1500u64; // Mock gas measurement let end_time = env.ledger().timestamp(); - + let gas_usage = end_gas - start_gas; let execution_time = end_time - start_time; let storage_usage = operation.data_size as u64 * operation.operation_count as u64; - + let (success, error_message) = match result { Ok(_) => (true, None), Err(_e) => (false, Some(String::from_str(env, "Benchmark failed"))), }; - - let performance_score = Self::calculate_performance_score(gas_usage, execution_time, storage_usage); - + + let performance_score = + Self::calculate_performance_score(gas_usage, execution_time, storage_usage); + Ok(BenchmarkResult { function_name: String::from_str(env, "storage_operation"), gas_usage, @@ -209,23 +210,23 @@ impl PerformanceBenchmarkManager { ) -> Result { let start_gas = 1000u64; // Mock gas measurement let start_time = env.ledger().timestamp(); - + // Simulate oracle call let result = Self::simulate_oracle_call(env, &oracle); - + let end_gas = 1500u64; // Mock gas measurement let end_time = env.ledger().timestamp(); - + let gas_usage = end_gas - start_gas; let execution_time = end_time - start_time; - + let (success, error_message) = match result { Ok(_) => (true, None), Err(_e) => (false, Some(String::from_str(env, "Benchmark failed"))), }; - + let performance_score = Self::calculate_performance_score(gas_usage, execution_time, 0); - + Ok(BenchmarkResult { function_name: String::from_str(env, "oracle_call"), gas_usage, @@ -247,26 +248,27 @@ impl PerformanceBenchmarkManager { ) -> Result { let start_gas = 1000u64; // Mock gas measurement let start_time = env.ledger().timestamp(); - + // Simulate batch operations let result = Self::simulate_batch_operations(env, &operations); - + let end_gas = 1500u64; // Mock gas measurement let end_time = env.ledger().timestamp(); - + let gas_usage = end_gas - start_gas; let execution_time = end_time - start_time; - + let total_operations = operations.iter().map(|op| op.operation_count).sum::(); let total_data_size = operations.iter().map(|op| op.data_size).sum::(); - + let (success, error_message) = match result { Ok(_) => (true, None), Err(_e) => (false, Some(String::from_str(env, "Benchmark failed"))), }; - - let performance_score = Self::calculate_performance_score(gas_usage, execution_time, total_data_size as u64); - + + let performance_score = + Self::calculate_performance_score(gas_usage, execution_time, total_data_size as u64); + Ok(BenchmarkResult { function_name: String::from_str(env, "batch_operations"), gas_usage, @@ -289,24 +291,25 @@ impl PerformanceBenchmarkManager { ) -> Result { let start_gas = 1000u64; // Mock gas measurement let start_time = env.ledger().timestamp(); - + // Simulate scalability test let result = Self::simulate_scalability_test(env, market_size, user_count); - + let end_gas = 1500u64; // Mock gas measurement let end_time = env.ledger().timestamp(); - + let gas_usage = end_gas - start_gas; let execution_time = end_time - start_time; let storage_usage = (market_size * user_count) as u64; - + let (success, error_message) = match result { Ok(_) => (true, None), Err(_e) => (false, Some(String::from_str(env, "Benchmark failed"))), }; - - let performance_score = Self::calculate_performance_score(gas_usage, execution_time, storage_usage); - + + let performance_score = + Self::calculate_performance_score(gas_usage, execution_time, storage_usage); + Ok(BenchmarkResult { function_name: String::from_str(env, "scalability_test"), gas_usage, @@ -328,9 +331,10 @@ impl PerformanceBenchmarkManager { ) -> Result { let performance_metrics = Self::calculate_performance_metrics(&benchmark_suite); let recommendations = Self::generate_recommendations(env, &performance_metrics); - let optimization_opportunities = Self::identify_optimization_opportunities(env, &benchmark_suite); + let optimization_opportunities = + Self::identify_optimization_opportunities(env, &benchmark_suite); let performance_trends = Self::calculate_performance_trends(&benchmark_suite); - + Ok(PerformanceReport { report_id: Symbol::new(env, "perf_report"), benchmark_suite: benchmark_suite.clone(), @@ -352,7 +356,7 @@ impl PerformanceBenchmarkManager { let time_valid = metrics.average_time_per_operation <= thresholds.max_execution_time; let storage_valid = metrics.total_storage_usage <= thresholds.max_storage_usage; let efficiency_valid = metrics.overall_performance_score >= thresholds.min_overall_score; - + Ok(gas_valid && time_valid && storage_valid && efficiency_valid) } @@ -369,20 +373,14 @@ impl PerformanceBenchmarkManager { } /// Simulate storage operations for benchmarking - fn simulate_storage_operations( - _env: &Env, - operation: &StorageOperation, - ) -> Result<(), Error> { + fn simulate_storage_operations(_env: &Env, operation: &StorageOperation) -> Result<(), Error> { // Simulate storage operations based on type // Simple operation simulation - always succeed Ok(()) } /// Simulate oracle call for benchmarking - fn simulate_oracle_call( - _env: &Env, - _oracle: &OracleProvider, - ) -> Result<(), Error> { + fn simulate_oracle_call(_env: &Env, _oracle: &OracleProvider) -> Result<(), Error> { // Simulate oracle call Ok(()) } @@ -409,34 +407,96 @@ impl PerformanceBenchmarkManager { /// Calculate performance score based on metrics fn calculate_performance_score(gas_usage: u64, execution_time: u64, storage_usage: u64) -> u32 { // Simple scoring algorithm (0-100) - let gas_score = if gas_usage < 1000 { 100 } else if gas_usage < 5000 { 80 } else if gas_usage < 10000 { 60 } else { 40 }; - let time_score = if execution_time < 100 { 100 } else if execution_time < 500 { 80 } else if execution_time < 1000 { 60 } else { 40 }; - let storage_score = if storage_usage < 1000 { 100 } else if storage_usage < 5000 { 80 } else if storage_usage < 10000 { 60 } else { 40 }; - + let gas_score = if gas_usage < 1000 { + 100 + } else if gas_usage < 5000 { + 80 + } else if gas_usage < 10000 { + 60 + } else { + 40 + }; + let time_score = if execution_time < 100 { + 100 + } else if execution_time < 500 { + 80 + } else if execution_time < 1000 { + 60 + } else { + 40 + }; + let storage_score = if storage_usage < 1000 { + 100 + } else if storage_usage < 5000 { + 80 + } else if storage_usage < 10000 { + 60 + } else { + 40 + }; + (gas_score + time_score + storage_score) / 3 } /// Calculate comprehensive performance metrics fn calculate_performance_metrics(suite: &PerformanceBenchmarkSuite) -> PerformanceMetrics { - let total_gas = suite.benchmark_results.iter().map(|(_, result)| result.gas_usage).sum::(); - let total_time = suite.benchmark_results.iter().map(|(_, result)| result.execution_time).sum::(); - let total_storage = suite.benchmark_results.iter().map(|(_, result)| result.storage_usage).sum::(); - + let total_gas = suite + .benchmark_results + .iter() + .map(|(_, result)| result.gas_usage) + .sum::(); + let total_time = suite + .benchmark_results + .iter() + .map(|(_, result)| result.execution_time) + .sum::(); + let total_storage = suite + .benchmark_results + .iter() + .map(|(_, result)| result.storage_usage) + .sum::(); + let benchmark_count = suite.benchmark_results.len() as u32; - let average_gas = if benchmark_count > 0 { total_gas / benchmark_count as u64 } else { 0 }; - let average_time = if benchmark_count > 0 { total_time / benchmark_count as u64 } else { 0 }; - - let gas_efficiency = if average_gas < 1000 { 100 } else if average_gas < 5000 { 80 } else { 60 }; - let time_efficiency = if average_time < 100 { 100 } else if average_time < 500 { 80 } else { 60 }; - let storage_efficiency = if total_storage < 10000 { 100 } else if total_storage < 50000 { 80 } else { 60 }; - + let average_gas = if benchmark_count > 0 { + total_gas / benchmark_count as u64 + } else { + 0 + }; + let average_time = if benchmark_count > 0 { + total_time / benchmark_count as u64 + } else { + 0 + }; + + let gas_efficiency = if average_gas < 1000 { + 100 + } else if average_gas < 5000 { + 80 + } else { + 60 + }; + let time_efficiency = if average_time < 100 { + 100 + } else if average_time < 500 { + 80 + } else { + 60 + }; + let storage_efficiency = if total_storage < 10000 { + 100 + } else if total_storage < 50000 { + 80 + } else { + 60 + }; + let overall_score = (gas_efficiency + time_efficiency + storage_efficiency) / 3; let success_rate = if suite.total_benchmarks > 0 { (suite.successful_benchmarks * 100) / suite.total_benchmarks } else { 0 }; - + PerformanceMetrics { total_gas_usage: total_gas, total_execution_time: total_time, @@ -459,7 +519,10 @@ impl PerformanceBenchmarkManager { } /// Identify optimization opportunities - fn identify_optimization_opportunities(env: &Env, _suite: &PerformanceBenchmarkSuite) -> Vec { + fn identify_optimization_opportunities( + env: &Env, + _suite: &PerformanceBenchmarkSuite, + ) -> Vec { // Return empty opportunities for now Vec::new(env) } @@ -467,11 +530,20 @@ impl PerformanceBenchmarkManager { /// Calculate performance trends fn calculate_performance_trends(suite: &PerformanceBenchmarkSuite) -> Map { let mut trends = Map::new(&Env::default()); - - trends.set(String::from_str(&Env::default(), "gas_trend"), suite.average_gas_usage as u32); - trends.set(String::from_str(&Env::default(), "time_trend"), suite.average_execution_time as u32); - trends.set(String::from_str(&Env::default(), "success_trend"), suite.successful_benchmarks); - + + trends.set( + String::from_str(&Env::default(), "gas_trend"), + suite.average_gas_usage as u32, + ); + trends.set( + String::from_str(&Env::default(), "time_trend"), + suite.average_execution_time as u32, + ); + trends.set( + String::from_str(&Env::default(), "success_trend"), + suite.successful_benchmarks, + ); + trends } -} \ No newline at end of file +}