sway_core/abi_generation/
evm_abi.rs

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
use sway_types::integer_bits::IntegerBits;

use crate::{
    asm_generation::EvmAbiResult,
    decl_engine::DeclId,
    language::ty::{TyFunctionDecl, TyProgram, TyProgramKind},
    Engines, TypeArgument, TypeId, TypeInfo,
};

pub fn generate_abi_program(program: &TyProgram, engines: &Engines) -> EvmAbiResult {
    match &program.kind {
        TyProgramKind::Contract { abi_entries, .. } => abi_entries
            .iter()
            .map(|x| generate_abi_function(x, engines))
            .collect(),
        TyProgramKind::Script { entry_function, .. }
        | TyProgramKind::Predicate { entry_function, .. } => {
            vec![generate_abi_function(entry_function, engines)]
        }
        _ => vec![],
    }
}

/// Gives back a string that represents the type, considering what it resolves to
fn get_type_str(type_id: &TypeId, engines: &Engines, resolved_type_id: TypeId) -> String {
    let type_engine = engines.te();
    if type_id.is_generic_parameter(engines, resolved_type_id) {
        format!("generic {}", abi_str(&type_engine.get(*type_id), engines))
    } else {
        match (
            &*type_engine.get(*type_id),
            &*type_engine.get(resolved_type_id),
        ) {
            (TypeInfo::Custom { .. }, TypeInfo::Struct { .. }) => {
                format!("struct {}", abi_str(&type_engine.get(*type_id), engines))
            }
            (TypeInfo::Custom { .. }, TypeInfo::Enum { .. }) => {
                format!("enum {}", abi_str(&type_engine.get(*type_id), engines))
            }
            (TypeInfo::Tuple(fields), TypeInfo::Tuple(resolved_fields)) => {
                assert_eq!(fields.len(), resolved_fields.len());
                let field_strs = fields
                    .iter()
                    .map(|_| "_".to_string())
                    .collect::<Vec<String>>();
                format!("({})", field_strs.join(", "))
            }
            (TypeInfo::Array(_, count), TypeInfo::Array(_, resolved_count)) => {
                assert_eq!(count.val(), resolved_count.val());
                format!("[_; {}]", count.val())
            }
            (TypeInfo::Slice(_), TypeInfo::Slice(_)) => "__slice[_]".into(),
            (TypeInfo::Custom { .. }, _) => {
                format!("generic {}", abi_str(&type_engine.get(*type_id), engines))
            }
            _ => abi_str(&type_engine.get(*type_id), engines),
        }
    }
}

pub fn abi_str(type_info: &TypeInfo, engines: &Engines) -> String {
    use TypeInfo::*;
    let decl_engine = engines.de();
    match type_info {
        Unknown => "unknown".into(),
        Never => "never".into(),
        UnknownGeneric { name, .. } => name.to_string(),
        Placeholder(_) => "_".to_string(),
        TypeParam(n) => format!("typeparam({n})"),
        StringSlice => "str".into(),
        StringArray(x) => format!("str[{}]", x.val()),
        UnsignedInteger(x) => match x {
            IntegerBits::Eight => "uint8",
            IntegerBits::Sixteen => "uint16",
            IntegerBits::ThirtyTwo => "uint32",
            IntegerBits::SixtyFour => "uint64",
            IntegerBits::V256 => "uint256",
        }
        .into(),
        Boolean => "bool".into(),
        Custom {
            qualified_call_path: call_path,
            ..
        } => call_path.call_path.suffix.to_string(),
        Tuple(fields) => {
            let field_strs = fields
                .iter()
                .map(|field| abi_str_type_arg(field, engines))
                .collect::<Vec<String>>();
            format!("({})", field_strs.join(", "))
        }
        B256 => "uint256".into(),
        Numeric => "u64".into(), // u64 is the default
        Contract => "contract".into(),
        ErrorRecovery(_) => "unknown due to error".into(),
        UntypedEnum(decl_id) => {
            let decl = engines.pe().get_enum(decl_id);
            format!("untyped enum {}", decl.name)
        }
        UntypedStruct(decl_id) => {
            let decl = engines.pe().get_struct(decl_id);
            format!("untyped struct {}", decl.name)
        }
        Enum(decl_ref) => {
            let decl = decl_engine.get_enum(decl_ref);
            format!("enum {}", decl.call_path.suffix)
        }
        Struct(decl_ref) => {
            let decl = decl_engine.get_struct(decl_ref);
            format!("struct {}", decl.call_path.suffix)
        }
        ContractCaller { abi_name, .. } => {
            format!("contract caller {abi_name}")
        }
        Array(elem_ty, length) => {
            format!("{}[{}]", abi_str_type_arg(elem_ty, engines), length.val())
        }
        RawUntypedPtr => "raw untyped ptr".into(),
        RawUntypedSlice => "raw untyped slice".into(),
        Ptr(ty) => {
            format!("__ptr {}", abi_str_type_arg(ty, engines))
        }
        Slice(ty) => {
            format!("__slice {}", abi_str_type_arg(ty, engines))
        }
        Alias { ty, .. } => abi_str_type_arg(ty, engines),
        TraitType {
            name,
            trait_type_id: _,
        } => format!("trait type {}", name),
        Ref {
            to_mutable_value,
            referenced_type,
        } => {
            format!(
                "__ref {}{}", // TODO-IG: No references in ABIs according to the RFC. Or we want to have them?
                if *to_mutable_value { "mut " } else { "" },
                abi_str_type_arg(referenced_type, engines)
            )
        }
    }
}

pub fn abi_param_type(type_info: &TypeInfo, engines: &Engines) -> ethabi::ParamType {
    use TypeInfo::*;
    let type_engine = engines.te();
    let decl_engine = engines.de();
    match type_info {
        StringArray(x) => {
            ethabi::ParamType::FixedArray(Box::new(ethabi::ParamType::String), x.val())
        }
        UnsignedInteger(x) => match x {
            IntegerBits::Eight => ethabi::ParamType::Uint(8),
            IntegerBits::Sixteen => ethabi::ParamType::Uint(16),
            IntegerBits::ThirtyTwo => ethabi::ParamType::Uint(32),
            IntegerBits::SixtyFour => ethabi::ParamType::Uint(64),
            IntegerBits::V256 => ethabi::ParamType::Uint(256),
        },
        Boolean => ethabi::ParamType::Bool,
        B256 => ethabi::ParamType::Uint(256),
        Contract => ethabi::ParamType::Address,
        Enum { .. } => ethabi::ParamType::Uint(8),
        Tuple(fields) => ethabi::ParamType::Tuple(
            fields
                .iter()
                .map(|f| abi_param_type(&type_engine.get(f.type_id), engines))
                .collect::<Vec<ethabi::ParamType>>(),
        ),
        Struct(decl_ref) => {
            let decl = decl_engine.get_struct(decl_ref);
            ethabi::ParamType::Tuple(
                decl.fields
                    .iter()
                    .map(|f| abi_param_type(&type_engine.get(f.type_argument.type_id), engines))
                    .collect::<Vec<ethabi::ParamType>>(),
            )
        }
        Array(elem_ty, ..) => ethabi::ParamType::Array(Box::new(abi_param_type(
            &type_engine.get(elem_ty.type_id),
            engines,
        ))),
        _ => panic!("cannot convert type to Solidity ABI param type: {type_info:?}",),
    }
}

fn generate_abi_function(
    fn_decl_id: &DeclId<TyFunctionDecl>,
    engines: &Engines,
) -> ethabi::operation::Operation {
    let decl_engine = engines.de();
    let fn_decl = decl_engine.get_function(fn_decl_id);
    // A list of all `ethabi::Param`s needed for inputs
    let input_types = fn_decl
        .parameters
        .iter()
        .map(|x| ethabi::Param {
            name: x.name.to_string(),
            kind: ethabi::ParamType::Address,
            internal_type: Some(get_type_str(
                &x.type_argument.type_id,
                engines,
                x.type_argument.type_id,
            )),
        })
        .collect::<Vec<_>>();

    // The single `ethabi::Param` needed for the output
    let output_type = ethabi::Param {
        name: String::default(),
        kind: ethabi::ParamType::Address,
        internal_type: Some(get_type_str(
            &fn_decl.return_type.type_id,
            engines,
            fn_decl.return_type.type_id,
        )),
    };

    // Generate the ABI data for the function
    #[allow(deprecated)]
    ethabi::operation::Operation::Function(ethabi::Function {
        name: fn_decl.name.as_str().to_string(),
        inputs: input_types,
        outputs: vec![output_type],
        constant: None,
        state_mutability: ethabi::StateMutability::Payable,
    })
}

fn abi_str_type_arg(type_arg: &TypeArgument, engines: &Engines) -> String {
    abi_str(&engines.te().get(type_arg.type_id), engines)
}