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

difftreelog

source

crates/evm-coder-macros/src/lib.rs8.5 KiBsourcehistory
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)]1819use darling::FromMeta;20use inflector::cases;21use proc_macro::TokenStream;22use quote::quote;23use sha3::{Digest, Keccak256};24use syn::{25	AttributeArgs, DeriveInput, GenericArgument, Ident, ItemImpl, Pat, Path, PathArguments,26	PathSegment, Type, parse_macro_input, spanned::Spanned,27};2829mod solidity_interface;30mod to_log;3132fn fn_selector_str(input: &str) -> u32 {33	let mut hasher = Keccak256::new();34	hasher.update(input.as_bytes());35	let result = hasher.finalize();3637	let mut selector_bytes = [0; 4];38	selector_bytes.copy_from_slice(&result[0..4]);3940	u32::from_be_bytes(selector_bytes)41}4243/// Returns solidity function selector (first 4 bytes of hash) by its44/// textual representation45///46/// ```ignore47/// use evm_coder_macros::fn_selector;48///49/// assert_eq!(fn_selector!(transfer(address, uint256)), 0xa9059cbb);50/// ```51#[proc_macro]52pub fn fn_selector(input: TokenStream) -> TokenStream {53	let input = input.to_string().replace(' ', "");54	let selector = fn_selector_str(&input);5556	(quote! {57		#selector58	})59	.into()60}6162fn event_selector_str(input: &str) -> [u8; 32] {63	let mut hasher = Keccak256::new();64	hasher.update(input.as_bytes());65	let result = hasher.finalize();6667	let mut selector_bytes = [0; 32];68	selector_bytes.copy_from_slice(&result[0..32]);69	selector_bytes70}7172/// Returns solidity topic (hash) by its textual representation73///74/// ```ignore75/// use evm_coder_macros::event_topic;76///77/// assert_eq!(78///     format!("{:x}", event_topic!(Transfer(address, address, uint256))),79///     "ddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef",80/// );81/// ```82#[proc_macro]83pub fn event_topic(stream: TokenStream) -> TokenStream {84	let input = stream.to_string().replace(' ', "");85	let selector_bytes = event_selector_str(&input);8687	(quote! {88		::primitive_types::H256([#(89			#selector_bytes,90		)*])91	})92	.into()93}9495fn parse_path(ty: &Type) -> syn::Result<&Path> {96	match &ty {97		syn::Type::Path(pat) => {98			if let Some(qself) = &pat.qself {99				return Err(syn::Error::new(qself.ty.span(), "no receiver expected"));100			}101			Ok(&pat.path)102		}103		_ => Err(syn::Error::new(ty.span(), "expected ty to be path")),104	}105}106107fn parse_path_segment(path: &Path) -> syn::Result<&PathSegment> {108	if path.segments.len() != 1 {109		return Err(syn::Error::new(110			path.span(),111			"expected path to have only segment",112		));113	}114	let last_segment = &path.segments.last().unwrap();115	Ok(last_segment)116}117118fn parse_ident_from_pat(pat: &Pat) -> syn::Result<&Ident> {119	match pat {120		Pat::Ident(i) => Ok(&i.ident),121		_ => Err(syn::Error::new(pat.span(), "expected pat ident")),122	}123}124125fn parse_ident_from_segment(segment: &PathSegment, allow_generics: bool) -> syn::Result<&Ident> {126	if segment.arguments != PathArguments::None && !allow_generics {127		return Err(syn::Error::new(128			segment.arguments.span(),129			"unexpected generic type",130		));131	}132	Ok(&segment.ident)133}134135fn parse_ident_from_path(path: &Path, allow_generics: bool) -> syn::Result<&Ident> {136	let segment = parse_path_segment(path)?;137	parse_ident_from_segment(segment, allow_generics)138}139140fn parse_ident_from_type(ty: &Type, allow_generics: bool) -> syn::Result<&Ident> {141	let path = parse_path(ty)?;142	parse_ident_from_path(path, allow_generics)143}144145// Gets T out of Result<T>146fn parse_result_ok(ty: &Type) -> syn::Result<&Type> {147	let path = parse_path(ty)?;148	let segment = parse_path_segment(path)?;149150	if segment.ident != "Result" {151		return Err(syn::Error::new(152			ty.span(),153			"expected Result as return type (no renamed aliases allowed)",154		));155	}156	let args = match &segment.arguments {157		PathArguments::AngleBracketed(e) => e,158		_ => {159			return Err(syn::Error::new(160				segment.arguments.span(),161				"missing Result generics",162			))163		}164	};165166	let args = &args.args;167	let arg = args.first().unwrap();168169	let ty = match arg {170		GenericArgument::Type(ty) => ty,171		_ => {172			return Err(syn::Error::new(173				arg.span(),174				"expected first generic to be type",175			))176		}177	};178179	Ok(ty)180}181182fn pascal_ident_to_call(ident: &Ident) -> Ident {183	let name = format!("{}Call", ident);184	Ident::new(&name, ident.span())185}186fn snake_ident_to_pascal(ident: &Ident) -> Ident {187	let name = ident.to_string();188	let name = cases::pascalcase::to_pascal_case(&name);189	Ident::new(&name, ident.span())190}191fn snake_ident_to_screaming(ident: &Ident) -> Ident {192	let name = ident.to_string();193	let name = cases::screamingsnakecase::to_screaming_snake_case(&name);194	Ident::new(&name, ident.span())195}196fn pascal_ident_to_snake_call(ident: &Ident) -> Ident {197	let name = ident.to_string();198	let name = cases::snakecase::to_snake_case(&name);199	let name = format!("call_{}", name);200	Ident::new(&name, ident.span())201}202203/// Derives call enum implementing [`evm_coder::Callable`], [`evm_coder::Weighted`]204/// and [`evm_coder::Call`] from impl block205///206/// ## Macro syntax207///208/// `#[solidity_interface(name, is, inline_is, events)]`209/// - *name*: used in generated code, and for Call enum name210/// - *is*: used to provide call inheritance, not found methods will be delegated to all contracts211/// specified in is/inline_is212/// - *inline_is*: same as is, but selectors for passed contracts will be used by derived ERC165213/// implementation214///215/// `#[weight(value)]`216/// Can be added to every method of impl block, used for deriving [`evm_coder::Weighted`], which217/// is used by substrate bridge218/// - *value*: expression, which evaluates to weight required to call this method.219/// This expression can use call arguments to calculate non-constant execution time.220/// This expression should evaluate faster than actual execution does, and may provide worser case221/// than one is called222///223/// `#[solidity_interface(rename_selector)]`224/// - *rename_selector*: by default, selector name will be generated by transforming method name225/// from snake_case to camelCase. Use this option, if other naming convention is required.226/// I.e: method `token_uri` will be automatically renamed to `tokenUri` in selector, but name227/// required by ERC721 standard is `tokenURI`, thus we need to specify `rename_selector = "tokenURI"`228/// explicitly229///230/// Also, any contract method may have doc comments, which will be automatically added to generated231/// solidity interface definitions232///233/// ## Example234///235/// ```ignore236/// struct SuperContract;237/// struct InlineContract;238/// struct Contract;239///240/// #[derive(ToLog)]241/// enum ContractEvents {242///     Event(#[indexed] uint32),243/// }244///245/// #[solidity_interface(name = "MyContract", is(SuperContract), inline_is(InlineContract))]246/// impl Contract {247///     /// Multiply two numbers248///     #[weight(200 + a + b)]249///     #[solidity_interface(rename_selector = "mul")]250///     fn mul(&mut self, a: uint32, b: uint32) -> Result<uint32> {251///         Ok(a.checked_mul(b).ok_or("overflow")?)252///     }253/// }254/// ```255#[proc_macro_attribute]256pub fn solidity_interface(args: TokenStream, stream: TokenStream) -> TokenStream {257	let args = parse_macro_input!(args as AttributeArgs);258	let args = solidity_interface::InterfaceInfo::from_list(&args).unwrap();259260	let input: ItemImpl = match syn::parse(stream) {261		Ok(t) => t,262		Err(e) => return e.to_compile_error().into(),263	};264265	let expanded = match solidity_interface::SolidityInterface::try_from(args, &input) {266		Ok(v) => v.expand(),267		Err(e) => e.to_compile_error(),268	};269270	(quote! {271		#input272273		#expanded274	})275	.into()276}277278#[proc_macro_attribute]279pub fn solidity(_args: TokenStream, stream: TokenStream) -> TokenStream {280	stream281}282#[proc_macro_attribute]283pub fn weight(_args: TokenStream, stream: TokenStream) -> TokenStream {284	stream285}286287/// ## Syntax288///289/// `#[indexed]`290/// Marks this field as indexed, so it will appear in [`ethereum::Log`] topics instead of data291#[proc_macro_derive(ToLog, attributes(indexed))]292pub fn to_log(value: TokenStream) -> TokenStream {293	let input = parse_macro_input!(value as DeriveInput);294295	match to_log::Events::try_from(&input) {296		Ok(e) => e.expand(),297		Err(e) => e.to_compile_error(),298	}299	.into()300}