alloy_dyn_abi/dynamic/
ty.rs

1use crate::{DynSolValue, DynToken, Error, Result, SolType, Specifier, Word};
2use alloc::{borrow::Cow, boxed::Box, string::String, vec::Vec};
3use alloy_primitives::{
4    try_vec,
5    utils::{box_try_new, vec_try_with_capacity},
6};
7use alloy_sol_types::{abi::Decoder, sol_data};
8use core::{fmt, iter::zip, num::NonZeroUsize, str::FromStr};
9use parser::TypeSpecifier;
10
11#[cfg(feature = "eip712")]
12macro_rules! as_tuple {
13    ($ty:ident $t:tt) => {
14        $ty::Tuple($t) | $ty::CustomStruct { tuple: $t, .. }
15    };
16}
17#[cfg(not(feature = "eip712"))]
18macro_rules! as_tuple {
19    ($ty:ident $t:tt) => {
20        $ty::Tuple($t)
21    };
22}
23pub(crate) use as_tuple;
24
25/// A dynamic Solidity type.
26///
27/// Equivalent to an enum wrapper around all implementers of [`SolType`].
28///
29/// This is used to represent Solidity types that are not known at compile time.
30/// It is used in conjunction with [`DynToken`] and [`DynSolValue`] to allow for
31/// dynamic ABI encoding and decoding.
32///
33/// # Examples
34///
35/// Parsing Solidity type strings:
36///
37/// ```
38/// use alloy_dyn_abi::DynSolType;
39///
40/// let type_name = "(bool,address)[]";
41/// let ty = DynSolType::parse(type_name)?;
42/// assert_eq!(
43///     ty,
44///     DynSolType::Array(Box::new(DynSolType::Tuple(
45///         vec![DynSolType::Bool, DynSolType::Address,]
46///     )))
47/// );
48/// assert_eq!(ty.sol_type_name(), type_name);
49///
50/// // alternatively, you can use the FromStr impl
51/// let ty2 = type_name.parse::<DynSolType>()?;
52/// assert_eq!(ty, ty2);
53/// # Ok::<_, alloy_dyn_abi::Error>(())
54/// ```
55///
56/// Decoding dynamic types:
57///
58/// ```
59/// use alloy_dyn_abi::{DynSolType, DynSolValue};
60/// use alloy_primitives::U256;
61///
62/// let my_type = DynSolType::Uint(256);
63/// let my_data: DynSolValue = U256::from(183u64).into();
64///
65/// let encoded = my_data.abi_encode();
66/// let decoded = my_type.abi_decode(&encoded)?;
67///
68/// assert_eq!(decoded, my_data);
69///
70/// let my_type = DynSolType::Array(Box::new(my_type));
71/// let my_data = DynSolValue::Array(vec![my_data.clone()]);
72///
73/// let encoded = my_data.abi_encode();
74/// let decoded = my_type.abi_decode(&encoded)?;
75///
76/// assert_eq!(decoded, my_data);
77/// # Ok::<_, alloy_dyn_abi::Error>(())
78/// ```
79#[derive(Clone, Debug, PartialEq, Eq, Hash)]
80pub enum DynSolType {
81    /// Boolean.
82    Bool,
83    /// Signed Integer.
84    Int(usize),
85    /// Unsigned Integer.
86    Uint(usize),
87    /// Fixed-size bytes, up to 32.
88    FixedBytes(usize),
89    /// Address.
90    Address,
91    /// Function.
92    Function,
93
94    /// Dynamic bytes.
95    Bytes,
96    /// String.
97    String,
98
99    /// Dynamically sized array.
100    Array(Box<DynSolType>),
101    /// Fixed-sized array.
102    FixedArray(Box<DynSolType>, usize),
103    /// Tuple.
104    Tuple(Vec<DynSolType>),
105
106    /// User-defined struct.
107    #[cfg(feature = "eip712")]
108    CustomStruct {
109        /// Name of the struct.
110        name: String,
111        /// Prop names.
112        prop_names: Vec<String>,
113        /// Inner types.
114        tuple: Vec<DynSolType>,
115    },
116}
117
118impl fmt::Display for DynSolType {
119    #[inline]
120    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
121        f.write_str(&self.sol_type_name())
122    }
123}
124
125impl FromStr for DynSolType {
126    type Err = Error;
127
128    #[inline]
129    fn from_str(s: &str) -> Result<Self, Self::Err> {
130        Self::parse(s)
131    }
132}
133
134impl DynSolType {
135    /// Parses a Solidity type name string into a [`DynSolType`].
136    ///
137    /// # Examples
138    ///
139    /// ```
140    /// # use alloy_dyn_abi::DynSolType;
141    /// let type_name = "uint256";
142    /// let ty = DynSolType::parse(type_name)?;
143    /// assert_eq!(ty, DynSolType::Uint(256));
144    /// assert_eq!(ty.sol_type_name(), type_name);
145    /// assert_eq!(ty.to_string(), type_name);
146    ///
147    /// // alternatively, you can use the FromStr impl
148    /// let ty2 = type_name.parse::<DynSolType>()?;
149    /// assert_eq!(ty2, ty);
150    /// # Ok::<_, alloy_dyn_abi::Error>(())
151    /// ```
152    #[inline]
153    pub fn parse(s: &str) -> Result<Self> {
154        TypeSpecifier::parse(s).map_err(Error::TypeParser).and_then(|t| t.resolve())
155    }
156
157    /// Calculate the nesting depth of this type. Simple types have a nesting
158    /// depth of 0, while all other types have a nesting depth of at least 1.
159    pub fn nesting_depth(&self) -> usize {
160        match self {
161            Self::Bool
162            | Self::Int(_)
163            | Self::Uint(_)
164            | Self::FixedBytes(_)
165            | Self::Address
166            | Self::Function
167            | Self::Bytes
168            | Self::String => 0,
169            Self::Array(contents) | Self::FixedArray(contents, _) => 1 + contents.nesting_depth(),
170            as_tuple!(Self tuple) => 1 + tuple.iter().map(Self::nesting_depth).max().unwrap_or(0),
171        }
172    }
173
174    /// Fallible cast to the contents of a variant.
175    #[inline]
176    pub fn as_tuple(&self) -> Option<&[Self]> {
177        match self {
178            Self::Tuple(t) => Some(t),
179            _ => None,
180        }
181    }
182
183    /// Fallible cast to the contents of a variant.
184    #[inline]
185    #[allow(clippy::missing_const_for_fn)]
186    pub fn as_custom_struct(&self) -> Option<(&str, &[String], &[Self])> {
187        match self {
188            #[cfg(feature = "eip712")]
189            Self::CustomStruct { name, prop_names, tuple } => Some((name, prop_names, tuple)),
190            _ => None,
191        }
192    }
193
194    /// Returns whether this type is contains a custom struct.
195    #[inline]
196    #[allow(clippy::missing_const_for_fn)]
197    pub fn has_custom_struct(&self) -> bool {
198        #[cfg(feature = "eip712")]
199        {
200            match self {
201                Self::CustomStruct { .. } => true,
202                Self::Array(t) => t.has_custom_struct(),
203                Self::FixedArray(t, _) => t.has_custom_struct(),
204                Self::Tuple(t) => t.iter().any(Self::has_custom_struct),
205                _ => false,
206            }
207        }
208        #[cfg(not(feature = "eip712"))]
209        {
210            false
211        }
212    }
213
214    /// Check that the given [`DynSolValue`]s match these types.
215    ///
216    /// See [`matches`](Self::matches) for more information.
217    #[inline]
218    pub fn matches_many(types: &[Self], values: &[DynSolValue]) -> bool {
219        types.len() == values.len() && zip(types, values).all(|(t, v)| t.matches(v))
220    }
221
222    /// Check that the given [`DynSolValue`] matches this type.
223    ///
224    /// Note: this will not check any names, but just the types; e.g for
225    /// `CustomStruct`, when the "eip712" feature is enabled, this will only
226    /// check equality between the lengths and types of the tuple.
227    pub fn matches(&self, value: &DynSolValue) -> bool {
228        match self {
229            Self::Bool => matches!(value, DynSolValue::Bool(_)),
230            Self::Int(size) => matches!(value, DynSolValue::Int(_, s) if s == size),
231            Self::Uint(size) => matches!(value, DynSolValue::Uint(_, s) if s == size),
232            Self::FixedBytes(size) => matches!(value, DynSolValue::FixedBytes(_, s) if s == size),
233            Self::Address => matches!(value, DynSolValue::Address(_)),
234            Self::Function => matches!(value, DynSolValue::Function(_)),
235            Self::Bytes => matches!(value, DynSolValue::Bytes(_)),
236            Self::String => matches!(value, DynSolValue::String(_)),
237            Self::Array(t) => {
238                matches!(value, DynSolValue::Array(v) if v.iter().all(|v| t.matches(v)))
239            }
240            Self::FixedArray(t, size) => matches!(
241                value,
242                DynSolValue::FixedArray(v) if v.len() == *size && v.iter().all(|v| t.matches(v))
243            ),
244            Self::Tuple(types) => {
245                matches!(value, as_tuple!(DynSolValue tuple) if zip(types, tuple).all(|(t, v)| t.matches(v)))
246            }
247            #[cfg(feature = "eip712")]
248            Self::CustomStruct { name: _, prop_names, tuple } => {
249                if let DynSolValue::CustomStruct { name: _, prop_names: p, tuple: t } = value {
250                    // check just types
251                    prop_names.len() == tuple.len()
252                        && prop_names.len() == p.len()
253                        && tuple.len() == t.len()
254                        && zip(tuple, t).all(|(a, b)| a.matches(b))
255                } else if let DynSolValue::Tuple(v) = value {
256                    zip(v, tuple).all(|(v, t)| t.matches(v))
257                } else {
258                    false
259                }
260            }
261        }
262    }
263
264    /// Dynamic detokenization.
265    // This should not fail when using a token created by `Self::empty_dyn_token`.
266    #[allow(clippy::unnecessary_to_owned)] // https://github.com/rust-lang/rust-clippy/issues/8148
267    pub fn detokenize(&self, token: DynToken<'_>) -> Result<DynSolValue> {
268        match (self, token) {
269            (Self::Bool, DynToken::Word(word)) => {
270                Ok(DynSolValue::Bool(sol_data::Bool::detokenize(word.into())))
271            }
272
273            // cheating here, but it's ok
274            (Self::Int(size), DynToken::Word(word)) => {
275                Ok(DynSolValue::Int(sol_data::Int::<256>::detokenize(word.into()), *size))
276            }
277
278            (Self::Uint(size), DynToken::Word(word)) => {
279                Ok(DynSolValue::Uint(sol_data::Uint::<256>::detokenize(word.into()), *size))
280            }
281
282            (Self::FixedBytes(size), DynToken::Word(word)) => Ok(DynSolValue::FixedBytes(
283                sol_data::FixedBytes::<32>::detokenize(word.into()),
284                *size,
285            )),
286
287            (Self::Address, DynToken::Word(word)) => {
288                Ok(DynSolValue::Address(sol_data::Address::detokenize(word.into())))
289            }
290
291            (Self::Function, DynToken::Word(word)) => {
292                Ok(DynSolValue::Function(sol_data::Function::detokenize(word.into())))
293            }
294
295            (Self::Bytes, DynToken::PackedSeq(buf)) => Ok(DynSolValue::Bytes(buf.to_vec())),
296
297            (Self::String, DynToken::PackedSeq(buf)) => {
298                Ok(DynSolValue::String(sol_data::String::detokenize(buf.into())))
299            }
300
301            (Self::Array(t), DynToken::DynSeq { contents, .. }) => {
302                t.detokenize_array(contents.into_owned()).map(DynSolValue::Array)
303            }
304
305            (Self::FixedArray(t, size), DynToken::FixedSeq(tokens, _)) => {
306                if *size != tokens.len() {
307                    return Err(crate::Error::custom(
308                        "array length mismatch on dynamic detokenization",
309                    ));
310                }
311                t.detokenize_array(tokens.into_owned()).map(DynSolValue::FixedArray)
312            }
313
314            (Self::Tuple(types), DynToken::FixedSeq(tokens, _)) => {
315                if types.len() != tokens.len() {
316                    return Err(crate::Error::custom(
317                        "tuple length mismatch on dynamic detokenization",
318                    ));
319                }
320                Self::detokenize_many(types, tokens.into_owned()).map(DynSolValue::Tuple)
321            }
322
323            #[cfg(feature = "eip712")]
324            (Self::CustomStruct { name, tuple, prop_names }, DynToken::FixedSeq(tokens, len)) => {
325                if len != tokens.len() || len != tuple.len() {
326                    return Err(crate::Error::custom(
327                        "custom length mismatch on dynamic detokenization",
328                    ));
329                }
330                Self::detokenize_many(tuple, tokens.into_owned()).map(|tuple| {
331                    DynSolValue::CustomStruct {
332                        name: name.clone(),
333                        prop_names: prop_names.clone(),
334                        tuple,
335                    }
336                })
337            }
338
339            _ => Err(crate::Error::custom("mismatched types on dynamic detokenization")),
340        }
341    }
342
343    fn detokenize_array(&self, tokens: Vec<DynToken<'_>>) -> Result<Vec<DynSolValue>> {
344        let mut values = vec_try_with_capacity(tokens.len())?;
345        for token in tokens {
346            values.push(self.detokenize(token)?);
347        }
348        Ok(values)
349    }
350
351    fn detokenize_many(types: &[Self], tokens: Vec<DynToken<'_>>) -> Result<Vec<DynSolValue>> {
352        assert_eq!(types.len(), tokens.len());
353        let mut values = vec_try_with_capacity(tokens.len())?;
354        for (ty, token) in zip(types, tokens) {
355            values.push(ty.detokenize(token)?);
356        }
357        Ok(values)
358    }
359
360    #[inline]
361    #[allow(clippy::missing_const_for_fn)]
362    fn sol_type_name_simple(&self) -> Option<&'static str> {
363        match self {
364            Self::Address => Some("address"),
365            Self::Function => Some("function"),
366            Self::Bool => Some("bool"),
367            Self::Bytes => Some("bytes"),
368            Self::String => Some("string"),
369            _ => None,
370        }
371    }
372
373    #[inline]
374    fn sol_type_name_raw(&self, out: &mut String) {
375        match self {
376            Self::Address | Self::Function | Self::Bool | Self::Bytes | Self::String => {
377                out.push_str(unsafe { self.sol_type_name_simple().unwrap_unchecked() });
378            }
379
380            Self::FixedBytes(size) | Self::Int(size) | Self::Uint(size) => {
381                let prefix = match self {
382                    Self::FixedBytes(..) => "bytes",
383                    Self::Int(..) => "int",
384                    Self::Uint(..) => "uint",
385                    _ => unreachable!(),
386                };
387                out.push_str(prefix);
388                out.push_str(itoa::Buffer::new().format(*size));
389            }
390
391            as_tuple!(Self tuple) => {
392                out.push('(');
393                for (i, val) in tuple.iter().enumerate() {
394                    if i > 0 {
395                        out.push(',');
396                    }
397                    val.sol_type_name_raw(out);
398                }
399                if tuple.len() == 1 {
400                    out.push(',');
401                }
402                out.push(')');
403            }
404            Self::Array(t) => {
405                t.sol_type_name_raw(out);
406                out.push_str("[]");
407            }
408            Self::FixedArray(t, len) => {
409                t.sol_type_name_raw(out);
410                out.push('[');
411                out.push_str(itoa::Buffer::new().format(*len));
412                out.push(']');
413            }
414        }
415    }
416
417    /// Returns an estimate of the number of bytes needed to format this type.
418    ///
419    /// This calculation is meant to be an upper bound for valid types to avoid
420    /// a second allocation in `sol_type_name_raw` and thus is almost never
421    /// going to be exact.
422    fn sol_type_name_capacity(&self) -> usize {
423        match self {
424            | Self::Address // 7
425            | Self::Function // 8
426            | Self::Bool // 4
427            | Self::Bytes // 5
428            | Self::String // 6
429            | Self::FixedBytes(_) // 5 + 2
430            | Self::Int(_) // 3 + 3
431            | Self::Uint(_) // 4 + 3
432            => 8,
433
434            | Self::Array(t) // t + 2
435            | Self::FixedArray(t, _) // t + 2 + log10(len)
436            => t.sol_type_name_capacity() + 8,
437
438            as_tuple!(Self tuple) // sum(tuple) + len(tuple) + 2
439            => tuple.iter().map(Self::sol_type_name_capacity).sum::<usize>() + 8,
440        }
441    }
442
443    /// The Solidity type name. This returns the Solidity type corresponding to
444    /// this value, if it is known. A type will not be known if the value
445    /// contains an empty sequence, e.g. `T[0]`.
446    pub fn sol_type_name(&self) -> Cow<'static, str> {
447        if let Some(s) = self.sol_type_name_simple() {
448            Cow::Borrowed(s)
449        } else {
450            let mut s = String::with_capacity(self.sol_type_name_capacity());
451            self.sol_type_name_raw(&mut s);
452            Cow::Owned(s)
453        }
454    }
455
456    /// The Solidity type name, as a `String`.
457    ///
458    /// Note: this shadows the inherent [`ToString`] implementation, derived
459    /// from [`fmt::Display`], for performance reasons.
460    #[inline]
461    #[allow(clippy::inherent_to_string_shadow_display)]
462    pub fn to_string(&self) -> String {
463        self.sol_type_name().into_owned()
464    }
465
466    /// Instantiate an empty dyn token, to be decoded into.
467    ///
468    /// ## Warning
469    ///
470    /// This function may allocate an unbounded amount of memory based on user
471    /// input types. It must be used with care to avoid DOS issues.
472    fn empty_dyn_token<'a>(&self) -> Result<DynToken<'a>> {
473        Ok(match self {
474            Self::Address
475            | Self::Function
476            | Self::Bool
477            | Self::FixedBytes(_)
478            | Self::Int(_)
479            | Self::Uint(_) => DynToken::Word(Word::ZERO),
480
481            Self::Bytes | Self::String => DynToken::PackedSeq(&[]),
482
483            Self::Array(t) => DynToken::DynSeq {
484                contents: Default::default(),
485                template: Some(box_try_new(t.empty_dyn_token()?)?),
486            },
487            &Self::FixedArray(ref t, size) => {
488                DynToken::FixedSeq(try_vec![t.empty_dyn_token()?; size]?.into(), size)
489            }
490            as_tuple!(Self tuple) => {
491                let mut tokens = vec_try_with_capacity(tuple.len())?;
492                for ty in tuple {
493                    tokens.push(ty.empty_dyn_token()?);
494                }
495                DynToken::FixedSeq(tokens.into(), tuple.len())
496            }
497        })
498    }
499
500    /// Decode an event topic into a [`DynSolValue`].
501    pub(crate) fn decode_event_topic(&self, topic: Word) -> DynSolValue {
502        match self {
503            Self::Address
504            | Self::Function
505            | Self::Bool
506            | Self::FixedBytes(_)
507            | Self::Int(_)
508            | Self::Uint(_) => self.detokenize(DynToken::Word(topic)).unwrap(),
509            _ => DynSolValue::FixedBytes(topic, 32),
510        }
511    }
512
513    /// Decode a [`DynSolValue`] from a byte slice. Fails if the value does not
514    /// match this type.
515    ///
516    /// This method is used for decoding single values. It assumes the `data`
517    /// argument is an encoded single-element sequence wrapping the `self` type.
518    #[inline]
519    #[cfg_attr(debug_assertions, track_caller)]
520    pub fn abi_decode(&self, data: &[u8]) -> Result<DynSolValue> {
521        self.abi_decode_inner(&mut Decoder::new(data), DynToken::decode_single_populate)
522    }
523
524    /// Decode a [`DynSolValue`] from a byte slice. Fails if the value does not
525    /// match this type.
526    ///
527    /// This method is used for decoding function arguments. It tries to
528    /// determine whether the user intended to decode a sequence or an
529    /// individual value. If the `self` type is a tuple, the `data` will be
530    /// decoded as a sequence, otherwise it will be decoded as a single value.
531    ///
532    /// # Examples
533    ///
534    /// ```solidity
535    /// // This function takes a single simple param:
536    /// // DynSolType::Uint(256).decode_params(data)
537    /// function myFunc(uint256 a) public;
538    ///
539    /// // This function takes 2 params:
540    /// // DynSolType::Tuple(vec![DynSolType::Uint(256), DynSolType::Bool])
541    /// //     .decode_params(data)
542    /// function myFunc(uint256 b, bool c) public;
543    /// ```
544    #[inline]
545    #[cfg_attr(debug_assertions, track_caller)]
546    pub fn abi_decode_params(&self, data: &[u8]) -> Result<DynSolValue> {
547        match self {
548            Self::Tuple(_) => self.abi_decode_sequence(data),
549            _ => self.abi_decode(data),
550        }
551    }
552
553    /// Decode a [`DynSolValue`] from a byte slice. Fails if the value does not
554    /// match this type.
555    #[inline]
556    #[cfg_attr(debug_assertions, track_caller)]
557    pub fn abi_decode_sequence(&self, data: &[u8]) -> Result<DynSolValue> {
558        self.abi_decode_inner(&mut Decoder::new(data), DynToken::decode_sequence_populate)
559    }
560
561    /// Calculate the minimum number of ABI words necessary to encode this
562    /// type.
563    pub fn minimum_words(&self) -> usize {
564        match self {
565            // word types are always 1
566            Self::Bool |
567            Self::Int(_) |
568            Self::Uint(_) |
569            Self::FixedBytes(_) |
570            Self::Address |
571            Self::Function |
572            // packed/dynamic seq types may be empty
573            Self::Bytes |
574            Self::String |
575            Self::Array(_) => 1,
576            // fixed-seq types are the sum of their components
577            Self::FixedArray(v, size) => size * v.minimum_words(),
578            Self::Tuple(tuple) => tuple.iter().map(|ty| ty.minimum_words()).sum(),
579            #[cfg(feature = "eip712")]
580            Self::CustomStruct { tuple, ..} => tuple.iter().map(|ty| ty.minimum_words()).sum(),
581        }
582    }
583
584    #[inline]
585    #[cfg_attr(debug_assertions, track_caller)]
586    pub(crate) fn abi_decode_inner<'d, F>(
587        &self,
588        decoder: &mut Decoder<'d>,
589        f: F,
590    ) -> Result<DynSolValue>
591    where
592        F: FnOnce(&mut DynToken<'d>, &mut Decoder<'d>) -> Result<()>,
593    {
594        if self.is_zst() {
595            return Ok(self.zero_sized_value().expect("checked"));
596        }
597
598        if decoder.remaining_words() < self.minimum_words() {
599            return Err(Error::SolTypes(alloy_sol_types::Error::Overrun));
600        }
601
602        let mut token = self.empty_dyn_token()?;
603        f(&mut token, decoder)?;
604        let value = self.detokenize(token).expect("invalid empty_dyn_token");
605        debug_assert!(
606            self.matches(&value),
607            "decoded value does not match type:\n  type: {self:?}\n value: {value:?}"
608        );
609        Ok(value)
610    }
611
612    /// Wrap in an array of the specified size
613    #[inline]
614    pub(crate) fn array_wrap(self, size: Option<NonZeroUsize>) -> Self {
615        match size {
616            Some(size) => Self::FixedArray(Box::new(self), size.get()),
617            None => Self::Array(Box::new(self)),
618        }
619    }
620
621    /// Iteratively wrap in arrays.
622    #[inline]
623    pub(crate) fn array_wrap_from_iter(
624        self,
625        iter: impl IntoIterator<Item = Option<NonZeroUsize>>,
626    ) -> Self {
627        iter.into_iter().fold(self, Self::array_wrap)
628    }
629
630    /// Return true if the type is zero-sized, e.g. `()` or `T[0]`
631    #[inline]
632    pub fn is_zst(&self) -> bool {
633        match self {
634            Self::Array(inner) => inner.is_zst(),
635            Self::FixedArray(inner, size) => *size == 0 || inner.is_zst(),
636            Self::Tuple(inner) => inner.is_empty() || inner.iter().all(|t| t.is_zst()),
637            _ => false,
638        }
639    }
640
641    #[inline]
642    const fn zero_sized_value(&self) -> Option<DynSolValue> {
643        match self {
644            Self::Array(_) => Some(DynSolValue::Array(vec![])),
645            Self::FixedArray(_, _) => Some(DynSolValue::FixedArray(vec![])),
646            Self::Tuple(_) => Some(DynSolValue::Tuple(vec![])),
647            _ => None,
648        }
649    }
650}
651
652#[cfg(test)]
653mod tests {
654    use super::*;
655    use alloc::string::ToString;
656    use alloy_primitives::{hex, Address};
657
658    #[test]
659    fn dynamically_encodes() {
660        let word1 =
661            "0000000000000000000000000101010101010101010101010101010101010101".parse().unwrap();
662        let word2 =
663            "0000000000000000000000000202020202020202020202020202020202020202".parse().unwrap();
664
665        let val = DynSolValue::Address(Address::repeat_byte(0x01));
666        let token = val.tokenize();
667        assert_eq!(token, DynToken::from(word1));
668
669        let val = DynSolValue::FixedArray(vec![
670            Address::repeat_byte(0x01).into(),
671            Address::repeat_byte(0x02).into(),
672        ]);
673
674        let token = val.tokenize();
675        assert_eq!(
676            token,
677            DynToken::FixedSeq(vec![DynToken::Word(word1), DynToken::Word(word2)].into(), 2)
678        );
679        let mut enc = crate::Encoder::default();
680        DynSolValue::encode_seq_to(val.as_fixed_seq().unwrap(), &mut enc);
681        assert_eq!(enc.finish(), vec![word1, word2]);
682    }
683
684    // also tests the type name parser
685    macro_rules! encoder_tests {
686        ($($name:ident($ty:literal, $encoded:literal)),* $(,)?) => {$(
687            #[test]
688            fn $name() {
689                encoder_test($ty, &hex!($encoded));
690            }
691        )*};
692    }
693
694    fn encoder_test(s: &str, encoded: &[u8]) {
695        let ty: DynSolType = s.parse().expect("parsing failed");
696        assert_eq!(ty.sol_type_name(), s, "type names are not the same");
697
698        let value = ty.abi_decode_params(encoded).expect("decoding failed");
699        if let Some(value_name) = value.sol_type_name() {
700            assert_eq!(value_name, s, "value names are not the same");
701        }
702
703        // Tuples are treated as top-level lists. So if we encounter a
704        // dynamic tuple, the total length of the encoded data will include
705        // the offset, but the encoding/decoding process will not. To
706        // account for this, we add 32 bytes to the expected length when
707        // the type is a dynamic tuple.
708        let mut len = encoded.len();
709        if value.as_tuple().is_some() && value.is_dynamic() {
710            len += 32;
711        }
712        assert_eq!(value.total_words() * 32, len, "dyn_tuple={}", len != encoded.len());
713
714        let re_encoded = value.abi_encode_params();
715        assert!(
716            re_encoded == encoded,
717            "
718  type: {ty}
719 value: {value:?}
720re-enc: {re_enc}
721   enc: {encoded}",
722            re_enc = hex::encode(re_encoded),
723            encoded = hex::encode(encoded),
724        );
725    }
726
727    encoder_tests! {
728        address("address", "0000000000000000000000001111111111111111111111111111111111111111"),
729
730        dynamic_array_of_addresses("address[]", "
731            0000000000000000000000000000000000000000000000000000000000000020
732            0000000000000000000000000000000000000000000000000000000000000002
733            0000000000000000000000001111111111111111111111111111111111111111
734            0000000000000000000000002222222222222222222222222222222222222222
735        "),
736
737        fixed_array_of_addresses("address[2]", "
738            0000000000000000000000001111111111111111111111111111111111111111
739            0000000000000000000000002222222222222222222222222222222222222222
740        "),
741
742        two_addresses("(address,address)", "
743            0000000000000000000000001111111111111111111111111111111111111111
744            0000000000000000000000002222222222222222222222222222222222222222
745        "),
746
747        fixed_array_of_dynamic_arrays_of_addresses("address[][2]", "
748            0000000000000000000000000000000000000000000000000000000000000020
749            0000000000000000000000000000000000000000000000000000000000000040
750            00000000000000000000000000000000000000000000000000000000000000a0
751            0000000000000000000000000000000000000000000000000000000000000002
752            0000000000000000000000001111111111111111111111111111111111111111
753            0000000000000000000000002222222222222222222222222222222222222222
754            0000000000000000000000000000000000000000000000000000000000000002
755            0000000000000000000000003333333333333333333333333333333333333333
756            0000000000000000000000004444444444444444444444444444444444444444
757        "),
758
759        dynamic_array_of_fixed_arrays_of_addresses("address[2][]", "
760            0000000000000000000000000000000000000000000000000000000000000020
761            0000000000000000000000000000000000000000000000000000000000000002
762            0000000000000000000000001111111111111111111111111111111111111111
763            0000000000000000000000002222222222222222222222222222222222222222
764            0000000000000000000000003333333333333333333333333333333333333333
765            0000000000000000000000004444444444444444444444444444444444444444
766        "),
767
768        dynamic_array_of_dynamic_arrays("address[][]", "
769            0000000000000000000000000000000000000000000000000000000000000020
770            0000000000000000000000000000000000000000000000000000000000000002
771            0000000000000000000000000000000000000000000000000000000000000040
772            0000000000000000000000000000000000000000000000000000000000000080
773            0000000000000000000000000000000000000000000000000000000000000001
774            0000000000000000000000001111111111111111111111111111111111111111
775            0000000000000000000000000000000000000000000000000000000000000001
776            0000000000000000000000002222222222222222222222222222222222222222
777        "),
778
779        dynamic_array_of_dynamic_arrays2("address[][]", "
780            0000000000000000000000000000000000000000000000000000000000000020
781            0000000000000000000000000000000000000000000000000000000000000002
782            0000000000000000000000000000000000000000000000000000000000000040
783            00000000000000000000000000000000000000000000000000000000000000a0
784            0000000000000000000000000000000000000000000000000000000000000002
785            0000000000000000000000001111111111111111111111111111111111111111
786            0000000000000000000000002222222222222222222222222222222222222222
787            0000000000000000000000000000000000000000000000000000000000000002
788            0000000000000000000000003333333333333333333333333333333333333333
789            0000000000000000000000004444444444444444444444444444444444444444
790        "),
791
792        fixed_array_of_fixed_arrays("address[2][2]", "
793            0000000000000000000000001111111111111111111111111111111111111111
794            0000000000000000000000002222222222222222222222222222222222222222
795            0000000000000000000000003333333333333333333333333333333333333333
796            0000000000000000000000004444444444444444444444444444444444444444
797        "),
798
799        fixed_array_of_static_tuples_followed_by_dynamic_type("((uint256,uint256,address)[2],string)", "
800            0000000000000000000000000000000000000000000000000000000005930cc5
801            0000000000000000000000000000000000000000000000000000000015002967
802            0000000000000000000000004444444444444444444444444444444444444444
803            000000000000000000000000000000000000000000000000000000000000307b
804            00000000000000000000000000000000000000000000000000000000000001c3
805            0000000000000000000000002222222222222222222222222222222222222222
806            00000000000000000000000000000000000000000000000000000000000000e0
807            0000000000000000000000000000000000000000000000000000000000000009
808            6761766f66796f726b0000000000000000000000000000000000000000000000
809        "),
810
811        empty_array("address[]", "
812            0000000000000000000000000000000000000000000000000000000000000020
813            0000000000000000000000000000000000000000000000000000000000000000
814        "),
815
816        empty_array_2("(address[],address[])", "
817            0000000000000000000000000000000000000000000000000000000000000040
818            0000000000000000000000000000000000000000000000000000000000000060
819            0000000000000000000000000000000000000000000000000000000000000000
820            0000000000000000000000000000000000000000000000000000000000000000
821        "),
822
823        // Nested empty arrays
824        empty_array_3("(address[][],address[][])", "
825            0000000000000000000000000000000000000000000000000000000000000040
826            00000000000000000000000000000000000000000000000000000000000000a0
827            0000000000000000000000000000000000000000000000000000000000000001
828            0000000000000000000000000000000000000000000000000000000000000020
829            0000000000000000000000000000000000000000000000000000000000000000
830            0000000000000000000000000000000000000000000000000000000000000001
831            0000000000000000000000000000000000000000000000000000000000000020
832            0000000000000000000000000000000000000000000000000000000000000000
833        "),
834
835        fixed_bytes("bytes2", "1234000000000000000000000000000000000000000000000000000000000000"),
836
837        string("string", "
838            0000000000000000000000000000000000000000000000000000000000000020
839            0000000000000000000000000000000000000000000000000000000000000009
840            6761766f66796f726b0000000000000000000000000000000000000000000000
841        "),
842
843        bytes("bytes", "
844            0000000000000000000000000000000000000000000000000000000000000020
845            0000000000000000000000000000000000000000000000000000000000000002
846            1234000000000000000000000000000000000000000000000000000000000000
847        "),
848
849        bytes_2("bytes", "
850            0000000000000000000000000000000000000000000000000000000000000020
851            000000000000000000000000000000000000000000000000000000000000001f
852            1000000000000000000000000000000000000000000000000000000000000200
853        "),
854
855        bytes_3("bytes", "
856            0000000000000000000000000000000000000000000000000000000000000020
857            0000000000000000000000000000000000000000000000000000000000000040
858            1000000000000000000000000000000000000000000000000000000000000000
859            1000000000000000000000000000000000000000000000000000000000000000
860        "),
861
862        two_bytes("(bytes,bytes)", "
863            0000000000000000000000000000000000000000000000000000000000000040
864            0000000000000000000000000000000000000000000000000000000000000080
865            000000000000000000000000000000000000000000000000000000000000001f
866            1000000000000000000000000000000000000000000000000000000000000200
867            0000000000000000000000000000000000000000000000000000000000000020
868            0010000000000000000000000000000000000000000000000000000000000002
869        "),
870
871        uint("uint256", "0000000000000000000000000000000000000000000000000000000000000004"),
872
873        int("int256", "0000000000000000000000000000000000000000000000000000000000000004"),
874
875        bool("bool", "0000000000000000000000000000000000000000000000000000000000000001"),
876
877        bool2("bool", "0000000000000000000000000000000000000000000000000000000000000000"),
878
879        comprehensive_test("(uint8,bytes,uint8,bytes)", "
880            0000000000000000000000000000000000000000000000000000000000000005
881            0000000000000000000000000000000000000000000000000000000000000080
882            0000000000000000000000000000000000000000000000000000000000000003
883            00000000000000000000000000000000000000000000000000000000000000e0
884            0000000000000000000000000000000000000000000000000000000000000040
885            131a3afc00d1b1e3461b955e53fc866dcf303b3eb9f4c16f89e388930f48134b
886            131a3afc00d1b1e3461b955e53fc866dcf303b3eb9f4c16f89e388930f48134b
887            0000000000000000000000000000000000000000000000000000000000000040
888            131a3afc00d1b1e3461b955e53fc866dcf303b3eb9f4c16f89e388930f48134b
889            131a3afc00d1b1e3461b955e53fc866dcf303b3eb9f4c16f89e388930f48134b
890        "),
891
892        comprehensive_test2("(bool,string,uint8,uint8,uint8,uint8[])", "
893            0000000000000000000000000000000000000000000000000000000000000001
894            00000000000000000000000000000000000000000000000000000000000000c0
895            0000000000000000000000000000000000000000000000000000000000000002
896            0000000000000000000000000000000000000000000000000000000000000003
897            0000000000000000000000000000000000000000000000000000000000000004
898            0000000000000000000000000000000000000000000000000000000000000100
899            0000000000000000000000000000000000000000000000000000000000000009
900            6761766f66796f726b0000000000000000000000000000000000000000000000
901            0000000000000000000000000000000000000000000000000000000000000003
902            0000000000000000000000000000000000000000000000000000000000000005
903            0000000000000000000000000000000000000000000000000000000000000006
904            0000000000000000000000000000000000000000000000000000000000000007
905        "),
906
907        dynamic_array_of_bytes("bytes[]", "
908            0000000000000000000000000000000000000000000000000000000000000020
909            0000000000000000000000000000000000000000000000000000000000000001
910            0000000000000000000000000000000000000000000000000000000000000020
911            0000000000000000000000000000000000000000000000000000000000000026
912            019c80031b20d5e69c8093a571162299032018d913930d93ab320ae5ea44a421
913            8a274f00d6070000000000000000000000000000000000000000000000000000
914        "),
915
916        dynamic_array_of_bytes2("bytes[]", "
917            0000000000000000000000000000000000000000000000000000000000000020
918            0000000000000000000000000000000000000000000000000000000000000002
919            0000000000000000000000000000000000000000000000000000000000000040
920            00000000000000000000000000000000000000000000000000000000000000a0
921            0000000000000000000000000000000000000000000000000000000000000026
922            4444444444444444444444444444444444444444444444444444444444444444
923            4444444444440000000000000000000000000000000000000000000000000000
924            0000000000000000000000000000000000000000000000000000000000000026
925            6666666666666666666666666666666666666666666666666666666666666666
926            6666666666660000000000000000000000000000000000000000000000000000
927        "),
928
929        static_tuple_of_addresses("(address,address)", "
930            0000000000000000000000001111111111111111111111111111111111111111
931            0000000000000000000000002222222222222222222222222222222222222222
932        "),
933
934        dynamic_tuple("((string,string),)", "
935            0000000000000000000000000000000000000000000000000000000000000020
936            0000000000000000000000000000000000000000000000000000000000000040
937            0000000000000000000000000000000000000000000000000000000000000080
938            0000000000000000000000000000000000000000000000000000000000000009
939            6761766f66796f726b0000000000000000000000000000000000000000000000
940            0000000000000000000000000000000000000000000000000000000000000009
941            6761766f66796f726b0000000000000000000000000000000000000000000000
942        "),
943
944        dynamic_tuple_of_bytes("((bytes,bytes),)", "
945            0000000000000000000000000000000000000000000000000000000000000020
946            0000000000000000000000000000000000000000000000000000000000000040
947            00000000000000000000000000000000000000000000000000000000000000a0
948            0000000000000000000000000000000000000000000000000000000000000026
949            4444444444444444444444444444444444444444444444444444444444444444
950            4444444444440000000000000000000000000000000000000000000000000000
951            0000000000000000000000000000000000000000000000000000000000000026
952            6666666666666666666666666666666666666666666666666666666666666666
953            6666666666660000000000000000000000000000000000000000000000000000
954        "),
955
956        complex_tuple("((uint256,string,address,address),)", "
957            0000000000000000000000000000000000000000000000000000000000000020
958            1111111111111111111111111111111111111111111111111111111111111111
959            0000000000000000000000000000000000000000000000000000000000000080
960            0000000000000000000000001111111111111111111111111111111111111111
961            0000000000000000000000002222222222222222222222222222222222222222
962            0000000000000000000000000000000000000000000000000000000000000009
963            6761766f66796f726b0000000000000000000000000000000000000000000000
964        "),
965
966        nested_tuple("((string,bool,string,(string,string,(string,string))),)", "
967            0000000000000000000000000000000000000000000000000000000000000020
968            0000000000000000000000000000000000000000000000000000000000000080
969            0000000000000000000000000000000000000000000000000000000000000001
970            00000000000000000000000000000000000000000000000000000000000000c0
971            0000000000000000000000000000000000000000000000000000000000000100
972            0000000000000000000000000000000000000000000000000000000000000004
973            7465737400000000000000000000000000000000000000000000000000000000
974            0000000000000000000000000000000000000000000000000000000000000006
975            6379626f72670000000000000000000000000000000000000000000000000000
976            0000000000000000000000000000000000000000000000000000000000000060
977            00000000000000000000000000000000000000000000000000000000000000a0
978            00000000000000000000000000000000000000000000000000000000000000e0
979            0000000000000000000000000000000000000000000000000000000000000005
980            6e69676874000000000000000000000000000000000000000000000000000000
981            0000000000000000000000000000000000000000000000000000000000000003
982            6461790000000000000000000000000000000000000000000000000000000000
983            0000000000000000000000000000000000000000000000000000000000000040
984            0000000000000000000000000000000000000000000000000000000000000080
985            0000000000000000000000000000000000000000000000000000000000000004
986            7765656500000000000000000000000000000000000000000000000000000000
987            0000000000000000000000000000000000000000000000000000000000000008
988            66756e7465737473000000000000000000000000000000000000000000000000
989        "),
990
991        params_containing_dynamic_tuple("(address,(bool,string,string),address,address,bool)", "
992            0000000000000000000000002222222222222222222222222222222222222222
993            00000000000000000000000000000000000000000000000000000000000000a0
994            0000000000000000000000003333333333333333333333333333333333333333
995            0000000000000000000000004444444444444444444444444444444444444444
996            0000000000000000000000000000000000000000000000000000000000000000
997            0000000000000000000000000000000000000000000000000000000000000001
998            0000000000000000000000000000000000000000000000000000000000000060
999            00000000000000000000000000000000000000000000000000000000000000a0
1000            0000000000000000000000000000000000000000000000000000000000000009
1001            7370616365736869700000000000000000000000000000000000000000000000
1002            0000000000000000000000000000000000000000000000000000000000000006
1003            6379626f72670000000000000000000000000000000000000000000000000000
1004        "),
1005
1006        params_containing_static_tuple("(address,(address,bool,bool),address,address)", "
1007            0000000000000000000000001111111111111111111111111111111111111111
1008            0000000000000000000000002222222222222222222222222222222222222222
1009            0000000000000000000000000000000000000000000000000000000000000001
1010            0000000000000000000000000000000000000000000000000000000000000000
1011            0000000000000000000000003333333333333333333333333333333333333333
1012            0000000000000000000000004444444444444444444444444444444444444444
1013        "),
1014
1015        dynamic_tuple_with_nested_static_tuples("((((bool,uint16),),uint16[]),)", "
1016            0000000000000000000000000000000000000000000000000000000000000020
1017            0000000000000000000000000000000000000000000000000000000000000000
1018            0000000000000000000000000000000000000000000000000000000000000777
1019            0000000000000000000000000000000000000000000000000000000000000060
1020            0000000000000000000000000000000000000000000000000000000000000002
1021            0000000000000000000000000000000000000000000000000000000000000042
1022            0000000000000000000000000000000000000000000000000000000000001337
1023        "),
1024
1025        // https://github.com/foundry-rs/book/issues/1286
1026        tuple_array("((uint256,)[],uint256)", "
1027            0000000000000000000000000000000000000000000000000000000000000040
1028            000000000000000000000000000000000000000000000000000000000000007b
1029            0000000000000000000000000000000000000000000000000000000000000001
1030            0000000000000000000000000000000000000000000000000000000000000001
1031        "),
1032        nested_tuple_array("(((uint256,)[],uint256),)", "
1033            0000000000000000000000000000000000000000000000000000000000000020
1034            0000000000000000000000000000000000000000000000000000000000000040
1035            000000000000000000000000000000000000000000000000000000000000007b
1036            0000000000000000000000000000000000000000000000000000000000000001
1037            0000000000000000000000000000000000000000000000000000000000000001
1038        "),
1039    }
1040
1041    // https://github.com/alloy-rs/core/issues/392
1042    #[test]
1043    fn zst_dos() {
1044        let my_type: DynSolType = "()[]".parse().unwrap();
1045        let value = my_type.abi_decode(&hex!("000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000FFFFFFFF"));
1046        assert_eq!(value, Ok(DynSolValue::Array(vec![])));
1047    }
1048
1049    #[test]
1050    #[cfg_attr(miri, ignore = "takes too long")]
1051    fn recursive_dos() {
1052        // https://github.com/alloy-rs/core/issues/490
1053        let payload = "0000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000000a0000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000020";
1054
1055        // Used to eat 60 gb of memory and then crash.
1056        let my_type: DynSolType = "uint256[][][][][][][][][][]".parse().unwrap();
1057        let decoded = my_type.abi_decode(&hex::decode(payload).unwrap());
1058        assert_eq!(decoded, Err(alloy_sol_types::Error::RecursionLimitExceeded(16).into()));
1059
1060        // https://github.com/paulmillr/micro-eth-signer/discussions/20
1061        let payload = &"0000000000000000000000000000000000000000000000000000000000000020\
1062             000000000000000000000000000000000000000000000000000000000000000a\
1063             0000000000000000000000000000000000000000000000000000000000000020"
1064            .repeat(64);
1065        let my_type: DynSolType = "uint256[][][][][][][][][][]".parse().unwrap();
1066        let decoded = my_type.abi_decode(&hex::decode(payload).unwrap());
1067        assert_eq!(
1068            decoded,
1069            Err(alloy_sol_types::Error::TypeCheckFail {
1070                expected_type: "offset (usize)".into(),
1071                data: "0000000000000000000000000000000000000000000a00000000000000000000"
1072                    .to_string()
1073            }
1074            .into())
1075        );
1076
1077        let my_type: DynSolType = "bytes[][][][][][][][][][]".parse().unwrap();
1078        let decoded = my_type.abi_decode(&hex::decode(payload).unwrap());
1079        assert_eq!(
1080            decoded,
1081            Err(alloy_sol_types::Error::TypeCheckFail {
1082                expected_type: "offset (usize)".into(),
1083                data: "0000000000000000000000000000000000000000000a00000000000000000000"
1084                    .to_string()
1085            }
1086            .into())
1087        );
1088    }
1089
1090    // https://github.com/alloy-rs/core/issues/490
1091    #[test]
1092    fn large_dyn_array_dos() {
1093        let payload = "000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000FFFFFFFF";
1094
1095        // Used to eat 60 gb of memory.
1096        let my_type: DynSolType = "uint32[1][]".parse().unwrap();
1097        let decoded = my_type.abi_decode(&hex::decode(payload).unwrap());
1098        assert_eq!(decoded, Err(alloy_sol_types::Error::Overrun.into()))
1099    }
1100
1101    #[test]
1102    fn fixed_array_dos() {
1103        let t = "uint32[9999999999]".parse::<DynSolType>().unwrap();
1104        let decoded = t.abi_decode(&[]);
1105        assert_eq!(decoded, Err(alloy_sol_types::Error::Overrun.into()))
1106    }
1107
1108    macro_rules! packed_tests {
1109        ($($name:ident($ty:literal, $v:literal, $encoded:literal)),* $(,)?) => {
1110            mod packed {
1111                use super::*;
1112
1113                $(
1114                    #[test]
1115                    fn $name() {
1116                        packed_test($ty, $v, &hex!($encoded));
1117                    }
1118                )*
1119            }
1120        };
1121    }
1122
1123    fn packed_test(t_s: &str, v_s: &str, expected: &[u8]) {
1124        let ty: DynSolType = t_s.parse().expect("parsing failed");
1125        assert_eq!(ty.sol_type_name(), t_s, "type names are not the same");
1126
1127        let value = match ty.coerce_str(v_s) {
1128            Ok(v) => v,
1129            Err(e) => {
1130                panic!("failed to coerce to a value: {e}");
1131            }
1132        };
1133        if let Some(value_name) = value.sol_type_name() {
1134            assert_eq!(value_name, t_s, "value names are not the same");
1135        }
1136
1137        let packed = value.abi_encode_packed();
1138        assert!(
1139            packed == expected,
1140            "
1141    type: {ty}
1142   value: {value:?}
1143  packed: {packed}
1144expected: {expected}",
1145            packed = hex::encode(packed),
1146            expected = hex::encode(expected),
1147        );
1148    }
1149
1150    packed_tests! {
1151        address("address", "1111111111111111111111111111111111111111", "1111111111111111111111111111111111111111"),
1152
1153        bool_false("bool", "false", "00"),
1154        bool_true("bool", "true", "01"),
1155
1156        int8_1("int8", "0", "00"),
1157        int8_2("int8", "1", "01"),
1158        int8_3("int8", "16", "10"),
1159        int8_4("int8", "127", "7f"),
1160        neg_int8_1("int8", "-1", "ff"),
1161        neg_int8_2("int8", "-16", "f0"),
1162        neg_int8_3("int8", "-127", "81"),
1163        neg_int8_4("int8", "-128", "80"),
1164
1165        int16_1("int16", "0", "0000"),
1166        int16_2("int16", "1", "0001"),
1167        int16_3("int16", "16", "0010"),
1168        int16_4("int16", "127", "007f"),
1169        int16_5("int16", "128", "0080"),
1170        int16_6("int16", "8192", "2000"),
1171        int16_7("int16", "32767", "7fff"),
1172        neg_int16_1("int16", "-1", "ffff"),
1173        neg_int16_2("int16", "-16", "fff0"),
1174        neg_int16_3("int16", "-127", "ff81"),
1175        neg_int16_4("int16", "-128", "ff80"),
1176        neg_int16_5("int16", "-129", "ff7f"),
1177        neg_int16_6("int16", "-32767", "8001"),
1178        neg_int16_7("int16", "-32768", "8000"),
1179
1180        int32_1("int32", "0", "00000000"),
1181        int32_2("int32", "-1", "ffffffff"),
1182        int64_1("int64", "0", "0000000000000000"),
1183        int64_2("int64", "-1", "ffffffffffffffff"),
1184        int128_1("int128", "0", "00000000000000000000000000000000"),
1185        int128_2("int128", "-1", "ffffffffffffffffffffffffffffffff"),
1186        int256_1("int256", "0", "0000000000000000000000000000000000000000000000000000000000000000"),
1187        int256_2("int256", "-1", "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),
1188
1189        uint8_1("uint8", "0", "00"),
1190        uint8_2("uint8", "1", "01"),
1191        uint8_3("uint8", "16", "10"),
1192        uint16("uint16", "0", "0000"),
1193        uint32("uint32", "0", "00000000"),
1194        uint64("uint64", "0", "0000000000000000"),
1195        uint128("uint128", "0", "00000000000000000000000000000000"),
1196        uint256_1("uint256", "0", "0000000000000000000000000000000000000000000000000000000000000000"),
1197        uint256_2("uint256", "42", "000000000000000000000000000000000000000000000000000000000000002a"),
1198        uint256_3("uint256", "115792089237316195423570985008687907853269984665640564039457584007913129639935", "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),
1199
1200        string_1("string", "a", "61"),
1201        string_2("string", "ab", "6162"),
1202        string_3("string", "abc", "616263"),
1203
1204        bytes_1("bytes", "00", "00"),
1205        bytes_2("bytes", "0001", "0001"),
1206        bytes_3("bytes", "000102", "000102"),
1207
1208        fbytes_1("bytes1", "00", "00"),
1209        fbytes_2("bytes2", "1234", "1234"),
1210        fbytes_3("(address,bytes20)", "(\
1211            1111111111111111111111111111111111111111,\
1212            2222222222222222222222222222222222222222\
1213        )", "
1214            1111111111111111111111111111111111111111
1215            2222222222222222222222222222222222222222
1216        "),
1217        fbytes_4("bytes20[]", "[\
1218            1111111111111111111111111111111111111111,\
1219            2222222222222222222222222222222222222222\
1220        ]", "
1221            0000000000000000000000001111111111111111111111111111111111111111
1222            0000000000000000000000002222222222222222222222222222222222222222
1223        "),
1224        fbytes_5("bytes20[2]", "[\
1225            1111111111111111111111111111111111111111,\
1226            2222222222222222222222222222222222222222\
1227        ]", "
1228            0000000000000000000000001111111111111111111111111111111111111111
1229            0000000000000000000000002222222222222222222222222222222222222222
1230        "),
1231
1232        dynamic_array_of_addresses("address[]", "[\
1233            1111111111111111111111111111111111111111,\
1234            2222222222222222222222222222222222222222\
1235        ]", "
1236            0000000000000000000000001111111111111111111111111111111111111111
1237            0000000000000000000000002222222222222222222222222222222222222222
1238        "),
1239
1240        fixed_array_of_addresses("address[2]", "[\
1241            1111111111111111111111111111111111111111,\
1242            2222222222222222222222222222222222222222\
1243        ]", "
1244            0000000000000000000000001111111111111111111111111111111111111111
1245            0000000000000000000000002222222222222222222222222222222222222222
1246        "),
1247
1248        two_addresses("(address,address)", "(\
1249            1111111111111111111111111111111111111111,\
1250            2222222222222222222222222222222222222222\
1251        )", "
1252            1111111111111111111111111111111111111111
1253            2222222222222222222222222222222222222222
1254        "),
1255
1256        fixed_array_of_dynamic_arrays_of_addresses("address[][2]", "[\
1257            [1111111111111111111111111111111111111111, 2222222222222222222222222222222222222222],\
1258            [3333333333333333333333333333333333333333, 4444444444444444444444444444444444444444]\
1259        ]", "
1260            0000000000000000000000001111111111111111111111111111111111111111
1261            0000000000000000000000002222222222222222222222222222222222222222
1262            0000000000000000000000003333333333333333333333333333333333333333
1263            0000000000000000000000004444444444444444444444444444444444444444
1264        "),
1265
1266        dynamic_array_of_fixed_arrays_of_addresses("address[2][]", "[\
1267            [1111111111111111111111111111111111111111, 2222222222222222222222222222222222222222],\
1268            [3333333333333333333333333333333333333333, 4444444444444444444444444444444444444444]\
1269        ]", "
1270            0000000000000000000000001111111111111111111111111111111111111111
1271            0000000000000000000000002222222222222222222222222222222222222222
1272            0000000000000000000000003333333333333333333333333333333333333333
1273            0000000000000000000000004444444444444444444444444444444444444444
1274        "),
1275
1276        dynamic_array_of_dynamic_arrays("address[][]", "[\
1277            [1111111111111111111111111111111111111111],\
1278            [2222222222222222222222222222222222222222]\
1279        ]", "
1280            0000000000000000000000001111111111111111111111111111111111111111
1281            0000000000000000000000002222222222222222222222222222222222222222
1282        "),
1283
1284        dynamic_array_of_dynamic_arrays2("address[][]", "[\
1285            [1111111111111111111111111111111111111111, 2222222222222222222222222222222222222222],\
1286            [3333333333333333333333333333333333333333, 4444444444444444444444444444444444444444]\
1287        ]", "
1288            0000000000000000000000001111111111111111111111111111111111111111
1289            0000000000000000000000002222222222222222222222222222222222222222
1290            0000000000000000000000003333333333333333333333333333333333333333
1291            0000000000000000000000004444444444444444444444444444444444444444
1292        "),
1293
1294        dynamic_array_of_dynamic_arrays3("uint32[][]", "[\
1295            [1, 2],\
1296            [3, 4]\
1297        ]", "
1298            0000000000000000000000000000000000000000000000000000000000000001
1299            0000000000000000000000000000000000000000000000000000000000000002
1300            0000000000000000000000000000000000000000000000000000000000000003
1301            0000000000000000000000000000000000000000000000000000000000000004
1302        "),
1303    }
1304}