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
use crate::utils::first_four_bytes_of_sha256_hash;
use crate::{unzip_param_types, ByteArray};
use fuels_types::param_types::ParamType;

/// Given a function name and its inputs  will return a ByteArray representing
/// the function selector as specified in the Fuel specs.
pub fn resolve_fn_selector(name: &str, inputs: &[ParamType]) -> ByteArray {
    let fn_signature = resolve_fn_signature(name, inputs);

    first_four_bytes_of_sha256_hash(&fn_signature)
}

fn resolve_fn_signature(name: &str, inputs: &[ParamType]) -> String {
    let fn_args = resolve_args(inputs);

    format!("{}({})", name, fn_args)
}

fn resolve_args(arg: &[ParamType]) -> String {
    arg.iter().map(resolve_arg).collect::<Vec<_>>().join(",")
}

fn resolve_arg(arg: &ParamType) -> String {
    match &arg {
        ParamType::U8 => "u8".to_owned(),
        ParamType::U16 => "u16".to_owned(),
        ParamType::U32 => "u32".to_owned(),
        ParamType::U64 => "u64".to_owned(),
        ParamType::Bool => "bool".to_owned(),
        ParamType::Byte => "byte".to_owned(),
        ParamType::B256 => "b256".to_owned(),
        ParamType::Unit => "()".to_owned(),
        ParamType::String(len) => {
            format!("str[{len}]")
        }
        ParamType::Array(internal_type, len) => {
            let inner = resolve_arg(internal_type);
            format!("a[{inner};{len}]")
        }
        ParamType::Struct {
            fields, generics, ..
        } => {
            let gen_params = resolve_args(generics);
            let fields = unzip_param_types(fields);
            let field_params = resolve_args(&fields);
            let gen_params = if !gen_params.is_empty() {
                format!("<{gen_params}>")
            } else {
                gen_params
            };
            format!("s{gen_params}({field_params})")
        }
        ParamType::Enum {
            variants: fields,
            generics,
            ..
        } => {
            let gen_params = resolve_args(generics);
            let field_params = resolve_args(&fields.param_types());
            let gen_params = if !gen_params.is_empty() {
                format!("<{gen_params}>")
            } else {
                gen_params
            };
            format!("e{gen_params}({field_params})")
        }
        ParamType::Tuple(inner) => {
            let inner = resolve_args(inner);
            format!("({inner})")
        }
        ParamType::Vector(el_type) => {
            let inner = resolve_arg(el_type);
            format!("s<{inner}>(s<{inner}>(rawptr,u64),u64)")
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use fuels_test_helpers::generate_unused_field_names;
    use fuels_types::enum_variants::EnumVariants;

    #[test]
    fn handles_primitive_types() {
        let check_selector_for_type = |primitive_type: ParamType, expected_selector: &str| {
            let selector = resolve_fn_signature("some_fun", &[primitive_type]);

            assert_eq!(selector, format!("some_fun({})", expected_selector));
        };

        for (param_type, expected_signature) in [
            (ParamType::U8, "u8"),
            (ParamType::U16, "u16"),
            (ParamType::U32, "u32"),
            (ParamType::U64, "u64"),
            (ParamType::Bool, "bool"),
            (ParamType::Byte, "byte"),
            (ParamType::B256, "b256"),
            (ParamType::Unit, "()"),
            (ParamType::String(15), "str[15]"),
        ] {
            check_selector_for_type(param_type, expected_signature);
        }
    }

    #[test]
    fn handles_arrays() {
        let inputs = [ParamType::Array(Box::new(ParamType::U8), 1)];

        let signature = resolve_fn_signature("some_fun", &inputs);

        assert_eq!(signature, format!("some_fun(a[u8;1])"));
    }

    #[test]
    fn handles_tuples() {
        let inputs = [ParamType::Tuple(vec![ParamType::U8, ParamType::U8])];

        let selector = resolve_fn_signature("some_fun", &inputs);

        assert_eq!(selector, format!("some_fun((u8,u8))"));
    }

    #[test]
    fn handles_structs() {
        let fields = generate_unused_field_names(vec![ParamType::U64, ParamType::U32]);
        let generics = vec![ParamType::U32];
        let inputs = [ParamType::Struct {
            name: "".to_string(),
            fields,
            generics,
        }];

        let selector = resolve_fn_signature("some_fun", &inputs);

        assert_eq!(selector, format!("some_fun(s<u32>(u64,u32))"));
    }

    #[test]
    fn handles_vectors() {
        let inputs = [ParamType::Vector(Box::new(ParamType::U32))];

        let selector = resolve_fn_signature("some_fun", &inputs);

        assert_eq!(selector, "some_fun(s<u32>(s<u32>(rawptr,u64),u64))")
    }

    #[test]
    fn handles_enums() {
        let variants = EnumVariants::new(generate_unused_field_names(vec![
            ParamType::U64,
            ParamType::U32,
        ]))
        .unwrap();
        let generics = vec![ParamType::U32];
        let inputs = [ParamType::Enum {
            name: "".to_string(),
            variants,
            generics,
        }];

        let selector = resolve_fn_signature("some_fun", &inputs);

        assert_eq!(selector, format!("some_fun(e<u32>(u64,u32))"));
    }

    #[test]
    fn ultimate_test() {
        let struct_a = ParamType::Struct {
            name: "".to_string(),
            fields: generate_unused_field_names(vec![ParamType::Struct {
                name: "".to_string(),
                fields: generate_unused_field_names(vec![ParamType::String(2)]),
                generics: vec![ParamType::String(2)],
            }]),
            generics: vec![ParamType::String(2)],
        };
        let struct_b = ParamType::Struct {
            name: "".to_string(),
            fields: generate_unused_field_names(vec![ParamType::Array(
                Box::new(struct_a.clone()),
                2,
            )]),
            generics: vec![struct_a],
        };
        let struct_c = ParamType::Struct {
            name: "".to_string(),
            fields: generate_unused_field_names(vec![ParamType::Tuple(vec![
                struct_b.clone(),
                struct_b.clone(),
            ])]),
            generics: vec![struct_b],
        };
        let inputs = [ParamType::Struct {
            name: "".to_string(),
            fields: generate_unused_field_names(vec![
                ParamType::Tuple(vec![
                    ParamType::Array(Box::new(ParamType::B256), 2),
                    ParamType::String(2),
                ]),
                ParamType::Tuple(vec![
                    ParamType::Array(
                        Box::new(ParamType::Enum {
                            name: "".to_string(),
                            variants: EnumVariants::new(generate_unused_field_names(vec![
                                ParamType::U64,
                                struct_c.clone(),
                            ]))
                            .unwrap(),
                            generics: vec![struct_c],
                        }),
                        1,
                    ),
                    ParamType::U32,
                ]),
            ]),
            generics: vec![ParamType::String(2), ParamType::B256],
        }];

        let selector = resolve_fn_signature("complex_test", &inputs);

        assert_eq!(selector, "complex_test(s<str[2],b256>((a[b256;2],str[2]),(a[e<s<s<s<str[2]>(s<str[2]>(str[2]))>(a[s<str[2]>(s<str[2]>(str[2]));2])>((s<s<str[2]>(s<str[2]>(str[2]))>(a[s<str[2]>(s<str[2]>(str[2]));2]),s<s<str[2]>(s<str[2]>(str[2]))>(a[s<str[2]>(s<str[2]>(str[2]));2])))>(u64,s<s<s<str[2]>(s<str[2]>(str[2]))>(a[s<str[2]>(s<str[2]>(str[2]));2])>((s<s<str[2]>(s<str[2]>(str[2]))>(a[s<str[2]>(s<str[2]>(str[2]));2]),s<s<str[2]>(s<str[2]>(str[2]))>(a[s<str[2]>(s<str[2]>(str[2]));2]))));1],u32)))");
    }
}