git.delta.rocks / unique-network / refs/commits / 3ae92b8aacb2

difftreelog

refactor move collection dispatch to runtime

Yaroslav Bolyukin2022-04-07parent: #059f10c.patch.diff
in: master

13 files changed

addedpallets/common/src/dispatch.rsdiffbeforeafterboth
--- /dev/null
+++ b/pallets/common/src/dispatch.rs
@@ -0,0 +1,68 @@
+use frame_support::{
+	dispatch::{
+		DispatchResultWithPostInfo, PostDispatchInfo, Weight, DispatchErrorWithPostInfo,
+		DispatchResult,
+	},
+	weights::Pays,
+	traits::Get,
+};
+use up_data_structs::{CollectionId, CreateCollectionData};
+
+use crate::{pallet::Config, CommonCollectionOperations, CollectionHandle};
+
+// TODO: move to benchmarking
+/// Price of [`dispatch_call`] call with noop `call` argument
+pub fn dispatch_weight<T: Config>() -> Weight {
+	// Read collection
+	<T as frame_system::Config>::DbWeight::get().reads(1)
+	// Dynamic dispatch?
+	+ 6_000_000
+	// submit_logs is measured as part of collection pallets
+}
+
+/// Helper function to implement substrate calls for common collection methods
+pub fn dispatch_call<
+	T: Config,
+	C: FnOnce(&dyn CommonCollectionOperations<T>) -> DispatchResultWithPostInfo,
+>(
+	collection: CollectionId,
+	call: C,
+) -> DispatchResultWithPostInfo {
+	let handle =
+		CollectionHandle::try_get(collection).map_err(|error| DispatchErrorWithPostInfo {
+			post_info: PostDispatchInfo {
+				actual_weight: Some(dispatch_weight::<T>()),
+				pays_fee: Pays::Yes,
+			},
+			error,
+		})?;
+	let dispatched = T::CollectionDispatch::dispatch(handle);
+	let mut result = call(dispatched.as_dyn());
+	match &mut result {
+		Ok(PostDispatchInfo {
+			actual_weight: Some(weight),
+			..
+		})
+		| Err(DispatchErrorWithPostInfo {
+			post_info: PostDispatchInfo {
+				actual_weight: Some(weight),
+				..
+			},
+			..
+		}) => *weight += dispatch_weight::<T>(),
+		_ => {}
+	}
+
+	dispatched.into_inner().submit_logs();
+	result
+}
+
+pub trait CollectionDispatch<T: Config> {
+	fn create(sender: T::AccountId, data: CreateCollectionData<T::AccountId>) -> DispatchResult;
+	fn destroy(sender: T::CrossAccountId, handle: CollectionHandle<T>) -> DispatchResult;
+
+	fn dispatch(handle: CollectionHandle<T>) -> Self;
+	fn into_inner(self) -> CollectionHandle<T>;
+
+	fn as_dyn(&self) -> &dyn CommonCollectionOperations<T>;
+}
modifiedpallets/common/src/lib.rsdiffbeforeafterboth
before · pallets/common/src/lib.rs
1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617#![cfg_attr(not(feature = "std"), no_std)]1819use core::ops::{Deref, DerefMut};20use pallet_evm_coder_substrate::{SubstrateRecorder, WithRecorder};21use sp_std::vec::Vec;22use pallet_evm::account::CrossAccountId;23use frame_support::{24	dispatch::{DispatchErrorWithPostInfo, DispatchResultWithPostInfo},25	ensure, fail,26	traits::{Imbalance, Get, Currency},27	BoundedVec,28};29use pallet_evm::GasWeightMapping;30use up_data_structs::{31	COLLECTION_NUMBER_LIMIT, Collection, CollectionId, CreateItemData, ExistenceRequirement,32	MAX_TOKEN_PREFIX_LENGTH, COLLECTION_ADMINS_LIMIT, MetaUpdatePermission, Pays, PostDispatchInfo,33	TokenId, Weight, WithdrawReasons, CollectionStats, MAX_TOKEN_OWNERSHIP, CollectionMode,34	NFT_SPONSOR_TRANSFER_TIMEOUT, FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,35	REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT, MAX_SPONSOR_TIMEOUT, CUSTOM_DATA_LIMIT, CollectionLimits,36	CustomDataLimit, CreateCollectionData, SponsorshipState, CreateItemExData, SponsoringRateLimit,37};38pub use pallet::*;39use sp_core::H160;40use sp_runtime::{ArithmeticError, DispatchError, DispatchResult};41#[cfg(feature = "runtime-benchmarks")]42pub mod benchmarking;43pub mod erc;44pub mod eth;4546#[must_use = "Should call submit_logs or save, otherwise some data will be lost for evm side"]47pub struct CollectionHandle<T: Config> {48	pub id: CollectionId,49	collection: Collection<T::AccountId>,50	pub recorder: SubstrateRecorder<T>,51}52impl<T: Config> WithRecorder<T> for CollectionHandle<T> {53	fn recorder(&self) -> &SubstrateRecorder<T> {54		&self.recorder55	}56	fn into_recorder(self) -> SubstrateRecorder<T> {57		self.recorder58	}59}60impl<T: Config> CollectionHandle<T> {61	pub fn new_with_gas_limit(id: CollectionId, gas_limit: u64) -> Option<Self> {62		<CollectionById<T>>::get(id).map(|collection| Self {63			id,64			collection,65			recorder: SubstrateRecorder::new(eth::collection_id_to_address(id), gas_limit),66		})67	}68	pub fn new(id: CollectionId) -> Option<Self> {69		Self::new_with_gas_limit(id, u64::MAX)70	}71	pub fn try_get(id: CollectionId) -> Result<Self, DispatchError> {72		Ok(Self::new(id).ok_or(<Error<T>>::CollectionNotFound)?)73	}74	pub fn log_mirrored(&self, log: impl evm_coder::ToLog) {75		self.recorder.log_mirrored(log)76	}77	pub fn log_direct(&self, log: impl evm_coder::ToLog) {78		self.recorder.log_direct(log)79	}80	pub fn consume_store_reads(&self, reads: u64) -> evm_coder::execution::Result<()> {81		self.recorder82			.consume_gas(T::GasWeightMapping::weight_to_gas(83				<T as frame_system::Config>::DbWeight::get()84					.read85					.saturating_mul(reads),86			))87	}88	pub fn consume_store_writes(&self, writes: u64) -> evm_coder::execution::Result<()> {89		self.recorder90			.consume_gas(T::GasWeightMapping::weight_to_gas(91				<T as frame_system::Config>::DbWeight::get()92					.write93					.saturating_mul(writes),94			))95	}96	pub fn submit_logs(self) {97		self.recorder.submit_logs()98	}99	pub fn save(self) -> DispatchResult {100		self.recorder.submit_logs();101		<CollectionById<T>>::insert(self.id, self.collection);102		Ok(())103	}104}105impl<T: Config> Deref for CollectionHandle<T> {106	type Target = Collection<T::AccountId>;107108	fn deref(&self) -> &Self::Target {109		&self.collection110	}111}112113impl<T: Config> DerefMut for CollectionHandle<T> {114	fn deref_mut(&mut self) -> &mut Self::Target {115		&mut self.collection116	}117}118119impl<T: Config> CollectionHandle<T> {120	pub fn check_is_owner(&self, subject: &T::CrossAccountId) -> DispatchResult {121		ensure!(*subject.as_sub() == self.owner, <Error<T>>::NoPermission);122		Ok(())123	}124	pub fn is_owner_or_admin(&self, subject: &T::CrossAccountId) -> bool {125		*subject.as_sub() == self.owner || <IsAdmin<T>>::get((self.id, subject))126	}127	pub fn check_is_owner_or_admin(&self, subject: &T::CrossAccountId) -> DispatchResult {128		ensure!(self.is_owner_or_admin(subject), <Error<T>>::NoPermission);129		Ok(())130	}131	pub fn ignores_allowance(&self, user: &T::CrossAccountId) -> bool {132		self.limits.owner_can_transfer() && self.is_owner_or_admin(user)133	}134	pub fn ignores_owned_amount(&self, user: &T::CrossAccountId) -> bool {135		self.limits.owner_can_transfer() && self.is_owner_or_admin(user)136	}137	pub fn check_allowlist(&self, user: &T::CrossAccountId) -> DispatchResult {138		ensure!(139			<Allowlist<T>>::get((self.id, user)),140			<Error<T>>::AddressNotInAllowlist141		);142		Ok(())143	}144145	pub fn check_can_update_meta(146		&self,147		subject: &T::CrossAccountId,148		item_owner: &T::CrossAccountId,149	) -> DispatchResult {150		match self.meta_update_permission {151			MetaUpdatePermission::ItemOwner => {152				ensure!(subject == item_owner, <Error<T>>::NoPermission);153				Ok(())154			}155			MetaUpdatePermission::Admin => self.check_is_owner_or_admin(subject),156			MetaUpdatePermission::None => fail!(<Error<T>>::NoPermission),157		}158	}159}160161#[frame_support::pallet]162pub mod pallet {163	use super::*;164	use frame_support::{Blake2_128Concat, pallet_prelude::*, storage::Key};165	use pallet_evm::account;166	use frame_support::traits::Currency;167	use up_data_structs::TokenId;168	use scale_info::TypeInfo;169170	#[pallet::config]171	pub trait Config:172		frame_system::Config + pallet_evm_coder_substrate::Config + TypeInfo + account::Config173	{174		type Event: IsType<<Self as frame_system::Config>::Event> + From<Event<Self>>;175176		type Currency: Currency<Self::AccountId>;177178		#[pallet::constant]179		type CollectionCreationPrice: Get<180			<<Self as Config>::Currency as Currency<Self::AccountId>>::Balance,181		>;182183		type TreasuryAccountId: Get<Self::AccountId>;184	}185186	#[pallet::pallet]187	#[pallet::generate_store(pub(super) trait Store)]188	pub struct Pallet<T>(_);189190	#[pallet::extra_constants]191	impl<T: Config> Pallet<T> {192		pub fn collection_admins_limit() -> u32 {193			COLLECTION_ADMINS_LIMIT194		}195	}196197	#[pallet::event]198	#[pallet::generate_deposit(pub fn deposit_event)]199	pub enum Event<T: Config> {200		/// New collection was created201		///202		/// # Arguments203		///204		/// * collection_id: Globally unique identifier of newly created collection.205		///206		/// * mode: [CollectionMode] converted into u8.207		///208		/// * account_id: Collection owner.209		CollectionCreated(CollectionId, u8, T::AccountId),210211		/// New collection was destroyed212		///213		/// # Arguments214		///215		/// * collection_id: Globally unique identifier of collection.216		CollectionDestroyed(CollectionId),217218		/// New item was created.219		///220		/// # Arguments221		///222		/// * collection_id: Id of the collection where item was created.223		///224		/// * item_id: Id of an item. Unique within the collection.225		///226		/// * recipient: Owner of newly created item227		///228		/// * amount: Always 1 for NFT229		ItemCreated(CollectionId, TokenId, T::CrossAccountId, u128),230231		/// Collection item was burned.232		///233		/// # Arguments234		///235		/// * collection_id.236		///237		/// * item_id: Identifier of burned NFT.238		///239		/// * owner: which user has destroyed its tokens240		///241		/// * amount: Always 1 for NFT242		ItemDestroyed(CollectionId, TokenId, T::CrossAccountId, u128),243244		/// Item was transferred245		///246		/// * collection_id: Id of collection to which item is belong247		///248		/// * item_id: Id of an item249		///250		/// * sender: Original owner of item251		///252		/// * recipient: New owner of item253		///254		/// * amount: Always 1 for NFT255		Transfer(256			CollectionId,257			TokenId,258			T::CrossAccountId,259			T::CrossAccountId,260			u128,261		),262263		/// * collection_id264		///265		/// * item_id266		///267		/// * sender268		///269		/// * spender270		///271		/// * amount272		Approved(273			CollectionId,274			TokenId,275			T::CrossAccountId,276			T::CrossAccountId,277			u128,278		),279	}280281	#[pallet::error]282	pub enum Error<T> {283		/// This collection does not exist.284		CollectionNotFound,285		/// Sender parameter and item owner must be equal.286		MustBeTokenOwner,287		/// No permission to perform action288		NoPermission,289		/// Collection is not in mint mode.290		PublicMintingNotAllowed,291		/// Address is not in allow list.292		AddressNotInAllowlist,293294		/// Collection name can not be longer than 63 char.295		CollectionNameLimitExceeded,296		/// Collection description can not be longer than 255 char.297		CollectionDescriptionLimitExceeded,298		/// Token prefix can not be longer than 15 char.299		CollectionTokenPrefixLimitExceeded,300		/// Total collections bound exceeded.301		TotalCollectionsLimitExceeded,302		/// variable_data exceeded data limit.303		TokenVariableDataLimitExceeded,304		/// Exceeded max admin count305		CollectionAdminCountExceeded,306		/// Collection limit bounds per collection exceeded307		CollectionLimitBoundsExceeded,308		/// Tried to enable permissions which are only permitted to be disabled309		OwnerPermissionsCantBeReverted,310311		/// Collection settings not allowing items transferring312		TransferNotAllowed,313		/// Account token limit exceeded per collection314		AccountTokenLimitExceeded,315		/// Collection token limit exceeded316		CollectionTokenLimitExceeded,317		/// Metadata flag frozen318		MetadataFlagFrozen,319320		/// Item not exists.321		TokenNotFound,322		/// Item balance not enough.323		TokenValueTooLow,324		/// Requested value more than approved.325		ApprovedValueTooLow,326		/// Tried to approve more than owned327		CantApproveMoreThanOwned,328329		/// Can't transfer tokens to ethereum zero address330		AddressIsZero,331		/// Target collection doesn't supports this operation332		UnsupportedOperation,333334		/// Not sufficient founds to perform action335		NotSufficientFounds,336	}337338	#[pallet::storage]339	pub type CreatedCollectionCount<T> = StorageValue<Value = CollectionId, QueryKind = ValueQuery>;340	#[pallet::storage]341	pub type DestroyedCollectionCount<T> =342		StorageValue<Value = CollectionId, QueryKind = ValueQuery>;343344	/// Collection info345	#[pallet::storage]346	pub type CollectionById<T> = StorageMap<347		Hasher = Blake2_128Concat,348		Key = CollectionId,349		Value = Collection<<T as frame_system::Config>::AccountId>,350		QueryKind = OptionQuery,351	>;352353	#[pallet::storage]354	pub type AdminAmount<T> = StorageMap<355		Hasher = Blake2_128Concat,356		Key = CollectionId,357		Value = u32,358		QueryKind = ValueQuery,359	>;360361	/// List of collection admins362	#[pallet::storage]363	pub type IsAdmin<T: Config> = StorageNMap<364		Key = (365			Key<Blake2_128Concat, CollectionId>,366			Key<Blake2_128Concat, T::CrossAccountId>,367		),368		Value = bool,369		QueryKind = ValueQuery,370	>;371372	/// Allowlisted collection users373	#[pallet::storage]374	pub type Allowlist<T: Config> = StorageNMap<375		Key = (376			Key<Blake2_128Concat, CollectionId>,377			Key<Blake2_128Concat, T::CrossAccountId>,378		),379		Value = bool,380		QueryKind = ValueQuery,381	>;382383	/// Not used by code, exists only to provide some types to metadata384	#[pallet::storage]385	pub type DummyStorageValue<T> =386		StorageValue<Value = (CollectionStats, CollectionId, TokenId), QueryKind = OptionQuery>;387}388389impl<T: Config> Pallet<T> {390	/// Ethereum receiver 0x0000000000000000000000000000000000000000 is reserved, and shouldn't own tokens391	pub fn ensure_correct_receiver(receiver: &T::CrossAccountId) -> DispatchResult {392		ensure!(393			&T::CrossAccountId::from_eth(H160([0; 20])) != receiver,394			<Error<T>>::AddressIsZero395		);396		Ok(())397	}398	pub fn adminlist(collection: CollectionId) -> Vec<T::CrossAccountId> {399		<IsAdmin<T>>::iter_prefix((collection,))400			.map(|(a, _)| a)401			.collect()402	}403	pub fn allowlist(collection: CollectionId) -> Vec<T::CrossAccountId> {404		<Allowlist<T>>::iter_prefix((collection,))405			.map(|(a, _)| a)406			.collect()407	}408	pub fn allowed(collection: CollectionId, user: T::CrossAccountId) -> bool {409		<Allowlist<T>>::get((collection, user))410	}411	pub fn collection_stats() -> CollectionStats {412		let created = <CreatedCollectionCount<T>>::get();413		let destroyed = <DestroyedCollectionCount<T>>::get();414		CollectionStats {415			created: created.0,416			destroyed: destroyed.0,417			alive: created.0 - destroyed.0,418		}419	}420421	pub fn effective_collection_limits(collection: CollectionId) -> Option<CollectionLimits> {422		let collection = <CollectionById<T>>::get(collection);423		if collection.is_none() {424			return None;425		}426427		let collection = collection.unwrap();428		let limits = collection.limits;429		let effective_limits = CollectionLimits {430			account_token_ownership_limit: Some(limits.account_token_ownership_limit()),431			sponsored_data_size: Some(limits.sponsored_data_size()),432			sponsored_data_rate_limit: Some(433				limits434					.sponsored_data_rate_limit435					.unwrap_or(SponsoringRateLimit::SponsoringDisabled),436			),437			token_limit: Some(limits.token_limit()),438			sponsor_transfer_timeout: Some(limits.sponsor_transfer_timeout(439				match collection.mode {440					CollectionMode::NFT => NFT_SPONSOR_TRANSFER_TIMEOUT,441					CollectionMode::Fungible(_) => FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,442					CollectionMode::ReFungible => REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,443				},444			)),445			sponsor_approve_timeout: Some(limits.sponsor_approve_timeout()),446			owner_can_transfer: Some(limits.owner_can_transfer()),447			owner_can_destroy: Some(limits.owner_can_destroy()),448			transfers_enabled: Some(limits.transfers_enabled()),449		};450451		Some(effective_limits)452	}453}454455impl<T: Config> Pallet<T> {456	pub fn init_collection(457		owner: T::AccountId,458		data: CreateCollectionData<T::AccountId>,459	) -> Result<CollectionId, DispatchError> {460		{461			ensure!(462				data.token_prefix.len() <= MAX_TOKEN_PREFIX_LENGTH as usize,463				Error::<T>::CollectionTokenPrefixLimitExceeded464			);465		}466467		let created_count = <CreatedCollectionCount<T>>::get()468			.0469			.checked_add(1)470			.ok_or(ArithmeticError::Overflow)?;471		let destroyed_count = <DestroyedCollectionCount<T>>::get().0;472		let id = CollectionId(created_count);473474		// bound Total number of collections475		ensure!(476			created_count - destroyed_count <= COLLECTION_NUMBER_LIMIT,477			<Error<T>>::TotalCollectionsLimitExceeded478		);479480		// =========481482		let collection = Collection {483			owner: owner.clone(),484			name: data.name,485			mode: data.mode.clone(),486			mint_mode: false,487			access: data.access.unwrap_or_default(),488			description: data.description,489			token_prefix: data.token_prefix,490			offchain_schema: data.offchain_schema,491			schema_version: data.schema_version.unwrap_or_default(),492			sponsorship: data493				.pending_sponsor494				.map(SponsorshipState::Unconfirmed)495				.unwrap_or_default(),496			variable_on_chain_schema: data.variable_on_chain_schema,497			const_on_chain_schema: data.const_on_chain_schema,498			limits: data499				.limits500				.map(|limits| Self::clamp_limits(data.mode.clone(), &Default::default(), limits))501				.unwrap_or_else(|| Ok(CollectionLimits::default()))?,502			meta_update_permission: data.meta_update_permission.unwrap_or_default(),503		};504505		// Take a (non-refundable) deposit of collection creation506		{507			let mut imbalance =508				<<<T as Config>::Currency as Currency<T::AccountId>>::PositiveImbalance>::zero();509			imbalance.subsume(510				<<T as Config>::Currency as Currency<T::AccountId>>::deposit_creating(511					&T::TreasuryAccountId::get(),512					T::CollectionCreationPrice::get(),513				),514			);515			<T as Config>::Currency::settle(516				&owner,517				imbalance,518				WithdrawReasons::TRANSFER,519				ExistenceRequirement::KeepAlive,520			)521			.map_err(|_| Error::<T>::NotSufficientFounds)?;522		}523524		<CreatedCollectionCount<T>>::put(created_count);525		<Pallet<T>>::deposit_event(Event::CollectionCreated(id, data.mode.id(), owner.clone()));526		<CollectionById<T>>::insert(id, collection);527		Ok(id)528	}529530	pub fn destroy_collection(531		collection: CollectionHandle<T>,532		sender: &T::CrossAccountId,533	) -> DispatchResult {534		ensure!(535			collection.limits.owner_can_destroy(),536			<Error<T>>::NoPermission,537		);538		collection.check_is_owner(sender)?;539540		let destroyed_collections = <DestroyedCollectionCount<T>>::get()541			.0542			.checked_add(1)543			.ok_or(ArithmeticError::Overflow)?;544545		// =========546547		<DestroyedCollectionCount<T>>::put(destroyed_collections);548		<CollectionById<T>>::remove(collection.id);549		<AdminAmount<T>>::remove(collection.id);550		<IsAdmin<T>>::remove_prefix((collection.id,), None);551		<Allowlist<T>>::remove_prefix((collection.id,), None);552553		<Pallet<T>>::deposit_event(Event::CollectionDestroyed(collection.id));554		Ok(())555	}556557	pub fn toggle_allowlist(558		collection: &CollectionHandle<T>,559		sender: &T::CrossAccountId,560		user: &T::CrossAccountId,561		allowed: bool,562	) -> DispatchResult {563		collection.check_is_owner_or_admin(sender)?;564565		// =========566567		if allowed {568			<Allowlist<T>>::insert((collection.id, user), true);569		} else {570			<Allowlist<T>>::remove((collection.id, user));571		}572573		Ok(())574	}575576	pub fn toggle_admin(577		collection: &CollectionHandle<T>,578		sender: &T::CrossAccountId,579		user: &T::CrossAccountId,580		admin: bool,581	) -> DispatchResult {582		collection.check_is_owner_or_admin(sender)?;583584		let was_admin = <IsAdmin<T>>::get((collection.id, user));585		if was_admin == admin {586			return Ok(());587		}588		let amount = <AdminAmount<T>>::get(collection.id);589590		if admin {591			let amount = amount592				.checked_add(1)593				.ok_or(<Error<T>>::CollectionAdminCountExceeded)?;594			ensure!(595				amount <= Self::collection_admins_limit(),596				<Error<T>>::CollectionAdminCountExceeded,597			);598599			// =========600601			<AdminAmount<T>>::insert(collection.id, amount);602			<IsAdmin<T>>::insert((collection.id, user), true);603		} else {604			<AdminAmount<T>>::insert(collection.id, amount.saturating_sub(1));605			<IsAdmin<T>>::remove((collection.id, user));606		}607608		Ok(())609	}610611	pub fn clamp_limits(612		mode: CollectionMode,613		old_limit: &CollectionLimits,614		mut new_limit: CollectionLimits,615	) -> Result<CollectionLimits, DispatchError> {616		macro_rules! limit_default {617				($old:ident, $new:ident, $($field:ident $(($arg:expr))? => $check:expr),* $(,)?) => {{618					$(619						if let Some($new) = $new.$field {620							let $old = $old.$field($($arg)?);621							let _ = $new;622							let _ = $old;623							$check624						} else {625							$new.$field = $old.$field626						}627					)*628				}};629			}630631		limit_default!(old_limit, new_limit,632			account_token_ownership_limit => ensure!(633				new_limit <= MAX_TOKEN_OWNERSHIP,634				<Error<T>>::CollectionLimitBoundsExceeded,635			),636			sponsor_transfer_timeout(match mode {637				CollectionMode::NFT => NFT_SPONSOR_TRANSFER_TIMEOUT,638				CollectionMode::Fungible(_) => FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,639				CollectionMode::ReFungible => REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,640			}) => ensure!(641				new_limit <= MAX_SPONSOR_TIMEOUT,642				<Error<T>>::CollectionLimitBoundsExceeded,643			),644			sponsored_data_size => ensure!(645				new_limit <= CUSTOM_DATA_LIMIT,646				<Error<T>>::CollectionLimitBoundsExceeded,647			),648			token_limit => ensure!(649				old_limit >= new_limit && new_limit > 0,650				<Error<T>>::CollectionTokenLimitExceeded651			),652			owner_can_transfer => ensure!(653				old_limit || !new_limit,654				<Error<T>>::OwnerPermissionsCantBeReverted,655			),656			owner_can_destroy => ensure!(657				old_limit || !new_limit,658				<Error<T>>::OwnerPermissionsCantBeReverted,659			),660			sponsored_data_rate_limit => {},661			transfers_enabled => {},662		);663		Ok(new_limit)664	}665}666667#[macro_export]668macro_rules! unsupported {669	() => {670		Err(<Error<T>>::UnsupportedOperation.into())671	};672}673674/// Worst cases675pub trait CommonWeightInfo<CrossAccountId> {676	fn create_item() -> Weight;677	fn create_multiple_items(amount: u32) -> Weight;678	fn create_multiple_items_ex(cost: &CreateItemExData<CrossAccountId>) -> Weight;679	fn burn_item() -> Weight;680	fn transfer() -> Weight;681	fn approve() -> Weight;682	fn transfer_from() -> Weight;683	fn burn_from() -> Weight;684	fn set_variable_metadata(bytes: u32) -> Weight;685}686687pub trait CommonCollectionOperations<T: Config> {688	fn create_item(689		&self,690		sender: T::CrossAccountId,691		to: T::CrossAccountId,692		data: CreateItemData,693	) -> DispatchResultWithPostInfo;694	fn create_multiple_items(695		&self,696		sender: T::CrossAccountId,697		to: T::CrossAccountId,698		data: Vec<CreateItemData>,699	) -> DispatchResultWithPostInfo;700	fn create_multiple_items_ex(701		&self,702		sender: T::CrossAccountId,703		data: CreateItemExData<T::CrossAccountId>,704	) -> DispatchResultWithPostInfo;705	fn burn_item(706		&self,707		sender: T::CrossAccountId,708		token: TokenId,709		amount: u128,710	) -> DispatchResultWithPostInfo;711712	fn transfer(713		&self,714		sender: T::CrossAccountId,715		to: T::CrossAccountId,716		token: TokenId,717		amount: u128,718	) -> DispatchResultWithPostInfo;719	fn approve(720		&self,721		sender: T::CrossAccountId,722		spender: T::CrossAccountId,723		token: TokenId,724		amount: u128,725	) -> DispatchResultWithPostInfo;726	fn transfer_from(727		&self,728		sender: T::CrossAccountId,729		from: T::CrossAccountId,730		to: T::CrossAccountId,731		token: TokenId,732		amount: u128,733	) -> DispatchResultWithPostInfo;734	fn burn_from(735		&self,736		sender: T::CrossAccountId,737		from: T::CrossAccountId,738		token: TokenId,739		amount: u128,740	) -> DispatchResultWithPostInfo;741742	fn set_variable_metadata(743		&self,744		sender: T::CrossAccountId,745		token: TokenId,746		data: BoundedVec<u8, CustomDataLimit>,747	) -> DispatchResultWithPostInfo;748749	fn account_tokens(&self, account: T::CrossAccountId) -> Vec<TokenId>;750	fn token_exists(&self, token: TokenId) -> bool;751	fn last_token_id(&self) -> TokenId;752753	fn token_owner(&self, token: TokenId) -> Option<T::CrossAccountId>;754	fn const_metadata(&self, token: TokenId) -> Vec<u8>;755	fn variable_metadata(&self, token: TokenId) -> Vec<u8>;756757	/// How many tokens collection contains (Applicable to nonfungible/refungible)758	fn collection_tokens(&self) -> u32;759	/// Amount of different tokens account has (Applicable to nonfungible/refungible)760	fn account_balance(&self, account: T::CrossAccountId) -> u32;761	/// Amount of specific token account have (Applicable to fungible/refungible)762	fn balance(&self, account: T::CrossAccountId, token: TokenId) -> u128;763	fn allowance(764		&self,765		sender: T::CrossAccountId,766		spender: T::CrossAccountId,767		token: TokenId,768	) -> u128;769}770771// Flexible enough for implementing CommonCollectionOperations772pub fn with_weight(res: DispatchResult, weight: Weight) -> DispatchResultWithPostInfo {773	let post_info = PostDispatchInfo {774		actual_weight: Some(weight),775		pays_fee: Pays::Yes,776	};777	match res {778		Ok(()) => Ok(post_info),779		Err(error) => Err(DispatchErrorWithPostInfo { post_info, error }),780	}781}
after · pallets/common/src/lib.rs
1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617#![cfg_attr(not(feature = "std"), no_std)]1819use core::ops::{Deref, DerefMut};20use pallet_evm_coder_substrate::{SubstrateRecorder, WithRecorder};21use sp_std::vec::Vec;22use pallet_evm::account::CrossAccountId;23use frame_support::{24	dispatch::{DispatchErrorWithPostInfo, DispatchResultWithPostInfo, Weight, PostDispatchInfo},25	ensure, fail,26	traits::{Imbalance, Get, Currency, WithdrawReasons, ExistenceRequirement},27	BoundedVec,28	weights::Pays,29};30use pallet_evm::GasWeightMapping;31use up_data_structs::{32	COLLECTION_NUMBER_LIMIT, Collection, CollectionId, CreateItemData, MAX_TOKEN_PREFIX_LENGTH,33	COLLECTION_ADMINS_LIMIT, MetaUpdatePermission, TokenId, CollectionStats, MAX_TOKEN_OWNERSHIP,34	CollectionMode, NFT_SPONSOR_TRANSFER_TIMEOUT, FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,35	REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT, MAX_SPONSOR_TIMEOUT, CUSTOM_DATA_LIMIT, CollectionLimits,36	CustomDataLimit, CreateCollectionData, SponsorshipState, CreateItemExData, SponsoringRateLimit,37};38pub use pallet::*;39use sp_core::H160;40use sp_runtime::{ArithmeticError, DispatchError, DispatchResult};41#[cfg(feature = "runtime-benchmarks")]42pub mod benchmarking;43pub mod dispatch;44pub mod erc;45pub mod eth;4647#[must_use = "Should call submit_logs or save, otherwise some data will be lost for evm side"]48pub struct CollectionHandle<T: Config> {49	pub id: CollectionId,50	collection: Collection<T::AccountId>,51	pub recorder: SubstrateRecorder<T>,52}53impl<T: Config> WithRecorder<T> for CollectionHandle<T> {54	fn recorder(&self) -> &SubstrateRecorder<T> {55		&self.recorder56	}57	fn into_recorder(self) -> SubstrateRecorder<T> {58		self.recorder59	}60}61impl<T: Config> CollectionHandle<T> {62	pub fn new_with_gas_limit(id: CollectionId, gas_limit: u64) -> Option<Self> {63		<CollectionById<T>>::get(id).map(|collection| Self {64			id,65			collection,66			recorder: SubstrateRecorder::new(eth::collection_id_to_address(id), gas_limit),67		})68	}69	pub fn new(id: CollectionId) -> Option<Self> {70		Self::new_with_gas_limit(id, u64::MAX)71	}72	pub fn try_get(id: CollectionId) -> Result<Self, DispatchError> {73		Ok(Self::new(id).ok_or(<Error<T>>::CollectionNotFound)?)74	}75	pub fn log_mirrored(&self, log: impl evm_coder::ToLog) {76		self.recorder.log_mirrored(log)77	}78	pub fn log_direct(&self, log: impl evm_coder::ToLog) {79		self.recorder.log_direct(log)80	}81	pub fn consume_store_reads(&self, reads: u64) -> evm_coder::execution::Result<()> {82		self.recorder83			.consume_gas(T::GasWeightMapping::weight_to_gas(84				<T as frame_system::Config>::DbWeight::get()85					.read86					.saturating_mul(reads),87			))88	}89	pub fn consume_store_writes(&self, writes: u64) -> evm_coder::execution::Result<()> {90		self.recorder91			.consume_gas(T::GasWeightMapping::weight_to_gas(92				<T as frame_system::Config>::DbWeight::get()93					.write94					.saturating_mul(writes),95			))96	}97	pub fn submit_logs(self) {98		self.recorder.submit_logs()99	}100	pub fn save(self) -> DispatchResult {101		self.recorder.submit_logs();102		<CollectionById<T>>::insert(self.id, self.collection);103		Ok(())104	}105}106impl<T: Config> Deref for CollectionHandle<T> {107	type Target = Collection<T::AccountId>;108109	fn deref(&self) -> &Self::Target {110		&self.collection111	}112}113114impl<T: Config> DerefMut for CollectionHandle<T> {115	fn deref_mut(&mut self) -> &mut Self::Target {116		&mut self.collection117	}118}119120impl<T: Config> CollectionHandle<T> {121	pub fn check_is_owner(&self, subject: &T::CrossAccountId) -> DispatchResult {122		ensure!(*subject.as_sub() == self.owner, <Error<T>>::NoPermission);123		Ok(())124	}125	pub fn is_owner_or_admin(&self, subject: &T::CrossAccountId) -> bool {126		*subject.as_sub() == self.owner || <IsAdmin<T>>::get((self.id, subject))127	}128	pub fn check_is_owner_or_admin(&self, subject: &T::CrossAccountId) -> DispatchResult {129		ensure!(self.is_owner_or_admin(subject), <Error<T>>::NoPermission);130		Ok(())131	}132	pub fn ignores_allowance(&self, user: &T::CrossAccountId) -> bool {133		self.limits.owner_can_transfer() && self.is_owner_or_admin(user)134	}135	pub fn ignores_owned_amount(&self, user: &T::CrossAccountId) -> bool {136		self.limits.owner_can_transfer() && self.is_owner_or_admin(user)137	}138	pub fn check_allowlist(&self, user: &T::CrossAccountId) -> DispatchResult {139		ensure!(140			<Allowlist<T>>::get((self.id, user)),141			<Error<T>>::AddressNotInAllowlist142		);143		Ok(())144	}145146	pub fn check_can_update_meta(147		&self,148		subject: &T::CrossAccountId,149		item_owner: &T::CrossAccountId,150	) -> DispatchResult {151		match self.meta_update_permission {152			MetaUpdatePermission::ItemOwner => {153				ensure!(subject == item_owner, <Error<T>>::NoPermission);154				Ok(())155			}156			MetaUpdatePermission::Admin => self.check_is_owner_or_admin(subject),157			MetaUpdatePermission::None => fail!(<Error<T>>::NoPermission),158		}159	}160}161162#[frame_support::pallet]163pub mod pallet {164	use super::*;165	use frame_support::{Blake2_128Concat, pallet_prelude::*, storage::Key};166	use pallet_evm::account;167	use dispatch::CollectionDispatch;168	use frame_support::traits::Currency;169	use up_data_structs::TokenId;170	use scale_info::TypeInfo;171	use up_evm_mapping::CrossAccountId;172173	#[pallet::config]174	pub trait Config:175		frame_system::Config + pallet_evm_coder_substrate::Config + TypeInfo + account::Config176	{177		type Event: IsType<<Self as frame_system::Config>::Event> + From<Event<Self>>;178179		type Currency: Currency<Self::AccountId>;180181		#[pallet::constant]182		type CollectionCreationPrice: Get<183			<<Self as Config>::Currency as Currency<Self::AccountId>>::Balance,184		>;185		type CollectionDispatch: CollectionDispatch<Self>;186187		type TreasuryAccountId: Get<Self::AccountId>;188	}189190	#[pallet::pallet]191	#[pallet::generate_store(pub(super) trait Store)]192	pub struct Pallet<T>(_);193194	#[pallet::extra_constants]195	impl<T: Config> Pallet<T> {196		pub fn collection_admins_limit() -> u32 {197			COLLECTION_ADMINS_LIMIT198		}199	}200201	#[pallet::event]202	#[pallet::generate_deposit(pub fn deposit_event)]203	pub enum Event<T: Config> {204		/// New collection was created205		///206		/// # Arguments207		///208		/// * collection_id: Globally unique identifier of newly created collection.209		///210		/// * mode: [CollectionMode] converted into u8.211		///212		/// * account_id: Collection owner.213		CollectionCreated(CollectionId, u8, T::AccountId),214215		/// New collection was destroyed216		///217		/// # Arguments218		///219		/// * collection_id: Globally unique identifier of collection.220		CollectionDestroyed(CollectionId),221222		/// New item was created.223		///224		/// # Arguments225		///226		/// * collection_id: Id of the collection where item was created.227		///228		/// * item_id: Id of an item. Unique within the collection.229		///230		/// * recipient: Owner of newly created item231		///232		/// * amount: Always 1 for NFT233		ItemCreated(CollectionId, TokenId, T::CrossAccountId, u128),234235		/// Collection item was burned.236		///237		/// # Arguments238		///239		/// * collection_id.240		///241		/// * item_id: Identifier of burned NFT.242		///243		/// * owner: which user has destroyed its tokens244		///245		/// * amount: Always 1 for NFT246		ItemDestroyed(CollectionId, TokenId, T::CrossAccountId, u128),247248		/// Item was transferred249		///250		/// * collection_id: Id of collection to which item is belong251		///252		/// * item_id: Id of an item253		///254		/// * sender: Original owner of item255		///256		/// * recipient: New owner of item257		///258		/// * amount: Always 1 for NFT259		Transfer(260			CollectionId,261			TokenId,262			T::CrossAccountId,263			T::CrossAccountId,264			u128,265		),266267		/// * collection_id268		///269		/// * item_id270		///271		/// * sender272		///273		/// * spender274		///275		/// * amount276		Approved(277			CollectionId,278			TokenId,279			T::CrossAccountId,280			T::CrossAccountId,281			u128,282		),283	}284285	#[pallet::error]286	pub enum Error<T> {287		/// This collection does not exist.288		CollectionNotFound,289		/// Sender parameter and item owner must be equal.290		MustBeTokenOwner,291		/// No permission to perform action292		NoPermission,293		/// Collection is not in mint mode.294		PublicMintingNotAllowed,295		/// Address is not in allow list.296		AddressNotInAllowlist,297298		/// Collection name can not be longer than 63 char.299		CollectionNameLimitExceeded,300		/// Collection description can not be longer than 255 char.301		CollectionDescriptionLimitExceeded,302		/// Token prefix can not be longer than 15 char.303		CollectionTokenPrefixLimitExceeded,304		/// Total collections bound exceeded.305		TotalCollectionsLimitExceeded,306		/// variable_data exceeded data limit.307		TokenVariableDataLimitExceeded,308		/// Exceeded max admin count309		CollectionAdminCountExceeded,310		/// Collection limit bounds per collection exceeded311		CollectionLimitBoundsExceeded,312		/// Tried to enable permissions which are only permitted to be disabled313		OwnerPermissionsCantBeReverted,314315		/// Collection settings not allowing items transferring316		TransferNotAllowed,317		/// Account token limit exceeded per collection318		AccountTokenLimitExceeded,319		/// Collection token limit exceeded320		CollectionTokenLimitExceeded,321		/// Metadata flag frozen322		MetadataFlagFrozen,323324		/// Item not exists.325		TokenNotFound,326		/// Item balance not enough.327		TokenValueTooLow,328		/// Requested value more than approved.329		ApprovedValueTooLow,330		/// Tried to approve more than owned331		CantApproveMoreThanOwned,332333		/// Can't transfer tokens to ethereum zero address334		AddressIsZero,335		/// Target collection doesn't supports this operation336		UnsupportedOperation,337338		/// Not sufficient founds to perform action339		NotSufficientFounds,340	}341342	#[pallet::storage]343	pub type CreatedCollectionCount<T> = StorageValue<Value = CollectionId, QueryKind = ValueQuery>;344	#[pallet::storage]345	pub type DestroyedCollectionCount<T> =346		StorageValue<Value = CollectionId, QueryKind = ValueQuery>;347348	/// Collection info349	#[pallet::storage]350	pub type CollectionById<T> = StorageMap<351		Hasher = Blake2_128Concat,352		Key = CollectionId,353		Value = Collection<<T as frame_system::Config>::AccountId>,354		QueryKind = OptionQuery,355	>;356357	#[pallet::storage]358	pub type AdminAmount<T> = StorageMap<359		Hasher = Blake2_128Concat,360		Key = CollectionId,361		Value = u32,362		QueryKind = ValueQuery,363	>;364365	/// List of collection admins366	#[pallet::storage]367	pub type IsAdmin<T: Config> = StorageNMap<368		Key = (369			Key<Blake2_128Concat, CollectionId>,370			Key<Blake2_128Concat, T::CrossAccountId>,371		),372		Value = bool,373		QueryKind = ValueQuery,374	>;375376	/// Allowlisted collection users377	#[pallet::storage]378	pub type Allowlist<T: Config> = StorageNMap<379		Key = (380			Key<Blake2_128Concat, CollectionId>,381			Key<Blake2_128Concat, T::CrossAccountId>,382		),383		Value = bool,384		QueryKind = ValueQuery,385	>;386387	/// Not used by code, exists only to provide some types to metadata388	#[pallet::storage]389	pub type DummyStorageValue<T> =390		StorageValue<Value = (CollectionStats, CollectionId, TokenId), QueryKind = OptionQuery>;391}392393impl<T: Config> Pallet<T> {394	/// Ethereum receiver 0x0000000000000000000000000000000000000000 is reserved, and shouldn't own tokens395	pub fn ensure_correct_receiver(receiver: &T::CrossAccountId) -> DispatchResult {396		ensure!(397			&T::CrossAccountId::from_eth(H160([0; 20])) != receiver,398			<Error<T>>::AddressIsZero399		);400		Ok(())401	}402	pub fn adminlist(collection: CollectionId) -> Vec<T::CrossAccountId> {403		<IsAdmin<T>>::iter_prefix((collection,))404			.map(|(a, _)| a)405			.collect()406	}407	pub fn allowlist(collection: CollectionId) -> Vec<T::CrossAccountId> {408		<Allowlist<T>>::iter_prefix((collection,))409			.map(|(a, _)| a)410			.collect()411	}412	pub fn allowed(collection: CollectionId, user: T::CrossAccountId) -> bool {413		<Allowlist<T>>::get((collection, user))414	}415	pub fn collection_stats() -> CollectionStats {416		let created = <CreatedCollectionCount<T>>::get();417		let destroyed = <DestroyedCollectionCount<T>>::get();418		CollectionStats {419			created: created.0,420			destroyed: destroyed.0,421			alive: created.0 - destroyed.0,422		}423	}424425	pub fn effective_collection_limits(collection: CollectionId) -> Option<CollectionLimits> {426		let collection = <CollectionById<T>>::get(collection);427		if collection.is_none() {428			return None;429		}430431		let collection = collection.unwrap();432		let limits = collection.limits;433		let effective_limits = CollectionLimits {434			account_token_ownership_limit: Some(limits.account_token_ownership_limit()),435			sponsored_data_size: Some(limits.sponsored_data_size()),436			sponsored_data_rate_limit: Some(437				limits438					.sponsored_data_rate_limit439					.unwrap_or(SponsoringRateLimit::SponsoringDisabled),440			),441			token_limit: Some(limits.token_limit()),442			sponsor_transfer_timeout: Some(limits.sponsor_transfer_timeout(443				match collection.mode {444					CollectionMode::NFT => NFT_SPONSOR_TRANSFER_TIMEOUT,445					CollectionMode::Fungible(_) => FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,446					CollectionMode::ReFungible => REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,447				},448			)),449			sponsor_approve_timeout: Some(limits.sponsor_approve_timeout()),450			owner_can_transfer: Some(limits.owner_can_transfer()),451			owner_can_destroy: Some(limits.owner_can_destroy()),452			transfers_enabled: Some(limits.transfers_enabled()),453		};454455		Some(effective_limits)456	}457}458459impl<T: Config> Pallet<T> {460	pub fn init_collection(461		owner: T::AccountId,462		data: CreateCollectionData<T::AccountId>,463	) -> Result<CollectionId, DispatchError> {464		{465			ensure!(466				data.token_prefix.len() <= MAX_TOKEN_PREFIX_LENGTH as usize,467				Error::<T>::CollectionTokenPrefixLimitExceeded468			);469		}470471		let created_count = <CreatedCollectionCount<T>>::get()472			.0473			.checked_add(1)474			.ok_or(ArithmeticError::Overflow)?;475		let destroyed_count = <DestroyedCollectionCount<T>>::get().0;476		let id = CollectionId(created_count);477478		// bound Total number of collections479		ensure!(480			created_count - destroyed_count <= COLLECTION_NUMBER_LIMIT,481			<Error<T>>::TotalCollectionsLimitExceeded482		);483484		// =========485486		let collection = Collection {487			owner: owner.clone(),488			name: data.name,489			mode: data.mode.clone(),490			mint_mode: false,491			access: data.access.unwrap_or_default(),492			description: data.description,493			token_prefix: data.token_prefix,494			offchain_schema: data.offchain_schema,495			schema_version: data.schema_version.unwrap_or_default(),496			sponsorship: data497				.pending_sponsor498				.map(SponsorshipState::Unconfirmed)499				.unwrap_or_default(),500			variable_on_chain_schema: data.variable_on_chain_schema,501			const_on_chain_schema: data.const_on_chain_schema,502			limits: data503				.limits504				.map(|limits| Self::clamp_limits(data.mode.clone(), &Default::default(), limits))505				.unwrap_or_else(|| Ok(CollectionLimits::default()))?,506			meta_update_permission: data.meta_update_permission.unwrap_or_default(),507		};508509		// Take a (non-refundable) deposit of collection creation510		{511			let mut imbalance =512				<<<T as Config>::Currency as Currency<T::AccountId>>::PositiveImbalance>::zero();513			imbalance.subsume(514				<<T as Config>::Currency as Currency<T::AccountId>>::deposit_creating(515					&T::TreasuryAccountId::get(),516					T::CollectionCreationPrice::get(),517				),518			);519			<T as Config>::Currency::settle(520				&owner,521				imbalance,522				WithdrawReasons::TRANSFER,523				ExistenceRequirement::KeepAlive,524			)525			.map_err(|_| Error::<T>::NotSufficientFounds)?;526		}527528		<CreatedCollectionCount<T>>::put(created_count);529		<Pallet<T>>::deposit_event(Event::CollectionCreated(id, data.mode.id(), owner.clone()));530		<CollectionById<T>>::insert(id, collection);531		Ok(id)532	}533534	pub fn destroy_collection(535		collection: CollectionHandle<T>,536		sender: &T::CrossAccountId,537	) -> DispatchResult {538		ensure!(539			collection.limits.owner_can_destroy(),540			<Error<T>>::NoPermission,541		);542		collection.check_is_owner(sender)?;543544		let destroyed_collections = <DestroyedCollectionCount<T>>::get()545			.0546			.checked_add(1)547			.ok_or(ArithmeticError::Overflow)?;548549		// =========550551		<DestroyedCollectionCount<T>>::put(destroyed_collections);552		<CollectionById<T>>::remove(collection.id);553		<AdminAmount<T>>::remove(collection.id);554		<IsAdmin<T>>::remove_prefix((collection.id,), None);555		<Allowlist<T>>::remove_prefix((collection.id,), None);556557		<Pallet<T>>::deposit_event(Event::CollectionDestroyed(collection.id));558		Ok(())559	}560561	pub fn toggle_allowlist(562		collection: &CollectionHandle<T>,563		sender: &T::CrossAccountId,564		user: &T::CrossAccountId,565		allowed: bool,566	) -> DispatchResult {567		collection.check_is_owner_or_admin(sender)?;568569		// =========570571		if allowed {572			<Allowlist<T>>::insert((collection.id, user), true);573		} else {574			<Allowlist<T>>::remove((collection.id, user));575		}576577		Ok(())578	}579580	pub fn toggle_admin(581		collection: &CollectionHandle<T>,582		sender: &T::CrossAccountId,583		user: &T::CrossAccountId,584		admin: bool,585	) -> DispatchResult {586		collection.check_is_owner_or_admin(sender)?;587588		let was_admin = <IsAdmin<T>>::get((collection.id, user));589		if was_admin == admin {590			return Ok(());591		}592		let amount = <AdminAmount<T>>::get(collection.id);593594		if admin {595			let amount = amount596				.checked_add(1)597				.ok_or(<Error<T>>::CollectionAdminCountExceeded)?;598			ensure!(599				amount <= Self::collection_admins_limit(),600				<Error<T>>::CollectionAdminCountExceeded,601			);602603			// =========604605			<AdminAmount<T>>::insert(collection.id, amount);606			<IsAdmin<T>>::insert((collection.id, user), true);607		} else {608			<AdminAmount<T>>::insert(collection.id, amount.saturating_sub(1));609			<IsAdmin<T>>::remove((collection.id, user));610		}611612		Ok(())613	}614615	pub fn clamp_limits(616		mode: CollectionMode,617		old_limit: &CollectionLimits,618		mut new_limit: CollectionLimits,619	) -> Result<CollectionLimits, DispatchError> {620		macro_rules! limit_default {621				($old:ident, $new:ident, $($field:ident $(($arg:expr))? => $check:expr),* $(,)?) => {{622					$(623						if let Some($new) = $new.$field {624							let $old = $old.$field($($arg)?);625							let _ = $new;626							let _ = $old;627							$check628						} else {629							$new.$field = $old.$field630						}631					)*632				}};633			}634635		limit_default!(old_limit, new_limit,636			account_token_ownership_limit => ensure!(637				new_limit <= MAX_TOKEN_OWNERSHIP,638				<Error<T>>::CollectionLimitBoundsExceeded,639			),640			sponsor_transfer_timeout(match mode {641				CollectionMode::NFT => NFT_SPONSOR_TRANSFER_TIMEOUT,642				CollectionMode::Fungible(_) => FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,643				CollectionMode::ReFungible => REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,644			}) => ensure!(645				new_limit <= MAX_SPONSOR_TIMEOUT,646				<Error<T>>::CollectionLimitBoundsExceeded,647			),648			sponsored_data_size => ensure!(649				new_limit <= CUSTOM_DATA_LIMIT,650				<Error<T>>::CollectionLimitBoundsExceeded,651			),652			token_limit => ensure!(653				old_limit >= new_limit && new_limit > 0,654				<Error<T>>::CollectionTokenLimitExceeded655			),656			owner_can_transfer => ensure!(657				old_limit || !new_limit,658				<Error<T>>::OwnerPermissionsCantBeReverted,659			),660			owner_can_destroy => ensure!(661				old_limit || !new_limit,662				<Error<T>>::OwnerPermissionsCantBeReverted,663			),664			sponsored_data_rate_limit => {},665			transfers_enabled => {},666		);667		Ok(new_limit)668	}669}670671#[macro_export]672macro_rules! unsupported {673	() => {674		Err(<Error<T>>::UnsupportedOperation.into())675	};676}677678/// Worst cases679pub trait CommonWeightInfo<CrossAccountId> {680	fn create_item() -> Weight;681	fn create_multiple_items(amount: u32) -> Weight;682	fn create_multiple_items_ex(cost: &CreateItemExData<CrossAccountId>) -> Weight;683	fn burn_item() -> Weight;684	fn transfer() -> Weight;685	fn approve() -> Weight;686	fn transfer_from() -> Weight;687	fn burn_from() -> Weight;688	fn set_variable_metadata(bytes: u32) -> Weight;689}690691pub trait CommonCollectionOperations<T: Config> {692	fn create_item(693		&self,694		sender: T::CrossAccountId,695		to: T::CrossAccountId,696		data: CreateItemData,697	) -> DispatchResultWithPostInfo;698	fn create_multiple_items(699		&self,700		sender: T::CrossAccountId,701		to: T::CrossAccountId,702		data: Vec<CreateItemData>,703	) -> DispatchResultWithPostInfo;704	fn create_multiple_items_ex(705		&self,706		sender: T::CrossAccountId,707		data: CreateItemExData<T::CrossAccountId>,708	) -> DispatchResultWithPostInfo;709	fn burn_item(710		&self,711		sender: T::CrossAccountId,712		token: TokenId,713		amount: u128,714	) -> DispatchResultWithPostInfo;715716	fn transfer(717		&self,718		sender: T::CrossAccountId,719		to: T::CrossAccountId,720		token: TokenId,721		amount: u128,722	) -> DispatchResultWithPostInfo;723	fn approve(724		&self,725		sender: T::CrossAccountId,726		spender: T::CrossAccountId,727		token: TokenId,728		amount: u128,729	) -> DispatchResultWithPostInfo;730	fn transfer_from(731		&self,732		sender: T::CrossAccountId,733		from: T::CrossAccountId,734		to: T::CrossAccountId,735		token: TokenId,736		amount: u128,737	) -> DispatchResultWithPostInfo;738	fn burn_from(739		&self,740		sender: T::CrossAccountId,741		from: T::CrossAccountId,742		token: TokenId,743		amount: u128,744	) -> DispatchResultWithPostInfo;745746	fn set_variable_metadata(747		&self,748		sender: T::CrossAccountId,749		token: TokenId,750		data: BoundedVec<u8, CustomDataLimit>,751	) -> DispatchResultWithPostInfo;752753	fn account_tokens(&self, account: T::CrossAccountId) -> Vec<TokenId>;754	fn token_exists(&self, token: TokenId) -> bool;755	fn last_token_id(&self) -> TokenId;756757	fn token_owner(&self, token: TokenId) -> Option<T::CrossAccountId>;758	fn const_metadata(&self, token: TokenId) -> Vec<u8>;759	fn variable_metadata(&self, token: TokenId) -> Vec<u8>;760761	/// How many tokens collection contains (Applicable to nonfungible/refungible)762	fn collection_tokens(&self) -> u32;763	/// Amount of different tokens account has (Applicable to nonfungible/refungible)764	fn account_balance(&self, account: T::CrossAccountId) -> u32;765	/// Amount of specific token account have (Applicable to fungible/refungible)766	fn balance(&self, account: T::CrossAccountId, token: TokenId) -> u128;767	fn allowance(768		&self,769		sender: T::CrossAccountId,770		spender: T::CrossAccountId,771		token: TokenId,772	) -> u128;773}774775// Flexible enough for implementing CommonCollectionOperations776pub fn with_weight(res: DispatchResult, weight: Weight) -> DispatchResultWithPostInfo {777	let post_info = PostDispatchInfo {778		actual_weight: Some(weight),779		pays_fee: Pays::Yes,780	};781	match res {782		Ok(()) => Ok(post_info),783		Err(error) => Err(DispatchErrorWithPostInfo { post_info, error }),784	}785}
modifiedpallets/unique/src/common.rsdiffbeforeafterboth
--- a/pallets/unique/src/common.rs
+++ b/pallets/unique/src/common.rs
@@ -16,14 +16,14 @@
 
 use core::marker::PhantomData;
 use frame_support::{weights::Weight};
-use pallet_common::{CommonWeightInfo};
+use pallet_common::{CommonWeightInfo, dispatch::dispatch_weight};
 
 use pallet_fungible::{common::CommonWeights as FungibleWeights};
 use pallet_nonfungible::{common::CommonWeights as NonfungibleWeights};
 use pallet_refungible::{common::CommonWeights as RefungibleWeights};
 use up_data_structs::CreateItemExData;
 
-use crate::{Config, dispatch::dispatch_weight};
+use crate::Config;
 
 macro_rules! max_weight_of {
 	($method:ident ( $($args:tt)* )) => {
@@ -35,7 +35,7 @@
 
 pub struct CommonWeights<T: Config>(PhantomData<T>);
 impl<T: Config> CommonWeightInfo<T::CrossAccountId> for CommonWeights<T> {
-	fn create_item() -> up_data_structs::Weight {
+	fn create_item() -> Weight {
 		dispatch_weight::<T>() + max_weight_of!(create_item())
 	}
 
@@ -51,19 +51,19 @@
 		dispatch_weight::<T>() + max_weight_of!(burn_item())
 	}
 
-	fn transfer() -> up_data_structs::Weight {
+	fn transfer() -> Weight {
 		dispatch_weight::<T>() + max_weight_of!(transfer())
 	}
 
-	fn approve() -> up_data_structs::Weight {
+	fn approve() -> Weight {
 		dispatch_weight::<T>() + max_weight_of!(approve())
 	}
 
-	fn transfer_from() -> up_data_structs::Weight {
+	fn transfer_from() -> Weight {
 		dispatch_weight::<T>() + max_weight_of!(transfer_from())
 	}
 
-	fn set_variable_metadata(bytes: u32) -> up_data_structs::Weight {
+	fn set_variable_metadata(bytes: u32) -> Weight {
 		dispatch_weight::<T>() + max_weight_of!(set_variable_metadata(bytes))
 	}
 
deletedpallets/unique/src/dispatch.rsdiffbeforeafterboth
--- a/pallets/unique/src/dispatch.rs
+++ /dev/null
@@ -1,104 +0,0 @@
-// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.
-// This file is part of Unique Network.
-
-// Unique Network is free software: you can redistribute it and/or modify
-// it under the terms of the GNU General Public License as published by
-// the Free Software Foundation, either version 3 of the License, or
-// (at your option) any later version.
-
-// Unique Network is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-// GNU General Public License for more details.
-
-// You should have received a copy of the GNU General Public License
-// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
-
-use frame_support::{
-	dispatch::{DispatchErrorWithPostInfo, DispatchResultWithPostInfo},
-	traits::Get,
-	weights::Weight,
-};
-use up_data_structs::{CollectionId, CollectionMode, Pays, PostDispatchInfo};
-use pallet_common::{CollectionHandle, CommonCollectionOperations};
-use pallet_fungible::FungibleHandle;
-use pallet_nonfungible::NonfungibleHandle;
-use pallet_refungible::RefungibleHandle;
-
-use crate::Config;
-
-// TODO: move to benchmarking
-/// Price of [`dispatch_call`] call with noop `call` argument
-pub fn dispatch_weight<T: Config>() -> Weight {
-	// Read collection
-	<T as frame_system::Config>::DbWeight::get().reads(1)
-	// Dynamic dispatch?
-	+ 6_000_000
-	// submit_logs is measured as part of collection pallets
-}
-
-pub enum Dispatched<T: Config> {
-	Fungible(FungibleHandle<T>),
-	Nonfungible(NonfungibleHandle<T>),
-	Refungible(RefungibleHandle<T>),
-}
-impl<T: Config> Dispatched<T> {
-	pub fn dispatch(handle: CollectionHandle<T>) -> Self {
-		match handle.mode {
-			CollectionMode::Fungible(_) => Self::Fungible(FungibleHandle::cast(handle)),
-			CollectionMode::NFT => Self::Nonfungible(NonfungibleHandle::cast(handle)),
-			CollectionMode::ReFungible => Self::Refungible(RefungibleHandle::cast(handle)),
-		}
-	}
-	fn into_inner(self) -> CollectionHandle<T> {
-		match self {
-			Dispatched::Fungible(f) => f.into_inner(),
-			Dispatched::Nonfungible(f) => f.into_inner(),
-			Dispatched::Refungible(f) => f.into_inner(),
-		}
-	}
-	pub fn as_dyn(&self) -> &dyn CommonCollectionOperations<T> {
-		match self {
-			Dispatched::Fungible(h) => h,
-			Dispatched::Nonfungible(h) => h,
-			Dispatched::Refungible(h) => h,
-		}
-	}
-}
-
-/// Helper function to implement substrate calls for common collection methods
-pub fn dispatch_call<
-	T: Config,
-	C: FnOnce(&dyn pallet_common::CommonCollectionOperations<T>) -> DispatchResultWithPostInfo,
->(
-	collection: CollectionId,
-	call: C,
-) -> DispatchResultWithPostInfo {
-	let handle =
-		CollectionHandle::try_get(collection).map_err(|error| DispatchErrorWithPostInfo {
-			post_info: PostDispatchInfo {
-				actual_weight: Some(dispatch_weight::<T>()),
-				pays_fee: Pays::Yes,
-			},
-			error,
-		})?;
-	let dispatched = Dispatched::dispatch(handle);
-	let mut result = call(dispatched.as_dyn());
-	match &mut result {
-		Ok(PostDispatchInfo {
-			actual_weight: Some(weight),
-			..
-		})
-		| Err(DispatchErrorWithPostInfo {
-			post_info: PostDispatchInfo {
-				actual_weight: Some(weight),
-				..
-			},
-			..
-		}) => *weight += dispatch_weight::<T>(),
-		_ => {}
-	}
-
-	dispatched.into_inner().submit_logs();
-	result
-}
modifiedpallets/unique/src/eth/mod.rsdiffbeforeafterboth
--- a/pallets/unique/src/eth/mod.rs
+++ b/pallets/unique/src/eth/mod.rs
@@ -15,82 +15,3 @@
 // along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
 
 pub mod sponsoring;
-
-use fp_evm::PrecompileResult;
-use pallet_common::{
-	CollectionById,
-	erc::CommonEvmHandler,
-	eth::{map_eth_to_id, map_eth_to_token_id},
-};
-use pallet_fungible::FungibleHandle;
-use pallet_nonfungible::NonfungibleHandle;
-use pallet_refungible::{RefungibleHandle, erc::RefungibleTokenHandle};
-use sp_std::borrow::ToOwned;
-use sp_std::vec::Vec;
-use sp_core::{H160, U256};
-use crate::{CollectionMode, Config, dispatch::Dispatched};
-use pallet_common::CollectionHandle;
-
-pub struct UniqueErcSupport<T: Config>(core::marker::PhantomData<T>);
-
-impl<T: Config> pallet_evm::OnMethodCall<T> for UniqueErcSupport<T> {
-	fn is_reserved(target: &H160) -> bool {
-		map_eth_to_id(target).is_some()
-	}
-	fn is_used(target: &H160) -> bool {
-		map_eth_to_id(target)
-			.map(<CollectionById<T>>::contains_key)
-			.unwrap_or(false)
-	}
-	fn get_code(target: &H160) -> Option<Vec<u8>> {
-		if let Some(collection_id) = map_eth_to_id(target) {
-			let collection = <CollectionById<T>>::get(collection_id)?;
-			Some(
-				match collection.mode {
-					CollectionMode::NFT => <NonfungibleHandle<T>>::CODE,
-					CollectionMode::Fungible(_) => <FungibleHandle<T>>::CODE,
-					CollectionMode::ReFungible => <RefungibleHandle<T>>::CODE,
-				}
-				.to_owned(),
-			)
-		} else if let Some((collection_id, _token_id)) = map_eth_to_token_id(target) {
-			let collection = <CollectionById<T>>::get(collection_id)?;
-			if collection.mode != CollectionMode::ReFungible {
-				return None;
-			}
-			// TODO: check token existence
-			Some(<RefungibleTokenHandle<T>>::CODE.to_owned())
-		} else {
-			None
-		}
-	}
-	fn call(
-		source: &H160,
-		target: &H160,
-		gas_limit: u64,
-		input: &[u8],
-		value: U256,
-	) -> Option<PrecompileResult> {
-		if let Some(collection_id) = map_eth_to_id(target) {
-			let collection = <CollectionHandle<T>>::new_with_gas_limit(collection_id, gas_limit)?;
-			let dispatched = Dispatched::dispatch(collection);
-
-			match dispatched {
-				Dispatched::Fungible(h) => h.call(source, input, value),
-				Dispatched::Nonfungible(h) => h.call(source, input, value),
-				Dispatched::Refungible(h) => h.call(source, input, value),
-			}
-		} else if let Some((collection_id, token_id)) = map_eth_to_token_id(target) {
-			let collection = <CollectionHandle<T>>::new_with_gas_limit(collection_id, gas_limit)?;
-			if collection.mode != CollectionMode::ReFungible {
-				return None;
-			}
-
-			let handle = RefungibleHandle::cast(collection);
-			// TODO: check token existence
-			RefungibleTokenHandle(handle, token_id).call(source, input, value)
-		} else {
-			None
-		}
-	}
-}
modifiedpallets/unique/src/eth/sponsoring.rsdiffbeforeafterboth
--- a/pallets/unique/src/eth/sponsoring.rs
+++ b/pallets/unique/src/eth/sponsoring.rs
@@ -25,6 +25,7 @@
 use core::marker::PhantomData;
 use core::convert::TryInto;
 use pallet_evm::account::CrossAccountId;
+use up_data_structs::{TokenId, CreateItemData, CreateNftData};
 
 use pallet_nonfungible::erc::{
 	UniqueNFTCall, ERC721UniqueExtensionsCall, ERC721MintableCall, ERC721Call,
modifiedpallets/unique/src/lib.rsdiffbeforeafterboth
--- a/pallets/unique/src/lib.rs
+++ b/pallets/unique/src/lib.rs
@@ -26,20 +26,12 @@
 
 pub use serde::{Serialize, Deserialize};
 
-pub use frame_support::{
-	construct_runtime, decl_module, decl_storage, decl_error, decl_event,
+use frame_support::{
+	decl_module, decl_storage, decl_error, decl_event,
 	dispatch::DispatchResult,
-	ensure, fail, parameter_types,
-	traits::{
-		ExistenceRequirement, Get, Imbalance, KeyOwnerProofSystem, OnUnbalanced, Randomness,
-		IsSubType, WithdrawReasons,
-	},
-	weights::{
-		constants::{BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight, WEIGHT_PER_SECOND},
-		DispatchInfo, GetDispatchInfo, IdentityFee, Pays, PostDispatchInfo, Weight,
-		WeightToFeePolynomial, DispatchClass,
-	},
-	StorageValue, transactional,
+	ensure,
+	weights::{Weight},
+	transactional,
 	pallet_prelude::{DispatchResultWithPostInfo, ConstU32},
 	BoundedVec,
 };
@@ -47,17 +39,17 @@
 use frame_system::{self as system, ensure_signed};
 use sp_runtime::{sp_std::prelude::Vec};
 use up_data_structs::{
-	MAX_DECIMAL_POINTS, VARIABLE_ON_CHAIN_SCHEMA_LIMIT, CONST_ON_CHAIN_SCHEMA_LIMIT,
-	OFFCHAIN_SCHEMA_LIMIT, MAX_COLLECTION_NAME_LENGTH, MAX_COLLECTION_DESCRIPTION_LENGTH,
-	MAX_TOKEN_PREFIX_LENGTH, AccessMode, CreateItemData, CollectionLimits, CollectionId,
-	CollectionMode, TokenId, SchemaVersion, SponsorshipState, MetaUpdatePermission,
-	CreateCollectionData, CustomDataLimit, CreateItemExData,
+	VARIABLE_ON_CHAIN_SCHEMA_LIMIT, CONST_ON_CHAIN_SCHEMA_LIMIT, OFFCHAIN_SCHEMA_LIMIT,
+	MAX_COLLECTION_NAME_LENGTH, MAX_COLLECTION_DESCRIPTION_LENGTH, MAX_TOKEN_PREFIX_LENGTH,
+	AccessMode, CreateItemData, CollectionLimits, CollectionId, CollectionMode, TokenId,
+	SchemaVersion, SponsorshipState, MetaUpdatePermission, CreateCollectionData, CustomDataLimit,
+	CreateItemExData,
 };
-use pallet_common::{CollectionHandle, Pallet as PalletCommon, Error as CommonError, CommonWeightInfo};
 use pallet_evm::account::CrossAccountId;
-use pallet_refungible::{Pallet as PalletRefungible, RefungibleHandle};
-use pallet_fungible::{Pallet as PalletFungible, FungibleHandle};
-use pallet_nonfungible::{Pallet as PalletNonfungible, NonfungibleHandle};
+use pallet_common::{
+	CollectionHandle, Pallet as PalletCommon, Error as CommonError, CommonWeightInfo,
+	dispatch::dispatch_call, dispatch::CollectionDispatch,
+};
 
 #[cfg(test)]
 mod mock;
@@ -70,12 +62,8 @@
 pub use sponsorship::{UniqueSponsorshipHandler, UniqueSponsorshipPredict};
 pub use eth::sponsoring::UniqueEthSponsorshipHandler;
 
-pub use eth::UniqueErcSupport;
-
 pub mod common;
 use common::CommonWeights;
-pub mod dispatch;
-use dispatch::dispatch_call;
 
 #[cfg(feature = "runtime-benchmarks")]
 mod benchmarking;
@@ -352,19 +340,11 @@
 		#[weight = <SelfWeightOf<T>>::create_collection()]
 		#[transactional]
 		pub fn create_collection_ex(origin, data: CreateCollectionData<T::AccountId>) -> DispatchResult {
-			let owner = ensure_signed(origin)?;
+			let sender = ensure_signed(origin)?;
+
+			// =========
 
-			let _id = match data.mode {
-				CollectionMode::NFT => {<PalletNonfungible<T>>::init_collection(owner, data)?},
-				CollectionMode::Fungible(decimal_points) => {
-					// check params
-					ensure!(decimal_points <= MAX_DECIMAL_POINTS, Error::<T>::CollectionDecimalPointLimitExceeded);
-					<PalletFungible<T>>::init_collection(owner, data)?
-				}
-				CollectionMode::ReFungible => {
-					<PalletRefungible<T>>::init_collection(owner, data)?
-				}
-			};
+			T::CollectionDispatch::create(sender, data)?;
 
 			Ok(())
 		}
@@ -382,17 +362,11 @@
 		#[transactional]
 		pub fn destroy_collection(origin, collection_id: CollectionId) -> DispatchResult {
 			let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);
-
 			let collection = <CollectionHandle<T>>::try_get(collection_id)?;
-			collection.check_is_owner(&sender)?;
 
 			// =========
 
-			match collection.mode {
-				CollectionMode::ReFungible => PalletRefungible::destroy_collection(RefungibleHandle::cast(collection), &sender)?,
-				CollectionMode::Fungible(_) => PalletFungible::destroy_collection(FungibleHandle::cast(collection), &sender)?,
-				CollectionMode::NFT => PalletNonfungible::destroy_collection(NonfungibleHandle::cast(collection), &sender)?,
-			}
+			T::CollectionDispatch::destroy(sender, collection)?;
 
 			<NftTransferBasket<T>>::remove_prefix(collection_id, None);
 			<FungibleTransferBasket<T>>::remove_prefix(collection_id, None);
modifiedruntime/common/Cargo.tomldiffbeforeafterboth
--- a/runtime/common/Cargo.toml
+++ b/runtime/common/Cargo.toml
@@ -12,12 +12,19 @@
 default = ['std']
 std = [
     'sp-core/std',
+    'sp-std/std',
     'sp-runtime/std',
     'codec/std',
     'frame-support/std',
     'frame-system/std',
     'sp-consensus-aura/std',
     'pallet-common/std',
+    'pallet-unique/std',
+    'pallet-fungible/std',
+    'pallet-nonfungible/std',
+    'pallet-refungible/std',
+    'up-data-structs/std',
+    'pallet-evm/std',
     'fp-rpc/std',
 ]
 runtime-benchmarks = [
@@ -31,6 +38,11 @@
 git = "https://github.com/paritytech/substrate"
 branch = "polkadot-v0.9.20"
 
+[dependencies.sp-std]
+default-features = false
+git = 'https://github.com/paritytech/substrate.git'
+branch = 'polkadot-v0.9.17'
+
 [dependencies.sp-runtime]
 default-features = false
 git = "https://github.com/paritytech/substrate"
@@ -61,6 +73,31 @@
 default-features = false
 path = "../../pallets/common"
 
+[dependencies.pallet-unique]
+default-features = false
+path = "../../pallets/unique"
+
+[dependencies.pallet-fungible]
+default-features = false
+path = "../../pallets/fungible"
+
+[dependencies.pallet-nonfungible]
+default-features = false
+path = "../../pallets/nonfungible"
+
+[dependencies.pallet-refungible]
+default-features = false
+path = "../../pallets/refungible"
+
+[dependencies.up-data-structs]
+default-features = false
+path = "../../primitives/data-structs"
+
+[dependencies.pallet-evm]
+default-features = false
+git = "https://github.com/uniquenetwork/frontier.git"
+branch = "unique-polkadot-v0.9.17"
+
 [dependencies.sp-consensus-aura]
 default-features = false
 git = "https://github.com/paritytech/substrate"
addedruntime/common/src/dispatch.rsdiffbeforeafterboth
--- /dev/null
+++ b/runtime/common/src/dispatch.rs
@@ -0,0 +1,160 @@
+use frame_support::{dispatch::DispatchResult, ensure};
+use pallet_evm::PrecompileResult;
+use sp_core::{H160, U256};
+use sp_std::{borrow::ToOwned, vec::Vec};
+use pallet_common::{
+	CollectionById, CollectionHandle, CommonCollectionOperations, erc::CommonEvmHandler,
+	eth::map_eth_to_id,
+};
+pub use pallet_common::dispatch::CollectionDispatch;
+use pallet_fungible::{Pallet as PalletFungible, FungibleHandle};
+use pallet_nonfungible::{Pallet as PalletNonfungible, NonfungibleHandle};
+use pallet_refungible::{Pallet as PalletRefungible, RefungibleHandle, erc::RefungibleTokenHandle};
+use up_data_structs::{
+	CollectionMode, CreateCollectionData, MAX_DECIMAL_POINTS, mapping::TokenAddressMapping,
+};
+
+pub enum CollectionDispatchT<T>
+where
+	T: pallet_fungible::Config + pallet_nonfungible::Config + pallet_refungible::Config,
+{
+	Fungible(FungibleHandle<T>),
+	Nonfungible(NonfungibleHandle<T>),
+	Refungible(RefungibleHandle<T>),
+}
+impl<T> CollectionDispatch<T> for CollectionDispatchT<T>
+where
+	T: pallet_common::Config
+		+ pallet_unique::Config
+		+ pallet_fungible::Config
+		+ pallet_nonfungible::Config
+		+ pallet_refungible::Config,
+{
+	fn create(sender: T::AccountId, data: CreateCollectionData<T::AccountId>) -> DispatchResult {
+		let _id = match data.mode {
+			CollectionMode::NFT => <PalletNonfungible<T>>::init_collection(sender, data)?,
+			CollectionMode::Fungible(decimal_points) => {
+				// check params
+				ensure!(
+					decimal_points <= MAX_DECIMAL_POINTS,
+					pallet_unique::Error::<T>::CollectionDecimalPointLimitExceeded
+				);
+				<PalletFungible<T>>::init_collection(sender, data)?
+			}
+			CollectionMode::ReFungible => <PalletRefungible<T>>::init_collection(sender, data)?,
+		};
+		Ok(())
+	}
+
+	fn destroy(sender: T::CrossAccountId, collection: CollectionHandle<T>) -> DispatchResult {
+		match collection.mode {
+			CollectionMode::ReFungible => {
+				PalletRefungible::destroy_collection(RefungibleHandle::cast(collection), &sender)?
+			}
+			CollectionMode::Fungible(_) => {
+				PalletFungible::destroy_collection(FungibleHandle::cast(collection), &sender)?
+			}
+			CollectionMode::NFT => {
+				PalletNonfungible::destroy_collection(NonfungibleHandle::cast(collection), &sender)?
+			}
+		}
+		Ok(())
+	}
+
+	fn dispatch(handle: CollectionHandle<T>) -> Self {
+		match handle.mode {
+			CollectionMode::Fungible(_) => Self::Fungible(FungibleHandle::cast(handle)),
+			CollectionMode::NFT => Self::Nonfungible(NonfungibleHandle::cast(handle)),
+			CollectionMode::ReFungible => Self::Refungible(RefungibleHandle::cast(handle)),
+		}
+	}
+
+	fn into_inner(self) -> CollectionHandle<T> {
+		match self {
+			Self::Fungible(f) => f.into_inner(),
+			Self::Nonfungible(f) => f.into_inner(),
+			Self::Refungible(f) => f.into_inner(),
+		}
+	}
+
+	fn as_dyn(&self) -> &dyn CommonCollectionOperations<T> {
+		match self {
+			Self::Fungible(h) => h,
+			Self::Nonfungible(h) => h,
+			Self::Refungible(h) => h,
+		}
+	}
+}
+
+impl<T> pallet_evm::OnMethodCall<T> for CollectionDispatchT<T>
+where
+	T: pallet_common::Config
+		+ pallet_unique::Config
+		+ pallet_fungible::Config
+		+ pallet_nonfungible::Config
+		+ pallet_refungible::Config,
+{
+	fn is_reserved(target: &H160) -> bool {
+		map_eth_to_id(target).is_some()
+	}
+	fn is_used(target: &H160) -> bool {
+		map_eth_to_id(target)
+			.map(<CollectionById<T>>::contains_key)
+			.unwrap_or(false)
+	}
+	fn get_code(target: &H160) -> Option<Vec<u8>> {
+		if let Some(collection_id) = map_eth_to_id(target) {
+			let collection = <CollectionById<T>>::get(collection_id)?;
+			Some(
+				match collection.mode {
+					CollectionMode::NFT => <NonfungibleHandle<T>>::CODE,
+					CollectionMode::Fungible(_) => <FungibleHandle<T>>::CODE,
+					CollectionMode::ReFungible => <RefungibleHandle<T>>::CODE,
+				}
+				.to_owned(),
+			)
+		} else if let Some((collection_id, _token_id)) =
+			<T as pallet_common::Config>::EvmTokenAddressMapping::address_to_token(target)
+		{
+			let collection = <CollectionById<T>>::get(collection_id)?;
+			if collection.mode != CollectionMode::ReFungible {
+				return None;
+			}
+			// TODO: check token existence
+			Some(<RefungibleTokenHandle<T>>::CODE.to_owned())
+		} else {
+			None
+		}
+	}
+	fn call(
+		source: &H160,
+		target: &H160,
+		gas_limit: u64,
+		input: &[u8],
+		value: U256,
+	) -> Option<PrecompileResult> {
+		if let Some(collection_id) = map_eth_to_id(target) {
+			let collection = <CollectionHandle<T>>::new_with_gas_limit(collection_id, gas_limit)?;
+			let dispatched = Self::dispatch(collection);
+
+			match dispatched {
+				Self::Fungible(h) => h.call(source, input, value),
+				Self::Nonfungible(h) => h.call(source, input, value),
+				Self::Refungible(h) => h.call(source, input, value),
+			}
+		} else if let Some((collection_id, token_id)) =
+			<T as pallet_common::Config>::EvmTokenAddressMapping::address_to_token(target)
+		{
+			let collection = <CollectionHandle<T>>::new_with_gas_limit(collection_id, gas_limit)?;
+			if collection.mode != CollectionMode::ReFungible {
+				return None;
+			}
+
+			let handle = RefungibleHandle::cast(collection);
+			// TODO: check token existence
+			RefungibleTokenHandle(handle, token_id).call(source, input, value)
+		} else {
+			None
+		}
+	}
+}
modifiedruntime/common/src/lib.rsdiffbeforeafterboth
--- a/runtime/common/src/lib.rs
+++ b/runtime/common/src/lib.rs
@@ -1,5 +1,6 @@
 #![cfg_attr(not(feature = "std"), no_std)]
 
 pub mod constants;
+pub mod dispatch;
 pub mod runtime_apis;
 pub mod types;
modifiedruntime/opal/src/lib.rsdiffbeforeafterboth
--- a/runtime/opal/src/lib.rs
+++ b/runtime/opal/src/lib.rs
@@ -58,7 +58,7 @@
 	traits::{
 		tokens::currency::Currency as CurrencyT, OnUnbalanced as OnUnbalancedT, Everything,
 		Currency, ExistenceRequirement, Get, IsInVec, KeyOwnerProofSystem, LockIdentifier,
-		OnUnbalanced, Randomness, FindAuthor,
+		OnUnbalanced, Randomness, FindAuthor, ConstU32, Imbalance,
 	},
 	weights::{
 		constants::{BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight, WEIGHT_PER_SECOND},
@@ -66,7 +66,7 @@
 		WeightToFeePolynomial, WeightToFeeCoefficient, WeightToFeeCoefficients, ConstantMultiplier,
 	},
 };
-use up_data_structs::*;
+use up_data_structs::{CollectionId, TokenId, CollectionStats, Collection};
 // use pallet_contracts::weights::WeightInfo;
 // #[cfg(any(feature = "std", test))]
 use frame_system::{
@@ -114,7 +114,12 @@
 //use xcm_executor::traits::MatchesFungible;
 use sp_runtime::traits::CheckedConversion;
 
-use unique_runtime_common::{impl_common_runtime_apis, types::*, constants::*};
+use unique_runtime_common::{
+	impl_common_runtime_apis,
+	types::*,
+	constants::*,
+	dispatch::{CollectionDispatchT, CollectionDispatch},
+};
 
 pub const RUNTIME_NAME: &str = "opal";
 pub const TOKEN_SYMBOL: &str = "OPL";
@@ -295,8 +300,8 @@
 	type Event = Event;
 	type OnMethodCall = (
 		pallet_evm_migration::OnMethodCall<Self>,
-		pallet_unique::UniqueErcSupport<Self>,
 		pallet_evm_contract_helpers::HelpersOnMethodCall<Self>,
+		CollectionDispatchT<Self>,
 	);
 	type OnCreate = pallet_evm_contract_helpers::HelpersOnCreate<Self>;
 	type ChainId = ChainId;
@@ -871,8 +876,18 @@
 	type Currency = Balances;
 	type CollectionCreationPrice = CollectionCreationPrice;
 	type TreasuryAccountId = TreasuryAccountId;
+	type CollectionDispatch = CollectionDispatchT<Self>;
+
+	type EvmTokenAddressMapping = EvmTokenAddressMapping;
+	type CrossTokenAddressMapping = CrossTokenAddressMapping<Self::AccountId>;
 }
 
+impl pallet_structure::Config for Runtime {
+	type Event = Event;
+	type Call = Call;
+	type WeightInfo = pallet_structure::weights::SubstrateWeight<Self>;
+}
+
 impl pallet_fungible::Config for Runtime {
 	type WeightInfo = pallet_fungible::weights::SubstrateWeight<Self>;
 }
@@ -1119,9 +1134,7 @@
 
 macro_rules! dispatch_unique_runtime {
 	($collection:ident.$method:ident($($name:ident),*)) => {{
-		use pallet_unique::dispatch::Dispatched;
-
-		let collection = Dispatched::dispatch(<pallet_common::CollectionHandle<Runtime>>::try_get($collection)?);
+		let collection = <Runtime as pallet_common::Config>::CollectionDispatch::dispatch(<pallet_common::CollectionHandle<Runtime>>::try_get($collection)?);
 		let dispatch = collection.as_dyn();
 
 		Ok(dispatch.$method($($name),*))
modifiedruntime/quartz/src/lib.rsdiffbeforeafterboth
--- a/runtime/quartz/src/lib.rs
+++ b/runtime/quartz/src/lib.rs
@@ -58,7 +58,7 @@
 	traits::{
 		tokens::currency::Currency as CurrencyT, OnUnbalanced as OnUnbalancedT, Everything,
 		Currency, ExistenceRequirement, Get, IsInVec, KeyOwnerProofSystem, LockIdentifier,
-		OnUnbalanced, Randomness, FindAuthor,
+		OnUnbalanced, Randomness, FindAuthor, ConstU32, Imbalance,
 	},
 	weights::{
 		constants::{BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight, WEIGHT_PER_SECOND},
@@ -66,6 +66,7 @@
 		WeightToFeePolynomial, WeightToFeeCoefficient, WeightToFeeCoefficients, ConstantMultiplier,
 	},
 };
+use unique_runtime_common::dispatch::{CollectionDispatchT, CollectionDispatch};
 use up_data_structs::*;
 // use pallet_contracts::weights::WeightInfo;
 // #[cfg(any(feature = "std", test))]
@@ -92,6 +93,7 @@
 // Polkadot imports
 use pallet_xcm::XcmPassthrough;
 use polkadot_parachain::primitives::Sibling;
+use up_data_structs::mapping::{CrossTokenAddressMapping, EvmTokenAddressMapping};
 use xcm::v1::{BodyId, Junction::*, MultiLocation, NetworkId, Junctions::*};
 use xcm_builder::{
 	AccountId32Aliases, AllowTopLevelPaidExecutionFrom, AllowUnpaidExecutionFrom, CurrencyAdapter,
@@ -274,8 +276,8 @@
 	type Event = Event;
 	type OnMethodCall = (
 		pallet_evm_migration::OnMethodCall<Self>,
-		pallet_unique::UniqueErcSupport<Self>,
 		pallet_evm_contract_helpers::HelpersOnMethodCall<Self>,
+		CollectionDispatchT<Self>,
 	);
 	type OnCreate = pallet_evm_contract_helpers::HelpersOnCreate<Self>;
 	type ChainId = ChainId;
@@ -851,8 +853,18 @@
 	type Currency = Balances;
 	type CollectionCreationPrice = CollectionCreationPrice;
 	type TreasuryAccountId = TreasuryAccountId;
+	type CollectionDispatch = CollectionDispatchT<Self>;
+
+	type EvmTokenAddressMapping = EvmTokenAddressMapping;
+	type CrossTokenAddressMapping = CrossTokenAddressMapping<Self::AccountId>;
 }
 
+impl pallet_structure::Config for Runtime {
+	type Event = Event;
+	type Call = Call;
+	type WeightInfo = pallet_structure::weights::SubstrateWeight<Self>;
+}
+
 impl pallet_evm::account::Config for Runtime {
 	type CrossAccountId = pallet_evm::account::BasicCrossAccountId<Self>;
 	type EvmAddressMapping = HashedAddressMapping<Self::Hashing>;
@@ -979,6 +991,7 @@
 		Fungible: pallet_fungible::{Pallet, Storage} = 67,
 		Refungible: pallet_refungible::{Pallet, Storage} = 68,
 		Nonfungible: pallet_nonfungible::{Pallet, Storage} = 69,
+		Structure: pallet_structure::{Pallet, Call, Storage, Event<T>} = 70,
 
 		// Frontier
 		EVM: pallet_evm::{Pallet, Config, Call, Storage, Event<T>} = 100,
@@ -1105,9 +1118,7 @@
 
 macro_rules! dispatch_unique_runtime {
 	($collection:ident.$method:ident($($name:ident),*)) => {{
-		use pallet_unique::dispatch::Dispatched;
-
-		let collection = Dispatched::dispatch(<pallet_common::CollectionHandle<Runtime>>::try_get($collection)?);
+		let collection = <Runtime as pallet_common::Config>::CollectionDispatch::dispatch(<pallet_common::CollectionHandle<Runtime>>::try_get($collection)?);
 		let dispatch = collection.as_dyn();
 
 		Ok(dispatch.$method($($name),*))
modifiedruntime/unique/src/lib.rsdiffbeforeafterboth
--- a/runtime/unique/src/lib.rs
+++ b/runtime/unique/src/lib.rs
@@ -58,7 +58,7 @@
 	traits::{
 		tokens::currency::Currency as CurrencyT, OnUnbalanced as OnUnbalancedT, Everything,
 		Currency, ExistenceRequirement, Get, IsInVec, KeyOwnerProofSystem, LockIdentifier,
-		OnUnbalanced, Randomness, FindAuthor,
+		OnUnbalanced, Randomness, FindAuthor, ConstU32, Imbalance,
 	},
 	weights::{
 		constants::{BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight, WEIGHT_PER_SECOND},
@@ -66,6 +66,7 @@
 		WeightToFeePolynomial, WeightToFeeCoefficient, WeightToFeeCoefficients, ConstantMultiplier,
 	},
 };
+use unique_runtime_common::dispatch::{CollectionDispatchT, CollectionDispatch};
 use up_data_structs::*;
 // use pallet_contracts::weights::WeightInfo;
 // #[cfg(any(feature = "std", test))]
@@ -91,6 +92,7 @@
 // Polkadot imports
 use pallet_xcm::XcmPassthrough;
 use polkadot_parachain::primitives::Sibling;
+use up_data_structs::mapping::{CrossTokenAddressMapping, EvmTokenAddressMapping};
 use xcm::v1::{BodyId, Junction::*, MultiLocation, NetworkId, Junctions::*};
 use xcm_builder::{
 	AccountId32Aliases, AllowTopLevelPaidExecutionFrom, AllowUnpaidExecutionFrom, CurrencyAdapter,
@@ -273,8 +275,8 @@
 	type Event = Event;
 	type OnMethodCall = (
 		pallet_evm_migration::OnMethodCall<Self>,
-		pallet_unique::UniqueErcSupport<Self>,
 		pallet_evm_contract_helpers::HelpersOnMethodCall<Self>,
+		CollectionDispatchT<Self>,
 	);
 	type OnCreate = pallet_evm_contract_helpers::HelpersOnCreate<Self>;
 	type ChainId = ChainId;
@@ -849,8 +851,18 @@
 	type Currency = Balances;
 	type CollectionCreationPrice = CollectionCreationPrice;
 	type TreasuryAccountId = TreasuryAccountId;
+	type CollectionDispatch = CollectionDispatchT<Self>;
+
+	type EvmTokenAddressMapping = EvmTokenAddressMapping;
+	type CrossTokenAddressMapping = CrossTokenAddressMapping<Self::AccountId>;
 }
 
+impl pallet_structure::Config for Runtime {
+	type Event = Event;
+	type Call = Call;
+	type WeightInfo = pallet_structure::weights::SubstrateWeight<Self>;
+}
+
 impl pallet_evm::account::Config for Runtime {
 	type CrossAccountId = pallet_evm::account::BasicCrossAccountId<Self>;
 	type EvmAddressMapping = HashedAddressMapping<Self::Hashing>;
@@ -977,6 +989,7 @@
 		Fungible: pallet_fungible::{Pallet, Storage} = 67,
 		Refungible: pallet_refungible::{Pallet, Storage} = 68,
 		Nonfungible: pallet_nonfungible::{Pallet, Storage} = 69,
+		Structure: pallet_structure::{Pallet, Call, Storage, Event<T>} = 70,
 
 		// Frontier
 		EVM: pallet_evm::{Pallet, Config, Call, Storage, Event<T>} = 100,
@@ -1103,9 +1116,7 @@
 
 macro_rules! dispatch_unique_runtime {
 	($collection:ident.$method:ident($($name:ident),*)) => {{
-		use pallet_unique::dispatch::Dispatched;
-
-		let collection = Dispatched::dispatch(<pallet_common::CollectionHandle<Runtime>>::try_get($collection)?);
+		let collection = <Runtime as pallet_common::Config>::CollectionDispatch::dispatch(<pallet_common::CollectionHandle<Runtime>>::try_get($collection)?);
 		let dispatch = collection.as_dyn();
 
 		Ok(dispatch.$method($($name),*))