neo-cli 1.0.0

Command-line interface for the NeoRust SDK
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
use crate::{
	commands::defi::create_h160_param, errors::CliError, print_error, print_info, print_success,
	prompt_password,
};
use base64::{engine::general_purpose, Engine as _};
use clap::{Args, Subcommand};
use neo3::{
	builder::{AccountSigner, ScriptBuilder, Signer, TransactionBuilder},
	codec::NeoSerializable,
	neo_clients::APITrait,
	neo_contract::PolicyContract,
	neo_protocol::AccountTrait,
	neo_types::{ContractManifest, NefFile},
	prelude::*,
};
use primitive_types::H160;
use std::{path::PathBuf, str::FromStr};

#[derive(Args, Debug)]
pub struct ContractArgs {
	#[command(subcommand)]
	pub command: ContractCommands,
}

#[derive(Subcommand, Debug)]
pub enum ContractCommands {
	/// Deploy a smart contract
	Deploy {
		/// Path to the contract file (.nef)
		#[arg(short, long)]
		nef: PathBuf,

		/// Path to the contract manifest file (.json)
		#[arg(short, long)]
		manifest: PathBuf,

		/// Account to pay for deployment
		#[arg(short, long)]
		account: Option<String>,
	},

	/// Update an existing contract
	Update {
		/// Contract script hash
		#[arg(short, long)]
		script_hash: String,

		/// Path to the new contract file (.nef)
		#[arg(short, long)]
		nef: PathBuf,

		/// Path to the new contract manifest file (.json)
		#[arg(short, long)]
		manifest: PathBuf,

		/// Account to pay for update
		#[arg(short, long)]
		account: Option<String>,
	},

	/// Invoke a contract method
	Invoke {
		/// Contract script hash
		#[arg(short, long)]
		script_hash: String,

		/// Method name
		#[arg(short, long)]
		method: String,

		/// Method parameters as JSON array
		#[arg(short, long)]
		params: Option<String>,

		/// Account to pay for invocation
		#[arg(short, long)]
		account: Option<String>,

		/// Whether to just test the invocation without submitting to the blockchain
		#[arg(short, long, default_value = "false")]
		test_invoke: bool,
	},

	/// List native contracts
	ListNativeContracts,

	/// Show current network policy values
	Policy,
}

/// CLI state is defined in wallet.rs
pub async fn handle_contract_command(
	args: ContractArgs,
	state: &mut crate::commands::wallet::CliState,
) -> Result<(), CliError> {
	match args.command {
		ContractCommands::Deploy { nef, manifest, account } => {
			deploy_contract(nef, manifest, account, state).await
		},
		ContractCommands::Update { script_hash, nef, manifest, account } => {
			update_contract(script_hash, nef, manifest, account, state).await
		},
		ContractCommands::Invoke { script_hash, method, params, account, test_invoke } => {
			invoke_contract(script_hash, method, params, account, test_invoke, state).await
		},
		ContractCommands::ListNativeContracts => list_native_contracts(state).await,
		ContractCommands::Policy => show_policy(state).await,
	}
}

async fn deploy_contract(
	nef_path: PathBuf,
	manifest_path: PathBuf,
	account: Option<String>,
	state: &mut crate::commands::wallet::CliState,
) -> Result<(), CliError> {
	if state.wallet.is_none() {
		print_error("No wallet is currently open");
		return Err(CliError::Wallet("No wallet is currently open".to_string()));
	}

	if state.rpc_client.is_none() {
		print_error("No RPC client is connected. Please connect to a node first.");
		return Err(CliError::Network("No RPC client is connected".to_string()));
	}

	// Check if files exist
	if !nef_path.exists() {
		print_error(&format!("NEF file not found: {:?}", nef_path));
		return Err(CliError::Input(format!("NEF file not found: {:?}", nef_path)));
	}

	if !manifest_path.exists() {
		print_error(&format!("Manifest file not found: {:?}", manifest_path));
		return Err(CliError::Input(format!("Manifest file not found: {:?}", manifest_path)));
	}

	print_info("Deploying smart contract...");

	// Read NEF and manifest files
	let nef_bytes = std::fs::read(&nef_path).map_err(|e| CliError::Io(e))?;
	let manifest_json = std::fs::read_to_string(&manifest_path).map_err(|e| CliError::Io(e))?;

	// Parse NEF and manifest
	let _nef = NefFile::deserialize(&nef_bytes)
		.map_err(|e| CliError::Input(format!("Failed to parse NEF file: {}", e)))?;
	let _manifest: ContractManifest = serde_json::from_str(&manifest_json)
		.map_err(|e| CliError::Input(format!("Failed to parse manifest file: {}", e)))?;

	// Get account to pay for deployment
	let wallet = state.wallet.as_ref().unwrap();
	let account_address = match account {
		Some(addr) => addr,
		None => {
			// If no account specified, use the first account in the wallet
			let accounts = wallet.get_accounts();
			if accounts.is_empty() {
				print_error("No accounts in wallet");
				return Err(CliError::Wallet("No accounts in wallet".to_string()));
			}
			accounts[0].get_address().to_string()
		},
	};

	// Find account in wallet
	let account_obj = wallet
		.get_accounts()
		.into_iter()
		.find(|a| a.get_address() == account_address)
		.cloned()
		.ok_or_else(|| CliError::Wallet(format!("Account not found: {}", account_address)))?;

	// Get password for signing
	let password = prompt_password("Enter wallet password")?;

	// Create and sign deployment transaction
	let rpc_client = state.rpc_client.as_ref().unwrap();

	// Get system fee
	let params =
		vec![ContractParameter::byte_array(nef_bytes), ContractParameter::string(manifest_json)];

	let invocation_result = rpc_client
		.invoke_function(
			&H160::from_hex("fffdc93764dbaddd97c48f252a53ea4643faa3fd").unwrap(), // Management contract
			"deploy".to_string(),
			params.clone(),
			Some(vec![Signer::from(
				AccountSigner::called_by_entry(&account_obj)
					.map_err(|e| CliError::TransactionBuilder(e.to_string()))?,
			)]),
		)
		.await
		.map_err(|e| CliError::Network(format!("Failed to test invoke deploy: {}", e)))?;

	let system_fee = invocation_result.gas_consumed;
	print_info(&format!("Estimated system fee: {} GAS", system_fee));

	// Get current block count and calculate validUntilBlock
	let block_count = rpc_client
		.get_block_count()
		.await
		.map_err(|e| CliError::Network(format!("Failed to get block count: {}", e)))?;
	let valid_until_block = block_count + 100; // Valid for ~16 minutes (assuming 10s blocks)

	// Build transaction
	let signer = AccountSigner::called_by_entry(&account_obj)
		.map_err(|e| CliError::TransactionBuilder(e.to_string()))?;
	let signers = vec![Signer::AccountSigner(signer)];

	let mut tx_builder: TransactionBuilder<'_, neo3::neo_clients::HttpProvider> =
		TransactionBuilder::new();

	// Set up the transaction builder with all required parameters
	tx_builder.version(0);
	tx_builder
		.nonce((rand::random::<u32>() % 1000000) as u32)
		.map_err(|e| CliError::from(e))?;
	tx_builder.valid_until_block(valid_until_block).map_err(|e| CliError::from(e))?;
	tx_builder.set_signers(signers).map_err(|e| CliError::from(e))?;

	// Add the script
	let method = "deploy".to_string();
	let script = ScriptBuilder::new()
		.contract_call(
			&H160::from_hex("fffdc93764dbaddd97c48f252a53ea4643faa3fd").unwrap(),
			&method,
			&params,
			None,
		)
		.map_err(|e| CliError::Builder(e.to_string()))?
		.to_bytes();

	tx_builder.set_script(Some(script));

	// Convert to string for network fee calculation
	// let tx_hex = tx_builder.to_hex()
	//     .map_err(|e| CliError::TransactionBuilder(format!("Failed to convert transaction to hex: {}", e)))?;

	// Calculate network fee
	// let network_fee = rpc_client.calculate_network_fee(tx_hex).await
	//     .map_err(|e| CliError::Network(format!("Failed to calculate network fee: {}", e)))?;

	// Set additional network fee - using a hardcoded value for testing
	tx_builder.set_additional_network_fee(100000000);

	// Build and sign the transaction
	let mut tx = tx_builder
		.build()
		.await
		.map_err(|e| CliError::Transaction(format!("Failed to build transaction: {}", e)))?;

	// Sign the transaction with the account's private key
	print_info("Signing transaction with account's private key...");

	// Decrypt the account's private key using the password
	let mut account_clone = account_obj.clone();
	account_clone
		.decrypt_private_key(&password)
		.map_err(|e| CliError::Wallet(format!("Failed to decrypt private key: {}", e)))?;

	// Get the key pair from the decrypted account
	let key_pair = account_clone
		.key_pair()
		.as_ref()
		.ok_or_else(|| CliError::Wallet("No key pair available after decryption".to_string()))?
		.clone();

	// Create a witness for the transaction
	let tx_hash = tx
		.get_hash_data()
		.await
		.map_err(|e| CliError::Transaction(format!("Failed to get transaction hash: {}", e)))?;

	let witness = neo3::builder::Witness::create(tx_hash, &key_pair)
		.map_err(|e| CliError::Transaction(format!("Failed to create witness: {}", e)))?;

	// Add the witness to the transaction
	tx.add_witness(witness);

	// Create a JSON structure directly that matches the expected format
	let mut encoder = neo3::codec::Encoder::new();
	tx.encode(&mut encoder);
	let tx_bytes = encoder.to_bytes();

	let tx_json = serde_json::json!({
		"jsonrpc": "2.0",
		"method": "sendrawtransaction",
		"params": [general_purpose::STANDARD.encode(&tx_bytes)],
		"id": 1
	})
	.to_string();

	// Send transaction
	let result = rpc_client
		.send_raw_transaction(tx_json)
		.await
		.map_err(|e| CliError::Network(format!("Failed to send transaction: {}", e)))?;

	print_success("Contract deployment transaction sent successfully");
	println!("Transaction hash: {}", result.hash);
	println!("Note: The contract hash can be obtained from the transaction when it is confirmed on the blockchain.");

	Ok(())
}

async fn update_contract(
	script_hash: String,
	nef_path: PathBuf,
	manifest_path: PathBuf,
	account: Option<String>,
	state: &mut crate::commands::wallet::CliState,
) -> Result<(), CliError> {
	if state.wallet.is_none() {
		print_error("No wallet is currently open");
		return Err(CliError::Wallet("No wallet is currently open".to_string()));
	}

	if state.rpc_client.is_none() {
		print_error("No RPC client is connected. Please connect to a node first.");
		return Err(CliError::Network("No RPC client is connected".to_string()));
	}

	// Check if files exist
	if !nef_path.exists() {
		print_error(&format!("NEF file not found: {:?}", nef_path));
		return Err(CliError::Input(format!("NEF file not found: {:?}", nef_path)));
	}

	if !manifest_path.exists() {
		print_error(&format!("Manifest file not found: {:?}", manifest_path));
		return Err(CliError::Input(format!("Manifest file not found: {:?}", manifest_path)));
	}

	print_info(&format!("Updating contract: {}", script_hash));

	// Read NEF and manifest files
	let nef_bytes = std::fs::read(&nef_path).map_err(|e| CliError::Io(e))?;
	let manifest_json = std::fs::read_to_string(&manifest_path).map_err(|e| CliError::Io(e))?;

	// Parse NEF and manifest
	let _nef = NefFile::deserialize(&nef_bytes)
		.map_err(|e| CliError::Input(format!("Failed to parse NEF file: {}", e)))?;
	let _manifest: ContractManifest = serde_json::from_str(&manifest_json)
		.map_err(|e| CliError::Input(format!("Failed to parse manifest file: {}", e)))?;

	// Get account to pay for update
	let wallet = state.wallet.as_ref().unwrap();
	let account_address = match account {
		Some(addr) => addr,
		None => {
			// If no account specified, use the first account in the wallet
			let accounts = wallet.get_accounts();
			if accounts.is_empty() {
				print_error("No accounts in wallet");
				return Err(CliError::Wallet("No accounts in wallet".to_string()));
			}
			accounts[0].get_address().to_string()
		},
	};

	// Find account in wallet
	let account_obj = wallet
		.get_accounts()
		.into_iter()
		.find(|a| a.get_address() == account_address)
		.cloned()
		.ok_or_else(|| CliError::Wallet(format!("Account not found: {}", account_address)))?;

	// Get password for signing
	let password = prompt_password("Enter wallet password")?;

	// Parse contract hash
	let contract_hash = H160::from_str(&script_hash)
		.map_err(|_| CliError::Input("Invalid script hash format".to_string()))?;

	// Create and sign update transaction
	let rpc_client = state.rpc_client.as_ref().unwrap();

	// Get system fee
	let params = vec![
		ContractParameter::h160(&contract_hash),
		ContractParameter::byte_array(nef_bytes),
		ContractParameter::string(manifest_json),
	];

	let invocation_result = rpc_client
		.invoke_function(
			&contract_hash,
			"update".to_string(),
			params.clone(),
			Some(vec![Signer::from(
				AccountSigner::called_by_entry(&account_obj)
					.map_err(|e| CliError::TransactionBuilder(e.to_string()))?,
			)]),
		)
		.await
		.map_err(|e| CliError::Network(format!("Failed to test invoke update: {}", e)))?;

	let system_fee = invocation_result.gas_consumed;
	print_info(&format!("Estimated system fee: {} GAS", system_fee));

	// Get current block count and calculate validUntilBlock
	let block_count = rpc_client
		.get_block_count()
		.await
		.map_err(|e| CliError::Network(format!("Failed to get block count: {}", e)))?;
	let valid_until_block = block_count + 100; // Valid for ~16 minutes (assuming 10s blocks)

	// Build transaction
	let signer = AccountSigner::called_by_entry(&account_obj)
		.map_err(|e| CliError::TransactionBuilder(e.to_string()))?;
	let signers = vec![Signer::AccountSigner(signer)];

	let mut tx_builder: TransactionBuilder<'_, neo3::neo_clients::HttpProvider> =
		TransactionBuilder::new();

	// Set up the transaction builder with all required parameters
	tx_builder.version(0);
	tx_builder
		.nonce((rand::random::<u32>() % 1000000) as u32)
		.map_err(|e| CliError::from(e))?;
	tx_builder.valid_until_block(valid_until_block).map_err(|e| CliError::from(e))?;
	tx_builder.set_signers(signers).map_err(|e| CliError::from(e))?;

	// Add the script
	let method = "update".to_string();
	let script = ScriptBuilder::new()
		.contract_call(&contract_hash, &method, &params, None)
		.map_err(|e| CliError::Builder(e.to_string()))?
		.to_bytes();

	tx_builder.set_script(Some(script));

	// Convert to string for network fee calculation
	// let tx_hex = tx_builder.to_hex()
	//     .map_err(|e| CliError::TransactionBuilder(format!("Failed to convert transaction to hex: {}", e)))?;

	// Calculate network fee
	// let network_fee = rpc_client.calculate_network_fee(tx_hex).await
	//     .map_err(|e| CliError::Network(format!("Failed to calculate network fee: {}", e)))?;

	// Set additional network fee - using a hardcoded value for testing
	tx_builder.set_additional_network_fee(100000000);

	// Build and sign the transaction
	let mut tx = tx_builder
		.build()
		.await
		.map_err(|e| CliError::Transaction(format!("Failed to build transaction: {}", e)))?;

	// Sign the transaction with the account's private key
	print_info("Signing transaction with account's private key...");

	// Decrypt the account's private key using the password
	let mut account_clone = account_obj.clone();
	account_clone
		.decrypt_private_key(&password)
		.map_err(|e| CliError::Wallet(format!("Failed to decrypt private key: {}", e)))?;

	// Get the key pair from the decrypted account
	let key_pair = account_clone
		.key_pair()
		.as_ref()
		.ok_or_else(|| CliError::Wallet("No key pair available after decryption".to_string()))?
		.clone();

	// Create a witness for the transaction
	let tx_hash = tx
		.get_hash_data()
		.await
		.map_err(|e| CliError::Transaction(format!("Failed to get transaction hash: {}", e)))?;

	let witness = neo3::builder::Witness::create(tx_hash, &key_pair)
		.map_err(|e| CliError::Transaction(format!("Failed to create witness: {}", e)))?;

	// Add the witness to the transaction
	tx.add_witness(witness);

	// Create a JSON structure directly that matches the expected format
	let mut encoder = neo3::codec::Encoder::new();
	tx.encode(&mut encoder);
	let tx_bytes = encoder.to_bytes();

	let tx_json = serde_json::json!({
		"jsonrpc": "2.0",
		"method": "sendrawtransaction",
		"params": [general_purpose::STANDARD.encode(&tx_bytes)],
		"id": 1
	})
	.to_string();

	// Send transaction
	let result = rpc_client
		.send_raw_transaction(tx_json)
		.await
		.map_err(|e| CliError::Network(format!("Failed to send transaction: {}", e)))?;

	print_success("Contract updated successfully");
	println!("Transaction hash: {}", result.hash);

	Ok(())
}

async fn invoke_contract(
	script_hash: String,
	method: String,
	params: Option<String>,
	account: Option<String>,
	test_invoke: bool,
	state: &mut crate::commands::wallet::CliState,
) -> Result<(), CliError> {
	if state.rpc_client.is_none() {
		print_error("No RPC client is connected. Please connect to a node first.");
		return Err(CliError::Network("No RPC client is connected".to_string()));
	}

	// Parse parameters if provided
	let parameters = match params {
		Some(p) => {
			let params_json: Vec<serde_json::Value> = serde_json::from_str(&p)
				.map_err(|e| CliError::Input(format!("Invalid JSON parameters: {}", e)))?;

			// Convert JSON parameters to ContractParameter
			params_json
				.into_iter()
				.map(|v| contract_parameter_from_json(v))
				.collect::<Result<Vec<_>, _>>()?
		},
		None => Vec::new(),
	};

	// Convert script hash
	let contract_hash = H160::from_str(&script_hash)
		.map_err(|_| CliError::Input("Invalid script hash format".to_string()))?;

	let rpc_client = state.rpc_client.as_ref().unwrap();

	if test_invoke {
		print_info(&format!("Test invoking method '{}' on contract {}", method, script_hash));

		// Test invoke
		let result = rpc_client
			.invoke_function(&contract_hash, method.clone(), parameters, None)
			.await
			.map_err(|e| CliError::Network(format!("Failed to invoke function: {}", e)))?;

		// Display result
		println!("Invocation result:");
		println!("  State: {:?}", result.state);
		println!("  Gas consumed: {}", result.gas_consumed);
		println!("  Stack:");
		for (i, item) in result.stack.iter().enumerate() {
			println!("    {}: {:?}", i, item);
		}
	} else {
		// Real invocation
		if state.wallet.is_none() {
			print_error("No wallet is currently open");
			return Err(CliError::Wallet("No wallet is currently open".to_string()));
		}

		print_info(&format!("Invoking method '{}' on contract {}", method, script_hash));

		// Get account to pay for invocation
		let wallet = state.wallet.as_ref().unwrap();
		let account_address = match account {
			Some(addr) => addr,
			None => {
				// If no account specified, use the first account in the wallet
				let accounts = wallet.get_accounts();
				if accounts.is_empty() {
					print_error("No accounts in wallet");
					return Err(CliError::Wallet("No accounts in wallet".to_string()));
				}
				accounts[0].get_address().to_string()
			},
		};

		// Find account in wallet
		let account_obj = wallet
			.get_accounts()
			.into_iter()
			.find(|a| a.get_address() == account_address)
			.cloned()
			.ok_or_else(|| CliError::Wallet(format!("Account not found: {}", account_address)))?;

		// Get password for signing
		let password = prompt_password("Enter wallet password")?;

		// Get system fee
		let invocation_result = rpc_client
			.invoke_function(
				&contract_hash,
				method.clone(),
				parameters.clone(),
				Some(vec![Signer::from(
					AccountSigner::called_by_entry(&account_obj)
						.map_err(|e| CliError::TransactionBuilder(e.to_string()))?,
				)]),
			)
			.await
			.map_err(|e| CliError::Network(format!("Failed to test invoke: {}", e)))?;

		let system_fee = invocation_result.gas_consumed;
		print_info(&format!("Estimated system fee: {} GAS", system_fee));

		// Get current block count and calculate validUntilBlock
		let block_count = rpc_client
			.get_block_count()
			.await
			.map_err(|e| CliError::Network(format!("Failed to get block count: {}", e)))?;
		let valid_until_block = block_count + 100; // Valid for ~16 minutes (assuming 10s blocks)

		// Build transaction
		let signer = AccountSigner::called_by_entry(&account_obj)
			.map_err(|e| CliError::TransactionBuilder(e.to_string()))?;
		let signers = vec![Signer::AccountSigner(signer)];

		let mut tx_builder: TransactionBuilder<'_, neo3::neo_clients::HttpProvider> =
			TransactionBuilder::new();

		// Set up the transaction builder with all required parameters
		tx_builder.version(0);
		tx_builder
			.nonce((rand::random::<u32>() % 1000000) as u32)
			.map_err(|e| CliError::from(e))?;
		tx_builder.valid_until_block(valid_until_block).map_err(|e| CliError::from(e))?;
		tx_builder.set_signers(signers).map_err(|e| CliError::from(e))?;

		// Add the script
		let script = ScriptBuilder::new()
			.contract_call(&contract_hash, &method, &parameters, None)
			.map_err(|e| CliError::Builder(e.to_string()))?
			.to_bytes();

		tx_builder.set_script(Some(script));

		// Convert to string for network fee calculation
		// let tx_hex = tx_builder.to_hex()
		//     .map_err(|e| CliError::TransactionBuilder(format!("Failed to convert transaction to hex: {}", e)))?;

		// Calculate network fee
		// let network_fee = rpc_client.calculate_network_fee(tx_hex).await
		//     .map_err(|e| CliError::Network(format!("Failed to calculate network fee: {}", e)))?;

		// Set additional network fee - using a hardcoded value for testing
		tx_builder.set_additional_network_fee(100000000);

		// Build and sign the transaction
		let mut tx = tx_builder
			.build()
			.await
			.map_err(|e| CliError::Transaction(format!("Failed to build transaction: {}", e)))?;

		// Sign the transaction with the account's private key
		print_info("Signing transaction with account's private key...");

		// Decrypt the account's private key using the password
		let mut account_clone = account_obj.clone();
		account_clone
			.decrypt_private_key(&password)
			.map_err(|e| CliError::Wallet(format!("Failed to decrypt private key: {}", e)))?;

		// Get the key pair from the decrypted account
		let key_pair = account_clone
			.key_pair()
			.as_ref()
			.ok_or_else(|| CliError::Wallet("No key pair available after decryption".to_string()))?
			.clone();

		// Create a witness for the transaction
		let tx_hash = tx
			.get_hash_data()
			.await
			.map_err(|e| CliError::Transaction(format!("Failed to get transaction hash: {}", e)))?;

		let witness = neo3::builder::Witness::create(tx_hash, &key_pair)
			.map_err(|e| CliError::Transaction(format!("Failed to create witness: {}", e)))?;

		// Add the witness to the transaction
		tx.add_witness(witness);

		// Create a JSON structure directly that matches the expected format
		let mut encoder = neo3::codec::Encoder::new();
		tx.encode(&mut encoder);
		let tx_bytes = encoder.to_bytes();

		let tx_json = serde_json::json!({
			"jsonrpc": "2.0",
			"method": "sendrawtransaction",
			"params": [general_purpose::STANDARD.encode(&tx_bytes)],
			"id": 1
		})
		.to_string();

		// Send transaction
		let result = rpc_client
			.send_raw_transaction(tx_json)
			.await
			.map_err(|e| CliError::Network(format!("Failed to send transaction: {}", e)))?;

		print_success("Contract method invoked successfully");
		println!("Transaction hash: {}", result.hash);
	}

	Ok(())
}

async fn list_native_contracts(
	state: &mut crate::commands::wallet::CliState,
) -> Result<(), CliError> {
	if state.rpc_client.is_none() {
		print_error("No RPC client is connected. Please connect to a node first.");
		return Err(CliError::Network("No RPC client is connected".to_string()));
	}

	print_info("Native contracts:");

	// List native contracts
	let rpc_client = state.rpc_client.as_ref().unwrap();
	let native_contracts = rpc_client
		.get_native_contracts()
		.await
		.map_err(|e| CliError::Network(format!("Failed to get native contracts: {}", e)))?;

	for (i, contract) in native_contracts.iter().enumerate() {
		println!(
			"{}. {} ({})",
			i + 1,
			contract.manifest().name.as_ref().unwrap_or(&"Unknown".to_string()),
			contract.hash()
		);
		println!("  Supported Standards: {:?}", contract.manifest().supported_standards);
		println!();
	}

	print_success("Native contracts retrieved successfully");
	Ok(())
}

async fn show_policy(state: &mut crate::commands::wallet::CliState) -> Result<(), CliError> {
	if state.rpc_client.is_none() {
		print_error("No RPC client is connected. Please connect to a node first.");
		return Err(CliError::Network("No RPC client is connected".to_string()));
	}

	let policy = PolicyContract::new(state.rpc_client.as_ref());

	print_info("Fetching policy values...");

	let fee_per_byte = policy
		.get_fee_per_byte()
		.await
		.map_err(|e| CliError::Network(format!("Failed to get fee per byte: {}", e)))?;

	let exec_fee_factor = policy
		.get_exec_fee_factor()
		.await
		.map_err(|e| CliError::Network(format!("Failed to get exec fee factor: {}", e)))?;

	let storage_price = policy
		.get_storage_price()
		.await
		.map_err(|e| CliError::Network(format!("Failed to get storage price: {}", e)))?;

	let pico_factor = match policy.get_exec_pico_fee_factor().await {
		Ok(val) => val.to_string(),
		Err(_) => "Not supported (Neo 3.9+)".to_string(),
	};

	let milliseconds_per_block = match policy.get_milliseconds_per_block().await {
		Ok(val) => format!("{} ms", val),
		Err(_) => "Not supported".to_string(),
	};

	println!("Policy Contract State:");
	println!("  Fee Per Byte:         {}", fee_per_byte);
	println!("  Exec Fee Factor:      {}", exec_fee_factor);
	println!("  Storage Price:        {}", storage_price);
	println!("  Exec Pico Fee Factor: {}", pico_factor);
	println!("  Milliseconds/Block:   {}", milliseconds_per_block);

	Ok(())
}

// Helper to convert JSON to ContractParameter
fn contract_parameter_from_json(value: serde_json::Value) -> Result<ContractParameter, CliError> {
	match value {
		serde_json::Value::Null => Ok(ContractParameter::any()),
		serde_json::Value::Bool(b) => Ok(ContractParameter::bool(b)),
		serde_json::Value::Number(n) => {
			if n.is_i64() {
				Ok(ContractParameter::integer(n.as_i64().unwrap()))
			} else if n.is_f64() {
				Ok(ContractParameter::string(n.to_string()))
			} else {
				Err(CliError::Input("Invalid number type".to_string()))
			}
		},
		serde_json::Value::String(s) => {
			// Check if it's a hex string (for ByteArray)
			if let Some(hex_str) = s.strip_prefix("0x") {
				match hex::decode(hex_str) {
					Ok(bytes) => Ok(ContractParameter::byte_array(bytes)),
					Err(_) => Ok(ContractParameter::string(s)),
				}
			} else if let Some(hash_str) = s.strip_prefix("@") {
				// Special format for Hash160
				match H160::from_str(hash_str) {
					Ok(hash) => create_h160_param(&format!("{:x}", hash)),
					Err(_) => Ok(ContractParameter::string(s)),
				}
			} else {
				Ok(ContractParameter::string(s))
			}
		},
		serde_json::Value::Array(arr) => {
			let mut params = Vec::new();
			for item in arr {
				params.push(contract_parameter_from_json(item)?);
			}
			Ok(ContractParameter::array(params))
		},
		serde_json::Value::Object(_) => {
			Err(CliError::Input("Object parameters not supported".to_string()))
		},
	}
}