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}
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
 ///