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, false), 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, false), 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 alloy_primitives::{hex, Address};
656
657    #[test]
658    fn dynamically_encodes() {
659        let word1 =
660            "0000000000000000000000000101010101010101010101010101010101010101".parse().unwrap();
661        let word2 =
662            "0000000000000000000000000202020202020202020202020202020202020202".parse().unwrap();
663
664        let val = DynSolValue::Address(Address::repeat_byte(0x01));
665        let token = val.tokenize();
666        assert_eq!(token, DynToken::from(word1));
667
668        let val = DynSolValue::FixedArray(vec![
669            Address::repeat_byte(0x01).into(),
670            Address::repeat_byte(0x02).into(),
671        ]);
672
673        let token = val.tokenize();
674        assert_eq!(
675            token,
676            DynToken::FixedSeq(vec![DynToken::Word(word1), DynToken::Word(word2)].into(), 2)
677        );
678        let mut enc = crate::Encoder::default();
679        DynSolValue::encode_seq_to(val.as_fixed_seq().unwrap(), &mut enc);
680        assert_eq!(enc.finish(), vec![word1, word2]);
681    }
682
683    // also tests the type name parser
684    macro_rules! encoder_tests {
685        ($($name:ident($ty:literal, $encoded:literal)),* $(,)?) => {$(
686            #[test]
687            fn $name() {
688                encoder_test($ty, &hex!($encoded));
689            }
690        )*};
691    }
692
693    fn encoder_test(s: &str, encoded: &[u8]) {
694        let ty: DynSolType = s.parse().expect("parsing failed");
695        assert_eq!(ty.sol_type_name(), s, "type names are not the same");
696
697        let value = ty.abi_decode_params(encoded).expect("decoding failed");
698        if let Some(value_name) = value.sol_type_name() {
699            assert_eq!(value_name, s, "value names are not the same");
700        }
701
702        // Tuples are treated as top-level lists. So if we encounter a
703        // dynamic tuple, the total length of the encoded data will include
704        // the offset, but the encoding/decoding process will not. To
705        // account for this, we add 32 bytes to the expected length when
706        // the type is a dynamic tuple.
707        let mut len = encoded.len();
708        if value.as_tuple().is_some() && value.is_dynamic() {
709            len += 32;
710        }
711        assert_eq!(value.total_words() * 32, len, "dyn_tuple={}", len != encoded.len());
712
713        let re_encoded = value.abi_encode_params();
714        assert!(
715            re_encoded == encoded,
716            "
717  type: {ty}
718 value: {value:?}
719re-enc: {re_enc}
720   enc: {encoded}",
721            re_enc = hex::encode(re_encoded),
722            encoded = hex::encode(encoded),
723        );
724    }
725
726    encoder_tests! {
727        address("address", "0000000000000000000000001111111111111111111111111111111111111111"),
728
729        dynamic_array_of_addresses("address[]", "
730            0000000000000000000000000000000000000000000000000000000000000020
731            0000000000000000000000000000000000000000000000000000000000000002
732            0000000000000000000000001111111111111111111111111111111111111111
733            0000000000000000000000002222222222222222222222222222222222222222
734        "),
735
736        fixed_array_of_addresses("address[2]", "
737            0000000000000000000000001111111111111111111111111111111111111111
738            0000000000000000000000002222222222222222222222222222222222222222
739        "),
740
741        two_addresses("(address,address)", "
742            0000000000000000000000001111111111111111111111111111111111111111
743            0000000000000000000000002222222222222222222222222222222222222222
744        "),
745
746        fixed_array_of_dynamic_arrays_of_addresses("address[][2]", "
747            0000000000000000000000000000000000000000000000000000000000000020
748            0000000000000000000000000000000000000000000000000000000000000040
749            00000000000000000000000000000000000000000000000000000000000000a0
750            0000000000000000000000000000000000000000000000000000000000000002
751            0000000000000000000000001111111111111111111111111111111111111111
752            0000000000000000000000002222222222222222222222222222222222222222
753            0000000000000000000000000000000000000000000000000000000000000002
754            0000000000000000000000003333333333333333333333333333333333333333
755            0000000000000000000000004444444444444444444444444444444444444444
756        "),
757
758        dynamic_array_of_fixed_arrays_of_addresses("address[2][]", "
759            0000000000000000000000000000000000000000000000000000000000000020
760            0000000000000000000000000000000000000000000000000000000000000002
761            0000000000000000000000001111111111111111111111111111111111111111
762            0000000000000000000000002222222222222222222222222222222222222222
763            0000000000000000000000003333333333333333333333333333333333333333
764            0000000000000000000000004444444444444444444444444444444444444444
765        "),
766
767        dynamic_array_of_dynamic_arrays("address[][]", "
768            0000000000000000000000000000000000000000000000000000000000000020
769            0000000000000000000000000000000000000000000000000000000000000002
770            0000000000000000000000000000000000000000000000000000000000000040
771            0000000000000000000000000000000000000000000000000000000000000080
772            0000000000000000000000000000000000000000000000000000000000000001
773            0000000000000000000000001111111111111111111111111111111111111111
774            0000000000000000000000000000000000000000000000000000000000000001
775            0000000000000000000000002222222222222222222222222222222222222222
776        "),
777
778        dynamic_array_of_dynamic_arrays2("address[][]", "
779            0000000000000000000000000000000000000000000000000000000000000020
780            0000000000000000000000000000000000000000000000000000000000000002
781            0000000000000000000000000000000000000000000000000000000000000040
782            00000000000000000000000000000000000000000000000000000000000000a0
783            0000000000000000000000000000000000000000000000000000000000000002
784            0000000000000000000000001111111111111111111111111111111111111111
785            0000000000000000000000002222222222222222222222222222222222222222
786            0000000000000000000000000000000000000000000000000000000000000002
787            0000000000000000000000003333333333333333333333333333333333333333
788            0000000000000000000000004444444444444444444444444444444444444444
789        "),
790
791        fixed_array_of_fixed_arrays("address[2][2]", "
792            0000000000000000000000001111111111111111111111111111111111111111
793            0000000000000000000000002222222222222222222222222222222222222222
794            0000000000000000000000003333333333333333333333333333333333333333
795            0000000000000000000000004444444444444444444444444444444444444444
796        "),
797
798        fixed_array_of_static_tuples_followed_by_dynamic_type("((uint256,uint256,address)[2],string)", "
799            0000000000000000000000000000000000000000000000000000000005930cc5
800            0000000000000000000000000000000000000000000000000000000015002967
801            0000000000000000000000004444444444444444444444444444444444444444
802            000000000000000000000000000000000000000000000000000000000000307b
803            00000000000000000000000000000000000000000000000000000000000001c3
804            0000000000000000000000002222222222222222222222222222222222222222
805            00000000000000000000000000000000000000000000000000000000000000e0
806            0000000000000000000000000000000000000000000000000000000000000009
807            6761766f66796f726b0000000000000000000000000000000000000000000000
808        "),
809
810        empty_array("address[]", "
811            0000000000000000000000000000000000000000000000000000000000000020
812            0000000000000000000000000000000000000000000000000000000000000000
813        "),
814
815        empty_array_2("(address[],address[])", "
816            0000000000000000000000000000000000000000000000000000000000000040
817            0000000000000000000000000000000000000000000000000000000000000060
818            0000000000000000000000000000000000000000000000000000000000000000
819            0000000000000000000000000000000000000000000000000000000000000000
820        "),
821
822        // Nested empty arrays
823        empty_array_3("(address[][],address[][])", "
824            0000000000000000000000000000000000000000000000000000000000000040
825            00000000000000000000000000000000000000000000000000000000000000a0
826            0000000000000000000000000000000000000000000000000000000000000001
827            0000000000000000000000000000000000000000000000000000000000000020
828            0000000000000000000000000000000000000000000000000000000000000000
829            0000000000000000000000000000000000000000000000000000000000000001
830            0000000000000000000000000000000000000000000000000000000000000020
831            0000000000000000000000000000000000000000000000000000000000000000
832        "),
833
834        fixed_bytes("bytes2", "1234000000000000000000000000000000000000000000000000000000000000"),
835
836        string("string", "
837            0000000000000000000000000000000000000000000000000000000000000020
838            0000000000000000000000000000000000000000000000000000000000000009
839            6761766f66796f726b0000000000000000000000000000000000000000000000
840        "),
841
842        bytes("bytes", "
843            0000000000000000000000000000000000000000000000000000000000000020
844            0000000000000000000000000000000000000000000000000000000000000002
845            1234000000000000000000000000000000000000000000000000000000000000
846        "),
847
848        bytes_2("bytes", "
849            0000000000000000000000000000000000000000000000000000000000000020
850            000000000000000000000000000000000000000000000000000000000000001f
851            1000000000000000000000000000000000000000000000000000000000000200
852        "),
853
854        bytes_3("bytes", "
855            0000000000000000000000000000000000000000000000000000000000000020
856            0000000000000000000000000000000000000000000000000000000000000040
857            1000000000000000000000000000000000000000000000000000000000000000
858            1000000000000000000000000000000000000000000000000000000000000000
859        "),
860
861        two_bytes("(bytes,bytes)", "
862            0000000000000000000000000000000000000000000000000000000000000040
863            0000000000000000000000000000000000000000000000000000000000000080
864            000000000000000000000000000000000000000000000000000000000000001f
865            1000000000000000000000000000000000000000000000000000000000000200
866            0000000000000000000000000000000000000000000000000000000000000020
867            0010000000000000000000000000000000000000000000000000000000000002
868        "),
869
870        uint("uint256", "0000000000000000000000000000000000000000000000000000000000000004"),
871
872        int("int256", "0000000000000000000000000000000000000000000000000000000000000004"),
873
874        bool("bool", "0000000000000000000000000000000000000000000000000000000000000001"),
875
876        bool2("bool", "0000000000000000000000000000000000000000000000000000000000000000"),
877
878        comprehensive_test("(uint8,bytes,uint8,bytes)", "
879            0000000000000000000000000000000000000000000000000000000000000005
880            0000000000000000000000000000000000000000000000000000000000000080
881            0000000000000000000000000000000000000000000000000000000000000003
882            00000000000000000000000000000000000000000000000000000000000000e0
883            0000000000000000000000000000000000000000000000000000000000000040
884            131a3afc00d1b1e3461b955e53fc866dcf303b3eb9f4c16f89e388930f48134b
885            131a3afc00d1b1e3461b955e53fc866dcf303b3eb9f4c16f89e388930f48134b
886            0000000000000000000000000000000000000000000000000000000000000040
887            131a3afc00d1b1e3461b955e53fc866dcf303b3eb9f4c16f89e388930f48134b
888            131a3afc00d1b1e3461b955e53fc866dcf303b3eb9f4c16f89e388930f48134b
889        "),
890
891        comprehensive_test2("(bool,string,uint8,uint8,uint8,uint8[])", "
892            0000000000000000000000000000000000000000000000000000000000000001
893            00000000000000000000000000000000000000000000000000000000000000c0
894            0000000000000000000000000000000000000000000000000000000000000002
895            0000000000000000000000000000000000000000000000000000000000000003
896            0000000000000000000000000000000000000000000000000000000000000004
897            0000000000000000000000000000000000000000000000000000000000000100
898            0000000000000000000000000000000000000000000000000000000000000009
899            6761766f66796f726b0000000000000000000000000000000000000000000000
900            0000000000000000000000000000000000000000000000000000000000000003
901            0000000000000000000000000000000000000000000000000000000000000005
902            0000000000000000000000000000000000000000000000000000000000000006
903            0000000000000000000000000000000000000000000000000000000000000007
904        "),
905
906        dynamic_array_of_bytes("bytes[]", "
907            0000000000000000000000000000000000000000000000000000000000000020
908            0000000000000000000000000000000000000000000000000000000000000001
909            0000000000000000000000000000000000000000000000000000000000000020
910            0000000000000000000000000000000000000000000000000000000000000026
911            019c80031b20d5e69c8093a571162299032018d913930d93ab320ae5ea44a421
912            8a274f00d6070000000000000000000000000000000000000000000000000000
913        "),
914
915        dynamic_array_of_bytes2("bytes[]", "
916            0000000000000000000000000000000000000000000000000000000000000020
917            0000000000000000000000000000000000000000000000000000000000000002
918            0000000000000000000000000000000000000000000000000000000000000040
919            00000000000000000000000000000000000000000000000000000000000000a0
920            0000000000000000000000000000000000000000000000000000000000000026
921            4444444444444444444444444444444444444444444444444444444444444444
922            4444444444440000000000000000000000000000000000000000000000000000
923            0000000000000000000000000000000000000000000000000000000000000026
924            6666666666666666666666666666666666666666666666666666666666666666
925            6666666666660000000000000000000000000000000000000000000000000000
926        "),
927
928        static_tuple_of_addresses("(address,address)", "
929            0000000000000000000000001111111111111111111111111111111111111111
930            0000000000000000000000002222222222222222222222222222222222222222
931        "),
932
933        dynamic_tuple("((string,string),)", "
934            0000000000000000000000000000000000000000000000000000000000000020
935            0000000000000000000000000000000000000000000000000000000000000040
936            0000000000000000000000000000000000000000000000000000000000000080
937            0000000000000000000000000000000000000000000000000000000000000009
938            6761766f66796f726b0000000000000000000000000000000000000000000000
939            0000000000000000000000000000000000000000000000000000000000000009
940            6761766f66796f726b0000000000000000000000000000000000000000000000
941        "),
942
943        dynamic_tuple_of_bytes("((bytes,bytes),)", "
944            0000000000000000000000000000000000000000000000000000000000000020
945            0000000000000000000000000000000000000000000000000000000000000040
946            00000000000000000000000000000000000000000000000000000000000000a0
947            0000000000000000000000000000000000000000000000000000000000000026
948            4444444444444444444444444444444444444444444444444444444444444444
949            4444444444440000000000000000000000000000000000000000000000000000
950            0000000000000000000000000000000000000000000000000000000000000026
951            6666666666666666666666666666666666666666666666666666666666666666
952            6666666666660000000000000000000000000000000000000000000000000000
953        "),
954
955        complex_tuple("((uint256,string,address,address),)", "
956            0000000000000000000000000000000000000000000000000000000000000020
957            1111111111111111111111111111111111111111111111111111111111111111
958            0000000000000000000000000000000000000000000000000000000000000080
959            0000000000000000000000001111111111111111111111111111111111111111
960            0000000000000000000000002222222222222222222222222222222222222222
961            0000000000000000000000000000000000000000000000000000000000000009
962            6761766f66796f726b0000000000000000000000000000000000000000000000
963        "),
964
965        nested_tuple("((string,bool,string,(string,string,(string,string))),)", "
966            0000000000000000000000000000000000000000000000000000000000000020
967            0000000000000000000000000000000000000000000000000000000000000080
968            0000000000000000000000000000000000000000000000000000000000000001
969            00000000000000000000000000000000000000000000000000000000000000c0
970            0000000000000000000000000000000000000000000000000000000000000100
971            0000000000000000000000000000000000000000000000000000000000000004
972            7465737400000000000000000000000000000000000000000000000000000000
973            0000000000000000000000000000000000000000000000000000000000000006
974            6379626f72670000000000000000000000000000000000000000000000000000
975            0000000000000000000000000000000000000000000000000000000000000060
976            00000000000000000000000000000000000000000000000000000000000000a0
977            00000000000000000000000000000000000000000000000000000000000000e0
978            0000000000000000000000000000000000000000000000000000000000000005
979            6e69676874000000000000000000000000000000000000000000000000000000
980            0000000000000000000000000000000000000000000000000000000000000003
981            6461790000000000000000000000000000000000000000000000000000000000
982            0000000000000000000000000000000000000000000000000000000000000040
983            0000000000000000000000000000000000000000000000000000000000000080
984            0000000000000000000000000000000000000000000000000000000000000004
985            7765656500000000000000000000000000000000000000000000000000000000
986            0000000000000000000000000000000000000000000000000000000000000008
987            66756e7465737473000000000000000000000000000000000000000000000000
988        "),
989
990        params_containing_dynamic_tuple("(address,(bool,string,string),address,address,bool)", "
991            0000000000000000000000002222222222222222222222222222222222222222
992            00000000000000000000000000000000000000000000000000000000000000a0
993            0000000000000000000000003333333333333333333333333333333333333333
994            0000000000000000000000004444444444444444444444444444444444444444
995            0000000000000000000000000000000000000000000000000000000000000000
996            0000000000000000000000000000000000000000000000000000000000000001
997            0000000000000000000000000000000000000000000000000000000000000060
998            00000000000000000000000000000000000000000000000000000000000000a0
999            0000000000000000000000000000000000000000000000000000000000000009
1000            7370616365736869700000000000000000000000000000000000000000000000
1001            0000000000000000000000000000000000000000000000000000000000000006
1002            6379626f72670000000000000000000000000000000000000000000000000000
1003        "),
1004
1005        params_containing_static_tuple("(address,(address,bool,bool),address,address)", "
1006            0000000000000000000000001111111111111111111111111111111111111111
1007            0000000000000000000000002222222222222222222222222222222222222222
1008            0000000000000000000000000000000000000000000000000000000000000001
1009            0000000000000000000000000000000000000000000000000000000000000000
1010            0000000000000000000000003333333333333333333333333333333333333333
1011            0000000000000000000000004444444444444444444444444444444444444444
1012        "),
1013
1014        dynamic_tuple_with_nested_static_tuples("((((bool,uint16),),uint16[]),)", "
1015            0000000000000000000000000000000000000000000000000000000000000020
1016            0000000000000000000000000000000000000000000000000000000000000000
1017            0000000000000000000000000000000000000000000000000000000000000777
1018            0000000000000000000000000000000000000000000000000000000000000060
1019            0000000000000000000000000000000000000000000000000000000000000002
1020            0000000000000000000000000000000000000000000000000000000000000042
1021            0000000000000000000000000000000000000000000000000000000000001337
1022        "),
1023
1024        // https://github.com/foundry-rs/book/issues/1286
1025        tuple_array("((uint256,)[],uint256)", "
1026            0000000000000000000000000000000000000000000000000000000000000040
1027            000000000000000000000000000000000000000000000000000000000000007b
1028            0000000000000000000000000000000000000000000000000000000000000001
1029            0000000000000000000000000000000000000000000000000000000000000001
1030        "),
1031        nested_tuple_array("(((uint256,)[],uint256),)", "
1032            0000000000000000000000000000000000000000000000000000000000000020
1033            0000000000000000000000000000000000000000000000000000000000000040
1034            000000000000000000000000000000000000000000000000000000000000007b
1035            0000000000000000000000000000000000000000000000000000000000000001
1036            0000000000000000000000000000000000000000000000000000000000000001
1037        "),
1038    }
1039
1040    // https://github.com/alloy-rs/core/issues/392
1041    #[test]
1042    fn zst_dos() {
1043        let my_type: DynSolType = "()[]".parse().unwrap();
1044        let value = my_type.abi_decode(&hex!("000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000FFFFFFFF"));
1045        assert_eq!(value, Ok(DynSolValue::Array(vec![])));
1046    }
1047
1048    #[test]
1049    #[cfg_attr(miri, ignore = "takes too long")]
1050    fn recursive_dos() {
1051        // https://github.com/alloy-rs/core/issues/490
1052        let payload = "0000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000000a0000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000020";
1053
1054        // Used to eat 60 gb of memory and then crash.
1055        let my_type: DynSolType = "uint256[][][][][][][][][][]".parse().unwrap();
1056        let decoded = my_type.abi_decode(&hex::decode(payload).unwrap());
1057        assert_eq!(decoded, Err(alloy_sol_types::Error::RecursionLimitExceeded(16).into()));
1058
1059        // https://github.com/paulmillr/micro-eth-signer/discussions/20
1060        let payload = &"0000000000000000000000000000000000000000000000000000000000000020\
1061             000000000000000000000000000000000000000000000000000000000000000a\
1062             0000000000000000000000000000000000000000000000000000000000000020"
1063            .repeat(64);
1064        let my_type: DynSolType = "uint256[][][][][][][][][][]".parse().unwrap();
1065        let decoded = my_type.abi_decode(&hex::decode(payload).unwrap());
1066        assert_eq!(decoded, Err(alloy_sol_types::Error::RecursionLimitExceeded(16).into()));
1067
1068        let my_type: DynSolType = "bytes[][][][][][][][][][]".parse().unwrap();
1069        let decoded = my_type.abi_decode(&hex::decode(payload).unwrap());
1070        assert_eq!(decoded, Err(alloy_sol_types::Error::RecursionLimitExceeded(16).into()));
1071    }
1072
1073    // https://github.com/alloy-rs/core/issues/490
1074    #[test]
1075    fn large_dyn_array_dos() {
1076        let payload = "000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000FFFFFFFF";
1077
1078        // Used to eat 60 gb of memory.
1079        let my_type: DynSolType = "uint32[1][]".parse().unwrap();
1080        let decoded = my_type.abi_decode(&hex::decode(payload).unwrap());
1081        assert_eq!(decoded, Err(alloy_sol_types::Error::Overrun.into()))
1082    }
1083
1084    #[test]
1085    fn fixed_array_dos() {
1086        let t = "uint32[9999999999]".parse::<DynSolType>().unwrap();
1087        let decoded = t.abi_decode(&[]);
1088        assert_eq!(decoded, Err(alloy_sol_types::Error::Overrun.into()))
1089    }
1090
1091    macro_rules! packed_tests {
1092        ($($name:ident($ty:literal, $v:literal, $encoded:literal)),* $(,)?) => {
1093            mod packed {
1094                use super::*;
1095
1096                $(
1097                    #[test]
1098                    fn $name() {
1099                        packed_test($ty, $v, &hex!($encoded));
1100                    }
1101                )*
1102            }
1103        };
1104    }
1105
1106    fn packed_test(t_s: &str, v_s: &str, expected: &[u8]) {
1107        let ty: DynSolType = t_s.parse().expect("parsing failed");
1108        assert_eq!(ty.sol_type_name(), t_s, "type names are not the same");
1109
1110        let value = match ty.coerce_str(v_s) {
1111            Ok(v) => v,
1112            Err(e) => {
1113                panic!("failed to coerce to a value: {e}");
1114            }
1115        };
1116        if let Some(value_name) = value.sol_type_name() {
1117            assert_eq!(value_name, t_s, "value names are not the same");
1118        }
1119
1120        let packed = value.abi_encode_packed();
1121        assert!(
1122            packed == expected,
1123            "
1124    type: {ty}
1125   value: {value:?}
1126  packed: {packed}
1127expected: {expected}",
1128            packed = hex::encode(packed),
1129            expected = hex::encode(expected),
1130        );
1131    }
1132
1133    packed_tests! {
1134        address("address", "1111111111111111111111111111111111111111", "1111111111111111111111111111111111111111"),
1135
1136        bool_false("bool", "false", "00"),
1137        bool_true("bool", "true", "01"),
1138
1139        int8_1("int8", "0", "00"),
1140        int8_2("int8", "1", "01"),
1141        int8_3("int8", "16", "10"),
1142        int8_4("int8", "127", "7f"),
1143        neg_int8_1("int8", "-1", "ff"),
1144        neg_int8_2("int8", "-16", "f0"),
1145        neg_int8_3("int8", "-127", "81"),
1146        neg_int8_4("int8", "-128", "80"),
1147
1148        int16_1("int16", "0", "0000"),
1149        int16_2("int16", "1", "0001"),
1150        int16_3("int16", "16", "0010"),
1151        int16_4("int16", "127", "007f"),
1152        int16_5("int16", "128", "0080"),
1153        int16_6("int16", "8192", "2000"),
1154        int16_7("int16", "32767", "7fff"),
1155        neg_int16_1("int16", "-1", "ffff"),
1156        neg_int16_2("int16", "-16", "fff0"),
1157        neg_int16_3("int16", "-127", "ff81"),
1158        neg_int16_4("int16", "-128", "ff80"),
1159        neg_int16_5("int16", "-129", "ff7f"),
1160        neg_int16_6("int16", "-32767", "8001"),
1161        neg_int16_7("int16", "-32768", "8000"),
1162
1163        int32_1("int32", "0", "00000000"),
1164        int32_2("int32", "-1", "ffffffff"),
1165        int64_1("int64", "0", "0000000000000000"),
1166        int64_2("int64", "-1", "ffffffffffffffff"),
1167        int128_1("int128", "0", "00000000000000000000000000000000"),
1168        int128_2("int128", "-1", "ffffffffffffffffffffffffffffffff"),
1169        int256_1("int256", "0", "0000000000000000000000000000000000000000000000000000000000000000"),
1170        int256_2("int256", "-1", "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),
1171
1172        uint8_1("uint8", "0", "00"),
1173        uint8_2("uint8", "1", "01"),
1174        uint8_3("uint8", "16", "10"),
1175        uint16("uint16", "0", "0000"),
1176        uint32("uint32", "0", "00000000"),
1177        uint64("uint64", "0", "0000000000000000"),
1178        uint128("uint128", "0", "00000000000000000000000000000000"),
1179        uint256_1("uint256", "0", "0000000000000000000000000000000000000000000000000000000000000000"),
1180        uint256_2("uint256", "42", "000000000000000000000000000000000000000000000000000000000000002a"),
1181        uint256_3("uint256", "115792089237316195423570985008687907853269984665640564039457584007913129639935", "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),
1182
1183        string_1("string", "a", "61"),
1184        string_2("string", "ab", "6162"),
1185        string_3("string", "abc", "616263"),
1186
1187        bytes_1("bytes", "00", "00"),
1188        bytes_2("bytes", "0001", "0001"),
1189        bytes_3("bytes", "000102", "000102"),
1190
1191        fbytes_1("bytes1", "00", "00"),
1192        fbytes_2("bytes2", "1234", "1234"),
1193        fbytes_3("(address,bytes20)", "(\
1194            1111111111111111111111111111111111111111,\
1195            2222222222222222222222222222222222222222\
1196        )", "
1197            1111111111111111111111111111111111111111
1198            2222222222222222222222222222222222222222
1199        "),
1200        fbytes_4("bytes20[]", "[\
1201            1111111111111111111111111111111111111111,\
1202            2222222222222222222222222222222222222222\
1203        ]", "
1204            0000000000000000000000001111111111111111111111111111111111111111
1205            0000000000000000000000002222222222222222222222222222222222222222
1206        "),
1207        fbytes_5("bytes20[2]", "[\
1208            1111111111111111111111111111111111111111,\
1209            2222222222222222222222222222222222222222\
1210        ]", "
1211            0000000000000000000000001111111111111111111111111111111111111111
1212            0000000000000000000000002222222222222222222222222222222222222222
1213        "),
1214
1215        dynamic_array_of_addresses("address[]", "[\
1216            1111111111111111111111111111111111111111,\
1217            2222222222222222222222222222222222222222\
1218        ]", "
1219            0000000000000000000000001111111111111111111111111111111111111111
1220            0000000000000000000000002222222222222222222222222222222222222222
1221        "),
1222
1223        fixed_array_of_addresses("address[2]", "[\
1224            1111111111111111111111111111111111111111,\
1225            2222222222222222222222222222222222222222\
1226        ]", "
1227            0000000000000000000000001111111111111111111111111111111111111111
1228            0000000000000000000000002222222222222222222222222222222222222222
1229        "),
1230
1231        two_addresses("(address,address)", "(\
1232            1111111111111111111111111111111111111111,\
1233            2222222222222222222222222222222222222222\
1234        )", "
1235            1111111111111111111111111111111111111111
1236            2222222222222222222222222222222222222222
1237        "),
1238
1239        fixed_array_of_dynamic_arrays_of_addresses("address[][2]", "[\
1240            [1111111111111111111111111111111111111111, 2222222222222222222222222222222222222222],\
1241            [3333333333333333333333333333333333333333, 4444444444444444444444444444444444444444]\
1242        ]", "
1243            0000000000000000000000001111111111111111111111111111111111111111
1244            0000000000000000000000002222222222222222222222222222222222222222
1245            0000000000000000000000003333333333333333333333333333333333333333
1246            0000000000000000000000004444444444444444444444444444444444444444
1247        "),
1248
1249        dynamic_array_of_fixed_arrays_of_addresses("address[2][]", "[\
1250            [1111111111111111111111111111111111111111, 2222222222222222222222222222222222222222],\
1251            [3333333333333333333333333333333333333333, 4444444444444444444444444444444444444444]\
1252        ]", "
1253            0000000000000000000000001111111111111111111111111111111111111111
1254            0000000000000000000000002222222222222222222222222222222222222222
1255            0000000000000000000000003333333333333333333333333333333333333333
1256            0000000000000000000000004444444444444444444444444444444444444444
1257        "),
1258
1259        dynamic_array_of_dynamic_arrays("address[][]", "[\
1260            [1111111111111111111111111111111111111111],\
1261            [2222222222222222222222222222222222222222]\
1262        ]", "
1263            0000000000000000000000001111111111111111111111111111111111111111
1264            0000000000000000000000002222222222222222222222222222222222222222
1265        "),
1266
1267        dynamic_array_of_dynamic_arrays2("address[][]", "[\
1268            [1111111111111111111111111111111111111111, 2222222222222222222222222222222222222222],\
1269            [3333333333333333333333333333333333333333, 4444444444444444444444444444444444444444]\
1270        ]", "
1271            0000000000000000000000001111111111111111111111111111111111111111
1272            0000000000000000000000002222222222222222222222222222222222222222
1273            0000000000000000000000003333333333333333333333333333333333333333
1274            0000000000000000000000004444444444444444444444444444444444444444
1275        "),
1276
1277        dynamic_array_of_dynamic_arrays3("uint32[][]", "[\
1278            [1, 2],\
1279            [3, 4]\
1280        ]", "
1281            0000000000000000000000000000000000000000000000000000000000000001
1282            0000000000000000000000000000000000000000000000000000000000000002
1283            0000000000000000000000000000000000000000000000000000000000000003
1284            0000000000000000000000000000000000000000000000000000000000000004
1285        "),
1286    }
1287}