|
1 | | -use crate::cli::args::{InspectArgs, InteractiveArgs, RunArgs}; |
| 1 | +use crate::cli::args::{InspectArgs, InteractiveArgs, OptimizeArgs, RunArgs}; |
2 | 2 | use crate::debugger::engine::DebuggerEngine; |
3 | 3 | use crate::runtime::executor::ContractExecutor; |
4 | 4 | use crate::ui::tui::DebuggerUI; |
@@ -125,3 +125,59 @@ fn parse_storage(json: &str) -> Result<String> { |
125 | 125 | .with_context(|| format!("Invalid JSON storage: {}", json))?; |
126 | 126 | Ok(json.to_string()) |
127 | 127 | } |
| 128 | + |
| 129 | +/// Execute the optimize command |
| 130 | +pub fn optimize(args: OptimizeArgs) -> Result<()> { |
| 131 | + println!("Analyzing contract for gas optimization: {:?}", args.contract); |
| 132 | + |
| 133 | + let wasm_bytes = fs::read(&args.contract) |
| 134 | + .with_context(|| format!("Failed to read WASM file: {:?}", args.contract))?; |
| 135 | + |
| 136 | + println!("Contract loaded successfully ({} bytes)", wasm_bytes.len()); |
| 137 | + |
| 138 | + let mut executor = ContractExecutor::new(wasm_bytes)?; |
| 139 | + |
| 140 | + if let Some(storage_json) = &args.storage { |
| 141 | + let storage = parse_storage(storage_json)?; |
| 142 | + executor.set_initial_storage(storage)?; |
| 143 | + } |
| 144 | + |
| 145 | + let functions_to_analyze = if args.function.is_empty() { |
| 146 | + println!("No functions specified, analyzing all exported functions..."); |
| 147 | + crate::utils::wasm::parse_functions(&wasm_bytes)? |
| 148 | + } else { |
| 149 | + args.function.clone() |
| 150 | + }; |
| 151 | + |
| 152 | + let mut optimizer = crate::profiler::analyzer::GasOptimizer::new(executor); |
| 153 | + |
| 154 | + println!("\nAnalyzing {} function(s)...", functions_to_analyze.len()); |
| 155 | + |
| 156 | + for function_name in &functions_to_analyze { |
| 157 | + println!(" Analyzing function: {}", function_name); |
| 158 | + match optimizer.analyze_function(function_name, args.args.as_deref()) { |
| 159 | + Ok(profile) => { |
| 160 | + println!(" CPU: {} instructions, Memory: {} bytes", |
| 161 | + profile.total_cpu, profile.total_memory); |
| 162 | + } |
| 163 | + Err(e) => { |
| 164 | + eprintln!(" Warning: Failed to analyze function {}: {}", function_name, e); |
| 165 | + } |
| 166 | + } |
| 167 | + } |
| 168 | + |
| 169 | + let contract_path_str = args.contract.to_string_lossy().to_string(); |
| 170 | + let report = optimizer.generate_report(&contract_path_str); |
| 171 | + |
| 172 | + let markdown = optimizer.generate_markdown_report(&report); |
| 173 | + |
| 174 | + if let Some(output_path) = &args.output { |
| 175 | + fs::write(output_path, &markdown) |
| 176 | + .with_context(|| format!("Failed to write report to: {:?}", output_path))?; |
| 177 | + println!("\nOptimization report written to: {:?}", output_path); |
| 178 | + } else { |
| 179 | + println!("\n{}", markdown); |
| 180 | + } |
| 181 | + |
| 182 | + Ok(()) |
| 183 | +} |
0 commit comments