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
use crate::abi_encoder::ABIEncoder;
use crate::code_gen::custom_types_gen::extract_custom_type_name_from_abi_property;
use crate::code_gen::docs_gen::expand_doc;
use crate::errors::Error;
use crate::json_abi::{parse_param, ABIParser};
use crate::types::expand_type;
use crate::utils::{ident, safe_ident};
use crate::{ParamType, Selector};
use fuels_types::{CustomType, Function, Property, ENUM_KEYWORD, STRUCT_KEYWORD};
use inflector::Inflector;
use proc_macro2::{Literal, TokenStream};
use quote::quote;
use std::collections::HashMap;
pub fn expand_function(
function: &Function,
abi_parser: &ABIParser,
custom_enums: &HashMap<String, Property>,
custom_structs: &HashMap<String, Property>,
) -> Result<TokenStream, Error> {
let name = safe_ident(&function.name);
let fn_signature = abi_parser.build_fn_selector(&function.name, &function.inputs);
let encoded = ABIEncoder::encode_function_selector(fn_signature?.as_bytes());
let tokenized_signature = expand_selector(encoded);
let tokenized_output = expand_fn_outputs(&function.outputs)?;
let result = quote! { ContractCall<#tokenized_output> };
let (input, arg) = expand_function_arguments(function, custom_enums, custom_structs)?;
let doc = expand_doc(&format!(
"Calls the contract's `{}` (0x{}) function",
function.name,
hex::encode(encoded)
));
let mut output_params = vec![];
for output in &function.outputs {
let mut param_type_str: String = "ParamType::".to_owned();
let p = parse_param(output).unwrap();
param_type_str.push_str(&p.to_string());
let tok: proc_macro2::TokenStream = param_type_str.parse().unwrap();
output_params.push(tok);
}
let output_params_token = quote! { &[#( #output_params ),*] };
Ok(quote! {
#doc
pub fn #name(&self #input) -> #result {
Contract::method_hash(&self.wallet.get_provider().expect("Provider not set up"), self.contract_id, &self.wallet,
#tokenized_signature, #output_params_token, #arg).expect("method not found (this should never happen)")
}
})
}
fn expand_selector(selector: Selector) -> TokenStream {
let bytes = selector.iter().copied().map(Literal::u8_unsuffixed);
quote! { [#( #bytes ),*] }
}
fn expand_fn_outputs(outputs: &[Property]) -> Result<TokenStream, Error> {
match outputs.len() {
0 => Ok(quote! { () }),
1 => {
let output = outputs.first().expect("Outputs shouldn't not be empty");
if !output.is_custom_type() {
return expand_type(&parse_param(output)?);
}
match output.is_struct_type() {
true => {
let parsed_custom_type_name = extract_custom_type_name_from_abi_property(
output,
Some(CustomType::Struct),
)?
.parse()
.expect("Custom type name should be a valid Rust identifier");
Ok(parsed_custom_type_name)
}
false => match output.is_enum_type() {
true => {
let parsed_custom_type_name = extract_custom_type_name_from_abi_property(
output,
Some(CustomType::Enum),
)?
.parse()
.expect("Custom type name should be a valid Rust identifier");
Ok(parsed_custom_type_name)
}
false => match output.has_custom_type_in_array() {
true => {
let parsed_custom_type_name: TokenStream =
extract_custom_type_name_from_abi_property(
output,
Some(
output
.get_custom_type()
.expect("Custom type in array should be set"),
),
)?
.parse()
.unwrap();
Ok(quote! { ::std::vec::Vec<#parsed_custom_type_name> })
}
false => match output.has_custom_type_in_tuple() {
true => {
let tuple_type_signature: TokenStream = output
.type_field
.replace(STRUCT_KEYWORD, "")
.replace(ENUM_KEYWORD, "")
.parse()
.expect("could not parse tuple type signature");
Ok(tuple_type_signature)
}
false => {
panic!("{}", format!("Output is of custom type, but not an enum, struct or enum/struct inside an array/tuple. This shouldn't never happen. Output received: {:?}", output));
}
},
},
},
}
}
_ => {
let types = outputs
.iter()
.map(|param| expand_fn_outputs(&[param.clone()]))
.collect::<Result<Vec<_>, Error>>()?;
Ok(quote! { (#( #types ),*) })
}
}
}
fn expand_function_arguments(
fun: &Function,
custom_enums: &HashMap<String, Property>,
custom_structs: &HashMap<String, Property>,
) -> Result<(TokenStream, TokenStream), Error> {
let mut args = vec![];
let mut call_args = vec![];
for (i, param) in fun.inputs.iter().enumerate() {
let name = expand_input_name(i, ¶m.name);
let custom_property = match param.is_custom_type() {
false => None,
true => {
if param.is_enum_type() {
let name =
extract_custom_type_name_from_abi_property(param, Some(CustomType::Enum))
.expect("couldn't extract enum name from ABI property");
custom_enums.get(&name)
} else if param.is_struct_type() {
let name =
extract_custom_type_name_from_abi_property(param, Some(CustomType::Struct))
.expect("couldn't extract struct name from ABI property");
custom_structs.get(&name)
} else {
match param.has_custom_type_in_array() {
true => match param.get_custom_type() {
Some(custom_type) => {
let name = extract_custom_type_name_from_abi_property(
param,
Some(custom_type),
)
.expect("couldn't extract custom type name from ABI property");
match custom_type {
CustomType::Enum => custom_enums.get(&name),
CustomType::Struct => custom_structs.get(&name),
}
}
None => {
return Err(Error::InvalidType(format!(
"Custom type in array is not a struct or enum. Type: {:?}",
param
)))
}
},
false => None,
}
}
}
};
let kind = parse_param(param)?;
let tok = if let ParamType::Tuple(_tuple) = kind {
let toks = build_expanded_tuple_params(param)
.expect("failed to build expanded tuple parameters");
toks.parse::<TokenStream>().unwrap()
} else {
expand_input_param(fun, ¶m.name, &parse_param(param)?, &custom_property)?
};
args.push(quote! { #name: #tok });
call_args.push(name);
}
let args = quote! { #( , #args )* };
let call_args = quote! { &[ #(#call_args.into_token(), )* ] };
Ok((args, call_args))
}
fn build_expanded_tuple_params(tuple_param: &Property) -> Result<String, Error> {
let mut toks: String = "(".to_string();
for component in tuple_param
.components
.as_ref()
.expect("tuple parameter should have components")
{
if !component.is_custom_type() {
let p = parse_param(component)?;
let tok = expand_type(&p)?;
toks.push_str(&tok.to_string());
} else {
let tok = component
.type_field
.replace(STRUCT_KEYWORD, "")
.replace(ENUM_KEYWORD, "");
toks.push_str(&tok.to_string());
}
toks.push(',');
}
toks.push(')');
Ok(toks)
}
pub fn expand_input_name(index: usize, name: &str) -> TokenStream {
let name_str = match name {
"" => format!("p{}", index),
n => n.to_snake_case(),
};
let name = safe_ident(&name_str);
quote! { #name }
}
fn expand_input_param(
fun: &Function,
param: &str,
kind: &ParamType,
custom_type_property: &Option<&Property>,
) -> Result<TokenStream, Error> {
match kind {
ParamType::Array(ty, _) => {
let ty = expand_input_param(fun, param, ty, custom_type_property)?;
Ok(quote! {
::std::vec::Vec<#ty>
})
}
ParamType::Enum(_) => {
let ident = ident(
&extract_custom_type_name_from_abi_property(
custom_type_property.expect("Custom type property not found for enum"),
Some(CustomType::Enum),
)?
.to_class_case(),
);
Ok(quote! { #ident })
}
ParamType::Struct(_) => {
let ident = ident(
&extract_custom_type_name_from_abi_property(
custom_type_property.expect("Custom type property not found for struct"),
Some(CustomType::Struct),
)?
.to_class_case(),
);
Ok(quote! { #ident })
}
_ => expand_type(kind),
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::str::FromStr;
#[test]
fn test_expand_function_simple() {
let mut the_function = Function {
type_field: "unused".to_string(),
inputs: vec![],
name: "HelloWorld".to_string(),
outputs: vec![],
};
the_function.inputs.push(Property {
name: String::from("bimbam"),
type_field: String::from("bool"),
components: None,
});
let result = expand_function(
&the_function,
&ABIParser::new(),
&Default::default(),
&Default::default(),
);
let expected = TokenStream::from_str(
r#"
#[doc = "Calls the contract's `HelloWorld` (0x0000000097d4de45) function"]
pub fn HelloWorld(&self, bimbam: bool) -> ContractCall<()> {
Contract::method_hash(
&self.wallet.get_provider().expect("Provider not set up"),
self.contract_id,
&self.wallet,
[0, 0, 0, 0, 151, 212, 222, 69],
&[],
&[bimbam.into_token() ,]
)
.expect("method not found (this should never happen)")
}
"#,
);
let expected = expected.unwrap().to_string();
assert_eq!(result.unwrap().to_string(), expected);
}
#[test]
fn test_expand_function_complex() {
let mut the_function = Function {
type_field: "function".to_string(),
name: "hello_world".to_string(),
inputs: vec![],
outputs: vec![
Property {
name: String::from("notused"),
type_field: String::from("struct CoolIndieGame"),
components: Some(vec![
Property {
name: String::from("SuperMeat"),
type_field: String::from("bool"),
components: None,
},
Property {
name: String::from("BoyOrGirl"),
type_field: String::from("u64"),
components: None,
},
]),
},
Property {
name: String::from("stillnotused"),
type_field: String::from("enum EntropyCirclesEnum"),
components: Some(vec![
Property {
name: String::from("Postcard"),
type_field: String::from("bool"),
components: None,
},
Property {
name: String::from("Teacup"),
type_field: String::from("u64"),
components: None,
},
]),
},
],
};
the_function.inputs.push(Property {
name: String::from("the_only_allowed_input"),
type_field: String::from("struct BurgundyBeefStruct"),
components: Some(vec![
Property {
name: String::from("Beef"),
type_field: String::from("bool"),
components: None,
},
Property {
name: String::from("BurgundyWine"),
type_field: String::from("u64"),
components: None,
},
]),
});
let mut custom_structs = HashMap::new();
custom_structs.insert(
"BurgundyBeefStruct".to_string(),
Property {
name: "unused".to_string(),
type_field: "struct SomeWeirdFrenchCuisine".to_string(),
components: None,
},
);
custom_structs.insert(
"CoolIndieGame".to_string(),
Property {
name: "unused".to_string(),
type_field: "struct CoolIndieGame".to_string(),
components: None,
},
);
let mut custom_enums = HashMap::new();
custom_enums.insert(
"EntropyCirclesEnum".to_string(),
Property {
name: "unused".to_string(),
type_field: "enum EntropyCirclesEnum".to_string(),
components: None,
},
);
let abi_parser = ABIParser::new();
let result = expand_function(&the_function, &abi_parser, &custom_enums, &custom_structs);
let expected = TokenStream::from_str(
r#"
#[doc = "Calls the contract's `hello_world` (0x0000000076b25a24) function"]
pub fn hello_world(
&self,
the_only_allowed_input: SomeWeirdFrenchCuisine
) -> ContractCall<(CoolIndieGame , EntropyCirclesEnum)> {
Contract::method_hash(
&self.wallet.get_provider().expect("Provider not set up"),
self.contract_id,
&self.wallet,
[0, 0, 0, 0, 118, 178, 90, 36],
&[
ParamType::Struct(vec![ParamType::Bool, ParamType::U64]),
ParamType::Enum(vec![ParamType::Bool , ParamType::U64])] ,
&[the_only_allowed_input . into_token () ,]
)
.expect("method not found (this should never happen)")
}
"#,
);
let expected = expected.unwrap().to_string();
assert_eq!(result.unwrap().to_string(), expected);
}
#[test]
fn test_expand_selector() {
let result = expand_selector(Selector::default());
assert_eq!(result.to_string(), "[0 , 0 , 0 , 0 , 0 , 0 , 0 , 0]");
let result = expand_selector([1, 2, 3, 4, 5, 6, 7, 8]);
assert_eq!(result.to_string(), "[1 , 2 , 3 , 4 , 5 , 6 , 7 , 8]");
}
#[test]
fn test_expand_fn_outputs() {
let result = expand_fn_outputs(&[]);
assert_eq!(result.unwrap().to_string(), "()");
let result = expand_fn_outputs(&[Property {
name: "unused".to_string(),
type_field: "bool".to_string(),
components: None,
}]);
assert_eq!(result.unwrap().to_string(), "bool");
let result = expand_fn_outputs(&[Property {
name: "unused".to_string(),
type_field: String::from("struct streaming_services"),
components: Some(vec![
Property {
name: String::from("unused"),
type_field: String::from("thistypedoesntexist"),
components: None,
},
Property {
name: String::from("unused"),
type_field: String::from("thistypedoesntexist"),
components: None,
},
]),
}]);
assert_eq!(result.unwrap().to_string(), "streaming_services");
let result = expand_fn_outputs(&[Property {
name: "unused".to_string(),
type_field: String::from("enum StreamingServices"),
components: Some(vec![
Property {
name: String::from("unused"),
type_field: String::from("bool"),
components: None,
},
Property {
name: String::from("unused"),
type_field: String::from("u64"),
components: None,
},
]),
}]);
assert_eq!(result.unwrap().to_string(), "StreamingServices");
}
#[test]
fn test_expand_fn_outputs_two_more_arguments() {
let result = expand_fn_outputs(&[
Property {
name: "unused".to_string(),
type_field: String::from("bool"),
components: None,
},
Property {
name: "unused".to_string(),
type_field: String::from("u64"),
components: None,
},
Property {
name: "unused".to_string(),
type_field: String::from("u32"),
components: None,
},
]);
assert_eq!(result.unwrap().to_string(), "(bool , u64 , u32)");
let two_empty_components = vec![
Property {
name: String::from("unused"),
type_field: String::from("nonexistingtype"),
components: None,
},
Property {
name: String::from("unused"),
type_field: String::from("anotherunexistingtype"),
components: None,
},
];
let some_enum = Property {
name: "unused".to_string(),
type_field: String::from("enum Carmaker"),
components: Some(two_empty_components.clone()),
};
let result = expand_fn_outputs(&[some_enum.clone(), some_enum]);
assert_eq!(result.unwrap().to_string(), "(Carmaker , Carmaker)");
let some_struct = Property {
name: "unused".to_string(),
type_field: String::from("struct Carmaker"),
components: Some(two_empty_components),
};
let result = expand_fn_outputs(&[some_struct.clone(), some_struct]);
assert_eq!(result.unwrap().to_string(), "(Carmaker , Carmaker)")
}
#[test]
fn test_expand_function_arguments() {
let hm: HashMap<String, Property> = HashMap::new();
let the_argument = Property {
name: "some_argument".to_string(),
type_field: String::from("u32"),
components: None,
};
let mut the_function = Function {
type_field: "".to_string(),
inputs: vec![],
name: "".to_string(),
outputs: vec![],
};
the_function.inputs.push(the_argument);
let result = expand_function_arguments(&the_function, &hm, &hm);
let (args, call_args) = result.unwrap();
let result = format!("({},{})", args, call_args);
let expected = "(, some_argument : u32,& [some_argument . into_token () ,])";
assert_eq!(result, expected);
}
#[test]
fn test_expand_function_arguments_primitive() {
let hm: HashMap<String, Property> = HashMap::new();
let mut the_function = Function {
type_field: "function".to_string(),
inputs: vec![],
name: "pip_pop".to_string(),
outputs: vec![],
};
the_function.inputs.push(Property {
name: "bim_bam".to_string(),
type_field: String::from("u64"),
components: None,
});
let result = expand_function_arguments(&the_function, &hm, &hm);
let (args, call_args) = result.unwrap();
let result = format!("({},{})", args, call_args);
assert_eq!(result, "(, bim_bam : u64,& [bim_bam . into_token () ,])");
the_function.inputs[0].name = String::from("");
let result = expand_function_arguments(&the_function, &hm, &hm);
let (args, call_args) = result.unwrap();
let result = format!("({},{})", args, call_args);
assert_eq!(result, "(, p0 : u64,& [p0 . into_token () ,])");
}
#[test]
fn test_expand_function_arguments_composite() {
let mut function = Function {
type_field: "zig_zag".to_string(),
inputs: vec![],
name: "PipPopFunction".to_string(),
outputs: vec![],
};
function.inputs.push(Property {
name: "bim_bam".to_string(),
type_field: String::from("struct CarMaker"),
components: Some(vec![]),
});
let mut custom_structs = HashMap::new();
custom_structs.insert(
"CarMaker".to_string(),
Property {
name: "unused".to_string(),
type_field: "struct CarMaker".to_string(),
components: None,
},
);
let mut custom_enums = HashMap::new();
custom_enums.insert(
"Cocktail".to_string(),
Property {
name: "Cocktail".to_string(),
type_field: "enum Cocktail".to_string(),
components: None,
},
);
let result = expand_function_arguments(&function, &custom_enums, &custom_structs);
let (args, call_args) = result.unwrap();
let result = format!("({},{})", args, call_args);
let expected = r#"(, bim_bam : CarMaker,& [bim_bam . into_token () ,])"#;
assert_eq!(result, expected);
function.inputs[0].type_field = "enum Cocktail".to_string();
let result = expand_function_arguments(&function, &custom_enums, &custom_structs);
let (args, call_args) = result.unwrap();
let result = format!("({},{})", args, call_args);
let expected = r#"(, bim_bam : Cocktail,& [bim_bam . into_token () ,])"#;
assert_eq!(result, expected);
}
#[test]
fn test_expand_input_name() {
let result = expand_input_name(0, "CamelCaseHello");
assert_eq!(result.to_string(), "camel_case_hello");
let result = expand_input_name(1080, "");
assert_eq!(result.to_string(), "p1080");
let result = expand_input_name(0, "if");
assert_eq!(result.to_string(), "if_");
let result = expand_input_name(0, "let");
assert_eq!(result.to_string(), "let_");
}
#[test]
fn test_expand_input_param_primitive() {
let def = Function::default();
let result = expand_input_param(&def, "unused", &ParamType::Bool, &None);
assert_eq!(result.unwrap().to_string(), "bool");
let result = expand_input_param(&def, "unused", &ParamType::U64, &None);
assert_eq!(result.unwrap().to_string(), "u64");
let result = expand_input_param(&def, "unused", &ParamType::String(10), &None);
assert_eq!(result.unwrap().to_string(), "String");
}
#[test]
fn test_expand_input_param_array() {
let array_type = ParamType::Array(Box::new(ParamType::U64), 10);
let result = expand_input_param(&Function::default(), "unused", &array_type, &None);
assert_eq!(result.unwrap().to_string(), ":: std :: vec :: Vec < u64 >");
}
#[test]
fn test_expand_input_param_custom_type() {
let def = Function::default();
let struct_type = ParamType::Struct(vec![ParamType::Bool, ParamType::U64]);
let struct_prop = Property {
name: String::from("unused"),
type_field: String::from("struct babies"),
components: None,
};
let struct_name = Some(&struct_prop);
let result = expand_input_param(&def, "unused", &struct_type, &struct_name);
assert_eq!(result.unwrap().to_string(), "Baby");
let enum_type = ParamType::Enum(vec![ParamType::U8, ParamType::U32]);
let enum_prop = Property {
name: String::from("unused"),
type_field: String::from("enum babies"),
components: None,
};
let enum_name = Some(&enum_prop);
let result = expand_input_param(&def, "unused", &enum_type, &enum_name);
assert_eq!(result.unwrap().to_string(), "Baby");
}
#[test]
fn test_expand_input_param_struct_wrong_name() {
let def = Function::default();
let struct_type = ParamType::Struct(vec![ParamType::Bool, ParamType::U64]);
let struct_prop = Property {
name: String::from("unused"),
type_field: String::from("not_the_right_format"),
components: None,
};
let struct_name = Some(&struct_prop);
let result = expand_input_param(&def, "unused", &struct_type, &struct_name);
assert!(matches!(result, Err(Error::MissingData(_))));
}
#[test]
fn test_expand_input_param_struct_with_enum_name() {
let def = Function::default();
let struct_type = ParamType::Struct(vec![ParamType::Bool, ParamType::U64]);
let struct_prop = Property {
name: String::from("unused"),
type_field: String::from("enum butitsastruct"),
components: None,
};
let struct_name = Some(&struct_prop);
let result = expand_input_param(&def, "unused", &struct_type, &struct_name);
assert!(matches!(result, Err(Error::InvalidType(_))));
}
}