ethers-rs/ethers-contract/ethers-contract-abigen/src/contract/common.rs

76 lines
2.4 KiB
Rust
Raw Normal View History

use super::{util, Context};
2020-05-26 18:57:59 +00:00
2020-05-31 16:01:34 +00:00
use ethers_core::types::Address;
2020-05-26 18:57:59 +00:00
use proc_macro2::{Literal, TokenStream};
use quote::quote;
pub(crate) fn imports(name: &str) -> TokenStream {
let doc = util::expand_doc(&format!("{} was auto-generated with ethers-rs Abigen. More information at: https://github.com/gakonst/ethers-rs", name));
2020-05-26 18:57:59 +00:00
quote! {
#![allow(dead_code)]
#![allow(unused_imports)]
#doc
use std::sync::Arc;
use ethers::{
core::{
abi::{Abi, Token, Detokenize, InvalidOutputType, Tokenizable, parse_abi},
types::*, // import all the types so that we can codegen for everything
},
2020-06-11 06:45:14 +00:00
contract::{Contract, builders::{ContractCall, Event}, Lazy},
providers::Middleware,
2020-05-26 18:57:59 +00:00
};
}
}
2020-06-02 21:10:46 +00:00
pub(crate) fn struct_declaration(cx: &Context, abi_name: &proc_macro2::Ident) -> TokenStream {
2020-05-26 18:57:59 +00:00
let name = &cx.contract_name;
let abi = &cx.abi_str;
let abi_parse = if !cx.human_readable {
quote! {
pub static #abi_name: Lazy<Abi> = Lazy::new(|| serde_json::from_str(#abi)
.expect("invalid abi"));
}
} else {
quote! {
pub static #abi_name: Lazy<Abi> = Lazy::new(|| {
let abi_str = #abi.replace('[', "").replace(']', "").replace(',', "");
// split lines and get only the non-empty things
let split: Vec<&str> = abi_str
.split("\n")
.map(|x| x.trim())
.filter(|x| !x.is_empty())
.collect();
parse_abi(&split).expect("invalid abi")
});
}
};
2020-05-26 18:57:59 +00:00
quote! {
// Inline ABI declaration
#abi_parse
2020-05-26 18:57:59 +00:00
// Struct declaration
#[derive(Clone)]
pub struct #name<M>(Contract<M>);
2020-05-26 18:57:59 +00:00
// Deref to the inner contract in order to access more specific functions functions
impl<M> std::ops::Deref for #name<M> {
type Target = Contract<M>;
2020-05-26 18:57:59 +00:00
fn deref(&self) -> &Self::Target { &self.0 }
}
impl<M: Middleware> std::fmt::Debug for #name<M> {
2020-05-26 18:57:59 +00:00
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
f.debug_tuple(stringify!(#name))
.field(&self.address())
.finish()
}
}
}
}