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
--- a/crates/evm-coder/src/lib.rs
+++ b/crates/evm-coder/src/lib.rs
@@ -122,7 +122,7 @@
 	use primitive_types::{U256, H160, H256};
 	use core::str::from_utf8;
 
-	use crate::custom_signature::{SignatureUnit, SIGNATURE_SIZE_LIMIT};
+	use crate::custom_signature::SignatureUnit;
 
 	pub trait Signature {
 		const SIGNATURE: SignatureUnit;
@@ -133,14 +133,14 @@
 	}
 
 	impl Signature for bool {
-		make_signature!(new fixed("bool"));
+		const SIGNATURE: SignatureUnit = make_signature!(new fixed("bool"));
 	}
 
 	macro_rules! define_simple_type {
 		(type $ident:ident = $ty:ty) => {
 			pub type $ident = $ty;
 			impl Signature for $ty {
-				make_signature!(new fixed(stringify!($ident)));
+				const SIGNATURE: SignatureUnit = make_signature!(new fixed(stringify!($ident)));
 			}
 		};
 	}
@@ -165,7 +165,7 @@
 	#[derive(Default, Debug)]
 	pub struct bytes(pub Vec<u8>);
 	impl Signature for bytes {
-		make_signature!(new fixed("bytes"));
+		const SIGNATURE: SignatureUnit = make_signature!(new fixed("bytes"));
 	}
 
 	/// Solidity doesn't have `void` type, however we have special implementation
@@ -259,7 +259,7 @@
 	}
 
 	impl Signature for EthCrossAccount {
-		make_signature!(new fixed("(address,uint256)"));
+		const SIGNATURE: SignatureUnit = make_signature!(new fixed("(address,uint256)"));
 	}
 
 	/// Convert `CrossAccountId` to `uint256`.
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
before · pallets/refungible/src/erc.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//! # Refungible Pallet EVM API for tokens18//!19//! Provides ERC-721 standart support implementation and EVM API for unique extensions for Refungible Pallet.20//! Method implementations are mostly doing parameter conversion and calling Refungible Pallet methods.2122extern crate alloc;2324use core::{25	char::{REPLACEMENT_CHARACTER, decode_utf16},26	convert::TryInto,27};28use evm_coder::{29	ToLog,30	execution::*,31	generate_stubgen, solidity, solidity_interface,32	types::*,33	weight,34	custom_signature::{SignatureUnit, FunctionSignature, SignaturePreferences},35	make_signature,36};37use frame_support::{BoundedBTreeMap, BoundedVec};38use pallet_common::{39	CollectionHandle, CollectionPropertyPermissions,40	erc::{CommonEvmHandler, CollectionCall, static_property::key},41};42use pallet_evm::{account::CrossAccountId, PrecompileHandle};43use pallet_evm_coder_substrate::{call, dispatch_to_evm};44use pallet_structure::{SelfWeightOf as StructureWeight, weights::WeightInfo as _};45use sp_core::H160;46use sp_std::{collections::btree_map::BTreeMap, vec::Vec, vec};47use up_data_structs::{48	CollectionId, CollectionPropertiesVec, mapping::TokenAddressMapping, Property, PropertyKey,49	PropertyKeyPermission, PropertyPermission, TokenId,50};5152use crate::{53	AccountBalance, Balance, Config, CreateItemData, Pallet, RefungibleHandle, SelfWeightOf,54	TokenProperties, TokensMinted, TotalSupply, weights::WeightInfo,55};5657pub const ADDRESS_FOR_PARTIALLY_OWNED_TOKENS: H160 = H160::repeat_byte(0xff);5859/// @title A contract that allows to set and delete token properties and change token property permissions.60#[solidity_interface(name = TokenProperties)]61impl<T: Config> RefungibleHandle<T> {62	/// @notice Set permissions for token property.63	/// @dev Throws error if `msg.sender` is not admin or owner of the collection.64	/// @param key Property key.65	/// @param isMutable Permission to mutate property.66	/// @param collectionAdmin Permission to mutate property by collection admin if property is mutable.67	/// @param tokenOwner Permission to mutate property by token owner if property is mutable.68	fn set_token_property_permission(69		&mut self,70		caller: caller,71		key: string,72		is_mutable: bool,73		collection_admin: bool,74		token_owner: bool,75	) -> Result<()> {76		let caller = T::CrossAccountId::from_eth(caller);77		<Pallet<T>>::set_token_property_permissions(78			self,79			&caller,80			vec![PropertyKeyPermission {81				key: <Vec<u8>>::from(key)82					.try_into()83					.map_err(|_| "too long key")?,84				permission: PropertyPermission {85					mutable: is_mutable,86					collection_admin,87					token_owner,88				},89			}],90		)91		.map_err(dispatch_to_evm::<T>)92	}9394	/// @notice Set token property value.95	/// @dev Throws error if `msg.sender` has no permission to edit the property.96	/// @param tokenId ID of the token.97	/// @param key Property key.98	/// @param value Property value.99	fn set_property(100		&mut self,101		caller: caller,102		token_id: uint256,103		key: string,104		value: bytes,105	) -> Result<()> {106		let caller = T::CrossAccountId::from_eth(caller);107		let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;108		let key = <Vec<u8>>::from(key)109			.try_into()110			.map_err(|_| "key too long")?;111		let value = value.0.try_into().map_err(|_| "value too long")?;112113		let nesting_budget = self114			.recorder115			.weight_calls_budget(<StructureWeight<T>>::find_parent());116117		<Pallet<T>>::set_token_property(118			self,119			&caller,120			TokenId(token_id),121			Property { key, value },122			&nesting_budget,123		)124		.map_err(dispatch_to_evm::<T>)125	}126127	/// @notice Set token properties value.128	/// @dev Throws error if `msg.sender` has no permission to edit the property.129	/// @param tokenId ID of the token.130	/// @param properties settable properties131	fn set_properties(132		&mut self,133		caller: caller,134		token_id: uint256,135		properties: Vec<(string, bytes)>,136	) -> Result<()> {137		let caller = T::CrossAccountId::from_eth(caller);138		let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;139140		let nesting_budget = self141			.recorder142			.weight_calls_budget(<StructureWeight<T>>::find_parent());143144		let properties = properties145			.into_iter()146			.map(|(key, value)| {147				let key = <Vec<u8>>::from(key)148					.try_into()149					.map_err(|_| "key too large")?;150151				let value = value.0.try_into().map_err(|_| "value too large")?;152153				Ok(Property { key, value })154			})155			.collect::<Result<Vec<_>>>()?;156157		<Pallet<T>>::set_token_properties(158			self,159			&caller,160			TokenId(token_id),161			properties.into_iter(),162			<Pallet<T>>::token_exists(&self, TokenId(token_id)),163			&nesting_budget,164		)165		.map_err(dispatch_to_evm::<T>)166	}167168	/// @notice Delete token property value.169	/// @dev Throws error if `msg.sender` has no permission to edit the property.170	/// @param tokenId ID of the token.171	/// @param key Property key.172	fn delete_property(&mut self, token_id: uint256, caller: caller, key: string) -> Result<()> {173		let caller = T::CrossAccountId::from_eth(caller);174		let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;175		let key = <Vec<u8>>::from(key)176			.try_into()177			.map_err(|_| "key too long")?;178179		let nesting_budget = self180			.recorder181			.weight_calls_budget(<StructureWeight<T>>::find_parent());182183		<Pallet<T>>::delete_token_property(self, &caller, TokenId(token_id), key, &nesting_budget)184			.map_err(dispatch_to_evm::<T>)185	}186187	/// @notice Get token property value.188	/// @dev Throws error if key not found189	/// @param tokenId ID of the token.190	/// @param key Property key.191	/// @return Property value bytes192	fn property(&self, token_id: uint256, key: string) -> Result<bytes> {193		let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;194		let key = <Vec<u8>>::from(key)195			.try_into()196			.map_err(|_| "key too long")?;197198		let props = <TokenProperties<T>>::get((self.id, token_id));199		let prop = props.get(&key).ok_or("key not found")?;200201		Ok(prop.to_vec().into())202	}203}204205#[derive(ToLog)]206pub enum ERC721Events {207	/// @dev This event emits when NFTs are created (`from` == 0) and destroyed208	///  (`to` == 0). Exception: during contract creation, any number of RFTs209	///  may be created and assigned without emitting Transfer.210	Transfer {211		#[indexed]212		from: address,213		#[indexed]214		to: address,215		#[indexed]216		token_id: uint256,217	},218	/// @dev Not supported219	Approval {220		#[indexed]221		owner: address,222		#[indexed]223		approved: address,224		#[indexed]225		token_id: uint256,226	},227	/// @dev Not supported228	#[allow(dead_code)]229	ApprovalForAll {230		#[indexed]231		owner: address,232		#[indexed]233		operator: address,234		approved: bool,235	},236}237238#[derive(ToLog)]239pub enum ERC721UniqueMintableEvents {240	/// @dev Not supported241	#[allow(dead_code)]242	MintingFinished {},243}244245#[solidity_interface(name = ERC721Metadata)]246impl<T: Config> RefungibleHandle<T>247where248	T::AccountId: From<[u8; 32]>,249{250	/// @notice A descriptive name for a collection of NFTs in this contract251	/// @dev real implementation of this function lies in `ERC721UniqueExtensions`252	#[solidity(hide, rename_selector = "name")]253	fn name_proxy(&self) -> Result<string> {254		self.name()255	}256257	/// @notice An abbreviated name for NFTs in this contract258	/// @dev real implementation of this function lies in `ERC721UniqueExtensions`259	#[solidity(hide, rename_selector = "symbol")]260	fn symbol_proxy(&self) -> Result<string> {261		self.symbol()262	}263264	/// @notice A distinct Uniform Resource Identifier (URI) for a given asset.265	///266	/// @dev If the token has a `url` property and it is not empty, it is returned.267	///  Else If the collection does not have a property with key `schemaName` or its value is not equal to `ERC721Metadata`, it return an error `tokenURI not set`.268	///  If the collection property `baseURI` is empty or absent, return "" (empty string)269	///  otherwise, if token property `suffix` present and is non-empty, return concatenation of baseURI and suffix270	///  otherwise, return concatenation of `baseURI` and stringified token id (decimal stringifying, without paddings).271	///272	/// @return token's const_metadata273	#[solidity(rename_selector = "tokenURI")]274	fn token_uri(&self, token_id: uint256) -> Result<string> {275		let token_id_u32: u32 = token_id.try_into().map_err(|_| "token id overflow")?;276277		match get_token_property(self, token_id_u32, &key::url()).as_deref() {278			Err(_) | Ok("") => (),279			Ok(url) => {280				return Ok(url.into());281			}282		};283284		let base_uri =285			pallet_common::Pallet::<T>::get_collection_property(self.id, &key::base_uri())286				.map(BoundedVec::into_inner)287				.map(string::from_utf8)288				.transpose()289				.map_err(|e| {290					Error::Revert(alloc::format!(291						"Can not convert value \"baseURI\" to string with error \"{}\"",292						e293					))294				})?;295296		let base_uri = match base_uri.as_deref() {297			None | Some("") => {298				return Ok("".into());299			}300			Some(base_uri) => base_uri.into(),301		};302303		Ok(304			match get_token_property(self, token_id_u32, &key::suffix()).as_deref() {305				Err(_) | Ok("") => base_uri,306				Ok(suffix) => base_uri + suffix,307			},308		)309	}310}311312/// @title ERC-721 Non-Fungible Token Standard, optional enumeration extension313/// @dev See https://eips.ethereum.org/EIPS/eip-721314#[solidity_interface(name = ERC721Enumerable)]315impl<T: Config> RefungibleHandle<T> {316	/// @notice Enumerate valid RFTs317	/// @param index A counter less than `totalSupply()`318	/// @return The token identifier for the `index`th NFT,319	///  (sort order not specified)320	fn token_by_index(&self, index: uint256) -> Result<uint256> {321		Ok(index)322	}323324	/// Not implemented325	fn token_of_owner_by_index(&self, _owner: address, _index: uint256) -> Result<uint256> {326		// TODO: Not implemetable327		Err("not implemented".into())328	}329330	/// @notice Count RFTs tracked by this contract331	/// @return A count of valid RFTs tracked by this contract, where each one of332	///  them has an assigned and queryable owner not equal to the zero address333	fn total_supply(&self) -> Result<uint256> {334		self.consume_store_reads(1)?;335		Ok(<Pallet<T>>::total_supply(self).into())336	}337}338339/// @title ERC-721 Non-Fungible Token Standard340/// @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md341#[solidity_interface(name = ERC721, events(ERC721Events))]342impl<T: Config> RefungibleHandle<T> {343	/// @notice Count all RFTs assigned to an owner344	/// @dev RFTs assigned to the zero address are considered invalid, and this345	///  function throws for queries about the zero address.346	/// @param owner An address for whom to query the balance347	/// @return The number of RFTs owned by `owner`, possibly zero348	fn balance_of(&self, owner: address) -> Result<uint256> {349		self.consume_store_reads(1)?;350		let owner = T::CrossAccountId::from_eth(owner);351		let balance = <AccountBalance<T>>::get((self.id, owner));352		Ok(balance.into())353	}354355	/// @notice Find the owner of an RFT356	/// @dev RFTs assigned to zero address are considered invalid, and queries357	///  about them do throw.358	///  Returns special 0xffffffffffffffffffffffffffffffffffffffff address for359	///  the tokens that are partially owned.360	/// @param tokenId The identifier for an RFT361	/// @return The address of the owner of the RFT362	fn owner_of(&self, token_id: uint256) -> Result<address> {363		self.consume_store_reads(2)?;364		let token = token_id.try_into()?;365		let owner = <Pallet<T>>::token_owner(self.id, token);366		Ok(owner367			.map(|address| *address.as_eth())368			.unwrap_or_else(|| ADDRESS_FOR_PARTIALLY_OWNED_TOKENS))369	}370371	/// @dev Not implemented372	fn safe_transfer_from_with_data(373		&mut self,374		_from: address,375		_to: address,376		_token_id: uint256,377		_data: bytes,378	) -> Result<void> {379		// TODO: Not implemetable380		Err("not implemented".into())381	}382383	/// @dev Not implemented384	fn safe_transfer_from(385		&mut self,386		_from: address,387		_to: address,388		_token_id: uint256,389	) -> Result<void> {390		// TODO: Not implemetable391		Err("not implemented".into())392	}393394	/// @notice Transfer ownership of an RFT -- THE CALLER IS RESPONSIBLE395	///  TO CONFIRM THAT `to` IS CAPABLE OF RECEIVING NFTS OR ELSE396	///  THEY MAY BE PERMANENTLY LOST397	/// @dev Throws unless `msg.sender` is the current owner or an authorized398	///  operator for this RFT. Throws if `from` is not the current owner. Throws399	///  if `to` is the zero address. Throws if `tokenId` is not a valid RFT.400	///  Throws if RFT pieces have multiple owners.401	/// @param from The current owner of the NFT402	/// @param to The new owner403	/// @param tokenId The NFT to transfer404	#[weight(<SelfWeightOf<T>>::transfer_from_creating_removing())]405	fn transfer_from(406		&mut self,407		caller: caller,408		from: address,409		to: address,410		token_id: uint256,411	) -> Result<void> {412		let caller = T::CrossAccountId::from_eth(caller);413		let from = T::CrossAccountId::from_eth(from);414		let to = T::CrossAccountId::from_eth(to);415		let token = token_id.try_into()?;416		let budget = self417			.recorder418			.weight_calls_budget(<StructureWeight<T>>::find_parent());419420		let balance = balance(&self, token, &from)?;421		ensure_single_owner(&self, token, balance)?;422423		<Pallet<T>>::transfer_from(self, &caller, &from, &to, token, balance, &budget)424			.map_err(dispatch_to_evm::<T>)?;425426		Ok(())427	}428429	/// @dev Not implemented430	fn approve(&mut self, _caller: caller, _approved: address, _token_id: uint256) -> Result<void> {431		Err("not implemented".into())432	}433434	/// @dev Not implemented435	fn set_approval_for_all(436		&mut self,437		_caller: caller,438		_operator: address,439		_approved: bool,440	) -> Result<void> {441		// TODO: Not implemetable442		Err("not implemented".into())443	}444445	/// @dev Not implemented446	fn get_approved(&self, _token_id: uint256) -> Result<address> {447		// TODO: Not implemetable448		Err("not implemented".into())449	}450451	/// @dev Not implemented452	fn is_approved_for_all(&self, _owner: address, _operator: address) -> Result<address> {453		// TODO: Not implemetable454		Err("not implemented".into())455	}456}457458/// Returns amount of pieces of `token` that `owner` have459pub fn balance<T: Config>(460	collection: &RefungibleHandle<T>,461	token: TokenId,462	owner: &T::CrossAccountId,463) -> Result<u128> {464	collection.consume_store_reads(1)?;465	let balance = <Balance<T>>::get((collection.id, token, &owner));466	Ok(balance)467}468469/// Throws if `owner_balance` is lower than total amount of `token` pieces470pub fn ensure_single_owner<T: Config>(471	collection: &RefungibleHandle<T>,472	token: TokenId,473	owner_balance: u128,474) -> Result<()> {475	collection.consume_store_reads(1)?;476	let total_supply = <TotalSupply<T>>::get((collection.id, token));477	if total_supply != owner_balance {478		return Err("token has multiple owners".into());479	}480	Ok(())481}482483/// @title ERC721 Token that can be irreversibly burned (destroyed).484#[solidity_interface(name = ERC721Burnable)]485impl<T: Config> RefungibleHandle<T> {486	/// @notice Burns a specific ERC721 token.487	/// @dev Throws unless `msg.sender` is the current RFT owner, or an authorized488	///  operator of the current owner.489	/// @param tokenId The RFT to approve490	#[weight(<SelfWeightOf<T>>::burn_item_fully())]491	fn burn(&mut self, caller: caller, token_id: uint256) -> Result<void> {492		let caller = T::CrossAccountId::from_eth(caller);493		let token = token_id.try_into()?;494495		let balance = balance(&self, token, &caller)?;496		ensure_single_owner(&self, token, balance)?;497498		<Pallet<T>>::burn(self, &caller, token, balance).map_err(dispatch_to_evm::<T>)?;499		Ok(())500	}501}502503/// @title ERC721 minting logic.504#[solidity_interface(name = ERC721UniqueMintable, events(ERC721UniqueMintableEvents))]505impl<T: Config> RefungibleHandle<T> {506	fn minting_finished(&self) -> Result<bool> {507		Ok(false)508	}509510	/// @notice Function to mint token.511	/// @param to The new owner512	/// @return uint256 The id of the newly minted token513	#[weight(<SelfWeightOf<T>>::create_item())]514	fn mint(&mut self, caller: caller, to: address) -> Result<uint256> {515		let token_id: uint256 = <TokensMinted<T>>::get(self.id)516			.checked_add(1)517			.ok_or("item id overflow")?518			.into();519		self.mint_check_id(caller, to, token_id)?;520		Ok(token_id)521	}522523	/// @notice Function to mint token.524	/// @dev `tokenId` should be obtained with `nextTokenId` method,525	///  unlike standard, you can't specify it manually526	/// @param to The new owner527	/// @param tokenId ID of the minted RFT528	#[solidity(hide, rename_selector = "mint")]529	#[weight(<SelfWeightOf<T>>::create_item())]530	fn mint_check_id(&mut self, caller: caller, to: address, token_id: uint256) -> Result<bool> {531		let caller = T::CrossAccountId::from_eth(caller);532		let to = T::CrossAccountId::from_eth(to);533		let token_id: u32 = token_id.try_into()?;534		let budget = self535			.recorder536			.weight_calls_budget(<StructureWeight<T>>::find_parent());537538		if <TokensMinted<T>>::get(self.id)539			.checked_add(1)540			.ok_or("item id overflow")?541			!= token_id542		{543			return Err("item id should be next".into());544		}545546		let users = [(to.clone(), 1)]547			.into_iter()548			.collect::<BTreeMap<_, _>>()549			.try_into()550			.unwrap();551		<Pallet<T>>::create_item(552			self,553			&caller,554			CreateItemData::<T::CrossAccountId> {555				users,556				properties: CollectionPropertiesVec::default(),557			},558			&budget,559		)560		.map_err(dispatch_to_evm::<T>)?;561562		Ok(true)563	}564565	/// @notice Function to mint token with the given tokenUri.566	/// @param to The new owner567	/// @param tokenUri Token URI that would be stored in the NFT properties568	/// @return uint256 The id of the newly minted token569	#[solidity(rename_selector = "mintWithTokenURI")]570	#[weight(<SelfWeightOf<T>>::create_item())]571	fn mint_with_token_uri(572		&mut self,573		caller: caller,574		to: address,575		token_uri: string,576	) -> Result<uint256> {577		let token_id: uint256 = <TokensMinted<T>>::get(self.id)578			.checked_add(1)579			.ok_or("item id overflow")?580			.into();581		self.mint_with_token_uri_check_id(caller, to, token_id, token_uri)?;582		Ok(token_id)583	}584585	/// @notice Function to mint token with the given tokenUri.586	/// @dev `tokenId` should be obtained with `nextTokenId` method,587	///  unlike standard, you can't specify it manually588	/// @param to The new owner589	/// @param tokenId ID of the minted RFT590	/// @param tokenUri Token URI that would be stored in the RFT properties591	#[solidity(hide, rename_selector = "mintWithTokenURI")]592	#[weight(<SelfWeightOf<T>>::create_item())]593	fn mint_with_token_uri_check_id(594		&mut self,595		caller: caller,596		to: address,597		token_id: uint256,598		token_uri: string,599	) -> Result<bool> {600		let key = key::url();601		let permission = get_token_permission::<T>(self.id, &key)?;602		if !permission.collection_admin {603			return Err("Operation is not allowed".into());604		}605606		let caller = T::CrossAccountId::from_eth(caller);607		let to = T::CrossAccountId::from_eth(to);608		let token_id: u32 = token_id.try_into().map_err(|_| "amount overflow")?;609		let budget = self610			.recorder611			.weight_calls_budget(<StructureWeight<T>>::find_parent());612613		if <TokensMinted<T>>::get(self.id)614			.checked_add(1)615			.ok_or("item id overflow")?616			!= token_id617		{618			return Err("item id should be next".into());619		}620621		let mut properties = CollectionPropertiesVec::default();622		properties623			.try_push(Property {624				key,625				value: token_uri626					.into_bytes()627					.try_into()628					.map_err(|_| "token uri is too long")?,629			})630			.map_err(|e| Error::Revert(alloc::format!("Can't add property: {:?}", e)))?;631632		let users = [(to.clone(), 1)]633			.into_iter()634			.collect::<BTreeMap<_, _>>()635			.try_into()636			.unwrap();637		<Pallet<T>>::create_item(638			self,639			&caller,640			CreateItemData::<T::CrossAccountId> { users, properties },641			&budget,642		)643		.map_err(dispatch_to_evm::<T>)?;644		Ok(true)645	}646647	/// @dev Not implemented648	fn finish_minting(&mut self, _caller: caller) -> Result<bool> {649		Err("not implementable".into())650	}651}652653fn get_token_property<T: Config>(654	collection: &CollectionHandle<T>,655	token_id: u32,656	key: &up_data_structs::PropertyKey,657) -> Result<string> {658	collection.consume_store_reads(1)?;659	let properties = <TokenProperties<T>>::try_get((collection.id, token_id))660		.map_err(|_| Error::Revert("Token properties not found".into()))?;661	if let Some(property) = properties.get(key) {662		return Ok(string::from_utf8_lossy(property).into());663	}664665	Err("Property tokenURI not found".into())666}667668fn get_token_permission<T: Config>(669	collection_id: CollectionId,670	key: &PropertyKey,671) -> Result<PropertyPermission> {672	let token_property_permissions = CollectionPropertyPermissions::<T>::try_get(collection_id)673		.map_err(|_| Error::Revert("No permissions for collection".into()))?;674	let a = token_property_permissions675		.get(key)676		.map(Clone::clone)677		.ok_or_else(|| {678			let key = string::from_utf8(key.clone().into_inner()).unwrap_or_default();679			Error::Revert(alloc::format!("No permission for key {}", key))680		})?;681	Ok(a)682}683684/// @title Unique extensions for ERC721.685#[solidity_interface(name = ERC721UniqueExtensions)]686impl<T: Config> RefungibleHandle<T>687where688	T::AccountId: From<[u8; 32]>,689{690	/// @notice A descriptive name for a collection of NFTs in this contract691	fn name(&self) -> Result<string> {692		Ok(decode_utf16(self.name.iter().copied())693			.map(|r| r.unwrap_or(REPLACEMENT_CHARACTER))694			.collect::<string>())695	}696697	/// @notice An abbreviated name for NFTs in this contract698	fn symbol(&self) -> Result<string> {699		Ok(string::from_utf8_lossy(&self.token_prefix).into())700	}701702	/// @notice Transfer ownership of an RFT703	/// @dev Throws unless `msg.sender` is the current owner. Throws if `to`704	///  is the zero address. Throws if `tokenId` is not a valid RFT.705	///  Throws if RFT pieces have multiple owners.706	/// @param to The new owner707	/// @param tokenId The RFT to transfer708	#[weight(<SelfWeightOf<T>>::transfer_creating_removing())]709	fn transfer(&mut self, caller: caller, to: address, token_id: uint256) -> Result<void> {710		let caller = T::CrossAccountId::from_eth(caller);711		let to = T::CrossAccountId::from_eth(to);712		let token = token_id.try_into()?;713		let budget = self714			.recorder715			.weight_calls_budget(<StructureWeight<T>>::find_parent());716717		let balance = balance(self, token, &caller)?;718		ensure_single_owner(self, token, balance)?;719720		<Pallet<T>>::transfer(self, &caller, &to, token, balance, &budget)721			.map_err(dispatch_to_evm::<T>)?;722		Ok(())723	}724725	/// @notice Transfer ownership of an RFT726	/// @dev Throws unless `msg.sender` is the current owner. Throws if `to`727	///  is the zero address. Throws if `tokenId` is not a valid RFT.728	///  Throws if RFT pieces have multiple owners.729	/// @param to The new owner730	/// @param tokenId The RFT to transfer731	#[weight(<SelfWeightOf<T>>::transfer_creating_removing())]732	fn transfer_from_cross(733		&mut self,734		caller: caller,735		from: EthCrossAccount,736		to: EthCrossAccount,737		token_id: uint256,738	) -> Result<void> {739		let caller = T::CrossAccountId::from_eth(caller);740		let from = from.into_sub_cross_account::<T>()?;741		let to = to.into_sub_cross_account::<T>()?;742		let token_id = token_id.try_into()?;743		let budget = self744			.recorder745			.weight_calls_budget(<StructureWeight<T>>::find_parent());746747		let balance = balance(self, token_id, &from)?;748		ensure_single_owner(self, token_id, balance)?;749750		Pallet::<T>::transfer_from(self, &caller, &from, &to, token_id, balance, &budget)751			.map_err(dispatch_to_evm::<T>)?;752		Ok(())753	}754755	/// @notice Burns a specific ERC721 token.756	/// @dev Throws unless `msg.sender` is the current owner or an authorized757	///  operator for this RFT. Throws if `from` is not the current owner. Throws758	///  if `to` is the zero address. Throws if `tokenId` is not a valid RFT.759	///  Throws if RFT pieces have multiple owners.760	/// @param from The current owner of the RFT761	/// @param tokenId The RFT to transfer762	#[weight(<SelfWeightOf<T>>::burn_from())]763	fn burn_from(&mut self, caller: caller, from: address, token_id: uint256) -> Result<void> {764		let caller = T::CrossAccountId::from_eth(caller);765		let from = T::CrossAccountId::from_eth(from);766		let token = token_id.try_into()?;767		let budget = self768			.recorder769			.weight_calls_budget(<StructureWeight<T>>::find_parent());770771		let balance = balance(self, token, &from)?;772		ensure_single_owner(self, token, balance)?;773774		<Pallet<T>>::burn_from(self, &caller, &from, token, balance, &budget)775			.map_err(dispatch_to_evm::<T>)?;776		Ok(())777	}778779	/// @notice Burns a specific ERC721 token.780	/// @dev Throws unless `msg.sender` is the current owner or an authorized781	///  operator for this RFT. Throws if `from` is not the current owner. Throws782	///  if `to` is the zero address. Throws if `tokenId` is not a valid RFT.783	///  Throws if RFT pieces have multiple owners.784	/// @param from The current owner of the RFT785	/// @param tokenId The RFT to transfer786	#[weight(<SelfWeightOf<T>>::burn_from())]787	fn burn_from_cross(788		&mut self,789		caller: caller,790		from: EthCrossAccount,791		token_id: uint256,792	) -> Result<void> {793		let caller = T::CrossAccountId::from_eth(caller);794		let from = from.into_sub_cross_account::<T>()?;795		let token = token_id.try_into()?;796		let budget = self797			.recorder798			.weight_calls_budget(<StructureWeight<T>>::find_parent());799800		let balance = balance(self, token, &from)?;801		ensure_single_owner(self, token, balance)?;802803		<Pallet<T>>::burn_from(self, &caller, &from, token, balance, &budget)804			.map_err(dispatch_to_evm::<T>)?;805		Ok(())806	}807808	/// @notice Returns next free RFT ID.809	fn next_token_id(&self) -> Result<uint256> {810		self.consume_store_reads(1)?;811		Ok(<TokensMinted<T>>::get(self.id)812			.checked_add(1)813			.ok_or("item id overflow")?814			.into())815	}816817	/// @notice Function to mint multiple tokens.818	/// @dev `tokenIds` should be an array of consecutive numbers and first number819	///  should be obtained with `nextTokenId` method820	/// @param to The new owner821	/// @param tokenIds IDs of the minted RFTs822	#[solidity(hide)]823	#[weight(<SelfWeightOf<T>>::create_multiple_items(token_ids.len() as u32))]824	fn mint_bulk(&mut self, caller: caller, to: address, token_ids: Vec<uint256>) -> Result<bool> {825		let caller = T::CrossAccountId::from_eth(caller);826		let to = T::CrossAccountId::from_eth(to);827		let mut expected_index = <TokensMinted<T>>::get(self.id)828			.checked_add(1)829			.ok_or("item id overflow")?;830		let budget = self831			.recorder832			.weight_calls_budget(<StructureWeight<T>>::find_parent());833834		let total_tokens = token_ids.len();835		for id in token_ids.into_iter() {836			let id: u32 = id.try_into().map_err(|_| "token id overflow")?;837			if id != expected_index {838				return Err("item id should be next".into());839			}840			expected_index = expected_index.checked_add(1).ok_or("item id overflow")?;841		}842		let users = [(to.clone(), 1)]843			.into_iter()844			.collect::<BTreeMap<_, _>>()845			.try_into()846			.unwrap();847		let create_item_data = CreateItemData::<T::CrossAccountId> {848			users,849			properties: CollectionPropertiesVec::default(),850		};851		let data = (0..total_tokens)852			.map(|_| create_item_data.clone())853			.collect();854855		<Pallet<T>>::create_multiple_items(self, &caller, data, &budget)856			.map_err(dispatch_to_evm::<T>)?;857		Ok(true)858	}859860	/// @notice Function to mint multiple tokens with the given tokenUris.861	/// @dev `tokenIds` is array of pairs of token ID and token URI. Token IDs should be consecutive862	///  numbers and first number should be obtained with `nextTokenId` method863	/// @param to The new owner864	/// @param tokens array of pairs of token ID and token URI for minted tokens865	#[solidity(hide, rename_selector = "mintBulkWithTokenURI")]866	#[weight(<SelfWeightOf<T>>::create_multiple_items(tokens.len() as u32))]867	fn mint_bulk_with_token_uri(868		&mut self,869		caller: caller,870		to: address,871		tokens: Vec<(uint256, string)>,872	) -> Result<bool> {873		let key = key::url();874		let caller = T::CrossAccountId::from_eth(caller);875		let to = T::CrossAccountId::from_eth(to);876		let mut expected_index = <TokensMinted<T>>::get(self.id)877			.checked_add(1)878			.ok_or("item id overflow")?;879		let budget = self880			.recorder881			.weight_calls_budget(<StructureWeight<T>>::find_parent());882883		let mut data = Vec::with_capacity(tokens.len());884		let users: BoundedBTreeMap<_, _, _> = [(to.clone(), 1)]885			.into_iter()886			.collect::<BTreeMap<_, _>>()887			.try_into()888			.unwrap();889		for (id, token_uri) in tokens {890			let id: u32 = id.try_into().map_err(|_| "token id overflow")?;891			if id != expected_index {892				return Err("item id should be next".into());893			}894			expected_index = expected_index.checked_add(1).ok_or("item id overflow")?;895896			let mut properties = CollectionPropertiesVec::default();897			properties898				.try_push(Property {899					key: key.clone(),900					value: token_uri901						.into_bytes()902						.try_into()903						.map_err(|_| "token uri is too long")?,904				})905				.map_err(|e| Error::Revert(alloc::format!("Can't add property: {:?}", e)))?;906907			let create_item_data = CreateItemData::<T::CrossAccountId> {908				users: users.clone(),909				properties,910			};911			data.push(create_item_data);912		}913914		<Pallet<T>>::create_multiple_items(self, &caller, data, &budget)915			.map_err(dispatch_to_evm::<T>)?;916		Ok(true)917	}918919	/// Returns EVM address for refungible token920	///921	/// @param token ID of the token922	fn token_contract_address(&self, token: uint256) -> Result<address> {923		Ok(T::EvmTokenAddressMapping::token_to_address(924			self.id,925			token.try_into().map_err(|_| "token id overflow")?,926		))927	}928}929930#[solidity_interface(931	name = UniqueRefungible,932	is(933		ERC721,934		ERC721Enumerable,935		ERC721UniqueExtensions,936		ERC721UniqueMintable,937		ERC721Burnable,938		ERC721Metadata(if(this.flags.erc721metadata)),939		Collection(via(common_mut returns CollectionHandle<T>)),940		TokenProperties,941	)942)]943impl<T: Config> RefungibleHandle<T> where T::AccountId: From<[u8; 32]> + AsRef<[u8; 32]> {}944945// Not a tests, but code generators946generate_stubgen!(gen_impl, UniqueRefungibleCall<()>, true);947generate_stubgen!(gen_iface, UniqueRefungibleCall<()>, false);948949impl<T: Config> CommonEvmHandler for RefungibleHandle<T>950where951	T::AccountId: From<[u8; 32]> + AsRef<[u8; 32]>,952{953	const CODE: &'static [u8] = include_bytes!("./stubs/UniqueRefungible.raw");954	fn call(955		self,956		handle: &mut impl PrecompileHandle,957	) -> Option<pallet_common::erc::PrecompileResult> {958		call::<T, UniqueRefungibleCall<T>, _, _>(handle, self)959	}960}
after · pallets/refungible/src/erc.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//! # Refungible Pallet EVM API for tokens18//!19//! Provides ERC-721 standart support implementation and EVM API for unique extensions for Refungible Pallet.20//! Method implementations are mostly doing parameter conversion and calling Refungible Pallet methods.2122extern crate alloc;2324use core::{25	char::{REPLACEMENT_CHARACTER, decode_utf16},26	convert::TryInto,27};28use evm_coder::{ToLog, execution::*, generate_stubgen, solidity, solidity_interface, types::*, weight};29use frame_support::{BoundedBTreeMap, BoundedVec};30use pallet_common::{31	CollectionHandle, CollectionPropertyPermissions,32	erc::{CommonEvmHandler, CollectionCall, static_property::key},33};34use pallet_evm::{account::CrossAccountId, PrecompileHandle};35use pallet_evm_coder_substrate::{call, dispatch_to_evm};36use pallet_structure::{SelfWeightOf as StructureWeight, weights::WeightInfo as _};37use sp_core::H160;38use sp_std::{collections::btree_map::BTreeMap, vec::Vec, vec};39use up_data_structs::{40	CollectionId, CollectionPropertiesVec, mapping::TokenAddressMapping, Property, PropertyKey,41	PropertyKeyPermission, PropertyPermission, TokenId,42};4344use crate::{45	AccountBalance, Balance, Config, CreateItemData, Pallet, RefungibleHandle, SelfWeightOf,46	TokenProperties, TokensMinted, TotalSupply, weights::WeightInfo,47};4849pub const ADDRESS_FOR_PARTIALLY_OWNED_TOKENS: H160 = H160::repeat_byte(0xff);5051/// @title A contract that allows to set and delete token properties and change token property permissions.52#[solidity_interface(name = TokenProperties)]53impl<T: Config> RefungibleHandle<T> {54	/// @notice Set permissions for token property.55	/// @dev Throws error if `msg.sender` is not admin or owner of the collection.56	/// @param key Property key.57	/// @param isMutable Permission to mutate property.58	/// @param collectionAdmin Permission to mutate property by collection admin if property is mutable.59	/// @param tokenOwner Permission to mutate property by token owner if property is mutable.60	fn set_token_property_permission(61		&mut self,62		caller: caller,63		key: string,64		is_mutable: bool,65		collection_admin: bool,66		token_owner: bool,67	) -> Result<()> {68		let caller = T::CrossAccountId::from_eth(caller);69		<Pallet<T>>::set_token_property_permissions(70			self,71			&caller,72			vec![PropertyKeyPermission {73				key: <Vec<u8>>::from(key)74					.try_into()75					.map_err(|_| "too long key")?,76				permission: PropertyPermission {77					mutable: is_mutable,78					collection_admin,79					token_owner,80				},81			}],82		)83		.map_err(dispatch_to_evm::<T>)84	}8586	/// @notice Set token property value.87	/// @dev Throws error if `msg.sender` has no permission to edit the property.88	/// @param tokenId ID of the token.89	/// @param key Property key.90	/// @param value Property value.91	fn set_property(92		&mut self,93		caller: caller,94		token_id: uint256,95		key: string,96		value: bytes,97	) -> Result<()> {98		let caller = T::CrossAccountId::from_eth(caller);99		let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;100		let key = <Vec<u8>>::from(key)101			.try_into()102			.map_err(|_| "key too long")?;103		let value = value.0.try_into().map_err(|_| "value too long")?;104105		let nesting_budget = self106			.recorder107			.weight_calls_budget(<StructureWeight<T>>::find_parent());108109		<Pallet<T>>::set_token_property(110			self,111			&caller,112			TokenId(token_id),113			Property { key, value },114			&nesting_budget,115		)116		.map_err(dispatch_to_evm::<T>)117	}118119	/// @notice Set token properties value.120	/// @dev Throws error if `msg.sender` has no permission to edit the property.121	/// @param tokenId ID of the token.122	/// @param properties settable properties123	fn set_properties(124		&mut self,125		caller: caller,126		token_id: uint256,127		properties: Vec<(string, bytes)>,128	) -> Result<()> {129		let caller = T::CrossAccountId::from_eth(caller);130		let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;131132		let nesting_budget = self133			.recorder134			.weight_calls_budget(<StructureWeight<T>>::find_parent());135136		let properties = properties137			.into_iter()138			.map(|(key, value)| {139				let key = <Vec<u8>>::from(key)140					.try_into()141					.map_err(|_| "key too large")?;142143				let value = value.0.try_into().map_err(|_| "value too large")?;144145				Ok(Property { key, value })146			})147			.collect::<Result<Vec<_>>>()?;148149		<Pallet<T>>::set_token_properties(150			self,151			&caller,152			TokenId(token_id),153			properties.into_iter(),154			<Pallet<T>>::token_exists(&self, TokenId(token_id)),155			&nesting_budget,156		)157		.map_err(dispatch_to_evm::<T>)158	}159160	/// @notice Delete token property value.161	/// @dev Throws error if `msg.sender` has no permission to edit the property.162	/// @param tokenId ID of the token.163	/// @param key Property key.164	fn delete_property(&mut self, token_id: uint256, caller: caller, key: string) -> Result<()> {165		let caller = T::CrossAccountId::from_eth(caller);166		let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;167		let key = <Vec<u8>>::from(key)168			.try_into()169			.map_err(|_| "key too long")?;170171		let nesting_budget = self172			.recorder173			.weight_calls_budget(<StructureWeight<T>>::find_parent());174175		<Pallet<T>>::delete_token_property(self, &caller, TokenId(token_id), key, &nesting_budget)176			.map_err(dispatch_to_evm::<T>)177	}178179	/// @notice Get token property value.180	/// @dev Throws error if key not found181	/// @param tokenId ID of the token.182	/// @param key Property key.183	/// @return Property value bytes184	fn property(&self, token_id: uint256, key: string) -> Result<bytes> {185		let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;186		let key = <Vec<u8>>::from(key)187			.try_into()188			.map_err(|_| "key too long")?;189190		let props = <TokenProperties<T>>::get((self.id, token_id));191		let prop = props.get(&key).ok_or("key not found")?;192193		Ok(prop.to_vec().into())194	}195}196197#[derive(ToLog)]198pub enum ERC721Events {199	/// @dev This event emits when NFTs are created (`from` == 0) and destroyed200	///  (`to` == 0). Exception: during contract creation, any number of RFTs201	///  may be created and assigned without emitting Transfer.202	Transfer {203		#[indexed]204		from: address,205		#[indexed]206		to: address,207		#[indexed]208		token_id: uint256,209	},210	/// @dev Not supported211	Approval {212		#[indexed]213		owner: address,214		#[indexed]215		approved: address,216		#[indexed]217		token_id: uint256,218	},219	/// @dev Not supported220	#[allow(dead_code)]221	ApprovalForAll {222		#[indexed]223		owner: address,224		#[indexed]225		operator: address,226		approved: bool,227	},228}229230#[derive(ToLog)]231pub enum ERC721UniqueMintableEvents {232	/// @dev Not supported233	#[allow(dead_code)]234	MintingFinished {},235}236237#[solidity_interface(name = ERC721Metadata)]238impl<T: Config> RefungibleHandle<T>239where240	T::AccountId: From<[u8; 32]>,241{242	/// @notice A descriptive name for a collection of NFTs in this contract243	/// @dev real implementation of this function lies in `ERC721UniqueExtensions`244	#[solidity(hide, rename_selector = "name")]245	fn name_proxy(&self) -> Result<string> {246		self.name()247	}248249	/// @notice An abbreviated name for NFTs in this contract250	/// @dev real implementation of this function lies in `ERC721UniqueExtensions`251	#[solidity(hide, rename_selector = "symbol")]252	fn symbol_proxy(&self) -> Result<string> {253		self.symbol()254	}255256	/// @notice A distinct Uniform Resource Identifier (URI) for a given asset.257	///258	/// @dev If the token has a `url` property and it is not empty, it is returned.259	///  Else If the collection does not have a property with key `schemaName` or its value is not equal to `ERC721Metadata`, it return an error `tokenURI not set`.260	///  If the collection property `baseURI` is empty or absent, return "" (empty string)261	///  otherwise, if token property `suffix` present and is non-empty, return concatenation of baseURI and suffix262	///  otherwise, return concatenation of `baseURI` and stringified token id (decimal stringifying, without paddings).263	///264	/// @return token's const_metadata265	#[solidity(rename_selector = "tokenURI")]266	fn token_uri(&self, token_id: uint256) -> Result<string> {267		let token_id_u32: u32 = token_id.try_into().map_err(|_| "token id overflow")?;268269		match get_token_property(self, token_id_u32, &key::url()).as_deref() {270			Err(_) | Ok("") => (),271			Ok(url) => {272				return Ok(url.into());273			}274		};275276		let base_uri =277			pallet_common::Pallet::<T>::get_collection_property(self.id, &key::base_uri())278				.map(BoundedVec::into_inner)279				.map(string::from_utf8)280				.transpose()281				.map_err(|e| {282					Error::Revert(alloc::format!(283						"Can not convert value \"baseURI\" to string with error \"{}\"",284						e285					))286				})?;287288		let base_uri = match base_uri.as_deref() {289			None | Some("") => {290				return Ok("".into());291			}292			Some(base_uri) => base_uri.into(),293		};294295		Ok(296			match get_token_property(self, token_id_u32, &key::suffix()).as_deref() {297				Err(_) | Ok("") => base_uri,298				Ok(suffix) => base_uri + suffix,299			},300		)301	}302}303304/// @title ERC-721 Non-Fungible Token Standard, optional enumeration extension305/// @dev See https://eips.ethereum.org/EIPS/eip-721306#[solidity_interface(name = ERC721Enumerable)]307impl<T: Config> RefungibleHandle<T> {308	/// @notice Enumerate valid RFTs309	/// @param index A counter less than `totalSupply()`310	/// @return The token identifier for the `index`th NFT,311	///  (sort order not specified)312	fn token_by_index(&self, index: uint256) -> Result<uint256> {313		Ok(index)314	}315316	/// Not implemented317	fn token_of_owner_by_index(&self, _owner: address, _index: uint256) -> Result<uint256> {318		// TODO: Not implemetable319		Err("not implemented".into())320	}321322	/// @notice Count RFTs tracked by this contract323	/// @return A count of valid RFTs tracked by this contract, where each one of324	///  them has an assigned and queryable owner not equal to the zero address325	fn total_supply(&self) -> Result<uint256> {326		self.consume_store_reads(1)?;327		Ok(<Pallet<T>>::total_supply(self).into())328	}329}330331/// @title ERC-721 Non-Fungible Token Standard332/// @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md333#[solidity_interface(name = ERC721, events(ERC721Events))]334impl<T: Config> RefungibleHandle<T> {335	/// @notice Count all RFTs assigned to an owner336	/// @dev RFTs assigned to the zero address are considered invalid, and this337	///  function throws for queries about the zero address.338	/// @param owner An address for whom to query the balance339	/// @return The number of RFTs owned by `owner`, possibly zero340	fn balance_of(&self, owner: address) -> Result<uint256> {341		self.consume_store_reads(1)?;342		let owner = T::CrossAccountId::from_eth(owner);343		let balance = <AccountBalance<T>>::get((self.id, owner));344		Ok(balance.into())345	}346347	/// @notice Find the owner of an RFT348	/// @dev RFTs assigned to zero address are considered invalid, and queries349	///  about them do throw.350	///  Returns special 0xffffffffffffffffffffffffffffffffffffffff address for351	///  the tokens that are partially owned.352	/// @param tokenId The identifier for an RFT353	/// @return The address of the owner of the RFT354	fn owner_of(&self, token_id: uint256) -> Result<address> {355		self.consume_store_reads(2)?;356		let token = token_id.try_into()?;357		let owner = <Pallet<T>>::token_owner(self.id, token);358		Ok(owner359			.map(|address| *address.as_eth())360			.unwrap_or_else(|| ADDRESS_FOR_PARTIALLY_OWNED_TOKENS))361	}362363	/// @dev Not implemented364	fn safe_transfer_from_with_data(365		&mut self,366		_from: address,367		_to: address,368		_token_id: uint256,369		_data: bytes,370	) -> Result<void> {371		// TODO: Not implemetable372		Err("not implemented".into())373	}374375	/// @dev Not implemented376	fn safe_transfer_from(377		&mut self,378		_from: address,379		_to: address,380		_token_id: uint256,381	) -> Result<void> {382		// TODO: Not implemetable383		Err("not implemented".into())384	}385386	/// @notice Transfer ownership of an RFT -- THE CALLER IS RESPONSIBLE387	///  TO CONFIRM THAT `to` IS CAPABLE OF RECEIVING NFTS OR ELSE388	///  THEY MAY BE PERMANENTLY LOST389	/// @dev Throws unless `msg.sender` is the current owner or an authorized390	///  operator for this RFT. Throws if `from` is not the current owner. Throws391	///  if `to` is the zero address. Throws if `tokenId` is not a valid RFT.392	///  Throws if RFT pieces have multiple owners.393	/// @param from The current owner of the NFT394	/// @param to The new owner395	/// @param tokenId The NFT to transfer396	#[weight(<SelfWeightOf<T>>::transfer_from_creating_removing())]397	fn transfer_from(398		&mut self,399		caller: caller,400		from: address,401		to: address,402		token_id: uint256,403	) -> Result<void> {404		let caller = T::CrossAccountId::from_eth(caller);405		let from = T::CrossAccountId::from_eth(from);406		let to = T::CrossAccountId::from_eth(to);407		let token = token_id.try_into()?;408		let budget = self409			.recorder410			.weight_calls_budget(<StructureWeight<T>>::find_parent());411412		let balance = balance(&self, token, &from)?;413		ensure_single_owner(&self, token, balance)?;414415		<Pallet<T>>::transfer_from(self, &caller, &from, &to, token, balance, &budget)416			.map_err(dispatch_to_evm::<T>)?;417418		Ok(())419	}420421	/// @dev Not implemented422	fn approve(&mut self, _caller: caller, _approved: address, _token_id: uint256) -> Result<void> {423		Err("not implemented".into())424	}425426	/// @dev Not implemented427	fn set_approval_for_all(428		&mut self,429		_caller: caller,430		_operator: address,431		_approved: bool,432	) -> Result<void> {433		// TODO: Not implemetable434		Err("not implemented".into())435	}436437	/// @dev Not implemented438	fn get_approved(&self, _token_id: uint256) -> Result<address> {439		// TODO: Not implemetable440		Err("not implemented".into())441	}442443	/// @dev Not implemented444	fn is_approved_for_all(&self, _owner: address, _operator: address) -> Result<address> {445		// TODO: Not implemetable446		Err("not implemented".into())447	}448}449450/// Returns amount of pieces of `token` that `owner` have451pub fn balance<T: Config>(452	collection: &RefungibleHandle<T>,453	token: TokenId,454	owner: &T::CrossAccountId,455) -> Result<u128> {456	collection.consume_store_reads(1)?;457	let balance = <Balance<T>>::get((collection.id, token, &owner));458	Ok(balance)459}460461/// Throws if `owner_balance` is lower than total amount of `token` pieces462pub fn ensure_single_owner<T: Config>(463	collection: &RefungibleHandle<T>,464	token: TokenId,465	owner_balance: u128,466) -> Result<()> {467	collection.consume_store_reads(1)?;468	let total_supply = <TotalSupply<T>>::get((collection.id, token));469	if total_supply != owner_balance {470		return Err("token has multiple owners".into());471	}472	Ok(())473}474475/// @title ERC721 Token that can be irreversibly burned (destroyed).476#[solidity_interface(name = ERC721Burnable)]477impl<T: Config> RefungibleHandle<T> {478	/// @notice Burns a specific ERC721 token.479	/// @dev Throws unless `msg.sender` is the current RFT owner, or an authorized480	///  operator of the current owner.481	/// @param tokenId The RFT to approve482	#[weight(<SelfWeightOf<T>>::burn_item_fully())]483	fn burn(&mut self, caller: caller, token_id: uint256) -> Result<void> {484		let caller = T::CrossAccountId::from_eth(caller);485		let token = token_id.try_into()?;486487		let balance = balance(&self, token, &caller)?;488		ensure_single_owner(&self, token, balance)?;489490		<Pallet<T>>::burn(self, &caller, token, balance).map_err(dispatch_to_evm::<T>)?;491		Ok(())492	}493}494495/// @title ERC721 minting logic.496#[solidity_interface(name = ERC721UniqueMintable, events(ERC721UniqueMintableEvents))]497impl<T: Config> RefungibleHandle<T> {498	fn minting_finished(&self) -> Result<bool> {499		Ok(false)500	}501502	/// @notice Function to mint token.503	/// @param to The new owner504	/// @return uint256 The id of the newly minted token505	#[weight(<SelfWeightOf<T>>::create_item())]506	fn mint(&mut self, caller: caller, to: address) -> Result<uint256> {507		let token_id: uint256 = <TokensMinted<T>>::get(self.id)508			.checked_add(1)509			.ok_or("item id overflow")?510			.into();511		self.mint_check_id(caller, to, token_id)?;512		Ok(token_id)513	}514515	/// @notice Function to mint token.516	/// @dev `tokenId` should be obtained with `nextTokenId` method,517	///  unlike standard, you can't specify it manually518	/// @param to The new owner519	/// @param tokenId ID of the minted RFT520	#[solidity(hide, rename_selector = "mint")]521	#[weight(<SelfWeightOf<T>>::create_item())]522	fn mint_check_id(&mut self, caller: caller, to: address, token_id: uint256) -> Result<bool> {523		let caller = T::CrossAccountId::from_eth(caller);524		let to = T::CrossAccountId::from_eth(to);525		let token_id: u32 = token_id.try_into()?;526		let budget = self527			.recorder528			.weight_calls_budget(<StructureWeight<T>>::find_parent());529530		if <TokensMinted<T>>::get(self.id)531			.checked_add(1)532			.ok_or("item id overflow")?533			!= token_id534		{535			return Err("item id should be next".into());536		}537538		let users = [(to.clone(), 1)]539			.into_iter()540			.collect::<BTreeMap<_, _>>()541			.try_into()542			.unwrap();543		<Pallet<T>>::create_item(544			self,545			&caller,546			CreateItemData::<T::CrossAccountId> {547				users,548				properties: CollectionPropertiesVec::default(),549			},550			&budget,551		)552		.map_err(dispatch_to_evm::<T>)?;553554		Ok(true)555	}556557	/// @notice Function to mint token with the given tokenUri.558	/// @param to The new owner559	/// @param tokenUri Token URI that would be stored in the NFT properties560	/// @return uint256 The id of the newly minted token561	#[solidity(rename_selector = "mintWithTokenURI")]562	#[weight(<SelfWeightOf<T>>::create_item())]563	fn mint_with_token_uri(564		&mut self,565		caller: caller,566		to: address,567		token_uri: string,568	) -> Result<uint256> {569		let token_id: uint256 = <TokensMinted<T>>::get(self.id)570			.checked_add(1)571			.ok_or("item id overflow")?572			.into();573		self.mint_with_token_uri_check_id(caller, to, token_id, token_uri)?;574		Ok(token_id)575	}576577	/// @notice Function to mint token with the given tokenUri.578	/// @dev `tokenId` should be obtained with `nextTokenId` method,579	///  unlike standard, you can't specify it manually580	/// @param to The new owner581	/// @param tokenId ID of the minted RFT582	/// @param tokenUri Token URI that would be stored in the RFT properties583	#[solidity(hide, rename_selector = "mintWithTokenURI")]584	#[weight(<SelfWeightOf<T>>::create_item())]585	fn mint_with_token_uri_check_id(586		&mut self,587		caller: caller,588		to: address,589		token_id: uint256,590		token_uri: string,591	) -> Result<bool> {592		let key = key::url();593		let permission = get_token_permission::<T>(self.id, &key)?;594		if !permission.collection_admin {595			return Err("Operation is not allowed".into());596		}597598		let caller = T::CrossAccountId::from_eth(caller);599		let to = T::CrossAccountId::from_eth(to);600		let token_id: u32 = token_id.try_into().map_err(|_| "amount overflow")?;601		let budget = self602			.recorder603			.weight_calls_budget(<StructureWeight<T>>::find_parent());604605		if <TokensMinted<T>>::get(self.id)606			.checked_add(1)607			.ok_or("item id overflow")?608			!= token_id609		{610			return Err("item id should be next".into());611		}612613		let mut properties = CollectionPropertiesVec::default();614		properties615			.try_push(Property {616				key,617				value: token_uri618					.into_bytes()619					.try_into()620					.map_err(|_| "token uri is too long")?,621			})622			.map_err(|e| Error::Revert(alloc::format!("Can't add property: {:?}", e)))?;623624		let users = [(to.clone(), 1)]625			.into_iter()626			.collect::<BTreeMap<_, _>>()627			.try_into()628			.unwrap();629		<Pallet<T>>::create_item(630			self,631			&caller,632			CreateItemData::<T::CrossAccountId> { users, properties },633			&budget,634		)635		.map_err(dispatch_to_evm::<T>)?;636		Ok(true)637	}638639	/// @dev Not implemented640	fn finish_minting(&mut self, _caller: caller) -> Result<bool> {641		Err("not implementable".into())642	}643}644645fn get_token_property<T: Config>(646	collection: &CollectionHandle<T>,647	token_id: u32,648	key: &up_data_structs::PropertyKey,649) -> Result<string> {650	collection.consume_store_reads(1)?;651	let properties = <TokenProperties<T>>::try_get((collection.id, token_id))652		.map_err(|_| Error::Revert("Token properties not found".into()))?;653	if let Some(property) = properties.get(key) {654		return Ok(string::from_utf8_lossy(property).into());655	}656657	Err("Property tokenURI not found".into())658}659660fn get_token_permission<T: Config>(661	collection_id: CollectionId,662	key: &PropertyKey,663) -> Result<PropertyPermission> {664	let token_property_permissions = CollectionPropertyPermissions::<T>::try_get(collection_id)665		.map_err(|_| Error::Revert("No permissions for collection".into()))?;666	let a = token_property_permissions667		.get(key)668		.map(Clone::clone)669		.ok_or_else(|| {670			let key = string::from_utf8(key.clone().into_inner()).unwrap_or_default();671			Error::Revert(alloc::format!("No permission for key {}", key))672		})?;673	Ok(a)674}675676/// @title Unique extensions for ERC721.677#[solidity_interface(name = ERC721UniqueExtensions)]678impl<T: Config> RefungibleHandle<T>679where680	T::AccountId: From<[u8; 32]>,681{682	/// @notice A descriptive name for a collection of NFTs in this contract683	fn name(&self) -> Result<string> {684		Ok(decode_utf16(self.name.iter().copied())685			.map(|r| r.unwrap_or(REPLACEMENT_CHARACTER))686			.collect::<string>())687	}688689	/// @notice An abbreviated name for NFTs in this contract690	fn symbol(&self) -> Result<string> {691		Ok(string::from_utf8_lossy(&self.token_prefix).into())692	}693694	/// @notice Transfer ownership of an RFT695	/// @dev Throws unless `msg.sender` is the current owner. Throws if `to`696	///  is the zero address. Throws if `tokenId` is not a valid RFT.697	///  Throws if RFT pieces have multiple owners.698	/// @param to The new owner699	/// @param tokenId The RFT to transfer700	#[weight(<SelfWeightOf<T>>::transfer_creating_removing())]701	fn transfer(&mut self, caller: caller, to: address, token_id: uint256) -> Result<void> {702		let caller = T::CrossAccountId::from_eth(caller);703		let to = T::CrossAccountId::from_eth(to);704		let token = token_id.try_into()?;705		let budget = self706			.recorder707			.weight_calls_budget(<StructureWeight<T>>::find_parent());708709		let balance = balance(self, token, &caller)?;710		ensure_single_owner(self, token, balance)?;711712		<Pallet<T>>::transfer(self, &caller, &to, token, balance, &budget)713			.map_err(dispatch_to_evm::<T>)?;714		Ok(())715	}716717	/// @notice Transfer ownership of an RFT718	/// @dev Throws unless `msg.sender` is the current owner. Throws if `to`719	///  is the zero address. Throws if `tokenId` is not a valid RFT.720	///  Throws if RFT pieces have multiple owners.721	/// @param to The new owner722	/// @param tokenId The RFT to transfer723	#[weight(<SelfWeightOf<T>>::transfer_creating_removing())]724	fn transfer_from_cross(725		&mut self,726		caller: caller,727		from: EthCrossAccount,728		to: EthCrossAccount,729		token_id: uint256,730	) -> Result<void> {731		let caller = T::CrossAccountId::from_eth(caller);732		let from = from.into_sub_cross_account::<T>()?;733		let to = to.into_sub_cross_account::<T>()?;734		let token_id = token_id.try_into()?;735		let budget = self736			.recorder737			.weight_calls_budget(<StructureWeight<T>>::find_parent());738739		let balance = balance(self, token_id, &from)?;740		ensure_single_owner(self, token_id, balance)?;741742		Pallet::<T>::transfer_from(self, &caller, &from, &to, token_id, balance, &budget)743			.map_err(dispatch_to_evm::<T>)?;744		Ok(())745	}746747	/// @notice Burns a specific ERC721 token.748	/// @dev Throws unless `msg.sender` is the current owner or an authorized749	///  operator for this RFT. Throws if `from` is not the current owner. Throws750	///  if `to` is the zero address. Throws if `tokenId` is not a valid RFT.751	///  Throws if RFT pieces have multiple owners.752	/// @param from The current owner of the RFT753	/// @param tokenId The RFT to transfer754	#[weight(<SelfWeightOf<T>>::burn_from())]755	fn burn_from(&mut self, caller: caller, from: address, token_id: uint256) -> Result<void> {756		let caller = T::CrossAccountId::from_eth(caller);757		let from = T::CrossAccountId::from_eth(from);758		let token = token_id.try_into()?;759		let budget = self760			.recorder761			.weight_calls_budget(<StructureWeight<T>>::find_parent());762763		let balance = balance(self, token, &from)?;764		ensure_single_owner(self, token, balance)?;765766		<Pallet<T>>::burn_from(self, &caller, &from, token, balance, &budget)767			.map_err(dispatch_to_evm::<T>)?;768		Ok(())769	}770771	/// @notice Burns a specific ERC721 token.772	/// @dev Throws unless `msg.sender` is the current owner or an authorized773	///  operator for this RFT. Throws if `from` is not the current owner. Throws774	///  if `to` is the zero address. Throws if `tokenId` is not a valid RFT.775	///  Throws if RFT pieces have multiple owners.776	/// @param from The current owner of the RFT777	/// @param tokenId The RFT to transfer778	#[weight(<SelfWeightOf<T>>::burn_from())]779	fn burn_from_cross(780		&mut self,781		caller: caller,782		from: EthCrossAccount,783		token_id: uint256,784	) -> Result<void> {785		let caller = T::CrossAccountId::from_eth(caller);786		let from = from.into_sub_cross_account::<T>()?;787		let token = token_id.try_into()?;788		let budget = self789			.recorder790			.weight_calls_budget(<StructureWeight<T>>::find_parent());791792		let balance = balance(self, token, &from)?;793		ensure_single_owner(self, token, balance)?;794795		<Pallet<T>>::burn_from(self, &caller, &from, token, balance, &budget)796			.map_err(dispatch_to_evm::<T>)?;797		Ok(())798	}799800	/// @notice Returns next free RFT ID.801	fn next_token_id(&self) -> Result<uint256> {802		self.consume_store_reads(1)?;803		Ok(<TokensMinted<T>>::get(self.id)804			.checked_add(1)805			.ok_or("item id overflow")?806			.into())807	}808809	/// @notice Function to mint multiple tokens.810	/// @dev `tokenIds` should be an array of consecutive numbers and first number811	///  should be obtained with `nextTokenId` method812	/// @param to The new owner813	/// @param tokenIds IDs of the minted RFTs814	#[solidity(hide)]815	#[weight(<SelfWeightOf<T>>::create_multiple_items(token_ids.len() as u32))]816	fn mint_bulk(&mut self, caller: caller, to: address, token_ids: Vec<uint256>) -> Result<bool> {817		let caller = T::CrossAccountId::from_eth(caller);818		let to = T::CrossAccountId::from_eth(to);819		let mut expected_index = <TokensMinted<T>>::get(self.id)820			.checked_add(1)821			.ok_or("item id overflow")?;822		let budget = self823			.recorder824			.weight_calls_budget(<StructureWeight<T>>::find_parent());825826		let total_tokens = token_ids.len();827		for id in token_ids.into_iter() {828			let id: u32 = id.try_into().map_err(|_| "token id overflow")?;829			if id != expected_index {830				return Err("item id should be next".into());831			}832			expected_index = expected_index.checked_add(1).ok_or("item id overflow")?;833		}834		let users = [(to.clone(), 1)]835			.into_iter()836			.collect::<BTreeMap<_, _>>()837			.try_into()838			.unwrap();839		let create_item_data = CreateItemData::<T::CrossAccountId> {840			users,841			properties: CollectionPropertiesVec::default(),842		};843		let data = (0..total_tokens)844			.map(|_| create_item_data.clone())845			.collect();846847		<Pallet<T>>::create_multiple_items(self, &caller, data, &budget)848			.map_err(dispatch_to_evm::<T>)?;849		Ok(true)850	}851852	/// @notice Function to mint multiple tokens with the given tokenUris.853	/// @dev `tokenIds` is array of pairs of token ID and token URI. Token IDs should be consecutive854	///  numbers and first number should be obtained with `nextTokenId` method855	/// @param to The new owner856	/// @param tokens array of pairs of token ID and token URI for minted tokens857	#[solidity(hide, rename_selector = "mintBulkWithTokenURI")]858	#[weight(<SelfWeightOf<T>>::create_multiple_items(tokens.len() as u32))]859	fn mint_bulk_with_token_uri(860		&mut self,861		caller: caller,862		to: address,863		tokens: Vec<(uint256, string)>,864	) -> Result<bool> {865		let key = key::url();866		let caller = T::CrossAccountId::from_eth(caller);867		let to = T::CrossAccountId::from_eth(to);868		let mut expected_index = <TokensMinted<T>>::get(self.id)869			.checked_add(1)870			.ok_or("item id overflow")?;871		let budget = self872			.recorder873			.weight_calls_budget(<StructureWeight<T>>::find_parent());874875		let mut data = Vec::with_capacity(tokens.len());876		let users: BoundedBTreeMap<_, _, _> = [(to.clone(), 1)]877			.into_iter()878			.collect::<BTreeMap<_, _>>()879			.try_into()880			.unwrap();881		for (id, token_uri) in tokens {882			let id: u32 = id.try_into().map_err(|_| "token id overflow")?;883			if id != expected_index {884				return Err("item id should be next".into());885			}886			expected_index = expected_index.checked_add(1).ok_or("item id overflow")?;887888			let mut properties = CollectionPropertiesVec::default();889			properties890				.try_push(Property {891					key: key.clone(),892					value: token_uri893						.into_bytes()894						.try_into()895						.map_err(|_| "token uri is too long")?,896				})897				.map_err(|e| Error::Revert(alloc::format!("Can't add property: {:?}", e)))?;898899			let create_item_data = CreateItemData::<T::CrossAccountId> {900				users: users.clone(),901				properties,902			};903			data.push(create_item_data);904		}905906		<Pallet<T>>::create_multiple_items(self, &caller, data, &budget)907			.map_err(dispatch_to_evm::<T>)?;908		Ok(true)909	}910911	/// Returns EVM address for refungible token912	///913	/// @param token ID of the token914	fn token_contract_address(&self, token: uint256) -> Result<address> {915		Ok(T::EvmTokenAddressMapping::token_to_address(916			self.id,917			token.try_into().map_err(|_| "token id overflow")?,918		))919	}920}921922#[solidity_interface(923	name = UniqueRefungible,924	is(925		ERC721,926		ERC721Enumerable,927		ERC721UniqueExtensions,928		ERC721UniqueMintable,929		ERC721Burnable,930		ERC721Metadata(if(this.flags.erc721metadata)),931		Collection(via(common_mut returns CollectionHandle<T>)),932		TokenProperties,933	)934)]935impl<T: Config> RefungibleHandle<T> where T::AccountId: From<[u8; 32]> + AsRef<[u8; 32]> {}936937// Not a tests, but code generators938generate_stubgen!(gen_impl, UniqueRefungibleCall<()>, true);939generate_stubgen!(gen_iface, UniqueRefungibleCall<()>, false);940941impl<T: Config> CommonEvmHandler for RefungibleHandle<T>942where943	T::AccountId: From<[u8; 32]> + AsRef<[u8; 32]>,944{945	const CODE: &'static [u8] = include_bytes!("./stubs/UniqueRefungible.raw");946	fn call(947		self,948		handle: &mut impl PrecompileHandle,949	) -> Option<pallet_common::erc::PrecompileResult> {950		call::<T, UniqueRefungibleCall<T>, _, _>(handle, self)951	}952}
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;