git.delta.rocks / unique-network / refs/commits / b1f22167a941

difftreelog

fix remove from_ref_time usages

Yaroslav Bolyukin2023-04-17parent: #07a293d.patch.diff
in: master

9 files changed

modifiedpallets/common/src/dispatch.rsdiffbeforeafterboth
--- a/pallets/common/src/dispatch.rs
+++ b/pallets/common/src/dispatch.rs
@@ -19,7 +19,7 @@
 	// Read collection
 	<T as frame_system::Config>::DbWeight::get().reads(1)
 	// Dynamic dispatch?
-	+ Weight::from_ref_time(6_000_000)
+	+ Weight::from_parts(6_000_000, 0)
 	// submit_logs is measured as part of collection pallets
 }
 
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, 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, CollectionProperties as CollectionPropertiesT, TokenProperties,80	PropertiesPermissionMap, PropertyKey, PropertyValue, PropertyPermission, PropertiesError,81	TokenOwnerError, PropertyKeyPermission, TokenData, TrySetProperty, PropertyScope,82	CollectionPermissions,83};84use up_pov_estimate_rpc::PovInfo;8586pub use pallet::*;87use sp_core::H160;88use sp_runtime::{ArithmeticError, DispatchError, DispatchResult};8990#[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	pub struct Pallet<T>(_);466467	#[pallet::extra_constants]468	impl<T: Config> Pallet<T> {469		/// Maximum admins per collection.470		pub fn collection_admins_limit() -> u32 {471			COLLECTION_ADMINS_LIMIT472		}473	}474475	impl<T: Config> Pallet<T> {476		/// Helper function that handles deposit events477		pub fn deposit_event(event: Event<T>) {478			let event = <T as Config>::RuntimeEvent::from(event);479			let event = event.into();480			<frame_system::Pallet<T>>::deposit_event(event)481		}482	}483484	#[pallet::event]485	pub enum Event<T: Config> {486		/// New collection was created487		CollectionCreated(488			/// Globally unique identifier of newly created collection.489			CollectionId,490			/// [`CollectionMode`] converted into _u8_.491			u8,492			/// Collection owner.493			T::AccountId,494		),495496		/// New collection was destroyed497		CollectionDestroyed(498			/// Globally unique identifier of collection.499			CollectionId,500		),501502		/// New item was created.503		ItemCreated(504			/// Id of the collection where item was created.505			CollectionId,506			/// Id of an item. Unique within the collection.507			TokenId,508			/// Owner of newly created item509			T::CrossAccountId,510			/// Always 1 for NFT511			u128,512		),513514		/// Collection item was burned.515		ItemDestroyed(516			/// Id of the collection where item was destroyed.517			CollectionId,518			/// Identifier of burned NFT.519			TokenId,520			/// Which user has destroyed its tokens.521			T::CrossAccountId,522			/// Amount of token pieces destroed. Always 1 for NFT.523			u128,524		),525526		/// Item was transferred527		Transfer(528			/// Id of collection to which item is belong.529			CollectionId,530			/// Id of an item.531			TokenId,532			/// Original owner of item.533			T::CrossAccountId,534			/// New owner of item.535			T::CrossAccountId,536			/// Amount of token pieces transfered. Always 1 for NFT.537			u128,538		),539540		/// Amount pieces of token owned by `sender` was approved for `spender`.541		Approved(542			/// Id of collection to which item is belong.543			CollectionId,544			/// Id of an item.545			TokenId,546			/// Original owner of item.547			T::CrossAccountId,548			/// Id for which the approval was granted.549			T::CrossAccountId,550			/// Amount of token pieces transfered. Always 1 for NFT.551			u128,552		),553554		/// A `sender` approves operations on all owned tokens for `spender`.555		ApprovedForAll(556			/// Id of collection to which item is belong.557			CollectionId,558			/// Owner of a wallet.559			T::CrossAccountId,560			/// Id for which operator status was granted or rewoked.561			T::CrossAccountId,562			/// Is operator status granted or revoked?563			bool,564		),565566		/// The colletion property has been added or edited.567		CollectionPropertySet(568			/// Id of collection to which property has been set.569			CollectionId,570			/// The property that was set.571			PropertyKey,572		),573574		/// The property has been deleted.575		CollectionPropertyDeleted(576			/// Id of collection to which property has been deleted.577			CollectionId,578			/// The property that was deleted.579			PropertyKey,580		),581582		/// The token property has been added or edited.583		TokenPropertySet(584			/// Identifier of the collection whose token has the property set.585			CollectionId,586			/// The token for which the property was set.587			TokenId,588			/// The property that was set.589			PropertyKey,590		),591592		/// The token property has been deleted.593		TokenPropertyDeleted(594			/// Identifier of the collection whose token has the property deleted.595			CollectionId,596			/// The token for which the property was deleted.597			TokenId,598			/// The property that was deleted.599			PropertyKey,600		),601602		/// The token property permission of a collection has been set.603		PropertyPermissionSet(604			/// ID of collection to which property permission has been set.605			CollectionId,606			/// The property permission that was set.607			PropertyKey,608		),609610		/// Address was added to the allow list.611		AllowListAddressAdded(612			/// ID of the affected collection.613			CollectionId,614			/// Address of the added account.615			T::CrossAccountId,616		),617618		/// Address was removed from the allow list.619		AllowListAddressRemoved(620			/// ID of the affected collection.621			CollectionId,622			/// Address of the removed account.623			T::CrossAccountId,624		),625626		/// Collection admin was added.627		CollectionAdminAdded(628			/// ID of the affected collection.629			CollectionId,630			/// Admin address.631			T::CrossAccountId,632		),633634		/// Collection admin was removed.635		CollectionAdminRemoved(636			/// ID of the affected collection.637			CollectionId,638			/// Removed admin address.639			T::CrossAccountId,640		),641642		/// Collection limits were set.643		CollectionLimitSet(644			/// ID of the affected collection.645			CollectionId,646		),647648		/// Collection owned was changed.649		CollectionOwnerChanged(650			/// ID of the affected collection.651			CollectionId,652			/// New owner address.653			T::AccountId,654		),655656		/// Collection permissions were set.657		CollectionPermissionSet(658			/// ID of the affected collection.659			CollectionId,660		),661662		/// Collection sponsor was set.663		CollectionSponsorSet(664			/// ID of the affected collection.665			CollectionId,666			/// New sponsor address.667			T::AccountId,668		),669670		/// New sponsor was confirm.671		SponsorshipConfirmed(672			/// ID of the affected collection.673			CollectionId,674			/// New sponsor address.675			T::AccountId,676		),677678		/// Collection sponsor was removed.679		CollectionSponsorRemoved(680			/// ID of the affected collection.681			CollectionId,682		),683	}684685	#[pallet::error]686	pub enum Error<T> {687		/// This collection does not exist.688		CollectionNotFound,689		/// Sender parameter and item owner must be equal.690		MustBeTokenOwner,691		/// No permission to perform action692		NoPermission,693		/// Destroying only empty collections is allowed694		CantDestroyNotEmptyCollection,695		/// Collection is not in mint mode.696		PublicMintingNotAllowed,697		/// Address is not in allow list.698		AddressNotInAllowlist,699700		/// Collection name can not be longer than 63 char.701		CollectionNameLimitExceeded,702		/// Collection description can not be longer than 255 char.703		CollectionDescriptionLimitExceeded,704		/// Token prefix can not be longer than 15 char.705		CollectionTokenPrefixLimitExceeded,706		/// Total collections bound exceeded.707		TotalCollectionsLimitExceeded,708		/// Exceeded max admin count709		CollectionAdminCountExceeded,710		/// Collection limit bounds per collection exceeded711		CollectionLimitBoundsExceeded,712		/// Tried to enable permissions which are only permitted to be disabled713		OwnerPermissionsCantBeReverted,714		/// Collection settings not allowing items transferring715		TransferNotAllowed,716		/// Account token limit exceeded per collection717		AccountTokenLimitExceeded,718		/// Collection token limit exceeded719		CollectionTokenLimitExceeded,720		/// Metadata flag frozen721		MetadataFlagFrozen,722723		/// Item does not exist724		TokenNotFound,725		/// Item is balance not enough726		TokenValueTooLow,727		/// Requested value is more than the approved728		ApprovedValueTooLow,729		/// Tried to approve more than owned730		CantApproveMoreThanOwned,731		/// Only spending from eth mirror could be approved732		AddressIsNotEthMirror,733734		/// Can't transfer tokens to ethereum zero address735		AddressIsZero,736737		/// The operation is not supported738		UnsupportedOperation,739740		/// Insufficient funds to perform an action741		NotSufficientFounds,742743		/// User does not satisfy the nesting rule744		UserIsNotAllowedToNest,745		/// Only tokens from specific collections may nest tokens under this one746		SourceCollectionIsNotAllowedToNest,747748		/// Tried to store more data than allowed in collection field749		CollectionFieldSizeExceeded,750751		/// Tried to store more property data than allowed752		NoSpaceForProperty,753754		/// Tried to store more property keys than allowed755		PropertyLimitReached,756757		/// Property key is too long758		PropertyKeyIsTooLong,759760		/// Only ASCII letters, digits, and symbols `_`, `-`, and `.` are allowed761		InvalidCharacterInPropertyKey,762763		/// Empty property keys are forbidden764		EmptyPropertyKey,765766		/// Tried to access an external collection with an internal API767		CollectionIsExternal,768769		/// Tried to access an internal collection with an external API770		CollectionIsInternal,771772		/// This address is not set as sponsor, use setCollectionSponsor first.773		ConfirmSponsorshipFail,774775		/// The user is not an administrator.776		UserIsNotCollectionAdmin,777	}778779	/// Storage of the count of created collections. Essentially contains the last collection ID.780	#[pallet::storage]781	pub type CreatedCollectionCount<T> = StorageValue<Value = CollectionId, QueryKind = ValueQuery>;782783	/// Storage of the count of deleted collections.784	#[pallet::storage]785	pub type DestroyedCollectionCount<T> =786		StorageValue<Value = CollectionId, QueryKind = ValueQuery>;787788	/// Storage of collection info.789	#[pallet::storage]790	pub type CollectionById<T> = StorageMap<791		Hasher = Blake2_128Concat,792		Key = CollectionId,793		Value = Collection<<T as frame_system::Config>::AccountId>,794		QueryKind = OptionQuery,795	>;796797	/// Storage of collection properties.798	#[pallet::storage]799	#[pallet::getter(fn collection_properties)]800	pub type CollectionProperties<T> = StorageMap<801		Hasher = Blake2_128Concat,802		Key = CollectionId,803		Value = CollectionPropertiesT,804		QueryKind = ValueQuery,805	>;806807	/// Storage of token property permissions of a collection.808	#[pallet::storage]809	#[pallet::getter(fn property_permissions)]810	pub type CollectionPropertyPermissions<T> = StorageMap<811		Hasher = Blake2_128Concat,812		Key = CollectionId,813		Value = PropertiesPermissionMap,814		QueryKind = ValueQuery,815	>;816817	/// Storage of the amount of collection admins.818	#[pallet::storage]819	pub type AdminAmount<T> = StorageMap<820		Hasher = Blake2_128Concat,821		Key = CollectionId,822		Value = u32,823		QueryKind = ValueQuery,824	>;825826	/// List of collection admins.827	#[pallet::storage]828	pub type IsAdmin<T: Config> = StorageNMap<829		Key = (830			Key<Blake2_128Concat, CollectionId>,831			Key<Blake2_128Concat, T::CrossAccountId>,832		),833		Value = bool,834		QueryKind = ValueQuery,835	>;836837	/// Allowlisted collection users.838	#[pallet::storage]839	pub type Allowlist<T: Config> = StorageNMap<840		Key = (841			Key<Blake2_128Concat, CollectionId>,842			Key<Blake2_128Concat, T::CrossAccountId>,843		),844		Value = bool,845		QueryKind = ValueQuery,846	>;847848	/// Not used by code, exists only to provide some types to metadata.849	#[pallet::storage]850	pub type DummyStorageValue<T: Config> = StorageValue<851		Value = (852			CollectionStats,853			CollectionId,854			TokenId,855			TokenChild,856			PhantomType<(857				TokenData<T::CrossAccountId>,858				RpcCollection<T::AccountId>,859				// PoV Estimate Info860				PovInfo,861			)>,862		),863		QueryKind = OptionQuery,864	>;865866	#[pallet::hooks]867	impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {868		fn on_runtime_upgrade() -> Weight {869			StorageVersion::new(1).put::<Pallet<T>>();870871			Weight::zero()872		}873	}874}875876impl<T: Config> Pallet<T> {877	/// Enshure that receiver address is correct.878	///879	/// Ethereum receiver 0x0000000000000000000000000000000000000000 is reserved, and shouldn't own tokens.880	pub fn ensure_correct_receiver(receiver: &T::CrossAccountId) -> DispatchResult {881		ensure!(882			&T::CrossAccountId::from_eth(H160([0; 20])) != receiver,883			<Error<T>>::AddressIsZero884		);885		Ok(())886	}887888	/// Get a vector of collection admins.889	pub fn adminlist(collection: CollectionId) -> Vec<T::CrossAccountId> {890		<IsAdmin<T>>::iter_prefix((collection,))891			.map(|(a, _)| a)892			.collect()893	}894895	/// Get a vector of users allowed to mint tokens.896	pub fn allowlist(collection: CollectionId) -> Vec<T::CrossAccountId> {897		<Allowlist<T>>::iter_prefix((collection,))898			.map(|(a, _)| a)899			.collect()900	}901902	/// Is `user` allowed to mint token in `collection`.903	pub fn allowed(collection: CollectionId, user: T::CrossAccountId) -> bool {904		<Allowlist<T>>::get((collection, user))905	}906907	/// Get statistics of collections.908	pub fn collection_stats() -> CollectionStats {909		let created = <CreatedCollectionCount<T>>::get();910		let destroyed = <DestroyedCollectionCount<T>>::get();911		CollectionStats {912			created: created.0,913			destroyed: destroyed.0,914			alive: created.0 - destroyed.0,915		}916	}917918	/// Get the effective limits for the collection.919	pub fn effective_collection_limits(collection: CollectionId) -> Option<CollectionLimits> {920		let collection = <CollectionById<T>>::get(collection)?;921		let limits = collection.limits;922		let effective_limits = CollectionLimits {923			account_token_ownership_limit: Some(limits.account_token_ownership_limit()),924			sponsored_data_size: Some(limits.sponsored_data_size()),925			sponsored_data_rate_limit: Some(926				limits927					.sponsored_data_rate_limit928					.unwrap_or(SponsoringRateLimit::SponsoringDisabled),929			),930			token_limit: Some(limits.token_limit()),931			sponsor_transfer_timeout: Some(limits.sponsor_transfer_timeout(932				match collection.mode {933					CollectionMode::NFT => NFT_SPONSOR_TRANSFER_TIMEOUT,934					CollectionMode::Fungible(_) => FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,935					CollectionMode::ReFungible => REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,936				},937			)),938			sponsor_approve_timeout: Some(limits.sponsor_approve_timeout()),939			owner_can_transfer: Some(limits.owner_can_transfer()),940			owner_can_destroy: Some(limits.owner_can_destroy()),941			transfers_enabled: Some(limits.transfers_enabled()),942		};943944		Some(effective_limits)945	}946947	/// Returns information about the `collection` adapted for rpc.948	pub fn rpc_collection(collection: CollectionId) -> Option<RpcCollection<T::AccountId>> {949		let Collection {950			name,951			description,952			owner,953			mode,954			token_prefix,955			sponsorship,956			limits,957			permissions,958			flags,959		} = <CollectionById<T>>::get(collection)?;960961		let token_property_permissions = <CollectionPropertyPermissions<T>>::get(collection)962			.into_iter()963			.map(|(key, permission)| PropertyKeyPermission { key, permission })964			.collect();965966		let properties = <CollectionProperties<T>>::get(collection)967			.into_iter()968			.map(|(key, value)| Property { key, value })969			.collect();970971		let permissions = CollectionPermissions {972			access: Some(permissions.access()),973			mint_mode: Some(permissions.mint_mode()),974			nesting: Some(permissions.nesting().clone()),975		};976977		Some(RpcCollection {978			name: name.into_inner(),979			description: description.into_inner(),980			owner,981			mode,982			token_prefix: token_prefix.into_inner(),983			sponsorship,984			limits,985			permissions,986			token_property_permissions,987			properties,988			read_only: flags.external,989990			flags: RpcCollectionFlags {991				foreign: flags.foreign,992				erc721metadata: flags.erc721metadata,993			},994		})995	}996}997998macro_rules! limit_default {999	($old:ident, $new:ident, $($field:ident $(($arg:expr))? => $check:expr),* $(,)?) => {{1000		$(1001			if let Some($new) = $new.$field {1002				let $old = $old.$field($($arg)?);1003				let _ = $new;1004				let _ = $old;1005				$check1006			} else {1007				$new.$field = $old.$field1008			}1009		)*1010	}};1011}1012macro_rules! limit_default_clone {1013	($old:ident, $new:ident, $($field:ident $(($arg:expr))? => $check:expr),* $(,)?) => {{1014		$(1015			if let Some($new) = $new.$field.clone() {1016				let $old = $old.$field($($arg)?);1017				let _ = $new;1018				let _ = $old;1019				$check1020			} else {1021				$new.$field = $old.$field.clone()1022			}1023		)*1024	}};1025}10261027impl<T: Config> Pallet<T> {1028	/// Create new collection.1029	///1030	/// * `owner` - The owner of the collection.1031	/// * `data` - Description of the created collection.1032	/// * `flags` - Extra flags to store.1033	pub fn init_collection(1034		owner: T::CrossAccountId,1035		payer: T::CrossAccountId,1036		data: CreateCollectionData<T::AccountId>,1037		flags: CollectionFlags,1038	) -> Result<CollectionId, DispatchError> {1039		{1040			ensure!(1041				data.token_prefix.len() <= MAX_TOKEN_PREFIX_LENGTH as usize,1042				Error::<T>::CollectionTokenPrefixLimitExceeded1043			);1044		}10451046		let created_count = <CreatedCollectionCount<T>>::get()1047			.01048			.checked_add(1)1049			.ok_or(ArithmeticError::Overflow)?;1050		let destroyed_count = <DestroyedCollectionCount<T>>::get().0;1051		let id = CollectionId(created_count);10521053		// bound Total number of collections1054		ensure!(1055			created_count - destroyed_count <= COLLECTION_NUMBER_LIMIT,1056			<Error<T>>::TotalCollectionsLimitExceeded1057		);10581059		// =========10601061		let collection = Collection {1062			owner: owner.as_sub().clone(),1063			name: data.name,1064			mode: data.mode.clone(),1065			description: data.description,1066			token_prefix: data.token_prefix,1067			sponsorship: data1068				.pending_sponsor1069				.map(SponsorshipState::Unconfirmed)1070				.unwrap_or_default(),1071			limits: data1072				.limits1073				.map(|limits| Self::clamp_limits(data.mode.clone(), &Default::default(), limits))1074				.unwrap_or_else(|| Ok(CollectionLimits::default()))?,1075			permissions: data1076				.permissions1077				.map(|permissions| {1078					Self::clamp_permissions(data.mode.clone(), &Default::default(), permissions)1079				})1080				.unwrap_or_else(|| Ok(CollectionPermissions::default()))?,1081			flags,1082		};10831084		let mut collection_properties = CollectionPropertiesT::new();1085		collection_properties1086			.try_set_from_iter(data.properties.into_iter())1087			.map_err(<Error<T>>::from)?;10881089		CollectionProperties::<T>::insert(id, collection_properties);10901091		let mut token_props_permissions = PropertiesPermissionMap::new();1092		token_props_permissions1093			.try_set_from_iter(data.token_property_permissions.into_iter())1094			.map_err(<Error<T>>::from)?;10951096		CollectionPropertyPermissions::<T>::insert(id, token_props_permissions);10971098		// Take a (non-refundable) deposit of collection creation1099		{1100			let mut imbalance =1101				<<<T as Config>::Currency as Currency<T::AccountId>>::PositiveImbalance>::zero();1102			imbalance.subsume(1103				<<T as Config>::Currency as Currency<T::AccountId>>::deposit_creating(1104					&T::TreasuryAccountId::get(),1105					T::CollectionCreationPrice::get(),1106				),1107			);1108			<T as Config>::Currency::settle(1109				payer.as_sub(),1110				imbalance,1111				WithdrawReasons::TRANSFER,1112				ExistenceRequirement::KeepAlive,1113			)1114			.map_err(|_| Error::<T>::NotSufficientFounds)?;1115		}11161117		<CreatedCollectionCount<T>>::put(created_count);1118		<Pallet<T>>::deposit_event(Event::CollectionCreated(1119			id,1120			data.mode.id(),1121			owner.as_sub().clone(),1122		));1123		<PalletEvm<T>>::deposit_log(1124			erc::CollectionHelpersEvents::CollectionCreated {1125				owner: *owner.as_eth(),1126				collection_id: eth::collection_id_to_address(id),1127			}1128			.to_log(T::ContractAddress::get()),1129		);1130		<CollectionById<T>>::insert(id, collection);1131		Ok(id)1132	}11331134	/// Destroy collection.1135	///1136	/// * `collection` - Collection handler.1137	/// * `sender` - The owner or administrator of the collection.1138	pub fn destroy_collection(1139		collection: CollectionHandle<T>,1140		sender: &T::CrossAccountId,1141	) -> DispatchResult {1142		ensure!(1143			collection.limits.owner_can_destroy(),1144			<Error<T>>::NoPermission,1145		);1146		collection.check_is_owner(sender)?;11471148		let destroyed_collections = <DestroyedCollectionCount<T>>::get()1149			.01150			.checked_add(1)1151			.ok_or(ArithmeticError::Overflow)?;11521153		// =========11541155		<DestroyedCollectionCount<T>>::put(destroyed_collections);1156		<CollectionById<T>>::remove(collection.id);1157		<AdminAmount<T>>::remove(collection.id);1158		let _ = <IsAdmin<T>>::clear_prefix((collection.id,), u32::MAX, None);1159		let _ = <Allowlist<T>>::clear_prefix((collection.id,), u32::MAX, None);1160		<CollectionProperties<T>>::remove(collection.id);11611162		<Pallet<T>>::deposit_event(Event::CollectionDestroyed(collection.id));11631164		<PalletEvm<T>>::deposit_log(1165			erc::CollectionHelpersEvents::CollectionDestroyed {1166				collection_id: eth::collection_id_to_address(collection.id),1167			}1168			.to_log(T::ContractAddress::get()),1169		);1170		Ok(())1171	}11721173	/// This function sets or removes a collection properties according to1174	/// `properties_updates` contents:1175	/// * sets a property under the <key> with the value provided `(<key>, Some(<value>))`1176	/// * removes a property under the <key> if the value is `None` `(<key>, None)`.1177	///1178	/// This function fires an event for each property change.1179	/// In case of an error, all the changes (including the events) will be reverted1180	/// since the function is transactional.1181	#[transactional]1182	fn modify_collection_properties(1183		collection: &CollectionHandle<T>,1184		sender: &T::CrossAccountId,1185		properties_updates: impl Iterator<Item = (PropertyKey, Option<PropertyValue>)>,1186	) -> DispatchResult {1187		collection.check_is_owner_or_admin(sender)?;11881189		let mut stored_properties = <CollectionProperties<T>>::get(collection.id);11901191		for (key, value) in properties_updates {1192			match value {1193				Some(value) => {1194					stored_properties1195						.try_set(key.clone(), value)1196						.map_err(<Error<T>>::from)?;11971198					Self::deposit_event(Event::CollectionPropertySet(collection.id, key));1199					<PalletEvm<T>>::deposit_log(1200						erc::CollectionHelpersEvents::CollectionChanged {1201							collection_id: eth::collection_id_to_address(collection.id),1202						}1203						.to_log(T::ContractAddress::get()),1204					);1205				}1206				None => {1207					stored_properties.remove(&key).map_err(<Error<T>>::from)?;12081209					Self::deposit_event(Event::CollectionPropertyDeleted(collection.id, key));1210					<PalletEvm<T>>::deposit_log(1211						erc::CollectionHelpersEvents::CollectionChanged {1212							collection_id: eth::collection_id_to_address(collection.id),1213						}1214						.to_log(T::ContractAddress::get()),1215					);1216				}1217			}1218		}12191220		<CollectionProperties<T>>::set(collection.id, stored_properties);12211222		Ok(())1223	}12241225	/// A batch operation to add, edit or remove properties for a token.1226	/// It sets or removes a token's properties according to1227	/// `properties_updates` contents:1228	/// * sets a property under the <key> with the value provided `(<key>, Some(<value>))`1229	/// * removes a property under the <key> if the value is `None` `(<key>, None)`.1230	///1231	/// - `nesting_budget`: Limit for searching parents in-depth to check ownership.1232	/// - `is_token_create`: Indicates that method is called during token initialization.1233	///   Allows to bypass ownership check.1234	///1235	/// All affected properties should have `mutable` permission1236	/// to be **deleted** or to be **set more than once**,1237	/// and the sender should have permission to edit those properties.1238	///1239	/// This function fires an event for each property change.1240	/// In case of an error, all the changes (including the events) will be reverted1241	/// since the function is transactional.1242	pub fn modify_token_properties(1243		collection: &CollectionHandle<T>,1244		sender: &T::CrossAccountId,1245		token_id: TokenId,1246		properties_updates: impl Iterator<Item = (PropertyKey, Option<PropertyValue>)>,1247		is_token_create: bool,1248		mut stored_properties: TokenProperties,1249		is_token_owner: impl Fn() -> Result<bool, DispatchError>,1250		set_token_properties: impl FnOnce(TokenProperties),1251		log: evm_coder::ethereum::Log,1252	) -> DispatchResult {1253		let is_collection_admin = collection.is_owner_or_admin(sender);1254		let permissions = Self::property_permissions(collection.id);12551256		let mut token_owner_result = None;1257		let mut is_token_owner = || -> Result<bool, DispatchError> {1258			*token_owner_result.get_or_insert_with(&is_token_owner)1259		};12601261		for (key, value) in properties_updates {1262			let permission = permissions1263				.get(&key)1264				.cloned()1265				.unwrap_or_else(PropertyPermission::none);12661267			let is_property_exists = stored_properties.get(&key).is_some();12681269			match permission {1270				PropertyPermission { mutable: false, .. } if is_property_exists => {1271					return Err(<Error<T>>::NoPermission.into());1272				}12731274				PropertyPermission {1275					collection_admin,1276					token_owner,1277					..1278				} => {1279					//TODO: investigate threats during public minting.1280					let is_token_create =1281						is_token_create && (collection_admin || token_owner) && value.is_some();1282					if !(is_token_create1283						|| (collection_admin && is_collection_admin)1284						|| (token_owner && is_token_owner()?))1285					{1286						fail!(<Error<T>>::NoPermission);1287					}1288				}1289			}12901291			match value {1292				Some(value) => {1293					stored_properties1294						.try_set(key.clone(), value)1295						.map_err(<Error<T>>::from)?;12961297					Self::deposit_event(Event::TokenPropertySet(collection.id, token_id, key));1298				}1299				None => {1300					stored_properties.remove(&key).map_err(<Error<T>>::from)?;13011302					Self::deposit_event(Event::TokenPropertyDeleted(collection.id, token_id, key));1303				}1304			}13051306			<PalletEvm<T>>::deposit_log(log.clone());1307		}13081309		set_token_properties(stored_properties);13101311		Ok(())1312	}13131314	/// Sets or unsets the approval of a given operator.1315	///1316	/// The `operator` is allowed to transfer all token pieces of the `owner` on their behalf.1317	/// - `owner`: Token owner1318	/// - `operator`: Operator1319	/// - `approve`: Should operator status be granted or revoked?1320	pub fn set_allowance_for_all(1321		collection: &CollectionHandle<T>,1322		owner: &T::CrossAccountId,1323		operator: &T::CrossAccountId,1324		approve: bool,1325		set_allowance: impl FnOnce(),1326		log: evm_coder::ethereum::Log,1327	) -> DispatchResult {1328		if collection.permissions.access() == AccessMode::AllowList {1329			collection.check_allowlist(owner)?;1330			collection.check_allowlist(operator)?;1331		}13321333		Self::ensure_correct_receiver(operator)?;13341335		set_allowance();13361337		<PalletEvm<T>>::deposit_log(log);1338		Self::deposit_event(Event::ApprovedForAll(1339			collection.id,1340			owner.clone(),1341			operator.clone(),1342			approve,1343		));1344		Ok(())1345	}13461347	/// Set collection property.1348	///1349	/// * `collection` - Collection handler.1350	/// * `sender` - The owner or administrator of the collection.1351	/// * `property` - The property to set.1352	pub fn set_collection_property(1353		collection: &CollectionHandle<T>,1354		sender: &T::CrossAccountId,1355		property: Property,1356	) -> DispatchResult {1357		Self::set_collection_properties(collection, sender, [property].into_iter())1358	}13591360	/// Set a scoped collection property, where the scope is a special prefix1361	/// prohibiting a user access to change the property directly.1362	///1363	/// * `collection_id` - ID of the collection for which the property is being set.1364	/// * `scope` - Property scope.1365	/// * `property` - The property to set.1366	pub fn set_scoped_collection_property(1367		collection_id: CollectionId,1368		scope: PropertyScope,1369		property: Property,1370	) -> DispatchResult {1371		CollectionProperties::<T>::try_mutate(collection_id, |properties| {1372			properties.try_scoped_set(scope, property.key, property.value)1373		})1374		.map_err(<Error<T>>::from)?;13751376		Ok(())1377	}13781379	/// Set scoped collection properties, where the scope is a special prefix1380	/// prohibiting a user access to change the properties directly.1381	///1382	/// * `collection_id` - ID of the collection for which the properties is being set.1383	/// * `scope` - Property scope.1384	/// * `properties` - The properties to set.1385	pub fn set_scoped_collection_properties(1386		collection_id: CollectionId,1387		scope: PropertyScope,1388		properties: impl Iterator<Item = Property>,1389	) -> DispatchResult {1390		CollectionProperties::<T>::try_mutate(collection_id, |stored_properties| {1391			stored_properties.try_scoped_set_from_iter(scope, properties)1392		})1393		.map_err(<Error<T>>::from)?;13941395		Ok(())1396	}13971398	/// Set collection properties.1399	///1400	/// * `collection` - Collection handler.1401	/// * `sender` - The owner or administrator of the collection.1402	/// * `properties` - The properties to set.1403	pub fn set_collection_properties(1404		collection: &CollectionHandle<T>,1405		sender: &T::CrossAccountId,1406		properties: impl Iterator<Item = Property>,1407	) -> DispatchResult {1408		Self::modify_collection_properties(1409			collection,1410			sender,1411			properties.map(|property| (property.key, Some(property.value))),1412		)1413	}14141415	/// Delete collection property.1416	///1417	/// * `collection` - Collection handler.1418	/// * `sender` - The owner or administrator of the collection.1419	/// * `property` - The property to delete.1420	pub fn delete_collection_property(1421		collection: &CollectionHandle<T>,1422		sender: &T::CrossAccountId,1423		property_key: PropertyKey,1424	) -> DispatchResult {1425		Self::delete_collection_properties(collection, sender, [property_key].into_iter())1426	}14271428	/// Delete collection properties.1429	///1430	/// * `collection` - Collection handler.1431	/// * `sender` - The owner or administrator of the collection.1432	/// * `properties` - The properties to delete.1433	pub fn delete_collection_properties(1434		collection: &CollectionHandle<T>,1435		sender: &T::CrossAccountId,1436		property_keys: impl Iterator<Item = PropertyKey>,1437	) -> DispatchResult {1438		Self::modify_collection_properties(collection, sender, property_keys.map(|key| (key, None)))1439	}14401441	/// Set collection propetry permission without any checks.1442	///1443	/// Used for migrations.1444	///1445	/// * `collection` - Collection handler.1446	/// * `property_permissions` - Property permissions.1447	pub fn set_property_permission_unchecked(1448		collection: CollectionId,1449		property_permission: PropertyKeyPermission,1450	) -> DispatchResult {1451		<CollectionPropertyPermissions<T>>::try_mutate(collection, |permissions| {1452			permissions.try_set(property_permission.key, property_permission.permission)1453		})1454		.map_err(<Error<T>>::from)?;1455		Ok(())1456	}14571458	/// Set collection property permission.1459	///1460	/// * `collection` - Collection handler.1461	/// * `sender` - The owner or administrator of the collection.1462	/// * `property_permission` - Property permission.1463	pub fn set_property_permission(1464		collection: &CollectionHandle<T>,1465		sender: &T::CrossAccountId,1466		property_permission: PropertyKeyPermission,1467	) -> DispatchResult {1468		Self::set_scoped_property_permission(1469			collection,1470			sender,1471			PropertyScope::None,1472			property_permission,1473		)1474	}14751476	/// Set collection property permission with scope.1477	///1478	/// * `collection` - Collection handler.1479	/// * `sender` - The owner or administrator of the collection.1480	/// * `scope` - Property scope.1481	/// * `property_permission` - Property permission.1482	pub fn set_scoped_property_permission(1483		collection: &CollectionHandle<T>,1484		sender: &T::CrossAccountId,1485		scope: PropertyScope,1486		property_permission: PropertyKeyPermission,1487	) -> DispatchResult {1488		collection.check_is_owner_or_admin(sender)?;14891490		let all_permissions = CollectionPropertyPermissions::<T>::get(collection.id);1491		let current_permission = all_permissions.get(&property_permission.key);1492		if matches![1493			current_permission,1494			Some(PropertyPermission { mutable: false, .. })1495		] {1496			return Err(<Error<T>>::NoPermission.into());1497		}14981499		CollectionPropertyPermissions::<T>::try_mutate(collection.id, |permissions| {1500			let property_permission = property_permission.clone();1501			permissions.try_scoped_set(1502				scope,1503				property_permission.key,1504				property_permission.permission,1505			)1506		})1507		.map_err(<Error<T>>::from)?;15081509		Self::deposit_event(Event::PropertyPermissionSet(1510			collection.id,1511			property_permission.key,1512		));1513		<PalletEvm<T>>::deposit_log(1514			erc::CollectionHelpersEvents::CollectionChanged {1515				collection_id: eth::collection_id_to_address(collection.id),1516			}1517			.to_log(T::ContractAddress::get()),1518		);15191520		Ok(())1521	}15221523	/// Set token property permission.1524	///1525	/// * `collection` - Collection handler.1526	/// * `sender` - The owner or administrator of the collection.1527	/// * `property_permissions` - Property permissions.1528	#[transactional]1529	pub fn set_token_property_permissions(1530		collection: &CollectionHandle<T>,1531		sender: &T::CrossAccountId,1532		property_permissions: Vec<PropertyKeyPermission>,1533	) -> DispatchResult {1534		Self::set_scoped_token_property_permissions(1535			collection,1536			sender,1537			PropertyScope::None,1538			property_permissions,1539		)1540	}15411542	/// Set token property permission with scope.1543	///1544	/// * `collection` - Collection handler.1545	/// * `sender` - The owner or administrator of the collection.1546	/// * `scope` - Property scope.1547	/// * `property_permissions` - Property permissions.1548	#[transactional]1549	pub fn set_scoped_token_property_permissions(1550		collection: &CollectionHandle<T>,1551		sender: &T::CrossAccountId,1552		scope: PropertyScope,1553		property_permissions: Vec<PropertyKeyPermission>,1554	) -> DispatchResult {1555		for prop_pemission in property_permissions {1556			Self::set_scoped_property_permission(collection, sender, scope, prop_pemission)?;1557		}15581559		Ok(())1560	}15611562	/// Get collection property.1563	pub fn get_collection_property(1564		collection_id: CollectionId,1565		key: &PropertyKey,1566	) -> Option<PropertyValue> {1567		Self::collection_properties(collection_id).get(key).cloned()1568	}15691570	/// Convert byte vector to property key vector.1571	pub fn bytes_keys_to_property_keys(1572		keys: Vec<Vec<u8>>,1573	) -> Result<Vec<PropertyKey>, DispatchError> {1574		keys.into_iter()1575			.map(|key| -> Result<PropertyKey, DispatchError> {1576				key.try_into()1577					.map_err(|_| <Error<T>>::PropertyKeyIsTooLong.into())1578			})1579			.collect::<Result<Vec<PropertyKey>, DispatchError>>()1580	}15811582	/// Get properties according to given keys.1583	pub fn filter_collection_properties(1584		collection_id: CollectionId,1585		keys: Option<Vec<PropertyKey>>,1586	) -> Result<Vec<Property>, DispatchError> {1587		let properties = Self::collection_properties(collection_id);15881589		let properties = keys1590			.map(|keys| {1591				keys.into_iter()1592					.filter_map(|key| {1593						properties.get(&key).map(|value| Property {1594							key,1595							value: value.clone(),1596						})1597					})1598					.collect()1599			})1600			.unwrap_or_else(|| {1601				properties1602					.into_iter()1603					.map(|(key, value)| Property { key, value })1604					.collect()1605			});16061607		Ok(properties)1608	}16091610	/// Get property permissions according to given keys.1611	pub fn filter_property_permissions(1612		collection_id: CollectionId,1613		keys: Option<Vec<PropertyKey>>,1614	) -> Result<Vec<PropertyKeyPermission>, DispatchError> {1615		let permissions = Self::property_permissions(collection_id);16161617		let key_permissions = keys1618			.map(|keys| {1619				keys.into_iter()1620					.filter_map(|key| {1621						permissions1622							.get(&key)1623							.map(|permission| PropertyKeyPermission {1624								key,1625								permission: permission.clone(),1626							})1627					})1628					.collect()1629			})1630			.unwrap_or_else(|| {1631				permissions1632					.into_iter()1633					.map(|(key, permission)| PropertyKeyPermission { key, permission })1634					.collect()1635			});16361637		Ok(key_permissions)1638	}16391640	/// Toggle `user` participation in the `collection`'s allow list.1641	/// #### Store read/writes1642	/// 1 writes1643	pub fn toggle_allowlist(1644		collection: &CollectionHandle<T>,1645		sender: &T::CrossAccountId,1646		user: &T::CrossAccountId,1647		allowed: bool,1648	) -> DispatchResult {1649		collection.check_is_owner_or_admin(sender)?;16501651		// =========16521653		if allowed {1654			<Allowlist<T>>::insert((collection.id, user), true);1655			Self::deposit_event(Event::<T>::AllowListAddressAdded(1656				collection.id,1657				user.clone(),1658			));1659		} else {1660			<Allowlist<T>>::remove((collection.id, user));1661			Self::deposit_event(Event::<T>::AllowListAddressRemoved(1662				collection.id,1663				user.clone(),1664			));1665		}16661667		<PalletEvm<T>>::deposit_log(1668			erc::CollectionHelpersEvents::CollectionChanged {1669				collection_id: eth::collection_id_to_address(collection.id),1670			}1671			.to_log(T::ContractAddress::get()),1672		);16731674		Ok(())1675	}16761677	/// Toggle `user` participation in the `collection`'s admin list.1678	/// #### Store read/writes1679	/// 2 reads, 2 writes1680	pub fn toggle_admin(1681		collection: &CollectionHandle<T>,1682		sender: &T::CrossAccountId,1683		user: &T::CrossAccountId,1684		admin: bool,1685	) -> DispatchResult {1686		collection.check_is_internal()?;1687		collection.check_is_owner(sender)?;16881689		let is_admin = <IsAdmin<T>>::get((collection.id, user));1690		if is_admin == admin {1691			if admin {1692				return Ok(());1693			} else {1694				return Err(Error::<T>::UserIsNotCollectionAdmin.into());1695			}1696		}1697		let amount = <AdminAmount<T>>::get(collection.id);16981699		// =========17001701		if admin {1702			let amount = amount1703				.checked_add(1)1704				.ok_or(<Error<T>>::CollectionAdminCountExceeded)?;1705			ensure!(1706				amount <= Self::collection_admins_limit(),1707				<Error<T>>::CollectionAdminCountExceeded,1708			);17091710			<AdminAmount<T>>::insert(collection.id, amount);1711			<IsAdmin<T>>::insert((collection.id, user), true);17121713			Self::deposit_event(Event::<T>::CollectionAdminAdded(1714				collection.id,1715				user.clone(),1716			));1717		} else {1718			<AdminAmount<T>>::insert(collection.id, amount.saturating_sub(1));1719			<IsAdmin<T>>::remove((collection.id, user));17201721			Self::deposit_event(Event::<T>::CollectionAdminRemoved(1722				collection.id,1723				user.clone(),1724			));1725		}17261727		<PalletEvm<T>>::deposit_log(1728			erc::CollectionHelpersEvents::CollectionChanged {1729				collection_id: eth::collection_id_to_address(collection.id),1730			}1731			.to_log(T::ContractAddress::get()),1732		);17331734		Ok(())1735	}17361737	/// Update collection limits.1738	pub fn update_limits(1739		user: &T::CrossAccountId,1740		collection: &mut CollectionHandle<T>,1741		new_limit: CollectionLimits,1742	) -> DispatchResult {1743		collection.check_is_internal()?;1744		collection.check_is_owner_or_admin(user)?;17451746		collection.limits =1747			Self::clamp_limits(collection.mode.clone(), &collection.limits, new_limit)?;17481749		Self::deposit_event(Event::<T>::CollectionLimitSet(collection.id));1750		<PalletEvm<T>>::deposit_log(1751			erc::CollectionHelpersEvents::CollectionChanged {1752				collection_id: eth::collection_id_to_address(collection.id),1753			}1754			.to_log(T::ContractAddress::get()),1755		);17561757		collection.save()1758	}17591760	/// Merge set fields from `new_limit` to `old_limit`.1761	fn clamp_limits(1762		mode: CollectionMode,1763		old_limit: &CollectionLimits,1764		mut new_limit: CollectionLimits,1765	) -> Result<CollectionLimits, DispatchError> {1766		let limits = old_limit;1767		limit_default!(old_limit, new_limit,1768			account_token_ownership_limit => ensure!(1769				new_limit <= MAX_TOKEN_OWNERSHIP,1770				<Error<T>>::CollectionLimitBoundsExceeded,1771			),1772			sponsored_data_size => ensure!(1773				new_limit <= CUSTOM_DATA_LIMIT,1774				<Error<T>>::CollectionLimitBoundsExceeded,1775			),17761777			sponsored_data_rate_limit => {},1778			token_limit => ensure!(1779				old_limit >= new_limit && new_limit > 0,1780				<Error<T>>::CollectionTokenLimitExceeded1781			),17821783			sponsor_transfer_timeout(match mode {1784				CollectionMode::NFT => NFT_SPONSOR_TRANSFER_TIMEOUT,1785				CollectionMode::Fungible(_) => FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,1786				CollectionMode::ReFungible => REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,1787			}) => ensure!(1788				new_limit <= MAX_SPONSOR_TIMEOUT,1789				<Error<T>>::CollectionLimitBoundsExceeded,1790			),1791			sponsor_approve_timeout => {},1792			owner_can_transfer => ensure!(1793				!limits.owner_can_transfer_instaled() ||1794				old_limit || !new_limit,1795				<Error<T>>::OwnerPermissionsCantBeReverted,1796			),1797			owner_can_destroy => ensure!(1798				old_limit || !new_limit,1799				<Error<T>>::OwnerPermissionsCantBeReverted,1800			),1801			transfers_enabled => {},1802		);1803		Ok(new_limit)1804	}18051806	/// Update collection permissions.1807	pub fn update_permissions(1808		user: &T::CrossAccountId,1809		collection: &mut CollectionHandle<T>,1810		new_permission: CollectionPermissions,1811	) -> DispatchResult {1812		collection.check_is_internal()?;1813		collection.check_is_owner_or_admin(user)?;1814		collection.permissions = Self::clamp_permissions(1815			collection.mode.clone(),1816			&collection.permissions,1817			new_permission,1818		)?;18191820		Self::deposit_event(Event::<T>::CollectionPermissionSet(collection.id));1821		<PalletEvm<T>>::deposit_log(1822			erc::CollectionHelpersEvents::CollectionChanged {1823				collection_id: eth::collection_id_to_address(collection.id),1824			}1825			.to_log(T::ContractAddress::get()),1826		);18271828		collection.save()1829	}18301831	/// Merge set fields from `new_permission` to `old_permission`.1832	fn clamp_permissions(1833		_mode: CollectionMode,1834		old_permission: &CollectionPermissions,1835		mut new_permission: CollectionPermissions,1836	) -> Result<CollectionPermissions, DispatchError> {1837		limit_default_clone!(old_permission, new_permission,1838			access => {},1839			mint_mode => {},1840			nesting => { /* todo check for permissive, if only it gets out of benchmarks */ },1841		);1842		Ok(new_permission)1843	}18441845	/// Repair possibly broken properties of a collection.1846	pub fn repair_collection(collection_id: CollectionId) -> DispatchResult {1847		CollectionProperties::<T>::mutate(collection_id, |properties| {1848			properties.recompute_consumed_space();1849		});18501851		Ok(())1852	}1853}18541855/// Indicates unsupported methods by returning [Error::UnsupportedOperation].1856#[macro_export]1857macro_rules! unsupported {1858	($runtime:path) => {1859		Err($crate::Error::<$runtime>::UnsupportedOperation.into())1860	};1861}18621863/// Return weights for various worst-case operations.1864pub trait CommonWeightInfo<CrossAccountId> {1865	/// Weight of item creation.1866	fn create_item(data: &CreateItemData) -> Weight {1867		Self::create_multiple_items(from_ref(data))1868	}18691870	/// Weight of items creation.1871	fn create_multiple_items(amount: &[CreateItemData]) -> Weight;18721873	/// Weight of items creation.1874	fn create_multiple_items_ex(cost: &CreateItemExData<CrossAccountId>) -> Weight;18751876	/// The weight of the burning item.1877	fn burn_item() -> Weight;18781879	/// Property setting weight.1880	///1881	/// * `amount`- The number of properties to set.1882	fn set_collection_properties(amount: u32) -> Weight;18831884	/// Collection property deletion weight.1885	///1886	/// * `amount`- The number of properties to set.1887	fn delete_collection_properties(amount: u32) -> Weight;18881889	/// Token property setting weight.1890	///1891	/// * `amount`- The number of properties to set.1892	fn set_token_properties(amount: u32) -> Weight;18931894	/// Token property deletion weight.1895	///1896	/// * `amount`- The number of properties to delete.1897	fn delete_token_properties(amount: u32) -> Weight;18981899	/// Token property permissions set weight.1900	///1901	/// * `amount`- The number of property permissions to set.1902	fn set_token_property_permissions(amount: u32) -> Weight;19031904	/// Transfer price of the token or its parts.1905	fn transfer() -> Weight;19061907	/// The price of setting the permission of the operation from another user.1908	fn approve() -> Weight;19091910	/// The price of setting the permission of the operation from another user for eth mirror.1911	fn approve_from() -> Weight;19121913	/// Transfer price from another user.1914	fn transfer_from() -> Weight;19151916	/// The price of burning a token from another user.1917	fn burn_from() -> Weight;19181919	/// Differs from burn_item in case of Fungible and Refungible, as it should burn1920	/// whole users's balance.1921	///1922	/// This method shouldn't be used directly, as it doesn't count breadth price, use [burn_recursively](CommonWeightInfo::burn_recursively) instead1923	fn burn_recursively_self_raw() -> Weight;19241925	/// Cost of iterating over `amount` children while burning, without counting child burning itself.1926	///1927	/// This method shouldn't be used directly, as it doesn't count depth price, use [burn_recursively](CommonWeightInfo::burn_recursively) instead1928	fn burn_recursively_breadth_raw(amount: u32) -> Weight;19291930	/// The price of recursive burning a token.1931	///1932	/// `max_selfs` - The maximum burning weight of the token itself.1933	/// `max_breadth` - The maximum number of nested tokens to burn.1934	fn burn_recursively(max_selfs: u32, max_breadth: u32) -> Weight {1935		Self::burn_recursively_self_raw()1936			.saturating_mul(max_selfs.max(1) as u64)1937			.saturating_add(Self::burn_recursively_breadth_raw(max_breadth))1938	}19391940	/// The price of retrieving token owner1941	fn token_owner() -> Weight;19421943	/// The price of setting approval for all1944	fn set_allowance_for_all() -> Weight;19451946	/// The price of repairing an item.1947	fn force_repair_item() -> Weight;1948}19491950/// Weight info extension trait for refungible pallet.1951pub trait RefungibleExtensionsWeightInfo {1952	/// Weight of token repartition.1953	fn repartition() -> Weight;1954}19551956/// Common collection operations.1957///1958/// It wraps methods in Fungible, Nonfungible and Refungible pallets1959/// and adds weight info.1960pub trait CommonCollectionOperations<T: Config> {1961	/// Create token.1962	///1963	/// * `sender` - The user who mint the token and pays for the transaction.1964	/// * `to` - The user who will own the token.1965	/// * `data` - Token data.1966	/// * `nesting_budget` - A budget that can be spent on nesting tokens.1967	fn create_item(1968		&self,1969		sender: T::CrossAccountId,1970		to: T::CrossAccountId,1971		data: CreateItemData,1972		nesting_budget: &dyn Budget,1973	) -> DispatchResultWithPostInfo;19741975	/// Create multiple tokens.1976	///1977	/// * `sender` - The user who mint the token and pays for the transaction.1978	/// * `to` - The user who will own the token.1979	/// * `data` - Token data.1980	/// * `nesting_budget` - A budget that can be spent on nesting tokens.1981	fn create_multiple_items(1982		&self,1983		sender: T::CrossAccountId,1984		to: T::CrossAccountId,1985		data: Vec<CreateItemData>,1986		nesting_budget: &dyn Budget,1987	) -> DispatchResultWithPostInfo;19881989	/// Create multiple tokens.1990	///1991	/// * `sender` - The user who mint the token and pays for the transaction.1992	/// * `to` - The user who will own the token.1993	/// * `data` - Token data.1994	/// * `nesting_budget` - A budget that can be spent on nesting tokens.1995	fn create_multiple_items_ex(1996		&self,1997		sender: T::CrossAccountId,1998		data: CreateItemExData<T::CrossAccountId>,1999		nesting_budget: &dyn Budget,2000	) -> DispatchResultWithPostInfo;20012002	/// Burn token.2003	///2004	/// * `sender` - The user who owns the token.2005	/// * `token` - Token id that will burned.2006	/// * `amount` - The number of parts of the token that will be burned.2007	fn burn_item(2008		&self,2009		sender: T::CrossAccountId,2010		token: TokenId,2011		amount: u128,2012	) -> DispatchResultWithPostInfo;20132014	/// Burn token and all nested tokens recursievly.2015	///2016	/// * `sender` - The user who owns the token.2017	/// * `token` - Token id that will burned.2018	/// * `self_budget` - The budget that can be spent on burning tokens.2019	/// * `breadth_budget` - The budget that can be spent on burning nested tokens.2020	fn burn_item_recursively(2021		&self,2022		sender: T::CrossAccountId,2023		token: TokenId,2024		self_budget: &dyn Budget,2025		breadth_budget: &dyn Budget,2026	) -> DispatchResultWithPostInfo;20272028	/// Set collection properties.2029	///2030	/// * `sender` - Must be either the owner of the collection or its admin.2031	/// * `properties` - Properties to be set.2032	fn set_collection_properties(2033		&self,2034		sender: T::CrossAccountId,2035		properties: Vec<Property>,2036	) -> DispatchResultWithPostInfo;20372038	/// Delete collection properties.2039	///2040	/// * `sender` - Must be either the owner of the collection or its admin.2041	/// * `properties` - The properties to be removed.2042	fn delete_collection_properties(2043		&self,2044		sender: &T::CrossAccountId,2045		property_keys: Vec<PropertyKey>,2046	) -> DispatchResultWithPostInfo;20472048	/// Set token properties.2049	///2050	/// The appropriate [`PropertyPermission`] for the token property2051	/// must be set with [`Self::set_token_property_permissions`].2052	///2053	/// * `sender` - Must be either the owner of the token or its admin.2054	/// * `token_id` - The token for which the properties are being set.2055	/// * `properties` - Properties to be set.2056	/// * `budget` - Budget for setting properties.2057	fn set_token_properties(2058		&self,2059		sender: T::CrossAccountId,2060		token_id: TokenId,2061		properties: Vec<Property>,2062		budget: &dyn Budget,2063	) -> DispatchResultWithPostInfo;20642065	/// Remove token properties.2066	///2067	/// The appropriate [`PropertyPermission`] for the token property2068	/// must be set with [`Self::set_token_property_permissions`].2069	///2070	/// * `sender` - Must be either the owner of the token or its admin.2071	/// * `token_id` - The token for which the properties are being remove.2072	/// * `property_keys` - Keys to remove corresponding properties.2073	/// * `budget` - Budget for removing properties.2074	fn delete_token_properties(2075		&self,2076		sender: T::CrossAccountId,2077		token_id: TokenId,2078		property_keys: Vec<PropertyKey>,2079		budget: &dyn Budget,2080	) -> DispatchResultWithPostInfo;20812082	/// Set token property permissions.2083	///2084	/// * `sender` - Must be either the owner of the token or its admin.2085	/// * `token_id` - The token for which the properties are being set.2086	/// * `property_permissions` - Property permissions to be set.2087	/// * `budget` - Budget for setting properties.2088	fn set_token_property_permissions(2089		&self,2090		sender: &T::CrossAccountId,2091		property_permissions: Vec<PropertyKeyPermission>,2092	) -> DispatchResultWithPostInfo;20932094	/// Transfer amount of token pieces.2095	///2096	/// * `sender` - Donor user.2097	/// * `to` - Recepient user.2098	/// * `token` - The token of which parts are being sent.2099	/// * `amount` - The number of parts of the token that will be transferred.2100	/// * `budget` - The maximum budget that can be spent on the transfer.2101	fn transfer(2102		&self,2103		sender: T::CrossAccountId,2104		to: T::CrossAccountId,2105		token: TokenId,2106		amount: u128,2107		budget: &dyn Budget,2108	) -> DispatchResultWithPostInfo;21092110	/// Grant access to another account to transfer parts of the token owned by the calling user via [Self::transfer_from].2111	///2112	/// * `sender` - The user who grants access to the token.2113	/// * `spender` - The user to whom the rights are granted.2114	/// * `token` - The token to which access is granted.2115	/// * `amount` - The amount of pieces that another user can dispose of.2116	fn approve(2117		&self,2118		sender: T::CrossAccountId,2119		spender: T::CrossAccountId,2120		token: TokenId,2121		amount: u128,2122	) -> DispatchResultWithPostInfo;21232124	/// Grant access to another account to transfer parts of the token owned by the calling user's eth mirror via [Self::transfer_from].2125	///2126	/// * `sender` - The user who grants access to the token.2127	/// * `from` - Spender's eth mirror.2128	/// * `to` - The user to whom the rights are granted.2129	/// * `token` - The token to which access is granted.2130	/// * `amount` - The amount of pieces that another user can dispose of.2131	fn approve_from(2132		&self,2133		sender: T::CrossAccountId,2134		from: T::CrossAccountId,2135		to: T::CrossAccountId,2136		token: TokenId,2137		amount: u128,2138	) -> DispatchResultWithPostInfo;21392140	/// Send parts of a token owned by another user.2141	///2142	/// Before calling this method, you must grant rights to the calling user via [`Self::approve`].2143	///2144	/// * `sender` - The user who must have access to the token (see [`Self::approve`]).2145	/// * `from` - The user who owns the token.2146	/// * `to` - Recepient user.2147	/// * `token` - The token of which parts are being sent.2148	/// * `amount` - The number of parts of the token that will be transferred.2149	/// * `budget` - The maximum budget that can be spent on the transfer.2150	fn transfer_from(2151		&self,2152		sender: T::CrossAccountId,2153		from: T::CrossAccountId,2154		to: T::CrossAccountId,2155		token: TokenId,2156		amount: u128,2157		budget: &dyn Budget,2158	) -> DispatchResultWithPostInfo;21592160	/// Burn parts of a token owned by another user.2161	///2162	/// Before calling this method, you must grant rights to the calling user via [`Self::approve`].2163	///2164	/// * `sender` - The user who must have access to the token (see [`Self::approve`]).2165	/// * `from` - The user who owns the token.2166	/// * `token` - The token of which parts are being sent.2167	/// * `amount` - The number of parts of the token that will be transferred.2168	/// * `budget` - The maximum budget that can be spent on the burn.2169	fn burn_from(2170		&self,2171		sender: T::CrossAccountId,2172		from: T::CrossAccountId,2173		token: TokenId,2174		amount: u128,2175		budget: &dyn Budget,2176	) -> DispatchResultWithPostInfo;21772178	/// Check permission to nest token.2179	///2180	/// * `sender` - The user who initiated the check.2181	/// * `from` - The token that is checked for embedding.2182	/// * `under` - Token under which to check.2183	/// * `budget` - The maximum budget that can be spent on the check.2184	fn check_nesting(2185		&self,2186		sender: T::CrossAccountId,2187		from: (CollectionId, TokenId),2188		under: TokenId,2189		budget: &dyn Budget,2190	) -> DispatchResult;21912192	/// Nest one token into another.2193	///2194	/// * `under` - Token holder.2195	/// * `to_nest` - Nested token.2196	fn nest(&self, under: TokenId, to_nest: (CollectionId, TokenId));21972198	/// Unnest token.2199	///2200	/// * `under` - Token holder.2201	/// * `to_nest` - Token to unnest.2202	fn unnest(&self, under: TokenId, to_nest: (CollectionId, TokenId));22032204	/// Get all user tokens.2205	///2206	/// * `account` - Account for which you need to get tokens.2207	fn account_tokens(&self, account: T::CrossAccountId) -> Vec<TokenId>;22082209	/// Get all the tokens in the collection.2210	fn collection_tokens(&self) -> Vec<TokenId>;22112212	/// Check if the token exists.2213	///2214	/// * `token` - Id token to check.2215	fn token_exists(&self, token: TokenId) -> bool;22162217	/// Get the id of the last minted token.2218	fn last_token_id(&self) -> TokenId;22192220	/// Get the owner of the token.2221	///2222	/// * `token` - The token for which you need to find out the owner.2223	fn token_owner(&self, token: TokenId) -> Result<T::CrossAccountId, TokenOwnerError>;22242225	/// Returns 10 tokens owners in no particular order.2226	///2227	/// * `token` - The token for which you need to find out the owners.2228	fn token_owners(&self, token: TokenId) -> Vec<T::CrossAccountId>;22292230	/// Get the value of the token property by key.2231	///2232	/// * `token` - Token with the property to get.2233	/// * `key` - Property name.2234	fn token_property(&self, token_id: TokenId, key: &PropertyKey) -> Option<PropertyValue>;22352236	/// Get a set of token properties by key vector.2237	///2238	/// * `token` - Token with the property to get.2239	/// * `keys` - Vector of property keys. If this parameter is [None](sp_std::result::Result),2240	/// then all properties are returned.2241	fn token_properties(&self, token: TokenId, keys: Option<Vec<PropertyKey>>) -> Vec<Property>;22422243	/// Amount of unique collection tokens2244	fn total_supply(&self) -> u32;22452246	/// Amount of different tokens account has.2247	///2248	/// * `account` - The account for which need to get the balance.2249	fn account_balance(&self, account: T::CrossAccountId) -> u32;22502251	/// Amount of specific token account have.2252	fn balance(&self, account: T::CrossAccountId, token: TokenId) -> u128;22532254	/// Amount of token pieces2255	fn total_pieces(&self, token: TokenId) -> Option<u128>;22562257	/// Get the number of parts of the token that a trusted user can manage.2258	///2259	/// * `sender` - Trusted user.2260	/// * `spender` - Owner of the token.2261	/// * `token` - The token for which to get the value.2262	fn allowance(2263		&self,2264		sender: T::CrossAccountId,2265		spender: T::CrossAccountId,2266		token: TokenId,2267	) -> u128;22682269	/// Get extension for RFT collection.2270	fn refungible_extensions(&self) -> Option<&dyn RefungibleExtensions<T>>;22712272	/// The `operator` is allowed to transfer all tokens of the `owner` on their behalf.2273	/// * `owner` - Token owner2274	/// * `operator` - Operator2275	/// * `approve` - Should operator status be granted or revoked?2276	fn set_allowance_for_all(2277		&self,2278		owner: T::CrossAccountId,2279		operator: T::CrossAccountId,2280		approve: bool,2281	) -> DispatchResultWithPostInfo;22822283	/// Tells whether the given `owner` approves the `operator`.2284	fn allowance_for_all(&self, owner: T::CrossAccountId, operator: T::CrossAccountId) -> bool;22852286	/// Repairs a possibly broken item.2287	fn repair_item(&self, token: TokenId) -> DispatchResultWithPostInfo;2288}22892290/// Extension for RFT collection.2291pub trait RefungibleExtensions<T>2292where2293	T: Config,2294{2295	/// Change the number of parts of the token.2296	///2297	/// When the value changes down, this function is equivalent to burning parts of the token.2298	///2299	/// * `sender` - The user calling the repartition operation. Must be the owner of the token.2300	/// * `token` - The token for which you want to change the number of parts.2301	/// * `amount` - The new value of the parts of the token.2302	fn repartition(2303		&self,2304		sender: &T::CrossAccountId,2305		token: TokenId,2306		amount: u128,2307	) -> DispatchResultWithPostInfo;2308}23092310/// Merge [`DispatchResult`] with [`Weight`] into [`DispatchResultWithPostInfo`].2311///2312/// Used for [`CommonCollectionOperations`] implementations and flexible enough to do so.2313pub fn with_weight(res: DispatchResult, weight: Weight) -> DispatchResultWithPostInfo {2314	let post_info = PostDispatchInfo {2315		actual_weight: Some(weight),2316		pays_fee: Pays::Yes,2317	};2318	match res {2319		Ok(()) => Ok(post_info),2320		Err(error) => Err(DispatchErrorWithPostInfo { post_info, error }),2321	}2322}23232324impl<T: Config> From<PropertiesError> for Error<T> {2325	fn from(error: PropertiesError) -> Self {2326		match error {2327			PropertiesError::NoSpaceForProperty => Self::NoSpaceForProperty,2328			PropertiesError::PropertyLimitReached => Self::PropertyLimitReached,2329			PropertiesError::InvalidCharacterInPropertyKey => Self::InvalidCharacterInPropertyKey,2330			PropertiesError::PropertyKeyIsTooLong => Self::PropertyKeyIsTooLong,2331			PropertiesError::EmptyPropertyKey => Self::EmptyPropertyKey,2332		}2333	}2334}
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, CollectionProperties as CollectionPropertiesT, TokenProperties,80	PropertiesPermissionMap, PropertyKey, PropertyValue, PropertyPermission, PropertiesError,81	TokenOwnerError, PropertyKeyPermission, TokenData, TrySetProperty, PropertyScope,82	CollectionPermissions,83};84use up_pov_estimate_rpc::PovInfo;8586pub use pallet::*;87use sp_core::H160;88use sp_runtime::{ArithmeticError, DispatchError, DispatchResult};8990#[cfg(feature = "runtime-benchmarks")]91pub mod benchmarking;92pub mod dispatch;93pub mod erc;94pub mod eth;95#[allow(missing_docs)]96pub mod weights;9798/// Weight info.99pub type SelfWeightOf<T> = <T as Config>::WeightInfo;100101/// Collection handle contains information about collection data and id.102/// Also provides functionality to count consumed gas.103///104/// CollectionHandle is used as a generic wrapper for collections of all types.105/// It allows to perform common operations and queries on any collection type,106/// both completely general for all, as well as their respective implementations of [`CommonCollectionOperations`].107#[must_use = "Should call submit_logs or save, otherwise some data will be lost for evm side"]108pub struct CollectionHandle<T: Config> {109	/// Collection id110	pub id: CollectionId,111	collection: Collection<T::AccountId>,112	/// Substrate recorder for counting consumed gas113	pub recorder: SubstrateRecorder<T>,114}115116impl<T: Config> WithRecorder<T> for CollectionHandle<T> {117	fn recorder(&self) -> &SubstrateRecorder<T> {118		&self.recorder119	}120	fn into_recorder(self) -> SubstrateRecorder<T> {121		self.recorder122	}123}124125impl<T: Config> CollectionHandle<T> {126	/// Same as [CollectionHandle::new] but with an explicit gas limit.127	pub fn new_with_gas_limit(id: CollectionId, gas_limit: u64) -> Option<Self> {128		<CollectionById<T>>::get(id).map(|collection| Self {129			id,130			collection,131			recorder: SubstrateRecorder::new(gas_limit),132		})133	}134135	/// Same as [CollectionHandle::new] but with an existed [`SubstrateRecorder`].136	pub fn new_with_recorder(id: CollectionId, recorder: SubstrateRecorder<T>) -> Option<Self> {137		<CollectionById<T>>::get(id).map(|collection| Self {138			id,139			collection,140			recorder,141		})142	}143144	/// Retrives collection data from storage and creates collection handle with default parameters.145	/// If collection not found return `None`146	pub fn new(id: CollectionId) -> Option<Self> {147		Self::new_with_gas_limit(id, u64::MAX)148	}149150	/// Same as [`CollectionHandle::new`] but if collection not found [CollectionNotFound](Error::CollectionNotFound) returned.151	pub fn try_get(id: CollectionId) -> Result<Self, DispatchError> {152		Ok(Self::new(id).ok_or(<Error<T>>::CollectionNotFound)?)153	}154155	/// Consume gas for reading.156	pub fn consume_store_reads(157		&self,158		reads: u64,159	) -> pallet_evm_coder_substrate::execution::Result<()> {160		self.recorder161			.consume_gas(T::GasWeightMapping::weight_to_gas(Weight::from_parts(162				<T as frame_system::Config>::DbWeight::get()163					.read164					.saturating_mul(reads),165				// TODO: measure proof166				0,167			)))168	}169170	/// Consume gas for writing.171	pub fn consume_store_writes(172		&self,173		writes: u64,174	) -> pallet_evm_coder_substrate::execution::Result<()> {175		self.recorder176			.consume_gas(T::GasWeightMapping::weight_to_gas(Weight::from_parts(177				<T as frame_system::Config>::DbWeight::get()178					.write179					.saturating_mul(writes),180				// TODO: measure proof181				0,182			)))183	}184185	/// Consume gas for reading and writing.186	pub fn consume_store_reads_and_writes(187		&self,188		reads: u64,189		writes: u64,190	) -> pallet_evm_coder_substrate::execution::Result<()> {191		let weight = <T as frame_system::Config>::DbWeight::get();192		let reads = weight.read.saturating_mul(reads);193		let writes = weight.read.saturating_mul(writes);194		self.recorder195			.consume_gas(T::GasWeightMapping::weight_to_gas(Weight::from_parts(196				reads.saturating_add(writes),197				// TODO: measure proof198				0,199			)))200	}201202	/// Save collection to storage.203	pub fn save(&self) -> DispatchResult {204		<CollectionById<T>>::insert(self.id, &self.collection);205		Ok(())206	}207208	/// Set collection sponsor.209	///210	/// Unique collections allows sponsoring for certain actions.211	/// This method allows you to set the sponsor of the collection.212	/// In order for sponsorship to become active, it must be confirmed through [`Self::confirm_sponsorship`].213	pub fn set_sponsor(214		&mut self,215		sender: &T::CrossAccountId,216		sponsor: T::AccountId,217	) -> DispatchResult {218		self.check_is_internal()?;219		self.check_is_owner_or_admin(sender)?;220221		self.collection.sponsorship = SponsorshipState::Unconfirmed(sponsor.clone());222223		<Pallet<T>>::deposit_event(Event::<T>::CollectionSponsorSet(self.id, sponsor));224		<PalletEvm<T>>::deposit_log(225			erc::CollectionHelpersEvents::CollectionChanged {226				collection_id: eth::collection_id_to_address(self.id),227			}228			.to_log(T::ContractAddress::get()),229		);230231		self.save()232	}233234	/// Force set `sponsor`.235	///236	/// Differs from [`set_sponsor`][`Self::set_sponsor`] in that confirmation237	/// from the `sponsor` is not required.238	///239	/// # Arguments240	///241	/// * `sender`: Caller's account.242	/// * `sponsor`: ID of the account of the sponsor-to-be.243	pub fn force_set_sponsor(&mut self, sponsor: T::AccountId) -> DispatchResult {244		self.check_is_internal()?;245246		self.collection.sponsorship = SponsorshipState::Confirmed(sponsor.clone());247248		<Pallet<T>>::deposit_event(Event::<T>::CollectionSponsorSet(self.id, sponsor.clone()));249		<Pallet<T>>::deposit_event(Event::<T>::SponsorshipConfirmed(self.id, sponsor));250		<PalletEvm<T>>::deposit_log(251			erc::CollectionHelpersEvents::CollectionChanged {252				collection_id: eth::collection_id_to_address(self.id),253			}254			.to_log(T::ContractAddress::get()),255		);256257		self.save()258	}259260	/// Confirm sponsorship261	///262	/// In order for the sponsorship to become active, the user set as the sponsor must confirm their participation.263	/// Before confirming sponsorship, the user must be specified as the sponsor of the collection via [`Self::set_sponsor`].264	pub fn confirm_sponsorship(&mut self, sender: &T::AccountId) -> DispatchResult {265		self.check_is_internal()?;266		ensure!(267			self.collection.sponsorship.pending_sponsor() == Some(sender),268			Error::<T>::ConfirmSponsorshipFail269		);270271		self.collection.sponsorship = SponsorshipState::Confirmed(sender.clone());272273		<Pallet<T>>::deposit_event(Event::<T>::SponsorshipConfirmed(self.id, sender.clone()));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	/// Remove collection sponsor.285	pub fn remove_sponsor(&mut self, sender: &T::CrossAccountId) -> DispatchResult {286		self.check_is_internal()?;287		self.check_is_owner_or_admin(sender)?;288289		self.collection.sponsorship = SponsorshipState::Disabled;290291		<Pallet<T>>::deposit_event(Event::<T>::CollectionSponsorRemoved(self.id));292		<PalletEvm<T>>::deposit_log(293			erc::CollectionHelpersEvents::CollectionChanged {294				collection_id: eth::collection_id_to_address(self.id),295			}296			.to_log(T::ContractAddress::get()),297		);298		self.save()299	}300301	/// Force remove `sponsor`.302	///303	/// Differs from `remove_sponsor` in that304	/// it doesn't require consent from the `owner` of the collection.305	pub fn force_remove_sponsor(&mut self) -> DispatchResult {306		self.check_is_internal()?;307308		self.collection.sponsorship = SponsorshipState::Disabled;309310		<Pallet<T>>::deposit_event(Event::<T>::CollectionSponsorRemoved(self.id));311		<PalletEvm<T>>::deposit_log(312			erc::CollectionHelpersEvents::CollectionChanged {313				collection_id: eth::collection_id_to_address(self.id),314			}315			.to_log(T::ContractAddress::get()),316		);317		self.save()318	}319320	/// Checks that the collection was created with, and must be operated upon through **Unique API**.321	/// Now check only the `external` flag and if it's **true**, then return [`Error::CollectionIsExternal`] error.322	pub fn check_is_internal(&self) -> DispatchResult {323		if self.flags.external {324			return Err(<Error<T>>::CollectionIsExternal)?;325		}326327		Ok(())328	}329330	/// Checks that the collection was created with, and must be operated upon through an **assimilated API**.331	/// Now check only the `external` flag and if it's **false**, then return [`Error::CollectionIsInternal`] error.332	pub fn check_is_external(&self) -> DispatchResult {333		if !self.flags.external {334			return Err(<Error<T>>::CollectionIsInternal)?;335		}336337		Ok(())338	}339}340341impl<T: Config> Deref for CollectionHandle<T> {342	type Target = Collection<T::AccountId>;343344	fn deref(&self) -> &Self::Target {345		&self.collection346	}347}348349impl<T: Config> DerefMut for CollectionHandle<T> {350	fn deref_mut(&mut self) -> &mut Self::Target {351		&mut self.collection352	}353}354355impl<T: Config> CollectionHandle<T> {356	/// Checks if the `user` is the owner of the collection.357	pub fn check_is_owner(&self, user: &T::CrossAccountId) -> DispatchResult {358		ensure!(*user.as_sub() == self.owner, <Error<T>>::NoPermission);359		Ok(())360	}361362	/// Returns **true** if the `user` is the owner or administrator of the collection.363	pub fn is_owner_or_admin(&self, user: &T::CrossAccountId) -> bool {364		*user.as_sub() == self.owner || <IsAdmin<T>>::get((self.id, user))365	}366367	/// Checks if the `user` is the owner or administrator of the collection.368	pub fn check_is_owner_or_admin(&self, user: &T::CrossAccountId) -> DispatchResult {369		ensure!(self.is_owner_or_admin(user), <Error<T>>::NoPermission);370		Ok(())371	}372373	/// Returns **true** if374	/// * the `user`is a collection owner or admin375	/// * the collection limits allow the owner/admins to transfer/burn any collection token376	pub fn ignores_token_restrictions(&self, user: &T::CrossAccountId) -> bool {377		self.limits.owner_can_transfer() && self.is_owner_or_admin(user)378	}379380	/// Return **true** if `user` does not have enough token parts, and he can ignore such restrictions.381	pub fn ignores_owned_amount(&self, user: &T::CrossAccountId) -> bool {382		self.limits.owner_can_transfer() && self.is_owner_or_admin(user)383	}384385	/// Checks if the user is in the allow list. If not [Error::AddressNotInAllowlist] returns.386	pub fn check_allowlist(&self, user: &T::CrossAccountId) -> DispatchResult {387		ensure!(388			<Allowlist<T>>::get((self.id, user)),389			<Error<T>>::AddressNotInAllowlist390		);391		Ok(())392	}393394	/// Changes collection owner to another account395	/// #### Store read/writes396	/// 1 writes397	pub fn change_owner(398		&mut self,399		caller: T::CrossAccountId,400		new_owner: T::CrossAccountId,401	) -> DispatchResult {402		self.check_is_internal()?;403		self.check_is_owner(&caller)?;404		self.collection.owner = new_owner.as_sub().clone();405406		<Pallet<T>>::deposit_event(Event::<T>::CollectionOwnerChanged(407			self.id,408			new_owner.as_sub().clone(),409		));410		<PalletEvm<T>>::deposit_log(411			erc::CollectionHelpersEvents::CollectionChanged {412				collection_id: eth::collection_id_to_address(self.id),413			}414			.to_log(T::ContractAddress::get()),415		);416417		self.save()418	}419}420421#[frame_support::pallet]422pub mod pallet {423	use super::*;424	use dispatch::CollectionDispatch;425	use frame_support::{Blake2_128Concat, pallet_prelude::*, storage::Key, traits::StorageVersion};426	use frame_system::pallet_prelude::*;427	use frame_support::traits::Currency;428	use up_data_structs::{TokenId, mapping::TokenAddressMapping};429	use scale_info::TypeInfo;430	use weights::WeightInfo;431432	#[pallet::config]433	pub trait Config:434		frame_system::Config + pallet_evm_coder_substrate::Config + pallet_evm::Config + TypeInfo435	{436		/// Weight information for functions of this pallet.437		type WeightInfo: WeightInfo;438439		/// Events compatible with [`frame_system::Config::Event`].440		type RuntimeEvent: IsType<<Self as frame_system::Config>::RuntimeEvent> + From<Event<Self>>;441442		/// Handler of accounts and payment.443		type Currency: Currency<Self::AccountId>;444445		/// Set price to create a collection.446		#[pallet::constant]447		type CollectionCreationPrice: Get<448			<<Self as Config>::Currency as Currency<Self::AccountId>>::Balance,449		>;450451		/// Dispatcher of operations on collections.452		type CollectionDispatch: CollectionDispatch<Self>;453454		/// Account which holds the chain's treasury.455		type TreasuryAccountId: Get<Self::AccountId>;456457		/// Address under which the CollectionHelper contract would be available.458		#[pallet::constant]459		type ContractAddress: Get<H160>;460461		/// Mapper for token addresses to Ethereum addresses.462		type EvmTokenAddressMapping: TokenAddressMapping<H160>;463464		/// Mapper for token addresses to [`CrossAccountId`].465		type CrossTokenAddressMapping: TokenAddressMapping<Self::CrossAccountId>;466	}467468	const STORAGE_VERSION: StorageVersion = StorageVersion::new(1);469470	#[pallet::pallet]471	#[pallet::storage_version(STORAGE_VERSION)]472	pub struct Pallet<T>(_);473474	#[pallet::extra_constants]475	impl<T: Config> Pallet<T> {476		/// Maximum admins per collection.477		pub fn collection_admins_limit() -> u32 {478			COLLECTION_ADMINS_LIMIT479		}480	}481482	impl<T: Config> Pallet<T> {483		/// Helper function that handles deposit events484		pub fn deposit_event(event: Event<T>) {485			let event = <T as Config>::RuntimeEvent::from(event);486			let event = event.into();487			<frame_system::Pallet<T>>::deposit_event(event)488		}489	}490491	#[pallet::event]492	pub enum Event<T: Config> {493		/// New collection was created494		CollectionCreated(495			/// Globally unique identifier of newly created collection.496			CollectionId,497			/// [`CollectionMode`] converted into _u8_.498			u8,499			/// Collection owner.500			T::AccountId,501		),502503		/// New collection was destroyed504		CollectionDestroyed(505			/// Globally unique identifier of collection.506			CollectionId,507		),508509		/// New item was created.510		ItemCreated(511			/// Id of the collection where item was created.512			CollectionId,513			/// Id of an item. Unique within the collection.514			TokenId,515			/// Owner of newly created item516			T::CrossAccountId,517			/// Always 1 for NFT518			u128,519		),520521		/// Collection item was burned.522		ItemDestroyed(523			/// Id of the collection where item was destroyed.524			CollectionId,525			/// Identifier of burned NFT.526			TokenId,527			/// Which user has destroyed its tokens.528			T::CrossAccountId,529			/// Amount of token pieces destroed. Always 1 for NFT.530			u128,531		),532533		/// Item was transferred534		Transfer(535			/// Id of collection to which item is belong.536			CollectionId,537			/// Id of an item.538			TokenId,539			/// Original owner of item.540			T::CrossAccountId,541			/// New owner of item.542			T::CrossAccountId,543			/// Amount of token pieces transfered. Always 1 for NFT.544			u128,545		),546547		/// Amount pieces of token owned by `sender` was approved for `spender`.548		Approved(549			/// Id of collection to which item is belong.550			CollectionId,551			/// Id of an item.552			TokenId,553			/// Original owner of item.554			T::CrossAccountId,555			/// Id for which the approval was granted.556			T::CrossAccountId,557			/// Amount of token pieces transfered. Always 1 for NFT.558			u128,559		),560561		/// A `sender` approves operations on all owned tokens for `spender`.562		ApprovedForAll(563			/// Id of collection to which item is belong.564			CollectionId,565			/// Owner of a wallet.566			T::CrossAccountId,567			/// Id for which operator status was granted or rewoked.568			T::CrossAccountId,569			/// Is operator status granted or revoked?570			bool,571		),572573		/// The colletion property has been added or edited.574		CollectionPropertySet(575			/// Id of collection to which property has been set.576			CollectionId,577			/// The property that was set.578			PropertyKey,579		),580581		/// The property has been deleted.582		CollectionPropertyDeleted(583			/// Id of collection to which property has been deleted.584			CollectionId,585			/// The property that was deleted.586			PropertyKey,587		),588589		/// The token property has been added or edited.590		TokenPropertySet(591			/// Identifier of the collection whose token has the property set.592			CollectionId,593			/// The token for which the property was set.594			TokenId,595			/// The property that was set.596			PropertyKey,597		),598599		/// The token property has been deleted.600		TokenPropertyDeleted(601			/// Identifier of the collection whose token has the property deleted.602			CollectionId,603			/// The token for which the property was deleted.604			TokenId,605			/// The property that was deleted.606			PropertyKey,607		),608609		/// The token property permission of a collection has been set.610		PropertyPermissionSet(611			/// ID of collection to which property permission has been set.612			CollectionId,613			/// The property permission that was set.614			PropertyKey,615		),616617		/// Address was added to the allow list.618		AllowListAddressAdded(619			/// ID of the affected collection.620			CollectionId,621			/// Address of the added account.622			T::CrossAccountId,623		),624625		/// Address was removed from the allow list.626		AllowListAddressRemoved(627			/// ID of the affected collection.628			CollectionId,629			/// Address of the removed account.630			T::CrossAccountId,631		),632633		/// Collection admin was added.634		CollectionAdminAdded(635			/// ID of the affected collection.636			CollectionId,637			/// Admin address.638			T::CrossAccountId,639		),640641		/// Collection admin was removed.642		CollectionAdminRemoved(643			/// ID of the affected collection.644			CollectionId,645			/// Removed admin address.646			T::CrossAccountId,647		),648649		/// Collection limits were set.650		CollectionLimitSet(651			/// ID of the affected collection.652			CollectionId,653		),654655		/// Collection owned was changed.656		CollectionOwnerChanged(657			/// ID of the affected collection.658			CollectionId,659			/// New owner address.660			T::AccountId,661		),662663		/// Collection permissions were set.664		CollectionPermissionSet(665			/// ID of the affected collection.666			CollectionId,667		),668669		/// Collection sponsor was set.670		CollectionSponsorSet(671			/// ID of the affected collection.672			CollectionId,673			/// New sponsor address.674			T::AccountId,675		),676677		/// New sponsor was confirm.678		SponsorshipConfirmed(679			/// ID of the affected collection.680			CollectionId,681			/// New sponsor address.682			T::AccountId,683		),684685		/// Collection sponsor was removed.686		CollectionSponsorRemoved(687			/// ID of the affected collection.688			CollectionId,689		),690	}691692	#[pallet::error]693	pub enum Error<T> {694		/// This collection does not exist.695		CollectionNotFound,696		/// Sender parameter and item owner must be equal.697		MustBeTokenOwner,698		/// No permission to perform action699		NoPermission,700		/// Destroying only empty collections is allowed701		CantDestroyNotEmptyCollection,702		/// Collection is not in mint mode.703		PublicMintingNotAllowed,704		/// Address is not in allow list.705		AddressNotInAllowlist,706707		/// Collection name can not be longer than 63 char.708		CollectionNameLimitExceeded,709		/// Collection description can not be longer than 255 char.710		CollectionDescriptionLimitExceeded,711		/// Token prefix can not be longer than 15 char.712		CollectionTokenPrefixLimitExceeded,713		/// Total collections bound exceeded.714		TotalCollectionsLimitExceeded,715		/// Exceeded max admin count716		CollectionAdminCountExceeded,717		/// Collection limit bounds per collection exceeded718		CollectionLimitBoundsExceeded,719		/// Tried to enable permissions which are only permitted to be disabled720		OwnerPermissionsCantBeReverted,721		/// Collection settings not allowing items transferring722		TransferNotAllowed,723		/// Account token limit exceeded per collection724		AccountTokenLimitExceeded,725		/// Collection token limit exceeded726		CollectionTokenLimitExceeded,727		/// Metadata flag frozen728		MetadataFlagFrozen,729730		/// Item does not exist731		TokenNotFound,732		/// Item is balance not enough733		TokenValueTooLow,734		/// Requested value is more than the approved735		ApprovedValueTooLow,736		/// Tried to approve more than owned737		CantApproveMoreThanOwned,738		/// Only spending from eth mirror could be approved739		AddressIsNotEthMirror,740741		/// Can't transfer tokens to ethereum zero address742		AddressIsZero,743744		/// The operation is not supported745		UnsupportedOperation,746747		/// Insufficient funds to perform an action748		NotSufficientFounds,749750		/// User does not satisfy the nesting rule751		UserIsNotAllowedToNest,752		/// Only tokens from specific collections may nest tokens under this one753		SourceCollectionIsNotAllowedToNest,754755		/// Tried to store more data than allowed in collection field756		CollectionFieldSizeExceeded,757758		/// Tried to store more property data than allowed759		NoSpaceForProperty,760761		/// Tried to store more property keys than allowed762		PropertyLimitReached,763764		/// Property key is too long765		PropertyKeyIsTooLong,766767		/// Only ASCII letters, digits, and symbols `_`, `-`, and `.` are allowed768		InvalidCharacterInPropertyKey,769770		/// Empty property keys are forbidden771		EmptyPropertyKey,772773		/// Tried to access an external collection with an internal API774		CollectionIsExternal,775776		/// Tried to access an internal collection with an external API777		CollectionIsInternal,778779		/// This address is not set as sponsor, use setCollectionSponsor first.780		ConfirmSponsorshipFail,781782		/// The user is not an administrator.783		UserIsNotCollectionAdmin,784	}785786	/// Storage of the count of created collections. Essentially contains the last collection ID.787	#[pallet::storage]788	pub type CreatedCollectionCount<T> = StorageValue<Value = CollectionId, QueryKind = ValueQuery>;789790	/// Storage of the count of deleted collections.791	#[pallet::storage]792	pub type DestroyedCollectionCount<T> =793		StorageValue<Value = CollectionId, QueryKind = ValueQuery>;794795	/// Storage of collection info.796	#[pallet::storage]797	pub type CollectionById<T> = StorageMap<798		Hasher = Blake2_128Concat,799		Key = CollectionId,800		Value = Collection<<T as frame_system::Config>::AccountId>,801		QueryKind = OptionQuery,802	>;803804	/// Storage of collection properties.805	#[pallet::storage]806	#[pallet::getter(fn collection_properties)]807	pub type CollectionProperties<T> = StorageMap<808		Hasher = Blake2_128Concat,809		Key = CollectionId,810		Value = CollectionPropertiesT,811		QueryKind = ValueQuery,812	>;813814	/// Storage of token property permissions of a collection.815	#[pallet::storage]816	#[pallet::getter(fn property_permissions)]817	pub type CollectionPropertyPermissions<T> = StorageMap<818		Hasher = Blake2_128Concat,819		Key = CollectionId,820		Value = PropertiesPermissionMap,821		QueryKind = ValueQuery,822	>;823824	/// Storage of the amount of collection admins.825	#[pallet::storage]826	pub type AdminAmount<T> = StorageMap<827		Hasher = Blake2_128Concat,828		Key = CollectionId,829		Value = u32,830		QueryKind = ValueQuery,831	>;832833	/// List of collection admins.834	#[pallet::storage]835	pub type IsAdmin<T: Config> = StorageNMap<836		Key = (837			Key<Blake2_128Concat, CollectionId>,838			Key<Blake2_128Concat, T::CrossAccountId>,839		),840		Value = bool,841		QueryKind = ValueQuery,842	>;843844	/// Allowlisted collection users.845	#[pallet::storage]846	pub type Allowlist<T: Config> = StorageNMap<847		Key = (848			Key<Blake2_128Concat, CollectionId>,849			Key<Blake2_128Concat, T::CrossAccountId>,850		),851		Value = bool,852		QueryKind = ValueQuery,853	>;854855	/// Not used by code, exists only to provide some types to metadata.856	#[pallet::storage]857	pub type DummyStorageValue<T: Config> = StorageValue<858		Value = (859			CollectionStats,860			CollectionId,861			TokenId,862			TokenChild,863			PhantomType<(864				TokenData<T::CrossAccountId>,865				RpcCollection<T::AccountId>,866				// PoV Estimate Info867				PovInfo,868			)>,869		),870		QueryKind = OptionQuery,871	>;872873	#[pallet::hooks]874	impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {875		fn on_runtime_upgrade() -> Weight {876			StorageVersion::new(1).put::<Pallet<T>>();877878			Weight::zero()879		}880	}881}882883impl<T: Config> Pallet<T> {884	/// Enshure that receiver address is correct.885	///886	/// Ethereum receiver 0x0000000000000000000000000000000000000000 is reserved, and shouldn't own tokens.887	pub fn ensure_correct_receiver(receiver: &T::CrossAccountId) -> DispatchResult {888		ensure!(889			&T::CrossAccountId::from_eth(H160([0; 20])) != receiver,890			<Error<T>>::AddressIsZero891		);892		Ok(())893	}894895	/// Get a vector of collection admins.896	pub fn adminlist(collection: CollectionId) -> Vec<T::CrossAccountId> {897		<IsAdmin<T>>::iter_prefix((collection,))898			.map(|(a, _)| a)899			.collect()900	}901902	/// Get a vector of users allowed to mint tokens.903	pub fn allowlist(collection: CollectionId) -> Vec<T::CrossAccountId> {904		<Allowlist<T>>::iter_prefix((collection,))905			.map(|(a, _)| a)906			.collect()907	}908909	/// Is `user` allowed to mint token in `collection`.910	pub fn allowed(collection: CollectionId, user: T::CrossAccountId) -> bool {911		<Allowlist<T>>::get((collection, user))912	}913914	/// Get statistics of collections.915	pub fn collection_stats() -> CollectionStats {916		let created = <CreatedCollectionCount<T>>::get();917		let destroyed = <DestroyedCollectionCount<T>>::get();918		CollectionStats {919			created: created.0,920			destroyed: destroyed.0,921			alive: created.0 - destroyed.0,922		}923	}924925	/// Get the effective limits for the collection.926	pub fn effective_collection_limits(collection: CollectionId) -> Option<CollectionLimits> {927		let collection = <CollectionById<T>>::get(collection)?;928		let limits = collection.limits;929		let effective_limits = CollectionLimits {930			account_token_ownership_limit: Some(limits.account_token_ownership_limit()),931			sponsored_data_size: Some(limits.sponsored_data_size()),932			sponsored_data_rate_limit: Some(933				limits934					.sponsored_data_rate_limit935					.unwrap_or(SponsoringRateLimit::SponsoringDisabled),936			),937			token_limit: Some(limits.token_limit()),938			sponsor_transfer_timeout: Some(limits.sponsor_transfer_timeout(939				match collection.mode {940					CollectionMode::NFT => NFT_SPONSOR_TRANSFER_TIMEOUT,941					CollectionMode::Fungible(_) => FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,942					CollectionMode::ReFungible => REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,943				},944			)),945			sponsor_approve_timeout: Some(limits.sponsor_approve_timeout()),946			owner_can_transfer: Some(limits.owner_can_transfer()),947			owner_can_destroy: Some(limits.owner_can_destroy()),948			transfers_enabled: Some(limits.transfers_enabled()),949		};950951		Some(effective_limits)952	}953954	/// Returns information about the `collection` adapted for rpc.955	pub fn rpc_collection(collection: CollectionId) -> Option<RpcCollection<T::AccountId>> {956		let Collection {957			name,958			description,959			owner,960			mode,961			token_prefix,962			sponsorship,963			limits,964			permissions,965			flags,966		} = <CollectionById<T>>::get(collection)?;967968		let token_property_permissions = <CollectionPropertyPermissions<T>>::get(collection)969			.into_iter()970			.map(|(key, permission)| PropertyKeyPermission { key, permission })971			.collect();972973		let properties = <CollectionProperties<T>>::get(collection)974			.into_iter()975			.map(|(key, value)| Property { key, value })976			.collect();977978		let permissions = CollectionPermissions {979			access: Some(permissions.access()),980			mint_mode: Some(permissions.mint_mode()),981			nesting: Some(permissions.nesting().clone()),982		};983984		Some(RpcCollection {985			name: name.into_inner(),986			description: description.into_inner(),987			owner,988			mode,989			token_prefix: token_prefix.into_inner(),990			sponsorship,991			limits,992			permissions,993			token_property_permissions,994			properties,995			read_only: flags.external,996997			flags: RpcCollectionFlags {998				foreign: flags.foreign,999				erc721metadata: flags.erc721metadata,1000			},1001		})1002	}1003}10041005macro_rules! limit_default {1006	($old:ident, $new:ident, $($field:ident $(($arg:expr))? => $check:expr),* $(,)?) => {{1007		$(1008			if let Some($new) = $new.$field {1009				let $old = $old.$field($($arg)?);1010				let _ = $new;1011				let _ = $old;1012				$check1013			} else {1014				$new.$field = $old.$field1015			}1016		)*1017	}};1018}1019macro_rules! limit_default_clone {1020	($old:ident, $new:ident, $($field:ident $(($arg:expr))? => $check:expr),* $(,)?) => {{1021		$(1022			if let Some($new) = $new.$field.clone() {1023				let $old = $old.$field($($arg)?);1024				let _ = $new;1025				let _ = $old;1026				$check1027			} else {1028				$new.$field = $old.$field.clone()1029			}1030		)*1031	}};1032}10331034impl<T: Config> Pallet<T> {1035	/// Create new collection.1036	///1037	/// * `owner` - The owner of the collection.1038	/// * `data` - Description of the created collection.1039	/// * `flags` - Extra flags to store.1040	pub fn init_collection(1041		owner: T::CrossAccountId,1042		payer: T::CrossAccountId,1043		data: CreateCollectionData<T::AccountId>,1044		flags: CollectionFlags,1045	) -> Result<CollectionId, DispatchError> {1046		{1047			ensure!(1048				data.token_prefix.len() <= MAX_TOKEN_PREFIX_LENGTH as usize,1049				Error::<T>::CollectionTokenPrefixLimitExceeded1050			);1051		}10521053		let created_count = <CreatedCollectionCount<T>>::get()1054			.01055			.checked_add(1)1056			.ok_or(ArithmeticError::Overflow)?;1057		let destroyed_count = <DestroyedCollectionCount<T>>::get().0;1058		let id = CollectionId(created_count);10591060		// bound Total number of collections1061		ensure!(1062			created_count - destroyed_count <= COLLECTION_NUMBER_LIMIT,1063			<Error<T>>::TotalCollectionsLimitExceeded1064		);10651066		// =========10671068		let collection = Collection {1069			owner: owner.as_sub().clone(),1070			name: data.name,1071			mode: data.mode.clone(),1072			description: data.description,1073			token_prefix: data.token_prefix,1074			sponsorship: data1075				.pending_sponsor1076				.map(SponsorshipState::Unconfirmed)1077				.unwrap_or_default(),1078			limits: data1079				.limits1080				.map(|limits| Self::clamp_limits(data.mode.clone(), &Default::default(), limits))1081				.unwrap_or_else(|| Ok(CollectionLimits::default()))?,1082			permissions: data1083				.permissions1084				.map(|permissions| {1085					Self::clamp_permissions(data.mode.clone(), &Default::default(), permissions)1086				})1087				.unwrap_or_else(|| Ok(CollectionPermissions::default()))?,1088			flags,1089		};10901091		let mut collection_properties = CollectionPropertiesT::new();1092		collection_properties1093			.try_set_from_iter(data.properties.into_iter())1094			.map_err(<Error<T>>::from)?;10951096		CollectionProperties::<T>::insert(id, collection_properties);10971098		let mut token_props_permissions = PropertiesPermissionMap::new();1099		token_props_permissions1100			.try_set_from_iter(data.token_property_permissions.into_iter())1101			.map_err(<Error<T>>::from)?;11021103		CollectionPropertyPermissions::<T>::insert(id, token_props_permissions);11041105		// Take a (non-refundable) deposit of collection creation1106		{1107			let mut imbalance =1108				<<<T as Config>::Currency as Currency<T::AccountId>>::PositiveImbalance>::zero();1109			imbalance.subsume(1110				<<T as Config>::Currency as Currency<T::AccountId>>::deposit_creating(1111					&T::TreasuryAccountId::get(),1112					T::CollectionCreationPrice::get(),1113				),1114			);1115			<T as Config>::Currency::settle(1116				payer.as_sub(),1117				imbalance,1118				WithdrawReasons::TRANSFER,1119				ExistenceRequirement::KeepAlive,1120			)1121			.map_err(|_| Error::<T>::NotSufficientFounds)?;1122		}11231124		<CreatedCollectionCount<T>>::put(created_count);1125		<Pallet<T>>::deposit_event(Event::CollectionCreated(1126			id,1127			data.mode.id(),1128			owner.as_sub().clone(),1129		));1130		<PalletEvm<T>>::deposit_log(1131			erc::CollectionHelpersEvents::CollectionCreated {1132				owner: *owner.as_eth(),1133				collection_id: eth::collection_id_to_address(id),1134			}1135			.to_log(T::ContractAddress::get()),1136		);1137		<CollectionById<T>>::insert(id, collection);1138		Ok(id)1139	}11401141	/// Destroy collection.1142	///1143	/// * `collection` - Collection handler.1144	/// * `sender` - The owner or administrator of the collection.1145	pub fn destroy_collection(1146		collection: CollectionHandle<T>,1147		sender: &T::CrossAccountId,1148	) -> DispatchResult {1149		ensure!(1150			collection.limits.owner_can_destroy(),1151			<Error<T>>::NoPermission,1152		);1153		collection.check_is_owner(sender)?;11541155		let destroyed_collections = <DestroyedCollectionCount<T>>::get()1156			.01157			.checked_add(1)1158			.ok_or(ArithmeticError::Overflow)?;11591160		// =========11611162		<DestroyedCollectionCount<T>>::put(destroyed_collections);1163		<CollectionById<T>>::remove(collection.id);1164		<AdminAmount<T>>::remove(collection.id);1165		let _ = <IsAdmin<T>>::clear_prefix((collection.id,), u32::MAX, None);1166		let _ = <Allowlist<T>>::clear_prefix((collection.id,), u32::MAX, None);1167		<CollectionProperties<T>>::remove(collection.id);11681169		<Pallet<T>>::deposit_event(Event::CollectionDestroyed(collection.id));11701171		<PalletEvm<T>>::deposit_log(1172			erc::CollectionHelpersEvents::CollectionDestroyed {1173				collection_id: eth::collection_id_to_address(collection.id),1174			}1175			.to_log(T::ContractAddress::get()),1176		);1177		Ok(())1178	}11791180	/// This function sets or removes a collection properties according to1181	/// `properties_updates` contents:1182	/// * sets a property under the <key> with the value provided `(<key>, Some(<value>))`1183	/// * removes a property under the <key> if the value is `None` `(<key>, None)`.1184	///1185	/// This function fires an event for each property change.1186	/// In case of an error, all the changes (including the events) will be reverted1187	/// since the function is transactional.1188	#[transactional]1189	fn modify_collection_properties(1190		collection: &CollectionHandle<T>,1191		sender: &T::CrossAccountId,1192		properties_updates: impl Iterator<Item = (PropertyKey, Option<PropertyValue>)>,1193	) -> DispatchResult {1194		collection.check_is_owner_or_admin(sender)?;11951196		let mut stored_properties = <CollectionProperties<T>>::get(collection.id);11971198		for (key, value) in properties_updates {1199			match value {1200				Some(value) => {1201					stored_properties1202						.try_set(key.clone(), value)1203						.map_err(<Error<T>>::from)?;12041205					Self::deposit_event(Event::CollectionPropertySet(collection.id, key));1206					<PalletEvm<T>>::deposit_log(1207						erc::CollectionHelpersEvents::CollectionChanged {1208							collection_id: eth::collection_id_to_address(collection.id),1209						}1210						.to_log(T::ContractAddress::get()),1211					);1212				}1213				None => {1214					stored_properties.remove(&key).map_err(<Error<T>>::from)?;12151216					Self::deposit_event(Event::CollectionPropertyDeleted(collection.id, key));1217					<PalletEvm<T>>::deposit_log(1218						erc::CollectionHelpersEvents::CollectionChanged {1219							collection_id: eth::collection_id_to_address(collection.id),1220						}1221						.to_log(T::ContractAddress::get()),1222					);1223				}1224			}1225		}12261227		<CollectionProperties<T>>::set(collection.id, stored_properties);12281229		Ok(())1230	}12311232	/// A batch operation to add, edit or remove properties for a token.1233	/// It sets or removes a token's properties according to1234	/// `properties_updates` contents:1235	/// * sets a property under the <key> with the value provided `(<key>, Some(<value>))`1236	/// * removes a property under the <key> if the value is `None` `(<key>, None)`.1237	///1238	/// - `nesting_budget`: Limit for searching parents in-depth to check ownership.1239	/// - `is_token_create`: Indicates that method is called during token initialization.1240	///   Allows to bypass ownership check.1241	///1242	/// All affected properties should have `mutable` permission1243	/// to be **deleted** or to be **set more than once**,1244	/// and the sender should have permission to edit those properties.1245	///1246	/// This function fires an event for each property change.1247	/// In case of an error, all the changes (including the events) will be reverted1248	/// since the function is transactional.1249	pub fn modify_token_properties(1250		collection: &CollectionHandle<T>,1251		sender: &T::CrossAccountId,1252		token_id: TokenId,1253		properties_updates: impl Iterator<Item = (PropertyKey, Option<PropertyValue>)>,1254		is_token_create: bool,1255		mut stored_properties: TokenProperties,1256		is_token_owner: impl Fn() -> Result<bool, DispatchError>,1257		set_token_properties: impl FnOnce(TokenProperties),1258		log: evm_coder::ethereum::Log,1259	) -> DispatchResult {1260		let is_collection_admin = collection.is_owner_or_admin(sender);1261		let permissions = Self::property_permissions(collection.id);12621263		let mut token_owner_result = None;1264		let mut is_token_owner = || -> Result<bool, DispatchError> {1265			*token_owner_result.get_or_insert_with(&is_token_owner)1266		};12671268		for (key, value) in properties_updates {1269			let permission = permissions1270				.get(&key)1271				.cloned()1272				.unwrap_or_else(PropertyPermission::none);12731274			let is_property_exists = stored_properties.get(&key).is_some();12751276			match permission {1277				PropertyPermission { mutable: false, .. } if is_property_exists => {1278					return Err(<Error<T>>::NoPermission.into());1279				}12801281				PropertyPermission {1282					collection_admin,1283					token_owner,1284					..1285				} => {1286					//TODO: investigate threats during public minting.1287					let is_token_create =1288						is_token_create && (collection_admin || token_owner) && value.is_some();1289					if !(is_token_create1290						|| (collection_admin && is_collection_admin)1291						|| (token_owner && is_token_owner()?))1292					{1293						fail!(<Error<T>>::NoPermission);1294					}1295				}1296			}12971298			match value {1299				Some(value) => {1300					stored_properties1301						.try_set(key.clone(), value)1302						.map_err(<Error<T>>::from)?;13031304					Self::deposit_event(Event::TokenPropertySet(collection.id, token_id, key));1305				}1306				None => {1307					stored_properties.remove(&key).map_err(<Error<T>>::from)?;13081309					Self::deposit_event(Event::TokenPropertyDeleted(collection.id, token_id, key));1310				}1311			}13121313			<PalletEvm<T>>::deposit_log(log.clone());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/evm-coder-substrate/src/execution.rsdiffbeforeafterboth
--- a/pallets/evm-coder-substrate/src/execution.rs
+++ b/pallets/evm-coder-substrate/src/execution.rs
@@ -61,7 +61,7 @@
 	fn dispatch_info(&self) -> DispatchInfo {
 		DispatchInfo {
 			// ERC165 impl should be cheap
-			weight: Weight::from_ref_time(200),
+			weight: Weight::from_parts(200, 0),
 		}
 	}
 }
@@ -77,10 +77,11 @@
 		Self { weight }
 	}
 }
+// TODO: use 2-dimensional weight after frontier upgrade
 impl From<u64> for DispatchInfo {
 	fn from(weight: u64) -> Self {
 		Self {
-			weight: Weight::from_ref_time(weight),
+			weight: Weight::from_parts(weight, 0),
 		}
 	}
 }
modifiedpallets/evm-migration/src/lib.rsdiffbeforeafterboth
--- a/pallets/evm-migration/src/lib.rs
+++ b/pallets/evm-migration/src/lib.rs
@@ -21,6 +21,7 @@
 pub use pallet::*;
 #[cfg(feature = "runtime-benchmarks")]
 pub mod benchmarking;
+#[allow(missing_docs)]
 pub mod weights;
 
 #[frame_support::pallet]
modifiedpallets/unique/src/benchmarking.rsdiffbeforeafterboth
--- a/pallets/unique/src/benchmarking.rs
+++ b/pallets/unique/src/benchmarking.rs
@@ -26,6 +26,11 @@
 	Config as CommonConfig,
 	benchmarking::{create_data, create_u16_data},
 };
+use up_data_structs::{
+	CollectionId, CollectionMode, MAX_COLLECTION_NAME_LENGTH, MAX_TOKEN_PREFIX_LENGTH,
+	MAX_COLLECTION_DESCRIPTION_LENGTH, CollectionLimits,
+};
+use pallet_common::erc::CrossAccountId;
 
 const SEED: u32 = 1;
 
@@ -34,9 +39,9 @@
 	mode: CollectionMode,
 ) -> Result<CollectionId, DispatchError> {
 	<T as CommonConfig>::Currency::deposit_creating(&owner, T::CollectionCreationPrice::get());
-	let col_name = create_u16_data::<MAX_COLLECTION_NAME_LENGTH>();
-	let col_desc = create_u16_data::<MAX_COLLECTION_DESCRIPTION_LENGTH>();
-	let token_prefix = create_data::<MAX_TOKEN_PREFIX_LENGTH>();
+	let col_name = create_u16_data::<{ MAX_COLLECTION_NAME_LENGTH }>();
+	let col_desc = create_u16_data::<{ MAX_COLLECTION_DESCRIPTION_LENGTH }>();
+	let token_prefix = create_data::<{ MAX_TOKEN_PREFIX_LENGTH }>();
 	<Pallet<T>>::create_collection(
 		RawOrigin::Signed(owner).into(),
 		col_name,
@@ -54,9 +59,9 @@
 
 benchmarks! {
 	create_collection {
-		let col_name = create_u16_data::<MAX_COLLECTION_NAME_LENGTH>();
-		let col_desc = create_u16_data::<MAX_COLLECTION_DESCRIPTION_LENGTH>();
-		let token_prefix = create_data::<MAX_TOKEN_PREFIX_LENGTH>();
+		let col_name = create_u16_data::<{MAX_COLLECTION_NAME_LENGTH}>();
+		let col_desc = create_u16_data::<{MAX_COLLECTION_DESCRIPTION_LENGTH}>();
+		let token_prefix = create_data::<{MAX_TOKEN_PREFIX_LENGTH}>();
 		let mode: CollectionMode = CollectionMode::NFT;
 		let caller: T::AccountId = account("caller", 0, SEED);
 		<T as CommonConfig>::Currency::deposit_creating(&caller, T::CollectionCreationPrice::get());
modifiedpallets/unique/src/lib.rsdiffbeforeafterboth
--- a/pallets/unique/src/lib.rs
+++ b/pallets/unique/src/lib.rs
@@ -89,14 +89,11 @@
 	use frame_support::{
 		dispatch::DispatchResult,
 		ensure, fail,
-		weights::{Weight},
-		pallet_prelude::{*},
 		BoundedVec,
 		storage::Key,
 	};
-	use frame_system::pallet_prelude::*;
 	use scale_info::TypeInfo;
-	use frame_system::{self as system, ensure_signed, ensure_root};
+	use frame_system::{ensure_signed, ensure_root};
 	use sp_std::{vec, vec::Vec};
 	use up_data_structs::{
 		MAX_COLLECTION_NAME_LENGTH, MAX_COLLECTION_DESCRIPTION_LENGTH, MAX_TOKEN_PREFIX_LENGTH,
modifiedprimitives/common/src/constants.rsdiffbeforeafterboth
--- a/primitives/common/src/constants.rs
+++ b/primitives/common/src/constants.rs
@@ -64,9 +64,10 @@
 /// by  Operational  extrinsics.
 pub const NORMAL_DISPATCH_RATIO: Perbill = Perbill::from_percent(75);
 /// We allow for 2 seconds of compute with a 6 second average block time.
-pub const MAXIMUM_BLOCK_WEIGHT: Weight =
-	Weight::from_ref_time(WEIGHT_REF_TIME_PER_SECOND.saturating_div(2))
-		.set_proof_size(MAX_POV_SIZE as u64);
+pub const MAXIMUM_BLOCK_WEIGHT: Weight = Weight::from_parts(
+	WEIGHT_REF_TIME_PER_SECOND.saturating_div(2),
+	MAX_POV_SIZE as u64,
+);
 
 parameter_types! {
 	pub const TransactionByteFee: Balance = 501 * MICROUNIQUE / 2;
modifiedruntime/common/config/ethereum.rsdiffbeforeafterboth
--- a/runtime/common/config/ethereum.rs
+++ b/runtime/common/config/ethereum.rs
@@ -28,7 +28,7 @@
 	pub const GasPerSecond: u64 = WritesPerSecond::get() * 20000;
 	pub const WeightTimePerGas: u64 = WEIGHT_REF_TIME_PER_SECOND / GasPerSecond::get();
 
-	pub const WeightPerGas: Weight = Weight::from_ref_time(WeightTimePerGas::get());
+	pub const WeightPerGas: Weight = Weight::from_parts(WeightTimePerGas::get(), 0);
 }
 
 /// Limiting EVM execution to 50% of block for substrate users and management tasks
modifiedruntime/common/mod.rsdiffbeforeafterboth
--- a/runtime/common/mod.rs
+++ b/runtime/common/mod.rs
@@ -27,6 +27,7 @@
 pub mod scheduler;
 
 pub mod sponsoring;
+#[allow(missing_docs)]
 pub mod weights;
 
 #[cfg(test)]
@@ -152,7 +153,7 @@
 	}
 	#[cfg(feature = "runtime-benchmarks")]
 	fn set_block_number(block: Self::BlockNumber) {
-		cumulus_pallet_parachain_system::RelaychainBlockNumberProvider::<T>::set_block_number(block)
+		cumulus_pallet_parachain_system::RelaychainDataProvider::<T>::set_block_number(block)
 	}
 }