Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Prestwich/ingest encode type #15

Merged
merged 7 commits into from
Apr 25, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 16 additions & 7 deletions abi/sol-type-parser/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
use proc_macro::TokenStream as TS;
use proc_macro2::TokenStream;
use syn::{parse::Parse, parse_macro_input, token::Struct, Token};
use syn::{
parse::{discouraged::Speculative, Parse},
parse_macro_input,
};

use quote::{quote, ToTokens};

Expand All @@ -21,13 +24,19 @@ enum SolInput {

impl Parse for SolInput {
fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> {
if input.peek(Struct) {
Ok(SolInput::StructDef(input.parse()?))
} else if input.peek(Token![type]) {
Ok(SolInput::ValueTypeDef(input.parse()?))
} else {
Ok(SolInput::Type(input.parse()?))
let fork = input.fork();
if let Ok(sol_ty) = fork.parse::<SolType>() {
input.advance_to(&fork);
return Ok(SolInput::Type(sol_ty));
}

let fork = input.fork();
if let Ok(udt) = fork.parse::<Udt>() {
input.advance_to(&fork);
return Ok(SolInput::ValueTypeDef(udt));
}

Ok(SolInput::StructDef(input.parse()?))
}
}

Expand Down
13 changes: 9 additions & 4 deletions abi/sol-type-parser/src/struct.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ use syn::{
parse::Parse,
punctuated::Punctuated,
token::{Brace, Struct},
Ident, Index, Token,
Attribute, Ident, Index, Token,
};

#[derive(Debug, Clone)]
Expand Down Expand Up @@ -42,6 +42,7 @@ impl ToTokens for SolStructField {
}

pub struct SolStructDef {
attrs: Vec<Attribute>,
_struct: Struct,
name: Ident,
_brace: Brace,
Expand All @@ -52,6 +53,7 @@ impl Parse for SolStructDef {
fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> {
let content;
Ok(Self {
attrs: input.call(Attribute::parse_outer)?,
_struct: input.parse()?,
name: input.parse()?,
_brace: braced!(content in input),
Expand All @@ -76,12 +78,12 @@ impl SolStructDef {
.unzip();

quote! {
type UnderlyingSolTuple = (#(#field_ty),*);
type UnderlyingRustTuple = (#(<#field_ty2 as ::ethers_abi_enc::SolType>::RustType),*);
type UnderlyingSolTuple = (#(#field_ty,)*);
type UnderlyingRustTuple = (#(<#field_ty2 as ::ethers_abi_enc::SolType>::RustType,)*);

impl From<#name> for UnderlyingRustTuple {
fn from(value: #name) -> UnderlyingRustTuple {
(#(value.#field_names),*)
(#(value.#field_names,)*)
}
}

Expand Down Expand Up @@ -147,9 +149,12 @@ impl SolStructDef {
)*].concat()
}
};
let attrs = self.attrs.iter();

quote! {
#[doc = #doc]
#(#attrs)*
#[allow(non_snake_case)]
#[derive(Debug, Clone, PartialEq)]
pub struct #name {
#(pub #fields),*
Expand Down
4 changes: 4 additions & 0 deletions abi/sol-type-parser/src/udt.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ mod kw {
}

pub struct Udt {
attrs: Vec<syn::Attribute>,
_type: syn::Token![type],
name: syn::Ident,
_is: kw::is,
Expand All @@ -18,6 +19,7 @@ pub struct Udt {
impl Parse for Udt {
fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> {
Ok(Udt {
attrs: input.call(syn::Attribute::parse_outer)?,
_type: input.parse()?,
name: input.parse()?,
_is: input.parse()?,
Expand All @@ -32,13 +34,15 @@ impl ToTokens for Udt {
let name = &self.name;
let mod_name = syn::Ident::new(&format!("__{}", name), name.span());
let ty = &self.ty;
let attrs = self.attrs.iter();
tokens.extend(quote! {
pub use #mod_name::#name;
#[allow(non_snake_case)]
mod #mod_name {
use ::ethers_abi_enc::define_udt;
define_udt! {
/// A solidity user-defined type
#(#attrs)*
#name,
underlying: #ty,
}
Expand Down
9 changes: 1 addition & 8 deletions abi/src/coder/encoder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -194,7 +194,7 @@ mod tests {

#[cfg(not(feature = "std"))]
use crate::no_std_prelude::*;
use crate::{sol_type, util::pad_u32, SolType, TokenType};
use crate::{sol_type, util::pad_u32, SolType};

#[test]
fn encode_address() {
Expand Down Expand Up @@ -261,7 +261,6 @@ mod tests {
#[test]
fn encode_fixed_array_of_dynamic_array_of_addresses() {
type MyTy = sol_type::FixedArray<sol_type::Array<sol_type::Address>, 2>;
dbg!(MyTy::sol_type_name());
let fixed = [
vec![B160([0x11u8; 20]), B160([0x22u8; 20])],
vec![B160([0x33u8; 20]), B160([0x44u8; 20])],
Expand Down Expand Up @@ -827,12 +826,6 @@ mod tests {
type MyTy = (sol_type::String, sol_type::String);
let data = ("gavofyork".to_string(), "gavofyork".to_string());

let tok1 = <(MyTy,)>::tokenize((data.clone(),));
let tok2 = <MyTy>::tokenize(data.clone());

dbg!(tok1.head_words());
dbg!(tok2.head_words());

let expected = hex!(
"
0000000000000000000000000000000000000000000000000000000000000020
Expand Down
86 changes: 46 additions & 40 deletions abi/src/util.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,6 @@

//! Utils used by different modules.

use ethers_primitives::U256;
use serde::{Deserialize, Deserializer};

use crate::{AbiResult, Error, Word};

/// Converts a u32 to a right aligned array of 32 bytes.
Expand Down Expand Up @@ -80,49 +77,58 @@ pub(crate) fn check_bool(slice: Word) -> bool {
check_zeroes(&slice[..31])
}

/// Helper type to parse numeric strings, `u64` and `U256`
#[derive(serde::Deserialize, Debug, Clone)]
#[serde(untagged)]
pub(crate) enum StringifiedNumeric {
String(String),
U256(U256),
Num(u64),
}
#[cfg(feature = "eip712-serde")]
pub(crate) use serde_helper::*;

#[cfg(feature = "eip712-serde")]
mod serde_helper {
use ethers_primitives::U256;
use serde::{Deserialize, Deserializer};

/// Helper type to parse numeric strings, `u64` and `U256`
#[derive(serde::Deserialize, Debug, Clone)]
#[serde(untagged)]
pub(crate) enum StringifiedNumeric {
String(String),
U256(U256),
Num(u64),
}

impl TryFrom<StringifiedNumeric> for U256 {
type Error = String;

fn try_from(value: StringifiedNumeric) -> Result<Self, Self::Error> {
match value {
StringifiedNumeric::U256(n) => Ok(n),
StringifiedNumeric::Num(n) => Ok(U256::from(n)),
StringifiedNumeric::String(s) => {
if let Ok(val) = s.parse::<u128>() {
Ok(U256::from(val))
} else if s.starts_with("0x") {
U256::from_str_radix(s.strip_prefix("0x").unwrap(), 16)
.map_err(|err| err.to_string())
} else {
U256::from_str_radix(&s, 10).map_err(|err| err.to_string())
impl TryFrom<StringifiedNumeric> for U256 {
type Error = String;

fn try_from(value: StringifiedNumeric) -> Result<Self, Self::Error> {
match value {
StringifiedNumeric::U256(n) => Ok(n),
StringifiedNumeric::Num(n) => Ok(U256::from(n)),
StringifiedNumeric::String(s) => {
if let Ok(val) = s.parse::<u128>() {
Ok(U256::from(val))
} else if s.starts_with("0x") {
U256::from_str_radix(s.strip_prefix("0x").unwrap(), 16)
.map_err(|err| err.to_string())
} else {
U256::from_str_radix(&s, 10).map_err(|err| err.to_string())
}
}
}
}
}
}

/// Supports parsing numbers as strings
///
/// See <https://github.com/gakonst/ethers-rs/issues/1507>
pub(crate) fn deserialize_stringified_numeric_opt<'de, D>(
deserializer: D,
) -> Result<Option<U256>, D::Error>
where
D: Deserializer<'de>,
{
if let Some(num) = Option::<StringifiedNumeric>::deserialize(deserializer)? {
num.try_into().map(Some).map_err(serde::de::Error::custom)
} else {
Ok(None)
/// Supports parsing numbers as strings
///
/// See <https://github.com/gakonst/ethers-rs/issues/1507>
pub(crate) fn deserialize_stringified_numeric_opt<'de, D>(
deserializer: D,
) -> Result<Option<U256>, D::Error>
where
D: Deserializer<'de>,
{
if let Some(num) = Option::<StringifiedNumeric>::deserialize(deserializer)? {
num.try_into().map(Some).map_err(serde::de::Error::custom)
} else {
Ok(None)
}
}
}

Expand Down
8 changes: 8 additions & 0 deletions abi/tests/proc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,14 @@ use ethers_abi_enc::{sol, SolStruct, SolType};

use ethers_primitives::{B160, U256};

sol!(
/// Hello this is extra docs
#[derive(Hash)]
struct MySingleProp {
uint256 a;
}
);

sol! {
struct MyStruct {
uint256 a;
Expand Down
25 changes: 24 additions & 1 deletion dyn-abi/src/eip712/parser.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,9 @@
use crate::{no_std_prelude::*, parser::TypeSpecifier, DynAbiError};
use crate::{
eip712::resolver::{PropertyDef, TypeDef},
no_std_prelude::*,
parser::TypeSpecifier,
DynAbiError,
};

/// A property is a type and a name. Of the form `type name`. E.g.
/// `uint256 foo` or `(MyStruct[23],bool) bar`.
Expand All @@ -10,6 +15,13 @@ pub struct PropDef<'a> {
pub name: &'a str,
}

impl PropDef<'_> {
/// Convert to an owned `PropertyDef`
pub fn to_owned(&self) -> PropertyDef {
DaniPopes marked this conversation as resolved.
Show resolved Hide resolved
PropertyDef::new(self.ty.span, self.name).unwrap()
}
}

impl<'a> TryFrom<&'a str> for PropDef<'a> {
type Error = DynAbiError;

Expand Down Expand Up @@ -38,6 +50,17 @@ pub struct ComponentType<'a> {
pub props: Vec<PropDef<'a>>,
}

impl ComponentType<'_> {
/// Convert to an owned TypeDef
pub fn to_owned(&self) -> TypeDef {
TypeDef::new(
self.type_name,
self.props.iter().map(|p| p.to_owned()).collect(),
)
.unwrap()
}
}

// This impl handles
impl<'a> TryFrom<&'a str> for ComponentType<'a> {
type Error = DynAbiError;
Expand Down
Loading