alloy_dyn_abi/
specifier.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
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
//! Contains utilities for parsing Solidity types.
//!
//! This is a simple representation of Solidity type grammar.

use crate::{DynSolCall, DynSolType, Result};
use alloc::vec::Vec;
use alloy_json_abi::{EventParam, Function, Param};
use parser::{ParameterSpecifier, Parameters, RootType, TupleSpecifier, TypeSpecifier, TypeStem};

#[cfg(feature = "eip712")]
use alloy_json_abi::InternalType;

/// Trait for items that can be resolved to `DynSol*`, i.e. they specify some Solidity interface
/// item.
///
/// The `Specifier` trait is implemented by types that can be resolved into Solidity interface
/// items, e.g. [`DynSolType`] or [`DynSolEvent`](crate::DynSolEvent).
///
/// ABI and related systems have many different ways of specifying Solidity interfaces.
/// This trait provides a single pattern for resolving those encodings into
/// Solidity interface items.
///
/// `Specifier<DynSolType>` is implemented for all the [`parser`] types, the
/// [`Param`] and [`EventParam`] structs, and [`str`]. The [`str`]
/// implementation calls [`DynSolType::parse`].
///
/// # Examples
///
/// ```
/// # use alloy_dyn_abi::{DynSolType, Specifier};
/// # use alloy_sol_type_parser::{RootType, TypeSpecifier};
/// let my_ty = TypeSpecifier::parse("bool")?.resolve()?;
/// assert_eq!(my_ty, DynSolType::Bool);
///
/// let my_ty = RootType::parse("uint256")?.resolve()?;
/// assert_eq!(my_ty, DynSolType::Uint(256));
///
/// assert_eq!("bytes32".resolve()?, DynSolType::FixedBytes(32));
/// # Ok::<_, alloy_dyn_abi::Error>(())
/// ```
pub trait Specifier<T> {
    /// Resolve the type into a value.
    fn resolve(&self) -> Result<T>;
}

impl Specifier<DynSolType> for str {
    #[inline]
    fn resolve(&self) -> Result<DynSolType> {
        DynSolType::parse(self)
    }
}

impl Specifier<DynSolType> for RootType<'_> {
    fn resolve(&self) -> Result<DynSolType> {
        match self.span() {
            "address" => Ok(DynSolType::Address),
            "function" => Ok(DynSolType::Function),
            "bool" => Ok(DynSolType::Bool),
            "string" => Ok(DynSolType::String),
            "bytes" => Ok(DynSolType::Bytes),
            "uint" => Ok(DynSolType::Uint(256)),
            "int" => Ok(DynSolType::Int(256)),
            name => {
                if let Some(sz) = name.strip_prefix("bytes") {
                    if let Ok(sz) = sz.parse() {
                        if sz != 0 && sz <= 32 {
                            return Ok(DynSolType::FixedBytes(sz));
                        }
                    }
                    return Err(parser::Error::invalid_size(name).into());
                }

                // fast path both integer types
                let (s, is_uint) =
                    if let Some(s) = name.strip_prefix('u') { (s, true) } else { (name, false) };

                if let Some(sz) = s.strip_prefix("int") {
                    if let Ok(sz) = sz.parse() {
                        if sz != 0 && sz <= 256 && sz % 8 == 0 {
                            return if is_uint {
                                Ok(DynSolType::Uint(sz))
                            } else {
                                Ok(DynSolType::Int(sz))
                            };
                        }
                    }
                    Err(parser::Error::invalid_size(name).into())
                } else {
                    Err(parser::Error::invalid_type_string(name).into())
                }
            }
        }
    }
}

impl Specifier<DynSolType> for TupleSpecifier<'_> {
    #[inline]
    fn resolve(&self) -> Result<DynSolType> {
        tuple(&self.types).map(DynSolType::Tuple)
    }
}

impl Specifier<DynSolType> for TypeStem<'_> {
    #[inline]
    fn resolve(&self) -> Result<DynSolType> {
        match self {
            Self::Root(root) => root.resolve(),
            Self::Tuple(tuple) => tuple.resolve(),
        }
    }
}

impl Specifier<DynSolType> for TypeSpecifier<'_> {
    fn resolve(&self) -> Result<DynSolType> {
        self.stem.resolve().map(|ty| ty.array_wrap_from_iter(self.sizes.iter().copied()))
    }
}

impl Specifier<DynSolType> for ParameterSpecifier<'_> {
    #[inline]
    fn resolve(&self) -> Result<DynSolType> {
        self.ty.resolve()
    }
}

impl Specifier<DynSolType> for Parameters<'_> {
    #[inline]
    fn resolve(&self) -> Result<DynSolType> {
        tuple(&self.params).map(DynSolType::Tuple)
    }
}

impl Specifier<DynSolType> for Param {
    #[inline]
    fn resolve(&self) -> Result<DynSolType> {
        resolve_param(
            &self.ty,
            &self.components,
            #[cfg(feature = "eip712")]
            self.internal_type(),
        )
    }
}

impl Specifier<DynSolType> for EventParam {
    #[inline]
    fn resolve(&self) -> Result<DynSolType> {
        resolve_param(
            &self.ty,
            &self.components,
            #[cfg(feature = "eip712")]
            self.internal_type(),
        )
    }
}

impl Specifier<DynSolCall> for Function {
    #[inline]
    fn resolve(&self) -> Result<DynSolCall> {
        let selector = self.selector();
        let parameters =
            self.inputs.iter().map(Specifier::<DynSolType>::resolve).collect::<Result<Vec<_>>>()?;
        let returns = self
            .outputs
            .iter()
            .map(Specifier::<DynSolType>::resolve)
            .collect::<Result<Vec<_>>>()?
            .into();
        let method = self.name.clone();

        Ok(DynSolCall::new(selector, parameters, Some(method), returns))
    }
}

fn resolve_param(
    ty: &str,
    components: &[Param],
    #[cfg(feature = "eip712")] it: Option<&InternalType>,
) -> Result<DynSolType> {
    let ty = TypeSpecifier::parse(ty)?;

    // type is simple, and we can resolve it via the specifier
    if components.is_empty() {
        return ty.resolve();
    }

    // type is complex
    let tuple = tuple(components)?;

    #[cfg(feature = "eip712")]
    let resolved = if let Some((_, name)) = it.and_then(|i| i.as_struct()) {
        DynSolType::CustomStruct {
            // skip array sizes, since we have them already from parsing `ty`
            name: name.split('[').next().unwrap().into(),
            prop_names: components.iter().map(|c| c.name.clone()).collect(),
            tuple,
        }
    } else {
        DynSolType::Tuple(tuple)
    };

    #[cfg(not(feature = "eip712"))]
    let resolved = DynSolType::Tuple(tuple);

    Ok(resolved.array_wrap_from_iter(ty.sizes))
}

fn tuple<T: Specifier<DynSolType>>(slice: &[T]) -> Result<Vec<DynSolType>> {
    let mut types = Vec::with_capacity(slice.len());
    for ty in slice {
        types.push(ty.resolve()?);
    }
    Ok(types)
}

macro_rules! deref_impls {
    ($($(#[$attr:meta])* [$($gen:tt)*] $t:ty),+ $(,)?) => {$(
        $(#[$attr])*
        impl<$($gen)*> Specifier<DynSolType> for $t {
            #[inline]
            fn resolve(&self) -> Result<DynSolType> {
                (**self).resolve()
            }
        }
    )+};
}

deref_impls! {
    [] alloc::string::String,
    [T: ?Sized + Specifier<DynSolType>] &T,
    [T: ?Sized + Specifier<DynSolType>] &mut T,
    [T: ?Sized + Specifier<DynSolType>] alloc::boxed::Box<T>,
    [T: ?Sized + alloc::borrow::ToOwned + Specifier<DynSolType>] alloc::borrow::Cow<'_, T>,
    [T: ?Sized + Specifier<DynSolType>] alloc::rc::Rc<T>,
    [T: ?Sized + Specifier<DynSolType>] alloc::sync::Arc<T>,
}

#[cfg(test)]
mod tests {
    use super::*;
    use alloc::boxed::Box;

    fn parse(s: &str) -> Result<DynSolType> {
        s.parse()
    }

    #[test]
    fn extra_close_parens() {
        parse("(bool,uint256))").unwrap_err();
        parse("bool,uint256))").unwrap_err();
        parse("bool,uint256)").unwrap_err();
    }

    #[test]
    fn extra_open_parents() {
        parse("((bool,uint256)").unwrap_err();
        parse("((bool,uint256").unwrap_err();
        parse("(bool,uint256").unwrap_err();
    }

    #[test]
    fn it_parses_tuples() {
        assert_eq!(parse("(bool,)"), Ok(DynSolType::Tuple(vec![DynSolType::Bool])));
        assert_eq!(
            parse("(uint256,uint256)"),
            Ok(DynSolType::Tuple(vec![DynSolType::Uint(256), DynSolType::Uint(256)]))
        );
        assert_eq!(
            parse("(uint256,uint256)[2]"),
            Ok(DynSolType::FixedArray(
                Box::new(DynSolType::Tuple(vec![DynSolType::Uint(256), DynSolType::Uint(256)])),
                2
            ))
        );
    }

    #[test]
    fn nested_tuples() {
        assert_eq!(
            parse("(bool,(uint256,uint256))"),
            Ok(DynSolType::Tuple(vec![
                DynSolType::Bool,
                DynSolType::Tuple(vec![DynSolType::Uint(256), DynSolType::Uint(256)])
            ]))
        );
        assert_eq!(
            parse("(((bool),),)"),
            Ok(DynSolType::Tuple(vec![DynSolType::Tuple(vec![DynSolType::Tuple(vec![
                DynSolType::Bool
            ])])]))
        );
    }

    #[test]
    fn empty_tuples() {
        assert_eq!(parse("()"), Ok(DynSolType::Tuple(vec![])));
        assert_eq!(
            parse("((),())"),
            Ok(DynSolType::Tuple(vec![DynSolType::Tuple(vec![]), DynSolType::Tuple(vec![])]))
        );
        assert_eq!(
            parse("((()))"),
            Ok(DynSolType::Tuple(vec![DynSolType::Tuple(vec![DynSolType::Tuple(vec![])])]))
        );
    }

    #[test]
    fn it_parses_simple_types() {
        assert_eq!(parse("uint256"), Ok(DynSolType::Uint(256)));
        assert_eq!(parse("uint8"), Ok(DynSolType::Uint(8)));
        assert_eq!(parse("uint"), Ok(DynSolType::Uint(256)));
        assert_eq!(parse("address"), Ok(DynSolType::Address));
        assert_eq!(parse("bool"), Ok(DynSolType::Bool));
        assert_eq!(parse("string"), Ok(DynSolType::String));
        assert_eq!(parse("bytes"), Ok(DynSolType::Bytes));
        assert_eq!(parse("bytes32"), Ok(DynSolType::FixedBytes(32)));
    }

    #[test]
    fn it_parses_complex_solidity_types() {
        assert_eq!(parse("uint256[]"), Ok(DynSolType::Array(Box::new(DynSolType::Uint(256)))));
        assert_eq!(
            parse("uint256[2]"),
            Ok(DynSolType::FixedArray(Box::new(DynSolType::Uint(256)), 2))
        );
        assert_eq!(
            parse("uint256[2][3]"),
            Ok(DynSolType::FixedArray(
                Box::new(DynSolType::FixedArray(Box::new(DynSolType::Uint(256)), 2)),
                3
            ))
        );
        assert_eq!(
            parse("uint256[][][]"),
            Ok(DynSolType::Array(Box::new(DynSolType::Array(Box::new(DynSolType::Array(
                Box::new(DynSolType::Uint(256))
            ))))))
        );

        assert_eq!(
            parse("tuple(address,bytes,(bool,(string,uint256)[][3]))[2]"),
            Ok(DynSolType::FixedArray(
                Box::new(DynSolType::Tuple(vec![
                    DynSolType::Address,
                    DynSolType::Bytes,
                    DynSolType::Tuple(vec![
                        DynSolType::Bool,
                        DynSolType::FixedArray(
                            Box::new(DynSolType::Array(Box::new(DynSolType::Tuple(vec![
                                DynSolType::String,
                                DynSolType::Uint(256)
                            ])))),
                            3
                        ),
                    ]),
                ])),
                2
            ))
        );
    }

    #[test]
    fn library_enum_workaround() {
        assert_eq!(parse("MyLibrary.MyEnum"), Ok(DynSolType::Uint(8)));
        assert_eq!(
            parse("MyLibrary.MyEnum[]"),
            Ok(DynSolType::Array(Box::new(DynSolType::Uint(8))))
        );
    }
}