git.delta.rocks / unique-network / refs/commits / 905f9b3923e7

difftreelog

refactor fix complex value type support in evm-coder

Yaroslav Bolyukin2023-08-29parent: #1a4aa2d.patch.diff
in: master

14 files changed

modifiedCargo.lockdiffbeforeafterboth
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -2653,8 +2653,9 @@
 
 [[package]]
 name = "evm-coder"
-version = "0.3.6"
-source = "git+https://github.com/uniquenetwork/evm-coder?tag=v0.3.6#be59ae41a5d2ec9389bae22d54f81122b6ba55a4"
+version = "0.4.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b88ae5a449e7e9dfef59c0dd2df396bc56d81a6f4e297490c0c64aa73f7f7ad4"
 dependencies = [
  "ethereum",
  "evm-coder-procedural",
@@ -2665,8 +2666,9 @@
 
 [[package]]
 name = "evm-coder-procedural"
-version = "0.3.6"
-source = "git+https://github.com/uniquenetwork/evm-coder?tag=v0.3.6#be59ae41a5d2ec9389bae22d54f81122b6ba55a4"
+version = "0.4.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6223c1063c1f53380b4b9aaf2e4d82eba4808c661c61265619b804b09b7a6b1a"
 dependencies = [
  "Inflector",
  "hex",
modifiedCargo.tomldiffbeforeafterboth
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -27,7 +27,7 @@
 [workspace.dependencies]
 # Unique
 app-promotion-rpc = { path = "primitives/app_promotion_rpc", default-features = false }
-evm-coder = { git = "https://github.com/uniquenetwork/evm-coder", tag = "v0.3.6", default-features = false, features = [
+evm-coder = { version = "0.4.2", default-features = false, features = [
 	'bondrewd',
 ] }
 pallet-app-promotion = { path = "pallets/app-promotion", default-features = false }
modifiedpallets/common/Cargo.tomldiffbeforeafterboth
--- a/pallets/common/Cargo.toml
+++ b/pallets/common/Cargo.toml
@@ -35,7 +35,8 @@
 	"sp-std/std",
 	"up-data-structs/std",
 	"up-pov-estimate-rpc/std",
+	"evm-coder/std",
 ]
-stubgen = ["evm-coder/stubgen"]
+stubgen = ["evm-coder/stubgen", "up-data-structs/stubgen"]
 tests = []
 try-runtime = ["frame-support/try-runtime"]
modifiedpallets/common/src/eth.rsdiffbeforeafterboth
--- a/pallets/common/src/eth.rs
+++ b/pallets/common/src/eth.rs
@@ -549,8 +549,6 @@
 /// Collection properties
 #[derive(Debug, Default, AbiCoder)]
 pub struct CreateCollectionData {
-	/// Collection sponsor
-	pub pending_sponsor: CrossAddress,
 	/// Collection name
 	pub name: String,
 	/// Collection description
@@ -571,6 +569,8 @@
 	pub nesting_settings: CollectionNestingAndPermission,
 	/// Collection limits
 	pub limits: Vec<CollectionLimitValue>,
+	/// Collection sponsor
+	pub pending_sponsor: CrossAddress,
 	/// Extra collection flags
 	pub flags: CollectionFlags,
 }
modifiedpallets/evm-coder-substrate/src/lib.rsdiffbeforeafterboth
--- a/pallets/evm-coder-substrate/src/lib.rs
+++ b/pallets/evm-coder-substrate/src/lib.rs
@@ -26,7 +26,7 @@
 use frame_support::dispatch::Weight;
 
 use core::marker::PhantomData;
-use sp_std::cell::RefCell;
+use sp_std::{cell::RefCell, vec::Vec};
 
 use codec::Decode;
 use frame_support::pallet_prelude::DispatchError;
@@ -46,8 +46,8 @@
 pub use spez::spez;
 
 use evm_coder::{
-	abi::{AbiReader, AbiWrite, AbiWriter},
 	types::{Msg, Value},
+	AbiEncode,
 };
 
 pub use pallet::*;
@@ -168,7 +168,7 @@
 	pub fn evm_to_precompile_output(
 		self,
 		handle: &mut impl PrecompileHandle,
-		result: execution::Result<Option<AbiWriter>>,
+		result: execution::Result<Option<Vec<u8>>>,
 	) -> Option<PrecompileResult> {
 		use execution::Error;
 		// We ignore error here, as it should not occur, as we have our own bookkeeping of gas
@@ -176,18 +176,13 @@
 		Some(match result {
 			Ok(Some(v)) => Ok(PrecompileOutput {
 				exit_status: ExitSucceed::Returned,
-				output: v.finish(),
+				output: v,
 			}),
 			Ok(None) => return None,
-			Err(Error::Revert(e)) => {
-				let mut writer = AbiWriter::new_call(evm_coder::fn_selector!(Error(string)));
-				(&e as &str).abi_write(&mut writer);
-
-				Err(PrecompileFailure::Revert {
-					exit_status: ExitRevert::Reverted,
-					output: writer.finish(),
-				})
-			}
+			Err(Error::Revert(e)) => Err(PrecompileFailure::Revert {
+				exit_status: ExitRevert::Reverted,
+				output: (&e as &str,).abi_encode_call(evm_coder::fn_selector!(Error(string))),
+			}),
 			Err(Error::Fatal(f)) => Err(PrecompileFailure::Fatal { exit_status: f }),
 			Err(Error::Error(e)) => Err(e.into()),
 		})
@@ -266,7 +261,7 @@
 	C: evm_coder::Call + PreDispatch,
 	E: evm_coder::Callable<C> + WithRecorder<T>,
 	H: PrecompileHandle,
-	execution::ResultWithPostInfo<AbiWriter>: From<ResultWithPostInfoOf<E, AbiWriter>>,
+	execution::ResultWithPostInfo<Vec<u8>>: From<ResultWithPostInfoOf<E, Vec<u8>>>,
 {
 	let result = call_internal(
 		handle.context().caller,
@@ -282,18 +277,16 @@
 	e: &mut E,
 	value: Value,
 	input: &[u8],
-) -> execution::Result<Option<AbiWriter>>
+) -> execution::Result<Option<Vec<u8>>>
 where
 	T: Config,
 	C: evm_coder::Call + PreDispatch,
 	E: Contract + evm_coder::Callable<C> + WithRecorder<T>,
-	execution::ResultWithPostInfo<AbiWriter>: From<ResultWithPostInfoOf<E, AbiWriter>>,
+	execution::ResultWithPostInfo<Vec<u8>>: From<ResultWithPostInfoOf<E, Vec<u8>>>,
 {
-	let (selector, mut reader) = AbiReader::new_call(input)?;
-	let call = C::parse(selector, &mut reader)?;
+	let call = C::parse_full(input)?;
 	if call.is_none() {
-		let selector = u32::from_be_bytes(selector);
-		return Err(format!("unrecognized selector: 0x{selector:0<8x}").into());
+		return Err("unrecognized selector".into());
 	}
 	let call = call.unwrap();
 
modifiedpallets/evm-contract-helpers/src/eth.rsdiffbeforeafterboth
--- a/pallets/evm-contract-helpers/src/eth.rs
+++ b/pallets/evm-contract-helpers/src/eth.rs
@@ -19,7 +19,7 @@
 extern crate alloc;
 use core::marker::PhantomData;
 use evm_coder::{
-	abi::{AbiWriter, AbiType},
+	abi::{AbiType, AbiEncode},
 	generate_stubgen, solidity_interface,
 	types::*,
 	ToLog,
@@ -370,11 +370,8 @@
 		{
 			return Some(Err(PrecompileFailure::Revert {
 				exit_status: ExitRevert::Reverted,
-				output: {
-					let mut writer = AbiWriter::new_call(evm_coder::fn_selector!(Error(string)));
-					writer.string("Target contract is allowlisted");
-					writer.finish()
-				},
+				output: ("target contract is allowlisted",)
+					.abi_encode_call(evm_coder::fn_selector!(Error(string))),
 			}));
 		}
 
modifiedpallets/gov-origins/src/lib.rsdiffbeforeafterboth
--- a/pallets/gov-origins/src/lib.rs
+++ b/pallets/gov-origins/src/lib.rs
@@ -31,6 +31,7 @@
 
 	#[derive(PartialEq, Eq, Clone, MaxEncodedLen, Encode, Decode, TypeInfo, RuntimeDebug)]
 	#[pallet::origin]
+	#[non_exhaustive]
 	pub enum Origin {
 		/// Origin able to send proposal from fellowship collective to democracy pallet.
 		FellowshipProposition,
modifiedpallets/unique/src/eth/mod.rsdiffbeforeafterboth
before · pallets/unique/src/eth/mod.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//! Implementation of CollectionHelpers contract.18//!19use core::marker::PhantomData;20use ethereum as _;21use evm_coder::{abi::AbiType, generate_stubgen, solidity_interface, types::*};22use frame_support::{BoundedVec, traits::Get};23use pallet_common::{24	CollectionById,25	dispatch::CollectionDispatch,26	erc::{CollectionHelpersEvents, static_property::key},27	eth::{self, map_eth_to_id, collection_id_to_address},28	Pallet as PalletCommon, CollectionHandle,29};30use pallet_evm::{account::CrossAccountId, OnMethodCall, PrecompileHandle, PrecompileResult};31use pallet_evm_coder_substrate::{32	dispatch_to_evm, SubstrateRecorder, WithRecorder,33	execution::{PreDispatch, Result, Error},34	frontier_contract,35};36use up_data_structs::{37	CollectionDescription, CollectionMode, CollectionName, CollectionPermissions,38	CollectionTokenPrefix, CreateCollectionData, NestingPermissions,39};4041use crate::{weights::WeightInfo, Config, Pallet, SelfWeightOf};4243use alloc::{format, collections::BTreeSet};44use sp_std::vec::Vec;4546frontier_contract! {47	macro_rules! EvmCollectionHelpers_result {...}48	impl<T: Config> Contract for EvmCollectionHelpers<T> {...}49}50/// See [`CollectionHelpersCall`]51pub struct EvmCollectionHelpers<T: Config>(SubstrateRecorder<T>);52impl<T: Config> WithRecorder<T> for EvmCollectionHelpers<T> {53	fn recorder(&self) -> &SubstrateRecorder<T> {54		&self.055	}5657	fn into_recorder(self) -> SubstrateRecorder<T> {58		self.059	}60}6162fn convert_data<T: Config>(63	caller: Caller,64	name: String,65	description: String,66	token_prefix: String,67) -> Result<(68	T::CrossAccountId,69	CollectionName,70	CollectionDescription,71	CollectionTokenPrefix,72)> {73	let caller = T::CrossAccountId::from_eth(caller);74	let name = name75		.encode_utf16()76		.collect::<Vec<u16>>()77		.try_into()78		.map_err(|_| error_field_too_long(stringify!(name), CollectionName::bound()))?;79	let description = description80		.encode_utf16()81		.collect::<Vec<u16>>()82		.try_into()83		.map_err(|_| {84			error_field_too_long(stringify!(description), CollectionDescription::bound())85		})?;86	let token_prefix = token_prefix.into_bytes().try_into().map_err(|_| {87		error_field_too_long(stringify!(token_prefix), CollectionTokenPrefix::bound())88	})?;89	Ok((caller, name, description, token_prefix))90}9192#[inline(always)]93fn create_collection_internal<T: Config>(94	caller: Caller,95	value: Value,96	name: String,97	collection_mode: CollectionMode,98	description: String,99	token_prefix: String,100) -> Result<Address> {101	let (caller, name, description, token_prefix) =102		convert_data::<T>(caller, name, description, token_prefix)?;103	let data = CreateCollectionData {104		name,105		mode: collection_mode,106		description,107		token_prefix,108		..Default::default()109	};110	check_sent_amount_equals_collection_creation_price::<T>(value)?;111	let collection_helpers_address =112		T::CrossAccountId::from_eth(<T as pallet_common::Config>::ContractAddress::get());113114	let collection_id = T::CollectionDispatch::create(caller, collection_helpers_address, data)115		.map_err(pallet_evm_coder_substrate::dispatch_to_evm::<T>)?;116	let address = pallet_common::eth::collection_id_to_address(collection_id);117	Ok(address)118}119120fn check_sent_amount_equals_collection_creation_price<T: Config>(value: Value) -> Result<()> {121	let value = value.as_u128();122	let creation_price: u128 = T::CollectionCreationPrice::get()123		.try_into()124		.map_err(|_| ()) // workaround for `expect` requiring `Debug` trait125		.expect("Collection creation price should be convertible to u128");126	if value != creation_price {127		return Err(format!(128			"Sent amount not equals to collection creation price ({creation_price})",129		)130		.into());131	}132	Ok(())133}134135/// @title Contract, which allows users to operate with collections136#[solidity_interface(name = CollectionHelpers, events(CollectionHelpersEvents), enum(derive(PreDispatch)), enum_attr(weight))]137impl<T> EvmCollectionHelpers<T>138where139	T: Config + pallet_common::Config + pallet_nonfungible::Config + pallet_refungible::Config,140	T::AccountId: From<[u8; 32]>,141{142	/*143		/// Create a collection144		/// @return address Address of the newly created collection145		#[weight(<SelfWeightOf<T>>::create_collection())]146		#[solidity(rename_selector = "createCollection")]147		fn create_collection(148			&mut self,149			caller: Caller,150			value: Value,151			data: eth::CreateCollectionData,152		) -> Result<Address> {153			let (caller, name, description, token_prefix) =154				convert_data::<T>(caller, data.name, data.description, data.token_prefix)?;155			if data.mode != eth::CollectionMode::Fungible && data.decimals != 0 {156				return Err("decimals are only supported for NFT and RFT collections".into());157			}158			let mode = match data.mode {159				eth::CollectionMode::Fungible => CollectionMode::Fungible(data.decimals),160				eth::CollectionMode::Nonfungible => CollectionMode::NFT,161				eth::CollectionMode::Refungible => CollectionMode::ReFungible,162			};163164			let properties: BoundedVec<_, _> = data165				.properties166				.into_iter()167				.map(eth::Property::try_into)168				.collect::<Result<Vec<_>>>()?169				.try_into()170				.map_err(|_| "too many properties")?;171172			let token_property_permissions =173				eth::TokenPropertyPermission::into_property_key_permissions(174					data.token_property_permissions,175				)?176				.try_into()177				.map_err(|_| "too many property permissions")?;178179			let limits = if !data.limits.is_empty() {180				Some(181					data.limits182						.into_iter()183						.collect::<Result<up_data_structs::CollectionLimits>>()?,184				)185			} else {186				None187			};188189			let pending_sponsor = data.pending_sponsor.into_option_sub_cross_account::<T>()?;190191			let restricted = if !data.nesting_settings.restricted.is_empty() {192				Some(193					data.nesting_settings194						.restricted195						.iter()196						.map(map_eth_to_id)197						.collect::<Option<BTreeSet<_>>>()198						.ok_or("can't convert address into collection id")?199						.try_into()200						.map_err(|_| "too many collections")?,201				)202			} else {203				None204			};205206			let admin_list = data207				.admin_list208				.into_iter()209				.map(|admin| admin.into_sub_cross_account::<T>())210				.collect::<Result<Vec<_>>>()?;211212			let flags = data.flags;213			if !flags.is_allowed_for_user() {214				return Err("internal flags were used".into());215			}216217			let data = CreateCollectionData {218				name,219				mode,220				description,221				token_prefix,222				properties,223				token_property_permissions,224				limits,225				pending_sponsor,226				access: None,227				permissions: Some(CollectionPermissions {228					access: None,229					mint_mode: None,230					nesting: Some(NestingPermissions {231						token_owner: data.nesting_settings.token_owner,232						collection_admin: data.nesting_settings.collection_admin,233						restricted,234						#[cfg(feature = "runtime-benchmarks")]235						permissive: true,236					}),237				}),238				admin_list,239				flags,240			};241			check_sent_amount_equals_collection_creation_price::<T>(value)?;242			let collection_helpers_address =243				T::CrossAccountId::from_eth(<T as pallet_common::Config>::ContractAddress::get());244245			let collection_id = T::CollectionDispatch::create(caller, collection_helpers_address, data)246				.map_err(dispatch_to_evm::<T>)?;247248			let address = pallet_common::eth::collection_id_to_address(collection_id);249			Ok(address)250		}251	*/252253	/// Create an NFT collection254	/// @param name Name of the collection255	/// @param description Informative description of the collection256	/// @param tokenPrefix Token prefix to represent the collection tokens in UI and user applications257	/// @return address Address of the newly created collection258	#[weight(<SelfWeightOf<T>>::create_collection())]259	#[solidity(rename_selector = "createNFTCollection")]260	fn create_nft_collection(261		&mut self,262		caller: Caller,263		value: Value,264		name: String,265		description: String,266		token_prefix: String,267	) -> Result<Address> {268		let (caller, name, description, token_prefix) =269			convert_data::<T>(caller, name, description, token_prefix)?;270		let data = CreateCollectionData {271			name,272			mode: CollectionMode::NFT,273			description,274			token_prefix,275			..Default::default()276		};277		check_sent_amount_equals_collection_creation_price::<T>(value)?;278		let collection_helpers_address =279			T::CrossAccountId::from_eth(<T as pallet_common::Config>::ContractAddress::get());280		let collection_id = T::CollectionDispatch::create(caller, collection_helpers_address, data)281			.map_err(dispatch_to_evm::<T>)?;282283		let address = pallet_common::eth::collection_id_to_address(collection_id);284		Ok(address)285	}286	/// Create an NFT collection287	/// @param name Name of the collection288	/// @param description Informative description of the collection289	/// @param tokenPrefix Token prefix to represent the collection tokens in UI and user applications290	/// @return address Address of the newly created collection291	#[deprecated(note = "mathod was renamed to `create_nft_collection`, prefer it instead")]292	#[solidity(hide)]293	#[weight(<SelfWeightOf<T>>::create_collection())]294	fn create_nonfungible_collection(295		&mut self,296		caller: Caller,297		value: Value,298		name: String,299		description: String,300		token_prefix: String,301	) -> Result<Address> {302		create_collection_internal::<T>(303			caller,304			value,305			name,306			CollectionMode::NFT,307			description,308			token_prefix,309		)310	}311312	#[weight(<SelfWeightOf<T>>::create_collection())]313	#[solidity(rename_selector = "createRFTCollection")]314	fn create_rft_collection(315		&mut self,316		caller: Caller,317		value: Value,318		name: String,319		description: String,320		token_prefix: String,321	) -> Result<Address> {322		create_collection_internal::<T>(323			caller,324			value,325			name,326			CollectionMode::ReFungible,327			description,328			token_prefix,329		)330	}331332	#[weight(<SelfWeightOf<T>>::create_collection())]333	#[solidity(rename_selector = "createFTCollection")]334	fn create_fungible_collection(335		&mut self,336		caller: Caller,337		value: Value,338		name: String,339		decimals: u8,340		description: String,341		token_prefix: String,342	) -> Result<Address> {343		create_collection_internal::<T>(344			caller,345			value,346			name,347			CollectionMode::Fungible(decimals),348			description,349			token_prefix,350		)351	}352353	#[solidity(rename_selector = "makeCollectionERC721MetadataCompatible")]354	fn make_collection_metadata_compatible(355		&mut self,356		caller: Caller,357		collection: Address,358		base_uri: String,359	) -> Result<()> {360		let caller = T::CrossAccountId::from_eth(caller);361		let collection =362			pallet_common::eth::map_eth_to_id(&collection).ok_or("not a collection address")?;363		let mut collection =364			<CollectionHandle<T>>::new(collection).ok_or("collection not found")?;365366		if !matches!(367			collection.mode,368			CollectionMode::NFT | CollectionMode::ReFungible369		) {370			return Err("target collection should be either NFT or Refungible".into());371		}372373		self.recorder().consume_sstore()?;374		collection375			.check_is_owner_or_admin(&caller)376			.map_err(dispatch_to_evm::<T>)?;377378		if collection.flags.erc721metadata {379			return Err("target collection is already Erc721Metadata compatible".into());380		}381		collection.flags.erc721metadata = true;382383		let all_permissions = <pallet_common::CollectionPropertyPermissions<T>>::get(collection.id);384		if all_permissions.get(&key::url()).is_none() {385			self.recorder().consume_sstore()?;386			<PalletCommon<T>>::set_property_permission(387				&collection,388				&caller,389				up_data_structs::PropertyKeyPermission {390					key: key::url(),391					permission: up_data_structs::PropertyPermission {392						mutable: true,393						collection_admin: true,394						token_owner: false,395					},396				},397			)398			.map_err(dispatch_to_evm::<T>)?;399		}400		if all_permissions.get(&key::suffix()).is_none() {401			self.recorder().consume_sstore()?;402			<PalletCommon<T>>::set_property_permission(403				&collection,404				&caller,405				up_data_structs::PropertyKeyPermission {406					key: key::suffix(),407					permission: up_data_structs::PropertyPermission {408						mutable: true,409						collection_admin: true,410						token_owner: false,411					},412				},413			)414			.map_err(dispatch_to_evm::<T>)?;415		}416417		let all_properties = <pallet_common::CollectionProperties<T>>::get(collection.id);418		if all_properties.get(&key::base_uri()).is_none() && !base_uri.is_empty() {419			self.recorder().consume_sstore()?;420			<PalletCommon<T>>::set_collection_properties(421				&collection,422				&caller,423				[up_data_structs::Property {424					key: key::base_uri(),425					value: base_uri426						.into_bytes()427						.try_into()428						.map_err(|_| "base uri is too large")?,429				}]430				.into_iter(),431			)432			.map_err(dispatch_to_evm::<T>)?;433		}434435		self.recorder().consume_sstore()?;436		collection.save().map_err(dispatch_to_evm::<T>)?;437438		Ok(())439	}440441	#[weight(<SelfWeightOf<T>>::destroy_collection())]442	fn destroy_collection(&mut self, caller: Caller, collection_address: Address) -> Result<()> {443		let caller = T::CrossAccountId::from_eth(caller);444445		let collection_id = pallet_common::eth::map_eth_to_id(&collection_address)446			.ok_or("Invalid collection address format")?;447		<Pallet<T>>::destroy_collection_internal(caller, collection_id)448			.map_err(pallet_evm_coder_substrate::dispatch_to_evm::<T>)449	}450451	/// Check if a collection exists452	/// @param collectionAddress Address of the collection in question453	/// @return bool Does the collection exist?454	fn is_collection_exist(&self, _caller: Caller, collection_address: Address) -> Result<bool> {455		if let Some(id) = pallet_common::eth::map_eth_to_id(&collection_address) {456			let collection_id = id;457			return Ok(<CollectionById<T>>::contains_key(collection_id));458		}459460		Ok(false)461	}462463	fn collection_creation_fee(&self) -> Result<Value> {464		let price: u128 = T::CollectionCreationPrice::get()465			.try_into()466			.map_err(|_| ()) // workaround for `expect` requiring `Debug` trait467			.expect("Collection creation price should be convertible to u128");468		Ok(price.into())469	}470471	/// Returns address of a collection.472	/// @param collectionId  - CollectionId  of the collection473	/// @return eth mirror address of the collection474	fn collection_address(&self, collection_id: u32) -> Result<Address> {475		Ok(collection_id_to_address(collection_id.into()))476	}477478	/// Returns collectionId of a collection.479	/// @param collectionAddress  - Eth address of the collection480	/// @return collectionId of the collection481	fn collection_id(&self, collection_address: Address) -> Result<u32> {482		map_eth_to_id(&collection_address)483			.map(|id| id.0)484			.ok_or(Error::Revert(format!(485				"failed to convert address {collection_address} into collectionId."486			)))487	}488}489490/// Implements [`OnMethodCall`], which delegates call to [`EvmCollectionHelpers`]491pub struct CollectionHelpersOnMethodCall<T: Config>(PhantomData<*const T>);492impl<T: Config + pallet_nonfungible::Config + pallet_refungible::Config> OnMethodCall<T>493	for CollectionHelpersOnMethodCall<T>494where495	T::AccountId: From<[u8; 32]>,496{497	fn is_reserved(contract: &sp_core::H160) -> bool {498		contract == &T::ContractAddress::get()499	}500501	fn is_used(contract: &sp_core::H160) -> bool {502		contract == &T::ContractAddress::get()503	}504505	fn call(handle: &mut impl PrecompileHandle) -> Option<PrecompileResult> {506		if handle.code_address() != T::ContractAddress::get() {507			return None;508		}509510		let helpers =511			EvmCollectionHelpers::<T>(SubstrateRecorder::<T>::new(handle.remaining_gas()));512		pallet_evm_coder_substrate::call(handle, helpers)513	}514515	fn get_code(contract: &sp_core::H160) -> Option<Vec<u8>> {516		(contract == &T::ContractAddress::get())517			.then(|| include_bytes!("./stubs/CollectionHelpers.raw").to_vec())518	}519}520521generate_stubgen!(collection_helper_impl, CollectionHelpersCall<()>, true);522generate_stubgen!(collection_helper_iface, CollectionHelpersCall<()>, false);523524fn error_field_too_long(feild: &str, bound: usize) -> Error {525	Error::Revert(format!("{feild} is too long. Max length is {bound}."))526}
after · pallets/unique/src/eth/mod.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//! Implementation of CollectionHelpers contract.18//!19use core::marker::PhantomData;20use ethereum as _;21use evm_coder::{abi::AbiType, generate_stubgen, solidity_interface, types::*};22use frame_support::{BoundedVec, traits::Get};23use pallet_common::{24	CollectionById,25	dispatch::CollectionDispatch,26	erc::{CollectionHelpersEvents, static_property::key},27	eth::{self, map_eth_to_id, collection_id_to_address},28	Pallet as PalletCommon, CollectionHandle,29};30use pallet_evm::{account::CrossAccountId, OnMethodCall, PrecompileHandle, PrecompileResult};31use pallet_evm_coder_substrate::{32	dispatch_to_evm, SubstrateRecorder, WithRecorder,33	execution::{PreDispatch, Result, Error},34	frontier_contract,35};36use up_data_structs::{37	CollectionDescription, CollectionMode, CollectionName, CollectionPermissions,38	CollectionTokenPrefix, CreateCollectionData, NestingPermissions,39};4041use crate::{weights::WeightInfo, Config, Pallet, SelfWeightOf};4243use alloc::{format, collections::BTreeSet};44use sp_std::vec::Vec;4546frontier_contract! {47	macro_rules! EvmCollectionHelpers_result {...}48	impl<T: Config> Contract for EvmCollectionHelpers<T> {...}49}50/// See [`CollectionHelpersCall`]51pub struct EvmCollectionHelpers<T: Config>(SubstrateRecorder<T>);52impl<T: Config> WithRecorder<T> for EvmCollectionHelpers<T> {53	fn recorder(&self) -> &SubstrateRecorder<T> {54		&self.055	}5657	fn into_recorder(self) -> SubstrateRecorder<T> {58		self.059	}60}6162fn convert_data<T: Config>(63	caller: Caller,64	name: String,65	description: String,66	token_prefix: String,67) -> Result<(68	T::CrossAccountId,69	CollectionName,70	CollectionDescription,71	CollectionTokenPrefix,72)> {73	let caller = T::CrossAccountId::from_eth(caller);74	let name = name75		.encode_utf16()76		.collect::<Vec<u16>>()77		.try_into()78		.map_err(|_| error_field_too_long(stringify!(name), CollectionName::bound()))?;79	let description = description80		.encode_utf16()81		.collect::<Vec<u16>>()82		.try_into()83		.map_err(|_| {84			error_field_too_long(stringify!(description), CollectionDescription::bound())85		})?;86	let token_prefix = token_prefix.into_bytes().try_into().map_err(|_| {87		error_field_too_long(stringify!(token_prefix), CollectionTokenPrefix::bound())88	})?;89	Ok((caller, name, description, token_prefix))90}9192#[inline(always)]93fn create_collection_internal<T: Config>(94	caller: Caller,95	value: Value,96	name: String,97	collection_mode: CollectionMode,98	description: String,99	token_prefix: String,100) -> Result<Address> {101	let (caller, name, description, token_prefix) =102		convert_data::<T>(caller, name, description, token_prefix)?;103	let data = CreateCollectionData {104		name,105		mode: collection_mode,106		description,107		token_prefix,108		..Default::default()109	};110	check_sent_amount_equals_collection_creation_price::<T>(value)?;111	let collection_helpers_address =112		T::CrossAccountId::from_eth(<T as pallet_common::Config>::ContractAddress::get());113114	let collection_id = T::CollectionDispatch::create(caller, collection_helpers_address, data)115		.map_err(pallet_evm_coder_substrate::dispatch_to_evm::<T>)?;116	let address = pallet_common::eth::collection_id_to_address(collection_id);117	Ok(address)118}119120fn check_sent_amount_equals_collection_creation_price<T: Config>(value: Value) -> Result<()> {121	let value = value.as_u128();122	let creation_price: u128 = T::CollectionCreationPrice::get()123		.try_into()124		.map_err(|_| ()) // workaround for `expect` requiring `Debug` trait125		.expect("Collection creation price should be convertible to u128");126	if value != creation_price {127		return Err(format!(128			"Sent amount not equals to collection creation price ({creation_price})",129		)130		.into());131	}132	Ok(())133}134135/// @title Contract, which allows users to operate with collections136#[solidity_interface(name = CollectionHelpers, events(CollectionHelpersEvents), enum(derive(PreDispatch)), enum_attr(weight))]137impl<T> EvmCollectionHelpers<T>138where139	T: Config + pallet_common::Config + pallet_nonfungible::Config + pallet_refungible::Config,140	T::AccountId: From<[u8; 32]>,141{142	/// Create a collection143	/// @return address Address of the newly created collection144	#[weight(<SelfWeightOf<T>>::create_collection())]145	#[solidity(rename_selector = "createCollection")]146	fn create_collection(147		&mut self,148		caller: Caller,149		value: Value,150		data: eth::CreateCollectionData,151	) -> Result<Address> {152		let (caller, name, description, token_prefix) =153			convert_data::<T>(caller, data.name, data.description, data.token_prefix)?;154		if data.mode != eth::CollectionMode::Fungible && data.decimals != 0 {155			return Err("decimals are only supported for NFT and RFT collections".into());156		}157		let mode = match data.mode {158			eth::CollectionMode::Fungible => CollectionMode::Fungible(data.decimals),159			eth::CollectionMode::Nonfungible => CollectionMode::NFT,160			eth::CollectionMode::Refungible => CollectionMode::ReFungible,161		};162163		let properties: BoundedVec<_, _> = data164			.properties165			.into_iter()166			.map(eth::Property::try_into)167			.collect::<Result<Vec<_>>>()?168			.try_into()169			.map_err(|_| "too many properties")?;170171		let token_property_permissions =172			eth::TokenPropertyPermission::into_property_key_permissions(173				data.token_property_permissions,174			)?175			.try_into()176			.map_err(|_| "too many property permissions")?;177178		let limits = if !data.limits.is_empty() {179			Some(180				data.limits181					.into_iter()182					.collect::<Result<up_data_structs::CollectionLimits>>()?,183			)184		} else {185			None186		};187188		let pending_sponsor = data.pending_sponsor.into_option_sub_cross_account::<T>()?;189190		let restricted = if !data.nesting_settings.restricted.is_empty() {191			Some(192				data.nesting_settings193					.restricted194					.iter()195					.map(map_eth_to_id)196					.collect::<Option<BTreeSet<_>>>()197					.ok_or("can't convert address into collection id")?198					.try_into()199					.map_err(|_| "too many collections")?,200			)201		} else {202			None203		};204205		let admin_list = data206			.admin_list207			.into_iter()208			.map(|admin| admin.into_sub_cross_account::<T>())209			.collect::<Result<Vec<_>>>()?;210211		let flags = data.flags;212		if !flags.is_allowed_for_user() {213			return Err("internal flags were used".into());214		}215216		let data = CreateCollectionData {217			name,218			mode,219			description,220			token_prefix,221			properties,222			token_property_permissions,223			limits,224			pending_sponsor,225			access: None,226			permissions: Some(CollectionPermissions {227				access: None,228				mint_mode: None,229				nesting: Some(NestingPermissions {230					token_owner: data.nesting_settings.token_owner,231					collection_admin: data.nesting_settings.collection_admin,232					restricted,233					#[cfg(feature = "runtime-benchmarks")]234					permissive: true,235				}),236			}),237			admin_list,238			flags,239		};240		check_sent_amount_equals_collection_creation_price::<T>(value)?;241		let collection_helpers_address =242			T::CrossAccountId::from_eth(<T as pallet_common::Config>::ContractAddress::get());243244		let collection_id = T::CollectionDispatch::create(caller, collection_helpers_address, data)245			.map_err(dispatch_to_evm::<T>)?;246247		let address = pallet_common::eth::collection_id_to_address(collection_id);248		Ok(address)249	}250251	/// Create an NFT collection252	/// @param name Name of the collection253	/// @param description Informative description of the collection254	/// @param tokenPrefix Token prefix to represent the collection tokens in UI and user applications255	/// @return address Address of the newly created collection256	#[weight(<SelfWeightOf<T>>::create_collection())]257	#[solidity(rename_selector = "createNFTCollection")]258	fn create_nft_collection(259		&mut self,260		caller: Caller,261		value: Value,262		name: String,263		description: String,264		token_prefix: String,265	) -> Result<Address> {266		let (caller, name, description, token_prefix) =267			convert_data::<T>(caller, name, description, token_prefix)?;268		let data = CreateCollectionData {269			name,270			mode: CollectionMode::NFT,271			description,272			token_prefix,273			..Default::default()274		};275		check_sent_amount_equals_collection_creation_price::<T>(value)?;276		let collection_helpers_address =277			T::CrossAccountId::from_eth(<T as pallet_common::Config>::ContractAddress::get());278		let collection_id = T::CollectionDispatch::create(caller, collection_helpers_address, data)279			.map_err(dispatch_to_evm::<T>)?;280281		let address = pallet_common::eth::collection_id_to_address(collection_id);282		Ok(address)283	}284	/// Create an NFT collection285	/// @param name Name of the collection286	/// @param description Informative description of the collection287	/// @param tokenPrefix Token prefix to represent the collection tokens in UI and user applications288	/// @return address Address of the newly created collection289	#[deprecated(note = "mathod was renamed to `create_nft_collection`, prefer it instead")]290	#[solidity(hide)]291	#[weight(<SelfWeightOf<T>>::create_collection())]292	fn create_nonfungible_collection(293		&mut self,294		caller: Caller,295		value: Value,296		name: String,297		description: String,298		token_prefix: String,299	) -> Result<Address> {300		create_collection_internal::<T>(301			caller,302			value,303			name,304			CollectionMode::NFT,305			description,306			token_prefix,307		)308	}309310	#[weight(<SelfWeightOf<T>>::create_collection())]311	#[solidity(rename_selector = "createRFTCollection")]312	fn create_rft_collection(313		&mut self,314		caller: Caller,315		value: Value,316		name: String,317		description: String,318		token_prefix: String,319	) -> Result<Address> {320		create_collection_internal::<T>(321			caller,322			value,323			name,324			CollectionMode::ReFungible,325			description,326			token_prefix,327		)328	}329330	#[weight(<SelfWeightOf<T>>::create_collection())]331	#[solidity(rename_selector = "createFTCollection")]332	fn create_fungible_collection(333		&mut self,334		caller: Caller,335		value: Value,336		name: String,337		decimals: u8,338		description: String,339		token_prefix: String,340	) -> Result<Address> {341		create_collection_internal::<T>(342			caller,343			value,344			name,345			CollectionMode::Fungible(decimals),346			description,347			token_prefix,348		)349	}350351	#[solidity(rename_selector = "makeCollectionERC721MetadataCompatible")]352	fn make_collection_metadata_compatible(353		&mut self,354		caller: Caller,355		collection: Address,356		base_uri: String,357	) -> Result<()> {358		let caller = T::CrossAccountId::from_eth(caller);359		let collection =360			pallet_common::eth::map_eth_to_id(&collection).ok_or("not a collection address")?;361		let mut collection =362			<CollectionHandle<T>>::new(collection).ok_or("collection not found")?;363364		if !matches!(365			collection.mode,366			CollectionMode::NFT | CollectionMode::ReFungible367		) {368			return Err("target collection should be either NFT or Refungible".into());369		}370371		self.recorder().consume_sstore()?;372		collection373			.check_is_owner_or_admin(&caller)374			.map_err(dispatch_to_evm::<T>)?;375376		if collection.flags.erc721metadata {377			return Err("target collection is already Erc721Metadata compatible".into());378		}379		collection.flags.erc721metadata = true;380381		let all_permissions = <pallet_common::CollectionPropertyPermissions<T>>::get(collection.id);382		if all_permissions.get(&key::url()).is_none() {383			self.recorder().consume_sstore()?;384			<PalletCommon<T>>::set_property_permission(385				&collection,386				&caller,387				up_data_structs::PropertyKeyPermission {388					key: key::url(),389					permission: up_data_structs::PropertyPermission {390						mutable: true,391						collection_admin: true,392						token_owner: false,393					},394				},395			)396			.map_err(dispatch_to_evm::<T>)?;397		}398		if all_permissions.get(&key::suffix()).is_none() {399			self.recorder().consume_sstore()?;400			<PalletCommon<T>>::set_property_permission(401				&collection,402				&caller,403				up_data_structs::PropertyKeyPermission {404					key: key::suffix(),405					permission: up_data_structs::PropertyPermission {406						mutable: true,407						collection_admin: true,408						token_owner: false,409					},410				},411			)412			.map_err(dispatch_to_evm::<T>)?;413		}414415		let all_properties = <pallet_common::CollectionProperties<T>>::get(collection.id);416		if all_properties.get(&key::base_uri()).is_none() && !base_uri.is_empty() {417			self.recorder().consume_sstore()?;418			<PalletCommon<T>>::set_collection_properties(419				&collection,420				&caller,421				[up_data_structs::Property {422					key: key::base_uri(),423					value: base_uri424						.into_bytes()425						.try_into()426						.map_err(|_| "base uri is too large")?,427				}]428				.into_iter(),429			)430			.map_err(dispatch_to_evm::<T>)?;431		}432433		self.recorder().consume_sstore()?;434		collection.save().map_err(dispatch_to_evm::<T>)?;435436		Ok(())437	}438439	#[weight(<SelfWeightOf<T>>::destroy_collection())]440	fn destroy_collection(&mut self, caller: Caller, collection_address: Address) -> Result<()> {441		let caller = T::CrossAccountId::from_eth(caller);442443		let collection_id = pallet_common::eth::map_eth_to_id(&collection_address)444			.ok_or("Invalid collection address format")?;445		<Pallet<T>>::destroy_collection_internal(caller, collection_id)446			.map_err(pallet_evm_coder_substrate::dispatch_to_evm::<T>)447	}448449	/// Check if a collection exists450	/// @param collectionAddress Address of the collection in question451	/// @return bool Does the collection exist?452	fn is_collection_exist(&self, _caller: Caller, collection_address: Address) -> Result<bool> {453		if let Some(id) = pallet_common::eth::map_eth_to_id(&collection_address) {454			let collection_id = id;455			return Ok(<CollectionById<T>>::contains_key(collection_id));456		}457458		Ok(false)459	}460461	fn collection_creation_fee(&self) -> Result<Value> {462		let price: u128 = T::CollectionCreationPrice::get()463			.try_into()464			.map_err(|_| ()) // workaround for `expect` requiring `Debug` trait465			.expect("Collection creation price should be convertible to u128");466		Ok(price.into())467	}468469	/// Returns address of a collection.470	/// @param collectionId  - CollectionId  of the collection471	/// @return eth mirror address of the collection472	fn collection_address(&self, collection_id: u32) -> Result<Address> {473		Ok(collection_id_to_address(collection_id.into()))474	}475476	/// Returns collectionId of a collection.477	/// @param collectionAddress  - Eth address of the collection478	/// @return collectionId of the collection479	fn collection_id(&self, collection_address: Address) -> Result<u32> {480		map_eth_to_id(&collection_address)481			.map(|id| id.0)482			.ok_or(Error::Revert(format!(483				"failed to convert address {collection_address} into collectionId."484			)))485	}486}487488/// Implements [`OnMethodCall`], which delegates call to [`EvmCollectionHelpers`]489pub struct CollectionHelpersOnMethodCall<T: Config>(PhantomData<*const T>);490impl<T: Config + pallet_nonfungible::Config + pallet_refungible::Config> OnMethodCall<T>491	for CollectionHelpersOnMethodCall<T>492where493	T::AccountId: From<[u8; 32]>,494{495	fn is_reserved(contract: &sp_core::H160) -> bool {496		contract == &T::ContractAddress::get()497	}498499	fn is_used(contract: &sp_core::H160) -> bool {500		contract == &T::ContractAddress::get()501	}502503	fn call(handle: &mut impl PrecompileHandle) -> Option<PrecompileResult> {504		if handle.code_address() != T::ContractAddress::get() {505			return None;506		}507508		let helpers =509			EvmCollectionHelpers::<T>(SubstrateRecorder::<T>::new(handle.remaining_gas()));510		pallet_evm_coder_substrate::call(handle, helpers)511	}512513	fn get_code(contract: &sp_core::H160) -> Option<Vec<u8>> {514		(contract == &T::ContractAddress::get())515			.then(|| include_bytes!("./stubs/CollectionHelpers.raw").to_vec())516	}517}518519generate_stubgen!(collection_helper_impl, CollectionHelpersCall<()>, true);520generate_stubgen!(collection_helper_iface, CollectionHelpersCall<()>, false);521522fn error_field_too_long(feild: &str, bound: usize) -> Error {523	Error::Revert(format!("{feild} is too long. Max length is {bound}."))524}
modifiedprimitives/data-structs/Cargo.tomldiffbeforeafterboth
--- a/primitives/data-structs/Cargo.toml
+++ b/primitives/data-structs/Cargo.toml
@@ -39,3 +39,4 @@
 	"sp-runtime/std",
 	"sp-std/std",
 ]
+stubgen = ["evm-coder/stubgen"]
modifiedruntime/common/config/pallets/mod.rsdiffbeforeafterboth
--- a/runtime/common/config/pallets/mod.rs
+++ b/runtime/common/config/pallets/mod.rs
@@ -24,7 +24,7 @@
 		weights::CommonWeights,
 		RelayChainBlockNumberProvider,
 	},
-	Runtime, RuntimeEvent, RuntimeCall, RuntimeOrigin, RUNTIME_NAME, TOKEN_SYMBOL, DECIMALS,
+	Runtime, RuntimeEvent, RuntimeCall, RUNTIME_NAME, TOKEN_SYMBOL, DECIMALS,
 	Balances,
 };
 use frame_support::traits::{ConstU32, ConstU64, Currency};
modifiedruntime/common/ethereum/sponsoring.rsdiffbeforeafterboth
--- a/runtime/common/ethereum/sponsoring.rs
+++ b/runtime/common/ethereum/sponsoring.rs
@@ -17,7 +17,7 @@
 //! Implements EVM sponsoring logic via TransactionValidityHack
 
 use core::{convert::TryInto, marker::PhantomData};
-use evm_coder::{Call, abi::AbiReader};
+use evm_coder::{Call};
 use pallet_common::{CollectionHandle, eth::map_eth_to_id};
 use pallet_evm::account::CrossAccountId;
 use pallet_evm_transaction_payment::CallContext;
@@ -66,11 +66,11 @@
 		if let Some(collection_id) = map_eth_to_id(&call_context.contract_address) {
 			let collection = <CollectionHandle<T>>::new(collection_id)?;
 			let sponsor = collection.sponsorship.sponsor()?.clone();
-			let (method_id, mut reader) = AbiReader::new_call(&call_context.input).ok()?;
+			// let (method_id, mut reader) = AbiReader::new_call(&call_context.input).ok()?;
 			Some(T::CrossAccountId::from_sub(match &collection.mode {
 				CollectionMode::NFT => {
 					let collection = NonfungibleHandle::cast(collection);
-					let call = <UniqueNFTCall<T>>::parse(method_id, &mut reader).ok()??;
+					let call = <UniqueNFTCall<T>>::parse_full(&call_context.input).ok()??;
 					match call {
 						UniqueNFTCall::TokenProperties(call) => match call {
 							TokenPropertiesCall::SetProperty {
@@ -161,11 +161,11 @@
 					}
 				}
 				CollectionMode::ReFungible => {
-					let call = <UniqueRefungibleCall<T>>::parse(method_id, &mut reader).ok()??;
+					let call = <UniqueRefungibleCall<T>>::parse_full(&call_context.input).ok()??;
 					refungible::call_sponsor(call, collection, who).map(|()| sponsor)
 				}
 				CollectionMode::Fungible(_) => {
-					let call = <UniqueFungibleCall<T>>::parse(method_id, &mut reader).ok()??;
+					let call = <UniqueFungibleCall<T>>::parse_full(&call_context.input).ok()??;
 					match call {
 						UniqueFungibleCall::ERC20(ERC20Call::Transfer { .. }) => {
 							withdraw_transfer::<T>(&collection, who, &TokenId::default())
@@ -196,8 +196,7 @@
 			// Token existance isn't checked at this point and should be checked in `withdraw` method.
 			let token = RefungibleTokenHandle(rft_collection, token_id);
 
-			let (method_id, mut reader) = AbiReader::new_call(&call_context.input).ok()?;
-			let call = <UniqueRefungibleTokenCall<T>>::parse(method_id, &mut reader).ok()??;
+			let call = <UniqueRefungibleTokenCall<T>>::parse_full(&call_context.input).ok()??;
 			Some(T::CrossAccountId::from_sub(
 				refungible::token_call_sponsor(call, token, who).map(|()| sponsor)?,
 			))
modifiedtests/src/eth/abi/collectionHelpers.jsondiffbeforeafterboth
--- a/tests/src/eth/abi/collectionHelpers.json
+++ b/tests/src/eth/abi/collectionHelpers.json
@@ -77,15 +77,6 @@
     "inputs": [
       {
         "components": [
-          {
-            "components": [
-              { "internalType": "address", "name": "eth", "type": "address" },
-              { "internalType": "uint256", "name": "sub", "type": "uint256" }
-            ],
-            "internalType": "struct CrossAddress",
-            "name": "pending_sponsor",
-            "type": "tuple"
-          },
           { "internalType": "string", "name": "name", "type": "string" },
           { "internalType": "string", "name": "description", "type": "string" },
           {
@@ -170,6 +161,15 @@
             "type": "tuple[]"
           },
           {
+            "components": [
+              { "internalType": "address", "name": "eth", "type": "address" },
+              { "internalType": "uint256", "name": "sub", "type": "uint256" }
+            ],
+            "internalType": "struct CrossAddress",
+            "name": "pending_sponsor",
+            "type": "tuple"
+          },
+          {
             "internalType": "CollectionFlags",
             "name": "flags",
             "type": "uint8"
modifiedtests/src/eth/util/playgrounds/types.tsdiffbeforeafterboth
--- a/tests/src/eth/util/playgrounds/types.ts
+++ b/tests/src/eth/util/playgrounds/types.ts
@@ -59,8 +59,8 @@
 }
 
 export enum CollectionMode {
+	Nonfungible,
 	Fungible,
-	Nonfungible,
 	Refungible,
 }
 
@@ -129,4 +129,4 @@
     else
       this.decimals = 0;
   }
-}
\ No newline at end of file
+}
modifiedtests/src/eth/util/playgrounds/unique.dev.tsdiffbeforeafterboth
--- a/tests/src/eth/util/playgrounds/unique.dev.ts
+++ b/tests/src/eth/util/playgrounds/unique.dev.ts
@@ -216,7 +216,6 @@
     }
 
     const tx = collectionHelper.methods.createCollection([
-      this.data.pendingSponsor,
       this.data.name,
       this.data.description,
       this.data.tokenPrefix,
@@ -227,6 +226,7 @@
       this.data.adminList,
       this.data.nestingSettings,
       this.data.limits,
+      this.data.pendingSponsor,
       this.data.flags,
     ]);
     return tx;