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

difftreelog

refactor LazyValue without generic Fn

Daniel Shiposha2023-10-11parent: #5a68a95.patch.diff
in: master

1 file changed

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::{57	marker::PhantomData,58	ops::{Deref, DerefMut},59	slice::from_ref,60};6162use evm_coder::ToLog;63use frame_support::{64	dispatch::{DispatchErrorWithPostInfo, DispatchResultWithPostInfo, Pays, PostDispatchInfo},65	ensure, fail,66	traits::{67		fungible::{Balanced, Debt, Inspect},68		tokens::{Imbalance, Precision, Preservation},69		Get,70	},71	transactional,72};73pub use pallet::*;74use pallet_evm::{account::CrossAccountId, Pallet as PalletEvm};75use pallet_evm_coder_substrate::{SubstrateRecorder, WithRecorder};76use sp_core::H160;77use sp_runtime::{traits::Zero, ArithmeticError, DispatchError, DispatchResult};78use sp_std::vec::Vec;79use sp_weights::Weight;80use up_data_structs::{81	budget::Budget, AccessMode, Collection, CollectionId, CollectionLimits, CollectionMode,82	CollectionPermissions, CollectionProperties as CollectionPropertiesT, CollectionStats,83	CreateCollectionData, CreateItemData, CreateItemExData, PhantomType, PropertiesError,84	PropertiesPermissionMap, Property, PropertyKey, PropertyKeyPermission, PropertyPermission,85	PropertyScope, PropertyValue, RpcCollection, RpcCollectionFlags, SponsoringRateLimit,86	SponsorshipState, TokenChild, TokenData, TokenId, TokenOwnerError, TokenProperties,87	TrySetProperty, COLLECTION_ADMINS_LIMIT, COLLECTION_NUMBER_LIMIT, CUSTOM_DATA_LIMIT,88	FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT, MAX_SPONSOR_TIMEOUT, MAX_TOKEN_OWNERSHIP,89	MAX_TOKEN_PREFIX_LENGTH, NFT_SPONSOR_TRANSFER_TIMEOUT, REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,90};91use up_pov_estimate_rpc::PovInfo;9293#[cfg(feature = "runtime-benchmarks")]94pub mod benchmarking;95pub mod dispatch;96pub mod erc;97pub mod eth;98pub mod helpers;99#[allow(missing_docs)]100pub mod weights;101102use weights::WeightInfo;103104/// Weight info.105pub type SelfWeightOf<T> = <T as Config>::WeightInfo;106107/// Collection handle contains information about collection data and id.108/// Also provides functionality to count consumed gas.109///110/// CollectionHandle is used as a generic wrapper for collections of all types (except native fungible).111/// It allows to perform common operations and queries on any collection type,112/// both completely general for all, as well as their respective implementations of [`CommonCollectionOperations`].113#[must_use = "Should call submit_logs or save, otherwise some data will be lost for evm side"]114pub struct CollectionHandle<T: Config> {115	/// Collection id116	pub id: CollectionId,117	collection: Collection<T::AccountId>,118	/// Substrate recorder for counting consumed gas119	pub recorder: SubstrateRecorder<T>,120}121122impl<T: Config> WithRecorder<T> for CollectionHandle<T> {123	fn recorder(&self) -> &SubstrateRecorder<T> {124		&self.recorder125	}126	fn into_recorder(self) -> SubstrateRecorder<T> {127		self.recorder128	}129}130131impl<T: Config> CollectionHandle<T> {132	/// Same as [CollectionHandle::new] but with an explicit gas limit.133	pub fn new_with_gas_limit(id: CollectionId, gas_limit: u64) -> Option<Self> {134		Self::new_with_recorder(id, SubstrateRecorder::new(gas_limit))135	}136137	/// Same as [CollectionHandle::new] but with an existed [`SubstrateRecorder`].138	pub fn new_with_recorder(id: CollectionId, recorder: SubstrateRecorder<T>) -> Option<Self> {139		<CollectionById<T>>::get(id).map(|collection| Self {140			id,141			collection,142			recorder,143		})144	}145146	/// Retrives collection data from storage and creates collection handle with default parameters.147	/// If collection not found return `None`148	pub fn new(id: CollectionId) -> Option<Self> {149		Self::new_with_gas_limit(id, u64::MAX)150	}151152	/// Same as [`CollectionHandle::new`] but if collection not found [CollectionNotFound](Error::CollectionNotFound) returned.153	pub fn try_get(id: CollectionId) -> Result<Self, DispatchError> {154		Ok(Self::new(id).ok_or(<Error<T>>::CollectionNotFound)?)155	}156157	/// Consume gas for reading.158	pub fn consume_store_reads(159		&self,160		reads: u64,161	) -> pallet_evm_coder_substrate::execution::Result<()> {162		self.recorder().consume_store_reads(reads)163	}164165	/// Consume gas for writing.166	pub fn consume_store_writes(167		&self,168		writes: u64,169	) -> pallet_evm_coder_substrate::execution::Result<()> {170		self.recorder().consume_store_writes(writes)171	}172173	/// Consume gas for reading and writing.174	pub fn consume_store_reads_and_writes(175		&self,176		reads: u64,177		writes: u64,178	) -> pallet_evm_coder_substrate::execution::Result<()> {179		self.recorder()180			.consume_store_reads_and_writes(reads, writes)181	}182183	/// Save collection to storage.184	pub fn save(&self) -> DispatchResult {185		<CollectionById<T>>::insert(self.id, &self.collection);186		Ok(())187	}188189	/// Set collection sponsor.190	///191	/// Unique collections allows sponsoring for certain actions.192	/// This method allows you to set the sponsor of the collection.193	/// In order for sponsorship to become active, it must be confirmed through [`Self::confirm_sponsorship`].194	pub fn set_sponsor(195		&mut self,196		sender: &T::CrossAccountId,197		sponsor: T::AccountId,198	) -> DispatchResult {199		self.check_is_internal()?;200		self.check_is_owner_or_admin(sender)?;201202		self.collection.sponsorship = SponsorshipState::Unconfirmed(sponsor.clone());203204		<Pallet<T>>::deposit_event(Event::<T>::CollectionSponsorSet(self.id, sponsor));205		<PalletEvm<T>>::deposit_log(206			erc::CollectionHelpersEvents::CollectionChanged {207				collection_id: eth::collection_id_to_address(self.id),208			}209			.to_log(T::ContractAddress::get()),210		);211212		self.save()213	}214215	/// Force set `sponsor`.216	///217	/// Differs from [`set_sponsor`][`Self::set_sponsor`] in that confirmation218	/// from the `sponsor` is not required.219	///220	/// # Arguments221	///222	/// * `sponsor`: ID of the account of the sponsor-to-be.223	pub fn force_set_sponsor(&mut self, sponsor: T::AccountId) -> DispatchResult {224		self.check_is_internal()?;225226		self.collection.sponsorship = SponsorshipState::Confirmed(sponsor.clone());227228		<Pallet<T>>::deposit_event(Event::<T>::CollectionSponsorSet(self.id, sponsor.clone()));229		<Pallet<T>>::deposit_event(Event::<T>::SponsorshipConfirmed(self.id, sponsor));230		<PalletEvm<T>>::deposit_log(231			erc::CollectionHelpersEvents::CollectionChanged {232				collection_id: eth::collection_id_to_address(self.id),233			}234			.to_log(T::ContractAddress::get()),235		);236237		self.save()238	}239240	/// Confirm sponsorship241	///242	/// In order for the sponsorship to become active, the user set as the sponsor must confirm their participation.243	/// Before confirming sponsorship, the user must be specified as the sponsor of the collection via [`Self::set_sponsor`].244	pub fn confirm_sponsorship(&mut self, sender: &T::AccountId) -> DispatchResult {245		self.check_is_internal()?;246		ensure!(247			self.collection.sponsorship.pending_sponsor() == Some(sender),248			Error::<T>::ConfirmSponsorshipFail249		);250251		self.collection.sponsorship = SponsorshipState::Confirmed(sender.clone());252253		<Pallet<T>>::deposit_event(Event::<T>::SponsorshipConfirmed(self.id, sender.clone()));254		<PalletEvm<T>>::deposit_log(255			erc::CollectionHelpersEvents::CollectionChanged {256				collection_id: eth::collection_id_to_address(self.id),257			}258			.to_log(T::ContractAddress::get()),259		);260261		self.save()262	}263264	/// Remove collection sponsor.265	pub fn remove_sponsor(&mut self, sender: &T::CrossAccountId) -> DispatchResult {266		self.check_is_internal()?;267		self.check_is_owner_or_admin(sender)?;268269		self.collection.sponsorship = SponsorshipState::Disabled;270271		<Pallet<T>>::deposit_event(Event::<T>::CollectionSponsorRemoved(self.id));272		<PalletEvm<T>>::deposit_log(273			erc::CollectionHelpersEvents::CollectionChanged {274				collection_id: eth::collection_id_to_address(self.id),275			}276			.to_log(T::ContractAddress::get()),277		);278		self.save()279	}280281	/// Force remove `sponsor`.282	///283	/// Differs from `remove_sponsor` in that284	/// it doesn't require consent from the `owner` of the collection.285	pub fn force_remove_sponsor(&mut self) -> DispatchResult {286		self.check_is_internal()?;287288		self.collection.sponsorship = SponsorshipState::Disabled;289290		<Pallet<T>>::deposit_event(Event::<T>::CollectionSponsorRemoved(self.id));291		<PalletEvm<T>>::deposit_log(292			erc::CollectionHelpersEvents::CollectionChanged {293				collection_id: eth::collection_id_to_address(self.id),294			}295			.to_log(T::ContractAddress::get()),296		);297		self.save()298	}299300	/// Checks that the collection was created with, and must be operated upon through **Unique API**.301	/// Now check only the `external` flag and if it's **true**, then return [`Error::CollectionIsExternal`] error.302	pub fn check_is_internal(&self) -> DispatchResult {303		if self.flags.external {304			return Err(<Error<T>>::CollectionIsExternal)?;305		}306307		Ok(())308	}309310	/// Checks that the collection was created with, and must be operated upon through an **assimilated API**.311	/// Now check only the `external` flag and if it's **false**, then return [`Error::CollectionIsInternal`] error.312	pub fn check_is_external(&self) -> DispatchResult {313		if !self.flags.external {314			return Err(<Error<T>>::CollectionIsInternal)?;315		}316317		Ok(())318	}319}320321impl<T: Config> Deref for CollectionHandle<T> {322	type Target = Collection<T::AccountId>;323324	fn deref(&self) -> &Self::Target {325		&self.collection326	}327}328329impl<T: Config> DerefMut for CollectionHandle<T> {330	fn deref_mut(&mut self) -> &mut Self::Target {331		&mut self.collection332	}333}334335impl<T: Config> CollectionHandle<T> {336	/// Checks if the `user` is the owner of the collection.337	pub fn check_is_owner(&self, user: &T::CrossAccountId) -> DispatchResult {338		ensure!(*user.as_sub() == self.owner, <Error<T>>::NoPermission);339		Ok(())340	}341342	/// Returns **true** if the `user` is the owner or administrator of the collection.343	pub fn is_owner_or_admin(&self, user: &T::CrossAccountId) -> bool {344		*user.as_sub() == self.owner || <IsAdmin<T>>::get((self.id, user))345	}346347	/// Checks if the `user` is the owner or administrator of the collection.348	pub fn check_is_owner_or_admin(&self, user: &T::CrossAccountId) -> DispatchResult {349		ensure!(self.is_owner_or_admin(user), <Error<T>>::NoPermission);350		Ok(())351	}352353	/// Returns **true** if354	/// * the `user`is a collection owner or admin355	/// * the collection limits allow the owner/admins to transfer/burn any collection token356	pub fn ignores_token_restrictions(&self, user: &T::CrossAccountId) -> bool {357		self.limits.owner_can_transfer() && self.is_owner_or_admin(user)358	}359360	/// Return **true** if `user` does not have enough token parts, and he can ignore such restrictions.361	pub fn ignores_owned_amount(&self, user: &T::CrossAccountId) -> bool {362		self.limits.owner_can_transfer() && self.is_owner_or_admin(user)363	}364365	/// Checks if the user is in the allow list. If not [Error::AddressNotInAllowlist] returns.366	pub fn check_allowlist(&self, user: &T::CrossAccountId) -> DispatchResult {367		ensure!(368			<Allowlist<T>>::get((self.id, user)),369			<Error<T>>::AddressNotInAllowlist370		);371		Ok(())372	}373374	/// Changes collection owner to another account375	/// #### Store read/writes376	/// 1 writes377	pub fn change_owner(378		&mut self,379		caller: T::CrossAccountId,380		new_owner: T::CrossAccountId,381	) -> DispatchResult {382		self.check_is_internal()?;383		self.check_is_owner(&caller)?;384		self.collection.owner = new_owner.as_sub().clone();385386		<Pallet<T>>::deposit_event(Event::<T>::CollectionOwnerChanged(387			self.id,388			new_owner.as_sub().clone(),389		));390		<PalletEvm<T>>::deposit_log(391			erc::CollectionHelpersEvents::CollectionChanged {392				collection_id: eth::collection_id_to_address(self.id),393			}394			.to_log(T::ContractAddress::get()),395		);396397		self.save()398	}399}400401#[frame_support::pallet]402pub mod pallet {403404	use dispatch::CollectionDispatch;405	use frame_support::{406		pallet_prelude::*, storage::Key, traits::StorageVersion, Blake2_128Concat,407	};408	use scale_info::TypeInfo;409	use up_data_structs::{mapping::TokenAddressMapping, TokenId};410	use weights::WeightInfo;411412	use super::*;413414	#[pallet::config]415	pub trait Config:416		frame_system::Config + pallet_evm_coder_substrate::Config + pallet_evm::Config + TypeInfo417	{418		/// Weight information for functions of this pallet.419		type WeightInfo: WeightInfo;420421		/// Events compatible with [`frame_system::Config::Event`].422		type RuntimeEvent: IsType<<Self as frame_system::Config>::RuntimeEvent> + From<Event<Self>>;423424		/// Handler of accounts and payment.425		type Currency: Balanced<Self::AccountId> + Inspect<Self::AccountId>;426427		/// Set price to create a collection.428		#[pallet::constant]429		type CollectionCreationPrice: Get<430			<<Self as Config>::Currency as Inspect<Self::AccountId>>::Balance,431		>;432433		/// Dispatcher of operations on collections.434		type CollectionDispatch: CollectionDispatch<Self>;435436		/// Account which holds the chain's treasury.437		type TreasuryAccountId: Get<Self::AccountId>;438439		/// Address under which the CollectionHelper contract would be available.440		#[pallet::constant]441		type ContractAddress: Get<H160>;442443		/// Mapper for token addresses to Ethereum addresses.444		type EvmTokenAddressMapping: TokenAddressMapping<H160>;445446		/// Mapper for token addresses to [`CrossAccountId`].447		type CrossTokenAddressMapping: TokenAddressMapping<Self::CrossAccountId>;448	}449450	const STORAGE_VERSION: StorageVersion = StorageVersion::new(1);451	/// Collection id for native fungible collction.452	pub const NATIVE_FUNGIBLE_COLLECTION_ID: CollectionId = CollectionId(0);453454	#[pallet::pallet]455	#[pallet::storage_version(STORAGE_VERSION)]456	pub struct Pallet<T>(_);457458	#[pallet::extra_constants]459	impl<T: Config> Pallet<T> {460		/// Maximum admins per collection.461		pub fn collection_admins_limit() -> u32 {462			COLLECTION_ADMINS_LIMIT463		}464	}465466	#[pallet::genesis_config]467	pub struct GenesisConfig<T>(PhantomData<T>);468469	impl<T: Config> Default for GenesisConfig<T> {470		fn default() -> Self {471			Self(Default::default())472		}473	}474475	#[pallet::genesis_build]476	impl<T: Config> BuildGenesisConfig for GenesisConfig<T> {477		fn build(&self) {478			StorageVersion::new(1).put::<Pallet<T>>();479		}480	}481482	impl<T: Config> Pallet<T> {483		/// Helper function that handles deposit events484		pub fn deposit_event(event: Event<T>) {485			let event = <T as Config>::RuntimeEvent::from(event);486			let event = event.into();487			<frame_system::Pallet<T>>::deposit_event(event)488		}489	}490491	#[pallet::event]492	pub enum Event<T: Config> {493		/// New collection was created494		CollectionCreated(495			/// Globally unique identifier of newly created collection.496			CollectionId,497			/// [`CollectionMode`] converted into _u8_.498			u8,499			/// Collection owner.500			T::AccountId,501		),502503		/// New collection was destroyed504		CollectionDestroyed(505			/// Globally unique identifier of collection.506			CollectionId,507		),508509		/// New item was created.510		ItemCreated(511			/// Id of the collection where item was created.512			CollectionId,513			/// Id of an item. Unique within the collection.514			TokenId,515			/// Owner of newly created item516			T::CrossAccountId,517			/// Always 1 for NFT518			u128,519		),520521		/// Collection item was burned.522		ItemDestroyed(523			/// Id of the collection where item was destroyed.524			CollectionId,525			/// Identifier of burned NFT.526			TokenId,527			/// Which user has destroyed its tokens.528			T::CrossAccountId,529			/// Amount of token pieces destroed. Always 1 for NFT.530			u128,531		),532533		/// Item was transferred534		Transfer(535			/// Id of collection to which item is belong.536			CollectionId,537			/// Id of an item.538			TokenId,539			/// Original owner of item.540			T::CrossAccountId,541			/// New owner of item.542			T::CrossAccountId,543			/// Amount of token pieces transfered. Always 1 for NFT.544			u128,545		),546547		/// Amount pieces of token owned by `sender` was approved for `spender`.548		Approved(549			/// Id of collection to which item is belong.550			CollectionId,551			/// Id of an item.552			TokenId,553			/// Original owner of item.554			T::CrossAccountId,555			/// Id for which the approval was granted.556			T::CrossAccountId,557			/// Amount of token pieces transfered. Always 1 for NFT.558			u128,559		),560561		/// A `sender` approves operations on all owned tokens for `spender`.562		ApprovedForAll(563			/// Id of collection to which item is belong.564			CollectionId,565			/// Owner of a wallet.566			T::CrossAccountId,567			/// Id for which operator status was granted or rewoked.568			T::CrossAccountId,569			/// Is operator status granted or revoked?570			bool,571		),572573		/// The colletion property has been added or edited.574		CollectionPropertySet(575			/// Id of collection to which property has been set.576			CollectionId,577			/// The property that was set.578			PropertyKey,579		),580581		/// The property has been deleted.582		CollectionPropertyDeleted(583			/// Id of collection to which property has been deleted.584			CollectionId,585			/// The property that was deleted.586			PropertyKey,587		),588589		/// The token property has been added or edited.590		TokenPropertySet(591			/// Identifier of the collection whose token has the property set.592			CollectionId,593			/// The token for which the property was set.594			TokenId,595			/// The property that was set.596			PropertyKey,597		),598599		/// The token property has been deleted.600		TokenPropertyDeleted(601			/// Identifier of the collection whose token has the property deleted.602			CollectionId,603			/// The token for which the property was deleted.604			TokenId,605			/// The property that was deleted.606			PropertyKey,607		),608609		/// The token property permission of a collection has been set.610		PropertyPermissionSet(611			/// ID of collection to which property permission has been set.612			CollectionId,613			/// The property permission that was set.614			PropertyKey,615		),616617		/// Address was added to the allow list.618		AllowListAddressAdded(619			/// ID of the affected collection.620			CollectionId,621			/// Address of the added account.622			T::CrossAccountId,623		),624625		/// Address was removed from the allow list.626		AllowListAddressRemoved(627			/// ID of the affected collection.628			CollectionId,629			/// Address of the removed account.630			T::CrossAccountId,631		),632633		/// Collection admin was added.634		CollectionAdminAdded(635			/// ID of the affected collection.636			CollectionId,637			/// Admin address.638			T::CrossAccountId,639		),640641		/// Collection admin was removed.642		CollectionAdminRemoved(643			/// ID of the affected collection.644			CollectionId,645			/// Removed admin address.646			T::CrossAccountId,647		),648649		/// Collection limits were set.650		CollectionLimitSet(651			/// ID of the affected collection.652			CollectionId,653		),654655		/// Collection owned was changed.656		CollectionOwnerChanged(657			/// ID of the affected collection.658			CollectionId,659			/// New owner address.660			T::AccountId,661		),662663		/// Collection permissions were set.664		CollectionPermissionSet(665			/// ID of the affected collection.666			CollectionId,667		),668669		/// Collection sponsor was set.670		CollectionSponsorSet(671			/// ID of the affected collection.672			CollectionId,673			/// New sponsor address.674			T::AccountId,675		),676677		/// New sponsor was confirm.678		SponsorshipConfirmed(679			/// ID of the affected collection.680			CollectionId,681			/// New sponsor address.682			T::AccountId,683		),684685		/// Collection sponsor was removed.686		CollectionSponsorRemoved(687			/// ID of the affected collection.688			CollectionId,689		),690	}691692	#[pallet::error]693	pub enum Error<T> {694		/// This collection does not exist.695		CollectionNotFound,696		/// Sender parameter and item owner must be equal.697		MustBeTokenOwner,698		/// No permission to perform action699		NoPermission,700		/// Destroying only empty collections is allowed701		CantDestroyNotEmptyCollection,702		/// Collection is not in mint mode.703		PublicMintingNotAllowed,704		/// Address is not in allow list.705		AddressNotInAllowlist,706707		/// Collection name can not be longer than 63 char.708		CollectionNameLimitExceeded,709		/// Collection description can not be longer than 255 char.710		CollectionDescriptionLimitExceeded,711		/// Token prefix can not be longer than 15 char.712		CollectionTokenPrefixLimitExceeded,713		/// Total collections bound exceeded.714		TotalCollectionsLimitExceeded,715		/// Exceeded max admin count716		CollectionAdminCountExceeded,717		/// Collection limit bounds per collection exceeded718		CollectionLimitBoundsExceeded,719		/// Tried to enable permissions which are only permitted to be disabled720		OwnerPermissionsCantBeReverted,721		/// Collection settings not allowing items transferring722		TransferNotAllowed,723		/// Account token limit exceeded per collection724		AccountTokenLimitExceeded,725		/// Collection token limit exceeded726		CollectionTokenLimitExceeded,727		/// Metadata flag frozen728		MetadataFlagFrozen,729730		/// Item does not exist731		TokenNotFound,732		/// Item is balance not enough733		TokenValueTooLow,734		/// Requested value is more than the approved735		ApprovedValueTooLow,736		/// Tried to approve more than owned737		CantApproveMoreThanOwned,738		/// Only spending from eth mirror could be approved739		AddressIsNotEthMirror,740741		/// Can't transfer tokens to ethereum zero address742		AddressIsZero,743744		/// The operation is not supported745		UnsupportedOperation,746747		/// Insufficient funds to perform an action748		NotSufficientFounds,749750		/// User does not satisfy the nesting rule751		UserIsNotAllowedToNest,752		/// Only tokens from specific collections may nest tokens under this one753		SourceCollectionIsNotAllowedToNest,754755		/// Tried to store more data than allowed in collection field756		CollectionFieldSizeExceeded,757758		/// Tried to store more property data than allowed759		NoSpaceForProperty,760761		/// Tried to store more property keys than allowed762		PropertyLimitReached,763764		/// Property key is too long765		PropertyKeyIsTooLong,766767		/// Only ASCII letters, digits, and symbols `_`, `-`, and `.` are allowed768		InvalidCharacterInPropertyKey,769770		/// Empty property keys are forbidden771		EmptyPropertyKey,772773		/// Tried to access an external collection with an internal API774		CollectionIsExternal,775776		/// Tried to access an internal collection with an external API777		CollectionIsInternal,778779		/// This address is not set as sponsor, use setCollectionSponsor first.780		ConfirmSponsorshipFail,781782		/// The user is not an administrator.783		UserIsNotCollectionAdmin,784	}785786	/// Storage of the count of created collections. Essentially contains the last collection ID.787	#[pallet::storage]788	pub type CreatedCollectionCount<T> = StorageValue<Value = CollectionId, QueryKind = ValueQuery>;789790	/// Storage of the count of deleted collections.791	#[pallet::storage]792	pub type DestroyedCollectionCount<T> =793		StorageValue<Value = CollectionId, QueryKind = ValueQuery>;794795	/// Storage of collection info.796	#[pallet::storage]797	pub type CollectionById<T> = StorageMap<798		Hasher = Blake2_128Concat,799		Key = CollectionId,800		Value = Collection<<T as frame_system::Config>::AccountId>,801		QueryKind = OptionQuery,802	>;803804	/// Storage of collection properties.805	#[pallet::storage]806	#[pallet::getter(fn collection_properties)]807	pub type CollectionProperties<T> = StorageMap<808		Hasher = Blake2_128Concat,809		Key = CollectionId,810		Value = CollectionPropertiesT,811		QueryKind = ValueQuery,812	>;813814	/// Storage of token property permissions of a collection.815	#[pallet::storage]816	#[pallet::getter(fn property_permissions)]817	pub type CollectionPropertyPermissions<T> = StorageMap<818		Hasher = Blake2_128Concat,819		Key = CollectionId,820		Value = PropertiesPermissionMap,821		QueryKind = ValueQuery,822	>;823824	/// Storage of the amount of collection admins.825	#[pallet::storage]826	pub type AdminAmount<T> = StorageMap<827		Hasher = Blake2_128Concat,828		Key = CollectionId,829		Value = u32,830		QueryKind = ValueQuery,831	>;832833	/// List of collection admins.834	#[pallet::storage]835	pub type IsAdmin<T: Config> = StorageNMap<836		Key = (837			Key<Blake2_128Concat, CollectionId>,838			Key<Blake2_128Concat, T::CrossAccountId>,839		),840		Value = bool,841		QueryKind = ValueQuery,842	>;843844	/// Allowlisted collection users.845	#[pallet::storage]846	pub type Allowlist<T: Config> = StorageNMap<847		Key = (848			Key<Blake2_128Concat, CollectionId>,849			Key<Blake2_128Concat, T::CrossAccountId>,850		),851		Value = bool,852		QueryKind = ValueQuery,853	>;854855	/// Not used by code, exists only to provide some types to metadata.856	#[pallet::storage]857	pub type DummyStorageValue<T: Config> = StorageValue<858		Value = (859			CollectionStats,860			CollectionId,861			TokenId,862			TokenChild,863			PhantomType<(864				TokenData<T::CrossAccountId>,865				RpcCollection<T::AccountId>,866				// PoV Estimate Info867				PovInfo,868			)>,869		),870		QueryKind = OptionQuery,871	>;872}873874/// Value representation with delayed initialization time.875pub struct LazyValue<T, F> {876	value: Option<T>,877	f: Option<F>,878}879880impl<T, F: FnOnce() -> T> LazyValue<T, F> {881	/// Create a new LazyValue.882	pub fn new(f: F) -> Self {883		Self {884			value: None,885			f: Some(f),886		}887	}888889	/// Get the value. If it is called the first time, the value will be initialized.890	pub fn value(&mut self) -> &T {891		self.force_value();892		self.value.as_ref().unwrap()893	}894895	/// Get the value. If it is called the first time, the value will be initialized.896	pub fn value_mut(&mut self) -> &mut T {897		self.force_value();898		self.value.as_mut().unwrap()899	}900901	fn into_inner(mut self) -> T {902		self.force_value();903		self.value.unwrap()904	}905906	/// Is value initialized?907	pub fn has_value(&self) -> bool {908		self.value.is_some()909	}910911	fn force_value(&mut self) {912		if self.value.is_none() {913			self.value = Some(self.f.take().unwrap()())914		}915	}916}917918fn check_token_permissions<T, FCA, FTO, FTE>(919	collection_admin_permitted: bool,920	token_owner_permitted: bool,921	is_collection_admin: &mut LazyValue<bool, FCA>,922	is_token_owner: &mut LazyValue<Result<bool, DispatchError>, FTO>,923	is_token_exist: &mut LazyValue<bool, FTE>,924) -> DispatchResult925where926	T: Config,927	FCA: FnOnce() -> bool,928	FTO: FnOnce() -> Result<bool, DispatchError>,929	FTE: FnOnce() -> bool,930{931	if !(collection_admin_permitted && *is_collection_admin.value()932		|| token_owner_permitted && (*is_token_owner.value())?)933	{934		fail!(<Error<T>>::NoPermission);935	}936937	let token_exist_due_to_owner_check_success =938		is_token_owner.has_value() && (*is_token_owner.value())?;939940	// If the token owner check has occurred and succeeded,941	// we know the token exists (otherwise, the owner check must fail).942	if !token_exist_due_to_owner_check_success {943		// If the token owner check didn't occur,944		// we must check the token's existence ourselves.945		if !is_token_exist.value() {946			fail!(<Error<T>>::TokenNotFound);947		}948	}949950	Ok(())951}952953impl<T: Config> Pallet<T> {954	/// Enshure that receiver address is correct.955	///956	/// Ethereum receiver 0x0000000000000000000000000000000000000000 is reserved, and shouldn't own tokens.957	pub fn ensure_correct_receiver(receiver: &T::CrossAccountId) -> DispatchResult {958		ensure!(959			&T::CrossAccountId::from_eth(H160([0; 20])) != receiver,960			<Error<T>>::AddressIsZero961		);962		Ok(())963	}964965	/// Get a vector of collection admins.966	pub fn adminlist(collection: CollectionId) -> Vec<T::CrossAccountId> {967		<IsAdmin<T>>::iter_prefix((collection,))968			.map(|(a, _)| a)969			.collect()970	}971972	/// Get a vector of users allowed to mint tokens.973	pub fn allowlist(collection: CollectionId) -> Vec<T::CrossAccountId> {974		<Allowlist<T>>::iter_prefix((collection,))975			.map(|(a, _)| a)976			.collect()977	}978979	/// Is `user` allowed to mint token in `collection`.980	pub fn allowed(collection: CollectionId, user: T::CrossAccountId) -> bool {981		<Allowlist<T>>::get((collection, user))982	}983984	/// Get statistics of collections.985	pub fn collection_stats() -> CollectionStats {986		let created = <CreatedCollectionCount<T>>::get();987		let destroyed = <DestroyedCollectionCount<T>>::get();988		CollectionStats {989			created: created.0,990			destroyed: destroyed.0,991			alive: created.0 - destroyed.0,992		}993	}994995	/// Get the effective limits for the collection.996	pub fn effective_collection_limits(collection: CollectionId) -> Option<CollectionLimits> {997		let collection = <CollectionById<T>>::get(collection)?;998		let limits = collection.limits;999		let effective_limits = CollectionLimits {1000			account_token_ownership_limit: Some(limits.account_token_ownership_limit()),1001			sponsored_data_size: Some(limits.sponsored_data_size()),1002			sponsored_data_rate_limit: Some(1003				limits1004					.sponsored_data_rate_limit1005					.unwrap_or(SponsoringRateLimit::SponsoringDisabled),1006			),1007			token_limit: Some(limits.token_limit()),1008			sponsor_transfer_timeout: Some(limits.sponsor_transfer_timeout(1009				match collection.mode {1010					CollectionMode::NFT => NFT_SPONSOR_TRANSFER_TIMEOUT,1011					CollectionMode::Fungible(_) => FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,1012					CollectionMode::ReFungible => REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,1013				},1014			)),1015			sponsor_approve_timeout: Some(limits.sponsor_approve_timeout()),1016			owner_can_transfer: Some(limits.owner_can_transfer()),1017			owner_can_destroy: Some(limits.owner_can_destroy()),1018			transfers_enabled: Some(limits.transfers_enabled()),1019		};10201021		Some(effective_limits)1022	}10231024	/// Returns information about the `collection` adapted for rpc.1025	pub fn rpc_collection(collection: CollectionId) -> Option<RpcCollection<T::AccountId>> {1026		let Collection {1027			name,1028			description,1029			owner,1030			mode,1031			token_prefix,1032			sponsorship,1033			limits,1034			permissions,1035			flags,1036		} = <CollectionById<T>>::get(collection)?;10371038		let token_property_permissions = <CollectionPropertyPermissions<T>>::get(collection)1039			.into_iter()1040			.map(|(key, permission)| PropertyKeyPermission { key, permission })1041			.collect();10421043		let properties = <CollectionProperties<T>>::get(collection)1044			.into_iter()1045			.map(|(key, value)| Property { key, value })1046			.collect();10471048		let permissions = CollectionPermissions {1049			access: Some(permissions.access()),1050			mint_mode: Some(permissions.mint_mode()),1051			nesting: Some(permissions.nesting().clone()),1052		};10531054		Some(RpcCollection {1055			name: name.into_inner(),1056			description: description.into_inner(),1057			owner,1058			mode,1059			token_prefix: token_prefix.into_inner(),1060			sponsorship,1061			limits,1062			permissions,1063			token_property_permissions,1064			properties,1065			read_only: flags.external,10661067			flags: RpcCollectionFlags {1068				foreign: flags.foreign,1069				erc721metadata: flags.erc721metadata,1070			},1071		})1072	}1073}10741075macro_rules! limit_default {1076	($old:ident, $new:ident, $($field:ident $(($arg:expr))? => $check:expr),* $(,)?) => {{1077		$(1078			if let Some($new) = $new.$field {1079				let $old = $old.$field($($arg)?);1080				let _ = $new;1081				let _ = $old;1082				$check1083			} else {1084				$new.$field = $old.$field1085			}1086		)*1087	}};1088}1089macro_rules! limit_default_clone {1090	($old:ident, $new:ident, $($field:ident $(($arg:expr))? => $check:expr),* $(,)?) => {{1091		$(1092			if let Some($new) = $new.$field.clone() {1093				let $old = $old.$field($($arg)?);1094				let _ = $new;1095				let _ = $old;1096				$check1097			} else {1098				$new.$field = $old.$field.clone()1099			}1100		)*1101	}};1102}11031104impl<T: Config> Pallet<T> {1105	/// Create new collection.1106	///1107	/// * `owner` - The owner of the collection.1108	/// * `data` - Description of the created collection.1109	/// * `flags` - Extra flags to store.1110	pub fn init_collection(1111		owner: T::CrossAccountId,1112		payer: T::CrossAccountId,1113		data: CreateCollectionData<T::CrossAccountId>,1114	) -> Result<CollectionId, DispatchError> {1115		ensure!(data.flags.is_allowed_for_user(), <Error<T>>::NoPermission);1116		Self::init_collection_internal(owner, payer, data)1117	}11181119	/// Initializes the collection with ForeignCollection flag. Returns [CollectionId] on success, [DispatchError] otherwise.1120	pub fn init_foreign_collection(1121		owner: T::CrossAccountId,1122		payer: T::CrossAccountId,1123		mut data: CreateCollectionData<T::CrossAccountId>,1124	) -> Result<CollectionId, DispatchError> {1125		data.flags.foreign = true;1126		let id = Self::init_collection_internal(owner, payer, data)?;1127		Ok(id)1128	}11291130	fn init_collection_internal(1131		owner: T::CrossAccountId,1132		payer: T::CrossAccountId,1133		data: CreateCollectionData<T::CrossAccountId>,1134	) -> Result<CollectionId, DispatchError> {1135		{1136			ensure!(1137				data.token_prefix.len() <= MAX_TOKEN_PREFIX_LENGTH as usize,1138				Error::<T>::CollectionTokenPrefixLimitExceeded1139			);1140		}11411142		let created_count = <CreatedCollectionCount<T>>::get()1143			.01144			.checked_add(1)1145			.ok_or(ArithmeticError::Overflow)?;1146		let destroyed_count = <DestroyedCollectionCount<T>>::get().0;1147		let id = CollectionId(created_count);11481149		// bound Total number of collections1150		ensure!(1151			created_count - destroyed_count <= COLLECTION_NUMBER_LIMIT,1152			<Error<T>>::TotalCollectionsLimitExceeded1153		);11541155		// =========11561157		let collection = Collection {1158			owner: owner.as_sub().clone(),1159			name: data.name,1160			mode: data.mode.clone(),1161			description: data.description,1162			token_prefix: data.token_prefix,1163			sponsorship: data1164				.pending_sponsor1165				.map(|sponsor| SponsorshipState::Unconfirmed(sponsor.as_sub().clone()))1166				.unwrap_or_default(),1167			limits: data1168				.limits1169				.map(|limits| Self::clamp_limits(data.mode.clone(), &Default::default(), limits))1170				.unwrap_or_else(|| Ok(CollectionLimits::default()))?,1171			permissions: data1172				.permissions1173				.map(|permissions| {1174					Self::clamp_permissions(data.mode.clone(), &Default::default(), permissions)1175				})1176				.unwrap_or_else(|| Ok(CollectionPermissions::default()))?,1177			flags: data.flags,1178		};11791180		let mut collection_properties = CollectionPropertiesT::new();1181		collection_properties1182			.try_set_from_iter(data.properties.into_iter())1183			.map_err(<Error<T>>::from)?;11841185		CollectionProperties::<T>::insert(id, collection_properties);11861187		let mut token_props_permissions = PropertiesPermissionMap::new();1188		token_props_permissions1189			.try_set_from_iter(data.token_property_permissions.into_iter())1190			.map_err(<Error<T>>::from)?;11911192		CollectionPropertyPermissions::<T>::insert(id, token_props_permissions);11931194		let mut admin_amount = 0u32;1195		for admin in data.admin_list.iter() {1196			if !<IsAdmin<T>>::get((id, admin)) {1197				<IsAdmin<T>>::insert((id, admin), true);1198				admin_amount = admin_amount1199					.checked_add(1)1200					.ok_or(<Error<T>>::CollectionAdminCountExceeded)?;1201			}1202		}1203		ensure!(1204			admin_amount <= Self::collection_admins_limit(),1205			<Error<T>>::CollectionAdminCountExceeded,1206		);1207		<AdminAmount<T>>::insert(id, admin_amount);12081209		// Take a (non-refundable) deposit of collection creation1210		{1211			let mut imbalance = <Debt<T::AccountId, <T as Config>::Currency>>::zero();1212			imbalance.subsume(<T as Config>::Currency::deposit(1213				&T::TreasuryAccountId::get(),1214				T::CollectionCreationPrice::get(),1215				Precision::Exact,1216			)?);1217			let credit =1218				<T as Config>::Currency::settle(payer.as_sub(), imbalance, Preservation::Preserve)1219					.map_err(|_| Error::<T>::NotSufficientFounds)?;12201221			debug_assert!(credit.peek().is_zero())1222		}12231224		<CreatedCollectionCount<T>>::put(created_count);1225		<Pallet<T>>::deposit_event(Event::CollectionCreated(1226			id,1227			data.mode.id(),1228			owner.as_sub().clone(),1229		));1230		<PalletEvm<T>>::deposit_log(1231			erc::CollectionHelpersEvents::CollectionCreated {1232				owner: *owner.as_eth(),1233				collection_id: eth::collection_id_to_address(id),1234			}1235			.to_log(T::ContractAddress::get()),1236		);1237		<CollectionById<T>>::insert(id, collection);1238		Ok(id)1239	}12401241	/// Destroy collection.1242	///1243	/// * `collection` - Collection handler.1244	/// * `sender` - The owner or administrator of the collection.1245	pub fn destroy_collection(1246		collection: CollectionHandle<T>,1247		sender: &T::CrossAccountId,1248	) -> DispatchResult {1249		ensure!(1250			collection.limits.owner_can_destroy(),1251			<Error<T>>::NoPermission,1252		);1253		collection.check_is_owner(sender)?;12541255		let destroyed_collections = <DestroyedCollectionCount<T>>::get()1256			.01257			.checked_add(1)1258			.ok_or(ArithmeticError::Overflow)?;12591260		// =========12611262		<DestroyedCollectionCount<T>>::put(destroyed_collections);1263		<CollectionById<T>>::remove(collection.id);1264		<AdminAmount<T>>::remove(collection.id);1265		let _ = <IsAdmin<T>>::clear_prefix((collection.id,), u32::MAX, None);1266		let _ = <Allowlist<T>>::clear_prefix((collection.id,), u32::MAX, None);1267		<CollectionProperties<T>>::remove(collection.id);12681269		<Pallet<T>>::deposit_event(Event::CollectionDestroyed(collection.id));12701271		<PalletEvm<T>>::deposit_log(1272			erc::CollectionHelpersEvents::CollectionDestroyed {1273				collection_id: eth::collection_id_to_address(collection.id),1274			}1275			.to_log(T::ContractAddress::get()),1276		);1277		Ok(())1278	}12791280	/// This function sets or removes a collection properties according to1281	/// `properties_updates` contents:1282	/// * sets a property under the <key> with the value provided `(<key>, Some(<value>))`1283	/// * removes a property under the <key> if the value is `None` `(<key>, None)`.1284	///1285	/// This function fires an event for each property change.1286	/// In case of an error, all the changes (including the events) will be reverted1287	/// since the function is transactional.1288	#[transactional]1289	fn modify_collection_properties(1290		collection: &CollectionHandle<T>,1291		sender: &T::CrossAccountId,1292		properties_updates: impl Iterator<Item = (PropertyKey, Option<PropertyValue>)>,1293	) -> DispatchResult {1294		collection.check_is_owner_or_admin(sender)?;12951296		let mut stored_properties = <CollectionProperties<T>>::get(collection.id);12971298		for (key, value) in properties_updates {1299			match value {1300				Some(value) => {1301					stored_properties1302						.try_set(key.clone(), value)1303						.map_err(<Error<T>>::from)?;13041305					Self::deposit_event(Event::CollectionPropertySet(collection.id, key));1306					<PalletEvm<T>>::deposit_log(1307						erc::CollectionHelpersEvents::CollectionChanged {1308							collection_id: eth::collection_id_to_address(collection.id),1309						}1310						.to_log(T::ContractAddress::get()),1311					);1312				}1313				None => {1314					stored_properties.remove(&key).map_err(<Error<T>>::from)?;13151316					Self::deposit_event(Event::CollectionPropertyDeleted(collection.id, key));1317					<PalletEvm<T>>::deposit_log(1318						erc::CollectionHelpersEvents::CollectionChanged {1319							collection_id: eth::collection_id_to_address(collection.id),1320						}1321						.to_log(T::ContractAddress::get()),1322					);1323				}1324			}1325		}13261327		<CollectionProperties<T>>::set(collection.id, stored_properties);13281329		Ok(())1330	}13311332	/// Sets or unsets the approval of a given operator.1333	///1334	/// The `operator` is allowed to transfer all token pieces of the `owner` on their behalf.1335	/// - `owner`: Token owner1336	/// - `operator`: Operator1337	/// - `approve`: Should operator status be granted or revoked?1338	pub fn set_allowance_for_all(1339		collection: &CollectionHandle<T>,1340		owner: &T::CrossAccountId,1341		operator: &T::CrossAccountId,1342		approve: bool,1343		set_allowance: impl FnOnce(),1344		log: evm_coder::ethereum::Log,1345	) -> DispatchResult {1346		if collection.permissions.access() == AccessMode::AllowList {1347			collection.check_allowlist(owner)?;1348			collection.check_allowlist(operator)?;1349		}13501351		Self::ensure_correct_receiver(operator)?;13521353		set_allowance();13541355		<PalletEvm<T>>::deposit_log(log);1356		Self::deposit_event(Event::ApprovedForAll(1357			collection.id,1358			owner.clone(),1359			operator.clone(),1360			approve,1361		));1362		Ok(())1363	}13641365	/// Set collection property.1366	///1367	/// * `collection` - Collection handler.1368	/// * `sender` - The owner or administrator of the collection.1369	/// * `property` - The property to set.1370	pub fn set_collection_property(1371		collection: &CollectionHandle<T>,1372		sender: &T::CrossAccountId,1373		property: Property,1374	) -> DispatchResult {1375		Self::set_collection_properties(collection, sender, [property].into_iter())1376	}13771378	/// Set a scoped collection property, where the scope is a special prefix1379	/// prohibiting a user access to change the property directly.1380	///1381	/// * `collection_id` - ID of the collection for which the property is being set.1382	/// * `scope` - Property scope.1383	/// * `property` - The property to set.1384	pub fn set_scoped_collection_property(1385		collection_id: CollectionId,1386		scope: PropertyScope,1387		property: Property,1388	) -> DispatchResult {1389		CollectionProperties::<T>::try_mutate(collection_id, |properties| {1390			properties.try_scoped_set(scope, property.key, property.value)1391		})1392		.map_err(<Error<T>>::from)?;13931394		Ok(())1395	}13961397	/// Set scoped collection properties, where the scope is a special prefix1398	/// prohibiting a user access to change the properties directly.1399	///1400	/// * `collection_id` - ID of the collection for which the properties is being set.1401	/// * `scope` - Property scope.1402	/// * `properties` - The properties to set.1403	pub fn set_scoped_collection_properties(1404		collection_id: CollectionId,1405		scope: PropertyScope,1406		properties: impl Iterator<Item = Property>,1407	) -> DispatchResult {1408		CollectionProperties::<T>::try_mutate(collection_id, |stored_properties| {1409			stored_properties.try_scoped_set_from_iter(scope, properties)1410		})1411		.map_err(<Error<T>>::from)?;14121413		Ok(())1414	}14151416	/// Set collection properties.1417	///1418	/// * `collection` - Collection handler.1419	/// * `sender` - The owner or administrator of the collection.1420	/// * `properties` - The properties to set.1421	pub fn set_collection_properties(1422		collection: &CollectionHandle<T>,1423		sender: &T::CrossAccountId,1424		properties: impl Iterator<Item = Property>,1425	) -> DispatchResult {1426		Self::modify_collection_properties(1427			collection,1428			sender,1429			properties.map(|property| (property.key, Some(property.value))),1430		)1431	}14321433	/// Delete collection property.1434	///1435	/// * `collection` - Collection handler.1436	/// * `sender` - The owner or administrator of the collection.1437	/// * `property` - The property to delete.1438	pub fn delete_collection_property(1439		collection: &CollectionHandle<T>,1440		sender: &T::CrossAccountId,1441		property_key: PropertyKey,1442	) -> DispatchResult {1443		Self::delete_collection_properties(collection, sender, [property_key].into_iter())1444	}14451446	/// Delete collection properties.1447	///1448	/// * `collection` - Collection handler.1449	/// * `sender` - The owner or administrator of the collection.1450	/// * `properties` - The properties to delete.1451	pub fn delete_collection_properties(1452		collection: &CollectionHandle<T>,1453		sender: &T::CrossAccountId,1454		property_keys: impl Iterator<Item = PropertyKey>,1455	) -> DispatchResult {1456		Self::modify_collection_properties(collection, sender, property_keys.map(|key| (key, None)))1457	}14581459	/// Set collection propetry permission without any checks.1460	///1461	/// Used for migrations.1462	///1463	/// * `collection` - Collection handler.1464	/// * `property_permissions` - Property permissions.1465	pub fn set_property_permission_unchecked(1466		collection: CollectionId,1467		property_permission: PropertyKeyPermission,1468	) -> DispatchResult {1469		<CollectionPropertyPermissions<T>>::try_mutate(collection, |permissions| {1470			permissions.try_set(property_permission.key, property_permission.permission)1471		})1472		.map_err(<Error<T>>::from)?;1473		Ok(())1474	}14751476	/// Set collection property permission.1477	///1478	/// * `collection` - Collection handler.1479	/// * `sender` - The owner or administrator of the collection.1480	/// * `property_permission` - Property permission.1481	pub fn set_property_permission(1482		collection: &CollectionHandle<T>,1483		sender: &T::CrossAccountId,1484		property_permission: PropertyKeyPermission,1485	) -> DispatchResult {1486		Self::set_scoped_property_permission(1487			collection,1488			sender,1489			PropertyScope::None,1490			property_permission,1491		)1492	}14931494	/// Set collection property permission with scope.1495	///1496	/// * `collection` - Collection handler.1497	/// * `sender` - The owner or administrator of the collection.1498	/// * `scope` - Property scope.1499	/// * `property_permission` - Property permission.1500	pub fn set_scoped_property_permission(1501		collection: &CollectionHandle<T>,1502		sender: &T::CrossAccountId,1503		scope: PropertyScope,1504		property_permission: PropertyKeyPermission,1505	) -> DispatchResult {1506		collection.check_is_owner_or_admin(sender)?;15071508		let all_permissions = CollectionPropertyPermissions::<T>::get(collection.id);1509		let current_permission = all_permissions.get(&property_permission.key);1510		if matches![1511			current_permission,1512			Some(PropertyPermission { mutable: false, .. })1513		] {1514			return Err(<Error<T>>::NoPermission.into());1515		}15161517		CollectionPropertyPermissions::<T>::try_mutate(collection.id, |permissions| {1518			let property_permission = property_permission.clone();1519			permissions.try_scoped_set(1520				scope,1521				property_permission.key,1522				property_permission.permission,1523			)1524		})1525		.map_err(<Error<T>>::from)?;15261527		Self::deposit_event(Event::PropertyPermissionSet(1528			collection.id,1529			property_permission.key,1530		));1531		<PalletEvm<T>>::deposit_log(1532			erc::CollectionHelpersEvents::CollectionChanged {1533				collection_id: eth::collection_id_to_address(collection.id),1534			}1535			.to_log(T::ContractAddress::get()),1536		);15371538		Ok(())1539	}15401541	/// Set token property permission.1542	///1543	/// * `collection` - Collection handler.1544	/// * `sender` - The owner or administrator of the collection.1545	/// * `property_permissions` - Property permissions.1546	#[transactional]1547	pub fn set_token_property_permissions(1548		collection: &CollectionHandle<T>,1549		sender: &T::CrossAccountId,1550		property_permissions: Vec<PropertyKeyPermission>,1551	) -> DispatchResult {1552		Self::set_scoped_token_property_permissions(1553			collection,1554			sender,1555			PropertyScope::None,1556			property_permissions,1557		)1558	}15591560	/// Set token property permission with scope.1561	///1562	/// * `collection` - Collection handler.1563	/// * `sender` - The owner or administrator of the collection.1564	/// * `scope` - Property scope.1565	/// * `property_permissions` - Property permissions.1566	#[transactional]1567	pub fn set_scoped_token_property_permissions(1568		collection: &CollectionHandle<T>,1569		sender: &T::CrossAccountId,1570		scope: PropertyScope,1571		property_permissions: Vec<PropertyKeyPermission>,1572	) -> DispatchResult {1573		for prop_pemission in property_permissions {1574			Self::set_scoped_property_permission(collection, sender, scope, prop_pemission)?;1575		}15761577		Ok(())1578	}15791580	/// Get collection property.1581	pub fn get_collection_property(1582		collection_id: CollectionId,1583		key: &PropertyKey,1584	) -> Option<PropertyValue> {1585		Self::collection_properties(collection_id).get(key).cloned()1586	}15871588	/// Convert byte vector to property key vector.1589	pub fn bytes_keys_to_property_keys(1590		keys: Vec<Vec<u8>>,1591	) -> Result<Vec<PropertyKey>, DispatchError> {1592		keys.into_iter()1593			.map(|key| -> Result<PropertyKey, DispatchError> {1594				key.try_into()1595					.map_err(|_| <Error<T>>::PropertyKeyIsTooLong.into())1596			})1597			.collect::<Result<Vec<PropertyKey>, DispatchError>>()1598	}15991600	/// Get properties according to given keys.1601	pub fn filter_collection_properties(1602		collection_id: CollectionId,1603		keys: Option<Vec<PropertyKey>>,1604	) -> Result<Vec<Property>, DispatchError> {1605		let properties = Self::collection_properties(collection_id);16061607		let properties = keys1608			.map(|keys| {1609				keys.into_iter()1610					.filter_map(|key| {1611						properties.get(&key).map(|value| Property {1612							key,1613							value: value.clone(),1614						})1615					})1616					.collect()1617			})1618			.unwrap_or_else(|| {1619				properties1620					.into_iter()1621					.map(|(key, value)| Property { key, value })1622					.collect()1623			});16241625		Ok(properties)1626	}16271628	/// Get property permissions according to given keys.1629	pub fn filter_property_permissions(1630		collection_id: CollectionId,1631		keys: Option<Vec<PropertyKey>>,1632	) -> Result<Vec<PropertyKeyPermission>, DispatchError> {1633		let permissions = Self::property_permissions(collection_id);16341635		let key_permissions = keys1636			.map(|keys| {1637				keys.into_iter()1638					.filter_map(|key| {1639						permissions1640							.get(&key)1641							.map(|permission| PropertyKeyPermission {1642								key,1643								permission: permission.clone(),1644							})1645					})1646					.collect()1647			})1648			.unwrap_or_else(|| {1649				permissions1650					.into_iter()1651					.map(|(key, permission)| PropertyKeyPermission { key, permission })1652					.collect()1653			});16541655		Ok(key_permissions)1656	}16571658	/// Toggle `user` participation in the `collection`'s allow list.1659	/// #### Store read/writes1660	/// 1 writes1661	pub fn toggle_allowlist(1662		collection: &CollectionHandle<T>,1663		sender: &T::CrossAccountId,1664		user: &T::CrossAccountId,1665		allowed: bool,1666	) -> DispatchResult {1667		collection.check_is_owner_or_admin(sender)?;16681669		// =========16701671		if allowed {1672			<Allowlist<T>>::insert((collection.id, user), true);1673			Self::deposit_event(Event::<T>::AllowListAddressAdded(1674				collection.id,1675				user.clone(),1676			));1677		} else {1678			<Allowlist<T>>::remove((collection.id, user));1679			Self::deposit_event(Event::<T>::AllowListAddressRemoved(1680				collection.id,1681				user.clone(),1682			));1683		}16841685		<PalletEvm<T>>::deposit_log(1686			erc::CollectionHelpersEvents::CollectionChanged {1687				collection_id: eth::collection_id_to_address(collection.id),1688			}1689			.to_log(T::ContractAddress::get()),1690		);16911692		Ok(())1693	}16941695	/// Toggle `user` participation in the `collection`'s admin list.1696	/// #### Store read/writes1697	/// 2 reads, 2 writes1698	pub fn toggle_admin(1699		collection: &CollectionHandle<T>,1700		sender: &T::CrossAccountId,1701		user: &T::CrossAccountId,1702		admin: bool,1703	) -> DispatchResult {1704		collection.check_is_internal()?;1705		collection.check_is_owner(sender)?;17061707		let is_admin = <IsAdmin<T>>::get((collection.id, user));1708		if is_admin == admin {1709			if admin {1710				return Ok(());1711			} else {1712				return Err(Error::<T>::UserIsNotCollectionAdmin.into());1713			}1714		}1715		let amount = <AdminAmount<T>>::get(collection.id);17161717		// =========17181719		if admin {1720			let amount = amount1721				.checked_add(1)1722				.ok_or(<Error<T>>::CollectionAdminCountExceeded)?;1723			ensure!(1724				amount <= Self::collection_admins_limit(),1725				<Error<T>>::CollectionAdminCountExceeded,1726			);17271728			<AdminAmount<T>>::insert(collection.id, amount);1729			<IsAdmin<T>>::insert((collection.id, user), true);17301731			Self::deposit_event(Event::<T>::CollectionAdminAdded(1732				collection.id,1733				user.clone(),1734			));1735		} else {1736			<AdminAmount<T>>::insert(collection.id, amount.saturating_sub(1));1737			<IsAdmin<T>>::remove((collection.id, user));17381739			Self::deposit_event(Event::<T>::CollectionAdminRemoved(1740				collection.id,1741				user.clone(),1742			));1743		}17441745		<PalletEvm<T>>::deposit_log(1746			erc::CollectionHelpersEvents::CollectionChanged {1747				collection_id: eth::collection_id_to_address(collection.id),1748			}1749			.to_log(T::ContractAddress::get()),1750		);17511752		Ok(())1753	}17541755	/// Update collection limits.1756	pub fn update_limits(1757		user: &T::CrossAccountId,1758		collection: &mut CollectionHandle<T>,1759		new_limit: CollectionLimits,1760	) -> DispatchResult {1761		collection.check_is_internal()?;1762		collection.check_is_owner_or_admin(user)?;17631764		collection.limits =1765			Self::clamp_limits(collection.mode.clone(), &collection.limits, new_limit)?;17661767		Self::deposit_event(Event::<T>::CollectionLimitSet(collection.id));1768		<PalletEvm<T>>::deposit_log(1769			erc::CollectionHelpersEvents::CollectionChanged {1770				collection_id: eth::collection_id_to_address(collection.id),1771			}1772			.to_log(T::ContractAddress::get()),1773		);17741775		collection.save()1776	}17771778	/// Merge set fields from `new_limit` to `old_limit`.1779	fn clamp_limits(1780		mode: CollectionMode,1781		old_limit: &CollectionLimits,1782		mut new_limit: CollectionLimits,1783	) -> Result<CollectionLimits, DispatchError> {1784		let limits = old_limit;1785		limit_default!(old_limit, new_limit,1786			account_token_ownership_limit => ensure!(1787				new_limit <= MAX_TOKEN_OWNERSHIP,1788				<Error<T>>::CollectionLimitBoundsExceeded,1789			),1790			sponsored_data_size => ensure!(1791				new_limit <= CUSTOM_DATA_LIMIT,1792				<Error<T>>::CollectionLimitBoundsExceeded,1793			),17941795			sponsored_data_rate_limit => {},1796			token_limit => ensure!(1797				old_limit >= new_limit && new_limit > 0,1798				<Error<T>>::CollectionTokenLimitExceeded1799			),18001801			sponsor_transfer_timeout(match mode {1802				CollectionMode::NFT => NFT_SPONSOR_TRANSFER_TIMEOUT,1803				CollectionMode::Fungible(_) => FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,1804				CollectionMode::ReFungible => REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,1805			}) => ensure!(1806				new_limit <= MAX_SPONSOR_TIMEOUT,1807				<Error<T>>::CollectionLimitBoundsExceeded,1808			),1809			sponsor_approve_timeout => {},1810			owner_can_transfer => ensure!(1811				!limits.owner_can_transfer_instaled() ||1812				old_limit || !new_limit,1813				<Error<T>>::OwnerPermissionsCantBeReverted,1814			),1815			owner_can_destroy => ensure!(1816				old_limit || !new_limit,1817				<Error<T>>::OwnerPermissionsCantBeReverted,1818			),1819			transfers_enabled => {},1820		);1821		Ok(new_limit)1822	}18231824	/// Update collection permissions.1825	pub fn update_permissions(1826		user: &T::CrossAccountId,1827		collection: &mut CollectionHandle<T>,1828		new_permission: CollectionPermissions,1829	) -> DispatchResult {1830		collection.check_is_internal()?;1831		collection.check_is_owner_or_admin(user)?;1832		collection.permissions = Self::clamp_permissions(1833			collection.mode.clone(),1834			&collection.permissions,1835			new_permission,1836		)?;18371838		Self::deposit_event(Event::<T>::CollectionPermissionSet(collection.id));1839		<PalletEvm<T>>::deposit_log(1840			erc::CollectionHelpersEvents::CollectionChanged {1841				collection_id: eth::collection_id_to_address(collection.id),1842			}1843			.to_log(T::ContractAddress::get()),1844		);18451846		collection.save()1847	}18481849	/// Merge set fields from `new_permission` to `old_permission`.1850	fn clamp_permissions(1851		_mode: CollectionMode,1852		old_permission: &CollectionPermissions,1853		mut new_permission: CollectionPermissions,1854	) -> Result<CollectionPermissions, DispatchError> {1855		limit_default_clone!(old_permission, new_permission,1856			access => {},1857			mint_mode => {},1858			nesting => { /* todo check for permissive, if only it gets out of benchmarks */ },1859		);1860		Ok(new_permission)1861	}18621863	/// Repair possibly broken properties of a collection.1864	pub fn repair_collection(collection_id: CollectionId) -> DispatchResult {1865		CollectionProperties::<T>::mutate(collection_id, |properties| {1866			properties.recompute_consumed_space();1867		});18681869		Ok(())1870	}1871}18721873/// Indicates unsupported methods by returning [Error::UnsupportedOperation].1874#[macro_export]1875macro_rules! unsupported {1876	($runtime:path) => {1877		Err($crate::Error::<$runtime>::UnsupportedOperation.into())1878	};1879}18801881/// Return weights for various worst-case operations.1882pub trait CommonWeightInfo<CrossAccountId> {1883	/// Weight of item creation.1884	fn create_item(data: &CreateItemData) -> Weight {1885		Self::create_multiple_items(from_ref(data))1886	}18871888	/// Weight of items creation.1889	fn create_multiple_items(amount: &[CreateItemData]) -> Weight;18901891	/// Weight of items creation.1892	fn create_multiple_items_ex(cost: &CreateItemExData<CrossAccountId>) -> Weight;18931894	/// The weight of the burning item.1895	fn burn_item() -> Weight;18961897	/// Property setting weight.1898	///1899	/// * `amount`- The number of properties to set.1900	fn set_collection_properties(amount: u32) -> Weight;19011902	/// Collection property deletion weight.1903	///1904	/// * `amount`- The number of properties to set.1905	fn delete_collection_properties(amount: u32) -> Weight {1906		Self::set_collection_properties(amount)1907	}19081909	/// Token property setting weight.1910	///1911	/// * `amount`- The number of properties to set.1912	fn set_token_properties(amount: u32) -> Weight;19131914	/// Token property deletion weight.1915	///1916	/// * `amount`- The number of properties to delete.1917	fn delete_token_properties(amount: u32) -> Weight {1918		Self::set_token_properties(amount)1919	}19201921	/// Token property permissions set weight.1922	///1923	/// * `amount`- The number of property permissions to set.1924	fn set_token_property_permissions(amount: u32) -> Weight;19251926	/// Transfer price of the token or its parts.1927	fn transfer() -> Weight;19281929	/// The price of setting the permission of the operation from another user.1930	fn approve() -> Weight;19311932	/// The price of setting the permission of the operation from another user for eth mirror.1933	fn approve_from() -> Weight;19341935	/// Transfer price from another user.1936	fn transfer_from() -> Weight;19371938	/// The price of burning a token from another user.1939	fn burn_from() -> Weight;19401941	/// The price of setting approval for all1942	fn set_allowance_for_all() -> Weight;19431944	/// The price of repairing an item.1945	fn force_repair_item() -> Weight;1946}19471948/// Weight info extension trait for refungible pallet.1949pub trait RefungibleExtensionsWeightInfo {1950	/// Weight of token repartition.1951	fn repartition() -> Weight;1952}19531954/// Common collection operations.1955///1956/// It wraps methods in Fungible, Nonfungible and Refungible pallets1957/// and adds weight info.1958pub trait CommonCollectionOperations<T: Config> {1959	/// Create token.1960	///1961	/// * `sender` - The user who mint the token and pays for the transaction.1962	/// * `to` - The user who will own the token.1963	/// * `data` - Token data.1964	/// * `nesting_budget` - A budget that can be spent on nesting tokens.1965	fn create_item(1966		&self,1967		sender: T::CrossAccountId,1968		to: T::CrossAccountId,1969		data: CreateItemData,1970		nesting_budget: &dyn Budget,1971	) -> DispatchResultWithPostInfo;19721973	/// Create multiple tokens.1974	///1975	/// * `sender` - The user who mint the token and pays for the transaction.1976	/// * `to` - The user who will own the token.1977	/// * `data` - Token data.1978	/// * `nesting_budget` - A budget that can be spent on nesting tokens.1979	fn create_multiple_items(1980		&self,1981		sender: T::CrossAccountId,1982		to: T::CrossAccountId,1983		data: Vec<CreateItemData>,1984		nesting_budget: &dyn Budget,1985	) -> DispatchResultWithPostInfo;19861987	/// Create multiple tokens.1988	///1989	/// * `sender` - The user who mint the token and pays for the transaction.1990	/// * `to` - The user who will own the token.1991	/// * `data` - Token data.1992	/// * `nesting_budget` - A budget that can be spent on nesting tokens.1993	fn create_multiple_items_ex(1994		&self,1995		sender: T::CrossAccountId,1996		data: CreateItemExData<T::CrossAccountId>,1997		nesting_budget: &dyn Budget,1998	) -> DispatchResultWithPostInfo;19992000	/// Burn token.2001	///2002	/// * `sender` - The user who owns the token.2003	/// * `token` - Token id that will burned.2004	/// * `amount` - The number of parts of the token that will be burned.2005	fn burn_item(2006		&self,2007		sender: T::CrossAccountId,2008		token: TokenId,2009		amount: u128,2010	) -> DispatchResultWithPostInfo;20112012	/// Set collection properties.2013	///2014	/// * `sender` - Must be either the owner of the collection or its admin.2015	/// * `properties` - Properties to be set.2016	fn set_collection_properties(2017		&self,2018		sender: T::CrossAccountId,2019		properties: Vec<Property>,2020	) -> DispatchResultWithPostInfo;20212022	/// Delete collection properties.2023	///2024	/// * `sender` - Must be either the owner of the collection or its admin.2025	/// * `properties` - The properties to be removed.2026	fn delete_collection_properties(2027		&self,2028		sender: &T::CrossAccountId,2029		property_keys: Vec<PropertyKey>,2030	) -> DispatchResultWithPostInfo;20312032	/// Set token properties.2033	///2034	/// The appropriate [`PropertyPermission`] for the token property2035	/// must be set with [`Self::set_token_property_permissions`].2036	///2037	/// * `sender` - Must be either the owner of the token or its admin.2038	/// * `token_id` - The token for which the properties are being set.2039	/// * `properties` - Properties to be set.2040	/// * `budget` - Budget for setting properties.2041	fn set_token_properties(2042		&self,2043		sender: T::CrossAccountId,2044		token_id: TokenId,2045		properties: Vec<Property>,2046		budget: &dyn Budget,2047	) -> DispatchResultWithPostInfo;20482049	/// Remove token properties.2050	///2051	/// The appropriate [`PropertyPermission`] for the token property2052	/// must be set with [`Self::set_token_property_permissions`].2053	///2054	/// * `sender` - Must be either the owner of the token or its admin.2055	/// * `token_id` - The token for which the properties are being remove.2056	/// * `property_keys` - Keys to remove corresponding properties.2057	/// * `budget` - Budget for removing properties.2058	fn delete_token_properties(2059		&self,2060		sender: T::CrossAccountId,2061		token_id: TokenId,2062		property_keys: Vec<PropertyKey>,2063		budget: &dyn Budget,2064	) -> DispatchResultWithPostInfo;20652066	/// Get token properties raw map.2067	///2068	/// * `token_id` - The token which properties are needed.2069	fn get_token_properties_raw(&self, token_id: TokenId) -> Option<TokenProperties>;20702071	/// Set token properties raw map.2072	///2073	/// * `token_id` - The token for which the properties are being set.2074	/// * `map` - The raw map containing the token's properties.2075	fn set_token_properties_raw(&self, token_id: TokenId, map: TokenProperties);20762077	/// Set token property permissions.2078	///2079	/// * `sender` - Must be either the owner of the token or its admin.2080	/// * `token_id` - The token for which the properties are being set.2081	/// * `property_permissions` - Property permissions to be set.2082	/// * `budget` - Budget for setting properties.2083	fn set_token_property_permissions(2084		&self,2085		sender: &T::CrossAccountId,2086		property_permissions: Vec<PropertyKeyPermission>,2087	) -> DispatchResultWithPostInfo;20882089	/// Transfer amount of token pieces.2090	///2091	/// * `sender` - Donor user.2092	/// * `to` - Recepient user.2093	/// * `token` - The token of which parts are being sent.2094	/// * `amount` - The number of parts of the token that will be transferred.2095	/// * `budget` - The maximum budget that can be spent on the transfer.2096	fn transfer(2097		&self,2098		sender: T::CrossAccountId,2099		to: T::CrossAccountId,2100		token: TokenId,2101		amount: u128,2102		budget: &dyn Budget,2103	) -> DispatchResultWithPostInfo;21042105	/// Grant access to another account to transfer parts of the token owned by the calling user via [Self::transfer_from].2106	///2107	/// * `sender` - The user who grants access to the token.2108	/// * `spender` - The user to whom the rights are granted.2109	/// * `token` - The token to which access is granted.2110	/// * `amount` - The amount of pieces that another user can dispose of.2111	fn approve(2112		&self,2113		sender: T::CrossAccountId,2114		spender: T::CrossAccountId,2115		token: TokenId,2116		amount: u128,2117	) -> DispatchResultWithPostInfo;21182119	/// Grant access to another account to transfer parts of the token owned by the calling user's eth mirror via [Self::transfer_from].2120	///2121	/// * `sender` - The user who grants access to the token.2122	/// * `from` - Spender's eth mirror.2123	/// * `to` - The user to whom the rights are granted.2124	/// * `token` - The token to which access is granted.2125	/// * `amount` - The amount of pieces that another user can dispose of.2126	fn approve_from(2127		&self,2128		sender: T::CrossAccountId,2129		from: T::CrossAccountId,2130		to: T::CrossAccountId,2131		token: TokenId,2132		amount: u128,2133	) -> DispatchResultWithPostInfo;21342135	/// Send parts of a token owned by another user.2136	///2137	/// Before calling this method, you must grant rights to the calling user via [`Self::approve`].2138	///2139	/// * `sender` - The user who must have access to the token (see [`Self::approve`]).2140	/// * `from` - The user who owns the token.2141	/// * `to` - Recepient user.2142	/// * `token` - The token of which parts are being sent.2143	/// * `amount` - The number of parts of the token that will be transferred.2144	/// * `budget` - The maximum budget that can be spent on the transfer.2145	fn transfer_from(2146		&self,2147		sender: T::CrossAccountId,2148		from: T::CrossAccountId,2149		to: T::CrossAccountId,2150		token: TokenId,2151		amount: u128,2152		budget: &dyn Budget,2153	) -> DispatchResultWithPostInfo;21542155	/// Burn parts of a token owned by another user.2156	///2157	/// Before calling this method, you must grant rights to the calling user via [`Self::approve`].2158	///2159	/// * `sender` - The user who must have access to the token (see [`Self::approve`]).2160	/// * `from` - The user who owns the token.2161	/// * `token` - The token of which parts are being sent.2162	/// * `amount` - The number of parts of the token that will be transferred.2163	/// * `budget` - The maximum budget that can be spent on the burn.2164	fn burn_from(2165		&self,2166		sender: T::CrossAccountId,2167		from: T::CrossAccountId,2168		token: TokenId,2169		amount: u128,2170		budget: &dyn Budget,2171	) -> DispatchResultWithPostInfo;21722173	/// Check permission to nest token.2174	///2175	/// * `sender` - The user who initiated the check.2176	/// * `from` - The token that is checked for embedding.2177	/// * `under` - Token under which to check.2178	/// * `budget` - The maximum budget that can be spent on the check.2179	fn check_nesting(2180		&self,2181		sender: T::CrossAccountId,2182		from: (CollectionId, TokenId),2183		under: TokenId,2184		budget: &dyn Budget,2185	) -> DispatchResult;21862187	/// Nest one token into another.2188	///2189	/// * `under` - Token holder.2190	/// * `to_nest` - Nested token.2191	fn nest(&self, under: TokenId, to_nest: (CollectionId, TokenId));21922193	/// Unnest token.2194	///2195	/// * `under` - Token holder.2196	/// * `to_nest` - Token to unnest.2197	fn unnest(&self, under: TokenId, to_nest: (CollectionId, TokenId));21982199	/// Get all user tokens.2200	///2201	/// * `account` - Account for which you need to get tokens.2202	fn account_tokens(&self, account: T::CrossAccountId) -> Vec<TokenId>;22032204	/// Get all the tokens in the collection.2205	fn collection_tokens(&self) -> Vec<TokenId>;22062207	/// Check if the token exists.2208	///2209	/// * `token` - Id token to check.2210	fn token_exists(&self, token: TokenId) -> bool;22112212	/// Get the id of the last minted token.2213	fn last_token_id(&self) -> TokenId;22142215	/// Get the owner of the token.2216	///2217	/// * `token` - The token for which you need to find out the owner.2218	fn token_owner(&self, token: TokenId) -> Result<T::CrossAccountId, TokenOwnerError>;22192220	/// Checks if the `maybe_owner` is the indirect owner of the `token`.2221	///2222	/// * `token` - Id token to check.2223	/// * `maybe_owner` - The account to check.2224	/// * `nesting_budget` - A budget that can be spent on nesting tokens.2225	fn check_token_indirect_owner(2226		&self,2227		token: TokenId,2228		maybe_owner: &T::CrossAccountId,2229		nesting_budget: &dyn Budget,2230	) -> Result<bool, DispatchError>;22312232	/// Returns 10 tokens owners in no particular order.2233	///2234	/// * `token` - The token for which you need to find out the owners.2235	fn token_owners(&self, token: TokenId) -> Vec<T::CrossAccountId>;22362237	/// Get the value of the token property by key.2238	///2239	/// * `token` - Token with the property to get.2240	/// * `key` - Property name.2241	fn token_property(&self, token_id: TokenId, key: &PropertyKey) -> Option<PropertyValue>;22422243	/// Get a set of token properties by key vector.2244	///2245	/// * `token` - Token with the property to get.2246	/// * `keys` - Vector of property keys. If this parameter is [None](sp_std::result::Result),2247	/// then all properties are returned.2248	fn token_properties(&self, token: TokenId, keys: Option<Vec<PropertyKey>>) -> Vec<Property>;22492250	/// Amount of unique collection tokens2251	fn total_supply(&self) -> u32;22522253	/// Amount of different tokens account has.2254	///2255	/// * `account` - The account for which need to get the balance.2256	fn account_balance(&self, account: T::CrossAccountId) -> u32;22572258	/// Amount of specific token account have.2259	fn balance(&self, account: T::CrossAccountId, token: TokenId) -> u128;22602261	/// Amount of token pieces2262	fn total_pieces(&self, token: TokenId) -> Option<u128>;22632264	/// Get the number of parts of the token that a trusted user can manage.2265	///2266	/// * `sender` - Trusted user.2267	/// * `spender` - Owner of the token.2268	/// * `token` - The token for which to get the value.2269	fn allowance(2270		&self,2271		sender: T::CrossAccountId,2272		spender: T::CrossAccountId,2273		token: TokenId,2274	) -> u128;22752276	/// Get extension for RFT collection.2277	fn refungible_extensions(&self) -> Option<&dyn RefungibleExtensions<T>>;22782279	/// The `operator` is allowed to transfer all tokens of the `owner` on their behalf.2280	/// * `owner` - Token owner2281	/// * `operator` - Operator2282	/// * `approve` - Should operator status be granted or revoked?2283	fn set_allowance_for_all(2284		&self,2285		owner: T::CrossAccountId,2286		operator: T::CrossAccountId,2287		approve: bool,2288	) -> DispatchResultWithPostInfo;22892290	/// Tells whether the given `owner` approves the `operator`.2291	fn allowance_for_all(&self, owner: T::CrossAccountId, operator: T::CrossAccountId) -> bool;22922293	/// Repairs a possibly broken item.2294	fn repair_item(&self, token: TokenId) -> DispatchResultWithPostInfo;2295}22962297/// Extension for RFT collection.2298pub trait RefungibleExtensions<T>2299where2300	T: Config,2301{2302	/// Change the number of parts of the token.2303	///2304	/// When the value changes down, this function is equivalent to burning parts of the token.2305	///2306	/// * `sender` - The user calling the repartition operation. Must be the owner of the token.2307	/// * `token` - The token for which you want to change the number of parts.2308	/// * `amount` - The new value of the parts of the token.2309	fn repartition(2310		&self,2311		sender: &T::CrossAccountId,2312		token: TokenId,2313		amount: u128,2314	) -> DispatchResultWithPostInfo;2315}23162317/// Merge [`DispatchResult`] with [`Weight`] into [`DispatchResultWithPostInfo`].2318///2319/// Used for [`CommonCollectionOperations`] implementations and flexible enough to do so.2320pub fn with_weight(res: DispatchResult, weight: Weight) -> DispatchResultWithPostInfo {2321	let post_info = PostDispatchInfo {2322		actual_weight: Some(weight),2323		pays_fee: Pays::Yes,2324	};2325	match res {2326		Ok(()) => Ok(post_info),2327		Err(error) => Err(DispatchErrorWithPostInfo { post_info, error }),2328	}2329}23302331impl<T: Config> From<PropertiesError> for Error<T> {2332	fn from(error: PropertiesError) -> Self {2333		match error {2334			PropertiesError::NoSpaceForProperty => Self::NoSpaceForProperty,2335			PropertiesError::PropertyLimitReached => Self::PropertyLimitReached,2336			PropertiesError::InvalidCharacterInPropertyKey => Self::InvalidCharacterInPropertyKey,2337			PropertiesError::PropertyKeyIsTooLong => Self::PropertyKeyIsTooLong,2338			PropertiesError::EmptyPropertyKey => Self::EmptyPropertyKey,2339		}2340	}2341}23422343/// The type-safe interface for writing properties (setting or deleting) to tokens.2344/// It has two distinct implementations for newly created tokens and existing ones.2345///2346/// This type utilizes the lazy evaluation to avoid repeating the computation2347/// of several performance-heavy or PoV-heavy tasks,2348/// such as checking the indirect ownership or reading the token property permissions.2349pub struct PropertyWriter<'a, WriterVariant, T, Handle, FIsAdmin, FPropertyPermissions> {2350	collection: &'a Handle,2351	collection_lazy_info: PropertyWriterLazyCollectionInfo<FIsAdmin, FPropertyPermissions>,2352	_phantom: PhantomData<(T, WriterVariant)>,2353}23542355impl<'a, T, Handle, WriterVariant, FIsAdmin, FPropertyPermissions>2356	PropertyWriter<'a, WriterVariant, T, Handle, FIsAdmin, FPropertyPermissions>2357where2358	T: Config,2359	Handle: CommonCollectionOperations<T> + Deref<Target = CollectionHandle<T>>,2360	FIsAdmin: FnOnce() -> bool,2361	FPropertyPermissions: FnOnce() -> PropertiesPermissionMap,2362{2363	fn internal_write_token_properties<FCheckTokenExist, FCheckTokenOwner, FGetProperties>(2364		&mut self,2365		token_id: TokenId,2366		mut token_lazy_info: PropertyWriterLazyTokenInfo<2367			FCheckTokenExist,2368			FCheckTokenOwner,2369			FGetProperties,2370		>,2371		properties_updates: impl Iterator<Item = (PropertyKey, Option<PropertyValue>)>,2372		log: evm_coder::ethereum::Log,2373	) -> DispatchResult2374	where2375		FCheckTokenExist: FnOnce() -> bool,2376		FCheckTokenOwner: FnOnce() -> Result<bool, DispatchError>,2377		FGetProperties: FnOnce() -> TokenProperties,2378	{2379		for (key, value) in properties_updates {2380			let permission = self2381				.collection_lazy_info2382				.property_permissions2383				.value()2384				.get(&key)2385				.cloned()2386				.unwrap_or_else(PropertyPermission::none);23872388			match permission {2389				PropertyPermission { mutable: false, .. }2390					if token_lazy_info2391						.stored_properties2392						.value()2393						.get(&key)2394						.is_some() =>2395				{2396					return Err(<Error<T>>::NoPermission.into());2397				}23982399				PropertyPermission {2400					collection_admin,2401					token_owner,2402					..2403				} => check_token_permissions::<T, _, _, _>(2404					collection_admin,2405					token_owner,2406					&mut self.collection_lazy_info.is_collection_admin,2407					&mut token_lazy_info.is_token_owner,2408					&mut token_lazy_info.is_token_exist,2409				)?,2410			}24112412			match value {2413				Some(value) => {2414					token_lazy_info2415						.stored_properties2416						.value_mut()2417						.try_set(key.clone(), value)2418						.map_err(<Error<T>>::from)?;24192420					<Pallet<T>>::deposit_event(Event::TokenPropertySet(2421						self.collection.id,2422						token_id,2423						key,2424					));2425				}2426				None => {2427					token_lazy_info2428						.stored_properties2429						.value_mut()2430						.remove(&key)2431						.map_err(<Error<T>>::from)?;24322433					<Pallet<T>>::deposit_event(Event::TokenPropertyDeleted(2434						self.collection.id,2435						token_id,2436						key,2437					));2438				}2439			}2440		}24412442		let properties_changed = token_lazy_info.stored_properties.has_value();2443		if properties_changed {2444			<PalletEvm<T>>::deposit_log(log);24452446			self.collection2447				.set_token_properties_raw(token_id, token_lazy_info.stored_properties.into_inner());2448		}24492450		Ok(())2451	}2452}24532454/// A helper structure for the [`PropertyWriter`] that holds2455/// the collection-related info. The info is loaded using lazy evaluation.2456/// This info is common for any token for which we write properties.2457pub struct PropertyWriterLazyCollectionInfo<FIsAdmin, FPropertyPermissions> {2458	is_collection_admin: LazyValue<bool, FIsAdmin>,2459	property_permissions: LazyValue<PropertiesPermissionMap, FPropertyPermissions>,2460}24612462/// A helper structure for the [`PropertyWriter`] that holds2463/// the token-related info. The info is loaded using lazy evaluation.2464pub struct PropertyWriterLazyTokenInfo<FCheckTokenExist, FCheckTokenOwner, FGetProperties> {2465	is_token_exist: LazyValue<bool, FCheckTokenExist>,2466	is_token_owner: LazyValue<Result<bool, DispatchError>, FCheckTokenOwner>,2467	stored_properties: LazyValue<TokenProperties, FGetProperties>,2468}24692470impl<FCheckTokenExist, FCheckTokenOwner, FGetProperties>2471	PropertyWriterLazyTokenInfo<FCheckTokenExist, FCheckTokenOwner, FGetProperties>2472where2473	FCheckTokenExist: FnOnce() -> bool,2474	FCheckTokenOwner: FnOnce() -> Result<bool, DispatchError>,2475	FGetProperties: FnOnce() -> TokenProperties,2476{2477	/// Create a lazy token info.2478	pub fn new(2479		check_token_exist: FCheckTokenExist,2480		check_token_owner: FCheckTokenOwner,2481		get_token_properties: FGetProperties,2482	) -> Self {2483		Self {2484			is_token_exist: LazyValue::new(check_token_exist),2485			is_token_owner: LazyValue::new(check_token_owner),2486			stored_properties: LazyValue::new(get_token_properties),2487		}2488	}2489}24902491/// A marker structure that enables the writer implementation2492/// to provide the interface to write properties to **newly created** tokens.2493pub struct NewTokenPropertyWriter<T>(PhantomData<T>);2494impl<T: Config> NewTokenPropertyWriter<T> {2495	/// Creates a [`PropertyWriter`] for **newly created** tokens.2496	pub fn new<'a, Handle>(2497		collection: &'a Handle,2498		sender: &'a T::CrossAccountId,2499	) -> PropertyWriter<2500		'a,2501		Self,2502		T,2503		Handle,2504		impl FnOnce() -> bool + 'a,2505		impl FnOnce() -> PropertiesPermissionMap + 'a,2506	>2507	where2508		T: Config,2509		Handle: CommonCollectionOperations<T> + Deref<Target = CollectionHandle<T>>,2510	{2511		PropertyWriter {2512			collection,2513			collection_lazy_info: PropertyWriterLazyCollectionInfo {2514				is_collection_admin: LazyValue::new(|| collection.is_owner_or_admin(sender)),2515				property_permissions: LazyValue::new(|| {2516					<Pallet<T>>::property_permissions(collection.id)2517				}),2518			},2519			_phantom: PhantomData,2520		}2521	}2522}25232524impl<'a, T, Handle, FIsAdmin, FPropertyPermissions>2525	PropertyWriter<'a, NewTokenPropertyWriter<T>, T, Handle, FIsAdmin, FPropertyPermissions>2526where2527	T: Config,2528	Handle: CommonCollectionOperations<T> + Deref<Target = CollectionHandle<T>>,2529	FIsAdmin: FnOnce() -> bool,2530	FPropertyPermissions: FnOnce() -> PropertiesPermissionMap,2531{2532	/// A function to write properties to a **newly created** token.2533	pub fn write_token_properties(2534		&mut self,2535		mint_target_is_sender: bool,2536		token_id: TokenId,2537		properties_updates: impl Iterator<Item = Property>,2538		log: evm_coder::ethereum::Log,2539	) -> DispatchResult {2540		let check_token_exist = || {2541			debug_assert!(self.collection.token_exists(token_id));2542			true2543		};25442545		let check_token_owner = || Ok(mint_target_is_sender);25462547		let get_token_properties = || {2548			debug_assert!(self.collection.get_token_properties_raw(token_id).is_none());2549			TokenProperties::new()2550		};25512552		self.internal_write_token_properties(2553			token_id,2554			PropertyWriterLazyTokenInfo::new(2555				check_token_exist,2556				check_token_owner,2557				get_token_properties,2558			),2559			properties_updates.map(|p| (p.key, Some(p.value))),2560			log,2561		)2562	}2563}25642565/// A marker structure that enables the writer implementation2566/// to provide the interface to write properties to **already existing** tokens.2567pub struct ExistingTokenPropertyWriter<T>(PhantomData<T>);2568impl<T: Config> ExistingTokenPropertyWriter<T> {2569	/// Creates a [`PropertyWriter`] for **already existing** tokens.2570	pub fn new<'a, Handle>(2571		collection: &'a Handle,2572		sender: &'a T::CrossAccountId,2573	) -> PropertyWriter<2574		'a,2575		Self,2576		T,2577		Handle,2578		impl FnOnce() -> bool + 'a,2579		impl FnOnce() -> PropertiesPermissionMap + 'a,2580	>2581	where2582		Handle: CommonCollectionOperations<T> + Deref<Target = CollectionHandle<T>>,2583	{2584		PropertyWriter {2585			collection,2586			collection_lazy_info: PropertyWriterLazyCollectionInfo {2587				is_collection_admin: LazyValue::new(|| collection.is_owner_or_admin(sender)),2588				property_permissions: LazyValue::new(|| {2589					<Pallet<T>>::property_permissions(collection.id)2590				}),2591			},2592			_phantom: PhantomData,2593		}2594	}2595}25962597impl<'a, T, Handle, FIsAdmin, FPropertyPermissions>2598	PropertyWriter<'a, ExistingTokenPropertyWriter<T>, T, Handle, FIsAdmin, FPropertyPermissions>2599where2600	T: Config,2601	Handle: CommonCollectionOperations<T> + Deref<Target = CollectionHandle<T>>,2602	FIsAdmin: FnOnce() -> bool,2603	FPropertyPermissions: FnOnce() -> PropertiesPermissionMap,2604{2605	/// A function to write properties to an **already existing** token.2606	pub fn write_token_properties(2607		&mut self,2608		sender: &T::CrossAccountId,2609		token_id: TokenId,2610		properties_updates: impl Iterator<Item = (PropertyKey, Option<PropertyValue>)>,2611		nesting_budget: &dyn Budget,2612		log: evm_coder::ethereum::Log,2613	) -> DispatchResult {2614		let check_token_exist = || self.collection.token_exists(token_id);2615		let check_token_owner = || {2616			self.collection2617				.check_token_indirect_owner(token_id, sender, nesting_budget)2618		};2619		let get_token_properties = || {2620			self.collection2621				.get_token_properties_raw(token_id)2622				.unwrap_or_default()2623		};26242625		self.internal_write_token_properties(2626			token_id,2627			PropertyWriterLazyTokenInfo::new(2628				check_token_exist,2629				check_token_owner,2630				get_token_properties,2631			),2632			properties_updates,2633			log,2634		)2635	}2636}26372638/// A marker structure that enables the writer implementation2639/// to benchmark the token properties writing.2640#[cfg(feature = "runtime-benchmarks")]2641pub struct BenchmarkPropertyWriter<T>(PhantomData<T>);26422643#[cfg(feature = "runtime-benchmarks")]2644impl<T: Config> BenchmarkPropertyWriter<T> {2645	/// Creates a [`PropertyWriter`] for benchmarking tokens properties writing.2646	pub fn new<'a, Handle, FIsAdmin, FPropertyPermissions>(2647		collection: &Handle,2648		collection_lazy_info: PropertyWriterLazyCollectionInfo<FIsAdmin, FPropertyPermissions>,2649	) -> PropertyWriter<Self, T, Handle, FIsAdmin, FPropertyPermissions>2650	where2651		Handle: CommonCollectionOperations<T> + Deref<Target = CollectionHandle<T>>,2652		FIsAdmin: FnOnce() -> bool,2653		FPropertyPermissions: FnOnce() -> PropertiesPermissionMap,2654	{2655		PropertyWriter {2656			collection,2657			collection_lazy_info,2658			_phantom: PhantomData,2659		}2660	}26612662	/// Load the [`PropertyWriterLazyCollectionInfo`] from the storage.2663	pub fn load_collection_info<Handle>(2664		collection_handle: &Handle,2665		sender: &T::CrossAccountId,2666	) -> PropertyWriterLazyCollectionInfo<2667		impl FnOnce() -> bool,2668		impl FnOnce() -> PropertiesPermissionMap,2669	>2670	where2671		Handle: Deref<Target = CollectionHandle<T>>,2672	{2673		let is_collection_admin = collection_handle.is_owner_or_admin(sender);2674		let property_permissions = <Pallet<T>>::property_permissions(collection_handle.id);26752676		PropertyWriterLazyCollectionInfo {2677			is_collection_admin: LazyValue::new(move || is_collection_admin),2678			property_permissions: LazyValue::new(move || property_permissions),2679		}2680	}26812682	/// Load the [`PropertyWriterLazyTokenInfo`] with token properties from the storage.2683	pub fn load_token_properties<Handle>(2684		collection: &Handle,2685		token_id: TokenId,2686	) -> PropertyWriterLazyTokenInfo<2687		impl FnOnce() -> bool,2688		impl FnOnce() -> Result<bool, DispatchError>,2689		impl FnOnce() -> TokenProperties,2690	>2691	where2692		Handle: CommonCollectionOperations<T>,2693	{2694		let stored_properties = collection2695			.get_token_properties_raw(token_id)2696			.unwrap_or_default();26972698		PropertyWriterLazyTokenInfo {2699			is_token_exist: LazyValue::new(|| true),2700			is_token_owner: LazyValue::new(|| Ok(true)),2701			stored_properties: LazyValue::new(move || stored_properties),2702		}2703	}2704}27052706#[cfg(feature = "runtime-benchmarks")]2707impl<'a, T, Handle, FIsAdmin, FPropertyPermissions>2708	PropertyWriter<'a, BenchmarkPropertyWriter<T>, T, Handle, FIsAdmin, FPropertyPermissions>2709where2710	T: Config,2711	Handle: CommonCollectionOperations<T> + Deref<Target = CollectionHandle<T>>,2712	FIsAdmin: FnOnce() -> bool,2713	FPropertyPermissions: FnOnce() -> PropertiesPermissionMap,2714{2715	/// A function to benchmark the writing of token properties.2716	pub fn write_token_properties(2717		&mut self,2718		token_id: TokenId,2719		properties_updates: impl Iterator<Item = Property>,2720		log: evm_coder::ethereum::Log,2721	) -> DispatchResult {2722		let check_token_exist = || true;2723		let check_token_owner = || Ok(true);2724		let get_token_properties = || TokenProperties::new();27252726		self.internal_write_token_properties(2727			token_id,2728			PropertyWriterLazyTokenInfo::new(2729				check_token_exist,2730				check_token_owner,2731				get_token_properties,2732			),2733			properties_updates.map(|p| (p.key, Some(p.value))),2734			log,2735		)2736	}2737}27382739/// Computes the weight of writing properties to tokens.2740/// * `properties_nums` - The properties num of each created token.2741/// * `per_token_weight_weight` - The function to obtain the weight2742/// of writing properties from a token's properties num.2743pub fn write_token_properties_total_weight<T: Config, I: Fn(u32) -> Weight>(2744	properties_nums: impl Iterator<Item = u32>,2745	per_token_weight: I,2746) -> Weight {2747	let mut weight = properties_nums2748		.filter_map(|properties_num| {2749			if properties_num > 0 {2750				Some(per_token_weight(properties_num))2751			} else {2752				None2753			}2754		})2755		.fold(Weight::zero(), |a, b| a.saturating_add(b));27562757	if !weight.is_zero() {2758		// If we are here, it means the token properties were written at least once.2759		// Because of that, some common collection data was also loaded; we must add this weight.2760		// However, this common data was loaded only once, which is guaranteed by the `PropertyWriter`.27612762		weight = weight.saturating_add(<SelfWeightOf<T>>::property_writer_load_collection_info());2763	}27642765	weight2766}27672768#[cfg(any(feature = "tests", test))]2769#[allow(missing_docs)]2770pub mod tests {2771	use crate::{Config, DispatchError, DispatchResult, LazyValue};27722773	const fn to_bool(u: u8) -> bool {2774		u != 02775	}27762777	#[derive(Debug)]2778	pub struct TestCase {2779		pub collection_admin: bool,2780		pub is_collection_admin: bool,2781		pub token_owner: bool,2782		pub is_token_owner: bool,2783		pub no_permission: bool,2784	}27852786	impl TestCase {2787		const fn new(2788			collection_admin: u8,2789			is_collection_admin: u8,2790			token_owner: u8,2791			is_token_owner: u8,2792			no_permission: u8,2793		) -> Self {2794			Self {2795				collection_admin: to_bool(collection_admin),2796				is_collection_admin: to_bool(is_collection_admin),2797				token_owner: to_bool(token_owner),2798				is_token_owner: to_bool(is_token_owner),2799				no_permission: to_bool(no_permission),2800			}2801		}2802	}28032804	#[rustfmt::skip]2805	pub const TABLE: [TestCase; 16] = [2806		//                    ┌╴collection_admin2807		//                    │  ┌╴is_collection_admin2808		//                    │  │   ┌╴token_owner2809		//                    │  │   │  ┌╴is_token_ownership2810		//                    │  │   │  │   ┌╴no_permission2811		/*  0*/ TestCase::new(0, 0,  0, 0,  1),2812		/*  1*/ TestCase::new(0, 0,  0, 1,  1),2813		/*  2*/ TestCase::new(0, 0,  1, 0,  1),2814		/*  3*/ TestCase::new(0, 0,  1, 1,  0),2815		/*  4*/ TestCase::new(0, 1,  0, 0,  1),2816		/*  5*/ TestCase::new(0, 1,  0, 1,  1),2817		/*  6*/ TestCase::new(0, 1,  1, 0,  1),2818		/*  7*/ TestCase::new(0, 1,  1, 1,  0),2819		/*  8*/ TestCase::new(1, 0,  0, 0,  1),2820		/*  9*/ TestCase::new(1, 0,  0, 1,  1),2821		/* 10*/ TestCase::new(1, 0,  1, 0,  1),2822		/* 11*/ TestCase::new(1, 0,  1, 1,  0),2823		/* 12*/ TestCase::new(1, 1,  0, 0,  0),2824		/* 13*/ TestCase::new(1, 1,  0, 1,  0),2825		/* 14*/ TestCase::new(1, 1,  1, 0,  0),2826		/* 15*/ TestCase::new(1, 1,  1, 1,  0),2827	];28282829	pub fn check_token_permissions<T, FCA, FTO, FTE>(2830		collection_admin_permitted: bool,2831		token_owner_permitted: bool,2832		is_collection_admin: &mut LazyValue<bool, FCA>,2833		check_token_ownership: &mut LazyValue<Result<bool, DispatchError>, FTO>,2834		check_token_existence: &mut LazyValue<bool, FTE>,2835	) -> DispatchResult2836	where2837		T: Config,2838		FCA: FnOnce() -> bool,2839		FTO: FnOnce() -> Result<bool, DispatchError>,2840		FTE: FnOnce() -> bool,2841	{2842		crate::check_token_permissions::<T, FCA, FTO, FTE>(2843			collection_admin_permitted,2844			token_owner_permitted,2845			is_collection_admin,2846			check_token_ownership,2847			check_token_existence,2848		)2849	}2850}
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 alloc::boxed::Box;57use core::{58	marker::PhantomData,59	ops::{Deref, DerefMut},60	slice::from_ref,61	unreachable,62};6364use evm_coder::ToLog;65use frame_support::{66	dispatch::{DispatchErrorWithPostInfo, DispatchResultWithPostInfo, Pays, PostDispatchInfo},67	ensure, fail,68	traits::{69		fungible::{Balanced, Debt, Inspect},70		tokens::{Imbalance, Precision, Preservation},71		Get,72	},73	transactional,74};75pub use pallet::*;76use pallet_evm::{account::CrossAccountId, Pallet as PalletEvm};77use pallet_evm_coder_substrate::{SubstrateRecorder, WithRecorder};78use sp_core::H160;79use sp_runtime::{traits::Zero, ArithmeticError, DispatchError, DispatchResult};80use sp_std::vec::Vec;81use sp_weights::Weight;82use up_data_structs::{83	budget::Budget, AccessMode, Collection, CollectionId, CollectionLimits, CollectionMode,84	CollectionPermissions, CollectionProperties as CollectionPropertiesT, CollectionStats,85	CreateCollectionData, CreateItemData, CreateItemExData, PhantomType, PropertiesError,86	PropertiesPermissionMap, Property, PropertyKey, PropertyKeyPermission, PropertyPermission,87	PropertyScope, PropertyValue, RpcCollection, RpcCollectionFlags, SponsoringRateLimit,88	SponsorshipState, TokenChild, TokenData, TokenId, TokenOwnerError, TokenProperties,89	TrySetProperty, COLLECTION_ADMINS_LIMIT, COLLECTION_NUMBER_LIMIT, CUSTOM_DATA_LIMIT,90	FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT, MAX_SPONSOR_TIMEOUT, MAX_TOKEN_OWNERSHIP,91	MAX_TOKEN_PREFIX_LENGTH, NFT_SPONSOR_TRANSFER_TIMEOUT, REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,92};93use up_pov_estimate_rpc::PovInfo;9495#[cfg(feature = "runtime-benchmarks")]96pub mod benchmarking;97pub mod dispatch;98pub mod erc;99pub mod eth;100pub mod helpers;101#[allow(missing_docs)]102pub mod weights;103104use weights::WeightInfo;105106/// Weight info.107pub type SelfWeightOf<T> = <T as Config>::WeightInfo;108109/// Collection handle contains information about collection data and id.110/// Also provides functionality to count consumed gas.111///112/// CollectionHandle is used as a generic wrapper for collections of all types (except native fungible).113/// It allows to perform common operations and queries on any collection type,114/// both completely general for all, as well as their respective implementations of [`CommonCollectionOperations`].115#[must_use = "Should call submit_logs or save, otherwise some data will be lost for evm side"]116pub struct CollectionHandle<T: Config> {117	/// Collection id118	pub id: CollectionId,119	collection: Collection<T::AccountId>,120	/// Substrate recorder for counting consumed gas121	pub recorder: SubstrateRecorder<T>,122}123124impl<T: Config> WithRecorder<T> for CollectionHandle<T> {125	fn recorder(&self) -> &SubstrateRecorder<T> {126		&self.recorder127	}128	fn into_recorder(self) -> SubstrateRecorder<T> {129		self.recorder130	}131}132133impl<T: Config> CollectionHandle<T> {134	/// Same as [CollectionHandle::new] but with an explicit gas limit.135	pub fn new_with_gas_limit(id: CollectionId, gas_limit: u64) -> Option<Self> {136		Self::new_with_recorder(id, SubstrateRecorder::new(gas_limit))137	}138139	/// Same as [CollectionHandle::new] but with an existed [`SubstrateRecorder`].140	pub fn new_with_recorder(id: CollectionId, recorder: SubstrateRecorder<T>) -> Option<Self> {141		<CollectionById<T>>::get(id).map(|collection| Self {142			id,143			collection,144			recorder,145		})146	}147148	/// Retrives collection data from storage and creates collection handle with default parameters.149	/// If collection not found return `None`150	pub fn new(id: CollectionId) -> Option<Self> {151		Self::new_with_gas_limit(id, u64::MAX)152	}153154	/// Same as [`CollectionHandle::new`] but if collection not found [CollectionNotFound](Error::CollectionNotFound) returned.155	pub fn try_get(id: CollectionId) -> Result<Self, DispatchError> {156		Ok(Self::new(id).ok_or(<Error<T>>::CollectionNotFound)?)157	}158159	/// Consume gas for reading.160	pub fn consume_store_reads(161		&self,162		reads: u64,163	) -> pallet_evm_coder_substrate::execution::Result<()> {164		self.recorder().consume_store_reads(reads)165	}166167	/// Consume gas for writing.168	pub fn consume_store_writes(169		&self,170		writes: u64,171	) -> pallet_evm_coder_substrate::execution::Result<()> {172		self.recorder().consume_store_writes(writes)173	}174175	/// Consume gas for reading and writing.176	pub fn consume_store_reads_and_writes(177		&self,178		reads: u64,179		writes: u64,180	) -> pallet_evm_coder_substrate::execution::Result<()> {181		self.recorder()182			.consume_store_reads_and_writes(reads, writes)183	}184185	/// Save collection to storage.186	pub fn save(&self) -> DispatchResult {187		<CollectionById<T>>::insert(self.id, &self.collection);188		Ok(())189	}190191	/// Set collection sponsor.192	///193	/// Unique collections allows sponsoring for certain actions.194	/// This method allows you to set the sponsor of the collection.195	/// In order for sponsorship to become active, it must be confirmed through [`Self::confirm_sponsorship`].196	pub fn set_sponsor(197		&mut self,198		sender: &T::CrossAccountId,199		sponsor: T::AccountId,200	) -> DispatchResult {201		self.check_is_internal()?;202		self.check_is_owner_or_admin(sender)?;203204		self.collection.sponsorship = SponsorshipState::Unconfirmed(sponsor.clone());205206		<Pallet<T>>::deposit_event(Event::<T>::CollectionSponsorSet(self.id, sponsor));207		<PalletEvm<T>>::deposit_log(208			erc::CollectionHelpersEvents::CollectionChanged {209				collection_id: eth::collection_id_to_address(self.id),210			}211			.to_log(T::ContractAddress::get()),212		);213214		self.save()215	}216217	/// Force set `sponsor`.218	///219	/// Differs from [`set_sponsor`][`Self::set_sponsor`] in that confirmation220	/// from the `sponsor` is not required.221	///222	/// # Arguments223	///224	/// * `sponsor`: ID of the account of the sponsor-to-be.225	pub fn force_set_sponsor(&mut self, sponsor: T::AccountId) -> DispatchResult {226		self.check_is_internal()?;227228		self.collection.sponsorship = SponsorshipState::Confirmed(sponsor.clone());229230		<Pallet<T>>::deposit_event(Event::<T>::CollectionSponsorSet(self.id, sponsor.clone()));231		<Pallet<T>>::deposit_event(Event::<T>::SponsorshipConfirmed(self.id, sponsor));232		<PalletEvm<T>>::deposit_log(233			erc::CollectionHelpersEvents::CollectionChanged {234				collection_id: eth::collection_id_to_address(self.id),235			}236			.to_log(T::ContractAddress::get()),237		);238239		self.save()240	}241242	/// Confirm sponsorship243	///244	/// In order for the sponsorship to become active, the user set as the sponsor must confirm their participation.245	/// Before confirming sponsorship, the user must be specified as the sponsor of the collection via [`Self::set_sponsor`].246	pub fn confirm_sponsorship(&mut self, sender: &T::AccountId) -> DispatchResult {247		self.check_is_internal()?;248		ensure!(249			self.collection.sponsorship.pending_sponsor() == Some(sender),250			Error::<T>::ConfirmSponsorshipFail251		);252253		self.collection.sponsorship = SponsorshipState::Confirmed(sender.clone());254255		<Pallet<T>>::deposit_event(Event::<T>::SponsorshipConfirmed(self.id, sender.clone()));256		<PalletEvm<T>>::deposit_log(257			erc::CollectionHelpersEvents::CollectionChanged {258				collection_id: eth::collection_id_to_address(self.id),259			}260			.to_log(T::ContractAddress::get()),261		);262263		self.save()264	}265266	/// Remove collection sponsor.267	pub fn remove_sponsor(&mut self, sender: &T::CrossAccountId) -> DispatchResult {268		self.check_is_internal()?;269		self.check_is_owner_or_admin(sender)?;270271		self.collection.sponsorship = SponsorshipState::Disabled;272273		<Pallet<T>>::deposit_event(Event::<T>::CollectionSponsorRemoved(self.id));274		<PalletEvm<T>>::deposit_log(275			erc::CollectionHelpersEvents::CollectionChanged {276				collection_id: eth::collection_id_to_address(self.id),277			}278			.to_log(T::ContractAddress::get()),279		);280		self.save()281	}282283	/// Force remove `sponsor`.284	///285	/// Differs from `remove_sponsor` in that286	/// it doesn't require consent from the `owner` of the collection.287	pub fn force_remove_sponsor(&mut self) -> DispatchResult {288		self.check_is_internal()?;289290		self.collection.sponsorship = SponsorshipState::Disabled;291292		<Pallet<T>>::deposit_event(Event::<T>::CollectionSponsorRemoved(self.id));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		);299		self.save()300	}301302	/// Checks that the collection was created with, and must be operated upon through **Unique API**.303	/// Now check only the `external` flag and if it's **true**, then return [`Error::CollectionIsExternal`] error.304	pub fn check_is_internal(&self) -> DispatchResult {305		if self.flags.external {306			return Err(<Error<T>>::CollectionIsExternal)?;307		}308309		Ok(())310	}311312	/// Checks that the collection was created with, and must be operated upon through an **assimilated API**.313	/// Now check only the `external` flag and if it's **false**, then return [`Error::CollectionIsInternal`] error.314	pub fn check_is_external(&self) -> DispatchResult {315		if !self.flags.external {316			return Err(<Error<T>>::CollectionIsInternal)?;317		}318319		Ok(())320	}321}322323impl<T: Config> Deref for CollectionHandle<T> {324	type Target = Collection<T::AccountId>;325326	fn deref(&self) -> &Self::Target {327		&self.collection328	}329}330331impl<T: Config> DerefMut for CollectionHandle<T> {332	fn deref_mut(&mut self) -> &mut Self::Target {333		&mut self.collection334	}335}336337impl<T: Config> CollectionHandle<T> {338	/// Checks if the `user` is the owner of the collection.339	pub fn check_is_owner(&self, user: &T::CrossAccountId) -> DispatchResult {340		ensure!(*user.as_sub() == self.owner, <Error<T>>::NoPermission);341		Ok(())342	}343344	/// Returns **true** if the `user` is the owner or administrator of the collection.345	pub fn is_owner_or_admin(&self, user: &T::CrossAccountId) -> bool {346		*user.as_sub() == self.owner || <IsAdmin<T>>::get((self.id, user))347	}348349	/// Checks if the `user` is the owner or administrator of the collection.350	pub fn check_is_owner_or_admin(&self, user: &T::CrossAccountId) -> DispatchResult {351		ensure!(self.is_owner_or_admin(user), <Error<T>>::NoPermission);352		Ok(())353	}354355	/// Returns **true** if356	/// * the `user`is a collection owner or admin357	/// * the collection limits allow the owner/admins to transfer/burn any collection token358	pub fn ignores_token_restrictions(&self, user: &T::CrossAccountId) -> bool {359		self.limits.owner_can_transfer() && self.is_owner_or_admin(user)360	}361362	/// Return **true** if `user` does not have enough token parts, and he can ignore such restrictions.363	pub fn ignores_owned_amount(&self, user: &T::CrossAccountId) -> bool {364		self.limits.owner_can_transfer() && self.is_owner_or_admin(user)365	}366367	/// Checks if the user is in the allow list. If not [Error::AddressNotInAllowlist] returns.368	pub fn check_allowlist(&self, user: &T::CrossAccountId) -> DispatchResult {369		ensure!(370			<Allowlist<T>>::get((self.id, user)),371			<Error<T>>::AddressNotInAllowlist372		);373		Ok(())374	}375376	/// Changes collection owner to another account377	/// #### Store read/writes378	/// 1 writes379	pub fn change_owner(380		&mut self,381		caller: T::CrossAccountId,382		new_owner: T::CrossAccountId,383	) -> DispatchResult {384		self.check_is_internal()?;385		self.check_is_owner(&caller)?;386		self.collection.owner = new_owner.as_sub().clone();387388		<Pallet<T>>::deposit_event(Event::<T>::CollectionOwnerChanged(389			self.id,390			new_owner.as_sub().clone(),391		));392		<PalletEvm<T>>::deposit_log(393			erc::CollectionHelpersEvents::CollectionChanged {394				collection_id: eth::collection_id_to_address(self.id),395			}396			.to_log(T::ContractAddress::get()),397		);398399		self.save()400	}401}402403#[frame_support::pallet]404pub mod pallet {405406	use dispatch::CollectionDispatch;407	use frame_support::{408		pallet_prelude::*, storage::Key, traits::StorageVersion, Blake2_128Concat,409	};410	use scale_info::TypeInfo;411	use up_data_structs::{mapping::TokenAddressMapping, TokenId};412	use weights::WeightInfo;413414	use super::*;415416	#[pallet::config]417	pub trait Config:418		frame_system::Config + pallet_evm_coder_substrate::Config + pallet_evm::Config + TypeInfo419	{420		/// Weight information for functions of this pallet.421		type WeightInfo: WeightInfo;422423		/// Events compatible with [`frame_system::Config::Event`].424		type RuntimeEvent: IsType<<Self as frame_system::Config>::RuntimeEvent> + From<Event<Self>>;425426		/// Handler of accounts and payment.427		type Currency: Balanced<Self::AccountId> + Inspect<Self::AccountId>;428429		/// Set price to create a collection.430		#[pallet::constant]431		type CollectionCreationPrice: Get<432			<<Self as Config>::Currency as Inspect<Self::AccountId>>::Balance,433		>;434435		/// Dispatcher of operations on collections.436		type CollectionDispatch: CollectionDispatch<Self>;437438		/// Account which holds the chain's treasury.439		type TreasuryAccountId: Get<Self::AccountId>;440441		/// Address under which the CollectionHelper contract would be available.442		#[pallet::constant]443		type ContractAddress: Get<H160>;444445		/// Mapper for token addresses to Ethereum addresses.446		type EvmTokenAddressMapping: TokenAddressMapping<H160>;447448		/// Mapper for token addresses to [`CrossAccountId`].449		type CrossTokenAddressMapping: TokenAddressMapping<Self::CrossAccountId>;450	}451452	const STORAGE_VERSION: StorageVersion = StorageVersion::new(1);453	/// Collection id for native fungible collction.454	pub const NATIVE_FUNGIBLE_COLLECTION_ID: CollectionId = CollectionId(0);455456	#[pallet::pallet]457	#[pallet::storage_version(STORAGE_VERSION)]458	pub struct Pallet<T>(_);459460	#[pallet::extra_constants]461	impl<T: Config> Pallet<T> {462		/// Maximum admins per collection.463		pub fn collection_admins_limit() -> u32 {464			COLLECTION_ADMINS_LIMIT465		}466	}467468	#[pallet::genesis_config]469	pub struct GenesisConfig<T>(PhantomData<T>);470471	impl<T: Config> Default for GenesisConfig<T> {472		fn default() -> Self {473			Self(Default::default())474		}475	}476477	#[pallet::genesis_build]478	impl<T: Config> BuildGenesisConfig for GenesisConfig<T> {479		fn build(&self) {480			StorageVersion::new(1).put::<Pallet<T>>();481		}482	}483484	impl<T: Config> Pallet<T> {485		/// Helper function that handles deposit events486		pub fn deposit_event(event: Event<T>) {487			let event = <T as Config>::RuntimeEvent::from(event);488			let event = event.into();489			<frame_system::Pallet<T>>::deposit_event(event)490		}491	}492493	#[pallet::event]494	pub enum Event<T: Config> {495		/// New collection was created496		CollectionCreated(497			/// Globally unique identifier of newly created collection.498			CollectionId,499			/// [`CollectionMode`] converted into _u8_.500			u8,501			/// Collection owner.502			T::AccountId,503		),504505		/// New collection was destroyed506		CollectionDestroyed(507			/// Globally unique identifier of collection.508			CollectionId,509		),510511		/// New item was created.512		ItemCreated(513			/// Id of the collection where item was created.514			CollectionId,515			/// Id of an item. Unique within the collection.516			TokenId,517			/// Owner of newly created item518			T::CrossAccountId,519			/// Always 1 for NFT520			u128,521		),522523		/// Collection item was burned.524		ItemDestroyed(525			/// Id of the collection where item was destroyed.526			CollectionId,527			/// Identifier of burned NFT.528			TokenId,529			/// Which user has destroyed its tokens.530			T::CrossAccountId,531			/// Amount of token pieces destroed. Always 1 for NFT.532			u128,533		),534535		/// Item was transferred536		Transfer(537			/// Id of collection to which item is belong.538			CollectionId,539			/// Id of an item.540			TokenId,541			/// Original owner of item.542			T::CrossAccountId,543			/// New owner of item.544			T::CrossAccountId,545			/// Amount of token pieces transfered. Always 1 for NFT.546			u128,547		),548549		/// Amount pieces of token owned by `sender` was approved for `spender`.550		Approved(551			/// Id of collection to which item is belong.552			CollectionId,553			/// Id of an item.554			TokenId,555			/// Original owner of item.556			T::CrossAccountId,557			/// Id for which the approval was granted.558			T::CrossAccountId,559			/// Amount of token pieces transfered. Always 1 for NFT.560			u128,561		),562563		/// A `sender` approves operations on all owned tokens for `spender`.564		ApprovedForAll(565			/// Id of collection to which item is belong.566			CollectionId,567			/// Owner of a wallet.568			T::CrossAccountId,569			/// Id for which operator status was granted or rewoked.570			T::CrossAccountId,571			/// Is operator status granted or revoked?572			bool,573		),574575		/// The colletion property has been added or edited.576		CollectionPropertySet(577			/// Id of collection to which property has been set.578			CollectionId,579			/// The property that was set.580			PropertyKey,581		),582583		/// The property has been deleted.584		CollectionPropertyDeleted(585			/// Id of collection to which property has been deleted.586			CollectionId,587			/// The property that was deleted.588			PropertyKey,589		),590591		/// The token property has been added or edited.592		TokenPropertySet(593			/// Identifier of the collection whose token has the property set.594			CollectionId,595			/// The token for which the property was set.596			TokenId,597			/// The property that was set.598			PropertyKey,599		),600601		/// The token property has been deleted.602		TokenPropertyDeleted(603			/// Identifier of the collection whose token has the property deleted.604			CollectionId,605			/// The token for which the property was deleted.606			TokenId,607			/// The property that was deleted.608			PropertyKey,609		),610611		/// The token property permission of a collection has been set.612		PropertyPermissionSet(613			/// ID of collection to which property permission has been set.614			CollectionId,615			/// The property permission that was set.616			PropertyKey,617		),618619		/// Address was added to the allow list.620		AllowListAddressAdded(621			/// ID of the affected collection.622			CollectionId,623			/// Address of the added account.624			T::CrossAccountId,625		),626627		/// Address was removed from the allow list.628		AllowListAddressRemoved(629			/// ID of the affected collection.630			CollectionId,631			/// Address of the removed account.632			T::CrossAccountId,633		),634635		/// Collection admin was added.636		CollectionAdminAdded(637			/// ID of the affected collection.638			CollectionId,639			/// Admin address.640			T::CrossAccountId,641		),642643		/// Collection admin was removed.644		CollectionAdminRemoved(645			/// ID of the affected collection.646			CollectionId,647			/// Removed admin address.648			T::CrossAccountId,649		),650651		/// Collection limits were set.652		CollectionLimitSet(653			/// ID of the affected collection.654			CollectionId,655		),656657		/// Collection owned was changed.658		CollectionOwnerChanged(659			/// ID of the affected collection.660			CollectionId,661			/// New owner address.662			T::AccountId,663		),664665		/// Collection permissions were set.666		CollectionPermissionSet(667			/// ID of the affected collection.668			CollectionId,669		),670671		/// Collection sponsor was set.672		CollectionSponsorSet(673			/// ID of the affected collection.674			CollectionId,675			/// New sponsor address.676			T::AccountId,677		),678679		/// New sponsor was confirm.680		SponsorshipConfirmed(681			/// ID of the affected collection.682			CollectionId,683			/// New sponsor address.684			T::AccountId,685		),686687		/// Collection sponsor was removed.688		CollectionSponsorRemoved(689			/// ID of the affected collection.690			CollectionId,691		),692	}693694	#[pallet::error]695	pub enum Error<T> {696		/// This collection does not exist.697		CollectionNotFound,698		/// Sender parameter and item owner must be equal.699		MustBeTokenOwner,700		/// No permission to perform action701		NoPermission,702		/// Destroying only empty collections is allowed703		CantDestroyNotEmptyCollection,704		/// Collection is not in mint mode.705		PublicMintingNotAllowed,706		/// Address is not in allow list.707		AddressNotInAllowlist,708709		/// Collection name can not be longer than 63 char.710		CollectionNameLimitExceeded,711		/// Collection description can not be longer than 255 char.712		CollectionDescriptionLimitExceeded,713		/// Token prefix can not be longer than 15 char.714		CollectionTokenPrefixLimitExceeded,715		/// Total collections bound exceeded.716		TotalCollectionsLimitExceeded,717		/// Exceeded max admin count718		CollectionAdminCountExceeded,719		/// Collection limit bounds per collection exceeded720		CollectionLimitBoundsExceeded,721		/// Tried to enable permissions which are only permitted to be disabled722		OwnerPermissionsCantBeReverted,723		/// Collection settings not allowing items transferring724		TransferNotAllowed,725		/// Account token limit exceeded per collection726		AccountTokenLimitExceeded,727		/// Collection token limit exceeded728		CollectionTokenLimitExceeded,729		/// Metadata flag frozen730		MetadataFlagFrozen,731732		/// Item does not exist733		TokenNotFound,734		/// Item is balance not enough735		TokenValueTooLow,736		/// Requested value is more than the approved737		ApprovedValueTooLow,738		/// Tried to approve more than owned739		CantApproveMoreThanOwned,740		/// Only spending from eth mirror could be approved741		AddressIsNotEthMirror,742743		/// Can't transfer tokens to ethereum zero address744		AddressIsZero,745746		/// The operation is not supported747		UnsupportedOperation,748749		/// Insufficient funds to perform an action750		NotSufficientFounds,751752		/// User does not satisfy the nesting rule753		UserIsNotAllowedToNest,754		/// Only tokens from specific collections may nest tokens under this one755		SourceCollectionIsNotAllowedToNest,756757		/// Tried to store more data than allowed in collection field758		CollectionFieldSizeExceeded,759760		/// Tried to store more property data than allowed761		NoSpaceForProperty,762763		/// Tried to store more property keys than allowed764		PropertyLimitReached,765766		/// Property key is too long767		PropertyKeyIsTooLong,768769		/// Only ASCII letters, digits, and symbols `_`, `-`, and `.` are allowed770		InvalidCharacterInPropertyKey,771772		/// Empty property keys are forbidden773		EmptyPropertyKey,774775		/// Tried to access an external collection with an internal API776		CollectionIsExternal,777778		/// Tried to access an internal collection with an external API779		CollectionIsInternal,780781		/// This address is not set as sponsor, use setCollectionSponsor first.782		ConfirmSponsorshipFail,783784		/// The user is not an administrator.785		UserIsNotCollectionAdmin,786	}787788	/// Storage of the count of created collections. Essentially contains the last collection ID.789	#[pallet::storage]790	pub type CreatedCollectionCount<T> = StorageValue<Value = CollectionId, QueryKind = ValueQuery>;791792	/// Storage of the count of deleted collections.793	#[pallet::storage]794	pub type DestroyedCollectionCount<T> =795		StorageValue<Value = CollectionId, QueryKind = ValueQuery>;796797	/// Storage of collection info.798	#[pallet::storage]799	pub type CollectionById<T> = StorageMap<800		Hasher = Blake2_128Concat,801		Key = CollectionId,802		Value = Collection<<T as frame_system::Config>::AccountId>,803		QueryKind = OptionQuery,804	>;805806	/// Storage of collection properties.807	#[pallet::storage]808	#[pallet::getter(fn collection_properties)]809	pub type CollectionProperties<T> = StorageMap<810		Hasher = Blake2_128Concat,811		Key = CollectionId,812		Value = CollectionPropertiesT,813		QueryKind = ValueQuery,814	>;815816	/// Storage of token property permissions of a collection.817	#[pallet::storage]818	#[pallet::getter(fn property_permissions)]819	pub type CollectionPropertyPermissions<T> = StorageMap<820		Hasher = Blake2_128Concat,821		Key = CollectionId,822		Value = PropertiesPermissionMap,823		QueryKind = ValueQuery,824	>;825826	/// Storage of the amount of collection admins.827	#[pallet::storage]828	pub type AdminAmount<T> = StorageMap<829		Hasher = Blake2_128Concat,830		Key = CollectionId,831		Value = u32,832		QueryKind = ValueQuery,833	>;834835	/// List of collection admins.836	#[pallet::storage]837	pub type IsAdmin<T: Config> = StorageNMap<838		Key = (839			Key<Blake2_128Concat, CollectionId>,840			Key<Blake2_128Concat, T::CrossAccountId>,841		),842		Value = bool,843		QueryKind = ValueQuery,844	>;845846	/// Allowlisted collection users.847	#[pallet::storage]848	pub type Allowlist<T: Config> = StorageNMap<849		Key = (850			Key<Blake2_128Concat, CollectionId>,851			Key<Blake2_128Concat, T::CrossAccountId>,852		),853		Value = bool,854		QueryKind = ValueQuery,855	>;856857	/// Not used by code, exists only to provide some types to metadata.858	#[pallet::storage]859	pub type DummyStorageValue<T: Config> = StorageValue<860		Value = (861			CollectionStats,862			CollectionId,863			TokenId,864			TokenChild,865			PhantomType<(866				TokenData<T::CrossAccountId>,867				RpcCollection<T::AccountId>,868				// PoV Estimate Info869				PovInfo,870			)>,871		),872		QueryKind = OptionQuery,873	>;874}875876enum LazyValueState<'a, T> {877	Pending(Box<dyn FnOnce() -> T + 'a>),878	InProgress(PhantomData<sp_std::cell::Cell<T>>),879	Computed(T),880}881882/// Value representation with delayed initialization time.883pub struct LazyValue<'a, T> {884	state: LazyValueState<'a, T>,885}886887impl<'a, T> LazyValue<'a, T> {888	/// Create a new LazyValue.889	pub fn new(f: impl FnOnce() -> T + 'a) -> Self {890		Self {891			state: LazyValueState::Pending(Box::new(f)),892		}893	}894895	/// Get the value. If it is called the first time, the value will be initialized.896	pub fn value(&mut self) -> &T {897		self.force_value();898		self.value_mut()899	}900901	/// Get the value. If it is called the first time, the value will be initialized.902	pub fn value_mut(&mut self) -> &mut T {903		self.force_value();904905		if let LazyValueState::Computed(value) = &mut self.state {906			value907		} else {908			unreachable!()909		}910	}911912	fn into_inner(mut self) -> T {913		self.force_value();914		if let LazyValueState::Computed(value) = self.state {915			value916		} else {917			unreachable!()918		}919	}920921	/// Is value initialized?922	pub fn has_value(&self) -> bool {923		matches!(self.state, LazyValueState::Computed(_))924	}925926	fn force_value(&mut self) {927		use LazyValueState::*;928929		if self.has_value() {930			return;931		}932933		match sp_std::mem::replace(&mut self.state, InProgress(PhantomData)) {934			Pending(f) => self.state = Computed(f()),935			_ => {936				// Computed is ruled out by the above condition937				// InProgress is ruled out by not implementing Sync and absence of recursion938				unreachable!()939			}940		}941	}942}943944fn check_token_permissions<T: Config>(945	collection_admin_permitted: bool,946	token_owner_permitted: bool,947	is_collection_admin: &mut LazyValue<bool>,948	is_token_owner: &mut LazyValue<Result<bool, DispatchError>>,949	is_token_exist: &mut LazyValue<bool>,950) -> DispatchResult {951	if !(collection_admin_permitted && *is_collection_admin.value()952		|| token_owner_permitted && (*is_token_owner.value())?)953	{954		fail!(<Error<T>>::NoPermission);955	}956957	let token_exist_due_to_owner_check_success =958		is_token_owner.has_value() && (*is_token_owner.value())?;959960	// If the token owner check has occurred and succeeded,961	// we know the token exists (otherwise, the owner check must fail).962	if !token_exist_due_to_owner_check_success {963		// If the token owner check didn't occur,964		// we must check the token's existence ourselves.965		if !is_token_exist.value() {966			fail!(<Error<T>>::TokenNotFound);967		}968	}969970	Ok(())971}972973impl<T: Config> Pallet<T> {974	/// Enshure that receiver address is correct.975	///976	/// Ethereum receiver 0x0000000000000000000000000000000000000000 is reserved, and shouldn't own tokens.977	pub fn ensure_correct_receiver(receiver: &T::CrossAccountId) -> DispatchResult {978		ensure!(979			&T::CrossAccountId::from_eth(H160([0; 20])) != receiver,980			<Error<T>>::AddressIsZero981		);982		Ok(())983	}984985	/// Get a vector of collection admins.986	pub fn adminlist(collection: CollectionId) -> Vec<T::CrossAccountId> {987		<IsAdmin<T>>::iter_prefix((collection,))988			.map(|(a, _)| a)989			.collect()990	}991992	/// Get a vector of users allowed to mint tokens.993	pub fn allowlist(collection: CollectionId) -> Vec<T::CrossAccountId> {994		<Allowlist<T>>::iter_prefix((collection,))995			.map(|(a, _)| a)996			.collect()997	}998999	/// Is `user` allowed to mint token in `collection`.1000	pub fn allowed(collection: CollectionId, user: T::CrossAccountId) -> bool {1001		<Allowlist<T>>::get((collection, user))1002	}10031004	/// Get statistics of collections.1005	pub fn collection_stats() -> CollectionStats {1006		let created = <CreatedCollectionCount<T>>::get();1007		let destroyed = <DestroyedCollectionCount<T>>::get();1008		CollectionStats {1009			created: created.0,1010			destroyed: destroyed.0,1011			alive: created.0 - destroyed.0,1012		}1013	}10141015	/// Get the effective limits for the collection.1016	pub fn effective_collection_limits(collection: CollectionId) -> Option<CollectionLimits> {1017		let collection = <CollectionById<T>>::get(collection)?;1018		let limits = collection.limits;1019		let effective_limits = CollectionLimits {1020			account_token_ownership_limit: Some(limits.account_token_ownership_limit()),1021			sponsored_data_size: Some(limits.sponsored_data_size()),1022			sponsored_data_rate_limit: Some(1023				limits1024					.sponsored_data_rate_limit1025					.unwrap_or(SponsoringRateLimit::SponsoringDisabled),1026			),1027			token_limit: Some(limits.token_limit()),1028			sponsor_transfer_timeout: Some(limits.sponsor_transfer_timeout(1029				match collection.mode {1030					CollectionMode::NFT => NFT_SPONSOR_TRANSFER_TIMEOUT,1031					CollectionMode::Fungible(_) => FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,1032					CollectionMode::ReFungible => REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,1033				},1034			)),1035			sponsor_approve_timeout: Some(limits.sponsor_approve_timeout()),1036			owner_can_transfer: Some(limits.owner_can_transfer()),1037			owner_can_destroy: Some(limits.owner_can_destroy()),1038			transfers_enabled: Some(limits.transfers_enabled()),1039		};10401041		Some(effective_limits)1042	}10431044	/// Returns information about the `collection` adapted for rpc.1045	pub fn rpc_collection(collection: CollectionId) -> Option<RpcCollection<T::AccountId>> {1046		let Collection {1047			name,1048			description,1049			owner,1050			mode,1051			token_prefix,1052			sponsorship,1053			limits,1054			permissions,1055			flags,1056		} = <CollectionById<T>>::get(collection)?;10571058		let token_property_permissions = <CollectionPropertyPermissions<T>>::get(collection)1059			.into_iter()1060			.map(|(key, permission)| PropertyKeyPermission { key, permission })1061			.collect();10621063		let properties = <CollectionProperties<T>>::get(collection)1064			.into_iter()1065			.map(|(key, value)| Property { key, value })1066			.collect();10671068		let permissions = CollectionPermissions {1069			access: Some(permissions.access()),1070			mint_mode: Some(permissions.mint_mode()),1071			nesting: Some(permissions.nesting().clone()),1072		};10731074		Some(RpcCollection {1075			name: name.into_inner(),1076			description: description.into_inner(),1077			owner,1078			mode,1079			token_prefix: token_prefix.into_inner(),1080			sponsorship,1081			limits,1082			permissions,1083			token_property_permissions,1084			properties,1085			read_only: flags.external,10861087			flags: RpcCollectionFlags {1088				foreign: flags.foreign,1089				erc721metadata: flags.erc721metadata,1090			},1091		})1092	}1093}10941095macro_rules! limit_default {1096	($old:ident, $new:ident, $($field:ident $(($arg:expr))? => $check:expr),* $(,)?) => {{1097		$(1098			if let Some($new) = $new.$field {1099				let $old = $old.$field($($arg)?);1100				let _ = $new;1101				let _ = $old;1102				$check1103			} else {1104				$new.$field = $old.$field1105			}1106		)*1107	}};1108}1109macro_rules! limit_default_clone {1110	($old:ident, $new:ident, $($field:ident $(($arg:expr))? => $check:expr),* $(,)?) => {{1111		$(1112			if let Some($new) = $new.$field.clone() {1113				let $old = $old.$field($($arg)?);1114				let _ = $new;1115				let _ = $old;1116				$check1117			} else {1118				$new.$field = $old.$field.clone()1119			}1120		)*1121	}};1122}11231124impl<T: Config> Pallet<T> {1125	/// Create new collection.1126	///1127	/// * `owner` - The owner of the collection.1128	/// * `data` - Description of the created collection.1129	/// * `flags` - Extra flags to store.1130	pub fn init_collection(1131		owner: T::CrossAccountId,1132		payer: T::CrossAccountId,1133		data: CreateCollectionData<T::CrossAccountId>,1134	) -> Result<CollectionId, DispatchError> {1135		ensure!(data.flags.is_allowed_for_user(), <Error<T>>::NoPermission);1136		Self::init_collection_internal(owner, payer, data)1137	}11381139	/// Initializes the collection with ForeignCollection flag. Returns [CollectionId] on success, [DispatchError] otherwise.1140	pub fn init_foreign_collection(1141		owner: T::CrossAccountId,1142		payer: T::CrossAccountId,1143		mut data: CreateCollectionData<T::CrossAccountId>,1144	) -> Result<CollectionId, DispatchError> {1145		data.flags.foreign = true;1146		let id = Self::init_collection_internal(owner, payer, data)?;1147		Ok(id)1148	}11491150	fn init_collection_internal(1151		owner: T::CrossAccountId,1152		payer: T::CrossAccountId,1153		data: CreateCollectionData<T::CrossAccountId>,1154	) -> Result<CollectionId, DispatchError> {1155		{1156			ensure!(1157				data.token_prefix.len() <= MAX_TOKEN_PREFIX_LENGTH as usize,1158				Error::<T>::CollectionTokenPrefixLimitExceeded1159			);1160		}11611162		let created_count = <CreatedCollectionCount<T>>::get()1163			.01164			.checked_add(1)1165			.ok_or(ArithmeticError::Overflow)?;1166		let destroyed_count = <DestroyedCollectionCount<T>>::get().0;1167		let id = CollectionId(created_count);11681169		// bound Total number of collections1170		ensure!(1171			created_count - destroyed_count <= COLLECTION_NUMBER_LIMIT,1172			<Error<T>>::TotalCollectionsLimitExceeded1173		);11741175		// =========11761177		let collection = Collection {1178			owner: owner.as_sub().clone(),1179			name: data.name,1180			mode: data.mode.clone(),1181			description: data.description,1182			token_prefix: data.token_prefix,1183			sponsorship: data1184				.pending_sponsor1185				.map(|sponsor| SponsorshipState::Unconfirmed(sponsor.as_sub().clone()))1186				.unwrap_or_default(),1187			limits: data1188				.limits1189				.map(|limits| Self::clamp_limits(data.mode.clone(), &Default::default(), limits))1190				.unwrap_or_else(|| Ok(CollectionLimits::default()))?,1191			permissions: data1192				.permissions1193				.map(|permissions| {1194					Self::clamp_permissions(data.mode.clone(), &Default::default(), permissions)1195				})1196				.unwrap_or_else(|| Ok(CollectionPermissions::default()))?,1197			flags: data.flags,1198		};11991200		let mut collection_properties = CollectionPropertiesT::new();1201		collection_properties1202			.try_set_from_iter(data.properties.into_iter())1203			.map_err(<Error<T>>::from)?;12041205		CollectionProperties::<T>::insert(id, collection_properties);12061207		let mut token_props_permissions = PropertiesPermissionMap::new();1208		token_props_permissions1209			.try_set_from_iter(data.token_property_permissions.into_iter())1210			.map_err(<Error<T>>::from)?;12111212		CollectionPropertyPermissions::<T>::insert(id, token_props_permissions);12131214		let mut admin_amount = 0u32;1215		for admin in data.admin_list.iter() {1216			if !<IsAdmin<T>>::get((id, admin)) {1217				<IsAdmin<T>>::insert((id, admin), true);1218				admin_amount = admin_amount1219					.checked_add(1)1220					.ok_or(<Error<T>>::CollectionAdminCountExceeded)?;1221			}1222		}1223		ensure!(1224			admin_amount <= Self::collection_admins_limit(),1225			<Error<T>>::CollectionAdminCountExceeded,1226		);1227		<AdminAmount<T>>::insert(id, admin_amount);12281229		// Take a (non-refundable) deposit of collection creation1230		{1231			let mut imbalance = <Debt<T::AccountId, <T as Config>::Currency>>::zero();1232			imbalance.subsume(<T as Config>::Currency::deposit(1233				&T::TreasuryAccountId::get(),1234				T::CollectionCreationPrice::get(),1235				Precision::Exact,1236			)?);1237			let credit =1238				<T as Config>::Currency::settle(payer.as_sub(), imbalance, Preservation::Preserve)1239					.map_err(|_| Error::<T>::NotSufficientFounds)?;12401241			debug_assert!(credit.peek().is_zero())1242		}12431244		<CreatedCollectionCount<T>>::put(created_count);1245		<Pallet<T>>::deposit_event(Event::CollectionCreated(1246			id,1247			data.mode.id(),1248			owner.as_sub().clone(),1249		));1250		<PalletEvm<T>>::deposit_log(1251			erc::CollectionHelpersEvents::CollectionCreated {1252				owner: *owner.as_eth(),1253				collection_id: eth::collection_id_to_address(id),1254			}1255			.to_log(T::ContractAddress::get()),1256		);1257		<CollectionById<T>>::insert(id, collection);1258		Ok(id)1259	}12601261	/// Destroy collection.1262	///1263	/// * `collection` - Collection handler.1264	/// * `sender` - The owner or administrator of the collection.1265	pub fn destroy_collection(1266		collection: CollectionHandle<T>,1267		sender: &T::CrossAccountId,1268	) -> DispatchResult {1269		ensure!(1270			collection.limits.owner_can_destroy(),1271			<Error<T>>::NoPermission,1272		);1273		collection.check_is_owner(sender)?;12741275		let destroyed_collections = <DestroyedCollectionCount<T>>::get()1276			.01277			.checked_add(1)1278			.ok_or(ArithmeticError::Overflow)?;12791280		// =========12811282		<DestroyedCollectionCount<T>>::put(destroyed_collections);1283		<CollectionById<T>>::remove(collection.id);1284		<AdminAmount<T>>::remove(collection.id);1285		let _ = <IsAdmin<T>>::clear_prefix((collection.id,), u32::MAX, None);1286		let _ = <Allowlist<T>>::clear_prefix((collection.id,), u32::MAX, None);1287		<CollectionProperties<T>>::remove(collection.id);12881289		<Pallet<T>>::deposit_event(Event::CollectionDestroyed(collection.id));12901291		<PalletEvm<T>>::deposit_log(1292			erc::CollectionHelpersEvents::CollectionDestroyed {1293				collection_id: eth::collection_id_to_address(collection.id),1294			}1295			.to_log(T::ContractAddress::get()),1296		);1297		Ok(())1298	}12991300	/// This function sets or removes a collection properties according to1301	/// `properties_updates` contents:1302	/// * sets a property under the <key> with the value provided `(<key>, Some(<value>))`1303	/// * removes a property under the <key> if the value is `None` `(<key>, None)`.1304	///1305	/// This function fires an event for each property change.1306	/// In case of an error, all the changes (including the events) will be reverted1307	/// since the function is transactional.1308	#[transactional]1309	fn modify_collection_properties(1310		collection: &CollectionHandle<T>,1311		sender: &T::CrossAccountId,1312		properties_updates: impl Iterator<Item = (PropertyKey, Option<PropertyValue>)>,1313	) -> DispatchResult {1314		collection.check_is_owner_or_admin(sender)?;13151316		let mut stored_properties = <CollectionProperties<T>>::get(collection.id);13171318		for (key, value) in properties_updates {1319			match value {1320				Some(value) => {1321					stored_properties1322						.try_set(key.clone(), value)1323						.map_err(<Error<T>>::from)?;13241325					Self::deposit_event(Event::CollectionPropertySet(collection.id, key));1326					<PalletEvm<T>>::deposit_log(1327						erc::CollectionHelpersEvents::CollectionChanged {1328							collection_id: eth::collection_id_to_address(collection.id),1329						}1330						.to_log(T::ContractAddress::get()),1331					);1332				}1333				None => {1334					stored_properties.remove(&key).map_err(<Error<T>>::from)?;13351336					Self::deposit_event(Event::CollectionPropertyDeleted(collection.id, key));1337					<PalletEvm<T>>::deposit_log(1338						erc::CollectionHelpersEvents::CollectionChanged {1339							collection_id: eth::collection_id_to_address(collection.id),1340						}1341						.to_log(T::ContractAddress::get()),1342					);1343				}1344			}1345		}13461347		<CollectionProperties<T>>::set(collection.id, stored_properties);13481349		Ok(())1350	}13511352	/// Sets or unsets the approval of a given operator.1353	///1354	/// The `operator` is allowed to transfer all token pieces of the `owner` on their behalf.1355	/// - `owner`: Token owner1356	/// - `operator`: Operator1357	/// - `approve`: Should operator status be granted or revoked?1358	pub fn set_allowance_for_all(1359		collection: &CollectionHandle<T>,1360		owner: &T::CrossAccountId,1361		operator: &T::CrossAccountId,1362		approve: bool,1363		set_allowance: impl FnOnce(),1364		log: evm_coder::ethereum::Log,1365	) -> DispatchResult {1366		if collection.permissions.access() == AccessMode::AllowList {1367			collection.check_allowlist(owner)?;1368			collection.check_allowlist(operator)?;1369		}13701371		Self::ensure_correct_receiver(operator)?;13721373		set_allowance();13741375		<PalletEvm<T>>::deposit_log(log);1376		Self::deposit_event(Event::ApprovedForAll(1377			collection.id,1378			owner.clone(),1379			operator.clone(),1380			approve,1381		));1382		Ok(())1383	}13841385	/// Set collection property.1386	///1387	/// * `collection` - Collection handler.1388	/// * `sender` - The owner or administrator of the collection.1389	/// * `property` - The property to set.1390	pub fn set_collection_property(1391		collection: &CollectionHandle<T>,1392		sender: &T::CrossAccountId,1393		property: Property,1394	) -> DispatchResult {1395		Self::set_collection_properties(collection, sender, [property].into_iter())1396	}13971398	/// Set a scoped collection property, where the scope is a special prefix1399	/// prohibiting a user access to change the property directly.1400	///1401	/// * `collection_id` - ID of the collection for which the property is being set.1402	/// * `scope` - Property scope.1403	/// * `property` - The property to set.1404	pub fn set_scoped_collection_property(1405		collection_id: CollectionId,1406		scope: PropertyScope,1407		property: Property,1408	) -> DispatchResult {1409		CollectionProperties::<T>::try_mutate(collection_id, |properties| {1410			properties.try_scoped_set(scope, property.key, property.value)1411		})1412		.map_err(<Error<T>>::from)?;14131414		Ok(())1415	}14161417	/// Set scoped collection properties, where the scope is a special prefix1418	/// prohibiting a user access to change the properties directly.1419	///1420	/// * `collection_id` - ID of the collection for which the properties is being set.1421	/// * `scope` - Property scope.1422	/// * `properties` - The properties to set.1423	pub fn set_scoped_collection_properties(1424		collection_id: CollectionId,1425		scope: PropertyScope,1426		properties: impl Iterator<Item = Property>,1427	) -> DispatchResult {1428		CollectionProperties::<T>::try_mutate(collection_id, |stored_properties| {1429			stored_properties.try_scoped_set_from_iter(scope, properties)1430		})1431		.map_err(<Error<T>>::from)?;14321433		Ok(())1434	}14351436	/// Set collection properties.1437	///1438	/// * `collection` - Collection handler.1439	/// * `sender` - The owner or administrator of the collection.1440	/// * `properties` - The properties to set.1441	pub fn set_collection_properties(1442		collection: &CollectionHandle<T>,1443		sender: &T::CrossAccountId,1444		properties: impl Iterator<Item = Property>,1445	) -> DispatchResult {1446		Self::modify_collection_properties(1447			collection,1448			sender,1449			properties.map(|property| (property.key, Some(property.value))),1450		)1451	}14521453	/// Delete collection property.1454	///1455	/// * `collection` - Collection handler.1456	/// * `sender` - The owner or administrator of the collection.1457	/// * `property` - The property to delete.1458	pub fn delete_collection_property(1459		collection: &CollectionHandle<T>,1460		sender: &T::CrossAccountId,1461		property_key: PropertyKey,1462	) -> DispatchResult {1463		Self::delete_collection_properties(collection, sender, [property_key].into_iter())1464	}14651466	/// Delete collection properties.1467	///1468	/// * `collection` - Collection handler.1469	/// * `sender` - The owner or administrator of the collection.1470	/// * `properties` - The properties to delete.1471	pub fn delete_collection_properties(1472		collection: &CollectionHandle<T>,1473		sender: &T::CrossAccountId,1474		property_keys: impl Iterator<Item = PropertyKey>,1475	) -> DispatchResult {1476		Self::modify_collection_properties(collection, sender, property_keys.map(|key| (key, None)))1477	}14781479	/// Set collection propetry permission without any checks.1480	///1481	/// Used for migrations.1482	///1483	/// * `collection` - Collection handler.1484	/// * `property_permissions` - Property permissions.1485	pub fn set_property_permission_unchecked(1486		collection: CollectionId,1487		property_permission: PropertyKeyPermission,1488	) -> DispatchResult {1489		<CollectionPropertyPermissions<T>>::try_mutate(collection, |permissions| {1490			permissions.try_set(property_permission.key, property_permission.permission)1491		})1492		.map_err(<Error<T>>::from)?;1493		Ok(())1494	}14951496	/// Set collection property permission.1497	///1498	/// * `collection` - Collection handler.1499	/// * `sender` - The owner or administrator of the collection.1500	/// * `property_permission` - Property permission.1501	pub fn set_property_permission(1502		collection: &CollectionHandle<T>,1503		sender: &T::CrossAccountId,1504		property_permission: PropertyKeyPermission,1505	) -> DispatchResult {1506		Self::set_scoped_property_permission(1507			collection,1508			sender,1509			PropertyScope::None,1510			property_permission,1511		)1512	}15131514	/// Set collection property permission with scope.1515	///1516	/// * `collection` - Collection handler.1517	/// * `sender` - The owner or administrator of the collection.1518	/// * `scope` - Property scope.1519	/// * `property_permission` - Property permission.1520	pub fn set_scoped_property_permission(1521		collection: &CollectionHandle<T>,1522		sender: &T::CrossAccountId,1523		scope: PropertyScope,1524		property_permission: PropertyKeyPermission,1525	) -> DispatchResult {1526		collection.check_is_owner_or_admin(sender)?;15271528		let all_permissions = CollectionPropertyPermissions::<T>::get(collection.id);1529		let current_permission = all_permissions.get(&property_permission.key);1530		if matches![1531			current_permission,1532			Some(PropertyPermission { mutable: false, .. })1533		] {1534			return Err(<Error<T>>::NoPermission.into());1535		}15361537		CollectionPropertyPermissions::<T>::try_mutate(collection.id, |permissions| {1538			let property_permission = property_permission.clone();1539			permissions.try_scoped_set(1540				scope,1541				property_permission.key,1542				property_permission.permission,1543			)1544		})1545		.map_err(<Error<T>>::from)?;15461547		Self::deposit_event(Event::PropertyPermissionSet(1548			collection.id,1549			property_permission.key,1550		));1551		<PalletEvm<T>>::deposit_log(1552			erc::CollectionHelpersEvents::CollectionChanged {1553				collection_id: eth::collection_id_to_address(collection.id),1554			}1555			.to_log(T::ContractAddress::get()),1556		);15571558		Ok(())1559	}15601561	/// Set token property permission.1562	///1563	/// * `collection` - Collection handler.1564	/// * `sender` - The owner or administrator of the collection.1565	/// * `property_permissions` - Property permissions.1566	#[transactional]1567	pub fn set_token_property_permissions(1568		collection: &CollectionHandle<T>,1569		sender: &T::CrossAccountId,1570		property_permissions: Vec<PropertyKeyPermission>,1571	) -> DispatchResult {1572		Self::set_scoped_token_property_permissions(1573			collection,1574			sender,1575			PropertyScope::None,1576			property_permissions,1577		)1578	}15791580	/// Set token property permission with scope.1581	///1582	/// * `collection` - Collection handler.1583	/// * `sender` - The owner or administrator of the collection.1584	/// * `scope` - Property scope.1585	/// * `property_permissions` - Property permissions.1586	#[transactional]1587	pub fn set_scoped_token_property_permissions(1588		collection: &CollectionHandle<T>,1589		sender: &T::CrossAccountId,1590		scope: PropertyScope,1591		property_permissions: Vec<PropertyKeyPermission>,1592	) -> DispatchResult {1593		for prop_pemission in property_permissions {1594			Self::set_scoped_property_permission(collection, sender, scope, prop_pemission)?;1595		}15961597		Ok(())1598	}15991600	/// Get collection property.1601	pub fn get_collection_property(1602		collection_id: CollectionId,1603		key: &PropertyKey,1604	) -> Option<PropertyValue> {1605		Self::collection_properties(collection_id).get(key).cloned()1606	}16071608	/// Convert byte vector to property key vector.1609	pub fn bytes_keys_to_property_keys(1610		keys: Vec<Vec<u8>>,1611	) -> Result<Vec<PropertyKey>, DispatchError> {1612		keys.into_iter()1613			.map(|key| -> Result<PropertyKey, DispatchError> {1614				key.try_into()1615					.map_err(|_| <Error<T>>::PropertyKeyIsTooLong.into())1616			})1617			.collect::<Result<Vec<PropertyKey>, DispatchError>>()1618	}16191620	/// Get properties according to given keys.1621	pub fn filter_collection_properties(1622		collection_id: CollectionId,1623		keys: Option<Vec<PropertyKey>>,1624	) -> Result<Vec<Property>, DispatchError> {1625		let properties = Self::collection_properties(collection_id);16261627		let properties = keys1628			.map(|keys| {1629				keys.into_iter()1630					.filter_map(|key| {1631						properties.get(&key).map(|value| Property {1632							key,1633							value: value.clone(),1634						})1635					})1636					.collect()1637			})1638			.unwrap_or_else(|| {1639				properties1640					.into_iter()1641					.map(|(key, value)| Property { key, value })1642					.collect()1643			});16441645		Ok(properties)1646	}16471648	/// Get property permissions according to given keys.1649	pub fn filter_property_permissions(1650		collection_id: CollectionId,1651		keys: Option<Vec<PropertyKey>>,1652	) -> Result<Vec<PropertyKeyPermission>, DispatchError> {1653		let permissions = Self::property_permissions(collection_id);16541655		let key_permissions = keys1656			.map(|keys| {1657				keys.into_iter()1658					.filter_map(|key| {1659						permissions1660							.get(&key)1661							.map(|permission| PropertyKeyPermission {1662								key,1663								permission: permission.clone(),1664							})1665					})1666					.collect()1667			})1668			.unwrap_or_else(|| {1669				permissions1670					.into_iter()1671					.map(|(key, permission)| PropertyKeyPermission { key, permission })1672					.collect()1673			});16741675		Ok(key_permissions)1676	}16771678	/// Toggle `user` participation in the `collection`'s allow list.1679	/// #### Store read/writes1680	/// 1 writes1681	pub fn toggle_allowlist(1682		collection: &CollectionHandle<T>,1683		sender: &T::CrossAccountId,1684		user: &T::CrossAccountId,1685		allowed: bool,1686	) -> DispatchResult {1687		collection.check_is_owner_or_admin(sender)?;16881689		// =========16901691		if allowed {1692			<Allowlist<T>>::insert((collection.id, user), true);1693			Self::deposit_event(Event::<T>::AllowListAddressAdded(1694				collection.id,1695				user.clone(),1696			));1697		} else {1698			<Allowlist<T>>::remove((collection.id, user));1699			Self::deposit_event(Event::<T>::AllowListAddressRemoved(1700				collection.id,1701				user.clone(),1702			));1703		}17041705		<PalletEvm<T>>::deposit_log(1706			erc::CollectionHelpersEvents::CollectionChanged {1707				collection_id: eth::collection_id_to_address(collection.id),1708			}1709			.to_log(T::ContractAddress::get()),1710		);17111712		Ok(())1713	}17141715	/// Toggle `user` participation in the `collection`'s admin list.1716	/// #### Store read/writes1717	/// 2 reads, 2 writes1718	pub fn toggle_admin(1719		collection: &CollectionHandle<T>,1720		sender: &T::CrossAccountId,1721		user: &T::CrossAccountId,1722		admin: bool,1723	) -> DispatchResult {1724		collection.check_is_internal()?;1725		collection.check_is_owner(sender)?;17261727		let is_admin = <IsAdmin<T>>::get((collection.id, user));1728		if is_admin == admin {1729			if admin {1730				return Ok(());1731			} else {1732				return Err(Error::<T>::UserIsNotCollectionAdmin.into());1733			}1734		}1735		let amount = <AdminAmount<T>>::get(collection.id);17361737		// =========17381739		if admin {1740			let amount = amount1741				.checked_add(1)1742				.ok_or(<Error<T>>::CollectionAdminCountExceeded)?;1743			ensure!(1744				amount <= Self::collection_admins_limit(),1745				<Error<T>>::CollectionAdminCountExceeded,1746			);17471748			<AdminAmount<T>>::insert(collection.id, amount);1749			<IsAdmin<T>>::insert((collection.id, user), true);17501751			Self::deposit_event(Event::<T>::CollectionAdminAdded(1752				collection.id,1753				user.clone(),1754			));1755		} else {1756			<AdminAmount<T>>::insert(collection.id, amount.saturating_sub(1));1757			<IsAdmin<T>>::remove((collection.id, user));17581759			Self::deposit_event(Event::<T>::CollectionAdminRemoved(1760				collection.id,1761				user.clone(),1762			));1763		}17641765		<PalletEvm<T>>::deposit_log(1766			erc::CollectionHelpersEvents::CollectionChanged {1767				collection_id: eth::collection_id_to_address(collection.id),1768			}1769			.to_log(T::ContractAddress::get()),1770		);17711772		Ok(())1773	}17741775	/// Update collection limits.1776	pub fn update_limits(1777		user: &T::CrossAccountId,1778		collection: &mut CollectionHandle<T>,1779		new_limit: CollectionLimits,1780	) -> DispatchResult {1781		collection.check_is_internal()?;1782		collection.check_is_owner_or_admin(user)?;17831784		collection.limits =1785			Self::clamp_limits(collection.mode.clone(), &collection.limits, new_limit)?;17861787		Self::deposit_event(Event::<T>::CollectionLimitSet(collection.id));1788		<PalletEvm<T>>::deposit_log(1789			erc::CollectionHelpersEvents::CollectionChanged {1790				collection_id: eth::collection_id_to_address(collection.id),1791			}1792			.to_log(T::ContractAddress::get()),1793		);17941795		collection.save()1796	}17971798	/// Merge set fields from `new_limit` to `old_limit`.1799	fn clamp_limits(1800		mode: CollectionMode,1801		old_limit: &CollectionLimits,1802		mut new_limit: CollectionLimits,1803	) -> Result<CollectionLimits, DispatchError> {1804		let limits = old_limit;1805		limit_default!(old_limit, new_limit,1806			account_token_ownership_limit => ensure!(1807				new_limit <= MAX_TOKEN_OWNERSHIP,1808				<Error<T>>::CollectionLimitBoundsExceeded,1809			),1810			sponsored_data_size => ensure!(1811				new_limit <= CUSTOM_DATA_LIMIT,1812				<Error<T>>::CollectionLimitBoundsExceeded,1813			),18141815			sponsored_data_rate_limit => {},1816			token_limit => ensure!(1817				old_limit >= new_limit && new_limit > 0,1818				<Error<T>>::CollectionTokenLimitExceeded1819			),18201821			sponsor_transfer_timeout(match mode {1822				CollectionMode::NFT => NFT_SPONSOR_TRANSFER_TIMEOUT,1823				CollectionMode::Fungible(_) => FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,1824				CollectionMode::ReFungible => REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,1825			}) => ensure!(1826				new_limit <= MAX_SPONSOR_TIMEOUT,1827				<Error<T>>::CollectionLimitBoundsExceeded,1828			),1829			sponsor_approve_timeout => {},1830			owner_can_transfer => ensure!(1831				!limits.owner_can_transfer_instaled() ||1832				old_limit || !new_limit,1833				<Error<T>>::OwnerPermissionsCantBeReverted,1834			),1835			owner_can_destroy => ensure!(1836				old_limit || !new_limit,1837				<Error<T>>::OwnerPermissionsCantBeReverted,1838			),1839			transfers_enabled => {},1840		);1841		Ok(new_limit)1842	}18431844	/// Update collection permissions.1845	pub fn update_permissions(1846		user: &T::CrossAccountId,1847		collection: &mut CollectionHandle<T>,1848		new_permission: CollectionPermissions,1849	) -> DispatchResult {1850		collection.check_is_internal()?;1851		collection.check_is_owner_or_admin(user)?;1852		collection.permissions = Self::clamp_permissions(1853			collection.mode.clone(),1854			&collection.permissions,1855			new_permission,1856		)?;18571858		Self::deposit_event(Event::<T>::CollectionPermissionSet(collection.id));1859		<PalletEvm<T>>::deposit_log(1860			erc::CollectionHelpersEvents::CollectionChanged {1861				collection_id: eth::collection_id_to_address(collection.id),1862			}1863			.to_log(T::ContractAddress::get()),1864		);18651866		collection.save()1867	}18681869	/// Merge set fields from `new_permission` to `old_permission`.1870	fn clamp_permissions(1871		_mode: CollectionMode,1872		old_permission: &CollectionPermissions,1873		mut new_permission: CollectionPermissions,1874	) -> Result<CollectionPermissions, DispatchError> {1875		limit_default_clone!(old_permission, new_permission,1876			access => {},1877			mint_mode => {},1878			nesting => { /* todo check for permissive, if only it gets out of benchmarks */ },1879		);1880		Ok(new_permission)1881	}18821883	/// Repair possibly broken properties of a collection.1884	pub fn repair_collection(collection_id: CollectionId) -> DispatchResult {1885		CollectionProperties::<T>::mutate(collection_id, |properties| {1886			properties.recompute_consumed_space();1887		});18881889		Ok(())1890	}1891}18921893/// Indicates unsupported methods by returning [Error::UnsupportedOperation].1894#[macro_export]1895macro_rules! unsupported {1896	($runtime:path) => {1897		Err($crate::Error::<$runtime>::UnsupportedOperation.into())1898	};1899}19001901/// Return weights for various worst-case operations.1902pub trait CommonWeightInfo<CrossAccountId> {1903	/// Weight of item creation.1904	fn create_item(data: &CreateItemData) -> Weight {1905		Self::create_multiple_items(from_ref(data))1906	}19071908	/// Weight of items creation.1909	fn create_multiple_items(amount: &[CreateItemData]) -> Weight;19101911	/// Weight of items creation.1912	fn create_multiple_items_ex(cost: &CreateItemExData<CrossAccountId>) -> Weight;19131914	/// The weight of the burning item.1915	fn burn_item() -> Weight;19161917	/// Property setting weight.1918	///1919	/// * `amount`- The number of properties to set.1920	fn set_collection_properties(amount: u32) -> Weight;19211922	/// Collection property deletion weight.1923	///1924	/// * `amount`- The number of properties to set.1925	fn delete_collection_properties(amount: u32) -> Weight {1926		Self::set_collection_properties(amount)1927	}19281929	/// Token property setting weight.1930	///1931	/// * `amount`- The number of properties to set.1932	fn set_token_properties(amount: u32) -> Weight;19331934	/// Token property deletion weight.1935	///1936	/// * `amount`- The number of properties to delete.1937	fn delete_token_properties(amount: u32) -> Weight {1938		Self::set_token_properties(amount)1939	}19401941	/// Token property permissions set weight.1942	///1943	/// * `amount`- The number of property permissions to set.1944	fn set_token_property_permissions(amount: u32) -> Weight;19451946	/// Transfer price of the token or its parts.1947	fn transfer() -> Weight;19481949	/// The price of setting the permission of the operation from another user.1950	fn approve() -> Weight;19511952	/// The price of setting the permission of the operation from another user for eth mirror.1953	fn approve_from() -> Weight;19541955	/// Transfer price from another user.1956	fn transfer_from() -> Weight;19571958	/// The price of burning a token from another user.1959	fn burn_from() -> Weight;19601961	/// The price of setting approval for all1962	fn set_allowance_for_all() -> Weight;19631964	/// The price of repairing an item.1965	fn force_repair_item() -> Weight;1966}19671968/// Weight info extension trait for refungible pallet.1969pub trait RefungibleExtensionsWeightInfo {1970	/// Weight of token repartition.1971	fn repartition() -> Weight;1972}19731974/// Common collection operations.1975///1976/// It wraps methods in Fungible, Nonfungible and Refungible pallets1977/// and adds weight info.1978pub trait CommonCollectionOperations<T: Config> {1979	/// Create token.1980	///1981	/// * `sender` - The user who mint the token and pays for the transaction.1982	/// * `to` - The user who will own the token.1983	/// * `data` - Token data.1984	/// * `nesting_budget` - A budget that can be spent on nesting tokens.1985	fn create_item(1986		&self,1987		sender: T::CrossAccountId,1988		to: T::CrossAccountId,1989		data: CreateItemData,1990		nesting_budget: &dyn Budget,1991	) -> DispatchResultWithPostInfo;19921993	/// Create multiple tokens.1994	///1995	/// * `sender` - The user who mint the token and pays for the transaction.1996	/// * `to` - The user who will own the token.1997	/// * `data` - Token data.1998	/// * `nesting_budget` - A budget that can be spent on nesting tokens.1999	fn create_multiple_items(2000		&self,2001		sender: T::CrossAccountId,2002		to: T::CrossAccountId,2003		data: Vec<CreateItemData>,2004		nesting_budget: &dyn Budget,2005	) -> DispatchResultWithPostInfo;20062007	/// Create multiple tokens.2008	///2009	/// * `sender` - The user who mint the token and pays for the transaction.2010	/// * `to` - The user who will own the token.2011	/// * `data` - Token data.2012	/// * `nesting_budget` - A budget that can be spent on nesting tokens.2013	fn create_multiple_items_ex(2014		&self,2015		sender: T::CrossAccountId,2016		data: CreateItemExData<T::CrossAccountId>,2017		nesting_budget: &dyn Budget,2018	) -> DispatchResultWithPostInfo;20192020	/// Burn token.2021	///2022	/// * `sender` - The user who owns the token.2023	/// * `token` - Token id that will burned.2024	/// * `amount` - The number of parts of the token that will be burned.2025	fn burn_item(2026		&self,2027		sender: T::CrossAccountId,2028		token: TokenId,2029		amount: u128,2030	) -> DispatchResultWithPostInfo;20312032	/// Set collection properties.2033	///2034	/// * `sender` - Must be either the owner of the collection or its admin.2035	/// * `properties` - Properties to be set.2036	fn set_collection_properties(2037		&self,2038		sender: T::CrossAccountId,2039		properties: Vec<Property>,2040	) -> DispatchResultWithPostInfo;20412042	/// Delete collection properties.2043	///2044	/// * `sender` - Must be either the owner of the collection or its admin.2045	/// * `properties` - The properties to be removed.2046	fn delete_collection_properties(2047		&self,2048		sender: &T::CrossAccountId,2049		property_keys: Vec<PropertyKey>,2050	) -> DispatchResultWithPostInfo;20512052	/// Set token properties.2053	///2054	/// The appropriate [`PropertyPermission`] for the token property2055	/// must be set with [`Self::set_token_property_permissions`].2056	///2057	/// * `sender` - Must be either the owner of the token or its admin.2058	/// * `token_id` - The token for which the properties are being set.2059	/// * `properties` - Properties to be set.2060	/// * `budget` - Budget for setting properties.2061	fn set_token_properties(2062		&self,2063		sender: T::CrossAccountId,2064		token_id: TokenId,2065		properties: Vec<Property>,2066		budget: &dyn Budget,2067	) -> DispatchResultWithPostInfo;20682069	/// Remove token properties.2070	///2071	/// The appropriate [`PropertyPermission`] for the token property2072	/// must be set with [`Self::set_token_property_permissions`].2073	///2074	/// * `sender` - Must be either the owner of the token or its admin.2075	/// * `token_id` - The token for which the properties are being remove.2076	/// * `property_keys` - Keys to remove corresponding properties.2077	/// * `budget` - Budget for removing properties.2078	fn delete_token_properties(2079		&self,2080		sender: T::CrossAccountId,2081		token_id: TokenId,2082		property_keys: Vec<PropertyKey>,2083		budget: &dyn Budget,2084	) -> DispatchResultWithPostInfo;20852086	/// Get token properties raw map.2087	///2088	/// * `token_id` - The token which properties are needed.2089	fn get_token_properties_raw(&self, token_id: TokenId) -> Option<TokenProperties>;20902091	/// Set token properties raw map.2092	///2093	/// * `token_id` - The token for which the properties are being set.2094	/// * `map` - The raw map containing the token's properties.2095	fn set_token_properties_raw(&self, token_id: TokenId, map: TokenProperties);20962097	/// Set token property permissions.2098	///2099	/// * `sender` - Must be either the owner of the token or its admin.2100	/// * `token_id` - The token for which the properties are being set.2101	/// * `property_permissions` - Property permissions to be set.2102	/// * `budget` - Budget for setting properties.2103	fn set_token_property_permissions(2104		&self,2105		sender: &T::CrossAccountId,2106		property_permissions: Vec<PropertyKeyPermission>,2107	) -> DispatchResultWithPostInfo;21082109	/// Transfer amount of token pieces.2110	///2111	/// * `sender` - Donor user.2112	/// * `to` - Recepient user.2113	/// * `token` - The token of which parts are being sent.2114	/// * `amount` - The number of parts of the token that will be transferred.2115	/// * `budget` - The maximum budget that can be spent on the transfer.2116	fn transfer(2117		&self,2118		sender: T::CrossAccountId,2119		to: T::CrossAccountId,2120		token: TokenId,2121		amount: u128,2122		budget: &dyn Budget,2123	) -> DispatchResultWithPostInfo;21242125	/// Grant access to another account to transfer parts of the token owned by the calling user via [Self::transfer_from].2126	///2127	/// * `sender` - The user who grants access to the token.2128	/// * `spender` - The user to whom the rights are granted.2129	/// * `token` - The token to which access is granted.2130	/// * `amount` - The amount of pieces that another user can dispose of.2131	fn approve(2132		&self,2133		sender: T::CrossAccountId,2134		spender: T::CrossAccountId,2135		token: TokenId,2136		amount: u128,2137	) -> DispatchResultWithPostInfo;21382139	/// Grant access to another account to transfer parts of the token owned by the calling user's eth mirror via [Self::transfer_from].2140	///2141	/// * `sender` - The user who grants access to the token.2142	/// * `from` - Spender's eth mirror.2143	/// * `to` - The user to whom the rights are granted.2144	/// * `token` - The token to which access is granted.2145	/// * `amount` - The amount of pieces that another user can dispose of.2146	fn approve_from(2147		&self,2148		sender: T::CrossAccountId,2149		from: T::CrossAccountId,2150		to: T::CrossAccountId,2151		token: TokenId,2152		amount: u128,2153	) -> DispatchResultWithPostInfo;21542155	/// Send parts of a token owned by another user.2156	///2157	/// Before calling this method, you must grant rights to the calling user via [`Self::approve`].2158	///2159	/// * `sender` - The user who must have access to the token (see [`Self::approve`]).2160	/// * `from` - The user who owns the token.2161	/// * `to` - Recepient user.2162	/// * `token` - The token of which parts are being sent.2163	/// * `amount` - The number of parts of the token that will be transferred.2164	/// * `budget` - The maximum budget that can be spent on the transfer.2165	fn transfer_from(2166		&self,2167		sender: T::CrossAccountId,2168		from: T::CrossAccountId,2169		to: T::CrossAccountId,2170		token: TokenId,2171		amount: u128,2172		budget: &dyn Budget,2173	) -> DispatchResultWithPostInfo;21742175	/// Burn parts of a token owned by another user.2176	///2177	/// Before calling this method, you must grant rights to the calling user via [`Self::approve`].2178	///2179	/// * `sender` - The user who must have access to the token (see [`Self::approve`]).2180	/// * `from` - The user who owns the token.2181	/// * `token` - The token of which parts are being sent.2182	/// * `amount` - The number of parts of the token that will be transferred.2183	/// * `budget` - The maximum budget that can be spent on the burn.2184	fn burn_from(2185		&self,2186		sender: T::CrossAccountId,2187		from: T::CrossAccountId,2188		token: TokenId,2189		amount: u128,2190		budget: &dyn Budget,2191	) -> DispatchResultWithPostInfo;21922193	/// Check permission to nest token.2194	///2195	/// * `sender` - The user who initiated the check.2196	/// * `from` - The token that is checked for embedding.2197	/// * `under` - Token under which to check.2198	/// * `budget` - The maximum budget that can be spent on the check.2199	fn check_nesting(2200		&self,2201		sender: T::CrossAccountId,2202		from: (CollectionId, TokenId),2203		under: TokenId,2204		budget: &dyn Budget,2205	) -> DispatchResult;22062207	/// Nest one token into another.2208	///2209	/// * `under` - Token holder.2210	/// * `to_nest` - Nested token.2211	fn nest(&self, under: TokenId, to_nest: (CollectionId, TokenId));22122213	/// Unnest token.2214	///2215	/// * `under` - Token holder.2216	/// * `to_nest` - Token to unnest.2217	fn unnest(&self, under: TokenId, to_nest: (CollectionId, TokenId));22182219	/// Get all user tokens.2220	///2221	/// * `account` - Account for which you need to get tokens.2222	fn account_tokens(&self, account: T::CrossAccountId) -> Vec<TokenId>;22232224	/// Get all the tokens in the collection.2225	fn collection_tokens(&self) -> Vec<TokenId>;22262227	/// Check if the token exists.2228	///2229	/// * `token` - Id token to check.2230	fn token_exists(&self, token: TokenId) -> bool;22312232	/// Get the id of the last minted token.2233	fn last_token_id(&self) -> TokenId;22342235	/// Get the owner of the token.2236	///2237	/// * `token` - The token for which you need to find out the owner.2238	fn token_owner(&self, token: TokenId) -> Result<T::CrossAccountId, TokenOwnerError>;22392240	/// Checks if the `maybe_owner` is the indirect owner of the `token`.2241	///2242	/// * `token` - Id token to check.2243	/// * `maybe_owner` - The account to check.2244	/// * `nesting_budget` - A budget that can be spent on nesting tokens.2245	fn check_token_indirect_owner(2246		&self,2247		token: TokenId,2248		maybe_owner: &T::CrossAccountId,2249		nesting_budget: &dyn Budget,2250	) -> Result<bool, DispatchError>;22512252	/// Returns 10 tokens owners in no particular order.2253	///2254	/// * `token` - The token for which you need to find out the owners.2255	fn token_owners(&self, token: TokenId) -> Vec<T::CrossAccountId>;22562257	/// Get the value of the token property by key.2258	///2259	/// * `token` - Token with the property to get.2260	/// * `key` - Property name.2261	fn token_property(&self, token_id: TokenId, key: &PropertyKey) -> Option<PropertyValue>;22622263	/// Get a set of token properties by key vector.2264	///2265	/// * `token` - Token with the property to get.2266	/// * `keys` - Vector of property keys. If this parameter is [None](sp_std::result::Result),2267	/// then all properties are returned.2268	fn token_properties(&self, token: TokenId, keys: Option<Vec<PropertyKey>>) -> Vec<Property>;22692270	/// Amount of unique collection tokens2271	fn total_supply(&self) -> u32;22722273	/// Amount of different tokens account has.2274	///2275	/// * `account` - The account for which need to get the balance.2276	fn account_balance(&self, account: T::CrossAccountId) -> u32;22772278	/// Amount of specific token account have.2279	fn balance(&self, account: T::CrossAccountId, token: TokenId) -> u128;22802281	/// Amount of token pieces2282	fn total_pieces(&self, token: TokenId) -> Option<u128>;22832284	/// Get the number of parts of the token that a trusted user can manage.2285	///2286	/// * `sender` - Trusted user.2287	/// * `spender` - Owner of the token.2288	/// * `token` - The token for which to get the value.2289	fn allowance(2290		&self,2291		sender: T::CrossAccountId,2292		spender: T::CrossAccountId,2293		token: TokenId,2294	) -> u128;22952296	/// Get extension for RFT collection.2297	fn refungible_extensions(&self) -> Option<&dyn RefungibleExtensions<T>>;22982299	/// The `operator` is allowed to transfer all tokens of the `owner` on their behalf.2300	/// * `owner` - Token owner2301	/// * `operator` - Operator2302	/// * `approve` - Should operator status be granted or revoked?2303	fn set_allowance_for_all(2304		&self,2305		owner: T::CrossAccountId,2306		operator: T::CrossAccountId,2307		approve: bool,2308	) -> DispatchResultWithPostInfo;23092310	/// Tells whether the given `owner` approves the `operator`.2311	fn allowance_for_all(&self, owner: T::CrossAccountId, operator: T::CrossAccountId) -> bool;23122313	/// Repairs a possibly broken item.2314	fn repair_item(&self, token: TokenId) -> DispatchResultWithPostInfo;2315}23162317/// Extension for RFT collection.2318pub trait RefungibleExtensions<T>2319where2320	T: Config,2321{2322	/// Change the number of parts of the token.2323	///2324	/// When the value changes down, this function is equivalent to burning parts of the token.2325	///2326	/// * `sender` - The user calling the repartition operation. Must be the owner of the token.2327	/// * `token` - The token for which you want to change the number of parts.2328	/// * `amount` - The new value of the parts of the token.2329	fn repartition(2330		&self,2331		sender: &T::CrossAccountId,2332		token: TokenId,2333		amount: u128,2334	) -> DispatchResultWithPostInfo;2335}23362337/// Merge [`DispatchResult`] with [`Weight`] into [`DispatchResultWithPostInfo`].2338///2339/// Used for [`CommonCollectionOperations`] implementations and flexible enough to do so.2340pub fn with_weight(res: DispatchResult, weight: Weight) -> DispatchResultWithPostInfo {2341	let post_info = PostDispatchInfo {2342		actual_weight: Some(weight),2343		pays_fee: Pays::Yes,2344	};2345	match res {2346		Ok(()) => Ok(post_info),2347		Err(error) => Err(DispatchErrorWithPostInfo { post_info, error }),2348	}2349}23502351impl<T: Config> From<PropertiesError> for Error<T> {2352	fn from(error: PropertiesError) -> Self {2353		match error {2354			PropertiesError::NoSpaceForProperty => Self::NoSpaceForProperty,2355			PropertiesError::PropertyLimitReached => Self::PropertyLimitReached,2356			PropertiesError::InvalidCharacterInPropertyKey => Self::InvalidCharacterInPropertyKey,2357			PropertiesError::PropertyKeyIsTooLong => Self::PropertyKeyIsTooLong,2358			PropertiesError::EmptyPropertyKey => Self::EmptyPropertyKey,2359		}2360	}2361}23622363/// The type-safe interface for writing properties (setting or deleting) to tokens.2364/// It has two distinct implementations for newly created tokens and existing ones.2365///2366/// This type utilizes the lazy evaluation to avoid repeating the computation2367/// of several performance-heavy or PoV-heavy tasks,2368/// such as checking the indirect ownership or reading the token property permissions.2369pub struct PropertyWriter<'a, WriterVariant, T, Handle> {2370	collection: &'a Handle,2371	collection_lazy_info: PropertyWriterLazyCollectionInfo<'a>,2372	_phantom: PhantomData<(T, WriterVariant)>,2373}23742375impl<'a, T, Handle, WriterVariant> PropertyWriter<'a, WriterVariant, T, Handle>2376where2377	T: Config,2378	Handle: CommonCollectionOperations<T> + Deref<Target = CollectionHandle<T>>,2379{2380	fn internal_write_token_properties(2381		&mut self,2382		token_id: TokenId,2383		mut token_lazy_info: PropertyWriterLazyTokenInfo,2384		properties_updates: impl Iterator<Item = (PropertyKey, Option<PropertyValue>)>,2385		log: evm_coder::ethereum::Log,2386	) -> DispatchResult {2387		for (key, value) in properties_updates {2388			let permission = self2389				.collection_lazy_info2390				.property_permissions2391				.value()2392				.get(&key)2393				.cloned()2394				.unwrap_or_else(PropertyPermission::none);23952396			match permission {2397				PropertyPermission { mutable: false, .. }2398					if token_lazy_info2399						.stored_properties2400						.value()2401						.get(&key)2402						.is_some() =>2403				{2404					return Err(<Error<T>>::NoPermission.into());2405				}24062407				PropertyPermission {2408					collection_admin,2409					token_owner,2410					..2411				} => check_token_permissions::<T>(2412					collection_admin,2413					token_owner,2414					&mut self.collection_lazy_info.is_collection_admin,2415					&mut token_lazy_info.is_token_owner,2416					&mut token_lazy_info.is_token_exist,2417				)?,2418			}24192420			match value {2421				Some(value) => {2422					token_lazy_info2423						.stored_properties2424						.value_mut()2425						.try_set(key.clone(), value)2426						.map_err(<Error<T>>::from)?;24272428					<Pallet<T>>::deposit_event(Event::TokenPropertySet(2429						self.collection.id,2430						token_id,2431						key,2432					));2433				}2434				None => {2435					token_lazy_info2436						.stored_properties2437						.value_mut()2438						.remove(&key)2439						.map_err(<Error<T>>::from)?;24402441					<Pallet<T>>::deposit_event(Event::TokenPropertyDeleted(2442						self.collection.id,2443						token_id,2444						key,2445					));2446				}2447			}2448		}24492450		let properties_changed = token_lazy_info.stored_properties.has_value();2451		if properties_changed {2452			<PalletEvm<T>>::deposit_log(log);24532454			self.collection2455				.set_token_properties_raw(token_id, token_lazy_info.stored_properties.into_inner());2456		}24572458		Ok(())2459	}2460}24612462/// A helper structure for the [`PropertyWriter`] that holds2463/// the collection-related info. The info is loaded using lazy evaluation.2464/// This info is common for any token for which we write properties.2465pub struct PropertyWriterLazyCollectionInfo<'a> {2466	is_collection_admin: LazyValue<'a, bool>,2467	property_permissions: LazyValue<'a, PropertiesPermissionMap>,2468}24692470/// A helper structure for the [`PropertyWriter`] that holds2471/// the token-related info. The info is loaded using lazy evaluation.2472pub struct PropertyWriterLazyTokenInfo<'a> {2473	is_token_exist: LazyValue<'a, bool>,2474	is_token_owner: LazyValue<'a, Result<bool, DispatchError>>,2475	stored_properties: LazyValue<'a, TokenProperties>,2476}24772478impl<'a> PropertyWriterLazyTokenInfo<'a> {2479	/// Create a lazy token info.2480	pub fn new(2481		check_token_exist: impl FnOnce() -> bool + 'a,2482		check_token_owner: impl FnOnce() -> Result<bool, DispatchError> + 'a,2483		get_token_properties: impl FnOnce() -> TokenProperties + 'a,2484	) -> Self {2485		Self {2486			is_token_exist: LazyValue::new(check_token_exist),2487			is_token_owner: LazyValue::new(check_token_owner),2488			stored_properties: LazyValue::new(get_token_properties),2489		}2490	}2491}24922493/// A marker structure that enables the writer implementation2494/// to provide the interface to write properties to **newly created** tokens.2495pub struct NewTokenPropertyWriter<T>(PhantomData<T>);2496impl<T: Config> NewTokenPropertyWriter<T> {2497	/// Creates a [`PropertyWriter`] for **newly created** tokens.2498	pub fn new<'a, Handle>(2499		collection: &'a Handle,2500		sender: &'a T::CrossAccountId,2501	) -> PropertyWriter<'a, Self, T, Handle>2502	where2503		T: Config,2504		Handle: CommonCollectionOperations<T> + Deref<Target = CollectionHandle<T>>,2505	{2506		PropertyWriter {2507			collection,2508			collection_lazy_info: PropertyWriterLazyCollectionInfo {2509				is_collection_admin: LazyValue::new(|| collection.is_owner_or_admin(sender)),2510				property_permissions: LazyValue::new(|| {2511					<Pallet<T>>::property_permissions(collection.id)2512				}),2513			},2514			_phantom: PhantomData,2515		}2516	}2517}25182519impl<'a, T, Handle> PropertyWriter<'a, NewTokenPropertyWriter<T>, T, Handle>2520where2521	T: Config,2522	Handle: CommonCollectionOperations<T> + Deref<Target = CollectionHandle<T>>,2523{2524	/// A function to write properties to a **newly created** token.2525	pub fn write_token_properties(2526		&mut self,2527		mint_target_is_sender: bool,2528		token_id: TokenId,2529		properties_updates: impl Iterator<Item = Property>,2530		log: evm_coder::ethereum::Log,2531	) -> DispatchResult {2532		let check_token_exist = || {2533			debug_assert!(self.collection.token_exists(token_id));2534			true2535		};25362537		let check_token_owner = || Ok(mint_target_is_sender);25382539		let get_token_properties = || {2540			debug_assert!(self.collection.get_token_properties_raw(token_id).is_none());2541			TokenProperties::new()2542		};25432544		self.internal_write_token_properties(2545			token_id,2546			PropertyWriterLazyTokenInfo::new(2547				check_token_exist,2548				check_token_owner,2549				get_token_properties,2550			),2551			properties_updates.map(|p| (p.key, Some(p.value))),2552			log,2553		)2554	}2555}25562557/// A marker structure that enables the writer implementation2558/// to provide the interface to write properties to **already existing** tokens.2559pub struct ExistingTokenPropertyWriter<T>(PhantomData<T>);2560impl<T: Config> ExistingTokenPropertyWriter<T> {2561	/// Creates a [`PropertyWriter`] for **already existing** tokens.2562	pub fn new<'a, Handle>(2563		collection: &'a Handle,2564		sender: &'a T::CrossAccountId,2565	) -> PropertyWriter<'a, Self, T, Handle>2566	where2567		Handle: CommonCollectionOperations<T> + Deref<Target = CollectionHandle<T>>,2568	{2569		PropertyWriter {2570			collection,2571			collection_lazy_info: PropertyWriterLazyCollectionInfo {2572				is_collection_admin: LazyValue::new(|| collection.is_owner_or_admin(sender)),2573				property_permissions: LazyValue::new(|| {2574					<Pallet<T>>::property_permissions(collection.id)2575				}),2576			},2577			_phantom: PhantomData,2578		}2579	}2580}25812582impl<'a, T, Handle> PropertyWriter<'a, ExistingTokenPropertyWriter<T>, T, Handle>2583where2584	T: Config,2585	Handle: CommonCollectionOperations<T> + Deref<Target = CollectionHandle<T>>,2586{2587	/// A function to write properties to an **already existing** token.2588	pub fn write_token_properties(2589		&mut self,2590		sender: &T::CrossAccountId,2591		token_id: TokenId,2592		properties_updates: impl Iterator<Item = (PropertyKey, Option<PropertyValue>)>,2593		nesting_budget: &dyn Budget,2594		log: evm_coder::ethereum::Log,2595	) -> DispatchResult {2596		let check_token_exist = || self.collection.token_exists(token_id);2597		let check_token_owner = || {2598			self.collection2599				.check_token_indirect_owner(token_id, sender, nesting_budget)2600		};2601		let get_token_properties = || {2602			self.collection2603				.get_token_properties_raw(token_id)2604				.unwrap_or_default()2605		};26062607		self.internal_write_token_properties(2608			token_id,2609			PropertyWriterLazyTokenInfo::new(2610				check_token_exist,2611				check_token_owner,2612				get_token_properties,2613			),2614			properties_updates,2615			log,2616		)2617	}2618}26192620/// A marker structure that enables the writer implementation2621/// to benchmark the token properties writing.2622#[cfg(feature = "runtime-benchmarks")]2623pub struct BenchmarkPropertyWriter<T>(PhantomData<T>);26242625#[cfg(feature = "runtime-benchmarks")]2626impl<T: Config> BenchmarkPropertyWriter<T> {2627	/// Creates a [`PropertyWriter`] for benchmarking tokens properties writing.2628	pub fn new<'a, Handle>(2629		collection: &Handle,2630		collection_lazy_info: PropertyWriterLazyCollectionInfo,2631	) -> PropertyWriter<'a, Self, T, Handle>2632	where2633		Handle: CommonCollectionOperations<T> + Deref<Target = CollectionHandle<T>>,2634	{2635		PropertyWriter {2636			collection,2637			collection_lazy_info,2638			_phantom: PhantomData,2639		}2640	}26412642	/// Load the [`PropertyWriterLazyCollectionInfo`] from the storage.2643	pub fn load_collection_info<Handle>(2644		collection_handle: &Handle,2645		sender: &T::CrossAccountId,2646	) -> PropertyWriterLazyCollectionInfo<'static>2647	where2648		Handle: Deref<Target = CollectionHandle<T>>,2649	{2650		let is_collection_admin = collection_handle.is_owner_or_admin(sender);2651		let property_permissions = <Pallet<T>>::property_permissions(collection_handle.id);26522653		PropertyWriterLazyCollectionInfo {2654			is_collection_admin: LazyValue::new(move || is_collection_admin),2655			property_permissions: LazyValue::new(move || property_permissions),2656		}2657	}26582659	/// Load the [`PropertyWriterLazyTokenInfo`] with token properties from the storage.2660	pub fn load_token_properties<Handle>(2661		collection: &Handle,2662		token_id: TokenId,2663	) -> PropertyWriterLazyTokenInfo2664	where2665		Handle: CommonCollectionOperations<T>,2666	{2667		let stored_properties = collection2668			.get_token_properties_raw(token_id)2669			.unwrap_or_default();26702671		PropertyWriterLazyTokenInfo {2672			is_token_exist: LazyValue::new(|| true),2673			is_token_owner: LazyValue::new(|| Ok(true)),2674			stored_properties: LazyValue::new(move || stored_properties),2675		}2676	}2677}26782679#[cfg(feature = "runtime-benchmarks")]2680impl<'a, T, Handle> PropertyWriter<'a, BenchmarkPropertyWriter<T>, T, Handle>2681where2682	T: Config,2683	Handle: CommonCollectionOperations<T> + Deref<Target = CollectionHandle<T>>,2684{2685	/// A function to benchmark the writing of token properties.2686	pub fn write_token_properties(2687		&mut self,2688		token_id: TokenId,2689		properties_updates: impl Iterator<Item = Property>,2690		log: evm_coder::ethereum::Log,2691	) -> DispatchResult {2692		let check_token_exist = || true;2693		let check_token_owner = || Ok(true);2694		let get_token_properties = || TokenProperties::new();26952696		self.internal_write_token_properties(2697			token_id,2698			PropertyWriterLazyTokenInfo::new(2699				check_token_exist,2700				check_token_owner,2701				get_token_properties,2702			),2703			properties_updates.map(|p| (p.key, Some(p.value))),2704			log,2705		)2706	}2707}27082709/// Computes the weight of writing properties to tokens.2710/// * `properties_nums` - The properties num of each created token.2711/// * `per_token_weight_weight` - The function to obtain the weight2712/// of writing properties from a token's properties num.2713pub fn write_token_properties_total_weight<T: Config, I: Fn(u32) -> Weight>(2714	properties_nums: impl Iterator<Item = u32>,2715	per_token_weight: I,2716) -> Weight {2717	let mut weight = properties_nums2718		.filter_map(|properties_num| {2719			if properties_num > 0 {2720				Some(per_token_weight(properties_num))2721			} else {2722				None2723			}2724		})2725		.fold(Weight::zero(), |a, b| a.saturating_add(b));27262727	if !weight.is_zero() {2728		// If we are here, it means the token properties were written at least once.2729		// Because of that, some common collection data was also loaded; we must add this weight.2730		// However, this common data was loaded only once, which is guaranteed by the `PropertyWriter`.27312732		weight = weight.saturating_add(<SelfWeightOf<T>>::property_writer_load_collection_info());2733	}27342735	weight2736}27372738#[cfg(any(feature = "tests", test))]2739#[allow(missing_docs)]2740pub mod tests {2741	use crate::{Config, DispatchError, DispatchResult, LazyValue};27422743	const fn to_bool(u: u8) -> bool {2744		u != 02745	}27462747	#[derive(Debug)]2748	pub struct TestCase {2749		pub collection_admin: bool,2750		pub is_collection_admin: bool,2751		pub token_owner: bool,2752		pub is_token_owner: bool,2753		pub no_permission: bool,2754	}27552756	impl TestCase {2757		const fn new(2758			collection_admin: u8,2759			is_collection_admin: u8,2760			token_owner: u8,2761			is_token_owner: u8,2762			no_permission: u8,2763		) -> Self {2764			Self {2765				collection_admin: to_bool(collection_admin),2766				is_collection_admin: to_bool(is_collection_admin),2767				token_owner: to_bool(token_owner),2768				is_token_owner: to_bool(is_token_owner),2769				no_permission: to_bool(no_permission),2770			}2771		}2772	}27732774	#[rustfmt::skip]2775	pub const TABLE: [TestCase; 16] = [2776		//                    ┌╴collection_admin2777		//                    │  ┌╴is_collection_admin2778		//                    │  │   ┌╴token_owner2779		//                    │  │   │  ┌╴is_token_ownership2780		//                    │  │   │  │   ┌╴no_permission2781		/*  0*/ TestCase::new(0, 0,  0, 0,  1),2782		/*  1*/ TestCase::new(0, 0,  0, 1,  1),2783		/*  2*/ TestCase::new(0, 0,  1, 0,  1),2784		/*  3*/ TestCase::new(0, 0,  1, 1,  0),2785		/*  4*/ TestCase::new(0, 1,  0, 0,  1),2786		/*  5*/ TestCase::new(0, 1,  0, 1,  1),2787		/*  6*/ TestCase::new(0, 1,  1, 0,  1),2788		/*  7*/ TestCase::new(0, 1,  1, 1,  0),2789		/*  8*/ TestCase::new(1, 0,  0, 0,  1),2790		/*  9*/ TestCase::new(1, 0,  0, 1,  1),2791		/* 10*/ TestCase::new(1, 0,  1, 0,  1),2792		/* 11*/ TestCase::new(1, 0,  1, 1,  0),2793		/* 12*/ TestCase::new(1, 1,  0, 0,  0),2794		/* 13*/ TestCase::new(1, 1,  0, 1,  0),2795		/* 14*/ TestCase::new(1, 1,  1, 0,  0),2796		/* 15*/ TestCase::new(1, 1,  1, 1,  0),2797	];27982799	pub fn check_token_permissions<T: Config>(2800		collection_admin_permitted: bool,2801		token_owner_permitted: bool,2802		is_collection_admin: &mut LazyValue<bool>,2803		check_token_ownership: &mut LazyValue<Result<bool, DispatchError>>,2804		check_token_existence: &mut LazyValue<bool>,2805	) -> DispatchResult {2806		crate::check_token_permissions::<T>(2807			collection_admin_permitted,2808			token_owner_permitted,2809			is_collection_admin,2810			check_token_ownership,2811			check_token_existence,2812		)2813	}2814}