avail-rust-core 0.5.1

Avail Rust SDK core library
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
use crate::{rpc, rpc::Error, types::H256};
use codec::{Decode, Encode};
use std::marker::PhantomData;
use subxt_rpcs::RpcClient;

#[derive(Debug, Clone, Copy)]
pub enum StorageHasher {
	/// 128-bit Blake2 hash.
	Blake2_128,
	/// 256-bit Blake2 hash.
	Blake2_256,
	/// Multiple 128-bit Blake2 hashes concatenated.
	Blake2_128Concat,
	/// 128-bit XX hash.
	Twox128,
	/// 256-bit XX hash.
	Twox256,
	/// Multiple 64-bit XX hashes concatenated.
	Twox64Concat,
	/// Identity hashing (no hashing).
	Identity,
}

impl StorageHasher {
	pub fn hash(&self, data: &[u8]) -> Vec<u8> {
		match self {
			StorageHasher::Blake2_128 => sp_crypto_hashing::blake2_128(data).into(),
			StorageHasher::Blake2_256 => sp_crypto_hashing::blake2_256(data).into(),
			StorageHasher::Blake2_128Concat => {
				let mut hash = sp_crypto_hashing::blake2_128(data).to_vec();
				hash.extend_from_slice(data);
				hash
			},
			StorageHasher::Twox128 => sp_crypto_hashing::twox_128(data).into(),
			StorageHasher::Twox256 => sp_crypto_hashing::twox_256(data).into(),
			StorageHasher::Twox64Concat => {
				let mut hash = sp_crypto_hashing::twox_64(data).to_vec();
				hash.extend_from_slice(data);
				hash
			},
			StorageHasher::Identity => data.to_vec(),
		}
	}

	pub fn from_hash<Key: codec::Decode>(&self, data: &mut &[u8]) -> Result<Key, codec::Error> {
		match self {
			StorageHasher::Blake2_128Concat => {
				if data.len() < 17 {
					return Err(codec::Error::from("Not enough data to compute Blake2_128Concat"));
				}
				Key::decode(&mut &data[16..])
			},
			StorageHasher::Twox64Concat => {
				if data.len() < 9 {
					return Err(codec::Error::from("Not enough data to compute Twox64Concat"));
				}
				Key::decode(&mut &data[8..])
			},
			StorageHasher::Identity => Key::decode(data),
			_ => unimplemented!(),
		}
	}
}

pub trait StorageValue {
	const PALLET_NAME: &str;
	const STORAGE_NAME: &str;
	type VALUE: codec::Decode;

	fn encode_storage_key() -> [u8; 32] {
		use sp_crypto_hashing::twox_128;

		let mut encoded_storage_key = [0u8; 32];
		encoded_storage_key[0..16].copy_from_slice(&twox_128(Self::PALLET_NAME.as_bytes()));
		encoded_storage_key[16..].copy_from_slice(&twox_128(Self::STORAGE_NAME.as_bytes()));

		encoded_storage_key
	}

	fn hex_encode_storage_key() -> String {
		std::format!("0x{}", const_hex::encode(Self::encode_storage_key()))
	}

	/// Decodes the Hex and SCALE encoded Storage Value
	/// This is equal to Hex::decode + Self::decode
	///
	/// If you need to decode bytes call `decode`
	fn decode_hex_storage_value(value: &str) -> Result<Self::VALUE, codec::Error> {
		let Ok(hex_decoded) = const_hex::decode(value.trim_start_matches("0x")) else {
			return Err("Failed to hex decode storage".into());
		};
		Self::decode_storage_value(&mut hex_decoded.as_slice())
	}

	/// Decodes the SCALE encoded Storage Value
	///
	/// If you need to decode Hex string call `hex_decode`
	fn decode_storage_value(value: &mut &[u8]) -> Result<Self::VALUE, codec::Error> {
		Self::VALUE::decode(value)
	}

	/// Fetches and decodes a Storage Value
	///
	/// Returns None if no Storage Value is present
	fn fetch(
		client: &RpcClient,
		at: Option<H256>,
	) -> impl std::future::Future<Output = Result<Option<Self::VALUE>, Error>> {
		async move {
			let storage_key = const_hex::encode(Self::encode_storage_key());

			let storage_value = rpc::state::get_storage(client, &storage_key, at).await?;
			let Some(storage_value) = storage_value else {
				return Ok(None);
			};

			let storage_value = Self::decode_storage_value(&mut storage_value.as_slice())
				.map_err(|x| Error::DecodingFailed(x.to_string()))?;
			Ok(Some(storage_value))
		}
	}
}

pub trait StorageMap {
	const PALLET_NAME: &str;
	const STORAGE_NAME: &str;
	const KEY_HASHER: StorageHasher;
	type KEY: codec::Decode + codec::Encode;
	type VALUE: codec::Decode;

	fn encode_partial_key() -> [u8; 32] {
		use sp_crypto_hashing::twox_128;

		let mut encoded_storage_key = [0u8; 32];
		encoded_storage_key[0..16].copy_from_slice(&twox_128(Self::PALLET_NAME.as_bytes()));
		encoded_storage_key[16..].copy_from_slice(&twox_128(Self::STORAGE_NAME.as_bytes()));

		encoded_storage_key
	}

	fn hex_encode_partial_key() -> String {
		std::format!("0x{}", const_hex::encode(Self::encode_partial_key()))
	}

	fn encode_storage_key(key: &Self::KEY) -> Vec<u8> {
		let mut storage_key: Vec<u8> = Vec::new();
		storage_key.extend_from_slice(&Self::encode_partial_key());

		let encoded_key = key.encode();
		storage_key.extend_from_slice(&Self::KEY_HASHER.hash(&encoded_key));

		storage_key
	}

	fn hex_encode_storage_key(key: &Self::KEY) -> String {
		std::format!("0x{}", const_hex::encode(Self::encode_storage_key(key)))
	}

	/// Decodes the Hex and SCALE encoded Storage Key
	/// This is equal to Hex::decode + Self::decode_storage_key
	///
	/// If you need to decode bytes call `decode_storage_key`
	#[inline(always)]
	fn decode_hex_storage_key(value: &str) -> Result<Self::KEY, codec::Error> {
		let Ok(hex_decoded) = const_hex::decode(value.trim_start_matches("0x")) else {
			return Err("Failed to hex decode storage key".into());
		};
		Self::decode_storage_key(&mut hex_decoded.as_slice())
	}

	/// Decodes the SCALE encoded Storage Key
	///
	/// If you need to decode Hex string call `decode_hex_storage_key`
	fn decode_storage_key(value: &mut &[u8]) -> Result<Self::KEY, codec::Error> {
		if value.len() < 32 {
			return Err("Storage Key is malformed. Has less than 32 bytes".into());
		}

		// Skip pallet/variant
		*value = &value[32..];

		Self::KEY_HASHER.from_hash::<Self::KEY>(value)
	}

	/// Decodes the Hex and SCALE encoded Storage Value
	/// This is equal to Hex::decode + Self::decode_storage_value
	///
	/// If you need to decode bytes call `decode_storage_value`
	#[inline(always)]
	fn decode_hex_storage_value(value: &str) -> Result<Self::VALUE, codec::Error> {
		let Ok(hex_decoded) = const_hex::decode(value.trim_start_matches("0x")) else {
			return Err("Failed to hex decode storage value".into());
		};
		Self::decode_storage_value(&mut hex_decoded.as_slice())
	}

	/// Decodes the SCALE encoded Storage Value
	///
	/// If you need to decode Hex string call `decode_hex_storage_value`
	fn decode_storage_value(value: &mut &[u8]) -> Result<Self::VALUE, codec::Error> {
		Self::VALUE::decode(value)
	}

	/// Fetches and decodes a Storage Value
	///
	/// Returns None if no Storage Value is present
	fn fetch(
		client: &RpcClient,
		key: &Self::KEY,
		at: Option<H256>,
	) -> impl std::future::Future<Output = Result<Option<Self::VALUE>, Error>> {
		async move {
			let storage_key = const_hex::encode(Self::encode_storage_key(key));
			let storage_value = rpc::state::get_storage(client, &storage_key, at).await?;
			let Some(storage_value) = storage_value else {
				return Ok(None);
			};

			let storage_value = Self::decode_storage_value(&mut storage_value.as_slice())
				.map_err(|x| Error::DecodingFailed(x.to_string()))?;
			Ok(Some(storage_value))
		}
	}

	fn iter(client: RpcClient, block_hash: H256) -> StorageMapIterator<Self>
	where
		Self: Sized,
	{
		StorageMapIterator::new(client, block_hash)
	}
}

pub trait StorageDoubleMap {
	const PALLET_NAME: &str;
	const STORAGE_NAME: &str;
	const KEY1_HASHER: StorageHasher;
	const KEY2_HASHER: StorageHasher;
	type KEY1: codec::Decode + codec::Encode;
	type KEY2: codec::Decode + codec::Encode;
	type VALUE: codec::Decode;

	fn encode_partial_key(key1: &Self::KEY1) -> Vec<u8> {
		use sp_crypto_hashing::twox_128;

		let mut encoded_storage_key = Vec::new();
		encoded_storage_key.extend_from_slice(&twox_128(Self::PALLET_NAME.as_bytes()));
		encoded_storage_key.extend_from_slice(&twox_128(Self::STORAGE_NAME.as_bytes()));
		encoded_storage_key.extend_from_slice(&Self::KEY1_HASHER.hash(&key1.encode()));

		encoded_storage_key
	}

	fn hex_encode_partial_key(key1: &Self::KEY1) -> String {
		std::format!("0x{}", const_hex::encode(Self::encode_partial_key(key1)))
	}

	fn encode_storage_key(key1: &Self::KEY1, key2: &Self::KEY2) -> Vec<u8> {
		let mut storage_key: Vec<u8> = Vec::new();
		storage_key.extend_from_slice(&Self::encode_partial_key(key1));
		storage_key.extend_from_slice(&Self::KEY2_HASHER.hash(&key2.encode()));

		storage_key
	}

	fn hex_encode_storage_key(key1: &Self::KEY1, key2: &Self::KEY2) -> String {
		std::format!("0x{}", const_hex::encode(Self::encode_storage_key(key1, key2)))
	}

	fn decode_partial_key(value: &mut &[u8]) -> Result<Self::KEY1, codec::Error> {
		if value.len() < 32 {
			return Err("Storage Key is malformed. Has less than 32 bytes".into());
		}

		// Skip pallet/variant
		*value = &value[32..];

		Self::KEY1_HASHER.from_hash::<Self::KEY1>(value)
	}

	/// Decodes the Hex and SCALE encoded Storage Key
	/// This is equal to Hex::decode + Self::decode_storage_key
	///
	/// If you need to decode bytes call `decode_storage_key`
	fn decode_hex_storage_key(value: &str) -> Result<(Self::KEY1, Self::KEY2), codec::Error> {
		let Ok(hex_decoded) = const_hex::decode(value.trim_start_matches("0x")) else {
			return Err("Failed to hex decode storage key".into());
		};
		Self::decode_storage_key(&mut hex_decoded.as_slice())
	}

	/// Decodes the SCALE encoded Storage Key
	///
	/// If you need to decode Hex string call `decode_hex_storage_key`
	fn decode_storage_key(value: &mut &[u8]) -> Result<(Self::KEY1, Self::KEY2), codec::Error> {
		if value.len() < 32 {
			return Err("Storage Key is malformed. Has less than 32 bytes".into());
		}

		// Skip pallet/variant
		*value = &value[32..];

		let key1 = Self::KEY1_HASHER.from_hash::<Self::KEY1>(value)?;
		let key2 = Self::KEY2_HASHER.from_hash::<Self::KEY2>(value)?;
		Ok((key1, key2))
	}

	/// Decodes the Hex and SCALE encoded Storage Value
	/// This is equal to Hex::decode + Self::decode_storage_value
	///
	/// If you need to decode bytes call `decode_storage_value`
	fn decode_hex_storage_value(value: &str) -> Result<Self::VALUE, codec::Error> {
		let Ok(hex_decoded) = const_hex::decode(value.trim_start_matches("0x")) else {
			return Err("Failed to hex decode storage value".into());
		};
		Self::decode_storage_value(&mut hex_decoded.as_slice())
	}

	/// Decodes the SCALE encoded Storage Value
	///
	/// If you need to decode Hex string call `decode_hex_storage_value`
	fn decode_storage_value(value: &mut &[u8]) -> Result<Self::VALUE, codec::Error> {
		Self::VALUE::decode(value)
	}

	/// Fetches and decodes a Storage Value
	///
	/// Returns None if no Storage Value is present
	fn fetch(
		client: &RpcClient,
		key_1: &Self::KEY1,
		key_2: &Self::KEY2,
		at: Option<H256>,
	) -> impl std::future::Future<Output = Result<Option<Self::VALUE>, Error>> {
		async move {
			let storage_key = const_hex::encode(Self::encode_storage_key(key_1, key_2));
			let storage_value = rpc::state::get_storage(client, &storage_key, at).await?;
			let Some(storage_value) = storage_value else {
				return Ok(None);
			};

			let storage_value = Self::decode_storage_value(&mut storage_value.as_slice())
				.map_err(|x| Error::DecodingFailed(x.to_string()))?;
			Ok(Some(storage_value))
		}
	}

	fn iter(client: RpcClient, key_1: &Self::KEY1, block_hash: H256) -> StorageDoubleMapIterator<Self>
	where
		Self: Sized,
	{
		StorageDoubleMapIterator::new(client, key_1, block_hash)
	}
}

#[derive(Clone)]
pub struct StorageMapIterator<T: StorageMap> {
	client: RpcClient,
	phantom: PhantomData<T>,
	block_hash: H256,
	fetched_keys: Vec<String>,
	last_key: Option<String>,
	is_done: bool,
	prefix: String,
}

impl<T: StorageMap> StorageMapIterator<T> {
	pub fn new(client: RpcClient, block_hash: H256) -> Self {
		Self {
			client,
			phantom: PhantomData::<T>,
			block_hash,
			fetched_keys: Vec::new(),
			last_key: None,
			is_done: false,
			prefix: const_hex::encode(T::encode_partial_key()),
		}
	}

	pub async fn next_key_value(&mut self) -> Result<Option<(T::KEY, T::VALUE)>, Error> {
		if self.is_done {
			return Ok(None);
		}

		// Fetch new keys
		if self.fetched_keys.is_empty() {
			self.fetch_new_keys().await?;
		}

		let Some(storage_key) = self.fetched_keys.last() else {
			return Ok(None);
		};

		let Some(storage_value) = self.fetch_storage_value(storage_key).await? else {
			return Ok(None);
		};

		let key = const_hex::decode(storage_key.trim_start_matches("0x"))
			.map_err(|x| Error::DecodingFailed(x.to_string()))?;
		let key = T::decode_storage_key(&mut key.as_slice()).map_err(|x| Error::DecodingFailed(x.to_string()))?;

		self.last_key = Some(storage_key.clone());
		self.fetched_keys.pop();

		Ok(Some((key, storage_value)))
	}

	pub async fn next(&mut self) -> Result<Option<T::VALUE>, Error> {
		if self.is_done {
			return Ok(None);
		}

		// Fetch new keys
		if self.fetched_keys.is_empty() {
			self.fetch_new_keys().await?;
		}

		let Some(storage_key) = self.fetched_keys.last() else {
			return Ok(None);
		};

		let Some(storage_value) = self.fetch_storage_value(storage_key).await? else {
			return Ok(None);
		};

		self.last_key = Some(storage_key.clone());
		self.fetched_keys.pop();

		Ok(Some(storage_value))
	}

	async fn fetch_new_keys(&mut self) -> Result<(), Error> {
		self.fetched_keys = rpc::state::get_keys_paged(
			&self.client,
			Some(&self.prefix),
			100,
			self.last_key.as_ref().map(|x| x.as_str()),
			Some(self.block_hash),
		)
		.await?;

		self.fetched_keys.reverse();
		if self.fetched_keys.is_empty() {
			self.is_done = true
		}

		Ok(())
	}

	async fn fetch_storage_value(&self, key: &str) -> Result<Option<T::VALUE>, Error> {
		let storage_value = rpc::state::get_storage(&self.client, key, Some(self.block_hash)).await?;
		let Some(storage_value) = storage_value else {
			return Ok(None);
		};

		let storage_value =
			T::decode_storage_value(&mut storage_value.as_slice()).map_err(|x| Error::DecodingFailed(x.to_string()))?;

		Ok(Some(storage_value))
	}
}

#[derive(Clone)]
pub struct StorageDoubleMapIterator<T: StorageDoubleMap> {
	client: RpcClient,
	phantom: PhantomData<T>,
	block_hash: H256,
	fetched_keys: Vec<String>,
	last_key: Option<String>,
	is_done: bool,
	prefix: String,
}

impl<T: StorageDoubleMap> StorageDoubleMapIterator<T> {
	pub fn new(client: RpcClient, key_1: &T::KEY1, block_hash: H256) -> Self {
		Self {
			client,
			phantom: PhantomData::<T>,
			block_hash,
			fetched_keys: Vec::new(),
			last_key: None,
			is_done: false,

			prefix: const_hex::encode(T::encode_partial_key(key_1)),
		}
	}

	pub async fn next_key_value(&mut self) -> Result<Option<(T::KEY1, T::KEY2, T::VALUE)>, Error> {
		if self.is_done {
			return Ok(None);
		}

		// Fetch new keys
		if self.fetched_keys.is_empty() {
			self.fetch_new_keys().await?;
		}

		let Some(storage_key) = self.fetched_keys.last() else {
			return Ok(None);
		};

		let Some(storage_value) = self.fetch_storage_value(storage_key).await? else {
			return Ok(None);
		};

		let key = const_hex::decode(storage_key.trim_start_matches("0x"))
			.map_err(|x| x.to_string())
			.map_err(|x| Error::DecodingFailed(x.to_string()))?;
		let (key1, key2) =
			T::decode_storage_key(&mut key.as_slice()).map_err(|x| Error::DecodingFailed(x.to_string()))?;

		self.last_key = Some(storage_key.clone());
		self.fetched_keys.pop();

		Ok(Some((key1, key2, storage_value)))
	}

	pub async fn next(&mut self) -> Result<Option<(T::KEY2, T::VALUE)>, Error> {
		if self.is_done {
			return Ok(None);
		}

		// Fetch new keys
		if self.fetched_keys.is_empty() {
			self.fetch_new_keys().await?;
		}

		let Some(storage_key) = self.fetched_keys.last() else {
			return Ok(None);
		};

		let Some(storage_value) = self.fetch_storage_value(storage_key).await? else {
			return Ok(None);
		};

		let key = const_hex::decode(storage_key.trim_start_matches("0x"))
			.map_err(|x| x.to_string())
			.map_err(|x| Error::DecodingFailed(x.to_string()))?;
		let (_, key2) = T::decode_storage_key(&mut key.as_slice()).map_err(|x| Error::DecodingFailed(x.to_string()))?;

		self.last_key = Some(storage_key.clone());
		self.fetched_keys.pop();

		Ok(Some((key2, storage_value)))
	}

	async fn fetch_new_keys(&mut self) -> Result<(), Error> {
		self.fetched_keys = rpc::state::get_keys_paged(
			&self.client,
			Some(&self.prefix),
			100,
			self.last_key.as_ref().map(|x| x.as_str()),
			Some(self.block_hash),
		)
		.await?;

		self.fetched_keys.reverse();
		if self.fetched_keys.is_empty() {
			self.is_done = true
		}

		Ok(())
	}

	async fn fetch_storage_value(&self, key: &str) -> Result<Option<T::VALUE>, Error> {
		let storage_value = rpc::state::get_storage(&self.client, key, Some(self.block_hash)).await?;
		let Some(storage_value) = storage_value else {
			return Ok(None);
		};
		let storage_value =
			T::decode_storage_value(&mut storage_value.as_slice()).map_err(|x| Error::DecodingFailed(x.to_string()))?;

		Ok(Some(storage_value))
	}
}