-
Notifications
You must be signed in to change notification settings - Fork 39
Expand file tree
/
Copy pathmod.rs
More file actions
1326 lines (1206 loc) · 38.1 KB
/
mod.rs
File metadata and controls
1326 lines (1206 loc) · 38.1 KB
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
990
991
992
993
994
995
996
997
998
999
1000
// SPDX-License-Identifier: GPL-3.0
use crate::errors::Error;
use params::Param;
use scale_value::{Composite, ValueDef, stringify::custom_parsers};
use std::fmt::{Display, Formatter, Write};
use subxt::{
Metadata, OnlineClient, SubstrateConfig,
dynamic::Value,
ext::futures::TryStreamExt,
metadata::types::{PalletMetadata, StorageEntryType},
utils::to_hex,
};
pub mod action;
pub mod params;
pub type RawValue = Value<u32>;
fn format_single_tuples<T, W: Write>(value: &Value<T>, mut writer: W) -> Option<core::fmt::Result> {
if let ValueDef::Composite(Composite::Unnamed(vals)) = &value.value &&
vals.len() == 1
{
let val = &vals[0];
return match raw_value_to_string(val, "") {
Ok(r) => match writer.write_str(&r) {
Ok(_) => Some(Ok(())),
Err(_) => None,
},
Err(_) => None,
}
}
None
}
// Formats to hexadecimal in lowercase
fn format_hex<T, W: Write>(value: &Value<T>, mut writer: W) -> Option<core::fmt::Result> {
let mut result = String::new();
match scale_value::stringify::custom_formatters::format_hex(value, &mut result) {
Some(res) => match res {
Ok(_) => match writer.write_str(&result.to_lowercase()) {
Ok(_) => Some(Ok(())),
Err(_) => None,
},
Err(_) => None,
},
None => None,
}
}
/// Converts a raw SCALE value to a human-readable string representation.
///
/// This function takes a raw SCALE value and formats it into a string using custom formatters:
/// - Formats byte sequences as hex strings.
/// - Unwraps single-element tuples.
/// - Uses pretty printing for better readability.
///
/// # Arguments
/// * `value` - The raw SCALE value to convert to string.
///
/// # Returns
/// * `Ok(String)` - The formatted string representation of the value.
/// * `Err(_)` - If the value cannot be converted to string.
pub fn raw_value_to_string<T>(value: &Value<T>, indent: &str) -> anyhow::Result<String> {
let mut result = String::new();
scale_value::stringify::to_writer_custom()
.compact()
.pretty()
.add_custom_formatter(|v, w| format_hex(v, w))
.add_custom_formatter(|v, w| format_single_tuples(v, w))
.write(value, &mut result)?;
// Add indentation to each line
let indented = result
.lines()
.map(|line| format!("{indent}{line}"))
.collect::<Vec<_>>()
.join("\n");
Ok(indented)
}
/// Renders storage key-value pairs into a human-readable string format.
///
/// Takes a slice of tuples containing storage keys and their associated values and formats them
/// into a readable string representation. Each key-value pair is rendered on separate lines within
/// square brackets.
///
/// # Arguments
/// * `key_value_pairs` - A slice of tuples where each tuple contains:
/// - A vector of storage keys.
/// - The associated storage value.
///
/// # Returns
/// * `Ok(String)` - A formatted string containing the rendered key-value pairs.
/// * `Err(_)` - If there's an error converting the values to strings.
pub fn render_storage_key_values(
key_value_pairs: &[(Vec<Value>, RawValue)],
) -> anyhow::Result<String> {
let mut result = String::new();
let indent = " ";
for (keys, value) in key_value_pairs {
result.push_str("[\n");
if !keys.is_empty() {
for key in keys {
result.push_str(&raw_value_to_string(key, indent)?);
result.push_str(",\n");
}
}
result.push_str(&raw_value_to_string(value, indent)?);
result.push_str("\n]\n");
}
Ok(result)
}
/// Represents different types of callable items that can be interacted with in the runtime.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum CallItem {
/// A dispatchable function (extrinsic) that can be called.
Function(Function),
/// A constant value defined in the runtime.
Constant(Constant),
/// A storage item that can be queried.
Storage(Storage),
}
impl Default for CallItem {
fn default() -> Self {
Self::Function(Function::default())
}
}
impl Display for CallItem {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
match self {
CallItem::Function(function) => function.fmt(f),
CallItem::Constant(constant) => constant.fmt(f),
CallItem::Storage(storage) => storage.fmt(f),
}
}
}
impl CallItem {
/// Returns a reference to the [`Function`] if this is a function call item.
pub fn as_function(&self) -> Option<&Function> {
match self {
CallItem::Function(f) => Some(f),
_ => None,
}
}
/// Returns a reference to the [`Constant`] if this is a constant call item.
pub fn as_constant(&self) -> Option<&Constant> {
match self {
CallItem::Constant(c) => Some(c),
_ => None,
}
}
/// Returns a reference to the [`Storage`] if this is a storage call item.
pub fn as_storage(&self) -> Option<&Storage> {
match self {
CallItem::Storage(s) => Some(s),
_ => None,
}
}
/// Returns the name of this call item.
pub fn name(&self) -> &str {
match self {
CallItem::Function(function) => &function.name,
CallItem::Constant(constant) => &constant.name,
CallItem::Storage(storage) => &storage.name,
}
}
/// Returns a descriptive hint string indicating the type of this call item.
pub fn hint(&self) -> &str {
match self {
CallItem::Function(_) => "📝 [EXTRINSIC]",
CallItem::Constant(_) => "[CONSTANT]",
CallItem::Storage(_) => "[STORAGE]",
}
}
/// Returns the documentation string associated with this call item.
pub fn docs(&self) -> &str {
match self {
CallItem::Function(function) => &function.docs,
CallItem::Constant(constant) => &constant.docs,
CallItem::Storage(storage) => &storage.docs,
}
}
/// Returns the name of the pallet containing this call item.
pub fn pallet(&self) -> &str {
match self {
CallItem::Function(function) => &function.pallet,
CallItem::Constant(constant) => &constant.pallet,
CallItem::Storage(storage) => &storage.pallet,
}
}
}
/// Represents a pallet in the blockchain, including its dispatchable functions.
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct Pallet {
/// The name of the pallet.
pub name: String,
/// The index of the pallet within the runtime.
pub index: u8,
/// The documentation of the pallet.
pub docs: String,
/// The dispatchable functions of the pallet.
pub functions: Vec<Function>,
/// The constants of the pallet.
pub constants: Vec<Constant>,
/// The storage items of the pallet.
pub state: Vec<Storage>,
}
impl Display for Pallet {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.name)
}
}
impl Pallet {
/// Returns a vector containing all callable items (functions, constants, and storage) defined
/// in this pallet.
///
/// This method collects and returns all available callable items from the pallet:
/// - Dispatchable functions (extrinsics)
/// - Constants
/// - Storage items
///
/// # Returns
/// A `Vec<CallItem>` containing all callable items from this pallet.
pub fn get_all_callables(&self) -> Vec<CallItem> {
let mut callables = Vec::new();
for function in &self.functions {
callables.push(CallItem::Function(function.clone()));
}
for constant in &self.constants {
callables.push(CallItem::Constant(constant.clone()));
}
for storage in &self.state {
callables.push(CallItem::Storage(storage.clone()));
}
callables
}
}
/// Represents a dispatchable function.
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct Function {
/// The pallet containing the dispatchable function.
pub pallet: String,
/// The name of the function.
pub name: String,
/// The index of the function within the pallet.
pub index: u8,
/// The documentation of the function.
pub docs: String,
/// The parameters of the function.
pub params: Vec<Param>,
/// Whether this function is supported (no recursive or unsupported types like `RuntimeCall`).
pub is_supported: bool,
}
impl Display for Function {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.name)
}
}
/// Represents a runtime constant.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Constant {
/// The pallet containing the dispatchable function.
pub pallet: String,
/// The name of the constant.
pub name: String,
/// The documentation of the constant.
pub docs: String,
/// The value of the constant.
pub value: RawValue,
}
impl Display for Constant {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.name)
}
}
/// Represents a storage item.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Storage {
/// The pallet containing the storage item.
pub pallet: String,
/// The name of the storage item.
pub name: String,
/// The documentation of the storage item.
pub docs: String,
/// The type ID for decoding the storage value.
pub type_id: u32,
/// Optional type ID for map-type storage items. Usually a tuple.
pub key_id: Option<u32>,
/// Whether to query all values for a storage item, optionally filtered by provided keys.
pub query_all: bool,
}
impl Display for Storage {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.name)
}
}
impl Storage {
/// Queries all values for a storage item, optionally filtered by provided keys.
///
/// This method allows retrieving multiple values from storage by iterating through all entries
/// that match the provided keys. For map-type storage items, keys can be used to filter
/// the results.
///
/// # Arguments
/// * `client` - The client to interact with the chain.
/// * `keys` - Optional storage keys for map-type storage items to filter results.
pub async fn query_all(
&self,
client: &OnlineClient<SubstrateConfig>,
keys: Vec<Value>,
) -> Result<Vec<(Vec<Value>, RawValue)>, Error> {
let mut elements = Vec::new();
let metadata = client.metadata();
let types = metadata.types();
let storage_address = subxt::dynamic::storage(&self.pallet, &self.name, keys);
let mut stream = client
.storage()
.at_latest()
.await
.map_err(|e| Error::MetadataParsingError(format!("Failed to get storage: {}", e)))?
.iter(storage_address)
.await
.map_err(|e| {
Error::MetadataParsingError(format!("Failed to fetch storage value: {}", e))
})?;
while let Some(storage_data) = stream.try_next().await.map_err(|e| {
Error::MetadataParsingError(format!("Failed to fetch storage value: {}", e))
})? {
let keys = storage_data.keys;
let mut bytes = storage_data.value.encoded();
let decoded_value = scale_value::scale::decode_as_type(&mut bytes, self.type_id, types)
.map_err(|e| {
Error::MetadataParsingError(format!("Failed to decode storage value: {}", e))
})?;
elements.push((keys, decoded_value));
}
Ok(elements)
}
/// Query the storage value from the chain and return it as a formatted string.
///
/// # Arguments
/// * `client` - The client to interact with the chain.
/// * `keys` - Optional storage keys for map-type storage items.
pub async fn query(
&self,
client: &OnlineClient<SubstrateConfig>,
keys: Vec<Value>,
) -> Result<Option<RawValue>, Error> {
let metadata = client.metadata();
let types = metadata.types();
let storage_address = subxt::dynamic::storage(&self.pallet, &self.name, keys);
let storage_data = client
.storage()
.at_latest()
.await
.map_err(|e| Error::MetadataParsingError(format!("Failed to get storage: {}", e)))?
.fetch(&storage_address)
.await
.map_err(|e| {
Error::MetadataParsingError(format!("Failed to fetch storage value: {}", e))
})?;
// Decode the value if it exists
match storage_data {
Some(value) => {
// Try to decode using the type information
let mut bytes = value.encoded();
let decoded_value = scale_value::scale::decode_as_type(
&mut bytes,
self.type_id,
types,
)
.map_err(|e| {
Error::MetadataParsingError(format!("Failed to decode storage value: {}", e))
})?;
Ok(Some(decoded_value))
},
None => Ok(None),
}
}
}
fn extract_chain_state_from_pallet_metadata(
pallet: &PalletMetadata,
) -> anyhow::Result<Vec<Storage>> {
pallet
.storage()
.map(|storage_metadata| {
storage_metadata
.entries()
.iter()
.map(|entry| {
Ok(Storage {
pallet: pallet.name().to_string(),
name: entry.name().to_string(),
docs: entry
.docs()
.iter()
.filter(|l| !l.is_empty())
.cloned()
.collect::<Vec<_>>()
.join("")
.trim()
.to_string(),
type_id: entry.entry_type().value_ty(),
key_id: match entry.entry_type() {
StorageEntryType::Plain(_) => None,
StorageEntryType::Map { key_ty, .. } => Some(*key_ty),
},
query_all: false,
})
})
.collect::<Result<Vec<Storage>, Error>>()
})
.unwrap_or_else(|| Ok(vec![]))
.map_err(|e| anyhow::Error::msg(e.to_string()))
}
fn extract_constants_from_pallet_metadata(
pallet: &PalletMetadata,
metadata: &Metadata,
) -> anyhow::Result<Vec<Constant>> {
let types = metadata.types();
pallet
.constants()
.map(|constant| {
// Decode the SCALE-encoded constant value using its type information
let mut value_bytes = constant.value();
let decoded_value =
scale_value::scale::decode_as_type(&mut value_bytes, constant.ty(), types)
.map_err(|e| {
Error::MetadataParsingError(format!(
"Failed to decode constant {}: {}",
constant.name(),
e
))
})?;
Ok(Constant {
pallet: pallet.name().to_string(),
name: constant.name().to_string(),
docs: constant
.docs()
.iter()
.filter(|l| !l.is_empty())
.cloned()
.collect::<Vec<_>>()
.join("")
.trim()
.to_string(),
value: decoded_value,
})
})
.collect::<Result<Vec<Constant>, Error>>()
.map_err(|e| anyhow::Error::msg(e.to_string()))
}
fn extract_functions_from_pallet_metadata(
pallet: &PalletMetadata,
metadata: &Metadata,
) -> anyhow::Result<Vec<Function>> {
pallet
.call_variants()
.map(|variants| {
variants
.iter()
.map(|variant| {
let mut is_supported = true;
// Parse parameters for the dispatchable function.
let params = {
let mut parsed_params = Vec::new();
for field in &variant.fields {
match params::field_to_param(metadata, field) {
Ok(param) => parsed_params.push(param),
Err(_) => {
// If an error occurs while parsing the values, mark the
// dispatchable function as unsupported rather than
// error.
is_supported = false;
break;
},
}
}
parsed_params
};
Ok(Function {
pallet: pallet.name().to_string(),
name: variant.name.clone(),
index: variant.index,
docs: if is_supported {
// Filter out blank lines and then flatten into a single value.
variant
.docs
.iter()
.filter(|l| !l.is_empty())
.cloned()
.collect::<Vec<_>>()
.join(" ")
.trim()
.to_string()
} else {
// To display the message in the UI
"Function Not Supported".to_string()
},
params,
is_supported,
})
})
.collect::<Result<Vec<Function>, Error>>()
})
.unwrap_or_else(|| Ok(vec![]))
.map_err(|e| anyhow::Error::msg(e.to_string()))
}
/// Parses the chain metadata to extract information about pallets and their dispatchable functions.
///
/// # Arguments
/// * `client`: The client to interact with the chain.
///
/// NOTE: pallets are ordered by their index within the runtime by default.
pub fn parse_chain_metadata(client: &OnlineClient<SubstrateConfig>) -> Result<Vec<Pallet>, Error> {
let metadata: Metadata = client.metadata();
let pallets = metadata
.pallets()
.map(|pallet| {
Ok(Pallet {
name: pallet.name().to_string(),
index: pallet.index(),
docs: pallet.docs().join("").trim().to_string(),
functions: extract_functions_from_pallet_metadata(&pallet, &metadata)?,
constants: extract_constants_from_pallet_metadata(&pallet, &metadata)?,
state: extract_chain_state_from_pallet_metadata(&pallet)?,
})
})
.collect::<Result<Vec<Pallet>, Error>>()?;
Ok(pallets)
}
/// Finds a specific pallet by name and retrieves its details from metadata.
///
/// # Arguments
/// * `pallets`: List of pallets available within the chain's runtime.
/// * `pallet_name`: The name of the pallet to find.
pub fn find_pallet_by_name<'a>(
pallets: &'a [Pallet],
pallet_name: &str,
) -> Result<&'a Pallet, Error> {
if let Some(pallet) = pallets.iter().find(|p| p.name == pallet_name) {
Ok(pallet)
} else {
Err(Error::PalletNotFound(pallet_name.to_string()))
}
}
/// Finds a specific dispatchable function by name and retrieves its details from metadata.
///
/// # Arguments
/// * `pallets`: List of pallets available within the chain's runtime.
/// * `pallet_name`: The name of the pallet.
/// * `function_name`: Name of the dispatchable function to locate.
pub fn find_callable_by_name(
pallets: &[Pallet],
pallet_name: &str,
function_name: &str,
) -> Result<CallItem, Error> {
let pallet = find_pallet_by_name(pallets, pallet_name)?;
if let Some(function) = pallet.functions.iter().find(|&e| e.name == function_name) {
return Ok(CallItem::Function(function.clone()));
}
if let Some(constant) = pallet.constants.iter().find(|&e| e.name == function_name) {
return Ok(CallItem::Constant(constant.clone()));
}
if let Some(storage) = pallet.state.iter().find(|&e| e.name == function_name) {
return Ok(CallItem::Storage(storage.clone()));
}
Err(Error::FunctionNotFound(format!(
"Could not find a function, constant or storage with the name \"{function_name}\""
)))
}
/// Parses and processes raw string parameter values for a dispatchable function, mapping them to
/// `Value` types.
///
/// # Arguments
/// * `params`: The metadata definition for each parameter of the corresponding dispatchable
/// function.
/// * `raw_params`: A vector of raw string arguments for the dispatchable function.
pub fn parse_dispatchable_arguments(
params: &[Param],
raw_params: Vec<String>,
) -> Result<Vec<Value>, Error> {
params
.iter()
.zip(raw_params)
.map(|(param, raw_param)| {
// Convert sequence parameters to hex if is_sequence
let processed_param = if param.is_sequence && !raw_param.starts_with("0x") {
to_hex(&raw_param)
} else {
raw_param
};
scale_value::stringify::from_str_custom()
.add_custom_parser(custom_parsers::parse_hex)
.add_custom_parser(custom_parsers::parse_ss58)
.parse(&processed_param)
.0
.map_err(|_| Error::ParamProcessingError)
})
.collect()
}
#[cfg(test)]
mod tests {
use super::*;
use anyhow::Result;
use sp_core::bytes::from_hex;
use subxt::ext::scale_bits;
#[test]
fn parse_dispatchable_arguments_works() -> Result<()> {
// Values for testing from: https://docs.rs/scale-value/0.18.0/scale_value/stringify/fn.from_str.html
// and https://docs.rs/scale-value/0.18.0/scale_value/stringify/fn.from_str_custom.html
let args = [
"1".to_string(),
"-1".to_string(),
"true".to_string(),
"'a'".to_string(),
"\"hi\"".to_string(),
"{ a: true, b: \"hello\" }".to_string(),
"MyVariant { a: true, b: \"hello\" }".to_string(),
"<0101>".to_string(),
"(1,2,0x030405)".to_string(),
r#"{
name: "Alice",
address: 5FHneW46xGXgs5mUiveU4sbTyGBzmstUspZC92UhjJM694ty
}"#
.to_string(),
]
.to_vec();
let addr: Vec<_> =
from_hex("8eaf04151687736326c9fea17e25fc5287613693c912909cb226aa4794f26a48")?
.into_iter()
.map(|b| Value::u128(b as u128))
.collect();
// Define mock dispatchable function parameters for testing.
let params = vec![
Param { type_name: "u128".to_string(), ..Default::default() },
Param { type_name: "i128".to_string(), ..Default::default() },
Param { type_name: "bool".to_string(), ..Default::default() },
Param { type_name: "char".to_string(), ..Default::default() },
Param { type_name: "string".to_string(), ..Default::default() },
Param { type_name: "composite".to_string(), ..Default::default() },
Param { type_name: "variant".to_string(), is_variant: true, ..Default::default() },
Param { type_name: "bit_sequence".to_string(), ..Default::default() },
Param { type_name: "tuple".to_string(), is_tuple: true, ..Default::default() },
Param { type_name: "composite".to_string(), ..Default::default() },
];
assert_eq!(
parse_dispatchable_arguments(¶ms, args)?,
[
Value::u128(1),
Value::i128(-1),
Value::bool(true),
Value::char('a'),
Value::string("hi"),
Value::named_composite(vec![
("a", Value::bool(true)),
("b", Value::string("hello"))
]),
Value::named_variant(
"MyVariant",
vec![("a", Value::bool(true)), ("b", Value::string("hello"))]
),
Value::bit_sequence(scale_bits::Bits::from_iter([false, true, false, true])),
Value::unnamed_composite(vec![
Value::u128(1),
Value::u128(2),
Value::unnamed_composite(vec![Value::u128(3), Value::u128(4), Value::u128(5),])
]),
Value::named_composite(vec![
("name", Value::string("Alice")),
("address", Value::unnamed_composite(addr))
])
]
);
Ok(())
}
#[test]
fn constant_display_works() {
let value = Value::u128(250).map_context(|_| 0u32);
let constant = Constant {
pallet: "System".to_string(),
name: "BlockHashCount".to_string(),
docs: "Maximum number of block number to block hash mappings to keep.".to_string(),
value,
};
assert_eq!(format!("{constant}"), "BlockHashCount");
}
#[test]
fn constant_struct_fields_work() {
let value = Value::u128(100).map_context(|_| 0u32);
let constant = Constant {
pallet: "Balances".to_string(),
name: "ExistentialDeposit".to_string(),
docs: "The minimum amount required to keep an account open.".to_string(),
value: value.clone(),
};
assert_eq!(constant.pallet, "Balances");
assert_eq!(constant.name, "ExistentialDeposit");
assert_eq!(constant.docs, "The minimum amount required to keep an account open.");
assert_eq!(constant.value, value);
}
#[test]
fn storage_display_works() {
let storage = Storage {
pallet: "System".to_string(),
name: "Account".to_string(),
docs: "The full account information for a particular account ID.".to_string(),
type_id: 42,
key_id: None,
query_all: false,
};
assert_eq!(format!("{storage}"), "Account");
}
#[test]
fn pallet_with_constants_and_storage() {
// Create a test value using map_context to convert Value<()> to Value<u32>
let value = Value::u128(250).map_context(|_| 0u32);
let pallet = Pallet {
name: "System".to_string(),
index: 0,
docs: "System pallet".to_string(),
functions: vec![],
constants: vec![Constant {
pallet: "System".to_string(),
name: "BlockHashCount".to_string(),
docs: "Maximum number of block number to block hash mappings to keep.".to_string(),
value,
}],
state: vec![Storage {
pallet: "System".to_string(),
name: "Account".to_string(),
docs: "The full account information for a particular account ID.".to_string(),
type_id: 42,
key_id: None,
query_all: false,
}],
};
assert_eq!(pallet.constants.len(), 1);
assert_eq!(pallet.state.len(), 1);
assert_eq!(pallet.constants[0].name, "BlockHashCount");
assert_eq!(pallet.state[0].name, "Account");
}
#[test]
fn storage_struct_with_key_id_works() {
// Test storage without key_id (plain storage)
let plain_storage = Storage {
pallet: "Timestamp".to_string(),
name: "Now".to_string(),
docs: "Current time for the current block.".to_string(),
type_id: 10,
key_id: None,
query_all: false,
};
assert_eq!(plain_storage.pallet, "Timestamp");
assert_eq!(plain_storage.name, "Now");
assert!(plain_storage.key_id.is_none());
// Test storage with key_id (storage map)
let map_storage = Storage {
pallet: "System".to_string(),
name: "Account".to_string(),
docs: "The full account information for a particular account ID.".to_string(),
type_id: 42,
key_id: Some(100),
query_all: false,
};
assert_eq!(map_storage.pallet, "System");
assert_eq!(map_storage.name, "Account");
assert_eq!(map_storage.key_id, Some(100));
}
#[test]
fn raw_value_to_string_works() -> Result<()> {
// Test simple integer value
let value = Value::u128(250).map_context(|_| 0u32);
let result = raw_value_to_string(&value, "")?;
assert_eq!(result, "250");
// Test boolean value
let value = Value::bool(true).map_context(|_| 0u32);
let result = raw_value_to_string(&value, "")?;
assert_eq!(result, "true");
// Test string value
let value = Value::string("hello").map_context(|_| 0u32);
let result = raw_value_to_string(&value, "")?;
assert_eq!(result, "\"hello\"");
// Test single-element tuple (should unwrap) - demonstrates format_single_tuples
let inner = Value::u128(42);
let value = Value::unnamed_composite(vec![inner]).map_context(|_| 0u32);
let result = raw_value_to_string(&value, "")?;
assert_eq!(result, "0x2a"); // 42 in hex - unwrapped from tuple
// Test multi-element composite - hex formatted
let value =
Value::unnamed_composite(vec![Value::u128(1), Value::u128(2)]).map_context(|_| 0u32);
let result = raw_value_to_string(&value, "")?;
assert_eq!(result, "0x0102"); // Formatted as hex bytes
Ok(())
}
#[test]
fn call_item_default_works() {
let item = CallItem::default();
assert!(matches!(item, CallItem::Function(_)));
if let CallItem::Function(f) = item {
assert_eq!(f, Function::default());
}
}
#[test]
fn call_item_display_works() {
let function = Function {
pallet: "System".to_string(),
name: "remark".to_string(),
..Default::default()
};
let item = CallItem::Function(function);
assert_eq!(format!("{item}"), "remark");
let constant = Constant {
pallet: "System".to_string(),
name: "BlockHashCount".to_string(),
docs: "docs".to_string(),
value: Value::u128(250).map_context(|_| 0u32),
};
let item = CallItem::Constant(constant);
assert_eq!(format!("{item}"), "BlockHashCount");
let storage = Storage {
pallet: "System".to_string(),
name: "Account".to_string(),
docs: "docs".to_string(),
type_id: 42,
key_id: None,
query_all: false,
};
let item = CallItem::Storage(storage);
assert_eq!(format!("{item}"), "Account");
}
#[test]
fn call_item_as_methods_work() {
let function = Function {
pallet: "System".to_string(),
name: "remark".to_string(),
..Default::default()
};
let item = CallItem::Function(function.clone());
assert_eq!(item.as_function(), Some(&function));
assert_eq!(item.as_constant(), None);
assert_eq!(item.as_storage(), None);
let constant = Constant {
pallet: "System".to_string(),
name: "BlockHashCount".to_string(),
docs: "docs".to_string(),
value: Value::u128(250).map_context(|_| 0u32),
};
let item = CallItem::Constant(constant.clone());
assert_eq!(item.as_function(), None);
assert_eq!(item.as_constant(), Some(&constant));
assert_eq!(item.as_storage(), None);
let storage = Storage {
pallet: "System".to_string(),
name: "Account".to_string(),
docs: "docs".to_string(),
type_id: 42,
key_id: None,
query_all: false,
};
let item = CallItem::Storage(storage.clone());
assert_eq!(item.as_function(), None);
assert_eq!(item.as_constant(), None);
assert_eq!(item.as_storage(), Some(&storage));
}
#[test]
fn call_item_name_works() {
let function = Function {
pallet: "System".to_string(),
name: "remark".to_string(),
..Default::default()
};
let item = CallItem::Function(function);
assert_eq!(item.name(), "remark");
let constant = Constant {
pallet: "System".to_string(),
name: "BlockHashCount".to_string(),
docs: "docs".to_string(),
value: Value::u128(250).map_context(|_| 0u32),
};
let item = CallItem::Constant(constant);
assert_eq!(item.name(), "BlockHashCount");
let storage = Storage {
pallet: "System".to_string(),
name: "Account".to_string(),
docs: "docs".to_string(),
type_id: 42,
key_id: None,
query_all: false,
};
let item = CallItem::Storage(storage);
assert_eq!(item.name(), "Account");
}
#[test]
fn call_item_hint_works() {
let function = Function {
pallet: "System".to_string(),
name: "remark".to_string(),
..Default::default()
};
let item = CallItem::Function(function);
assert_eq!(item.hint(), "📝 [EXTRINSIC]");
let constant = Constant {
pallet: "System".to_string(),
name: "BlockHashCount".to_string(),
docs: "docs".to_string(),
value: Value::u128(250).map_context(|_| 0u32),
};
let item = CallItem::Constant(constant);
assert_eq!(item.hint(), "[CONSTANT]");
let storage = Storage {
pallet: "System".to_string(),
name: "Account".to_string(),
docs: "docs".to_string(),
type_id: 42,
key_id: None,
query_all: false,
};
let item = CallItem::Storage(storage);
assert_eq!(item.hint(), "[STORAGE]");
}
#[test]
fn call_item_docs_works() {
let function = Function {
pallet: "System".to_string(),
name: "remark".to_string(),
docs: "Make some on-chain remark.".to_string(),
..Default::default()
};
let item = CallItem::Function(function);
assert_eq!(item.docs(), "Make some on-chain remark.");
let constant = Constant {
pallet: "System".to_string(),
name: "BlockHashCount".to_string(),
docs: "Maximum number of block number to block hash mappings to keep.".to_string(),
value: Value::u128(250).map_context(|_| 0u32),