neo3 1.0.9

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
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
use crate::{
	builder::{BuilderError, CallFlags, InteropService},
	codec::Encoder,
	crypto::Secp256r1PublicKey,
	neo_crypto::utils::{FromBase64String, FromHexString, ToHexString},
	Bytes, ContractParameter, ContractParameterType, OpCode, ParameterValue, ScriptHashExtension,
};
use getset::{Getters, Setters};
use num_bigint::BigInt;
use num_traits::{Signed, ToPrimitive};
use primitive_types::H160;
use serde::{Deserialize, Serialize};
use std::{
	cmp::PartialEq,
	collections::HashMap,
	convert::TryInto,
	fmt::{Debug, Formatter},
	str::FromStr,
};

/// A builder for constructing Neo smart contract scripts.
///
/// The `ScriptBuilder` provides methods to create and manipulate scripts
/// by adding opcodes, pushing data, and performing various operations
/// required for Neo smart contract execution.
///
/// # Examples
///
/// ```rust
/// use neo3::neo_builder::ScriptBuilder;
/// use neo3::neo_types::OpCode;
/// use num_bigint::BigInt;
///
/// let mut builder = ScriptBuilder::new();
/// builder.push_integer(BigInt::from(42))
///        .push_data("Hello, Neo!".as_bytes().to_vec())
///        .op_code(&[OpCode::Add]);
///
/// let script = builder.to_bytes();
/// ```
#[derive(Debug, PartialEq, Eq, Hash, Getters, Setters)]
pub struct ScriptBuilder {
	#[getset(get = "pub")]
	pub script: Encoder,
}

impl ScriptBuilder {
	/// Creates a new `ScriptBuilder` instance.
	///
	/// # Examples
	///
	/// ```rust
	/// use neo3::neo_builder::ScriptBuilder;
	///
	/// let builder = ScriptBuilder::new();
	/// ```
	pub fn new() -> Self {
		Self { script: Encoder::new() }
	}

	/// Appends one or more opcodes to the script.
	///
	/// # Arguments
	///
	/// * `op_codes` - A slice of `OpCode` values to append to the script.
	///
	/// # Returns
	///
	/// A mutable reference to the `ScriptBuilder` for method chaining.
	///
	/// # Examples
	///
	/// ```rust
	/// use neo3::neo_builder::ScriptBuilder;
	/// use neo3::neo_types::OpCode;
	///
	/// let mut builder = ScriptBuilder::new();
	/// builder.op_code(&[OpCode::Push1, OpCode::Push2, OpCode::Add]);
	/// ```
	pub fn op_code(&mut self, op_codes: &[OpCode]) -> &mut Self {
		for opcode in op_codes {
			self.script.write_u8(opcode.opcode());
		}
		self
	}

	/// Appends an opcode with an argument to the script.
	///
	/// # Arguments
	///
	/// * `opcode` - The `OpCode` to append.
	/// * `argument` - The data argument for the opcode.
	///
	/// # Returns
	///
	/// A mutable reference to the `ScriptBuilder` for method chaining.
	///
	/// # Examples
	///
	/// ```rust
	/// use neo3::neo_builder::ScriptBuilder;
	/// use neo3::neo_types::OpCode;
	///
	/// let mut builder = ScriptBuilder::new();
	/// builder.op_code_with_arg(OpCode::PushData1, vec![0x01, 0x02, 0x03]);
	/// ```
	pub fn op_code_with_arg(&mut self, opcode: OpCode, argument: Bytes) -> &mut Self {
		self.script.write_u8(opcode.opcode());
		let _ = self.script.write_bytes(&argument);
		self
	}

	/// Appends a contract call operation to the script.
	///
	/// # Arguments
	///
	/// * `hash160` - The 160-bit hash of the contract to call.
	/// * `method` - The name of the method to call.
	/// * `params` - A slice of `ContractParameter` values to pass as arguments to the method.
	/// * `call_flags` - An optional `CallFlags` value specifying the call flags.
	///
	/// # Returns
	///
	/// A `Result` containing a mutable reference to the `ScriptBuilder` for method chaining,
	/// or a `BuilderError` if an error occurs.
	///
	/// # Examples
	///
	/// ```rust
	/// use neo3::neo_builder::ScriptBuilder;
	/// use primitive_types::H160;
	/// use neo3::neo_types::ContractParameter;
	/// use neo3::builder::CallFlags;
	///
	/// let mut builder = ScriptBuilder::new();
	/// let contract_hash = H160::from_slice(&[0; 20]);
	/// let result = builder.contract_call(
	///     &contract_hash,
	///     "transfer",
	///     &[ContractParameter::from("NeoToken"), ContractParameter::from(1000)],
	///     Some(CallFlags::All)
	/// );
	/// ```
	pub fn contract_call(
		&mut self,
		hash160: &H160,
		method: &str,
		params: &[ContractParameter],
		call_flags: Option<CallFlags>,
	) -> Result<&mut Self, BuilderError> {
		if params.is_empty() {
			self.op_code(&[OpCode::NewArray0]);
		} else {
			self.push_params(params);
		}

		Ok(self
			.push_integer(BigInt::from(match call_flags {
				Some(flags) => flags.value(),
				None => CallFlags::All.value(),
			}))
			.push_data(method.as_bytes().to_vec())
			.push_data(hash160.to_vec())
			.sys_call(InteropService::SystemContractCall))
	}

	/// Appends a system call operation to the script.
	///
	/// # Arguments
	///
	/// * `operation` - The `InteropService` to call.
	///
	/// # Returns
	///
	/// A mutable reference to the `ScriptBuilder` for method chaining.
	///
	/// # Examples
	///
	/// ```rust
	/// use neo3::neo_builder::ScriptBuilder;
	/// use neo3::builder::InteropService;
	///
	/// let mut builder = ScriptBuilder::new();
	/// builder.sys_call(InteropService::SystemRuntimeCheckWitness);
	/// ```
	pub fn sys_call(&mut self, operation: InteropService) -> &mut Self {
		let hash_bytes = match operation.hash().from_hex_string() {
			Ok(bytes) => bytes,
			Err(e) => {
				// `InteropService::hash()` is derived from `hex::encode`, so this should be
				// unreachable. Still, avoid panicking so callers can't trigger a DoS by
				// feeding malformed data into higher-level builders.
				tracing::warn!(
					error = %e,
					operation = %operation,
					"Failed to decode InteropService hash; using zero bytes"
				);
				vec![0u8; 4]
			},
		};

		self.push_opcode_bytes(OpCode::Syscall, hash_bytes)
	}

	/// Pushes an array of contract parameters to the script.
	///
	/// # Arguments
	///
	/// * `params` - A slice of `ContractParameter` values to push to the script.
	///
	/// # Returns
	///
	/// A mutable reference to the `ScriptBuilder` for method chaining.
	///
	/// # Examples
	///
	/// ```rust
	/// use neo3::neo_builder::ScriptBuilder;
	/// use neo3::neo_types::ContractParameter;
	///
	/// let mut builder = ScriptBuilder::new();
	/// builder.push_params(&[
	///     ContractParameter::from("param1"),
	///     ContractParameter::from(42),
	///     ContractParameter::from(true)
	/// ]);
	/// ```
	pub fn push_params(&mut self, params: &[ContractParameter]) -> Result<&mut Self, BuilderError> {
		for param in params {
			self.push_param(param).map_err(|e| {
				BuilderError::IllegalArgument(format!("Failed to push parameter: {}", e))
			})?;
		}

		Ok(self.push_integer(BigInt::from(params.len())).op_code(&[OpCode::Pack]))
	}

	/// Pushes a single contract parameter to the script.
	///
	/// # Arguments
	///
	/// * `param` - The `ContractParameter` value to push to the script.
	///
	/// # Returns
	///
	/// A `Result` containing a mutable reference to the `ScriptBuilder` for method chaining,
	/// or a `BuilderError` if an error occurs.
	///
	/// # Examples
	///
	/// ```rust
	/// use neo3::neo_builder::ScriptBuilder;
	/// use neo3::neo_types::ContractParameter;
	///
	/// let mut builder = ScriptBuilder::new();
	/// builder.push_param(&ContractParameter::from("Hello, Neo!")).unwrap();
	/// ```
	pub fn push_param(&mut self, param: &ContractParameter) -> Result<&mut Self, BuilderError> {
		if param.get_type() == ContractParameterType::Any {
			self.op_code(&[OpCode::PushNull]);
			return Ok(self);
		}
		match &param
			.value
			.clone()
			.ok_or_else(|| BuilderError::IllegalArgument("Parameter value is None".to_string()))?
		{
			ParameterValue::Boolean(b) => self.push_bool(*b),
			ParameterValue::Integer(i) => self.push_integer(BigInt::from(i.clone())),
			ParameterValue::ByteArray(b) => {
				// Decode the base64-encoded string to get the actual bytes
				let bytes = b.from_base64_string().map_err(|e| {
					BuilderError::IllegalArgument(format!(
						"Failed to decode base64 ByteArray: {}",
						e
					))
				})?;
				self.push_data(bytes)
			},
			ParameterValue::Signature(b) | ParameterValue::PublicKey(b) => {
				self.push_data(b.as_bytes().to_vec())
			},
			ParameterValue::H160(h) => self.push_data(h.as_bytes().to_vec()),
			ParameterValue::H256(h) => self.push_data(h.as_bytes().to_vec()),
			ParameterValue::String(s) => self.push_data(s.as_bytes().to_vec()),
			ParameterValue::Array(arr) => self.push_array(arr).map_err(|e| {
				BuilderError::IllegalArgument(format!("Failed to push array: {}", e))
			})?,
			ParameterValue::Map(map) => self
				.push_map(&map.0)
				.map_err(|e| BuilderError::IllegalArgument(format!("Failed to push map: {}", e)))?,
			_ => {
				return Err(BuilderError::IllegalArgument("Unsupported parameter type".to_string()))
			},
		};

		Ok(self)
	}

	/// Adds a push operation with the given integer to the script.
	///
	/// The integer is encoded in its two's complement representation and little-endian byte order.
	///
	/// The integer can be up to 32 bytes in length. Values larger than 32 bytes can be
	/// handled explicitly with [`ScriptBuilder::try_push_integer`]. This convenience method
	/// panics on oversized values instead of silently truncating them.
	///
	/// # Arguments
	///
	/// * `i` - The integer to push to the script
	///
	/// # Returns
	///
	/// A mutable reference to the `ScriptBuilder` for method chaining.
	///
	/// # Examples
	///
	/// ```rust
	/// use neo3::neo_builder::ScriptBuilder;
	/// use num_bigint::BigInt;
	///
	/// let mut builder = ScriptBuilder::new();
	/// builder.push_integer(BigInt::from(42));
	/// ```
	pub fn push_integer(&mut self, i: BigInt) -> &mut Self {
		self.try_push_integer(i).unwrap_or_else(|err| {
			panic!(
				"integer exceeds Neo VM 32-byte limit; use ScriptBuilder::try_push_integer for fallible handling: {}",
				err
			)
		})
	}

	/// Adds a push operation with the given integer to the script, returning an error
	/// instead of truncating values that exceed the Neo VM 32-byte integer limit.
	///
	/// This method preserves Neo VM signed integer semantics. For example, `255` is encoded
	/// as `PushInt16` with bytes `[0xff, 0x00]` rather than `PushInt8`, because `PushInt8`
	/// operands are interpreted as signed 8-bit two's-complement integers.
	pub fn try_push_integer(&mut self, i: BigInt) -> Result<&mut Self, BuilderError> {
		if i >= BigInt::from(-1) && i <= BigInt::from(16) {
			let Some(i32_value) = i.to_i32() else {
				return Err(BuilderError::IllegalState(
					"failed to convert small integer to i32".to_string(),
				));
			};

			let opcode_u8 = i32_value as u8 + OpCode::Push0 as u8;
			let opcode = OpCode::try_from(opcode_u8).map_err(|_| {
				BuilderError::IllegalState(format!(
					"invalid opcode for small integer push: {opcode_u8}",
				))
			})?;

			self.op_code(&[opcode]);
			return Ok(self);
		}

		let bytes = i.to_signed_bytes_le();
		let len = bytes.len();

		match len {
			1 => self.push_opcode_bytes(OpCode::PushInt8, bytes),
			2 => self.push_opcode_bytes(OpCode::PushInt16, bytes),
			len if len <= 4 => self
				.push_opcode_bytes(OpCode::PushInt32, Self::pad_right(&bytes, 4, i.is_negative())),
			len if len <= 8 => self
				.push_opcode_bytes(OpCode::PushInt64, Self::pad_right(&bytes, 8, i.is_negative())),
			len if len <= 16 => self.push_opcode_bytes(
				OpCode::PushInt128,
				Self::pad_right(&bytes, 16, i.is_negative()),
			),
			len if len <= 32 => self.push_opcode_bytes(
				OpCode::PushInt256,
				Self::pad_right(&bytes, 32, i.is_negative()),
			),
			_ => {
				return Err(BuilderError::IllegalArgument(
					"integer exceeds Neo VM 32-byte limit".to_string(),
				));
			},
		};

		Ok(self)
	}

	/// Append opcodes to the script in the provided order.
	///
	/// # Arguments
	///
	/// * `opcode` - The opcode to append
	/// * `argument` - The data argument for the opcode
	///
	/// # Returns
	///
	/// A mutable reference to the `ScriptBuilder` for method chaining.
	///
	/// # Examples
	///
	/// ```rust
	/// use neo3::neo_builder::ScriptBuilder;
	/// use neo3::neo_types::OpCode;
	///
	/// let mut builder = ScriptBuilder::new();
	/// builder.push_opcode_bytes(OpCode::PushData1, vec![0x01, 0x02, 0x03]);
	/// ```
	pub fn push_opcode_bytes(&mut self, opcode: OpCode, argument: Vec<u8>) -> &mut ScriptBuilder {
		self.script.write_u8(opcode as u8);
		self.script.write_bytes(&argument);

		self
	}

	fn pad_right(bytes: &[u8], size: usize, negative: bool) -> Vec<u8> {
		let pad_value = if negative { 0xFF } else { 0 };

		let mut padded = vec![0; size];
		padded[0..bytes.len()].copy_from_slice(bytes);
		padded[bytes.len()..].fill(pad_value);
		padded
	}

	// Push data handling

	/// Pushes data to the script.
	///
	/// # Arguments
	///
	/// * `data` - The data to push to the script.
	///
	/// # Returns
	///
	/// A mutable reference to the `ScriptBuilder` for method chaining.
	///
	/// # Examples
	///
	/// ```rust
	/// use neo3::neo_builder::ScriptBuilder;
	///
	/// let mut builder = ScriptBuilder::new();
	/// builder.push_data("Hello, Neo!".as_bytes().to_vec());
	/// ```
	pub fn push_data(&mut self, data: Vec<u8>) -> &mut Self {
		match data.len() {
			0..=0xff => {
				self.op_code(&[OpCode::PushData1]);
				self.script.write_u8(data.len() as u8);
				let _ = self.script.write_bytes(&data);
			},
			0x100..=0xffff => {
				self.op_code(&[OpCode::PushData2]);
				self.script.write_u16(data.len() as u16);
				let _ = self.script.write_bytes(&data);
			},
			_ => {
				self.op_code(&[OpCode::PushData4]);
				self.script.write_u32(data.len() as u32);
				let _ = self.script.write_bytes(&data);
			}, // _ => return Err(BuilderError::IllegalArgument("Data too long".to_string())),
		}
		self
	}

	/// Pushes a boolean value to the script.
	///
	/// # Arguments
	///
	/// * `b` - The boolean value to push to the script.
	///
	/// # Returns
	///
	/// A mutable reference to the `ScriptBuilder` for method chaining.
	///
	/// # Examples
	///
	/// ```rust
	/// use neo3::neo_builder::ScriptBuilder;
	///
	/// let mut builder = ScriptBuilder::new();
	/// builder.push_bool(true);
	/// ```
	pub fn push_bool(&mut self, b: bool) -> &mut Self {
		if b {
			self.op_code(&[OpCode::PushTrue])
		} else {
			self.op_code(&[OpCode::PushFalse])
		};
		self
	}

	/// Pushes an array of contract parameters to the script.
	///
	/// # Arguments
	///
	/// * `arr` - A slice of `ContractParameter` values to push to the script.
	///
	/// # Returns
	///
	/// A `Result` containing a mutable reference to the `ScriptBuilder` for method chaining,
	/// or a `BuilderError` if an error occurs.
	///
	pub fn push_array(&mut self, arr: &[ContractParameter]) -> Result<&mut Self, BuilderError> {
		if arr.is_empty() {
			self.op_code(&[OpCode::NewArray0]);
		} else {
			self.push_params(arr);
		};
		Ok(self)
	}

	/// Pushes a map of contract parameters to the script.
	///
	/// # Arguments
	///
	/// * `map` - A reference to a `HashMap` mapping `ContractParameter` keys to `ContractParameter` values.
	///
	/// # Returns
	///
	/// A `Result` containing a mutable reference to the `ScriptBuilder` for method chaining,
	/// or a `BuilderError` if an error occurs.
	pub fn push_map(
		&mut self,
		map: &HashMap<ContractParameter, ContractParameter>,
	) -> Result<&mut Self, BuilderError> {
		for (k, v) in map {
			let kk: ContractParameter = k.clone().into();
			let vv: ContractParameter = v.clone().into();
			self.push_param(&vv)?;
			self.push_param(&kk)?;
		}

		Ok(self.push_integer(BigInt::from(map.len())).op_code(&[OpCode::PackMap]))
	}

	/// Appends the `Pack` opcode to the script.
	///
	/// # Returns
	///
	/// A mutable reference to the `ScriptBuilder` for method chaining.
	pub fn pack(&mut self) -> &mut Self {
		self.op_code(&[OpCode::Pack])
	}

	/// Returns the script as a `Bytes` object.
	pub fn to_bytes(&self) -> Bytes {
		self.script.to_bytes()
	}

	/// Builds a verification script for the given public key.
	///
	/// # Arguments
	///
	/// * `pub_key` - The public key to use for verification.
	///
	/// # Returns
	///
	/// A `Bytes` object containing the verification script.
	pub fn build_verification_script(pub_key: &Secp256r1PublicKey) -> Bytes {
		let mut sb = ScriptBuilder::new();
		sb.push_data(pub_key.get_encoded(true))
			.sys_call(InteropService::SystemCryptoCheckSig);
		sb.to_bytes()
	}

	/// Builds a multi-signature script for the given public keys and threshold.
	///
	/// # Arguments
	///
	/// * `pubkeys` - A mutable slice of `Secp256r1PublicKey` values representing the public keys.
	/// * `threshold` - The minimum number of signatures required to validate the script.
	///
	/// # Returns
	///
	/// A `Result` containing a `Bytes` object containing the multi-signature script,
	/// or a `BuilderError` if an error occurs.
	pub fn build_multi_sig_script(
		pubkeys: &mut [Secp256r1PublicKey],
		threshold: u8,
	) -> Result<Bytes, BuilderError> {
		let mut sb = ScriptBuilder::new();
		sb.push_integer(BigInt::from(threshold));
		// Canonical Neo N3 sort: by compressed encoded bytes (via Ord impl)
		pubkeys.sort();
		for pk in pubkeys.iter() {
			sb.push_data(pk.get_encoded(true));
		}
		sb.push_integer(BigInt::from(pubkeys.len()));
		sb.sys_call(InteropService::SystemCryptoCheckMultiSig);
		Ok(sb.to_bytes())
	}

	/// Builds a contract script for the given sender, NEF checksum, and contract name.
	///
	/// This method creates a script for deploying a smart contract on the Neo N3 blockchain.
	///
	/// # Arguments
	///
	/// * `sender` - The 160-bit hash of the contract sender.
	/// * `nef_checksum` - The checksum of the NEF (Neo Executable Format) file.
	/// * `name` - The name of the contract.
	///
	/// # Returns
	///
	/// A `Result` containing a `Bytes` object with the contract deployment script,
	/// or a `BuilderError` if an error occurs.
	///
	/// # Examples
	///
	/// ```rust
	/// use neo3::neo_builder::ScriptBuilder;
	/// use primitive_types::H160;
	/// use std::str::FromStr;
	///
	/// let sender = H160::from_str("0xd2a4cff31913016155e38e474a2c06d08be276cf").unwrap();
	/// let nef_checksum = 1234567890;
	/// let name = "MyContract";
	///
	/// let script = ScriptBuilder::build_contract_script(&sender, nef_checksum, name).unwrap();
	/// ```
	/// * `nef_checksum` - The checksum of the NEF file.
	/// * `name` - The name of the contract.
	///
	/// # Returns
	///
	/// A `Result` containing a `Bytes` object containing the contract script,
	/// or a `BuilderError` if an error occurs.
	pub fn build_contract_script(
		sender: &H160,
		nef_checksum: u32,
		name: &str,
	) -> Result<Bytes, BuilderError> {
		let mut sb = ScriptBuilder::new();
		sb.op_code(&[OpCode::Abort])
			.push_data(sender.to_vec())
			.push_integer(BigInt::from(nef_checksum))
			.push_data(name.as_bytes().to_vec());
		Ok(sb.to_bytes())
	}

	/// Builds a script that calls a contract method and unwraps the iterator result.
	///
	/// This method is particularly useful when calling contract methods that return iterators.
	/// It automatically handles the iteration process and collects the results into an array.
	///
	/// # Arguments
	///
	/// * `contract_hash` - The 160-bit hash of the contract to call.
	/// * `method` - The name of the method to call.
	/// * `params` - A slice of `ContractParameter` values to pass as arguments to the method.
	/// * `max_items` - The maximum number of items to retrieve from the iterator.
	/// * `call_flags` - An optional `CallFlags` value specifying the call flags.
	///
	/// # Returns
	///
	/// A `Result` containing a `Bytes` object with the script that calls the contract method
	/// and unwraps the iterator result into an array, or a `BuilderError` if an error occurs.
	///
	/// # Examples
	///
	/// ```rust
	/// use neo3::neo_builder::ScriptBuilder;
	/// use neo3::neo_types::ContractParameter;
	/// use neo3::builder::CallFlags;
	/// use primitive_types::H160;
	/// use std::str::FromStr;
	///
	/// // Call a contract method that returns an iterator and collect up to 100 items
	/// let contract_hash = H160::from_str("0xd2a4cff31913016155e38e474a2c06d08be276cf").unwrap();
	/// let method = "getTokens";
	/// let params = vec![ContractParameter::from("owner_address")];
	/// let max_items = 100;
	///
	/// // Build the script
	/// let script = ScriptBuilder::build_contract_call_and_unwrap_iterator(
	///     &contract_hash,
	///     method,
	///     &params,
	///     max_items,
	///     Some(CallFlags::All)
	/// ).unwrap();
	///
	/// // The resulting script will:
	/// // 1. Call the contract method
	/// // 2. Iterate through the returned iterator
	/// // 3. Collect up to max_items into an array
	/// // 4. Leave the array on the stack
	/// ```
	pub fn build_contract_call_and_unwrap_iterator(
		contract_hash: &H160,
		method: &str,
		params: &[ContractParameter],
		max_items: u32,
		call_flags: Option<CallFlags>,
	) -> Result<Bytes, BuilderError> {
		let mut sb = Self::new();
		sb.push_integer(BigInt::from(max_items));

		sb.contract_call(contract_hash, method, params, call_flags)?;

		sb.op_code(&[OpCode::NewArray]);

		let cycle_start = sb.len();
		sb.op_code(&[OpCode::Over]);
		sb.sys_call(InteropService::SystemIteratorNext);

		let jmp_if_not = sb.len();
		sb.op_code_with_arg(OpCode::JmpIf, vec![0]);

		sb.op_code(&[OpCode::Dup, OpCode::Push2, OpCode::Pick])
			.sys_call(InteropService::SystemIteratorValue)
			.op_code(&[
				OpCode::Append,
				OpCode::Dup,
				OpCode::Size,
				OpCode::Push3,
				OpCode::Pick,
				OpCode::Ge,
			]);

		let jmp_if_max = sb.len();
		sb.op_code_with_arg(OpCode::JmpIf, vec![0]);

		let jmp_offset = sb.len();
		// Calculate backward jump as a signed offset
		let jmp_bytes = (cycle_start as i32 - jmp_offset as i32) as i8;
		sb.op_code_with_arg(OpCode::Jmp, vec![jmp_bytes as u8]);

		let load_result = sb.len();
		sb.op_code(&[OpCode::Nip, OpCode::Nip]);

		let mut script = sb.to_bytes();
		let jmp_not_bytes = (load_result - jmp_if_not) as i8;
		script[jmp_if_not + 1] = jmp_not_bytes as u8;

		let jmp_max_bytes = (load_result - jmp_if_max) as i8;
		script[jmp_if_max + 1] = jmp_max_bytes as u8;

		Ok(script)
	}

	/// Returns the length of the script in bytes.
	///
	/// This method is useful for determining the current position in the script,
	/// which is needed for calculating jump offsets in control flow operations.
	///
	/// # Returns
	///
	/// The length of the script in bytes.
	///
	/// # Examples
	///
	/// ```rust
	/// use neo3::neo_builder::ScriptBuilder;
	///
	/// let mut builder = ScriptBuilder::new();
	/// builder.push_data("Hello, Neo!".as_bytes().to_vec());
	/// let script_length = builder.len();
	/// println!("Script length: {} bytes", script_length);
	/// ```
	pub fn len(&self) -> usize {
		self.script().size()
	}
}

#[cfg(test)]
mod tests {
	use super::*;
	use crate::{
		neo_types::{contract::ContractParameterMap, ContractParameter, ContractParameterType},
		prelude::Bytes,
	};
	use num_bigint::BigInt;
	use std::collections::HashMap;

	#[test]
	fn test_push_empty_array() {
		let mut builder = ScriptBuilder::new();
		builder.push_array(&[]).unwrap();
		assert_builder(&builder, &[OpCode::NewArray0 as u8]);
	}

	#[test]
	fn test_push_byte_array() {
		let mut builder = ScriptBuilder::new();
		let data = vec![0x01, 0x02, 0x03];
		builder.push_data(data.clone());

		let mut expected = vec![OpCode::PushData1 as u8, data.len() as u8];
		expected.extend(data);
		assert_builder(&builder, &expected);
	}

	#[test]
	fn test_push_string() {
		let mut builder = ScriptBuilder::new();
		let string_data = "Hello, Neo!";
		builder.push_data(string_data.as_bytes().to_vec());

		let mut expected = vec![OpCode::PushData1 as u8, string_data.len() as u8];
		expected.extend(string_data.as_bytes());
		assert_builder(&builder, &expected);
	}

	#[test]
	fn test_push_integer() {
		let mut builder = ScriptBuilder::new();

		// Test small integers (-1 to 16)
		builder.push_integer(BigInt::from(0));
		assert_builder(&builder, &[OpCode::Push0 as u8]);

		let mut builder = ScriptBuilder::new();
		builder.push_integer(BigInt::from(16));
		assert_builder(&builder, &[OpCode::Push16 as u8]);

		// Test larger positive integers near sign boundaries
		let mut builder = ScriptBuilder::new();
		builder.push_integer(BigInt::from(127));
		assert_builder(&builder, &[OpCode::PushInt8 as u8, 0x7f]);

		let mut builder = ScriptBuilder::new();
		builder.push_integer(BigInt::from(128));
		assert_builder(&builder, &[OpCode::PushInt16 as u8, 0x80, 0x00]);

		let mut builder = ScriptBuilder::new();
		builder.push_integer(BigInt::from(255));
		assert_builder(&builder, &[OpCode::PushInt16 as u8, 0xff, 0x00]);

		let mut builder = ScriptBuilder::new();
		builder.push_integer(BigInt::from(256));
		assert_builder(&builder, &[OpCode::PushInt16 as u8, 0x00, 0x01]);

		let mut builder = ScriptBuilder::new();
		builder.push_integer(BigInt::from(32767));
		assert_builder(&builder, &[OpCode::PushInt16 as u8, 0xff, 0x7f]);

		let mut builder = ScriptBuilder::new();
		builder.push_integer(BigInt::from(32768));
		assert_builder(&builder, &[OpCode::PushInt32 as u8, 0x00, 0x80, 0x00, 0x00]);

		let mut builder = ScriptBuilder::new();
		builder.push_integer(BigInt::from(65535));
		assert_builder(&builder, &[OpCode::PushInt32 as u8, 0xff, 0xff, 0x00, 0x00]);

		// Test negative integers - update expectations to match our more efficient implementation
		let mut builder = ScriptBuilder::new();
		builder.push_integer(BigInt::from(-1000000000000000i64));
		// Our implementation uses PushInt64 (more efficient) instead of PushInt128
		// The actual bytes are: [0, 128, 57, 91, 129, 114, 252] padded to 8 bytes with 0xFF
		let expected_bytes = vec![OpCode::PushInt64 as u8, 0, 128, 57, 91, 129, 114, 252, 255];
		assert_builder(&builder, &expected_bytes);

		let mut builder = ScriptBuilder::new();
		builder.push_integer(BigInt::from(1000000000000000i64));
		// Similarly, this should use PushInt64 instead of PushInt128
		// The actual bytes for positive 1000000000000000 should be different
		let pos_big_int = BigInt::from(1000000000000000i64);
		let pos_bytes = pos_big_int.to_signed_bytes_le();
		let mut expected_pos = vec![OpCode::PushInt64 as u8];
		let padded_pos = ScriptBuilder::pad_right(&pos_bytes, 8, false);
		expected_pos.extend(padded_pos);
		assert_builder(&builder, &expected_pos);
	}

	#[test]
	fn test_try_push_integer_rejects_values_larger_than_32_bytes() {
		let mut builder = ScriptBuilder::new();
		let too_large = BigInt::from(1u8) << 256;

		let result = builder.try_push_integer(too_large);
		assert!(result.is_err());
	}

	#[test]
	#[should_panic(expected = "integer exceeds Neo VM 32-byte limit")]
	fn test_push_integer_panics_on_values_larger_than_32_bytes() {
		let mut builder = ScriptBuilder::new();
		let too_large = BigInt::from(1u8) << 256;

		builder.push_integer(too_large);
	}

	#[test]
	fn test_try_push_integer_matches_legacy_encoding_for_supported_values() {
		let value = BigInt::from(255);

		let mut legacy = ScriptBuilder::new();
		legacy.push_integer(value.clone());

		let mut fallible = ScriptBuilder::new();
		fallible
			.try_push_integer(value)
			.expect("supported integer should encode successfully");

		assert_eq!(legacy.to_bytes().to_vec(), fallible.to_bytes().to_vec());
	}

	#[test]
	fn test_verification_script() {
		let public_key = Secp256r1PublicKey::from_bytes(
			&hex::decode("035fdb1d1f06759547020891ae97c729327853aeb1256b6fe0473bc2e9fa42ff50")
				.unwrap(),
		)
		.unwrap();

		let script = ScriptBuilder::build_verification_script(&public_key);

		// The script should be: PushData1 (0x0c) + length (33/0x21) + public key (33 bytes) + Syscall (0x41) + SystemCryptoCheckSig hash
		// Let's build the expected result dynamically to ensure it's correct
		let mut expected = vec![0x0c, 0x21]; // PushData1 + length 33
		expected.extend_from_slice(
			&hex::decode("035fdb1d1f06759547020891ae97c729327853aeb1256b6fe0473bc2e9fa42ff50")
				.unwrap(),
		);
		expected.push(0x41); // Syscall opcode
		expected
			.extend_from_slice(&hex::decode(&InteropService::SystemCryptoCheckSig.hash()).unwrap());

		assert_eq!(script.to_vec(), expected);
	}

	#[test]
	fn test_map() {
		let mut map = HashMap::new();
		map.insert(
			ContractParameter::string("first".to_string()),
			ContractParameter::byte_array(hex::decode("7365636f6e64").unwrap()),
		);

		let mut builder = ScriptBuilder::new();
		builder.push_map(&map).unwrap();

		let expected = builder.to_bytes().to_hex_string();

		let mut builder2 = ScriptBuilder::new();
		builder2
			.push_data(hex::decode("7365636f6e64").unwrap())
			.push_data("first".as_bytes().to_vec())
			.push_integer(BigInt::from(1))
			.op_code(&[OpCode::PackMap]);

		let expected2 = builder2.to_bytes().to_hex_string();

		let mut builder3 = ScriptBuilder::new().push_map(&map).unwrap().to_bytes().to_hex_string();

		assert_eq!(expected, expected2);
		assert_eq!(expected, builder3);
	}

	#[test]
	fn test_map_nested() {
		let mut inner = ContractParameterMap::new();
		inner.0.insert(
			ContractParameter::string("inner_key".to_string()),
			ContractParameter::integer(42),
		);

		let mut outer = ContractParameterMap::new();
		outer.0.insert(
			ContractParameter::string("outer_key".to_string()),
			ContractParameter::map(inner),
		);

		let expected = ScriptBuilder::new().push_map(&outer.0).unwrap().to_bytes().to_hex_string();

		// Manually build the expected script
		let mut manual_builder = ScriptBuilder::new();
		manual_builder
			.push_integer(BigInt::from(42))
			.push_data("inner_key".as_bytes().to_vec())
			.push_integer(BigInt::from(1))
			.op_code(&[OpCode::PackMap])
			.push_data("outer_key".as_bytes().to_vec())
			.push_integer(BigInt::from(1))
			.op_code(&[OpCode::PackMap]);

		let manual_expected = manual_builder.to_bytes().to_hex_string();

		assert_eq!(expected, manual_expected);
	}

	fn assert_builder(builder: &ScriptBuilder, expected: &[u8]) {
		assert_eq!(builder.to_bytes().to_vec(), expected);
	}

	fn byte_array(size: usize) -> Vec<u8> {
		(0..size).map(|i| (i % 256) as u8).collect()
	}
}