neo3 1.0.8

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
//! Policy native contract for Neo N3.
//!
//! The Policy contract manages system policies including fees, blocked accounts,
//! and various network parameters.
//!
//! Updated for Neo 3.9 with support for:
//! - Milliseconds per block (HF_Echidna)
//! - Max valid until block increment (HF_Echidna)
//! - Max traceable blocks (HF_Echidna)
//! - Attribute fees (HF_Echidna)
//! - Execution fee factor with decimals (HF_Faun)
//! - Whitelist fee contracts (HF_Faun)
//! - Fund recovery from blocked accounts (HF_Faun)

use async_trait::async_trait;
use primitive_types::H160;
use serde::{Deserialize, Serialize};
use std::sync::Arc;

use crate::{
	neo_builder::TransactionBuilder,
	neo_clients::{JsonRpcProvider, RpcClient},
	neo_contract::{traits::SmartContractTrait, ContractError, NeoIterator},
	neo_types::{
		serde_with_utils::{deserialize_script_hash, serialize_script_hash},
		ScriptHash, StackItem, WhitelistedContract,
	},
	ScriptHashExtension,
};

/// The Policy native contract for managing system policies.
///
/// This contract controls network parameters such as fees, blocked accounts,
/// and various protocol settings.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PolicyContract<'a, P: JsonRpcProvider> {
	#[serde(deserialize_with = "deserialize_script_hash")]
	#[serde(serialize_with = "serialize_script_hash")]
	script_hash: ScriptHash,
	#[serde(skip)]
	provider: Option<&'a RpcClient<P>>,
}

impl<'a, P: JsonRpcProvider + 'static> PolicyContract<'a, P> {
	/// The name of the Policy contract.
	pub const NAME: &'static str = "PolicyContract";

	/// The default execution fee factor.
	pub const DEFAULT_EXEC_FEE_FACTOR: u32 = 30;

	/// The default storage price.
	pub const DEFAULT_STORAGE_PRICE: u32 = 100000;

	/// The default network fee per byte (in datoshi, 1 datoshi = 1e-8 GAS).
	pub const DEFAULT_FEE_PER_BYTE: u32 = 1000;

	/// The default fee for transaction attributes.
	pub const DEFAULT_ATTRIBUTE_FEE: u32 = 0;

	/// The default fee for NotaryAssisted attribute (in datoshi).
	pub const DEFAULT_NOTARY_ASSISTED_ATTRIBUTE_FEE: u32 = 10_000_000;

	/// The maximum execution fee factor.
	pub const MAX_EXEC_FEE_FACTOR: u64 = 100;

	/// The maximum fee for transaction attributes.
	pub const MAX_ATTRIBUTE_FEE: u32 = 10_0000_0000;

	/// The maximum storage price.
	pub const MAX_STORAGE_PRICE: u32 = 10_000_000;

	/// The maximum block generation time in milliseconds.
	pub const MAX_MILLISECONDS_PER_BLOCK: u32 = 30_000;

	/// The maximum MaxValidUntilBlockIncrement value (1 day of 1-second blocks).
	pub const MAX_MAX_VALID_UNTIL_BLOCK_INCREMENT: u32 = 86400;

	/// The maximum MaxTraceableBlocks value (1 year of 15-second blocks).
	pub const MAX_MAX_TRACEABLE_BLOCKS: u32 = 2_102_400;

	/// Creates a new PolicyContract instance.
	pub fn new(provider: Option<&'a RpcClient<P>>) -> Self {
		Self { script_hash: Self::calc_native_contract_hash_unchecked(Self::NAME), provider }
	}

	// ========== Basic Policy Methods ==========

	/// Gets the network fee per transaction byte (in datoshi).
	pub async fn get_fee_per_byte(&self) -> Result<i64, ContractError> {
		Ok(self.call_function_returning_int("getFeePerByte", vec![]).await? as i64)
	}

	/// Gets the execution fee factor.
	///
	/// This is a multiplier used to calculate system fees for transactions.
	/// After HF_Faun, this returns the factor without decimals (use `get_exec_pico_fee_factor`
	/// for the full precision value).
	pub async fn get_exec_fee_factor(&self) -> Result<u32, ContractError> {
		Ok(self.call_function_returning_int("getExecFeeFactor", vec![]).await? as u32)
	}

	/// Gets the execution fee factor in pico-GAS (1 pico-GAS = 1e-12 GAS).
	///
	/// This method is available after HF_Faun and returns the fee factor with full decimal precision.
	pub async fn get_exec_pico_fee_factor(&self) -> Result<i64, ContractError> {
		Ok(self.call_function_returning_int("getExecPicoFeeFactor", vec![]).await? as i64)
	}

	/// Gets the storage price (cost per byte of storage).
	pub async fn get_storage_price(&self) -> Result<u32, ContractError> {
		Ok(self.call_function_returning_int("getStoragePrice", vec![]).await? as u32)
	}

	// ========== Block Time and Limits (HF_Echidna) ==========

	/// Gets the block generation time in milliseconds.
	///
	/// This method is available after HF_Echidna.
	pub async fn get_milliseconds_per_block(&self) -> Result<u32, ContractError> {
		Ok(self.call_function_returning_int("getMillisecondsPerBlock", vec![]).await? as u32)
	}

	/// Sets the block generation time in milliseconds.
	///
	/// This method requires committee approval.
	/// Value must be between 1 and MAX_MILLISECONDS_PER_BLOCK (30,000).
	///
	/// Available after HF_Echidna.
	pub async fn set_milliseconds_per_block(
		&self,
		value: u32,
	) -> Result<TransactionBuilder<'_, P>, ContractError> {
		self.invoke_function("setMillisecondsPerBlock", vec![value.into()]).await
	}

	/// Gets the maximum ValidUntilBlock increment for transactions.
	///
	/// This method is available after HF_Echidna.
	pub async fn get_max_valid_until_block_increment(&self) -> Result<u32, ContractError> {
		Ok(self
			.call_function_returning_int("getMaxValidUntilBlockIncrement", vec![])
			.await? as u32)
	}

	/// Sets the maximum ValidUntilBlock increment.
	///
	/// This method requires committee approval.
	/// Value must be between 1 and MAX_MAX_VALID_UNTIL_BLOCK_INCREMENT (86,400)
	/// and less than MaxTraceableBlocks.
	///
	/// Available after HF_Echidna.
	pub async fn set_max_valid_until_block_increment(
		&self,
		value: u32,
	) -> Result<TransactionBuilder<'_, P>, ContractError> {
		self.invoke_function("setMaxValidUntilBlockIncrement", vec![value.into()]).await
	}

	/// Gets the maximum number of blocks accessible to smart contracts.
	///
	/// This method is available after HF_Echidna.
	pub async fn get_max_traceable_blocks(&self) -> Result<u32, ContractError> {
		Ok(self.call_function_returning_int("getMaxTraceableBlocks", vec![]).await? as u32)
	}

	/// Sets the maximum number of traceable blocks.
	///
	/// This method requires committee approval.
	/// Value must be between 1 and MAX_MAX_TRACEABLE_BLOCKS (2,102,400),
	/// cannot be increased, and must be greater than MaxValidUntilBlockIncrement.
	///
	/// Available after HF_Echidna.
	pub async fn set_max_traceable_blocks(
		&self,
		value: u32,
	) -> Result<TransactionBuilder<'_, P>, ContractError> {
		self.invoke_function("setMaxTraceableBlocks", vec![value.into()]).await
	}

	// ========== Attribute Fees (HF_Echidna) ==========

	/// Gets the fee for a specific transaction attribute type.
	///
	/// Available after HF_Echidna.
	///
	/// # Arguments
	///
	/// * `attribute_type` - The transaction attribute type (as a byte value).
	pub async fn get_attribute_fee(&self, attribute_type: u8) -> Result<u32, ContractError> {
		Ok(self
			.call_function_returning_int("getAttributeFee", vec![attribute_type.into()])
			.await? as u32)
	}

	/// Sets the fee for a specific transaction attribute type.
	///
	/// This method requires committee approval.
	///
	/// Available after HF_Echidna.
	///
	/// # Arguments
	///
	/// * `attribute_type` - The transaction attribute type (as a byte value).
	/// * `value` - The fee value (must be <= MAX_ATTRIBUTE_FEE).
	pub async fn set_attribute_fee(
		&self,
		attribute_type: u8,
		value: u32,
	) -> Result<TransactionBuilder<'_, P>, ContractError> {
		self.invoke_function("setAttributeFee", vec![attribute_type.into(), value.into()])
			.await
	}

	// ========== Account Blocking ==========

	/// Checks if the specified account is blocked.
	pub async fn is_blocked(&self, script_hash: &H160) -> Result<bool, ContractError> {
		self.call_function_returning_bool("isBlocked", vec![script_hash.into()]).await
	}

	/// Gets blocked accounts as an iterator.
	///
	/// Available after HF_Faun.
	pub async fn get_blocked_accounts(&self) -> Result<NeoIterator<'_, H160, P>, ContractError> {
		self.call_function_returning_iterator(
			"getBlockedAccounts",
			vec![],
			Arc::new(|item: StackItem| {
				item.as_hash160()
					.ok_or_else(|| ContractError::UnexpectedReturnType("Hash160".to_string()))
			}),
		)
		.await
	}

	/// Gets all blocked accounts by fully unwrapping the iterator.
	///
	/// Available after HF_Faun.
	pub async fn get_blocked_accounts_all(&self) -> Result<Vec<H160>, ContractError> {
		self.get_blocked_accounts_all_with_batch(
			<Self as SmartContractTrait>::DEFAULT_ITERATOR_COUNT,
		)
		.await
	}

	/// Gets all blocked accounts using a custom batch size.
	///
	/// Available after HF_Faun.
	pub async fn get_blocked_accounts_all_with_batch(
		&self,
		batch_size: usize,
	) -> Result<Vec<H160>, ContractError> {
		let iterator = self.get_blocked_accounts().await?;
		self.collect_all(iterator, batch_size).await
	}

	/// Blocks an account.
	///
	/// This method requires committee approval.
	/// After HF_Faun, blocking an account will also clear its votes.
	pub async fn block_account(
		&self,
		account: &H160,
	) -> Result<TransactionBuilder<'_, P>, ContractError> {
		self.invoke_function("blockAccount", vec![account.into()]).await
	}

	/// Blocks an account by address.
	///
	/// This method requires committee approval.
	pub async fn block_account_address(
		&self,
		address: &str,
	) -> Result<TransactionBuilder<'_, P>, ContractError> {
		let account = ScriptHash::from_address(address)
			.map_err(|_| ContractError::InvalidAccount("Invalid address".to_string()))?;
		self.block_account(&account).await
	}

	/// Unblocks an account.
	///
	/// This method requires committee approval.
	pub async fn unblock_account(
		&self,
		account: &H160,
	) -> Result<TransactionBuilder<'_, P>, ContractError> {
		self.invoke_function("unblockAccount", vec![account.into()]).await
	}

	/// Unblocks an account by address.
	///
	/// This method requires committee approval.
	pub async fn unblock_account_address(
		&self,
		address: &str,
	) -> Result<TransactionBuilder<'_, P>, ContractError> {
		let account = ScriptHash::from_address(address)
			.map_err(|_| ContractError::InvalidAccount("Invalid address".to_string()))?;
		self.unblock_account(&account).await
	}

	// ========== Fee Factor and Price Setters ==========

	/// Sets the network fee per byte.
	///
	/// This method requires committee approval.
	/// Value must be between 0 and 100,000,000.
	pub async fn set_fee_per_byte(
		&self,
		fee: i64,
	) -> Result<TransactionBuilder<'_, P>, ContractError> {
		self.invoke_function("setFeePerByte", vec![fee.into()]).await
	}

	/// Sets the execution fee factor.
	///
	/// This method requires committee approval.
	/// After HF_Faun, the maximum value is increased to account for decimals.
	pub async fn set_exec_fee_factor(
		&self,
		fee: u64,
	) -> Result<TransactionBuilder<'_, P>, ContractError> {
		self.invoke_function("setExecFeeFactor", vec![fee.into()]).await
	}

	/// Sets the storage price.
	///
	/// This method requires committee approval.
	/// Value must be between 1 and MAX_STORAGE_PRICE (10,000,000).
	pub async fn set_storage_price(
		&self,
		price: u32,
	) -> Result<TransactionBuilder<'_, P>, ContractError> {
		self.invoke_function("setStoragePrice", vec![price.into()]).await
	}

	// ========== Whitelist Fee Contracts (HF_Faun) ==========

	/// Gets whitelisted fee contracts as an iterator.
	///
	/// Available after HF_Faun.
	pub async fn get_whitelist_fee_contracts(
		&self,
	) -> Result<NeoIterator<'_, WhitelistedContract, P>, ContractError> {
		self.call_function_returning_iterator(
			"getWhitelistFeeContracts",
			vec![],
			Arc::new(|item: StackItem| {
				WhitelistedContract::from_stack_item(&item).map_err(|err| {
					ContractError::UnexpectedReturnType(format!("WhitelistedContract: {err}"))
				})
			}),
		)
		.await
	}

	/// Gets all whitelisted fee contracts by fully unwrapping the iterator.
	///
	/// Available after HF_Faun.
	pub async fn get_whitelist_fee_contracts_all(
		&self,
	) -> Result<Vec<WhitelistedContract>, ContractError> {
		self.get_whitelist_fee_contracts_all_with_batch(
			<Self as SmartContractTrait>::DEFAULT_ITERATOR_COUNT,
		)
		.await
	}

	/// Gets all whitelisted fee contracts using a custom batch size.
	///
	/// Available after HF_Faun.
	pub async fn get_whitelist_fee_contracts_all_with_batch(
		&self,
		batch_size: usize,
	) -> Result<Vec<WhitelistedContract>, ContractError> {
		let iterator = self.get_whitelist_fee_contracts().await?;
		self.collect_all(iterator, batch_size).await
	}

	async fn collect_all<T>(
		&self,
		iterator: NeoIterator<'_, T, P>,
		batch_size: usize,
	) -> Result<Vec<T>, ContractError> {
		if batch_size == 0 {
			return Err(ContractError::InvalidArgError(
				"Batch size must be greater than zero".to_string(),
			));
		}

		let mut all_items = Vec::new();
		let mut traverse_error: Option<ContractError> = None;

		loop {
			match iterator.traverse(batch_size as i32).await {
				Ok(batch) => {
					if batch.is_empty() {
						break;
					}
					all_items.extend(batch);
				},
				Err(err) => {
					traverse_error = Some(err);
					break;
				},
			}
		}

		if let Some(err) = traverse_error {
			let _ = iterator.terminate_session().await;
			return Err(err);
		}

		iterator.terminate_session().await?;
		Ok(all_items)
	}

	/// Sets a whitelisted contract method for fee exemption.
	///
	/// When a contract method is whitelisted, invocations use the specified fixed fee
	/// instead of the calculated execution fee.
	///
	/// This method requires committee approval.
	/// Available after HF_Faun.
	///
	/// # Arguments
	///
	/// * `contract_hash` - The contract to whitelist.
	/// * `method` - The method name.
	/// * `arg_count` - The number of arguments the method takes.
	/// * `fixed_fee` - The fixed execution fee for this method.
	pub async fn set_whitelist_fee_contract(
		&self,
		contract_hash: &H160,
		method: &str,
		arg_count: i32,
		fixed_fee: i64,
	) -> Result<TransactionBuilder<'_, P>, ContractError> {
		self.invoke_function(
			"setWhitelistFeeContract",
			vec![contract_hash.into(), method.into(), arg_count.into(), fixed_fee.into()],
		)
		.await
	}

	/// Removes a whitelisted contract method.
	///
	/// This method requires committee approval.
	/// Available after HF_Faun.
	///
	/// # Arguments
	///
	/// * `contract_hash` - The contract to remove from whitelist.
	/// * `method` - The method name.
	/// * `arg_count` - The number of arguments the method takes.
	pub async fn remove_whitelist_fee_contract(
		&self,
		contract_hash: &H160,
		method: &str,
		arg_count: i32,
	) -> Result<TransactionBuilder<'_, P>, ContractError> {
		self.invoke_function(
			"removeWhitelistFeeContract",
			vec![contract_hash.into(), method.into(), arg_count.into()],
		)
		.await
	}

	// ========== Fund Recovery (HF_Faun) ==========

	/// Recovers funds from a blocked account.
	///
	/// This method requires almost full committee approval and can only be called
	/// after the account has been blocked for at least 1 year.
	///
	/// Available after HF_Faun.
	///
	/// # Arguments
	///
	/// * `account` - The blocked account to recover funds from.
	/// * `token` - The token contract to recover (must implement NEP-17).
	pub async fn recover_fund(
		&self,
		account: &H160,
		token: &H160,
	) -> Result<TransactionBuilder<'_, P>, ContractError> {
		self.invoke_function("recoverFund", vec![account.into(), token.into()]).await
	}
}

#[async_trait]
impl<'a, P: JsonRpcProvider> SmartContractTrait<'a> for PolicyContract<'a, P> {
	type P = P;

	fn script_hash(&self) -> H160 {
		self.script_hash
	}

	fn set_script_hash(&mut self, script_hash: H160) {
		self.script_hash = script_hash;
	}

	fn provider(&self) -> Option<&RpcClient<P>> {
		self.provider
	}
}

#[cfg(test)]
mod tests {
	use super::*;
	use crate::{
		neo_clients::{MockProvider, RpcClient},
		neo_types::{InvocationResult, NeoVMStateType, StackItem},
	};
	use serde_json::json;

	fn iterator_invocation_result(session_id: &str, iterator_id: &str) -> InvocationResult {
		InvocationResult::new(
			String::new(),
			NeoVMStateType::Halt,
			"0".to_string(),
			None,
			None,
			None,
			vec![StackItem::InteropInterface {
				id: iterator_id.to_string(),
				interface: "IIterator".to_string(),
			}],
			None,
			None,
			Some(session_id.to_string()),
		)
	}

	#[test]
	fn test_policy_contract_constants() {
		assert_eq!(PolicyContract::<MockProvider>::DEFAULT_EXEC_FEE_FACTOR, 30);
		assert_eq!(PolicyContract::<MockProvider>::DEFAULT_STORAGE_PRICE, 100000);
		assert_eq!(PolicyContract::<MockProvider>::DEFAULT_FEE_PER_BYTE, 1000);
		assert_eq!(PolicyContract::<MockProvider>::MAX_MILLISECONDS_PER_BLOCK, 30_000);
		assert_eq!(PolicyContract::<MockProvider>::MAX_MAX_VALID_UNTIL_BLOCK_INCREMENT, 86400);
		assert_eq!(PolicyContract::<MockProvider>::MAX_MAX_TRACEABLE_BLOCKS, 2_102_400);
	}

	#[test]
	fn test_policy_contract_name() {
		assert_eq!(PolicyContract::<MockProvider>::NAME, "PolicyContract");
	}

	#[tokio::test]
	async fn test_get_blocked_accounts_iterator_rejects_invalid_items() {
		let provider = MockProvider::new();
		let client = RpcClient::new(provider.clone());
		let contract = PolicyContract::new(Some(&client));
		let hash = contract.script_hash();

		provider.push_result_with_params(
			"invokefunction",
			json!([hash.to_hex(), "getBlockedAccounts", [], []]),
			serde_json::to_value(iterator_invocation_result("session-1", "iter-1")).unwrap(),
		);
		provider.push_result_with_params(
			"traverseiterator",
			json!(["session-1", "iter-1", 1]),
			serde_json::to_value(vec![StackItem::Integer { value: 7 }]).unwrap(),
		);

		let iterator = contract.get_blocked_accounts().await.unwrap();
		let result = iterator.traverse(1).await;
		assert!(matches!(
			result,
			Err(ContractError::UnexpectedReturnType(message))
				if message.contains("Hash160")
		));
	}

	#[tokio::test]
	async fn test_get_whitelist_fee_contracts_iterator_rejects_invalid_items() {
		let provider = MockProvider::new();
		let client = RpcClient::new(provider.clone());
		let contract = PolicyContract::new(Some(&client));
		let hash = contract.script_hash();

		provider.push_result_with_params(
			"invokefunction",
			json!([hash.to_hex(), "getWhitelistFeeContracts", [], []]),
			serde_json::to_value(iterator_invocation_result("session-2", "iter-2")).unwrap(),
		);
		provider.push_result_with_params(
			"traverseiterator",
			json!(["session-2", "iter-2", 1]),
			serde_json::to_value(vec![StackItem::Integer { value: 11 }]).unwrap(),
		);

		let iterator = contract.get_whitelist_fee_contracts().await.unwrap();
		let result = iterator.traverse(1).await;
		assert!(matches!(
			result,
			Err(ContractError::UnexpectedReturnType(message))
				if message.contains("WhitelistedContract")
		));
	}
}