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
use crate::code_gen::{
    custom_types::{param_type_calls, single_param_type_call, Component},
    docs_gen::expand_doc,
    resolved_type,
    resolved_type::ResolvedType,
};
use crate::utils::safe_ident;
use fuels_types::{errors::Error, ABIFunction, TypeDeclaration};
use inflector::Inflector;
use proc_macro2::TokenStream;
use quote::quote;
use resolved_type::resolve_type;
use std::collections::HashMap;

/// Functions used by the Abigen to expand functions defined in an ABI spec.

/// Transforms a function defined in [`ABIFunction`] into a [`TokenStream`]
/// that represents that same function signature as a Rust-native function
/// declaration.
///
/// The actual logic inside the function is the function `method_hash` under
/// [`Contract`], which is responsible for encoding
/// the function selector and the function parameters that will be used
/// in the actual contract call.
///
/// [`Contract`]: fuels_contract::contract::Contract
// TODO (oleksii/docs): linkify the above `Contract` link properly
pub fn expand_function(
    function: &ABIFunction,
    types: &HashMap<usize, TypeDeclaration>,
) -> Result<TokenStream, Error> {
    if function.name.is_empty() {
        return Err(Error::InvalidData("Function name can not be empty".into()));
    }

    let args = function_arguments(function, types)?;

    let arg_names = args.iter().map(|component| &component.field_name);

    let param_type_calls = param_type_calls(&args);

    let arg_declarations = args.iter().map(|component| {
        let name = &component.field_name;
        let field_type: TokenStream = (&component.field_type).into();
        quote! { #name: #field_type }
    });

    let doc = expand_doc(&format!(
        "Calls the contract's `{}` function",
        function.name,
    ));

    let name = safe_ident(&function.name);
    let name_stringified = name.to_string();

    let output_type: TokenStream = resolve_fn_output_type(function, types)?.into();

    Ok(quote! {
        #doc
        pub fn #name(&self #(,#arg_declarations)*) -> ContractCallHandler<#output_type> {
            let provider = self.wallet.get_provider().expect("Provider not set up");
            let encoded_fn_selector = resolve_fn_selector(#name_stringified, &[#(#param_type_calls),*]);
            let tokens = [#(#arg_names.into_token()),*];
            let log_decoder = LogDecoder{logs_map: self.logs_map.clone()};
            Contract::method_hash(
                &provider,
                self.contract_id.clone(),
                &self.wallet,
                encoded_fn_selector,
                &tokens,
                log_decoder
            )
            .expect("method not found (this should never happen)")
        }
    })
}

/// Generate the `main` function of a script
pub fn generate_script_main_function(
    main_function_abi: &ABIFunction,
    types: &HashMap<usize, TypeDeclaration>,
) -> Result<TokenStream, Error> {
    if main_function_abi.name != "main" {
        return Err(Error::InvalidData(
            "Script `main` function name can not be different from `main`".into(),
        ));
    }

    let output_type_resolved = resolve_fn_output_type(main_function_abi, types)?;
    let output_params = single_param_type_call(&output_type_resolved);
    let output_type: TokenStream = output_type_resolved.into();

    let args = function_arguments(main_function_abi, types)?;

    let arg_names = args.iter().map(|component| &component.field_name);

    let arg_declarations = args.iter().map(|component| {
        let name = &component.field_name;
        let field_type: TokenStream = (&component.field_type).into();
        quote! { #name: #field_type }
    });

    let doc = expand_doc("Run the script's `main` function with the provided arguments");

    let name = safe_ident("main");

    Ok(quote! {
        #doc
        pub fn #name(&self #(,#arg_declarations)*) -> ScriptCallHandler<#output_type> {
            let arg_name_tokens = [#(#arg_names.into_token()),*];
            let script_binary = std::fs::read(self.binary_filepath.as_str())
                                        .expect("Could not read from binary filepath");
            let encoded_args = ABIEncoder::encode(&arg_name_tokens).expect("Cannot encode script
            arguments");
            let provider = self.wallet.get_provider().expect("Provider not set up").clone();
            let log_decoder = LogDecoder{logs_map: self.logs_map.clone()};
            ScriptCallHandler::new(
                script_binary,
                encoded_args,
                self.wallet.clone(),
                provider,
                #output_params,
                log_decoder
            )
        }
    })
}

fn resolve_fn_output_type(
    function: &ABIFunction,
    types: &HashMap<usize, TypeDeclaration>,
) -> Result<ResolvedType, Error> {
    let output_type = resolve_type(&function.output, types)?;
    if output_type.uses_vectors() {
        Err(Error::CompilationError(format!(
            "function '{}' contains a vector in its return type. This currently isn't supported.",
            function.name
        )))
    } else {
        Ok(output_type)
    }
}

fn function_arguments(
    fun: &ABIFunction,
    types: &HashMap<usize, TypeDeclaration>,
) -> Result<Vec<Component>, Error> {
    fun.inputs
        .iter()
        .map(|input| Component::new(input, types, true))
        .collect::<Result<Vec<_>, Error>>()
        .map_err(|e| Error::InvalidType(e.to_string()))
}

/// Expands a positional identifier string that may be empty.
/// Note that this expands the parameter name with `safe_ident`, meaning that
/// identifiers that are reserved keywords get `_` appended to them.
pub fn expand_input_name(name: &str) -> Result<TokenStream, Error> {
    if name.is_empty() {
        return Err(Error::InvalidData(
            "Function arguments can not have empty names".into(),
        ));
    }
    let name = safe_ident(&name.to_snake_case());
    Ok(quote! { #name })
}

// Regarding string->TokenStream->string, refer to `custom_types` tests for more details.
#[cfg(test)]
mod tests {
    use super::*;
    use fuels_types::{ProgramABI, TypeApplication};
    use std::str::FromStr;

    #[test]
    fn test_expand_function_simpleabi() -> Result<(), Error> {
        let s = r#"
            {
                "types": [
                  {
                    "typeId": 6,
                    "type": "u64",
                    "components": null,
                    "typeParameters": null
                  },
                  {
                    "typeId": 8,
                    "type": "b256",
                    "components": null,
                    "typeParameters": null
                  },
                  {
                    "typeId": 6,
                    "type": "u64",
                    "components": null,
                    "typeParameters": null
                  },
                  {
                    "typeId": 8,
                    "type": "b256",
                    "components": null,
                    "typeParameters": null
                  },
                  {
                    "typeId": 10,
                    "type": "bool",
                    "components": null,
                    "typeParameters": null
                  },
                  {
                    "typeId": 12,
                    "type": "struct MyStruct1",
                    "components": [
                      {
                        "name": "x",
                        "type": 6,
                        "typeArguments": null
                      },
                      {
                        "name": "y",
                        "type": 8,
                        "typeArguments": null
                      }
                    ],
                    "typeParameters": null
                  },
                  {
                    "typeId": 6,
                    "type": "u64",
                    "components": null,
                    "typeParameters": null
                  },
                  {
                    "typeId": 8,
                    "type": "b256",
                    "components": null,
                    "typeParameters": null
                  },
                  {
                    "typeId": 2,
                    "type": "struct MyStruct1",
                    "components": [
                      {
                        "name": "x",
                        "type": 6,
                        "typeArguments": null
                      },
                      {
                        "name": "y",
                        "type": 8,
                        "typeArguments": null
                      }
                    ],
                    "typeParameters": null
                  },
                  {
                    "typeId": 3,
                    "type": "struct MyStruct2",
                    "components": [
                      {
                        "name": "x",
                        "type": 10,
                        "typeArguments": null
                      },
                      {
                        "name": "y",
                        "type": 12,
                        "typeArguments": []
                      }
                    ],
                    "typeParameters": null
                  },
                  {
                    "typeId": 26,
                    "type": "struct MyStruct1",
                    "components": [
                      {
                        "name": "x",
                        "type": 6,
                        "typeArguments": null
                      },
                      {
                        "name": "y",
                        "type": 8,
                        "typeArguments": null
                      }
                    ],
                    "typeParameters": null
                  }
                ],
                "functions": [
                  {
                    "type": "function",
                    "inputs": [
                      {
                        "name": "s1",
                        "type": 2,
                        "typeArguments": []
                      },
                      {
                        "name": "s2",
                        "type": 3,
                        "typeArguments": []
                      }
                    ],
                    "name": "some_abi_funct",
                    "output": {
                      "name": "",
                      "type": 26,
                      "typeArguments": []
                    }
                  }
                ]
              }
    "#;
        let parsed_abi: ProgramABI = serde_json::from_str(s)?;
        let all_types = parsed_abi
            .types
            .into_iter()
            .map(|t| (t.type_id, t))
            .collect::<HashMap<usize, TypeDeclaration>>();

        // Grabbing the one and only function in it.
        let result = expand_function(&parsed_abi.functions[0], &all_types)?;

        let expected_code = r#"
                #[doc = "Calls the contract's `some_abi_funct` function"]
                pub fn some_abi_funct(&self, s_1: MyStruct1, s_2: MyStruct2) -> ContractCallHandler<MyStruct1> {
                    let provider = self.wallet.get_provider().expect("Provider not set up");
                    let encoded_fn_selector = resolve_fn_selector(
                        "some_abi_funct",
                        &[<MyStruct1> :: param_type(), <MyStruct2> :: param_type()]
                    );
                    let tokens = [s_1.into_token(), s_2.into_token()];
                    let log_decoder = LogDecoder{logs_map: self.logs_map.clone()};
                    Contract::method_hash(
                        &provider,
                        self.contract_id.clone(),
                        &self.wallet,
                        encoded_fn_selector,
                        &tokens,
                        log_decoder
                    )
                    .expect("method not found (this should never happen)")
                }
        "#;

        let expected = TokenStream::from_str(expected_code).unwrap().to_string();

        assert_eq!(result.to_string(), expected);

        Ok(())
    }

    #[test]
    fn test_expand_function_simple() -> Result<(), Error> {
        let the_function = ABIFunction {
            inputs: vec![TypeApplication {
                name: String::from("bimbam"),
                type_id: 1,
                ..Default::default()
            }],
            name: "HelloWorld".to_string(),
            ..Default::default()
        };
        let types = [
            (
                0,
                TypeDeclaration {
                    type_id: 0,
                    type_field: String::from("()"),
                    ..Default::default()
                },
            ),
            (
                1,
                TypeDeclaration {
                    type_id: 1,
                    type_field: String::from("bool"),
                    ..Default::default()
                },
            ),
        ]
        .into_iter()
        .collect::<HashMap<_, _>>();
        let result = expand_function(&the_function, &types);
        let expected = TokenStream::from_str(
            r#"
            #[doc = "Calls the contract's `HelloWorld` function"]
            pub fn HelloWorld(&self, bimbam: bool) -> ContractCallHandler<()> {
                let provider = self.wallet.get_provider().expect("Provider not set up");
                let encoded_fn_selector = resolve_fn_selector("HelloWorld", &[<bool> :: param_type()]);
                let tokens = [bimbam.into_token()];
                let log_decoder = LogDecoder{logs_map: self.logs_map.clone()};
                Contract::method_hash(
                    &provider,
                    self.contract_id.clone(),
                    &self.wallet,
                    encoded_fn_selector,
                    &tokens,
                    log_decoder
                )
                .expect("method not found (this should never happen)")
            }
            "#,
        );
        let expected = expected?.to_string();

        assert_eq!(result?.to_string(), expected);
        Ok(())
    }

    #[test]
    fn test_expand_function_complex() -> Result<(), Error> {
        let the_function = ABIFunction {
            inputs: vec![TypeApplication {
                name: String::from("the_only_allowed_input"),
                type_id: 4,
                ..Default::default()
            }],
            name: "hello_world".to_string(),
            output: TypeApplication {
                name: String::from("stillnotused"),
                type_id: 1,
                ..Default::default()
            },
            ..Default::default()
        };
        let types = [
            (
                1,
                TypeDeclaration {
                    type_id: 1,
                    type_field: String::from("enum EntropyCirclesEnum"),
                    components: Some(vec![
                        TypeApplication {
                            name: String::from("Postcard"),
                            type_id: 2,
                            ..Default::default()
                        },
                        TypeApplication {
                            name: String::from("Teacup"),
                            type_id: 3,
                            ..Default::default()
                        },
                    ]),
                    ..Default::default()
                },
            ),
            (
                2,
                TypeDeclaration {
                    type_id: 2,
                    type_field: String::from("bool"),
                    ..Default::default()
                },
            ),
            (
                3,
                TypeDeclaration {
                    type_id: 3,
                    type_field: String::from("u64"),
                    ..Default::default()
                },
            ),
            (
                4,
                TypeDeclaration {
                    type_id: 4,
                    type_field: String::from("struct SomeWeirdFrenchCuisine"),
                    components: Some(vec![
                        TypeApplication {
                            name: String::from("Beef"),
                            type_id: 2,
                            ..Default::default()
                        },
                        TypeApplication {
                            name: String::from("BurgundyWine"),
                            type_id: 3,
                            ..Default::default()
                        },
                    ]),
                    ..Default::default()
                },
            ),
        ]
        .into_iter()
        .collect::<HashMap<_, _>>();
        let result = expand_function(&the_function, &types);
        // Some more editing was required because it is not rustfmt-compatible (adding/removing parentheses or commas)
        let expected = TokenStream::from_str(
            r#"
            #[doc = "Calls the contract's `hello_world` function"]
            pub fn hello_world(
                &self,
                the_only_allowed_input: SomeWeirdFrenchCuisine
            ) -> ContractCallHandler<EntropyCirclesEnum> {
                let provider = self.wallet.get_provider().expect("Provider not set up");
                let encoded_fn_selector = resolve_fn_selector("hello_world", &[<SomeWeirdFrenchCuisine> :: param_type()]);
                let tokens = [the_only_allowed_input.into_token()];
                let log_decoder = LogDecoder{logs_map: self.logs_map.clone()};
                Contract::method_hash(
                    &provider,
                    self.contract_id.clone(),
                    &self.wallet,
                    encoded_fn_selector,
                    &tokens,
                    log_decoder
                )
                .expect("method not found (this should never happen)")
            }
            "#,
        );
        let expected = expected?.to_string();

        assert_eq!(result?.to_string(), expected);
        Ok(())
    }

    // --- expand_selector ---

    // // --- expand_function_argument ---
    #[test]
    fn test_expand_function_arguments() -> Result<(), Error> {
        let the_argument = TypeApplication {
            name: "some_argument".to_string(),
            type_id: 0,
            ..Default::default()
        };

        // All arguments are here
        let the_function = ABIFunction {
            inputs: vec![the_argument],
            ..ABIFunction::default()
        };

        let types = [(
            0,
            TypeDeclaration {
                type_id: 0,
                type_field: String::from("u32"),
                ..Default::default()
            },
        )]
        .into_iter()
        .collect::<HashMap<_, _>>();
        let result = function_arguments(&the_function, &types)?;
        let component = &result[0];

        assert_eq!(&component.field_name.to_string(), "some_argument");
        assert_eq!(&component.field_type.to_string(), "u32");

        Ok(())
    }

    #[test]
    fn test_expand_function_arguments_primitive() -> Result<(), Error> {
        let the_function = ABIFunction {
            inputs: vec![TypeApplication {
                name: "bim_bam".to_string(),
                type_id: 1,
                ..Default::default()
            }],
            name: "pip_pop".to_string(),
            ..Default::default()
        };

        let types = [
            (
                0,
                TypeDeclaration {
                    type_id: 0,
                    type_field: String::from("()"),
                    ..Default::default()
                },
            ),
            (
                1,
                TypeDeclaration {
                    type_id: 1,
                    type_field: String::from("u64"),
                    ..Default::default()
                },
            ),
        ]
        .into_iter()
        .collect::<HashMap<_, _>>();
        let result = function_arguments(&the_function, &types)?;
        let component = &result[0];

        assert_eq!(&component.field_name.to_string(), "bim_bam");
        assert_eq!(&component.field_type.to_string(), "u64");

        Ok(())
    }

    #[test]
    fn test_expand_function_arguments_composite() -> Result<(), Error> {
        let mut function = ABIFunction {
            inputs: vec![TypeApplication {
                name: "bim_bam".to_string(),
                type_id: 0,
                ..Default::default()
            }],
            name: "PipPopFunction".to_string(),
            ..Default::default()
        };

        let types = [
            (
                0,
                TypeDeclaration {
                    type_id: 0,
                    type_field: "struct CarMaker".to_string(),
                    components: Some(vec![TypeApplication {
                        name: "name".to_string(),
                        type_id: 1,
                        ..Default::default()
                    }]),
                    ..Default::default()
                },
            ),
            (
                1,
                TypeDeclaration {
                    type_id: 1,
                    type_field: "str[5]".to_string(),
                    ..Default::default()
                },
            ),
            (
                2,
                TypeDeclaration {
                    type_id: 2,
                    type_field: "enum Cocktail".to_string(),
                    components: Some(vec![TypeApplication {
                        name: "variant".to_string(),
                        type_id: 3,
                        ..Default::default()
                    }]),
                    ..Default::default()
                },
            ),
            (
                3,
                TypeDeclaration {
                    type_id: 3,
                    type_field: "u32".to_string(),
                    ..Default::default()
                },
            ),
        ]
        .into_iter()
        .collect::<HashMap<_, _>>();
        let result = function_arguments(&function, &types)?;
        assert_eq!(&result[0].field_name.to_string(), "bim_bam");
        assert_eq!(&result[0].field_type.to_string(), "CarMaker");

        function.inputs[0].type_id = 2;
        let result = function_arguments(&function, &types)?;
        assert_eq!(&result[0].field_name.to_string(), "bim_bam");
        assert_eq!(&result[0].field_type.to_string(), "Cocktail");

        Ok(())
    }

    #[test]
    fn transform_name_to_snake_case() -> Result<(), Error> {
        let result = expand_input_name("CamelCaseHello");
        assert_eq!(result?.to_string(), "camel_case_hello");
        Ok(())
    }

    #[test]
    fn avoids_collisions_with_keywords() -> Result<(), Error> {
        let result = expand_input_name("if");
        assert_eq!(result?.to_string(), "if_");

        let result = expand_input_name("let");
        assert_eq!(result?.to_string(), "let_");
        Ok(())
    }
}