Enum alloy_dyn_abi::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§

impl Arbitrary for DynSolType

Available on crate feature arbitrary only.
§

type Parameters = (u32, u32, u32)

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

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

§

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

This method tests for self and other values to be equal, and is used by ==.
1.0.0 · source§

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

This method 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> 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,

§

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>,

§

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>,

§

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