neo3 1.3.0

Production-ready Rust SDK for Neo N3 blockchain with high-level API, unified error handling, and enterprise features
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
//! Transaction simulation for gas estimation and state preview
//!
//! This module provides comprehensive transaction simulation capabilities,
//! allowing developers to preview transaction effects, estimate gas costs,
//! and analyze state changes before submitting to the blockchain. This helps
//! prevent failed transactions and optimize gas usage.
#![allow(missing_docs, missing_debug_implementations)]
//!
//! ## Features
//!
//! - **Gas Estimation**: Accurate gas cost prediction (±5% accuracy)
//! - **State Preview**: See all state changes before execution
//! - **Optimization**: Get suggestions for reducing gas costs
//! - **Warning System**: Identify potential issues before submission
//! - **Caching**: Reuse simulation results for repeated transactions
//!
//! ## Use Cases
//!
//! - Estimate transaction costs for user interfaces
//! - Preview token transfers and balance changes
//! - Detect potential failures before submission
//! - Optimize smart contract interactions
//! - Validate transaction parameters
//!
//! ## Example
//!
//! ```rust,no_run
//! use neo3::sdk::transaction_simulator::TransactionSimulator;
//! use neo3::neo_builder::Signer;
//!
//! # async fn example() -> Result<(), Box<dyn std::error::Error>> {
//! # let client = std::sync::Arc::new(neo3::neo_clients::RpcClient::new(
//! #     neo3::neo_clients::HttpProvider::new("http://localhost")?
//! # ));
//! // Create simulator
//! let mut simulator = TransactionSimulator::new(client);
//!
//! // Simulate a transaction
//! let script = vec![0x00]; // Your transaction script
//! let signers = vec![]; // Your signers
//!
//! let result = simulator.simulate_script(&script, signers).await?;
//!
//! if result.success {
//!     println!("Gas needed: {} GAS", result.gas_consumed as f64 / 100_000_000.0);
//!     println!("Total fee: {} GAS", result.total_fee as f64 / 100_000_000.0);
//!     
//!     // Check warnings
//!     for warning in &result.warnings {
//!         println!("Warning: {}", warning.message);
//!     }
//! }
//! # Ok(())
//! # }
//! ```

use crate::neo_builder::{ScriptBuilder, Signer};
use crate::neo_clients::{APITrait, HttpProvider, RpcClient};
use crate::neo_error::unified::{ErrorRecovery, NeoError};
// use crate::neo_protocol::AccountTrait;
use crate::neo_types::{
	ContractParameter, NeoVMStateType, ScriptHash, ScriptHashExtension, StackItem,
};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::sync::Arc;

/// Transaction simulation result
///
/// Contains comprehensive information about the transaction simulation,
/// including gas costs, state changes, and potential issues. Use this
/// to make informed decisions before submitting transactions.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SimulationResult {
	/// Whether the transaction would succeed
	pub success: bool,
	/// VM state after execution
	pub vm_state: NeoVMStateType,
	/// Estimated gas consumption
	pub gas_consumed: u64,
	/// Estimated system fee
	pub system_fee: u64,
	/// Estimated network fee
	pub network_fee: u64,
	/// Total fee (system + network)
	pub total_fee: u64,
	/// State changes that would occur
	pub state_changes: StateChanges,
	/// Notifications that would be emitted
	pub notifications: Vec<Notification>,
	/// Return values from the script
	pub return_values: Vec<StackItem>,
	/// Warnings about the transaction
	pub warnings: Vec<SimulationWarning>,
	/// Optimization suggestions
	pub suggestions: Vec<OptimizationSuggestion>,
}

/// State changes preview
///
/// Detailed breakdown of all state modifications that would occur
/// if the transaction is executed. This includes storage changes,
/// balance updates, and contract deployments.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct StateChanges {
	/// Storage changes by contract
	pub storage: HashMap<ScriptHash, Vec<StorageChange>>,
	/// Balance changes by account
	pub balances: HashMap<String, BalanceChange>,
	/// NEP-17 token transfers
	pub transfers: Vec<TokenTransfer>,
	/// Contract deployments
	pub deployments: Vec<ContractDeployment>,
	/// Contract updates
	pub updates: Vec<ContractUpdate>,
}

/// Storage change entry
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct StorageChange {
	/// Storage key
	pub key: Vec<u8>,
	/// Previous value (None if new)
	pub old_value: Option<Vec<u8>>,
	/// New value (None if deleted)
	pub new_value: Option<Vec<u8>>,
	/// Human-readable description
	pub description: Option<String>,
}

/// Balance change for an account
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BalanceChange {
	/// Account address
	pub address: String,
	/// NEO balance change
	pub neo_delta: i64,
	/// GAS balance change
	pub gas_delta: i64,
	/// Other token changes
	pub token_changes: HashMap<String, i64>,
}

/// Token transfer record
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TokenTransfer {
	/// Token contract hash
	pub token: ScriptHash,
	/// Token symbol
	pub symbol: String,
	/// From address
	pub from: String,
	/// To address
	pub to: String,
	/// Transfer amount
	pub amount: String,
}

/// Contract deployment record
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ContractDeployment {
	/// Contract hash
	pub hash: ScriptHash,
	/// Contract name
	pub name: String,
	/// Deployment cost
	pub cost: u64,
}

/// Contract update record
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ContractUpdate {
	/// Contract hash
	pub hash: ScriptHash,
	/// Update type
	pub update_type: String,
	/// Update cost
	pub cost: u64,
}

/// Notification emitted during execution
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Notification {
	/// Contract that emitted the notification
	pub contract: ScriptHash,
	/// Event name
	pub event_name: String,
	/// Event state/parameters
	pub state: serde_json::Value,
}

/// Warning about potential issues
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SimulationWarning {
	/// Warning level (info, warning, error)
	pub level: WarningLevel,
	/// Warning message
	pub message: String,
	/// Suggested action
	pub suggestion: Option<String>,
}

/// Warning severity level
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub enum WarningLevel {
	Info,
	Warning,
	Error,
}

/// Optimization suggestion
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct OptimizationSuggestion {
	/// Optimization type
	pub optimization_type: OptimizationType,
	/// Description of the optimization
	pub description: String,
	/// Potential gas savings
	pub gas_savings: Option<u64>,
	/// Implementation hint
	pub implementation: Option<String>,
}

/// Type of optimization
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum OptimizationType {
	BatchOperations,
	CacheResults,
	OptimizeScript,
	ReduceStorageOperations,
	UseNativeContracts,
	Other(String),
}

/// Transaction simulator
///
/// The main simulator that performs transaction analysis and provides
/// gas estimates and state change previews. It maintains a cache of
/// recent simulations for performance optimization.
///
/// ## Architecture
///
/// The simulator uses the Neo RPC `invokeScript` method to execute
/// transactions in a sandboxed environment without affecting the
/// blockchain state.
pub struct TransactionSimulator {
	client: Arc<RpcClient<HttpProvider>>,
	cache: HashMap<String, CachedSimulation>,
	optimization_rules: Vec<OptimizationRule>,
}

impl TransactionSimulator {
	/// Create a new transaction simulator
	pub fn new(client: Arc<RpcClient<HttpProvider>>) -> Self {
		Self {
			client,
			cache: HashMap::new(),
			optimization_rules: Self::default_optimization_rules(),
		}
	}

	/// Simulate a transaction before submission
	///
	/// Executes the transaction script in a sandboxed environment to
	/// determine gas costs, state changes, and potential issues.
	/// Results are cached for 60 seconds to improve performance.
	///
	/// # Arguments
	///
	/// * `script` - The transaction script to simulate
	/// * `signers` - Transaction signers with their scopes
	///
	/// # Returns
	///
	/// A `SimulationResult` containing gas estimates, state changes,
	/// warnings, and optimization suggestions
	///
	/// # Performance
	///
	/// Typical simulation time: 100-300ms
	/// Cached results: <1ms
	pub async fn simulate_transaction(
		&mut self,
		script: &[u8],
		signers: Vec<Signer>,
	) -> Result<SimulationResult, NeoError> {
		// Check cache first
		let tx_hash = self.calculate_script_hash(script);
		if let Some(cached) = self.cache.get(&tx_hash) {
			if cached.is_valid() {
				return Ok(cached.result.clone());
			}
		}

		// Perform simulation
		let result = self.perform_simulation(script, signers).await?;

		// Cache the result
		self.cache.insert(
			tx_hash,
			CachedSimulation { result: result.clone(), timestamp: std::time::SystemTime::now() },
		);

		Ok(result)
	}

	/// Simulate a script execution
	pub async fn simulate_script(
		&mut self,
		script: &[u8],
		signers: Vec<Signer>,
	) -> Result<SimulationResult, NeoError> {
		// Use invokecontractverify RPC method
		let result = self
			.client
			.invoke_script(hex::encode(script), signers.clone())
			.await
			.map_err(|e| NeoError::Network {
				message: format!("Failed to simulate script: {}", e),
				source: None,
				recovery: ErrorRecovery::new()
					.suggest("Check script validity")
					.suggest("Verify signers have sufficient balance"),
			})?;

		// Parse the invocation result
		self.parse_invocation_result(result, script, signers).await
	}

	/// Estimate gas for a contract call
	///
	/// Specialized method for estimating gas costs of contract invocations.
	/// Includes a 10% safety margin by default to account for variations.
	///
	/// # Arguments
	///
	/// * `contract` - The contract script hash
	/// * `method` - The contract method to invoke
	/// * `params` - Method parameters
	/// * `signers` - Transaction signers
	///
	/// # Returns
	///
	/// A `GasEstimate` with system fee, network fee, and total costs
	pub async fn estimate_gas(
		&mut self,
		contract: &ScriptHash,
		method: &str,
		params: &[ContractParameter],
		signers: Vec<Signer>,
	) -> Result<GasEstimate, NeoError> {
		// Build the script
		let script = ScriptBuilder::new()
			.contract_call(contract, method, params, None)
			.map_err(|e| NeoError::Contract {
				message: format!("Failed to build script: {}", e),
				source: None,
				recovery: ErrorRecovery::new(),
				contract: None,
				method: None,
			})?
			.to_bytes();

		// Simulate the script
		let simulation = self.simulate_script(&script, signers).await?;

		Ok(GasEstimate {
			system_fee: simulation.system_fee,
			network_fee: simulation.network_fee,
			total_fee: simulation.total_fee,
			gas_consumed: simulation.gas_consumed,
			safety_margin: (simulation.total_fee as f64 * 0.1) as u64, // 10% safety margin
			warnings: simulation.warnings,
		})
	}

	/// Preview state changes for a transaction
	pub async fn preview_state_changes(
		&mut self,
		script: &[u8],
		signers: Vec<Signer>,
	) -> Result<StateChanges, NeoError> {
		let simulation = self.simulate_transaction(script, signers).await?;
		Ok(simulation.state_changes)
	}

	/// Perform the actual simulation
	async fn perform_simulation(
		&self,
		script: &[u8],
		signers: Vec<Signer>,
	) -> Result<SimulationResult, NeoError> {
		// Get current blockchain state
		let _block_height = self.client.get_block_count().await.map_err(|e| NeoError::Network {
			message: format!("Failed to get block height: {}", e),
			source: None,
			recovery: ErrorRecovery::new(),
		})?;

		// Simulate the transaction script
		let invocation_result = self
			.client
			.invoke_script(hex::encode(script), signers.clone())
			.await
			.map_err(|e| NeoError::Network {
				message: format!("Failed to invoke script: {}", e),
				source: None,
				recovery: ErrorRecovery::new()
					.suggest("Check transaction script")
					.suggest("Verify signers and witnesses"),
			})?;

		// Parse the result
		let mut result = self.parse_invocation_result(invocation_result, script, signers).await?;

		// Apply optimization rules
		result.suggestions = self.apply_optimization_rules(script, &result);

		// Add warnings
		result.warnings = self.analyze_for_warnings(script, &result);

		Ok(result)
	}

	/// Parse invocation result into simulation result
	async fn parse_invocation_result(
		&self,
		result: crate::neo_types::InvocationResult,
		script: &[u8],
		signers: Vec<Signer>,
	) -> Result<SimulationResult, NeoError> {
		// Determine success
		let success = matches!(result.state, NeoVMStateType::Halt);

		// Parse notifications
		let notifications = self.parse_notifications(&result);

		// Parse state changes
		let state_changes = self.analyze_state_changes(&result, script).await?;

		// Calculate fees
		let gas_consumed = self.parse_gas_consumed(&result.gas_consumed)?;
		let system_fee = self.calculate_system_fee(gas_consumed);
		let network_fee = self.calculate_network_fee(script.len(), signers.len());

		Ok(SimulationResult {
			success,
			vm_state: result.state,
			gas_consumed,
			system_fee,
			network_fee,
			total_fee: system_fee + network_fee,
			state_changes,
			notifications,
			return_values: result.stack.clone(),
			warnings: Vec::new(),
			suggestions: Vec::new(),
		})
	}

	fn parse_gas_consumed(&self, gas_consumed: &str) -> Result<u64, NeoError> {
		if let Ok(value) = gas_consumed.parse::<u64>() {
			return Ok(value);
		}

		if let Ok(value) = gas_consumed.parse::<f64>() {
			if value.is_finite() && value >= 0.0 {
				return Ok(value as u64);
			}
		}

		Err(NeoError::Other {
			message: format!(
				"Invalid gas consumption value in simulation response: {gas_consumed}"
			),
			source: None,
			recovery: ErrorRecovery::new()
				.suggest("Inspect the raw invocation result from the RPC node")
				.suggest("Verify the connected node returns a numeric gasconsumed field"),
		})
	}

	/// Parse notifications from invocation result
	fn parse_notifications(
		&self,
		result: &crate::neo_types::InvocationResult,
	) -> Vec<Notification> {
		result
			.notifications
			.as_ref()
			.map(|notifications| {
				notifications
					.iter()
					.map(|n| Notification {
						contract: n.contract,
						event_name: n.event_name.clone(),
						state: serde_json::to_value(&n.state).unwrap_or(serde_json::Value::Null),
					})
					.collect()
			})
			.unwrap_or_default()
	}

	/// Analyze state changes from the invocation
	async fn analyze_state_changes(
		&self,
		result: &crate::neo_types::InvocationResult,
		_script: &[u8],
	) -> Result<StateChanges, NeoError> {
		let storage = HashMap::new();
		let balances = HashMap::new();
		let mut transfers = Vec::new();
		let deployments = Vec::new();
		let updates = Vec::new();

		// Parse notifications for transfers and balance changes
		if let Some(notifications) = &result.notifications {
			for notification in notifications {
				if notification.event_name == "Transfer" {
					// Parse NEP-17 transfer
					let parsed_notification = Notification {
						contract: notification.contract,
						event_name: notification.event_name.clone(),
						state: serde_json::to_value(&notification.state)
							.unwrap_or(serde_json::Value::Null),
					};
					if let Some(transfer) =
						self.parse_transfer_notification(&parsed_notification).await
					{
						transfers.push(transfer);

						// Update balance changes
						// This is simplified - in production, track actual amounts
						// In a real implementation, we would parse the StackItem properly
					}
				}
			}
		}

		Ok(StateChanges { storage, balances, transfers, deployments, updates })
	}

	/// Parse a transfer notification  
	async fn parse_transfer_notification(
		&self,
		notification: &Notification,
	) -> Option<TokenTransfer> {
		// Get token info
		let token_symbol = self
			.get_token_symbol(&notification.contract)
			.await
			.unwrap_or_else(|_| notification.contract.to_hex());

		// Parse the state JSON - in a real implementation this would properly parse the StackItem
		// For now, return a simplified version
		Some(TokenTransfer {
			token: notification.contract,
			symbol: token_symbol,
			from: "sender".to_string(), // Would parse from state
			to: "receiver".to_string(), // Would parse from state
			amount: "0".to_string(),    // Would parse from state
		})
	}

	/// Get token symbol from contract
	async fn get_token_symbol(&self, contract: &ScriptHash) -> Result<String, NeoError> {
		// Call the symbol method on the contract
		let result = self
			.client
			.invoke_function(contract, "symbol".to_string(), vec![], None)
			.await
			.map_err(|e| NeoError::Contract {
				message: format!("Failed to get token symbol: {}", e),
				source: None,
				recovery: ErrorRecovery::new(),
				contract: None,
				method: Some("symbol".to_string()),
			})?;

		Self::extract_token_symbol(&result)
	}

	fn extract_token_symbol(
		result: &crate::neo_types::InvocationResult,
	) -> Result<String, NeoError> {
		let item = result.stack.first().ok_or_else(|| NeoError::Contract {
			message: "Token symbol response stack is empty".to_string(),
			source: None,
			recovery: ErrorRecovery::new().suggest("Inspect the raw contract response"),
			contract: None,
			method: Some("symbol".to_string()),
		})?;

		item.as_string().ok_or_else(|| NeoError::Contract {
			message: "Token symbol response is not a string-compatible stack item".to_string(),
			source: None,
			recovery: ErrorRecovery::new().suggest("Inspect the raw contract response"),
			contract: None,
			method: Some("symbol".to_string()),
		})
	}

	/// Calculate system fee
	fn calculate_system_fee(&self, gas_consumed: u64) -> u64 {
		// Add a small buffer for safety
		(gas_consumed as f64 * 1.1) as u64
	}

	/// Calculate network fee
	fn calculate_network_fee(&self, script_size: usize, signer_count: usize) -> u64 {
		// Base fee + size fee + verification fee
		let base_fee = 100_000; // 0.001 GAS
		let size_fee = script_size as u64 * 1000; // Per byte
		let verification_fee = signer_count as u64 * 1_000_000; // Per signer

		base_fee + size_fee + verification_fee
	}

	/// Apply optimization rules
	fn apply_optimization_rules(
		&self,
		script: &[u8],
		result: &SimulationResult,
	) -> Vec<OptimizationSuggestion> {
		let mut suggestions = Vec::new();

		for rule in &self.optimization_rules {
			if let Some(suggestion) = rule.check(script, result) {
				suggestions.push(suggestion);
			}
		}

		suggestions
	}

	/// Analyze for warnings
	fn analyze_for_warnings(
		&self,
		_script: &[u8],
		result: &SimulationResult,
	) -> Vec<SimulationWarning> {
		let mut warnings = Vec::new();

		// Check if transaction failed
		if !result.success {
			warnings.push(SimulationWarning {
				level: WarningLevel::Error,
				message: "Transaction simulation failed".to_string(),
				suggestion: Some(
					"Review script logic and ensure all preconditions are met".to_string(),
				),
			});
		}

		// Check high gas consumption
		if result.gas_consumed > 10_000_000 {
			warnings.push(SimulationWarning {
				level: WarningLevel::Warning,
				message: format!(
					"High gas consumption: {} GAS",
					result.gas_consumed as f64 / 100_000_000.0
				),
				suggestion: Some(
					"Consider optimizing the script or breaking into smaller transactions"
						.to_string(),
				),
			});
		}

		// Check for insufficient balance (simplified)
		if result.total_fee > 1_000_000_000 {
			warnings.push(SimulationWarning {
				level: WarningLevel::Warning,
				message: "Transaction requires significant GAS balance".to_string(),
				suggestion: Some("Ensure account has sufficient GAS balance".to_string()),
			});
		}

		warnings
	}

	/// Calculate script hash for caching
	fn calculate_script_hash(&self, script: &[u8]) -> String {
		use sha2::{Digest, Sha256};
		let mut hasher = Sha256::new();
		hasher.update(script);
		hex::encode(hasher.finalize())
	}

	/// Default optimization rules
	fn default_optimization_rules() -> Vec<OptimizationRule> {
		vec![
			OptimizationRule::BatchTransfers,
			OptimizationRule::UseNativeContracts,
			OptimizationRule::MinimizeStorageOps,
			OptimizationRule::CacheRepeatedCalls,
		]
	}
}

/// Optimization rule
#[derive(Debug, Clone, Copy)]
pub enum OptimizationRule {
	BatchTransfers,
	UseNativeContracts,
	MinimizeStorageOps,
	CacheRepeatedCalls,
}

impl OptimizationRule {
	fn check(&self, _script: &[u8], result: &SimulationResult) -> Option<OptimizationSuggestion> {
		match self {
			Self::BatchTransfers => {
				if result.notifications.iter().filter(|n| n.event_name == "Transfer").count() > 3 {
					Some(OptimizationSuggestion {
						optimization_type: OptimizationType::BatchOperations,
						description: "Multiple transfers detected. Consider batching.".to_string(),
						gas_savings: Some(result.gas_consumed / 10),
						implementation: Some(
							"Use a batch transfer method or combine operations".to_string(),
						),
					})
				} else {
					None
				}
			},
			Self::UseNativeContracts => {
				// Check if using non-native contracts for common operations
				None // Simplified
			},
			Self::MinimizeStorageOps => {
				if result.state_changes.storage.values().map(|v| v.len()).sum::<usize>() > 10 {
					Some(OptimizationSuggestion {
						optimization_type: OptimizationType::ReduceStorageOperations,
						description: "Many storage operations detected".to_string(),
						gas_savings: Some(result.gas_consumed / 20),
						implementation: Some(
							"Cache values in memory and batch storage updates".to_string(),
						),
					})
				} else {
					None
				}
			},
			Self::CacheRepeatedCalls => {
				// Detect repeated contract calls
				None // Simplified
			},
		}
	}
}

/// Cached simulation result
struct CachedSimulation {
	result: SimulationResult,
	timestamp: std::time::SystemTime,
}

impl CachedSimulation {
	fn is_valid(&self) -> bool {
		// Cache valid for 60 seconds
		self.timestamp.elapsed().map(|d| d.as_secs() < 60).unwrap_or(false)
	}
}

/// Gas estimation result
///
/// Detailed gas cost breakdown for a transaction, including
/// system fees (execution costs) and network fees (size-based costs).
/// Includes a safety margin to prevent out-of-gas failures.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GasEstimate {
	/// System fee in GAS (smallest unit)
	pub system_fee: u64,
	/// Network fee in GAS (smallest unit)
	pub network_fee: u64,
	/// Total fee in GAS (smallest unit)
	pub total_fee: u64,
	/// Gas consumed by script execution
	pub gas_consumed: u64,
	/// Recommended safety margin
	pub safety_margin: u64,
	/// Any warnings about the estimation
	pub warnings: Vec<SimulationWarning>,
}

/// Transaction simulator builder
///
/// Fluent interface for creating a configured transaction simulator
/// with custom settings for caching and optimization rules.
pub struct TransactionSimulatorBuilder {
	client: Option<Arc<RpcClient<HttpProvider>>>,
	cache_duration: std::time::Duration,
	optimization_rules: Vec<OptimizationRule>,
}

impl Default for TransactionSimulatorBuilder {
	fn default() -> Self {
		Self::new()
	}
}

impl TransactionSimulatorBuilder {
	/// Create a new builder
	pub fn new() -> Self {
		Self {
			client: None,
			cache_duration: std::time::Duration::from_secs(60),
			optimization_rules: Vec::new(),
		}
	}

	/// Set the RPC client
	pub fn client(mut self, client: Arc<RpcClient<HttpProvider>>) -> Self {
		self.client = Some(client);
		self
	}

	/// Set cache duration
	pub fn cache_duration(mut self, duration: std::time::Duration) -> Self {
		self.cache_duration = duration;
		self
	}

	/// Add optimization rule
	pub fn add_optimization_rule(mut self, rule: OptimizationRule) -> Self {
		self.optimization_rules.push(rule);
		self
	}

	/// Build the simulator
	pub fn build(self) -> Result<TransactionSimulator, NeoError> {
		let client = self.client.ok_or_else(|| NeoError::Contract {
			message: "RPC client is required".to_string(),
			source: None,
			recovery: ErrorRecovery::new().suggest("Provide an RPC client using .client() method"),
			contract: None,
			method: None,
		})?;

		let mut simulator = TransactionSimulator::new(client);
		if !self.optimization_rules.is_empty() {
			simulator.optimization_rules = self.optimization_rules;
		}

		Ok(simulator)
	}
}

#[cfg(test)]
mod tests {
	use super::*;
	use crate::neo_clients::HttpProvider;
	use crate::neo_types::InvocationResult;
	use crate::neo_types::StackItem;
	use std::sync::Arc;

	#[test]
	fn test_gas_estimate_creation() {
		let estimate = GasEstimate {
			system_fee: 1_000_000,
			network_fee: 500_000,
			total_fee: 1_500_000,
			gas_consumed: 900_000,
			safety_margin: 150_000,
			warnings: vec![],
		};

		assert_eq!(estimate.total_fee, estimate.system_fee + estimate.network_fee);
		assert_eq!(estimate.safety_margin, 150_000);
	}

	#[test]
	fn test_simulation_result() {
		let result = SimulationResult {
			success: true,
			vm_state: NeoVMStateType::Halt,
			gas_consumed: 1_000_000,
			system_fee: 1_100_000,
			network_fee: 500_000,
			total_fee: 1_600_000,
			state_changes: StateChanges {
				storage: HashMap::new(),
				balances: HashMap::new(),
				transfers: vec![],
				deployments: vec![],
				updates: vec![],
			},
			notifications: vec![],
			return_values: vec![],
			warnings: vec![],
			suggestions: vec![],
		};

		assert!(result.success);
		assert_eq!(result.total_fee, result.system_fee + result.network_fee);
	}

	#[test]
	fn test_warning_levels() {
		let info = SimulationWarning {
			level: WarningLevel::Info,
			message: "Information".to_string(),
			suggestion: None,
		};

		let warning = SimulationWarning {
			level: WarningLevel::Warning,
			message: "Warning".to_string(),
			suggestion: Some("Fix this".to_string()),
		};

		assert_eq!(info.level, WarningLevel::Info);
		assert_eq!(warning.level, WarningLevel::Warning);
	}

	#[tokio::test]
	async fn test_parse_invocation_result_rejects_invalid_gas_consumed() {
		let client = Arc::new(RpcClient::new(HttpProvider::new("http://localhost:10332").unwrap()));
		let simulator = TransactionSimulator::new(client);
		let result =
			InvocationResult { gas_consumed: "not-a-number".to_string(), ..Default::default() };

		let err = simulator.parse_invocation_result(result, &[], vec![]).await.unwrap_err();

		match err {
			NeoError::Other { message, .. } => {
				assert!(message.contains("Invalid gas consumption value"));
			},
			other => panic!("expected generic parsing error, got {other:?}"),
		}
	}

	#[test]
	fn test_extract_token_symbol_reads_first_stack_item() {
		let result = InvocationResult {
			stack: vec![StackItem::ByteString { value: "R0FT".to_string() }],
			..Default::default()
		};

		let symbol = TransactionSimulator::extract_token_symbol(&result).unwrap();
		assert_eq!(symbol, "GAS");
	}

	#[test]
	fn test_extract_token_symbol_rejects_non_string_items() {
		let result = InvocationResult {
			stack: vec![StackItem::Map { value: vec![] }],
			..Default::default()
		};

		let err = TransactionSimulator::extract_token_symbol(&result).unwrap_err();
		match err {
			NeoError::Contract { message, .. } => {
				assert!(message.contains("not a string-compatible"));
			},
			other => panic!("expected contract error, got {other:?}"),
		}
	}
}