Skip to content
This repository has been archived by the owner on Oct 19, 2024. It is now read-only.

Commit

Permalink
chore: rm allows
Browse files Browse the repository at this point in the history
  • Loading branch information
mattsse committed Oct 9, 2021
1 parent 0c94b58 commit f530288
Show file tree
Hide file tree
Showing 11 changed files with 72 additions and 132 deletions.
9 changes: 3 additions & 6 deletions ethers-contract/ethers-contract-abigen/src/contract.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,16 +10,13 @@ use super::Abigen;
use crate::contract::structs::InternalStructs;
use crate::rawabi::RawAbi;
use anyhow::{anyhow, Context as _, Result};
use ethers_core::{
abi::{parse_abi, Abi, AbiParser},
types::Address,
};
use inflector::Inflector;
use ethers_core::abi::{Abi, AbiParser};

use proc_macro2::{Ident, Literal, TokenStream};
use quote::quote;
use serde::Deserialize;
use std::collections::BTreeMap;
use syn::{Path, Visibility};
use syn::Path;

/// Internal shared context for generating smart contract bindings.
pub(crate) struct Context {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
use super::{util, Context};

use ethers_core::types::Address;
use proc_macro2::{Literal, TokenStream};
use proc_macro2::TokenStream;
use quote::quote;

use super::util::{ethers_contract_crate, ethers_core_crate, ethers_providers_crate};
Expand Down
75 changes: 13 additions & 62 deletions ethers-contract/ethers-contract-abigen/src/contract/events.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use super::{types, util, Context};
use anyhow::Result;
use ethers_core::abi::{Event, EventExt, EventParam, Hash, ParamType, SolStruct};
use ethers_core::abi::{Event, EventExt, EventParam, ParamType, SolStruct};
use inflector::Inflector;
use proc_macro2::{Ident, Literal, TokenStream};
use quote::quote;
Expand Down Expand Up @@ -274,49 +274,6 @@ impl Context {
pub #data_type_definition
})
}

/// Expands a event parameter into an event builder filter method for the
/// specified topic index.
fn expand_builder_topic_filter(
&self,
topic_index: usize,
param: &EventParam,
) -> Result<TokenStream> {
let doc = util::expand_doc(&format!(
"Adds a filter for the `{}` event parameter.",
param.name,
));
let topic = util::ident(&format!("topic{}", topic_index));
let name = if param.name.is_empty() {
topic.clone()
} else {
util::safe_ident(&param.name.to_snake_case())
};
let ty = self.expand_input_type(param)?;

Ok(quote! {
#doc
pub fn #name(mut self, topic: Topic<#ty>) -> Self {
self.0 = (self.0).#topic(topic);
self
}
})
}

/// Expands an ABI event into filter methods for its indexed parameters.
fn expand_builder_topic_filters(&self, event: &Event) -> Result<TokenStream> {
let topic_filters = event
.inputs
.iter()
.filter(|input| input.indexed)
.enumerate()
.map(|(topic_index, input)| self.expand_builder_topic_filter(topic_index, input))
.collect::<Result<Vec<_>>>()?;

Ok(quote! {
#( #topic_filters )*
})
}
}

/// Expands an ABI event into an identifier for its event data type.
Expand Down Expand Up @@ -363,32 +320,26 @@ fn expand_data_tuple(name: &Ident, params: &[(TokenStream, TokenStream, bool)])
quote! { struct #name( #( #fields ),* ); }
}

/// Expands an ABI event into an identifier for its event data type.
fn expand_builder_name(event: &Event) -> TokenStream {
let builder_name = util::ident(&format!("{}Builder", &event.name.to_pascal_case()));
quote! { #builder_name }
}

fn expand_derives(derives: &[Path]) -> TokenStream {
quote! {#(#derives),*}
}

/// Expands a 256-bit `Hash` into a literal representation that can be used with
/// quasi-quoting for code generation. We do this to avoid allocating at runtime
fn expand_hash(hash: Hash) -> TokenStream {
let bytes = hash.as_bytes().iter().copied().map(Literal::u8_unsuffixed);
let ethers_core = util::ethers_core_crate();

quote! {
#ethers_core::types::H256([#( #bytes ),*])
}
}

#[cfg(test)]
mod tests {
use super::*;
use crate::Abigen;
use ethers_core::abi::{EventParam, ParamType};
use ethers_core::abi::{EventParam, Hash, ParamType};

/// Expands a 256-bit `Hash` into a literal representation that can be used with
/// quasi-quoting for code generation. We do this to avoid allocating at runtime
fn expand_hash(hash: Hash) -> TokenStream {
let bytes = hash.as_bytes().iter().copied().map(Literal::u8_unsuffixed);
let ethers_core = util::ethers_core_crate();

quote! {
#ethers_core::types::H256([#( #bytes ),*])
}
}

fn test_context() -> Context {
Context::from_abigen(Abigen::new("TestToken", "[]").unwrap()).unwrap()
Expand Down
86 changes: 43 additions & 43 deletions ethers-contract/ethers-contract-abigen/src/contract/methods.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
use super::{types, util, Context};
use anyhow::{anyhow, Context as _, Result};
use anyhow::{Context as _, Result};
use ethers_core::abi::ParamType;
use ethers_core::{
abi::{Function, FunctionExt, Param, StateMutability},
abi::{Function, FunctionExt, Param},
types::Selector,
};
use inflector::Inflector;
Expand Down Expand Up @@ -129,47 +129,6 @@ impl Context {
}
}

// converts the function params to name/type pairs
pub(crate) fn expand_inputs(inputs: &[Param]) -> Result<TokenStream> {
let params = inputs
.iter()
.enumerate()
.map(|(i, param)| {
let name = util::expand_input_name(i, &param.name);
let kind = types::expand(&param.kind)?;
Ok(quote! { #name: #kind })
})
.collect::<Result<Vec<_>>>()?;
Ok(quote! { #( , #params )* })
}

// packs the argument in a tuple to be used for the contract call
pub(crate) fn expand_inputs_call_arg(inputs: &[Param]) -> TokenStream {
let names = inputs
.iter()
.enumerate()
.map(|(i, param)| {
let name = util::expand_input_name(i, &param.name);
match param.kind {
// this is awkward edge case where the function inputs are a single struct
// we need to force this argument into a tuple so it gets expanded to `((#name,))`
// this is currently necessary because internally `flatten_tokens` is called which removes the outermost `tuple` level
// and since `((#name))` is not a rust tuple it doesn't get wrapped into another tuple that will be peeled off by `flatten_tokens`
ParamType::Tuple(_) if inputs.len() == 1 => {
// make sure the tuple gets converted to `Token::Tuple`
quote! {(#name,)}
}
_ => name,
}
})
.collect::<Vec<TokenStream>>();
match names.len() {
0 => quote! { () },
1 => quote! { #( #names )* },
_ => quote! { ( #(#names, )* ) },
}
}

fn expand_fn_outputs(outputs: &[Param]) -> Result<TokenStream> {
match outputs.len() {
0 => Ok(quote! { () }),
Expand All @@ -194,6 +153,47 @@ mod tests {
use super::*;
use ethers_core::abi::ParamType;

// packs the argument in a tuple to be used for the contract call
fn expand_inputs_call_arg(inputs: &[Param]) -> TokenStream {
let names = inputs
.iter()
.enumerate()
.map(|(i, param)| {
let name = util::expand_input_name(i, &param.name);
match param.kind {
// this is awkward edge case where the function inputs are a single struct
// we need to force this argument into a tuple so it gets expanded to `((#name,))`
// this is currently necessary because internally `flatten_tokens` is called which removes the outermost `tuple` level
// and since `((#name))` is not a rust tuple it doesn't get wrapped into another tuple that will be peeled off by `flatten_tokens`
ParamType::Tuple(_) if inputs.len() == 1 => {
// make sure the tuple gets converted to `Token::Tuple`
quote! {(#name,)}
}
_ => name,
}
})
.collect::<Vec<TokenStream>>();
match names.len() {
0 => quote! { () },
1 => quote! { #( #names )* },
_ => quote! { ( #(#names, )* ) },
}
}

// converts the function params to name/type pairs
fn expand_inputs(inputs: &[Param]) -> Result<TokenStream> {
let params = inputs
.iter()
.enumerate()
.map(|(i, param)| {
let name = util::expand_input_name(i, &param.name);
let kind = types::expand(&param.kind)?;
Ok(quote! { #name: #kind })
})
.collect::<Result<Vec<_>>>()?;
Ok(quote! { #( , #params )* })
}

#[test]
fn test_expand_inputs_call_arg() {
// no inputs
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ use std::collections::{HashMap, VecDeque};

use anyhow::{Context as _, Result};
use inflector::Inflector;
use proc_macro2::{Literal, TokenStream};
use proc_macro2::TokenStream;
use quote::quote;

use ethers_core::abi::{
Expand All @@ -15,7 +15,6 @@ use ethers_core::abi::{
use crate::contract::{types, Context};
use crate::rawabi::{Component, RawAbi};
use crate::util;
use std::any::Any;

impl Context {
/// Generate corresponding types for structs parsed from a human readable ABI
Expand Down Expand Up @@ -193,9 +192,6 @@ impl Context {
/// This is currently used to get access to all the unique solidity structs used as function in/output until `ethabi` supports it as well.
#[derive(Debug, Clone, Default)]
pub struct InternalStructs {
/// All unique internal types that are function inputs or outputs
pub(crate) top_level_internal_types: HashMap<String, Component>,

/// (function name, param name) -> struct which are the identifying properties we get the name from ethabi.
pub(crate) function_params: HashMap<(String, String), String>,

Expand Down Expand Up @@ -269,7 +265,6 @@ impl InternalStructs {
}

Self {
top_level_internal_types,
function_params,
outputs,
structs,
Expand Down
2 changes: 0 additions & 2 deletions ethers-contract/ethers-contract-abigen/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
#![allow(dead_code)]
#![allow(unused_imports)]
#![deny(missing_docs, unsafe_code)]

//! Module for generating type-safe bindings to Ethereum smart contracts. This
Expand Down
2 changes: 1 addition & 1 deletion ethers-contract/ethers-contract-abigen/src/rawabi.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
#![allow(missing_docs)]
use serde::{
de::{EnumAccess, Error, MapAccess, SeqAccess, Visitor},
de::{MapAccess, SeqAccess, Visitor},
Deserialize, Deserializer, Serialize,
};

Expand Down
8 changes: 4 additions & 4 deletions ethers-contract/ethers-contract-abigen/src/source.rs
Original file line number Diff line number Diff line change
Expand Up @@ -113,23 +113,23 @@ impl Source {
}

/// Creates a local filesystem source from a path string.
fn local<P>(path: P) -> Self
pub fn local<P>(path: P) -> Self
where
P: AsRef<Path>,
{
Source::Local(path.as_ref().into())
}

/// Creates an HTTP source from a URL.
fn http<S>(url: S) -> Result<Self>
pub fn http<S>(url: S) -> Result<Self>
where
S: AsRef<str>,
{
Ok(Source::Http(Url::parse(url.as_ref())?))
}

/// Creates an Etherscan source from an address string.
fn etherscan<S>(address: S) -> Result<Self>
pub fn etherscan<S>(address: S) -> Result<Self>
where
S: AsRef<str>,
{
Expand All @@ -139,7 +139,7 @@ impl Source {
}

/// Creates an Etherscan source from an address string.
fn npm<S>(package_path: S) -> Self
pub fn npm<S>(package_path: S) -> Self
where
S: Into<String>,
{
Expand Down
4 changes: 2 additions & 2 deletions ethers-contract/ethers-contract-abigen/src/util.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
use ethers_core::types::Address;

use anyhow::{anyhow, Result};
use cargo_metadata::{CargoOpt, DependencyKind, Metadata, MetadataCommand};
use cargo_metadata::{DependencyKind, MetadataCommand};
use inflector::Inflector;
use once_cell::sync::Lazy;
use proc_macro2::{Ident, Literal, Span, TokenStream};
use quote::quote;
use reqwest::Client;

use syn::{Ident as SynIdent, Path};

/// See `determine_ethers_crates`
Expand Down
4 changes: 2 additions & 2 deletions ethers-contract/tests/abigen.rs
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,6 @@ fn can_gen_human_readable_with_structs() {

let (client, _mock) = Provider::mocked();
let contract = SimpleContract::new(Address::default(), Arc::new(client));
let foo = Foo { x: 100u64.into() };
let _ = contract.foo(foo);
let f = Foo { x: 100u64.into() };
let _ = contract.foo(f);
}
4 changes: 2 additions & 2 deletions ethers-contract/tests/contract.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use ethers_contract::{abigen, ContractFactory, EthAbiType};
use ethers_core::types::{Filter, ValueOrArray, H256};



mod common;
pub use common::*;
Expand Down

0 comments on commit f530288

Please sign in to comment.