git.delta.rocks / unique-network / refs/commits / 5a3fe2c70832

difftreelog

refactor unify function and type signature handling

Yaroslav Bolyukin2022-11-02parent: #4c1a924.patch.diff
in: master

12 files changed

modifiedcrates/evm-coder/procedural/src/solidity_interface.rsdiffbeforeafterboth
--- a/crates/evm-coder/procedural/src/solidity_interface.rs
+++ b/crates/evm-coder/procedural/src/solidity_interface.rs
@@ -24,8 +24,8 @@
 use quote::{quote, format_ident};
 use inflector::cases;
 use syn::{
-	Expr, FnArg, GenericArgument, Generics, Ident, ImplItem, ImplItemMethod, ItemImpl, Lit, Meta,
-	MetaNameValue, PatType, PathArguments, ReturnType, Type,
+	Expr, FnArg, Generics, Ident, ImplItem, ImplItemMethod, ItemImpl, Lit, Meta, MetaNameValue,
+	PatType, ReturnType, Type,
 	spanned::Spanned,
 	parse::{Parse, ParseStream},
 	parenthesized, Token, LitInt, LitStr,
@@ -601,12 +601,12 @@
 		let screaming_name_signature = format_ident!("{}_SIGNATURE", &self.screaming_name);
 		let custom_signature = self.expand_custom_signature();
 		quote! {
-			const #screaming_name_signature: ::evm_coder::custom_signature::FunctionSignature = #custom_signature;
+			const #screaming_name_signature: ::evm_coder::custom_signature::SignatureUnit = #custom_signature;
 			const #screaming_name: ::evm_coder::types::bytes4 = {
 				let mut sum = ::evm_coder::sha3_const::Keccak256::new();
 				let mut pos = 0;
-				while pos < Self::#screaming_name_signature.unit.len {
-					sum = sum.update(&[Self::#screaming_name_signature.unit.data[pos]; 1]);
+				while pos < Self::#screaming_name_signature.len {
+					sum = sum.update(&[Self::#screaming_name_signature.data[pos]; 1]);
 					pos += 1;
 				}
 				let a = sum.finalize();
@@ -710,192 +710,28 @@
 			};
 			quote! {
 				Self::#pascal_name #matcher => ().into()
-			}
-		}
-	}
-
-	fn expand_type(ty: &Type, token_stream: &mut proc_macro2::TokenStream, read_signature: bool) {
-		match ty {
-			Type::Path(tp) => {
-				if let Some(qself) = &tp.qself {
-					panic!("no receiver expected {:?}", qself.ty.span());
-				}
-				let path = &tp.path;
-				if path.segments.len() != 1 {
-					panic!("expected path to have only one segment {:?}", path.span());
-				}
-				let last_segment = path.segments.last().unwrap();
-
-				if last_segment.ident == "Vec" {
-					let args = match &last_segment.arguments {
-						PathArguments::AngleBracketed(e) => e,
-						_ => {
-							panic!("missing Vec generic {:?}", last_segment.arguments.span());
-						}
-					};
-					let args = &args.args;
-					if args.len() != 1 {
-						panic!("expected only one generic for vec {:?}", args.span());
-					}
-					let arg = args.first().expect("first arg");
-
-					let ty = match arg {
-						GenericArgument::Type(ty) => ty,
-						_ => {
-							panic!("expected first generic to be type {:?}", arg.span());
-						}
-					};
-
-					let mut vec_token = proc_macro2::TokenStream::new();
-					Self::expand_type(ty, &mut vec_token, false);
-					vec_token = if read_signature {
-						quote! { (<Vec<#vec_token>>::SIGNATURE) }
-					} else {
-						quote! { <Vec<#vec_token>> }
-					};
-					token_stream.extend(vec_token);
-				} else {
-					if !last_segment.arguments.is_empty() {
-						panic!(
-							"unexpected generic arguments for non-vec type {:?}",
-							last_segment.arguments.span()
-						);
-					}
-
-					let ident = &last_segment.ident;
-					let plain_token = if read_signature {
-						quote! {
-							(<#ident>::SIGNATURE)
-						}
-					} else {
-						quote! {
-							#ident
-						}
-					};
-
-					token_stream.extend(plain_token);
-				}
-			}
-
-			Type::Tuple(tt) => {
-				// for ty in tt.elems.iter() {
-				// 	out.push(AbiType::try_from(ty)?)
-				// }
-
-				let mut tuple_types = proc_macro2::TokenStream::new();
-				let mut is_first = true;
-
-				for ty in tt.elems.iter() {
-					if is_first {
-						is_first = false
-					} else {
-						tuple_types.extend(quote!(,));
-					}
-					Self::expand_type(ty, &mut tuple_types, false);
-				}
-				tuple_types = if read_signature {
-					quote! { (<(#tuple_types)>::SIGNATURE) }
-				} else {
-					quote! { (#tuple_types) }
-				};
-				token_stream.extend(tuple_types);
 			}
-
-			// 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::<usize>()?;
-			// 				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")),
-			// 	}
-			// }
-			_ => panic!("Unexpected type {ty:?}"),
 		}
-		// match ty {
-		// 	AbiType::Plain(ref ident) => {
-		// 		let plain_token = if read_signature {
-		// 			quote! {
-		// 				(<#ident>::SIGNATURE)
-		// 			}
-		// 		} else {
-		// 			quote! {
-		// 				#ident
-		// 			}
-		// 		};
-
-		// 		token_stream.extend(plain_token);
-		// 	}
-
-		// 	AbiType::Tuple(ref tuple_type) => {
-		// 		let mut tuple_types = proc_macro2::TokenStream::new();
-		// 		let mut is_first = true;
-
-		// 		for ty in tuple_type {
-		// 			if is_first {
-		// 				is_first = false
-		// 			} else {
-		// 				tuple_types.extend(quote!(,));
-		// 			}
-		// 			Self::expand_type(ty, &mut tuple_types, false);
-		// 		}
-		// 		tuple_types = if read_signature {
-		// 			quote! { (<(#tuple_types)>::SIGNATURE) }
-		// 		} else {
-		// 			quote! { (#tuple_types) }
-		// 		};
-		// 		token_stream.extend(tuple_types);
-		// 	}
-
-		// 	AbiType::Vec(ref vec_type) => {
-		// 		let mut vec_token = proc_macro2::TokenStream::new();
-		// 		Self::expand_type(vec_type.as_ref(), &mut vec_token, false);
-		// 		vec_token = if read_signature {
-		// 			quote! { (<Vec<#vec_token>>::SIGNATURE) }
-		// 		} else {
-		// 			quote! { <Vec<#vec_token>> }
-		// 		};
-		// 		token_stream.extend(vec_token);
-		// 	}
-
-		// 	AbiType::Array(_, _) => todo!("Array eth signature"),
-		// };
 	}
 
 	fn expand_custom_signature(&self) -> proc_macro2::TokenStream {
-		let mut token_stream = TokenStream::new();
+		let mut args = TokenStream::new();
 
 		let mut is_first = true;
-		for arg in &self.args {
-			if arg.is_special() {
-				continue;
-			}
-
-			if is_first {
-				is_first = false;
-			} else {
-				token_stream.extend(quote!(,));
-			}
-			Self::expand_type(&arg.ty, &mut token_stream, true);
+		for arg in self.args.iter().filter(|a| !a.is_special()) {
+			is_first = false;
+			let ty = &arg.ty;
+			args.extend(quote! {nameof(#ty)});
+			args.extend(quote! {fixed(",")})
 		}
 
+		// Remove trailing comma
 		if !is_first {
-			token_stream.extend(quote!(,));
+			args.extend(quote! {shift_left(1)})
 		}
 
 		let func_name = self.camel_name.clone();
-		let func_name = quote!(SignaturePreferences {
-			open_name: Some(SignatureUnit::new(#func_name)),
-			open_delimiter: Some(SignatureUnit::new("(")),
-			param_delimiter: Some(SignatureUnit::new(",")),
-			close_delimiter: Some(SignatureUnit::new(")")),
-			close_name: None,
-		});
-		quote!({ ::evm_coder::make_signature!(new fn(#func_name), #token_stream) })
+		quote! { ::evm_coder::make_signature!(new fixed(#func_name) fixed("(") #args fixed(")")) }
 	}
 
 	fn expand_solidity_function(&self) -> proc_macro2::TokenStream {
@@ -916,12 +752,6 @@
 		let screaming_name = &self.screaming_name;
 		let hide = self.hide;
 		let custom_signature = self.expand_custom_signature();
-		let custom_signature = quote!(
-			{
-				const cs: FunctionSignature = #custom_signature;
-				cs
-			}
-		);
 		let is_payable = self.has_value_args;
 
 		quote! {
modifiedcrates/evm-coder/src/abi.rsdiffbeforeafterboth
--- a/crates/evm-coder/src/abi.rs
+++ b/crates/evm-coder/src/abi.rs
@@ -27,7 +27,7 @@
 	execution::{Error, ResultWithPostInfo, WithPostDispatchInfo},
 	types::*,
 	make_signature,
-	custom_signature::{SignatureUnit, SIGNATURE_SIZE_LIMIT},
+	custom_signature::{SignatureUnit},
 };
 use crate::execution::Result;
 
@@ -428,7 +428,7 @@
 }
 
 impl<R: Signature> Signature for Vec<R> {
-	make_signature!(new nameof(R) fixed("[]"));
+	const SIGNATURE: SignatureUnit = make_signature!(new nameof(R) fixed("[]"));
 }
 
 impl sealed::CanBePlacedInVec for EthCrossAccount {}
@@ -522,7 +522,7 @@
 		where
 		$($ident: Signature,)+
 		{
-			make_signature!(
+			const SIGNATURE: SignatureUnit = make_signature!(
 				new fixed("(")
 				$(nameof($ident) fixed(","))+
 				shift_left(1)
@@ -758,13 +758,13 @@
 				1ACF2D55
 				0000000000000000000000000000000000000000000000000000000000000020 // offset of (address, uint256)[]
 				0000000000000000000000000000000000000000000000000000000000000003 // length of (address, uint256)[]
-	
+
 				0000000000000000000000002D2FF76104B7BACB2E8F6731D5BFC184EBECDDBC // address
 				000000000000000000000000000000000000000000000000000000000000000A // uint256
-	
+
 				000000000000000000000000AB8E3D9134955566483B11E6825C9223B6737B10 // address
 				0000000000000000000000000000000000000000000000000000000000000014 // uint256
-	
+
 				0000000000000000000000008C582BDF2953046705FC56F189385255EFC1BE18 // address
 				000000000000000000000000000000000000000000000000000000000000001E // uint256
 			"
modifiedcrates/evm-coder/src/custom_signature.rsdiffbeforeafterboth
--- a/crates/evm-coder/src/custom_signature.rs
+++ b/crates/evm-coder/src/custom_signature.rs
@@ -74,132 +74,11 @@
 //!	impl<T: SoliditySignature> SoliditySignature for Vec<T> {
 //!		make_signature!(new nameof(T) fixed("[]"));
 //!	}
-//!
-//! // Function signature settings
-//! const SIGNATURE_PREFERENCES: SignaturePreferences = SignaturePreferences {
-//!		open_name: Some(SignatureUnit::new("some_funk")),
-//!		open_delimiter: Some(SignatureUnit::new("(")),
-//!		param_delimiter: Some(SignatureUnit::new(",")),
-//!		close_delimiter: Some(SignatureUnit::new(")")),
-//!		close_name: None,
-//!	};
-//!
-//! // Create functions signatures
-//! fn make_func_without_args() {
-//!		const SIG: FunctionSignature = make_signature!(
-//!			new fn(SIGNATURE_PREFERENCES),
-//!		);
-//!		let name = SIG.as_str();
-//!		similar_asserts::assert_eq!(name, "some_funk()");
-//!	}
-//!
-//! fn make_func_with_3_args() {
-//!		const SIG: FunctionSignature = make_signature!(
-//!			new fn(SIGNATURE_PREFERENCES),
-//!			(<u8>::SIGNATURE),
-//!			(<u8>::SIGNATURE),
-//!			(<Vec<u8>>::SIGNATURE),
-//!		);
-//!		let name = SIG.as_str();
-//!		similar_asserts::assert_eq!(name, "some_funk(uint8,uint8,uint8[])");
-//!	}
 //! ```
-use core::str::from_utf8;
 
 /// The maximum length of the signature.
 pub const SIGNATURE_SIZE_LIMIT: usize = 256;
-
-/// Function signature formatting preferences.
-#[derive(Debug)]
-pub struct SignaturePreferences {
-	/// The name of the function before the list of parameters: `*some*(param1,param2)func`
-	pub open_name: Option<SignatureUnit>,
-	/// Opening separator: `some*(*param1,param2)func`
-	pub open_delimiter: Option<SignatureUnit>,
-	/// Parameters separator: `some(param1*,*param2)func`
-	pub param_delimiter: Option<SignatureUnit>,
-	/// Closinging separator: `some(param1,param2*)*func`
-	pub close_delimiter: Option<SignatureUnit>,
-	/// The name of the function after the list of parameters: `some(param1,param2)*func*`
-	pub close_name: Option<SignatureUnit>,
-}
-
-/// Constructs and stores the signature of the function.
-#[derive(Debug)]
-pub struct FunctionSignature {
-	/// Storage for function signature.
-	pub unit: SignatureUnit,
-	preferences: SignaturePreferences,
-}
 
-impl FunctionSignature {
-	/// Start constructing the signature. It is written to the storage
-	/// [`SignaturePreferences::open_name`] and [`SignaturePreferences::open_delimiter`].
-	pub const fn new(preferences: SignaturePreferences) -> FunctionSignature {
-		let mut dst = [0_u8; SIGNATURE_SIZE_LIMIT];
-		let mut dst_offset = 0;
-		if let Some(ref name) = preferences.open_name {
-			crate::make_signature!(@copy(name.data, dst, name.len, dst_offset));
-		}
-		if let Some(ref delimiter) = preferences.open_delimiter {
-			crate::make_signature!(@copy(delimiter.data, dst, delimiter.len, dst_offset));
-		}
-		FunctionSignature {
-			unit: SignatureUnit {
-				data: dst,
-				len: dst_offset,
-			},
-			preferences,
-		}
-	}
-
-	/// Add a function parameter to the signature. It is written to the storage
-	/// `param` [`SignatureUnit`] and [`SignaturePreferences::param_delimiter`].
-	pub const fn add_param(
-		signature: FunctionSignature,
-		param: SignatureUnit,
-	) -> FunctionSignature {
-		let mut dst = signature.unit.data;
-		let mut dst_offset = signature.unit.len;
-		crate::make_signature!(@copy(param.data, dst, param.len, dst_offset));
-		if let Some(ref delimiter) = signature.preferences.param_delimiter {
-			crate::make_signature!(@copy(delimiter.data, dst, delimiter.len, dst_offset));
-		}
-		FunctionSignature {
-			unit: SignatureUnit {
-				data: dst,
-				len: dst_offset,
-			},
-			..signature
-		}
-	}
-
-	/// Complete signature construction. It is written to the storage
-	/// [`SignaturePreferences::close_delimiter`] and [`SignaturePreferences::close_name`].
-	pub const fn done(signature: FunctionSignature, owerride: bool) -> FunctionSignature {
-		let mut dst = signature.unit.data;
-		let mut dst_offset = signature.unit.len - if owerride { 1 } else { 0 };
-		if let Some(ref delimiter) = signature.preferences.close_delimiter {
-			crate::make_signature!(@copy(delimiter.data, dst, delimiter.len, dst_offset));
-		}
-		if let Some(ref name) = signature.preferences.close_name {
-			crate::make_signature!(@copy(name.data, dst, name.len, dst_offset));
-		}
-		FunctionSignature {
-			unit: SignatureUnit {
-				data: dst,
-				len: dst_offset,
-			},
-			..signature
-		}
-	}
-
-	/// Represent the signature as `&str'.
-	pub fn as_str(&self) -> &str {
-		from_utf8(&self.unit.data[..self.unit.len]).expect("bad utf-8")
-	}
-}
-
 /// Storage for the signature or its elements.
 #[derive(Debug)]
 pub struct SignatureUnit {
@@ -222,6 +101,10 @@
 			len: name_len,
 		}
 	}
+	/// String conversion
+	pub fn as_str(&self) -> Option<&str> {
+		core::str::from_utf8(&self.data[0..self.len]).ok()
+	}
 }
 
 /// ### Macro to create signatures of types and functions.
@@ -231,85 +114,52 @@
 /// make_signature!(new fixed("uint8")); // Simple type
 /// make_signature!(new fixed("(") nameof(u8) fixed(",") nameof(u8) fixed(")")); // Composite type
 /// ```
-/// Format for creating a function of the function:
-/// ```ignore
-/// const SIG: FunctionSignature = make_signature!(
-///		new fn(SIGNATURE_PREFERENCES),
-///		(u8::SIGNATURE),
-///		(<(u8,u8)>::SIGNATURE),
-///	);
-/// ```
 #[macro_export]
 macro_rules! make_signature {
-	(new fn($func:expr)$(,)*) => {
-		{
-			let fs = FunctionSignature::new($func);
-			let fs = FunctionSignature::done(fs, false);
-			fs
-		}
-	};
-	(new fn($func:expr), $($tt:tt,)*) => {
-		{
-			let fs = FunctionSignature::new($func);
-			let fs = make_signature!(@param; fs, $($tt),*);
-			fs
-		}
+	(new $($tt:tt)*) => {
+		($crate::custom_signature::SignatureUnit {
+			data: {
+				let mut out = [0u8; $crate::custom_signature::SIGNATURE_SIZE_LIMIT];
+				let mut dst_offset = 0;
+				$crate::make_signature!(@data(out, dst_offset); $($tt)*);
+				out
+			},
+			len: {0 + $crate::make_signature!(@size; $($tt)*)},
+		})
 	};
 
-	(@param; $func:expr) => {
-		FunctionSignature::done($func, true)
+	(@size;) => {
+		0
 	};
-	(@param; $func:expr, $param:expr) => {
-		make_signature!(@param; FunctionSignature::add_param($func, $param))
+	(@size; fixed($expr:expr) $($tt:tt)*) => {
+		$expr.len() + $crate::make_signature!(@size; $($tt)*)
 	};
-	(@param; $func:expr, $param:expr, $($tt:tt),*) => {
-		make_signature!(@param; FunctionSignature::add_param($func, $param), $($tt),*)
+	(@size; nameof($expr:ty) $($tt:tt)*) => {
+		<$expr>::SIGNATURE.len + $crate::make_signature!(@size; $($tt)*)
 	};
-
-    (new $($tt:tt)*) => {
-        const SIGNATURE: SignatureUnit = SignatureUnit {
-			data: {
-				let mut out = [0u8; SIGNATURE_SIZE_LIMIT];
-				let mut dst_offset = 0;
-				make_signature!(@data(out, dst_offset); $($tt)*);
-				out
-			},
-			len: {0 + make_signature!(@size; $($tt)*)},
-        };
-    };
-
-    (@size;) => {
-        0
-    };
-    (@size; fixed($expr:expr) $($tt:tt)*) => {
-        $expr.len() + make_signature!(@size; $($tt)*)
-    };
-    (@size; nameof($expr:ty) $($tt:tt)*) => {
-		<$expr>::SIGNATURE.len + make_signature!(@size; $($tt)*)
-    };
 	(@size; shift_left($expr:expr) $($tt:tt)*) => {
-		make_signature!(@size; $($tt)*) - $expr
+		$crate::make_signature!(@size; $($tt)*) - $expr
 	};
 
-    (@data($dst:ident, $dst_offset:ident);) => {};
-    (@data($dst:ident, $dst_offset:ident); fixed($expr:expr) $($tt:tt)*) => {
-        {
-            let data = $expr.as_bytes();
+	(@data($dst:ident, $dst_offset:ident);) => {};
+	(@data($dst:ident, $dst_offset:ident); fixed($expr:expr) $($tt:tt)*) => {
+		{
+			let data = $expr.as_bytes();
 			let data_len = data.len();
-			make_signature!(@copy(data, $dst, data_len, $dst_offset));
-        }
-        make_signature!(@data($dst, $dst_offset); $($tt)*)
-    };
-    (@data($dst:ident, $dst_offset:ident); nameof($expr:ty) $($tt:tt)*) => {
-        {
-            make_signature!(@copy(&<$expr>::SIGNATURE.data, $dst, <$expr>::SIGNATURE.len, $dst_offset));
-        }
-        make_signature!(@data($dst, $dst_offset); $($tt)*)
-    };
+			$crate::make_signature!(@copy(data, $dst, data_len, $dst_offset));
+		}
+		$crate::make_signature!(@data($dst, $dst_offset); $($tt)*)
+	};
+	(@data($dst:ident, $dst_offset:ident); nameof($expr:ty) $($tt:tt)*) => {
+		{
+			$crate::make_signature!(@copy(&<$expr>::SIGNATURE.data, $dst, <$expr>::SIGNATURE.len, $dst_offset));
+		}
+		$crate::make_signature!(@data($dst, $dst_offset); $($tt)*)
+	};
 	(@data($dst:ident, $dst_offset:ident); shift_left($expr:expr) $($tt:tt)*) => {
-        $dst_offset -= $expr;
-        make_signature!(@data($dst, $dst_offset); $($tt)*)
-    };
+		$dst_offset -= $expr;
+		$crate::make_signature!(@data($dst, $dst_offset); $($tt)*)
+	};
 
 	(@copy($src:expr, $dst:expr, $src_len:expr, $dst_offset:ident)) => {
 		{
@@ -328,7 +178,7 @@
 mod test {
 	use core::str::from_utf8;
 
-	use super::{SIGNATURE_SIZE_LIMIT, SignatureUnit, FunctionSignature, SignaturePreferences};
+	use super::{SIGNATURE_SIZE_LIMIT, SignatureUnit};
 
 	trait Name {
 		const SIGNATURE: SignatureUnit;
@@ -339,19 +189,21 @@
 	}
 
 	impl Name for u8 {
-		make_signature!(new fixed("uint8"));
+		const SIGNATURE: SignatureUnit = make_signature!(new fixed("uint8"));
 	}
 	impl Name for u32 {
-		make_signature!(new fixed("uint32"));
+		const SIGNATURE: SignatureUnit = make_signature!(new fixed("uint32"));
 	}
 	impl<T: Name> Name for Vec<T> {
-		make_signature!(new nameof(T) fixed("[]"));
+		const SIGNATURE: SignatureUnit = make_signature!(new nameof(T) fixed("[]"));
 	}
 	impl<A: Name, B: Name> Name for (A, B) {
-		make_signature!(new fixed("(") nameof(A) fixed(",") nameof(B) fixed(")"));
+		const SIGNATURE: SignatureUnit =
+			make_signature!(new fixed("(") nameof(A) fixed(",") nameof(B) fixed(")"));
 	}
 	impl<A: Name> Name for (A,) {
-		make_signature!(new fixed("(") nameof(A) fixed(",") shift_left(1) fixed(")"));
+		const SIGNATURE: SignatureUnit =
+			make_signature!(new fixed("(") nameof(A) fixed(",") shift_left(1) fixed(")"));
 	}
 
 	struct MaxSize();
@@ -361,14 +213,6 @@
 			len: SIGNATURE_SIZE_LIMIT,
 		};
 	}
-
-	const SIGNATURE_PREFERENCES: SignaturePreferences = SignaturePreferences {
-		open_name: Some(SignatureUnit::new("some_funk")),
-		open_delimiter: Some(SignatureUnit::new("(")),
-		param_delimiter: Some(SignatureUnit::new(",")),
-		close_delimiter: Some(SignatureUnit::new(")")),
-		close_name: None,
-	};
 
 	#[test]
 	fn simple() {
@@ -421,68 +265,6 @@
 	#[test]
 	fn max_size() {
 		assert_eq!(<MaxSize>::name(), "!".repeat(SIGNATURE_SIZE_LIMIT));
-	}
-
-	#[test]
-	fn make_func_without_args() {
-		const SIG: FunctionSignature = make_signature!(
-			new fn(SIGNATURE_PREFERENCES)
-		);
-		let name = SIG.as_str();
-		similar_asserts::assert_eq!(name, "some_funk()");
-	}
-
-	#[test]
-	fn make_func_with_1_args() {
-		const SIG: FunctionSignature = make_signature!(
-			new fn(SIGNATURE_PREFERENCES),
-			(<u8>::SIGNATURE),
-		);
-		let name = SIG.as_str();
-		similar_asserts::assert_eq!(name, "some_funk(uint8)");
-	}
-
-	#[test]
-	fn make_func_with_2_args() {
-		const SIG: FunctionSignature = make_signature!(
-			new fn(SIGNATURE_PREFERENCES),
-			(u8::SIGNATURE),
-			(<Vec<u32>>::SIGNATURE),
-		);
-		let name = SIG.as_str();
-		similar_asserts::assert_eq!(name, "some_funk(uint8,uint32[])");
-	}
-
-	#[test]
-	fn make_func_with_3_args() {
-		const SIG: FunctionSignature = make_signature!(
-			new fn(SIGNATURE_PREFERENCES),
-			(<u8>::SIGNATURE),
-			(<u32>::SIGNATURE),
-			(<Vec<u32>>::SIGNATURE),
-		);
-		let name = SIG.as_str();
-		similar_asserts::assert_eq!(name, "some_funk(uint8,uint32,uint32[])");
-	}
-
-	#[test]
-	fn make_slice_from_signature() {
-		const SIG: FunctionSignature = make_signature!(
-			new fn(SIGNATURE_PREFERENCES),
-			(<u8>::SIGNATURE),
-			(<u32>::SIGNATURE),
-			(<Vec<u32>>::SIGNATURE),
-		);
-		const NAME: [u8; SIG.unit.len] = {
-			let mut name: [u8; SIG.unit.len] = [0; SIG.unit.len];
-			let mut i = 0;
-			while i < SIG.unit.len {
-				name[i] = SIG.unit.data[i];
-				i += 1;
-			}
-			name
-		};
-		similar_asserts::assert_eq!(&NAME, b"some_funk(uint8,uint32,uint32[])");
 	}
 
 	#[test]
modifiedcrates/evm-coder/src/lib.rsdiffbeforeafterboth
before · crates/evm-coder/src/lib.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#![doc = include_str!("../README.md")]18#![deny(missing_docs)]19#![macro_use]20#![cfg_attr(not(feature = "std"), no_std)]21#[cfg(not(feature = "std"))]22extern crate alloc;2324use abi::{AbiRead, AbiReader, AbiWriter};25pub use evm_coder_procedural::{event_topic, fn_selector};26pub mod abi;27pub use events::{ToLog, ToTopic};28use execution::DispatchInfo;29pub mod execution;30#[macro_use]31pub mod custom_signature;3233/// Derives call enum implementing [`crate::Callable`], [`crate::Weighted`]34/// and [`crate::Call`] from impl block.35///36/// ## Macro syntax37///38/// `#[solidity_interface(name, is, inline_is, events)]`39/// - *name* - used in generated code, and for Call enum name40/// - *is* - used to provide inheritance in Solidity41/// - *inline_is* - same as `is`, but ERC165::SupportsInterface will work differently: For `is` SupportsInterface(A) will return true42///   if A is one of the interfaces the contract is inherited from (e.g. B is created as `is(A)`). If B is created as `inline_is(A)`43///   SupportsInterface(A) will internally create a new interface that combines all methods of A and B, so SupportsInterface(A) will return44///   false.45///46/// `#[weight(value)]`47/// Can be added to every method of impl block, used for deriving [`crate::Weighted`], which48/// is used by substrate bridge.49/// - *value*: expression, which evaluates to weight required to call this method.50/// This expression can use call arguments to calculate non-constant execution time.51/// This expression should evaluate faster than actual execution does, and may provide worse case52/// than one is called.53///54/// `#[solidity_interface(rename_selector)]`55/// - *rename_selector* - by default, selector name will be generated by transforming method name56/// from snake_case to camelCase. Use this option, if other naming convention is required.57/// I.e: method `token_uri` will be automatically renamed to `tokenUri` in selector, but name58/// required by ERC721 standard is `tokenURI`, thus we need to specify `rename_selector = "tokenURI"`59/// explicitly.60///61/// Both contract and contract methods may have doccomments, which will end up in a generated62/// solidity interface file, thus you should use [solidity syntax](https://docs.soliditylang.org/en/latest/natspec-format.html) for writing documentation in this macro63///64/// ## Example65///66/// ```ignore67/// struct SuperContract;68/// struct InlineContract;69/// struct Contract;70///71/// #[derive(ToLog)]72/// enum ContractEvents {73///     Event(#[indexed] uint32),74/// }75///76/// /// @dev This contract provides function to multiply two numbers77/// #[solidity_interface(name = MyContract, is(SuperContract), inline_is(InlineContract))]78/// impl Contract {79///     /// Multiply two numbers80///     /// @param a First number81///     /// @param b Second number82///     /// @return uint32 Product of two passed numbers83///     /// @dev This function returns error in case of overflow84///     #[weight(200 + a + b)]85///     #[solidity_interface(rename_selector = "mul")]86///     fn mul(&mut self, a: uint32, b: uint32) -> Result<uint32> {87///         Ok(a.checked_mul(b).ok_or("overflow")?)88///     }89/// }90/// ```91pub use evm_coder_procedural::solidity_interface;92/// See [`solidity_interface`]93pub use evm_coder_procedural::solidity;94/// See [`solidity_interface`]95pub use evm_coder_procedural::weight;96pub use sha3_const;9798/// Derives [`ToLog`] for enum99///100/// Selectors will be derived from variant names, there is currently no way to have custom naming101/// for them102///103/// `#[indexed]`104/// Marks this field as indexed, so it will appear in [`ethereum::Log`] topics instead of data105pub use evm_coder_procedural::ToLog;106107// Api of those modules shouldn't be consumed directly, it is only exported for usage in proc macros108#[doc(hidden)]109pub mod events;110#[doc(hidden)]111pub mod solidity;112113/// Solidity type definitions (aliases from solidity name to rust type)114/// To be used in [`solidity_interface`] definitions, to make sure there is no115/// type conflict between Rust code and generated definitions116pub mod types {117	#![allow(non_camel_case_types, missing_docs)]118119	#[cfg(not(feature = "std"))]120	use alloc::{vec::Vec};121	use pallet_evm::account::CrossAccountId;122	use primitive_types::{U256, H160, H256};123	use core::str::from_utf8;124125	use crate::custom_signature::{SignatureUnit, SIGNATURE_SIZE_LIMIT};126127	pub trait Signature {128		const SIGNATURE: SignatureUnit;129130		fn as_str() -> &'static str {131			from_utf8(&Self::SIGNATURE.data[..Self::SIGNATURE.len]).expect("bad utf-8")132		}133	}134135	impl Signature for bool {136		make_signature!(new fixed("bool"));137	}138139	macro_rules! define_simple_type {140		(type $ident:ident = $ty:ty) => {141			pub type $ident = $ty;142			impl Signature for $ty {143				make_signature!(new fixed(stringify!($ident)));144			}145		};146	}147148	define_simple_type!(type address = H160);149150	define_simple_type!(type uint8 = u8);151	define_simple_type!(type uint16 = u16);152	define_simple_type!(type uint32 = u32);153	define_simple_type!(type uint64 = u64);154	define_simple_type!(type uint128 = u128);155	define_simple_type!(type uint256 = U256);156	define_simple_type!(type bytes4 = [u8; 4]);157158	define_simple_type!(type topic = H256);159160	#[cfg(not(feature = "std"))]161	define_simple_type!(type string = ::alloc::string::String);162	#[cfg(feature = "std")]163	define_simple_type!(type string = ::std::string::String);164165	#[derive(Default, Debug)]166	pub struct bytes(pub Vec<u8>);167	impl Signature for bytes {168		make_signature!(new fixed("bytes"));169	}170171	/// Solidity doesn't have `void` type, however we have special implementation172	/// for empty tuple return type173	pub type void = ();174175	//#region Special types176	/// Makes function payable177	pub type value = U256;178	/// Makes function caller-sensitive179	pub type caller = address;180	//#endregion181182	/// Ethereum typed call message, similar to solidity183	/// `msg` object.184	pub struct Msg<C> {185		pub call: C,186		/// Address of user, which called this contract.187		pub caller: H160,188		/// Payment amount to contract.189		/// Contract should reject payment, if target call is not payable,190		/// and there is no `receiver()` function defined.191		pub value: U256,192	}193194	impl From<Vec<u8>> for bytes {195		fn from(src: Vec<u8>) -> Self {196			Self(src)197		}198	}199200	#[allow(clippy::from_over_into)]201	impl Into<Vec<u8>> for bytes {202		fn into(self) -> Vec<u8> {203			self.0204		}205	}206207	impl bytes {208		#[must_use]209		pub fn len(&self) -> usize {210			self.0.len()211		}212213		#[must_use]214		pub fn is_empty(&self) -> bool {215			self.len() == 0216		}217	}218219	#[derive(Debug, Default)]220	pub struct EthCrossAccount {221		pub(crate) eth: address,222		pub(crate) sub: uint256,223	}224225	impl EthCrossAccount {226		pub fn from_sub_cross_account<T>(cross_account_id: &T::CrossAccountId) -> Self227		where228			T: pallet_evm::account::Config,229			T::AccountId: AsRef<[u8; 32]>,230		{231			if cross_account_id.is_canonical_substrate() {232				Self {233					eth: Default::default(),234					sub: convert_cross_account_to_uint256::<T>(cross_account_id),235				}236			} else {237				Self {238					eth: *cross_account_id.as_eth(),239					sub: Default::default(),240				}241			}242		}243244		pub fn into_sub_cross_account<T>(&self) -> crate::execution::Result<T::CrossAccountId>245		where246			T: pallet_evm::account::Config,247			T::AccountId: From<[u8; 32]>,248		{249			if self.eth == Default::default() && self.sub == Default::default() {250				Err("All fields of cross account is zeroed".into())251			} else if self.eth == Default::default() {252				Ok(convert_uint256_to_cross_account::<T>(self.sub))253			} else if self.sub == Default::default() {254				Ok(T::CrossAccountId::from_eth(self.eth))255			} else {256				Err("All fields of cross account is non zeroed".into())257			}258		}259	}260261	impl Signature for EthCrossAccount {262		make_signature!(new fixed("(address,uint256)"));263	}264265	/// Convert `CrossAccountId` to `uint256`.266	pub fn convert_cross_account_to_uint256<T: pallet_evm::account::Config>(267		from: &T::CrossAccountId,268	) -> uint256269	where270		T::AccountId: AsRef<[u8; 32]>,271	{272		let slice = from.as_sub().as_ref();273		uint256::from_big_endian(slice)274	}275276	/// Convert `uint256` to `CrossAccountId`.277	pub fn convert_uint256_to_cross_account<T: pallet_evm::account::Config>(278		from: uint256,279	) -> T::CrossAccountId280	where281		T::AccountId: From<[u8; 32]>,282	{283		let mut new_admin_arr = [0_u8; 32];284		from.to_big_endian(&mut new_admin_arr);285		let account_id = T::AccountId::from(new_admin_arr);286		T::CrossAccountId::from_sub(account_id)287	}288}289290/// Parseable EVM call, this trait should be implemented with [`solidity_interface`] macro291pub trait Call: Sized {292	/// Parse call buffer into typed call enum293	fn parse(selector: types::bytes4, input: &mut AbiReader) -> execution::Result<Option<Self>>;294}295296/// Intended to be used as `#[weight]` output type297/// Should be same between evm-coder and substrate to avoid confusion298///299/// Isn't same thing as gas, some mapping is required between those types300pub type Weight = frame_support::weights::Weight;301302/// In substrate, we have benchmarking, which allows303/// us to not rely on gas metering, but instead predict amount of gas to execute call304pub trait Weighted: Call {305	/// Predict weight of this call306	fn weight(&self) -> DispatchInfo;307}308309/// Type callable with ethereum message, may be implemented by [`solidity_interface`] macro310/// on interface implementation, or for externally-owned real EVM contract311pub trait Callable<C: Call> {312	/// Call contract using specified call data313	fn call(&mut self, call: types::Msg<C>) -> execution::ResultWithPostInfo<AbiWriter>;314}315316/// Implementation of ERC165 is implicitly generated for all interfaces in [`solidity_interface`],317/// this structure holds parsed data for ERC165Call subvariant318///319/// Note: no [`Callable`] implementation is provided, call implementation is inlined into every320/// implementing contract321///322/// See <https://eips.ethereum.org/EIPS/eip-165>323#[derive(Debug)]324pub enum ERC165Call {325	/// ERC165 provides single method, which returns true, if contract326	/// implements specified interface327	SupportsInterface {328		/// Requested interface329		interface_id: types::bytes4,330	},331}332333impl ERC165Call {334	/// ERC165 selector is provided by standard335	pub const INTERFACE_ID: types::bytes4 = u32::to_be_bytes(0x01ffc9a7);336}337338impl Call for ERC165Call {339	fn parse(selector: types::bytes4, input: &mut AbiReader) -> execution::Result<Option<Self>> {340		if selector != Self::INTERFACE_ID {341			return Ok(None);342		}343		Ok(Some(Self::SupportsInterface {344			interface_id: types::bytes4::abi_read(input)?,345		}))346	}347}348349/// Generate "tests", which will generate solidity code on execution and print it to stdout350/// Script at .maintain/scripts/generate_api.sh can split this output from test runtime351///352/// This macro receives type usage as second argument, but you can use anything as generics,353/// because no bounds are implied354#[macro_export]355macro_rules! generate_stubgen {356	($name:ident, $decl:ty, $is_impl:literal) => {357		#[test]358		#[ignore]359		fn $name() {360			use evm_coder::solidity::TypeCollector;361			let mut out = TypeCollector::new();362			<$decl>::generate_solidity_interface(&mut out, $is_impl);363			println!("=== SNIP START ===");364			println!("// SPDX-License-Identifier: OTHER");365			println!("// This code is automatically generated");366			println!();367			println!("pragma solidity >=0.8.0 <0.9.0;");368			println!();369			for b in out.finish() {370				println!("{}", b);371			}372			println!("=== SNIP END ===");373		}374	};375}376377#[cfg(test)]378mod tests {379	use super::*;380381	#[test]382	fn function_selector_generation() {383		assert_eq!(fn_selector!(transfer(address, uint256)), 0xa9059cbb);384	}385386	#[test]387	fn event_topic_generation() {388		assert_eq!(389			hex::encode(&event_topic!(Transfer(address, address, uint256))[..]),390			"ddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef",391		);392	}393}
modifiedcrates/evm-coder/src/solidity.rsdiffbeforeafterboth
--- a/crates/evm-coder/src/solidity.rs
+++ b/crates/evm-coder/src/solidity.rs
@@ -32,7 +32,7 @@
 	cmp::Reverse,
 };
 use impl_trait_for_tuples::impl_for_tuples;
-use crate::{types::*, custom_signature::FunctionSignature};
+use crate::{types::*, custom_signature::SignatureUnit};
 
 #[derive(Default)]
 pub struct TypeCollector {
@@ -486,7 +486,7 @@
 	pub docs: &'static [&'static str],
 	pub selector: u32,
 	pub hide: bool,
-	pub custom_signature: FunctionSignature,
+	pub custom_signature: SignatureUnit,
 	pub name: &'static str,
 	pub args: A,
 	pub result: R,
@@ -512,7 +512,7 @@
 		writeln!(
 			writer,
 			"\t{hide_comment}///  or in textual repr: {}",
-			self.custom_signature.as_str()
+			self.custom_signature.as_str().expect("bad utf-8")
 		)?;
 		write!(writer, "\t{hide_comment}function {}(", self.name)?;
 		self.args.solidity_name(writer, tc)?;
modifiedpallets/common/src/erc.rsdiffbeforeafterboth
--- a/pallets/common/src/erc.rs
+++ b/pallets/common/src/erc.rs
@@ -21,8 +21,6 @@
 	types::*,
 	execution::{Result, Error},
 	weight,
-	custom_signature::{SignatureUnit, FunctionSignature, SignaturePreferences},
-	make_signature,
 };
 pub use pallet_evm::{PrecompileOutput, PrecompileResult, PrecompileHandle, account::CrossAccountId};
 use pallet_evm_coder_substrate::dispatch_to_evm;
modifiedpallets/evm-contract-helpers/src/eth.rsdiffbeforeafterboth
--- a/pallets/evm-contract-helpers/src/eth.rs
+++ b/pallets/evm-contract-helpers/src/eth.rs
@@ -19,13 +19,7 @@
 extern crate alloc;
 use core::marker::PhantomData;
 use evm_coder::{
-	abi::AbiWriter,
-	execution::Result,
-	generate_stubgen, solidity_interface,
-	types::*,
-	ToLog,
-	custom_signature::{SignatureUnit, FunctionSignature, SignaturePreferences},
-	make_signature,
+	abi::AbiWriter, execution::Result, generate_stubgen, solidity_interface, types::*, ToLog,
 };
 use pallet_evm::{
 	ExitRevert, OnCreate, OnMethodCall, PrecompileResult, PrecompileFailure, PrecompileHandle,
modifiedpallets/fungible/src/erc.rsdiffbeforeafterboth
--- a/pallets/fungible/src/erc.rs
+++ b/pallets/fungible/src/erc.rs
@@ -19,15 +19,7 @@
 extern crate alloc;
 use core::char::{REPLACEMENT_CHARACTER, decode_utf16};
 use core::convert::TryInto;
-use evm_coder::{
-	ToLog,
-	execution::*,
-	generate_stubgen, solidity_interface,
-	types::*,
-	weight,
-	custom_signature::{SignatureUnit, FunctionSignature, SignaturePreferences},
-	make_signature,
-};
+use evm_coder::{ToLog, execution::*, generate_stubgen, solidity_interface, types::*, weight};
 use up_data_structs::CollectionMode;
 use pallet_common::erc::{CommonEvmHandler, PrecompileResult};
 use sp_std::vec::Vec;
modifiedpallets/nonfungible/src/erc.rsdiffbeforeafterboth
--- a/pallets/nonfungible/src/erc.rs
+++ b/pallets/nonfungible/src/erc.rs
@@ -24,15 +24,7 @@
 	char::{REPLACEMENT_CHARACTER, decode_utf16},
 	convert::TryInto,
 };
-use evm_coder::{
-	ToLog,
-	execution::*,
-	generate_stubgen, solidity, solidity_interface,
-	types::*,
-	weight,
-	custom_signature::{SignatureUnit, FunctionSignature, SignaturePreferences},
-	make_signature,
-};
+use evm_coder::{ToLog, execution::*, generate_stubgen, solidity, solidity_interface, types::*, weight};
 use frame_support::BoundedVec;
 use up_data_structs::{
 	TokenId, PropertyPermission, PropertyKeyPermission, Property, CollectionId, PropertyKey,
modifiedpallets/refungible/src/erc.rsdiffbeforeafterboth
--- a/pallets/refungible/src/erc.rs
+++ b/pallets/refungible/src/erc.rs
@@ -25,15 +25,7 @@
 	char::{REPLACEMENT_CHARACTER, decode_utf16},
 	convert::TryInto,
 };
-use evm_coder::{
-	ToLog,
-	execution::*,
-	generate_stubgen, solidity, solidity_interface,
-	types::*,
-	weight,
-	custom_signature::{SignatureUnit, FunctionSignature, SignaturePreferences},
-	make_signature,
-};
+use evm_coder::{ToLog, execution::*, generate_stubgen, solidity, solidity_interface, types::*, weight};
 use frame_support::{BoundedBTreeMap, BoundedVec};
 use pallet_common::{
 	CollectionHandle, CollectionPropertyPermissions,
modifiedpallets/refungible/src/erc_token.rsdiffbeforeafterboth
--- a/pallets/refungible/src/erc_token.rs
+++ b/pallets/refungible/src/erc_token.rs
@@ -29,15 +29,7 @@
 	convert::TryInto,
 	ops::Deref,
 };
-use evm_coder::{
-	ToLog,
-	execution::*,
-	generate_stubgen, solidity_interface,
-	types::*,
-	weight,
-	custom_signature::{SignatureUnit, FunctionSignature, SignaturePreferences},
-	make_signature,
-};
+use evm_coder::{ToLog, execution::*, generate_stubgen, solidity_interface, types::*, weight};
 use pallet_common::{
 	CommonWeightInfo,
 	erc::{CommonEvmHandler, PrecompileResult},
modifiedpallets/unique/src/eth/mod.rsdiffbeforeafterboth
--- a/pallets/unique/src/eth/mod.rs
+++ b/pallets/unique/src/eth/mod.rs
@@ -18,13 +18,7 @@
 
 use core::marker::PhantomData;
 use ethereum as _;
-use evm_coder::{
-	execution::*,
-	generate_stubgen, solidity, solidity_interface,
-	types::*,
-	custom_signature::{SignatureUnit, FunctionSignature, SignaturePreferences},
-	make_signature, weight,
-};
+use evm_coder::{execution::*, generate_stubgen, solidity, solidity_interface, types::*, weight};
 use frame_support::traits::Get;
 use crate::Pallet;