neo3 1.0.7

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
use std::sync::Arc;

use crate::neo_crypto::utils::ToHexString;
use async_trait::async_trait;
use num_bigint::BigInt;
use primitive_types::H160;

// Replace prelude imports with specific types
use crate::{
	neo_builder::{CallFlags, ScriptBuilder},
	neo_clients::{APITrait, JsonRpcProvider, RpcClient},
	neo_contract::{ContractError, NeoIterator},
	neo_types::{
		Bytes, ContractManifest, ContractParameter, InvocationResult, OpCode, ScriptHash, StackItem,
	},
	ScriptHashExtension,
};

// Import transaction types from the correct modules
use crate::neo_builder::{Signer, TransactionBuilder};

#[async_trait]
pub trait SmartContractTrait<'a>: Send + Sync {
	const DEFAULT_ITERATOR_COUNT: usize = 100;
	type P: JsonRpcProvider;

	async fn try_name(&self) -> Result<String, ContractError> {
		self.try_get_manifest()
			.await?
			.name
			.ok_or_else(|| ContractError::InvalidResponse("Contract manifest is missing name".to_string()))
	}

	async fn name(&self) -> String {
		self.try_name().await.unwrap_or_else(|err| {
			let fallback = self.script_hash().to_hex();
			tracing::warn!(
				error = %err,
				fallback = %fallback,
				"Failed to resolve contract name; returning contract hash"
			);
			fallback
		})
	}
	fn set_name(&mut self, _name: String) {
		// NNS contracts don't support setting names
		// This is intentionally a no-op as it's not supported
		tracing::warn!("Cannot set name for NNS contract - operation not supported");
	}

	fn script_hash(&self) -> H160;

	fn set_script_hash(&mut self, _script_hash: H160) {
		// NNS contracts don't support setting script hash
		// This is intentionally a no-op as it's not supported
		tracing::warn!("Cannot set script hash for NNS contract - operation not supported");
	}

	fn provider(&self) -> Option<&RpcClient<Self::P>>;

	async fn invoke_function(
		&self,
		function: &str,
		params: Vec<ContractParameter>,
	) -> Result<TransactionBuilder<Self::P>, ContractError> {
		let script = self.build_invoke_function_script(function, params).await?;
		let mut builder = TransactionBuilder::new();
		builder.set_script(Some(script));
		Ok(builder)
	}

	async fn build_invoke_function_script(
		&self,
		function: &str,
		params: Vec<ContractParameter>,
	) -> Result<Bytes, ContractError> {
		if function.is_empty() {
			return Err(ContractError::InvalidNeoName("Function name cannot be empty".to_string()));
		}

		let script = ScriptBuilder::new()
			.contract_call(&self.script_hash(), function, params.as_slice(), Some(CallFlags::None))
			.map_err(|e| {
				ContractError::RuntimeError(format!("Failed to build contract call: {e}"))
			})?
			.to_bytes();

		Ok(script)
	}

	async fn call_function_returning_string(
		&self,
		function: &str,
		params: Vec<ContractParameter>,
	) -> Result<String, ContractError> {
		let output = self.call_invoke_function(function, params, vec![]).await?;
		self.throw_if_fault_state(&output)?;

		let item = output
			.get_first_stack_item()
			.map_err(|e| ContractError::InvalidResponse(e.to_string()))?;
		match item.as_string() {
			Some(s) => Ok(s),
			None => Err(ContractError::UnexpectedReturnType("String".to_string())),
		}
	}

	async fn call_function_returning_int(
		&self,
		function: &str,
		params: Vec<ContractParameter>,
	) -> Result<i64, ContractError> {
		let output = self.call_invoke_function(function, params, vec![]).await?;
		self.throw_if_fault_state(&output)?;

		let item = output
			.get_first_stack_item()
			.map_err(|e| ContractError::InvalidResponse(e.to_string()))?;
		match item.as_int() {
			Some(i) => Ok(i),
			None => Err(ContractError::UnexpectedReturnType("Int".to_string())),
		}
	}

	async fn call_function_returning_bool(
		&self,
		function: &str,
		params: Vec<ContractParameter>,
	) -> Result<bool, ContractError> {
		let output = self.call_invoke_function(function, params, vec![]).await?;
		self.throw_if_fault_state(&output)?;

		let item = output
			.get_first_stack_item()
			.map_err(|e| ContractError::InvalidResponse(e.to_string()))?;
		match item.as_bool() {
			Some(b) => Ok(b),
			None => Err(ContractError::UnexpectedReturnType("Bool".to_string())),
		}
	}

	// Other methods

	async fn call_invoke_function(
		&self,
		function: &str,
		params: Vec<ContractParameter>,
		signers: Vec<Signer>,
	) -> Result<InvocationResult, ContractError> {
		if function.is_empty() {
			return Err(ContractError::InvalidNeoName("Function cannot be empty".to_string()));
		}

		let provider = self.provider().ok_or_else(|| {
			ContractError::ProviderNotSet(
				"Provider is required for contract invocations".to_string(),
			)
		})?;

		provider
			.invoke_function(&self.script_hash(), function.into(), params, Some(signers))
			.await
			.map_err(ContractError::from)
	}

	fn throw_if_fault_state(&self, output: &InvocationResult) -> Result<(), ContractError> {
		if output.has_state_fault() {
			let message =
				output.exception.clone().unwrap_or_else(|| "Invocation faulted".to_string());
			Err(ContractError::InvocationFailed(message))
		} else {
			Ok(())
		}
	}

	// Other methods for different return types
	async fn call_function_returning_script_hash(
		&self,
		function: &str,
		params: Vec<ContractParameter>,
	) -> Result<H160, ContractError> {
		let output = self.call_invoke_function(function, params, vec![]).await?;
		self.throw_if_fault_state(&output)?;

		let item = output
			.get_first_stack_item()
			.map_err(|e| ContractError::InvalidResponse(e.to_string()))?;

		let bytes = item
			.as_bytes()
			.ok_or_else(|| ContractError::UnexpectedReturnType("ByteString".to_string()))?;

		if bytes.len() != 20 {
			return Err(ContractError::InvalidResponse(format!(
				"Expected 20 bytes for ScriptHash, got {}",
				bytes.len()
			)));
		}

		Ok(H160::from_slice(&bytes))
	}

	async fn call_function_returning_iterator<U>(
		&self,
		function: &str,
		params: Vec<ContractParameter>,
		mapper: Arc<dyn Fn(StackItem) -> Result<U, ContractError> + Send + Sync>,
	) -> Result<NeoIterator<U, Self::P>, ContractError>
	where
		U: Send + Sync, // Adding this bound if necessary
	{
		let output = self.call_invoke_function(function, params, vec![]).await?;
		self.throw_if_fault_state(&output)?;

		let session_id = output.session_id.clone().ok_or_else(|| {
			ContractError::InvalidResponse(
				"No session ID returned from iterator invocation".to_string(),
			)
		})?;

		let item = output
			.get_first_stack_item()
			.map_err(|e| ContractError::InvalidResponse(e.to_string()))?;
		let StackItem::InteropInterface { id, interface: _ } = item else {
			return Err(ContractError::UnexpectedReturnType(format!(
				"Expected InteropInterface, got {:?}",
				item
			)));
		};

		let provider = self.provider().ok_or_else(|| {
			ContractError::ProviderNotSet("Provider is required for iterator traversal".to_string())
		})?;

		Ok(NeoIterator::new(session_id, id.clone(), mapper, Some(provider)))
	}

	async fn call_function_and_unwrap_iterator<U>(
		&self,
		function: &str,
		params: Vec<ContractParameter>,
		_max_items: usize,
		mapper: impl Fn(StackItem) -> Result<U, ContractError> + Send,
	) -> Result<Vec<U>, ContractError> {
		let script = ScriptBuilder::build_contract_call_and_unwrap_iterator(
			&self.script_hash(),
			function,
			&params,
			_max_items as u32, // Use the max_items parameter provided to the function
			Some(CallFlags::All),
		)
		.map_err(|e| {
			ContractError::RuntimeError(format!("Failed to build iterator script: {e}"))
		})?;

		let provider = self.provider().ok_or_else(|| {
			ContractError::ProviderNotSet(
				"Provider is required for contract invocations".to_string(),
			)
		})?;

		let output = provider.invoke_script(script.to_hex_string(), vec![]).await?;

		self.throw_if_fault_state(&output)?;

		let stack_item = output
			.get_first_stack_item()
			.map_err(|e| ContractError::InvalidResponse(e.to_string()))?;

		let array = stack_item
			.as_array()
			.ok_or_else(|| ContractError::UnexpectedReturnType("Array".to_string()))?;

		let items = array.into_iter().map(mapper).collect::<Result<Vec<_>, _>>()?;

		Ok(items)
	}

	fn calc_native_contract_hash(contract_name: &str) -> Result<H160, ContractError> {
		Self::calc_contract_hash(H160::zero(), 0, contract_name)
	}

	/// Calculates a native contract hash, panicking on failure.
	///
	/// This is intended for use with known-good constants like `NeoToken`, `GasToken`, etc.,
	/// where the only failure mode would be an empty name (a programming error).
	fn calc_native_contract_hash_unchecked(contract_name: &str) -> H160 {
		Self::calc_native_contract_hash(contract_name).unwrap_or_else(|e| {
			panic!("BUG: failed to compute native contract hash for '{}': {}", contract_name, e)
		})
	}

	fn calc_contract_hash(
		sender: H160,
		nef_checksum: u32,
		contract_name: &str,
	) -> Result<H160, ContractError> {
		if contract_name.is_empty() {
			return Err(ContractError::InvalidNeoName("Contract name cannot be empty".to_string()));
		}

		let mut script = ScriptBuilder::new();
		script
			.op_code(&[OpCode::Abort])
			.push_data(sender.to_vec())
			.push_integer(BigInt::from(nef_checksum))
			.push_data(contract_name.as_bytes().to_vec());

		Ok(ScriptHash::from_script(&script.to_bytes()))
	}

	async fn try_get_manifest(&self) -> Result<ContractManifest, ContractError> {
		let provider = self.provider().ok_or_else(|| {
			ContractError::ProviderNotSet(
				"Provider is required to fetch contract manifest".to_string(),
			)
		})?;

		let state = provider.get_contract_state(self.script_hash()).await?;
		Ok(state.manifest)
	}

	async fn get_manifest(&self) -> ContractManifest {
		self.try_get_manifest().await.unwrap_or_else(|err| {
			tracing::warn!(error = %err, "Failed to fetch contract manifest; returning default");
			ContractManifest::default()
		})
	}
}

#[cfg(test)]
mod tests {
	use super::*;
	use crate::{
		neo_clients::{MockProvider, RpcClient},
		neo_contract::ContractError,
		neo_types::{ContractManifest, ContractNef, ContractState},
	};
	use async_trait::async_trait;
	use primitive_types::H160;
	use serde_json::json;

	#[derive(Clone)]
	struct TestContract {
		script_hash: H160,
		provider: Option<RpcClient<MockProvider>>,
	}

	impl TestContract {
		fn without_provider(script_hash: H160) -> Self {
			Self { script_hash, provider: None }
		}

		fn with_provider(script_hash: H160, provider: RpcClient<MockProvider>) -> Self {
			Self { script_hash, provider: Some(provider) }
		}
	}

	#[async_trait]
	impl<'a> SmartContractTrait<'a> for TestContract {
		type P = MockProvider;

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

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

	fn test_manifest(name: &str) -> ContractManifest {
		ContractManifest::new(
			Some(name.to_string()),
			vec![],
			None,
			vec![],
			None,
			vec![],
			vec![],
			None,
		)
	}

	fn test_contract_state(hash: H160, manifest: ContractManifest) -> ContractState {
		ContractState::new(1, 0, hash, ContractNef::default(), manifest)
	}

	#[tokio::test]
	async fn test_try_get_manifest_returns_provider_not_set_without_provider() {
		let contract = TestContract::without_provider(H160::repeat_byte(0x11));

		assert!(matches!(
			contract.try_get_manifest().await,
			Err(ContractError::ProviderNotSet(message))
				if message.contains("contract manifest")
		));
	}

	#[tokio::test]
	async fn test_try_get_manifest_returns_manifest_from_provider() {
		let hash = H160::repeat_byte(0x22);
		let manifest = test_manifest("TestContract");
		let provider = MockProvider::new();
		provider.push_result_with_params(
			"getcontractstate",
			json!([hash.to_hex()]),
			serde_json::to_value(test_contract_state(hash, manifest.clone())).unwrap(),
		);
		let contract = TestContract::with_provider(hash, RpcClient::new(provider));

		let fetched = contract.try_get_manifest().await.unwrap();
		assert_eq!(fetched.name.as_deref(), Some("TestContract"));
	}

	#[tokio::test]
	async fn test_try_name_returns_manifest_name() {
		let hash = H160::repeat_byte(0x33);
		let manifest = test_manifest("FriendlyName");
		let provider = MockProvider::new();
		provider.push_result_with_params(
			"getcontractstate",
			json!([hash.to_hex()]),
			serde_json::to_value(test_contract_state(hash, manifest)).unwrap(),
		);
		let contract = TestContract::with_provider(hash, RpcClient::new(provider));

		assert_eq!(contract.try_name().await.unwrap(), "FriendlyName");
	}

	#[tokio::test]
	async fn test_try_name_rejects_missing_manifest_name() {
		let hash = H160::repeat_byte(0x34);
		let manifest = test_manifest("");
		let provider = MockProvider::new();
		provider.push_result_with_params(
			"getcontractstate",
			json!([hash.to_hex()]),
			serde_json::to_value(test_contract_state(hash, ContractManifest { name: None, ..manifest }))
				.unwrap(),
		);
		let contract = TestContract::with_provider(hash, RpcClient::new(provider));

		assert!(matches!(
			contract.try_name().await,
			Err(ContractError::InvalidResponse(message))
				if message.contains("missing name")
		));
	}

	#[tokio::test]
	async fn test_name_returns_contract_hash_when_manifest_name_missing() {
		let hash = H160::repeat_byte(0x35);
		let provider = MockProvider::new();
		provider.push_result_with_params(
			"getcontractstate",
			json!([hash.to_hex()]),
			serde_json::to_value(test_contract_state(hash, ContractManifest::default())).unwrap(),
		);
		let contract = TestContract::with_provider(hash, RpcClient::new(provider));

		assert_eq!(contract.name().await, hash.to_hex());
	}

	#[tokio::test]
	async fn test_get_manifest_returns_default_without_provider() {
		let contract = TestContract::without_provider(H160::repeat_byte(0x44));
		assert_eq!(contract.get_manifest().await.name, None);
	}

	#[tokio::test]
	async fn test_name_returns_contract_hash_without_provider() {
		let hash = H160::repeat_byte(0x55);
		let contract = TestContract::without_provider(hash);
		assert_eq!(contract.name().await, hash.to_hex());
	}
}