git.delta.rocks / unique-network / refs/commits / e2ead47ea043

difftreelog

Merge pull request #706 from UniqueNetwork/fix/evm-stubs

Yaroslav Bolyukin2022-11-08parents: #c0afeb6 #c633ab6.patch.diff
in: master
fix evm-stubs:

4 files changed

modifiedcrates/evm-coder/CHANGELOG.mddiffbeforeafterboth
--- a/crates/evm-coder/CHANGELOG.md
+++ b/crates/evm-coder/CHANGELOG.md
@@ -3,25 +3,28 @@
 All notable changes to this project will be documented in this file.
 
 <!-- bureaucrate goes here -->
+
 ## [v0.1.4] - 2022-11-02
+
 ### Added
- - Named structures support.
 
+- Named structures support.
+
 ## [v0.1.3] - 2022-08-29
 
 ### Fixed
 
- - Parsing simple values.
+- Parsing simple values.
 
 ## [v0.1.2] 2022-08-19
 
 ### Added
 
- - Implementation `AbiWrite` for tuples.
+- Implementation `AbiWrite` for tuples.
 
- ### Fixes
+### Fixes
 
- - Tuple generation for solidity.
+- Tuple generation for solidity.
 
 ## [v0.1.1] 2022-08-16
 
modifiedcrates/evm-coder/procedural/src/solidity_interface.rsdiffbeforeafterboth
before · crates/evm-coder/procedural/src/solidity_interface.rs
1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617#![allow(dead_code)]1819// NOTE: In order to understand this Rust macro better, first read this chapter20// about Procedural Macros in Rust book:21// https://doc.rust-lang.org/reference/procedural-macros.html2223use proc_macro2::TokenStream;24use quote::{quote, format_ident};25use inflector::cases;26use syn::{27	Expr, FnArg, Generics, Ident, ImplItem, ImplItemMethod, ItemImpl, Lit, Meta, MetaNameValue,28	PatType, ReturnType, Type,29	spanned::Spanned,30	parse::{Parse, ParseStream},31	parenthesized, Token, LitInt, LitStr,32};3334use crate::{35	parse_ident_from_pat, parse_ident_from_path, parse_path, parse_path_segment, parse_result_ok,36	pascal_ident_to_call, pascal_ident_to_snake_call, snake_ident_to_pascal,37	snake_ident_to_screaming,38};3940struct Is {41	name: Ident,42	pascal_call_name: Ident,43	snake_call_name: Ident,44	via: Option<(Type, Ident)>,45	condition: Option<Expr>,46}47impl Is {48	fn expand_call_def(&self, gen_ref: &proc_macro2::TokenStream) -> proc_macro2::TokenStream {49		let name = &self.name;50		let pascal_call_name = &self.pascal_call_name;51		quote! {52			#name(#pascal_call_name #gen_ref)53		}54	}5556	fn expand_interface_id(&self) -> proc_macro2::TokenStream {57		let pascal_call_name = &self.pascal_call_name;58		quote! {59			interface_id ^= u32::from_be_bytes(#pascal_call_name::interface_id());60		}61	}6263	fn expand_supports_interface(64		&self,65		generics: &proc_macro2::TokenStream,66	) -> proc_macro2::TokenStream {67		let pascal_call_name = &self.pascal_call_name;68		let condition = self.condition.as_ref().map(|condition| {69			quote! {70				(#condition) &&71			}72		});73		quote! {74			#condition <#pascal_call_name #generics>::supports_interface(this, interface_id)75		}76	}7778	fn expand_variant_weight(&self) -> proc_macro2::TokenStream {79		let name = &self.name;80		quote! {81			Self::#name(call) => call.weight()82		}83	}8485	fn expand_variant_call(86		&self,87		call_name: &proc_macro2::Ident,88		generics: &proc_macro2::TokenStream,89	) -> proc_macro2::TokenStream {90		let name = &self.name;91		let pascal_call_name = &self.pascal_call_name;92		let via_typ = self93			.via94			.as_ref()95			.map(|(t, _)| quote! {#t})96			.unwrap_or_else(|| quote! {Self});97		let via_map = self98			.via99			.as_ref()100			.map(|(_, i)| quote! {.#i()})101			.unwrap_or_default();102		let condition = self.condition.as_ref().map(|condition| {103			quote! {104				if ({let this = &self; (#condition)})105			}106		});107		quote! {108			#call_name::#name(call) #condition => return <#via_typ as ::evm_coder::Callable<#pascal_call_name #generics>>::call(self #via_map, Msg {109				call,110				caller: c.caller,111				value: c.value,112			})113		}114	}115116	fn expand_parse(&self, generics: &proc_macro2::TokenStream) -> proc_macro2::TokenStream {117		let name = &self.name;118		let pascal_call_name = &self.pascal_call_name;119		quote! {120			if let Some(parsed_call) = <#pascal_call_name #generics>::parse(method_id, reader)? {121				return Ok(Some(Self::#name(parsed_call)))122			}123		}124	}125126	fn expand_generator(&self, generics: &proc_macro2::TokenStream) -> proc_macro2::TokenStream {127		let pascal_call_name = &self.pascal_call_name;128		quote! {129			<#pascal_call_name #generics>::generate_solidity_interface(tc, is_impl);130		}131	}132133	fn expand_event_generator(&self) -> proc_macro2::TokenStream {134		let name = &self.name;135		quote! {136			#name::generate_solidity_interface(tc, is_impl);137		}138	}139}140141#[derive(Default)]142struct IsList(Vec<Is>);143impl Parse for IsList {144	fn parse(input: ParseStream) -> syn::Result<Self> {145		let mut out = vec![];146		loop {147			if input.is_empty() {148				break;149			}150			let name = input.parse::<Ident>()?;151			let lookahead = input.lookahead1();152153			let mut condition: Option<Expr> = None;154			let mut via: Option<(Type, Ident)> = None;155156			if lookahead.peek(syn::token::Paren) {157				let contents;158				parenthesized!(contents in input);159				let input = contents;160161				while !input.is_empty() {162					let lookahead = input.lookahead1();163					if lookahead.peek(Token![if]) {164						input.parse::<Token![if]>()?;165						let contents;166						parenthesized!(contents in input);167						let contents = contents.parse::<Expr>()?;168169						if condition.replace(contents).is_some() {170							return Err(syn::Error::new(input.span(), "condition is already set"));171						}172					} else if lookahead.peek(kw::via) {173						input.parse::<kw::via>()?;174						let contents;175						parenthesized!(contents in input);176177						let method = contents.parse::<Ident>()?;178						contents.parse::<kw::returns>()?;179						let ty = contents.parse::<Type>()?;180181						if via.replace((ty, method)).is_some() {182							return Err(syn::Error::new(input.span(), "via is already set"));183						}184					} else {185						return Err(lookahead.error());186					}187188					if input.peek(Token![,]) {189						input.parse::<Token![,]>()?;190					} else if !input.is_empty() {191						return Err(syn::Error::new(input.span(), "expected end"));192					}193				}194			} else if lookahead.peek(Token![,]) || input.is_empty() {195				// Pass196			} else {197				return Err(lookahead.error());198			};199			out.push(Is {200				pascal_call_name: pascal_ident_to_call(&name),201				snake_call_name: pascal_ident_to_snake_call(&name),202				name,203				via,204				condition,205			});206			if input.peek(Token![,]) {207				input.parse::<Token![,]>()?;208				continue;209			} else {210				break;211			}212		}213		Ok(Self(out))214	}215}216217pub struct InterfaceInfo {218	name: Ident,219	is: IsList,220	inline_is: IsList,221	events: IsList,222	expect_selector: Option<u32>,223}224impl Parse for InterfaceInfo {225	fn parse(input: ParseStream) -> syn::Result<Self> {226		let mut name = None;227		let mut is = None;228		let mut inline_is = None;229		let mut events = None;230		let mut expect_selector = None;231		// TODO: create proc-macro to optimize proc-macro boilerplate? :D232		loop {233			let lookahead = input.lookahead1();234			if lookahead.peek(kw::name) {235				let k = input.parse::<kw::name>()?;236				input.parse::<Token![=]>()?;237				if name.replace(input.parse::<Ident>()?).is_some() {238					return Err(syn::Error::new(k.span(), "name is already set"));239				}240			} else if lookahead.peek(kw::is) {241				let k = input.parse::<kw::is>()?;242				let contents;243				parenthesized!(contents in input);244				if is.replace(contents.parse::<IsList>()?).is_some() {245					return Err(syn::Error::new(k.span(), "is is already set"));246				}247			} else if lookahead.peek(kw::inline_is) {248				let k = input.parse::<kw::inline_is>()?;249				let contents;250				parenthesized!(contents in input);251				if inline_is.replace(contents.parse::<IsList>()?).is_some() {252					return Err(syn::Error::new(k.span(), "inline_is is already set"));253				}254			} else if lookahead.peek(kw::events) {255				let k = input.parse::<kw::events>()?;256				let contents;257				parenthesized!(contents in input);258				if events.replace(contents.parse::<IsList>()?).is_some() {259					return Err(syn::Error::new(k.span(), "events is already set"));260				}261			} else if lookahead.peek(kw::expect_selector) {262				let k = input.parse::<kw::expect_selector>()?;263				input.parse::<Token![=]>()?;264				let value = input.parse::<LitInt>()?;265				if expect_selector266					.replace(value.base10_parse::<u32>()?)267					.is_some()268				{269					return Err(syn::Error::new(k.span(), "expect_selector is already set"));270				}271			} else if input.is_empty() {272				break;273			} else {274				return Err(lookahead.error());275			}276			if input.peek(Token![,]) {277				input.parse::<Token![,]>()?;278			} else {279				break;280			}281		}282		Ok(Self {283			name: name.ok_or_else(|| syn::Error::new(input.span(), "missing name"))?,284			is: is.unwrap_or_default(),285			inline_is: inline_is.unwrap_or_default(),286			events: events.unwrap_or_default(),287			expect_selector,288		})289	}290}291292struct MethodInfo {293	rename_selector: Option<String>,294	hide: bool,295}296impl Parse for MethodInfo {297	fn parse(input: ParseStream) -> syn::Result<Self> {298		let mut rename_selector = None;299		let mut hide = false;300		while !input.is_empty() {301			let lookahead = input.lookahead1();302			if lookahead.peek(kw::rename_selector) {303				let k = input.parse::<kw::rename_selector>()?;304				input.parse::<Token![=]>()?;305				if rename_selector306					.replace(input.parse::<LitStr>()?.value())307					.is_some()308				{309					return Err(syn::Error::new(k.span(), "rename_selector is already set"));310				}311			} else if lookahead.peek(kw::hide) {312				input.parse::<kw::hide>()?;313				hide = true;314			} else {315				return Err(lookahead.error());316			}317318			if input.peek(Token![,]) {319				input.parse::<Token![,]>()?;320			} else if !input.is_empty() {321				return Err(syn::Error::new(input.span(), "expected end"));322			}323		}324		Ok(Self {325			rename_selector,326			hide,327		})328	}329}330331trait AbiType {332	fn plain(&self) -> syn::Result<&Ident>;333	fn is_value(&self) -> bool;334	fn is_caller(&self) -> bool;335	fn is_special(&self) -> bool;336}337338impl AbiType for Type {339	fn plain(&self) -> syn::Result<&Ident> {340		let path = parse_path(self)?;341		let segment = parse_path_segment(path)?;342		if !segment.arguments.is_empty() {343			return Err(syn::Error::new(self.span(), "Not plain type"));344		}345		Ok(&segment.ident)346	}347348	fn is_value(&self) -> bool {349		if let Ok(ident) = self.plain() {350			return ident == "value";351		}352		false353	}354355	fn is_caller(&self) -> bool {356		if let Ok(ident) = self.plain() {357			return ident == "caller";358		}359		false360	}361362	fn is_special(&self) -> bool {363		self.is_caller() || self.is_value()364	}365}366367#[derive(Debug)]368struct MethodArg {369	name: Ident,370	camel_name: String,371	ty: Type,372}373impl MethodArg {374	fn try_from(value: &PatType) -> syn::Result<Self> {375		let name = parse_ident_from_pat(&value.pat)?.clone();376		Ok(Self {377			camel_name: cases::camelcase::to_camel_case(&name.to_string()),378			name,379			ty: value.ty.as_ref().clone(),380		})381	}382	fn is_value(&self) -> bool {383		self.ty.is_value()384	}385	fn is_caller(&self) -> bool {386		self.ty.is_caller()387	}388	fn is_special(&self) -> bool {389		self.ty.is_special()390	}391392	fn expand_call_def(&self) -> proc_macro2::TokenStream {393		assert!(!self.is_special());394		let name = &self.name;395		let ty = &self.ty;396397		quote! {398			#name: #ty399		}400	}401402	fn expand_parse(&self) -> proc_macro2::TokenStream {403		assert!(!self.is_special());404		let name = &self.name;405		let ty = &self.ty;406		quote! {407			#name: <#ty>::abi_read(reader)?408		}409	}410411	fn expand_call_arg(&self) -> proc_macro2::TokenStream {412		if self.is_value() {413			quote! {414				c.value.clone()415			}416		} else if self.is_caller() {417			quote! {418				c.caller.clone()419			}420		} else {421			let name = &self.name;422			quote! {423				#name424			}425		}426	}427428	fn expand_solidity_argument(&self) -> proc_macro2::TokenStream {429		let camel_name = &self.camel_name.to_string();430		let ty = &self.ty;431		quote! {432			<NamedArgument<#ty>>::new(#camel_name)433		}434	}435}436437#[derive(PartialEq)]438enum Mutability {439	Mutable,440	View,441	Pure,442}443444/// Group all keywords for this macro. Usage example:445/// #[solidity_interface(name = "B", inline_is(A))]446mod kw {447	syn::custom_keyword!(weight);448449	syn::custom_keyword!(via);450	syn::custom_keyword!(returns);451	syn::custom_keyword!(name);452	syn::custom_keyword!(is);453	syn::custom_keyword!(inline_is);454	syn::custom_keyword!(events);455	syn::custom_keyword!(expect_selector);456457	syn::custom_keyword!(rename_selector);458	syn::custom_keyword!(hide);459}460461/// Rust methods are parsed into this structure when Solidity code is generated462struct Method {463	name: Ident,464	camel_name: String,465	pascal_name: Ident,466	screaming_name: Ident,467	hide: bool,468	args: Vec<MethodArg>,469	has_normal_args: bool,470	has_value_args: bool,471	mutability: Mutability,472	result: Type,473	weight: Option<Expr>,474	docs: Vec<String>,475}476impl Method {477	fn try_from(value: &ImplItemMethod) -> syn::Result<Self> {478		let mut info = MethodInfo {479			rename_selector: None,480			hide: false,481		};482		let mut docs = Vec::new();483		let mut weight = None;484		for attr in &value.attrs {485			let ident = parse_ident_from_path(&attr.path, false)?;486			if ident == "solidity" {487				info = attr.parse_args::<MethodInfo>()?;488			} else if ident == "doc" {489				let args = attr.parse_meta().unwrap();490				let value = match args {491					Meta::NameValue(MetaNameValue {492						lit: Lit::Str(str), ..493					}) => str.value(),494					_ => unreachable!(),495				};496				docs.push(value);497			} else if ident == "weight" {498				weight = Some(attr.parse_args::<Expr>()?);499			}500		}501		let ident = &value.sig.ident;502		let ident_str = ident.to_string();503		if !cases::snakecase::is_snake_case(&ident_str) {504			return Err(syn::Error::new(ident.span(), "method name should be snake_cased\nif alternative solidity name needs to be set - use #[solidity] attribute"));505		}506507		let mut mutability = Mutability::Pure;508509		if let Some(FnArg::Receiver(receiver)) = value510			.sig511			.inputs512			.iter()513			.find(|arg| matches!(arg, FnArg::Receiver(_)))514		{515			if receiver.reference.is_none() {516				return Err(syn::Error::new(517					receiver.span(),518					"receiver should be by ref",519				));520			}521			if receiver.mutability.is_some() {522				mutability = Mutability::Mutable;523			} else {524				mutability = Mutability::View;525			}526		}527		let mut args = Vec::new();528		for typ in value529			.sig530			.inputs531			.iter()532			.filter(|arg| matches!(arg, FnArg::Typed(_)))533		{534			let typ = match typ {535				FnArg::Typed(typ) => typ,536				_ => unreachable!(),537			};538			args.push(MethodArg::try_from(typ)?);539		}540541		if mutability != Mutability::Mutable && args.iter().any(|arg| arg.is_value()) {542			return Err(syn::Error::new(543				args.iter().find(|arg| arg.is_value()).unwrap().ty.span(),544				"payable function should be mutable",545			));546		}547548		let result = match &value.sig.output {549			ReturnType::Type(_, ty) => ty,550			_ => return Err(syn::Error::new(value.sig.output.span(), "interface method should return Result<value>\nif there is no value to return - specify void (which is alias to unit)")),551		};552		let result = parse_result_ok(result)?;553554		let camel_name = info555			.rename_selector556			.unwrap_or_else(|| cases::camelcase::to_camel_case(&ident.to_string()));557		let has_normal_args = args.iter().filter(|arg| !arg.is_special()).count() != 0;558		let has_value_args = args.iter().any(|a| a.is_value());559560		Ok(Self {561			name: ident.clone(),562			camel_name,563			pascal_name: snake_ident_to_pascal(ident),564			screaming_name: snake_ident_to_screaming(ident),565			hide: info.hide,566			args,567			has_normal_args,568			has_value_args,569			mutability,570			result: result.clone(),571			weight,572			docs,573		})574	}575	fn expand_call_def(&self) -> proc_macro2::TokenStream {576		let defs = self577			.args578			.iter()579			.filter(|a| !a.is_special())580			.map(|a| a.expand_call_def());581		let pascal_name = &self.pascal_name;582		let docs = &self.docs;583584		if self.has_normal_args {585			quote! {586				#(#[doc = #docs])*587				#[allow(missing_docs)]588				#pascal_name {589					#(590						#defs,591					)*592				}593			}594		} else {595			quote! {596				#(#[doc = #docs])*597				#[allow(missing_docs)]598				#pascal_name599			}600		}601	}602603	fn expand_const(&self) -> proc_macro2::TokenStream {604		let screaming_name = &self.screaming_name;605		let screaming_name_signature = format_ident!("{}_SIGNATURE", &self.screaming_name);606		let custom_signature = self.expand_custom_signature();607		quote! {608			const #screaming_name_signature: ::evm_coder::custom_signature::SignatureUnit = #custom_signature;609			const #screaming_name: ::evm_coder::types::bytes4 = {610				let mut sum = ::evm_coder::sha3_const::Keccak256::new();611				let mut pos = 0;612				while pos < Self::#screaming_name_signature.len {613					sum = sum.update(&[Self::#screaming_name_signature.data[pos]; 1]);614					pos += 1;615				}616				let a = sum.finalize();617				[a[0], a[1], a[2], a[3]]618			};619		}620	}621622	fn expand_interface_id(&self) -> proc_macro2::TokenStream {623		let screaming_name = &self.screaming_name;624		quote! {625			interface_id ^= u32::from_be_bytes(Self::#screaming_name);626		}627	}628629	fn expand_parse(&self) -> proc_macro2::TokenStream {630		let pascal_name = &self.pascal_name;631		let screaming_name = &self.screaming_name;632		if self.has_normal_args {633			let parsers = self634				.args635				.iter()636				.filter(|a| !a.is_special())637				.map(|a| a.expand_parse());638			quote! {639				Self::#screaming_name => return Ok(Some(Self::#pascal_name {640					#(641						#parsers,642					)*643				}))644			}645		} else {646			quote! { Self::#screaming_name => return Ok(Some(Self::#pascal_name)) }647		}648	}649650	fn expand_variant_call(&self, call_name: &proc_macro2::Ident) -> proc_macro2::TokenStream {651		let pascal_name = &self.pascal_name;652		let name = &self.name;653654		let matcher = if self.has_normal_args {655			let names = self656				.args657				.iter()658				.filter(|a| !a.is_special())659				.map(|a| &a.name);660661			quote! {{662				#(663					#names,664				)*665			}}666		} else {667			quote! {}668		};669670		let receiver = match self.mutability {671			Mutability::Mutable | Mutability::View => quote! {self.},672			Mutability::Pure => quote! {Self::},673		};674		let args = self.args.iter().map(|a| a.expand_call_arg());675676		quote! {677			#call_name::#pascal_name #matcher => {678				#[allow(deprecated)]679				let result = #receiver #name(680					#(681						#args,682					)*683				)?;684				(&result).to_result()685			}686		}687	}688689	fn expand_variant_weight(&self) -> proc_macro2::TokenStream {690		let pascal_name = &self.pascal_name;691		if let Some(weight) = &self.weight {692			let matcher = if self.has_normal_args {693				let names = self694					.args695					.iter()696					.filter(|a| !a.is_special())697					.map(|a| &a.name);698699				quote! {{700					#(701						#names,702					)*703				}}704			} else {705				quote! {}706			};707			quote! {708				Self::#pascal_name #matcher => (#weight).into()709			}710		} else {711			let matcher = if self.has_normal_args {712				quote! {{..}}713			} else {714				quote! {}715			};716			quote! {717				Self::#pascal_name #matcher => ().into()718			}719		}720	}721722	fn expand_custom_signature(&self) -> proc_macro2::TokenStream {723		let mut args = TokenStream::new();724725		let mut has_params = false;726		for arg in self.args.iter().filter(|a| !a.is_special()) {727			has_params = true;728			let ty = &arg.ty;729			args.extend(quote! {nameof(<#ty>::SIGNATURE)});730			args.extend(quote! {fixed(",")})731		}732733		// Remove trailing comma734		if has_params {735			args.extend(quote! {shift_left(1)})736		}737738		let func_name = self.camel_name.clone();739		quote! { ::evm_coder::make_signature!(new fixed(#func_name) fixed("(") #args fixed(")")) }740	}741742	fn expand_solidity_function(&self) -> proc_macro2::TokenStream {743		let camel_name = &self.camel_name;744		let mutability = match self.mutability {745			Mutability::Mutable => quote! {SolidityMutability::Mutable},746			Mutability::View => quote! { SolidityMutability::View },747			Mutability::Pure => quote! {SolidityMutability::Pure},748		};749		let result = &self.result;750751		let args = self752			.args753			.iter()754			.filter(|a| !a.is_special())755			.map(MethodArg::expand_solidity_argument);756		let docs = &self.docs;757		let screaming_name = &self.screaming_name;758		let hide = self.hide;759		let custom_signature = self.expand_custom_signature();760		let is_payable = self.has_value_args;761762		quote! {763			SolidityFunction {764				docs: &[#(#docs),*],765				hide: #hide,766				selector: u32::from_be_bytes(Self::#screaming_name),767				custom_signature: #custom_signature,768				name: #camel_name,769				mutability: #mutability,770				is_payable: #is_payable,771				args: (772					#(773						#args,774					)*775				),776				result: <UnnamedArgument<#result>>::default(),777			}778		}779	}780}781782fn generics_list(gen: &Generics) -> proc_macro2::TokenStream {783	if gen.params.is_empty() {784		return quote! {};785	}786	let params = gen.params.iter().map(|p| match p {787		syn::GenericParam::Type(id) => {788			let v = &id.ident;789			quote! {#v}790		}791		syn::GenericParam::Lifetime(lt) => {792			let v = &lt.lifetime;793			quote! {#v}794		}795		syn::GenericParam::Const(c) => {796			let i = &c.ident;797			quote! {#i}798		}799	});800	quote! { #(#params),* }801}802fn generics_reference(gen: &Generics) -> proc_macro2::TokenStream {803	if gen.params.is_empty() {804		return quote! {};805	}806	let list = generics_list(gen);807	quote! { <#list> }808}809fn generics_data(gen: &Generics) -> proc_macro2::TokenStream {810	let list = generics_list(gen);811	if gen.params.len() == 1 {812		quote! {#list}813	} else {814		quote! { (#list) }815	}816}817818pub struct SolidityInterface {819	generics: Generics,820	name: Box<syn::Type>,821	info: InterfaceInfo,822	methods: Vec<Method>,823	docs: Vec<String>,824}825impl SolidityInterface {826	pub fn try_from(info: InterfaceInfo, value: &ItemImpl) -> syn::Result<Self> {827		let mut methods = Vec::new();828829		for item in &value.items {830			if let ImplItem::Method(method) = item {831				methods.push(Method::try_from(method)?)832			}833		}834		let mut docs = vec![];835		for attr in &value.attrs {836			let ident = parse_ident_from_path(&attr.path, false)?;837			if ident == "doc" {838				let args = attr.parse_meta().unwrap();839				let value = match args {840					Meta::NameValue(MetaNameValue {841						lit: Lit::Str(str), ..842					}) => str.value(),843					_ => unreachable!(),844				};845				docs.push(value);846			}847		}848		Ok(Self {849			generics: value.generics.clone(),850			name: value.self_ty.clone(),851			info,852			methods,853			docs,854		})855	}856	pub fn expand(self) -> proc_macro2::TokenStream {857		let name = self.name;858859		let solidity_name = self.info.name.to_string();860		let call_name = pascal_ident_to_call(&self.info.name);861		let generics = self.generics;862		let gen_ref = generics_reference(&generics);863		let gen_data = generics_data(&generics);864		let gen_where = &generics.where_clause;865866		let call_sub = self867			.info868			.inline_is869			.0870			.iter()871			.chain(self.info.is.0.iter())872			.map(|c| Is::expand_call_def(c, &gen_ref));873		let call_parse = self874			.info875			.inline_is876			.0877			.iter()878			.chain(self.info.is.0.iter())879			.map(|is| Is::expand_parse(is, &gen_ref));880		let call_variants = self881			.info882			.inline_is883			.0884			.iter()885			.chain(self.info.is.0.iter())886			.map(|c| Is::expand_variant_call(c, &call_name, &gen_ref));887		let weight_variants = self888			.info889			.inline_is890			.0891			.iter()892			.chain(self.info.is.0.iter())893			.map(Is::expand_variant_weight);894895		let inline_interface_id = self.info.inline_is.0.iter().map(Is::expand_interface_id);896		let supports_interface = self897			.info898			.is899			.0900			.iter()901			.map(|is| Is::expand_supports_interface(is, &gen_ref));902903		let calls = self.methods.iter().map(Method::expand_call_def);904		let consts = self.methods.iter().map(Method::expand_const);905		let interface_id = self.methods.iter().map(Method::expand_interface_id);906		let parsers = self.methods.iter().map(Method::expand_parse);907		let call_variants_this = self908			.methods909			.iter()910			.map(|m| Method::expand_variant_call(m, &call_name));911		let weight_variants_this = self.methods.iter().map(Method::expand_variant_weight);912		let solidity_functions = self.methods.iter().map(Method::expand_solidity_function);913914		// TODO: Inline inline_is915		let solidity_is = self916			.info917			.is918			.0919			.iter()920			.chain(self.info.inline_is.0.iter())921			.map(|is| is.name.to_string());922		let solidity_events_is = self.info.events.0.iter().map(|is| is.name.to_string());923		let solidity_generators = self924			.info925			.is926			.0927			.iter()928			.chain(self.info.inline_is.0.iter())929			.map(|is| Is::expand_generator(is, &gen_ref));930		let solidity_event_generators = self.info.events.0.iter().map(Is::expand_event_generator);931932		let docs = &self.docs;933934		quote! {935			#[derive(Debug)]936			#(#[doc = #docs])*937			pub enum #call_name #gen_ref {938				/// Inherited method939				ERC165Call(::evm_coder::ERC165Call, ::core::marker::PhantomData<#gen_data>),940				#(941					#calls,942				)*943				#(944					#call_sub,945				)*946			}947			impl #gen_ref #call_name #gen_ref {948				#(949					#consts950				)*951				/// Return this call ERC165 selector952				pub fn interface_id() -> ::evm_coder::types::bytes4 {953					let mut interface_id = 0;954					#(#interface_id)*955					#(#inline_interface_id)*956					u32::to_be_bytes(interface_id)957				}958				/// Generate solidity definitions for methods described in this interface959				#[cfg(feature = "stubgen")]960				pub fn generate_solidity_interface(tc: &evm_coder::solidity::TypeCollector, is_impl: bool) {961					use evm_coder::solidity::*;962					use core::fmt::Write;963					let interface = SolidityInterface {964						docs: &[#(#docs),*],965						name: #solidity_name,966						selector: Self::interface_id(),967						is: &["Dummy", "ERC165", #(968							#solidity_is,969						)* #(970							#solidity_events_is,971						)* ],972						functions: (#(973							#solidity_functions,974						)*),975					};976977					let mut out = ::evm_coder::types::string::new();978					if #solidity_name.starts_with("Inline") {979						out.push_str("/// @dev inlined interface\n");980					}981					let _ = interface.format(is_impl, &mut out, tc);982					tc.collect(out);983					#(984						#solidity_event_generators985					)*986					#(987						#solidity_generators988					)*989					if is_impl {990						tc.collect("/// @dev 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());991					} else {992						tc.collect("/// @dev common stubs holder\ninterface Dummy {\n}\ninterface ERC165 is Dummy {\n\tfunction supportsInterface(bytes4 interfaceID) external view returns (bool);\n}\n".into());993					}994				}995			}996			impl #gen_ref ::evm_coder::Call for #call_name #gen_ref {997				fn parse(method_id: ::evm_coder::types::bytes4, reader: &mut ::evm_coder::abi::AbiReader) -> ::evm_coder::execution::Result<Option<Self>> {998					use ::evm_coder::abi::AbiRead;999					match method_id {1000						::evm_coder::ERC165Call::INTERFACE_ID => return Ok(1001							::evm_coder::ERC165Call::parse(method_id, reader)?1002							.map(|c| Self::ERC165Call(c, ::core::marker::PhantomData))1003						),1004						#(1005							#parsers,1006						)*1007						_ => {},1008					}1009					#(1010						#call_parse1011					)else*1012					return Ok(None);1013				}1014			}1015			impl #generics #call_name #gen_ref1016			#gen_where1017			{1018				/// Is this contract implements specified ERC165 selector1019				pub fn supports_interface(this: &#name, interface_id: ::evm_coder::types::bytes4) -> bool {1020					interface_id != u32::to_be_bytes(0xffffff) && (1021						interface_id == ::evm_coder::ERC165Call::INTERFACE_ID ||1022						interface_id == Self::interface_id()1023						#(1024							|| #supports_interface1025						)*1026					)1027				}1028			}1029			impl #generics ::evm_coder::Weighted for #call_name #gen_ref1030			#gen_where1031			{1032				#[allow(unused_variables)]1033				fn weight(&self) -> ::evm_coder::execution::DispatchInfo {1034					match self {1035						#(1036							#weight_variants,1037						)*1038						// TODO: It should be very cheap, but not free1039						Self::ERC165Call(::evm_coder::ERC165Call::SupportsInterface {..}, _) => ::frame_support::weights::Weight::from_ref_time(100).into(),1040						#(1041							#weight_variants_this,1042						)*1043					}1044				}1045			}1046			impl #generics ::evm_coder::Callable<#call_name #gen_ref> for #name1047			#gen_where1048			{1049				#[allow(unreachable_code)] // In case of no inner calls1050				fn call(&mut self, c: Msg<#call_name #gen_ref>) -> ::evm_coder::execution::ResultWithPostInfo<::evm_coder::abi::AbiWriter> {1051					use ::evm_coder::abi::AbiWrite;1052					match c.call {1053						#(1054							#call_variants,1055						)*1056						#call_name::ERC165Call(::evm_coder::ERC165Call::SupportsInterface {interface_id}, _) => {1057							let mut writer = ::evm_coder::abi::AbiWriter::default();1058							writer.bool(&<#call_name #gen_ref>::supports_interface(self, interface_id));1059							return Ok(writer.into());1060						}1061						_ => {},1062					}1063					let mut writer = ::evm_coder::abi::AbiWriter::default();1064					match c.call {1065						#(1066							#call_variants_this,1067						)*1068						_ => Err(::evm_coder::execution::Error::from("method is not available").into()),1069					}1070				}1071			}1072		}1073	}1074}
after · crates/evm-coder/procedural/src/solidity_interface.rs
1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617#![allow(dead_code)]1819// NOTE: In order to understand this Rust macro better, first read this chapter20// about Procedural Macros in Rust book:21// https://doc.rust-lang.org/reference/procedural-macros.html2223use proc_macro2::TokenStream;24use quote::{quote, format_ident};25use inflector::cases;26use syn::{27	Expr, FnArg, Generics, Ident, ImplItem, ImplItemMethod, ItemImpl, Lit, Meta, MetaNameValue,28	PatType, ReturnType, Type,29	spanned::Spanned,30	parse::{Parse, ParseStream},31	parenthesized, Token, LitInt, LitStr,32};3334use crate::{35	parse_ident_from_pat, parse_ident_from_path, parse_path, parse_path_segment, parse_result_ok,36	pascal_ident_to_call, pascal_ident_to_snake_call, snake_ident_to_pascal,37	snake_ident_to_screaming,38};3940struct Is {41	name: Ident,42	pascal_call_name: Ident,43	snake_call_name: Ident,44	via: Option<(Type, Ident)>,45	condition: Option<Expr>,46}47impl Is {48	fn expand_call_def(&self, gen_ref: &proc_macro2::TokenStream) -> proc_macro2::TokenStream {49		let name = &self.name;50		let pascal_call_name = &self.pascal_call_name;51		quote! {52			#name(#pascal_call_name #gen_ref)53		}54	}5556	fn expand_interface_id(&self) -> proc_macro2::TokenStream {57		let pascal_call_name = &self.pascal_call_name;58		quote! {59			interface_id ^= u32::from_be_bytes(#pascal_call_name::interface_id());60		}61	}6263	fn expand_supports_interface(64		&self,65		generics: &proc_macro2::TokenStream,66	) -> proc_macro2::TokenStream {67		let pascal_call_name = &self.pascal_call_name;68		let condition = self.condition.as_ref().map(|condition| {69			quote! {70				(#condition) &&71			}72		});73		quote! {74			#condition <#pascal_call_name #generics>::supports_interface(this, interface_id)75		}76	}7778	fn expand_variant_weight(&self) -> proc_macro2::TokenStream {79		let name = &self.name;80		quote! {81			Self::#name(call) => call.weight()82		}83	}8485	fn expand_variant_call(86		&self,87		call_name: &proc_macro2::Ident,88		generics: &proc_macro2::TokenStream,89	) -> proc_macro2::TokenStream {90		let name = &self.name;91		let pascal_call_name = &self.pascal_call_name;92		let via_typ = self93			.via94			.as_ref()95			.map(|(t, _)| quote! {#t})96			.unwrap_or_else(|| quote! {Self});97		let via_map = self98			.via99			.as_ref()100			.map(|(_, i)| quote! {.#i()})101			.unwrap_or_default();102		let condition = self.condition.as_ref().map(|condition| {103			quote! {104				if ({let this = &self; (#condition)})105			}106		});107		quote! {108			#call_name::#name(call) #condition => return <#via_typ as ::evm_coder::Callable<#pascal_call_name #generics>>::call(self #via_map, Msg {109				call,110				caller: c.caller,111				value: c.value,112			})113		}114	}115116	fn expand_parse(&self, generics: &proc_macro2::TokenStream) -> proc_macro2::TokenStream {117		let name = &self.name;118		let pascal_call_name = &self.pascal_call_name;119		quote! {120			if let Some(parsed_call) = <#pascal_call_name #generics>::parse(method_id, reader)? {121				return Ok(Some(Self::#name(parsed_call)))122			}123		}124	}125126	fn expand_generator(&self, generics: &proc_macro2::TokenStream) -> proc_macro2::TokenStream {127		let pascal_call_name = &self.pascal_call_name;128		quote! {129			<#pascal_call_name #generics>::generate_solidity_interface(tc, is_impl);130		}131	}132133	fn expand_event_generator(&self) -> proc_macro2::TokenStream {134		let name = &self.name;135		quote! {136			#name::generate_solidity_interface(tc, is_impl);137		}138	}139}140141#[derive(Default)]142struct IsList(Vec<Is>);143impl Parse for IsList {144	fn parse(input: ParseStream) -> syn::Result<Self> {145		let mut out = vec![];146		loop {147			if input.is_empty() {148				break;149			}150			let name = input.parse::<Ident>()?;151			let lookahead = input.lookahead1();152153			let mut condition: Option<Expr> = None;154			let mut via: Option<(Type, Ident)> = None;155156			if lookahead.peek(syn::token::Paren) {157				let contents;158				parenthesized!(contents in input);159				let input = contents;160161				while !input.is_empty() {162					let lookahead = input.lookahead1();163					if lookahead.peek(Token![if]) {164						input.parse::<Token![if]>()?;165						let contents;166						parenthesized!(contents in input);167						let contents = contents.parse::<Expr>()?;168169						if condition.replace(contents).is_some() {170							return Err(syn::Error::new(input.span(), "condition is already set"));171						}172					} else if lookahead.peek(kw::via) {173						input.parse::<kw::via>()?;174						let contents;175						parenthesized!(contents in input);176177						let method = contents.parse::<Ident>()?;178						contents.parse::<kw::returns>()?;179						let ty = contents.parse::<Type>()?;180181						if via.replace((ty, method)).is_some() {182							return Err(syn::Error::new(input.span(), "via is already set"));183						}184					} else {185						return Err(lookahead.error());186					}187188					if input.peek(Token![,]) {189						input.parse::<Token![,]>()?;190					} else if !input.is_empty() {191						return Err(syn::Error::new(input.span(), "expected end"));192					}193				}194			} else if lookahead.peek(Token![,]) || input.is_empty() {195				// Pass196			} else {197				return Err(lookahead.error());198			};199			out.push(Is {200				pascal_call_name: pascal_ident_to_call(&name),201				snake_call_name: pascal_ident_to_snake_call(&name),202				name,203				via,204				condition,205			});206			if input.peek(Token![,]) {207				input.parse::<Token![,]>()?;208				continue;209			} else {210				break;211			}212		}213		Ok(Self(out))214	}215}216217pub struct InterfaceInfo {218	name: Ident,219	is: IsList,220	inline_is: IsList,221	events: IsList,222	expect_selector: Option<u32>,223}224impl Parse for InterfaceInfo {225	fn parse(input: ParseStream) -> syn::Result<Self> {226		let mut name = None;227		let mut is = None;228		let mut inline_is = None;229		let mut events = None;230		let mut expect_selector = None;231		// TODO: create proc-macro to optimize proc-macro boilerplate? :D232		loop {233			let lookahead = input.lookahead1();234			if lookahead.peek(kw::name) {235				let k = input.parse::<kw::name>()?;236				input.parse::<Token![=]>()?;237				if name.replace(input.parse::<Ident>()?).is_some() {238					return Err(syn::Error::new(k.span(), "name is already set"));239				}240			} else if lookahead.peek(kw::is) {241				let k = input.parse::<kw::is>()?;242				let contents;243				parenthesized!(contents in input);244				if is.replace(contents.parse::<IsList>()?).is_some() {245					return Err(syn::Error::new(k.span(), "is is already set"));246				}247			} else if lookahead.peek(kw::inline_is) {248				let k = input.parse::<kw::inline_is>()?;249				let contents;250				parenthesized!(contents in input);251				if inline_is.replace(contents.parse::<IsList>()?).is_some() {252					return Err(syn::Error::new(k.span(), "inline_is is already set"));253				}254			} else if lookahead.peek(kw::events) {255				let k = input.parse::<kw::events>()?;256				let contents;257				parenthesized!(contents in input);258				if events.replace(contents.parse::<IsList>()?).is_some() {259					return Err(syn::Error::new(k.span(), "events is already set"));260				}261			} else if lookahead.peek(kw::expect_selector) {262				let k = input.parse::<kw::expect_selector>()?;263				input.parse::<Token![=]>()?;264				let value = input.parse::<LitInt>()?;265				if expect_selector266					.replace(value.base10_parse::<u32>()?)267					.is_some()268				{269					return Err(syn::Error::new(k.span(), "expect_selector is already set"));270				}271			} else if input.is_empty() {272				break;273			} else {274				return Err(lookahead.error());275			}276			if input.peek(Token![,]) {277				input.parse::<Token![,]>()?;278			} else {279				break;280			}281		}282		Ok(Self {283			name: name.ok_or_else(|| syn::Error::new(input.span(), "missing name"))?,284			is: is.unwrap_or_default(),285			inline_is: inline_is.unwrap_or_default(),286			events: events.unwrap_or_default(),287			expect_selector,288		})289	}290}291292struct MethodInfo {293	rename_selector: Option<String>,294	hide: bool,295}296impl Parse for MethodInfo {297	fn parse(input: ParseStream) -> syn::Result<Self> {298		let mut rename_selector = None;299		let mut hide = false;300		while !input.is_empty() {301			let lookahead = input.lookahead1();302			if lookahead.peek(kw::rename_selector) {303				let k = input.parse::<kw::rename_selector>()?;304				input.parse::<Token![=]>()?;305				if rename_selector306					.replace(input.parse::<LitStr>()?.value())307					.is_some()308				{309					return Err(syn::Error::new(k.span(), "rename_selector is already set"));310				}311			} else if lookahead.peek(kw::hide) {312				input.parse::<kw::hide>()?;313				hide = true;314			} else {315				return Err(lookahead.error());316			}317318			if input.peek(Token![,]) {319				input.parse::<Token![,]>()?;320			} else if !input.is_empty() {321				return Err(syn::Error::new(input.span(), "expected end"));322			}323		}324		Ok(Self {325			rename_selector,326			hide,327		})328	}329}330331trait AbiType {332	fn plain(&self) -> syn::Result<&Ident>;333	fn is_value(&self) -> bool;334	fn is_caller(&self) -> bool;335	fn is_special(&self) -> bool;336}337338impl AbiType for Type {339	fn plain(&self) -> syn::Result<&Ident> {340		let path = parse_path(self)?;341		let segment = parse_path_segment(path)?;342		if !segment.arguments.is_empty() {343			return Err(syn::Error::new(self.span(), "Not plain type"));344		}345		Ok(&segment.ident)346	}347348	fn is_value(&self) -> bool {349		if let Ok(ident) = self.plain() {350			return ident == "value";351		}352		false353	}354355	fn is_caller(&self) -> bool {356		if let Ok(ident) = self.plain() {357			return ident == "caller";358		}359		false360	}361362	fn is_special(&self) -> bool {363		self.is_caller() || self.is_value()364	}365}366367#[derive(Debug)]368struct MethodArg {369	name: Ident,370	camel_name: String,371	ty: Type,372}373impl MethodArg {374	fn try_from(value: &PatType) -> syn::Result<Self> {375		let name = parse_ident_from_pat(&value.pat)?.clone();376		Ok(Self {377			camel_name: cases::camelcase::to_camel_case(&name.to_string()),378			name,379			ty: value.ty.as_ref().clone(),380		})381	}382	fn is_value(&self) -> bool {383		self.ty.is_value()384	}385	fn is_caller(&self) -> bool {386		self.ty.is_caller()387	}388	fn is_special(&self) -> bool {389		self.ty.is_special()390	}391392	fn expand_call_def(&self) -> proc_macro2::TokenStream {393		assert!(!self.is_special());394		let name = &self.name;395		let ty = &self.ty;396397		quote! {398			#name: #ty399		}400	}401402	fn expand_parse(&self) -> proc_macro2::TokenStream {403		assert!(!self.is_special());404		let name = &self.name;405		let ty = &self.ty;406		quote! {407			#name: <#ty>::abi_read(reader)?408		}409	}410411	fn expand_call_arg(&self) -> proc_macro2::TokenStream {412		if self.is_value() {413			quote! {414				c.value.clone()415			}416		} else if self.is_caller() {417			quote! {418				c.caller.clone()419			}420		} else {421			let name = &self.name;422			quote! {423				#name424			}425		}426	}427428	fn expand_solidity_argument(&self) -> proc_macro2::TokenStream {429		let camel_name = &self.camel_name.to_string();430		let ty = &self.ty;431		quote! {432			<NamedArgument<#ty>>::new(#camel_name)433		}434	}435}436437#[derive(PartialEq)]438enum Mutability {439	Mutable,440	View,441	Pure,442}443444/// Group all keywords for this macro. Usage example:445/// #[solidity_interface(name = "B", inline_is(A))]446mod kw {447	syn::custom_keyword!(weight);448449	syn::custom_keyword!(via);450	syn::custom_keyword!(returns);451	syn::custom_keyword!(name);452	syn::custom_keyword!(is);453	syn::custom_keyword!(inline_is);454	syn::custom_keyword!(events);455	syn::custom_keyword!(expect_selector);456457	syn::custom_keyword!(rename_selector);458	syn::custom_keyword!(hide);459}460461/// Rust methods are parsed into this structure when Solidity code is generated462struct Method {463	name: Ident,464	camel_name: String,465	pascal_name: Ident,466	screaming_name: Ident,467	hide: bool,468	args: Vec<MethodArg>,469	has_normal_args: bool,470	has_value_args: bool,471	mutability: Mutability,472	result: Type,473	weight: Option<Expr>,474	docs: Vec<String>,475}476impl Method {477	fn try_from(value: &ImplItemMethod) -> syn::Result<Self> {478		let mut info = MethodInfo {479			rename_selector: None,480			hide: false,481		};482		let mut docs = Vec::new();483		let mut weight = None;484		for attr in &value.attrs {485			let ident = parse_ident_from_path(&attr.path, false)?;486			if ident == "solidity" {487				info = attr.parse_args::<MethodInfo>()?;488			} else if ident == "doc" {489				let args = attr.parse_meta().unwrap();490				let value = match args {491					Meta::NameValue(MetaNameValue {492						lit: Lit::Str(str), ..493					}) => str.value(),494					_ => unreachable!(),495				};496				docs.push(value);497			} else if ident == "weight" {498				weight = Some(attr.parse_args::<Expr>()?);499			}500		}501		let ident = &value.sig.ident;502		let ident_str = ident.to_string();503		if !cases::snakecase::is_snake_case(&ident_str) {504			return Err(syn::Error::new(ident.span(), "method name should be snake_cased\nif alternative solidity name needs to be set - use #[solidity] attribute"));505		}506507		let mut mutability = Mutability::Pure;508509		if let Some(FnArg::Receiver(receiver)) = value510			.sig511			.inputs512			.iter()513			.find(|arg| matches!(arg, FnArg::Receiver(_)))514		{515			if receiver.reference.is_none() {516				return Err(syn::Error::new(517					receiver.span(),518					"receiver should be by ref",519				));520			}521			if receiver.mutability.is_some() {522				mutability = Mutability::Mutable;523			} else {524				mutability = Mutability::View;525			}526		}527		let mut args = Vec::new();528		for typ in value529			.sig530			.inputs531			.iter()532			.filter(|arg| matches!(arg, FnArg::Typed(_)))533		{534			let typ = match typ {535				FnArg::Typed(typ) => typ,536				_ => unreachable!(),537			};538			args.push(MethodArg::try_from(typ)?);539		}540541		if mutability != Mutability::Mutable && args.iter().any(|arg| arg.is_value()) {542			return Err(syn::Error::new(543				args.iter().find(|arg| arg.is_value()).unwrap().ty.span(),544				"payable function should be mutable",545			));546		}547548		let result = match &value.sig.output {549			ReturnType::Type(_, ty) => ty,550			_ => return Err(syn::Error::new(value.sig.output.span(), "interface method should return Result<value>\nif there is no value to return - specify void (which is alias to unit)")),551		};552		let result = parse_result_ok(result)?;553554		let camel_name = info555			.rename_selector556			.unwrap_or_else(|| cases::camelcase::to_camel_case(&ident.to_string()));557		let has_normal_args = args.iter().filter(|arg| !arg.is_special()).count() != 0;558		let has_value_args = args.iter().any(|a| a.is_value());559560		Ok(Self {561			name: ident.clone(),562			camel_name,563			pascal_name: snake_ident_to_pascal(ident),564			screaming_name: snake_ident_to_screaming(ident),565			hide: info.hide,566			args,567			has_normal_args,568			has_value_args,569			mutability,570			result: result.clone(),571			weight,572			docs,573		})574	}575	fn expand_call_def(&self) -> proc_macro2::TokenStream {576		let defs = self577			.args578			.iter()579			.filter(|a| !a.is_special())580			.map(|a| a.expand_call_def());581		let pascal_name = &self.pascal_name;582		let docs = &self.docs;583584		if self.has_normal_args {585			quote! {586				#(#[doc = #docs])*587				#[allow(missing_docs)]588				#pascal_name {589					#(590						#defs,591					)*592				}593			}594		} else {595			quote! {596				#(#[doc = #docs])*597				#[allow(missing_docs)]598				#pascal_name599			}600		}601	}602603	fn expand_const(&self) -> proc_macro2::TokenStream {604		let screaming_name = &self.screaming_name;605		let screaming_name_signature = format_ident!("{}_SIGNATURE", &self.screaming_name);606		let custom_signature = self.expand_custom_signature();607		quote! {608			const #screaming_name_signature: ::evm_coder::custom_signature::SignatureUnit = #custom_signature;609			const #screaming_name: ::evm_coder::types::bytes4 = {610				let mut sum = ::evm_coder::sha3_const::Keccak256::new();611				let mut pos = 0;612				while pos < Self::#screaming_name_signature.len {613					sum = sum.update(&[Self::#screaming_name_signature.data[pos]; 1]);614					pos += 1;615				}616				let a = sum.finalize();617				[a[0], a[1], a[2], a[3]]618			};619		}620	}621622	fn expand_interface_id(&self) -> proc_macro2::TokenStream {623		let screaming_name = &self.screaming_name;624		quote! {625			interface_id ^= u32::from_be_bytes(Self::#screaming_name);626		}627	}628629	fn expand_parse(&self) -> proc_macro2::TokenStream {630		let pascal_name = &self.pascal_name;631		let screaming_name = &self.screaming_name;632		if self.has_normal_args {633			let parsers = self634				.args635				.iter()636				.filter(|a| !a.is_special())637				.map(|a| a.expand_parse());638			quote! {639				Self::#screaming_name => return Ok(Some(Self::#pascal_name {640					#(641						#parsers,642					)*643				}))644			}645		} else {646			quote! { Self::#screaming_name => return Ok(Some(Self::#pascal_name)) }647		}648	}649650	fn expand_variant_call(&self, call_name: &proc_macro2::Ident) -> proc_macro2::TokenStream {651		let pascal_name = &self.pascal_name;652		let name = &self.name;653654		let matcher = if self.has_normal_args {655			let names = self656				.args657				.iter()658				.filter(|a| !a.is_special())659				.map(|a| &a.name);660661			quote! {{662				#(663					#names,664				)*665			}}666		} else {667			quote! {}668		};669670		let receiver = match self.mutability {671			Mutability::Mutable | Mutability::View => quote! {self.},672			Mutability::Pure => quote! {Self::},673		};674		let args = self.args.iter().map(|a| a.expand_call_arg());675676		quote! {677			#call_name::#pascal_name #matcher => {678				#[allow(deprecated)]679				let result = #receiver #name(680					#(681						#args,682					)*683				)?;684				(&result).to_result()685			}686		}687	}688689	fn expand_variant_weight(&self) -> proc_macro2::TokenStream {690		let pascal_name = &self.pascal_name;691		if let Some(weight) = &self.weight {692			let matcher = if self.has_normal_args {693				let names = self694					.args695					.iter()696					.filter(|a| !a.is_special())697					.map(|a| &a.name);698699				quote! {{700					#(701						#names,702					)*703				}}704			} else {705				quote! {}706			};707			quote! {708				Self::#pascal_name #matcher => (#weight).into()709			}710		} else {711			let matcher = if self.has_normal_args {712				quote! {{..}}713			} else {714				quote! {}715			};716			quote! {717				Self::#pascal_name #matcher => ().into()718			}719		}720	}721722	fn expand_custom_signature(&self) -> proc_macro2::TokenStream {723		let mut args = TokenStream::new();724725		let mut has_params = false;726		for arg in self.args.iter().filter(|a| !a.is_special()) {727			has_params = true;728			let ty = &arg.ty;729			args.extend(quote! {nameof(<#ty>::SIGNATURE)});730			args.extend(quote! {fixed(",")})731		}732733		// Remove trailing comma734		if has_params {735			args.extend(quote! {shift_left(1)})736		}737738		let func_name = self.camel_name.clone();739		quote! { ::evm_coder::make_signature!(new fixed(#func_name) fixed("(") #args fixed(")")) }740	}741742	fn expand_solidity_function(&self) -> proc_macro2::TokenStream {743		let camel_name = &self.camel_name;744		let mutability = match self.mutability {745			Mutability::Mutable => quote! {SolidityMutability::Mutable},746			Mutability::View => quote! { SolidityMutability::View },747			Mutability::Pure => quote! {SolidityMutability::Pure},748		};749		let result = &self.result;750751		let args = self752			.args753			.iter()754			.filter(|a| !a.is_special())755			.map(MethodArg::expand_solidity_argument);756		let docs = &self.docs;757		let screaming_name = &self.screaming_name;758		let hide = self.hide;759		let custom_signature = self.expand_custom_signature();760		let is_payable = self.has_value_args;761762		quote! {763			SolidityFunction {764				docs: &[#(#docs),*],765				hide: #hide,766				selector: u32::from_be_bytes(Self::#screaming_name),767				custom_signature: #custom_signature,768				name: #camel_name,769				mutability: #mutability,770				is_payable: #is_payable,771				args: (772					#(773						#args,774					)*775				),776				result: <UnnamedArgument<#result>>::default(),777			}778		}779	}780}781782fn generics_list(gen: &Generics) -> proc_macro2::TokenStream {783	if gen.params.is_empty() {784		return quote! {};785	}786	let params = gen.params.iter().map(|p| match p {787		syn::GenericParam::Type(id) => {788			let v = &id.ident;789			quote! {#v}790		}791		syn::GenericParam::Lifetime(lt) => {792			let v = &lt.lifetime;793			quote! {#v}794		}795		syn::GenericParam::Const(c) => {796			let i = &c.ident;797			quote! {#i}798		}799	});800	quote! { #(#params),* }801}802fn generics_reference(gen: &Generics) -> proc_macro2::TokenStream {803	if gen.params.is_empty() {804		return quote! {};805	}806	let list = generics_list(gen);807	quote! { <#list> }808}809fn generics_data(gen: &Generics) -> proc_macro2::TokenStream {810	let list = generics_list(gen);811	if gen.params.len() == 1 {812		quote! {#list}813	} else {814		quote! { (#list) }815	}816}817818pub struct SolidityInterface {819	generics: Generics,820	name: Box<syn::Type>,821	info: InterfaceInfo,822	methods: Vec<Method>,823	docs: Vec<String>,824}825impl SolidityInterface {826	pub fn try_from(info: InterfaceInfo, value: &ItemImpl) -> syn::Result<Self> {827		let mut methods = Vec::new();828829		for item in &value.items {830			if let ImplItem::Method(method) = item {831				methods.push(Method::try_from(method)?)832			}833		}834		let mut docs = vec![];835		for attr in &value.attrs {836			let ident = parse_ident_from_path(&attr.path, false)?;837			if ident == "doc" {838				let args = attr.parse_meta().unwrap();839				let value = match args {840					Meta::NameValue(MetaNameValue {841						lit: Lit::Str(str), ..842					}) => str.value(),843					_ => unreachable!(),844				};845				docs.push(value);846			}847		}848		Ok(Self {849			generics: value.generics.clone(),850			name: value.self_ty.clone(),851			info,852			methods,853			docs,854		})855	}856	pub fn expand(self) -> proc_macro2::TokenStream {857		let name = self.name;858859		let solidity_name = self.info.name.to_string();860		let call_name = pascal_ident_to_call(&self.info.name);861		let generics = self.generics;862		let gen_ref = generics_reference(&generics);863		let gen_data = generics_data(&generics);864		let gen_where = &generics.where_clause;865866		let call_sub = self867			.info868			.inline_is869			.0870			.iter()871			.chain(self.info.is.0.iter())872			.map(|c| Is::expand_call_def(c, &gen_ref));873		let call_parse = self874			.info875			.inline_is876			.0877			.iter()878			.chain(self.info.is.0.iter())879			.map(|is| Is::expand_parse(is, &gen_ref));880		let call_variants = self881			.info882			.inline_is883			.0884			.iter()885			.chain(self.info.is.0.iter())886			.map(|c| Is::expand_variant_call(c, &call_name, &gen_ref));887		let weight_variants = self888			.info889			.inline_is890			.0891			.iter()892			.chain(self.info.is.0.iter())893			.map(Is::expand_variant_weight);894895		let inline_interface_id = self.info.inline_is.0.iter().map(Is::expand_interface_id);896		let supports_interface = self897			.info898			.is899			.0900			.iter()901			.map(|is| Is::expand_supports_interface(is, &gen_ref));902903		let calls = self.methods.iter().map(Method::expand_call_def);904		let consts = self.methods.iter().map(Method::expand_const);905		let interface_id = self.methods.iter().map(Method::expand_interface_id);906		let parsers = self.methods.iter().map(Method::expand_parse);907		let call_variants_this = self908			.methods909			.iter()910			.map(|m| Method::expand_variant_call(m, &call_name));911		let weight_variants_this = self.methods.iter().map(Method::expand_variant_weight);912		let solidity_functions = self.methods.iter().map(Method::expand_solidity_function);913914		// TODO: Inline inline_is915		let solidity_is = self916			.info917			.is918			.0919			.iter()920			.chain(self.info.inline_is.0.iter())921			.map(|is| is.name.to_string());922		let solidity_events_is = self.info.events.0.iter().map(|is| is.name.to_string());923		let solidity_generators = self924			.info925			.is926			.0927			.iter()928			.chain(self.info.inline_is.0.iter())929			.map(|is| Is::expand_generator(is, &gen_ref));930		let solidity_event_generators = self.info.events.0.iter().map(Is::expand_event_generator);931		let solidity_events_idents = self.info.events.0.iter().map(|is| is.name.clone());932		let docs = &self.docs;933934		quote! {935			#(936				const _: ::core::marker::PhantomData<#solidity_events_idents> = ::core::marker::PhantomData;937			)*938			#[derive(Debug)]939			#(#[doc = #docs])*940			pub enum #call_name #gen_ref {941				/// Inherited method942				ERC165Call(::evm_coder::ERC165Call, ::core::marker::PhantomData<#gen_data>),943				#(944					#calls,945				)*946				#(947					#call_sub,948				)*949			}950			impl #gen_ref #call_name #gen_ref {951				#(952					#consts953				)*954				/// Return this call ERC165 selector955				pub fn interface_id() -> ::evm_coder::types::bytes4 {956					let mut interface_id = 0;957					#(#interface_id)*958					#(#inline_interface_id)*959					u32::to_be_bytes(interface_id)960				}961				/// Generate solidity definitions for methods described in this interface962				#[cfg(feature = "stubgen")]963				pub fn generate_solidity_interface(tc: &evm_coder::solidity::TypeCollector, is_impl: bool) {964					use evm_coder::solidity::*;965					use core::fmt::Write;966					let interface = SolidityInterface {967						docs: &[#(#docs),*],968						name: #solidity_name,969						selector: Self::interface_id(),970						is: &["Dummy", "ERC165", #(971							#solidity_is,972						)* #(973							#solidity_events_is,974						)* ],975						functions: (#(976							#solidity_functions,977						)*),978					};979980					let mut out = ::evm_coder::types::string::new();981					if #solidity_name.starts_with("Inline") {982						out.push_str("/// @dev inlined interface\n");983					}984					let _ = interface.format(is_impl, &mut out, tc);985					tc.collect(out);986					#(987						#solidity_event_generators988					)*989					#(990						#solidity_generators991					)*992					if is_impl {993						tc.collect("/// @dev 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());994					} else {995						tc.collect("/// @dev common stubs holder\ninterface Dummy {\n}\ninterface ERC165 is Dummy {\n\tfunction supportsInterface(bytes4 interfaceID) external view returns (bool);\n}\n".into());996					}997				}998			}999			impl #gen_ref ::evm_coder::Call for #call_name #gen_ref {1000				fn parse(method_id: ::evm_coder::types::bytes4, reader: &mut ::evm_coder::abi::AbiReader) -> ::evm_coder::execution::Result<Option<Self>> {1001					use ::evm_coder::abi::AbiRead;1002					match method_id {1003						::evm_coder::ERC165Call::INTERFACE_ID => return Ok(1004							::evm_coder::ERC165Call::parse(method_id, reader)?1005							.map(|c| Self::ERC165Call(c, ::core::marker::PhantomData))1006						),1007						#(1008							#parsers,1009						)*1010						_ => {},1011					}1012					#(1013						#call_parse1014					)else*1015					return Ok(None);1016				}1017			}1018			impl #generics #call_name #gen_ref1019			#gen_where1020			{1021				/// Is this contract implements specified ERC165 selector1022				pub fn supports_interface(this: &#name, interface_id: ::evm_coder::types::bytes4) -> bool {1023					interface_id != u32::to_be_bytes(0xffffff) && (1024						interface_id == ::evm_coder::ERC165Call::INTERFACE_ID ||1025						interface_id == Self::interface_id()1026						#(1027							|| #supports_interface1028						)*1029					)1030				}1031			}1032			impl #generics ::evm_coder::Weighted for #call_name #gen_ref1033			#gen_where1034			{1035				#[allow(unused_variables)]1036				fn weight(&self) -> ::evm_coder::execution::DispatchInfo {1037					match self {1038						#(1039							#weight_variants,1040						)*1041						// TODO: It should be very cheap, but not free1042						Self::ERC165Call(::evm_coder::ERC165Call::SupportsInterface {..}, _) => ::frame_support::weights::Weight::from_ref_time(100).into(),1043						#(1044							#weight_variants_this,1045						)*1046					}1047				}1048			}1049			impl #generics ::evm_coder::Callable<#call_name #gen_ref> for #name1050			#gen_where1051			{1052				#[allow(unreachable_code)] // In case of no inner calls1053				fn call(&mut self, c: Msg<#call_name #gen_ref>) -> ::evm_coder::execution::ResultWithPostInfo<::evm_coder::abi::AbiWriter> {1054					use ::evm_coder::abi::AbiWrite;1055					match c.call {1056						#(1057							#call_variants,1058						)*1059						#call_name::ERC165Call(::evm_coder::ERC165Call::SupportsInterface {interface_id}, _) => {1060							let mut writer = ::evm_coder::abi::AbiWriter::default();1061							writer.bool(&<#call_name #gen_ref>::supports_interface(self, interface_id));1062							return Ok(writer.into());1063						}1064						_ => {},1065					}1066					let mut writer = ::evm_coder::abi::AbiWriter::default();1067					match c.call {1068						#(1069							#call_variants_this,1070						)*1071						_ => Err(::evm_coder::execution::Error::from("method is not available").into()),1072					}1073				}1074			}1075		}1076	}1077}
modifiedpallets/unique/Cargo.tomldiffbeforeafterboth
--- a/pallets/unique/Cargo.toml
+++ b/pallets/unique/Cargo.toml
@@ -34,7 +34,7 @@
 ]
 try-runtime = ["frame-support/try-runtime"]
 limit-testing = ["up-data-structs/limit-testing"]
-
+stubgen = ["evm-coder/stubgen", "pallet-common/stubgen"]
 ################################################################################
 # Standart Dependencies
 
modifiedpallets/unique/src/eth/mod.rsdiffbeforeafterboth
--- a/pallets/unique/src/eth/mod.rs
+++ b/pallets/unique/src/eth/mod.rs
@@ -23,7 +23,10 @@
 use crate::Pallet;
 
 use pallet_common::{
-	CollectionById, dispatch::CollectionDispatch, erc::static_property::key, Pallet as PalletCommon,
+	CollectionById,
+	dispatch::CollectionDispatch,
+	erc::{static_property::key, CollectionHelpersEvents},
+	Pallet as PalletCommon,
 };
 use pallet_evm::{account::CrossAccountId, OnMethodCall, PrecompileHandle, PrecompileResult};
 use pallet_evm_coder_substrate::{dispatch_to_evm, SubstrateRecorder, WithRecorder};