git.delta.rocks / unique-network / refs/commits / 68c3995040db

difftreelog

fix check token children in XCM extensions

Daniel Shiposha2023-10-25parent: #0e38a03.patch.diff
in: master

2 files 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 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, mapping::TokenAddressMapping, AccessMode, Collection, CollectionId,84	CollectionLimits, CollectionMode, CollectionPermissions,85	CollectionProperties as CollectionPropertiesT, CollectionStats, CreateCollectionData,86	CreateItemData, CreateItemExData, PhantomType, PropertiesError, PropertiesPermissionMap,87	Property, PropertyKey, PropertyKeyPermission, PropertyPermission, PropertyScope, PropertyValue,88	RpcCollection, RpcCollectionFlags, SponsoringRateLimit, SponsorshipState, TokenChild,89	TokenData, TokenId, TokenOwnerError, TokenProperties, TrySetProperty, COLLECTION_ADMINS_LIMIT,90	COLLECTION_NUMBER_LIMIT, CUSTOM_DATA_LIMIT, FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,91	MAX_SPONSOR_TIMEOUT, MAX_TOKEN_OWNERSHIP, MAX_TOKEN_PREFIX_LENGTH,92	NFT_SPONSOR_TRANSFER_TIMEOUT, REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,93};94use up_pov_estimate_rpc::PovInfo;9596#[cfg(feature = "runtime-benchmarks")]97pub mod benchmarking;98pub mod dispatch;99pub mod erc;100pub mod eth;101pub mod helpers;102#[allow(missing_docs)]103pub mod weights;104105use weights::WeightInfo;106107/// Weight info.108pub type SelfWeightOf<T> = <T as Config>::WeightInfo;109110/// Collection handle contains information about collection data and id.111/// Also provides functionality to count consumed gas.112///113/// CollectionHandle is used as a generic wrapper for collections of all types (except native fungible).114/// It allows to perform common operations and queries on any collection type,115/// both completely general for all, as well as their respective implementations of [`CommonCollectionOperations`].116#[must_use = "Should call submit_logs or save, otherwise some data will be lost for evm side"]117pub struct CollectionHandle<T: Config> {118	/// Collection id119	pub id: CollectionId,120	collection: Collection<T::AccountId>,121	/// Substrate recorder for counting consumed gas122	pub recorder: SubstrateRecorder<T>,123}124125impl<T: Config> WithRecorder<T> for CollectionHandle<T> {126	fn recorder(&self) -> &SubstrateRecorder<T> {127		&self.recorder128	}129	fn into_recorder(self) -> SubstrateRecorder<T> {130		self.recorder131	}132}133134impl<T: Config> CollectionHandle<T> {135	/// Same as [CollectionHandle::new] but with an explicit gas limit.136	pub fn new_with_gas_limit(id: CollectionId, gas_limit: u64) -> Option<Self> {137		Self::new_with_recorder(id, SubstrateRecorder::new(gas_limit))138	}139140	/// Same as [CollectionHandle::new] but with an existed [`SubstrateRecorder`].141	pub fn new_with_recorder(id: CollectionId, recorder: SubstrateRecorder<T>) -> Option<Self> {142		<CollectionById<T>>::get(id).map(|collection| Self {143			id,144			collection,145			recorder,146		})147	}148149	/// Retrives collection data from storage and creates collection handle with default parameters.150	/// If collection not found return `None`151	pub fn new(id: CollectionId) -> Option<Self> {152		Self::new_with_gas_limit(id, u64::MAX)153	}154155	/// Same as [`CollectionHandle::new`] but if collection not found [CollectionNotFound](Error::CollectionNotFound) returned.156	pub fn try_get(id: CollectionId) -> Result<Self, DispatchError> {157		Ok(Self::new(id).ok_or(<Error<T>>::CollectionNotFound)?)158	}159160	/// Consume gas for reading.161	pub fn consume_store_reads(162		&self,163		reads: u64,164	) -> pallet_evm_coder_substrate::execution::Result<()> {165		self.recorder().consume_store_reads(reads)166	}167168	/// Consume gas for writing.169	pub fn consume_store_writes(170		&self,171		writes: u64,172	) -> pallet_evm_coder_substrate::execution::Result<()> {173		self.recorder().consume_store_writes(writes)174	}175176	/// Consume gas for reading and writing.177	pub fn consume_store_reads_and_writes(178		&self,179		reads: u64,180		writes: u64,181	) -> pallet_evm_coder_substrate::execution::Result<()> {182		self.recorder()183			.consume_store_reads_and_writes(reads, writes)184	}185186	/// Save collection to storage.187	pub fn save(&self) -> DispatchResult {188		<CollectionById<T>>::insert(self.id, &self.collection);189		Ok(())190	}191192	/// Set collection sponsor.193	///194	/// Unique collections allows sponsoring for certain actions.195	/// This method allows you to set the sponsor of the collection.196	/// In order for sponsorship to become active, it must be confirmed through [`Self::confirm_sponsorship`].197	pub fn set_sponsor(198		&mut self,199		sender: &T::CrossAccountId,200		sponsor: T::AccountId,201	) -> DispatchResult {202		self.check_is_internal()?;203		self.check_is_owner_or_admin(sender)?;204205		self.collection.sponsorship = SponsorshipState::Unconfirmed(sponsor.clone());206207		<Pallet<T>>::deposit_event(Event::<T>::CollectionSponsorSet(self.id, sponsor));208		<PalletEvm<T>>::deposit_log(209			erc::CollectionHelpersEvents::CollectionChanged {210				collection_id: eth::collection_id_to_address(self.id),211			}212			.to_log(T::ContractAddress::get()),213		);214215		self.save()216	}217218	/// Force set `sponsor`.219	///220	/// Differs from [`set_sponsor`][`Self::set_sponsor`] in that confirmation221	/// from the `sponsor` is not required.222	///223	/// # Arguments224	///225	/// * `sponsor`: ID of the account of the sponsor-to-be.226	pub fn force_set_sponsor(&mut self, sponsor: T::AccountId) -> DispatchResult {227		self.check_is_internal()?;228229		self.collection.sponsorship = SponsorshipState::Confirmed(sponsor.clone());230231		<Pallet<T>>::deposit_event(Event::<T>::CollectionSponsorSet(self.id, sponsor.clone()));232		<Pallet<T>>::deposit_event(Event::<T>::SponsorshipConfirmed(self.id, sponsor));233		<PalletEvm<T>>::deposit_log(234			erc::CollectionHelpersEvents::CollectionChanged {235				collection_id: eth::collection_id_to_address(self.id),236			}237			.to_log(T::ContractAddress::get()),238		);239240		self.save()241	}242243	/// Confirm sponsorship244	///245	/// In order for the sponsorship to become active, the user set as the sponsor must confirm their participation.246	/// Before confirming sponsorship, the user must be specified as the sponsor of the collection via [`Self::set_sponsor`].247	pub fn confirm_sponsorship(&mut self, sender: &T::AccountId) -> DispatchResult {248		self.check_is_internal()?;249		ensure!(250			self.collection.sponsorship.pending_sponsor() == Some(sender),251			Error::<T>::ConfirmSponsorshipFail252		);253254		self.collection.sponsorship = SponsorshipState::Confirmed(sender.clone());255256		<Pallet<T>>::deposit_event(Event::<T>::SponsorshipConfirmed(self.id, sender.clone()));257		<PalletEvm<T>>::deposit_log(258			erc::CollectionHelpersEvents::CollectionChanged {259				collection_id: eth::collection_id_to_address(self.id),260			}261			.to_log(T::ContractAddress::get()),262		);263264		self.save()265	}266267	/// Remove collection sponsor.268	pub fn remove_sponsor(&mut self, sender: &T::CrossAccountId) -> DispatchResult {269		self.check_is_internal()?;270		self.check_is_owner_or_admin(sender)?;271272		self.collection.sponsorship = SponsorshipState::Disabled;273274		<Pallet<T>>::deposit_event(Event::<T>::CollectionSponsorRemoved(self.id));275		<PalletEvm<T>>::deposit_log(276			erc::CollectionHelpersEvents::CollectionChanged {277				collection_id: eth::collection_id_to_address(self.id),278			}279			.to_log(T::ContractAddress::get()),280		);281		self.save()282	}283284	/// Force remove `sponsor`.285	///286	/// Differs from `remove_sponsor` in that287	/// it doesn't require consent from the `owner` of the collection.288	pub fn force_remove_sponsor(&mut self) -> DispatchResult {289		self.check_is_internal()?;290291		self.collection.sponsorship = SponsorshipState::Disabled;292293		<Pallet<T>>::deposit_event(Event::<T>::CollectionSponsorRemoved(self.id));294		<PalletEvm<T>>::deposit_log(295			erc::CollectionHelpersEvents::CollectionChanged {296				collection_id: eth::collection_id_to_address(self.id),297			}298			.to_log(T::ContractAddress::get()),299		);300		self.save()301	}302303	/// Checks that the collection was created with, and must be operated upon through **Unique API**.304	/// Now check only the `external` flag and if it's **true**, then return [`Error::CollectionIsExternal`] error.305	pub fn check_is_internal(&self) -> DispatchResult {306		if self.flags.external {307			return Err(<Error<T>>::CollectionIsExternal)?;308		}309310		Ok(())311	}312313	/// Checks that the collection was created with, and must be operated upon through an **assimilated API**.314	/// Now check only the `external` flag and if it's **false**, then return [`Error::CollectionIsInternal`] error.315	pub fn check_is_external(&self) -> DispatchResult {316		if !self.flags.external {317			return Err(<Error<T>>::CollectionIsInternal)?;318		}319320		Ok(())321	}322}323324impl<T: Config> Deref for CollectionHandle<T> {325	type Target = Collection<T::AccountId>;326327	fn deref(&self) -> &Self::Target {328		&self.collection329	}330}331332impl<T: Config> DerefMut for CollectionHandle<T> {333	fn deref_mut(&mut self) -> &mut Self::Target {334		&mut self.collection335	}336}337338impl<T: Config> CollectionHandle<T> {339	/// Checks if the `user` is the owner of the collection.340	pub fn check_is_owner(&self, user: &T::CrossAccountId) -> DispatchResult {341		ensure!(*user.as_sub() == self.owner, <Error<T>>::NoPermission);342		Ok(())343	}344345	/// Returns **true** if the `user` is the owner or administrator of the collection.346	pub fn is_owner_or_admin(&self, user: &T::CrossAccountId) -> bool {347		*user.as_sub() == self.owner || <IsAdmin<T>>::get((self.id, user))348	}349350	/// Checks if the `user` is the owner or administrator of the collection.351	pub fn check_is_owner_or_admin(&self, user: &T::CrossAccountId) -> DispatchResult {352		ensure!(self.is_owner_or_admin(user), <Error<T>>::NoPermission);353		Ok(())354	}355356	/// Returns **true** if357	/// * the `user`is a collection owner or admin358	/// * the collection limits allow the owner/admins to transfer/burn any collection token359	pub fn ignores_token_restrictions(&self, user: &T::CrossAccountId) -> bool {360		self.limits.owner_can_transfer() && self.is_owner_or_admin(user)361	}362363	/// Return **true** if `user` does not have enough token parts, and he can ignore such restrictions.364	pub fn ignores_owned_amount(&self, user: &T::CrossAccountId) -> bool {365		self.limits.owner_can_transfer() && self.is_owner_or_admin(user)366	}367368	/// Checks if the user is in the allow list. If not [Error::AddressNotInAllowlist] returns.369	pub fn check_allowlist(&self, user: &T::CrossAccountId) -> DispatchResult {370		ensure!(371			<Allowlist<T>>::get((self.id, user)),372			<Error<T>>::AddressNotInAllowlist373		);374		Ok(())375	}376377	/// Changes collection owner to another account378	/// #### Store read/writes379	/// 1 writes380	pub fn change_owner(381		&mut self,382		caller: T::CrossAccountId,383		new_owner: T::CrossAccountId,384	) -> DispatchResult {385		self.check_is_internal()?;386		self.check_is_owner(&caller)?;387		self.collection.owner = new_owner.as_sub().clone();388389		<Pallet<T>>::deposit_event(Event::<T>::CollectionOwnerChanged(390			self.id,391			new_owner.as_sub().clone(),392		));393		<PalletEvm<T>>::deposit_log(394			erc::CollectionHelpersEvents::CollectionChanged {395				collection_id: eth::collection_id_to_address(self.id),396			}397			.to_log(T::ContractAddress::get()),398		);399400		self.save()401	}402}403404#[frame_support::pallet]405pub mod pallet {406407	use dispatch::CollectionDispatch;408	use frame_support::{409		pallet_prelude::*, storage::Key, traits::StorageVersion, Blake2_128Concat,410	};411	use scale_info::TypeInfo;412	use up_data_structs::{mapping::TokenAddressMapping, TokenId};413	use weights::WeightInfo;414415	use super::*;416417	#[pallet::config]418	pub trait Config:419		frame_system::Config + pallet_evm_coder_substrate::Config + pallet_evm::Config + TypeInfo420	{421		/// Weight information for functions of this pallet.422		type WeightInfo: WeightInfo;423424		/// Events compatible with [`frame_system::Config::Event`].425		type RuntimeEvent: IsType<<Self as frame_system::Config>::RuntimeEvent> + From<Event<Self>>;426427		/// Handler of accounts and payment.428		type Currency: Balanced<Self::AccountId> + Inspect<Self::AccountId>;429430		/// Set price to create a collection.431		#[pallet::constant]432		type CollectionCreationPrice: Get<433			<<Self as Config>::Currency as Inspect<Self::AccountId>>::Balance,434		>;435436		/// Dispatcher of operations on collections.437		type CollectionDispatch: CollectionDispatch<Self>;438439		/// Account which holds the chain's treasury.440		type TreasuryAccountId: Get<Self::AccountId>;441442		/// Address under which the CollectionHelper contract would be available.443		#[pallet::constant]444		type ContractAddress: Get<H160>;445446		/// Mapper for token addresses to Ethereum addresses.447		type EvmTokenAddressMapping: TokenAddressMapping<H160>;448449		/// Mapper for token addresses to [`CrossAccountId`].450		type CrossTokenAddressMapping: TokenAddressMapping<Self::CrossAccountId>;451	}452453	const STORAGE_VERSION: StorageVersion = StorageVersion::new(1);454	/// Collection id for native fungible collction.455	pub const NATIVE_FUNGIBLE_COLLECTION_ID: CollectionId = CollectionId(0);456457	#[pallet::pallet]458	#[pallet::storage_version(STORAGE_VERSION)]459	pub struct Pallet<T>(_);460461	#[pallet::extra_constants]462	impl<T: Config> Pallet<T> {463		/// Maximum admins per collection.464		pub fn collection_admins_limit() -> u32 {465			COLLECTION_ADMINS_LIMIT466		}467	}468469	#[pallet::genesis_config]470	pub struct GenesisConfig<T>(PhantomData<T>);471472	impl<T: Config> Default for GenesisConfig<T> {473		fn default() -> Self {474			Self(Default::default())475		}476	}477478	#[pallet::genesis_build]479	impl<T: Config> BuildGenesisConfig for GenesisConfig<T> {480		fn build(&self) {481			StorageVersion::new(1).put::<Pallet<T>>();482		}483	}484485	impl<T: Config> Pallet<T> {486		/// Helper function that handles deposit events487		pub fn deposit_event(event: Event<T>) {488			let event = <T as Config>::RuntimeEvent::from(event);489			let event = event.into();490			<frame_system::Pallet<T>>::deposit_event(event)491		}492	}493494	#[pallet::event]495	pub enum Event<T: Config> {496		/// New collection was created497		CollectionCreated(498			/// Globally unique identifier of newly created collection.499			CollectionId,500			/// [`CollectionMode`] converted into _u8_.501			u8,502			/// Collection owner.503			T::AccountId,504		),505506		/// New collection was destroyed507		CollectionDestroyed(508			/// Globally unique identifier of collection.509			CollectionId,510		),511512		/// New item was created.513		ItemCreated(514			/// Id of the collection where item was created.515			CollectionId,516			/// Id of an item. Unique within the collection.517			TokenId,518			/// Owner of newly created item519			T::CrossAccountId,520			/// Always 1 for NFT521			u128,522		),523524		/// Collection item was burned.525		ItemDestroyed(526			/// Id of the collection where item was destroyed.527			CollectionId,528			/// Identifier of burned NFT.529			TokenId,530			/// Which user has destroyed its tokens.531			T::CrossAccountId,532			/// Amount of token pieces destroed. Always 1 for NFT.533			u128,534		),535536		/// Item was transferred537		Transfer(538			/// Id of collection to which item is belong.539			CollectionId,540			/// Id of an item.541			TokenId,542			/// Original owner of item.543			T::CrossAccountId,544			/// New owner of item.545			T::CrossAccountId,546			/// Amount of token pieces transfered. Always 1 for NFT.547			u128,548		),549550		/// Amount pieces of token owned by `sender` was approved for `spender`.551		Approved(552			/// Id of collection to which item is belong.553			CollectionId,554			/// Id of an item.555			TokenId,556			/// Original owner of item.557			T::CrossAccountId,558			/// Id for which the approval was granted.559			T::CrossAccountId,560			/// Amount of token pieces transfered. Always 1 for NFT.561			u128,562		),563564		/// A `sender` approves operations on all owned tokens for `spender`.565		ApprovedForAll(566			/// Id of collection to which item is belong.567			CollectionId,568			/// Owner of a wallet.569			T::CrossAccountId,570			/// Id for which operator status was granted or rewoked.571			T::CrossAccountId,572			/// Is operator status granted or revoked?573			bool,574		),575576		/// The colletion property has been added or edited.577		CollectionPropertySet(578			/// Id of collection to which property has been set.579			CollectionId,580			/// The property that was set.581			PropertyKey,582		),583584		/// The property has been deleted.585		CollectionPropertyDeleted(586			/// Id of collection to which property has been deleted.587			CollectionId,588			/// The property that was deleted.589			PropertyKey,590		),591592		/// The token property has been added or edited.593		TokenPropertySet(594			/// Identifier of the collection whose token has the property set.595			CollectionId,596			/// The token for which the property was set.597			TokenId,598			/// The property that was set.599			PropertyKey,600		),601602		/// The token property has been deleted.603		TokenPropertyDeleted(604			/// Identifier of the collection whose token has the property deleted.605			CollectionId,606			/// The token for which the property was deleted.607			TokenId,608			/// The property that was deleted.609			PropertyKey,610		),611612		/// The token property permission of a collection has been set.613		PropertyPermissionSet(614			/// ID of collection to which property permission has been set.615			CollectionId,616			/// The property permission that was set.617			PropertyKey,618		),619620		/// Address was added to the allow list.621		AllowListAddressAdded(622			/// ID of the affected collection.623			CollectionId,624			/// Address of the added account.625			T::CrossAccountId,626		),627628		/// Address was removed from the allow list.629		AllowListAddressRemoved(630			/// ID of the affected collection.631			CollectionId,632			/// Address of the removed account.633			T::CrossAccountId,634		),635636		/// Collection admin was added.637		CollectionAdminAdded(638			/// ID of the affected collection.639			CollectionId,640			/// Admin address.641			T::CrossAccountId,642		),643644		/// Collection admin was removed.645		CollectionAdminRemoved(646			/// ID of the affected collection.647			CollectionId,648			/// Removed admin address.649			T::CrossAccountId,650		),651652		/// Collection limits were set.653		CollectionLimitSet(654			/// ID of the affected collection.655			CollectionId,656		),657658		/// Collection owned was changed.659		CollectionOwnerChanged(660			/// ID of the affected collection.661			CollectionId,662			/// New owner address.663			T::AccountId,664		),665666		/// Collection permissions were set.667		CollectionPermissionSet(668			/// ID of the affected collection.669			CollectionId,670		),671672		/// Collection sponsor was set.673		CollectionSponsorSet(674			/// ID of the affected collection.675			CollectionId,676			/// New sponsor address.677			T::AccountId,678		),679680		/// New sponsor was confirm.681		SponsorshipConfirmed(682			/// ID of the affected collection.683			CollectionId,684			/// New sponsor address.685			T::AccountId,686		),687688		/// Collection sponsor was removed.689		CollectionSponsorRemoved(690			/// ID of the affected collection.691			CollectionId,692		),693	}694695	#[pallet::error]696	pub enum Error<T> {697		/// This collection does not exist.698		CollectionNotFound,699		/// Sender parameter and item owner must be equal.700		MustBeTokenOwner,701		/// No permission to perform action702		NoPermission,703		/// Destroying only empty collections is allowed704		CantDestroyNotEmptyCollection,705		/// Collection is not in mint mode.706		PublicMintingNotAllowed,707		/// Address is not in allow list.708		AddressNotInAllowlist,709710		/// Collection name can not be longer than 63 char.711		CollectionNameLimitExceeded,712		/// Collection description can not be longer than 255 char.713		CollectionDescriptionLimitExceeded,714		/// Token prefix can not be longer than 15 char.715		CollectionTokenPrefixLimitExceeded,716		/// Total collections bound exceeded.717		TotalCollectionsLimitExceeded,718		/// Exceeded max admin count719		CollectionAdminCountExceeded,720		/// Collection limit bounds per collection exceeded721		CollectionLimitBoundsExceeded,722		/// Tried to enable permissions which are only permitted to be disabled723		OwnerPermissionsCantBeReverted,724		/// Collection settings not allowing items transferring725		TransferNotAllowed,726		/// Account token limit exceeded per collection727		AccountTokenLimitExceeded,728		/// Collection token limit exceeded729		CollectionTokenLimitExceeded,730		/// Metadata flag frozen731		MetadataFlagFrozen,732733		/// Item does not exist734		TokenNotFound,735		/// Item is balance not enough736		TokenValueTooLow,737		/// Requested value is more than the approved738		ApprovedValueTooLow,739		/// Tried to approve more than owned740		CantApproveMoreThanOwned,741		/// Only spending from eth mirror could be approved742		AddressIsNotEthMirror,743744		/// Can't transfer tokens to ethereum zero address745		AddressIsZero,746747		/// The operation is not supported748		UnsupportedOperation,749750		/// Insufficient funds to perform an action751		NotSufficientFounds,752753		/// User does not satisfy the nesting rule754		UserIsNotAllowedToNest,755		/// Only tokens from specific collections may nest tokens under this one756		SourceCollectionIsNotAllowedToNest,757758		/// Tried to store more data than allowed in collection field759		CollectionFieldSizeExceeded,760761		/// Tried to store more property data than allowed762		NoSpaceForProperty,763764		/// Tried to store more property keys than allowed765		PropertyLimitReached,766767		/// Property key is too long768		PropertyKeyIsTooLong,769770		/// Only ASCII letters, digits, and symbols `_`, `-`, and `.` are allowed771		InvalidCharacterInPropertyKey,772773		/// Empty property keys are forbidden774		EmptyPropertyKey,775776		/// Tried to access an external collection with an internal API777		CollectionIsExternal,778779		/// Tried to access an internal collection with an external API780		CollectionIsInternal,781782		/// This address is not set as sponsor, use setCollectionSponsor first.783		ConfirmSponsorshipFail,784785		/// The user is not an administrator.786		UserIsNotCollectionAdmin,787788		/// Fungible tokens hold no ID, and the default value of TokenId for a fungible collection is 0.789		FungibleItemsHaveNoId,790791		/// Not Fungible item data used to mint in Fungible collection.792		NotFungibleDataUsedToMintFungibleCollectionToken,793	}794795	/// Storage of the count of created collections. Essentially contains the last collection ID.796	#[pallet::storage]797	pub type CreatedCollectionCount<T> = StorageValue<Value = CollectionId, QueryKind = ValueQuery>;798799	/// Storage of the count of deleted collections.800	#[pallet::storage]801	pub type DestroyedCollectionCount<T> =802		StorageValue<Value = CollectionId, QueryKind = ValueQuery>;803804	/// Storage of collection info.805	#[pallet::storage]806	pub type CollectionById<T> = StorageMap<807		Hasher = Blake2_128Concat,808		Key = CollectionId,809		Value = Collection<<T as frame_system::Config>::AccountId>,810		QueryKind = OptionQuery,811	>;812813	/// Storage of collection properties.814	#[pallet::storage]815	#[pallet::getter(fn collection_properties)]816	pub type CollectionProperties<T> = StorageMap<817		Hasher = Blake2_128Concat,818		Key = CollectionId,819		Value = CollectionPropertiesT,820		QueryKind = ValueQuery,821	>;822823	/// Storage of token property permissions of a collection.824	#[pallet::storage]825	#[pallet::getter(fn property_permissions)]826	pub type CollectionPropertyPermissions<T> = StorageMap<827		Hasher = Blake2_128Concat,828		Key = CollectionId,829		Value = PropertiesPermissionMap,830		QueryKind = ValueQuery,831	>;832833	/// Storage of the amount of collection admins.834	#[pallet::storage]835	pub type AdminAmount<T> = StorageMap<836		Hasher = Blake2_128Concat,837		Key = CollectionId,838		Value = u32,839		QueryKind = ValueQuery,840	>;841842	/// List of collection admins.843	#[pallet::storage]844	pub type IsAdmin<T: Config> = StorageNMap<845		Key = (846			Key<Blake2_128Concat, CollectionId>,847			Key<Blake2_128Concat, T::CrossAccountId>,848		),849		Value = bool,850		QueryKind = ValueQuery,851	>;852853	/// Allowlisted collection users.854	#[pallet::storage]855	pub type Allowlist<T: Config> = StorageNMap<856		Key = (857			Key<Blake2_128Concat, CollectionId>,858			Key<Blake2_128Concat, T::CrossAccountId>,859		),860		Value = bool,861		QueryKind = ValueQuery,862	>;863864	/// Not used by code, exists only to provide some types to metadata.865	#[pallet::storage]866	pub type DummyStorageValue<T: Config> = StorageValue<867		Value = (868			CollectionStats,869			CollectionId,870			TokenId,871			TokenChild,872			PhantomType<(873				TokenData<T::CrossAccountId>,874				RpcCollection<T::AccountId>,875				// PoV Estimate Info876				PovInfo,877			)>,878		),879		QueryKind = OptionQuery,880	>;881}882883enum LazyValueState<'a, T> {884	Pending(Box<dyn FnOnce() -> T + 'a>),885	InProgress,886	Computed(T),887}888889/// Value representation with delayed initialization time.890pub struct LazyValue<'a, T> {891	state: LazyValueState<'a, T>,892}893894impl<'a, T> LazyValue<'a, T> {895	/// Create a new LazyValue.896	pub fn new(f: impl FnOnce() -> T + 'a) -> Self {897		Self {898			state: LazyValueState::Pending(Box::new(f)),899		}900	}901902	/// Get the value. If it is called the first time, the value will be initialized.903	pub fn value(&mut self) -> &T {904		self.force_value();905		self.value_mut()906	}907908	/// Get the value. If it is called the first time, the value will be initialized.909	pub fn value_mut(&mut self) -> &mut T {910		self.force_value();911912		if let LazyValueState::Computed(value) = &mut self.state {913			value914		} else {915			unreachable!()916		}917	}918919	fn into_inner(mut self) -> T {920		self.force_value();921		if let LazyValueState::Computed(value) = self.state {922			value923		} else {924			unreachable!()925		}926	}927928	/// Is value initialized?929	pub fn has_value(&self) -> bool {930		matches!(self.state, LazyValueState::Computed(_))931	}932933	fn force_value(&mut self) {934		use LazyValueState::*;935936		if self.has_value() {937			return;938		}939940		match sp_std::mem::replace(&mut self.state, InProgress) {941			Pending(f) => self.state = Computed(f()),942			_ => panic!("recursion isn't supported"),943		}944	}945}946947fn check_token_permissions<T: Config>(948	collection_admin_permitted: bool,949	token_owner_permitted: bool,950	is_collection_admin: &mut LazyValue<bool>,951	is_token_owner: &mut LazyValue<Result<bool, DispatchError>>,952	is_token_exist: &mut LazyValue<bool>,953) -> DispatchResult {954	if !(collection_admin_permitted && *is_collection_admin.value()955		|| token_owner_permitted && (*is_token_owner.value())?)956	{957		fail!(<Error<T>>::NoPermission);958	}959960	let token_exist_due_to_owner_check_success =961		is_token_owner.has_value() && (*is_token_owner.value())?;962963	// If the token owner check has occurred and succeeded,964	// we know the token exists (otherwise, the owner check must fail).965	if !token_exist_due_to_owner_check_success {966		// If the token owner check didn't occur,967		// we must check the token's existence ourselves.968		if !is_token_exist.value() {969			fail!(<Error<T>>::TokenNotFound);970		}971	}972973	Ok(())974}975976impl<T: Config> Pallet<T> {977	/// Enshure that receiver address is correct.978	///979	/// Ethereum receiver 0x0000000000000000000000000000000000000000 is reserved, and shouldn't own tokens.980	pub fn ensure_correct_receiver(receiver: &T::CrossAccountId) -> DispatchResult {981		ensure!(982			&T::CrossAccountId::from_eth(H160([0; 20])) != receiver,983			<Error<T>>::AddressIsZero984		);985		Ok(())986	}987988	/// Get a vector of collection admins.989	pub fn adminlist(collection: CollectionId) -> Vec<T::CrossAccountId> {990		<IsAdmin<T>>::iter_prefix((collection,))991			.map(|(a, _)| a)992			.collect()993	}994995	/// Get a vector of users allowed to mint tokens.996	pub fn allowlist(collection: CollectionId) -> Vec<T::CrossAccountId> {997		<Allowlist<T>>::iter_prefix((collection,))998			.map(|(a, _)| a)999			.collect()1000	}10011002	/// Is `user` allowed to mint token in `collection`.1003	pub fn allowed(collection: CollectionId, user: T::CrossAccountId) -> bool {1004		<Allowlist<T>>::get((collection, user))1005	}10061007	/// Get statistics of collections.1008	pub fn collection_stats() -> CollectionStats {1009		let created = <CreatedCollectionCount<T>>::get();1010		let destroyed = <DestroyedCollectionCount<T>>::get();1011		CollectionStats {1012			created: created.0,1013			destroyed: destroyed.0,1014			alive: created.0 - destroyed.0,1015		}1016	}10171018	/// Get the effective limits for the collection.1019	pub fn effective_collection_limits(collection: CollectionId) -> Option<CollectionLimits> {1020		let collection = <CollectionById<T>>::get(collection)?;1021		let limits = collection.limits;1022		let effective_limits = CollectionLimits {1023			account_token_ownership_limit: Some(limits.account_token_ownership_limit()),1024			sponsored_data_size: Some(limits.sponsored_data_size()),1025			sponsored_data_rate_limit: Some(1026				limits1027					.sponsored_data_rate_limit1028					.unwrap_or(SponsoringRateLimit::SponsoringDisabled),1029			),1030			token_limit: Some(limits.token_limit()),1031			sponsor_transfer_timeout: Some(limits.sponsor_transfer_timeout(1032				match collection.mode {1033					CollectionMode::NFT => NFT_SPONSOR_TRANSFER_TIMEOUT,1034					CollectionMode::Fungible(_) => FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,1035					CollectionMode::ReFungible => REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,1036				},1037			)),1038			sponsor_approve_timeout: Some(limits.sponsor_approve_timeout()),1039			owner_can_transfer: Some(limits.owner_can_transfer()),1040			owner_can_destroy: Some(limits.owner_can_destroy()),1041			transfers_enabled: Some(limits.transfers_enabled()),1042		};10431044		Some(effective_limits)1045	}10461047	/// Returns information about the `collection` adapted for rpc.1048	pub fn rpc_collection(collection: CollectionId) -> Option<RpcCollection<T::AccountId>> {1049		let Collection {1050			name,1051			description,1052			owner,1053			mode,1054			token_prefix,1055			sponsorship,1056			limits,1057			permissions,1058			flags,1059		} = <CollectionById<T>>::get(collection)?;10601061		let token_property_permissions = <CollectionPropertyPermissions<T>>::get(collection)1062			.into_iter()1063			.map(|(key, permission)| PropertyKeyPermission { key, permission })1064			.collect();10651066		let properties = <CollectionProperties<T>>::get(collection)1067			.into_iter()1068			.map(|(key, value)| Property { key, value })1069			.collect();10701071		let permissions = CollectionPermissions {1072			access: Some(permissions.access()),1073			mint_mode: Some(permissions.mint_mode()),1074			nesting: Some(permissions.nesting().clone()),1075		};10761077		Some(RpcCollection {1078			name: name.into_inner(),1079			description: description.into_inner(),1080			owner,1081			mode,1082			token_prefix: token_prefix.into_inner(),1083			sponsorship,1084			limits,1085			permissions,1086			token_property_permissions,1087			properties,1088			read_only: flags.external,10891090			flags: RpcCollectionFlags {1091				foreign: flags.foreign,1092				erc721metadata: flags.erc721metadata,1093			},1094		})1095	}1096}10971098macro_rules! limit_default {1099	($old:ident, $new:ident, $($field:ident $(($arg:expr))? => $check:expr),* $(,)?) => {{1100		$(1101			if let Some($new) = $new.$field {1102				let $old = $old.$field($($arg)?);1103				let _ = $new;1104				let _ = $old;1105				$check1106			} else {1107				$new.$field = $old.$field1108			}1109		)*1110	}};1111}1112macro_rules! limit_default_clone {1113	($old:ident, $new:ident, $($field:ident $(($arg:expr))? => $check:expr),* $(,)?) => {{1114		$(1115			if let Some($new) = $new.$field.clone() {1116				let $old = $old.$field($($arg)?);1117				let _ = $new;1118				let _ = $old;1119				$check1120			} else {1121				$new.$field = $old.$field.clone()1122			}1123		)*1124	}};1125}11261127impl<T: Config> Pallet<T> {1128	/// Create new collection.1129	///1130	/// * `owner` - The owner of the collection.1131	/// * `payer` - If set, the user that will pay a deposit for the collection creation.1132	/// * `data` - Description of the created collection.1133	/// * `is_special_collection` -- Whether this collection is a special one, i.e. can have special flags set.1134	pub fn init_collection(1135		owner: T::CrossAccountId,1136		payer: Option<T::CrossAccountId>,1137		is_special_collection: bool,1138		data: CreateCollectionData<T::CrossAccountId>,1139	) -> Result<CollectionId, DispatchError> {1140		if !is_special_collection {1141			ensure!(data.flags.is_allowed_for_user(), <Error<T>>::NoPermission);1142		}11431144		// Take a (non-refundable) deposit of collection creation1145		if let Some(payer) = payer {1146			let mut imbalance = <Debt<T::AccountId, <T as Config>::Currency>>::zero();1147			imbalance.subsume(<T as Config>::Currency::deposit(1148				&T::TreasuryAccountId::get(),1149				T::CollectionCreationPrice::get(),1150				Precision::Exact,1151			)?);1152			let credit =1153				<T as Config>::Currency::settle(payer.as_sub(), imbalance, Preservation::Preserve)1154					.map_err(|_| Error::<T>::NotSufficientFounds)?;11551156			debug_assert!(credit.peek().is_zero())1157		}11581159		{1160			ensure!(1161				data.token_prefix.len() <= MAX_TOKEN_PREFIX_LENGTH as usize,1162				Error::<T>::CollectionTokenPrefixLimitExceeded1163			);1164		}11651166		let created_count = <CreatedCollectionCount<T>>::get()1167			.01168			.checked_add(1)1169			.ok_or(ArithmeticError::Overflow)?;1170		let destroyed_count = <DestroyedCollectionCount<T>>::get().0;1171		let id = CollectionId(created_count);11721173		// bound Total number of collections1174		ensure!(1175			created_count - destroyed_count <= COLLECTION_NUMBER_LIMIT,1176			<Error<T>>::TotalCollectionsLimitExceeded1177		);11781179		// =========11801181		let collection = Collection {1182			owner: owner.as_sub().clone(),1183			name: data.name,1184			mode: data.mode.clone(),1185			description: data.description,1186			token_prefix: data.token_prefix,1187			sponsorship: data1188				.pending_sponsor1189				.map(|sponsor| SponsorshipState::Unconfirmed(sponsor.as_sub().clone()))1190				.unwrap_or_default(),1191			limits: data1192				.limits1193				.map(|limits| Self::clamp_limits(data.mode.clone(), &Default::default(), limits))1194				.unwrap_or_else(|| Ok(CollectionLimits::default()))?,1195			permissions: data1196				.permissions1197				.map(|permissions| {1198					Self::clamp_permissions(data.mode.clone(), &Default::default(), permissions)1199				})1200				.unwrap_or_else(|| Ok(CollectionPermissions::default()))?,1201			flags: data.flags,1202		};12031204		let mut collection_properties = CollectionPropertiesT::new();1205		collection_properties1206			.try_set_from_iter(data.properties.into_iter())1207			.map_err(<Error<T>>::from)?;12081209		CollectionProperties::<T>::insert(id, collection_properties);12101211		let mut token_props_permissions = PropertiesPermissionMap::new();1212		token_props_permissions1213			.try_set_from_iter(data.token_property_permissions.into_iter())1214			.map_err(<Error<T>>::from)?;12151216		CollectionPropertyPermissions::<T>::insert(id, token_props_permissions);12171218		let mut admin_amount = 0u32;1219		for admin in data.admin_list.iter() {1220			if !<IsAdmin<T>>::get((id, admin)) {1221				<IsAdmin<T>>::insert((id, admin), true);1222				admin_amount = admin_amount1223					.checked_add(1)1224					.ok_or(<Error<T>>::CollectionAdminCountExceeded)?;1225			}1226		}1227		ensure!(1228			admin_amount <= Self::collection_admins_limit(),1229			<Error<T>>::CollectionAdminCountExceeded,1230		);1231		<AdminAmount<T>>::insert(id, admin_amount);12321233		<CreatedCollectionCount<T>>::put(created_count);1234		<Pallet<T>>::deposit_event(Event::CollectionCreated(1235			id,1236			data.mode.id(),1237			owner.as_sub().clone(),1238		));1239		<PalletEvm<T>>::deposit_log(1240			erc::CollectionHelpersEvents::CollectionCreated {1241				owner: *owner.as_eth(),1242				collection_id: eth::collection_id_to_address(id),1243			}1244			.to_log(T::ContractAddress::get()),1245		);1246		<CollectionById<T>>::insert(id, collection);1247		Ok(id)1248	}12491250	/// Destroy collection.1251	///1252	/// * `collection` - Collection handler.1253	/// * `sender` - The owner or administrator of the collection.1254	pub fn destroy_collection(1255		collection: CollectionHandle<T>,1256		sender: &T::CrossAccountId,1257	) -> DispatchResult {1258		ensure!(1259			collection.limits.owner_can_destroy(),1260			<Error<T>>::NoPermission,1261		);1262		collection.check_is_owner(sender)?;12631264		let destroyed_collections = <DestroyedCollectionCount<T>>::get()1265			.01266			.checked_add(1)1267			.ok_or(ArithmeticError::Overflow)?;12681269		// =========12701271		<DestroyedCollectionCount<T>>::put(destroyed_collections);1272		<CollectionById<T>>::remove(collection.id);1273		<AdminAmount<T>>::remove(collection.id);1274		let _ = <IsAdmin<T>>::clear_prefix((collection.id,), u32::MAX, None);1275		let _ = <Allowlist<T>>::clear_prefix((collection.id,), u32::MAX, None);1276		<CollectionProperties<T>>::remove(collection.id);12771278		<Pallet<T>>::deposit_event(Event::CollectionDestroyed(collection.id));12791280		<PalletEvm<T>>::deposit_log(1281			erc::CollectionHelpersEvents::CollectionDestroyed {1282				collection_id: eth::collection_id_to_address(collection.id),1283			}1284			.to_log(T::ContractAddress::get()),1285		);1286		Ok(())1287	}12881289	/// This function sets or removes a collection properties according to1290	/// `properties_updates` contents:1291	/// * sets a property under the <key> with the value provided `(<key>, Some(<value>))`1292	/// * removes a property under the <key> if the value is `None` `(<key>, None)`.1293	///1294	/// This function fires an event for each property change.1295	/// In case of an error, all the changes (including the events) will be reverted1296	/// since the function is transactional.1297	#[transactional]1298	fn modify_collection_properties(1299		collection: &CollectionHandle<T>,1300		sender: &T::CrossAccountId,1301		properties_updates: impl Iterator<Item = (PropertyKey, Option<PropertyValue>)>,1302	) -> DispatchResult {1303		collection.check_is_owner_or_admin(sender)?;13041305		let mut stored_properties = <CollectionProperties<T>>::get(collection.id);13061307		for (key, value) in properties_updates {1308			match value {1309				Some(value) => {1310					stored_properties1311						.try_set(key.clone(), value)1312						.map_err(<Error<T>>::from)?;13131314					Self::deposit_event(Event::CollectionPropertySet(collection.id, key));1315					<PalletEvm<T>>::deposit_log(1316						erc::CollectionHelpersEvents::CollectionChanged {1317							collection_id: eth::collection_id_to_address(collection.id),1318						}1319						.to_log(T::ContractAddress::get()),1320					);1321				}1322				None => {1323					stored_properties.remove(&key).map_err(<Error<T>>::from)?;13241325					Self::deposit_event(Event::CollectionPropertyDeleted(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			}1334		}13351336		<CollectionProperties<T>>::set(collection.id, stored_properties);13371338		Ok(())1339	}13401341	/// Sets or unsets the approval of a given operator.1342	///1343	/// The `operator` is allowed to transfer all token pieces of the `owner` on their behalf.1344	/// - `owner`: Token owner1345	/// - `operator`: Operator1346	/// - `approve`: Should operator status be granted or revoked?1347	pub fn set_allowance_for_all(1348		collection: &CollectionHandle<T>,1349		owner: &T::CrossAccountId,1350		operator: &T::CrossAccountId,1351		approve: bool,1352		set_allowance: impl FnOnce(),1353		log: evm_coder::ethereum::Log,1354	) -> DispatchResult {1355		if collection.permissions.access() == AccessMode::AllowList {1356			collection.check_allowlist(owner)?;1357			collection.check_allowlist(operator)?;1358		}13591360		Self::ensure_correct_receiver(operator)?;13611362		set_allowance();13631364		<PalletEvm<T>>::deposit_log(log);1365		Self::deposit_event(Event::ApprovedForAll(1366			collection.id,1367			owner.clone(),1368			operator.clone(),1369			approve,1370		));1371		Ok(())1372	}13731374	/// Set collection property.1375	///1376	/// * `collection` - Collection handler.1377	/// * `sender` - The owner or administrator of the collection.1378	/// * `property` - The property to set.1379	pub fn set_collection_property(1380		collection: &CollectionHandle<T>,1381		sender: &T::CrossAccountId,1382		property: Property,1383	) -> DispatchResult {1384		Self::set_collection_properties(collection, sender, [property].into_iter())1385	}13861387	/// Set a scoped collection property, where the scope is a special prefix1388	/// prohibiting a user access to change the property directly.1389	///1390	/// * `collection_id` - ID of the collection for which the property is being set.1391	/// * `scope` - Property scope.1392	/// * `property` - The property to set.1393	pub fn set_scoped_collection_property(1394		collection_id: CollectionId,1395		scope: PropertyScope,1396		property: Property,1397	) -> DispatchResult {1398		CollectionProperties::<T>::try_mutate(collection_id, |properties| {1399			properties.try_scoped_set(scope, property.key, property.value)1400		})1401		.map_err(<Error<T>>::from)?;14021403		Ok(())1404	}14051406	/// Set scoped collection properties, where the scope is a special prefix1407	/// prohibiting a user access to change the properties directly.1408	///1409	/// * `collection_id` - ID of the collection for which the properties is being set.1410	/// * `scope` - Property scope.1411	/// * `properties` - The properties to set.1412	pub fn set_scoped_collection_properties(1413		collection_id: CollectionId,1414		scope: PropertyScope,1415		properties: impl Iterator<Item = Property>,1416	) -> DispatchResult {1417		CollectionProperties::<T>::try_mutate(collection_id, |stored_properties| {1418			stored_properties.try_scoped_set_from_iter(scope, properties)1419		})1420		.map_err(<Error<T>>::from)?;14211422		Ok(())1423	}14241425	/// Set collection properties.1426	///1427	/// * `collection` - Collection handler.1428	/// * `sender` - The owner or administrator of the collection.1429	/// * `properties` - The properties to set.1430	pub fn set_collection_properties(1431		collection: &CollectionHandle<T>,1432		sender: &T::CrossAccountId,1433		properties: impl Iterator<Item = Property>,1434	) -> DispatchResult {1435		Self::modify_collection_properties(1436			collection,1437			sender,1438			properties.map(|property| (property.key, Some(property.value))),1439		)1440	}14411442	/// Delete collection property.1443	///1444	/// * `collection` - Collection handler.1445	/// * `sender` - The owner or administrator of the collection.1446	/// * `property` - The property to delete.1447	pub fn delete_collection_property(1448		collection: &CollectionHandle<T>,1449		sender: &T::CrossAccountId,1450		property_key: PropertyKey,1451	) -> DispatchResult {1452		Self::delete_collection_properties(collection, sender, [property_key].into_iter())1453	}14541455	/// Delete collection properties.1456	///1457	/// * `collection` - Collection handler.1458	/// * `sender` - The owner or administrator of the collection.1459	/// * `properties` - The properties to delete.1460	pub fn delete_collection_properties(1461		collection: &CollectionHandle<T>,1462		sender: &T::CrossAccountId,1463		property_keys: impl Iterator<Item = PropertyKey>,1464	) -> DispatchResult {1465		Self::modify_collection_properties(collection, sender, property_keys.map(|key| (key, None)))1466	}14671468	/// Set collection propetry permission without any checks.1469	///1470	/// Used for migrations.1471	///1472	/// * `collection` - Collection handler.1473	/// * `property_permissions` - Property permissions.1474	pub fn set_property_permission_unchecked(1475		collection: CollectionId,1476		property_permission: PropertyKeyPermission,1477	) -> DispatchResult {1478		<CollectionPropertyPermissions<T>>::try_mutate(collection, |permissions| {1479			permissions.try_set(property_permission.key, property_permission.permission)1480		})1481		.map_err(<Error<T>>::from)?;1482		Ok(())1483	}14841485	/// Set collection property permission.1486	///1487	/// * `collection` - Collection handler.1488	/// * `sender` - The owner or administrator of the collection.1489	/// * `property_permission` - Property permission.1490	pub fn set_property_permission(1491		collection: &CollectionHandle<T>,1492		sender: &T::CrossAccountId,1493		property_permission: PropertyKeyPermission,1494	) -> DispatchResult {1495		Self::set_scoped_property_permission(1496			collection,1497			sender,1498			PropertyScope::None,1499			property_permission,1500		)1501	}15021503	/// Set collection property permission with scope.1504	///1505	/// * `collection` - Collection handler.1506	/// * `sender` - The owner or administrator of the collection.1507	/// * `scope` - Property scope.1508	/// * `property_permission` - Property permission.1509	pub fn set_scoped_property_permission(1510		collection: &CollectionHandle<T>,1511		sender: &T::CrossAccountId,1512		scope: PropertyScope,1513		property_permission: PropertyKeyPermission,1514	) -> DispatchResult {1515		collection.check_is_owner_or_admin(sender)?;15161517		let all_permissions = CollectionPropertyPermissions::<T>::get(collection.id);1518		let current_permission = all_permissions.get(&property_permission.key);1519		if matches![1520			current_permission,1521			Some(PropertyPermission { mutable: false, .. })1522		] {1523			return Err(<Error<T>>::NoPermission.into());1524		}15251526		CollectionPropertyPermissions::<T>::try_mutate(collection.id, |permissions| {1527			let property_permission = property_permission.clone();1528			permissions.try_scoped_set(1529				scope,1530				property_permission.key,1531				property_permission.permission,1532			)1533		})1534		.map_err(<Error<T>>::from)?;15351536		Self::deposit_event(Event::PropertyPermissionSet(1537			collection.id,1538			property_permission.key,1539		));1540		<PalletEvm<T>>::deposit_log(1541			erc::CollectionHelpersEvents::CollectionChanged {1542				collection_id: eth::collection_id_to_address(collection.id),1543			}1544			.to_log(T::ContractAddress::get()),1545		);15461547		Ok(())1548	}15491550	/// Set token property permission.1551	///1552	/// * `collection` - Collection handler.1553	/// * `sender` - The owner or administrator of the collection.1554	/// * `property_permissions` - Property permissions.1555	#[transactional]1556	pub fn set_token_property_permissions(1557		collection: &CollectionHandle<T>,1558		sender: &T::CrossAccountId,1559		property_permissions: Vec<PropertyKeyPermission>,1560	) -> DispatchResult {1561		Self::set_scoped_token_property_permissions(1562			collection,1563			sender,1564			PropertyScope::None,1565			property_permissions,1566		)1567	}15681569	/// Set token property permission with scope.1570	///1571	/// * `collection` - Collection handler.1572	/// * `sender` - The owner or administrator of the collection.1573	/// * `scope` - Property scope.1574	/// * `property_permissions` - Property permissions.1575	#[transactional]1576	pub fn set_scoped_token_property_permissions(1577		collection: &CollectionHandle<T>,1578		sender: &T::CrossAccountId,1579		scope: PropertyScope,1580		property_permissions: Vec<PropertyKeyPermission>,1581	) -> DispatchResult {1582		for prop_pemission in property_permissions {1583			Self::set_scoped_property_permission(collection, sender, scope, prop_pemission)?;1584		}15851586		Ok(())1587	}15881589	/// Get collection property.1590	pub fn get_collection_property(1591		collection_id: CollectionId,1592		key: &PropertyKey,1593	) -> Option<PropertyValue> {1594		Self::collection_properties(collection_id).get(key).cloned()1595	}15961597	/// Convert byte vector to property key vector.1598	pub fn bytes_keys_to_property_keys(1599		keys: Vec<Vec<u8>>,1600	) -> Result<Vec<PropertyKey>, DispatchError> {1601		keys.into_iter()1602			.map(|key| -> Result<PropertyKey, DispatchError> {1603				key.try_into()1604					.map_err(|_| <Error<T>>::PropertyKeyIsTooLong.into())1605			})1606			.collect::<Result<Vec<PropertyKey>, DispatchError>>()1607	}16081609	/// Get properties according to given keys.1610	pub fn filter_collection_properties(1611		collection_id: CollectionId,1612		keys: Option<Vec<PropertyKey>>,1613	) -> Result<Vec<Property>, DispatchError> {1614		let properties = Self::collection_properties(collection_id);16151616		let properties = keys1617			.map(|keys| {1618				keys.into_iter()1619					.filter_map(|key| {1620						properties.get(&key).map(|value| Property {1621							key,1622							value: value.clone(),1623						})1624					})1625					.collect()1626			})1627			.unwrap_or_else(|| {1628				properties1629					.into_iter()1630					.map(|(key, value)| Property { key, value })1631					.collect()1632			});16331634		Ok(properties)1635	}16361637	/// Get property permissions according to given keys.1638	pub fn filter_property_permissions(1639		collection_id: CollectionId,1640		keys: Option<Vec<PropertyKey>>,1641	) -> Result<Vec<PropertyKeyPermission>, DispatchError> {1642		let permissions = Self::property_permissions(collection_id);16431644		let key_permissions = keys1645			.map(|keys| {1646				keys.into_iter()1647					.filter_map(|key| {1648						permissions1649							.get(&key)1650							.map(|permission| PropertyKeyPermission {1651								key,1652								permission: permission.clone(),1653							})1654					})1655					.collect()1656			})1657			.unwrap_or_else(|| {1658				permissions1659					.into_iter()1660					.map(|(key, permission)| PropertyKeyPermission { key, permission })1661					.collect()1662			});16631664		Ok(key_permissions)1665	}16661667	/// Toggle `user` participation in the `collection`'s allow list.1668	/// #### Store read/writes1669	/// 1 writes1670	pub fn toggle_allowlist(1671		collection: &CollectionHandle<T>,1672		sender: &T::CrossAccountId,1673		user: &T::CrossAccountId,1674		allowed: bool,1675	) -> DispatchResult {1676		collection.check_is_owner_or_admin(sender)?;16771678		// =========16791680		if allowed {1681			<Allowlist<T>>::insert((collection.id, user), true);1682			Self::deposit_event(Event::<T>::AllowListAddressAdded(1683				collection.id,1684				user.clone(),1685			));1686		} else {1687			<Allowlist<T>>::remove((collection.id, user));1688			Self::deposit_event(Event::<T>::AllowListAddressRemoved(1689				collection.id,1690				user.clone(),1691			));1692		}16931694		<PalletEvm<T>>::deposit_log(1695			erc::CollectionHelpersEvents::CollectionChanged {1696				collection_id: eth::collection_id_to_address(collection.id),1697			}1698			.to_log(T::ContractAddress::get()),1699		);17001701		Ok(())1702	}17031704	/// Toggle `user` participation in the `collection`'s admin list.1705	/// #### Store read/writes1706	/// 2 reads, 2 writes1707	pub fn toggle_admin(1708		collection: &CollectionHandle<T>,1709		sender: &T::CrossAccountId,1710		user: &T::CrossAccountId,1711		admin: bool,1712	) -> DispatchResult {1713		collection.check_is_internal()?;1714		collection.check_is_owner(sender)?;17151716		let is_admin = <IsAdmin<T>>::get((collection.id, user));1717		if is_admin == admin {1718			if admin {1719				return Ok(());1720			} else {1721				return Err(Error::<T>::UserIsNotCollectionAdmin.into());1722			}1723		}1724		let amount = <AdminAmount<T>>::get(collection.id);17251726		// =========17271728		if admin {1729			let amount = amount1730				.checked_add(1)1731				.ok_or(<Error<T>>::CollectionAdminCountExceeded)?;1732			ensure!(1733				amount <= Self::collection_admins_limit(),1734				<Error<T>>::CollectionAdminCountExceeded,1735			);17361737			<AdminAmount<T>>::insert(collection.id, amount);1738			<IsAdmin<T>>::insert((collection.id, user), true);17391740			Self::deposit_event(Event::<T>::CollectionAdminAdded(1741				collection.id,1742				user.clone(),1743			));1744		} else {1745			<AdminAmount<T>>::insert(collection.id, amount.saturating_sub(1));1746			<IsAdmin<T>>::remove((collection.id, user));17471748			Self::deposit_event(Event::<T>::CollectionAdminRemoved(1749				collection.id,1750				user.clone(),1751			));1752		}17531754		<PalletEvm<T>>::deposit_log(1755			erc::CollectionHelpersEvents::CollectionChanged {1756				collection_id: eth::collection_id_to_address(collection.id),1757			}1758			.to_log(T::ContractAddress::get()),1759		);17601761		Ok(())1762	}17631764	/// Update collection limits.1765	pub fn update_limits(1766		user: &T::CrossAccountId,1767		collection: &mut CollectionHandle<T>,1768		new_limit: CollectionLimits,1769	) -> DispatchResult {1770		collection.check_is_internal()?;1771		collection.check_is_owner_or_admin(user)?;17721773		collection.limits =1774			Self::clamp_limits(collection.mode.clone(), &collection.limits, new_limit)?;17751776		Self::deposit_event(Event::<T>::CollectionLimitSet(collection.id));1777		<PalletEvm<T>>::deposit_log(1778			erc::CollectionHelpersEvents::CollectionChanged {1779				collection_id: eth::collection_id_to_address(collection.id),1780			}1781			.to_log(T::ContractAddress::get()),1782		);17831784		collection.save()1785	}17861787	/// Merge set fields from `new_limit` to `old_limit`.1788	fn clamp_limits(1789		mode: CollectionMode,1790		old_limit: &CollectionLimits,1791		mut new_limit: CollectionLimits,1792	) -> Result<CollectionLimits, DispatchError> {1793		let limits = old_limit;1794		limit_default!(old_limit, new_limit,1795			account_token_ownership_limit => ensure!(1796				new_limit <= MAX_TOKEN_OWNERSHIP,1797				<Error<T>>::CollectionLimitBoundsExceeded,1798			),1799			sponsored_data_size => ensure!(1800				new_limit <= CUSTOM_DATA_LIMIT,1801				<Error<T>>::CollectionLimitBoundsExceeded,1802			),18031804			sponsored_data_rate_limit => {},1805			token_limit => ensure!(1806				old_limit >= new_limit && new_limit > 0,1807				<Error<T>>::CollectionTokenLimitExceeded1808			),18091810			sponsor_transfer_timeout(match mode {1811				CollectionMode::NFT => NFT_SPONSOR_TRANSFER_TIMEOUT,1812				CollectionMode::Fungible(_) => FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,1813				CollectionMode::ReFungible => REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,1814			}) => ensure!(1815				new_limit <= MAX_SPONSOR_TIMEOUT,1816				<Error<T>>::CollectionLimitBoundsExceeded,1817			),1818			sponsor_approve_timeout => {},1819			owner_can_transfer => ensure!(1820				!limits.owner_can_transfer_instaled() ||1821				old_limit || !new_limit,1822				<Error<T>>::OwnerPermissionsCantBeReverted,1823			),1824			owner_can_destroy => ensure!(1825				old_limit || !new_limit,1826				<Error<T>>::OwnerPermissionsCantBeReverted,1827			),1828			transfers_enabled => {},1829		);1830		Ok(new_limit)1831	}18321833	/// Update collection permissions.1834	pub fn update_permissions(1835		user: &T::CrossAccountId,1836		collection: &mut CollectionHandle<T>,1837		new_permission: CollectionPermissions,1838	) -> DispatchResult {1839		collection.check_is_internal()?;1840		collection.check_is_owner_or_admin(user)?;1841		collection.permissions = Self::clamp_permissions(1842			collection.mode.clone(),1843			&collection.permissions,1844			new_permission,1845		)?;18461847		Self::deposit_event(Event::<T>::CollectionPermissionSet(collection.id));1848		<PalletEvm<T>>::deposit_log(1849			erc::CollectionHelpersEvents::CollectionChanged {1850				collection_id: eth::collection_id_to_address(collection.id),1851			}1852			.to_log(T::ContractAddress::get()),1853		);18541855		collection.save()1856	}18571858	/// Merge set fields from `new_permission` to `old_permission`.1859	fn clamp_permissions(1860		_mode: CollectionMode,1861		old_permission: &CollectionPermissions,1862		mut new_permission: CollectionPermissions,1863	) -> Result<CollectionPermissions, DispatchError> {1864		limit_default_clone!(old_permission, new_permission,1865			access => {},1866			mint_mode => {},1867			nesting => { /* todo check for permissive, if only it gets out of benchmarks */ },1868		);1869		Ok(new_permission)1870	}18711872	/// Repair possibly broken properties of a collection.1873	pub fn repair_collection(collection_id: CollectionId) -> DispatchResult {1874		CollectionProperties::<T>::mutate(collection_id, |properties| {1875			properties.recompute_consumed_space();1876		});18771878		Ok(())1879	}1880}18811882/// Indicates unsupported methods by returning [Error::UnsupportedOperation].1883#[macro_export]1884macro_rules! unsupported {1885	($runtime:path) => {1886		Err($crate::Error::<$runtime>::UnsupportedOperation.into())1887	};1888}18891890/// Return weights for various worst-case operations.1891pub trait CommonWeightInfo<CrossAccountId> {1892	/// Weight of item creation.1893	fn create_item(data: &CreateItemData) -> Weight {1894		Self::create_multiple_items(from_ref(data))1895	}18961897	/// Weight of items creation.1898	fn create_multiple_items(amount: &[CreateItemData]) -> Weight;18991900	/// Weight of items creation.1901	fn create_multiple_items_ex(cost: &CreateItemExData<CrossAccountId>) -> Weight;19021903	/// The weight of the burning item.1904	fn burn_item() -> Weight;19051906	/// Property setting weight.1907	///1908	/// * `amount`- The number of properties to set.1909	fn set_collection_properties(amount: u32) -> Weight;19101911	/// Collection property deletion weight.1912	///1913	/// * `amount`- The number of properties to set.1914	fn delete_collection_properties(amount: u32) -> Weight {1915		Self::set_collection_properties(amount)1916	}19171918	/// Token property setting weight.1919	///1920	/// * `amount`- The number of properties to set.1921	fn set_token_properties(amount: u32) -> Weight;19221923	/// Token property deletion weight.1924	///1925	/// * `amount`- The number of properties to delete.1926	fn delete_token_properties(amount: u32) -> Weight {1927		Self::set_token_properties(amount)1928	}19291930	/// Token property permissions set weight.1931	///1932	/// * `amount`- The number of property permissions to set.1933	fn set_token_property_permissions(amount: u32) -> Weight;19341935	/// Transfer price of the token or its parts.1936	fn transfer() -> Weight;19371938	/// The price of setting the permission of the operation from another user.1939	fn approve() -> Weight;19401941	/// The price of setting the permission of the operation from another user for eth mirror.1942	fn approve_from() -> Weight;19431944	/// Transfer price from another user.1945	fn transfer_from() -> Weight;19461947	/// The price of burning a token from another user.1948	fn burn_from() -> Weight;19491950	/// The price of setting approval for all1951	fn set_allowance_for_all() -> Weight;19521953	/// The price of repairing an item.1954	fn force_repair_item() -> Weight;1955}19561957/// Weight info extension trait for refungible pallet.1958pub trait RefungibleExtensionsWeightInfo {1959	/// Weight of token repartition.1960	fn repartition() -> Weight;1961}19621963/// Common collection operations.1964///1965/// It wraps methods in Fungible, Nonfungible and Refungible pallets1966/// and adds weight info.1967pub trait CommonCollectionOperations<T: Config> {1968	/// Create token.1969	///1970	/// * `sender` - The user who mint the token and pays for the transaction.1971	/// * `to` - The user who will own the token.1972	/// * `data` - Token data.1973	/// * `nesting_budget` - A budget that can be spent on nesting tokens.1974	fn create_item(1975		&self,1976		sender: T::CrossAccountId,1977		to: T::CrossAccountId,1978		data: CreateItemData,1979		nesting_budget: &dyn Budget,1980	) -> DispatchResultWithPostInfo;19811982	/// Create multiple tokens.1983	///1984	/// * `sender` - The user who mint the token and pays for the transaction.1985	/// * `to` - The user who will own the token.1986	/// * `data` - Token data.1987	/// * `nesting_budget` - A budget that can be spent on nesting tokens.1988	fn create_multiple_items(1989		&self,1990		sender: T::CrossAccountId,1991		to: T::CrossAccountId,1992		data: Vec<CreateItemData>,1993		nesting_budget: &dyn Budget,1994	) -> DispatchResultWithPostInfo;19951996	/// Create multiple tokens.1997	///1998	/// * `sender` - The user who mint the token and pays for the transaction.1999	/// * `to` - The user who will own the token.2000	/// * `data` - Token data.2001	/// * `nesting_budget` - A budget that can be spent on nesting tokens.2002	fn create_multiple_items_ex(2003		&self,2004		sender: T::CrossAccountId,2005		data: CreateItemExData<T::CrossAccountId>,2006		nesting_budget: &dyn Budget,2007	) -> DispatchResultWithPostInfo;20082009	/// Burn token.2010	///2011	/// * `sender` - The user who owns the token.2012	/// * `token` - Token id that will burned.2013	/// * `amount` - The number of parts of the token that will be burned.2014	fn burn_item(2015		&self,2016		sender: T::CrossAccountId,2017		token: TokenId,2018		amount: u128,2019	) -> DispatchResultWithPostInfo;20202021	/// Set collection properties.2022	///2023	/// * `sender` - Must be either the owner of the collection or its admin.2024	/// * `properties` - Properties to be set.2025	fn set_collection_properties(2026		&self,2027		sender: T::CrossAccountId,2028		properties: Vec<Property>,2029	) -> DispatchResultWithPostInfo;20302031	/// Delete collection properties.2032	///2033	/// * `sender` - Must be either the owner of the collection or its admin.2034	/// * `properties` - The properties to be removed.2035	fn delete_collection_properties(2036		&self,2037		sender: &T::CrossAccountId,2038		property_keys: Vec<PropertyKey>,2039	) -> DispatchResultWithPostInfo;20402041	/// Set token properties.2042	///2043	/// The appropriate [`PropertyPermission`] for the token property2044	/// must be set with [`Self::set_token_property_permissions`].2045	///2046	/// * `sender` - Must be either the owner of the token or its admin.2047	/// * `token_id` - The token for which the properties are being set.2048	/// * `properties` - Properties to be set.2049	/// * `budget` - Budget for setting properties.2050	fn set_token_properties(2051		&self,2052		sender: T::CrossAccountId,2053		token_id: TokenId,2054		properties: Vec<Property>,2055		budget: &dyn Budget,2056	) -> DispatchResultWithPostInfo;20572058	/// Remove token properties.2059	///2060	/// The appropriate [`PropertyPermission`] for the token property2061	/// must be set with [`Self::set_token_property_permissions`].2062	///2063	/// * `sender` - Must be either the owner of the token or its admin.2064	/// * `token_id` - The token for which the properties are being remove.2065	/// * `property_keys` - Keys to remove corresponding properties.2066	/// * `budget` - Budget for removing properties.2067	fn delete_token_properties(2068		&self,2069		sender: T::CrossAccountId,2070		token_id: TokenId,2071		property_keys: Vec<PropertyKey>,2072		budget: &dyn Budget,2073	) -> DispatchResultWithPostInfo;20742075	/// Get token properties raw map.2076	///2077	/// * `token_id` - The token which properties are needed.2078	fn get_token_properties_raw(&self, token_id: TokenId) -> Option<TokenProperties>;20792080	/// Set token properties raw map.2081	///2082	/// * `token_id` - The token for which the properties are being set.2083	/// * `map` - The raw map containing the token's properties.2084	fn set_token_properties_raw(&self, token_id: TokenId, map: TokenProperties);20852086	/// Set token property permissions.2087	///2088	/// * `sender` - Must be either the owner of the token or its admin.2089	/// * `token_id` - The token for which the properties are being set.2090	/// * `property_permissions` - Property permissions to be set.2091	/// * `budget` - Budget for setting properties.2092	fn set_token_property_permissions(2093		&self,2094		sender: &T::CrossAccountId,2095		property_permissions: Vec<PropertyKeyPermission>,2096	) -> DispatchResultWithPostInfo;20972098	/// Transfer amount of token pieces.2099	///2100	/// * `sender` - Donor user.2101	/// * `to` - Recepient user.2102	/// * `token` - The token of which parts are being sent.2103	/// * `amount` - The number of parts of the token that will be transferred.2104	/// * `budget` - The maximum budget that can be spent on the transfer.2105	fn transfer(2106		&self,2107		sender: T::CrossAccountId,2108		to: T::CrossAccountId,2109		token: TokenId,2110		amount: u128,2111		budget: &dyn Budget,2112	) -> DispatchResultWithPostInfo;21132114	/// Grant access to another account to transfer parts of the token owned by the calling user via [Self::transfer_from].2115	///2116	/// * `sender` - The user who grants access to the token.2117	/// * `spender` - The user to whom the rights are granted.2118	/// * `token` - The token to which access is granted.2119	/// * `amount` - The amount of pieces that another user can dispose of.2120	fn approve(2121		&self,2122		sender: T::CrossAccountId,2123		spender: T::CrossAccountId,2124		token: TokenId,2125		amount: u128,2126	) -> DispatchResultWithPostInfo;21272128	/// Grant access to another account to transfer parts of the token owned by the calling user's eth mirror via [Self::transfer_from].2129	///2130	/// * `sender` - The user who grants access to the token.2131	/// * `from` - Spender's eth mirror.2132	/// * `to` - The user to whom the rights are granted.2133	/// * `token` - The token to which access is granted.2134	/// * `amount` - The amount of pieces that another user can dispose of.2135	fn approve_from(2136		&self,2137		sender: T::CrossAccountId,2138		from: T::CrossAccountId,2139		to: T::CrossAccountId,2140		token: TokenId,2141		amount: u128,2142	) -> DispatchResultWithPostInfo;21432144	/// Send parts of a token owned by another user.2145	///2146	/// Before calling this method, you must grant rights to the calling user via [`Self::approve`].2147	///2148	/// * `sender` - The user who must have access to the token (see [`Self::approve`]).2149	/// * `from` - The user who owns the token.2150	/// * `to` - Recepient user.2151	/// * `token` - The token of which parts are being sent.2152	/// * `amount` - The number of parts of the token that will be transferred.2153	/// * `budget` - The maximum budget that can be spent on the transfer.2154	fn transfer_from(2155		&self,2156		sender: T::CrossAccountId,2157		from: T::CrossAccountId,2158		to: T::CrossAccountId,2159		token: TokenId,2160		amount: u128,2161		budget: &dyn Budget,2162	) -> DispatchResultWithPostInfo;21632164	/// Burn parts of a token owned by another user.2165	///2166	/// Before calling this method, you must grant rights to the calling user via [`Self::approve`].2167	///2168	/// * `sender` - The user who must have access to the token (see [`Self::approve`]).2169	/// * `from` - The user who owns the token.2170	/// * `token` - The token of which parts are being sent.2171	/// * `amount` - The number of parts of the token that will be transferred.2172	/// * `budget` - The maximum budget that can be spent on the burn.2173	fn burn_from(2174		&self,2175		sender: T::CrossAccountId,2176		from: T::CrossAccountId,2177		token: TokenId,2178		amount: u128,2179		budget: &dyn Budget,2180	) -> DispatchResultWithPostInfo;21812182	/// Check permission to nest token.2183	///2184	/// * `sender` - The user who initiated the check.2185	/// * `from` - The token that is checked for embedding.2186	/// * `under` - Token under which to check.2187	/// * `budget` - The maximum budget that can be spent on the check.2188	fn check_nesting(2189		&self,2190		sender: &T::CrossAccountId,2191		from: (CollectionId, TokenId),2192		under: TokenId,2193		budget: &dyn Budget,2194	) -> DispatchResult;21952196	/// Nest one token into another.2197	///2198	/// * `under` - Token holder.2199	/// * `to_nest` - Nested token.2200	fn nest(&self, under: TokenId, to_nest: (CollectionId, TokenId));22012202	/// Unnest token.2203	///2204	/// * `under` - Token holder.2205	/// * `to_nest` - Token to unnest.2206	fn unnest(&self, under: TokenId, to_nest: (CollectionId, TokenId));22072208	/// Get all user tokens.2209	///2210	/// * `account` - Account for which you need to get tokens.2211	fn account_tokens(&self, account: T::CrossAccountId) -> Vec<TokenId>;22122213	/// Get all the tokens in the collection.2214	fn collection_tokens(&self) -> Vec<TokenId>;22152216	/// Check if the token exists.2217	///2218	/// * `token` - Id token to check.2219	fn token_exists(&self, token: TokenId) -> bool;22202221	/// Get the id of the last minted token.2222	fn last_token_id(&self) -> TokenId;22232224	/// Get the owner of the token.2225	///2226	/// * `token` - The token for which you need to find out the owner.2227	fn token_owner(&self, token: TokenId) -> Result<T::CrossAccountId, TokenOwnerError>;22282229	/// Checks if the `maybe_owner` is the indirect owner of the `token`.2230	///2231	/// * `token` - Id token to check.2232	/// * `maybe_owner` - The account to check.2233	/// * `nesting_budget` - A budget that can be spent on nesting tokens.2234	fn check_token_indirect_owner(2235		&self,2236		token: TokenId,2237		maybe_owner: &T::CrossAccountId,2238		nesting_budget: &dyn Budget,2239	) -> Result<bool, DispatchError>;22402241	/// Returns 10 tokens owners in no particular order.2242	///2243	/// * `token` - The token for which you need to find out the owners.2244	fn token_owners(&self, token: TokenId) -> Vec<T::CrossAccountId>;22452246	/// Get the value of the token property by key.2247	///2248	/// * `token` - Token with the property to get.2249	/// * `key` - Property name.2250	fn token_property(&self, token_id: TokenId, key: &PropertyKey) -> Option<PropertyValue>;22512252	/// Get a set of token properties by key vector.2253	///2254	/// * `token` - Token with the property to get.2255	/// * `keys` - Vector of property keys. If this parameter is [None](sp_std::result::Result),2256	/// then all properties are returned.2257	fn token_properties(&self, token: TokenId, keys: Option<Vec<PropertyKey>>) -> Vec<Property>;22582259	/// Amount of unique collection tokens2260	fn total_supply(&self) -> u32;22612262	/// Amount of different tokens account has.2263	///2264	/// * `account` - The account for which need to get the balance.2265	fn account_balance(&self, account: T::CrossAccountId) -> u32;22662267	/// Amount of specific token account have.2268	fn balance(&self, account: T::CrossAccountId, token: TokenId) -> u128;22692270	/// Amount of token pieces2271	fn total_pieces(&self, token: TokenId) -> Option<u128>;22722273	/// Get the number of parts of the token that a trusted user can manage.2274	///2275	/// * `sender` - Trusted user.2276	/// * `spender` - Owner of the token.2277	/// * `token` - The token for which to get the value.2278	fn allowance(2279		&self,2280		sender: T::CrossAccountId,2281		spender: T::CrossAccountId,2282		token: TokenId,2283	) -> u128;22842285	/// Get extension for RFT collection.2286	fn refungible_extensions(&self) -> Option<&dyn RefungibleExtensions<T>> {2287		None2288	}22892290	/// Get XCM extensions.2291	fn xcm_extensions(&self) -> Option<&dyn XcmExtensions<T>> {2292		None2293	}22942295	/// The `operator` is allowed to transfer all tokens of the `owner` on their behalf.2296	/// * `owner` - Token owner2297	/// * `operator` - Operator2298	/// * `approve` - Should operator status be granted or revoked?2299	fn set_allowance_for_all(2300		&self,2301		owner: T::CrossAccountId,2302		operator: T::CrossAccountId,2303		approve: bool,2304	) -> DispatchResultWithPostInfo;23052306	/// Tells whether the given `owner` approves the `operator`.2307	fn allowance_for_all(&self, owner: T::CrossAccountId, operator: T::CrossAccountId) -> bool;23082309	/// Repairs a possibly broken item.2310	fn repair_item(&self, token: TokenId) -> DispatchResultWithPostInfo;2311}23122313/// Extension for RFT collection.2314pub trait RefungibleExtensions<T>2315where2316	T: Config,2317{2318	/// Change the number of parts of the token.2319	///2320	/// When the value changes down, this function is equivalent to burning parts of the token.2321	///2322	/// * `sender` - The user calling the repartition operation. Must be the owner of the token.2323	/// * `token` - The token for which you want to change the number of parts.2324	/// * `amount` - The new value of the parts of the token.2325	fn repartition(2326		&self,2327		sender: &T::CrossAccountId,2328		token: TokenId,2329		amount: u128,2330	) -> DispatchResultWithPostInfo;2331}23322333/// XCM extensions for fungible and NFT collections2334pub trait XcmExtensions<T>2335where2336	T: Config,2337{2338	/// Does the token have children?2339	fn token_has_children(&self, _token: TokenId) -> bool {2340		false2341	}23422343	/// Create a collection's item using a transaction.2344	///2345	/// This function performs additional XCM-related checks before the actual creation.2346	#[transactional]2347	fn create_item(2348		&self,2349		depositor: &T::CrossAccountId,2350		to: T::CrossAccountId,2351		data: CreateItemData,2352		nesting_budget: &dyn Budget,2353	) -> Result<TokenId, DispatchError> {2354		if T::CrossTokenAddressMapping::is_token_address(&to) {2355			return unsupported!(T);2356		}23572358		self.create_item_internal(depositor, to, data, nesting_budget)2359	}23602361	/// Create a collection's item.2362	fn create_item_internal(2363		&self,2364		depositor: &T::CrossAccountId,2365		to: T::CrossAccountId,2366		data: CreateItemData,2367		nesting_budget: &dyn Budget,2368	) -> Result<TokenId, DispatchError>;23692370	/// Transfer an item from the `from` account to the `to` account using a transaction.2371	///2372	/// This function performs additional XCM-related checks before the actual transfer.2373	#[transactional]2374	fn transfer_item(2375		&self,2376		depositor: &T::CrossAccountId,2377		from: &T::CrossAccountId,2378		to: &T::CrossAccountId,2379		token: TokenId,2380		amount: u128,2381		nesting_budget: &dyn Budget,2382	) -> DispatchResult {2383		if T::CrossTokenAddressMapping::is_token_address(to) {2384			return unsupported!(T);2385		}23862387		self.transfer_item_internal(depositor, from, to, token, amount, nesting_budget)2388	}23892390	/// Transfer an item from the `from` account to the `to` account.2391	fn transfer_item_internal(2392		&self,2393		depositor: &T::CrossAccountId,2394		from: &T::CrossAccountId,2395		to: &T::CrossAccountId,2396		token: TokenId,2397		amount: u128,2398		nesting_budget: &dyn Budget,2399	) -> DispatchResult;24002401	/// Burn a collection's item using a transaction.2402	#[transactional]2403	fn burn_item(&self, from: T::CrossAccountId, token: TokenId, amount: u128) -> DispatchResult {2404		self.burn_item_internal(from, token, amount)2405	}24062407	/// Burn a collection's item.2408	fn burn_item_internal(2409		&self,2410		from: T::CrossAccountId,2411		token: TokenId,2412		amount: u128,2413	) -> DispatchResult;2414}24152416/// Merge [`DispatchResult`] with [`Weight`] into [`DispatchResultWithPostInfo`].2417///2418/// Used for [`CommonCollectionOperations`] implementations and flexible enough to do so.2419pub fn with_weight(res: DispatchResult, weight: Weight) -> DispatchResultWithPostInfo {2420	let post_info = PostDispatchInfo {2421		actual_weight: Some(weight),2422		pays_fee: Pays::Yes,2423	};2424	match res {2425		Ok(()) => Ok(post_info),2426		Err(error) => Err(DispatchErrorWithPostInfo { post_info, error }),2427	}2428}24292430impl<T: Config> From<PropertiesError> for Error<T> {2431	fn from(error: PropertiesError) -> Self {2432		match error {2433			PropertiesError::NoSpaceForProperty => Self::NoSpaceForProperty,2434			PropertiesError::PropertyLimitReached => Self::PropertyLimitReached,2435			PropertiesError::InvalidCharacterInPropertyKey => Self::InvalidCharacterInPropertyKey,2436			PropertiesError::PropertyKeyIsTooLong => Self::PropertyKeyIsTooLong,2437			PropertiesError::EmptyPropertyKey => Self::EmptyPropertyKey,2438		}2439	}2440}24412442/// The type-safe interface for writing properties (setting or deleting) to tokens.2443/// It has two distinct implementations for newly created tokens and existing ones.2444///2445/// This type utilizes the lazy evaluation to avoid repeating the computation2446/// of several performance-heavy or PoV-heavy tasks,2447/// such as checking the indirect ownership or reading the token property permissions.2448pub struct PropertyWriter<'a, WriterVariant, T, Handle> {2449	collection: &'a Handle,2450	collection_lazy_info: PropertyWriterLazyCollectionInfo<'a>,2451	_phantom: PhantomData<(T, WriterVariant)>,2452}24532454impl<'a, T, Handle, WriterVariant> PropertyWriter<'a, WriterVariant, T, Handle>2455where2456	T: Config,2457	Handle: CommonCollectionOperations<T> + Deref<Target = CollectionHandle<T>>,2458{2459	fn internal_write_token_properties(2460		&mut self,2461		token_id: TokenId,2462		mut token_lazy_info: PropertyWriterLazyTokenInfo,2463		properties_updates: impl Iterator<Item = (PropertyKey, Option<PropertyValue>)>,2464		log: evm_coder::ethereum::Log,2465	) -> DispatchResult {2466		for (key, value) in properties_updates {2467			let permission = self2468				.collection_lazy_info2469				.property_permissions2470				.value()2471				.get(&key)2472				.cloned()2473				.unwrap_or_else(PropertyPermission::none);24742475			match permission {2476				PropertyPermission { mutable: false, .. }2477					if token_lazy_info2478						.stored_properties2479						.value()2480						.get(&key)2481						.is_some() =>2482				{2483					return Err(<Error<T>>::NoPermission.into());2484				}24852486				PropertyPermission {2487					collection_admin,2488					token_owner,2489					..2490				} => check_token_permissions::<T>(2491					collection_admin,2492					token_owner,2493					&mut self.collection_lazy_info.is_collection_admin,2494					&mut token_lazy_info.is_token_owner,2495					&mut token_lazy_info.is_token_exist,2496				)?,2497			}24982499			match value {2500				Some(value) => {2501					token_lazy_info2502						.stored_properties2503						.value_mut()2504						.try_set(key.clone(), value)2505						.map_err(<Error<T>>::from)?;25062507					<Pallet<T>>::deposit_event(Event::TokenPropertySet(2508						self.collection.id,2509						token_id,2510						key,2511					));2512				}2513				None => {2514					token_lazy_info2515						.stored_properties2516						.value_mut()2517						.remove(&key)2518						.map_err(<Error<T>>::from)?;25192520					<Pallet<T>>::deposit_event(Event::TokenPropertyDeleted(2521						self.collection.id,2522						token_id,2523						key,2524					));2525				}2526			}2527		}25282529		let properties_changed = token_lazy_info.stored_properties.has_value();2530		if properties_changed {2531			<PalletEvm<T>>::deposit_log(log);25322533			self.collection2534				.set_token_properties_raw(token_id, token_lazy_info.stored_properties.into_inner());2535		}25362537		Ok(())2538	}2539}25402541/// A helper structure for the [`PropertyWriter`] that holds2542/// the collection-related info. The info is loaded using lazy evaluation.2543/// This info is common for any token for which we write properties.2544pub struct PropertyWriterLazyCollectionInfo<'a> {2545	is_collection_admin: LazyValue<'a, bool>,2546	property_permissions: LazyValue<'a, PropertiesPermissionMap>,2547}25482549/// A helper structure for the [`PropertyWriter`] that holds2550/// the token-related info. The info is loaded using lazy evaluation.2551pub struct PropertyWriterLazyTokenInfo<'a> {2552	is_token_exist: LazyValue<'a, bool>,2553	is_token_owner: LazyValue<'a, Result<bool, DispatchError>>,2554	stored_properties: LazyValue<'a, TokenProperties>,2555}25562557impl<'a> PropertyWriterLazyTokenInfo<'a> {2558	/// Create a lazy token info.2559	pub fn new(2560		check_token_exist: impl FnOnce() -> bool + 'a,2561		check_token_owner: impl FnOnce() -> Result<bool, DispatchError> + 'a,2562		get_token_properties: impl FnOnce() -> TokenProperties + 'a,2563	) -> Self {2564		Self {2565			is_token_exist: LazyValue::new(check_token_exist),2566			is_token_owner: LazyValue::new(check_token_owner),2567			stored_properties: LazyValue::new(get_token_properties),2568		}2569	}2570}25712572/// A marker structure that enables the writer implementation2573/// to provide the interface to write properties to **newly created** tokens.2574pub struct NewTokenPropertyWriter<T>(PhantomData<T>);2575impl<T: Config> NewTokenPropertyWriter<T> {2576	/// Creates a [`PropertyWriter`] for **newly created** tokens.2577	pub fn new<'a, Handle>(2578		collection: &'a Handle,2579		sender: &'a T::CrossAccountId,2580	) -> PropertyWriter<'a, Self, T, Handle>2581	where2582		T: Config,2583		Handle: CommonCollectionOperations<T> + Deref<Target = CollectionHandle<T>>,2584	{2585		PropertyWriter {2586			collection,2587			collection_lazy_info: PropertyWriterLazyCollectionInfo {2588				is_collection_admin: LazyValue::new(|| collection.is_owner_or_admin(sender)),2589				property_permissions: LazyValue::new(|| {2590					<Pallet<T>>::property_permissions(collection.id)2591				}),2592			},2593			_phantom: PhantomData,2594		}2595	}2596}25972598impl<'a, T, Handle> PropertyWriter<'a, NewTokenPropertyWriter<T>, T, Handle>2599where2600	T: Config,2601	Handle: CommonCollectionOperations<T> + Deref<Target = CollectionHandle<T>>,2602{2603	/// A function to write properties to a **newly created** token.2604	pub fn write_token_properties(2605		&mut self,2606		mint_target_is_sender: bool,2607		token_id: TokenId,2608		properties_updates: impl Iterator<Item = Property>,2609		log: evm_coder::ethereum::Log,2610	) -> DispatchResult {2611		let check_token_exist = || {2612			debug_assert!(self.collection.token_exists(token_id));2613			true2614		};26152616		let check_token_owner = || Ok(mint_target_is_sender);26172618		let get_token_properties = || {2619			debug_assert!(self.collection.get_token_properties_raw(token_id).is_none());2620			TokenProperties::new()2621		};26222623		self.internal_write_token_properties(2624			token_id,2625			PropertyWriterLazyTokenInfo::new(2626				check_token_exist,2627				check_token_owner,2628				get_token_properties,2629			),2630			properties_updates.map(|p| (p.key, Some(p.value))),2631			log,2632		)2633	}2634}26352636/// A marker structure that enables the writer implementation2637/// to provide the interface to write properties to **already existing** tokens.2638pub struct ExistingTokenPropertyWriter<T>(PhantomData<T>);2639impl<T: Config> ExistingTokenPropertyWriter<T> {2640	/// Creates a [`PropertyWriter`] for **already existing** tokens.2641	pub fn new<'a, Handle>(2642		collection: &'a Handle,2643		sender: &'a T::CrossAccountId,2644	) -> PropertyWriter<'a, Self, T, Handle>2645	where2646		Handle: CommonCollectionOperations<T> + Deref<Target = CollectionHandle<T>>,2647	{2648		PropertyWriter {2649			collection,2650			collection_lazy_info: PropertyWriterLazyCollectionInfo {2651				is_collection_admin: LazyValue::new(|| collection.is_owner_or_admin(sender)),2652				property_permissions: LazyValue::new(|| {2653					<Pallet<T>>::property_permissions(collection.id)2654				}),2655			},2656			_phantom: PhantomData,2657		}2658	}2659}26602661impl<'a, T, Handle> PropertyWriter<'a, ExistingTokenPropertyWriter<T>, T, Handle>2662where2663	T: Config,2664	Handle: CommonCollectionOperations<T> + Deref<Target = CollectionHandle<T>>,2665{2666	/// A function to write properties to an **already existing** token.2667	pub fn write_token_properties(2668		&mut self,2669		sender: &T::CrossAccountId,2670		token_id: TokenId,2671		properties_updates: impl Iterator<Item = (PropertyKey, Option<PropertyValue>)>,2672		nesting_budget: &dyn Budget,2673		log: evm_coder::ethereum::Log,2674	) -> DispatchResult {2675		let check_token_exist = || self.collection.token_exists(token_id);2676		let check_token_owner = || {2677			self.collection2678				.check_token_indirect_owner(token_id, sender, nesting_budget)2679		};2680		let get_token_properties = || {2681			self.collection2682				.get_token_properties_raw(token_id)2683				.unwrap_or_default()2684		};26852686		self.internal_write_token_properties(2687			token_id,2688			PropertyWriterLazyTokenInfo::new(2689				check_token_exist,2690				check_token_owner,2691				get_token_properties,2692			),2693			properties_updates,2694			log,2695		)2696	}2697}26982699/// A marker structure that enables the writer implementation2700/// to benchmark the token properties writing.2701#[cfg(feature = "runtime-benchmarks")]2702pub struct BenchmarkPropertyWriter<T>(PhantomData<T>);27032704#[cfg(feature = "runtime-benchmarks")]2705impl<T: Config> BenchmarkPropertyWriter<T> {2706	/// Creates a [`PropertyWriter`] for benchmarking tokens properties writing.2707	pub fn new<'a, Handle>(2708		collection: &'a Handle,2709		collection_lazy_info: PropertyWriterLazyCollectionInfo<'a>,2710	) -> PropertyWriter<'a, Self, T, Handle>2711	where2712		Handle: CommonCollectionOperations<T> + Deref<Target = CollectionHandle<T>>,2713	{2714		PropertyWriter {2715			collection,2716			collection_lazy_info,2717			_phantom: PhantomData,2718		}2719	}27202721	/// Load the [`PropertyWriterLazyCollectionInfo`] from the storage.2722	pub fn load_collection_info<Handle>(2723		collection_handle: &Handle,2724		sender: &T::CrossAccountId,2725	) -> PropertyWriterLazyCollectionInfo<'static>2726	where2727		Handle: Deref<Target = CollectionHandle<T>>,2728	{2729		let is_collection_admin = collection_handle.is_owner_or_admin(sender);2730		let property_permissions = <Pallet<T>>::property_permissions(collection_handle.id);27312732		PropertyWriterLazyCollectionInfo {2733			is_collection_admin: LazyValue::new(move || is_collection_admin),2734			property_permissions: LazyValue::new(move || property_permissions),2735		}2736	}27372738	/// Load the [`PropertyWriterLazyTokenInfo`] with token properties from the storage.2739	pub fn load_token_properties<Handle>(2740		collection: &Handle,2741		token_id: TokenId,2742	) -> PropertyWriterLazyTokenInfo2743	where2744		Handle: CommonCollectionOperations<T>,2745	{2746		let stored_properties = collection2747			.get_token_properties_raw(token_id)2748			.unwrap_or_default();27492750		PropertyWriterLazyTokenInfo {2751			is_token_exist: LazyValue::new(|| true),2752			is_token_owner: LazyValue::new(|| Ok(true)),2753			stored_properties: LazyValue::new(move || stored_properties),2754		}2755	}2756}27572758#[cfg(feature = "runtime-benchmarks")]2759impl<'a, T, Handle> PropertyWriter<'a, BenchmarkPropertyWriter<T>, T, Handle>2760where2761	T: Config,2762	Handle: CommonCollectionOperations<T> + Deref<Target = CollectionHandle<T>>,2763{2764	/// A function to benchmark the writing of token properties.2765	pub fn write_token_properties(2766		&mut self,2767		token_id: TokenId,2768		properties_updates: impl Iterator<Item = Property>,2769		log: evm_coder::ethereum::Log,2770	) -> DispatchResult {2771		let check_token_exist = || true;2772		let check_token_owner = || Ok(true);2773		let get_token_properties = TokenProperties::new;27742775		self.internal_write_token_properties(2776			token_id,2777			PropertyWriterLazyTokenInfo::new(2778				check_token_exist,2779				check_token_owner,2780				get_token_properties,2781			),2782			properties_updates.map(|p| (p.key, Some(p.value))),2783			log,2784		)2785	}2786}27872788/// Computes the weight of writing properties to tokens.2789/// * `properties_nums` - The properties num of each created token.2790/// * `per_token_weight_weight` - The function to obtain the weight2791/// of writing properties from a token's properties num.2792pub fn write_token_properties_total_weight<T: Config, I: Fn(u32) -> Weight>(2793	properties_nums: impl Iterator<Item = u32>,2794	per_token_weight: I,2795) -> Weight {2796	let mut weight = properties_nums2797		.filter_map(|properties_num| {2798			if properties_num > 0 {2799				Some(per_token_weight(properties_num))2800			} else {2801				None2802			}2803		})2804		.fold(Weight::zero(), |a, b| a.saturating_add(b));28052806	if !weight.is_zero() {2807		// If we are here, it means the token properties were written at least once.2808		// Because of that, some common collection data was also loaded; we must add this weight.2809		// However, this common data was loaded only once, which is guaranteed by the `PropertyWriter`.28102811		weight = weight.saturating_add(<SelfWeightOf<T>>::property_writer_load_collection_info());2812	}28132814	weight2815}28162817#[cfg(any(feature = "tests", test))]2818#[allow(missing_docs)]2819pub mod tests {2820	use crate::{Config, DispatchError, DispatchResult, LazyValue};28212822	const fn to_bool(u: u8) -> bool {2823		u != 02824	}28252826	#[derive(Debug)]2827	pub struct TestCase {2828		pub collection_admin: bool,2829		pub is_collection_admin: bool,2830		pub token_owner: bool,2831		pub is_token_owner: bool,2832		pub no_permission: bool,2833	}28342835	impl TestCase {2836		const fn new(2837			collection_admin: u8,2838			is_collection_admin: u8,2839			token_owner: u8,2840			is_token_owner: u8,2841			no_permission: u8,2842		) -> Self {2843			Self {2844				collection_admin: to_bool(collection_admin),2845				is_collection_admin: to_bool(is_collection_admin),2846				token_owner: to_bool(token_owner),2847				is_token_owner: to_bool(is_token_owner),2848				no_permission: to_bool(no_permission),2849			}2850		}2851	}28522853	#[rustfmt::skip]2854	pub const TABLE: [TestCase; 16] = [2855		//                    ┌╴collection_admin2856		//                    │  ┌╴is_collection_admin2857		//                    │  │   ┌╴token_owner2858		//                    │  │   │  ┌╴is_token_ownership2859		//                    │  │   │  │   ┌╴no_permission2860		/*  0*/ TestCase::new(0, 0,  0, 0,  1),2861		/*  1*/ TestCase::new(0, 0,  0, 1,  1),2862		/*  2*/ TestCase::new(0, 0,  1, 0,  1),2863		/*  3*/ TestCase::new(0, 0,  1, 1,  0),2864		/*  4*/ TestCase::new(0, 1,  0, 0,  1),2865		/*  5*/ TestCase::new(0, 1,  0, 1,  1),2866		/*  6*/ TestCase::new(0, 1,  1, 0,  1),2867		/*  7*/ TestCase::new(0, 1,  1, 1,  0),2868		/*  8*/ TestCase::new(1, 0,  0, 0,  1),2869		/*  9*/ TestCase::new(1, 0,  0, 1,  1),2870		/* 10*/ TestCase::new(1, 0,  1, 0,  1),2871		/* 11*/ TestCase::new(1, 0,  1, 1,  0),2872		/* 12*/ TestCase::new(1, 1,  0, 0,  0),2873		/* 13*/ TestCase::new(1, 1,  0, 1,  0),2874		/* 14*/ TestCase::new(1, 1,  1, 0,  0),2875		/* 15*/ TestCase::new(1, 1,  1, 1,  0),2876	];28772878	pub fn check_token_permissions<T: Config>(2879		collection_admin_permitted: bool,2880		token_owner_permitted: bool,2881		is_collection_admin: &mut LazyValue<bool>,2882		check_token_ownership: &mut LazyValue<Result<bool, DispatchError>>,2883		check_token_existence: &mut LazyValue<bool>,2884	) -> DispatchResult {2885		crate::check_token_permissions::<T>(2886			collection_admin_permitted,2887			token_owner_permitted,2888			is_collection_admin,2889			check_token_ownership,2890			check_token_existence,2891		)2892	}2893}
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, mapping::TokenAddressMapping, AccessMode, Collection, CollectionId,84	CollectionLimits, CollectionMode, CollectionPermissions,85	CollectionProperties as CollectionPropertiesT, CollectionStats, CreateCollectionData,86	CreateItemData, CreateItemExData, PhantomType, PropertiesError, PropertiesPermissionMap,87	Property, PropertyKey, PropertyKeyPermission, PropertyPermission, PropertyScope, PropertyValue,88	RpcCollection, RpcCollectionFlags, SponsoringRateLimit, SponsorshipState, TokenChild,89	TokenData, TokenId, TokenOwnerError, TokenProperties, TrySetProperty, COLLECTION_ADMINS_LIMIT,90	COLLECTION_NUMBER_LIMIT, CUSTOM_DATA_LIMIT, FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,91	MAX_SPONSOR_TIMEOUT, MAX_TOKEN_OWNERSHIP, MAX_TOKEN_PREFIX_LENGTH,92	NFT_SPONSOR_TRANSFER_TIMEOUT, REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,93};94use up_pov_estimate_rpc::PovInfo;9596#[cfg(feature = "runtime-benchmarks")]97pub mod benchmarking;98pub mod dispatch;99pub mod erc;100pub mod eth;101pub mod helpers;102#[allow(missing_docs)]103pub mod weights;104105use weights::WeightInfo;106107/// Weight info.108pub type SelfWeightOf<T> = <T as Config>::WeightInfo;109110/// Collection handle contains information about collection data and id.111/// Also provides functionality to count consumed gas.112///113/// CollectionHandle is used as a generic wrapper for collections of all types (except native fungible).114/// It allows to perform common operations and queries on any collection type,115/// both completely general for all, as well as their respective implementations of [`CommonCollectionOperations`].116#[must_use = "Should call submit_logs or save, otherwise some data will be lost for evm side"]117pub struct CollectionHandle<T: Config> {118	/// Collection id119	pub id: CollectionId,120	collection: Collection<T::AccountId>,121	/// Substrate recorder for counting consumed gas122	pub recorder: SubstrateRecorder<T>,123}124125impl<T: Config> WithRecorder<T> for CollectionHandle<T> {126	fn recorder(&self) -> &SubstrateRecorder<T> {127		&self.recorder128	}129	fn into_recorder(self) -> SubstrateRecorder<T> {130		self.recorder131	}132}133134impl<T: Config> CollectionHandle<T> {135	/// Same as [CollectionHandle::new] but with an explicit gas limit.136	pub fn new_with_gas_limit(id: CollectionId, gas_limit: u64) -> Option<Self> {137		Self::new_with_recorder(id, SubstrateRecorder::new(gas_limit))138	}139140	/// Same as [CollectionHandle::new] but with an existed [`SubstrateRecorder`].141	pub fn new_with_recorder(id: CollectionId, recorder: SubstrateRecorder<T>) -> Option<Self> {142		<CollectionById<T>>::get(id).map(|collection| Self {143			id,144			collection,145			recorder,146		})147	}148149	/// Retrives collection data from storage and creates collection handle with default parameters.150	/// If collection not found return `None`151	pub fn new(id: CollectionId) -> Option<Self> {152		Self::new_with_gas_limit(id, u64::MAX)153	}154155	/// Same as [`CollectionHandle::new`] but if collection not found [CollectionNotFound](Error::CollectionNotFound) returned.156	pub fn try_get(id: CollectionId) -> Result<Self, DispatchError> {157		Ok(Self::new(id).ok_or(<Error<T>>::CollectionNotFound)?)158	}159160	/// Consume gas for reading.161	pub fn consume_store_reads(162		&self,163		reads: u64,164	) -> pallet_evm_coder_substrate::execution::Result<()> {165		self.recorder().consume_store_reads(reads)166	}167168	/// Consume gas for writing.169	pub fn consume_store_writes(170		&self,171		writes: u64,172	) -> pallet_evm_coder_substrate::execution::Result<()> {173		self.recorder().consume_store_writes(writes)174	}175176	/// Consume gas for reading and writing.177	pub fn consume_store_reads_and_writes(178		&self,179		reads: u64,180		writes: u64,181	) -> pallet_evm_coder_substrate::execution::Result<()> {182		self.recorder()183			.consume_store_reads_and_writes(reads, writes)184	}185186	/// Save collection to storage.187	pub fn save(&self) -> DispatchResult {188		<CollectionById<T>>::insert(self.id, &self.collection);189		Ok(())190	}191192	/// Set collection sponsor.193	///194	/// Unique collections allows sponsoring for certain actions.195	/// This method allows you to set the sponsor of the collection.196	/// In order for sponsorship to become active, it must be confirmed through [`Self::confirm_sponsorship`].197	pub fn set_sponsor(198		&mut self,199		sender: &T::CrossAccountId,200		sponsor: T::AccountId,201	) -> DispatchResult {202		self.check_is_internal()?;203		self.check_is_owner_or_admin(sender)?;204205		self.collection.sponsorship = SponsorshipState::Unconfirmed(sponsor.clone());206207		<Pallet<T>>::deposit_event(Event::<T>::CollectionSponsorSet(self.id, sponsor));208		<PalletEvm<T>>::deposit_log(209			erc::CollectionHelpersEvents::CollectionChanged {210				collection_id: eth::collection_id_to_address(self.id),211			}212			.to_log(T::ContractAddress::get()),213		);214215		self.save()216	}217218	/// Force set `sponsor`.219	///220	/// Differs from [`set_sponsor`][`Self::set_sponsor`] in that confirmation221	/// from the `sponsor` is not required.222	///223	/// # Arguments224	///225	/// * `sponsor`: ID of the account of the sponsor-to-be.226	pub fn force_set_sponsor(&mut self, sponsor: T::AccountId) -> DispatchResult {227		self.check_is_internal()?;228229		self.collection.sponsorship = SponsorshipState::Confirmed(sponsor.clone());230231		<Pallet<T>>::deposit_event(Event::<T>::CollectionSponsorSet(self.id, sponsor.clone()));232		<Pallet<T>>::deposit_event(Event::<T>::SponsorshipConfirmed(self.id, sponsor));233		<PalletEvm<T>>::deposit_log(234			erc::CollectionHelpersEvents::CollectionChanged {235				collection_id: eth::collection_id_to_address(self.id),236			}237			.to_log(T::ContractAddress::get()),238		);239240		self.save()241	}242243	/// Confirm sponsorship244	///245	/// In order for the sponsorship to become active, the user set as the sponsor must confirm their participation.246	/// Before confirming sponsorship, the user must be specified as the sponsor of the collection via [`Self::set_sponsor`].247	pub fn confirm_sponsorship(&mut self, sender: &T::AccountId) -> DispatchResult {248		self.check_is_internal()?;249		ensure!(250			self.collection.sponsorship.pending_sponsor() == Some(sender),251			Error::<T>::ConfirmSponsorshipFail252		);253254		self.collection.sponsorship = SponsorshipState::Confirmed(sender.clone());255256		<Pallet<T>>::deposit_event(Event::<T>::SponsorshipConfirmed(self.id, sender.clone()));257		<PalletEvm<T>>::deposit_log(258			erc::CollectionHelpersEvents::CollectionChanged {259				collection_id: eth::collection_id_to_address(self.id),260			}261			.to_log(T::ContractAddress::get()),262		);263264		self.save()265	}266267	/// Remove collection sponsor.268	pub fn remove_sponsor(&mut self, sender: &T::CrossAccountId) -> DispatchResult {269		self.check_is_internal()?;270		self.check_is_owner_or_admin(sender)?;271272		self.collection.sponsorship = SponsorshipState::Disabled;273274		<Pallet<T>>::deposit_event(Event::<T>::CollectionSponsorRemoved(self.id));275		<PalletEvm<T>>::deposit_log(276			erc::CollectionHelpersEvents::CollectionChanged {277				collection_id: eth::collection_id_to_address(self.id),278			}279			.to_log(T::ContractAddress::get()),280		);281		self.save()282	}283284	/// Force remove `sponsor`.285	///286	/// Differs from `remove_sponsor` in that287	/// it doesn't require consent from the `owner` of the collection.288	pub fn force_remove_sponsor(&mut self) -> DispatchResult {289		self.check_is_internal()?;290291		self.collection.sponsorship = SponsorshipState::Disabled;292293		<Pallet<T>>::deposit_event(Event::<T>::CollectionSponsorRemoved(self.id));294		<PalletEvm<T>>::deposit_log(295			erc::CollectionHelpersEvents::CollectionChanged {296				collection_id: eth::collection_id_to_address(self.id),297			}298			.to_log(T::ContractAddress::get()),299		);300		self.save()301	}302303	/// Checks that the collection was created with, and must be operated upon through **Unique API**.304	/// Now check only the `external` flag and if it's **true**, then return [`Error::CollectionIsExternal`] error.305	pub fn check_is_internal(&self) -> DispatchResult {306		if self.flags.external {307			return Err(<Error<T>>::CollectionIsExternal)?;308		}309310		Ok(())311	}312313	/// Checks that the collection was created with, and must be operated upon through an **assimilated API**.314	/// Now check only the `external` flag and if it's **false**, then return [`Error::CollectionIsInternal`] error.315	pub fn check_is_external(&self) -> DispatchResult {316		if !self.flags.external {317			return Err(<Error<T>>::CollectionIsInternal)?;318		}319320		Ok(())321	}322}323324impl<T: Config> Deref for CollectionHandle<T> {325	type Target = Collection<T::AccountId>;326327	fn deref(&self) -> &Self::Target {328		&self.collection329	}330}331332impl<T: Config> DerefMut for CollectionHandle<T> {333	fn deref_mut(&mut self) -> &mut Self::Target {334		&mut self.collection335	}336}337338impl<T: Config> CollectionHandle<T> {339	/// Checks if the `user` is the owner of the collection.340	pub fn check_is_owner(&self, user: &T::CrossAccountId) -> DispatchResult {341		ensure!(*user.as_sub() == self.owner, <Error<T>>::NoPermission);342		Ok(())343	}344345	/// Returns **true** if the `user` is the owner or administrator of the collection.346	pub fn is_owner_or_admin(&self, user: &T::CrossAccountId) -> bool {347		*user.as_sub() == self.owner || <IsAdmin<T>>::get((self.id, user))348	}349350	/// Checks if the `user` is the owner or administrator of the collection.351	pub fn check_is_owner_or_admin(&self, user: &T::CrossAccountId) -> DispatchResult {352		ensure!(self.is_owner_or_admin(user), <Error<T>>::NoPermission);353		Ok(())354	}355356	/// Returns **true** if357	/// * the `user`is a collection owner or admin358	/// * the collection limits allow the owner/admins to transfer/burn any collection token359	pub fn ignores_token_restrictions(&self, user: &T::CrossAccountId) -> bool {360		self.limits.owner_can_transfer() && self.is_owner_or_admin(user)361	}362363	/// Return **true** if `user` does not have enough token parts, and he can ignore such restrictions.364	pub fn ignores_owned_amount(&self, user: &T::CrossAccountId) -> bool {365		self.limits.owner_can_transfer() && self.is_owner_or_admin(user)366	}367368	/// Checks if the user is in the allow list. If not [Error::AddressNotInAllowlist] returns.369	pub fn check_allowlist(&self, user: &T::CrossAccountId) -> DispatchResult {370		ensure!(371			<Allowlist<T>>::get((self.id, user)),372			<Error<T>>::AddressNotInAllowlist373		);374		Ok(())375	}376377	/// Changes collection owner to another account378	/// #### Store read/writes379	/// 1 writes380	pub fn change_owner(381		&mut self,382		caller: T::CrossAccountId,383		new_owner: T::CrossAccountId,384	) -> DispatchResult {385		self.check_is_internal()?;386		self.check_is_owner(&caller)?;387		self.collection.owner = new_owner.as_sub().clone();388389		<Pallet<T>>::deposit_event(Event::<T>::CollectionOwnerChanged(390			self.id,391			new_owner.as_sub().clone(),392		));393		<PalletEvm<T>>::deposit_log(394			erc::CollectionHelpersEvents::CollectionChanged {395				collection_id: eth::collection_id_to_address(self.id),396			}397			.to_log(T::ContractAddress::get()),398		);399400		self.save()401	}402}403404#[frame_support::pallet]405pub mod pallet {406407	use dispatch::CollectionDispatch;408	use frame_support::{409		pallet_prelude::*, storage::Key, traits::StorageVersion, Blake2_128Concat,410	};411	use scale_info::TypeInfo;412	use up_data_structs::{mapping::TokenAddressMapping, TokenId};413	use weights::WeightInfo;414415	use super::*;416417	#[pallet::config]418	pub trait Config:419		frame_system::Config + pallet_evm_coder_substrate::Config + pallet_evm::Config + TypeInfo420	{421		/// Weight information for functions of this pallet.422		type WeightInfo: WeightInfo;423424		/// Events compatible with [`frame_system::Config::Event`].425		type RuntimeEvent: IsType<<Self as frame_system::Config>::RuntimeEvent> + From<Event<Self>>;426427		/// Handler of accounts and payment.428		type Currency: Balanced<Self::AccountId> + Inspect<Self::AccountId>;429430		/// Set price to create a collection.431		#[pallet::constant]432		type CollectionCreationPrice: Get<433			<<Self as Config>::Currency as Inspect<Self::AccountId>>::Balance,434		>;435436		/// Dispatcher of operations on collections.437		type CollectionDispatch: CollectionDispatch<Self>;438439		/// Account which holds the chain's treasury.440		type TreasuryAccountId: Get<Self::AccountId>;441442		/// Address under which the CollectionHelper contract would be available.443		#[pallet::constant]444		type ContractAddress: Get<H160>;445446		/// Mapper for token addresses to Ethereum addresses.447		type EvmTokenAddressMapping: TokenAddressMapping<H160>;448449		/// Mapper for token addresses to [`CrossAccountId`].450		type CrossTokenAddressMapping: TokenAddressMapping<Self::CrossAccountId>;451	}452453	const STORAGE_VERSION: StorageVersion = StorageVersion::new(1);454	/// Collection id for native fungible collction.455	pub const NATIVE_FUNGIBLE_COLLECTION_ID: CollectionId = CollectionId(0);456457	#[pallet::pallet]458	#[pallet::storage_version(STORAGE_VERSION)]459	pub struct Pallet<T>(_);460461	#[pallet::extra_constants]462	impl<T: Config> Pallet<T> {463		/// Maximum admins per collection.464		pub fn collection_admins_limit() -> u32 {465			COLLECTION_ADMINS_LIMIT466		}467	}468469	#[pallet::genesis_config]470	pub struct GenesisConfig<T>(PhantomData<T>);471472	impl<T: Config> Default for GenesisConfig<T> {473		fn default() -> Self {474			Self(Default::default())475		}476	}477478	#[pallet::genesis_build]479	impl<T: Config> BuildGenesisConfig for GenesisConfig<T> {480		fn build(&self) {481			StorageVersion::new(1).put::<Pallet<T>>();482		}483	}484485	impl<T: Config> Pallet<T> {486		/// Helper function that handles deposit events487		pub fn deposit_event(event: Event<T>) {488			let event = <T as Config>::RuntimeEvent::from(event);489			let event = event.into();490			<frame_system::Pallet<T>>::deposit_event(event)491		}492	}493494	#[pallet::event]495	pub enum Event<T: Config> {496		/// New collection was created497		CollectionCreated(498			/// Globally unique identifier of newly created collection.499			CollectionId,500			/// [`CollectionMode`] converted into _u8_.501			u8,502			/// Collection owner.503			T::AccountId,504		),505506		/// New collection was destroyed507		CollectionDestroyed(508			/// Globally unique identifier of collection.509			CollectionId,510		),511512		/// New item was created.513		ItemCreated(514			/// Id of the collection where item was created.515			CollectionId,516			/// Id of an item. Unique within the collection.517			TokenId,518			/// Owner of newly created item519			T::CrossAccountId,520			/// Always 1 for NFT521			u128,522		),523524		/// Collection item was burned.525		ItemDestroyed(526			/// Id of the collection where item was destroyed.527			CollectionId,528			/// Identifier of burned NFT.529			TokenId,530			/// Which user has destroyed its tokens.531			T::CrossAccountId,532			/// Amount of token pieces destroed. Always 1 for NFT.533			u128,534		),535536		/// Item was transferred537		Transfer(538			/// Id of collection to which item is belong.539			CollectionId,540			/// Id of an item.541			TokenId,542			/// Original owner of item.543			T::CrossAccountId,544			/// New owner of item.545			T::CrossAccountId,546			/// Amount of token pieces transfered. Always 1 for NFT.547			u128,548		),549550		/// Amount pieces of token owned by `sender` was approved for `spender`.551		Approved(552			/// Id of collection to which item is belong.553			CollectionId,554			/// Id of an item.555			TokenId,556			/// Original owner of item.557			T::CrossAccountId,558			/// Id for which the approval was granted.559			T::CrossAccountId,560			/// Amount of token pieces transfered. Always 1 for NFT.561			u128,562		),563564		/// A `sender` approves operations on all owned tokens for `spender`.565		ApprovedForAll(566			/// Id of collection to which item is belong.567			CollectionId,568			/// Owner of a wallet.569			T::CrossAccountId,570			/// Id for which operator status was granted or rewoked.571			T::CrossAccountId,572			/// Is operator status granted or revoked?573			bool,574		),575576		/// The colletion property has been added or edited.577		CollectionPropertySet(578			/// Id of collection to which property has been set.579			CollectionId,580			/// The property that was set.581			PropertyKey,582		),583584		/// The property has been deleted.585		CollectionPropertyDeleted(586			/// Id of collection to which property has been deleted.587			CollectionId,588			/// The property that was deleted.589			PropertyKey,590		),591592		/// The token property has been added or edited.593		TokenPropertySet(594			/// Identifier of the collection whose token has the property set.595			CollectionId,596			/// The token for which the property was set.597			TokenId,598			/// The property that was set.599			PropertyKey,600		),601602		/// The token property has been deleted.603		TokenPropertyDeleted(604			/// Identifier of the collection whose token has the property deleted.605			CollectionId,606			/// The token for which the property was deleted.607			TokenId,608			/// The property that was deleted.609			PropertyKey,610		),611612		/// The token property permission of a collection has been set.613		PropertyPermissionSet(614			/// ID of collection to which property permission has been set.615			CollectionId,616			/// The property permission that was set.617			PropertyKey,618		),619620		/// Address was added to the allow list.621		AllowListAddressAdded(622			/// ID of the affected collection.623			CollectionId,624			/// Address of the added account.625			T::CrossAccountId,626		),627628		/// Address was removed from the allow list.629		AllowListAddressRemoved(630			/// ID of the affected collection.631			CollectionId,632			/// Address of the removed account.633			T::CrossAccountId,634		),635636		/// Collection admin was added.637		CollectionAdminAdded(638			/// ID of the affected collection.639			CollectionId,640			/// Admin address.641			T::CrossAccountId,642		),643644		/// Collection admin was removed.645		CollectionAdminRemoved(646			/// ID of the affected collection.647			CollectionId,648			/// Removed admin address.649			T::CrossAccountId,650		),651652		/// Collection limits were set.653		CollectionLimitSet(654			/// ID of the affected collection.655			CollectionId,656		),657658		/// Collection owned was changed.659		CollectionOwnerChanged(660			/// ID of the affected collection.661			CollectionId,662			/// New owner address.663			T::AccountId,664		),665666		/// Collection permissions were set.667		CollectionPermissionSet(668			/// ID of the affected collection.669			CollectionId,670		),671672		/// Collection sponsor was set.673		CollectionSponsorSet(674			/// ID of the affected collection.675			CollectionId,676			/// New sponsor address.677			T::AccountId,678		),679680		/// New sponsor was confirm.681		SponsorshipConfirmed(682			/// ID of the affected collection.683			CollectionId,684			/// New sponsor address.685			T::AccountId,686		),687688		/// Collection sponsor was removed.689		CollectionSponsorRemoved(690			/// ID of the affected collection.691			CollectionId,692		),693	}694695	#[pallet::error]696	pub enum Error<T> {697		/// This collection does not exist.698		CollectionNotFound,699		/// Sender parameter and item owner must be equal.700		MustBeTokenOwner,701		/// No permission to perform action702		NoPermission,703		/// Destroying only empty collections is allowed704		CantDestroyNotEmptyCollection,705		/// Collection is not in mint mode.706		PublicMintingNotAllowed,707		/// Address is not in allow list.708		AddressNotInAllowlist,709710		/// Collection name can not be longer than 63 char.711		CollectionNameLimitExceeded,712		/// Collection description can not be longer than 255 char.713		CollectionDescriptionLimitExceeded,714		/// Token prefix can not be longer than 15 char.715		CollectionTokenPrefixLimitExceeded,716		/// Total collections bound exceeded.717		TotalCollectionsLimitExceeded,718		/// Exceeded max admin count719		CollectionAdminCountExceeded,720		/// Collection limit bounds per collection exceeded721		CollectionLimitBoundsExceeded,722		/// Tried to enable permissions which are only permitted to be disabled723		OwnerPermissionsCantBeReverted,724		/// Collection settings not allowing items transferring725		TransferNotAllowed,726		/// Account token limit exceeded per collection727		AccountTokenLimitExceeded,728		/// Collection token limit exceeded729		CollectionTokenLimitExceeded,730		/// Metadata flag frozen731		MetadataFlagFrozen,732733		/// Item does not exist734		TokenNotFound,735		/// Item is balance not enough736		TokenValueTooLow,737		/// Requested value is more than the approved738		ApprovedValueTooLow,739		/// Tried to approve more than owned740		CantApproveMoreThanOwned,741		/// Only spending from eth mirror could be approved742		AddressIsNotEthMirror,743744		/// Can't transfer tokens to ethereum zero address745		AddressIsZero,746747		/// The operation is not supported748		UnsupportedOperation,749750		/// Insufficient funds to perform an action751		NotSufficientFounds,752753		/// User does not satisfy the nesting rule754		UserIsNotAllowedToNest,755		/// Only tokens from specific collections may nest tokens under this one756		SourceCollectionIsNotAllowedToNest,757758		/// Tried to store more data than allowed in collection field759		CollectionFieldSizeExceeded,760761		/// Tried to store more property data than allowed762		NoSpaceForProperty,763764		/// Tried to store more property keys than allowed765		PropertyLimitReached,766767		/// Property key is too long768		PropertyKeyIsTooLong,769770		/// Only ASCII letters, digits, and symbols `_`, `-`, and `.` are allowed771		InvalidCharacterInPropertyKey,772773		/// Empty property keys are forbidden774		EmptyPropertyKey,775776		/// Tried to access an external collection with an internal API777		CollectionIsExternal,778779		/// Tried to access an internal collection with an external API780		CollectionIsInternal,781782		/// This address is not set as sponsor, use setCollectionSponsor first.783		ConfirmSponsorshipFail,784785		/// The user is not an administrator.786		UserIsNotCollectionAdmin,787788		/// Fungible tokens hold no ID, and the default value of TokenId for a fungible collection is 0.789		FungibleItemsHaveNoId,790791		/// Not Fungible item data used to mint in Fungible collection.792		NotFungibleDataUsedToMintFungibleCollectionToken,793	}794795	/// Storage of the count of created collections. Essentially contains the last collection ID.796	#[pallet::storage]797	pub type CreatedCollectionCount<T> = StorageValue<Value = CollectionId, QueryKind = ValueQuery>;798799	/// Storage of the count of deleted collections.800	#[pallet::storage]801	pub type DestroyedCollectionCount<T> =802		StorageValue<Value = CollectionId, QueryKind = ValueQuery>;803804	/// Storage of collection info.805	#[pallet::storage]806	pub type CollectionById<T> = StorageMap<807		Hasher = Blake2_128Concat,808		Key = CollectionId,809		Value = Collection<<T as frame_system::Config>::AccountId>,810		QueryKind = OptionQuery,811	>;812813	/// Storage of collection properties.814	#[pallet::storage]815	#[pallet::getter(fn collection_properties)]816	pub type CollectionProperties<T> = StorageMap<817		Hasher = Blake2_128Concat,818		Key = CollectionId,819		Value = CollectionPropertiesT,820		QueryKind = ValueQuery,821	>;822823	/// Storage of token property permissions of a collection.824	#[pallet::storage]825	#[pallet::getter(fn property_permissions)]826	pub type CollectionPropertyPermissions<T> = StorageMap<827		Hasher = Blake2_128Concat,828		Key = CollectionId,829		Value = PropertiesPermissionMap,830		QueryKind = ValueQuery,831	>;832833	/// Storage of the amount of collection admins.834	#[pallet::storage]835	pub type AdminAmount<T> = StorageMap<836		Hasher = Blake2_128Concat,837		Key = CollectionId,838		Value = u32,839		QueryKind = ValueQuery,840	>;841842	/// List of collection admins.843	#[pallet::storage]844	pub type IsAdmin<T: Config> = StorageNMap<845		Key = (846			Key<Blake2_128Concat, CollectionId>,847			Key<Blake2_128Concat, T::CrossAccountId>,848		),849		Value = bool,850		QueryKind = ValueQuery,851	>;852853	/// Allowlisted collection users.854	#[pallet::storage]855	pub type Allowlist<T: Config> = StorageNMap<856		Key = (857			Key<Blake2_128Concat, CollectionId>,858			Key<Blake2_128Concat, T::CrossAccountId>,859		),860		Value = bool,861		QueryKind = ValueQuery,862	>;863864	/// Not used by code, exists only to provide some types to metadata.865	#[pallet::storage]866	pub type DummyStorageValue<T: Config> = StorageValue<867		Value = (868			CollectionStats,869			CollectionId,870			TokenId,871			TokenChild,872			PhantomType<(873				TokenData<T::CrossAccountId>,874				RpcCollection<T::AccountId>,875				// PoV Estimate Info876				PovInfo,877			)>,878		),879		QueryKind = OptionQuery,880	>;881}882883enum LazyValueState<'a, T> {884	Pending(Box<dyn FnOnce() -> T + 'a>),885	InProgress,886	Computed(T),887}888889/// Value representation with delayed initialization time.890pub struct LazyValue<'a, T> {891	state: LazyValueState<'a, T>,892}893894impl<'a, T> LazyValue<'a, T> {895	/// Create a new LazyValue.896	pub fn new(f: impl FnOnce() -> T + 'a) -> Self {897		Self {898			state: LazyValueState::Pending(Box::new(f)),899		}900	}901902	/// Get the value. If it is called the first time, the value will be initialized.903	pub fn value(&mut self) -> &T {904		self.force_value();905		self.value_mut()906	}907908	/// Get the value. If it is called the first time, the value will be initialized.909	pub fn value_mut(&mut self) -> &mut T {910		self.force_value();911912		if let LazyValueState::Computed(value) = &mut self.state {913			value914		} else {915			unreachable!()916		}917	}918919	fn into_inner(mut self) -> T {920		self.force_value();921		if let LazyValueState::Computed(value) = self.state {922			value923		} else {924			unreachable!()925		}926	}927928	/// Is value initialized?929	pub fn has_value(&self) -> bool {930		matches!(self.state, LazyValueState::Computed(_))931	}932933	fn force_value(&mut self) {934		use LazyValueState::*;935936		if self.has_value() {937			return;938		}939940		match sp_std::mem::replace(&mut self.state, InProgress) {941			Pending(f) => self.state = Computed(f()),942			_ => panic!("recursion isn't supported"),943		}944	}945}946947fn check_token_permissions<T: Config>(948	collection_admin_permitted: bool,949	token_owner_permitted: bool,950	is_collection_admin: &mut LazyValue<bool>,951	is_token_owner: &mut LazyValue<Result<bool, DispatchError>>,952	is_token_exist: &mut LazyValue<bool>,953) -> DispatchResult {954	if !(collection_admin_permitted && *is_collection_admin.value()955		|| token_owner_permitted && (*is_token_owner.value())?)956	{957		fail!(<Error<T>>::NoPermission);958	}959960	let token_exist_due_to_owner_check_success =961		is_token_owner.has_value() && (*is_token_owner.value())?;962963	// If the token owner check has occurred and succeeded,964	// we know the token exists (otherwise, the owner check must fail).965	if !token_exist_due_to_owner_check_success {966		// If the token owner check didn't occur,967		// we must check the token's existence ourselves.968		if !is_token_exist.value() {969			fail!(<Error<T>>::TokenNotFound);970		}971	}972973	Ok(())974}975976impl<T: Config> Pallet<T> {977	/// Enshure that receiver address is correct.978	///979	/// Ethereum receiver 0x0000000000000000000000000000000000000000 is reserved, and shouldn't own tokens.980	pub fn ensure_correct_receiver(receiver: &T::CrossAccountId) -> DispatchResult {981		ensure!(982			&T::CrossAccountId::from_eth(H160([0; 20])) != receiver,983			<Error<T>>::AddressIsZero984		);985		Ok(())986	}987988	/// Get a vector of collection admins.989	pub fn adminlist(collection: CollectionId) -> Vec<T::CrossAccountId> {990		<IsAdmin<T>>::iter_prefix((collection,))991			.map(|(a, _)| a)992			.collect()993	}994995	/// Get a vector of users allowed to mint tokens.996	pub fn allowlist(collection: CollectionId) -> Vec<T::CrossAccountId> {997		<Allowlist<T>>::iter_prefix((collection,))998			.map(|(a, _)| a)999			.collect()1000	}10011002	/// Is `user` allowed to mint token in `collection`.1003	pub fn allowed(collection: CollectionId, user: T::CrossAccountId) -> bool {1004		<Allowlist<T>>::get((collection, user))1005	}10061007	/// Get statistics of collections.1008	pub fn collection_stats() -> CollectionStats {1009		let created = <CreatedCollectionCount<T>>::get();1010		let destroyed = <DestroyedCollectionCount<T>>::get();1011		CollectionStats {1012			created: created.0,1013			destroyed: destroyed.0,1014			alive: created.0 - destroyed.0,1015		}1016	}10171018	/// Get the effective limits for the collection.1019	pub fn effective_collection_limits(collection: CollectionId) -> Option<CollectionLimits> {1020		let collection = <CollectionById<T>>::get(collection)?;1021		let limits = collection.limits;1022		let effective_limits = CollectionLimits {1023			account_token_ownership_limit: Some(limits.account_token_ownership_limit()),1024			sponsored_data_size: Some(limits.sponsored_data_size()),1025			sponsored_data_rate_limit: Some(1026				limits1027					.sponsored_data_rate_limit1028					.unwrap_or(SponsoringRateLimit::SponsoringDisabled),1029			),1030			token_limit: Some(limits.token_limit()),1031			sponsor_transfer_timeout: Some(limits.sponsor_transfer_timeout(1032				match collection.mode {1033					CollectionMode::NFT => NFT_SPONSOR_TRANSFER_TIMEOUT,1034					CollectionMode::Fungible(_) => FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,1035					CollectionMode::ReFungible => REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,1036				},1037			)),1038			sponsor_approve_timeout: Some(limits.sponsor_approve_timeout()),1039			owner_can_transfer: Some(limits.owner_can_transfer()),1040			owner_can_destroy: Some(limits.owner_can_destroy()),1041			transfers_enabled: Some(limits.transfers_enabled()),1042		};10431044		Some(effective_limits)1045	}10461047	/// Returns information about the `collection` adapted for rpc.1048	pub fn rpc_collection(collection: CollectionId) -> Option<RpcCollection<T::AccountId>> {1049		let Collection {1050			name,1051			description,1052			owner,1053			mode,1054			token_prefix,1055			sponsorship,1056			limits,1057			permissions,1058			flags,1059		} = <CollectionById<T>>::get(collection)?;10601061		let token_property_permissions = <CollectionPropertyPermissions<T>>::get(collection)1062			.into_iter()1063			.map(|(key, permission)| PropertyKeyPermission { key, permission })1064			.collect();10651066		let properties = <CollectionProperties<T>>::get(collection)1067			.into_iter()1068			.map(|(key, value)| Property { key, value })1069			.collect();10701071		let permissions = CollectionPermissions {1072			access: Some(permissions.access()),1073			mint_mode: Some(permissions.mint_mode()),1074			nesting: Some(permissions.nesting().clone()),1075		};10761077		Some(RpcCollection {1078			name: name.into_inner(),1079			description: description.into_inner(),1080			owner,1081			mode,1082			token_prefix: token_prefix.into_inner(),1083			sponsorship,1084			limits,1085			permissions,1086			token_property_permissions,1087			properties,1088			read_only: flags.external,10891090			flags: RpcCollectionFlags {1091				foreign: flags.foreign,1092				erc721metadata: flags.erc721metadata,1093			},1094		})1095	}1096}10971098macro_rules! limit_default {1099	($old:ident, $new:ident, $($field:ident $(($arg:expr))? => $check:expr),* $(,)?) => {{1100		$(1101			if let Some($new) = $new.$field {1102				let $old = $old.$field($($arg)?);1103				let _ = $new;1104				let _ = $old;1105				$check1106			} else {1107				$new.$field = $old.$field1108			}1109		)*1110	}};1111}1112macro_rules! limit_default_clone {1113	($old:ident, $new:ident, $($field:ident $(($arg:expr))? => $check:expr),* $(,)?) => {{1114		$(1115			if let Some($new) = $new.$field.clone() {1116				let $old = $old.$field($($arg)?);1117				let _ = $new;1118				let _ = $old;1119				$check1120			} else {1121				$new.$field = $old.$field.clone()1122			}1123		)*1124	}};1125}11261127impl<T: Config> Pallet<T> {1128	/// Create new collection.1129	///1130	/// * `owner` - The owner of the collection.1131	/// * `payer` - If set, the user that will pay a deposit for the collection creation.1132	/// * `data` - Description of the created collection.1133	/// * `is_special_collection` -- Whether this collection is a special one, i.e. can have special flags set.1134	pub fn init_collection(1135		owner: T::CrossAccountId,1136		payer: Option<T::CrossAccountId>,1137		is_special_collection: bool,1138		data: CreateCollectionData<T::CrossAccountId>,1139	) -> Result<CollectionId, DispatchError> {1140		if !is_special_collection {1141			ensure!(data.flags.is_allowed_for_user(), <Error<T>>::NoPermission);1142		}11431144		// Take a (non-refundable) deposit of collection creation1145		if let Some(payer) = payer {1146			let mut imbalance = <Debt<T::AccountId, <T as Config>::Currency>>::zero();1147			imbalance.subsume(<T as Config>::Currency::deposit(1148				&T::TreasuryAccountId::get(),1149				T::CollectionCreationPrice::get(),1150				Precision::Exact,1151			)?);1152			let credit =1153				<T as Config>::Currency::settle(payer.as_sub(), imbalance, Preservation::Preserve)1154					.map_err(|_| Error::<T>::NotSufficientFounds)?;11551156			debug_assert!(credit.peek().is_zero())1157		}11581159		{1160			ensure!(1161				data.token_prefix.len() <= MAX_TOKEN_PREFIX_LENGTH as usize,1162				Error::<T>::CollectionTokenPrefixLimitExceeded1163			);1164		}11651166		let created_count = <CreatedCollectionCount<T>>::get()1167			.01168			.checked_add(1)1169			.ok_or(ArithmeticError::Overflow)?;1170		let destroyed_count = <DestroyedCollectionCount<T>>::get().0;1171		let id = CollectionId(created_count);11721173		// bound Total number of collections1174		ensure!(1175			created_count - destroyed_count <= COLLECTION_NUMBER_LIMIT,1176			<Error<T>>::TotalCollectionsLimitExceeded1177		);11781179		// =========11801181		let collection = Collection {1182			owner: owner.as_sub().clone(),1183			name: data.name,1184			mode: data.mode.clone(),1185			description: data.description,1186			token_prefix: data.token_prefix,1187			sponsorship: data1188				.pending_sponsor1189				.map(|sponsor| SponsorshipState::Unconfirmed(sponsor.as_sub().clone()))1190				.unwrap_or_default(),1191			limits: data1192				.limits1193				.map(|limits| Self::clamp_limits(data.mode.clone(), &Default::default(), limits))1194				.unwrap_or_else(|| Ok(CollectionLimits::default()))?,1195			permissions: data1196				.permissions1197				.map(|permissions| {1198					Self::clamp_permissions(data.mode.clone(), &Default::default(), permissions)1199				})1200				.unwrap_or_else(|| Ok(CollectionPermissions::default()))?,1201			flags: data.flags,1202		};12031204		let mut collection_properties = CollectionPropertiesT::new();1205		collection_properties1206			.try_set_from_iter(data.properties.into_iter())1207			.map_err(<Error<T>>::from)?;12081209		CollectionProperties::<T>::insert(id, collection_properties);12101211		let mut token_props_permissions = PropertiesPermissionMap::new();1212		token_props_permissions1213			.try_set_from_iter(data.token_property_permissions.into_iter())1214			.map_err(<Error<T>>::from)?;12151216		CollectionPropertyPermissions::<T>::insert(id, token_props_permissions);12171218		let mut admin_amount = 0u32;1219		for admin in data.admin_list.iter() {1220			if !<IsAdmin<T>>::get((id, admin)) {1221				<IsAdmin<T>>::insert((id, admin), true);1222				admin_amount = admin_amount1223					.checked_add(1)1224					.ok_or(<Error<T>>::CollectionAdminCountExceeded)?;1225			}1226		}1227		ensure!(1228			admin_amount <= Self::collection_admins_limit(),1229			<Error<T>>::CollectionAdminCountExceeded,1230		);1231		<AdminAmount<T>>::insert(id, admin_amount);12321233		<CreatedCollectionCount<T>>::put(created_count);1234		<Pallet<T>>::deposit_event(Event::CollectionCreated(1235			id,1236			data.mode.id(),1237			owner.as_sub().clone(),1238		));1239		<PalletEvm<T>>::deposit_log(1240			erc::CollectionHelpersEvents::CollectionCreated {1241				owner: *owner.as_eth(),1242				collection_id: eth::collection_id_to_address(id),1243			}1244			.to_log(T::ContractAddress::get()),1245		);1246		<CollectionById<T>>::insert(id, collection);1247		Ok(id)1248	}12491250	/// Destroy collection.1251	///1252	/// * `collection` - Collection handler.1253	/// * `sender` - The owner or administrator of the collection.1254	pub fn destroy_collection(1255		collection: CollectionHandle<T>,1256		sender: &T::CrossAccountId,1257	) -> DispatchResult {1258		ensure!(1259			collection.limits.owner_can_destroy(),1260			<Error<T>>::NoPermission,1261		);1262		collection.check_is_owner(sender)?;12631264		let destroyed_collections = <DestroyedCollectionCount<T>>::get()1265			.01266			.checked_add(1)1267			.ok_or(ArithmeticError::Overflow)?;12681269		// =========12701271		<DestroyedCollectionCount<T>>::put(destroyed_collections);1272		<CollectionById<T>>::remove(collection.id);1273		<AdminAmount<T>>::remove(collection.id);1274		let _ = <IsAdmin<T>>::clear_prefix((collection.id,), u32::MAX, None);1275		let _ = <Allowlist<T>>::clear_prefix((collection.id,), u32::MAX, None);1276		<CollectionProperties<T>>::remove(collection.id);12771278		<Pallet<T>>::deposit_event(Event::CollectionDestroyed(collection.id));12791280		<PalletEvm<T>>::deposit_log(1281			erc::CollectionHelpersEvents::CollectionDestroyed {1282				collection_id: eth::collection_id_to_address(collection.id),1283			}1284			.to_log(T::ContractAddress::get()),1285		);1286		Ok(())1287	}12881289	/// This function sets or removes a collection properties according to1290	/// `properties_updates` contents:1291	/// * sets a property under the <key> with the value provided `(<key>, Some(<value>))`1292	/// * removes a property under the <key> if the value is `None` `(<key>, None)`.1293	///1294	/// This function fires an event for each property change.1295	/// In case of an error, all the changes (including the events) will be reverted1296	/// since the function is transactional.1297	#[transactional]1298	fn modify_collection_properties(1299		collection: &CollectionHandle<T>,1300		sender: &T::CrossAccountId,1301		properties_updates: impl Iterator<Item = (PropertyKey, Option<PropertyValue>)>,1302	) -> DispatchResult {1303		collection.check_is_owner_or_admin(sender)?;13041305		let mut stored_properties = <CollectionProperties<T>>::get(collection.id);13061307		for (key, value) in properties_updates {1308			match value {1309				Some(value) => {1310					stored_properties1311						.try_set(key.clone(), value)1312						.map_err(<Error<T>>::from)?;13131314					Self::deposit_event(Event::CollectionPropertySet(collection.id, key));1315					<PalletEvm<T>>::deposit_log(1316						erc::CollectionHelpersEvents::CollectionChanged {1317							collection_id: eth::collection_id_to_address(collection.id),1318						}1319						.to_log(T::ContractAddress::get()),1320					);1321				}1322				None => {1323					stored_properties.remove(&key).map_err(<Error<T>>::from)?;13241325					Self::deposit_event(Event::CollectionPropertyDeleted(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			}1334		}13351336		<CollectionProperties<T>>::set(collection.id, stored_properties);13371338		Ok(())1339	}13401341	/// Sets or unsets the approval of a given operator.1342	///1343	/// The `operator` is allowed to transfer all token pieces of the `owner` on their behalf.1344	/// - `owner`: Token owner1345	/// - `operator`: Operator1346	/// - `approve`: Should operator status be granted or revoked?1347	pub fn set_allowance_for_all(1348		collection: &CollectionHandle<T>,1349		owner: &T::CrossAccountId,1350		operator: &T::CrossAccountId,1351		approve: bool,1352		set_allowance: impl FnOnce(),1353		log: evm_coder::ethereum::Log,1354	) -> DispatchResult {1355		if collection.permissions.access() == AccessMode::AllowList {1356			collection.check_allowlist(owner)?;1357			collection.check_allowlist(operator)?;1358		}13591360		Self::ensure_correct_receiver(operator)?;13611362		set_allowance();13631364		<PalletEvm<T>>::deposit_log(log);1365		Self::deposit_event(Event::ApprovedForAll(1366			collection.id,1367			owner.clone(),1368			operator.clone(),1369			approve,1370		));1371		Ok(())1372	}13731374	/// Set collection property.1375	///1376	/// * `collection` - Collection handler.1377	/// * `sender` - The owner or administrator of the collection.1378	/// * `property` - The property to set.1379	pub fn set_collection_property(1380		collection: &CollectionHandle<T>,1381		sender: &T::CrossAccountId,1382		property: Property,1383	) -> DispatchResult {1384		Self::set_collection_properties(collection, sender, [property].into_iter())1385	}13861387	/// Set a scoped collection property, where the scope is a special prefix1388	/// prohibiting a user access to change the property directly.1389	///1390	/// * `collection_id` - ID of the collection for which the property is being set.1391	/// * `scope` - Property scope.1392	/// * `property` - The property to set.1393	pub fn set_scoped_collection_property(1394		collection_id: CollectionId,1395		scope: PropertyScope,1396		property: Property,1397	) -> DispatchResult {1398		CollectionProperties::<T>::try_mutate(collection_id, |properties| {1399			properties.try_scoped_set(scope, property.key, property.value)1400		})1401		.map_err(<Error<T>>::from)?;14021403		Ok(())1404	}14051406	/// Set scoped collection properties, where the scope is a special prefix1407	/// prohibiting a user access to change the properties directly.1408	///1409	/// * `collection_id` - ID of the collection for which the properties is being set.1410	/// * `scope` - Property scope.1411	/// * `properties` - The properties to set.1412	pub fn set_scoped_collection_properties(1413		collection_id: CollectionId,1414		scope: PropertyScope,1415		properties: impl Iterator<Item = Property>,1416	) -> DispatchResult {1417		CollectionProperties::<T>::try_mutate(collection_id, |stored_properties| {1418			stored_properties.try_scoped_set_from_iter(scope, properties)1419		})1420		.map_err(<Error<T>>::from)?;14211422		Ok(())1423	}14241425	/// Set collection properties.1426	///1427	/// * `collection` - Collection handler.1428	/// * `sender` - The owner or administrator of the collection.1429	/// * `properties` - The properties to set.1430	pub fn set_collection_properties(1431		collection: &CollectionHandle<T>,1432		sender: &T::CrossAccountId,1433		properties: impl Iterator<Item = Property>,1434	) -> DispatchResult {1435		Self::modify_collection_properties(1436			collection,1437			sender,1438			properties.map(|property| (property.key, Some(property.value))),1439		)1440	}14411442	/// Delete collection property.1443	///1444	/// * `collection` - Collection handler.1445	/// * `sender` - The owner or administrator of the collection.1446	/// * `property` - The property to delete.1447	pub fn delete_collection_property(1448		collection: &CollectionHandle<T>,1449		sender: &T::CrossAccountId,1450		property_key: PropertyKey,1451	) -> DispatchResult {1452		Self::delete_collection_properties(collection, sender, [property_key].into_iter())1453	}14541455	/// Delete collection properties.1456	///1457	/// * `collection` - Collection handler.1458	/// * `sender` - The owner or administrator of the collection.1459	/// * `properties` - The properties to delete.1460	pub fn delete_collection_properties(1461		collection: &CollectionHandle<T>,1462		sender: &T::CrossAccountId,1463		property_keys: impl Iterator<Item = PropertyKey>,1464	) -> DispatchResult {1465		Self::modify_collection_properties(collection, sender, property_keys.map(|key| (key, None)))1466	}14671468	/// Set collection propetry permission without any checks.1469	///1470	/// Used for migrations.1471	///1472	/// * `collection` - Collection handler.1473	/// * `property_permissions` - Property permissions.1474	pub fn set_property_permission_unchecked(1475		collection: CollectionId,1476		property_permission: PropertyKeyPermission,1477	) -> DispatchResult {1478		<CollectionPropertyPermissions<T>>::try_mutate(collection, |permissions| {1479			permissions.try_set(property_permission.key, property_permission.permission)1480		})1481		.map_err(<Error<T>>::from)?;1482		Ok(())1483	}14841485	/// Set collection property permission.1486	///1487	/// * `collection` - Collection handler.1488	/// * `sender` - The owner or administrator of the collection.1489	/// * `property_permission` - Property permission.1490	pub fn set_property_permission(1491		collection: &CollectionHandle<T>,1492		sender: &T::CrossAccountId,1493		property_permission: PropertyKeyPermission,1494	) -> DispatchResult {1495		Self::set_scoped_property_permission(1496			collection,1497			sender,1498			PropertyScope::None,1499			property_permission,1500		)1501	}15021503	/// Set collection property permission with scope.1504	///1505	/// * `collection` - Collection handler.1506	/// * `sender` - The owner or administrator of the collection.1507	/// * `scope` - Property scope.1508	/// * `property_permission` - Property permission.1509	pub fn set_scoped_property_permission(1510		collection: &CollectionHandle<T>,1511		sender: &T::CrossAccountId,1512		scope: PropertyScope,1513		property_permission: PropertyKeyPermission,1514	) -> DispatchResult {1515		collection.check_is_owner_or_admin(sender)?;15161517		let all_permissions = CollectionPropertyPermissions::<T>::get(collection.id);1518		let current_permission = all_permissions.get(&property_permission.key);1519		if matches![1520			current_permission,1521			Some(PropertyPermission { mutable: false, .. })1522		] {1523			return Err(<Error<T>>::NoPermission.into());1524		}15251526		CollectionPropertyPermissions::<T>::try_mutate(collection.id, |permissions| {1527			let property_permission = property_permission.clone();1528			permissions.try_scoped_set(1529				scope,1530				property_permission.key,1531				property_permission.permission,1532			)1533		})1534		.map_err(<Error<T>>::from)?;15351536		Self::deposit_event(Event::PropertyPermissionSet(1537			collection.id,1538			property_permission.key,1539		));1540		<PalletEvm<T>>::deposit_log(1541			erc::CollectionHelpersEvents::CollectionChanged {1542				collection_id: eth::collection_id_to_address(collection.id),1543			}1544			.to_log(T::ContractAddress::get()),1545		);15461547		Ok(())1548	}15491550	/// Set token property permission.1551	///1552	/// * `collection` - Collection handler.1553	/// * `sender` - The owner or administrator of the collection.1554	/// * `property_permissions` - Property permissions.1555	#[transactional]1556	pub fn set_token_property_permissions(1557		collection: &CollectionHandle<T>,1558		sender: &T::CrossAccountId,1559		property_permissions: Vec<PropertyKeyPermission>,1560	) -> DispatchResult {1561		Self::set_scoped_token_property_permissions(1562			collection,1563			sender,1564			PropertyScope::None,1565			property_permissions,1566		)1567	}15681569	/// Set token property permission with scope.1570	///1571	/// * `collection` - Collection handler.1572	/// * `sender` - The owner or administrator of the collection.1573	/// * `scope` - Property scope.1574	/// * `property_permissions` - Property permissions.1575	#[transactional]1576	pub fn set_scoped_token_property_permissions(1577		collection: &CollectionHandle<T>,1578		sender: &T::CrossAccountId,1579		scope: PropertyScope,1580		property_permissions: Vec<PropertyKeyPermission>,1581	) -> DispatchResult {1582		for prop_pemission in property_permissions {1583			Self::set_scoped_property_permission(collection, sender, scope, prop_pemission)?;1584		}15851586		Ok(())1587	}15881589	/// Get collection property.1590	pub fn get_collection_property(1591		collection_id: CollectionId,1592		key: &PropertyKey,1593	) -> Option<PropertyValue> {1594		Self::collection_properties(collection_id).get(key).cloned()1595	}15961597	/// Convert byte vector to property key vector.1598	pub fn bytes_keys_to_property_keys(1599		keys: Vec<Vec<u8>>,1600	) -> Result<Vec<PropertyKey>, DispatchError> {1601		keys.into_iter()1602			.map(|key| -> Result<PropertyKey, DispatchError> {1603				key.try_into()1604					.map_err(|_| <Error<T>>::PropertyKeyIsTooLong.into())1605			})1606			.collect::<Result<Vec<PropertyKey>, DispatchError>>()1607	}16081609	/// Get properties according to given keys.1610	pub fn filter_collection_properties(1611		collection_id: CollectionId,1612		keys: Option<Vec<PropertyKey>>,1613	) -> Result<Vec<Property>, DispatchError> {1614		let properties = Self::collection_properties(collection_id);16151616		let properties = keys1617			.map(|keys| {1618				keys.into_iter()1619					.filter_map(|key| {1620						properties.get(&key).map(|value| Property {1621							key,1622							value: value.clone(),1623						})1624					})1625					.collect()1626			})1627			.unwrap_or_else(|| {1628				properties1629					.into_iter()1630					.map(|(key, value)| Property { key, value })1631					.collect()1632			});16331634		Ok(properties)1635	}16361637	/// Get property permissions according to given keys.1638	pub fn filter_property_permissions(1639		collection_id: CollectionId,1640		keys: Option<Vec<PropertyKey>>,1641	) -> Result<Vec<PropertyKeyPermission>, DispatchError> {1642		let permissions = Self::property_permissions(collection_id);16431644		let key_permissions = keys1645			.map(|keys| {1646				keys.into_iter()1647					.filter_map(|key| {1648						permissions1649							.get(&key)1650							.map(|permission| PropertyKeyPermission {1651								key,1652								permission: permission.clone(),1653							})1654					})1655					.collect()1656			})1657			.unwrap_or_else(|| {1658				permissions1659					.into_iter()1660					.map(|(key, permission)| PropertyKeyPermission { key, permission })1661					.collect()1662			});16631664		Ok(key_permissions)1665	}16661667	/// Toggle `user` participation in the `collection`'s allow list.1668	/// #### Store read/writes1669	/// 1 writes1670	pub fn toggle_allowlist(1671		collection: &CollectionHandle<T>,1672		sender: &T::CrossAccountId,1673		user: &T::CrossAccountId,1674		allowed: bool,1675	) -> DispatchResult {1676		collection.check_is_owner_or_admin(sender)?;16771678		// =========16791680		if allowed {1681			<Allowlist<T>>::insert((collection.id, user), true);1682			Self::deposit_event(Event::<T>::AllowListAddressAdded(1683				collection.id,1684				user.clone(),1685			));1686		} else {1687			<Allowlist<T>>::remove((collection.id, user));1688			Self::deposit_event(Event::<T>::AllowListAddressRemoved(1689				collection.id,1690				user.clone(),1691			));1692		}16931694		<PalletEvm<T>>::deposit_log(1695			erc::CollectionHelpersEvents::CollectionChanged {1696				collection_id: eth::collection_id_to_address(collection.id),1697			}1698			.to_log(T::ContractAddress::get()),1699		);17001701		Ok(())1702	}17031704	/// Toggle `user` participation in the `collection`'s admin list.1705	/// #### Store read/writes1706	/// 2 reads, 2 writes1707	pub fn toggle_admin(1708		collection: &CollectionHandle<T>,1709		sender: &T::CrossAccountId,1710		user: &T::CrossAccountId,1711		admin: bool,1712	) -> DispatchResult {1713		collection.check_is_internal()?;1714		collection.check_is_owner(sender)?;17151716		let is_admin = <IsAdmin<T>>::get((collection.id, user));1717		if is_admin == admin {1718			if admin {1719				return Ok(());1720			} else {1721				return Err(Error::<T>::UserIsNotCollectionAdmin.into());1722			}1723		}1724		let amount = <AdminAmount<T>>::get(collection.id);17251726		// =========17271728		if admin {1729			let amount = amount1730				.checked_add(1)1731				.ok_or(<Error<T>>::CollectionAdminCountExceeded)?;1732			ensure!(1733				amount <= Self::collection_admins_limit(),1734				<Error<T>>::CollectionAdminCountExceeded,1735			);17361737			<AdminAmount<T>>::insert(collection.id, amount);1738			<IsAdmin<T>>::insert((collection.id, user), true);17391740			Self::deposit_event(Event::<T>::CollectionAdminAdded(1741				collection.id,1742				user.clone(),1743			));1744		} else {1745			<AdminAmount<T>>::insert(collection.id, amount.saturating_sub(1));1746			<IsAdmin<T>>::remove((collection.id, user));17471748			Self::deposit_event(Event::<T>::CollectionAdminRemoved(1749				collection.id,1750				user.clone(),1751			));1752		}17531754		<PalletEvm<T>>::deposit_log(1755			erc::CollectionHelpersEvents::CollectionChanged {1756				collection_id: eth::collection_id_to_address(collection.id),1757			}1758			.to_log(T::ContractAddress::get()),1759		);17601761		Ok(())1762	}17631764	/// Update collection limits.1765	pub fn update_limits(1766		user: &T::CrossAccountId,1767		collection: &mut CollectionHandle<T>,1768		new_limit: CollectionLimits,1769	) -> DispatchResult {1770		collection.check_is_internal()?;1771		collection.check_is_owner_or_admin(user)?;17721773		collection.limits =1774			Self::clamp_limits(collection.mode.clone(), &collection.limits, new_limit)?;17751776		Self::deposit_event(Event::<T>::CollectionLimitSet(collection.id));1777		<PalletEvm<T>>::deposit_log(1778			erc::CollectionHelpersEvents::CollectionChanged {1779				collection_id: eth::collection_id_to_address(collection.id),1780			}1781			.to_log(T::ContractAddress::get()),1782		);17831784		collection.save()1785	}17861787	/// Merge set fields from `new_limit` to `old_limit`.1788	fn clamp_limits(1789		mode: CollectionMode,1790		old_limit: &CollectionLimits,1791		mut new_limit: CollectionLimits,1792	) -> Result<CollectionLimits, DispatchError> {1793		let limits = old_limit;1794		limit_default!(old_limit, new_limit,1795			account_token_ownership_limit => ensure!(1796				new_limit <= MAX_TOKEN_OWNERSHIP,1797				<Error<T>>::CollectionLimitBoundsExceeded,1798			),1799			sponsored_data_size => ensure!(1800				new_limit <= CUSTOM_DATA_LIMIT,1801				<Error<T>>::CollectionLimitBoundsExceeded,1802			),18031804			sponsored_data_rate_limit => {},1805			token_limit => ensure!(1806				old_limit >= new_limit && new_limit > 0,1807				<Error<T>>::CollectionTokenLimitExceeded1808			),18091810			sponsor_transfer_timeout(match mode {1811				CollectionMode::NFT => NFT_SPONSOR_TRANSFER_TIMEOUT,1812				CollectionMode::Fungible(_) => FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,1813				CollectionMode::ReFungible => REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,1814			}) => ensure!(1815				new_limit <= MAX_SPONSOR_TIMEOUT,1816				<Error<T>>::CollectionLimitBoundsExceeded,1817			),1818			sponsor_approve_timeout => {},1819			owner_can_transfer => ensure!(1820				!limits.owner_can_transfer_instaled() ||1821				old_limit || !new_limit,1822				<Error<T>>::OwnerPermissionsCantBeReverted,1823			),1824			owner_can_destroy => ensure!(1825				old_limit || !new_limit,1826				<Error<T>>::OwnerPermissionsCantBeReverted,1827			),1828			transfers_enabled => {},1829		);1830		Ok(new_limit)1831	}18321833	/// Update collection permissions.1834	pub fn update_permissions(1835		user: &T::CrossAccountId,1836		collection: &mut CollectionHandle<T>,1837		new_permission: CollectionPermissions,1838	) -> DispatchResult {1839		collection.check_is_internal()?;1840		collection.check_is_owner_or_admin(user)?;1841		collection.permissions = Self::clamp_permissions(1842			collection.mode.clone(),1843			&collection.permissions,1844			new_permission,1845		)?;18461847		Self::deposit_event(Event::<T>::CollectionPermissionSet(collection.id));1848		<PalletEvm<T>>::deposit_log(1849			erc::CollectionHelpersEvents::CollectionChanged {1850				collection_id: eth::collection_id_to_address(collection.id),1851			}1852			.to_log(T::ContractAddress::get()),1853		);18541855		collection.save()1856	}18571858	/// Merge set fields from `new_permission` to `old_permission`.1859	fn clamp_permissions(1860		_mode: CollectionMode,1861		old_permission: &CollectionPermissions,1862		mut new_permission: CollectionPermissions,1863	) -> Result<CollectionPermissions, DispatchError> {1864		limit_default_clone!(old_permission, new_permission,1865			access => {},1866			mint_mode => {},1867			nesting => { /* todo check for permissive, if only it gets out of benchmarks */ },1868		);1869		Ok(new_permission)1870	}18711872	/// Repair possibly broken properties of a collection.1873	pub fn repair_collection(collection_id: CollectionId) -> DispatchResult {1874		CollectionProperties::<T>::mutate(collection_id, |properties| {1875			properties.recompute_consumed_space();1876		});18771878		Ok(())1879	}1880}18811882/// Indicates unsupported methods by returning [Error::UnsupportedOperation].1883#[macro_export]1884macro_rules! unsupported {1885	($runtime:path) => {1886		Err($crate::Error::<$runtime>::UnsupportedOperation.into())1887	};1888}18891890/// Return weights for various worst-case operations.1891pub trait CommonWeightInfo<CrossAccountId> {1892	/// Weight of item creation.1893	fn create_item(data: &CreateItemData) -> Weight {1894		Self::create_multiple_items(from_ref(data))1895	}18961897	/// Weight of items creation.1898	fn create_multiple_items(amount: &[CreateItemData]) -> Weight;18991900	/// Weight of items creation.1901	fn create_multiple_items_ex(cost: &CreateItemExData<CrossAccountId>) -> Weight;19021903	/// The weight of the burning item.1904	fn burn_item() -> Weight;19051906	/// Property setting weight.1907	///1908	/// * `amount`- The number of properties to set.1909	fn set_collection_properties(amount: u32) -> Weight;19101911	/// Collection property deletion weight.1912	///1913	/// * `amount`- The number of properties to set.1914	fn delete_collection_properties(amount: u32) -> Weight {1915		Self::set_collection_properties(amount)1916	}19171918	/// Token property setting weight.1919	///1920	/// * `amount`- The number of properties to set.1921	fn set_token_properties(amount: u32) -> Weight;19221923	/// Token property deletion weight.1924	///1925	/// * `amount`- The number of properties to delete.1926	fn delete_token_properties(amount: u32) -> Weight {1927		Self::set_token_properties(amount)1928	}19291930	/// Token property permissions set weight.1931	///1932	/// * `amount`- The number of property permissions to set.1933	fn set_token_property_permissions(amount: u32) -> Weight;19341935	/// Transfer price of the token or its parts.1936	fn transfer() -> Weight;19371938	/// The price of setting the permission of the operation from another user.1939	fn approve() -> Weight;19401941	/// The price of setting the permission of the operation from another user for eth mirror.1942	fn approve_from() -> Weight;19431944	/// Transfer price from another user.1945	fn transfer_from() -> Weight;19461947	/// The price of burning a token from another user.1948	fn burn_from() -> Weight;19491950	/// The price of setting approval for all1951	fn set_allowance_for_all() -> Weight;19521953	/// The price of repairing an item.1954	fn force_repair_item() -> Weight;1955}19561957/// Weight info extension trait for refungible pallet.1958pub trait RefungibleExtensionsWeightInfo {1959	/// Weight of token repartition.1960	fn repartition() -> Weight;1961}19621963/// Common collection operations.1964///1965/// It wraps methods in Fungible, Nonfungible and Refungible pallets1966/// and adds weight info.1967pub trait CommonCollectionOperations<T: Config> {1968	/// Create token.1969	///1970	/// * `sender` - The user who mint the token and pays for the transaction.1971	/// * `to` - The user who will own the token.1972	/// * `data` - Token data.1973	/// * `nesting_budget` - A budget that can be spent on nesting tokens.1974	fn create_item(1975		&self,1976		sender: T::CrossAccountId,1977		to: T::CrossAccountId,1978		data: CreateItemData,1979		nesting_budget: &dyn Budget,1980	) -> DispatchResultWithPostInfo;19811982	/// Create multiple tokens.1983	///1984	/// * `sender` - The user who mint the token and pays for the transaction.1985	/// * `to` - The user who will own the token.1986	/// * `data` - Token data.1987	/// * `nesting_budget` - A budget that can be spent on nesting tokens.1988	fn create_multiple_items(1989		&self,1990		sender: T::CrossAccountId,1991		to: T::CrossAccountId,1992		data: Vec<CreateItemData>,1993		nesting_budget: &dyn Budget,1994	) -> DispatchResultWithPostInfo;19951996	/// Create multiple tokens.1997	///1998	/// * `sender` - The user who mint the token and pays for the transaction.1999	/// * `to` - The user who will own the token.2000	/// * `data` - Token data.2001	/// * `nesting_budget` - A budget that can be spent on nesting tokens.2002	fn create_multiple_items_ex(2003		&self,2004		sender: T::CrossAccountId,2005		data: CreateItemExData<T::CrossAccountId>,2006		nesting_budget: &dyn Budget,2007	) -> DispatchResultWithPostInfo;20082009	/// Burn token.2010	///2011	/// * `sender` - The user who owns the token.2012	/// * `token` - Token id that will burned.2013	/// * `amount` - The number of parts of the token that will be burned.2014	fn burn_item(2015		&self,2016		sender: T::CrossAccountId,2017		token: TokenId,2018		amount: u128,2019	) -> DispatchResultWithPostInfo;20202021	/// Set collection properties.2022	///2023	/// * `sender` - Must be either the owner of the collection or its admin.2024	/// * `properties` - Properties to be set.2025	fn set_collection_properties(2026		&self,2027		sender: T::CrossAccountId,2028		properties: Vec<Property>,2029	) -> DispatchResultWithPostInfo;20302031	/// Delete collection properties.2032	///2033	/// * `sender` - Must be either the owner of the collection or its admin.2034	/// * `properties` - The properties to be removed.2035	fn delete_collection_properties(2036		&self,2037		sender: &T::CrossAccountId,2038		property_keys: Vec<PropertyKey>,2039	) -> DispatchResultWithPostInfo;20402041	/// Set token properties.2042	///2043	/// The appropriate [`PropertyPermission`] for the token property2044	/// must be set with [`Self::set_token_property_permissions`].2045	///2046	/// * `sender` - Must be either the owner of the token or its admin.2047	/// * `token_id` - The token for which the properties are being set.2048	/// * `properties` - Properties to be set.2049	/// * `budget` - Budget for setting properties.2050	fn set_token_properties(2051		&self,2052		sender: T::CrossAccountId,2053		token_id: TokenId,2054		properties: Vec<Property>,2055		budget: &dyn Budget,2056	) -> DispatchResultWithPostInfo;20572058	/// Remove token properties.2059	///2060	/// The appropriate [`PropertyPermission`] for the token property2061	/// must be set with [`Self::set_token_property_permissions`].2062	///2063	/// * `sender` - Must be either the owner of the token or its admin.2064	/// * `token_id` - The token for which the properties are being remove.2065	/// * `property_keys` - Keys to remove corresponding properties.2066	/// * `budget` - Budget for removing properties.2067	fn delete_token_properties(2068		&self,2069		sender: T::CrossAccountId,2070		token_id: TokenId,2071		property_keys: Vec<PropertyKey>,2072		budget: &dyn Budget,2073	) -> DispatchResultWithPostInfo;20742075	/// Get token properties raw map.2076	///2077	/// * `token_id` - The token which properties are needed.2078	fn get_token_properties_raw(&self, token_id: TokenId) -> Option<TokenProperties>;20792080	/// Set token properties raw map.2081	///2082	/// * `token_id` - The token for which the properties are being set.2083	/// * `map` - The raw map containing the token's properties.2084	fn set_token_properties_raw(&self, token_id: TokenId, map: TokenProperties);20852086	/// Set token property permissions.2087	///2088	/// * `sender` - Must be either the owner of the token or its admin.2089	/// * `token_id` - The token for which the properties are being set.2090	/// * `property_permissions` - Property permissions to be set.2091	/// * `budget` - Budget for setting properties.2092	fn set_token_property_permissions(2093		&self,2094		sender: &T::CrossAccountId,2095		property_permissions: Vec<PropertyKeyPermission>,2096	) -> DispatchResultWithPostInfo;20972098	/// Transfer amount of token pieces.2099	///2100	/// * `sender` - Donor user.2101	/// * `to` - Recepient user.2102	/// * `token` - The token of which parts are being sent.2103	/// * `amount` - The number of parts of the token that will be transferred.2104	/// * `budget` - The maximum budget that can be spent on the transfer.2105	fn transfer(2106		&self,2107		sender: T::CrossAccountId,2108		to: T::CrossAccountId,2109		token: TokenId,2110		amount: u128,2111		budget: &dyn Budget,2112	) -> DispatchResultWithPostInfo;21132114	/// Grant access to another account to transfer parts of the token owned by the calling user via [Self::transfer_from].2115	///2116	/// * `sender` - The user who grants access to the token.2117	/// * `spender` - The user to whom the rights are granted.2118	/// * `token` - The token to which access is granted.2119	/// * `amount` - The amount of pieces that another user can dispose of.2120	fn approve(2121		&self,2122		sender: T::CrossAccountId,2123		spender: T::CrossAccountId,2124		token: TokenId,2125		amount: u128,2126	) -> DispatchResultWithPostInfo;21272128	/// Grant access to another account to transfer parts of the token owned by the calling user's eth mirror via [Self::transfer_from].2129	///2130	/// * `sender` - The user who grants access to the token.2131	/// * `from` - Spender's eth mirror.2132	/// * `to` - The user to whom the rights are granted.2133	/// * `token` - The token to which access is granted.2134	/// * `amount` - The amount of pieces that another user can dispose of.2135	fn approve_from(2136		&self,2137		sender: T::CrossAccountId,2138		from: T::CrossAccountId,2139		to: T::CrossAccountId,2140		token: TokenId,2141		amount: u128,2142	) -> DispatchResultWithPostInfo;21432144	/// Send parts of a token owned by another user.2145	///2146	/// Before calling this method, you must grant rights to the calling user via [`Self::approve`].2147	///2148	/// * `sender` - The user who must have access to the token (see [`Self::approve`]).2149	/// * `from` - The user who owns the token.2150	/// * `to` - Recepient user.2151	/// * `token` - The token of which parts are being sent.2152	/// * `amount` - The number of parts of the token that will be transferred.2153	/// * `budget` - The maximum budget that can be spent on the transfer.2154	fn transfer_from(2155		&self,2156		sender: T::CrossAccountId,2157		from: T::CrossAccountId,2158		to: T::CrossAccountId,2159		token: TokenId,2160		amount: u128,2161		budget: &dyn Budget,2162	) -> DispatchResultWithPostInfo;21632164	/// Burn parts of a token owned by another user.2165	///2166	/// Before calling this method, you must grant rights to the calling user via [`Self::approve`].2167	///2168	/// * `sender` - The user who must have access to the token (see [`Self::approve`]).2169	/// * `from` - The user who owns the token.2170	/// * `token` - The token of which parts are being sent.2171	/// * `amount` - The number of parts of the token that will be transferred.2172	/// * `budget` - The maximum budget that can be spent on the burn.2173	fn burn_from(2174		&self,2175		sender: T::CrossAccountId,2176		from: T::CrossAccountId,2177		token: TokenId,2178		amount: u128,2179		budget: &dyn Budget,2180	) -> DispatchResultWithPostInfo;21812182	/// Check permission to nest token.2183	///2184	/// * `sender` - The user who initiated the check.2185	/// * `from` - The token that is checked for embedding.2186	/// * `under` - Token under which to check.2187	/// * `budget` - The maximum budget that can be spent on the check.2188	fn check_nesting(2189		&self,2190		sender: &T::CrossAccountId,2191		from: (CollectionId, TokenId),2192		under: TokenId,2193		budget: &dyn Budget,2194	) -> DispatchResult;21952196	/// Nest one token into another.2197	///2198	/// * `under` - Token holder.2199	/// * `to_nest` - Nested token.2200	fn nest(&self, under: TokenId, to_nest: (CollectionId, TokenId));22012202	/// Unnest token.2203	///2204	/// * `under` - Token holder.2205	/// * `to_nest` - Token to unnest.2206	fn unnest(&self, under: TokenId, to_nest: (CollectionId, TokenId));22072208	/// Get all user tokens.2209	///2210	/// * `account` - Account for which you need to get tokens.2211	fn account_tokens(&self, account: T::CrossAccountId) -> Vec<TokenId>;22122213	/// Get all the tokens in the collection.2214	fn collection_tokens(&self) -> Vec<TokenId>;22152216	/// Check if the token exists.2217	///2218	/// * `token` - Id token to check.2219	fn token_exists(&self, token: TokenId) -> bool;22202221	/// Get the id of the last minted token.2222	fn last_token_id(&self) -> TokenId;22232224	/// Get the owner of the token.2225	///2226	/// * `token` - The token for which you need to find out the owner.2227	fn token_owner(&self, token: TokenId) -> Result<T::CrossAccountId, TokenOwnerError>;22282229	/// Checks if the `maybe_owner` is the indirect owner of the `token`.2230	///2231	/// * `token` - Id token to check.2232	/// * `maybe_owner` - The account to check.2233	/// * `nesting_budget` - A budget that can be spent on nesting tokens.2234	fn check_token_indirect_owner(2235		&self,2236		token: TokenId,2237		maybe_owner: &T::CrossAccountId,2238		nesting_budget: &dyn Budget,2239	) -> Result<bool, DispatchError>;22402241	/// Returns 10 tokens owners in no particular order.2242	///2243	/// * `token` - The token for which you need to find out the owners.2244	fn token_owners(&self, token: TokenId) -> Vec<T::CrossAccountId>;22452246	/// Get the value of the token property by key.2247	///2248	/// * `token` - Token with the property to get.2249	/// * `key` - Property name.2250	fn token_property(&self, token_id: TokenId, key: &PropertyKey) -> Option<PropertyValue>;22512252	/// Get a set of token properties by key vector.2253	///2254	/// * `token` - Token with the property to get.2255	/// * `keys` - Vector of property keys. If this parameter is [None](sp_std::result::Result),2256	/// then all properties are returned.2257	fn token_properties(&self, token: TokenId, keys: Option<Vec<PropertyKey>>) -> Vec<Property>;22582259	/// Amount of unique collection tokens2260	fn total_supply(&self) -> u32;22612262	/// Amount of different tokens account has.2263	///2264	/// * `account` - The account for which need to get the balance.2265	fn account_balance(&self, account: T::CrossAccountId) -> u32;22662267	/// Amount of specific token account have.2268	fn balance(&self, account: T::CrossAccountId, token: TokenId) -> u128;22692270	/// Amount of token pieces2271	fn total_pieces(&self, token: TokenId) -> Option<u128>;22722273	/// Get the number of parts of the token that a trusted user can manage.2274	///2275	/// * `sender` - Trusted user.2276	/// * `spender` - Owner of the token.2277	/// * `token` - The token for which to get the value.2278	fn allowance(2279		&self,2280		sender: T::CrossAccountId,2281		spender: T::CrossAccountId,2282		token: TokenId,2283	) -> u128;22842285	/// Get extension for RFT collection.2286	fn refungible_extensions(&self) -> Option<&dyn RefungibleExtensions<T>> {2287		None2288	}22892290	/// Get XCM extensions.2291	fn xcm_extensions(&self) -> Option<&dyn XcmExtensions<T>> {2292		None2293	}22942295	/// The `operator` is allowed to transfer all tokens of the `owner` on their behalf.2296	/// * `owner` - Token owner2297	/// * `operator` - Operator2298	/// * `approve` - Should operator status be granted or revoked?2299	fn set_allowance_for_all(2300		&self,2301		owner: T::CrossAccountId,2302		operator: T::CrossAccountId,2303		approve: bool,2304	) -> DispatchResultWithPostInfo;23052306	/// Tells whether the given `owner` approves the `operator`.2307	fn allowance_for_all(&self, owner: T::CrossAccountId, operator: T::CrossAccountId) -> bool;23082309	/// Repairs a possibly broken item.2310	fn repair_item(&self, token: TokenId) -> DispatchResultWithPostInfo;2311}23122313/// Extension for RFT collection.2314pub trait RefungibleExtensions<T>2315where2316	T: Config,2317{2318	/// Change the number of parts of the token.2319	///2320	/// When the value changes down, this function is equivalent to burning parts of the token.2321	///2322	/// * `sender` - The user calling the repartition operation. Must be the owner of the token.2323	/// * `token` - The token for which you want to change the number of parts.2324	/// * `amount` - The new value of the parts of the token.2325	fn repartition(2326		&self,2327		sender: &T::CrossAccountId,2328		token: TokenId,2329		amount: u128,2330	) -> DispatchResultWithPostInfo;2331}23322333/// XCM extensions for fungible and NFT collections2334pub trait XcmExtensions<T>2335where2336	T: Config,2337{2338	/// Does the token have children?2339	fn token_has_children(&self, _token: TokenId) -> bool {2340		false2341	}23422343	/// Create a collection's item using a transaction.2344	///2345	/// This function performs additional XCM-related checks before the actual creation.2346	#[transactional]2347	fn create_item(2348		&self,2349		depositor: &T::CrossAccountId,2350		to: T::CrossAccountId,2351		data: CreateItemData,2352		nesting_budget: &dyn Budget,2353	) -> Result<TokenId, DispatchError> {2354		if T::CrossTokenAddressMapping::is_token_address(&to) {2355			return unsupported!(T);2356		}23572358		self.create_item_internal(depositor, to, data, nesting_budget)2359	}23602361	/// Create a collection's item.2362	fn create_item_internal(2363		&self,2364		depositor: &T::CrossAccountId,2365		to: T::CrossAccountId,2366		data: CreateItemData,2367		nesting_budget: &dyn Budget,2368	) -> Result<TokenId, DispatchError>;23692370	/// Transfer an item from the `from` account to the `to` account using a transaction.2371	///2372	/// This function performs additional XCM-related checks before the actual transfer.2373	#[transactional]2374	fn transfer_item(2375		&self,2376		depositor: &T::CrossAccountId,2377		from: &T::CrossAccountId,2378		to: &T::CrossAccountId,2379		token: TokenId,2380		amount: u128,2381		nesting_budget: &dyn Budget,2382	) -> DispatchResult {2383		if T::CrossTokenAddressMapping::is_token_address(to) {2384			return unsupported!(T);2385		}23862387		if self.token_has_children(token) {2388			return unsupported!(T);2389		}23902391		self.transfer_item_internal(depositor, from, to, token, amount, nesting_budget)2392	}23932394	/// Transfer an item from the `from` account to the `to` account.2395	fn transfer_item_internal(2396		&self,2397		depositor: &T::CrossAccountId,2398		from: &T::CrossAccountId,2399		to: &T::CrossAccountId,2400		token: TokenId,2401		amount: u128,2402		nesting_budget: &dyn Budget,2403	) -> DispatchResult;24042405	/// Burn a collection's item using a transaction.2406	#[transactional]2407	fn burn_item(&self, from: T::CrossAccountId, token: TokenId, amount: u128) -> DispatchResult {2408		self.burn_item_internal(from, token, amount)2409	}24102411	/// Burn a collection's item.2412	fn burn_item_internal(2413		&self,2414		from: T::CrossAccountId,2415		token: TokenId,2416		amount: u128,2417	) -> DispatchResult;2418}24192420/// Merge [`DispatchResult`] with [`Weight`] into [`DispatchResultWithPostInfo`].2421///2422/// Used for [`CommonCollectionOperations`] implementations and flexible enough to do so.2423pub fn with_weight(res: DispatchResult, weight: Weight) -> DispatchResultWithPostInfo {2424	let post_info = PostDispatchInfo {2425		actual_weight: Some(weight),2426		pays_fee: Pays::Yes,2427	};2428	match res {2429		Ok(()) => Ok(post_info),2430		Err(error) => Err(DispatchErrorWithPostInfo { post_info, error }),2431	}2432}24332434impl<T: Config> From<PropertiesError> for Error<T> {2435	fn from(error: PropertiesError) -> Self {2436		match error {2437			PropertiesError::NoSpaceForProperty => Self::NoSpaceForProperty,2438			PropertiesError::PropertyLimitReached => Self::PropertyLimitReached,2439			PropertiesError::InvalidCharacterInPropertyKey => Self::InvalidCharacterInPropertyKey,2440			PropertiesError::PropertyKeyIsTooLong => Self::PropertyKeyIsTooLong,2441			PropertiesError::EmptyPropertyKey => Self::EmptyPropertyKey,2442		}2443	}2444}24452446/// The type-safe interface for writing properties (setting or deleting) to tokens.2447/// It has two distinct implementations for newly created tokens and existing ones.2448///2449/// This type utilizes the lazy evaluation to avoid repeating the computation2450/// of several performance-heavy or PoV-heavy tasks,2451/// such as checking the indirect ownership or reading the token property permissions.2452pub struct PropertyWriter<'a, WriterVariant, T, Handle> {2453	collection: &'a Handle,2454	collection_lazy_info: PropertyWriterLazyCollectionInfo<'a>,2455	_phantom: PhantomData<(T, WriterVariant)>,2456}24572458impl<'a, T, Handle, WriterVariant> PropertyWriter<'a, WriterVariant, T, Handle>2459where2460	T: Config,2461	Handle: CommonCollectionOperations<T> + Deref<Target = CollectionHandle<T>>,2462{2463	fn internal_write_token_properties(2464		&mut self,2465		token_id: TokenId,2466		mut token_lazy_info: PropertyWriterLazyTokenInfo,2467		properties_updates: impl Iterator<Item = (PropertyKey, Option<PropertyValue>)>,2468		log: evm_coder::ethereum::Log,2469	) -> DispatchResult {2470		for (key, value) in properties_updates {2471			let permission = self2472				.collection_lazy_info2473				.property_permissions2474				.value()2475				.get(&key)2476				.cloned()2477				.unwrap_or_else(PropertyPermission::none);24782479			match permission {2480				PropertyPermission { mutable: false, .. }2481					if token_lazy_info2482						.stored_properties2483						.value()2484						.get(&key)2485						.is_some() =>2486				{2487					return Err(<Error<T>>::NoPermission.into());2488				}24892490				PropertyPermission {2491					collection_admin,2492					token_owner,2493					..2494				} => check_token_permissions::<T>(2495					collection_admin,2496					token_owner,2497					&mut self.collection_lazy_info.is_collection_admin,2498					&mut token_lazy_info.is_token_owner,2499					&mut token_lazy_info.is_token_exist,2500				)?,2501			}25022503			match value {2504				Some(value) => {2505					token_lazy_info2506						.stored_properties2507						.value_mut()2508						.try_set(key.clone(), value)2509						.map_err(<Error<T>>::from)?;25102511					<Pallet<T>>::deposit_event(Event::TokenPropertySet(2512						self.collection.id,2513						token_id,2514						key,2515					));2516				}2517				None => {2518					token_lazy_info2519						.stored_properties2520						.value_mut()2521						.remove(&key)2522						.map_err(<Error<T>>::from)?;25232524					<Pallet<T>>::deposit_event(Event::TokenPropertyDeleted(2525						self.collection.id,2526						token_id,2527						key,2528					));2529				}2530			}2531		}25322533		let properties_changed = token_lazy_info.stored_properties.has_value();2534		if properties_changed {2535			<PalletEvm<T>>::deposit_log(log);25362537			self.collection2538				.set_token_properties_raw(token_id, token_lazy_info.stored_properties.into_inner());2539		}25402541		Ok(())2542	}2543}25442545/// A helper structure for the [`PropertyWriter`] that holds2546/// the collection-related info. The info is loaded using lazy evaluation.2547/// This info is common for any token for which we write properties.2548pub struct PropertyWriterLazyCollectionInfo<'a> {2549	is_collection_admin: LazyValue<'a, bool>,2550	property_permissions: LazyValue<'a, PropertiesPermissionMap>,2551}25522553/// A helper structure for the [`PropertyWriter`] that holds2554/// the token-related info. The info is loaded using lazy evaluation.2555pub struct PropertyWriterLazyTokenInfo<'a> {2556	is_token_exist: LazyValue<'a, bool>,2557	is_token_owner: LazyValue<'a, Result<bool, DispatchError>>,2558	stored_properties: LazyValue<'a, TokenProperties>,2559}25602561impl<'a> PropertyWriterLazyTokenInfo<'a> {2562	/// Create a lazy token info.2563	pub fn new(2564		check_token_exist: impl FnOnce() -> bool + 'a,2565		check_token_owner: impl FnOnce() -> Result<bool, DispatchError> + 'a,2566		get_token_properties: impl FnOnce() -> TokenProperties + 'a,2567	) -> Self {2568		Self {2569			is_token_exist: LazyValue::new(check_token_exist),2570			is_token_owner: LazyValue::new(check_token_owner),2571			stored_properties: LazyValue::new(get_token_properties),2572		}2573	}2574}25752576/// A marker structure that enables the writer implementation2577/// to provide the interface to write properties to **newly created** tokens.2578pub struct NewTokenPropertyWriter<T>(PhantomData<T>);2579impl<T: Config> NewTokenPropertyWriter<T> {2580	/// Creates a [`PropertyWriter`] for **newly created** tokens.2581	pub fn new<'a, Handle>(2582		collection: &'a Handle,2583		sender: &'a T::CrossAccountId,2584	) -> PropertyWriter<'a, Self, T, Handle>2585	where2586		T: Config,2587		Handle: CommonCollectionOperations<T> + Deref<Target = CollectionHandle<T>>,2588	{2589		PropertyWriter {2590			collection,2591			collection_lazy_info: PropertyWriterLazyCollectionInfo {2592				is_collection_admin: LazyValue::new(|| collection.is_owner_or_admin(sender)),2593				property_permissions: LazyValue::new(|| {2594					<Pallet<T>>::property_permissions(collection.id)2595				}),2596			},2597			_phantom: PhantomData,2598		}2599	}2600}26012602impl<'a, T, Handle> PropertyWriter<'a, NewTokenPropertyWriter<T>, T, Handle>2603where2604	T: Config,2605	Handle: CommonCollectionOperations<T> + Deref<Target = CollectionHandle<T>>,2606{2607	/// A function to write properties to a **newly created** token.2608	pub fn write_token_properties(2609		&mut self,2610		mint_target_is_sender: bool,2611		token_id: TokenId,2612		properties_updates: impl Iterator<Item = Property>,2613		log: evm_coder::ethereum::Log,2614	) -> DispatchResult {2615		let check_token_exist = || {2616			debug_assert!(self.collection.token_exists(token_id));2617			true2618		};26192620		let check_token_owner = || Ok(mint_target_is_sender);26212622		let get_token_properties = || {2623			debug_assert!(self.collection.get_token_properties_raw(token_id).is_none());2624			TokenProperties::new()2625		};26262627		self.internal_write_token_properties(2628			token_id,2629			PropertyWriterLazyTokenInfo::new(2630				check_token_exist,2631				check_token_owner,2632				get_token_properties,2633			),2634			properties_updates.map(|p| (p.key, Some(p.value))),2635			log,2636		)2637	}2638}26392640/// A marker structure that enables the writer implementation2641/// to provide the interface to write properties to **already existing** tokens.2642pub struct ExistingTokenPropertyWriter<T>(PhantomData<T>);2643impl<T: Config> ExistingTokenPropertyWriter<T> {2644	/// Creates a [`PropertyWriter`] for **already existing** tokens.2645	pub fn new<'a, Handle>(2646		collection: &'a Handle,2647		sender: &'a T::CrossAccountId,2648	) -> PropertyWriter<'a, Self, T, Handle>2649	where2650		Handle: CommonCollectionOperations<T> + Deref<Target = CollectionHandle<T>>,2651	{2652		PropertyWriter {2653			collection,2654			collection_lazy_info: PropertyWriterLazyCollectionInfo {2655				is_collection_admin: LazyValue::new(|| collection.is_owner_or_admin(sender)),2656				property_permissions: LazyValue::new(|| {2657					<Pallet<T>>::property_permissions(collection.id)2658				}),2659			},2660			_phantom: PhantomData,2661		}2662	}2663}26642665impl<'a, T, Handle> PropertyWriter<'a, ExistingTokenPropertyWriter<T>, T, Handle>2666where2667	T: Config,2668	Handle: CommonCollectionOperations<T> + Deref<Target = CollectionHandle<T>>,2669{2670	/// A function to write properties to an **already existing** token.2671	pub fn write_token_properties(2672		&mut self,2673		sender: &T::CrossAccountId,2674		token_id: TokenId,2675		properties_updates: impl Iterator<Item = (PropertyKey, Option<PropertyValue>)>,2676		nesting_budget: &dyn Budget,2677		log: evm_coder::ethereum::Log,2678	) -> DispatchResult {2679		let check_token_exist = || self.collection.token_exists(token_id);2680		let check_token_owner = || {2681			self.collection2682				.check_token_indirect_owner(token_id, sender, nesting_budget)2683		};2684		let get_token_properties = || {2685			self.collection2686				.get_token_properties_raw(token_id)2687				.unwrap_or_default()2688		};26892690		self.internal_write_token_properties(2691			token_id,2692			PropertyWriterLazyTokenInfo::new(2693				check_token_exist,2694				check_token_owner,2695				get_token_properties,2696			),2697			properties_updates,2698			log,2699		)2700	}2701}27022703/// A marker structure that enables the writer implementation2704/// to benchmark the token properties writing.2705#[cfg(feature = "runtime-benchmarks")]2706pub struct BenchmarkPropertyWriter<T>(PhantomData<T>);27072708#[cfg(feature = "runtime-benchmarks")]2709impl<T: Config> BenchmarkPropertyWriter<T> {2710	/// Creates a [`PropertyWriter`] for benchmarking tokens properties writing.2711	pub fn new<'a, Handle>(2712		collection: &'a Handle,2713		collection_lazy_info: PropertyWriterLazyCollectionInfo<'a>,2714	) -> PropertyWriter<'a, Self, T, Handle>2715	where2716		Handle: CommonCollectionOperations<T> + Deref<Target = CollectionHandle<T>>,2717	{2718		PropertyWriter {2719			collection,2720			collection_lazy_info,2721			_phantom: PhantomData,2722		}2723	}27242725	/// Load the [`PropertyWriterLazyCollectionInfo`] from the storage.2726	pub fn load_collection_info<Handle>(2727		collection_handle: &Handle,2728		sender: &T::CrossAccountId,2729	) -> PropertyWriterLazyCollectionInfo<'static>2730	where2731		Handle: Deref<Target = CollectionHandle<T>>,2732	{2733		let is_collection_admin = collection_handle.is_owner_or_admin(sender);2734		let property_permissions = <Pallet<T>>::property_permissions(collection_handle.id);27352736		PropertyWriterLazyCollectionInfo {2737			is_collection_admin: LazyValue::new(move || is_collection_admin),2738			property_permissions: LazyValue::new(move || property_permissions),2739		}2740	}27412742	/// Load the [`PropertyWriterLazyTokenInfo`] with token properties from the storage.2743	pub fn load_token_properties<Handle>(2744		collection: &Handle,2745		token_id: TokenId,2746	) -> PropertyWriterLazyTokenInfo2747	where2748		Handle: CommonCollectionOperations<T>,2749	{2750		let stored_properties = collection2751			.get_token_properties_raw(token_id)2752			.unwrap_or_default();27532754		PropertyWriterLazyTokenInfo {2755			is_token_exist: LazyValue::new(|| true),2756			is_token_owner: LazyValue::new(|| Ok(true)),2757			stored_properties: LazyValue::new(move || stored_properties),2758		}2759	}2760}27612762#[cfg(feature = "runtime-benchmarks")]2763impl<'a, T, Handle> PropertyWriter<'a, BenchmarkPropertyWriter<T>, T, Handle>2764where2765	T: Config,2766	Handle: CommonCollectionOperations<T> + Deref<Target = CollectionHandle<T>>,2767{2768	/// A function to benchmark the writing of token properties.2769	pub fn write_token_properties(2770		&mut self,2771		token_id: TokenId,2772		properties_updates: impl Iterator<Item = Property>,2773		log: evm_coder::ethereum::Log,2774	) -> DispatchResult {2775		let check_token_exist = || true;2776		let check_token_owner = || Ok(true);2777		let get_token_properties = TokenProperties::new;27782779		self.internal_write_token_properties(2780			token_id,2781			PropertyWriterLazyTokenInfo::new(2782				check_token_exist,2783				check_token_owner,2784				get_token_properties,2785			),2786			properties_updates.map(|p| (p.key, Some(p.value))),2787			log,2788		)2789	}2790}27912792/// Computes the weight of writing properties to tokens.2793/// * `properties_nums` - The properties num of each created token.2794/// * `per_token_weight_weight` - The function to obtain the weight2795/// of writing properties from a token's properties num.2796pub fn write_token_properties_total_weight<T: Config, I: Fn(u32) -> Weight>(2797	properties_nums: impl Iterator<Item = u32>,2798	per_token_weight: I,2799) -> Weight {2800	let mut weight = properties_nums2801		.filter_map(|properties_num| {2802			if properties_num > 0 {2803				Some(per_token_weight(properties_num))2804			} else {2805				None2806			}2807		})2808		.fold(Weight::zero(), |a, b| a.saturating_add(b));28092810	if !weight.is_zero() {2811		// If we are here, it means the token properties were written at least once.2812		// Because of that, some common collection data was also loaded; we must add this weight.2813		// However, this common data was loaded only once, which is guaranteed by the `PropertyWriter`.28142815		weight = weight.saturating_add(<SelfWeightOf<T>>::property_writer_load_collection_info());2816	}28172818	weight2819}28202821#[cfg(any(feature = "tests", test))]2822#[allow(missing_docs)]2823pub mod tests {2824	use crate::{Config, DispatchError, DispatchResult, LazyValue};28252826	const fn to_bool(u: u8) -> bool {2827		u != 02828	}28292830	#[derive(Debug)]2831	pub struct TestCase {2832		pub collection_admin: bool,2833		pub is_collection_admin: bool,2834		pub token_owner: bool,2835		pub is_token_owner: bool,2836		pub no_permission: bool,2837	}28382839	impl TestCase {2840		const fn new(2841			collection_admin: u8,2842			is_collection_admin: u8,2843			token_owner: u8,2844			is_token_owner: u8,2845			no_permission: u8,2846		) -> Self {2847			Self {2848				collection_admin: to_bool(collection_admin),2849				is_collection_admin: to_bool(is_collection_admin),2850				token_owner: to_bool(token_owner),2851				is_token_owner: to_bool(is_token_owner),2852				no_permission: to_bool(no_permission),2853			}2854		}2855	}28562857	#[rustfmt::skip]2858	pub const TABLE: [TestCase; 16] = [2859		//                    ┌╴collection_admin2860		//                    │  ┌╴is_collection_admin2861		//                    │  │   ┌╴token_owner2862		//                    │  │   │  ┌╴is_token_ownership2863		//                    │  │   │  │   ┌╴no_permission2864		/*  0*/ TestCase::new(0, 0,  0, 0,  1),2865		/*  1*/ TestCase::new(0, 0,  0, 1,  1),2866		/*  2*/ TestCase::new(0, 0,  1, 0,  1),2867		/*  3*/ TestCase::new(0, 0,  1, 1,  0),2868		/*  4*/ TestCase::new(0, 1,  0, 0,  1),2869		/*  5*/ TestCase::new(0, 1,  0, 1,  1),2870		/*  6*/ TestCase::new(0, 1,  1, 0,  1),2871		/*  7*/ TestCase::new(0, 1,  1, 1,  0),2872		/*  8*/ TestCase::new(1, 0,  0, 0,  1),2873		/*  9*/ TestCase::new(1, 0,  0, 1,  1),2874		/* 10*/ TestCase::new(1, 0,  1, 0,  1),2875		/* 11*/ TestCase::new(1, 0,  1, 1,  0),2876		/* 12*/ TestCase::new(1, 1,  0, 0,  0),2877		/* 13*/ TestCase::new(1, 1,  0, 1,  0),2878		/* 14*/ TestCase::new(1, 1,  1, 0,  0),2879		/* 15*/ TestCase::new(1, 1,  1, 1,  0),2880	];28812882	pub fn check_token_permissions<T: Config>(2883		collection_admin_permitted: bool,2884		token_owner_permitted: bool,2885		is_collection_admin: &mut LazyValue<bool>,2886		check_token_ownership: &mut LazyValue<Result<bool, DispatchError>>,2887		check_token_existence: &mut LazyValue<bool>,2888	) -> DispatchResult {2889		crate::check_token_permissions::<T>(2890			collection_admin_permitted,2891			token_owner_permitted,2892			is_collection_admin,2893			check_token_ownership,2894			check_token_existence,2895		)2896	}2897}
modifiedpallets/foreign-assets/src/lib.rsdiffbeforeafterboth
--- a/pallets/foreign-assets/src/lib.rs
+++ b/pallets/foreign-assets/src/lib.rs
@@ -396,10 +396,6 @@
 		let token_id = Self::asset_instance_to_token_id(collection_id, asset_instance)?
 			.ok_or(XcmError::AssetNotFound)?;
 
-		if xcm_ext.token_has_children(token_id) {
-			return Err(XcmError::Unimplemented);
-		}
-
 		let depositor = &from;
 		let to = Self::pallet_account();
 		let amount = 1;