git.delta.rocks / unique-network / refs/commits / 7680e6689f4d

difftreelog

refactor Generalization some operations.

Trubnikov Sergey2022-12-08parent: #1f2b5fa.patch.diff
in: master

13 files changed

modifiedpallets/common/src/erc.rsdiffbeforeafterboth
--- a/pallets/common/src/erc.rs
+++ b/pallets/common/src/erc.rs
@@ -222,12 +222,11 @@
 	fn set_collection_sponsor(&mut self, caller: caller, sponsor: address) -> Result<void> {
 		self.consume_store_reads_and_writes(1, 1)?;
 
-		check_is_owner_or_admin(caller, self)?;
+		let caller = T::CrossAccountId::from_eth(caller);
 
 		let sponsor = T::CrossAccountId::from_eth(sponsor);
-		self.set_sponsor(sponsor.as_sub().clone())
-			.map_err(dispatch_to_evm::<T>)?;
-		save(self)
+		self.set_sponsor(&caller, sponsor.as_sub().clone())
+			.map_err(dispatch_to_evm::<T>)
 	}
 
 	/// Set the sponsor of the collection.
@@ -242,12 +241,11 @@
 	) -> Result<void> {
 		self.consume_store_reads_and_writes(1, 1)?;
 
-		check_is_owner_or_admin(caller, self)?;
+		let caller = T::CrossAccountId::from_eth(caller);
 
 		let sponsor = sponsor.into_sub_cross_account::<T>()?;
-		self.set_sponsor(sponsor.as_sub().clone())
-			.map_err(dispatch_to_evm::<T>)?;
-		save(self)
+		self.set_sponsor(&caller, sponsor.as_sub().clone())
+			.map_err(dispatch_to_evm::<T>)
 	}
 
 	/// Whether there is a pending sponsor.
@@ -265,21 +263,15 @@
 		self.consume_store_writes(1)?;
 
 		let caller = T::CrossAccountId::from_eth(caller);
-		if !self
-			.confirm_sponsorship(caller.as_sub())
-			.map_err(dispatch_to_evm::<T>)?
-		{
-			return Err("caller is not set as sponsor".into());
-		}
-		save(self)
+		self.confirm_sponsorship(caller.as_sub())
+			.map_err(dispatch_to_evm::<T>)
 	}
 
 	/// Remove collection sponsor.
 	fn remove_collection_sponsor(&mut self, caller: caller) -> Result<void> {
 		self.consume_store_reads_and_writes(1, 1)?;
-		check_is_owner_or_admin(caller, self)?;
-		self.remove_sponsor().map_err(dispatch_to_evm::<T>)?;
-		save(self)
+		let caller = T::CrossAccountId::from_eth(caller);
+		self.remove_sponsor(&caller).map_err(dispatch_to_evm::<T>)
 	}
 
 	/// Get current sponsor.
@@ -333,7 +325,6 @@
 			}
 		};
 
-		check_is_owner_or_admin(caller, self)?;
 		let mut limits = self.limits.clone();
 
 		match limit.as_str() {
@@ -366,9 +357,9 @@
 			}
 			_ => return Err(Error::Revert(format!("unknown limit \"{}\"", limit))),
 		}
-		self.limits = <Pallet<T>>::clamp_limits(self.mode.clone(), &self.limits, limits)
-			.map_err(dispatch_to_evm::<T>)?;
-		save(self)
+
+		let caller = T::CrossAccountId::from_eth(caller);
+		<Pallet<T>>::update_limits(&caller, self, limits).map_err(dispatch_to_evm::<T>)
 	}
 
 	/// Get contract address.
@@ -383,7 +374,7 @@
 		caller: caller,
 		new_admin: EthCrossAccount,
 	) -> Result<void> {
-		self.consume_store_writes(2)?;
+		self.consume_store_reads_and_writes(2, 2)?;
 
 		let caller = T::CrossAccountId::from_eth(caller);
 		let new_admin = new_admin.into_sub_cross_account::<T>()?;
@@ -398,7 +389,7 @@
 		caller: caller,
 		admin: EthCrossAccount,
 	) -> Result<void> {
-		self.consume_store_writes(2)?;
+		self.consume_store_reads_and_writes(2, 2)?;
 
 		let caller = T::CrossAccountId::from_eth(caller);
 		let admin = admin.into_sub_cross_account::<T>()?;
@@ -410,7 +401,7 @@
 	/// @param newAdmin Address of the added administrator.
 	#[solidity(hide)]
 	fn add_collection_admin(&mut self, caller: caller, new_admin: address) -> Result<void> {
-		self.consume_store_writes(2)?;
+		self.consume_store_reads_and_writes(2, 2)?;
 
 		let caller = T::CrossAccountId::from_eth(caller);
 		let new_admin = T::CrossAccountId::from_eth(new_admin);
@@ -423,7 +414,7 @@
 	/// @param admin Address of the removed administrator.
 	#[solidity(hide)]
 	fn remove_collection_admin(&mut self, caller: caller, admin: address) -> Result<void> {
-		self.consume_store_writes(2)?;
+		self.consume_store_reads_and_writes(2, 2)?;
 
 		let caller = T::CrossAccountId::from_eth(caller);
 		let admin = T::CrossAccountId::from_eth(admin);
@@ -438,7 +429,7 @@
 	fn set_nesting_bool(&mut self, caller: caller, enable: bool) -> Result<void> {
 		self.consume_store_reads_and_writes(1, 1)?;
 
-		check_is_owner_or_admin(caller, self)?;
+		let caller = T::CrossAccountId::from_eth(caller);
 
 		let mut permissions = self.collection.permissions.clone();
 		let mut nesting = permissions.nesting().clone();
@@ -446,14 +437,7 @@
 		nesting.restricted = None;
 		permissions.nesting = Some(nesting);
 
-		self.collection.permissions = <Pallet<T>>::clamp_permissions(
-			self.collection.mode.clone(),
-			&self.collection.permissions,
-			permissions,
-		)
-		.map_err(dispatch_to_evm::<T>)?;
-
-		save(self)
+		<Pallet<T>>::update_permissions(&caller, self, permissions).map_err(dispatch_to_evm::<T>)
 	}
 
 	/// Toggle accessibility of collection nesting.
@@ -472,7 +456,7 @@
 		if collections.is_empty() {
 			return Err("no addresses provided".into());
 		}
-		check_is_owner_or_admin(caller, self)?;
+		let caller = T::CrossAccountId::from_eth(caller);
 
 		let mut permissions = self.collection.permissions.clone();
 		match enable {
@@ -497,14 +481,7 @@
 			}
 		};
 
-		self.collection.permissions = <Pallet<T>>::clamp_permissions(
-			self.collection.mode.clone(),
-			&self.collection.permissions,
-			permissions,
-		)
-		.map_err(dispatch_to_evm::<T>)?;
-
-		save(self)
+		<Pallet<T>>::update_permissions(&caller, self, permissions).map_err(dispatch_to_evm::<T>)
 	}
 
 	/// Set the collection access method.
@@ -514,7 +491,7 @@
 	fn set_collection_access(&mut self, caller: caller, mode: uint8) -> Result<void> {
 		self.consume_store_reads_and_writes(1, 1)?;
 
-		check_is_owner_or_admin(caller, self)?;
+		let caller = T::CrossAccountId::from_eth(caller);
 		let permissions = CollectionPermissions {
 			access: Some(match mode {
 				0 => AccessMode::Normal,
@@ -523,14 +500,7 @@
 			}),
 			..Default::default()
 		};
-		self.collection.permissions = <Pallet<T>>::clamp_permissions(
-			self.collection.mode.clone(),
-			&self.collection.permissions,
-			permissions,
-		)
-		.map_err(dispatch_to_evm::<T>)?;
-
-		save(self)
+		<Pallet<T>>::update_permissions(&caller, self, permissions).map_err(dispatch_to_evm::<T>)
 	}
 
 	/// Checks that user allowed to operate with collection.
@@ -605,19 +575,12 @@
 	fn set_collection_mint_mode(&mut self, caller: caller, mode: bool) -> Result<void> {
 		self.consume_store_reads_and_writes(1, 1)?;
 
-		check_is_owner_or_admin(caller, self)?;
+		let caller = T::CrossAccountId::from_eth(caller);
 		let permissions = CollectionPermissions {
 			mint_mode: Some(mode),
 			..Default::default()
 		};
-		self.collection.permissions = <Pallet<T>>::clamp_permissions(
-			self.collection.mode.clone(),
-			&self.collection.permissions,
-			permissions,
-		)
-		.map_err(dispatch_to_evm::<T>)?;
-
-		save(self)
+		<Pallet<T>>::update_permissions(&caller, self, permissions).map_err(dispatch_to_evm::<T>)
 	}
 
 	/// Check that account is the owner or admin of the collection
@@ -671,7 +634,7 @@
 
 		let caller = T::CrossAccountId::from_eth(caller);
 		let new_owner = T::CrossAccountId::from_eth(new_owner);
-		self.set_owner_internal(caller, new_owner)
+		self.change_owner(caller, new_owner)
 			.map_err(dispatch_to_evm::<T>)
 	}
 
@@ -699,7 +662,7 @@
 
 		let caller = T::CrossAccountId::from_eth(caller);
 		let new_owner = new_owner.into_sub_cross_account::<T>()?;
-		self.set_owner_internal(caller, new_owner)
+		self.change_owner(caller, new_owner)
 			.map_err(dispatch_to_evm::<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//! # Common pallet18//!19//! The Common pallet provides functionality for handling collections.20//!21//! ## Overview22//!23//! The Common pallet provides an interface for common collection operations for different collection types24//! (see [CommonCollectionOperations]), as well as a generic dispatcher for these, see [dispatch] module.25//! It also provides this functionality to EVM, see [erc] and [eth] modules.26//!27//! The Common pallet provides functions for:28//!29//! - Setting and approving collection sponsor.30//! - Get\set\delete allow list.31//! - Get\set\delete collection properties.32//! - Get\set\delete collection property permissions.33//! - Get\set\delete token property permissions.34//! - Get\set\delete collection administrators.35//! - Checking access permissions.36//!37//! ### Terminology38//! **Collection sponsor** - For the collection, you can set a sponsor, at whose expense it will39//! be possible to mint tokens.40//!41//! **Allow list** - List of users who have the right to minting tokens.42//!43//! **Collection properties** - Collection properties are simply key-value stores where various44//! metadata can be placed.45//!46//! **Permissions on token properties** - For each property in the token can be set permission47//! to change, see [`PropertyPermission`].48//!49//! **Collection administrator** - For a collection, you can set administrators who have the right50//! to most actions on the collection.5152#![warn(missing_docs)]53#![cfg_attr(not(feature = "std"), no_std)]54extern crate alloc;5556use core::ops::{Deref, DerefMut};57use pallet_evm_coder_substrate::{SubstrateRecorder, WithRecorder};58use sp_std::vec::Vec;59use pallet_evm::{account::CrossAccountId, Pallet as PalletEvm};60use evm_coder::ToLog;61use frame_support::{62	dispatch::{DispatchErrorWithPostInfo, DispatchResultWithPostInfo, Weight, PostDispatchInfo},63	ensure,64	traits::{Imbalance, Get, Currency, WithdrawReasons, ExistenceRequirement},65	dispatch::Pays,66	transactional,67};68use pallet_evm::GasWeightMapping;69use up_data_structs::{70	COLLECTION_NUMBER_LIMIT,71	Collection,72	RpcCollection,73	CollectionFlags,74	RpcCollectionFlags,75	CollectionId,76	CreateItemData,77	MAX_TOKEN_PREFIX_LENGTH,78	COLLECTION_ADMINS_LIMIT,79	TokenId,80	TokenChild,81	CollectionStats,82	MAX_TOKEN_OWNERSHIP,83	CollectionMode,84	NFT_SPONSOR_TRANSFER_TIMEOUT,85	FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,86	REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,87	MAX_SPONSOR_TIMEOUT,88	CUSTOM_DATA_LIMIT,89	CollectionLimits,90	CreateCollectionData,91	SponsorshipState,92	CreateItemExData,93	SponsoringRateLimit,94	budget::Budget,95	PhantomType,96	Property,97	Properties,98	PropertiesPermissionMap,99	PropertyKey,100	PropertyValue,101	PropertyPermission,102	PropertiesError,103	PropertyKeyPermission,104	TokenData,105	TrySetProperty,106	PropertyScope,107	// RMRK108	RmrkCollectionInfo,109	RmrkInstanceInfo,110	RmrkResourceInfo,111	RmrkPropertyInfo,112	RmrkBaseInfo,113	RmrkPartType,114	RmrkBoundedTheme,115	RmrkNftChild,116	CollectionPermissions,117};118119pub use pallet::*;120use sp_core::H160;121use sp_runtime::{ArithmeticError, DispatchError, DispatchResult};122#[cfg(feature = "runtime-benchmarks")]123pub mod benchmarking;124pub mod dispatch;125pub mod erc;126pub mod eth;127pub mod weights;128129/// Weight info.130pub type SelfWeightOf<T> = <T as Config>::WeightInfo;131132/// Collection handle contains information about collection data and id.133/// Also provides functionality to count consumed gas.134///135/// CollectionHandle is used as a generic wrapper for collections of all types.136/// It allows to perform common operations and queries on any collection type,137/// both completely general for all, as well as their respective implementations of [`CommonCollectionOperations`].138#[must_use = "Should call submit_logs or save, otherwise some data will be lost for evm side"]139pub struct CollectionHandle<T: Config> {140	/// Collection id141	pub id: CollectionId,142	collection: Collection<T::AccountId>,143	/// Substrate recorder for counting consumed gas144	pub recorder: SubstrateRecorder<T>,145}146147impl<T: Config> WithRecorder<T> for CollectionHandle<T> {148	fn recorder(&self) -> &SubstrateRecorder<T> {149		&self.recorder150	}151	fn into_recorder(self) -> SubstrateRecorder<T> {152		self.recorder153	}154}155156impl<T: Config> CollectionHandle<T> {157	/// Same as [CollectionHandle::new] but with an explicit gas limit.158	pub fn new_with_gas_limit(id: CollectionId, gas_limit: u64) -> Option<Self> {159		<CollectionById<T>>::get(id).map(|collection| Self {160			id,161			collection,162			recorder: SubstrateRecorder::new(gas_limit),163		})164	}165166	/// Same as [CollectionHandle::new] but with an existed [`SubstrateRecorder`].167	pub fn new_with_recorder(id: CollectionId, recorder: SubstrateRecorder<T>) -> Option<Self> {168		<CollectionById<T>>::get(id).map(|collection| Self {169			id,170			collection,171			recorder,172		})173	}174175	/// Retrives collection data from storage and creates collection handle with default parameters.176	/// If collection not found return `None`177	pub fn new(id: CollectionId) -> Option<Self> {178		Self::new_with_gas_limit(id, u64::MAX)179	}180181	/// Same as [`CollectionHandle::new`] but if collection not found [CollectionNotFound](Error::CollectionNotFound) returned.182	pub fn try_get(id: CollectionId) -> Result<Self, DispatchError> {183		Ok(Self::new(id).ok_or(<Error<T>>::CollectionNotFound)?)184	}185186	/// Consume gas for reading.187	pub fn consume_store_reads(&self, reads: u64) -> evm_coder::execution::Result<()> {188		self.recorder189			.consume_gas(T::GasWeightMapping::weight_to_gas(Weight::from_ref_time(190				<T as frame_system::Config>::DbWeight::get()191					.read192					.saturating_mul(reads),193			)))194	}195196	/// Consume gas for writing.197	pub fn consume_store_writes(&self, writes: u64) -> evm_coder::execution::Result<()> {198		self.recorder199			.consume_gas(T::GasWeightMapping::weight_to_gas(Weight::from_ref_time(200				<T as frame_system::Config>::DbWeight::get()201					.write202					.saturating_mul(writes),203			)))204	}205206	/// Consume gas for reading and writing.207	pub fn consume_store_reads_and_writes(208		&self,209		reads: u64,210		writes: u64,211	) -> evm_coder::execution::Result<()> {212		let weight = <T as frame_system::Config>::DbWeight::get();213		let reads = weight.read.saturating_mul(reads);214		let writes = weight.read.saturating_mul(writes);215		self.recorder216			.consume_gas(T::GasWeightMapping::weight_to_gas(Weight::from_ref_time(217				reads.saturating_add(writes),218			)))219	}220221	/// Save collection to storage.222	pub fn save(&self) -> DispatchResult {223		<CollectionById<T>>::insert(self.id, &self.collection);224		Ok(())225	}226227	/// Set collection sponsor.228	///229	/// Unique collections allows sponsoring for certain actions.230	/// This method allows you to set the sponsor of the collection.231	/// In order for sponsorship to become active, it must be confirmed through [`Self::confirm_sponsorship`].232	pub fn set_sponsor(&mut self, sponsor: T::AccountId) -> DispatchResult {233		self.collection.sponsorship = SponsorshipState::Unconfirmed(sponsor);234		Ok(())235	}236237	/// Confirm sponsorship238	///239	/// In order for the sponsorship to become active, the user set as the sponsor must confirm their participation.240	/// Before confirming sponsorship, the user must be specified as the sponsor of the collection via [`Self::set_sponsor`].241	pub fn confirm_sponsorship(&mut self, sender: &T::AccountId) -> Result<bool, DispatchError> {242		if self.collection.sponsorship.pending_sponsor() != Some(sender) {243			return Ok(false);244		}245246		self.collection.sponsorship = SponsorshipState::Confirmed(sender.clone());247		Ok(true)248	}249250	/// Remove collection sponsor.251	pub fn remove_sponsor(&mut self) -> DispatchResult {252		self.collection.sponsorship = SponsorshipState::Disabled;253		Ok(())254	}255256	/// Checks that the collection was created with, and must be operated upon through **Unique API**.257	/// Now check only the `external` flag and if it's **true**, then return [`Error::CollectionIsExternal`] error.258	pub fn check_is_internal(&self) -> DispatchResult {259		if self.flags.external {260			return Err(<Error<T>>::CollectionIsExternal)?;261		}262263		Ok(())264	}265266	/// Checks that the collection was created with, and must be operated upon through an **assimilated API**.267	/// Now check only the `external` flag and if it's **false**, then return [`Error::CollectionIsInternal`] error.268	pub fn check_is_external(&self) -> DispatchResult {269		if !self.flags.external {270			return Err(<Error<T>>::CollectionIsInternal)?;271		}272273		Ok(())274	}275}276277impl<T: Config> Deref for CollectionHandle<T> {278	type Target = Collection<T::AccountId>;279280	fn deref(&self) -> &Self::Target {281		&self.collection282	}283}284285impl<T: Config> DerefMut for CollectionHandle<T> {286	fn deref_mut(&mut self) -> &mut Self::Target {287		&mut self.collection288	}289}290291impl<T: Config> CollectionHandle<T> {292	/// Checks if the `user` is the owner of the collection.293	pub fn check_is_owner(&self, user: &T::CrossAccountId) -> DispatchResult {294		ensure!(*user.as_sub() == self.owner, <Error<T>>::NoPermission);295		Ok(())296	}297298	/// Returns **true** if the `user` is the owner or administrator of the collection.299	pub fn is_owner_or_admin(&self, user: &T::CrossAccountId) -> bool {300		*user.as_sub() == self.owner || <IsAdmin<T>>::get((self.id, user))301	}302303	/// Checks if the `user` is the owner or administrator of the collection.304	pub fn check_is_owner_or_admin(&self, user: &T::CrossAccountId) -> DispatchResult {305		ensure!(self.is_owner_or_admin(user), <Error<T>>::NoPermission);306		Ok(())307	}308309	/// Return **true** if `user` was not allowed to have tokens, and he can ignore such restrictions.310	pub fn ignores_allowance(&self, user: &T::CrossAccountId) -> bool {311		self.limits.owner_can_transfer() && self.is_owner_or_admin(user)312	}313314	/// Return **true** if `user` does not have enough token parts, and he can ignore such restrictions.315	pub fn ignores_owned_amount(&self, user: &T::CrossAccountId) -> bool {316		self.limits.owner_can_transfer() && self.is_owner_or_admin(user)317	}318319	/// Checks if the user is in the allow list. If not [Error::AddressNotInAllowlist] returns.320	pub fn check_allowlist(&self, user: &T::CrossAccountId) -> DispatchResult {321		ensure!(322			<Allowlist<T>>::get((self.id, user)),323			<Error<T>>::AddressNotInAllowlist324		);325		Ok(())326	}327328	/// Changes collection owner to another account329	/// #### Store read/writes330	/// 1 writes331	fn set_owner_internal(332		&mut self,333		caller: T::CrossAccountId,334		new_owner: T::CrossAccountId,335	) -> DispatchResult {336		self.check_is_owner(&caller)?;337		self.collection.owner = new_owner.as_sub().clone();338		self.save()339	}340}341342#[frame_support::pallet]343pub mod pallet {344	use super::*;345	use dispatch::CollectionDispatch;346	use frame_support::{Blake2_128Concat, pallet_prelude::*, storage::Key, traits::StorageVersion};347	use frame_system::pallet_prelude::*;348	use frame_support::traits::Currency;349	use up_data_structs::{TokenId, mapping::TokenAddressMapping};350	use scale_info::TypeInfo;351	use weights::WeightInfo;352353	#[pallet::config]354	pub trait Config:355		frame_system::Config + pallet_evm_coder_substrate::Config + pallet_evm::Config + TypeInfo356	{357		/// Weight information for functions of this pallet.358		type WeightInfo: WeightInfo;359360		/// Events compatible with [`frame_system::Config::Event`].361		type RuntimeEvent: IsType<<Self as frame_system::Config>::RuntimeEvent> + From<Event<Self>>;362363		/// Handler of accounts and payment.364		type Currency: Currency<Self::AccountId>;365366		/// Set price to create a collection.367		#[pallet::constant]368		type CollectionCreationPrice: Get<369			<<Self as Config>::Currency as Currency<Self::AccountId>>::Balance,370		>;371372		/// Dispatcher of operations on collections.373		type CollectionDispatch: CollectionDispatch<Self>;374375		/// Account which holds the chain's treasury.376		type TreasuryAccountId: Get<Self::AccountId>;377378		/// Address under which the CollectionHelper contract would be available.379		#[pallet::constant]380		type ContractAddress: Get<H160>;381382		/// Mapper for token addresses to Ethereum addresses.383		type EvmTokenAddressMapping: TokenAddressMapping<H160>;384385		/// Mapper for token addresses to [`CrossAccountId`].386		type CrossTokenAddressMapping: TokenAddressMapping<Self::CrossAccountId>;387	}388389	const STORAGE_VERSION: StorageVersion = StorageVersion::new(1);390391	#[pallet::pallet]392	#[pallet::storage_version(STORAGE_VERSION)]393	#[pallet::generate_store(pub(super) trait Store)]394	pub struct Pallet<T>(_);395396	#[pallet::extra_constants]397	impl<T: Config> Pallet<T> {398		/// Maximum admins per collection.399		pub fn collection_admins_limit() -> u32 {400			COLLECTION_ADMINS_LIMIT401		}402	}403404	#[pallet::event]405	#[pallet::generate_deposit(pub fn deposit_event)]406	pub enum Event<T: Config> {407		/// New collection was created408		CollectionCreated(409			/// Globally unique identifier of newly created collection.410			CollectionId,411			/// [`CollectionMode`] converted into _u8_.412			u8,413			/// Collection owner.414			T::AccountId,415		),416417		/// New collection was destroyed418		CollectionDestroyed(419			/// Globally unique identifier of collection.420			CollectionId,421		),422423		/// New item was created.424		ItemCreated(425			/// Id of the collection where item was created.426			CollectionId,427			/// Id of an item. Unique within the collection.428			TokenId,429			/// Owner of newly created item430			T::CrossAccountId,431			/// Always 1 for NFT432			u128,433		),434435		/// Collection item was burned.436		ItemDestroyed(437			/// Id of the collection where item was destroyed.438			CollectionId,439			/// Identifier of burned NFT.440			TokenId,441			/// Which user has destroyed its tokens.442			T::CrossAccountId,443			/// Amount of token pieces destroed. Always 1 for NFT.444			u128,445		),446447		/// Item was transferred448		Transfer(449			/// Id of collection to which item is belong.450			CollectionId,451			/// Id of an item.452			TokenId,453			/// Original owner of item.454			T::CrossAccountId,455			/// New owner of item.456			T::CrossAccountId,457			/// Amount of token pieces transfered. Always 1 for NFT.458			u128,459		),460461		/// Amount pieces of token owned by `sender` was approved for `spender`.462		Approved(463			/// Id of collection to which item is belong.464			CollectionId,465			/// Id of an item.466			TokenId,467			/// Original owner of item.468			T::CrossAccountId,469			/// Id for which the approval was granted.470			T::CrossAccountId,471			/// Amount of token pieces transfered. Always 1 for NFT.472			u128,473		),474475		/// A `sender` approves operations on all owned tokens for `spender`.476		ApprovedForAll(477			/// Id of collection to which item is belong.478			CollectionId,479			/// Owner of a wallet.480			T::CrossAccountId,481			/// Id for which operator status was granted or rewoked.482			T::CrossAccountId,483			/// Is operator status granted or revoked?484			bool,485		),486487		/// The colletion property has been added or edited.488		CollectionPropertySet(489			/// Id of collection to which property has been set.490			CollectionId,491			/// The property that was set.492			PropertyKey,493		),494495		/// The property has been deleted.496		CollectionPropertyDeleted(497			/// Id of collection to which property has been deleted.498			CollectionId,499			/// The property that was deleted.500			PropertyKey,501		),502503		/// The token property has been added or edited.504		TokenPropertySet(505			/// Identifier of the collection whose token has the property set.506			CollectionId,507			/// The token for which the property was set.508			TokenId,509			/// The property that was set.510			PropertyKey,511		),512513		/// The token property has been deleted.514		TokenPropertyDeleted(515			/// Identifier of the collection whose token has the property deleted.516			CollectionId,517			/// The token for which the property was deleted.518			TokenId,519			/// The property that was deleted.520			PropertyKey,521		),522523		/// The token property permission of a collection has been set.524		PropertyPermissionSet(525			/// ID of collection to which property permission has been set.526			CollectionId,527			/// The property permission that was set.528			PropertyKey,529		),530	}531532	#[pallet::error]533	pub enum Error<T> {534		/// This collection does not exist.535		CollectionNotFound,536		/// Sender parameter and item owner must be equal.537		MustBeTokenOwner,538		/// No permission to perform action539		NoPermission,540		/// Destroying only empty collections is allowed541		CantDestroyNotEmptyCollection,542		/// Collection is not in mint mode.543		PublicMintingNotAllowed,544		/// Address is not in allow list.545		AddressNotInAllowlist,546547		/// Collection name can not be longer than 63 char.548		CollectionNameLimitExceeded,549		/// Collection description can not be longer than 255 char.550		CollectionDescriptionLimitExceeded,551		/// Token prefix can not be longer than 15 char.552		CollectionTokenPrefixLimitExceeded,553		/// Total collections bound exceeded.554		TotalCollectionsLimitExceeded,555		/// Exceeded max admin count556		CollectionAdminCountExceeded,557		/// Collection limit bounds per collection exceeded558		CollectionLimitBoundsExceeded,559		/// Tried to enable permissions which are only permitted to be disabled560		OwnerPermissionsCantBeReverted,561		/// Collection settings not allowing items transferring562		TransferNotAllowed,563		/// Account token limit exceeded per collection564		AccountTokenLimitExceeded,565		/// Collection token limit exceeded566		CollectionTokenLimitExceeded,567		/// Metadata flag frozen568		MetadataFlagFrozen,569570		/// Item does not exist571		TokenNotFound,572		/// Item is balance not enough573		TokenValueTooLow,574		/// Requested value is more than the approved575		ApprovedValueTooLow,576		/// Tried to approve more than owned577		CantApproveMoreThanOwned,578579		/// Can't transfer tokens to ethereum zero address580		AddressIsZero,581582		/// The operation is not supported583		UnsupportedOperation,584585		/// Insufficient funds to perform an action586		NotSufficientFounds,587588		/// User does not satisfy the nesting rule589		UserIsNotAllowedToNest,590		/// Only tokens from specific collections may nest tokens under this one591		SourceCollectionIsNotAllowedToNest,592593		/// Tried to store more data than allowed in collection field594		CollectionFieldSizeExceeded,595596		/// Tried to store more property data than allowed597		NoSpaceForProperty,598599		/// Tried to store more property keys than allowed600		PropertyLimitReached,601602		/// Property key is too long603		PropertyKeyIsTooLong,604605		/// Only ASCII letters, digits, and symbols `_`, `-`, and `.` are allowed606		InvalidCharacterInPropertyKey,607608		/// Empty property keys are forbidden609		EmptyPropertyKey,610611		/// Tried to access an external collection with an internal API612		CollectionIsExternal,613614		/// Tried to access an internal collection with an external API615		CollectionIsInternal,616	}617618	/// Storage of the count of created collections. Essentially contains the last collection ID.619	#[pallet::storage]620	pub type CreatedCollectionCount<T> = StorageValue<Value = CollectionId, QueryKind = ValueQuery>;621622	/// Storage of the count of deleted collections.623	#[pallet::storage]624	pub type DestroyedCollectionCount<T> =625		StorageValue<Value = CollectionId, QueryKind = ValueQuery>;626627	/// Storage of collection info.628	#[pallet::storage]629	pub type CollectionById<T> = StorageMap<630		Hasher = Blake2_128Concat,631		Key = CollectionId,632		Value = Collection<<T as frame_system::Config>::AccountId>,633		QueryKind = OptionQuery,634	>;635636	/// Storage of collection properties.637	#[pallet::storage]638	#[pallet::getter(fn collection_properties)]639	pub type CollectionProperties<T> = StorageMap<640		Hasher = Blake2_128Concat,641		Key = CollectionId,642		Value = Properties,643		QueryKind = ValueQuery,644		OnEmpty = up_data_structs::CollectionProperties,645	>;646647	/// Storage of token property permissions of a collection.648	#[pallet::storage]649	#[pallet::getter(fn property_permissions)]650	pub type CollectionPropertyPermissions<T> = StorageMap<651		Hasher = Blake2_128Concat,652		Key = CollectionId,653		Value = PropertiesPermissionMap,654		QueryKind = ValueQuery,655	>;656657	/// Storage of the amount of collection admins.658	#[pallet::storage]659	pub type AdminAmount<T> = StorageMap<660		Hasher = Blake2_128Concat,661		Key = CollectionId,662		Value = u32,663		QueryKind = ValueQuery,664	>;665666	/// List of collection admins.667	#[pallet::storage]668	pub type IsAdmin<T: Config> = StorageNMap<669		Key = (670			Key<Blake2_128Concat, CollectionId>,671			Key<Blake2_128Concat, T::CrossAccountId>,672		),673		Value = bool,674		QueryKind = ValueQuery,675	>;676677	/// Allowlisted collection users.678	#[pallet::storage]679	pub type Allowlist<T: Config> = StorageNMap<680		Key = (681			Key<Blake2_128Concat, CollectionId>,682			Key<Blake2_128Concat, T::CrossAccountId>,683		),684		Value = bool,685		QueryKind = ValueQuery,686	>;687688	/// Not used by code, exists only to provide some types to metadata.689	#[pallet::storage]690	pub type DummyStorageValue<T: Config> = StorageValue<691		Value = (692			CollectionStats,693			CollectionId,694			TokenId,695			TokenChild,696			PhantomType<(697				TokenData<T::CrossAccountId>,698				RpcCollection<T::AccountId>,699				// RMRK700				RmrkCollectionInfo<T::AccountId>,701				RmrkInstanceInfo<T::AccountId>,702				RmrkResourceInfo,703				RmrkPropertyInfo,704				RmrkBaseInfo<T::AccountId>,705				RmrkPartType,706				RmrkBoundedTheme,707				RmrkNftChild,708			)>,709		),710		QueryKind = OptionQuery,711	>;712713	#[pallet::hooks]714	impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {715		fn on_runtime_upgrade() -> Weight {716			StorageVersion::new(1).put::<Pallet<T>>();717718			Weight::zero()719		}720	}721}722723impl<T: Config> Pallet<T> {724	/// Enshure that receiver address is correct.725	///726	/// Ethereum receiver 0x0000000000000000000000000000000000000000 is reserved, and shouldn't own tokens.727	pub fn ensure_correct_receiver(receiver: &T::CrossAccountId) -> DispatchResult {728		ensure!(729			&T::CrossAccountId::from_eth(H160([0; 20])) != receiver,730			<Error<T>>::AddressIsZero731		);732		Ok(())733	}734735	/// Get a vector of collection admins.736	pub fn adminlist(collection: CollectionId) -> Vec<T::CrossAccountId> {737		<IsAdmin<T>>::iter_prefix((collection,))738			.map(|(a, _)| a)739			.collect()740	}741742	/// Get a vector of users allowed to mint tokens.743	pub fn allowlist(collection: CollectionId) -> Vec<T::CrossAccountId> {744		<Allowlist<T>>::iter_prefix((collection,))745			.map(|(a, _)| a)746			.collect()747	}748749	/// Is `user` allowed to mint token in `collection`.750	pub fn allowed(collection: CollectionId, user: T::CrossAccountId) -> bool {751		<Allowlist<T>>::get((collection, user))752	}753754	/// Get statistics of collections.755	pub fn collection_stats() -> CollectionStats {756		let created = <CreatedCollectionCount<T>>::get();757		let destroyed = <DestroyedCollectionCount<T>>::get();758		CollectionStats {759			created: created.0,760			destroyed: destroyed.0,761			alive: created.0 - destroyed.0,762		}763	}764765	/// Get the effective limits for the collection.766	pub fn effective_collection_limits(collection: CollectionId) -> Option<CollectionLimits> {767		let collection = <CollectionById<T>>::get(collection)?;768		let limits = collection.limits;769		let effective_limits = CollectionLimits {770			account_token_ownership_limit: Some(limits.account_token_ownership_limit()),771			sponsored_data_size: Some(limits.sponsored_data_size()),772			sponsored_data_rate_limit: Some(773				limits774					.sponsored_data_rate_limit775					.unwrap_or(SponsoringRateLimit::SponsoringDisabled),776			),777			token_limit: Some(limits.token_limit()),778			sponsor_transfer_timeout: Some(limits.sponsor_transfer_timeout(779				match collection.mode {780					CollectionMode::NFT => NFT_SPONSOR_TRANSFER_TIMEOUT,781					CollectionMode::Fungible(_) => FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,782					CollectionMode::ReFungible => REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,783				},784			)),785			sponsor_approve_timeout: Some(limits.sponsor_approve_timeout()),786			owner_can_transfer: Some(limits.owner_can_transfer()),787			owner_can_destroy: Some(limits.owner_can_destroy()),788			transfers_enabled: Some(limits.transfers_enabled()),789		};790791		Some(effective_limits)792	}793794	/// Returns information about the `collection` adapted for rpc.795	pub fn rpc_collection(collection: CollectionId) -> Option<RpcCollection<T::AccountId>> {796		let Collection {797			name,798			description,799			owner,800			mode,801			token_prefix,802			sponsorship,803			limits,804			permissions,805			flags,806		} = <CollectionById<T>>::get(collection)?;807808		let token_property_permissions = <CollectionPropertyPermissions<T>>::get(collection)809			.into_iter()810			.map(|(key, permission)| PropertyKeyPermission { key, permission })811			.collect();812813		let properties = <CollectionProperties<T>>::get(collection)814			.into_iter()815			.map(|(key, value)| Property { key, value })816			.collect();817818		let permissions = CollectionPermissions {819			access: Some(permissions.access()),820			mint_mode: Some(permissions.mint_mode()),821			nesting: Some(permissions.nesting().clone()),822		};823824		Some(RpcCollection {825			name: name.into_inner(),826			description: description.into_inner(),827			owner,828			mode,829			token_prefix: token_prefix.into_inner(),830			sponsorship,831			limits,832			permissions,833			token_property_permissions,834			properties,835			read_only: flags.external,836837			flags: RpcCollectionFlags {838				foreign: flags.foreign,839				erc721metadata: flags.erc721metadata,840			},841		})842	}843}844845macro_rules! limit_default {846	($old:ident, $new:ident, $($field:ident $(($arg:expr))? => $check:expr),* $(,)?) => {{847		$(848			if let Some($new) = $new.$field {849				let $old = $old.$field($($arg)?);850				let _ = $new;851				let _ = $old;852				$check853			} else {854				$new.$field = $old.$field855			}856		)*857	}};858}859macro_rules! limit_default_clone {860	($old:ident, $new:ident, $($field:ident $(($arg:expr))? => $check:expr),* $(,)?) => {{861		$(862			if let Some($new) = $new.$field.clone() {863				let $old = $old.$field($($arg)?);864				let _ = $new;865				let _ = $old;866				$check867			} else {868				$new.$field = $old.$field.clone()869			}870		)*871	}};872}873874impl<T: Config> Pallet<T> {875	/// Create new collection.876	///877	/// * `owner` - The owner of the collection.878	/// * `data` - Description of the created collection.879	/// * `flags` - Extra flags to store.880	pub fn init_collection(881		owner: T::CrossAccountId,882		payer: T::CrossAccountId,883		data: CreateCollectionData<T::AccountId>,884		flags: CollectionFlags,885	) -> Result<CollectionId, DispatchError> {886		{887			ensure!(888				data.token_prefix.len() <= MAX_TOKEN_PREFIX_LENGTH as usize,889				Error::<T>::CollectionTokenPrefixLimitExceeded890			);891		}892893		let created_count = <CreatedCollectionCount<T>>::get()894			.0895			.checked_add(1)896			.ok_or(ArithmeticError::Overflow)?;897		let destroyed_count = <DestroyedCollectionCount<T>>::get().0;898		let id = CollectionId(created_count);899900		// bound Total number of collections901		ensure!(902			created_count - destroyed_count <= COLLECTION_NUMBER_LIMIT,903			<Error<T>>::TotalCollectionsLimitExceeded904		);905906		// =========907908		let collection = Collection {909			owner: owner.as_sub().clone(),910			name: data.name,911			mode: data.mode.clone(),912			description: data.description,913			token_prefix: data.token_prefix,914			sponsorship: data915				.pending_sponsor916				.map(SponsorshipState::Unconfirmed)917				.unwrap_or_default(),918			limits: data919				.limits920				.map(|limits| Self::clamp_limits(data.mode.clone(), &Default::default(), limits))921				.unwrap_or_else(|| Ok(CollectionLimits::default()))?,922			permissions: data923				.permissions924				.map(|permissions| {925					Self::clamp_permissions(data.mode.clone(), &Default::default(), permissions)926				})927				.unwrap_or_else(|| Ok(CollectionPermissions::default()))?,928			flags,929		};930931		let mut collection_properties = up_data_structs::CollectionProperties::get();932		collection_properties933			.try_set_from_iter(data.properties.into_iter())934			.map_err(<Error<T>>::from)?;935936		CollectionProperties::<T>::insert(id, collection_properties);937938		let mut token_props_permissions = PropertiesPermissionMap::new();939		token_props_permissions940			.try_set_from_iter(data.token_property_permissions.into_iter())941			.map_err(<Error<T>>::from)?;942943		CollectionPropertyPermissions::<T>::insert(id, token_props_permissions);944945		// Take a (non-refundable) deposit of collection creation946		{947			let mut imbalance =948				<<<T as Config>::Currency as Currency<T::AccountId>>::PositiveImbalance>::zero();949			imbalance.subsume(950				<<T as Config>::Currency as Currency<T::AccountId>>::deposit_creating(951					&T::TreasuryAccountId::get(),952					T::CollectionCreationPrice::get(),953				),954			);955			<T as Config>::Currency::settle(956				payer.as_sub(),957				imbalance,958				WithdrawReasons::TRANSFER,959				ExistenceRequirement::KeepAlive,960			)961			.map_err(|_| Error::<T>::NotSufficientFounds)?;962		}963964		<CreatedCollectionCount<T>>::put(created_count);965		<Pallet<T>>::deposit_event(Event::CollectionCreated(966			id,967			data.mode.id(),968			owner.as_sub().clone(),969		));970		<PalletEvm<T>>::deposit_log(971			erc::CollectionHelpersEvents::CollectionCreated {972				owner: *owner.as_eth(),973				collection_id: eth::collection_id_to_address(id),974			}975			.to_log(T::ContractAddress::get()),976		);977		<CollectionById<T>>::insert(id, collection);978		Ok(id)979	}980981	/// Destroy collection.982	///983	/// * `collection` - Collection handler.984	/// * `sender` - The owner or administrator of the collection.985	pub fn destroy_collection(986		collection: CollectionHandle<T>,987		sender: &T::CrossAccountId,988	) -> DispatchResult {989		ensure!(990			collection.limits.owner_can_destroy(),991			<Error<T>>::NoPermission,992		);993		collection.check_is_owner(sender)?;994995		let destroyed_collections = <DestroyedCollectionCount<T>>::get()996			.0997			.checked_add(1)998			.ok_or(ArithmeticError::Overflow)?;9991000		// =========10011002		<DestroyedCollectionCount<T>>::put(destroyed_collections);1003		<CollectionById<T>>::remove(collection.id);1004		<AdminAmount<T>>::remove(collection.id);1005		let _ = <IsAdmin<T>>::clear_prefix((collection.id,), u32::MAX, None);1006		let _ = <Allowlist<T>>::clear_prefix((collection.id,), u32::MAX, None);1007		<CollectionProperties<T>>::remove(collection.id);10081009		<Pallet<T>>::deposit_event(Event::CollectionDestroyed(collection.id));10101011		<PalletEvm<T>>::deposit_log(1012			erc::CollectionHelpersEvents::CollectionDestroyed {1013				collection_id: eth::collection_id_to_address(collection.id),1014			}1015			.to_log(T::ContractAddress::get()),1016		);1017		Ok(())1018	}10191020	/// Set collection property.1021	///1022	/// * `collection` - Collection handler.1023	/// * `sender` - The owner or administrator of the collection.1024	/// * `property` - The property to set.1025	pub fn set_collection_property(1026		collection: &CollectionHandle<T>,1027		sender: &T::CrossAccountId,1028		property: Property,1029	) -> DispatchResult {1030		collection.check_is_owner_or_admin(sender)?;10311032		CollectionProperties::<T>::try_mutate(collection.id, |properties| {1033			let property = property.clone();1034			properties.try_set(property.key, property.value)1035		})1036		.map_err(<Error<T>>::from)?;10371038		Self::deposit_event(Event::CollectionPropertySet(collection.id, property.key));1039		<PalletEvm<T>>::deposit_log(1040			erc::CollectionHelpersEvents::CollectionChanged {1041				collection_id: eth::collection_id_to_address(collection.id),1042			}1043			.to_log(T::ContractAddress::get()),1044		);10451046		Ok(())1047	}10481049	/// Set scouped collection property.1050	///1051	/// * `collection_id` - ID of the collection for which the property is being set.1052	/// * `scope` - Property scope.1053	/// * `property` - The property to set.1054	pub fn set_scoped_collection_property(1055		collection_id: CollectionId,1056		scope: PropertyScope,1057		property: Property,1058	) -> DispatchResult {1059		CollectionProperties::<T>::try_mutate(collection_id, |properties| {1060			properties.try_scoped_set(scope, property.key, property.value)1061		})1062		.map_err(<Error<T>>::from)?;10631064		Ok(())1065	}10661067	/// Set scouped collection properties.1068	///1069	/// * `collection_id` - ID of the collection for which the properties is being set.1070	/// * `scope` - Property scope.1071	/// * `properties` - The properties to set.1072	pub fn set_scoped_collection_properties(1073		collection_id: CollectionId,1074		scope: PropertyScope,1075		properties: impl Iterator<Item = Property>,1076	) -> DispatchResult {1077		CollectionProperties::<T>::try_mutate(collection_id, |stored_properties| {1078			stored_properties.try_scoped_set_from_iter(scope, properties)1079		})1080		.map_err(<Error<T>>::from)?;10811082		Ok(())1083	}10841085	/// Set collection properties.1086	///1087	/// * `collection` - Collection handler.1088	/// * `sender` - The owner or administrator of the collection.1089	/// * `properties` - The properties to set.1090	#[transactional]1091	pub fn set_collection_properties(1092		collection: &CollectionHandle<T>,1093		sender: &T::CrossAccountId,1094		properties: Vec<Property>,1095	) -> DispatchResult {1096		for property in properties {1097			Self::set_collection_property(collection, sender, property)?;1098		}10991100		Ok(())1101	}11021103	/// Delete collection property.1104	///1105	/// * `collection` - Collection handler.1106	/// * `sender` - The owner or administrator of the collection.1107	/// * `property` - The property to delete.1108	pub fn delete_collection_property(1109		collection: &CollectionHandle<T>,1110		sender: &T::CrossAccountId,1111		property_key: PropertyKey,1112	) -> DispatchResult {1113		collection.check_is_owner_or_admin(sender)?;11141115		CollectionProperties::<T>::try_mutate(collection.id, |properties| {1116			properties.remove(&property_key)1117		})1118		.map_err(<Error<T>>::from)?;11191120		Self::deposit_event(Event::CollectionPropertyDeleted(1121			collection.id,1122			property_key,1123		));1124		<PalletEvm<T>>::deposit_log(1125			erc::CollectionHelpersEvents::CollectionChanged {1126				collection_id: eth::collection_id_to_address(collection.id),1127			}1128			.to_log(T::ContractAddress::get()),1129		);11301131		Ok(())1132	}11331134	/// Delete collection properties.1135	///1136	/// * `collection` - Collection handler.1137	/// * `sender` - The owner or administrator of the collection.1138	/// * `properties` - The properties to delete.1139	#[transactional]1140	pub fn delete_collection_properties(1141		collection: &CollectionHandle<T>,1142		sender: &T::CrossAccountId,1143		property_keys: Vec<PropertyKey>,1144	) -> DispatchResult {1145		for key in property_keys {1146			Self::delete_collection_property(collection, sender, key)?;1147		}11481149		Ok(())1150	}11511152	/// Set collection propetry permission without any checks.1153	///1154	/// Used for migrations.1155	///1156	/// * `collection` - Collection handler.1157	/// * `property_permissions` - Property permissions.1158	pub fn set_property_permission_unchecked(1159		collection: CollectionId,1160		property_permission: PropertyKeyPermission,1161	) -> DispatchResult {1162		<CollectionPropertyPermissions<T>>::try_mutate(collection, |permissions| {1163			permissions.try_set(property_permission.key, property_permission.permission)1164		})1165		.map_err(<Error<T>>::from)?;1166		Ok(())1167	}11681169	/// Set collection property permission.1170	///1171	/// * `collection` - Collection handler.1172	/// * `sender` - The owner or administrator of the collection.1173	/// * `property_permission` - Property permission.1174	pub fn set_property_permission(1175		collection: &CollectionHandle<T>,1176		sender: &T::CrossAccountId,1177		property_permission: PropertyKeyPermission,1178	) -> DispatchResult {1179		Self::set_scoped_property_permission(1180			collection,1181			sender,1182			PropertyScope::None,1183			property_permission,1184		)1185	}11861187	/// Set collection property permission with scope.1188	///1189	/// * `collection` - Collection handler.1190	/// * `sender` - The owner or administrator of the collection.1191	/// * `scope` - Property scope.1192	/// * `property_permission` - Property permission.1193	pub fn set_scoped_property_permission(1194		collection: &CollectionHandle<T>,1195		sender: &T::CrossAccountId,1196		scope: PropertyScope,1197		property_permission: PropertyKeyPermission,1198	) -> DispatchResult {1199		collection.check_is_owner_or_admin(sender)?;12001201		let all_permissions = CollectionPropertyPermissions::<T>::get(collection.id);1202		let current_permission = all_permissions.get(&property_permission.key);1203		if matches![1204			current_permission,1205			Some(PropertyPermission { mutable: false, .. })1206		] {1207			return Err(<Error<T>>::NoPermission.into());1208		}12091210		CollectionPropertyPermissions::<T>::try_mutate(collection.id, |permissions| {1211			let property_permission = property_permission.clone();1212			permissions.try_scoped_set(1213				scope,1214				property_permission.key,1215				property_permission.permission,1216			)1217		})1218		.map_err(<Error<T>>::from)?;12191220		Self::deposit_event(Event::PropertyPermissionSet(1221			collection.id,1222			property_permission.key,1223		));1224		<PalletEvm<T>>::deposit_log(1225			erc::CollectionHelpersEvents::CollectionChanged {1226				collection_id: eth::collection_id_to_address(collection.id),1227			}1228			.to_log(T::ContractAddress::get()),1229		);12301231		Ok(())1232	}12331234	/// Set token property permission.1235	///1236	/// * `collection` - Collection handler.1237	/// * `sender` - The owner or administrator of the collection.1238	/// * `property_permissions` - Property permissions.1239	#[transactional]1240	pub fn set_token_property_permissions(1241		collection: &CollectionHandle<T>,1242		sender: &T::CrossAccountId,1243		property_permissions: Vec<PropertyKeyPermission>,1244	) -> DispatchResult {1245		Self::set_scoped_token_property_permissions(1246			collection,1247			sender,1248			PropertyScope::None,1249			property_permissions,1250		)1251	}12521253	/// Set token property permission with scope.1254	///1255	/// * `collection` - Collection handler.1256	/// * `sender` - The owner or administrator of the collection.1257	/// * `scope` - Property scope.1258	/// * `property_permissions` - Property permissions.1259	#[transactional]1260	pub fn set_scoped_token_property_permissions(1261		collection: &CollectionHandle<T>,1262		sender: &T::CrossAccountId,1263		scope: PropertyScope,1264		property_permissions: Vec<PropertyKeyPermission>,1265	) -> DispatchResult {1266		for prop_pemission in property_permissions {1267			Self::set_scoped_property_permission(collection, sender, scope, prop_pemission)?;1268		}12691270		Ok(())1271	}12721273	/// Get collection property.1274	pub fn get_collection_property(1275		collection_id: CollectionId,1276		key: &PropertyKey,1277	) -> Option<PropertyValue> {1278		Self::collection_properties(collection_id).get(key).cloned()1279	}12801281	/// Convert byte vector to property key vector.1282	pub fn bytes_keys_to_property_keys(1283		keys: Vec<Vec<u8>>,1284	) -> Result<Vec<PropertyKey>, DispatchError> {1285		keys.into_iter()1286			.map(|key| -> Result<PropertyKey, DispatchError> {1287				key.try_into()1288					.map_err(|_| <Error<T>>::PropertyKeyIsTooLong.into())1289			})1290			.collect::<Result<Vec<PropertyKey>, DispatchError>>()1291	}12921293	/// Get properties according to given keys.1294	pub fn filter_collection_properties(1295		collection_id: CollectionId,1296		keys: Option<Vec<PropertyKey>>,1297	) -> Result<Vec<Property>, DispatchError> {1298		let properties = Self::collection_properties(collection_id);12991300		let properties = keys1301			.map(|keys| {1302				keys.into_iter()1303					.filter_map(|key| {1304						properties.get(&key).map(|value| Property {1305							key,1306							value: value.clone(),1307						})1308					})1309					.collect()1310			})1311			.unwrap_or_else(|| {1312				properties1313					.into_iter()1314					.map(|(key, value)| Property { key, value })1315					.collect()1316			});13171318		Ok(properties)1319	}13201321	/// Get property permissions according to given keys.1322	pub fn filter_property_permissions(1323		collection_id: CollectionId,1324		keys: Option<Vec<PropertyKey>>,1325	) -> Result<Vec<PropertyKeyPermission>, DispatchError> {1326		let permissions = Self::property_permissions(collection_id);13271328		let key_permissions = keys1329			.map(|keys| {1330				keys.into_iter()1331					.filter_map(|key| {1332						permissions1333							.get(&key)1334							.map(|permission| PropertyKeyPermission {1335								key,1336								permission: permission.clone(),1337							})1338					})1339					.collect()1340			})1341			.unwrap_or_else(|| {1342				permissions1343					.into_iter()1344					.map(|(key, permission)| PropertyKeyPermission { key, permission })1345					.collect()1346			});13471348		Ok(key_permissions)1349	}13501351	/// Toggle `user` participation in the `collection`'s allow list.1352	/// #### Store read/writes1353	/// 1 writes1354	pub fn toggle_allowlist(1355		collection: &CollectionHandle<T>,1356		sender: &T::CrossAccountId,1357		user: &T::CrossAccountId,1358		allowed: bool,1359	) -> DispatchResult {1360		collection.check_is_owner_or_admin(sender)?;13611362		// =========13631364		if allowed {1365			<Allowlist<T>>::insert((collection.id, user), true);1366		} else {1367			<Allowlist<T>>::remove((collection.id, user));1368		}13691370		Ok(())1371	}13721373	/// Toggle `user` participation in the `collection`'s admin list.1374	/// #### Store read/writes1375	/// 2 writes1376	pub fn toggle_admin(1377		collection: &CollectionHandle<T>,1378		sender: &T::CrossAccountId,1379		user: &T::CrossAccountId,1380		admin: bool,1381	) -> DispatchResult {1382		collection.check_is_owner(sender)?;13831384		let was_admin = <IsAdmin<T>>::get((collection.id, user));1385		if was_admin == admin {1386			return Ok(());1387		}1388		let amount = <AdminAmount<T>>::get(collection.id);13891390		if admin {1391			let amount = amount1392				.checked_add(1)1393				.ok_or(<Error<T>>::CollectionAdminCountExceeded)?;1394			ensure!(1395				amount <= Self::collection_admins_limit(),1396				<Error<T>>::CollectionAdminCountExceeded,1397			);13981399			// =========14001401			<AdminAmount<T>>::insert(collection.id, amount);1402			<IsAdmin<T>>::insert((collection.id, user), true);1403		} else {1404			<AdminAmount<T>>::insert(collection.id, amount.saturating_sub(1));1405			<IsAdmin<T>>::remove((collection.id, user));1406		}14071408		Ok(())1409	}14101411	/// Merge set fields from `new_limit` to `old_limit`.1412	pub fn clamp_limits(1413		mode: CollectionMode,1414		old_limit: &CollectionLimits,1415		mut new_limit: CollectionLimits,1416	) -> Result<CollectionLimits, DispatchError> {1417		let limits = old_limit;1418		limit_default!(old_limit, new_limit,1419			account_token_ownership_limit => ensure!(1420				new_limit <= MAX_TOKEN_OWNERSHIP,1421				<Error<T>>::CollectionLimitBoundsExceeded,1422			),1423			sponsored_data_size => ensure!(1424				new_limit <= CUSTOM_DATA_LIMIT,1425				<Error<T>>::CollectionLimitBoundsExceeded,1426			),14271428			sponsored_data_rate_limit => {},1429			token_limit => ensure!(1430				old_limit >= new_limit && new_limit > 0,1431				<Error<T>>::CollectionTokenLimitExceeded1432			),14331434			sponsor_transfer_timeout(match mode {1435				CollectionMode::NFT => NFT_SPONSOR_TRANSFER_TIMEOUT,1436				CollectionMode::Fungible(_) => FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,1437				CollectionMode::ReFungible => REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,1438			}) => ensure!(1439				new_limit <= MAX_SPONSOR_TIMEOUT,1440				<Error<T>>::CollectionLimitBoundsExceeded,1441			),1442			sponsor_approve_timeout => {},1443			owner_can_transfer => ensure!(1444				!limits.owner_can_transfer_instaled() ||1445				old_limit || !new_limit,1446				<Error<T>>::OwnerPermissionsCantBeReverted,1447			),1448			owner_can_destroy => ensure!(1449				old_limit || !new_limit,1450				<Error<T>>::OwnerPermissionsCantBeReverted,1451			),1452			transfers_enabled => {},1453		);1454		Ok(new_limit)1455	}14561457	/// Merge set fields from `new_permission` to `old_permission`.1458	pub fn clamp_permissions(1459		_mode: CollectionMode,1460		old_permission: &CollectionPermissions,1461		mut new_permission: CollectionPermissions,1462	) -> Result<CollectionPermissions, DispatchError> {1463		limit_default_clone!(old_permission, new_permission,1464			access => {},1465			mint_mode => {},1466			nesting => { /* todo check for permissive, if only it gets out of benchmarks */ },1467		);1468		Ok(new_permission)1469	}1470}14711472/// Indicates unsupported methods by returning [Error::UnsupportedOperation].1473#[macro_export]1474macro_rules! unsupported {1475	($runtime:path) => {1476		Err($crate::Error::<$runtime>::UnsupportedOperation.into())1477	};1478}14791480/// Return weights for various worst-case operations.1481pub trait CommonWeightInfo<CrossAccountId> {1482	/// Weight of item creation.1483	fn create_item() -> Weight;14841485	/// Weight of items creation.1486	fn create_multiple_items(amount: &[CreateItemData]) -> Weight;14871488	/// Weight of items creation.1489	fn create_multiple_items_ex(cost: &CreateItemExData<CrossAccountId>) -> Weight;14901491	/// The weight of the burning item.1492	fn burn_item() -> Weight;14931494	/// Property setting weight.1495	///1496	/// * `amount`- The number of properties to set.1497	fn set_collection_properties(amount: u32) -> Weight;14981499	/// Collection property deletion weight.1500	///1501	/// * `amount`- The number of properties to set.1502	fn delete_collection_properties(amount: u32) -> Weight;15031504	/// Token property setting weight.1505	///1506	/// * `amount`- The number of properties to set.1507	fn set_token_properties(amount: u32) -> Weight;15081509	/// Token property deletion weight.1510	///1511	/// * `amount`- The number of properties to delete.1512	fn delete_token_properties(amount: u32) -> Weight;15131514	/// Token property permissions set weight.1515	///1516	/// * `amount`- The number of property permissions to set.1517	fn set_token_property_permissions(amount: u32) -> Weight;15181519	/// Transfer price of the token or its parts.1520	fn transfer() -> Weight;15211522	/// The price of setting the permission of the operation from another user.1523	fn approve() -> Weight;15241525	/// Transfer price from another user.1526	fn transfer_from() -> Weight;15271528	/// The price of burning a token from another user.1529	fn burn_from() -> Weight;15301531	/// Differs from burn_item in case of Fungible and Refungible, as it should burn1532	/// whole users's balance.1533	///1534	/// This method shouldn't be used directly, as it doesn't count breadth price, use [burn_recursively](CommonWeightInfo::burn_recursively) instead1535	fn burn_recursively_self_raw() -> Weight;15361537	/// Cost of iterating over `amount` children while burning, without counting child burning itself.1538	///1539	/// This method shouldn't be used directly, as it doesn't count depth price, use [burn_recursively](CommonWeightInfo::burn_recursively) instead1540	fn burn_recursively_breadth_raw(amount: u32) -> Weight;15411542	/// The price of recursive burning a token.1543	///1544	/// `max_selfs` - The maximum burning weight of the token itself.1545	/// `max_breadth` - The maximum number of nested tokens to burn.1546	fn burn_recursively(max_selfs: u32, max_breadth: u32) -> Weight {1547		Self::burn_recursively_self_raw()1548			.saturating_mul(max_selfs.max(1) as u64)1549			.saturating_add(Self::burn_recursively_breadth_raw(max_breadth))1550	}15511552	/// The price of retrieving token owner1553	fn token_owner() -> Weight;15541555	/// The price of setting approval for all1556	fn set_allowance_for_all() -> Weight;1557}15581559/// Weight info extension trait for refungible pallet.1560pub trait RefungibleExtensionsWeightInfo {1561	/// Weight of token repartition.1562	fn repartition() -> Weight;1563}15641565/// Common collection operations.1566///1567/// It wraps methods in Fungible, Nonfungible and Refungible pallets1568/// and adds weight info.1569pub trait CommonCollectionOperations<T: Config> {1570	/// Create token.1571	///1572	/// * `sender` - The user who mint the token and pays for the transaction.1573	/// * `to` - The user who will own the token.1574	/// * `data` - Token data.1575	/// * `nesting_budget` - A budget that can be spent on nesting tokens.1576	fn create_item(1577		&self,1578		sender: T::CrossAccountId,1579		to: T::CrossAccountId,1580		data: CreateItemData,1581		nesting_budget: &dyn Budget,1582	) -> DispatchResultWithPostInfo;15831584	/// Create multiple tokens.1585	///1586	/// * `sender` - The user who mint the token and pays for the transaction.1587	/// * `to` - The user who will own the token.1588	/// * `data` - Token data.1589	/// * `nesting_budget` - A budget that can be spent on nesting tokens.1590	fn create_multiple_items(1591		&self,1592		sender: T::CrossAccountId,1593		to: T::CrossAccountId,1594		data: Vec<CreateItemData>,1595		nesting_budget: &dyn Budget,1596	) -> DispatchResultWithPostInfo;15971598	/// Create multiple tokens.1599	///1600	/// * `sender` - The user who mint the token and pays for the transaction.1601	/// * `to` - The user who will own the token.1602	/// * `data` - Token data.1603	/// * `nesting_budget` - A budget that can be spent on nesting tokens.1604	fn create_multiple_items_ex(1605		&self,1606		sender: T::CrossAccountId,1607		data: CreateItemExData<T::CrossAccountId>,1608		nesting_budget: &dyn Budget,1609	) -> DispatchResultWithPostInfo;16101611	/// Burn token.1612	///1613	/// * `sender` - The user who owns the token.1614	/// * `token` - Token id that will burned.1615	/// * `amount` - The number of parts of the token that will be burned.1616	fn burn_item(1617		&self,1618		sender: T::CrossAccountId,1619		token: TokenId,1620		amount: u128,1621	) -> DispatchResultWithPostInfo;16221623	/// Burn token and all nested tokens recursievly.1624	///1625	/// * `sender` - The user who owns the token.1626	/// * `token` - Token id that will burned.1627	/// * `self_budget` - The budget that can be spent on burning tokens.1628	/// * `breadth_budget` - The budget that can be spent on burning nested tokens.1629	fn burn_item_recursively(1630		&self,1631		sender: T::CrossAccountId,1632		token: TokenId,1633		self_budget: &dyn Budget,1634		breadth_budget: &dyn Budget,1635	) -> DispatchResultWithPostInfo;16361637	/// Set collection properties.1638	///1639	/// * `sender` - Must be either the owner of the collection or its admin.1640	/// * `properties` - Properties to be set.1641	fn set_collection_properties(1642		&self,1643		sender: T::CrossAccountId,1644		properties: Vec<Property>,1645	) -> DispatchResultWithPostInfo;16461647	/// Delete collection properties.1648	///1649	/// * `sender` - Must be either the owner of the collection or its admin.1650	/// * `properties` - The properties to be removed.1651	fn delete_collection_properties(1652		&self,1653		sender: &T::CrossAccountId,1654		property_keys: Vec<PropertyKey>,1655	) -> DispatchResultWithPostInfo;16561657	/// Set token properties.1658	///1659	/// The appropriate [`PropertyPermission`] for the token property1660	/// must be set with [`Self::set_token_property_permissions`].1661	///1662	/// * `sender` - Must be either the owner of the token or its admin.1663	/// * `token_id` - The token for which the properties are being set.1664	/// * `properties` - Properties to be set.1665	/// * `budget` - Budget for setting properties.1666	fn set_token_properties(1667		&self,1668		sender: T::CrossAccountId,1669		token_id: TokenId,1670		properties: Vec<Property>,1671		budget: &dyn Budget,1672	) -> DispatchResultWithPostInfo;16731674	/// Remove token properties.1675	///1676	/// The appropriate [`PropertyPermission`] for the token property1677	/// must be set with [`Self::set_token_property_permissions`].1678	///1679	/// * `sender` - Must be either the owner of the token or its admin.1680	/// * `token_id` - The token for which the properties are being remove.1681	/// * `property_keys` - Keys to remove corresponding properties.1682	/// * `budget` - Budget for removing properties.1683	fn delete_token_properties(1684		&self,1685		sender: T::CrossAccountId,1686		token_id: TokenId,1687		property_keys: Vec<PropertyKey>,1688		budget: &dyn Budget,1689	) -> DispatchResultWithPostInfo;16901691	/// Set token property permissions.1692	///1693	/// * `sender` - Must be either the owner of the token or its admin.1694	/// * `token_id` - The token for which the properties are being set.1695	/// * `property_permissions` - Property permissions to be set.1696	/// * `budget` - Budget for setting properties.1697	fn set_token_property_permissions(1698		&self,1699		sender: &T::CrossAccountId,1700		property_permissions: Vec<PropertyKeyPermission>,1701	) -> DispatchResultWithPostInfo;17021703	/// Transfer amount of token pieces.1704	///1705	/// * `sender` - Donor user.1706	/// * `to` - Recepient user.1707	/// * `token` - The token of which parts are being sent.1708	/// * `amount` - The number of parts of the token that will be transferred.1709	/// * `budget` - The maximum budget that can be spent on the transfer.1710	fn transfer(1711		&self,1712		sender: T::CrossAccountId,1713		to: T::CrossAccountId,1714		token: TokenId,1715		amount: u128,1716		budget: &dyn Budget,1717	) -> DispatchResultWithPostInfo;17181719	/// Grant access to another account to transfer parts of the token owned by the calling user via [Self::transfer_from].1720	///1721	/// * `sender` - The user who grants access to the token.1722	/// * `spender` - The user to whom the rights are granted.1723	/// * `token` - The token to which access is granted.1724	/// * `amount` - The amount of pieces that another user can dispose of.1725	fn approve(1726		&self,1727		sender: T::CrossAccountId,1728		spender: T::CrossAccountId,1729		token: TokenId,1730		amount: u128,1731	) -> DispatchResultWithPostInfo;17321733	/// Send parts of a token owned by another user.1734	///1735	/// Before calling this method, you must grant rights to the calling user via [`Self::approve`].1736	///1737	/// * `sender` - The user who must have access to the token (see [`Self::approve`]).1738	/// * `from` - The user who owns the token.1739	/// * `to` - Recepient user.1740	/// * `token` - The token of which parts are being sent.1741	/// * `amount` - The number of parts of the token that will be transferred.1742	/// * `budget` - The maximum budget that can be spent on the transfer.1743	fn transfer_from(1744		&self,1745		sender: T::CrossAccountId,1746		from: T::CrossAccountId,1747		to: T::CrossAccountId,1748		token: TokenId,1749		amount: u128,1750		budget: &dyn Budget,1751	) -> DispatchResultWithPostInfo;17521753	/// Burn parts of a token owned by another user.1754	///1755	/// Before calling this method, you must grant rights to the calling user via [`Self::approve`].1756	///1757	/// * `sender` - The user who must have access to the token (see [`Self::approve`]).1758	/// * `from` - The user who owns the token.1759	/// * `token` - The token of which parts are being sent.1760	/// * `amount` - The number of parts of the token that will be transferred.1761	/// * `budget` - The maximum budget that can be spent on the burn.1762	fn burn_from(1763		&self,1764		sender: T::CrossAccountId,1765		from: T::CrossAccountId,1766		token: TokenId,1767		amount: u128,1768		budget: &dyn Budget,1769	) -> DispatchResultWithPostInfo;17701771	/// Check permission to nest token.1772	///1773	/// * `sender` - The user who initiated the check.1774	/// * `from` - The token that is checked for embedding.1775	/// * `under` - Token under which to check.1776	/// * `budget` - The maximum budget that can be spent on the check.1777	fn check_nesting(1778		&self,1779		sender: T::CrossAccountId,1780		from: (CollectionId, TokenId),1781		under: TokenId,1782		budget: &dyn Budget,1783	) -> DispatchResult;17841785	/// Nest one token into another.1786	///1787	/// * `under` - Token holder.1788	/// * `to_nest` - Nested token.1789	fn nest(&self, under: TokenId, to_nest: (CollectionId, TokenId));17901791	/// Unnest token.1792	///1793	/// * `under` - Token holder.1794	/// * `to_nest` - Token to unnest.1795	fn unnest(&self, under: TokenId, to_nest: (CollectionId, TokenId));17961797	/// Get all user tokens.1798	///1799	/// * `account` - Account for which you need to get tokens.1800	fn account_tokens(&self, account: T::CrossAccountId) -> Vec<TokenId>;18011802	/// Get all the tokens in the collection.1803	fn collection_tokens(&self) -> Vec<TokenId>;18041805	/// Check if the token exists.1806	///1807	/// * `token` - Id token to check.1808	fn token_exists(&self, token: TokenId) -> bool;18091810	/// Get the id of the last minted token.1811	fn last_token_id(&self) -> TokenId;18121813	/// Get the owner of the token.1814	///1815	/// * `token` - The token for which you need to find out the owner.1816	fn token_owner(&self, token: TokenId) -> Option<T::CrossAccountId>;18171818	/// Returns 10 tokens owners in no particular order.1819	///1820	/// * `token` - The token for which you need to find out the owners.1821	fn token_owners(&self, token: TokenId) -> Vec<T::CrossAccountId>;18221823	/// Get the value of the token property by key.1824	///1825	/// * `token` - Token with the property to get.1826	/// * `key` - Property name.1827	fn token_property(&self, token_id: TokenId, key: &PropertyKey) -> Option<PropertyValue>;18281829	/// Get a set of token properties by key vector.1830	///1831	/// * `token` - Token with the property to get.1832	/// * `keys` - Vector of property keys. If this parameter is [None](sp_std::result::Result),1833	/// then all properties are returned.1834	fn token_properties(&self, token: TokenId, keys: Option<Vec<PropertyKey>>) -> Vec<Property>;18351836	/// Amount of unique collection tokens1837	fn total_supply(&self) -> u32;18381839	/// Amount of different tokens account has.1840	///1841	/// * `account` - The account for which need to get the balance.1842	fn account_balance(&self, account: T::CrossAccountId) -> u32;18431844	/// Amount of specific token account have.1845	fn balance(&self, account: T::CrossAccountId, token: TokenId) -> u128;18461847	/// Amount of token pieces1848	fn total_pieces(&self, token: TokenId) -> Option<u128>;18491850	/// Get the number of parts of the token that a trusted user can manage.1851	///1852	/// * `sender` - Trusted user.1853	/// * `spender` - Owner of the token.1854	/// * `token` - The token for which to get the value.1855	fn allowance(1856		&self,1857		sender: T::CrossAccountId,1858		spender: T::CrossAccountId,1859		token: TokenId,1860	) -> u128;18611862	/// Get extension for RFT collection.1863	fn refungible_extensions(&self) -> Option<&dyn RefungibleExtensions<T>>;18641865	/// The `operator` is allowed to transfer all tokens of the `owner` on their behalf.1866	/// * `owner` - Token owner1867	/// * `operator` - Operator1868	/// * `approve` - Should operator status be granted or revoked?1869	fn set_allowance_for_all(1870		&self,1871		owner: T::CrossAccountId,1872		operator: T::CrossAccountId,1873		approve: bool,1874	) -> DispatchResultWithPostInfo;18751876	/// Tells whether the given `owner` approves the `operator`.1877	fn allowance_for_all(&self, owner: T::CrossAccountId, operator: T::CrossAccountId) -> bool;1878}18791880/// Extension for RFT collection.1881pub trait RefungibleExtensions<T>1882where1883	T: Config,1884{1885	/// Change the number of parts of the token.1886	///1887	/// When the value changes down, this function is equivalent to burning parts of the token.1888	///1889	/// * `sender` - The user calling the repartition operation. Must be the owner of the token.1890	/// * `token` - The token for which you want to change the number of parts.1891	/// * `amount` - The new value of the parts of the token.1892	fn repartition(1893		&self,1894		sender: &T::CrossAccountId,1895		token: TokenId,1896		amount: u128,1897	) -> DispatchResultWithPostInfo;1898}18991900/// Merge [`DispatchResult`] with [`Weight`] into [`DispatchResultWithPostInfo`].1901///1902/// Used for [`CommonCollectionOperations`] implementations and flexible enough to do so.1903pub fn with_weight(res: DispatchResult, weight: Weight) -> DispatchResultWithPostInfo {1904	let post_info = PostDispatchInfo {1905		actual_weight: Some(weight),1906		pays_fee: Pays::Yes,1907	};1908	match res {1909		Ok(()) => Ok(post_info),1910		Err(error) => Err(DispatchErrorWithPostInfo { post_info, error }),1911	}1912}19131914impl<T: Config> From<PropertiesError> for Error<T> {1915	fn from(error: PropertiesError) -> Self {1916		match error {1917			PropertiesError::NoSpaceForProperty => Self::NoSpaceForProperty,1918			PropertiesError::PropertyLimitReached => Self::PropertyLimitReached,1919			PropertiesError::InvalidCharacterInPropertyKey => Self::InvalidCharacterInPropertyKey,1920			PropertiesError::PropertyKeyIsTooLong => Self::PropertyKeyIsTooLong,1921			PropertiesError::EmptyPropertyKey => Self::EmptyPropertyKey,1922		}1923	}1924}
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//! # Common pallet18//!19//! The Common pallet provides functionality for handling collections.20//!21//! ## Overview22//!23//! The Common pallet provides an interface for common collection operations for different collection types24//! (see [CommonCollectionOperations]), as well as a generic dispatcher for these, see [dispatch] module.25//! It also provides this functionality to EVM, see [erc] and [eth] modules.26//!27//! The Common pallet provides functions for:28//!29//! - Setting and approving collection sponsor.30//! - Get\set\delete allow list.31//! - Get\set\delete collection properties.32//! - Get\set\delete collection property permissions.33//! - Get\set\delete token property permissions.34//! - Get\set\delete collection administrators.35//! - Checking access permissions.36//!37//! ### Terminology38//! **Collection sponsor** - For the collection, you can set a sponsor, at whose expense it will39//! be possible to mint tokens.40//!41//! **Allow list** - List of users who have the right to minting tokens.42//!43//! **Collection properties** - Collection properties are simply key-value stores where various44//! metadata can be placed.45//!46//! **Permissions on token properties** - For each property in the token can be set permission47//! to change, see [`PropertyPermission`].48//!49//! **Collection administrator** - For a collection, you can set administrators who have the right50//! to most actions on the collection.5152#![warn(missing_docs)]53#![cfg_attr(not(feature = "std"), no_std)]54extern crate alloc;5556use core::ops::{Deref, DerefMut};57use pallet_evm_coder_substrate::{SubstrateRecorder, WithRecorder};58use sp_std::vec::Vec;59use pallet_evm::{account::CrossAccountId, Pallet as PalletEvm};60use evm_coder::ToLog;61use frame_support::{62	dispatch::{DispatchErrorWithPostInfo, DispatchResultWithPostInfo, Weight, PostDispatchInfo},63	ensure,64	traits::{Imbalance, Get, Currency, WithdrawReasons, ExistenceRequirement},65	dispatch::Pays,66	transactional,67};68use pallet_evm::GasWeightMapping;69use up_data_structs::{70	COLLECTION_NUMBER_LIMIT,71	Collection,72	RpcCollection,73	CollectionFlags,74	RpcCollectionFlags,75	CollectionId,76	CreateItemData,77	MAX_TOKEN_PREFIX_LENGTH,78	COLLECTION_ADMINS_LIMIT,79	TokenId,80	TokenChild,81	CollectionStats,82	MAX_TOKEN_OWNERSHIP,83	CollectionMode,84	NFT_SPONSOR_TRANSFER_TIMEOUT,85	FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,86	REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,87	MAX_SPONSOR_TIMEOUT,88	CUSTOM_DATA_LIMIT,89	CollectionLimits,90	CreateCollectionData,91	SponsorshipState,92	CreateItemExData,93	SponsoringRateLimit,94	budget::Budget,95	PhantomType,96	Property,97	Properties,98	PropertiesPermissionMap,99	PropertyKey,100	PropertyValue,101	PropertyPermission,102	PropertiesError,103	PropertyKeyPermission,104	TokenData,105	TrySetProperty,106	PropertyScope,107	// RMRK108	RmrkCollectionInfo,109	RmrkInstanceInfo,110	RmrkResourceInfo,111	RmrkPropertyInfo,112	RmrkBaseInfo,113	RmrkPartType,114	RmrkBoundedTheme,115	RmrkNftChild,116	CollectionPermissions,117};118119pub use pallet::*;120use sp_core::H160;121use sp_runtime::{ArithmeticError, DispatchError, DispatchResult};122#[cfg(feature = "runtime-benchmarks")]123pub mod benchmarking;124pub mod dispatch;125pub mod erc;126pub mod eth;127pub mod weights;128129/// Weight info.130pub type SelfWeightOf<T> = <T as Config>::WeightInfo;131132/// Collection handle contains information about collection data and id.133/// Also provides functionality to count consumed gas.134///135/// CollectionHandle is used as a generic wrapper for collections of all types.136/// It allows to perform common operations and queries on any collection type,137/// both completely general for all, as well as their respective implementations of [`CommonCollectionOperations`].138#[must_use = "Should call submit_logs or save, otherwise some data will be lost for evm side"]139pub struct CollectionHandle<T: Config> {140	/// Collection id141	pub id: CollectionId,142	collection: Collection<T::AccountId>,143	/// Substrate recorder for counting consumed gas144	pub recorder: SubstrateRecorder<T>,145}146147impl<T: Config> WithRecorder<T> for CollectionHandle<T> {148	fn recorder(&self) -> &SubstrateRecorder<T> {149		&self.recorder150	}151	fn into_recorder(self) -> SubstrateRecorder<T> {152		self.recorder153	}154}155156impl<T: Config> CollectionHandle<T> {157	/// Same as [CollectionHandle::new] but with an explicit gas limit.158	pub fn new_with_gas_limit(id: CollectionId, gas_limit: u64) -> Option<Self> {159		<CollectionById<T>>::get(id).map(|collection| Self {160			id,161			collection,162			recorder: SubstrateRecorder::new(gas_limit),163		})164	}165166	/// Same as [CollectionHandle::new] but with an existed [`SubstrateRecorder`].167	pub fn new_with_recorder(id: CollectionId, recorder: SubstrateRecorder<T>) -> Option<Self> {168		<CollectionById<T>>::get(id).map(|collection| Self {169			id,170			collection,171			recorder,172		})173	}174175	/// Retrives collection data from storage and creates collection handle with default parameters.176	/// If collection not found return `None`177	pub fn new(id: CollectionId) -> Option<Self> {178		Self::new_with_gas_limit(id, u64::MAX)179	}180181	/// Same as [`CollectionHandle::new`] but if collection not found [CollectionNotFound](Error::CollectionNotFound) returned.182	pub fn try_get(id: CollectionId) -> Result<Self, DispatchError> {183		Ok(Self::new(id).ok_or(<Error<T>>::CollectionNotFound)?)184	}185186	/// Consume gas for reading.187	pub fn consume_store_reads(&self, reads: u64) -> evm_coder::execution::Result<()> {188		self.recorder189			.consume_gas(T::GasWeightMapping::weight_to_gas(Weight::from_ref_time(190				<T as frame_system::Config>::DbWeight::get()191					.read192					.saturating_mul(reads),193			)))194	}195196	/// Consume gas for writing.197	pub fn consume_store_writes(&self, writes: u64) -> evm_coder::execution::Result<()> {198		self.recorder199			.consume_gas(T::GasWeightMapping::weight_to_gas(Weight::from_ref_time(200				<T as frame_system::Config>::DbWeight::get()201					.write202					.saturating_mul(writes),203			)))204	}205206	/// Consume gas for reading and writing.207	pub fn consume_store_reads_and_writes(208		&self,209		reads: u64,210		writes: u64,211	) -> evm_coder::execution::Result<()> {212		let weight = <T as frame_system::Config>::DbWeight::get();213		let reads = weight.read.saturating_mul(reads);214		let writes = weight.read.saturating_mul(writes);215		self.recorder216			.consume_gas(T::GasWeightMapping::weight_to_gas(Weight::from_ref_time(217				reads.saturating_add(writes),218			)))219	}220221	/// Save collection to storage.222	pub fn save(&self) -> DispatchResult {223		<CollectionById<T>>::insert(self.id, &self.collection);224		Ok(())225	}226227	/// Set collection sponsor.228	///229	/// Unique collections allows sponsoring for certain actions.230	/// This method allows you to set the sponsor of the collection.231	/// In order for sponsorship to become active, it must be confirmed through [`Self::confirm_sponsorship`].232	pub fn set_sponsor(233		&mut self,234		sender: &T::CrossAccountId,235		sponsor: T::AccountId,236	) -> DispatchResult {237		self.check_is_internal()?;238		self.check_is_owner_or_admin(sender)?;239240		self.collection.sponsorship = SponsorshipState::Unconfirmed(sponsor.clone());241242		<Pallet<T>>::deposit_event(Event::<T>::CollectionSponsorSet(self.id, sponsor));243		<PalletEvm<T>>::deposit_log(244			erc::CollectionHelpersEvents::CollectionChanged {245				collection_id: eth::collection_id_to_address(self.id),246			}247			.to_log(T::ContractAddress::get()),248		);249250		self.save()251	}252253	/// Force set `sponsor`.254	///255	/// Differs from [`set_sponsor`][`Self::set_sponsor`] in that confirmation256	/// from the `sponsor` is not required.257	///258	/// # Arguments259	///260	/// * `sender`: Caller's account.261	/// * `sponsor`: ID of the account of the sponsor-to-be.262	pub fn force_set_sponsor(&mut self, sponsor: T::AccountId) -> DispatchResult {263		self.check_is_internal()?;264265		self.collection.sponsorship = SponsorshipState::Confirmed(sponsor.clone());266267		<Pallet<T>>::deposit_event(Event::<T>::CollectionSponsorSet(self.id, sponsor.clone()));268		<Pallet<T>>::deposit_event(Event::<T>::SponsorshipConfirmed(self.id, sponsor));269		<PalletEvm<T>>::deposit_log(270			erc::CollectionHelpersEvents::CollectionChanged {271				collection_id: eth::collection_id_to_address(self.id),272			}273			.to_log(T::ContractAddress::get()),274		);275276		self.save()277	}278279	/// Confirm sponsorship280	///281	/// In order for the sponsorship to become active, the user set as the sponsor must confirm their participation.282	/// Before confirming sponsorship, the user must be specified as the sponsor of the collection via [`Self::set_sponsor`].283	pub fn confirm_sponsorship(&mut self, sender: &T::AccountId) -> DispatchResult {284		self.check_is_internal()?;285		ensure!(286			self.collection.sponsorship.pending_sponsor() == Some(sender),287			Error::<T>::ConfirmUnsetSponsorFail288		);289290		self.collection.sponsorship = SponsorshipState::Confirmed(sender.clone());291292		<Pallet<T>>::deposit_event(Event::<T>::SponsorshipConfirmed(self.id, sender.clone()));293		<PalletEvm<T>>::deposit_log(294			erc::CollectionHelpersEvents::CollectionChanged {295				collection_id: eth::collection_id_to_address(self.id),296			}297			.to_log(T::ContractAddress::get()),298		);299300		self.save()301	}302303	/// Remove collection sponsor.304	pub fn remove_sponsor(&mut self, sender: &T::CrossAccountId) -> DispatchResult {305		self.check_is_internal()?;306		self.check_is_owner(sender)?;307308		self.collection.sponsorship = SponsorshipState::Disabled;309310		<Pallet<T>>::deposit_event(Event::<T>::CollectionSponsorRemoved(self.id));311		<PalletEvm<T>>::deposit_log(312			erc::CollectionHelpersEvents::CollectionChanged {313				collection_id: eth::collection_id_to_address(self.id),314			}315			.to_log(T::ContractAddress::get()),316		);317		self.save()318	}319320	/// Force remove `sponsor`.321	///322	/// Differs from `remove_sponsor` in that323	/// it doesn't require consent from the `owner` of the collection.324	pub fn force_remove_sponsor(&mut self) -> DispatchResult {325		self.check_is_internal()?;326327		self.collection.sponsorship = SponsorshipState::Disabled;328329		<Pallet<T>>::deposit_event(Event::<T>::CollectionSponsorRemoved(self.id));330		<PalletEvm<T>>::deposit_log(331			erc::CollectionHelpersEvents::CollectionChanged {332				collection_id: eth::collection_id_to_address(self.id),333			}334			.to_log(T::ContractAddress::get()),335		);336		self.save()337	}338339	/// Checks that the collection was created with, and must be operated upon through **Unique API**.340	/// Now check only the `external` flag and if it's **true**, then return [`Error::CollectionIsExternal`] error.341	pub fn check_is_internal(&self) -> DispatchResult {342		if self.flags.external {343			return Err(<Error<T>>::CollectionIsExternal)?;344		}345346		Ok(())347	}348349	/// Checks that the collection was created with, and must be operated upon through an **assimilated API**.350	/// Now check only the `external` flag and if it's **false**, then return [`Error::CollectionIsInternal`] error.351	pub fn check_is_external(&self) -> DispatchResult {352		if !self.flags.external {353			return Err(<Error<T>>::CollectionIsInternal)?;354		}355356		Ok(())357	}358}359360impl<T: Config> Deref for CollectionHandle<T> {361	type Target = Collection<T::AccountId>;362363	fn deref(&self) -> &Self::Target {364		&self.collection365	}366}367368impl<T: Config> DerefMut for CollectionHandle<T> {369	fn deref_mut(&mut self) -> &mut Self::Target {370		&mut self.collection371	}372}373374impl<T: Config> CollectionHandle<T> {375	/// Checks if the `user` is the owner of the collection.376	pub fn check_is_owner(&self, user: &T::CrossAccountId) -> DispatchResult {377		ensure!(*user.as_sub() == self.owner, <Error<T>>::NoPermission);378		Ok(())379	}380381	/// Returns **true** if the `user` is the owner or administrator of the collection.382	pub fn is_owner_or_admin(&self, user: &T::CrossAccountId) -> bool {383		*user.as_sub() == self.owner || <IsAdmin<T>>::get((self.id, user))384	}385386	/// Checks if the `user` is the owner or administrator of the collection.387	pub fn check_is_owner_or_admin(&self, user: &T::CrossAccountId) -> DispatchResult {388		ensure!(self.is_owner_or_admin(user), <Error<T>>::NoPermission);389		Ok(())390	}391392	/// Return **true** if `user` was not allowed to have tokens, and he can ignore such restrictions.393	pub fn ignores_allowance(&self, user: &T::CrossAccountId) -> bool {394		self.limits.owner_can_transfer() && self.is_owner_or_admin(user)395	}396397	/// Return **true** if `user` does not have enough token parts, and he can ignore such restrictions.398	pub fn ignores_owned_amount(&self, user: &T::CrossAccountId) -> bool {399		self.limits.owner_can_transfer() && self.is_owner_or_admin(user)400	}401402	/// Checks if the user is in the allow list. If not [Error::AddressNotInAllowlist] returns.403	pub fn check_allowlist(&self, user: &T::CrossAccountId) -> DispatchResult {404		ensure!(405			<Allowlist<T>>::get((self.id, user)),406			<Error<T>>::AddressNotInAllowlist407		);408		Ok(())409	}410411	/// Changes collection owner to another account412	/// #### Store read/writes413	/// 1 writes414	pub fn change_owner(415		&mut self,416		caller: T::CrossAccountId,417		new_owner: T::CrossAccountId,418	) -> DispatchResult {419		self.check_is_internal()?;420		self.check_is_owner(&caller)?;421		self.collection.owner = new_owner.as_sub().clone();422423		<Pallet<T>>::deposit_event(Event::<T>::CollectionOwnedChanged(424			self.id,425			new_owner.as_sub().clone(),426		));427		<PalletEvm<T>>::deposit_log(428			erc::CollectionHelpersEvents::CollectionChanged {429				collection_id: eth::collection_id_to_address(self.id),430			}431			.to_log(T::ContractAddress::get()),432		);433434		self.save()435	}436}437438#[frame_support::pallet]439pub mod pallet {440	use super::*;441	use dispatch::CollectionDispatch;442	use frame_support::{Blake2_128Concat, pallet_prelude::*, storage::Key, traits::StorageVersion};443	use frame_system::pallet_prelude::*;444	use frame_support::traits::Currency;445	use up_data_structs::{TokenId, mapping::TokenAddressMapping};446	use scale_info::TypeInfo;447	use weights::WeightInfo;448449	#[pallet::config]450	pub trait Config:451		frame_system::Config + pallet_evm_coder_substrate::Config + pallet_evm::Config + TypeInfo452	{453		/// Weight information for functions of this pallet.454		type WeightInfo: WeightInfo;455456		/// Events compatible with [`frame_system::Config::Event`].457		type RuntimeEvent: IsType<<Self as frame_system::Config>::RuntimeEvent> + From<Event<Self>>;458459		/// Handler of accounts and payment.460		type Currency: Currency<Self::AccountId>;461462		/// Set price to create a collection.463		#[pallet::constant]464		type CollectionCreationPrice: Get<465			<<Self as Config>::Currency as Currency<Self::AccountId>>::Balance,466		>;467468		/// Dispatcher of operations on collections.469		type CollectionDispatch: CollectionDispatch<Self>;470471		/// Account which holds the chain's treasury.472		type TreasuryAccountId: Get<Self::AccountId>;473474		/// Address under which the CollectionHelper contract would be available.475		#[pallet::constant]476		type ContractAddress: Get<H160>;477478		/// Mapper for token addresses to Ethereum addresses.479		type EvmTokenAddressMapping: TokenAddressMapping<H160>;480481		/// Mapper for token addresses to [`CrossAccountId`].482		type CrossTokenAddressMapping: TokenAddressMapping<Self::CrossAccountId>;483	}484485	const STORAGE_VERSION: StorageVersion = StorageVersion::new(1);486487	#[pallet::pallet]488	#[pallet::storage_version(STORAGE_VERSION)]489	#[pallet::generate_store(pub(super) trait Store)]490	pub struct Pallet<T>(_);491492	#[pallet::extra_constants]493	impl<T: Config> Pallet<T> {494		/// Maximum admins per collection.495		pub fn collection_admins_limit() -> u32 {496			COLLECTION_ADMINS_LIMIT497		}498	}499500	#[pallet::event]501	#[pallet::generate_deposit(pub fn deposit_event)]502	pub enum Event<T: Config> {503		/// New collection was created504		CollectionCreated(505			/// Globally unique identifier of newly created collection.506			CollectionId,507			/// [`CollectionMode`] converted into _u8_.508			u8,509			/// Collection owner.510			T::AccountId,511		),512513		/// New collection was destroyed514		CollectionDestroyed(515			/// Globally unique identifier of collection.516			CollectionId,517		),518519		/// New item was created.520		ItemCreated(521			/// Id of the collection where item was created.522			CollectionId,523			/// Id of an item. Unique within the collection.524			TokenId,525			/// Owner of newly created item526			T::CrossAccountId,527			/// Always 1 for NFT528			u128,529		),530531		/// Collection item was burned.532		ItemDestroyed(533			/// Id of the collection where item was destroyed.534			CollectionId,535			/// Identifier of burned NFT.536			TokenId,537			/// Which user has destroyed its tokens.538			T::CrossAccountId,539			/// Amount of token pieces destroed. Always 1 for NFT.540			u128,541		),542543		/// Item was transferred544		Transfer(545			/// Id of collection to which item is belong.546			CollectionId,547			/// Id of an item.548			TokenId,549			/// Original owner of item.550			T::CrossAccountId,551			/// New owner of item.552			T::CrossAccountId,553			/// Amount of token pieces transfered. Always 1 for NFT.554			u128,555		),556557		/// Amount pieces of token owned by `sender` was approved for `spender`.558		Approved(559			/// Id of collection to which item is belong.560			CollectionId,561			/// Id of an item.562			TokenId,563			/// Original owner of item.564			T::CrossAccountId,565			/// Id for which the approval was granted.566			T::CrossAccountId,567			/// Amount of token pieces transfered. Always 1 for NFT.568			u128,569		),570571		/// A `sender` approves operations on all owned tokens for `spender`.572		ApprovedForAll(573			/// Id of collection to which item is belong.574			CollectionId,575			/// Owner of a wallet.576			T::CrossAccountId,577			/// Id for which operator status was granted or rewoked.578			T::CrossAccountId,579			/// Is operator status granted or revoked?580			bool,581		),582583		/// The colletion property has been added or edited.584		CollectionPropertySet(585			/// Id of collection to which property has been set.586			CollectionId,587			/// The property that was set.588			PropertyKey,589		),590591		/// The property has been deleted.592		CollectionPropertyDeleted(593			/// Id of collection to which property has been deleted.594			CollectionId,595			/// The property that was deleted.596			PropertyKey,597		),598599		/// The token property has been added or edited.600		TokenPropertySet(601			/// Identifier of the collection whose token has the property set.602			CollectionId,603			/// The token for which the property was set.604			TokenId,605			/// The property that was set.606			PropertyKey,607		),608609		/// The token property has been deleted.610		TokenPropertyDeleted(611			/// Identifier of the collection whose token has the property deleted.612			CollectionId,613			/// The token for which the property was deleted.614			TokenId,615			/// The property that was deleted.616			PropertyKey,617		),618619		/// The token property permission of a collection has been set.620		PropertyPermissionSet(621			/// ID of collection to which property permission has been set.622			CollectionId,623			/// The property permission that was set.624			PropertyKey,625		),626627		/// Address was added to the allow list.628		AllowListAddressAdded(629			/// ID of the affected collection.630			CollectionId,631			/// Address of the added account.632			T::CrossAccountId,633		),634635		/// Address was removed from the allow list.636		AllowListAddressRemoved(637			/// ID of the affected collection.638			CollectionId,639			/// Address of the removed account.640			T::CrossAccountId,641		),642643		/// Collection admin was added.644		CollectionAdminAdded(645			/// ID of the affected collection.646			CollectionId,647			/// Admin address.648			T::CrossAccountId,649		),650651		/// Collection admin was removed.652		CollectionAdminRemoved(653			/// ID of the affected collection.654			CollectionId,655			/// Removed admin address.656			T::CrossAccountId,657		),658659		/// Collection limits were set.660		CollectionLimitSet(661			/// ID of the affected collection.662			CollectionId,663		),664665		/// Collection owned was changed.666		CollectionOwnedChanged(667			/// ID of the affected collection.668			CollectionId,669			/// New owner address.670			T::AccountId,671		),672673		/// Collection permissions were set.674		CollectionPermissionSet(675			/// ID of the affected collection.676			CollectionId,677		),678679		/// Collection sponsor was set.680		CollectionSponsorSet(681			/// ID of the affected collection.682			CollectionId,683			/// New sponsor address.684			T::AccountId,685		),686687		/// New sponsor was confirm.688		SponsorshipConfirmed(689			/// ID of the affected collection.690			CollectionId,691			/// New sponsor address.692			T::AccountId,693		),694695		/// Collection sponsor was removed.696		CollectionSponsorRemoved(697			/// ID of the affected collection.698			CollectionId,699		),700	}701702	#[pallet::error]703	pub enum Error<T> {704		/// This collection does not exist.705		CollectionNotFound,706		/// Sender parameter and item owner must be equal.707		MustBeTokenOwner,708		/// No permission to perform action709		NoPermission,710		/// Destroying only empty collections is allowed711		CantDestroyNotEmptyCollection,712		/// Collection is not in mint mode.713		PublicMintingNotAllowed,714		/// Address is not in allow list.715		AddressNotInAllowlist,716717		/// Collection name can not be longer than 63 char.718		CollectionNameLimitExceeded,719		/// Collection description can not be longer than 255 char.720		CollectionDescriptionLimitExceeded,721		/// Token prefix can not be longer than 15 char.722		CollectionTokenPrefixLimitExceeded,723		/// Total collections bound exceeded.724		TotalCollectionsLimitExceeded,725		/// Exceeded max admin count726		CollectionAdminCountExceeded,727		/// Collection limit bounds per collection exceeded728		CollectionLimitBoundsExceeded,729		/// Tried to enable permissions which are only permitted to be disabled730		OwnerPermissionsCantBeReverted,731		/// Collection settings not allowing items transferring732		TransferNotAllowed,733		/// Account token limit exceeded per collection734		AccountTokenLimitExceeded,735		/// Collection token limit exceeded736		CollectionTokenLimitExceeded,737		/// Metadata flag frozen738		MetadataFlagFrozen,739740		/// Item does not exist741		TokenNotFound,742		/// Item is balance not enough743		TokenValueTooLow,744		/// Requested value is more than the approved745		ApprovedValueTooLow,746		/// Tried to approve more than owned747		CantApproveMoreThanOwned,748749		/// Can't transfer tokens to ethereum zero address750		AddressIsZero,751752		/// The operation is not supported753		UnsupportedOperation,754755		/// Insufficient funds to perform an action756		NotSufficientFounds,757758		/// User does not satisfy the nesting rule759		UserIsNotAllowedToNest,760		/// Only tokens from specific collections may nest tokens under this one761		SourceCollectionIsNotAllowedToNest,762763		/// Tried to store more data than allowed in collection field764		CollectionFieldSizeExceeded,765766		/// Tried to store more property data than allowed767		NoSpaceForProperty,768769		/// Tried to store more property keys than allowed770		PropertyLimitReached,771772		/// Property key is too long773		PropertyKeyIsTooLong,774775		/// Only ASCII letters, digits, and symbols `_`, `-`, and `.` are allowed776		InvalidCharacterInPropertyKey,777778		/// Empty property keys are forbidden779		EmptyPropertyKey,780781		/// Tried to access an external collection with an internal API782		CollectionIsExternal,783784		/// Tried to access an internal collection with an external API785		CollectionIsInternal,786787		/// This address is not set as sponsor, use setCollectionSponsor first.788		ConfirmUnsetSponsorFail,789790		/// The user is not an administrator.791		UserIsNotAdmin,792	}793794	/// Storage of the count of created collections. Essentially contains the last collection ID.795	#[pallet::storage]796	pub type CreatedCollectionCount<T> = StorageValue<Value = CollectionId, QueryKind = ValueQuery>;797798	/// Storage of the count of deleted collections.799	#[pallet::storage]800	pub type DestroyedCollectionCount<T> =801		StorageValue<Value = CollectionId, QueryKind = ValueQuery>;802803	/// Storage of collection info.804	#[pallet::storage]805	pub type CollectionById<T> = StorageMap<806		Hasher = Blake2_128Concat,807		Key = CollectionId,808		Value = Collection<<T as frame_system::Config>::AccountId>,809		QueryKind = OptionQuery,810	>;811812	/// Storage of collection properties.813	#[pallet::storage]814	#[pallet::getter(fn collection_properties)]815	pub type CollectionProperties<T> = StorageMap<816		Hasher = Blake2_128Concat,817		Key = CollectionId,818		Value = Properties,819		QueryKind = ValueQuery,820		OnEmpty = up_data_structs::CollectionProperties,821	>;822823	/// Storage of token property permissions of a collection.824	#[pallet::storage]825	#[pallet::getter(fn property_permissions)]826	pub type CollectionPropertyPermissions<T> = StorageMap<827		Hasher = Blake2_128Concat,828		Key = CollectionId,829		Value = PropertiesPermissionMap,830		QueryKind = ValueQuery,831	>;832833	/// Storage of the amount of collection admins.834	#[pallet::storage]835	pub type AdminAmount<T> = StorageMap<836		Hasher = Blake2_128Concat,837		Key = CollectionId,838		Value = u32,839		QueryKind = ValueQuery,840	>;841842	/// List of collection admins.843	#[pallet::storage]844	pub type IsAdmin<T: Config> = StorageNMap<845		Key = (846			Key<Blake2_128Concat, CollectionId>,847			Key<Blake2_128Concat, T::CrossAccountId>,848		),849		Value = bool,850		QueryKind = ValueQuery,851	>;852853	/// Allowlisted collection users.854	#[pallet::storage]855	pub type Allowlist<T: Config> = StorageNMap<856		Key = (857			Key<Blake2_128Concat, CollectionId>,858			Key<Blake2_128Concat, T::CrossAccountId>,859		),860		Value = bool,861		QueryKind = ValueQuery,862	>;863864	/// Not used by code, exists only to provide some types to metadata.865	#[pallet::storage]866	pub type DummyStorageValue<T: Config> = StorageValue<867		Value = (868			CollectionStats,869			CollectionId,870			TokenId,871			TokenChild,872			PhantomType<(873				TokenData<T::CrossAccountId>,874				RpcCollection<T::AccountId>,875				// RMRK876				RmrkCollectionInfo<T::AccountId>,877				RmrkInstanceInfo<T::AccountId>,878				RmrkResourceInfo,879				RmrkPropertyInfo,880				RmrkBaseInfo<T::AccountId>,881				RmrkPartType,882				RmrkBoundedTheme,883				RmrkNftChild,884			)>,885		),886		QueryKind = OptionQuery,887	>;888889	#[pallet::hooks]890	impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {891		fn on_runtime_upgrade() -> Weight {892			StorageVersion::new(1).put::<Pallet<T>>();893894			Weight::zero()895		}896	}897}898899impl<T: Config> Pallet<T> {900	/// Enshure that receiver address is correct.901	///902	/// Ethereum receiver 0x0000000000000000000000000000000000000000 is reserved, and shouldn't own tokens.903	pub fn ensure_correct_receiver(receiver: &T::CrossAccountId) -> DispatchResult {904		ensure!(905			&T::CrossAccountId::from_eth(H160([0; 20])) != receiver,906			<Error<T>>::AddressIsZero907		);908		Ok(())909	}910911	/// Get a vector of collection admins.912	pub fn adminlist(collection: CollectionId) -> Vec<T::CrossAccountId> {913		<IsAdmin<T>>::iter_prefix((collection,))914			.map(|(a, _)| a)915			.collect()916	}917918	/// Get a vector of users allowed to mint tokens.919	pub fn allowlist(collection: CollectionId) -> Vec<T::CrossAccountId> {920		<Allowlist<T>>::iter_prefix((collection,))921			.map(|(a, _)| a)922			.collect()923	}924925	/// Is `user` allowed to mint token in `collection`.926	pub fn allowed(collection: CollectionId, user: T::CrossAccountId) -> bool {927		<Allowlist<T>>::get((collection, user))928	}929930	/// Get statistics of collections.931	pub fn collection_stats() -> CollectionStats {932		let created = <CreatedCollectionCount<T>>::get();933		let destroyed = <DestroyedCollectionCount<T>>::get();934		CollectionStats {935			created: created.0,936			destroyed: destroyed.0,937			alive: created.0 - destroyed.0,938		}939	}940941	/// Get the effective limits for the collection.942	pub fn effective_collection_limits(collection: CollectionId) -> Option<CollectionLimits> {943		let collection = <CollectionById<T>>::get(collection)?;944		let limits = collection.limits;945		let effective_limits = CollectionLimits {946			account_token_ownership_limit: Some(limits.account_token_ownership_limit()),947			sponsored_data_size: Some(limits.sponsored_data_size()),948			sponsored_data_rate_limit: Some(949				limits950					.sponsored_data_rate_limit951					.unwrap_or(SponsoringRateLimit::SponsoringDisabled),952			),953			token_limit: Some(limits.token_limit()),954			sponsor_transfer_timeout: Some(limits.sponsor_transfer_timeout(955				match collection.mode {956					CollectionMode::NFT => NFT_SPONSOR_TRANSFER_TIMEOUT,957					CollectionMode::Fungible(_) => FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,958					CollectionMode::ReFungible => REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,959				},960			)),961			sponsor_approve_timeout: Some(limits.sponsor_approve_timeout()),962			owner_can_transfer: Some(limits.owner_can_transfer()),963			owner_can_destroy: Some(limits.owner_can_destroy()),964			transfers_enabled: Some(limits.transfers_enabled()),965		};966967		Some(effective_limits)968	}969970	/// Returns information about the `collection` adapted for rpc.971	pub fn rpc_collection(collection: CollectionId) -> Option<RpcCollection<T::AccountId>> {972		let Collection {973			name,974			description,975			owner,976			mode,977			token_prefix,978			sponsorship,979			limits,980			permissions,981			flags,982		} = <CollectionById<T>>::get(collection)?;983984		let token_property_permissions = <CollectionPropertyPermissions<T>>::get(collection)985			.into_iter()986			.map(|(key, permission)| PropertyKeyPermission { key, permission })987			.collect();988989		let properties = <CollectionProperties<T>>::get(collection)990			.into_iter()991			.map(|(key, value)| Property { key, value })992			.collect();993994		let permissions = CollectionPermissions {995			access: Some(permissions.access()),996			mint_mode: Some(permissions.mint_mode()),997			nesting: Some(permissions.nesting().clone()),998		};9991000		Some(RpcCollection {1001			name: name.into_inner(),1002			description: description.into_inner(),1003			owner,1004			mode,1005			token_prefix: token_prefix.into_inner(),1006			sponsorship,1007			limits,1008			permissions,1009			token_property_permissions,1010			properties,1011			read_only: flags.external,10121013			flags: RpcCollectionFlags {1014				foreign: flags.foreign,1015				erc721metadata: flags.erc721metadata,1016			},1017		})1018	}1019}10201021macro_rules! limit_default {1022	($old:ident, $new:ident, $($field:ident $(($arg:expr))? => $check:expr),* $(,)?) => {{1023		$(1024			if let Some($new) = $new.$field {1025				let $old = $old.$field($($arg)?);1026				let _ = $new;1027				let _ = $old;1028				$check1029			} else {1030				$new.$field = $old.$field1031			}1032		)*1033	}};1034}1035macro_rules! limit_default_clone {1036	($old:ident, $new:ident, $($field:ident $(($arg:expr))? => $check:expr),* $(,)?) => {{1037		$(1038			if let Some($new) = $new.$field.clone() {1039				let $old = $old.$field($($arg)?);1040				let _ = $new;1041				let _ = $old;1042				$check1043			} else {1044				$new.$field = $old.$field.clone()1045			}1046		)*1047	}};1048}10491050impl<T: Config> Pallet<T> {1051	/// Create new collection.1052	///1053	/// * `owner` - The owner of the collection.1054	/// * `data` - Description of the created collection.1055	/// * `flags` - Extra flags to store.1056	pub fn init_collection(1057		owner: T::CrossAccountId,1058		payer: T::CrossAccountId,1059		data: CreateCollectionData<T::AccountId>,1060		flags: CollectionFlags,1061	) -> Result<CollectionId, DispatchError> {1062		{1063			ensure!(1064				data.token_prefix.len() <= MAX_TOKEN_PREFIX_LENGTH as usize,1065				Error::<T>::CollectionTokenPrefixLimitExceeded1066			);1067		}10681069		let created_count = <CreatedCollectionCount<T>>::get()1070			.01071			.checked_add(1)1072			.ok_or(ArithmeticError::Overflow)?;1073		let destroyed_count = <DestroyedCollectionCount<T>>::get().0;1074		let id = CollectionId(created_count);10751076		// bound Total number of collections1077		ensure!(1078			created_count - destroyed_count <= COLLECTION_NUMBER_LIMIT,1079			<Error<T>>::TotalCollectionsLimitExceeded1080		);10811082		// =========10831084		let collection = Collection {1085			owner: owner.as_sub().clone(),1086			name: data.name,1087			mode: data.mode.clone(),1088			description: data.description,1089			token_prefix: data.token_prefix,1090			sponsorship: data1091				.pending_sponsor1092				.map(SponsorshipState::Unconfirmed)1093				.unwrap_or_default(),1094			limits: data1095				.limits1096				.map(|limits| Self::clamp_limits(data.mode.clone(), &Default::default(), limits))1097				.unwrap_or_else(|| Ok(CollectionLimits::default()))?,1098			permissions: data1099				.permissions1100				.map(|permissions| {1101					Self::clamp_permissions(data.mode.clone(), &Default::default(), permissions)1102				})1103				.unwrap_or_else(|| Ok(CollectionPermissions::default()))?,1104			flags,1105		};11061107		let mut collection_properties = up_data_structs::CollectionProperties::get();1108		collection_properties1109			.try_set_from_iter(data.properties.into_iter())1110			.map_err(<Error<T>>::from)?;11111112		CollectionProperties::<T>::insert(id, collection_properties);11131114		let mut token_props_permissions = PropertiesPermissionMap::new();1115		token_props_permissions1116			.try_set_from_iter(data.token_property_permissions.into_iter())1117			.map_err(<Error<T>>::from)?;11181119		CollectionPropertyPermissions::<T>::insert(id, token_props_permissions);11201121		// Take a (non-refundable) deposit of collection creation1122		{1123			let mut imbalance =1124				<<<T as Config>::Currency as Currency<T::AccountId>>::PositiveImbalance>::zero();1125			imbalance.subsume(1126				<<T as Config>::Currency as Currency<T::AccountId>>::deposit_creating(1127					&T::TreasuryAccountId::get(),1128					T::CollectionCreationPrice::get(),1129				),1130			);1131			<T as Config>::Currency::settle(1132				payer.as_sub(),1133				imbalance,1134				WithdrawReasons::TRANSFER,1135				ExistenceRequirement::KeepAlive,1136			)1137			.map_err(|_| Error::<T>::NotSufficientFounds)?;1138		}11391140		<CreatedCollectionCount<T>>::put(created_count);1141		<Pallet<T>>::deposit_event(Event::CollectionCreated(1142			id,1143			data.mode.id(),1144			owner.as_sub().clone(),1145		));1146		<PalletEvm<T>>::deposit_log(1147			erc::CollectionHelpersEvents::CollectionCreated {1148				owner: *owner.as_eth(),1149				collection_id: eth::collection_id_to_address(id),1150			}1151			.to_log(T::ContractAddress::get()),1152		);1153		<CollectionById<T>>::insert(id, collection);1154		Ok(id)1155	}11561157	/// Destroy collection.1158	///1159	/// * `collection` - Collection handler.1160	/// * `sender` - The owner or administrator of the collection.1161	pub fn destroy_collection(1162		collection: CollectionHandle<T>,1163		sender: &T::CrossAccountId,1164	) -> DispatchResult {1165		ensure!(1166			collection.limits.owner_can_destroy(),1167			<Error<T>>::NoPermission,1168		);1169		collection.check_is_owner(sender)?;11701171		let destroyed_collections = <DestroyedCollectionCount<T>>::get()1172			.01173			.checked_add(1)1174			.ok_or(ArithmeticError::Overflow)?;11751176		// =========11771178		<DestroyedCollectionCount<T>>::put(destroyed_collections);1179		<CollectionById<T>>::remove(collection.id);1180		<AdminAmount<T>>::remove(collection.id);1181		let _ = <IsAdmin<T>>::clear_prefix((collection.id,), u32::MAX, None);1182		let _ = <Allowlist<T>>::clear_prefix((collection.id,), u32::MAX, None);1183		<CollectionProperties<T>>::remove(collection.id);11841185		<Pallet<T>>::deposit_event(Event::CollectionDestroyed(collection.id));11861187		<PalletEvm<T>>::deposit_log(1188			erc::CollectionHelpersEvents::CollectionDestroyed {1189				collection_id: eth::collection_id_to_address(collection.id),1190			}1191			.to_log(T::ContractAddress::get()),1192		);1193		Ok(())1194	}11951196	/// Set collection property.1197	///1198	/// * `collection` - Collection handler.1199	/// * `sender` - The owner or administrator of the collection.1200	/// * `property` - The property to set.1201	pub fn set_collection_property(1202		collection: &CollectionHandle<T>,1203		sender: &T::CrossAccountId,1204		property: Property,1205	) -> DispatchResult {1206		collection.check_is_owner_or_admin(sender)?;12071208		CollectionProperties::<T>::try_mutate(collection.id, |properties| {1209			let property = property.clone();1210			properties.try_set(property.key, property.value)1211		})1212		.map_err(<Error<T>>::from)?;12131214		Self::deposit_event(Event::CollectionPropertySet(collection.id, property.key));1215		<PalletEvm<T>>::deposit_log(1216			erc::CollectionHelpersEvents::CollectionChanged {1217				collection_id: eth::collection_id_to_address(collection.id),1218			}1219			.to_log(T::ContractAddress::get()),1220		);12211222		Ok(())1223	}12241225	/// Set scouped collection property.1226	///1227	/// * `collection_id` - ID of the collection for which the property is being set.1228	/// * `scope` - Property scope.1229	/// * `property` - The property to set.1230	pub fn set_scoped_collection_property(1231		collection_id: CollectionId,1232		scope: PropertyScope,1233		property: Property,1234	) -> DispatchResult {1235		CollectionProperties::<T>::try_mutate(collection_id, |properties| {1236			properties.try_scoped_set(scope, property.key, property.value)1237		})1238		.map_err(<Error<T>>::from)?;12391240		Ok(())1241	}12421243	/// Set scouped collection properties.1244	///1245	/// * `collection_id` - ID of the collection for which the properties is being set.1246	/// * `scope` - Property scope.1247	/// * `properties` - The properties to set.1248	pub fn set_scoped_collection_properties(1249		collection_id: CollectionId,1250		scope: PropertyScope,1251		properties: impl Iterator<Item = Property>,1252	) -> DispatchResult {1253		CollectionProperties::<T>::try_mutate(collection_id, |stored_properties| {1254			stored_properties.try_scoped_set_from_iter(scope, properties)1255		})1256		.map_err(<Error<T>>::from)?;12571258		Ok(())1259	}12601261	/// Set collection properties.1262	///1263	/// * `collection` - Collection handler.1264	/// * `sender` - The owner or administrator of the collection.1265	/// * `properties` - The properties to set.1266	#[transactional]1267	pub fn set_collection_properties(1268		collection: &CollectionHandle<T>,1269		sender: &T::CrossAccountId,1270		properties: Vec<Property>,1271	) -> DispatchResult {1272		for property in properties {1273			Self::set_collection_property(collection, sender, property)?;1274		}12751276		Ok(())1277	}12781279	/// Delete collection property.1280	///1281	/// * `collection` - Collection handler.1282	/// * `sender` - The owner or administrator of the collection.1283	/// * `property` - The property to delete.1284	pub fn delete_collection_property(1285		collection: &CollectionHandle<T>,1286		sender: &T::CrossAccountId,1287		property_key: PropertyKey,1288	) -> DispatchResult {1289		collection.check_is_owner_or_admin(sender)?;12901291		CollectionProperties::<T>::try_mutate(collection.id, |properties| {1292			properties.remove(&property_key)1293		})1294		.map_err(<Error<T>>::from)?;12951296		Self::deposit_event(Event::CollectionPropertyDeleted(1297			collection.id,1298			property_key,1299		));1300		<PalletEvm<T>>::deposit_log(1301			erc::CollectionHelpersEvents::CollectionChanged {1302				collection_id: eth::collection_id_to_address(collection.id),1303			}1304			.to_log(T::ContractAddress::get()),1305		);13061307		Ok(())1308	}13091310	/// Delete collection properties.1311	///1312	/// * `collection` - Collection handler.1313	/// * `sender` - The owner or administrator of the collection.1314	/// * `properties` - The properties to delete.1315	#[transactional]1316	pub fn delete_collection_properties(1317		collection: &CollectionHandle<T>,1318		sender: &T::CrossAccountId,1319		property_keys: Vec<PropertyKey>,1320	) -> DispatchResult {1321		for key in property_keys {1322			Self::delete_collection_property(collection, sender, key)?;1323		}13241325		Ok(())1326	}13271328	/// Set collection propetry permission without any checks.1329	///1330	/// Used for migrations.1331	///1332	/// * `collection` - Collection handler.1333	/// * `property_permissions` - Property permissions.1334	pub fn set_property_permission_unchecked(1335		collection: CollectionId,1336		property_permission: PropertyKeyPermission,1337	) -> DispatchResult {1338		<CollectionPropertyPermissions<T>>::try_mutate(collection, |permissions| {1339			permissions.try_set(property_permission.key, property_permission.permission)1340		})1341		.map_err(<Error<T>>::from)?;1342		Ok(())1343	}13441345	/// Set collection property permission.1346	///1347	/// * `collection` - Collection handler.1348	/// * `sender` - The owner or administrator of the collection.1349	/// * `property_permission` - Property permission.1350	pub fn set_property_permission(1351		collection: &CollectionHandle<T>,1352		sender: &T::CrossAccountId,1353		property_permission: PropertyKeyPermission,1354	) -> DispatchResult {1355		Self::set_scoped_property_permission(1356			collection,1357			sender,1358			PropertyScope::None,1359			property_permission,1360		)1361	}13621363	/// Set collection property permission with scope.1364	///1365	/// * `collection` - Collection handler.1366	/// * `sender` - The owner or administrator of the collection.1367	/// * `scope` - Property scope.1368	/// * `property_permission` - Property permission.1369	pub fn set_scoped_property_permission(1370		collection: &CollectionHandle<T>,1371		sender: &T::CrossAccountId,1372		scope: PropertyScope,1373		property_permission: PropertyKeyPermission,1374	) -> DispatchResult {1375		collection.check_is_owner_or_admin(sender)?;13761377		let all_permissions = CollectionPropertyPermissions::<T>::get(collection.id);1378		let current_permission = all_permissions.get(&property_permission.key);1379		if matches![1380			current_permission,1381			Some(PropertyPermission { mutable: false, .. })1382		] {1383			return Err(<Error<T>>::NoPermission.into());1384		}13851386		CollectionPropertyPermissions::<T>::try_mutate(collection.id, |permissions| {1387			let property_permission = property_permission.clone();1388			permissions.try_scoped_set(1389				scope,1390				property_permission.key,1391				property_permission.permission,1392			)1393		})1394		.map_err(<Error<T>>::from)?;13951396		Self::deposit_event(Event::PropertyPermissionSet(1397			collection.id,1398			property_permission.key,1399		));1400		<PalletEvm<T>>::deposit_log(1401			erc::CollectionHelpersEvents::CollectionChanged {1402				collection_id: eth::collection_id_to_address(collection.id),1403			}1404			.to_log(T::ContractAddress::get()),1405		);14061407		Ok(())1408	}14091410	/// Set token property permission.1411	///1412	/// * `collection` - Collection handler.1413	/// * `sender` - The owner or administrator of the collection.1414	/// * `property_permissions` - Property permissions.1415	#[transactional]1416	pub fn set_token_property_permissions(1417		collection: &CollectionHandle<T>,1418		sender: &T::CrossAccountId,1419		property_permissions: Vec<PropertyKeyPermission>,1420	) -> DispatchResult {1421		Self::set_scoped_token_property_permissions(1422			collection,1423			sender,1424			PropertyScope::None,1425			property_permissions,1426		)1427	}14281429	/// Set token property permission with scope.1430	///1431	/// * `collection` - Collection handler.1432	/// * `sender` - The owner or administrator of the collection.1433	/// * `scope` - Property scope.1434	/// * `property_permissions` - Property permissions.1435	#[transactional]1436	pub fn set_scoped_token_property_permissions(1437		collection: &CollectionHandle<T>,1438		sender: &T::CrossAccountId,1439		scope: PropertyScope,1440		property_permissions: Vec<PropertyKeyPermission>,1441	) -> DispatchResult {1442		for prop_pemission in property_permissions {1443			Self::set_scoped_property_permission(collection, sender, scope, prop_pemission)?;1444		}14451446		Ok(())1447	}14481449	/// Get collection property.1450	pub fn get_collection_property(1451		collection_id: CollectionId,1452		key: &PropertyKey,1453	) -> Option<PropertyValue> {1454		Self::collection_properties(collection_id).get(key).cloned()1455	}14561457	/// Convert byte vector to property key vector.1458	pub fn bytes_keys_to_property_keys(1459		keys: Vec<Vec<u8>>,1460	) -> Result<Vec<PropertyKey>, DispatchError> {1461		keys.into_iter()1462			.map(|key| -> Result<PropertyKey, DispatchError> {1463				key.try_into()1464					.map_err(|_| <Error<T>>::PropertyKeyIsTooLong.into())1465			})1466			.collect::<Result<Vec<PropertyKey>, DispatchError>>()1467	}14681469	/// Get properties according to given keys.1470	pub fn filter_collection_properties(1471		collection_id: CollectionId,1472		keys: Option<Vec<PropertyKey>>,1473	) -> Result<Vec<Property>, DispatchError> {1474		let properties = Self::collection_properties(collection_id);14751476		let properties = keys1477			.map(|keys| {1478				keys.into_iter()1479					.filter_map(|key| {1480						properties.get(&key).map(|value| Property {1481							key,1482							value: value.clone(),1483						})1484					})1485					.collect()1486			})1487			.unwrap_or_else(|| {1488				properties1489					.into_iter()1490					.map(|(key, value)| Property { key, value })1491					.collect()1492			});14931494		Ok(properties)1495	}14961497	/// Get property permissions according to given keys.1498	pub fn filter_property_permissions(1499		collection_id: CollectionId,1500		keys: Option<Vec<PropertyKey>>,1501	) -> Result<Vec<PropertyKeyPermission>, DispatchError> {1502		let permissions = Self::property_permissions(collection_id);15031504		let key_permissions = keys1505			.map(|keys| {1506				keys.into_iter()1507					.filter_map(|key| {1508						permissions1509							.get(&key)1510							.map(|permission| PropertyKeyPermission {1511								key,1512								permission: permission.clone(),1513							})1514					})1515					.collect()1516			})1517			.unwrap_or_else(|| {1518				permissions1519					.into_iter()1520					.map(|(key, permission)| PropertyKeyPermission { key, permission })1521					.collect()1522			});15231524		Ok(key_permissions)1525	}15261527	/// Toggle `user` participation in the `collection`'s allow list.1528	/// #### Store read/writes1529	/// 1 writes1530	pub fn toggle_allowlist(1531		collection: &CollectionHandle<T>,1532		sender: &T::CrossAccountId,1533		user: &T::CrossAccountId,1534		allowed: bool,1535	) -> DispatchResult {1536		collection.check_is_owner_or_admin(sender)?;15371538		// =========15391540		if allowed {1541			<Allowlist<T>>::insert((collection.id, user), true);1542			Self::deposit_event(Event::<T>::AllowListAddressAdded(1543				collection.id,1544				user.clone(),1545			));1546		} else {1547			<Allowlist<T>>::remove((collection.id, user));1548			Self::deposit_event(Event::<T>::AllowListAddressRemoved(1549				collection.id,1550				user.clone(),1551			));1552		}15531554		<PalletEvm<T>>::deposit_log(1555			erc::CollectionHelpersEvents::CollectionChanged {1556				collection_id: eth::collection_id_to_address(collection.id),1557			}1558			.to_log(T::ContractAddress::get()),1559		);15601561		Ok(())1562	}15631564	/// Toggle `user` participation in the `collection`'s admin list.1565	/// #### Store read/writes1566	/// 2 reads, 2 writes1567	pub fn toggle_admin(1568		collection: &CollectionHandle<T>,1569		sender: &T::CrossAccountId,1570		user: &T::CrossAccountId,1571		admin: bool,1572	) -> DispatchResult {1573		collection.check_is_internal()?;1574		collection.check_is_owner(sender)?;15751576		let is_admin = <IsAdmin<T>>::get((collection.id, user));1577		if is_admin == admin {1578			if admin {1579				return Ok(());1580			} else {1581				ensure!(false, Error::<T>::UserIsNotAdmin);1582			}1583		}1584		let amount = <AdminAmount<T>>::get(collection.id);15851586		if admin {1587			let amount = amount1588				.checked_add(1)1589				.ok_or(<Error<T>>::CollectionAdminCountExceeded)?;1590			ensure!(1591				amount <= Self::collection_admins_limit(),1592				<Error<T>>::CollectionAdminCountExceeded,1593			);15941595			// =========15961597			<AdminAmount<T>>::insert(collection.id, amount);1598			<IsAdmin<T>>::insert((collection.id, user), true);15991600			Self::deposit_event(Event::<T>::CollectionAdminAdded(1601				collection.id,1602				user.clone(),1603			));1604		} else {1605			<AdminAmount<T>>::insert(collection.id, amount.saturating_sub(1));1606			<IsAdmin<T>>::remove((collection.id, user));16071608			Self::deposit_event(Event::<T>::CollectionAdminRemoved(1609				collection.id,1610				user.clone(),1611			));1612		}16131614		<PalletEvm<T>>::deposit_log(1615			erc::CollectionHelpersEvents::CollectionChanged {1616				collection_id: eth::collection_id_to_address(collection.id),1617			}1618			.to_log(T::ContractAddress::get()),1619		);16201621		Ok(())1622	}16231624	/// Update collection limits.1625	pub fn update_limits(1626		user: &T::CrossAccountId,1627		collection: &mut CollectionHandle<T>,1628		new_limit: CollectionLimits,1629	) -> DispatchResult {1630		collection.check_is_internal()?;1631		collection.check_is_owner_or_admin(user)?;16321633		collection.limits =1634			Self::clamp_limits(collection.mode.clone(), &collection.limits, new_limit)?;16351636		Self::deposit_event(Event::<T>::CollectionLimitSet(collection.id));1637		<PalletEvm<T>>::deposit_log(1638			erc::CollectionHelpersEvents::CollectionChanged {1639				collection_id: eth::collection_id_to_address(collection.id),1640			}1641			.to_log(T::ContractAddress::get()),1642		);16431644		collection.save()1645	}16461647	/// Merge set fields from `new_limit` to `old_limit`.1648	fn clamp_limits(1649		mode: CollectionMode,1650		old_limit: &CollectionLimits,1651		mut new_limit: CollectionLimits,1652	) -> Result<CollectionLimits, DispatchError> {1653		let limits = old_limit;1654		limit_default!(old_limit, new_limit,1655			account_token_ownership_limit => ensure!(1656				new_limit <= MAX_TOKEN_OWNERSHIP,1657				<Error<T>>::CollectionLimitBoundsExceeded,1658			),1659			sponsored_data_size => ensure!(1660				new_limit <= CUSTOM_DATA_LIMIT,1661				<Error<T>>::CollectionLimitBoundsExceeded,1662			),16631664			sponsored_data_rate_limit => {},1665			token_limit => ensure!(1666				old_limit >= new_limit && new_limit > 0,1667				<Error<T>>::CollectionTokenLimitExceeded1668			),16691670			sponsor_transfer_timeout(match mode {1671				CollectionMode::NFT => NFT_SPONSOR_TRANSFER_TIMEOUT,1672				CollectionMode::Fungible(_) => FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,1673				CollectionMode::ReFungible => REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,1674			}) => ensure!(1675				new_limit <= MAX_SPONSOR_TIMEOUT,1676				<Error<T>>::CollectionLimitBoundsExceeded,1677			),1678			sponsor_approve_timeout => {},1679			owner_can_transfer => ensure!(1680				!limits.owner_can_transfer_instaled() ||1681				old_limit || !new_limit,1682				<Error<T>>::OwnerPermissionsCantBeReverted,1683			),1684			owner_can_destroy => ensure!(1685				old_limit || !new_limit,1686				<Error<T>>::OwnerPermissionsCantBeReverted,1687			),1688			transfers_enabled => {},1689		);1690		Ok(new_limit)1691	}16921693	/// Update collection permissions.1694	pub fn update_permissions(1695		user: &T::CrossAccountId,1696		collection: &mut CollectionHandle<T>,1697		new_permission: CollectionPermissions,1698	) -> DispatchResult {1699		collection.check_is_internal()?;1700		collection.check_is_owner_or_admin(user)?;1701		collection.permissions = Self::clamp_permissions(1702			collection.mode.clone(),1703			&collection.permissions,1704			new_permission,1705		)?;17061707		Self::deposit_event(Event::<T>::CollectionPermissionSet(collection.id));1708		<PalletEvm<T>>::deposit_log(1709			erc::CollectionHelpersEvents::CollectionChanged {1710				collection_id: eth::collection_id_to_address(collection.id),1711			}1712			.to_log(T::ContractAddress::get()),1713		);17141715		collection.save()1716	}17171718	/// Merge set fields from `new_permission` to `old_permission`.1719	fn clamp_permissions(1720		_mode: CollectionMode,1721		old_permission: &CollectionPermissions,1722		mut new_permission: CollectionPermissions,1723	) -> Result<CollectionPermissions, DispatchError> {1724		limit_default_clone!(old_permission, new_permission,1725			access => {},1726			mint_mode => {},1727			nesting => { /* todo check for permissive, if only it gets out of benchmarks */ },1728		);1729		Ok(new_permission)1730	}1731}17321733/// Indicates unsupported methods by returning [Error::UnsupportedOperation].1734#[macro_export]1735macro_rules! unsupported {1736	($runtime:path) => {1737		Err($crate::Error::<$runtime>::UnsupportedOperation.into())1738	};1739}17401741/// Return weights for various worst-case operations.1742pub trait CommonWeightInfo<CrossAccountId> {1743	/// Weight of item creation.1744	fn create_item() -> Weight;17451746	/// Weight of items creation.1747	fn create_multiple_items(amount: &[CreateItemData]) -> Weight;17481749	/// Weight of items creation.1750	fn create_multiple_items_ex(cost: &CreateItemExData<CrossAccountId>) -> Weight;17511752	/// The weight of the burning item.1753	fn burn_item() -> Weight;17541755	/// Property setting weight.1756	///1757	/// * `amount`- The number of properties to set.1758	fn set_collection_properties(amount: u32) -> Weight;17591760	/// Collection property deletion weight.1761	///1762	/// * `amount`- The number of properties to set.1763	fn delete_collection_properties(amount: u32) -> Weight;17641765	/// Token property setting weight.1766	///1767	/// * `amount`- The number of properties to set.1768	fn set_token_properties(amount: u32) -> Weight;17691770	/// Token property deletion weight.1771	///1772	/// * `amount`- The number of properties to delete.1773	fn delete_token_properties(amount: u32) -> Weight;17741775	/// Token property permissions set weight.1776	///1777	/// * `amount`- The number of property permissions to set.1778	fn set_token_property_permissions(amount: u32) -> Weight;17791780	/// Transfer price of the token or its parts.1781	fn transfer() -> Weight;17821783	/// The price of setting the permission of the operation from another user.1784	fn approve() -> Weight;17851786	/// Transfer price from another user.1787	fn transfer_from() -> Weight;17881789	/// The price of burning a token from another user.1790	fn burn_from() -> Weight;17911792	/// Differs from burn_item in case of Fungible and Refungible, as it should burn1793	/// whole users's balance.1794	///1795	/// This method shouldn't be used directly, as it doesn't count breadth price, use [burn_recursively](CommonWeightInfo::burn_recursively) instead1796	fn burn_recursively_self_raw() -> Weight;17971798	/// Cost of iterating over `amount` children while burning, without counting child burning itself.1799	///1800	/// This method shouldn't be used directly, as it doesn't count depth price, use [burn_recursively](CommonWeightInfo::burn_recursively) instead1801	fn burn_recursively_breadth_raw(amount: u32) -> Weight;18021803	/// The price of recursive burning a token.1804	///1805	/// `max_selfs` - The maximum burning weight of the token itself.1806	/// `max_breadth` - The maximum number of nested tokens to burn.1807	fn burn_recursively(max_selfs: u32, max_breadth: u32) -> Weight {1808		Self::burn_recursively_self_raw()1809			.saturating_mul(max_selfs.max(1) as u64)1810			.saturating_add(Self::burn_recursively_breadth_raw(max_breadth))1811	}18121813	/// The price of retrieving token owner1814	fn token_owner() -> Weight;18151816	/// The price of setting approval for all1817	fn set_allowance_for_all() -> Weight;1818}18191820/// Weight info extension trait for refungible pallet.1821pub trait RefungibleExtensionsWeightInfo {1822	/// Weight of token repartition.1823	fn repartition() -> Weight;1824}18251826/// Common collection operations.1827///1828/// It wraps methods in Fungible, Nonfungible and Refungible pallets1829/// and adds weight info.1830pub trait CommonCollectionOperations<T: Config> {1831	/// Create token.1832	///1833	/// * `sender` - The user who mint the token and pays for the transaction.1834	/// * `to` - The user who will own the token.1835	/// * `data` - Token data.1836	/// * `nesting_budget` - A budget that can be spent on nesting tokens.1837	fn create_item(1838		&self,1839		sender: T::CrossAccountId,1840		to: T::CrossAccountId,1841		data: CreateItemData,1842		nesting_budget: &dyn Budget,1843	) -> DispatchResultWithPostInfo;18441845	/// Create multiple tokens.1846	///1847	/// * `sender` - The user who mint the token and pays for the transaction.1848	/// * `to` - The user who will own the token.1849	/// * `data` - Token data.1850	/// * `nesting_budget` - A budget that can be spent on nesting tokens.1851	fn create_multiple_items(1852		&self,1853		sender: T::CrossAccountId,1854		to: T::CrossAccountId,1855		data: Vec<CreateItemData>,1856		nesting_budget: &dyn Budget,1857	) -> DispatchResultWithPostInfo;18581859	/// Create multiple tokens.1860	///1861	/// * `sender` - The user who mint the token and pays for the transaction.1862	/// * `to` - The user who will own the token.1863	/// * `data` - Token data.1864	/// * `nesting_budget` - A budget that can be spent on nesting tokens.1865	fn create_multiple_items_ex(1866		&self,1867		sender: T::CrossAccountId,1868		data: CreateItemExData<T::CrossAccountId>,1869		nesting_budget: &dyn Budget,1870	) -> DispatchResultWithPostInfo;18711872	/// Burn token.1873	///1874	/// * `sender` - The user who owns the token.1875	/// * `token` - Token id that will burned.1876	/// * `amount` - The number of parts of the token that will be burned.1877	fn burn_item(1878		&self,1879		sender: T::CrossAccountId,1880		token: TokenId,1881		amount: u128,1882	) -> DispatchResultWithPostInfo;18831884	/// Burn token and all nested tokens recursievly.1885	///1886	/// * `sender` - The user who owns the token.1887	/// * `token` - Token id that will burned.1888	/// * `self_budget` - The budget that can be spent on burning tokens.1889	/// * `breadth_budget` - The budget that can be spent on burning nested tokens.1890	fn burn_item_recursively(1891		&self,1892		sender: T::CrossAccountId,1893		token: TokenId,1894		self_budget: &dyn Budget,1895		breadth_budget: &dyn Budget,1896	) -> DispatchResultWithPostInfo;18971898	/// Set collection properties.1899	///1900	/// * `sender` - Must be either the owner of the collection or its admin.1901	/// * `properties` - Properties to be set.1902	fn set_collection_properties(1903		&self,1904		sender: T::CrossAccountId,1905		properties: Vec<Property>,1906	) -> DispatchResultWithPostInfo;19071908	/// Delete collection properties.1909	///1910	/// * `sender` - Must be either the owner of the collection or its admin.1911	/// * `properties` - The properties to be removed.1912	fn delete_collection_properties(1913		&self,1914		sender: &T::CrossAccountId,1915		property_keys: Vec<PropertyKey>,1916	) -> DispatchResultWithPostInfo;19171918	/// Set token properties.1919	///1920	/// The appropriate [`PropertyPermission`] for the token property1921	/// must be set with [`Self::set_token_property_permissions`].1922	///1923	/// * `sender` - Must be either the owner of the token or its admin.1924	/// * `token_id` - The token for which the properties are being set.1925	/// * `properties` - Properties to be set.1926	/// * `budget` - Budget for setting properties.1927	fn set_token_properties(1928		&self,1929		sender: T::CrossAccountId,1930		token_id: TokenId,1931		properties: Vec<Property>,1932		budget: &dyn Budget,1933	) -> DispatchResultWithPostInfo;19341935	/// Remove token properties.1936	///1937	/// The appropriate [`PropertyPermission`] for the token property1938	/// must be set with [`Self::set_token_property_permissions`].1939	///1940	/// * `sender` - Must be either the owner of the token or its admin.1941	/// * `token_id` - The token for which the properties are being remove.1942	/// * `property_keys` - Keys to remove corresponding properties.1943	/// * `budget` - Budget for removing properties.1944	fn delete_token_properties(1945		&self,1946		sender: T::CrossAccountId,1947		token_id: TokenId,1948		property_keys: Vec<PropertyKey>,1949		budget: &dyn Budget,1950	) -> DispatchResultWithPostInfo;19511952	/// Set token property permissions.1953	///1954	/// * `sender` - Must be either the owner of the token or its admin.1955	/// * `token_id` - The token for which the properties are being set.1956	/// * `property_permissions` - Property permissions to be set.1957	/// * `budget` - Budget for setting properties.1958	fn set_token_property_permissions(1959		&self,1960		sender: &T::CrossAccountId,1961		property_permissions: Vec<PropertyKeyPermission>,1962	) -> DispatchResultWithPostInfo;19631964	/// Transfer amount of token pieces.1965	///1966	/// * `sender` - Donor user.1967	/// * `to` - Recepient user.1968	/// * `token` - The token of which parts are being sent.1969	/// * `amount` - The number of parts of the token that will be transferred.1970	/// * `budget` - The maximum budget that can be spent on the transfer.1971	fn transfer(1972		&self,1973		sender: T::CrossAccountId,1974		to: T::CrossAccountId,1975		token: TokenId,1976		amount: u128,1977		budget: &dyn Budget,1978	) -> DispatchResultWithPostInfo;19791980	/// Grant access to another account to transfer parts of the token owned by the calling user via [Self::transfer_from].1981	///1982	/// * `sender` - The user who grants access to the token.1983	/// * `spender` - The user to whom the rights are granted.1984	/// * `token` - The token to which access is granted.1985	/// * `amount` - The amount of pieces that another user can dispose of.1986	fn approve(1987		&self,1988		sender: T::CrossAccountId,1989		spender: T::CrossAccountId,1990		token: TokenId,1991		amount: u128,1992	) -> DispatchResultWithPostInfo;19931994	/// Send parts of a token owned by another user.1995	///1996	/// Before calling this method, you must grant rights to the calling user via [`Self::approve`].1997	///1998	/// * `sender` - The user who must have access to the token (see [`Self::approve`]).1999	/// * `from` - The user who owns the token.2000	/// * `to` - Recepient user.2001	/// * `token` - The token of which parts are being sent.2002	/// * `amount` - The number of parts of the token that will be transferred.2003	/// * `budget` - The maximum budget that can be spent on the transfer.2004	fn transfer_from(2005		&self,2006		sender: T::CrossAccountId,2007		from: T::CrossAccountId,2008		to: T::CrossAccountId,2009		token: TokenId,2010		amount: u128,2011		budget: &dyn Budget,2012	) -> DispatchResultWithPostInfo;20132014	/// Burn parts of a token owned by another user.2015	///2016	/// Before calling this method, you must grant rights to the calling user via [`Self::approve`].2017	///2018	/// * `sender` - The user who must have access to the token (see [`Self::approve`]).2019	/// * `from` - The user who owns the token.2020	/// * `token` - The token of which parts are being sent.2021	/// * `amount` - The number of parts of the token that will be transferred.2022	/// * `budget` - The maximum budget that can be spent on the burn.2023	fn burn_from(2024		&self,2025		sender: T::CrossAccountId,2026		from: T::CrossAccountId,2027		token: TokenId,2028		amount: u128,2029		budget: &dyn Budget,2030	) -> DispatchResultWithPostInfo;20312032	/// Check permission to nest token.2033	///2034	/// * `sender` - The user who initiated the check.2035	/// * `from` - The token that is checked for embedding.2036	/// * `under` - Token under which to check.2037	/// * `budget` - The maximum budget that can be spent on the check.2038	fn check_nesting(2039		&self,2040		sender: T::CrossAccountId,2041		from: (CollectionId, TokenId),2042		under: TokenId,2043		budget: &dyn Budget,2044	) -> DispatchResult;20452046	/// Nest one token into another.2047	///2048	/// * `under` - Token holder.2049	/// * `to_nest` - Nested token.2050	fn nest(&self, under: TokenId, to_nest: (CollectionId, TokenId));20512052	/// Unnest token.2053	///2054	/// * `under` - Token holder.2055	/// * `to_nest` - Token to unnest.2056	fn unnest(&self, under: TokenId, to_nest: (CollectionId, TokenId));20572058	/// Get all user tokens.2059	///2060	/// * `account` - Account for which you need to get tokens.2061	fn account_tokens(&self, account: T::CrossAccountId) -> Vec<TokenId>;20622063	/// Get all the tokens in the collection.2064	fn collection_tokens(&self) -> Vec<TokenId>;20652066	/// Check if the token exists.2067	///2068	/// * `token` - Id token to check.2069	fn token_exists(&self, token: TokenId) -> bool;20702071	/// Get the id of the last minted token.2072	fn last_token_id(&self) -> TokenId;20732074	/// Get the owner of the token.2075	///2076	/// * `token` - The token for which you need to find out the owner.2077	fn token_owner(&self, token: TokenId) -> Option<T::CrossAccountId>;20782079	/// Returns 10 tokens owners in no particular order.2080	///2081	/// * `token` - The token for which you need to find out the owners.2082	fn token_owners(&self, token: TokenId) -> Vec<T::CrossAccountId>;20832084	/// Get the value of the token property by key.2085	///2086	/// * `token` - Token with the property to get.2087	/// * `key` - Property name.2088	fn token_property(&self, token_id: TokenId, key: &PropertyKey) -> Option<PropertyValue>;20892090	/// Get a set of token properties by key vector.2091	///2092	/// * `token` - Token with the property to get.2093	/// * `keys` - Vector of property keys. If this parameter is [None](sp_std::result::Result),2094	/// then all properties are returned.2095	fn token_properties(&self, token: TokenId, keys: Option<Vec<PropertyKey>>) -> Vec<Property>;20962097	/// Amount of unique collection tokens2098	fn total_supply(&self) -> u32;20992100	/// Amount of different tokens account has.2101	///2102	/// * `account` - The account for which need to get the balance.2103	fn account_balance(&self, account: T::CrossAccountId) -> u32;21042105	/// Amount of specific token account have.2106	fn balance(&self, account: T::CrossAccountId, token: TokenId) -> u128;21072108	/// Amount of token pieces2109	fn total_pieces(&self, token: TokenId) -> Option<u128>;21102111	/// Get the number of parts of the token that a trusted user can manage.2112	///2113	/// * `sender` - Trusted user.2114	/// * `spender` - Owner of the token.2115	/// * `token` - The token for which to get the value.2116	fn allowance(2117		&self,2118		sender: T::CrossAccountId,2119		spender: T::CrossAccountId,2120		token: TokenId,2121	) -> u128;21222123	/// Get extension for RFT collection.2124	fn refungible_extensions(&self) -> Option<&dyn RefungibleExtensions<T>>;21252126	/// The `operator` is allowed to transfer all tokens of the `owner` on their behalf.2127	/// * `owner` - Token owner2128	/// * `operator` - Operator2129	/// * `approve` - Should operator status be granted or revoked?2130	fn set_allowance_for_all(2131		&self,2132		owner: T::CrossAccountId,2133		operator: T::CrossAccountId,2134		approve: bool,2135	) -> DispatchResultWithPostInfo;21362137	/// Tells whether the given `owner` approves the `operator`.2138	fn allowance_for_all(&self, owner: T::CrossAccountId, operator: T::CrossAccountId) -> bool;2139}21402141/// Extension for RFT collection.2142pub trait RefungibleExtensions<T>2143where2144	T: Config,2145{2146	/// Change the number of parts of the token.2147	///2148	/// When the value changes down, this function is equivalent to burning parts of the token.2149	///2150	/// * `sender` - The user calling the repartition operation. Must be the owner of the token.2151	/// * `token` - The token for which you want to change the number of parts.2152	/// * `amount` - The new value of the parts of the token.2153	fn repartition(2154		&self,2155		sender: &T::CrossAccountId,2156		token: TokenId,2157		amount: u128,2158	) -> DispatchResultWithPostInfo;2159}21602161/// Merge [`DispatchResult`] with [`Weight`] into [`DispatchResultWithPostInfo`].2162///2163/// Used for [`CommonCollectionOperations`] implementations and flexible enough to do so.2164pub fn with_weight(res: DispatchResult, weight: Weight) -> DispatchResultWithPostInfo {2165	let post_info = PostDispatchInfo {2166		actual_weight: Some(weight),2167		pays_fee: Pays::Yes,2168	};2169	match res {2170		Ok(()) => Ok(post_info),2171		Err(error) => Err(DispatchErrorWithPostInfo { post_info, error }),2172	}2173}21742175impl<T: Config> From<PropertiesError> for Error<T> {2176	fn from(error: PropertiesError) -> Self {2177		match error {2178			PropertiesError::NoSpaceForProperty => Self::NoSpaceForProperty,2179			PropertiesError::PropertyLimitReached => Self::PropertyLimitReached,2180			PropertiesError::InvalidCharacterInPropertyKey => Self::InvalidCharacterInPropertyKey,2181			PropertiesError::PropertyKeyIsTooLong => Self::PropertyKeyIsTooLong,2182			PropertiesError::EmptyPropertyKey => Self::EmptyPropertyKey,2183		}2184	}2185}
modifiedpallets/unique/src/lib.rsdiffbeforeafterboth
--- a/pallets/unique/src/lib.rs
+++ b/pallets/unique/src/lib.rs
@@ -89,10 +89,9 @@
 	MAX_PROPERTIES_PER_ITEM, MAX_PROPERTY_KEY_LENGTH, MAX_PROPERTY_VALUE_LENGTH,
 	MAX_COLLECTION_PROPERTIES_SIZE, COLLECTION_ADMINS_LIMIT, MAX_TOKEN_PROPERTIES_SIZE,
 	CreateItemData, CollectionLimits, CollectionPermissions, CollectionId, CollectionMode, TokenId,
-	SponsorshipState, CreateCollectionData, CreateItemExData, budget, Property, PropertyKey,
-	PropertyKeyPermission,
+	CreateCollectionData, CreateItemExData, budget, Property, PropertyKey, PropertyKeyPermission,
 };
-use pallet_evm::account::CrossAccountId;
+use pallet_evm::{account::CrossAccountId};
 use pallet_common::{
 	CollectionHandle, Pallet as PalletCommon, CommonWeightInfo, dispatch::dispatch_tx,
 	dispatch::CollectionDispatch, RefungibleExtensionsWeightInfo,
@@ -112,8 +111,6 @@
 	pub enum Error for Module<T: Config> {
 		/// Decimal_points parameter must be lower than [`up_data_structs::MAX_DECIMAL_POINTS`].
 		CollectionDecimalPointLimitExceeded,
-		/// This address is not set as sponsor, use setCollectionSponsor first.
-		ConfirmUnsetSponsorFail,
 		/// Length of items properties must be greater than 0.
 		EmptyArgument,
 		/// Repertition is only supported by refungible collection.
@@ -140,27 +137,12 @@
 	pub enum Event<T>
 	where
 		<T as frame_system::Config>::AccountId,
-		<T as pallet_evm::Config>::CrossAccountId,
 	{
 		/// Collection sponsor was removed
 		///
 		/// # Arguments
 		/// * collection_id: ID of the affected collection.
 		CollectionSponsorRemoved(CollectionId),
-
-		/// Collection admin was added
-		///
-		/// # Arguments
-		/// * collection_id: ID of the affected collection.
-		/// * admin: Admin address.
-		CollectionAdminAdded(CollectionId, CrossAccountId),
-
-		/// Collection owned was changed
-		///
-		/// # Arguments
-		/// * collection_id: ID of the affected collection.
-		/// * owner: New owner address.
-		CollectionOwnedChanged(CollectionId, AccountId),
 
 		/// Collection sponsor was set
 		///
@@ -168,46 +150,7 @@
 		/// * collection_id: ID of the affected collection.
 		/// * owner: New sponsor address.
 		CollectionSponsorSet(CollectionId, AccountId),
-
-		/// New sponsor was confirm
-		///
-		/// # Arguments
-		/// * collection_id: ID of the affected collection.
-		/// * sponsor: New sponsor address.
-		SponsorshipConfirmed(CollectionId, AccountId),
-
-		/// Collection admin was removed
-		///
-		/// # Arguments
-		/// * collection_id: ID of the affected collection.
-		/// * admin: Removed admin address.
-		CollectionAdminRemoved(CollectionId, CrossAccountId),
 
-		/// Address was removed from the allow list
-		///
-		/// # Arguments
-		/// * collection_id: ID of the affected collection.
-		/// * user: Address of the removed account.
-		AllowListAddressRemoved(CollectionId, CrossAccountId),
-
-		/// Address was added to the allow list
-		///
-		/// # Arguments
-		/// * collection_id: ID of the affected collection.
-		/// * user: Address of the added account.
-		AllowListAddressAdded(CollectionId, CrossAccountId),
-
-		/// Collection limits were set
-		///
-		/// # Arguments
-		/// * collection_id: ID of the affected collection.
-		CollectionLimitSet(CollectionId),
-
-		/// Collection permissions were set
-		///
-		/// # Arguments
-		/// * collection_id: ID of the affected collection.
-		CollectionPermissionSet(CollectionId),
 	}
 }
 
@@ -432,11 +375,6 @@
 				&address,
 				true,
 			)?;
-
-			Self::deposit_event(Event::<T>::AllowListAddressAdded(
-				collection_id,
-				address
-			));
 
 			Ok(())
 		}
@@ -466,11 +404,6 @@
 				false,
 			)?;
 
-			<Pallet<T>>::deposit_event(Event::<T>::AllowListAddressRemoved(
-				collection_id,
-				address
-			));
-
 			Ok(())
 		}
 
@@ -486,20 +419,10 @@
 		/// * `new_owner`: ID of the account that will become the owner.
 		#[weight = <SelfWeightOf<T>>::change_collection_owner()]
 		pub fn change_collection_owner(origin, collection_id: CollectionId, new_owner: T::AccountId) -> DispatchResult {
-
 			let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);
-
+			let new_owner = T::CrossAccountId::from_sub(new_owner);
 			let mut target_collection = <CollectionHandle<T>>::try_get(collection_id)?;
-			target_collection.check_is_internal()?;
-			target_collection.check_is_owner(&sender)?;
-
-			target_collection.owner = new_owner.clone();
-			<Pallet<T>>::deposit_event(Event::<T>::CollectionOwnedChanged(
-				collection_id,
-				new_owner
-			));
-
-			target_collection.save()
+			target_collection.change_owner(sender, new_owner.clone())
 		}
 
 		/// Add an admin to a collection.
@@ -522,13 +445,6 @@
 		pub fn add_collection_admin(origin, collection_id: CollectionId, new_admin_id: T::CrossAccountId) -> DispatchResult {
 			let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);
 			let collection = <CollectionHandle<T>>::try_get(collection_id)?;
-			collection.check_is_internal()?;
-
-			<Pallet<T>>::deposit_event(Event::<T>::CollectionAdminAdded(
-				collection_id,
-				new_admin_id.clone()
-			));
-
 			<PalletCommon<T>>::toggle_admin(&collection, &sender, &new_admin_id, true)
 		}
 
@@ -550,13 +466,6 @@
 		pub fn remove_collection_admin(origin, collection_id: CollectionId, account_id: T::CrossAccountId) -> DispatchResult {
 			let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);
 			let collection = <CollectionHandle<T>>::try_get(collection_id)?;
-			collection.check_is_internal()?;
-
-			<Pallet<T>>::deposit_event(Event::<T>::CollectionAdminRemoved(
-				collection_id,
-				account_id.clone()
-			));
-
 			<PalletCommon<T>>::toggle_admin(&collection, &sender, &account_id, false)
 		}
 
@@ -576,19 +485,8 @@
 		#[weight = <SelfWeightOf<T>>::set_collection_sponsor()]
 		pub fn set_collection_sponsor(origin, collection_id: CollectionId, new_sponsor: T::AccountId) -> DispatchResult {
 			let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);
-
 			let mut target_collection = <CollectionHandle<T>>::try_get(collection_id)?;
-			target_collection.check_is_owner_or_admin(&sender)?;
-			target_collection.check_is_internal()?;
-
-			target_collection.set_sponsor(new_sponsor.clone())?;
-
-			<Pallet<T>>::deposit_event(Event::<T>::CollectionSponsorSet(
-				collection_id,
-				new_sponsor
-			));
-
-			target_collection.save()
+			target_collection.set_sponsor(&sender, new_sponsor.clone())
 		}
 
 		/// Confirm own sponsorship of a collection, becoming the sponsor.
@@ -607,20 +505,8 @@
 		#[weight = <SelfWeightOf<T>>::confirm_sponsorship()]
 		pub fn confirm_sponsorship(origin, collection_id: CollectionId) -> DispatchResult {
 			let sender = ensure_signed(origin)?;
-
 			let mut target_collection = <CollectionHandle<T>>::try_get(collection_id)?;
-			target_collection.check_is_internal()?;
-			ensure!(
-				target_collection.confirm_sponsorship(&sender)?,
-				Error::<T>::ConfirmUnsetSponsorFail
-			);
-
-			<Pallet<T>>::deposit_event(Event::<T>::SponsorshipConfirmed(
-				collection_id,
-				sender
-			));
-
-			target_collection.save()
+			target_collection.confirm_sponsorship(&sender)
 		}
 
 		/// Remove a collection's a sponsor, making everyone pay for their own transactions.
@@ -635,17 +521,8 @@
 		#[weight = <SelfWeightOf<T>>::remove_collection_sponsor()]
 		pub fn remove_collection_sponsor(origin, collection_id: CollectionId) -> DispatchResult {
 			let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);
-
 			let mut target_collection = <CollectionHandle<T>>::try_get(collection_id)?;
-			target_collection.check_is_internal()?;
-			target_collection.check_is_owner(&sender)?;
-
-			target_collection.sponsorship = SponsorshipState::Disabled;
-
-			<Pallet<T>>::deposit_event(Event::<T>::CollectionSponsorRemoved(
-				collection_id
-			));
-			target_collection.save()
+			target_collection.remove_sponsor(&sender)
 		}
 
 		/// Mint an item within a collection.
@@ -1053,17 +930,7 @@
 		) -> DispatchResult {
 			let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);
 			let mut target_collection = <CollectionHandle<T>>::try_get(collection_id)?;
-			target_collection.check_is_internal()?;
-			target_collection.check_is_owner_or_admin(&sender)?;
-			let old_limit = &target_collection.limits;
-
-			target_collection.limits = <PalletCommon<T>>::clamp_limits(target_collection.mode.clone(), &old_limit, new_limit)?;
-
-			<Pallet<T>>::deposit_event(Event::<T>::CollectionLimitSet(
-				collection_id
-			));
-
-			target_collection.save()
+			<PalletCommon<T>>::update_limits(&sender, &mut target_collection, new_limit)
 		}
 
 		/// Set specific permissions of a collection. Empty, or None fields mean chain default.
@@ -1086,17 +953,11 @@
 		) -> DispatchResult {
 			let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);
 			let mut target_collection = <CollectionHandle<T>>::try_get(collection_id)?;
-			target_collection.check_is_internal()?;
-			target_collection.check_is_owner_or_admin(&sender)?;
-			let old_limit = &target_collection.permissions;
-
-			target_collection.permissions = <PalletCommon<T>>::clamp_permissions(target_collection.mode.clone(), &old_limit, new_permission)?;
-
-			<Pallet<T>>::deposit_event(Event::<T>::CollectionPermissionSet(
-				collection_id
-			));
-
-			target_collection.save()
+			<PalletCommon<T>>::update_permissions(
+				&sender,
+				&mut target_collection,
+				new_permission
+			)
 		}
 
 		/// Re-partition a refungible token, while owning all of its parts/pieces.
@@ -1163,22 +1024,7 @@
 	/// * `collection_id`: ID of the modified collection.
 	pub fn force_set_sponsor(sponsor: T::AccountId, collection_id: CollectionId) -> DispatchResult {
 		let mut target_collection = <CollectionHandle<T>>::try_get(collection_id)?;
-		target_collection.check_is_internal()?;
-		target_collection.set_sponsor(sponsor.clone())?;
-
-		Self::deposit_event(Event::<T>::CollectionSponsorSet(
-			collection_id,
-			sponsor.clone(),
-		));
-
-		ensure!(
-			target_collection.confirm_sponsorship(&sponsor)?,
-			Error::<T>::ConfirmUnsetSponsorFail
-		);
-
-		Self::deposit_event(Event::<T>::SponsorshipConfirmed(collection_id, sponsor));
-
-		target_collection.save()
+		target_collection.force_set_sponsor(sponsor.clone())
 	}
 
 	/// Force remove `sponsor` for `collection`.
@@ -1191,12 +1037,7 @@
 	/// * `collection_id`: ID of the modified collection.
 	pub fn force_remove_collection_sponsor(collection_id: CollectionId) -> DispatchResult {
 		let mut target_collection = <CollectionHandle<T>>::try_get(collection_id)?;
-		target_collection.check_is_internal()?;
-		target_collection.sponsorship = SponsorshipState::Disabled;
-
-		Self::deposit_event(Event::<T>::CollectionSponsorRemoved(collection_id));
-
-		target_collection.save()
+		target_collection.force_remove_sponsor()
 	}
 
 	#[inline(always)]
modifiedtests/src/change-collection-owner.test.tsdiffbeforeafterboth
--- a/tests/src/change-collection-owner.test.ts
+++ b/tests/src/change-collection-owner.test.ts
@@ -146,7 +146,7 @@
     const confirmSponsorshipTx = () => collection.confirmSponsorship(alice);
     const removeSponsorTx = () => collection.removeSponsor(alice);
     await expect(setSponsorTx()).to.be.rejectedWith(/common\.NoPermission/);
-    await expect(confirmSponsorshipTx()).to.be.rejectedWith(/unique\.ConfirmUnsetSponsorFail/);
+    await expect(confirmSponsorshipTx()).to.be.rejectedWith(/common\.ConfirmUnsetSponsorFail/);
     await expect(removeSponsorTx()).to.be.rejectedWith(/common\.NoPermission/);
 
     const limits = {
modifiedtests/src/confirmSponsorship.test.tsdiffbeforeafterboth
--- a/tests/src/confirmSponsorship.test.ts
+++ b/tests/src/confirmSponsorship.test.ts
@@ -207,14 +207,14 @@
     const collection = await helper.nft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});
     await collection.setSponsor(alice, bob.address);
     const confirmSponsorshipTx = () => collection.confirmSponsorship(charlie);
-    await expect(confirmSponsorshipTx()).to.be.rejectedWith(/unique\.ConfirmUnsetSponsorFail/);
+    await expect(confirmSponsorshipTx()).to.be.rejectedWith(/common\.ConfirmUnsetSponsorFail/);
   });
 
   itSub('(!negative test!) Confirm sponsorship using owner address', async ({helper}) => {
     const collection = await helper.nft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});
     await collection.setSponsor(alice, bob.address);
     const confirmSponsorshipTx = () => collection.confirmSponsorship(alice);
-    await expect(confirmSponsorshipTx()).to.be.rejectedWith(/unique\.ConfirmUnsetSponsorFail/);
+    await expect(confirmSponsorshipTx()).to.be.rejectedWith(/common\.ConfirmUnsetSponsorFail/);
   });
 
   itSub('(!negative test!) Confirm sponsorship by collection admin', async ({helper}) => {
@@ -222,13 +222,13 @@
     await collection.setSponsor(alice, bob.address);
     await collection.addAdmin(alice, {Substrate: charlie.address});
     const confirmSponsorshipTx = () => collection.confirmSponsorship(charlie);
-    await expect(confirmSponsorshipTx()).to.be.rejectedWith(/unique\.ConfirmUnsetSponsorFail/);
+    await expect(confirmSponsorshipTx()).to.be.rejectedWith(/common\.ConfirmUnsetSponsorFail/);
   });
 
   itSub('(!negative test!) Confirm sponsorship without sponsor being set with setCollectionSponsor', async ({helper}) => {
     const collection = await helper.nft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});
     const confirmSponsorshipTx = () => collection.confirmSponsorship(charlie);
-    await expect(confirmSponsorshipTx()).to.be.rejectedWith(/unique\.ConfirmUnsetSponsorFail/);
+    await expect(confirmSponsorshipTx()).to.be.rejectedWith(/common\.ConfirmUnsetSponsorFail/);
   });
 
   itSub('(!negative test!) Confirm sponsorship in a collection that was destroyed', async ({helper}) => {
modifiedtests/src/eth/collectionSponsoring.test.tsdiffbeforeafterboth
--- a/tests/src/eth/collectionSponsoring.test.ts
+++ b/tests/src/eth/collectionSponsoring.test.ts
@@ -258,7 +258,7 @@
       await collectionEvm.methods[testCase](testCase === 'setCollectionSponsor' ? sponsor : sponsorCross).send();
       let collectionData = (await collectionSub.getData())!;
       expect(collectionData.raw.sponsorship.Unconfirmed).to.be.eq(helper.address.ethToSubstrate(sponsor, true));
-      await expect(collectionEvm.methods.confirmCollectionSponsorship().call()).to.be.rejectedWith('caller is not set as sponsor');
+      await expect(collectionEvm.methods.confirmCollectionSponsorship().call()).to.be.rejectedWith('ConfirmUnsetSponsorFail');
   
       await collectionEvm.methods.confirmCollectionSponsorship().send({from: sponsor});
       collectionData = (await collectionSub.getData())!;
modifiedtests/src/eth/createFTCollection.test.tsdiffbeforeafterboth
--- a/tests/src/eth/createFTCollection.test.ts
+++ b/tests/src/eth/createFTCollection.test.ts
@@ -46,7 +46,7 @@
     let data = (await helper.rft.getData(collectionId))!;
     expect(data.raw.sponsorship.Unconfirmed).to.be.equal(evmToAddress(sponsor, Number(ss58Format)));
 
-    await expect(collection.methods.confirmCollectionSponsorship().call()).to.be.rejectedWith('caller is not set as sponsor');
+    await expect(collection.methods.confirmCollectionSponsorship().call()).to.be.rejectedWith('ConfirmUnsetSponsorFail');
 
     const sponsorCollection = helper.ethNativeContract.collection(collectionAddress, 'rft', sponsor, true);
     await sponsorCollection.methods.confirmCollectionSponsorship().send();
@@ -69,7 +69,7 @@
     let data = (await helper.rft.getData(collectionId))!;
     expect(data.raw.sponsorship.Unconfirmed).to.be.equal(evmToAddress(sponsor, Number(ss58Format)));
 
-    await expect(collection.methods.confirmCollectionSponsorship().call()).to.be.rejectedWith('caller is not set as sponsor');
+    await expect(collection.methods.confirmCollectionSponsorship().call()).to.be.rejectedWith('ConfirmUnsetSponsorFail');
 
     const sponsorCollection = helper.ethNativeContract.collection(collectionAddress, 'rft', sponsor);
     await sponsorCollection.methods.confirmCollectionSponsorship().send();
@@ -192,11 +192,11 @@
       const sponsorCollection = helper.ethNativeContract.collection(collectionAddress, 'ft', sponsor, true);
       await expect(sponsorCollection.methods
         .confirmCollectionSponsorship()
-        .call()).to.be.rejectedWith('caller is not set as sponsor');
+        .call()).to.be.rejectedWith('ConfirmUnsetSponsorFail');
     }
     {
       await expect(peasantCollection.methods
-        .setCollectionLimit('account_token_ownership_limit', '1000')
+        .setCollectionLimit('accountTokenOwnershipLimit', '1000')
         .call()).to.be.rejectedWith(EXPECTED_ERROR);
     }
   });
@@ -217,11 +217,11 @@
       const sponsorCollection = helper.ethNativeContract.collection(collectionAddress, 'ft', sponsor);
       await expect(sponsorCollection.methods
         .confirmCollectionSponsorship()
-        .call()).to.be.rejectedWith('caller is not set as sponsor');
+        .call()).to.be.rejectedWith('ConfirmUnsetSponsorFail');
     }
     {
       await expect(peasantCollection.methods
-        .setCollectionLimit('account_token_ownership_limit', '1000')
+        .setCollectionLimit('accountTokenOwnershipLimit', '1000')
         .call()).to.be.rejectedWith(EXPECTED_ERROR);
     }
   });    
modifiedtests/src/eth/createNFTCollection.test.tsdiffbeforeafterboth
--- a/tests/src/eth/createNFTCollection.test.ts
+++ b/tests/src/eth/createNFTCollection.test.ts
@@ -86,7 +86,7 @@
     let data = (await helper.nft.getData(collectionId))!;
     expect(data.raw.sponsorship.Unconfirmed).to.be.equal(evmToAddress(sponsor, Number(ss58Format)));
 
-    await expect(collection.methods.confirmCollectionSponsorship().call()).to.be.rejectedWith('caller is not set as sponsor');
+    await expect(collection.methods.confirmCollectionSponsorship().call()).to.be.rejectedWith('ConfirmUnsetSponsorFail');
 
     const sponsorCollection = helper.ethNativeContract.collection(collectionAddress, 'nft', sponsor, true);
     await sponsorCollection.methods.confirmCollectionSponsorship().send();
@@ -109,7 +109,7 @@
     let data = (await helper.nft.getData(collectionId))!;
     expect(data.raw.sponsorship.Unconfirmed).to.be.equal(evmToAddress(sponsor, Number(ss58Format)));
 
-    await expect(collection.methods.confirmCollectionSponsorship().call()).to.be.rejectedWith('caller is not set as sponsor');
+    await expect(collection.methods.confirmCollectionSponsorship().call()).to.be.rejectedWith('ConfirmUnsetSponsorFail');
 
     const sponsorCollection = helper.ethNativeContract.collection(collectionAddress, 'nft', sponsor);
     await sponsorCollection.methods.confirmCollectionSponsorship().send();
@@ -203,11 +203,11 @@
       const sponsorCollection = helper.ethNativeContract.collection(collectionAddress, 'nft', sponsor, true);
       await expect(sponsorCollection.methods
         .confirmCollectionSponsorship()
-        .call()).to.be.rejectedWith('caller is not set as sponsor');
+        .call()).to.be.rejectedWith('ConfirmUnsetSponsorFail');
     }
     {
       await expect(malfeasantCollection.methods
-        .setCollectionLimit('account_token_ownership_limit', '1000')
+        .setCollectionLimit('accountTokenOwnershipLimit', '1000')
         .call()).to.be.rejectedWith(EXPECTED_ERROR);
     }
   });
@@ -228,11 +228,11 @@
       const sponsorCollection = helper.ethNativeContract.collection(collectionAddress, 'nft', sponsor);
       await expect(sponsorCollection.methods
         .confirmCollectionSponsorship()
-        .call()).to.be.rejectedWith('caller is not set as sponsor');
+        .call()).to.be.rejectedWith('ConfirmUnsetSponsorFail');
     }
     {
       await expect(malfeasantCollection.methods
-        .setCollectionLimit('account_token_ownership_limit', '1000')
+        .setCollectionLimit('accountTokenOwnershipLimit', '1000')
         .call()).to.be.rejectedWith(EXPECTED_ERROR);
     }
   });
modifiedtests/src/eth/createRFTCollection.test.tsdiffbeforeafterboth
--- a/tests/src/eth/createRFTCollection.test.ts
+++ b/tests/src/eth/createRFTCollection.test.ts
@@ -121,7 +121,7 @@
     let data = (await helper.rft.getData(collectionId))!;
     expect(data.raw.sponsorship.Unconfirmed).to.be.equal(evmToAddress(sponsor, Number(ss58Format)));
 
-    await expect(collection.methods.confirmCollectionSponsorship().call()).to.be.rejectedWith('caller is not set as sponsor');
+    await expect(collection.methods.confirmCollectionSponsorship().call()).to.be.rejectedWith('ConfirmUnsetSponsorFail');
 
     const sponsorCollection = helper.ethNativeContract.collection(collectionAddress, 'rft', sponsor, true);
     await sponsorCollection.methods.confirmCollectionSponsorship().send();
@@ -143,7 +143,7 @@
     let data = (await helper.rft.getData(collectionId))!;
     expect(data.raw.sponsorship.Unconfirmed).to.be.equal(evmToAddress(sponsor, Number(ss58Format)));
 
-    await expect(collection.methods.confirmCollectionSponsorship().call()).to.be.rejectedWith('caller is not set as sponsor');
+    await expect(collection.methods.confirmCollectionSponsorship().call()).to.be.rejectedWith('ConfirmUnsetSponsorFail');
 
     const sponsorCollection = helper.ethNativeContract.collection(collectionAddress, 'rft', sponsor);
     await sponsorCollection.methods.confirmCollectionSponsorship().send();
@@ -235,11 +235,11 @@
       const sponsorCollection = helper.ethNativeContract.collection(collectionAddress, 'rft', sponsor, true);
       await expect(sponsorCollection.methods
         .confirmCollectionSponsorship()
-        .call()).to.be.rejectedWith('caller is not set as sponsor');
+        .call()).to.be.rejectedWith('ConfirmUnsetSponsorFail');
     }
     {
       await expect(peasantCollection.methods
-        .setCollectionLimit('account_token_ownership_limit', '1000')
+        .setCollectionLimit('accountTokenOwnershipLimit', '1000')
         .call()).to.be.rejectedWith(EXPECTED_ERROR);
     }
   });
@@ -260,11 +260,11 @@
       const sponsorCollection = helper.ethNativeContract.collection(collectionAddress, 'rft', sponsor);
       await expect(sponsorCollection.methods
         .confirmCollectionSponsorship()
-        .call()).to.be.rejectedWith('caller is not set as sponsor');
+        .call()).to.be.rejectedWith('ConfirmUnsetSponsorFail');
     }
     {
       await expect(peasantCollection.methods
-        .setCollectionLimit('account_token_ownership_limit', '1000')
+        .setCollectionLimit('accountTokenOwnershipLimit', '1000')
         .call()).to.be.rejectedWith(EXPECTED_ERROR);
     }
   });
modifiedtests/src/eth/events.test.tsdiffbeforeafterboth
--- a/tests/src/eth/events.test.ts
+++ b/tests/src/eth/events.test.ts
@@ -14,11 +14,11 @@
 // You should have received a copy of the GNU General Public License
 // along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
 
+import { expect } from 'chai';
 import {IKeyringPair} from '@polkadot/types/types';
-import { expect } from 'chai';
 import { itEth, usingEthPlaygrounds } from './util';
 
-describe.only('NFT events', () => {
+describe('NFT events', () => {
     let donor: IKeyringPair;
   
     before(async function () {
@@ -29,8 +29,9 @@
 
     itEth('Create event', async ({helper}) => {
         const owner = await helper.eth.createAccountWithBalance(donor);
-        const {collectionAddress, events} = await helper.eth.createCollecion('createNFTCollection', owner, 'A', 'B', 'C');
-        expect(events).to.be.like([
+        const {unsubscribe, collectedEvents: subEvents} = await helper.subscribeEvents([{section: 'common', names: ['CollectionCreated']}]);
+        const {collectionAddress, events: ethEvents} = await helper.eth.createCollecion('createNFTCollection', owner, 'A', 'B', 'C');
+        expect(ethEvents).to.be.like([
             {
                 event: 'CollectionCreated',
                 args: {
@@ -39,20 +40,25 @@
                 }
             }
         ]);
+        expect(subEvents).to.be.like([{method: 'CollectionCreated'}]);
+        unsubscribe();
     });
 
     itEth('Destroy event', async ({helper}) => {
         const owner = await helper.eth.createAccountWithBalance(donor);
         const {collectionAddress} = await helper.eth.createCollecion('createNFTCollection', owner, 'A', 'B', 'C');
         const collectionHelper = helper.ethNativeContract.collectionHelpers(owner);
-        let resutl = await collectionHelper.methods.destroyCollection(collectionAddress).send({from:owner});
-        expect(resutl.events).to.be.like({
+        const {unsubscribe, collectedEvents} = await helper.subscribeEvents([{section: 'common', names: ['CollectionDestroyed']}]);
+        let result = await collectionHelper.methods.destroyCollection(collectionAddress).send({from:owner});
+        expect(result.events).to.be.like({
             CollectionDestroyed: {
                 returnValues: {
                     collectionId: collectionAddress
                 }
             }
         });
+        expect(collectedEvents).to.be.like([{method: 'CollectionDestroyed'}]);
+        unsubscribe();
     });
     
     itEth('CollectionChanged event for CollectionPropertySet and CollectionPropertyDeleted', async ({helper}) => {
@@ -61,13 +67,14 @@
         const collection = await helper.ethNativeContract.collection(collectionAddress, 'nft', owner);
         const collectionHelper = helper.ethNativeContract.collectionHelpers(owner);
         
+        let {unsubscribe, collectedEvents: subEvents} = await helper.subscribeEvents([{section: 'common', names: ['CollectionPropertySet', 'CollectionPropertyDeleted']}]);
         {
-            const events: any = [];
+            const ethEvents: any = [];
             collectionHelper.events.allEvents((_: any, event: any) => {
-                events.push(event);
+                ethEvents.push(event);
             });
             await collection.methods.setCollectionProperties([{key: 'A', value: [0,1,2,3]}]).send({from:owner});
-            expect(events).to.be.like([
+            expect(ethEvents).to.be.like([
                 {
                     event: 'CollectionChanged',
                     returnValues: {
@@ -75,14 +82,16 @@
                     }
                 }
             ]);
+            expect(subEvents).to.be.like([{method: 'CollectionPropertySet'}]);
+            subEvents.pop();
         }
         {
-            const events: any = [];
+            const ethEvents: any = [];
             collectionHelper.events.allEvents((_: any, event: any) => {
-                events.push(event);
+                ethEvents.push(event);
             });
             await collection.methods.deleteCollectionProperties(['A']).send({from:owner});
-            expect(events).to.be.like([
+            expect(ethEvents).to.be.like([
                 {
                     event: 'CollectionChanged',
                     returnValues: {
@@ -90,8 +99,9 @@
                     }
                 }
             ]);
+            expect(subEvents).to.be.like([{method: 'CollectionPropertyDeleted'}]);
         }
-
+        unsubscribe();
     });
     
     itEth('CollectionChanged event for PropertyPermissionSet', async ({helper}) => {
@@ -99,12 +109,13 @@
         const {collectionAddress} = await helper.eth.createCollecion('createNFTCollection', owner, 'A', 'B', 'C');
         const collection = await helper.ethNativeContract.collection(collectionAddress, 'nft', owner);
         const collectionHelper = helper.ethNativeContract.collectionHelpers(owner);
-        const events: any = [];
+        const eethEvents: any = [];
         collectionHelper.events.allEvents((_: any, event: any) => {
-            events.push(event);
+            eethEvents.push(event);
         });
+        const {unsubscribe, collectedEvents: subEvents} = await helper.subscribeEvents([{section: 'common', names: ['PropertyPermissionSet']}]);
         await collection.methods.setTokenPropertyPermission('testKey', true, true, true).send({from: owner});
-        expect(events).to.be.like([
+        expect(eethEvents).to.be.like([
             {
                 event: 'CollectionChanged',
                 returnValues: {
@@ -112,28 +123,236 @@
                 }
             }
         ]);
+        expect(subEvents).to.be.like([{method: 'PropertyPermissionSet'}]);
+        unsubscribe();
+    });
+    
+    itEth('CollectionChanged event for AllowListAddressAdded, AllowListAddressRemoved', async ({helper}) => {
+        const owner = await helper.eth.createAccountWithBalance(donor);
+        const user = helper.ethCrossAccount.createAccount();
+        const {collectionAddress} = await helper.eth.createCollecion('createNFTCollection', owner, 'A', 'B', 'C');
+        const collection = await helper.ethNativeContract.collection(collectionAddress, 'nft', owner);
+        const collectionHelper = helper.ethNativeContract.collectionHelpers(owner);
+        const ethEvents: any[] = [];
+        collectionHelper.events.allEvents((_: any, event: any) => {
+            ethEvents.push(event);
+        });
+
+        const {unsubscribe, collectedEvents: subEvents} = await helper.subscribeEvents([{section: 'common', names: ['AllowListAddressAdded', 'AllowListAddressRemoved']}]);
+        {
+            await collection.methods.addToCollectionAllowListCross(user).send({from: owner});
+            expect(ethEvents).to.be.like([
+                {
+                    event: 'CollectionChanged',
+                    returnValues: {
+                        collectionId: collectionAddress
+                    }
+                }
+            ]);
+            expect(subEvents).to.be.like([{method: 'AllowListAddressAdded'}]);
+            ethEvents.pop();
+            subEvents.pop();
+        }
+        {
+            await collection.methods.removeFromCollectionAllowListCross(user).send({from: owner});
+            expect(ethEvents.length).to.be.eq(1);
+            expect(ethEvents).to.be.like([
+                {
+                    event: 'CollectionChanged',
+                    returnValues: {
+                        collectionId: collectionAddress
+                    }
+                }
+            ]);
+            expect(subEvents).to.be.like([{method: 'AllowListAddressRemoved'}]);
+        }
+        unsubscribe();
     });
     
-    // itEth('CollectionChanged event for AllowListAddressAdded', async ({helper}) => {
-    //     const owner = await helper.eth.createAccountWithBalance(donor);
-    //     const user = await helper.eth.createAccount();
-    //     const userCross = helper.ethCrossAccount.fromAddress(user);
-    //     const {collectionId} = await helper.nft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});
-    //   // allow list does not need to be enabled to add someone in advance
-    //     const collection = await helper.ethNativeContract.collection(collectionAddress, 'nft', owner);
-    //     const collectionHelper = helper.ethNativeContract.collectionHelpers(owner);
-    //     const events: any = [];
-    //     collectionHelper.events.allEvents((_: any, event: any) => {
-    //         events.push(event);
-    //     });
-    //     await helper.nft.addToAllowList(alice, collectionId, {Substrate: bob.address});
-    //     expect(events).to.be.like([
-    //         {
-    //             event: 'CollectionChanged',
-    //             returnValues: {
-    //                 collectionId: collectionAddress
-    //             }
-    //         }
-    //     ]);
-    // });
+    itEth('CollectionChanged event for CollectionAdminAdded, CollectionAdminRemoved', async ({helper}) => {
+        const owner = await helper.eth.createAccountWithBalance(donor);
+        const user = helper.ethCrossAccount.createAccount();
+        const {collectionAddress} = await helper.eth.createCollecion('createNFTCollection', owner, 'A', 'B', 'C');
+        const collection = await helper.ethNativeContract.collection(collectionAddress, 'nft', owner);
+        const collectionHelper = helper.ethNativeContract.collectionHelpers(owner);
+        const ethEvents: any = [];
+        collectionHelper.events.allEvents((_: any, event: any) => {
+            ethEvents.push(event);
+        });
+        const {unsubscribe, collectedEvents: subEvents} = await helper.subscribeEvents([{section: 'common', names: ['CollectionAdminAdded', 'CollectionAdminRemoved']}]);
+        {
+            await collection.methods.addCollectionAdminCross(user).send({from: owner});
+            expect(ethEvents).to.be.like([
+                {
+                    event: 'CollectionChanged',
+                    returnValues: {
+                        collectionId: collectionAddress
+                    }
+                }
+            ]);
+            expect(subEvents).to.be.like([{method: 'CollectionAdminAdded'}]);
+            ethEvents.pop();
+            subEvents.pop();
+        }
+        {
+            await collection.methods.removeCollectionAdminCross(user).send({from: owner});
+            expect(ethEvents).to.be.like([
+                {
+                    event: 'CollectionChanged',
+                    returnValues: {
+                        collectionId: collectionAddress
+                    }
+                }
+            ]);
+            expect(subEvents).to.be.like([{method: 'CollectionAdminRemoved'}]);
+        }
+        unsubscribe();
+    });
+    
+    itEth('CollectionChanged event for CollectionLimitSet', async ({helper}) => {
+        const owner = await helper.eth.createAccountWithBalance(donor);
+        const {collectionAddress} = await helper.eth.createCollecion('createNFTCollection', owner, 'A', 'B', 'C');
+        const collection = await helper.ethNativeContract.collection(collectionAddress, 'nft', owner);
+        const collectionHelper = helper.ethNativeContract.collectionHelpers(owner);
+        const ethEvents: any = [];
+        collectionHelper.events.allEvents((_: any, event: any) => {
+            ethEvents.push(event);
+        });
+        const {unsubscribe, collectedEvents: subEvents} = await helper.subscribeEvents([{section: 'common', names: ['CollectionLimitSet']}]);
+        {
+            await collection.methods.setCollectionLimit('ownerCanTransfer', 0n).send({from: owner});
+            expect(ethEvents).to.be.like([
+                {
+                    event: 'CollectionChanged',
+                    returnValues: {
+                        collectionId: collectionAddress
+                    }
+                }
+            ]);
+            expect(subEvents).to.be.like([{method: 'CollectionLimitSet'}]);
+        }
+        unsubscribe();
+    });
+    
+    itEth('CollectionChanged event for CollectionOwnedChanged', async ({helper}) => {
+        const owner = await helper.eth.createAccountWithBalance(donor);
+        const new_owner = helper.ethCrossAccount.createAccount();
+        const {collectionAddress} = await helper.eth.createCollecion('createNFTCollection', owner, 'A', 'B', 'C');
+        const collection = await helper.ethNativeContract.collection(collectionAddress, 'nft', owner);
+        const collectionHelper = helper.ethNativeContract.collectionHelpers(owner);
+        const ethEvents: any = [];
+        collectionHelper.events.allEvents((_: any, event: any) => {
+            ethEvents.push(event);
+        });
+        const {unsubscribe, collectedEvents: subEvents} = await helper.subscribeEvents([{section: 'common', names: ['CollectionOwnedChanged']}]);
+        {
+            await collection.methods.changeCollectionOwnerCross(new_owner).send({from: owner});
+            expect(ethEvents).to.be.like([
+                {
+                    event: 'CollectionChanged',
+                    returnValues: {
+                        collectionId: collectionAddress
+                    }
+                }
+            ]);
+            expect(subEvents).to.be.like([{method: 'CollectionOwnedChanged'}]);
+        }
+        unsubscribe();
+    });
+    
+    itEth('CollectionChanged event for CollectionPermissionSet', async ({helper}) => {
+        const owner = await helper.eth.createAccountWithBalance(donor);
+        const {collectionAddress} = await helper.eth.createCollecion('createNFTCollection', owner, 'A', 'B', 'C');
+        const collection = await helper.ethNativeContract.collection(collectionAddress, 'nft', owner);
+        const collectionHelper = helper.ethNativeContract.collectionHelpers(owner);
+        const ethEvents: any = [];
+        collectionHelper.events.allEvents((_: any, event: any) => {
+            ethEvents.push(event);
+        });
+        const {unsubscribe, collectedEvents: subEvents} = await helper.subscribeEvents([{section: 'common', names: ['CollectionPermissionSet']}]);
+        {
+            await collection.methods.setCollectionMintMode(true).send({from: owner});
+            expect(ethEvents).to.be.like([
+                {
+                    event: 'CollectionChanged',
+                    returnValues: {
+                        collectionId: collectionAddress
+                    }
+                }
+            ]);
+            expect(subEvents).to.be.like([{method: 'CollectionPermissionSet'}]);
+            ethEvents.pop();
+            subEvents.pop();
+        }
+        {
+            await collection.methods.setCollectionAccess(1).send({from: owner});
+            expect(ethEvents).to.be.like([
+                {
+                    event: 'CollectionChanged',
+                    returnValues: {
+                        collectionId: collectionAddress
+                    }
+                }
+            ]);
+            expect(subEvents).to.be.like([{method: 'CollectionPermissionSet'}]);
+        }
+        unsubscribe();
+    });
+
+    itEth('CollectionChanged event for CollectionSponsorSet, SponsorshipConfirmed, CollectionSponsorRemoved', async ({helper}) => {
+        const owner = await helper.eth.createAccountWithBalance(donor);
+        const sponsor = await helper.ethCrossAccount.createAccountWithBalance(donor);
+        const {collectionAddress} = await helper.eth.createCollecion('createNFTCollection', owner, 'A', 'B', 'C');
+        const collection = await helper.ethNativeContract.collection(collectionAddress, 'nft', owner);
+        const collectionHelper = helper.ethNativeContract.collectionHelpers(owner);
+        const ethEvents: any = [];
+        collectionHelper.events.allEvents((_: any, event: any) => {
+            ethEvents.push(event);
+        });
+        const {unsubscribe, collectedEvents: subEvents} = await helper.subscribeEvents([{
+            section: 'common', names: ['CollectionSponsorSet', 'SponsorshipConfirmed', 'CollectionSponsorRemoved'
+        ]}]);
+        {
+            await collection.methods.setCollectionSponsorCross(sponsor).send({from: owner});
+            expect(ethEvents).to.be.like([
+                {
+                    event: 'CollectionChanged',
+                    returnValues: {
+                        collectionId: collectionAddress
+                    }
+                }
+            ]);
+            expect(subEvents).to.be.like([{method: 'CollectionSponsorSet'}]);
+            ethEvents.pop();
+            subEvents.pop();
+        }
+        {
+            await collection.methods.confirmCollectionSponsorship().send({from: sponsor.eth});
+            expect(ethEvents).to.be.like([
+                {
+                    event: 'CollectionChanged',
+                    returnValues: {
+                        collectionId: collectionAddress
+                    }
+                }
+            ]);
+            expect(subEvents).to.be.like([{method: 'SponsorshipConfirmed'}]);
+            ethEvents.pop();
+            subEvents.pop();
+        }
+        {
+            await collection.methods.removeCollectionSponsor().send({from: owner});
+            expect(ethEvents).to.be.like([
+                {
+                    event: 'CollectionChanged',
+                    returnValues: {
+                        collectionId: collectionAddress
+                    }
+                }
+            ]);
+            expect(subEvents).to.be.like([{method: 'CollectionSponsorRemoved'}]);
+        }
+        unsubscribe();
+    });
+    
 });
\ No newline at end of file
modifiedtests/src/removeCollectionAdmin.test.tsdiffbeforeafterboth
--- a/tests/src/removeCollectionAdmin.test.ts
+++ b/tests/src/removeCollectionAdmin.test.ts
@@ -51,7 +51,7 @@
     const adminListBeforeAddAdmin = await collection.getAdmins();
     expect(adminListBeforeAddAdmin).to.have.lengthOf(0);
 
-    await collection.removeAdmin(alice, {Substrate: alice.address});
+    await expect(collection.removeAdmin(alice, {Substrate: alice.address})).to.be.rejectedWith('common.UserIsNotAdmin');
   });
 });
 
modifiedtests/src/removeCollectionSponsor.test.tsdiffbeforeafterboth
--- a/tests/src/removeCollectionSponsor.test.ts
+++ b/tests/src/removeCollectionSponsor.test.ts
@@ -112,7 +112,7 @@
     const collection = await helper.nft.mintCollection(alice, {name: 'RemoveCollectionSponsor-Neg-4', tokenPrefix: 'RCS'});
     await collection.setSponsor(alice, bob.address);
     await collection.removeSponsor(alice);
-    await expect(collection.confirmSponsorship(bob)).to.be.rejectedWith(/unique\.ConfirmUnsetSponsorFail/);
+    await expect(collection.confirmSponsorship(bob)).to.be.rejectedWith(/common\.ConfirmUnsetSponsorFail/);
   });
 
   itSub('Set - confirm - remove - confirm: Sponsor cannot come back', async ({helper}) => {
@@ -120,6 +120,6 @@
     await collection.setSponsor(alice, bob.address);
     await collection.confirmSponsorship(bob);
     await collection.removeSponsor(alice);
-    await expect(collection.confirmSponsorship(bob)).to.be.rejectedWith(/unique\.ConfirmUnsetSponsorFail/);
+    await expect(collection.confirmSponsorship(bob)).to.be.rejectedWith(/common\.ConfirmUnsetSponsorFail/);
   });
 });
modifiedtests/src/util/playgrounds/unique.tsdiffbeforeafterboth
--- a/tests/src/util/playgrounds/unique.ts
+++ b/tests/src/util/playgrounds/unique.ts
@@ -43,6 +43,8 @@
   IEthCrossAccountId,
 } from './types';
 import {RuntimeDispatchInfo} from '@polkadot/types/interfaces';
+import type {Vec} from '@polkadot/types-codec';
+import { FrameSystemEventRecord } from '@polkadot/types/lookup';
 
 export class CrossAccountId implements ICrossAccountId {
   Substrate?: TSubstrateAccount;
@@ -404,6 +406,21 @@
     return this.api;
   }
 
+  async subscribeEvents(expectedEvents: {section: string, names: string[]}[]) {
+    const collectedEvents: IEvent[] = [];
+    const unsubscribe = await this.getApi().query.system.events((events: Vec<FrameSystemEventRecord>) => {
+        const ievents = this.eventHelper.extractEvents(events);
+        ievents.forEach((event) => {
+            expectedEvents.forEach((e => {
+                if (event.section === e.section && e.names.includes(event.method)) {
+                    collectedEvents.push(event);
+                }
+            }))
+        });
+    });
+    return {unsubscribe: unsubscribe as any, collectedEvents};
+}
+
   clearChainLog(): void {
     this.chainLog = [];
   }
@@ -834,7 +851,7 @@
       true,
     );
 
-    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionSponsorSet');
+    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionSponsorSet');
   }
 
   /**
@@ -852,7 +869,7 @@
       true,
     );
 
-    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'SponsorshipConfirmed');
+    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'SponsorshipConfirmed');
   }
 
   /**
@@ -870,7 +887,7 @@
       true,
     );
 
-    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionSponsorRemoved');
+    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionSponsorRemoved');
   }
 
   /**
@@ -897,7 +914,7 @@
       true,
     );
 
-    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionLimitSet');
+    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionLimitSet');
   }
 
   /**
@@ -916,7 +933,7 @@
       true,
     );
 
-    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionOwnedChanged');
+    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionOwnedChanged');
   }
 
   /**
@@ -935,7 +952,7 @@
       true,
     );
 
-    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionAdminAdded');
+    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionAdminAdded');
   }
 
   /**
@@ -954,7 +971,7 @@
       true,
     );
 
-    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionAdminRemoved');
+    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionAdminRemoved');
   }
 
   /**
@@ -983,7 +1000,7 @@
       true,
     );
 
-    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'AllowListAddressAdded');
+    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'AllowListAddressAdded');
   }
 
   /**
@@ -1001,7 +1018,7 @@
       true,
     );
 
-    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'AllowListAddressRemoved');
+    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'AllowListAddressRemoved');
   }
 
   /**
@@ -1020,7 +1037,7 @@
       true,
     );
 
-    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionPermissionSet');
+    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPermissionSet');
   }
 
   /**