--- a/.maintain/frame-weight-template.hbs
+++ b/.maintain/frame-weight-template.hbs
@@ -14,6 +14,7 @@
#![cfg_attr(rustfmt, rustfmt_skip)]
#![allow(unused_parens)]
#![allow(unused_imports)]
+#![allow(missing_docs)]
#![allow(clippy::unnecessary_cast)]
use frame_support::{traits::Get, weights::{Weight, constants::RocksDbWeight}};
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1772,41 +1772,6 @@
]
[[package]]
-name = "darling"
-version = "0.13.4"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "a01d95850c592940db9b8194bc39f4bc0e89dee5c4265e4b1807c34a9aba453c"
-dependencies = [
- "darling_core",
- "darling_macro",
-]
-
-[[package]]
-name = "darling_core"
-version = "0.13.4"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "859d65a907b6852c9361e3185c862aae7fafd2887876799fa55f5f99dc40d610"
-dependencies = [
- "fnv",
- "ident_case",
- "proc-macro2",
- "quote",
- "strsim",
- "syn",
-]
-
-[[package]]
-name = "darling_macro"
-version = "0.13.4"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "9c972679f83bdf9c42bd905396b6c3588a843a17f0f16dfcfa3e2c5d57441835"
-dependencies = [
- "darling_core",
- "quote",
- "syn",
-]
-
-[[package]]
name = "data-encoding"
version = "2.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -2207,7 +2172,7 @@
version = "0.1.1"
dependencies = [
"ethereum",
- "evm-coder-macros",
+ "evm-coder-procedural",
"evm-core",
"hex",
"hex-literal",
@@ -2216,15 +2181,14 @@
]
[[package]]
-name = "evm-coder-macros"
-version = "0.1.0"
+name = "evm-coder-procedural"
+version = "0.2.0"
dependencies = [
"Inflector",
- "darling",
"hex",
"proc-macro2",
"quote",
- "sha3 0.9.1",
+ "sha3 0.10.2",
"syn",
]
@@ -3427,12 +3391,6 @@
"wasm-bindgen",
"winapi",
]
-
-[[package]]
-name = "ident_case"
-version = "1.0.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "b9e0384b61958566e926dc50660321d12159025e767c18e043daf26b70104c39"
[[package]]
name = "idna"
--- a/crates/evm-coder-macros/Cargo.toml
+++ /dev/null
@@ -1,17 +0,0 @@
-[package]
-name = "evm-coder-macros"
-version = "0.1.0"
-license = "GPLv3"
-edition = "2021"
-
-[lib]
-proc-macro = true
-
-[dependencies]
-sha3 = "0.9.1"
-quote = "1.0"
-proc-macro2 = "1.0"
-syn = { version = "1.0", features = ["full"] }
-hex = "0.4.3"
-Inflector = "0.11.4"
-darling = "0.13.0"
--- a/crates/evm-coder-macros/src/lib.rs
+++ /dev/null
@@ -1,300 +0,0 @@
-// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.
-// This file is part of Unique Network.
-
-// Unique Network is free software: you can redistribute it and/or modify
-// it under the terms of the GNU General Public License as published by
-// the Free Software Foundation, either version 3 of the License, or
-// (at your option) any later version.
-
-// Unique Network is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-// GNU General Public License for more details.
-
-// You should have received a copy of the GNU General Public License
-// along with Unique Network. If not, see .
-
-#![allow(dead_code)]
-
-use darling::FromMeta;
-use inflector::cases;
-use proc_macro::TokenStream;
-use quote::quote;
-use sha3::{Digest, Keccak256};
-use syn::{
- AttributeArgs, DeriveInput, GenericArgument, Ident, ItemImpl, Pat, Path, PathArguments,
- PathSegment, Type, parse_macro_input, spanned::Spanned,
-};
-
-mod solidity_interface;
-mod to_log;
-
-fn fn_selector_str(input: &str) -> u32 {
- let mut hasher = Keccak256::new();
- hasher.update(input.as_bytes());
- let result = hasher.finalize();
-
- let mut selector_bytes = [0; 4];
- selector_bytes.copy_from_slice(&result[0..4]);
-
- u32::from_be_bytes(selector_bytes)
-}
-
-/// Returns solidity function selector (first 4 bytes of hash) by its
-/// textual representation
-///
-/// ```ignore
-/// use evm_coder_macros::fn_selector;
-///
-/// assert_eq!(fn_selector!(transfer(address, uint256)), 0xa9059cbb);
-/// ```
-#[proc_macro]
-pub fn fn_selector(input: TokenStream) -> TokenStream {
- let input = input.to_string().replace(' ', "");
- let selector = fn_selector_str(&input);
-
- (quote! {
- #selector
- })
- .into()
-}
-
-fn event_selector_str(input: &str) -> [u8; 32] {
- let mut hasher = Keccak256::new();
- hasher.update(input.as_bytes());
- let result = hasher.finalize();
-
- let mut selector_bytes = [0; 32];
- selector_bytes.copy_from_slice(&result[0..32]);
- selector_bytes
-}
-
-/// Returns solidity topic (hash) by its textual representation
-///
-/// ```ignore
-/// use evm_coder_macros::event_topic;
-///
-/// assert_eq!(
-/// format!("{:x}", event_topic!(Transfer(address, address, uint256))),
-/// "ddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef",
-/// );
-/// ```
-#[proc_macro]
-pub fn event_topic(stream: TokenStream) -> TokenStream {
- let input = stream.to_string().replace(' ', "");
- let selector_bytes = event_selector_str(&input);
-
- (quote! {
- ::primitive_types::H256([#(
- #selector_bytes,
- )*])
- })
- .into()
-}
-
-fn parse_path(ty: &Type) -> syn::Result<&Path> {
- match &ty {
- syn::Type::Path(pat) => {
- if let Some(qself) = &pat.qself {
- return Err(syn::Error::new(qself.ty.span(), "no receiver expected"));
- }
- Ok(&pat.path)
- }
- _ => Err(syn::Error::new(ty.span(), "expected ty to be path")),
- }
-}
-
-fn parse_path_segment(path: &Path) -> syn::Result<&PathSegment> {
- if path.segments.len() != 1 {
- return Err(syn::Error::new(
- path.span(),
- "expected path to have only segment",
- ));
- }
- let last_segment = &path.segments.last().unwrap();
- Ok(last_segment)
-}
-
-fn parse_ident_from_pat(pat: &Pat) -> syn::Result<&Ident> {
- match pat {
- Pat::Ident(i) => Ok(&i.ident),
- _ => Err(syn::Error::new(pat.span(), "expected pat ident")),
- }
-}
-
-fn parse_ident_from_segment(segment: &PathSegment, allow_generics: bool) -> syn::Result<&Ident> {
- if segment.arguments != PathArguments::None && !allow_generics {
- return Err(syn::Error::new(
- segment.arguments.span(),
- "unexpected generic type",
- ));
- }
- Ok(&segment.ident)
-}
-
-fn parse_ident_from_path(path: &Path, allow_generics: bool) -> syn::Result<&Ident> {
- let segment = parse_path_segment(path)?;
- parse_ident_from_segment(segment, allow_generics)
-}
-
-fn parse_ident_from_type(ty: &Type, allow_generics: bool) -> syn::Result<&Ident> {
- let path = parse_path(ty)?;
- parse_ident_from_path(path, allow_generics)
-}
-
-// Gets T out of Result
-fn parse_result_ok(ty: &Type) -> syn::Result<&Type> {
- let path = parse_path(ty)?;
- let segment = parse_path_segment(path)?;
-
- if segment.ident != "Result" {
- return Err(syn::Error::new(
- ty.span(),
- "expected Result as return type (no renamed aliases allowed)",
- ));
- }
- let args = match &segment.arguments {
- PathArguments::AngleBracketed(e) => e,
- _ => {
- return Err(syn::Error::new(
- segment.arguments.span(),
- "missing Result generics",
- ))
- }
- };
-
- let args = &args.args;
- let arg = args.first().unwrap();
-
- let ty = match arg {
- GenericArgument::Type(ty) => ty,
- _ => {
- return Err(syn::Error::new(
- arg.span(),
- "expected first generic to be type",
- ))
- }
- };
-
- Ok(ty)
-}
-
-fn pascal_ident_to_call(ident: &Ident) -> Ident {
- let name = format!("{}Call", ident);
- Ident::new(&name, ident.span())
-}
-fn snake_ident_to_pascal(ident: &Ident) -> Ident {
- let name = ident.to_string();
- let name = cases::pascalcase::to_pascal_case(&name);
- Ident::new(&name, ident.span())
-}
-fn snake_ident_to_screaming(ident: &Ident) -> Ident {
- let name = ident.to_string();
- let name = cases::screamingsnakecase::to_screaming_snake_case(&name);
- Ident::new(&name, ident.span())
-}
-fn pascal_ident_to_snake_call(ident: &Ident) -> Ident {
- let name = ident.to_string();
- let name = cases::snakecase::to_snake_case(&name);
- let name = format!("call_{}", name);
- Ident::new(&name, ident.span())
-}
-
-/// Derives call enum implementing [`evm_coder::Callable`], [`evm_coder::Weighted`]
-/// and [`evm_coder::Call`] from impl block
-///
-/// ## Macro syntax
-///
-/// `#[solidity_interface(name, is, inline_is, events)]`
-/// - *name*: used in generated code, and for Call enum name
-/// - *is*: used to provide call inheritance, not found methods will be delegated to all contracts
-/// specified in is/inline_is
-/// - *inline_is*: same as is, but selectors for passed contracts will be used by derived ERC165
-/// implementation
-///
-/// `#[weight(value)]`
-/// Can be added to every method of impl block, used for deriving [`evm_coder::Weighted`], which
-/// is used by substrate bridge
-/// - *value*: expression, which evaluates to weight required to call this method.
-/// This expression can use call arguments to calculate non-constant execution time.
-/// This expression should evaluate faster than actual execution does, and may provide worser case
-/// than one is called
-///
-/// `#[solidity_interface(rename_selector)]`
-/// - *rename_selector*: by default, selector name will be generated by transforming method name
-/// from snake_case to camelCase. Use this option, if other naming convention is required.
-/// I.e: method `token_uri` will be automatically renamed to `tokenUri` in selector, but name
-/// required by ERC721 standard is `tokenURI`, thus we need to specify `rename_selector = "tokenURI"`
-/// explicitly
-///
-/// Also, any contract method may have doc comments, which will be automatically added to generated
-/// solidity interface definitions
-///
-/// ## Example
-///
-/// ```ignore
-/// struct SuperContract;
-/// struct InlineContract;
-/// struct Contract;
-///
-/// #[derive(ToLog)]
-/// enum ContractEvents {
-/// Event(#[indexed] uint32),
-/// }
-///
-/// #[solidity_interface(name = "MyContract", is(SuperContract), inline_is(InlineContract))]
-/// impl Contract {
-/// /// Multiply two numbers
-/// #[weight(200 + a + b)]
-/// #[solidity_interface(rename_selector = "mul")]
-/// fn mul(&mut self, a: uint32, b: uint32) -> Result {
-/// Ok(a.checked_mul(b).ok_or("overflow")?)
-/// }
-/// }
-/// ```
-#[proc_macro_attribute]
-pub fn solidity_interface(args: TokenStream, stream: TokenStream) -> TokenStream {
- let args = parse_macro_input!(args as AttributeArgs);
- let args = solidity_interface::InterfaceInfo::from_list(&args).unwrap();
-
- let input: ItemImpl = match syn::parse(stream) {
- Ok(t) => t,
- Err(e) => return e.to_compile_error().into(),
- };
-
- let expanded = match solidity_interface::SolidityInterface::try_from(args, &input) {
- Ok(v) => v.expand(),
- Err(e) => e.to_compile_error(),
- };
-
- (quote! {
- #input
-
- #expanded
- })
- .into()
-}
-
-#[proc_macro_attribute]
-pub fn solidity(_args: TokenStream, stream: TokenStream) -> TokenStream {
- stream
-}
-#[proc_macro_attribute]
-pub fn weight(_args: TokenStream, stream: TokenStream) -> TokenStream {
- stream
-}
-
-/// ## Syntax
-///
-/// `#[indexed]`
-/// Marks this field as indexed, so it will appear in [`ethereum::Log`] topics instead of data
-#[proc_macro_derive(ToLog, attributes(indexed))]
-pub fn to_log(value: TokenStream) -> TokenStream {
- let input = parse_macro_input!(value as DeriveInput);
-
- match to_log::Events::try_from(&input) {
- Ok(e) => e.expand(),
- Err(e) => e.to_compile_error(),
- }
- .into()
-}
--- a/crates/evm-coder-macros/src/solidity_interface.rs
+++ /dev/null
@@ -1,1005 +0,0 @@
-// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.
-// This file is part of Unique Network.
-
-// Unique Network is free software: you can redistribute it and/or modify
-// it under the terms of the GNU General Public License as published by
-// the Free Software Foundation, either version 3 of the License, or
-// (at your option) any later version.
-
-// Unique Network is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-// GNU General Public License for more details.
-
-// You should have received a copy of the GNU General Public License
-// along with Unique Network. If not, see .
-
-#![allow(dead_code)]
-
-use quote::quote;
-use darling::{FromMeta, ToTokens};
-use inflector::cases;
-use std::fmt::Write;
-use syn::{
- Expr, FnArg, GenericArgument, Generics, Ident, ImplItem, ImplItemMethod, ItemImpl, Lit, Meta,
- MetaNameValue, NestedMeta, PatType, Path, PathArguments, ReturnType, Type, spanned::Spanned,
- parse_str,
-};
-
-use crate::{
- fn_selector_str, parse_ident_from_pat, parse_ident_from_path, parse_path, parse_path_segment,
- parse_result_ok, pascal_ident_to_call, pascal_ident_to_snake_call, snake_ident_to_pascal,
- snake_ident_to_screaming,
-};
-
-struct Is {
- name: Ident,
- pascal_call_name: Ident,
- snake_call_name: Ident,
- via: Option<(Type, Ident)>,
-}
-impl Is {
- fn new_via(path: &Path, via: Option<(Type, Ident)>) -> syn::Result {
- let name = parse_ident_from_path(path, false)?.clone();
- Ok(Self {
- pascal_call_name: pascal_ident_to_call(&name),
- snake_call_name: pascal_ident_to_snake_call(&name),
- name,
- via,
- })
- }
- fn new(path: &Path) -> syn::Result {
- Self::new_via(path, None)
- }
-
- fn expand_call_def(&self, gen_ref: &proc_macro2::TokenStream) -> proc_macro2::TokenStream {
- let name = &self.name;
- let pascal_call_name = &self.pascal_call_name;
- quote! {
- #name(#pascal_call_name #gen_ref)
- }
- }
-
- fn expand_interface_id(&self) -> proc_macro2::TokenStream {
- let pascal_call_name = &self.pascal_call_name;
- quote! {
- interface_id ^= u32::from_be_bytes(#pascal_call_name::interface_id());
- }
- }
-
- fn expand_supports_interface(
- &self,
- generics: &proc_macro2::TokenStream,
- ) -> proc_macro2::TokenStream {
- let pascal_call_name = &self.pascal_call_name;
- quote! {
- <#pascal_call_name #generics>::supports_interface(interface_id)
- }
- }
-
- fn expand_variant_weight(&self) -> proc_macro2::TokenStream {
- let name = &self.name;
- quote! {
- Self::#name(call) => call.weight()
- }
- }
-
- fn expand_variant_call(
- &self,
- call_name: &proc_macro2::Ident,
- generics: &proc_macro2::TokenStream,
- ) -> proc_macro2::TokenStream {
- let name = &self.name;
- let pascal_call_name = &self.pascal_call_name;
- let via_typ = self
- .via
- .as_ref()
- .map(|(t, _)| quote! {#t})
- .unwrap_or_else(|| quote! {Self});
- let via_map = self
- .via
- .as_ref()
- .map(|(_, i)| quote! {.#i()})
- .unwrap_or_default();
- quote! {
- #call_name::#name(call) => return <#via_typ as ::evm_coder::Callable<#pascal_call_name #generics>>::call(self #via_map, Msg {
- call,
- caller: c.caller,
- value: c.value,
- })
- }
- }
-
- fn expand_parse(&self, generics: &proc_macro2::TokenStream) -> proc_macro2::TokenStream {
- let name = &self.name;
- let pascal_call_name = &self.pascal_call_name;
- quote! {
- if let Some(parsed_call) = <#pascal_call_name #generics>::parse(method_id, reader)? {
- return Ok(Some(Self::#name(parsed_call)))
- }
- }
- }
-
- fn expand_generator(&self, generics: &proc_macro2::TokenStream) -> proc_macro2::TokenStream {
- let pascal_call_name = &self.pascal_call_name;
- quote! {
- <#pascal_call_name #generics>::generate_solidity_interface(tc, is_impl);
- }
- }
-
- fn expand_event_generator(&self) -> proc_macro2::TokenStream {
- let name = &self.name;
- quote! {
- #name::generate_solidity_interface(tc, is_impl);
- }
- }
-}
-
-#[derive(Default)]
-struct IsList(Vec);
-impl FromMeta for IsList {
- fn from_list(items: &[NestedMeta]) -> darling::Result {
- let mut out = Vec::new();
- for item in items {
- match item {
- NestedMeta::Meta(Meta::Path(path)) => out.push(Is::new(path)?),
- // TODO: replace meta parsing with manual
- NestedMeta::Meta(Meta::List(list))
- if list.path.is_ident("via") && list.nested.len() == 3 =>
- {
- let mut data = list.nested.iter();
- let typ = match data.next().expect("len == 3") {
- NestedMeta::Lit(Lit::Str(s)) => {
- let v = s.value();
- let typ: Type = parse_str(&v)?;
- typ
- }
- _ => {
- return Err(syn::Error::new(
- item.span(),
- "via typ should be type in string",
- )
- .into())
- }
- };
- let via = match data.next().expect("len == 3") {
- NestedMeta::Meta(Meta::Path(path)) => path
- .get_ident()
- .ok_or_else(|| syn::Error::new(item.span(), "via should be ident"))?,
- _ => return Err(syn::Error::new(item.span(), "via should be ident").into()),
- };
- let path = match data.next().expect("len == 3") {
- NestedMeta::Meta(Meta::Path(path)) => path,
- _ => return Err(syn::Error::new(item.span(), "path should be path").into()),
- };
-
- out.push(Is::new_via(path, Some((typ, via.clone())))?)
- }
- _ => {
- return Err(syn::Error::new(
- item.span(),
- "expected either Name or via(\"Type\", getter, Name)",
- )
- .into())
- }
- }
- }
- Ok(Self(out))
- }
-}
-
-#[derive(FromMeta)]
-pub struct InterfaceInfo {
- name: Ident,
- #[darling(default)]
- is: IsList,
- #[darling(default)]
- inline_is: IsList,
- #[darling(default)]
- events: IsList,
-}
-
-#[derive(FromMeta)]
-struct MethodInfo {
- #[darling(default)]
- rename_selector: Option,
-}
-
-enum AbiType {
- // type
- Plain(Ident),
- // (type1,type2)
- Tuple(Vec),
- // type[]
- Vec(Box),
- // type[20]
- Array(Box, usize),
-}
-impl AbiType {
- fn try_from(value: &Type) -> syn::Result {
- let value = Self::try_maybe_special_from(value)?;
- if value.is_special() {
- return Err(syn::Error::new(value.span(), "unexpected special type"));
- }
- Ok(value)
- }
- fn try_maybe_special_from(value: &Type) -> syn::Result {
- match value {
- Type::Array(arr) => {
- let wrapped = AbiType::try_from(&arr.elem)?;
- match &arr.len {
- Expr::Lit(l) => match &l.lit {
- Lit::Int(i) => {
- let num = i.base10_parse::()?;
- Ok(AbiType::Array(Box::new(wrapped), num as usize))
- }
- _ => Err(syn::Error::new(arr.len.span(), "should be int literal")),
- },
- _ => Err(syn::Error::new(arr.len.span(), "should be literal")),
- }
- }
- Type::Path(_) => {
- let path = parse_path(value)?;
- let segment = parse_path_segment(path)?;
- if segment.ident == "Vec" {
- let args = match &segment.arguments {
- PathArguments::AngleBracketed(e) => e,
- _ => {
- return Err(syn::Error::new(
- segment.arguments.span(),
- "missing Vec generic",
- ))
- }
- };
- let args = &args.args;
- if args.len() != 1 {
- return Err(syn::Error::new(
- args.span(),
- "expected only one generic for vec",
- ));
- }
- let arg = args.first().unwrap();
-
- let ty = match arg {
- GenericArgument::Type(ty) => ty,
- _ => {
- return Err(syn::Error::new(
- arg.span(),
- "expected first generic to be type",
- ))
- }
- };
-
- let wrapped = AbiType::try_from(ty)?;
- Ok(Self::Vec(Box::new(wrapped)))
- } else {
- if !segment.arguments.is_empty() {
- return Err(syn::Error::new(
- segment.arguments.span(),
- "unexpected generic arguments for non-vec type",
- ));
- }
- Ok(Self::Plain(segment.ident.clone()))
- }
- }
- Type::Tuple(t) => {
- let mut out = Vec::with_capacity(t.elems.len());
- for el in t.elems.iter() {
- out.push(AbiType::try_from(el)?)
- }
- Ok(Self::Tuple(out))
- }
- _ => Err(syn::Error::new(
- value.span(),
- "unexpected type, only arrays, plain types and tuples are supported",
- )),
- }
- }
- fn is_value(&self) -> bool {
- matches!(self, Self::Plain(v) if v == "value")
- }
- fn is_caller(&self) -> bool {
- matches!(self, Self::Plain(v) if v == "caller")
- }
- fn is_special(&self) -> bool {
- self.is_caller() || self.is_value()
- }
- fn selector_ty_buf(&self, buf: &mut String) -> std::fmt::Result {
- match self {
- AbiType::Plain(t) => {
- write!(buf, "{}", t)
- }
- AbiType::Tuple(t) => {
- write!(buf, "(")?;
- for (i, t) in t.iter().enumerate() {
- if i != 0 {
- write!(buf, ",")?;
- }
- t.selector_ty_buf(buf)?;
- }
- write!(buf, ")")
- }
- AbiType::Vec(v) => {
- v.selector_ty_buf(buf)?;
- write!(buf, "[]")
- }
- AbiType::Array(v, len) => {
- v.selector_ty_buf(buf)?;
- write!(buf, "[{}]", len)
- }
- }
- }
- fn selector_ty(&self) -> String {
- let mut out = String::new();
- self.selector_ty_buf(&mut out).expect("no fmt error");
- out
- }
-}
-impl ToTokens for AbiType {
- fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) {
- match self {
- AbiType::Plain(t) => tokens.extend(quote! {#t}),
- AbiType::Tuple(t) => {
- tokens.extend(quote! {(
- #(#t),*
- )});
- }
- AbiType::Vec(v) => tokens.extend(quote! {Vec<#v>}),
- AbiType::Array(v, l) => tokens.extend(quote! {[#v; #l]}),
- }
- }
-}
-
-struct MethodArg {
- name: Ident,
- camel_name: String,
- ty: AbiType,
-}
-impl MethodArg {
- fn try_from(value: &PatType) -> syn::Result {
- let name = parse_ident_from_pat(&value.pat)?.clone();
- Ok(Self {
- camel_name: cases::camelcase::to_camel_case(&name.to_string()),
- name,
- ty: AbiType::try_maybe_special_from(&value.ty)?,
- })
- }
- fn is_value(&self) -> bool {
- self.ty.is_value()
- }
- fn is_caller(&self) -> bool {
- self.ty.is_caller()
- }
- fn is_special(&self) -> bool {
- self.ty.is_special()
- }
- fn selector_ty(&self) -> String {
- assert!(!self.is_special());
- self.ty.selector_ty()
- }
-
- fn expand_call_def(&self) -> proc_macro2::TokenStream {
- assert!(!self.is_special());
- let name = &self.name;
- let ty = &self.ty;
-
- quote! {
- #name: #ty
- }
- }
-
- fn expand_parse(&self) -> proc_macro2::TokenStream {
- assert!(!self.is_special());
- let name = &self.name;
- quote! {
- #name: reader.abi_read()?
- }
- }
-
- fn expand_call_arg(&self) -> proc_macro2::TokenStream {
- if self.is_value() {
- quote! {
- c.value.clone()
- }
- } else if self.is_caller() {
- quote! {
- c.caller.clone()
- }
- } else {
- let name = &self.name;
- quote! {
- #name
- }
- }
- }
-
- fn expand_solidity_argument(&self) -> proc_macro2::TokenStream {
- let camel_name = &self.camel_name.to_string();
- let ty = &self.ty;
- quote! {
- >::new(#camel_name)
- }
- }
-}
-
-#[derive(PartialEq)]
-enum Mutability {
- Mutable,
- View,
- Pure,
-}
-
-pub struct WeightAttr(syn::Expr);
-
-mod keyword {
- syn::custom_keyword!(weight);
-}
-
-impl syn::parse::Parse for WeightAttr {
- fn parse(input: syn::parse::ParseStream) -> syn::Result {
- input.parse::()?;
- let content;
- syn::bracketed!(content in input);
- content.parse::()?;
-
- let weight_content;
- syn::parenthesized!(weight_content in content);
- Ok(WeightAttr(weight_content.parse::()?))
- }
-}
-
-struct Method {
- name: Ident,
- camel_name: String,
- pascal_name: Ident,
- screaming_name: Ident,
- selector_str: String,
- selector: u32,
- args: Vec,
- has_normal_args: bool,
- mutability: Mutability,
- result: Type,
- weight: Option,
- docs: Vec,
-}
-impl Method {
- fn try_from(value: &ImplItemMethod) -> syn::Result {
- let mut info = MethodInfo {
- rename_selector: None,
- };
- let mut docs = Vec::new();
- let mut weight = None;
- for attr in &value.attrs {
- let ident = parse_ident_from_path(&attr.path, false)?;
- if ident == "solidity" {
- let args = attr.parse_meta().unwrap();
- info = MethodInfo::from_meta(&args).unwrap();
- } else if ident == "doc" {
- let args = attr.parse_meta().unwrap();
- let value = match args {
- Meta::NameValue(MetaNameValue {
- lit: Lit::Str(str), ..
- }) => str.value(),
- _ => unreachable!(),
- };
- docs.push(value);
- } else if ident == "weight" {
- weight = Some(syn::parse2::(attr.to_token_stream())?.0);
- }
- }
- let ident = &value.sig.ident;
- let ident_str = ident.to_string();
- if !cases::snakecase::is_snake_case(&ident_str) {
- return Err(syn::Error::new(ident.span(), "method name should be snake_cased\nif alternative solidity name needs to be set - use #[solidity] attribute"));
- }
-
- let mut mutability = Mutability::Pure;
-
- if let Some(FnArg::Receiver(receiver)) = value
- .sig
- .inputs
- .iter()
- .find(|arg| matches!(arg, FnArg::Receiver(_)))
- {
- if receiver.reference.is_none() {
- return Err(syn::Error::new(
- receiver.span(),
- "receiver should be by ref",
- ));
- }
- if receiver.mutability.is_some() {
- mutability = Mutability::Mutable;
- } else {
- mutability = Mutability::View;
- }
- }
- let mut args = Vec::new();
- for typ in value
- .sig
- .inputs
- .iter()
- .filter(|arg| matches!(arg, FnArg::Typed(_)))
- {
- let typ = match typ {
- FnArg::Typed(typ) => typ,
- _ => unreachable!(),
- };
- args.push(MethodArg::try_from(typ)?);
- }
-
- if mutability != Mutability::Mutable && args.iter().any(|arg| arg.is_value()) {
- return Err(syn::Error::new(
- args.iter().find(|arg| arg.is_value()).unwrap().ty.span(),
- "payable function should be mutable",
- ));
- }
-
- let result = match &value.sig.output {
- ReturnType::Type(_, ty) => ty,
- _ => return Err(syn::Error::new(value.sig.output.span(), "interface method should return Result\nif there is no value to return - specify void (which is alias to unit)")),
- };
- let result = parse_result_ok(result)?;
-
- let camel_name = info
- .rename_selector
- .unwrap_or_else(|| cases::camelcase::to_camel_case(&ident.to_string()));
- let mut selector_str = camel_name.clone();
- selector_str.push('(');
- let mut has_normal_args = false;
- for (i, arg) in args.iter().filter(|arg| !arg.is_special()).enumerate() {
- if i != 0 {
- selector_str.push(',');
- }
- write!(selector_str, "{}", arg.selector_ty()).unwrap();
- has_normal_args = true;
- }
- selector_str.push(')');
- let selector = fn_selector_str(&selector_str);
-
- Ok(Self {
- name: ident.clone(),
- camel_name,
- pascal_name: snake_ident_to_pascal(ident),
- screaming_name: snake_ident_to_screaming(ident),
- selector_str,
- selector,
- args,
- has_normal_args,
- mutability,
- result: result.clone(),
- weight,
- docs,
- })
- }
- fn expand_call_def(&self) -> proc_macro2::TokenStream {
- let defs = self
- .args
- .iter()
- .filter(|a| !a.is_special())
- .map(|a| a.expand_call_def());
- let pascal_name = &self.pascal_name;
-
- if self.has_normal_args {
- quote! {
- #pascal_name {
- #(
- #defs,
- )*
- }
- }
- } else {
- quote! {#pascal_name}
- }
- }
-
- fn expand_const(&self) -> proc_macro2::TokenStream {
- let screaming_name = &self.screaming_name;
- let selector = u32::to_be_bytes(self.selector);
- let selector_str = &self.selector_str;
- quote! {
- #[doc = #selector_str]
- const #screaming_name: ::evm_coder::types::bytes4 = [#(#selector,)*];
- }
- }
-
- fn expand_interface_id(&self) -> proc_macro2::TokenStream {
- let screaming_name = &self.screaming_name;
- quote! {
- interface_id ^= u32::from_be_bytes(Self::#screaming_name);
- }
- }
-
- fn expand_parse(&self) -> proc_macro2::TokenStream {
- let pascal_name = &self.pascal_name;
- let screaming_name = &self.screaming_name;
- if self.has_normal_args {
- let parsers = self
- .args
- .iter()
- .filter(|a| !a.is_special())
- .map(|a| a.expand_parse());
- quote! {
- Self::#screaming_name => return Ok(Some(Self::#pascal_name {
- #(
- #parsers,
- )*
- }))
- }
- } else {
- quote! { Self::#screaming_name => return Ok(Some(Self::#pascal_name)) }
- }
- }
-
- fn expand_variant_call(&self, call_name: &proc_macro2::Ident) -> proc_macro2::TokenStream {
- let pascal_name = &self.pascal_name;
- let name = &self.name;
-
- let matcher = if self.has_normal_args {
- let names = self
- .args
- .iter()
- .filter(|a| !a.is_special())
- .map(|a| &a.name);
-
- quote! {{
- #(
- #names,
- )*
- }}
- } else {
- quote! {}
- };
-
- let receiver = match self.mutability {
- Mutability::Mutable | Mutability::View => quote! {self.},
- Mutability::Pure => quote! {Self::},
- };
- let args = self.args.iter().map(|a| a.expand_call_arg());
-
- quote! {
- #call_name::#pascal_name #matcher => {
- let result = #receiver #name(
- #(
- #args,
- )*
- )?;
- (&result).to_result()
- }
- }
- }
-
- fn expand_variant_weight(&self) -> proc_macro2::TokenStream {
- let pascal_name = &self.pascal_name;
- if let Some(weight) = &self.weight {
- let matcher = if self.has_normal_args {
- let names = self
- .args
- .iter()
- .filter(|a| !a.is_special())
- .map(|a| &a.name);
-
- quote! {{
- #(
- #names,
- )*
- }}
- } else {
- quote! {}
- };
- quote! {
- Self::#pascal_name #matcher => (#weight).into()
- }
- } else {
- let matcher = if self.has_normal_args {
- quote! {{..}}
- } else {
- quote! {}
- };
- quote! {
- Self::#pascal_name #matcher => ().into()
- }
- }
- }
-
- fn expand_solidity_function(&self) -> proc_macro2::TokenStream {
- let camel_name = &self.camel_name;
- let mutability = match self.mutability {
- Mutability::Mutable => quote! {SolidityMutability::Mutable},
- Mutability::View => quote! { SolidityMutability::View },
- Mutability::Pure => quote! {SolidityMutability::Pure},
- };
- let result = &self.result;
-
- let args = self
- .args
- .iter()
- .filter(|a| !a.is_special())
- .map(MethodArg::expand_solidity_argument);
- let docs = self.docs.iter();
- let selector = format!("{} {:0>8x}", self.selector_str, self.selector);
-
- quote! {
- SolidityFunction {
- docs: &[#(#docs),*],
- selector: #selector,
- name: #camel_name,
- mutability: #mutability,
- args: (
- #(
- #args,
- )*
- ),
- result: >::default(),
- }
- }
- }
-}
-
-fn generics_list(gen: &Generics) -> proc_macro2::TokenStream {
- if gen.params.is_empty() {
- return quote! {};
- }
- let params = gen.params.iter().map(|p| match p {
- syn::GenericParam::Type(id) => {
- let v = &id.ident;
- quote! {#v}
- }
- syn::GenericParam::Lifetime(lt) => {
- let v = <.lifetime;
- quote! {#v}
- }
- syn::GenericParam::Const(c) => {
- let i = &c.ident;
- quote! {#i}
- }
- });
- quote! { #(#params),* }
-}
-fn generics_reference(gen: &Generics) -> proc_macro2::TokenStream {
- if gen.params.is_empty() {
- return quote! {};
- }
- let list = generics_list(gen);
- quote! { <#list> }
-}
-fn generics_data(gen: &Generics) -> proc_macro2::TokenStream {
- let list = generics_list(gen);
- if gen.params.len() == 1 {
- quote! {#list}
- } else {
- quote! { (#list) }
- }
-}
-
-pub struct SolidityInterface {
- generics: Generics,
- name: Box,
- info: InterfaceInfo,
- methods: Vec,
-}
-impl SolidityInterface {
- pub fn try_from(info: InterfaceInfo, value: &ItemImpl) -> syn::Result {
- let mut methods = Vec::new();
-
- for item in &value.items {
- if let ImplItem::Method(method) = item {
- methods.push(Method::try_from(method)?)
- }
- }
- Ok(Self {
- generics: value.generics.clone(),
- name: value.self_ty.clone(),
- info,
- methods,
- })
- }
- pub fn expand(self) -> proc_macro2::TokenStream {
- let name = self.name;
-
- let solidity_name = self.info.name.to_string();
- let call_name = pascal_ident_to_call(&self.info.name);
- let generics = self.generics;
- let gen_ref = generics_reference(&generics);
- let gen_data = generics_data(&generics);
- let gen_where = &generics.where_clause;
-
- let call_sub = self
- .info
- .inline_is
- .0
- .iter()
- .chain(self.info.is.0.iter())
- .map(|c| Is::expand_call_def(c, &gen_ref));
- let call_parse = self
- .info
- .inline_is
- .0
- .iter()
- .chain(self.info.is.0.iter())
- .map(|is| Is::expand_parse(is, &gen_ref));
- let call_variants = self
- .info
- .inline_is
- .0
- .iter()
- .chain(self.info.is.0.iter())
- .map(|c| Is::expand_variant_call(c, &call_name, &gen_ref));
- let weight_variants = self
- .info
- .inline_is
- .0
- .iter()
- .chain(self.info.is.0.iter())
- .map(Is::expand_variant_weight);
-
- let inline_interface_id = self.info.inline_is.0.iter().map(Is::expand_interface_id);
- let supports_interface = self
- .info
- .is
- .0
- .iter()
- .map(|is| Is::expand_supports_interface(is, &gen_ref));
-
- let calls = self.methods.iter().map(Method::expand_call_def);
- let consts = self.methods.iter().map(Method::expand_const);
- let interface_id = self.methods.iter().map(Method::expand_interface_id);
- let parsers = self.methods.iter().map(Method::expand_parse);
- let call_variants_this = self
- .methods
- .iter()
- .map(|m| Method::expand_variant_call(m, &call_name));
- let weight_variants_this = self.methods.iter().map(Method::expand_variant_weight);
- let solidity_functions = self.methods.iter().map(Method::expand_solidity_function);
-
- // TODO: Inline inline_is
- let solidity_is = self
- .info
- .is
- .0
- .iter()
- .chain(self.info.inline_is.0.iter())
- .map(|is| is.name.to_string());
- let solidity_events_is = self.info.events.0.iter().map(|is| is.name.to_string());
- let solidity_generators = self
- .info
- .is
- .0
- .iter()
- .chain(self.info.inline_is.0.iter())
- .map(|is| Is::expand_generator(is, &gen_ref));
- let solidity_event_generators = self.info.events.0.iter().map(Is::expand_event_generator);
-
- // let methods = self.methods.iter().map(Method::solidity_def);
-
- quote! {
- #[derive(Debug)]
- pub enum #call_name #gen_ref {
- ERC165Call(::evm_coder::ERC165Call, ::core::marker::PhantomData<#gen_data>),
- #(
- #calls,
- )*
- #(
- #call_sub,
- )*
- }
- impl #gen_ref #call_name #gen_ref {
- #(
- #consts
- )*
- pub fn interface_id() -> ::evm_coder::types::bytes4 {
- let mut interface_id = 0;
- #(#interface_id)*
- #(#inline_interface_id)*
- u32::to_be_bytes(interface_id)
- }
- pub fn supports_interface(interface_id: ::evm_coder::types::bytes4) -> bool {
- interface_id != u32::to_be_bytes(0xffffff) && (
- interface_id == ::evm_coder::ERC165Call::INTERFACE_ID ||
- interface_id == Self::interface_id()
- #(
- || #supports_interface
- )*
- )
- }
- pub fn generate_solidity_interface(tc: &evm_coder::solidity::TypeCollector, is_impl: bool) {
- use evm_coder::solidity::*;
- use core::fmt::Write;
- let interface = SolidityInterface {
- name: #solidity_name,
- selector: Self::interface_id(),
- is: &["Dummy", "ERC165", #(
- #solidity_is,
- )* #(
- #solidity_events_is,
- )* ],
- functions: (#(
- #solidity_functions,
- )*),
- };
- if is_impl {
- tc.collect("// Common stubs holder\ncontract Dummy {\n\tuint8 dummy;\n\tstring stub_error = \"this contract is implemented in native\";\n}\ncontract ERC165 is Dummy {\n\tfunction supportsInterface(bytes4 interfaceID) external view returns (bool) {\n\t\trequire(false, stub_error);\n\t\tinterfaceID;\n\t\treturn true;\n\t}\n}\n".into());
- } else {
- tc.collect("// Common stubs holder\ninterface Dummy {\n}\ninterface ERC165 is Dummy {\n\tfunction supportsInterface(bytes4 interfaceID) external view returns (bool);\n}\n".into());
- }
- #(
- #solidity_generators
- )*
- #(
- #solidity_event_generators
- )*
-
- let mut out = string::new();
- // In solidity interface usage (is) should be preceeded by interface definition
- // This comment helps to sort it in a set
- if #solidity_name.starts_with("Inline") {
- out.push_str("// Inline\n");
- }
- let _ = interface.format(is_impl, &mut out, tc);
- tc.collect(out);
- }
- }
- impl #gen_ref ::evm_coder::Call for #call_name #gen_ref {
- fn parse(method_id: ::evm_coder::types::bytes4, reader: &mut ::evm_coder::abi::AbiReader) -> ::evm_coder::execution::Result