git.delta.rocks / unique-network / refs/commits / 12f11314c194

difftreelog

style fix formatting

Yaroslav Bolyukin2023-02-05parent: #586a87e.patch.diff
in: master

4 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 core::{57	ops::{Deref, DerefMut},58	slice::from_ref,59};60use pallet_evm_coder_substrate::{SubstrateRecorder, WithRecorder};61use sp_std::vec::Vec;62use pallet_evm::{account::CrossAccountId, Pallet as PalletEvm};63use evm_coder::ToLog;64use frame_support::{65	dispatch::{DispatchErrorWithPostInfo, DispatchResultWithPostInfo, Weight, PostDispatchInfo},66	ensure,67	traits::{Imbalance, Get, Currency, WithdrawReasons, ExistenceRequirement},68	dispatch::Pays,69	transactional, fail,70};71use pallet_evm::GasWeightMapping;72use up_data_structs::{73	AccessMode,74	COLLECTION_NUMBER_LIMIT,75	Collection,76	RpcCollection,77	CollectionFlags,78	RpcCollectionFlags,79	CollectionId,80	CreateItemData,81	MAX_TOKEN_PREFIX_LENGTH,82	COLLECTION_ADMINS_LIMIT,83	TokenId,84	TokenChild,85	CollectionStats,86	MAX_TOKEN_OWNERSHIP,87	CollectionMode,88	NFT_SPONSOR_TRANSFER_TIMEOUT,89	FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,90	REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,91	MAX_SPONSOR_TIMEOUT,92	CUSTOM_DATA_LIMIT,93	CollectionLimits,94	CreateCollectionData,95	SponsorshipState,96	CreateItemExData,97	SponsoringRateLimit,98	budget::Budget,99	PhantomType,100	Property,101	Properties,102	PropertiesPermissionMap,103	PropertyKey,104	PropertyValue,105	PropertyPermission,106	PropertiesError,107	TokenOwnerError,108	PropertyKeyPermission,109	TokenData,110	TrySetProperty,111	PropertyScope,112	CollectionPermissions,113};114use up_pov_estimate_rpc::PovInfo;115116pub use pallet::*;117use sp_core::H160;118use sp_runtime::{ArithmeticError, DispatchError, DispatchResult};119120use crate::erc::CollectionHelpersEvents;121#[cfg(feature = "runtime-benchmarks")]122pub mod benchmarking;123pub mod dispatch;124pub mod erc;125pub mod eth;126pub mod weights;127128/// Weight info.129pub type SelfWeightOf<T> = <T as Config>::WeightInfo;130131/// Collection handle contains information about collection data and id.132/// Also provides functionality to count consumed gas.133///134/// CollectionHandle is used as a generic wrapper for collections of all types.135/// It allows to perform common operations and queries on any collection type,136/// both completely general for all, as well as their respective implementations of [`CommonCollectionOperations`].137#[must_use = "Should call submit_logs or save, otherwise some data will be lost for evm side"]138pub struct CollectionHandle<T: Config> {139	/// Collection id140	pub id: CollectionId,141	collection: Collection<T::AccountId>,142	/// Substrate recorder for counting consumed gas143	pub recorder: SubstrateRecorder<T>,144}145146impl<T: Config> WithRecorder<T> for CollectionHandle<T> {147	fn recorder(&self) -> &SubstrateRecorder<T> {148		&self.recorder149	}150	fn into_recorder(self) -> SubstrateRecorder<T> {151		self.recorder152	}153}154155impl<T: Config> CollectionHandle<T> {156	/// Same as [CollectionHandle::new] but with an explicit gas limit.157	pub fn new_with_gas_limit(id: CollectionId, gas_limit: u64) -> Option<Self> {158		<CollectionById<T>>::get(id).map(|collection| Self {159			id,160			collection,161			recorder: SubstrateRecorder::new(gas_limit),162		})163	}164165	/// Same as [CollectionHandle::new] but with an existed [`SubstrateRecorder`].166	pub fn new_with_recorder(id: CollectionId, recorder: SubstrateRecorder<T>) -> Option<Self> {167		<CollectionById<T>>::get(id).map(|collection| Self {168			id,169			collection,170			recorder,171		})172	}173174	/// Retrives collection data from storage and creates collection handle with default parameters.175	/// If collection not found return `None`176	pub fn new(id: CollectionId) -> Option<Self> {177		Self::new_with_gas_limit(id, u64::MAX)178	}179180	/// Same as [`CollectionHandle::new`] but if collection not found [CollectionNotFound](Error::CollectionNotFound) returned.181	pub fn try_get(id: CollectionId) -> Result<Self, DispatchError> {182		Ok(Self::new(id).ok_or(<Error<T>>::CollectionNotFound)?)183	}184185	/// Consume gas for reading.186	pub fn consume_store_reads(187		&self,188		reads: u64,189	) -> pallet_evm_coder_substrate::execution::Result<()> {190		self.recorder191			.consume_gas(T::GasWeightMapping::weight_to_gas(Weight::from_ref_time(192				<T as frame_system::Config>::DbWeight::get()193					.read194					.saturating_mul(reads),195			)))196	}197198	/// Consume gas for writing.199	pub fn consume_store_writes(200		&self,201		writes: u64,202	) -> pallet_evm_coder_substrate::execution::Result<()> {203		self.recorder204			.consume_gas(T::GasWeightMapping::weight_to_gas(Weight::from_ref_time(205				<T as frame_system::Config>::DbWeight::get()206					.write207					.saturating_mul(writes),208			)))209	}210211	/// Consume gas for reading and writing.212	pub fn consume_store_reads_and_writes(213		&self,214		reads: u64,215		writes: u64,216	) -> pallet_evm_coder_substrate::execution::Result<()> {217		let weight = <T as frame_system::Config>::DbWeight::get();218		let reads = weight.read.saturating_mul(reads);219		let writes = weight.read.saturating_mul(writes);220		self.recorder221			.consume_gas(T::GasWeightMapping::weight_to_gas(Weight::from_ref_time(222				reads.saturating_add(writes),223			)))224	}225226	/// Save collection to storage.227	pub fn save(&self) -> DispatchResult {228		<CollectionById<T>>::insert(self.id, &self.collection);229		Ok(())230	}231232	/// Set collection sponsor.233	///234	/// Unique collections allows sponsoring for certain actions.235	/// This method allows you to set the sponsor of the collection.236	/// In order for sponsorship to become active, it must be confirmed through [`Self::confirm_sponsorship`].237	pub fn set_sponsor(238		&mut self,239		sender: &T::CrossAccountId,240		sponsor: T::AccountId,241	) -> DispatchResult {242		self.check_is_internal()?;243		self.check_is_owner_or_admin(sender)?;244245		self.collection.sponsorship = SponsorshipState::Unconfirmed(sponsor.clone());246247		<Pallet<T>>::deposit_event(Event::<T>::CollectionSponsorSet(self.id, sponsor));248		<PalletEvm<T>>::deposit_log(249			erc::CollectionHelpersEvents::CollectionChanged {250				collection_id: eth::collection_id_to_address(self.id),251			}252			.to_log(T::ContractAddress::get()),253		);254255		self.save()256	}257258	/// Force set `sponsor`.259	///260	/// Differs from [`set_sponsor`][`Self::set_sponsor`] in that confirmation261	/// from the `sponsor` is not required.262	///263	/// # Arguments264	///265	/// * `sender`: Caller's account.266	/// * `sponsor`: ID of the account of the sponsor-to-be.267	pub fn force_set_sponsor(&mut self, sponsor: T::AccountId) -> DispatchResult {268		self.check_is_internal()?;269270		self.collection.sponsorship = SponsorshipState::Confirmed(sponsor.clone());271272		<Pallet<T>>::deposit_event(Event::<T>::CollectionSponsorSet(self.id, sponsor.clone()));273		<Pallet<T>>::deposit_event(Event::<T>::SponsorshipConfirmed(self.id, sponsor));274		<PalletEvm<T>>::deposit_log(275			erc::CollectionHelpersEvents::CollectionChanged {276				collection_id: eth::collection_id_to_address(self.id),277			}278			.to_log(T::ContractAddress::get()),279		);280281		self.save()282	}283284	/// Confirm sponsorship285	///286	/// In order for the sponsorship to become active, the user set as the sponsor must confirm their participation.287	/// Before confirming sponsorship, the user must be specified as the sponsor of the collection via [`Self::set_sponsor`].288	pub fn confirm_sponsorship(&mut self, sender: &T::AccountId) -> DispatchResult {289		self.check_is_internal()?;290		ensure!(291			self.collection.sponsorship.pending_sponsor() == Some(sender),292			Error::<T>::ConfirmSponsorshipFail293		);294295		self.collection.sponsorship = SponsorshipState::Confirmed(sender.clone());296297		<Pallet<T>>::deposit_event(Event::<T>::SponsorshipConfirmed(self.id, sender.clone()));298		<PalletEvm<T>>::deposit_log(299			erc::CollectionHelpersEvents::CollectionChanged {300				collection_id: eth::collection_id_to_address(self.id),301			}302			.to_log(T::ContractAddress::get()),303		);304305		self.save()306	}307308	/// Remove collection sponsor.309	pub fn remove_sponsor(&mut self, sender: &T::CrossAccountId) -> DispatchResult {310		self.check_is_internal()?;311		self.check_is_owner_or_admin(sender)?;312313		self.collection.sponsorship = SponsorshipState::Disabled;314315		<Pallet<T>>::deposit_event(Event::<T>::CollectionSponsorRemoved(self.id));316		<PalletEvm<T>>::deposit_log(317			erc::CollectionHelpersEvents::CollectionChanged {318				collection_id: eth::collection_id_to_address(self.id),319			}320			.to_log(T::ContractAddress::get()),321		);322		self.save()323	}324325	/// Force remove `sponsor`.326	///327	/// Differs from `remove_sponsor` in that328	/// it doesn't require consent from the `owner` of the collection.329	pub fn force_remove_sponsor(&mut self) -> DispatchResult {330		self.check_is_internal()?;331332		self.collection.sponsorship = SponsorshipState::Disabled;333334		<Pallet<T>>::deposit_event(Event::<T>::CollectionSponsorRemoved(self.id));335		<PalletEvm<T>>::deposit_log(336			erc::CollectionHelpersEvents::CollectionChanged {337				collection_id: eth::collection_id_to_address(self.id),338			}339			.to_log(T::ContractAddress::get()),340		);341		self.save()342	}343344	/// Checks that the collection was created with, and must be operated upon through **Unique API**.345	/// Now check only the `external` flag and if it's **true**, then return [`Error::CollectionIsExternal`] error.346	pub fn check_is_internal(&self) -> DispatchResult {347		if self.flags.external {348			return Err(<Error<T>>::CollectionIsExternal)?;349		}350351		Ok(())352	}353354	/// Checks that the collection was created with, and must be operated upon through an **assimilated API**.355	/// Now check only the `external` flag and if it's **false**, then return [`Error::CollectionIsInternal`] error.356	pub fn check_is_external(&self) -> DispatchResult {357		if !self.flags.external {358			return Err(<Error<T>>::CollectionIsInternal)?;359		}360361		Ok(())362	}363}364365impl<T: Config> Deref for CollectionHandle<T> {366	type Target = Collection<T::AccountId>;367368	fn deref(&self) -> &Self::Target {369		&self.collection370	}371}372373impl<T: Config> DerefMut for CollectionHandle<T> {374	fn deref_mut(&mut self) -> &mut Self::Target {375		&mut self.collection376	}377}378379impl<T: Config> CollectionHandle<T> {380	/// Checks if the `user` is the owner of the collection.381	pub fn check_is_owner(&self, user: &T::CrossAccountId) -> DispatchResult {382		ensure!(*user.as_sub() == self.owner, <Error<T>>::NoPermission);383		Ok(())384	}385386	/// Returns **true** if the `user` is the owner or administrator of the collection.387	pub fn is_owner_or_admin(&self, user: &T::CrossAccountId) -> bool {388		*user.as_sub() == self.owner || <IsAdmin<T>>::get((self.id, user))389	}390391	/// Checks if the `user` is the owner or administrator of the collection.392	pub fn check_is_owner_or_admin(&self, user: &T::CrossAccountId) -> DispatchResult {393		ensure!(self.is_owner_or_admin(user), <Error<T>>::NoPermission);394		Ok(())395	}396397	/// Returns **true** if398	/// * the `user`is a collection owner or admin399	/// * the collection limits allow the owner/admins to transfer/burn any collection token400	pub fn ignores_token_restrictions(&self, user: &T::CrossAccountId) -> bool {401		self.limits.owner_can_transfer() && self.is_owner_or_admin(user)402	}403404	/// Return **true** if `user` does not have enough token parts, and he can ignore such restrictions.405	pub fn ignores_owned_amount(&self, user: &T::CrossAccountId) -> bool {406		self.limits.owner_can_transfer() && self.is_owner_or_admin(user)407	}408409	/// Checks if the user is in the allow list. If not [Error::AddressNotInAllowlist] returns.410	pub fn check_allowlist(&self, user: &T::CrossAccountId) -> DispatchResult {411		ensure!(412			<Allowlist<T>>::get((self.id, user)),413			<Error<T>>::AddressNotInAllowlist414		);415		Ok(())416	}417418	/// Changes collection owner to another account419	/// #### Store read/writes420	/// 1 writes421	pub fn change_owner(422		&mut self,423		caller: T::CrossAccountId,424		new_owner: T::CrossAccountId,425	) -> DispatchResult {426		self.check_is_internal()?;427		self.check_is_owner(&caller)?;428		self.collection.owner = new_owner.as_sub().clone();429430		<Pallet<T>>::deposit_event(Event::<T>::CollectionOwnerChanged(431			self.id,432			new_owner.as_sub().clone(),433		));434		<PalletEvm<T>>::deposit_log(435			erc::CollectionHelpersEvents::CollectionChanged {436				collection_id: eth::collection_id_to_address(self.id),437			}438			.to_log(T::ContractAddress::get()),439		);440441		self.save()442	}443}444445#[frame_support::pallet]446pub mod pallet {447	use super::*;448	use dispatch::CollectionDispatch;449	use frame_support::{Blake2_128Concat, pallet_prelude::*, storage::Key, traits::StorageVersion};450	use frame_system::pallet_prelude::*;451	use frame_support::traits::Currency;452	use up_data_structs::{TokenId, mapping::TokenAddressMapping};453	use scale_info::TypeInfo;454	use weights::WeightInfo;455456	#[pallet::config]457	pub trait Config:458		frame_system::Config + pallet_evm_coder_substrate::Config + pallet_evm::Config + TypeInfo459	{460		/// Weight information for functions of this pallet.461		type WeightInfo: WeightInfo;462463		/// Events compatible with [`frame_system::Config::Event`].464		type RuntimeEvent: IsType<<Self as frame_system::Config>::RuntimeEvent> + From<Event<Self>>;465466		/// Handler of accounts and payment.467		type Currency: Currency<Self::AccountId>;468469		/// Set price to create a collection.470		#[pallet::constant]471		type CollectionCreationPrice: Get<472			<<Self as Config>::Currency as Currency<Self::AccountId>>::Balance,473		>;474475		/// Dispatcher of operations on collections.476		type CollectionDispatch: CollectionDispatch<Self>;477478		/// Account which holds the chain's treasury.479		type TreasuryAccountId: Get<Self::AccountId>;480481		/// Address under which the CollectionHelper contract would be available.482		#[pallet::constant]483		type ContractAddress: Get<H160>;484485		/// Mapper for token addresses to Ethereum addresses.486		type EvmTokenAddressMapping: TokenAddressMapping<H160>;487488		/// Mapper for token addresses to [`CrossAccountId`].489		type CrossTokenAddressMapping: TokenAddressMapping<Self::CrossAccountId>;490	}491492	const STORAGE_VERSION: StorageVersion = StorageVersion::new(1);493494	#[pallet::pallet]495	#[pallet::storage_version(STORAGE_VERSION)]496	#[pallet::generate_store(pub(super) trait Store)]497	pub struct Pallet<T>(_);498499	#[pallet::extra_constants]500	impl<T: Config> Pallet<T> {501		/// Maximum admins per collection.502		pub fn collection_admins_limit() -> u32 {503			COLLECTION_ADMINS_LIMIT504		}505	}506507	impl<T: Config> Pallet<T> {508		/// Helper function that handles deposit events509		pub fn deposit_event(event: Event<T>) {510			let event = <T as Config>::RuntimeEvent::from(event);511			let event = event.into();512			<frame_system::Pallet<T>>::deposit_event(event)513		}514	}515516	#[pallet::event]517	pub enum Event<T: Config> {518		/// New collection was created519		CollectionCreated(520			/// Globally unique identifier of newly created collection.521			CollectionId,522			/// [`CollectionMode`] converted into _u8_.523			u8,524			/// Collection owner.525			T::AccountId,526		),527528		/// New collection was destroyed529		CollectionDestroyed(530			/// Globally unique identifier of collection.531			CollectionId,532		),533534		/// New item was created.535		ItemCreated(536			/// Id of the collection where item was created.537			CollectionId,538			/// Id of an item. Unique within the collection.539			TokenId,540			/// Owner of newly created item541			T::CrossAccountId,542			/// Always 1 for NFT543			u128,544		),545546		/// Collection item was burned.547		ItemDestroyed(548			/// Id of the collection where item was destroyed.549			CollectionId,550			/// Identifier of burned NFT.551			TokenId,552			/// Which user has destroyed its tokens.553			T::CrossAccountId,554			/// Amount of token pieces destroed. Always 1 for NFT.555			u128,556		),557558		/// Item was transferred559		Transfer(560			/// Id of collection to which item is belong.561			CollectionId,562			/// Id of an item.563			TokenId,564			/// Original owner of item.565			T::CrossAccountId,566			/// New owner of item.567			T::CrossAccountId,568			/// Amount of token pieces transfered. Always 1 for NFT.569			u128,570		),571572		/// Amount pieces of token owned by `sender` was approved for `spender`.573		Approved(574			/// Id of collection to which item is belong.575			CollectionId,576			/// Id of an item.577			TokenId,578			/// Original owner of item.579			T::CrossAccountId,580			/// Id for which the approval was granted.581			T::CrossAccountId,582			/// Amount of token pieces transfered. Always 1 for NFT.583			u128,584		),585586		/// A `sender` approves operations on all owned tokens for `spender`.587		ApprovedForAll(588			/// Id of collection to which item is belong.589			CollectionId,590			/// Owner of a wallet.591			T::CrossAccountId,592			/// Id for which operator status was granted or rewoked.593			T::CrossAccountId,594			/// Is operator status granted or revoked?595			bool,596		),597598		/// The colletion property has been added or edited.599		CollectionPropertySet(600			/// Id of collection to which property has been set.601			CollectionId,602			/// The property that was set.603			PropertyKey,604		),605606		/// The property has been deleted.607		CollectionPropertyDeleted(608			/// Id of collection to which property has been deleted.609			CollectionId,610			/// The property that was deleted.611			PropertyKey,612		),613614		/// The token property has been added or edited.615		TokenPropertySet(616			/// Identifier of the collection whose token has the property set.617			CollectionId,618			/// The token for which the property was set.619			TokenId,620			/// The property that was set.621			PropertyKey,622		),623624		/// The token property has been deleted.625		TokenPropertyDeleted(626			/// Identifier of the collection whose token has the property deleted.627			CollectionId,628			/// The token for which the property was deleted.629			TokenId,630			/// The property that was deleted.631			PropertyKey,632		),633634		/// The token property permission of a collection has been set.635		PropertyPermissionSet(636			/// ID of collection to which property permission has been set.637			CollectionId,638			/// The property permission that was set.639			PropertyKey,640		),641642		/// Address was added to the allow list.643		AllowListAddressAdded(644			/// ID of the affected collection.645			CollectionId,646			/// Address of the added account.647			T::CrossAccountId,648		),649650		/// Address was removed from the allow list.651		AllowListAddressRemoved(652			/// ID of the affected collection.653			CollectionId,654			/// Address of the removed account.655			T::CrossAccountId,656		),657658		/// Collection admin was added.659		CollectionAdminAdded(660			/// ID of the affected collection.661			CollectionId,662			/// Admin address.663			T::CrossAccountId,664		),665666		/// Collection admin was removed.667		CollectionAdminRemoved(668			/// ID of the affected collection.669			CollectionId,670			/// Removed admin address.671			T::CrossAccountId,672		),673674		/// Collection limits were set.675		CollectionLimitSet(676			/// ID of the affected collection.677			CollectionId,678		),679680		/// Collection owned was changed.681		CollectionOwnerChanged(682			/// ID of the affected collection.683			CollectionId,684			/// New owner address.685			T::AccountId,686		),687688		/// Collection permissions were set.689		CollectionPermissionSet(690			/// ID of the affected collection.691			CollectionId,692		),693694		/// Collection sponsor was set.695		CollectionSponsorSet(696			/// ID of the affected collection.697			CollectionId,698			/// New sponsor address.699			T::AccountId,700		),701702		/// New sponsor was confirm.703		SponsorshipConfirmed(704			/// ID of the affected collection.705			CollectionId,706			/// New sponsor address.707			T::AccountId,708		),709710		/// Collection sponsor was removed.711		CollectionSponsorRemoved(712			/// ID of the affected collection.713			CollectionId,714		),715	}716717	#[pallet::error]718	pub enum Error<T> {719		/// This collection does not exist.720		CollectionNotFound,721		/// Sender parameter and item owner must be equal.722		MustBeTokenOwner,723		/// No permission to perform action724		NoPermission,725		/// Destroying only empty collections is allowed726		CantDestroyNotEmptyCollection,727		/// Collection is not in mint mode.728		PublicMintingNotAllowed,729		/// Address is not in allow list.730		AddressNotInAllowlist,731732		/// Collection name can not be longer than 63 char.733		CollectionNameLimitExceeded,734		/// Collection description can not be longer than 255 char.735		CollectionDescriptionLimitExceeded,736		/// Token prefix can not be longer than 15 char.737		CollectionTokenPrefixLimitExceeded,738		/// Total collections bound exceeded.739		TotalCollectionsLimitExceeded,740		/// Exceeded max admin count741		CollectionAdminCountExceeded,742		/// Collection limit bounds per collection exceeded743		CollectionLimitBoundsExceeded,744		/// Tried to enable permissions which are only permitted to be disabled745		OwnerPermissionsCantBeReverted,746		/// Collection settings not allowing items transferring747		TransferNotAllowed,748		/// Account token limit exceeded per collection749		AccountTokenLimitExceeded,750		/// Collection token limit exceeded751		CollectionTokenLimitExceeded,752		/// Metadata flag frozen753		MetadataFlagFrozen,754755		/// Item does not exist756		TokenNotFound,757		/// Item is balance not enough758		TokenValueTooLow,759		/// Requested value is more than the approved760		ApprovedValueTooLow,761		/// Tried to approve more than owned762		CantApproveMoreThanOwned,763		/// Only spending from eth mirror could be approved764		AddressIsNotEthMirror,765766		/// Can't transfer tokens to ethereum zero address767		AddressIsZero,768769		/// The operation is not supported770		UnsupportedOperation,771772		/// Insufficient funds to perform an action773		NotSufficientFounds,774775		/// User does not satisfy the nesting rule776		UserIsNotAllowedToNest,777		/// Only tokens from specific collections may nest tokens under this one778		SourceCollectionIsNotAllowedToNest,779780		/// Tried to store more data than allowed in collection field781		CollectionFieldSizeExceeded,782783		/// Tried to store more property data than allowed784		NoSpaceForProperty,785786		/// Tried to store more property keys than allowed787		PropertyLimitReached,788789		/// Property key is too long790		PropertyKeyIsTooLong,791792		/// Only ASCII letters, digits, and symbols `_`, `-`, and `.` are allowed793		InvalidCharacterInPropertyKey,794795		/// Empty property keys are forbidden796		EmptyPropertyKey,797798		/// Tried to access an external collection with an internal API799		CollectionIsExternal,800801		/// Tried to access an internal collection with an external API802		CollectionIsInternal,803804		/// This address is not set as sponsor, use setCollectionSponsor first.805		ConfirmSponsorshipFail,806807		/// The user is not an administrator.808		UserIsNotCollectionAdmin,809	}810811	/// Storage of the count of created collections. Essentially contains the last collection ID.812	#[pallet::storage]813	pub type CreatedCollectionCount<T> = StorageValue<Value = CollectionId, QueryKind = ValueQuery>;814815	/// Storage of the count of deleted collections.816	#[pallet::storage]817	pub type DestroyedCollectionCount<T> =818		StorageValue<Value = CollectionId, QueryKind = ValueQuery>;819820	/// Storage of collection info.821	#[pallet::storage]822	pub type CollectionById<T> = StorageMap<823		Hasher = Blake2_128Concat,824		Key = CollectionId,825		Value = Collection<<T as frame_system::Config>::AccountId>,826		QueryKind = OptionQuery,827	>;828829	/// Storage of collection properties.830	#[pallet::storage]831	#[pallet::getter(fn collection_properties)]832	pub type CollectionProperties<T> = StorageMap<833		Hasher = Blake2_128Concat,834		Key = CollectionId,835		Value = Properties,836		QueryKind = ValueQuery,837		OnEmpty = up_data_structs::CollectionProperties,838	>;839840	/// Storage of token property permissions of a collection.841	#[pallet::storage]842	#[pallet::getter(fn property_permissions)]843	pub type CollectionPropertyPermissions<T> = StorageMap<844		Hasher = Blake2_128Concat,845		Key = CollectionId,846		Value = PropertiesPermissionMap,847		QueryKind = ValueQuery,848	>;849850	/// Storage of the amount of collection admins.851	#[pallet::storage]852	pub type AdminAmount<T> = StorageMap<853		Hasher = Blake2_128Concat,854		Key = CollectionId,855		Value = u32,856		QueryKind = ValueQuery,857	>;858859	/// List of collection admins.860	#[pallet::storage]861	pub type IsAdmin<T: Config> = StorageNMap<862		Key = (863			Key<Blake2_128Concat, CollectionId>,864			Key<Blake2_128Concat, T::CrossAccountId>,865		),866		Value = bool,867		QueryKind = ValueQuery,868	>;869870	/// Allowlisted collection users.871	#[pallet::storage]872	pub type Allowlist<T: Config> = StorageNMap<873		Key = (874			Key<Blake2_128Concat, CollectionId>,875			Key<Blake2_128Concat, T::CrossAccountId>,876		),877		Value = bool,878		QueryKind = ValueQuery,879	>;880881	/// Not used by code, exists only to provide some types to metadata.882	#[pallet::storage]883	pub type DummyStorageValue<T: Config> = StorageValue<884		Value = (885			CollectionStats,886			CollectionId,887			TokenId,888			TokenChild,889			PhantomType<(890				TokenData<T::CrossAccountId>,891				RpcCollection<T::AccountId>,892				// PoV Estimate Info893				PovInfo,894			)>,895		),896		QueryKind = OptionQuery,897	>;898899	#[pallet::hooks]900	impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {901		fn on_runtime_upgrade() -> Weight {902			StorageVersion::new(1).put::<Pallet<T>>();903904			Weight::zero()905		}906	}907}908909impl<T: Config> Pallet<T> {910	/// Enshure that receiver address is correct.911	///912	/// Ethereum receiver 0x0000000000000000000000000000000000000000 is reserved, and shouldn't own tokens.913	pub fn ensure_correct_receiver(receiver: &T::CrossAccountId) -> DispatchResult {914		ensure!(915			&T::CrossAccountId::from_eth(H160([0; 20])) != receiver,916			<Error<T>>::AddressIsZero917		);918		Ok(())919	}920921	/// Get a vector of collection admins.922	pub fn adminlist(collection: CollectionId) -> Vec<T::CrossAccountId> {923		<IsAdmin<T>>::iter_prefix((collection,))924			.map(|(a, _)| a)925			.collect()926	}927928	/// Get a vector of users allowed to mint tokens.929	pub fn allowlist(collection: CollectionId) -> Vec<T::CrossAccountId> {930		<Allowlist<T>>::iter_prefix((collection,))931			.map(|(a, _)| a)932			.collect()933	}934935	/// Is `user` allowed to mint token in `collection`.936	pub fn allowed(collection: CollectionId, user: T::CrossAccountId) -> bool {937		<Allowlist<T>>::get((collection, user))938	}939940	/// Get statistics of collections.941	pub fn collection_stats() -> CollectionStats {942		let created = <CreatedCollectionCount<T>>::get();943		let destroyed = <DestroyedCollectionCount<T>>::get();944		CollectionStats {945			created: created.0,946			destroyed: destroyed.0,947			alive: created.0 - destroyed.0,948		}949	}950951	/// Get the effective limits for the collection.952	pub fn effective_collection_limits(collection: CollectionId) -> Option<CollectionLimits> {953		let collection = <CollectionById<T>>::get(collection)?;954		let limits = collection.limits;955		let effective_limits = CollectionLimits {956			account_token_ownership_limit: Some(limits.account_token_ownership_limit()),957			sponsored_data_size: Some(limits.sponsored_data_size()),958			sponsored_data_rate_limit: Some(959				limits960					.sponsored_data_rate_limit961					.unwrap_or(SponsoringRateLimit::SponsoringDisabled),962			),963			token_limit: Some(limits.token_limit()),964			sponsor_transfer_timeout: Some(limits.sponsor_transfer_timeout(965				match collection.mode {966					CollectionMode::NFT => NFT_SPONSOR_TRANSFER_TIMEOUT,967					CollectionMode::Fungible(_) => FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,968					CollectionMode::ReFungible => REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,969				},970			)),971			sponsor_approve_timeout: Some(limits.sponsor_approve_timeout()),972			owner_can_transfer: Some(limits.owner_can_transfer()),973			owner_can_destroy: Some(limits.owner_can_destroy()),974			transfers_enabled: Some(limits.transfers_enabled()),975		};976977		Some(effective_limits)978	}979980	/// Returns information about the `collection` adapted for rpc.981	pub fn rpc_collection(collection: CollectionId) -> Option<RpcCollection<T::AccountId>> {982		let Collection {983			name,984			description,985			owner,986			mode,987			token_prefix,988			sponsorship,989			limits,990			permissions,991			flags,992		} = <CollectionById<T>>::get(collection)?;993994		let token_property_permissions = <CollectionPropertyPermissions<T>>::get(collection)995			.into_iter()996			.map(|(key, permission)| PropertyKeyPermission { key, permission })997			.collect();998999		let properties = <CollectionProperties<T>>::get(collection)1000			.into_iter()1001			.map(|(key, value)| Property { key, value })1002			.collect();10031004		let permissions = CollectionPermissions {1005			access: Some(permissions.access()),1006			mint_mode: Some(permissions.mint_mode()),1007			nesting: Some(permissions.nesting().clone()),1008		};10091010		Some(RpcCollection {1011			name: name.into_inner(),1012			description: description.into_inner(),1013			owner,1014			mode,1015			token_prefix: token_prefix.into_inner(),1016			sponsorship,1017			limits,1018			permissions,1019			token_property_permissions,1020			properties,1021			read_only: flags.external,10221023			flags: RpcCollectionFlags {1024				foreign: flags.foreign,1025				erc721metadata: flags.erc721metadata,1026			},1027		})1028	}1029}10301031macro_rules! limit_default {1032	($old:ident, $new:ident, $($field:ident $(($arg:expr))? => $check:expr),* $(,)?) => {{1033		$(1034			if let Some($new) = $new.$field {1035				let $old = $old.$field($($arg)?);1036				let _ = $new;1037				let _ = $old;1038				$check1039			} else {1040				$new.$field = $old.$field1041			}1042		)*1043	}};1044}1045macro_rules! limit_default_clone {1046	($old:ident, $new:ident, $($field:ident $(($arg:expr))? => $check:expr),* $(,)?) => {{1047		$(1048			if let Some($new) = $new.$field.clone() {1049				let $old = $old.$field($($arg)?);1050				let _ = $new;1051				let _ = $old;1052				$check1053			} else {1054				$new.$field = $old.$field.clone()1055			}1056		)*1057	}};1058}10591060impl<T: Config> Pallet<T> {1061	/// Create new collection.1062	///1063	/// * `owner` - The owner of the collection.1064	/// * `data` - Description of the created collection.1065	/// * `flags` - Extra flags to store.1066	pub fn init_collection(1067		owner: T::CrossAccountId,1068		payer: T::CrossAccountId,1069		data: CreateCollectionData<T::AccountId>,1070		flags: CollectionFlags,1071	) -> Result<CollectionId, DispatchError> {1072		{1073			ensure!(1074				data.token_prefix.len() <= MAX_TOKEN_PREFIX_LENGTH as usize,1075				Error::<T>::CollectionTokenPrefixLimitExceeded1076			);1077		}10781079		let created_count = <CreatedCollectionCount<T>>::get()1080			.01081			.checked_add(1)1082			.ok_or(ArithmeticError::Overflow)?;1083		let destroyed_count = <DestroyedCollectionCount<T>>::get().0;1084		let id = CollectionId(created_count);10851086		// bound Total number of collections1087		ensure!(1088			created_count - destroyed_count <= COLLECTION_NUMBER_LIMIT,1089			<Error<T>>::TotalCollectionsLimitExceeded1090		);10911092		// =========10931094		let collection = Collection {1095			owner: owner.as_sub().clone(),1096			name: data.name,1097			mode: data.mode.clone(),1098			description: data.description,1099			token_prefix: data.token_prefix,1100			sponsorship: data1101				.pending_sponsor1102				.map(SponsorshipState::Unconfirmed)1103				.unwrap_or_default(),1104			limits: data1105				.limits1106				.map(|limits| Self::clamp_limits(data.mode.clone(), &Default::default(), limits))1107				.unwrap_or_else(|| Ok(CollectionLimits::default()))?,1108			permissions: data1109				.permissions1110				.map(|permissions| {1111					Self::clamp_permissions(data.mode.clone(), &Default::default(), permissions)1112				})1113				.unwrap_or_else(|| Ok(CollectionPermissions::default()))?,1114			flags,1115		};11161117		let mut collection_properties = up_data_structs::CollectionProperties::get();1118		collection_properties1119			.try_set_from_iter(data.properties.into_iter())1120			.map_err(<Error<T>>::from)?;11211122		CollectionProperties::<T>::insert(id, collection_properties);11231124		let mut token_props_permissions = PropertiesPermissionMap::new();1125		token_props_permissions1126			.try_set_from_iter(data.token_property_permissions.into_iter())1127			.map_err(<Error<T>>::from)?;11281129		CollectionPropertyPermissions::<T>::insert(id, token_props_permissions);11301131		// Take a (non-refundable) deposit of collection creation1132		{1133			let mut imbalance =1134				<<<T as Config>::Currency as Currency<T::AccountId>>::PositiveImbalance>::zero();1135			imbalance.subsume(1136				<<T as Config>::Currency as Currency<T::AccountId>>::deposit_creating(1137					&T::TreasuryAccountId::get(),1138					T::CollectionCreationPrice::get(),1139				),1140			);1141			<T as Config>::Currency::settle(1142				payer.as_sub(),1143				imbalance,1144				WithdrawReasons::TRANSFER,1145				ExistenceRequirement::KeepAlive,1146			)1147			.map_err(|_| Error::<T>::NotSufficientFounds)?;1148		}11491150		<CreatedCollectionCount<T>>::put(created_count);1151		<Pallet<T>>::deposit_event(Event::CollectionCreated(1152			id,1153			data.mode.id(),1154			owner.as_sub().clone(),1155		));1156		<PalletEvm<T>>::deposit_log(1157			erc::CollectionHelpersEvents::CollectionCreated {1158				owner: *owner.as_eth(),1159				collection_id: eth::collection_id_to_address(id),1160			}1161			.to_log(T::ContractAddress::get()),1162		);1163		<CollectionById<T>>::insert(id, collection);1164		Ok(id)1165	}11661167	/// Destroy collection.1168	///1169	/// * `collection` - Collection handler.1170	/// * `sender` - The owner or administrator of the collection.1171	pub fn destroy_collection(1172		collection: CollectionHandle<T>,1173		sender: &T::CrossAccountId,1174	) -> DispatchResult {1175		ensure!(1176			collection.limits.owner_can_destroy(),1177			<Error<T>>::NoPermission,1178		);1179		collection.check_is_owner(sender)?;11801181		let destroyed_collections = <DestroyedCollectionCount<T>>::get()1182			.01183			.checked_add(1)1184			.ok_or(ArithmeticError::Overflow)?;11851186		// =========11871188		<DestroyedCollectionCount<T>>::put(destroyed_collections);1189		<CollectionById<T>>::remove(collection.id);1190		<AdminAmount<T>>::remove(collection.id);1191		let _ = <IsAdmin<T>>::clear_prefix((collection.id,), u32::MAX, None);1192		let _ = <Allowlist<T>>::clear_prefix((collection.id,), u32::MAX, None);1193		<CollectionProperties<T>>::remove(collection.id);11941195		<Pallet<T>>::deposit_event(Event::CollectionDestroyed(collection.id));11961197		<PalletEvm<T>>::deposit_log(1198			erc::CollectionHelpersEvents::CollectionDestroyed {1199				collection_id: eth::collection_id_to_address(collection.id),1200			}1201			.to_log(T::ContractAddress::get()),1202		);1203		Ok(())1204	}12051206	/// This function sets or removes a collection properties according to1207	/// `properties_updates` contents:1208	/// * sets a property under the <key> with the value provided `(<key>, Some(<value>))`1209	/// * removes a property under the <key> if the value is `None` `(<key>, None)`.1210	///1211	/// This function fires an event for each property change.1212	/// In case of an error, all the changes (including the events) will be reverted1213	/// since the function is transactional.1214	#[transactional]1215	fn modify_collection_properties(1216		collection: &CollectionHandle<T>,1217		sender: &T::CrossAccountId,1218		properties_updates: impl Iterator<Item = (PropertyKey, Option<PropertyValue>)>,1219	) -> DispatchResult {1220		collection.check_is_owner_or_admin(sender)?;12211222		let mut stored_properties = <CollectionProperties<T>>::get(collection.id);12231224		for (key, value) in properties_updates {1225			match value {1226				Some(value) => {1227					stored_properties1228						.try_set(key.clone(), value)1229						.map_err(<Error<T>>::from)?;12301231					Self::deposit_event(Event::CollectionPropertySet(collection.id, key));1232					<PalletEvm<T>>::deposit_log(1233						erc::CollectionHelpersEvents::CollectionChanged {1234							collection_id: eth::collection_id_to_address(collection.id),1235						}1236						.to_log(T::ContractAddress::get()),1237					);1238				}1239				None => {1240					stored_properties.remove(&key).map_err(<Error<T>>::from)?;12411242					Self::deposit_event(Event::CollectionPropertyDeleted(collection.id, key));1243					<PalletEvm<T>>::deposit_log(1244						erc::CollectionHelpersEvents::CollectionChanged {1245							collection_id: eth::collection_id_to_address(collection.id),1246						}1247						.to_log(T::ContractAddress::get()),1248					);1249				}1250			}1251		}12521253		<CollectionProperties<T>>::set(collection.id, stored_properties);12541255		Ok(())1256	}12571258	/// A batch operation to add, edit or remove properties for a token.1259	/// It sets or removes a token's properties according to1260	/// `properties_updates` contents:1261	/// * sets a property under the <key> with the value provided `(<key>, Some(<value>))`1262	/// * removes a property under the <key> if the value is `None` `(<key>, None)`.1263	///1264	/// - `nesting_budget`: Limit for searching parents in-depth to check ownership.1265	/// - `is_token_create`: Indicates that method is called during token initialization.1266	///   Allows to bypass ownership check.1267	///1268	/// All affected properties should have `mutable` permission1269	/// to be **deleted** or to be **set more than once**,1270	/// and the sender should have permission to edit those properties.1271	///1272	/// This function fires an event for each property change.1273	/// In case of an error, all the changes (including the events) will be reverted1274	/// since the function is transactional.1275	pub fn modify_token_properties(1276		collection: &CollectionHandle<T>,1277		sender: &T::CrossAccountId,1278		token_id: TokenId,1279		properties_updates: impl Iterator<Item = (PropertyKey, Option<PropertyValue>)>,1280		is_token_create: bool,1281		mut stored_properties: Properties,1282		is_token_owner: impl Fn() -> Result<bool, DispatchError>,1283		set_token_properties: impl FnOnce(Properties),1284	) -> DispatchResult {1285		let is_collection_admin = collection.is_owner_or_admin(sender);1286		let permissions = Self::property_permissions(collection.id);12871288		let mut token_owner_result = None;1289		let mut is_token_owner = || -> Result<bool, DispatchError> {1290			*token_owner_result.get_or_insert_with(&is_token_owner)1291		};12921293		for (key, value) in properties_updates {1294			let permission = permissions1295				.get(&key)1296				.cloned()1297				.unwrap_or_else(PropertyPermission::none);12981299			let is_property_exists = stored_properties.get(&key).is_some();13001301			match permission {1302				PropertyPermission { mutable: false, .. } if is_property_exists => {1303					return Err(<Error<T>>::NoPermission.into());1304				}13051306				PropertyPermission {1307					collection_admin,1308					token_owner,1309					..1310				} => {1311					//TODO: investigate threats during public minting.1312					let is_token_create =1313						is_token_create && (collection_admin || token_owner) && value.is_some();1314					if !(is_token_create1315						|| (collection_admin && is_collection_admin)1316						|| (token_owner && is_token_owner()?))1317					{1318						fail!(<Error<T>>::NoPermission);1319					}1320				}1321			}13221323			match value {1324				Some(value) => {1325					stored_properties1326						.try_set(key.clone(), value)1327						.map_err(<Error<T>>::from)?;13281329					Self::deposit_event(Event::TokenPropertySet(collection.id, token_id, key));1330				}1331				None => {1332					stored_properties.remove(&key).map_err(<Error<T>>::from)?;13331334					Self::deposit_event(Event::TokenPropertyDeleted(collection.id, token_id, key));1335				}1336			}13371338			<PalletEvm<T>>::deposit_log(1339				CollectionHelpersEvents::TokenChanged {1340					collection_id: eth::collection_id_to_address(collection.id),1341					token_id: token_id.into(),1342				}1343				.to_log(T::ContractAddress::get()),1344			);1345		}13461347		set_token_properties(stored_properties);13481349		Ok(())1350	}13511352	/// Sets or unsets the approval of a given operator.1353	///1354	/// The `operator` is allowed to transfer all token pieces of the `owner` on their behalf.1355	/// - `owner`: Token owner1356	/// - `operator`: Operator1357	/// - `approve`: Should operator status be granted or revoked?1358	pub fn set_allowance_for_all(1359		collection: &CollectionHandle<T>,1360		owner: &T::CrossAccountId,1361		operator: &T::CrossAccountId,1362		approve: bool,1363		set_allowance: impl FnOnce(),1364		log: evm_coder::ethereum::Log,1365	) -> DispatchResult {1366		if collection.permissions.access() == AccessMode::AllowList {1367			collection.check_allowlist(owner)?;1368			collection.check_allowlist(operator)?;1369		}13701371		Self::ensure_correct_receiver(operator)?;13721373		set_allowance();13741375		<PalletEvm<T>>::deposit_log(log);1376		Self::deposit_event(Event::ApprovedForAll(1377			collection.id,1378			owner.clone(),1379			operator.clone(),1380			approve,1381		));1382		Ok(())1383	}13841385	/// Set collection property.1386	///1387	/// * `collection` - Collection handler.1388	/// * `sender` - The owner or administrator of the collection.1389	/// * `property` - The property to set.1390	pub fn set_collection_property(1391		collection: &CollectionHandle<T>,1392		sender: &T::CrossAccountId,1393		property: Property,1394	) -> DispatchResult {1395		Self::set_collection_properties(collection, sender, [property].into_iter())1396	}13971398	/// Set a scoped collection property, where the scope is a special prefix1399	/// prohibiting a user access to change the property directly.1400	///1401	/// * `collection_id` - ID of the collection for which the property is being set.1402	/// * `scope` - Property scope.1403	/// * `property` - The property to set.1404	pub fn set_scoped_collection_property(1405		collection_id: CollectionId,1406		scope: PropertyScope,1407		property: Property,1408	) -> DispatchResult {1409		CollectionProperties::<T>::try_mutate(collection_id, |properties| {1410			properties.try_scoped_set(scope, property.key, property.value)1411		})1412		.map_err(<Error<T>>::from)?;14131414		Ok(())1415	}14161417	/// Set scoped collection properties, where the scope is a special prefix1418	/// prohibiting a user access to change the properties directly.1419	///1420	/// * `collection_id` - ID of the collection for which the properties is being set.1421	/// * `scope` - Property scope.1422	/// * `properties` - The properties to set.1423	pub fn set_scoped_collection_properties(1424		collection_id: CollectionId,1425		scope: PropertyScope,1426		properties: impl Iterator<Item = Property>,1427	) -> DispatchResult {1428		CollectionProperties::<T>::try_mutate(collection_id, |stored_properties| {1429			stored_properties.try_scoped_set_from_iter(scope, properties)1430		})1431		.map_err(<Error<T>>::from)?;14321433		Ok(())1434	}14351436	/// Set collection properties.1437	///1438	/// * `collection` - Collection handler.1439	/// * `sender` - The owner or administrator of the collection.1440	/// * `properties` - The properties to set.1441	pub fn set_collection_properties(1442		collection: &CollectionHandle<T>,1443		sender: &T::CrossAccountId,1444		properties: impl Iterator<Item = Property>,1445	) -> DispatchResult {1446		Self::modify_collection_properties(1447			collection,1448			sender,1449			properties.map(|property| (property.key, Some(property.value))),1450		)1451	}14521453	/// Delete collection property.1454	///1455	/// * `collection` - Collection handler.1456	/// * `sender` - The owner or administrator of the collection.1457	/// * `property` - The property to delete.1458	pub fn delete_collection_property(1459		collection: &CollectionHandle<T>,1460		sender: &T::CrossAccountId,1461		property_key: PropertyKey,1462	) -> DispatchResult {1463		Self::delete_collection_properties(collection, sender, [property_key].into_iter())1464	}14651466	/// Delete collection properties.1467	///1468	/// * `collection` - Collection handler.1469	/// * `sender` - The owner or administrator of the collection.1470	/// * `properties` - The properties to delete.1471	pub fn delete_collection_properties(1472		collection: &CollectionHandle<T>,1473		sender: &T::CrossAccountId,1474		property_keys: impl Iterator<Item = PropertyKey>,1475	) -> DispatchResult {1476		Self::modify_collection_properties(collection, sender, property_keys.map(|key| (key, None)))1477	}14781479	/// Set collection propetry permission without any checks.1480	///1481	/// Used for migrations.1482	///1483	/// * `collection` - Collection handler.1484	/// * `property_permissions` - Property permissions.1485	pub fn set_property_permission_unchecked(1486		collection: CollectionId,1487		property_permission: PropertyKeyPermission,1488	) -> DispatchResult {1489		<CollectionPropertyPermissions<T>>::try_mutate(collection, |permissions| {1490			permissions.try_set(property_permission.key, property_permission.permission)1491		})1492		.map_err(<Error<T>>::from)?;1493		Ok(())1494	}14951496	/// Set collection property permission.1497	///1498	/// * `collection` - Collection handler.1499	/// * `sender` - The owner or administrator of the collection.1500	/// * `property_permission` - Property permission.1501	pub fn set_property_permission(1502		collection: &CollectionHandle<T>,1503		sender: &T::CrossAccountId,1504		property_permission: PropertyKeyPermission,1505	) -> DispatchResult {1506		Self::set_scoped_property_permission(1507			collection,1508			sender,1509			PropertyScope::None,1510			property_permission,1511		)1512	}15131514	/// Set collection property permission with scope.1515	///1516	/// * `collection` - Collection handler.1517	/// * `sender` - The owner or administrator of the collection.1518	/// * `scope` - Property scope.1519	/// * `property_permission` - Property permission.1520	pub fn set_scoped_property_permission(1521		collection: &CollectionHandle<T>,1522		sender: &T::CrossAccountId,1523		scope: PropertyScope,1524		property_permission: PropertyKeyPermission,1525	) -> DispatchResult {1526		collection.check_is_owner_or_admin(sender)?;15271528		let all_permissions = CollectionPropertyPermissions::<T>::get(collection.id);1529		let current_permission = all_permissions.get(&property_permission.key);1530		if matches![1531			current_permission,1532			Some(PropertyPermission { mutable: false, .. })1533		] {1534			return Err(<Error<T>>::NoPermission.into());1535		}15361537		CollectionPropertyPermissions::<T>::try_mutate(collection.id, |permissions| {1538			let property_permission = property_permission.clone();1539			permissions.try_scoped_set(1540				scope,1541				property_permission.key,1542				property_permission.permission,1543			)1544		})1545		.map_err(<Error<T>>::from)?;15461547		Self::deposit_event(Event::PropertyPermissionSet(1548			collection.id,1549			property_permission.key,1550		));1551		<PalletEvm<T>>::deposit_log(1552			erc::CollectionHelpersEvents::CollectionChanged {1553				collection_id: eth::collection_id_to_address(collection.id),1554			}1555			.to_log(T::ContractAddress::get()),1556		);15571558		Ok(())1559	}15601561	/// Set token property permission.1562	///1563	/// * `collection` - Collection handler.1564	/// * `sender` - The owner or administrator of the collection.1565	/// * `property_permissions` - Property permissions.1566	#[transactional]1567	pub fn set_token_property_permissions(1568		collection: &CollectionHandle<T>,1569		sender: &T::CrossAccountId,1570		property_permissions: Vec<PropertyKeyPermission>,1571	) -> DispatchResult {1572		Self::set_scoped_token_property_permissions(1573			collection,1574			sender,1575			PropertyScope::None,1576			property_permissions,1577		)1578	}15791580	/// Set token property permission with scope.1581	///1582	/// * `collection` - Collection handler.1583	/// * `sender` - The owner or administrator of the collection.1584	/// * `scope` - Property scope.1585	/// * `property_permissions` - Property permissions.1586	#[transactional]1587	pub fn set_scoped_token_property_permissions(1588		collection: &CollectionHandle<T>,1589		sender: &T::CrossAccountId,1590		scope: PropertyScope,1591		property_permissions: Vec<PropertyKeyPermission>,1592	) -> DispatchResult {1593		for prop_pemission in property_permissions {1594			Self::set_scoped_property_permission(collection, sender, scope, prop_pemission)?;1595		}15961597		Ok(())1598	}15991600	/// Get collection property.1601	pub fn get_collection_property(1602		collection_id: CollectionId,1603		key: &PropertyKey,1604	) -> Option<PropertyValue> {1605		Self::collection_properties(collection_id).get(key).cloned()1606	}16071608	/// Convert byte vector to property key vector.1609	pub fn bytes_keys_to_property_keys(1610		keys: Vec<Vec<u8>>,1611	) -> Result<Vec<PropertyKey>, DispatchError> {1612		keys.into_iter()1613			.map(|key| -> Result<PropertyKey, DispatchError> {1614				key.try_into()1615					.map_err(|_| <Error<T>>::PropertyKeyIsTooLong.into())1616			})1617			.collect::<Result<Vec<PropertyKey>, DispatchError>>()1618	}16191620	/// Get properties according to given keys.1621	pub fn filter_collection_properties(1622		collection_id: CollectionId,1623		keys: Option<Vec<PropertyKey>>,1624	) -> Result<Vec<Property>, DispatchError> {1625		let properties = Self::collection_properties(collection_id);16261627		let properties = keys1628			.map(|keys| {1629				keys.into_iter()1630					.filter_map(|key| {1631						properties.get(&key).map(|value| Property {1632							key,1633							value: value.clone(),1634						})1635					})1636					.collect()1637			})1638			.unwrap_or_else(|| {1639				properties1640					.into_iter()1641					.map(|(key, value)| Property { key, value })1642					.collect()1643			});16441645		Ok(properties)1646	}16471648	/// Get property permissions according to given keys.1649	pub fn filter_property_permissions(1650		collection_id: CollectionId,1651		keys: Option<Vec<PropertyKey>>,1652	) -> Result<Vec<PropertyKeyPermission>, DispatchError> {1653		let permissions = Self::property_permissions(collection_id);16541655		let key_permissions = keys1656			.map(|keys| {1657				keys.into_iter()1658					.filter_map(|key| {1659						permissions1660							.get(&key)1661							.map(|permission| PropertyKeyPermission {1662								key,1663								permission: permission.clone(),1664							})1665					})1666					.collect()1667			})1668			.unwrap_or_else(|| {1669				permissions1670					.into_iter()1671					.map(|(key, permission)| PropertyKeyPermission { key, permission })1672					.collect()1673			});16741675		Ok(key_permissions)1676	}16771678	/// Toggle `user` participation in the `collection`'s allow list.1679	/// #### Store read/writes1680	/// 1 writes1681	pub fn toggle_allowlist(1682		collection: &CollectionHandle<T>,1683		sender: &T::CrossAccountId,1684		user: &T::CrossAccountId,1685		allowed: bool,1686	) -> DispatchResult {1687		collection.check_is_owner_or_admin(sender)?;16881689		// =========16901691		if allowed {1692			<Allowlist<T>>::insert((collection.id, user), true);1693			Self::deposit_event(Event::<T>::AllowListAddressAdded(1694				collection.id,1695				user.clone(),1696			));1697		} else {1698			<Allowlist<T>>::remove((collection.id, user));1699			Self::deposit_event(Event::<T>::AllowListAddressRemoved(1700				collection.id,1701				user.clone(),1702			));1703		}17041705		<PalletEvm<T>>::deposit_log(1706			erc::CollectionHelpersEvents::CollectionChanged {1707				collection_id: eth::collection_id_to_address(collection.id),1708			}1709			.to_log(T::ContractAddress::get()),1710		);17111712		Ok(())1713	}17141715	/// Toggle `user` participation in the `collection`'s admin list.1716	/// #### Store read/writes1717	/// 2 reads, 2 writes1718	pub fn toggle_admin(1719		collection: &CollectionHandle<T>,1720		sender: &T::CrossAccountId,1721		user: &T::CrossAccountId,1722		admin: bool,1723	) -> DispatchResult {1724		collection.check_is_internal()?;1725		collection.check_is_owner(sender)?;17261727		let is_admin = <IsAdmin<T>>::get((collection.id, user));1728		if is_admin == admin {1729			if admin {1730				return Ok(());1731			} else {1732				return Err(Error::<T>::UserIsNotCollectionAdmin.into());1733			}1734		}1735		let amount = <AdminAmount<T>>::get(collection.id);17361737		// =========17381739		if admin {1740			let amount = amount1741				.checked_add(1)1742				.ok_or(<Error<T>>::CollectionAdminCountExceeded)?;1743			ensure!(1744				amount <= Self::collection_admins_limit(),1745				<Error<T>>::CollectionAdminCountExceeded,1746			);17471748			<AdminAmount<T>>::insert(collection.id, amount);1749			<IsAdmin<T>>::insert((collection.id, user), true);17501751			Self::deposit_event(Event::<T>::CollectionAdminAdded(1752				collection.id,1753				user.clone(),1754			));1755		} else {1756			<AdminAmount<T>>::insert(collection.id, amount.saturating_sub(1));1757			<IsAdmin<T>>::remove((collection.id, user));17581759			Self::deposit_event(Event::<T>::CollectionAdminRemoved(1760				collection.id,1761				user.clone(),1762			));1763		}17641765		<PalletEvm<T>>::deposit_log(1766			erc::CollectionHelpersEvents::CollectionChanged {1767				collection_id: eth::collection_id_to_address(collection.id),1768			}1769			.to_log(T::ContractAddress::get()),1770		);17711772		Ok(())1773	}17741775	/// Update collection limits.1776	pub fn update_limits(1777		user: &T::CrossAccountId,1778		collection: &mut CollectionHandle<T>,1779		new_limit: CollectionLimits,1780	) -> DispatchResult {1781		collection.check_is_internal()?;1782		collection.check_is_owner_or_admin(user)?;17831784		collection.limits =1785			Self::clamp_limits(collection.mode.clone(), &collection.limits, new_limit)?;17861787		Self::deposit_event(Event::<T>::CollectionLimitSet(collection.id));1788		<PalletEvm<T>>::deposit_log(1789			erc::CollectionHelpersEvents::CollectionChanged {1790				collection_id: eth::collection_id_to_address(collection.id),1791			}1792			.to_log(T::ContractAddress::get()),1793		);17941795		collection.save()1796	}17971798	/// Merge set fields from `new_limit` to `old_limit`.1799	fn clamp_limits(1800		mode: CollectionMode,1801		old_limit: &CollectionLimits,1802		mut new_limit: CollectionLimits,1803	) -> Result<CollectionLimits, DispatchError> {1804		let limits = old_limit;1805		limit_default!(old_limit, new_limit,1806			account_token_ownership_limit => ensure!(1807				new_limit <= MAX_TOKEN_OWNERSHIP,1808				<Error<T>>::CollectionLimitBoundsExceeded,1809			),1810			sponsored_data_size => ensure!(1811				new_limit <= CUSTOM_DATA_LIMIT,1812				<Error<T>>::CollectionLimitBoundsExceeded,1813			),18141815			sponsored_data_rate_limit => {},1816			token_limit => ensure!(1817				old_limit >= new_limit && new_limit > 0,1818				<Error<T>>::CollectionTokenLimitExceeded1819			),18201821			sponsor_transfer_timeout(match mode {1822				CollectionMode::NFT => NFT_SPONSOR_TRANSFER_TIMEOUT,1823				CollectionMode::Fungible(_) => FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,1824				CollectionMode::ReFungible => REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,1825			}) => ensure!(1826				new_limit <= MAX_SPONSOR_TIMEOUT,1827				<Error<T>>::CollectionLimitBoundsExceeded,1828			),1829			sponsor_approve_timeout => {},1830			owner_can_transfer => ensure!(1831				!limits.owner_can_transfer_instaled() ||1832				old_limit || !new_limit,1833				<Error<T>>::OwnerPermissionsCantBeReverted,1834			),1835			owner_can_destroy => ensure!(1836				old_limit || !new_limit,1837				<Error<T>>::OwnerPermissionsCantBeReverted,1838			),1839			transfers_enabled => {},1840		);1841		Ok(new_limit)1842	}18431844	/// Update collection permissions.1845	pub fn update_permissions(1846		user: &T::CrossAccountId,1847		collection: &mut CollectionHandle<T>,1848		new_permission: CollectionPermissions,1849	) -> DispatchResult {1850		collection.check_is_internal()?;1851		collection.check_is_owner_or_admin(user)?;1852		collection.permissions = Self::clamp_permissions(1853			collection.mode.clone(),1854			&collection.permissions,1855			new_permission,1856		)?;18571858		Self::deposit_event(Event::<T>::CollectionPermissionSet(collection.id));1859		<PalletEvm<T>>::deposit_log(1860			erc::CollectionHelpersEvents::CollectionChanged {1861				collection_id: eth::collection_id_to_address(collection.id),1862			}1863			.to_log(T::ContractAddress::get()),1864		);18651866		collection.save()1867	}18681869	/// Merge set fields from `new_permission` to `old_permission`.1870	fn clamp_permissions(1871		_mode: CollectionMode,1872		old_permission: &CollectionPermissions,1873		mut new_permission: CollectionPermissions,1874	) -> Result<CollectionPermissions, DispatchError> {1875		limit_default_clone!(old_permission, new_permission,1876			access => {},1877			mint_mode => {},1878			nesting => { /* todo check for permissive, if only it gets out of benchmarks */ },1879		);1880		Ok(new_permission)1881	}18821883	/// Repair possibly broken properties of a collection.1884	pub fn repair_collection(collection_id: CollectionId) -> DispatchResult {1885		CollectionProperties::<T>::mutate(collection_id, |properties| {1886			properties.recompute_consumed_space();1887		});18881889		Ok(())1890	}1891}18921893/// Indicates unsupported methods by returning [Error::UnsupportedOperation].1894#[macro_export]1895macro_rules! unsupported {1896	($runtime:path) => {1897		Err($crate::Error::<$runtime>::UnsupportedOperation.into())1898	};1899}19001901/// Return weights for various worst-case operations.1902pub trait CommonWeightInfo<CrossAccountId> {1903	/// Weight of item creation.1904	fn create_item(data: &CreateItemData) -> Weight {1905		Self::create_multiple_items(from_ref(data))1906	}19071908	/// Weight of items creation.1909	fn create_multiple_items(amount: &[CreateItemData]) -> Weight;19101911	/// Weight of items creation.1912	fn create_multiple_items_ex(cost: &CreateItemExData<CrossAccountId>) -> Weight;19131914	/// The weight of the burning item.1915	fn burn_item() -> Weight;19161917	/// Property setting weight.1918	///1919	/// * `amount`- The number of properties to set.1920	fn set_collection_properties(amount: u32) -> Weight;19211922	/// Collection property deletion weight.1923	///1924	/// * `amount`- The number of properties to set.1925	fn delete_collection_properties(amount: u32) -> Weight;19261927	/// Token property setting weight.1928	///1929	/// * `amount`- The number of properties to set.1930	fn set_token_properties(amount: u32) -> Weight;19311932	/// Token property deletion weight.1933	///1934	/// * `amount`- The number of properties to delete.1935	fn delete_token_properties(amount: u32) -> Weight;19361937	/// Token property permissions set weight.1938	///1939	/// * `amount`- The number of property permissions to set.1940	fn set_token_property_permissions(amount: u32) -> Weight;19411942	/// Transfer price of the token or its parts.1943	fn transfer() -> Weight;19441945	/// The price of setting the permission of the operation from another user.1946	fn approve() -> Weight;19471948	/// The price of setting the permission of the operation from another user for eth mirror.1949	fn approve_from() -> Weight;19501951	/// Transfer price from another user.1952	fn transfer_from() -> Weight;19531954	/// The price of burning a token from another user.1955	fn burn_from() -> Weight;19561957	/// Differs from burn_item in case of Fungible and Refungible, as it should burn1958	/// whole users's balance.1959	///1960	/// This method shouldn't be used directly, as it doesn't count breadth price, use [burn_recursively](CommonWeightInfo::burn_recursively) instead1961	fn burn_recursively_self_raw() -> Weight;19621963	/// Cost of iterating over `amount` children while burning, without counting child burning itself.1964	///1965	/// This method shouldn't be used directly, as it doesn't count depth price, use [burn_recursively](CommonWeightInfo::burn_recursively) instead1966	fn burn_recursively_breadth_raw(amount: u32) -> Weight;19671968	/// The price of recursive burning a token.1969	///1970	/// `max_selfs` - The maximum burning weight of the token itself.1971	/// `max_breadth` - The maximum number of nested tokens to burn.1972	fn burn_recursively(max_selfs: u32, max_breadth: u32) -> Weight {1973		Self::burn_recursively_self_raw()1974			.saturating_mul(max_selfs.max(1) as u64)1975			.saturating_add(Self::burn_recursively_breadth_raw(max_breadth))1976	}19771978	/// The price of retrieving token owner1979	fn token_owner() -> Weight;19801981	/// The price of setting approval for all1982	fn set_allowance_for_all() -> Weight;19831984	/// The price of repairing an item.1985	fn force_repair_item() -> Weight;1986}19871988/// Weight info extension trait for refungible pallet.1989pub trait RefungibleExtensionsWeightInfo {1990	/// Weight of token repartition.1991	fn repartition() -> Weight;1992}19931994/// Common collection operations.1995///1996/// It wraps methods in Fungible, Nonfungible and Refungible pallets1997/// and adds weight info.1998pub trait CommonCollectionOperations<T: Config> {1999	/// Create token.2000	///2001	/// * `sender` - The user who mint the token and pays for the transaction.2002	/// * `to` - The user who will own the token.2003	/// * `data` - Token data.2004	/// * `nesting_budget` - A budget that can be spent on nesting tokens.2005	fn create_item(2006		&self,2007		sender: T::CrossAccountId,2008		to: T::CrossAccountId,2009		data: CreateItemData,2010		nesting_budget: &dyn Budget,2011	) -> DispatchResultWithPostInfo;20122013	/// Create multiple tokens.2014	///2015	/// * `sender` - The user who mint the token and pays for the transaction.2016	/// * `to` - The user who will own the token.2017	/// * `data` - Token data.2018	/// * `nesting_budget` - A budget that can be spent on nesting tokens.2019	fn create_multiple_items(2020		&self,2021		sender: T::CrossAccountId,2022		to: T::CrossAccountId,2023		data: Vec<CreateItemData>,2024		nesting_budget: &dyn Budget,2025	) -> DispatchResultWithPostInfo;20262027	/// Create multiple tokens.2028	///2029	/// * `sender` - The user who mint the token and pays for the transaction.2030	/// * `to` - The user who will own the token.2031	/// * `data` - Token data.2032	/// * `nesting_budget` - A budget that can be spent on nesting tokens.2033	fn create_multiple_items_ex(2034		&self,2035		sender: T::CrossAccountId,2036		data: CreateItemExData<T::CrossAccountId>,2037		nesting_budget: &dyn Budget,2038	) -> DispatchResultWithPostInfo;20392040	/// Burn token.2041	///2042	/// * `sender` - The user who owns the token.2043	/// * `token` - Token id that will burned.2044	/// * `amount` - The number of parts of the token that will be burned.2045	fn burn_item(2046		&self,2047		sender: T::CrossAccountId,2048		token: TokenId,2049		amount: u128,2050	) -> DispatchResultWithPostInfo;20512052	/// Burn token and all nested tokens recursievly.2053	///2054	/// * `sender` - The user who owns the token.2055	/// * `token` - Token id that will burned.2056	/// * `self_budget` - The budget that can be spent on burning tokens.2057	/// * `breadth_budget` - The budget that can be spent on burning nested tokens.2058	fn burn_item_recursively(2059		&self,2060		sender: T::CrossAccountId,2061		token: TokenId,2062		self_budget: &dyn Budget,2063		breadth_budget: &dyn Budget,2064	) -> DispatchResultWithPostInfo;20652066	/// Set collection properties.2067	///2068	/// * `sender` - Must be either the owner of the collection or its admin.2069	/// * `properties` - Properties to be set.2070	fn set_collection_properties(2071		&self,2072		sender: T::CrossAccountId,2073		properties: Vec<Property>,2074	) -> DispatchResultWithPostInfo;20752076	/// Delete collection properties.2077	///2078	/// * `sender` - Must be either the owner of the collection or its admin.2079	/// * `properties` - The properties to be removed.2080	fn delete_collection_properties(2081		&self,2082		sender: &T::CrossAccountId,2083		property_keys: Vec<PropertyKey>,2084	) -> DispatchResultWithPostInfo;20852086	/// Set token properties.2087	///2088	/// The appropriate [`PropertyPermission`] for the token property2089	/// must be set with [`Self::set_token_property_permissions`].2090	///2091	/// * `sender` - Must be either the owner of the token or its admin.2092	/// * `token_id` - The token for which the properties are being set.2093	/// * `properties` - Properties to be set.2094	/// * `budget` - Budget for setting properties.2095	fn set_token_properties(2096		&self,2097		sender: T::CrossAccountId,2098		token_id: TokenId,2099		properties: Vec<Property>,2100		budget: &dyn Budget,2101	) -> DispatchResultWithPostInfo;21022103	/// Remove token properties.2104	///2105	/// The appropriate [`PropertyPermission`] for the token property2106	/// must be set with [`Self::set_token_property_permissions`].2107	///2108	/// * `sender` - Must be either the owner of the token or its admin.2109	/// * `token_id` - The token for which the properties are being remove.2110	/// * `property_keys` - Keys to remove corresponding properties.2111	/// * `budget` - Budget for removing properties.2112	fn delete_token_properties(2113		&self,2114		sender: T::CrossAccountId,2115		token_id: TokenId,2116		property_keys: Vec<PropertyKey>,2117		budget: &dyn Budget,2118	) -> DispatchResultWithPostInfo;21192120	/// Set token property permissions.2121	///2122	/// * `sender` - Must be either the owner of the token or its admin.2123	/// * `token_id` - The token for which the properties are being set.2124	/// * `property_permissions` - Property permissions to be set.2125	/// * `budget` - Budget for setting properties.2126	fn set_token_property_permissions(2127		&self,2128		sender: &T::CrossAccountId,2129		property_permissions: Vec<PropertyKeyPermission>,2130	) -> DispatchResultWithPostInfo;21312132	/// Transfer amount of token pieces.2133	///2134	/// * `sender` - Donor user.2135	/// * `to` - Recepient user.2136	/// * `token` - The token of which parts are being sent.2137	/// * `amount` - The number of parts of the token that will be transferred.2138	/// * `budget` - The maximum budget that can be spent on the transfer.2139	fn transfer(2140		&self,2141		sender: T::CrossAccountId,2142		to: T::CrossAccountId,2143		token: TokenId,2144		amount: u128,2145		budget: &dyn Budget,2146	) -> DispatchResultWithPostInfo;21472148	/// Grant access to another account to transfer parts of the token owned by the calling user via [Self::transfer_from].2149	///2150	/// * `sender` - The user who grants access to the token.2151	/// * `spender` - The user to whom the rights are granted.2152	/// * `token` - The token to which access is granted.2153	/// * `amount` - The amount of pieces that another user can dispose of.2154	fn approve(2155		&self,2156		sender: T::CrossAccountId,2157		spender: T::CrossAccountId,2158		token: TokenId,2159		amount: u128,2160	) -> DispatchResultWithPostInfo;21612162	/// Grant access to another account to transfer parts of the token owned by the calling user's eth mirror via [Self::transfer_from].2163	///2164	/// * `sender` - The user who grants access to the token.2165	/// * `from` - Spender's eth mirror.2166	/// * `to` - The user to whom the rights are granted.2167	/// * `token` - The token to which access is granted.2168	/// * `amount` - The amount of pieces that another user can dispose of.2169	fn approve_from(2170		&self,2171		sender: T::CrossAccountId,2172		from: T::CrossAccountId,2173		to: T::CrossAccountId,2174		token: TokenId,2175		amount: u128,2176	) -> DispatchResultWithPostInfo;21772178	/// Send parts of a token owned by another user.2179	///2180	/// Before calling this method, you must grant rights to the calling user via [`Self::approve`].2181	///2182	/// * `sender` - The user who must have access to the token (see [`Self::approve`]).2183	/// * `from` - The user who owns the token.2184	/// * `to` - Recepient user.2185	/// * `token` - The token of which parts are being sent.2186	/// * `amount` - The number of parts of the token that will be transferred.2187	/// * `budget` - The maximum budget that can be spent on the transfer.2188	fn transfer_from(2189		&self,2190		sender: T::CrossAccountId,2191		from: T::CrossAccountId,2192		to: T::CrossAccountId,2193		token: TokenId,2194		amount: u128,2195		budget: &dyn Budget,2196	) -> DispatchResultWithPostInfo;21972198	/// Burn parts of a token owned by another user.2199	///2200	/// Before calling this method, you must grant rights to the calling user via [`Self::approve`].2201	///2202	/// * `sender` - The user who must have access to the token (see [`Self::approve`]).2203	/// * `from` - The user who owns the token.2204	/// * `token` - The token of which parts are being sent.2205	/// * `amount` - The number of parts of the token that will be transferred.2206	/// * `budget` - The maximum budget that can be spent on the burn.2207	fn burn_from(2208		&self,2209		sender: T::CrossAccountId,2210		from: T::CrossAccountId,2211		token: TokenId,2212		amount: u128,2213		budget: &dyn Budget,2214	) -> DispatchResultWithPostInfo;22152216	/// Check permission to nest token.2217	///2218	/// * `sender` - The user who initiated the check.2219	/// * `from` - The token that is checked for embedding.2220	/// * `under` - Token under which to check.2221	/// * `budget` - The maximum budget that can be spent on the check.2222	fn check_nesting(2223		&self,2224		sender: T::CrossAccountId,2225		from: (CollectionId, TokenId),2226		under: TokenId,2227		budget: &dyn Budget,2228	) -> DispatchResult;22292230	/// Nest one token into another.2231	///2232	/// * `under` - Token holder.2233	/// * `to_nest` - Nested token.2234	fn nest(&self, under: TokenId, to_nest: (CollectionId, TokenId));22352236	/// Unnest token.2237	///2238	/// * `under` - Token holder.2239	/// * `to_nest` - Token to unnest.2240	fn unnest(&self, under: TokenId, to_nest: (CollectionId, TokenId));22412242	/// Get all user tokens.2243	///2244	/// * `account` - Account for which you need to get tokens.2245	fn account_tokens(&self, account: T::CrossAccountId) -> Vec<TokenId>;22462247	/// Get all the tokens in the collection.2248	fn collection_tokens(&self) -> Vec<TokenId>;22492250	/// Check if the token exists.2251	///2252	/// * `token` - Id token to check.2253	fn token_exists(&self, token: TokenId) -> bool;22542255	/// Get the id of the last minted token.2256	fn last_token_id(&self) -> TokenId;22572258	/// Get the owner of the token.2259	///2260	/// * `token` - The token for which you need to find out the owner.2261	fn token_owner(&self, token: TokenId) -> Result<T::CrossAccountId, TokenOwnerError>;22622263	/// Returns 10 tokens owners in no particular order.2264	///2265	/// * `token` - The token for which you need to find out the owners.2266	fn token_owners(&self, token: TokenId) -> Vec<T::CrossAccountId>;22672268	/// Get the value of the token property by key.2269	///2270	/// * `token` - Token with the property to get.2271	/// * `key` - Property name.2272	fn token_property(&self, token_id: TokenId, key: &PropertyKey) -> Option<PropertyValue>;22732274	/// Get a set of token properties by key vector.2275	///2276	/// * `token` - Token with the property to get.2277	/// * `keys` - Vector of property keys. If this parameter is [None](sp_std::result::Result),2278	/// then all properties are returned.2279	fn token_properties(&self, token: TokenId, keys: Option<Vec<PropertyKey>>) -> Vec<Property>;22802281	/// Amount of unique collection tokens2282	fn total_supply(&self) -> u32;22832284	/// Amount of different tokens account has.2285	///2286	/// * `account` - The account for which need to get the balance.2287	fn account_balance(&self, account: T::CrossAccountId) -> u32;22882289	/// Amount of specific token account have.2290	fn balance(&self, account: T::CrossAccountId, token: TokenId) -> u128;22912292	/// Amount of token pieces2293	fn total_pieces(&self, token: TokenId) -> Option<u128>;22942295	/// Get the number of parts of the token that a trusted user can manage.2296	///2297	/// * `sender` - Trusted user.2298	/// * `spender` - Owner of the token.2299	/// * `token` - The token for which to get the value.2300	fn allowance(2301		&self,2302		sender: T::CrossAccountId,2303		spender: T::CrossAccountId,2304		token: TokenId,2305	) -> u128;23062307	/// Get extension for RFT collection.2308	fn refungible_extensions(&self) -> Option<&dyn RefungibleExtensions<T>>;23092310	/// The `operator` is allowed to transfer all tokens of the `owner` on their behalf.2311	/// * `owner` - Token owner2312	/// * `operator` - Operator2313	/// * `approve` - Should operator status be granted or revoked?2314	fn set_allowance_for_all(2315		&self,2316		owner: T::CrossAccountId,2317		operator: T::CrossAccountId,2318		approve: bool,2319	) -> DispatchResultWithPostInfo;23202321	/// Tells whether the given `owner` approves the `operator`.2322	fn allowance_for_all(&self, owner: T::CrossAccountId, operator: T::CrossAccountId) -> bool;23232324	/// Repairs a possibly broken item.2325	fn repair_item(&self, token: TokenId) -> DispatchResultWithPostInfo;2326}23272328/// Extension for RFT collection.2329pub trait RefungibleExtensions<T>2330where2331	T: Config,2332{2333	/// Change the number of parts of the token.2334	///2335	/// When the value changes down, this function is equivalent to burning parts of the token.2336	///2337	/// * `sender` - The user calling the repartition operation. Must be the owner of the token.2338	/// * `token` - The token for which you want to change the number of parts.2339	/// * `amount` - The new value of the parts of the token.2340	fn repartition(2341		&self,2342		sender: &T::CrossAccountId,2343		token: TokenId,2344		amount: u128,2345	) -> DispatchResultWithPostInfo;2346}23472348/// Merge [`DispatchResult`] with [`Weight`] into [`DispatchResultWithPostInfo`].2349///2350/// Used for [`CommonCollectionOperations`] implementations and flexible enough to do so.2351pub fn with_weight(res: DispatchResult, weight: Weight) -> DispatchResultWithPostInfo {2352	let post_info = PostDispatchInfo {2353		actual_weight: Some(weight),2354		pays_fee: Pays::Yes,2355	};2356	match res {2357		Ok(()) => Ok(post_info),2358		Err(error) => Err(DispatchErrorWithPostInfo { post_info, error }),2359	}2360}23612362impl<T: Config> From<PropertiesError> for Error<T> {2363	fn from(error: PropertiesError) -> Self {2364		match error {2365			PropertiesError::NoSpaceForProperty => Self::NoSpaceForProperty,2366			PropertiesError::PropertyLimitReached => Self::PropertyLimitReached,2367			PropertiesError::InvalidCharacterInPropertyKey => Self::InvalidCharacterInPropertyKey,2368			PropertiesError::PropertyKeyIsTooLong => Self::PropertyKeyIsTooLong,2369			PropertiesError::EmptyPropertyKey => Self::EmptyPropertyKey,2370		}2371	}2372}
after · pallets/common/src/lib.rs
1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617//! # Common pallet18//!19//! The Common pallet provides functionality for handling collections.20//!21//! ## Overview22//!23//! The Common pallet provides an interface for common collection operations for different collection types24//! (see [CommonCollectionOperations]), as well as a generic dispatcher for these, see [dispatch] module.25//! It also provides this functionality to EVM, see [erc] and [eth] modules.26//!27//! The Common pallet provides functions for:28//!29//! - Setting and approving collection sponsor.30//! - Get\set\delete allow list.31//! - Get\set\delete collection properties.32//! - Get\set\delete collection property permissions.33//! - Get\set\delete token property permissions.34//! - Get\set\delete collection administrators.35//! - Checking access permissions.36//!37//! ### Terminology38//! **Collection sponsor** - For the collection, you can set a sponsor, at whose expense it will39//! be possible to mint tokens.40//!41//! **Allow list** - List of users who have the right to minting tokens.42//!43//! **Collection properties** - Collection properties are simply key-value stores where various44//! metadata can be placed.45//!46//! **Permissions on token properties** - For each property in the token can be set permission47//! to change, see [`PropertyPermission`].48//!49//! **Collection administrator** - For a collection, you can set administrators who have the right50//! to most actions on the collection.5152#![warn(missing_docs)]53#![cfg_attr(not(feature = "std"), no_std)]54extern crate alloc;5556use core::{57	ops::{Deref, DerefMut},58	slice::from_ref,59};60use pallet_evm_coder_substrate::{SubstrateRecorder, WithRecorder};61use sp_std::vec::Vec;62use pallet_evm::{account::CrossAccountId, Pallet as PalletEvm};63use evm_coder::ToLog;64use frame_support::{65	dispatch::{DispatchErrorWithPostInfo, DispatchResultWithPostInfo, Weight, PostDispatchInfo},66	ensure,67	traits::{Imbalance, Get, Currency, WithdrawReasons, ExistenceRequirement},68	dispatch::Pays,69	transactional, fail,70};71use pallet_evm::GasWeightMapping;72use up_data_structs::{73	AccessMode, COLLECTION_NUMBER_LIMIT, Collection, RpcCollection, CollectionFlags,74	RpcCollectionFlags, CollectionId, CreateItemData, MAX_TOKEN_PREFIX_LENGTH,75	COLLECTION_ADMINS_LIMIT, TokenId, TokenChild, CollectionStats, MAX_TOKEN_OWNERSHIP,76	CollectionMode, NFT_SPONSOR_TRANSFER_TIMEOUT, FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,77	REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT, MAX_SPONSOR_TIMEOUT, CUSTOM_DATA_LIMIT, CollectionLimits,78	CreateCollectionData, SponsorshipState, CreateItemExData, SponsoringRateLimit, budget::Budget,79	PhantomType, Property, Properties, PropertiesPermissionMap, PropertyKey, PropertyValue,80	PropertyPermission, PropertiesError, TokenOwnerError, PropertyKeyPermission, TokenData,81	TrySetProperty, PropertyScope, CollectionPermissions,82};83use up_pov_estimate_rpc::PovInfo;8485pub use pallet::*;86use sp_core::H160;87use sp_runtime::{ArithmeticError, DispatchError, DispatchResult};8889use crate::erc::CollectionHelpersEvents;90#[cfg(feature = "runtime-benchmarks")]91pub mod benchmarking;92pub mod dispatch;93pub mod erc;94pub mod eth;95pub mod weights;9697/// Weight info.98pub type SelfWeightOf<T> = <T as Config>::WeightInfo;99100/// Collection handle contains information about collection data and id.101/// Also provides functionality to count consumed gas.102///103/// CollectionHandle is used as a generic wrapper for collections of all types.104/// It allows to perform common operations and queries on any collection type,105/// both completely general for all, as well as their respective implementations of [`CommonCollectionOperations`].106#[must_use = "Should call submit_logs or save, otherwise some data will be lost for evm side"]107pub struct CollectionHandle<T: Config> {108	/// Collection id109	pub id: CollectionId,110	collection: Collection<T::AccountId>,111	/// Substrate recorder for counting consumed gas112	pub recorder: SubstrateRecorder<T>,113}114115impl<T: Config> WithRecorder<T> for CollectionHandle<T> {116	fn recorder(&self) -> &SubstrateRecorder<T> {117		&self.recorder118	}119	fn into_recorder(self) -> SubstrateRecorder<T> {120		self.recorder121	}122}123124impl<T: Config> CollectionHandle<T> {125	/// Same as [CollectionHandle::new] but with an explicit gas limit.126	pub fn new_with_gas_limit(id: CollectionId, gas_limit: u64) -> Option<Self> {127		<CollectionById<T>>::get(id).map(|collection| Self {128			id,129			collection,130			recorder: SubstrateRecorder::new(gas_limit),131		})132	}133134	/// Same as [CollectionHandle::new] but with an existed [`SubstrateRecorder`].135	pub fn new_with_recorder(id: CollectionId, recorder: SubstrateRecorder<T>) -> Option<Self> {136		<CollectionById<T>>::get(id).map(|collection| Self {137			id,138			collection,139			recorder,140		})141	}142143	/// Retrives collection data from storage and creates collection handle with default parameters.144	/// If collection not found return `None`145	pub fn new(id: CollectionId) -> Option<Self> {146		Self::new_with_gas_limit(id, u64::MAX)147	}148149	/// Same as [`CollectionHandle::new`] but if collection not found [CollectionNotFound](Error::CollectionNotFound) returned.150	pub fn try_get(id: CollectionId) -> Result<Self, DispatchError> {151		Ok(Self::new(id).ok_or(<Error<T>>::CollectionNotFound)?)152	}153154	/// Consume gas for reading.155	pub fn consume_store_reads(156		&self,157		reads: u64,158	) -> pallet_evm_coder_substrate::execution::Result<()> {159		self.recorder160			.consume_gas(T::GasWeightMapping::weight_to_gas(Weight::from_ref_time(161				<T as frame_system::Config>::DbWeight::get()162					.read163					.saturating_mul(reads),164			)))165	}166167	/// Consume gas for writing.168	pub fn consume_store_writes(169		&self,170		writes: u64,171	) -> pallet_evm_coder_substrate::execution::Result<()> {172		self.recorder173			.consume_gas(T::GasWeightMapping::weight_to_gas(Weight::from_ref_time(174				<T as frame_system::Config>::DbWeight::get()175					.write176					.saturating_mul(writes),177			)))178	}179180	/// Consume gas for reading and writing.181	pub fn consume_store_reads_and_writes(182		&self,183		reads: u64,184		writes: u64,185	) -> pallet_evm_coder_substrate::execution::Result<()> {186		let weight = <T as frame_system::Config>::DbWeight::get();187		let reads = weight.read.saturating_mul(reads);188		let writes = weight.read.saturating_mul(writes);189		self.recorder190			.consume_gas(T::GasWeightMapping::weight_to_gas(Weight::from_ref_time(191				reads.saturating_add(writes),192			)))193	}194195	/// Save collection to storage.196	pub fn save(&self) -> DispatchResult {197		<CollectionById<T>>::insert(self.id, &self.collection);198		Ok(())199	}200201	/// Set collection sponsor.202	///203	/// Unique collections allows sponsoring for certain actions.204	/// This method allows you to set the sponsor of the collection.205	/// In order for sponsorship to become active, it must be confirmed through [`Self::confirm_sponsorship`].206	pub fn set_sponsor(207		&mut self,208		sender: &T::CrossAccountId,209		sponsor: T::AccountId,210	) -> DispatchResult {211		self.check_is_internal()?;212		self.check_is_owner_or_admin(sender)?;213214		self.collection.sponsorship = SponsorshipState::Unconfirmed(sponsor.clone());215216		<Pallet<T>>::deposit_event(Event::<T>::CollectionSponsorSet(self.id, sponsor));217		<PalletEvm<T>>::deposit_log(218			erc::CollectionHelpersEvents::CollectionChanged {219				collection_id: eth::collection_id_to_address(self.id),220			}221			.to_log(T::ContractAddress::get()),222		);223224		self.save()225	}226227	/// Force set `sponsor`.228	///229	/// Differs from [`set_sponsor`][`Self::set_sponsor`] in that confirmation230	/// from the `sponsor` is not required.231	///232	/// # Arguments233	///234	/// * `sender`: Caller's account.235	/// * `sponsor`: ID of the account of the sponsor-to-be.236	pub fn force_set_sponsor(&mut self, sponsor: T::AccountId) -> DispatchResult {237		self.check_is_internal()?;238239		self.collection.sponsorship = SponsorshipState::Confirmed(sponsor.clone());240241		<Pallet<T>>::deposit_event(Event::<T>::CollectionSponsorSet(self.id, sponsor.clone()));242		<Pallet<T>>::deposit_event(Event::<T>::SponsorshipConfirmed(self.id, sponsor));243		<PalletEvm<T>>::deposit_log(244			erc::CollectionHelpersEvents::CollectionChanged {245				collection_id: eth::collection_id_to_address(self.id),246			}247			.to_log(T::ContractAddress::get()),248		);249250		self.save()251	}252253	/// Confirm sponsorship254	///255	/// In order for the sponsorship to become active, the user set as the sponsor must confirm their participation.256	/// Before confirming sponsorship, the user must be specified as the sponsor of the collection via [`Self::set_sponsor`].257	pub fn confirm_sponsorship(&mut self, sender: &T::AccountId) -> DispatchResult {258		self.check_is_internal()?;259		ensure!(260			self.collection.sponsorship.pending_sponsor() == Some(sender),261			Error::<T>::ConfirmSponsorshipFail262		);263264		self.collection.sponsorship = SponsorshipState::Confirmed(sender.clone());265266		<Pallet<T>>::deposit_event(Event::<T>::SponsorshipConfirmed(self.id, sender.clone()));267		<PalletEvm<T>>::deposit_log(268			erc::CollectionHelpersEvents::CollectionChanged {269				collection_id: eth::collection_id_to_address(self.id),270			}271			.to_log(T::ContractAddress::get()),272		);273274		self.save()275	}276277	/// Remove collection sponsor.278	pub fn remove_sponsor(&mut self, sender: &T::CrossAccountId) -> DispatchResult {279		self.check_is_internal()?;280		self.check_is_owner_or_admin(sender)?;281282		self.collection.sponsorship = SponsorshipState::Disabled;283284		<Pallet<T>>::deposit_event(Event::<T>::CollectionSponsorRemoved(self.id));285		<PalletEvm<T>>::deposit_log(286			erc::CollectionHelpersEvents::CollectionChanged {287				collection_id: eth::collection_id_to_address(self.id),288			}289			.to_log(T::ContractAddress::get()),290		);291		self.save()292	}293294	/// Force remove `sponsor`.295	///296	/// Differs from `remove_sponsor` in that297	/// it doesn't require consent from the `owner` of the collection.298	pub fn force_remove_sponsor(&mut self) -> DispatchResult {299		self.check_is_internal()?;300301		self.collection.sponsorship = SponsorshipState::Disabled;302303		<Pallet<T>>::deposit_event(Event::<T>::CollectionSponsorRemoved(self.id));304		<PalletEvm<T>>::deposit_log(305			erc::CollectionHelpersEvents::CollectionChanged {306				collection_id: eth::collection_id_to_address(self.id),307			}308			.to_log(T::ContractAddress::get()),309		);310		self.save()311	}312313	/// Checks that the collection was created with, and must be operated upon through **Unique API**.314	/// Now check only the `external` flag and if it's **true**, then return [`Error::CollectionIsExternal`] error.315	pub fn check_is_internal(&self) -> DispatchResult {316		if self.flags.external {317			return Err(<Error<T>>::CollectionIsExternal)?;318		}319320		Ok(())321	}322323	/// Checks that the collection was created with, and must be operated upon through an **assimilated API**.324	/// Now check only the `external` flag and if it's **false**, then return [`Error::CollectionIsInternal`] error.325	pub fn check_is_external(&self) -> DispatchResult {326		if !self.flags.external {327			return Err(<Error<T>>::CollectionIsInternal)?;328		}329330		Ok(())331	}332}333334impl<T: Config> Deref for CollectionHandle<T> {335	type Target = Collection<T::AccountId>;336337	fn deref(&self) -> &Self::Target {338		&self.collection339	}340}341342impl<T: Config> DerefMut for CollectionHandle<T> {343	fn deref_mut(&mut self) -> &mut Self::Target {344		&mut self.collection345	}346}347348impl<T: Config> CollectionHandle<T> {349	/// Checks if the `user` is the owner of the collection.350	pub fn check_is_owner(&self, user: &T::CrossAccountId) -> DispatchResult {351		ensure!(*user.as_sub() == self.owner, <Error<T>>::NoPermission);352		Ok(())353	}354355	/// Returns **true** if the `user` is the owner or administrator of the collection.356	pub fn is_owner_or_admin(&self, user: &T::CrossAccountId) -> bool {357		*user.as_sub() == self.owner || <IsAdmin<T>>::get((self.id, user))358	}359360	/// Checks if the `user` is the owner or administrator of the collection.361	pub fn check_is_owner_or_admin(&self, user: &T::CrossAccountId) -> DispatchResult {362		ensure!(self.is_owner_or_admin(user), <Error<T>>::NoPermission);363		Ok(())364	}365366	/// Returns **true** if367	/// * the `user`is a collection owner or admin368	/// * the collection limits allow the owner/admins to transfer/burn any collection token369	pub fn ignores_token_restrictions(&self, user: &T::CrossAccountId) -> bool {370		self.limits.owner_can_transfer() && self.is_owner_or_admin(user)371	}372373	/// Return **true** if `user` does not have enough token parts, and he can ignore such restrictions.374	pub fn ignores_owned_amount(&self, user: &T::CrossAccountId) -> bool {375		self.limits.owner_can_transfer() && self.is_owner_or_admin(user)376	}377378	/// Checks if the user is in the allow list. If not [Error::AddressNotInAllowlist] returns.379	pub fn check_allowlist(&self, user: &T::CrossAccountId) -> DispatchResult {380		ensure!(381			<Allowlist<T>>::get((self.id, user)),382			<Error<T>>::AddressNotInAllowlist383		);384		Ok(())385	}386387	/// Changes collection owner to another account388	/// #### Store read/writes389	/// 1 writes390	pub fn change_owner(391		&mut self,392		caller: T::CrossAccountId,393		new_owner: T::CrossAccountId,394	) -> DispatchResult {395		self.check_is_internal()?;396		self.check_is_owner(&caller)?;397		self.collection.owner = new_owner.as_sub().clone();398399		<Pallet<T>>::deposit_event(Event::<T>::CollectionOwnerChanged(400			self.id,401			new_owner.as_sub().clone(),402		));403		<PalletEvm<T>>::deposit_log(404			erc::CollectionHelpersEvents::CollectionChanged {405				collection_id: eth::collection_id_to_address(self.id),406			}407			.to_log(T::ContractAddress::get()),408		);409410		self.save()411	}412}413414#[frame_support::pallet]415pub mod pallet {416	use super::*;417	use dispatch::CollectionDispatch;418	use frame_support::{Blake2_128Concat, pallet_prelude::*, storage::Key, traits::StorageVersion};419	use frame_system::pallet_prelude::*;420	use frame_support::traits::Currency;421	use up_data_structs::{TokenId, mapping::TokenAddressMapping};422	use scale_info::TypeInfo;423	use weights::WeightInfo;424425	#[pallet::config]426	pub trait Config:427		frame_system::Config + pallet_evm_coder_substrate::Config + pallet_evm::Config + TypeInfo428	{429		/// Weight information for functions of this pallet.430		type WeightInfo: WeightInfo;431432		/// Events compatible with [`frame_system::Config::Event`].433		type RuntimeEvent: IsType<<Self as frame_system::Config>::RuntimeEvent> + From<Event<Self>>;434435		/// Handler of accounts and payment.436		type Currency: Currency<Self::AccountId>;437438		/// Set price to create a collection.439		#[pallet::constant]440		type CollectionCreationPrice: Get<441			<<Self as Config>::Currency as Currency<Self::AccountId>>::Balance,442		>;443444		/// Dispatcher of operations on collections.445		type CollectionDispatch: CollectionDispatch<Self>;446447		/// Account which holds the chain's treasury.448		type TreasuryAccountId: Get<Self::AccountId>;449450		/// Address under which the CollectionHelper contract would be available.451		#[pallet::constant]452		type ContractAddress: Get<H160>;453454		/// Mapper for token addresses to Ethereum addresses.455		type EvmTokenAddressMapping: TokenAddressMapping<H160>;456457		/// Mapper for token addresses to [`CrossAccountId`].458		type CrossTokenAddressMapping: TokenAddressMapping<Self::CrossAccountId>;459	}460461	const STORAGE_VERSION: StorageVersion = StorageVersion::new(1);462463	#[pallet::pallet]464	#[pallet::storage_version(STORAGE_VERSION)]465	#[pallet::generate_store(pub(super) trait Store)]466	pub struct Pallet<T>(_);467468	#[pallet::extra_constants]469	impl<T: Config> Pallet<T> {470		/// Maximum admins per collection.471		pub fn collection_admins_limit() -> u32 {472			COLLECTION_ADMINS_LIMIT473		}474	}475476	impl<T: Config> Pallet<T> {477		/// Helper function that handles deposit events478		pub fn deposit_event(event: Event<T>) {479			let event = <T as Config>::RuntimeEvent::from(event);480			let event = event.into();481			<frame_system::Pallet<T>>::deposit_event(event)482		}483	}484485	#[pallet::event]486	pub enum Event<T: Config> {487		/// New collection was created488		CollectionCreated(489			/// Globally unique identifier of newly created collection.490			CollectionId,491			/// [`CollectionMode`] converted into _u8_.492			u8,493			/// Collection owner.494			T::AccountId,495		),496497		/// New collection was destroyed498		CollectionDestroyed(499			/// Globally unique identifier of collection.500			CollectionId,501		),502503		/// New item was created.504		ItemCreated(505			/// Id of the collection where item was created.506			CollectionId,507			/// Id of an item. Unique within the collection.508			TokenId,509			/// Owner of newly created item510			T::CrossAccountId,511			/// Always 1 for NFT512			u128,513		),514515		/// Collection item was burned.516		ItemDestroyed(517			/// Id of the collection where item was destroyed.518			CollectionId,519			/// Identifier of burned NFT.520			TokenId,521			/// Which user has destroyed its tokens.522			T::CrossAccountId,523			/// Amount of token pieces destroed. Always 1 for NFT.524			u128,525		),526527		/// Item was transferred528		Transfer(529			/// Id of collection to which item is belong.530			CollectionId,531			/// Id of an item.532			TokenId,533			/// Original owner of item.534			T::CrossAccountId,535			/// New owner of item.536			T::CrossAccountId,537			/// Amount of token pieces transfered. Always 1 for NFT.538			u128,539		),540541		/// Amount pieces of token owned by `sender` was approved for `spender`.542		Approved(543			/// Id of collection to which item is belong.544			CollectionId,545			/// Id of an item.546			TokenId,547			/// Original owner of item.548			T::CrossAccountId,549			/// Id for which the approval was granted.550			T::CrossAccountId,551			/// Amount of token pieces transfered. Always 1 for NFT.552			u128,553		),554555		/// A `sender` approves operations on all owned tokens for `spender`.556		ApprovedForAll(557			/// Id of collection to which item is belong.558			CollectionId,559			/// Owner of a wallet.560			T::CrossAccountId,561			/// Id for which operator status was granted or rewoked.562			T::CrossAccountId,563			/// Is operator status granted or revoked?564			bool,565		),566567		/// The colletion property has been added or edited.568		CollectionPropertySet(569			/// Id of collection to which property has been set.570			CollectionId,571			/// The property that was set.572			PropertyKey,573		),574575		/// The property has been deleted.576		CollectionPropertyDeleted(577			/// Id of collection to which property has been deleted.578			CollectionId,579			/// The property that was deleted.580			PropertyKey,581		),582583		/// The token property has been added or edited.584		TokenPropertySet(585			/// Identifier of the collection whose token has the property set.586			CollectionId,587			/// The token for which the property was set.588			TokenId,589			/// The property that was set.590			PropertyKey,591		),592593		/// The token property has been deleted.594		TokenPropertyDeleted(595			/// Identifier of the collection whose token has the property deleted.596			CollectionId,597			/// The token for which the property was deleted.598			TokenId,599			/// The property that was deleted.600			PropertyKey,601		),602603		/// The token property permission of a collection has been set.604		PropertyPermissionSet(605			/// ID of collection to which property permission has been set.606			CollectionId,607			/// The property permission that was set.608			PropertyKey,609		),610611		/// Address was added to the allow list.612		AllowListAddressAdded(613			/// ID of the affected collection.614			CollectionId,615			/// Address of the added account.616			T::CrossAccountId,617		),618619		/// Address was removed from the allow list.620		AllowListAddressRemoved(621			/// ID of the affected collection.622			CollectionId,623			/// Address of the removed account.624			T::CrossAccountId,625		),626627		/// Collection admin was added.628		CollectionAdminAdded(629			/// ID of the affected collection.630			CollectionId,631			/// Admin address.632			T::CrossAccountId,633		),634635		/// Collection admin was removed.636		CollectionAdminRemoved(637			/// ID of the affected collection.638			CollectionId,639			/// Removed admin address.640			T::CrossAccountId,641		),642643		/// Collection limits were set.644		CollectionLimitSet(645			/// ID of the affected collection.646			CollectionId,647		),648649		/// Collection owned was changed.650		CollectionOwnerChanged(651			/// ID of the affected collection.652			CollectionId,653			/// New owner address.654			T::AccountId,655		),656657		/// Collection permissions were set.658		CollectionPermissionSet(659			/// ID of the affected collection.660			CollectionId,661		),662663		/// Collection sponsor was set.664		CollectionSponsorSet(665			/// ID of the affected collection.666			CollectionId,667			/// New sponsor address.668			T::AccountId,669		),670671		/// New sponsor was confirm.672		SponsorshipConfirmed(673			/// ID of the affected collection.674			CollectionId,675			/// New sponsor address.676			T::AccountId,677		),678679		/// Collection sponsor was removed.680		CollectionSponsorRemoved(681			/// ID of the affected collection.682			CollectionId,683		),684	}685686	#[pallet::error]687	pub enum Error<T> {688		/// This collection does not exist.689		CollectionNotFound,690		/// Sender parameter and item owner must be equal.691		MustBeTokenOwner,692		/// No permission to perform action693		NoPermission,694		/// Destroying only empty collections is allowed695		CantDestroyNotEmptyCollection,696		/// Collection is not in mint mode.697		PublicMintingNotAllowed,698		/// Address is not in allow list.699		AddressNotInAllowlist,700701		/// Collection name can not be longer than 63 char.702		CollectionNameLimitExceeded,703		/// Collection description can not be longer than 255 char.704		CollectionDescriptionLimitExceeded,705		/// Token prefix can not be longer than 15 char.706		CollectionTokenPrefixLimitExceeded,707		/// Total collections bound exceeded.708		TotalCollectionsLimitExceeded,709		/// Exceeded max admin count710		CollectionAdminCountExceeded,711		/// Collection limit bounds per collection exceeded712		CollectionLimitBoundsExceeded,713		/// Tried to enable permissions which are only permitted to be disabled714		OwnerPermissionsCantBeReverted,715		/// Collection settings not allowing items transferring716		TransferNotAllowed,717		/// Account token limit exceeded per collection718		AccountTokenLimitExceeded,719		/// Collection token limit exceeded720		CollectionTokenLimitExceeded,721		/// Metadata flag frozen722		MetadataFlagFrozen,723724		/// Item does not exist725		TokenNotFound,726		/// Item is balance not enough727		TokenValueTooLow,728		/// Requested value is more than the approved729		ApprovedValueTooLow,730		/// Tried to approve more than owned731		CantApproveMoreThanOwned,732		/// Only spending from eth mirror could be approved733		AddressIsNotEthMirror,734735		/// Can't transfer tokens to ethereum zero address736		AddressIsZero,737738		/// The operation is not supported739		UnsupportedOperation,740741		/// Insufficient funds to perform an action742		NotSufficientFounds,743744		/// User does not satisfy the nesting rule745		UserIsNotAllowedToNest,746		/// Only tokens from specific collections may nest tokens under this one747		SourceCollectionIsNotAllowedToNest,748749		/// Tried to store more data than allowed in collection field750		CollectionFieldSizeExceeded,751752		/// Tried to store more property data than allowed753		NoSpaceForProperty,754755		/// Tried to store more property keys than allowed756		PropertyLimitReached,757758		/// Property key is too long759		PropertyKeyIsTooLong,760761		/// Only ASCII letters, digits, and symbols `_`, `-`, and `.` are allowed762		InvalidCharacterInPropertyKey,763764		/// Empty property keys are forbidden765		EmptyPropertyKey,766767		/// Tried to access an external collection with an internal API768		CollectionIsExternal,769770		/// Tried to access an internal collection with an external API771		CollectionIsInternal,772773		/// This address is not set as sponsor, use setCollectionSponsor first.774		ConfirmSponsorshipFail,775776		/// The user is not an administrator.777		UserIsNotCollectionAdmin,778	}779780	/// Storage of the count of created collections. Essentially contains the last collection ID.781	#[pallet::storage]782	pub type CreatedCollectionCount<T> = StorageValue<Value = CollectionId, QueryKind = ValueQuery>;783784	/// Storage of the count of deleted collections.785	#[pallet::storage]786	pub type DestroyedCollectionCount<T> =787		StorageValue<Value = CollectionId, QueryKind = ValueQuery>;788789	/// Storage of collection info.790	#[pallet::storage]791	pub type CollectionById<T> = StorageMap<792		Hasher = Blake2_128Concat,793		Key = CollectionId,794		Value = Collection<<T as frame_system::Config>::AccountId>,795		QueryKind = OptionQuery,796	>;797798	/// Storage of collection properties.799	#[pallet::storage]800	#[pallet::getter(fn collection_properties)]801	pub type CollectionProperties<T> = StorageMap<802		Hasher = Blake2_128Concat,803		Key = CollectionId,804		Value = Properties,805		QueryKind = ValueQuery,806		OnEmpty = up_data_structs::CollectionProperties,807	>;808809	/// Storage of token property permissions of a collection.810	#[pallet::storage]811	#[pallet::getter(fn property_permissions)]812	pub type CollectionPropertyPermissions<T> = StorageMap<813		Hasher = Blake2_128Concat,814		Key = CollectionId,815		Value = PropertiesPermissionMap,816		QueryKind = ValueQuery,817	>;818819	/// Storage of the amount of collection admins.820	#[pallet::storage]821	pub type AdminAmount<T> = StorageMap<822		Hasher = Blake2_128Concat,823		Key = CollectionId,824		Value = u32,825		QueryKind = ValueQuery,826	>;827828	/// List of collection admins.829	#[pallet::storage]830	pub type IsAdmin<T: Config> = StorageNMap<831		Key = (832			Key<Blake2_128Concat, CollectionId>,833			Key<Blake2_128Concat, T::CrossAccountId>,834		),835		Value = bool,836		QueryKind = ValueQuery,837	>;838839	/// Allowlisted collection users.840	#[pallet::storage]841	pub type Allowlist<T: Config> = StorageNMap<842		Key = (843			Key<Blake2_128Concat, CollectionId>,844			Key<Blake2_128Concat, T::CrossAccountId>,845		),846		Value = bool,847		QueryKind = ValueQuery,848	>;849850	/// Not used by code, exists only to provide some types to metadata.851	#[pallet::storage]852	pub type DummyStorageValue<T: Config> = StorageValue<853		Value = (854			CollectionStats,855			CollectionId,856			TokenId,857			TokenChild,858			PhantomType<(859				TokenData<T::CrossAccountId>,860				RpcCollection<T::AccountId>,861				// PoV Estimate Info862				PovInfo,863			)>,864		),865		QueryKind = OptionQuery,866	>;867868	#[pallet::hooks]869	impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {870		fn on_runtime_upgrade() -> Weight {871			StorageVersion::new(1).put::<Pallet<T>>();872873			Weight::zero()874		}875	}876}877878impl<T: Config> Pallet<T> {879	/// Enshure that receiver address is correct.880	///881	/// Ethereum receiver 0x0000000000000000000000000000000000000000 is reserved, and shouldn't own tokens.882	pub fn ensure_correct_receiver(receiver: &T::CrossAccountId) -> DispatchResult {883		ensure!(884			&T::CrossAccountId::from_eth(H160([0; 20])) != receiver,885			<Error<T>>::AddressIsZero886		);887		Ok(())888	}889890	/// Get a vector of collection admins.891	pub fn adminlist(collection: CollectionId) -> Vec<T::CrossAccountId> {892		<IsAdmin<T>>::iter_prefix((collection,))893			.map(|(a, _)| a)894			.collect()895	}896897	/// Get a vector of users allowed to mint tokens.898	pub fn allowlist(collection: CollectionId) -> Vec<T::CrossAccountId> {899		<Allowlist<T>>::iter_prefix((collection,))900			.map(|(a, _)| a)901			.collect()902	}903904	/// Is `user` allowed to mint token in `collection`.905	pub fn allowed(collection: CollectionId, user: T::CrossAccountId) -> bool {906		<Allowlist<T>>::get((collection, user))907	}908909	/// Get statistics of collections.910	pub fn collection_stats() -> CollectionStats {911		let created = <CreatedCollectionCount<T>>::get();912		let destroyed = <DestroyedCollectionCount<T>>::get();913		CollectionStats {914			created: created.0,915			destroyed: destroyed.0,916			alive: created.0 - destroyed.0,917		}918	}919920	/// Get the effective limits for the collection.921	pub fn effective_collection_limits(collection: CollectionId) -> Option<CollectionLimits> {922		let collection = <CollectionById<T>>::get(collection)?;923		let limits = collection.limits;924		let effective_limits = CollectionLimits {925			account_token_ownership_limit: Some(limits.account_token_ownership_limit()),926			sponsored_data_size: Some(limits.sponsored_data_size()),927			sponsored_data_rate_limit: Some(928				limits929					.sponsored_data_rate_limit930					.unwrap_or(SponsoringRateLimit::SponsoringDisabled),931			),932			token_limit: Some(limits.token_limit()),933			sponsor_transfer_timeout: Some(limits.sponsor_transfer_timeout(934				match collection.mode {935					CollectionMode::NFT => NFT_SPONSOR_TRANSFER_TIMEOUT,936					CollectionMode::Fungible(_) => FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,937					CollectionMode::ReFungible => REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,938				},939			)),940			sponsor_approve_timeout: Some(limits.sponsor_approve_timeout()),941			owner_can_transfer: Some(limits.owner_can_transfer()),942			owner_can_destroy: Some(limits.owner_can_destroy()),943			transfers_enabled: Some(limits.transfers_enabled()),944		};945946		Some(effective_limits)947	}948949	/// Returns information about the `collection` adapted for rpc.950	pub fn rpc_collection(collection: CollectionId) -> Option<RpcCollection<T::AccountId>> {951		let Collection {952			name,953			description,954			owner,955			mode,956			token_prefix,957			sponsorship,958			limits,959			permissions,960			flags,961		} = <CollectionById<T>>::get(collection)?;962963		let token_property_permissions = <CollectionPropertyPermissions<T>>::get(collection)964			.into_iter()965			.map(|(key, permission)| PropertyKeyPermission { key, permission })966			.collect();967968		let properties = <CollectionProperties<T>>::get(collection)969			.into_iter()970			.map(|(key, value)| Property { key, value })971			.collect();972973		let permissions = CollectionPermissions {974			access: Some(permissions.access()),975			mint_mode: Some(permissions.mint_mode()),976			nesting: Some(permissions.nesting().clone()),977		};978979		Some(RpcCollection {980			name: name.into_inner(),981			description: description.into_inner(),982			owner,983			mode,984			token_prefix: token_prefix.into_inner(),985			sponsorship,986			limits,987			permissions,988			token_property_permissions,989			properties,990			read_only: flags.external,991992			flags: RpcCollectionFlags {993				foreign: flags.foreign,994				erc721metadata: flags.erc721metadata,995			},996		})997	}998}9991000macro_rules! limit_default {1001	($old:ident, $new:ident, $($field:ident $(($arg:expr))? => $check:expr),* $(,)?) => {{1002		$(1003			if let Some($new) = $new.$field {1004				let $old = $old.$field($($arg)?);1005				let _ = $new;1006				let _ = $old;1007				$check1008			} else {1009				$new.$field = $old.$field1010			}1011		)*1012	}};1013}1014macro_rules! limit_default_clone {1015	($old:ident, $new:ident, $($field:ident $(($arg:expr))? => $check:expr),* $(,)?) => {{1016		$(1017			if let Some($new) = $new.$field.clone() {1018				let $old = $old.$field($($arg)?);1019				let _ = $new;1020				let _ = $old;1021				$check1022			} else {1023				$new.$field = $old.$field.clone()1024			}1025		)*1026	}};1027}10281029impl<T: Config> Pallet<T> {1030	/// Create new collection.1031	///1032	/// * `owner` - The owner of the collection.1033	/// * `data` - Description of the created collection.1034	/// * `flags` - Extra flags to store.1035	pub fn init_collection(1036		owner: T::CrossAccountId,1037		payer: T::CrossAccountId,1038		data: CreateCollectionData<T::AccountId>,1039		flags: CollectionFlags,1040	) -> Result<CollectionId, DispatchError> {1041		{1042			ensure!(1043				data.token_prefix.len() <= MAX_TOKEN_PREFIX_LENGTH as usize,1044				Error::<T>::CollectionTokenPrefixLimitExceeded1045			);1046		}10471048		let created_count = <CreatedCollectionCount<T>>::get()1049			.01050			.checked_add(1)1051			.ok_or(ArithmeticError::Overflow)?;1052		let destroyed_count = <DestroyedCollectionCount<T>>::get().0;1053		let id = CollectionId(created_count);10541055		// bound Total number of collections1056		ensure!(1057			created_count - destroyed_count <= COLLECTION_NUMBER_LIMIT,1058			<Error<T>>::TotalCollectionsLimitExceeded1059		);10601061		// =========10621063		let collection = Collection {1064			owner: owner.as_sub().clone(),1065			name: data.name,1066			mode: data.mode.clone(),1067			description: data.description,1068			token_prefix: data.token_prefix,1069			sponsorship: data1070				.pending_sponsor1071				.map(SponsorshipState::Unconfirmed)1072				.unwrap_or_default(),1073			limits: data1074				.limits1075				.map(|limits| Self::clamp_limits(data.mode.clone(), &Default::default(), limits))1076				.unwrap_or_else(|| Ok(CollectionLimits::default()))?,1077			permissions: data1078				.permissions1079				.map(|permissions| {1080					Self::clamp_permissions(data.mode.clone(), &Default::default(), permissions)1081				})1082				.unwrap_or_else(|| Ok(CollectionPermissions::default()))?,1083			flags,1084		};10851086		let mut collection_properties = up_data_structs::CollectionProperties::get();1087		collection_properties1088			.try_set_from_iter(data.properties.into_iter())1089			.map_err(<Error<T>>::from)?;10901091		CollectionProperties::<T>::insert(id, collection_properties);10921093		let mut token_props_permissions = PropertiesPermissionMap::new();1094		token_props_permissions1095			.try_set_from_iter(data.token_property_permissions.into_iter())1096			.map_err(<Error<T>>::from)?;10971098		CollectionPropertyPermissions::<T>::insert(id, token_props_permissions);10991100		// Take a (non-refundable) deposit of collection creation1101		{1102			let mut imbalance =1103				<<<T as Config>::Currency as Currency<T::AccountId>>::PositiveImbalance>::zero();1104			imbalance.subsume(1105				<<T as Config>::Currency as Currency<T::AccountId>>::deposit_creating(1106					&T::TreasuryAccountId::get(),1107					T::CollectionCreationPrice::get(),1108				),1109			);1110			<T as Config>::Currency::settle(1111				payer.as_sub(),1112				imbalance,1113				WithdrawReasons::TRANSFER,1114				ExistenceRequirement::KeepAlive,1115			)1116			.map_err(|_| Error::<T>::NotSufficientFounds)?;1117		}11181119		<CreatedCollectionCount<T>>::put(created_count);1120		<Pallet<T>>::deposit_event(Event::CollectionCreated(1121			id,1122			data.mode.id(),1123			owner.as_sub().clone(),1124		));1125		<PalletEvm<T>>::deposit_log(1126			erc::CollectionHelpersEvents::CollectionCreated {1127				owner: *owner.as_eth(),1128				collection_id: eth::collection_id_to_address(id),1129			}1130			.to_log(T::ContractAddress::get()),1131		);1132		<CollectionById<T>>::insert(id, collection);1133		Ok(id)1134	}11351136	/// Destroy collection.1137	///1138	/// * `collection` - Collection handler.1139	/// * `sender` - The owner or administrator of the collection.1140	pub fn destroy_collection(1141		collection: CollectionHandle<T>,1142		sender: &T::CrossAccountId,1143	) -> DispatchResult {1144		ensure!(1145			collection.limits.owner_can_destroy(),1146			<Error<T>>::NoPermission,1147		);1148		collection.check_is_owner(sender)?;11491150		let destroyed_collections = <DestroyedCollectionCount<T>>::get()1151			.01152			.checked_add(1)1153			.ok_or(ArithmeticError::Overflow)?;11541155		// =========11561157		<DestroyedCollectionCount<T>>::put(destroyed_collections);1158		<CollectionById<T>>::remove(collection.id);1159		<AdminAmount<T>>::remove(collection.id);1160		let _ = <IsAdmin<T>>::clear_prefix((collection.id,), u32::MAX, None);1161		let _ = <Allowlist<T>>::clear_prefix((collection.id,), u32::MAX, None);1162		<CollectionProperties<T>>::remove(collection.id);11631164		<Pallet<T>>::deposit_event(Event::CollectionDestroyed(collection.id));11651166		<PalletEvm<T>>::deposit_log(1167			erc::CollectionHelpersEvents::CollectionDestroyed {1168				collection_id: eth::collection_id_to_address(collection.id),1169			}1170			.to_log(T::ContractAddress::get()),1171		);1172		Ok(())1173	}11741175	/// This function sets or removes a collection properties according to1176	/// `properties_updates` contents:1177	/// * sets a property under the <key> with the value provided `(<key>, Some(<value>))`1178	/// * removes a property under the <key> if the value is `None` `(<key>, None)`.1179	///1180	/// This function fires an event for each property change.1181	/// In case of an error, all the changes (including the events) will be reverted1182	/// since the function is transactional.1183	#[transactional]1184	fn modify_collection_properties(1185		collection: &CollectionHandle<T>,1186		sender: &T::CrossAccountId,1187		properties_updates: impl Iterator<Item = (PropertyKey, Option<PropertyValue>)>,1188	) -> DispatchResult {1189		collection.check_is_owner_or_admin(sender)?;11901191		let mut stored_properties = <CollectionProperties<T>>::get(collection.id);11921193		for (key, value) in properties_updates {1194			match value {1195				Some(value) => {1196					stored_properties1197						.try_set(key.clone(), value)1198						.map_err(<Error<T>>::from)?;11991200					Self::deposit_event(Event::CollectionPropertySet(collection.id, key));1201					<PalletEvm<T>>::deposit_log(1202						erc::CollectionHelpersEvents::CollectionChanged {1203							collection_id: eth::collection_id_to_address(collection.id),1204						}1205						.to_log(T::ContractAddress::get()),1206					);1207				}1208				None => {1209					stored_properties.remove(&key).map_err(<Error<T>>::from)?;12101211					Self::deposit_event(Event::CollectionPropertyDeleted(collection.id, key));1212					<PalletEvm<T>>::deposit_log(1213						erc::CollectionHelpersEvents::CollectionChanged {1214							collection_id: eth::collection_id_to_address(collection.id),1215						}1216						.to_log(T::ContractAddress::get()),1217					);1218				}1219			}1220		}12211222		<CollectionProperties<T>>::set(collection.id, stored_properties);12231224		Ok(())1225	}12261227	/// A batch operation to add, edit or remove properties for a token.1228	/// It sets or removes a token's properties according to1229	/// `properties_updates` contents:1230	/// * sets a property under the <key> with the value provided `(<key>, Some(<value>))`1231	/// * removes a property under the <key> if the value is `None` `(<key>, None)`.1232	///1233	/// - `nesting_budget`: Limit for searching parents in-depth to check ownership.1234	/// - `is_token_create`: Indicates that method is called during token initialization.1235	///   Allows to bypass ownership check.1236	///1237	/// All affected properties should have `mutable` permission1238	/// to be **deleted** or to be **set more than once**,1239	/// and the sender should have permission to edit those properties.1240	///1241	/// This function fires an event for each property change.1242	/// In case of an error, all the changes (including the events) will be reverted1243	/// since the function is transactional.1244	pub fn modify_token_properties(1245		collection: &CollectionHandle<T>,1246		sender: &T::CrossAccountId,1247		token_id: TokenId,1248		properties_updates: impl Iterator<Item = (PropertyKey, Option<PropertyValue>)>,1249		is_token_create: bool,1250		mut stored_properties: Properties,1251		is_token_owner: impl Fn() -> Result<bool, DispatchError>,1252		set_token_properties: impl FnOnce(Properties),1253	) -> DispatchResult {1254		let is_collection_admin = collection.is_owner_or_admin(sender);1255		let permissions = Self::property_permissions(collection.id);12561257		let mut token_owner_result = None;1258		let mut is_token_owner = || -> Result<bool, DispatchError> {1259			*token_owner_result.get_or_insert_with(&is_token_owner)1260		};12611262		for (key, value) in properties_updates {1263			let permission = permissions1264				.get(&key)1265				.cloned()1266				.unwrap_or_else(PropertyPermission::none);12671268			let is_property_exists = stored_properties.get(&key).is_some();12691270			match permission {1271				PropertyPermission { mutable: false, .. } if is_property_exists => {1272					return Err(<Error<T>>::NoPermission.into());1273				}12741275				PropertyPermission {1276					collection_admin,1277					token_owner,1278					..1279				} => {1280					//TODO: investigate threats during public minting.1281					let is_token_create =1282						is_token_create && (collection_admin || token_owner) && value.is_some();1283					if !(is_token_create1284						|| (collection_admin && is_collection_admin)1285						|| (token_owner && is_token_owner()?))1286					{1287						fail!(<Error<T>>::NoPermission);1288					}1289				}1290			}12911292			match value {1293				Some(value) => {1294					stored_properties1295						.try_set(key.clone(), value)1296						.map_err(<Error<T>>::from)?;12971298					Self::deposit_event(Event::TokenPropertySet(collection.id, token_id, key));1299				}1300				None => {1301					stored_properties.remove(&key).map_err(<Error<T>>::from)?;13021303					Self::deposit_event(Event::TokenPropertyDeleted(collection.id, token_id, key));1304				}1305			}13061307			<PalletEvm<T>>::deposit_log(1308				CollectionHelpersEvents::TokenChanged {1309					collection_id: eth::collection_id_to_address(collection.id),1310					token_id: token_id.into(),1311				}1312				.to_log(T::ContractAddress::get()),1313			);1314		}13151316		set_token_properties(stored_properties);13171318		Ok(())1319	}13201321	/// Sets or unsets the approval of a given operator.1322	///1323	/// The `operator` is allowed to transfer all token pieces of the `owner` on their behalf.1324	/// - `owner`: Token owner1325	/// - `operator`: Operator1326	/// - `approve`: Should operator status be granted or revoked?1327	pub fn set_allowance_for_all(1328		collection: &CollectionHandle<T>,1329		owner: &T::CrossAccountId,1330		operator: &T::CrossAccountId,1331		approve: bool,1332		set_allowance: impl FnOnce(),1333		log: evm_coder::ethereum::Log,1334	) -> DispatchResult {1335		if collection.permissions.access() == AccessMode::AllowList {1336			collection.check_allowlist(owner)?;1337			collection.check_allowlist(operator)?;1338		}13391340		Self::ensure_correct_receiver(operator)?;13411342		set_allowance();13431344		<PalletEvm<T>>::deposit_log(log);1345		Self::deposit_event(Event::ApprovedForAll(1346			collection.id,1347			owner.clone(),1348			operator.clone(),1349			approve,1350		));1351		Ok(())1352	}13531354	/// Set collection property.1355	///1356	/// * `collection` - Collection handler.1357	/// * `sender` - The owner or administrator of the collection.1358	/// * `property` - The property to set.1359	pub fn set_collection_property(1360		collection: &CollectionHandle<T>,1361		sender: &T::CrossAccountId,1362		property: Property,1363	) -> DispatchResult {1364		Self::set_collection_properties(collection, sender, [property].into_iter())1365	}13661367	/// Set a scoped collection property, where the scope is a special prefix1368	/// prohibiting a user access to change the property directly.1369	///1370	/// * `collection_id` - ID of the collection for which the property is being set.1371	/// * `scope` - Property scope.1372	/// * `property` - The property to set.1373	pub fn set_scoped_collection_property(1374		collection_id: CollectionId,1375		scope: PropertyScope,1376		property: Property,1377	) -> DispatchResult {1378		CollectionProperties::<T>::try_mutate(collection_id, |properties| {1379			properties.try_scoped_set(scope, property.key, property.value)1380		})1381		.map_err(<Error<T>>::from)?;13821383		Ok(())1384	}13851386	/// Set scoped collection properties, where the scope is a special prefix1387	/// prohibiting a user access to change the properties directly.1388	///1389	/// * `collection_id` - ID of the collection for which the properties is being set.1390	/// * `scope` - Property scope.1391	/// * `properties` - The properties to set.1392	pub fn set_scoped_collection_properties(1393		collection_id: CollectionId,1394		scope: PropertyScope,1395		properties: impl Iterator<Item = Property>,1396	) -> DispatchResult {1397		CollectionProperties::<T>::try_mutate(collection_id, |stored_properties| {1398			stored_properties.try_scoped_set_from_iter(scope, properties)1399		})1400		.map_err(<Error<T>>::from)?;14011402		Ok(())1403	}14041405	/// Set collection properties.1406	///1407	/// * `collection` - Collection handler.1408	/// * `sender` - The owner or administrator of the collection.1409	/// * `properties` - The properties to set.1410	pub fn set_collection_properties(1411		collection: &CollectionHandle<T>,1412		sender: &T::CrossAccountId,1413		properties: impl Iterator<Item = Property>,1414	) -> DispatchResult {1415		Self::modify_collection_properties(1416			collection,1417			sender,1418			properties.map(|property| (property.key, Some(property.value))),1419		)1420	}14211422	/// Delete collection property.1423	///1424	/// * `collection` - Collection handler.1425	/// * `sender` - The owner or administrator of the collection.1426	/// * `property` - The property to delete.1427	pub fn delete_collection_property(1428		collection: &CollectionHandle<T>,1429		sender: &T::CrossAccountId,1430		property_key: PropertyKey,1431	) -> DispatchResult {1432		Self::delete_collection_properties(collection, sender, [property_key].into_iter())1433	}14341435	/// Delete collection properties.1436	///1437	/// * `collection` - Collection handler.1438	/// * `sender` - The owner or administrator of the collection.1439	/// * `properties` - The properties to delete.1440	pub fn delete_collection_properties(1441		collection: &CollectionHandle<T>,1442		sender: &T::CrossAccountId,1443		property_keys: impl Iterator<Item = PropertyKey>,1444	) -> DispatchResult {1445		Self::modify_collection_properties(collection, sender, property_keys.map(|key| (key, None)))1446	}14471448	/// Set collection propetry permission without any checks.1449	///1450	/// Used for migrations.1451	///1452	/// * `collection` - Collection handler.1453	/// * `property_permissions` - Property permissions.1454	pub fn set_property_permission_unchecked(1455		collection: CollectionId,1456		property_permission: PropertyKeyPermission,1457	) -> DispatchResult {1458		<CollectionPropertyPermissions<T>>::try_mutate(collection, |permissions| {1459			permissions.try_set(property_permission.key, property_permission.permission)1460		})1461		.map_err(<Error<T>>::from)?;1462		Ok(())1463	}14641465	/// Set collection property permission.1466	///1467	/// * `collection` - Collection handler.1468	/// * `sender` - The owner or administrator of the collection.1469	/// * `property_permission` - Property permission.1470	pub fn set_property_permission(1471		collection: &CollectionHandle<T>,1472		sender: &T::CrossAccountId,1473		property_permission: PropertyKeyPermission,1474	) -> DispatchResult {1475		Self::set_scoped_property_permission(1476			collection,1477			sender,1478			PropertyScope::None,1479			property_permission,1480		)1481	}14821483	/// Set collection property permission with scope.1484	///1485	/// * `collection` - Collection handler.1486	/// * `sender` - The owner or administrator of the collection.1487	/// * `scope` - Property scope.1488	/// * `property_permission` - Property permission.1489	pub fn set_scoped_property_permission(1490		collection: &CollectionHandle<T>,1491		sender: &T::CrossAccountId,1492		scope: PropertyScope,1493		property_permission: PropertyKeyPermission,1494	) -> DispatchResult {1495		collection.check_is_owner_or_admin(sender)?;14961497		let all_permissions = CollectionPropertyPermissions::<T>::get(collection.id);1498		let current_permission = all_permissions.get(&property_permission.key);1499		if matches![1500			current_permission,1501			Some(PropertyPermission { mutable: false, .. })1502		] {1503			return Err(<Error<T>>::NoPermission.into());1504		}15051506		CollectionPropertyPermissions::<T>::try_mutate(collection.id, |permissions| {1507			let property_permission = property_permission.clone();1508			permissions.try_scoped_set(1509				scope,1510				property_permission.key,1511				property_permission.permission,1512			)1513		})1514		.map_err(<Error<T>>::from)?;15151516		Self::deposit_event(Event::PropertyPermissionSet(1517			collection.id,1518			property_permission.key,1519		));1520		<PalletEvm<T>>::deposit_log(1521			erc::CollectionHelpersEvents::CollectionChanged {1522				collection_id: eth::collection_id_to_address(collection.id),1523			}1524			.to_log(T::ContractAddress::get()),1525		);15261527		Ok(())1528	}15291530	/// Set token property permission.1531	///1532	/// * `collection` - Collection handler.1533	/// * `sender` - The owner or administrator of the collection.1534	/// * `property_permissions` - Property permissions.1535	#[transactional]1536	pub fn set_token_property_permissions(1537		collection: &CollectionHandle<T>,1538		sender: &T::CrossAccountId,1539		property_permissions: Vec<PropertyKeyPermission>,1540	) -> DispatchResult {1541		Self::set_scoped_token_property_permissions(1542			collection,1543			sender,1544			PropertyScope::None,1545			property_permissions,1546		)1547	}15481549	/// Set token property permission with scope.1550	///1551	/// * `collection` - Collection handler.1552	/// * `sender` - The owner or administrator of the collection.1553	/// * `scope` - Property scope.1554	/// * `property_permissions` - Property permissions.1555	#[transactional]1556	pub fn set_scoped_token_property_permissions(1557		collection: &CollectionHandle<T>,1558		sender: &T::CrossAccountId,1559		scope: PropertyScope,1560		property_permissions: Vec<PropertyKeyPermission>,1561	) -> DispatchResult {1562		for prop_pemission in property_permissions {1563			Self::set_scoped_property_permission(collection, sender, scope, prop_pemission)?;1564		}15651566		Ok(())1567	}15681569	/// Get collection property.1570	pub fn get_collection_property(1571		collection_id: CollectionId,1572		key: &PropertyKey,1573	) -> Option<PropertyValue> {1574		Self::collection_properties(collection_id).get(key).cloned()1575	}15761577	/// Convert byte vector to property key vector.1578	pub fn bytes_keys_to_property_keys(1579		keys: Vec<Vec<u8>>,1580	) -> Result<Vec<PropertyKey>, DispatchError> {1581		keys.into_iter()1582			.map(|key| -> Result<PropertyKey, DispatchError> {1583				key.try_into()1584					.map_err(|_| <Error<T>>::PropertyKeyIsTooLong.into())1585			})1586			.collect::<Result<Vec<PropertyKey>, DispatchError>>()1587	}15881589	/// Get properties according to given keys.1590	pub fn filter_collection_properties(1591		collection_id: CollectionId,1592		keys: Option<Vec<PropertyKey>>,1593	) -> Result<Vec<Property>, DispatchError> {1594		let properties = Self::collection_properties(collection_id);15951596		let properties = keys1597			.map(|keys| {1598				keys.into_iter()1599					.filter_map(|key| {1600						properties.get(&key).map(|value| Property {1601							key,1602							value: value.clone(),1603						})1604					})1605					.collect()1606			})1607			.unwrap_or_else(|| {1608				properties1609					.into_iter()1610					.map(|(key, value)| Property { key, value })1611					.collect()1612			});16131614		Ok(properties)1615	}16161617	/// Get property permissions according to given keys.1618	pub fn filter_property_permissions(1619		collection_id: CollectionId,1620		keys: Option<Vec<PropertyKey>>,1621	) -> Result<Vec<PropertyKeyPermission>, DispatchError> {1622		let permissions = Self::property_permissions(collection_id);16231624		let key_permissions = keys1625			.map(|keys| {1626				keys.into_iter()1627					.filter_map(|key| {1628						permissions1629							.get(&key)1630							.map(|permission| PropertyKeyPermission {1631								key,1632								permission: permission.clone(),1633							})1634					})1635					.collect()1636			})1637			.unwrap_or_else(|| {1638				permissions1639					.into_iter()1640					.map(|(key, permission)| PropertyKeyPermission { key, permission })1641					.collect()1642			});16431644		Ok(key_permissions)1645	}16461647	/// Toggle `user` participation in the `collection`'s allow list.1648	/// #### Store read/writes1649	/// 1 writes1650	pub fn toggle_allowlist(1651		collection: &CollectionHandle<T>,1652		sender: &T::CrossAccountId,1653		user: &T::CrossAccountId,1654		allowed: bool,1655	) -> DispatchResult {1656		collection.check_is_owner_or_admin(sender)?;16571658		// =========16591660		if allowed {1661			<Allowlist<T>>::insert((collection.id, user), true);1662			Self::deposit_event(Event::<T>::AllowListAddressAdded(1663				collection.id,1664				user.clone(),1665			));1666		} else {1667			<Allowlist<T>>::remove((collection.id, user));1668			Self::deposit_event(Event::<T>::AllowListAddressRemoved(1669				collection.id,1670				user.clone(),1671			));1672		}16731674		<PalletEvm<T>>::deposit_log(1675			erc::CollectionHelpersEvents::CollectionChanged {1676				collection_id: eth::collection_id_to_address(collection.id),1677			}1678			.to_log(T::ContractAddress::get()),1679		);16801681		Ok(())1682	}16831684	/// Toggle `user` participation in the `collection`'s admin list.1685	/// #### Store read/writes1686	/// 2 reads, 2 writes1687	pub fn toggle_admin(1688		collection: &CollectionHandle<T>,1689		sender: &T::CrossAccountId,1690		user: &T::CrossAccountId,1691		admin: bool,1692	) -> DispatchResult {1693		collection.check_is_internal()?;1694		collection.check_is_owner(sender)?;16951696		let is_admin = <IsAdmin<T>>::get((collection.id, user));1697		if is_admin == admin {1698			if admin {1699				return Ok(());1700			} else {1701				return Err(Error::<T>::UserIsNotCollectionAdmin.into());1702			}1703		}1704		let amount = <AdminAmount<T>>::get(collection.id);17051706		// =========17071708		if admin {1709			let amount = amount1710				.checked_add(1)1711				.ok_or(<Error<T>>::CollectionAdminCountExceeded)?;1712			ensure!(1713				amount <= Self::collection_admins_limit(),1714				<Error<T>>::CollectionAdminCountExceeded,1715			);17161717			<AdminAmount<T>>::insert(collection.id, amount);1718			<IsAdmin<T>>::insert((collection.id, user), true);17191720			Self::deposit_event(Event::<T>::CollectionAdminAdded(1721				collection.id,1722				user.clone(),1723			));1724		} else {1725			<AdminAmount<T>>::insert(collection.id, amount.saturating_sub(1));1726			<IsAdmin<T>>::remove((collection.id, user));17271728			Self::deposit_event(Event::<T>::CollectionAdminRemoved(1729				collection.id,1730				user.clone(),1731			));1732		}17331734		<PalletEvm<T>>::deposit_log(1735			erc::CollectionHelpersEvents::CollectionChanged {1736				collection_id: eth::collection_id_to_address(collection.id),1737			}1738			.to_log(T::ContractAddress::get()),1739		);17401741		Ok(())1742	}17431744	/// Update collection limits.1745	pub fn update_limits(1746		user: &T::CrossAccountId,1747		collection: &mut CollectionHandle<T>,1748		new_limit: CollectionLimits,1749	) -> DispatchResult {1750		collection.check_is_internal()?;1751		collection.check_is_owner_or_admin(user)?;17521753		collection.limits =1754			Self::clamp_limits(collection.mode.clone(), &collection.limits, new_limit)?;17551756		Self::deposit_event(Event::<T>::CollectionLimitSet(collection.id));1757		<PalletEvm<T>>::deposit_log(1758			erc::CollectionHelpersEvents::CollectionChanged {1759				collection_id: eth::collection_id_to_address(collection.id),1760			}1761			.to_log(T::ContractAddress::get()),1762		);17631764		collection.save()1765	}17661767	/// Merge set fields from `new_limit` to `old_limit`.1768	fn clamp_limits(1769		mode: CollectionMode,1770		old_limit: &CollectionLimits,1771		mut new_limit: CollectionLimits,1772	) -> Result<CollectionLimits, DispatchError> {1773		let limits = old_limit;1774		limit_default!(old_limit, new_limit,1775			account_token_ownership_limit => ensure!(1776				new_limit <= MAX_TOKEN_OWNERSHIP,1777				<Error<T>>::CollectionLimitBoundsExceeded,1778			),1779			sponsored_data_size => ensure!(1780				new_limit <= CUSTOM_DATA_LIMIT,1781				<Error<T>>::CollectionLimitBoundsExceeded,1782			),17831784			sponsored_data_rate_limit => {},1785			token_limit => ensure!(1786				old_limit >= new_limit && new_limit > 0,1787				<Error<T>>::CollectionTokenLimitExceeded1788			),17891790			sponsor_transfer_timeout(match mode {1791				CollectionMode::NFT => NFT_SPONSOR_TRANSFER_TIMEOUT,1792				CollectionMode::Fungible(_) => FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,1793				CollectionMode::ReFungible => REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,1794			}) => ensure!(1795				new_limit <= MAX_SPONSOR_TIMEOUT,1796				<Error<T>>::CollectionLimitBoundsExceeded,1797			),1798			sponsor_approve_timeout => {},1799			owner_can_transfer => ensure!(1800				!limits.owner_can_transfer_instaled() ||1801				old_limit || !new_limit,1802				<Error<T>>::OwnerPermissionsCantBeReverted,1803			),1804			owner_can_destroy => ensure!(1805				old_limit || !new_limit,1806				<Error<T>>::OwnerPermissionsCantBeReverted,1807			),1808			transfers_enabled => {},1809		);1810		Ok(new_limit)1811	}18121813	/// Update collection permissions.1814	pub fn update_permissions(1815		user: &T::CrossAccountId,1816		collection: &mut CollectionHandle<T>,1817		new_permission: CollectionPermissions,1818	) -> DispatchResult {1819		collection.check_is_internal()?;1820		collection.check_is_owner_or_admin(user)?;1821		collection.permissions = Self::clamp_permissions(1822			collection.mode.clone(),1823			&collection.permissions,1824			new_permission,1825		)?;18261827		Self::deposit_event(Event::<T>::CollectionPermissionSet(collection.id));1828		<PalletEvm<T>>::deposit_log(1829			erc::CollectionHelpersEvents::CollectionChanged {1830				collection_id: eth::collection_id_to_address(collection.id),1831			}1832			.to_log(T::ContractAddress::get()),1833		);18341835		collection.save()1836	}18371838	/// Merge set fields from `new_permission` to `old_permission`.1839	fn clamp_permissions(1840		_mode: CollectionMode,1841		old_permission: &CollectionPermissions,1842		mut new_permission: CollectionPermissions,1843	) -> Result<CollectionPermissions, DispatchError> {1844		limit_default_clone!(old_permission, new_permission,1845			access => {},1846			mint_mode => {},1847			nesting => { /* todo check for permissive, if only it gets out of benchmarks */ },1848		);1849		Ok(new_permission)1850	}18511852	/// Repair possibly broken properties of a collection.1853	pub fn repair_collection(collection_id: CollectionId) -> DispatchResult {1854		CollectionProperties::<T>::mutate(collection_id, |properties| {1855			properties.recompute_consumed_space();1856		});18571858		Ok(())1859	}1860}18611862/// Indicates unsupported methods by returning [Error::UnsupportedOperation].1863#[macro_export]1864macro_rules! unsupported {1865	($runtime:path) => {1866		Err($crate::Error::<$runtime>::UnsupportedOperation.into())1867	};1868}18691870/// Return weights for various worst-case operations.1871pub trait CommonWeightInfo<CrossAccountId> {1872	/// Weight of item creation.1873	fn create_item(data: &CreateItemData) -> Weight {1874		Self::create_multiple_items(from_ref(data))1875	}18761877	/// Weight of items creation.1878	fn create_multiple_items(amount: &[CreateItemData]) -> Weight;18791880	/// Weight of items creation.1881	fn create_multiple_items_ex(cost: &CreateItemExData<CrossAccountId>) -> Weight;18821883	/// The weight of the burning item.1884	fn burn_item() -> Weight;18851886	/// Property setting weight.1887	///1888	/// * `amount`- The number of properties to set.1889	fn set_collection_properties(amount: u32) -> Weight;18901891	/// Collection property deletion weight.1892	///1893	/// * `amount`- The number of properties to set.1894	fn delete_collection_properties(amount: u32) -> Weight;18951896	/// Token property setting weight.1897	///1898	/// * `amount`- The number of properties to set.1899	fn set_token_properties(amount: u32) -> Weight;19001901	/// Token property deletion weight.1902	///1903	/// * `amount`- The number of properties to delete.1904	fn delete_token_properties(amount: u32) -> Weight;19051906	/// Token property permissions set weight.1907	///1908	/// * `amount`- The number of property permissions to set.1909	fn set_token_property_permissions(amount: u32) -> Weight;19101911	/// Transfer price of the token or its parts.1912	fn transfer() -> Weight;19131914	/// The price of setting the permission of the operation from another user.1915	fn approve() -> Weight;19161917	/// The price of setting the permission of the operation from another user for eth mirror.1918	fn approve_from() -> Weight;19191920	/// Transfer price from another user.1921	fn transfer_from() -> Weight;19221923	/// The price of burning a token from another user.1924	fn burn_from() -> Weight;19251926	/// Differs from burn_item in case of Fungible and Refungible, as it should burn1927	/// whole users's balance.1928	///1929	/// This method shouldn't be used directly, as it doesn't count breadth price, use [burn_recursively](CommonWeightInfo::burn_recursively) instead1930	fn burn_recursively_self_raw() -> Weight;19311932	/// Cost of iterating over `amount` children while burning, without counting child burning itself.1933	///1934	/// This method shouldn't be used directly, as it doesn't count depth price, use [burn_recursively](CommonWeightInfo::burn_recursively) instead1935	fn burn_recursively_breadth_raw(amount: u32) -> Weight;19361937	/// The price of recursive burning a token.1938	///1939	/// `max_selfs` - The maximum burning weight of the token itself.1940	/// `max_breadth` - The maximum number of nested tokens to burn.1941	fn burn_recursively(max_selfs: u32, max_breadth: u32) -> Weight {1942		Self::burn_recursively_self_raw()1943			.saturating_mul(max_selfs.max(1) as u64)1944			.saturating_add(Self::burn_recursively_breadth_raw(max_breadth))1945	}19461947	/// The price of retrieving token owner1948	fn token_owner() -> 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	/// Burn token and all nested tokens recursievly.2022	///2023	/// * `sender` - The user who owns the token.2024	/// * `token` - Token id that will burned.2025	/// * `self_budget` - The budget that can be spent on burning tokens.2026	/// * `breadth_budget` - The budget that can be spent on burning nested tokens.2027	fn burn_item_recursively(2028		&self,2029		sender: T::CrossAccountId,2030		token: TokenId,2031		self_budget: &dyn Budget,2032		breadth_budget: &dyn Budget,2033	) -> DispatchResultWithPostInfo;20342035	/// Set collection properties.2036	///2037	/// * `sender` - Must be either the owner of the collection or its admin.2038	/// * `properties` - Properties to be set.2039	fn set_collection_properties(2040		&self,2041		sender: T::CrossAccountId,2042		properties: Vec<Property>,2043	) -> DispatchResultWithPostInfo;20442045	/// Delete collection properties.2046	///2047	/// * `sender` - Must be either the owner of the collection or its admin.2048	/// * `properties` - The properties to be removed.2049	fn delete_collection_properties(2050		&self,2051		sender: &T::CrossAccountId,2052		property_keys: Vec<PropertyKey>,2053	) -> DispatchResultWithPostInfo;20542055	/// Set token properties.2056	///2057	/// The appropriate [`PropertyPermission`] for the token property2058	/// must be set with [`Self::set_token_property_permissions`].2059	///2060	/// * `sender` - Must be either the owner of the token or its admin.2061	/// * `token_id` - The token for which the properties are being set.2062	/// * `properties` - Properties to be set.2063	/// * `budget` - Budget for setting properties.2064	fn set_token_properties(2065		&self,2066		sender: T::CrossAccountId,2067		token_id: TokenId,2068		properties: Vec<Property>,2069		budget: &dyn Budget,2070	) -> DispatchResultWithPostInfo;20712072	/// Remove token properties.2073	///2074	/// The appropriate [`PropertyPermission`] for the token property2075	/// must be set with [`Self::set_token_property_permissions`].2076	///2077	/// * `sender` - Must be either the owner of the token or its admin.2078	/// * `token_id` - The token for which the properties are being remove.2079	/// * `property_keys` - Keys to remove corresponding properties.2080	/// * `budget` - Budget for removing properties.2081	fn delete_token_properties(2082		&self,2083		sender: T::CrossAccountId,2084		token_id: TokenId,2085		property_keys: Vec<PropertyKey>,2086		budget: &dyn Budget,2087	) -> DispatchResultWithPostInfo;20882089	/// Set token property permissions.2090	///2091	/// * `sender` - Must be either the owner of the token or its admin.2092	/// * `token_id` - The token for which the properties are being set.2093	/// * `property_permissions` - Property permissions to be set.2094	/// * `budget` - Budget for setting properties.2095	fn set_token_property_permissions(2096		&self,2097		sender: &T::CrossAccountId,2098		property_permissions: Vec<PropertyKeyPermission>,2099	) -> DispatchResultWithPostInfo;21002101	/// Transfer amount of token pieces.2102	///2103	/// * `sender` - Donor user.2104	/// * `to` - Recepient user.2105	/// * `token` - The token of which parts are being sent.2106	/// * `amount` - The number of parts of the token that will be transferred.2107	/// * `budget` - The maximum budget that can be spent on the transfer.2108	fn transfer(2109		&self,2110		sender: T::CrossAccountId,2111		to: T::CrossAccountId,2112		token: TokenId,2113		amount: u128,2114		budget: &dyn Budget,2115	) -> DispatchResultWithPostInfo;21162117	/// Grant access to another account to transfer parts of the token owned by the calling user via [Self::transfer_from].2118	///2119	/// * `sender` - The user who grants access to the token.2120	/// * `spender` - The user to whom the rights are granted.2121	/// * `token` - The token to which access is granted.2122	/// * `amount` - The amount of pieces that another user can dispose of.2123	fn approve(2124		&self,2125		sender: T::CrossAccountId,2126		spender: T::CrossAccountId,2127		token: TokenId,2128		amount: u128,2129	) -> DispatchResultWithPostInfo;21302131	/// Grant access to another account to transfer parts of the token owned by the calling user's eth mirror via [Self::transfer_from].2132	///2133	/// * `sender` - The user who grants access to the token.2134	/// * `from` - Spender's eth mirror.2135	/// * `to` - The user to whom the rights are granted.2136	/// * `token` - The token to which access is granted.2137	/// * `amount` - The amount of pieces that another user can dispose of.2138	fn approve_from(2139		&self,2140		sender: T::CrossAccountId,2141		from: T::CrossAccountId,2142		to: T::CrossAccountId,2143		token: TokenId,2144		amount: u128,2145	) -> DispatchResultWithPostInfo;21462147	/// Send parts of a token owned by another user.2148	///2149	/// Before calling this method, you must grant rights to the calling user via [`Self::approve`].2150	///2151	/// * `sender` - The user who must have access to the token (see [`Self::approve`]).2152	/// * `from` - The user who owns the token.2153	/// * `to` - Recepient user.2154	/// * `token` - The token of which parts are being sent.2155	/// * `amount` - The number of parts of the token that will be transferred.2156	/// * `budget` - The maximum budget that can be spent on the transfer.2157	fn transfer_from(2158		&self,2159		sender: T::CrossAccountId,2160		from: T::CrossAccountId,2161		to: T::CrossAccountId,2162		token: TokenId,2163		amount: u128,2164		budget: &dyn Budget,2165	) -> DispatchResultWithPostInfo;21662167	/// Burn parts of a token owned by another user.2168	///2169	/// Before calling this method, you must grant rights to the calling user via [`Self::approve`].2170	///2171	/// * `sender` - The user who must have access to the token (see [`Self::approve`]).2172	/// * `from` - The user who owns the token.2173	/// * `token` - The token of which parts are being sent.2174	/// * `amount` - The number of parts of the token that will be transferred.2175	/// * `budget` - The maximum budget that can be spent on the burn.2176	fn burn_from(2177		&self,2178		sender: T::CrossAccountId,2179		from: T::CrossAccountId,2180		token: TokenId,2181		amount: u128,2182		budget: &dyn Budget,2183	) -> DispatchResultWithPostInfo;21842185	/// Check permission to nest token.2186	///2187	/// * `sender` - The user who initiated the check.2188	/// * `from` - The token that is checked for embedding.2189	/// * `under` - Token under which to check.2190	/// * `budget` - The maximum budget that can be spent on the check.2191	fn check_nesting(2192		&self,2193		sender: T::CrossAccountId,2194		from: (CollectionId, TokenId),2195		under: TokenId,2196		budget: &dyn Budget,2197	) -> DispatchResult;21982199	/// Nest one token into another.2200	///2201	/// * `under` - Token holder.2202	/// * `to_nest` - Nested token.2203	fn nest(&self, under: TokenId, to_nest: (CollectionId, TokenId));22042205	/// Unnest token.2206	///2207	/// * `under` - Token holder.2208	/// * `to_nest` - Token to unnest.2209	fn unnest(&self, under: TokenId, to_nest: (CollectionId, TokenId));22102211	/// Get all user tokens.2212	///2213	/// * `account` - Account for which you need to get tokens.2214	fn account_tokens(&self, account: T::CrossAccountId) -> Vec<TokenId>;22152216	/// Get all the tokens in the collection.2217	fn collection_tokens(&self) -> Vec<TokenId>;22182219	/// Check if the token exists.2220	///2221	/// * `token` - Id token to check.2222	fn token_exists(&self, token: TokenId) -> bool;22232224	/// Get the id of the last minted token.2225	fn last_token_id(&self) -> TokenId;22262227	/// Get the owner of the token.2228	///2229	/// * `token` - The token for which you need to find out the owner.2230	fn token_owner(&self, token: TokenId) -> Result<T::CrossAccountId, TokenOwnerError>;22312232	/// Returns 10 tokens owners in no particular order.2233	///2234	/// * `token` - The token for which you need to find out the owners.2235	fn token_owners(&self, token: TokenId) -> Vec<T::CrossAccountId>;22362237	/// Get the value of the token property by key.2238	///2239	/// * `token` - Token with the property to get.2240	/// * `key` - Property name.2241	fn token_property(&self, token_id: TokenId, key: &PropertyKey) -> Option<PropertyValue>;22422243	/// Get a set of token properties by key vector.2244	///2245	/// * `token` - Token with the property to get.2246	/// * `keys` - Vector of property keys. If this parameter is [None](sp_std::result::Result),2247	/// then all properties are returned.2248	fn token_properties(&self, token: TokenId, keys: Option<Vec<PropertyKey>>) -> Vec<Property>;22492250	/// Amount of unique collection tokens2251	fn total_supply(&self) -> u32;22522253	/// Amount of different tokens account has.2254	///2255	/// * `account` - The account for which need to get the balance.2256	fn account_balance(&self, account: T::CrossAccountId) -> u32;22572258	/// Amount of specific token account have.2259	fn balance(&self, account: T::CrossAccountId, token: TokenId) -> u128;22602261	/// Amount of token pieces2262	fn total_pieces(&self, token: TokenId) -> Option<u128>;22632264	/// Get the number of parts of the token that a trusted user can manage.2265	///2266	/// * `sender` - Trusted user.2267	/// * `spender` - Owner of the token.2268	/// * `token` - The token for which to get the value.2269	fn allowance(2270		&self,2271		sender: T::CrossAccountId,2272		spender: T::CrossAccountId,2273		token: TokenId,2274	) -> u128;22752276	/// Get extension for RFT collection.2277	fn refungible_extensions(&self) -> Option<&dyn RefungibleExtensions<T>>;22782279	/// The `operator` is allowed to transfer all tokens of the `owner` on their behalf.2280	/// * `owner` - Token owner2281	/// * `operator` - Operator2282	/// * `approve` - Should operator status be granted or revoked?2283	fn set_allowance_for_all(2284		&self,2285		owner: T::CrossAccountId,2286		operator: T::CrossAccountId,2287		approve: bool,2288	) -> DispatchResultWithPostInfo;22892290	/// Tells whether the given `owner` approves the `operator`.2291	fn allowance_for_all(&self, owner: T::CrossAccountId, operator: T::CrossAccountId) -> bool;22922293	/// Repairs a possibly broken item.2294	fn repair_item(&self, token: TokenId) -> DispatchResultWithPostInfo;2295}22962297/// Extension for RFT collection.2298pub trait RefungibleExtensions<T>2299where2300	T: Config,2301{2302	/// Change the number of parts of the token.2303	///2304	/// When the value changes down, this function is equivalent to burning parts of the token.2305	///2306	/// * `sender` - The user calling the repartition operation. Must be the owner of the token.2307	/// * `token` - The token for which you want to change the number of parts.2308	/// * `amount` - The new value of the parts of the token.2309	fn repartition(2310		&self,2311		sender: &T::CrossAccountId,2312		token: TokenId,2313		amount: u128,2314	) -> DispatchResultWithPostInfo;2315}23162317/// Merge [`DispatchResult`] with [`Weight`] into [`DispatchResultWithPostInfo`].2318///2319/// Used for [`CommonCollectionOperations`] implementations and flexible enough to do so.2320pub fn with_weight(res: DispatchResult, weight: Weight) -> DispatchResultWithPostInfo {2321	let post_info = PostDispatchInfo {2322		actual_weight: Some(weight),2323		pays_fee: Pays::Yes,2324	};2325	match res {2326		Ok(()) => Ok(post_info),2327		Err(error) => Err(DispatchErrorWithPostInfo { post_info, error }),2328	}2329}23302331impl<T: Config> From<PropertiesError> for Error<T> {2332	fn from(error: PropertiesError) -> Self {2333		match error {2334			PropertiesError::NoSpaceForProperty => Self::NoSpaceForProperty,2335			PropertiesError::PropertyLimitReached => Self::PropertyLimitReached,2336			PropertiesError::InvalidCharacterInPropertyKey => Self::InvalidCharacterInPropertyKey,2337			PropertiesError::PropertyKeyIsTooLong => Self::PropertyKeyIsTooLong,2338			PropertiesError::EmptyPropertyKey => Self::EmptyPropertyKey,2339		}2340	}2341}
modifiedpallets/fungible/src/erc.rsdiffbeforeafterboth
--- a/pallets/fungible/src/erc.rs
+++ b/pallets/fungible/src/erc.rs
@@ -38,8 +38,8 @@
 use sp_core::{U256, Get};
 
 use crate::{
-	Allowance, Balance, Config, FungibleHandle, Pallet, TotalSupply,
-	SelfWeightOf, weights::WeightInfo,	
+	Allowance, Balance, Config, FungibleHandle, Pallet, TotalSupply, SelfWeightOf,
+	weights::WeightInfo,
 };
 
 frontier_contract! {
modifiedpallets/refungible/src/erc.rsdiffbeforeafterboth
--- a/pallets/refungible/src/erc.rs
+++ b/pallets/refungible/src/erc.rs
@@ -48,8 +48,8 @@
 };
 
 use crate::{
-	AccountBalance, Balance, Config, CreateItemData, Pallet, RefungibleHandle, 
-	TokenProperties, TokensMinted, TotalSupply, SelfWeightOf, weights::WeightInfo,
+	AccountBalance, Balance, Config, CreateItemData, Pallet, RefungibleHandle, TokenProperties,
+	TokensMinted, TotalSupply, SelfWeightOf, weights::WeightInfo,
 };
 
 frontier_contract! {
modifiedpallets/refungible/src/erc_token.rsdiffbeforeafterboth
--- a/pallets/refungible/src/erc_token.rs
+++ b/pallets/refungible/src/erc_token.rs
@@ -40,7 +40,10 @@
 use sp_core::U256;
 use up_data_structs::TokenId;
 
-use crate::{Allowance, Balance, Config, Pallet, RefungibleHandle, TotalSupply, common::CommonWeights, SelfWeightOf, weights::WeightInfo};
+use crate::{
+	Allowance, Balance, Config, Pallet, RefungibleHandle, TotalSupply, common::CommonWeights,
+	SelfWeightOf, weights::WeightInfo,
+};
 
 /// Refungible token handle contains information about token's collection and id
 ///