alloy_dyn_abi

Enum DynSolType

Source
pub enum DynSolType {
    Bool,
    Int(usize),
    Uint(usize),
    FixedBytes(usize),
    Address,
    Function,
    Bytes,
    String,
    Array(Box<DynSolType>),
    FixedArray(Box<DynSolType>, usize),
    Tuple(Vec<DynSolType>),
    CustomStruct {
        name: String,
        prop_names: Vec<String>,
        tuple: Vec<DynSolType>,
    },
}
Expand description

A dynamic Solidity type.

Equivalent to an enum wrapper around all implementers of SolType.

This is used to represent Solidity types that are not known at compile time. It is used in conjunction with DynToken and DynSolValue to allow for dynamic ABI encoding and decoding.

§Examples

Parsing Solidity type strings:

use alloy_dyn_abi::DynSolType;

let type_name = "(bool,address)[]";
let ty = DynSolType::parse(type_name)?;
assert_eq!(
    ty,
    DynSolType::Array(Box::new(DynSolType::Tuple(
        vec![DynSolType::Bool, DynSolType::Address,]
    )))
);
assert_eq!(ty.sol_type_name(), type_name);

// alternatively, you can use the FromStr impl
let ty2 = type_name.parse::<DynSolType>()?;
assert_eq!(ty, ty2);

Decoding dynamic types:

use alloy_dyn_abi::{DynSolType, DynSolValue};
use alloy_primitives::U256;

let my_type = DynSolType::Uint(256);
let my_data: DynSolValue = U256::from(183u64).into();

let encoded = my_data.abi_encode();
let decoded = my_type.abi_decode(&encoded)?;

assert_eq!(decoded, my_data);

let my_type = DynSolType::Array(Box::new(my_type));
let my_data = DynSolValue::Array(vec![my_data.clone()]);

let encoded = my_data.abi_encode();
let decoded = my_type.abi_decode(&encoded)?;

assert_eq!(decoded, my_data);

Variants§

§

Bool

Boolean.

§

Int(usize)

Signed Integer.

§

Uint(usize)

Unsigned Integer.

§

FixedBytes(usize)

Fixed-size bytes, up to 32.

§

Address

Address.

§

Function

Function.

§

Bytes

Dynamic bytes.

§

String

String.

§

Array(Box<DynSolType>)

Dynamically sized array.

§

FixedArray(Box<DynSolType>, usize)

Fixed-sized array.

§

Tuple(Vec<DynSolType>)

Tuple.

§

CustomStruct

Available on crate feature eip712 only.

User-defined struct.

Fields

§name: String

Name of the struct.

§prop_names: Vec<String>

Prop names.

§tuple: Vec<DynSolType>

Inner types.

Implementations§

Source§

impl DynSolType

Source

pub fn arbitrary_value(&self, u: &mut Unstructured<'_>) -> Result<DynSolValue>

Available on crate feature arbitrary only.

Generate an arbitrary DynSolValue from this type.

Source

pub fn value_strategy(&self) -> SBoxedStrategy<DynSolValue>

Available on crate feature arbitrary only.

Create a proptest strategy to generate DynSolValues from this type.

Source§

impl DynSolType

Source

pub fn coerce_str(&self, s: &str) -> Result<DynSolValue>

Coerces a string into a DynSolValue via this type.

§Syntax
  • Bool: true|false
  • Int: [+-]?{Uint}
  • Uint: {literal}(\.[0-9]+)?(\s*{unit})?
    • literal: base 2, 8, 10, or 16 integer literal. If not in base 10, must be prefixed with 0b, 0o, or 0x respectively.
    • unit: same as Solidity ether units
    • decimals with more digits than the unit’s exponent value are not allowed
  • FixedBytes: (0x)?[0-9A-Fa-f]{$0*2}
  • Address: (0x)?[0-9A-Fa-f]{40}
  • Function: (0x)?[0-9A-Fa-f]{48}
  • Bytes: (0x)?[0-9A-Fa-f]+
  • String: .*
    • can be surrounded by a pair of " or '
    • trims whitespace if not surrounded
  • Array: any number of the inner type delimited by commas (,) and surrounded by brackets ([])
  • FixedArray: exactly the given number of the inner type delimited by commas (,) and surrounded by brackets ([])
  • Tuple: the inner types delimited by commas (,) and surrounded by parentheses (())
  • CustomStruct: the same as Tuple
§Examples
use alloy_dyn_abi::{DynSolType, DynSolValue};
use alloy_primitives::U256;

let ty: DynSolType = "(uint256,string)[]".parse()?;
let value = ty.coerce_str("[(0, \"hello\"), (42, \"world\")]")?;
assert_eq!(
    value,
    DynSolValue::Array(vec![
        DynSolValue::Tuple(vec![
            DynSolValue::Uint(U256::from(0), 256),
            DynSolValue::String(String::from("hello"))
        ]),
        DynSolValue::Tuple(vec![
            DynSolValue::Uint(U256::from(42), 256),
            DynSolValue::String(String::from("world"))
        ]),
    ])
);
assert!(value.matches(&ty));
assert_eq!(value.as_type().unwrap(), ty);
Source§

impl DynSolType

Source

pub fn parse(s: &str) -> Result<Self>

Parses a Solidity type name string into a DynSolType.

§Examples
let type_name = "uint256";
let ty = DynSolType::parse(type_name)?;
assert_eq!(ty, DynSolType::Uint(256));
assert_eq!(ty.sol_type_name(), type_name);
assert_eq!(ty.to_string(), type_name);

// alternatively, you can use the FromStr impl
let ty2 = type_name.parse::<DynSolType>()?;
assert_eq!(ty2, ty);
Source

pub fn nesting_depth(&self) -> usize

Calculate the nesting depth of this type. Simple types have a nesting depth of 0, while all other types have a nesting depth of at least 1.

Source

pub fn as_tuple(&self) -> Option<&[Self]>

Fallible cast to the contents of a variant.

Source

pub fn as_custom_struct(&self) -> Option<(&str, &[String], &[Self])>

Fallible cast to the contents of a variant.

Source

pub fn has_custom_struct(&self) -> bool

Returns whether this type is contains a custom struct.

Source

pub fn matches_many(types: &[Self], values: &[DynSolValue]) -> bool

Check that the given DynSolValues match these types.

See matches for more information.

Source

pub fn matches(&self, value: &DynSolValue) -> bool

Check that the given DynSolValue matches this type.

Note: this will not check any names, but just the types; e.g for CustomStruct, when the “eip712” feature is enabled, this will only check equality between the lengths and types of the tuple.

Source

pub fn detokenize(&self, token: DynToken<'_>) -> Result<DynSolValue>

Dynamic detokenization.

Source

pub fn sol_type_name(&self) -> Cow<'static, str>

The Solidity type name. This returns the Solidity type corresponding to this value, if it is known. A type will not be known if the value contains an empty sequence, e.g. T[0].

Source

pub fn to_string(&self) -> String

The Solidity type name, as a String.

Note: this shadows the inherent ToString implementation, derived from fmt::Display, for performance reasons.

Source

pub fn abi_decode(&self, data: &[u8]) -> Result<DynSolValue>

Decode a DynSolValue from a byte slice. Fails if the value does not match this type.

This method is used for decoding single values. It assumes the data argument is an encoded single-element sequence wrapping the self type.

Source

pub fn abi_decode_params(&self, data: &[u8]) -> Result<DynSolValue>

Decode a DynSolValue from a byte slice. Fails if the value does not match this type.

This method is used for decoding function arguments. It tries to determine whether the user intended to decode a sequence or an individual value. If the self type is a tuple, the data will be decoded as a sequence, otherwise it will be decoded as a single value.

§Examples
// This function takes a single simple param:
// DynSolType::Uint(256).decode_params(data)
function myFunc(uint256 a) public;

// This function takes 2 params:
// DynSolType::Tuple(vec![DynSolType::Uint(256), DynSolType::Bool])
//     .decode_params(data)
function myFunc(uint256 b, bool c) public;
Source

pub fn abi_decode_sequence(&self, data: &[u8]) -> Result<DynSolValue>

Decode a DynSolValue from a byte slice. Fails if the value does not match this type.

Source

pub fn minimum_words(&self) -> usize

Calculate the minimum number of ABI words necessary to encode this type.

Source

pub fn is_zst(&self) -> bool

Return true if the type is zero-sized, e.g. () or T[0]

Source§

impl DynSolType

Source

pub fn coerce_json(&self, value: &Value) -> Result<DynSolValue>

Available on crate feature eip712 only.

Coerce a serde_json::Value to a DynSolValue via this type.

Trait Implementations§

Source§

impl<'a> Arbitrary<'a> for DynSolType

Available on crate feature arbitrary only.
Source§

fn arbitrary(u: &mut Unstructured<'a>) -> Result<Self>

Generate an arbitrary value of Self from the given unstructured data. Read more
Source§

fn size_hint(depth: usize) -> (usize, Option<usize>)

Get a size hint for how many bytes out of an Unstructured this type needs to construct itself. Read more
Source§

fn arbitrary_take_rest(u: Unstructured<'a>) -> Result<Self, Error>

Generate an arbitrary value of Self from the entirety of the given unstructured data. Read more
Source§

fn try_size_hint( depth: usize, ) -> Result<(usize, Option<usize>), MaxRecursionReached>

Get a size hint for how many bytes out of an Unstructured this type needs to construct itself. Read more
Source§

impl Arbitrary for DynSolType

Available on crate feature arbitrary only.
Source§

type Parameters = (u32, u32, u32)

The type of parameters that arbitrary_with accepts for configuration of the generated Strategy. Parameters must implement Default.
Source§

type Strategy = Recursive<DynSolType, fn(_: BoxedStrategy<DynSolType>) -> TupleUnion<((u32, Arc<BoxedStrategy<DynSolType>>), (u32, Arc<Map<BoxedStrategy<DynSolType>, fn(_: <BoxedStrategy<DynSolType> as Strategy>::Value) -> DynSolType>>), (u32, Arc<Map<(BoxedStrategy<DynSolType>, RangeInclusive<usize>), fn(_: <(BoxedStrategy<DynSolType>, RangeInclusive<usize>) as Strategy>::Value) -> DynSolType>>), (u32, Arc<Map<VecStrategy<BoxedStrategy<DynSolType>>, fn(_: <VecStrategy<BoxedStrategy<DynSolType>> as Strategy>::Value) -> DynSolType>>), (u32, Arc<BoxedStrategy<DynSolType>>))>>

The type of Strategy used to generate values of type Self.
Source§

fn arbitrary() -> Self::Strategy

Generates a Strategy for producing arbitrary values of type the implementing type (Self). Read more
Source§

fn arbitrary_with(args: Self::Parameters) -> Self::Strategy

Generates a Strategy for producing arbitrary values of type the implementing type (Self). The strategy is passed the arguments given in args. Read more
Source§

impl Clone for DynSolType

Source§

fn clone(&self) -> DynSolType

Returns a copy of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for DynSolType

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Display for DynSolType

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl FromStr for DynSolType

Source§

type Err = Error

The associated error which can be returned from parsing.
Source§

fn from_str(s: &str) -> Result<Self, Self::Err>

Parses a string s to return a value of this type. Read more
Source§

impl Hash for DynSolType

Source§

fn hash<__H: Hasher>(&self, state: &mut __H)

Feeds this value into the given Hasher. Read more
1.3.0 · Source§

fn hash_slice<H>(data: &[Self], state: &mut H)
where H: Hasher, Self: Sized,

Feeds a slice of this type into the given Hasher. Read more
Source§

impl PartialEq for DynSolType

Source§

fn eq(&self, other: &DynSolType) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl<T: ?Sized + Specifier<DynSolType>> Specifier<DynSolType> for &T

Source§

fn resolve(&self) -> Result<DynSolType>

Resolve the type into a value.
Source§

impl<T: ?Sized + Specifier<DynSolType>> Specifier<DynSolType> for &mut T

Source§

fn resolve(&self) -> Result<DynSolType>

Resolve the type into a value.
Source§

impl<T: ?Sized + Specifier<DynSolType>> Specifier<DynSolType> for Arc<T>

Source§

fn resolve(&self) -> Result<DynSolType>

Resolve the type into a value.
Source§

impl<T: ?Sized + Specifier<DynSolType>> Specifier<DynSolType> for Box<T>

Source§

fn resolve(&self) -> Result<DynSolType>

Resolve the type into a value.
Source§

impl<T: ?Sized + ToOwned + Specifier<DynSolType>> Specifier<DynSolType> for Cow<'_, T>

Source§

fn resolve(&self) -> Result<DynSolType>

Resolve the type into a value.
Source§

impl Specifier<DynSolType> for EventParam

Source§

fn resolve(&self) -> Result<DynSolType>

Resolve the type into a value.
Source§

impl Specifier<DynSolType> for Param

Source§

fn resolve(&self) -> Result<DynSolType>

Resolve the type into a value.
Source§

impl Specifier<DynSolType> for ParameterSpecifier<'_>

Source§

fn resolve(&self) -> Result<DynSolType>

Resolve the type into a value.
Source§

impl Specifier<DynSolType> for Parameters<'_>

Source§

fn resolve(&self) -> Result<DynSolType>

Resolve the type into a value.
Source§

impl<T: ?Sized + Specifier<DynSolType>> Specifier<DynSolType> for Rc<T>

Source§

fn resolve(&self) -> Result<DynSolType>

Resolve the type into a value.
Source§

impl Specifier<DynSolType> for RootType<'_>

Source§

fn resolve(&self) -> Result<DynSolType>

Resolve the type into a value.
Source§

impl Specifier<DynSolType> for String

Source§

fn resolve(&self) -> Result<DynSolType>

Resolve the type into a value.
Source§

impl Specifier<DynSolType> for TupleSpecifier<'_>

Source§

fn resolve(&self) -> Result<DynSolType>

Resolve the type into a value.
Source§

impl Specifier<DynSolType> for TypeSpecifier<'_>

Source§

fn resolve(&self) -> Result<DynSolType>

Resolve the type into a value.
Source§

impl Specifier<DynSolType> for TypeStem<'_>

Source§

fn resolve(&self) -> Result<DynSolType>

Resolve the type into a value.
Source§

impl Specifier<DynSolType> for str

Source§

fn resolve(&self) -> Result<DynSolType>

Resolve the type into a value.
Source§

impl Eq for DynSolType

Source§

impl StructuralPartialEq for DynSolType

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dst: *mut T)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dst. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T> ToString for T
where T: Display + ?Sized,

Source§

default fn to_string(&self) -> String

Converts the given value to a String. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V