git.delta.rocks / unique-network / refs/commits / 31c5482db3c6

difftreelog

doc: Fix PR

Trubnikov Sergey2022-07-15parent: #7dcd3b7.patch.diff
in: master

3 files changed

modifiedpallets/common/src/dispatch.rsdiffbeforeafterboth
--- a/pallets/common/src/dispatch.rs
+++ b/pallets/common/src/dispatch.rs
@@ -94,6 +94,6 @@
 	/// Get the collection handle for the corresponding implementation.
 	fn into_inner(self) -> CollectionHandle<T>;
 
-	/// Получить реализацию [CommonCollectionOperations].
+	/// Get the implementation of [CommonCollectionOperations].
 	fn as_dyn(&self) -> &dyn CommonCollectionOperations<T>;
 }
modifiedpallets/common/src/eth.rsdiffbeforeafterboth
--- a/pallets/common/src/eth.rs
+++ b/pallets/common/src/eth.rs
@@ -14,7 +14,7 @@
 // You should have received a copy of the GNU General Public License
 // along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
 
-//! The module contains a number of functions for converting and checking etherium identifiers.
+//! The module contains a number of functions for converting and checking ethereum identifiers.
 
 use up_data_structs::CollectionId;
 use sp_core::H160;
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 functions for:24//!25//! - Setting and approving collection soponsor.26//! - Get\set\delete allow list.27//! - Get\set\delete collection properties.28//! - Get\set\delete collection property permissions.29//! - Get\set\delete token property permissions.30//! - Get\set\delete collection administrators.31//! - Checking access permissions.32//! - Provides an interface for common collection operations for different collection types.33//! - Provides dispatching for implementations of common collection operations, see [dispatch] module.34//! - Provides functionality of collection into evm, see [erc] and [eth] module.35//!36//! ### Terminology37//! **Collection sponsor** - For the collection, you can set a sponsor, at whose expense it will38//! be possible to mint tokens.39//!40//! **Allow list** - List of users who have the right to minting tokens.41//!42//! **Collection properties** - Collection properties are simply key-value stores where various43//! metadata can be placed.44//!45//! **Collection property permissions** - For each property in the collection can be set permission46//! to change, see [PropertyPermission].47//!48//! **Permissions on token properties** - Similar to _permissions on collection properties_,49//! only restrictions apply to token properties.50//!51//! **Collection administrator** - For a collection, you can set administrators who have the right52//! to most actions on the collection.5354#![warn(missing_docs)]55#![cfg_attr(not(feature = "std"), no_std)]56extern crate alloc;5758use core::ops::{Deref, DerefMut};59use pallet_evm_coder_substrate::{SubstrateRecorder, WithRecorder};60use sp_std::vec::Vec;61use pallet_evm::{account::CrossAccountId, Pallet as PalletEvm};62use evm_coder::ToLog;63use frame_support::{64	dispatch::{DispatchErrorWithPostInfo, DispatchResultWithPostInfo, Weight, PostDispatchInfo},65	ensure,66	traits::{Imbalance, Get, Currency, WithdrawReasons, ExistenceRequirement},67	weights::Pays,68	transactional,69};70use pallet_evm::GasWeightMapping;71use up_data_structs::{72	COLLECTION_NUMBER_LIMIT,73	Collection,74	RpcCollection,75	CollectionId,76	CreateItemData,77	MAX_TOKEN_PREFIX_LENGTH,78	COLLECTION_ADMINS_LIMIT,79	TokenId,80	TokenChild,81	CollectionStats,82	MAX_TOKEN_OWNERSHIP,83	CollectionMode,84	NFT_SPONSOR_TRANSFER_TIMEOUT,85	FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,86	REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,87	MAX_SPONSOR_TIMEOUT,88	CUSTOM_DATA_LIMIT,89	CollectionLimits,90	CreateCollectionData,91	SponsorshipState,92	CreateItemExData,93	SponsoringRateLimit,94	budget::Budget,95	PhantomType,96	Property,97	Properties,98	PropertiesPermissionMap,99	PropertyKey,100	PropertyValue,101	PropertyPermission,102	PropertiesError,103	PropertyKeyPermission,104	TokenData,105	TrySetProperty,106	PropertyScope,107	// RMRK108	RmrkCollectionInfo,109	RmrkInstanceInfo,110	RmrkResourceInfo,111	RmrkPropertyInfo,112	RmrkBaseInfo,113	RmrkPartType,114	RmrkBoundedTheme,115	RmrkNftChild,116	CollectionPermissions,117	SchemaVersion,118};119120pub use pallet::*;121use sp_core::H160;122use sp_runtime::{ArithmeticError, DispatchError, DispatchResult};123#[cfg(feature = "runtime-benchmarks")]124pub mod benchmarking;125pub mod dispatch;126pub mod erc;127pub mod eth;128pub mod weights;129130/// Weight info.131pub type SelfWeightOf<T> = <T as Config>::WeightInfo;132133/// Collection handle contains information about collection data and id.134/// Also provides functionality to count consumed gas.135#[must_use = "Should call submit_logs or save, otherwise some data will be lost for evm side"]136pub struct CollectionHandle<T: Config> {137	/// Collection id138	pub id: CollectionId,139	collection: Collection<T::AccountId>,140	/// Substrate recorder for counting consumed gas141	pub recorder: SubstrateRecorder<T>,142}143144impl<T: Config> WithRecorder<T> for CollectionHandle<T> {145	fn recorder(&self) -> &SubstrateRecorder<T> {146		&self.recorder147	}148	fn into_recorder(self) -> SubstrateRecorder<T> {149		self.recorder150	}151}152153impl<T: Config> CollectionHandle<T> {154	/// Same as [CollectionHandle::new] but with an explicit gas limit.155	pub fn new_with_gas_limit(id: CollectionId, gas_limit: u64) -> Option<Self> {156		<CollectionById<T>>::get(id).map(|collection| Self {157			id,158			collection,159			recorder: SubstrateRecorder::new(gas_limit),160		})161	}162163	/// Same as [CollectionHandle::new] but with an existed [SubstrateRecorder].164	pub fn new_with_recorder(id: CollectionId, recorder: SubstrateRecorder<T>) -> Option<Self> {165		<CollectionById<T>>::get(id).map(|collection| Self {166			id,167			collection,168			recorder,169		})170	}171172	/// Retrives collection data from storage and creates collection handle with default parameters.173	/// If collection not found return `None`174	pub fn new(id: CollectionId) -> Option<Self> {175		Self::new_with_gas_limit(id, u64::MAX)176	}177178	/// Same as [CollectionHandle::new] but if collection not found [Error::CollectionNotFound] returned.179	pub fn try_get(id: CollectionId) -> Result<Self, DispatchError> {180		Ok(Self::new(id).ok_or(<Error<T>>::CollectionNotFound)?)181	}182183	/// Consume gas for reading.184	pub fn consume_store_reads(&self, reads: u64) -> evm_coder::execution::Result<()> {185		self.recorder186			.consume_gas(T::GasWeightMapping::weight_to_gas(187				<T as frame_system::Config>::DbWeight::get()188					.read189					.saturating_mul(reads),190			))191	}192193	/// Consume gas for writing.194	pub fn consume_store_writes(&self, writes: u64) -> evm_coder::execution::Result<()> {195		self.recorder196			.consume_gas(T::GasWeightMapping::weight_to_gas(197				<T as frame_system::Config>::DbWeight::get()198					.write199					.saturating_mul(writes),200			))201	}202203	/// Save collection to storage.204	pub fn save(self) -> DispatchResult {205		<CollectionById<T>>::insert(self.id, self.collection);206		Ok(())207	}208209	/// Set collection sponsor.210	///211	/// Unique collections allows sponsoring for certain actions.212	/// This method allows you to set the sponsor of the collection.213	/// In order for sponsorship to become active, it must be confirmed through [Self::confirm_sponsorship].214	pub fn set_sponsor(&mut self, sponsor: T::AccountId) -> DispatchResult {215		self.collection.sponsorship = SponsorshipState::Unconfirmed(sponsor);216		Ok(())217	}218219	/// Confirm sponsorship220	///221	/// In order for the sponsorship to become active, the user set as the sponsor must confirm their participation.222	/// Before confirming sponsorship, the user must be specified as the sponsor of the collection via [Self::set_sponsor].223	pub fn confirm_sponsorship(&mut self, sender: &T::AccountId) -> Result<bool, DispatchError> {224		if self.collection.sponsorship.pending_sponsor() != Some(sender) {225			return Ok(false);226		}227228		self.collection.sponsorship = SponsorshipState::Confirmed(sender.clone());229		Ok(true)230	}231232	/// Checks that the collection was created with, and must be operated upon through **Unique API**.233	/// Now check only the `external_collection` flag and if it's **true**, then return [Error::CollectionIsExternal] error.234	pub fn check_is_internal(&self) -> DispatchResult {235		if self.external_collection {236			return Err(<Error<T>>::CollectionIsExternal)?;237		}238239		Ok(())240	}241242	/// Checks that the collection was created with, and must be operated upon through an **assimilated API**.243	/// Now check only the `external_collection` flag and if it's **false**, then return [Error::CollectionIsInternal] error.244	pub fn check_is_external(&self) -> DispatchResult {245		if !self.external_collection {246			return Err(<Error<T>>::CollectionIsInternal)?;247		}248249		Ok(())250	}251}252253impl<T: Config> Deref for CollectionHandle<T> {254	type Target = Collection<T::AccountId>;255256	fn deref(&self) -> &Self::Target {257		&self.collection258	}259}260261impl<T: Config> DerefMut for CollectionHandle<T> {262	fn deref_mut(&mut self) -> &mut Self::Target {263		&mut self.collection264	}265}266267impl<T: Config> CollectionHandle<T> {268	/// Checks if the `user` is the owner of the collection.269	pub fn check_is_owner(&self, user: &T::CrossAccountId) -> DispatchResult {270		ensure!(*user.as_sub() == self.owner, <Error<T>>::NoPermission);271		Ok(())272	}273274	/// Returns **true** if the `user` is the owner or administrator of the collection.275	pub fn is_owner_or_admin(&self, user: &T::CrossAccountId) -> bool {276		*user.as_sub() == self.owner || <IsAdmin<T>>::get((self.id, user))277	}278279	/// Checks if the `user` is the owner or administrator of the collection.280	pub fn check_is_owner_or_admin(&self, user: &T::CrossAccountId) -> DispatchResult {281		ensure!(self.is_owner_or_admin(user), <Error<T>>::NoPermission);282		Ok(())283	}284285	/// Return **true** if `user` was not allowed to have tokens, and he can ignore such restrictions.286	pub fn ignores_allowance(&self, user: &T::CrossAccountId) -> bool {287		self.limits.owner_can_transfer() && self.is_owner_or_admin(user)288	}289290	/// Return **true** if `user` does not have enough token parts, and he can ignore such restrictions.291	pub fn ignores_owned_amount(&self, user: &T::CrossAccountId) -> bool {292		self.limits.owner_can_transfer() && self.is_owner_or_admin(user)293	}294295	/// Checks if the user is in the allow list. If not [Error::AddressNotInAllowlist] returns.296	pub fn check_allowlist(&self, user: &T::CrossAccountId) -> DispatchResult {297		ensure!(298			<Allowlist<T>>::get((self.id, user)),299			<Error<T>>::AddressNotInAllowlist300		);301		Ok(())302	}303}304305#[frame_support::pallet]306pub mod pallet {307	use super::*;308	use pallet_evm::account;309	use dispatch::CollectionDispatch;310	use frame_support::{Blake2_128Concat, pallet_prelude::*, storage::Key, traits::StorageVersion};311	use frame_system::pallet_prelude::*;312	use frame_support::traits::Currency;313	use up_data_structs::{TokenId, mapping::TokenAddressMapping};314	use scale_info::TypeInfo;315	use weights::WeightInfo;316317	#[pallet::config]318	pub trait Config:319		frame_system::Config320		+ pallet_evm_coder_substrate::Config321		+ pallet_evm::Config322		+ TypeInfo323		+ account::Config324	{325		/// Weight info.326		type WeightInfo: WeightInfo;327328		/// Events compatible with [frame_system::Config::Event].329		type Event: IsType<<Self as frame_system::Config>::Event> + From<Event<Self>>;330331		/// Currency.332		type Currency: Currency<Self::AccountId>;333334		/// Price getter to create the collection.335		#[pallet::constant]336		type CollectionCreationPrice: Get<337			<<Self as Config>::Currency as Currency<Self::AccountId>>::Balance,338		>;339340		/// Collection dispatcher.341		type CollectionDispatch: CollectionDispatch<Self>;342343		/// Treasury account id getter.344		type TreasuryAccountId: Get<Self::AccountId>;345346		/// Contract address getter.347		type ContractAddress: Get<H160>;348349		/// Mapper for tokens to Etherium addresses.350		type EvmTokenAddressMapping: TokenAddressMapping<H160>;351352		/// Mapper for tokens to [CrossAccountId].353		type CrossTokenAddressMapping: TokenAddressMapping<Self::CrossAccountId>;354	}355356	const STORAGE_VERSION: StorageVersion = StorageVersion::new(1);357358	#[pallet::pallet]359	#[pallet::storage_version(STORAGE_VERSION)]360	#[pallet::generate_store(pub(super) trait Store)]361	pub struct Pallet<T>(_);362363	#[pallet::extra_constants]364	impl<T: Config> Pallet<T> {365		/// Maximum admins per collection.366		pub fn collection_admins_limit() -> u32 {367			COLLECTION_ADMINS_LIMIT368		}369	}370371	#[pallet::event]372	#[pallet::generate_deposit(pub fn deposit_event)]373	pub enum Event<T: Config> {374		/// New collection was created375		CollectionCreated(376			/// Globally unique identifier of newly created collection.377			CollectionId,378			/// [CollectionMode] converted into _u8_.379			u8,380			/// Collection owner.381			T::AccountId,382		),383384		/// New collection was destroyed385		CollectionDestroyed(386			/// Globally unique identifier of collection.387			CollectionId,388		),389390		/// New item was created.391		ItemCreated(392			/// Id of the collection where item was created.393			CollectionId,394			/// Id of an item. Unique within the collection.395			TokenId,396			/// Owner of newly created item397			T::CrossAccountId,398			/// Always 1 for NFT399			u128,400		),401402		/// Collection item was burned.403		ItemDestroyed(404			/// Id of the collection where item was destroyed.405			CollectionId,406			/// Identifier of burned NFT.407			TokenId,408			/// Which user has destroyed its tokens.409			T::CrossAccountId,410			/// Amount of token pieces destroed. Always 1 for NFT.411			u128,412		),413414		/// Item was transferred415		Transfer(416			/// Id of collection to which item is belong.417			CollectionId,418			/// Id of an item.419			TokenId,420			/// Original owner of item.421			T::CrossAccountId,422			/// New owner of item.423			T::CrossAccountId,424			/// Amount of token pieces transfered. Always 1 for NFT.425			u128,426		),427428		/// Amount pieces of token owned by `sender` was approved for `spender`.429		Approved(430			/// Id of collection to which item is belong.431			CollectionId,432			/// Id of an item.433			TokenId,434			/// Original owner of item.435			T::CrossAccountId,436			/// Id for which the approval was granted.437			T::CrossAccountId,438			/// Amount of token pieces transfered. Always 1 for NFT.439			u128,440		),441442		/// The colletion property has been set.443		CollectionPropertySet(444			/// Id of collection to which property has been set.445			CollectionId,446			/// The property that was set.447			PropertyKey,448		),449450		/// The property has been deleted.451		CollectionPropertyDeleted(452			/// Id of collection to which property has been deleted.453			CollectionId,454			/// The property that was deleted.455			PropertyKey,456		),457458		/// The token property has been set.459		TokenPropertySet(460			/// Identifier of the collection whose token has the property set.461			CollectionId,462			/// The token for which the property was set.463			TokenId,464			/// The property that was set.465			PropertyKey,466		),467468		/// The token property has been deleted.469		TokenPropertyDeleted(470			/// Identifier of the collection whose token has the property deleted.471			CollectionId,472			/// The token for which the property was deleted.473			TokenId,474			/// The property that was deleted.475			PropertyKey,476		),477478		/// The colletion property permission has been set.479		PropertyPermissionSet(480			/// Id of collection to which property permission has been set.481			CollectionId,482			/// The property permission that was set.483			PropertyKey,484		),485	}486487	#[pallet::error]488	pub enum Error<T> {489		/// This collection does not exist.490		CollectionNotFound,491		/// Sender parameter and item owner must be equal.492		MustBeTokenOwner,493		/// No permission to perform action494		NoPermission,495		/// Destroying only empty collections is allowed496		CantDestroyNotEmptyCollection,497		/// Collection is not in mint mode.498		PublicMintingNotAllowed,499		/// Address is not in allow list.500		AddressNotInAllowlist,501502		/// Collection name can not be longer than 63 char.503		CollectionNameLimitExceeded,504		/// Collection description can not be longer than 255 char.505		CollectionDescriptionLimitExceeded,506		/// Token prefix can not be longer than 15 char.507		CollectionTokenPrefixLimitExceeded,508		/// Total collections bound exceeded.509		TotalCollectionsLimitExceeded,510		/// Exceeded max admin count511		CollectionAdminCountExceeded,512		/// Collection limit bounds per collection exceeded513		CollectionLimitBoundsExceeded,514		/// Tried to enable permissions which are only permitted to be disabled515		OwnerPermissionsCantBeReverted,516		/// Collection settings not allowing items transferring517		TransferNotAllowed,518		/// Account token limit exceeded per collection519		AccountTokenLimitExceeded,520		/// Collection token limit exceeded521		CollectionTokenLimitExceeded,522		/// Metadata flag frozen523		MetadataFlagFrozen,524525		/// Item not exists.526		TokenNotFound,527		/// Item balance not enough.528		TokenValueTooLow,529		/// Requested value more than approved.530		ApprovedValueTooLow,531		/// Tried to approve more than owned532		CantApproveMoreThanOwned,533534		/// Can't transfer tokens to ethereum zero address535		AddressIsZero,536		/// Target collection doesn't supports this operation537		UnsupportedOperation,538539		/// Not sufficient funds to perform action540		NotSufficientFounds,541542		/// User not passed nesting rule543		UserIsNotAllowedToNest,544		/// Only tokens from specific collections may nest tokens under this545		SourceCollectionIsNotAllowedToNest,546547		/// Tried to store more data than allowed in collection field548		CollectionFieldSizeExceeded,549550		/// Tried to store more property data than allowed551		NoSpaceForProperty,552553		/// Tried to store more property keys than allowed554		PropertyLimitReached,555556		/// Property key is too long557		PropertyKeyIsTooLong,558559		/// Only ASCII letters, digits, and '_', '-' are allowed560		InvalidCharacterInPropertyKey,561562		/// Empty property keys are forbidden563		EmptyPropertyKey,564565		/// Tried to access an external collection with an internal API566		CollectionIsExternal,567568		/// Tried to access an internal collection with an external API569		CollectionIsInternal,570	}571572	/// Storage of the count of created collections.573	#[pallet::storage]574	pub type CreatedCollectionCount<T> = StorageValue<Value = CollectionId, QueryKind = ValueQuery>;575576	/// Storage of the count of deleted collections.577	#[pallet::storage]578	pub type DestroyedCollectionCount<T> =579		StorageValue<Value = CollectionId, QueryKind = ValueQuery>;580581	/// Storage of collection info.582	#[pallet::storage]583	pub type CollectionById<T> = StorageMap<584		Hasher = Blake2_128Concat,585		Key = CollectionId,586		Value = Collection<<T as frame_system::Config>::AccountId>,587		QueryKind = OptionQuery,588	>;589590	/// Storage of collection properties.591	#[pallet::storage]592	#[pallet::getter(fn collection_properties)]593	pub type CollectionProperties<T> = StorageMap<594		Hasher = Blake2_128Concat,595		Key = CollectionId,596		Value = Properties,597		QueryKind = ValueQuery,598		OnEmpty = up_data_structs::CollectionProperties,599	>;600601	/// Storage of collection properties permissions.602	#[pallet::storage]603	#[pallet::getter(fn property_permissions)]604	pub type CollectionPropertyPermissions<T> = StorageMap<605		Hasher = Blake2_128Concat,606		Key = CollectionId,607		Value = PropertiesPermissionMap,608		QueryKind = ValueQuery,609	>;610611	/// Storage of collection admins count.612	#[pallet::storage]613	pub type AdminAmount<T> = StorageMap<614		Hasher = Blake2_128Concat,615		Key = CollectionId,616		Value = u32,617		QueryKind = ValueQuery,618	>;619620	/// List of collection admins621	#[pallet::storage]622	pub type IsAdmin<T: Config> = StorageNMap<623		Key = (624			Key<Blake2_128Concat, CollectionId>,625			Key<Blake2_128Concat, T::CrossAccountId>,626		),627		Value = bool,628		QueryKind = ValueQuery,629	>;630631	/// Allowlisted collection users632	#[pallet::storage]633	pub type Allowlist<T: Config> = StorageNMap<634		Key = (635			Key<Blake2_128Concat, CollectionId>,636			Key<Blake2_128Concat, T::CrossAccountId>,637		),638		Value = bool,639		QueryKind = ValueQuery,640	>;641642	/// Not used by code, exists only to provide some types to metadata.643	#[pallet::storage]644	pub type DummyStorageValue<T: Config> = StorageValue<645		Value = (646			CollectionStats,647			CollectionId,648			TokenId,649			TokenChild,650			PhantomType<(651				TokenData<T::CrossAccountId>,652				RpcCollection<T::AccountId>,653				// RMRK654				RmrkCollectionInfo<T::AccountId>,655				RmrkInstanceInfo<T::AccountId>,656				RmrkResourceInfo,657				RmrkPropertyInfo,658				RmrkBaseInfo<T::AccountId>,659				RmrkPartType,660				RmrkBoundedTheme,661				RmrkNftChild,662			)>,663		),664		QueryKind = OptionQuery,665	>;666667	#[pallet::hooks]668	impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {669		fn on_runtime_upgrade() -> Weight {670			if StorageVersion::get::<Pallet<T>>() < StorageVersion::new(1) {671				use up_data_structs::{CollectionVersion1, CollectionVersion2};672				<CollectionById<T>>::translate::<CollectionVersion1<T::AccountId>, _>(|id, v| {673					let mut props = Vec::new();674					if !v.offchain_schema.is_empty() {675						props.push(Property {676							key: b"_old_offchainSchema".to_vec().try_into().unwrap(),677							value: v678								.offchain_schema679								.clone()680								.into_inner()681								.try_into()682								.expect("offchain schema too big"),683						});684					}685					if !v.variable_on_chain_schema.is_empty() {686						props.push(Property {687							key: b"_old_variableOnChainSchema".to_vec().try_into().unwrap(),688							value: v689								.variable_on_chain_schema690								.clone()691								.into_inner()692								.try_into()693								.expect("offchain schema too big"),694						});695					}696					if !v.const_on_chain_schema.is_empty() {697						props.push(Property {698							key: b"_old_constOnChainSchema".to_vec().try_into().unwrap(),699							value: v700								.const_on_chain_schema701								.clone()702								.into_inner()703								.try_into()704								.expect("offchain schema too big"),705						});706					}707					props.push(Property {708						key: b"_old_schemaVersion".to_vec().try_into().unwrap(),709						value: match v.schema_version {710							SchemaVersion::ImageURL => b"ImageUrl".as_slice(),711							SchemaVersion::Unique => b"Unique".as_slice(),712						}713						.to_vec()714						.try_into()715						.unwrap(),716					});717					Self::set_scoped_collection_properties(718						id,719						PropertyScope::None,720						props.into_iter(),721					)722					.expect("existing data larger than properties");723					let mut new = CollectionVersion2::from(v.clone());724					new.permissions.access = Some(v.access);725					new.permissions.mint_mode = Some(v.mint_mode);726					Some(new)727				});728			}729730			0731		}732	}733}734735impl<T: Config> Pallet<T> {736	/// Enshure that receiver address is correct.737	///738	/// Ethereum receiver 0x0000000000000000000000000000000000000000 is reserved, and shouldn't own tokens.739	pub fn ensure_correct_receiver(receiver: &T::CrossAccountId) -> DispatchResult {740		ensure!(741			&T::CrossAccountId::from_eth(H160([0; 20])) != receiver,742			<Error<T>>::AddressIsZero743		);744		Ok(())745	}746747	/// Get a vector of collection admins.748	pub fn adminlist(collection: CollectionId) -> Vec<T::CrossAccountId> {749		<IsAdmin<T>>::iter_prefix((collection,))750			.map(|(a, _)| a)751			.collect()752	}753754	/// Get a vector of users allowed to mint tokens.755	pub fn allowlist(collection: CollectionId) -> Vec<T::CrossAccountId> {756		<Allowlist<T>>::iter_prefix((collection,))757			.map(|(a, _)| a)758			.collect()759	}760761	/// Is `user` allowed to mint token in `collection`.762	pub fn allowed(collection: CollectionId, user: T::CrossAccountId) -> bool {763		<Allowlist<T>>::get((collection, user))764	}765766	/// Get statistics of collections.767	pub fn collection_stats() -> CollectionStats {768		let created = <CreatedCollectionCount<T>>::get();769		let destroyed = <DestroyedCollectionCount<T>>::get();770		CollectionStats {771			created: created.0,772			destroyed: destroyed.0,773			alive: created.0 - destroyed.0,774		}775	}776777	/// Get the effective limits for the collection.778	pub fn effective_collection_limits(collection: CollectionId) -> Option<CollectionLimits> {779		let collection = <CollectionById<T>>::get(collection);780		if collection.is_none() {781			return None;782		}783784		let collection = collection.unwrap();785		let limits = collection.limits;786		let effective_limits = CollectionLimits {787			account_token_ownership_limit: Some(limits.account_token_ownership_limit()),788			sponsored_data_size: Some(limits.sponsored_data_size()),789			sponsored_data_rate_limit: Some(790				limits791					.sponsored_data_rate_limit792					.unwrap_or(SponsoringRateLimit::SponsoringDisabled),793			),794			token_limit: Some(limits.token_limit()),795			sponsor_transfer_timeout: Some(limits.sponsor_transfer_timeout(796				match collection.mode {797					CollectionMode::NFT => NFT_SPONSOR_TRANSFER_TIMEOUT,798					CollectionMode::Fungible(_) => FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,799					CollectionMode::ReFungible => REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,800				},801			)),802			sponsor_approve_timeout: Some(limits.sponsor_approve_timeout()),803			owner_can_transfer: Some(limits.owner_can_transfer()),804			owner_can_destroy: Some(limits.owner_can_destroy()),805			transfers_enabled: Some(limits.transfers_enabled()),806		};807808		Some(effective_limits)809	}810811	/// Returns information about the `collection` adapted for rpc.812	pub fn rpc_collection(collection: CollectionId) -> Option<RpcCollection<T::AccountId>> {813		let Collection {814			name,815			description,816			owner,817			mode,818			token_prefix,819			sponsorship,820			limits,821			permissions,822			external_collection,823		} = <CollectionById<T>>::get(collection)?;824825		let token_property_permissions = <CollectionPropertyPermissions<T>>::get(collection)826			.into_iter()827			.map(|(key, permission)| PropertyKeyPermission { key, permission })828			.collect();829830		let properties = <CollectionProperties<T>>::get(collection)831			.into_iter()832			.map(|(key, value)| Property { key, value })833			.collect();834835		let permissions = CollectionPermissions {836			access: Some(permissions.access()),837			mint_mode: Some(permissions.mint_mode()),838			nesting: Some(permissions.nesting().clone()),839		};840841		Some(RpcCollection {842			name: name.into_inner(),843			description: description.into_inner(),844			owner,845			mode,846			token_prefix: token_prefix.into_inner(),847			sponsorship,848			limits,849			permissions,850			token_property_permissions,851			properties,852			read_only: external_collection,853		})854	}855}856857macro_rules! limit_default {858	($old:ident, $new:ident, $($field:ident $(($arg:expr))? => $check:expr),* $(,)?) => {{859		$(860			if let Some($new) = $new.$field {861				let $old = $old.$field($($arg)?);862				let _ = $new;863				let _ = $old;864				$check865			} else {866				$new.$field = $old.$field867			}868		)*869	}};870}871macro_rules! limit_default_clone {872	($old:ident, $new:ident, $($field:ident $(($arg:expr))? => $check:expr),* $(,)?) => {{873		$(874			if let Some($new) = $new.$field.clone() {875				let $old = $old.$field($($arg)?);876				let _ = $new;877				let _ = $old;878				$check879			} else {880				$new.$field = $old.$field.clone()881			}882		)*883	}};884}885886impl<T: Config> Pallet<T> {887	/// Create new collection.888	///889	/// * `owner` - The owner of the collection.890	/// * `data` - Description of the created collection.891	/// * `is_external` - Marks that collection managet by not "Unique network".892	pub fn init_collection(893		owner: T::CrossAccountId,894		data: CreateCollectionData<T::AccountId>,895		is_external: bool,896	) -> Result<CollectionId, DispatchError> {897		{898			ensure!(899				data.token_prefix.len() <= MAX_TOKEN_PREFIX_LENGTH as usize,900				Error::<T>::CollectionTokenPrefixLimitExceeded901			);902		}903904		let created_count = <CreatedCollectionCount<T>>::get()905			.0906			.checked_add(1)907			.ok_or(ArithmeticError::Overflow)?;908		let destroyed_count = <DestroyedCollectionCount<T>>::get().0;909		let id = CollectionId(created_count);910911		// bound Total number of collections912		ensure!(913			created_count - destroyed_count <= COLLECTION_NUMBER_LIMIT,914			<Error<T>>::TotalCollectionsLimitExceeded915		);916917		// =========918919		let collection = Collection {920			owner: owner.as_sub().clone(),921			name: data.name,922			mode: data.mode.clone(),923			description: data.description,924			token_prefix: data.token_prefix,925			sponsorship: data926				.pending_sponsor927				.map(SponsorshipState::Unconfirmed)928				.unwrap_or_default(),929			limits: data930				.limits931				.map(|limits| Self::clamp_limits(data.mode.clone(), &Default::default(), limits))932				.unwrap_or_else(|| Ok(CollectionLimits::default()))?,933			permissions: data934				.permissions935				.map(|permissions| {936					Self::clamp_permissions(data.mode.clone(), &Default::default(), permissions)937				})938				.unwrap_or_else(|| Ok(CollectionPermissions::default()))?,939			external_collection: is_external,940		};941942		let mut collection_properties = up_data_structs::CollectionProperties::get();943		collection_properties944			.try_set_from_iter(data.properties.into_iter())945			.map_err(<Error<T>>::from)?;946947		CollectionProperties::<T>::insert(id, collection_properties);948949		let mut token_props_permissions = PropertiesPermissionMap::new();950		token_props_permissions951			.try_set_from_iter(data.token_property_permissions.into_iter())952			.map_err(<Error<T>>::from)?;953954		CollectionPropertyPermissions::<T>::insert(id, token_props_permissions);955956		// Take a (non-refundable) deposit of collection creation957		{958			let mut imbalance =959				<<<T as Config>::Currency as Currency<T::AccountId>>::PositiveImbalance>::zero();960			imbalance.subsume(961				<<T as Config>::Currency as Currency<T::AccountId>>::deposit_creating(962					&T::TreasuryAccountId::get(),963					T::CollectionCreationPrice::get(),964				),965			);966			<T as Config>::Currency::settle(967				&owner.as_sub(),968				imbalance,969				WithdrawReasons::TRANSFER,970				ExistenceRequirement::KeepAlive,971			)972			.map_err(|_| Error::<T>::NotSufficientFounds)?;973		}974975		<CreatedCollectionCount<T>>::put(created_count);976		<Pallet<T>>::deposit_event(Event::CollectionCreated(977			id,978			data.mode.id(),979			owner.as_sub().clone(),980		));981		<PalletEvm<T>>::deposit_log(982			erc::CollectionHelpersEvents::CollectionCreated {983				owner: *owner.as_eth(),984				collection_id: eth::collection_id_to_address(id),985			}986			.to_log(T::ContractAddress::get()),987		);988		<CollectionById<T>>::insert(id, collection);989		Ok(id)990	}991992	/// Destroy collection.993	///994	/// * `collection` - Collection handler.995	/// * `sender` - The owner or administrator of the collection.996	pub fn destroy_collection(997		collection: CollectionHandle<T>,998		sender: &T::CrossAccountId,999	) -> DispatchResult {1000		ensure!(1001			collection.limits.owner_can_destroy(),1002			<Error<T>>::NoPermission,1003		);1004		collection.check_is_owner(sender)?;10051006		let destroyed_collections = <DestroyedCollectionCount<T>>::get()1007			.01008			.checked_add(1)1009			.ok_or(ArithmeticError::Overflow)?;10101011		// =========10121013		<DestroyedCollectionCount<T>>::put(destroyed_collections);1014		<CollectionById<T>>::remove(collection.id);1015		<AdminAmount<T>>::remove(collection.id);1016		<IsAdmin<T>>::remove_prefix((collection.id,), None);1017		<Allowlist<T>>::remove_prefix((collection.id,), None);1018		<CollectionProperties<T>>::remove(collection.id);10191020		<Pallet<T>>::deposit_event(Event::CollectionDestroyed(collection.id));1021		Ok(())1022	}10231024	/// Set collection property.1025	///1026	/// * `collection` - Collection handler.1027	/// * `sender` - The owner or administrator of the collection.1028	/// * `property` - The property to set.1029	pub fn set_collection_property(1030		collection: &CollectionHandle<T>,1031		sender: &T::CrossAccountId,1032		property: Property,1033	) -> DispatchResult {1034		collection.check_is_owner_or_admin(sender)?;10351036		CollectionProperties::<T>::try_mutate(collection.id, |properties| {1037			let property = property.clone();1038			properties.try_set(property.key, property.value)1039		})1040		.map_err(<Error<T>>::from)?;10411042		Self::deposit_event(Event::CollectionPropertySet(collection.id, property.key));10431044		Ok(())1045	}10461047	/// Set scouped collection property.1048	///1049	/// * `collection_id` - ID of the collection for which the property is being set.1050	/// * `scope` - Property scope.1051	/// * `property` - The property to set.1052	pub fn set_scoped_collection_property(1053		collection_id: CollectionId,1054		scope: PropertyScope,1055		property: Property,1056	) -> DispatchResult {1057		CollectionProperties::<T>::try_mutate(collection_id, |properties| {1058			properties.try_scoped_set(scope, property.key, property.value)1059		})1060		.map_err(<Error<T>>::from)?;10611062		Ok(())1063	}10641065	/// Set scouped collection properties.1066	///1067	/// * `collection_id` - ID of the collection for which the properties is being set.1068	/// * `scope` - Property scope.1069	/// * `properties` - The properties to set.1070	pub fn set_scoped_collection_properties(1071		collection_id: CollectionId,1072		scope: PropertyScope,1073		properties: impl Iterator<Item = Property>,1074	) -> DispatchResult {1075		CollectionProperties::<T>::try_mutate(collection_id, |stored_properties| {1076			stored_properties.try_scoped_set_from_iter(scope, properties)1077		})1078		.map_err(<Error<T>>::from)?;10791080		Ok(())1081	}10821083	/// Set collection properties.1084	///1085	/// * `collection` - Collection handler.1086	/// * `sender` - The owner or administrator of the collection.1087	/// * `properties` - The properties to set.1088	#[transactional]1089	pub fn set_collection_properties(1090		collection: &CollectionHandle<T>,1091		sender: &T::CrossAccountId,1092		properties: Vec<Property>,1093	) -> DispatchResult {1094		for property in properties {1095			Self::set_collection_property(collection, sender, property)?;1096		}10971098		Ok(())1099	}11001101	/// Delete collection property.1102	///1103	/// * `collection` - Collection handler.1104	/// * `sender` - The owner or administrator of the collection.1105	/// * `property` - The property to delete.1106	pub fn delete_collection_property(1107		collection: &CollectionHandle<T>,1108		sender: &T::CrossAccountId,1109		property_key: PropertyKey,1110	) -> DispatchResult {1111		collection.check_is_owner_or_admin(sender)?;11121113		CollectionProperties::<T>::try_mutate(collection.id, |properties| {1114			properties.remove(&property_key)1115		})1116		.map_err(<Error<T>>::from)?;11171118		Self::deposit_event(Event::CollectionPropertyDeleted(1119			collection.id,1120			property_key,1121		));11221123		Ok(())1124	}11251126	/// Delete collection properties.1127	///1128	/// * `collection` - Collection handler.1129	/// * `sender` - The owner or administrator of the collection.1130	/// * `properties` - The properties to delete.1131	#[transactional]1132	pub fn delete_collection_properties(1133		collection: &CollectionHandle<T>,1134		sender: &T::CrossAccountId,1135		property_keys: Vec<PropertyKey>,1136	) -> DispatchResult {1137		for key in property_keys {1138			Self::delete_collection_property(collection, sender, key)?;1139		}11401141		Ok(())1142	}11431144	/// Set collection propetry permission without any checks.1145	///1146	/// Used for migrations.1147	///1148	/// * `collection` - Collection handler.1149	/// * `property_permissions` - Property permissions.1150	pub fn set_property_permission_unchecked(1151		collection: CollectionId,1152		property_permission: PropertyKeyPermission,1153	) -> DispatchResult {1154		<CollectionPropertyPermissions<T>>::try_mutate(collection, |permissions| {1155			permissions.try_set(property_permission.key, property_permission.permission)1156		})1157		.map_err(<Error<T>>::from)?;1158		Ok(())1159	}11601161	/// Set collection property permission.1162	///1163	/// * `collection` - Collection handler.1164	/// * `sender` - The owner or administrator of the collection.1165	/// * `property_permission` - Property permission.1166	pub fn set_property_permission(1167		collection: &CollectionHandle<T>,1168		sender: &T::CrossAccountId,1169		property_permission: PropertyKeyPermission,1170	) -> DispatchResult {1171		collection.check_is_owner_or_admin(sender)?;11721173		let all_permissions = CollectionPropertyPermissions::<T>::get(collection.id);1174		let current_permission = all_permissions.get(&property_permission.key);1175		if matches![1176			current_permission,1177			Some(PropertyPermission { mutable: false, .. })1178		] {1179			return Err(<Error<T>>::NoPermission.into());1180		}11811182		CollectionPropertyPermissions::<T>::try_mutate(collection.id, |permissions| {1183			let property_permission = property_permission.clone();1184			permissions.try_set(property_permission.key, property_permission.permission)1185		})1186		.map_err(<Error<T>>::from)?;11871188		Self::deposit_event(Event::PropertyPermissionSet(1189			collection.id,1190			property_permission.key,1191		));11921193		Ok(())1194	}11951196	/// Set token property permission.1197	///1198	/// * `collection` - Collection handler.1199	/// * `sender` - The owner or administrator of the collection.1200	/// * `property_permissions` - Property permissions.1201	#[transactional]1202	pub fn set_token_property_permissions(1203		collection: &CollectionHandle<T>,1204		sender: &T::CrossAccountId,1205		property_permissions: Vec<PropertyKeyPermission>,1206	) -> DispatchResult {1207		for prop_pemission in property_permissions {1208			Self::set_property_permission(collection, sender, prop_pemission)?;1209		}12101211		Ok(())1212	}12131214	/// Get collection property.1215	pub fn get_collection_property(1216		collection_id: CollectionId,1217		key: &PropertyKey,1218	) -> Option<PropertyValue> {1219		Self::collection_properties(collection_id).get(key).cloned()1220	}12211222	/// Convert byte vector to property key vector.1223	pub fn bytes_keys_to_property_keys(1224		keys: Vec<Vec<u8>>,1225	) -> Result<Vec<PropertyKey>, DispatchError> {1226		keys.into_iter()1227			.map(|key| -> Result<PropertyKey, DispatchError> {1228				key.try_into()1229					.map_err(|_| <Error<T>>::PropertyKeyIsTooLong.into())1230			})1231			.collect::<Result<Vec<PropertyKey>, DispatchError>>()1232	}12331234	/// Get properties according to given keys.1235	pub fn filter_collection_properties(1236		collection_id: CollectionId,1237		keys: Option<Vec<PropertyKey>>,1238	) -> Result<Vec<Property>, DispatchError> {1239		let properties = Self::collection_properties(collection_id);12401241		let properties = keys1242			.map(|keys| {1243				keys.into_iter()1244					.filter_map(|key| {1245						properties.get(&key).map(|value| Property {1246							key,1247							value: value.clone(),1248						})1249					})1250					.collect()1251			})1252			.unwrap_or_else(|| {1253				properties1254					.into_iter()1255					.map(|(key, value)| Property { key, value })1256					.collect()1257			});12581259		Ok(properties)1260	}12611262	/// Get property permissions according to given keys.1263	pub fn filter_property_permissions(1264		collection_id: CollectionId,1265		keys: Option<Vec<PropertyKey>>,1266	) -> Result<Vec<PropertyKeyPermission>, DispatchError> {1267		let permissions = Self::property_permissions(collection_id);12681269		let key_permissions = keys1270			.map(|keys| {1271				keys.into_iter()1272					.filter_map(|key| {1273						permissions1274							.get(&key)1275							.map(|permission| PropertyKeyPermission {1276								key,1277								permission: permission.clone(),1278							})1279					})1280					.collect()1281			})1282			.unwrap_or_else(|| {1283				permissions1284					.into_iter()1285					.map(|(key, permission)| PropertyKeyPermission { key, permission })1286					.collect()1287			});12881289		Ok(key_permissions)1290	}12911292	/// Toggle `user` participation in the `collection`'s allow list.1293	pub fn toggle_allowlist(1294		collection: &CollectionHandle<T>,1295		sender: &T::CrossAccountId,1296		user: &T::CrossAccountId,1297		allowed: bool,1298	) -> DispatchResult {1299		collection.check_is_owner_or_admin(sender)?;13001301		// =========13021303		if allowed {1304			<Allowlist<T>>::insert((collection.id, user), true);1305		} else {1306			<Allowlist<T>>::remove((collection.id, user));1307		}13081309		Ok(())1310	}13111312	/// Toggle `user` participation in the `collection`'s admin list.1313	pub fn toggle_admin(1314		collection: &CollectionHandle<T>,1315		sender: &T::CrossAccountId,1316		user: &T::CrossAccountId,1317		admin: bool,1318	) -> DispatchResult {1319		collection.check_is_owner(sender)?;13201321		let was_admin = <IsAdmin<T>>::get((collection.id, user));1322		if was_admin == admin {1323			return Ok(());1324		}1325		let amount = <AdminAmount<T>>::get(collection.id);13261327		if admin {1328			let amount = amount1329				.checked_add(1)1330				.ok_or(<Error<T>>::CollectionAdminCountExceeded)?;1331			ensure!(1332				amount <= Self::collection_admins_limit(),1333				<Error<T>>::CollectionAdminCountExceeded,1334			);13351336			// =========13371338			<AdminAmount<T>>::insert(collection.id, amount);1339			<IsAdmin<T>>::insert((collection.id, user), true);1340		} else {1341			<AdminAmount<T>>::insert(collection.id, amount.saturating_sub(1));1342			<IsAdmin<T>>::remove((collection.id, user));1343		}13441345		Ok(())1346	}13471348	/// Merge set fields from `new_limit` to `old_limit`.1349	pub fn clamp_limits(1350		mode: CollectionMode,1351		old_limit: &CollectionLimits,1352		mut new_limit: CollectionLimits,1353	) -> Result<CollectionLimits, DispatchError> {1354		let limits = old_limit;1355		limit_default!(old_limit, new_limit,1356			account_token_ownership_limit => ensure!(1357				new_limit <= MAX_TOKEN_OWNERSHIP,1358				<Error<T>>::CollectionLimitBoundsExceeded,1359			),1360			sponsored_data_size => ensure!(1361				new_limit <= CUSTOM_DATA_LIMIT,1362				<Error<T>>::CollectionLimitBoundsExceeded,1363			),13641365			sponsored_data_rate_limit => {},1366			token_limit => ensure!(1367				old_limit >= new_limit && new_limit > 0,1368				<Error<T>>::CollectionTokenLimitExceeded1369			),13701371			sponsor_transfer_timeout(match mode {1372				CollectionMode::NFT => NFT_SPONSOR_TRANSFER_TIMEOUT,1373				CollectionMode::Fungible(_) => FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,1374				CollectionMode::ReFungible => REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,1375			}) => ensure!(1376				new_limit <= MAX_SPONSOR_TIMEOUT,1377				<Error<T>>::CollectionLimitBoundsExceeded,1378			),1379			sponsor_approve_timeout => {},1380			owner_can_transfer => ensure!(1381				!limits.owner_can_transfer_instaled() ||1382				old_limit || !new_limit,1383				<Error<T>>::OwnerPermissionsCantBeReverted,1384			),1385			owner_can_destroy => ensure!(1386				old_limit || !new_limit,1387				<Error<T>>::OwnerPermissionsCantBeReverted,1388			),1389			transfers_enabled => {},1390		);1391		Ok(new_limit)1392	}13931394	/// Merge set fields from `new_permission` to `old_permission`.1395	pub fn clamp_permissions(1396		_mode: CollectionMode,1397		old_permission: &CollectionPermissions,1398		mut new_permission: CollectionPermissions,1399	) -> Result<CollectionPermissions, DispatchError> {1400		limit_default_clone!(old_permission, new_permission,1401			access => {},1402			mint_mode => {},1403			nesting => { /* todo check for permissive, if only it gets out of benchmarks */ },1404		);1405		Ok(new_permission)1406	}1407}14081409/// Indicates unsupported methods by returning [Error::UnsupportedOperation].1410#[macro_export]1411macro_rules! unsupported {1412	() => {1413		Err(<Error<T>>::UnsupportedOperation.into())1414	};1415}14161417/// Return weights for various worst-case operations.1418pub trait CommonWeightInfo<CrossAccountId> {1419	/// Weight of item creation.1420	fn create_item() -> Weight;14211422	/// Weight of items creation.1423	fn create_multiple_items(amount: &[CreateItemData]) -> Weight;14241425	/// Weight of items creation.1426	fn create_multiple_items_ex(cost: &CreateItemExData<CrossAccountId>) -> Weight;14271428	/// The weight of the burning item.1429	fn burn_item() -> Weight;14301431	/// Property setting weight.1432	///1433	/// * `amount`- The number of properties to set.1434	fn set_collection_properties(amount: u32) -> Weight;14351436	/// Collection property deletion weight.1437	///1438	/// * `amount`- The number of properties to set.1439	fn delete_collection_properties(amount: u32) -> Weight;14401441	/// Token property setting weight.1442	///1443	/// * `amount`- The number of properties to set.1444	fn set_token_properties(amount: u32) -> Weight;14451446	/// Token property deletion weight.1447	///1448	/// * `amount`- The number of properties to delete.1449	fn delete_token_properties(amount: u32) -> Weight;14501451	/// Token property permissions set weight.1452	///1453	/// * `amount`- The number of property permissions to set.1454	fn set_token_property_permissions(amount: u32) -> Weight;14551456	/// Transfer price of the token or its parts.1457	fn transfer() -> Weight;14581459	/// The price of setting the permission of the operation from another user.1460	fn approve() -> Weight;14611462	/// Transfer price from another user.1463	fn transfer_from() -> Weight;14641465	/// The price of burning a token from another user.1466	fn burn_from() -> Weight;14671468	/// Differs from burn_item in case of Fungible and Refungible, as it should burn1469	/// whole users's balance1470	///1471	/// This method shouldn't be used directly, as it doesn't count breadth price, use [burn_recursively](CommonWeightInfo::burn_recursively) instead1472	fn burn_recursively_self_raw() -> Weight;14731474	/// Cost of iterating over `amount` children while burning, without counting child burning itself1475	///1476	/// This method shouldn't be used directly, as it doesn't count depth price, use [burn_recursively](CommonWeightInfo::burn_recursively) instead1477	fn burn_recursively_breadth_raw(amount: u32) -> Weight;14781479	/// The price of recursive burning a token.1480	///1481	/// `max_selfs` -1482	fn burn_recursively(max_selfs: u32, max_breadth: u32) -> Weight {1483		Self::burn_recursively_self_raw()1484			.saturating_mul(max_selfs.max(1) as u64)1485			.saturating_add(Self::burn_recursively_breadth_raw(max_breadth))1486	}1487}14881489/// Weight info extension trait for refungible pallet.1490pub trait RefungibleExtensionsWeightInfo {1491	/// Weight of token repartition.1492	fn repartition() -> Weight;1493}14941495/// Common collection operations.1496///1497/// It wraps methods in Fungible, Nonfungible and Refungible pallets1498/// and adds weight info.1499pub trait CommonCollectionOperations<T: Config> {1500	/// Create token.1501	///1502	/// * `sender` - The user who mint the token and pays for the transaction.1503	/// * `to` - The user who will own the token.1504	/// * `data` - Token data.1505	/// * `nesting_budget` - A budget that can be spent on nesting tokens.1506	fn create_item(1507		&self,1508		sender: T::CrossAccountId,1509		to: T::CrossAccountId,1510		data: CreateItemData,1511		nesting_budget: &dyn Budget,1512	) -> DispatchResultWithPostInfo;15131514	/// Create multiple tokens.1515	///1516	/// * `sender` - The user who mint the token and pays for the transaction.1517	/// * `to` - The user who will own the token.1518	/// * `data` - Token data.1519	/// * `nesting_budget` - A budget that can be spent on nesting tokens.1520	fn create_multiple_items(1521		&self,1522		sender: T::CrossAccountId,1523		to: T::CrossAccountId,1524		data: Vec<CreateItemData>,1525		nesting_budget: &dyn Budget,1526	) -> DispatchResultWithPostInfo;15271528	/// Create multiple tokens.1529	///1530	/// * `sender` - The user who mint the token and pays for the transaction.1531	/// * `to` - The user who will own the token.1532	/// * `data` - Token data.1533	/// * `nesting_budget` - A budget that can be spent on nesting tokens.1534	fn create_multiple_items_ex(1535		&self,1536		sender: T::CrossAccountId,1537		data: CreateItemExData<T::CrossAccountId>,1538		nesting_budget: &dyn Budget,1539	) -> DispatchResultWithPostInfo;15401541	/// Burn token.1542	///1543	/// * `sender` - The user who owns the token.1544	/// * `token` - Token id that will burned.1545	/// * `amount` - The number of parts of the token that will be burned.1546	fn burn_item(1547		&self,1548		sender: T::CrossAccountId,1549		token: TokenId,1550		amount: u128,1551	) -> DispatchResultWithPostInfo;15521553	/// Burn token and all nested tokens recursievly.1554	///1555	/// * `sender` - The user who owns the token.1556	/// * `token` - Token id that will burned.1557	/// * `self_budget` - The budget that can be spent on burning tokens.1558	/// * `breadth_budget` - The budget that can be spent on burning nested tokens.1559	fn burn_item_recursively(1560		&self,1561		sender: T::CrossAccountId,1562		token: TokenId,1563		self_budget: &dyn Budget,1564		breadth_budget: &dyn Budget,1565	) -> DispatchResultWithPostInfo;15661567	/// Set collection properties.1568	///1569	/// * `sender` - Must be either the owner of the collection or its admin.1570	/// * `properties` - Properties to be set.1571	fn set_collection_properties(1572		&self,1573		sender: T::CrossAccountId,1574		properties: Vec<Property>,1575	) -> DispatchResultWithPostInfo;15761577	/// Delete collection properties.1578	///1579	/// * `sender` - Must be either the owner of the collection or its admin.1580	/// * `properties` - The properties to be removed.1581	fn delete_collection_properties(1582		&self,1583		sender: &T::CrossAccountId,1584		property_keys: Vec<PropertyKey>,1585	) -> DispatchResultWithPostInfo;15861587	/// Set token properties.1588	///1589	/// The appropriate [PropertyPermission] for the token property1590	/// must be set with [Self::set_token_property_permissions].1591	///1592	/// * `sender` - Must be either the owner of the token or its admin.1593	/// * `token_id` - The token for which the properties are being set.1594	/// * `properties` - Properties to be set.1595	/// * `budget` - Budget for setting properties.1596	fn set_token_properties(1597		&self,1598		sender: T::CrossAccountId,1599		token_id: TokenId,1600		properties: Vec<Property>,1601		budget: &dyn Budget,1602	) -> DispatchResultWithPostInfo;16031604	/// Remove token properties.1605	///1606	/// The appropriate [PropertyPermission] for the token property1607	/// must be set with [Self::set_token_property_permissions].1608	///1609	/// * `sender` - Must be either the owner of the token or its admin.1610	/// * `token_id` - The token for which the properties are being remove.1611	/// * `property_keys` - Keys to remove corresponding properties.1612	/// * `budget` - Budget for removing properties.1613	fn delete_token_properties(1614		&self,1615		sender: T::CrossAccountId,1616		token_id: TokenId,1617		property_keys: Vec<PropertyKey>,1618		budget: &dyn Budget,1619	) -> DispatchResultWithPostInfo;16201621	/// Set token property permissions.1622	///1623	/// * `sender` - Must be either the owner of the token or its admin.1624	/// * `token_id` - The token for which the properties are being set.1625	/// * `properties` - Properties to be set.1626	/// * `budget` - Budget for setting properties.1627	fn set_token_property_permissions(1628		&self,1629		sender: &T::CrossAccountId,1630		property_permissions: Vec<PropertyKeyPermission>,1631	) -> DispatchResultWithPostInfo;16321633	/// Transfer amount of token pieces.1634	///1635	/// * `sender` - Donor user.1636	/// * `to` - Recepient user.1637	/// * `token` - The token of which parts are being sent.1638	/// * `amount` - The number of parts of the token that will be transferred.1639	/// * `budget` - The maximum budget that can be spent on the transfer.1640	fn transfer(1641		&self,1642		sender: T::CrossAccountId,1643		to: T::CrossAccountId,1644		token: TokenId,1645		amount: u128,1646		budget: &dyn Budget,1647	) -> DispatchResultWithPostInfo;16481649	/// Grant access to another account to transfer parts of the token owned by the calling user via [Self::transfer_from].1650	///1651	/// * `sender` - The user who grants access to the token.1652	/// * `spender` - The user to whom the rights are granted.1653	/// * `token` - The token to which access is granted.1654	/// * `amount` - The amount of pieces that another user can dispose of.1655	fn approve(1656		&self,1657		sender: T::CrossAccountId,1658		spender: T::CrossAccountId,1659		token: TokenId,1660		amount: u128,1661	) -> DispatchResultWithPostInfo;16621663	/// Send parts of a token owned by another user.1664	///1665	/// Before calling this method, you must grant rights to the calling user via [Self::approve].1666	///1667	/// * `sender` - The user who has access to the token.1668	/// * `from` - The user who owns the token.1669	/// * `to` - Recepient user.1670	/// * `token` - The token of which parts are being sent.1671	/// * `amount` - The number of parts of the token that will be transferred.1672	/// * `budget` - The maximum budget that can be spent on the transfer.1673	fn transfer_from(1674		&self,1675		sender: T::CrossAccountId,1676		from: T::CrossAccountId,1677		to: T::CrossAccountId,1678		token: TokenId,1679		amount: u128,1680		budget: &dyn Budget,1681	) -> DispatchResultWithPostInfo;16821683	/// Burn parts of a token owned by another user.1684	///1685	/// Before calling this method, you must grant rights to the calling user via [Self::approve].1686	///1687	/// * `sender` - The user who has access to the token.1688	/// * `from` - The user who owns the token.1689	/// * `token` - The token of which parts are being sent.1690	/// * `amount` - The number of parts of the token that will be transferred.1691	/// * `budget` - The maximum budget that can be spent on the burn.1692	fn burn_from(1693		&self,1694		sender: T::CrossAccountId,1695		from: T::CrossAccountId,1696		token: TokenId,1697		amount: u128,1698		budget: &dyn Budget,1699	) -> DispatchResultWithPostInfo;17001701	/// Check permission to nest token.1702	///1703	/// * `sender` - The user who initiated the check.1704	/// * `from` - The token that is checked for embedding.1705	/// * `under` - Token under which to check.1706	/// * `budget` - The maximum budget that can be spent on the check.1707	fn check_nesting(1708		&self,1709		sender: T::CrossAccountId,1710		from: (CollectionId, TokenId),1711		under: TokenId,1712		budget: &dyn Budget,1713	) -> DispatchResult;17141715	/// Nest one token into another.1716	///1717	/// * `under` - Token holder.1718	/// * `to_nest` - Nested token.1719	fn nest(&self, under: TokenId, to_nest: (CollectionId, TokenId));17201721	/// Unnest token.1722	///1723	/// * `under` - Token holder.1724	/// * `to_nest` - Token to unnest.1725	fn unnest(&self, under: TokenId, to_nest: (CollectionId, TokenId));17261727	/// Get all user tokens.1728	///1729	/// * `account` - Account for which you need to get tokens.1730	fn account_tokens(&self, account: T::CrossAccountId) -> Vec<TokenId>;17311732	/// Get all the tokens in the collection.1733	fn collection_tokens(&self) -> Vec<TokenId>;17341735	/// Check if the token exists.1736	///1737	/// * `token` - Id token to check.1738	fn token_exists(&self, token: TokenId) -> bool;17391740	/// Get the id of the last minted token.1741	fn last_token_id(&self) -> TokenId;17421743	/// Get the owner of the token.1744	///1745	/// * `token` - The token for which you need to find out the owner.1746	fn token_owner(&self, token: TokenId) -> Option<T::CrossAccountId>;17471748	/// Get the value of the token property by key.1749	///1750	/// * `token` - Token property to get.1751	/// * `key` - Property name.1752	fn token_property(&self, token_id: TokenId, key: &PropertyKey) -> Option<PropertyValue>;17531754	/// Get a set of token properties by key vector.1755	///1756	/// * `token` - Token property to get.1757	/// * `keys` - Vector of keys. If this parameter is [None](sp_std::result::Result),1758	/// then all properties are returned.1759	fn token_properties(&self, token: TokenId, keys: Option<Vec<PropertyKey>>) -> Vec<Property>;17601761	/// Amount of unique collection tokens1762	fn total_supply(&self) -> u32;17631764	/// Amount of different tokens account has.1765	///1766	/// * `account` - The account for which need to get the balance.1767	fn account_balance(&self, account: T::CrossAccountId) -> u32;17681769	/// Amount of specific token account have.1770	fn balance(&self, account: T::CrossAccountId, token: TokenId) -> u128;17711772	/// Amount of token pieces1773	fn total_pieces(&self, token: TokenId) -> Option<u128>;17741775	/// Get the number of parts of the token that a trusted user can manage.1776	///1777	/// * `sender` - Trusted user.1778	/// * `spender` - Owner of the token.1779	/// * `token` - The token for which to get the value.1780	fn allowance(1781		&self,1782		sender: T::CrossAccountId,1783		spender: T::CrossAccountId,1784		token: TokenId,1785	) -> u128;17861787	/// Get extension for RFT collection.1788	fn refungible_extensions(&self) -> Option<&dyn RefungibleExtensions<T>>;1789}17901791/// Extension for RFT collection.1792pub trait RefungibleExtensions<T>1793where1794	T: Config,1795{1796	/// Change the number of parts of the token.1797	///1798	/// When the value changes down, this function is equivalent to burning parts of the token.1799	///1800	/// * `sender` - The user calling the repartition operation. Must be the owner of the token.1801	/// * `token` - The token for which you want to change the number of parts.1802	/// * `amount` - The new value of the parts of the token.1803	fn repartition(1804		&self,1805		sender: &T::CrossAccountId,1806		token: TokenId,1807		amount: u128,1808	) -> DispatchResultWithPostInfo;1809}18101811/// Merge [DispatchResult] with [Weight] into [DispatchResultWithPostInfo].1812///1813/// Used for [CommonCollectionOperations] implementations and flexible enough to do so.1814pub fn with_weight(res: DispatchResult, weight: Weight) -> DispatchResultWithPostInfo {1815	let post_info = PostDispatchInfo {1816		actual_weight: Some(weight),1817		pays_fee: Pays::Yes,1818	};1819	match res {1820		Ok(()) => Ok(post_info),1821		Err(error) => Err(DispatchErrorWithPostInfo { post_info, error }),1822	}1823}18241825impl<T: Config> From<PropertiesError> for Error<T> {1826	fn from(error: PropertiesError) -> Self {1827		match error {1828			PropertiesError::NoSpaceForProperty => Self::NoSpaceForProperty,1829			PropertiesError::PropertyLimitReached => Self::PropertyLimitReached,1830			PropertiesError::InvalidCharacterInPropertyKey => Self::InvalidCharacterInPropertyKey,1831			PropertiesError::PropertyKeyIsTooLong => Self::PropertyKeyIsTooLong,1832			PropertiesError::EmptyPropertyKey => Self::EmptyPropertyKey,1833		}1834	}1835}
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 functions for:24//!25//! - Setting and approving collection soponsor.26//! - Get\set\delete allow list.27//! - Get\set\delete collection properties.28//! - Get\set\delete collection property permissions.29//! - Get\set\delete token property permissions.30//! - Get\set\delete collection administrators.31//! - Checking access permissions.32//! - Provides an interface for common collection operations for different collection types.33//! - Provides dispatching for implementations of common collection operations, see [dispatch] module.34//! - Provides functionality of collection into evm, see [erc] and [eth] module.35//!36//! ### Terminology37//! **Collection sponsor** - For the collection, you can set a sponsor, at whose expense it will38//! be possible to mint tokens.39//!40//! **Allow list** - List of users who have the right to minting tokens.41//!42//! **Collection properties** - Collection properties are simply key-value stores where various43//! metadata can be placed.44//!45//! **Collection property permissions** - For each property in the collection can be set permission46//! to change, see [PropertyPermission].47//!48//! **Permissions on token properties** - Similar to _permissions on collection properties_,49//! only restrictions apply to token properties.50//!51//! **Collection administrator** - For a collection, you can set administrators who have the right52//! to most actions on the collection.5354#![warn(missing_docs)]55#![cfg_attr(not(feature = "std"), no_std)]56extern crate alloc;5758use core::ops::{Deref, DerefMut};59use pallet_evm_coder_substrate::{SubstrateRecorder, WithRecorder};60use sp_std::vec::Vec;61use pallet_evm::{account::CrossAccountId, Pallet as PalletEvm};62use evm_coder::ToLog;63use frame_support::{64	dispatch::{DispatchErrorWithPostInfo, DispatchResultWithPostInfo, Weight, PostDispatchInfo},65	ensure,66	traits::{Imbalance, Get, Currency, WithdrawReasons, ExistenceRequirement},67	weights::Pays,68	transactional,69};70use pallet_evm::GasWeightMapping;71use up_data_structs::{72	COLLECTION_NUMBER_LIMIT,73	Collection,74	RpcCollection,75	CollectionId,76	CreateItemData,77	MAX_TOKEN_PREFIX_LENGTH,78	COLLECTION_ADMINS_LIMIT,79	TokenId,80	TokenChild,81	CollectionStats,82	MAX_TOKEN_OWNERSHIP,83	CollectionMode,84	NFT_SPONSOR_TRANSFER_TIMEOUT,85	FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,86	REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,87	MAX_SPONSOR_TIMEOUT,88	CUSTOM_DATA_LIMIT,89	CollectionLimits,90	CreateCollectionData,91	SponsorshipState,92	CreateItemExData,93	SponsoringRateLimit,94	budget::Budget,95	PhantomType,96	Property,97	Properties,98	PropertiesPermissionMap,99	PropertyKey,100	PropertyValue,101	PropertyPermission,102	PropertiesError,103	PropertyKeyPermission,104	TokenData,105	TrySetProperty,106	PropertyScope,107	// RMRK108	RmrkCollectionInfo,109	RmrkInstanceInfo,110	RmrkResourceInfo,111	RmrkPropertyInfo,112	RmrkBaseInfo,113	RmrkPartType,114	RmrkBoundedTheme,115	RmrkNftChild,116	CollectionPermissions,117	SchemaVersion,118};119120pub use pallet::*;121use sp_core::H160;122use sp_runtime::{ArithmeticError, DispatchError, DispatchResult};123#[cfg(feature = "runtime-benchmarks")]124pub mod benchmarking;125pub mod dispatch;126pub mod erc;127pub mod eth;128pub mod weights;129130/// Weight info.131pub type SelfWeightOf<T> = <T as Config>::WeightInfo;132133/// Collection handle contains information about collection data and id.134/// Also provides functionality to count consumed gas.135/// CollectionHandle is used as a generic wrapper for collections of all types.136/// It allows to perform common operations and queries on any collection type,137/// both completely general for all, as well as their respective implementations of [CommonCollectionOperations].138#[must_use = "Should call submit_logs or save, otherwise some data will be lost for evm side"]139pub struct CollectionHandle<T: Config> {140	/// Collection id141	pub id: CollectionId,142	collection: Collection<T::AccountId>,143	/// Substrate recorder for counting consumed gas144	pub recorder: SubstrateRecorder<T>,145}146147impl<T: Config> WithRecorder<T> for CollectionHandle<T> {148	fn recorder(&self) -> &SubstrateRecorder<T> {149		&self.recorder150	}151	fn into_recorder(self) -> SubstrateRecorder<T> {152		self.recorder153	}154}155156impl<T: Config> CollectionHandle<T> {157	/// Same as [CollectionHandle::new] but with an explicit gas limit.158	pub fn new_with_gas_limit(id: CollectionId, gas_limit: u64) -> Option<Self> {159		<CollectionById<T>>::get(id).map(|collection| Self {160			id,161			collection,162			recorder: SubstrateRecorder::new(gas_limit),163		})164	}165166	/// Same as [CollectionHandle::new] but with an existed [SubstrateRecorder].167	pub fn new_with_recorder(id: CollectionId, recorder: SubstrateRecorder<T>) -> Option<Self> {168		<CollectionById<T>>::get(id).map(|collection| Self {169			id,170			collection,171			recorder,172		})173	}174175	/// Retrives collection data from storage and creates collection handle with default parameters.176	/// If collection not found return `None`177	pub fn new(id: CollectionId) -> Option<Self> {178		Self::new_with_gas_limit(id, u64::MAX)179	}180181	/// Same as [CollectionHandle::new] but if collection not found [Error::CollectionNotFound] returned.182	pub fn try_get(id: CollectionId) -> Result<Self, DispatchError> {183		Ok(Self::new(id).ok_or(<Error<T>>::CollectionNotFound)?)184	}185186	/// Consume gas for reading.187	pub fn consume_store_reads(&self, reads: u64) -> evm_coder::execution::Result<()> {188		self.recorder189			.consume_gas(T::GasWeightMapping::weight_to_gas(190				<T as frame_system::Config>::DbWeight::get()191					.read192					.saturating_mul(reads),193			))194	}195196	/// Consume gas for writing.197	pub fn consume_store_writes(&self, writes: u64) -> evm_coder::execution::Result<()> {198		self.recorder199			.consume_gas(T::GasWeightMapping::weight_to_gas(200				<T as frame_system::Config>::DbWeight::get()201					.write202					.saturating_mul(writes),203			))204	}205206	/// Save collection to storage.207	pub fn save(self) -> DispatchResult {208		<CollectionById<T>>::insert(self.id, self.collection);209		Ok(())210	}211212	/// Set collection sponsor.213	///214	/// Unique collections allows sponsoring for certain actions.215	/// This method allows you to set the sponsor of the collection.216	/// In order for sponsorship to become active, it must be confirmed through [Self::confirm_sponsorship].217	pub fn set_sponsor(&mut self, sponsor: T::AccountId) -> DispatchResult {218		self.collection.sponsorship = SponsorshipState::Unconfirmed(sponsor);219		Ok(())220	}221222	/// Confirm sponsorship223	///224	/// In order for the sponsorship to become active, the user set as the sponsor must confirm their participation.225	/// Before confirming sponsorship, the user must be specified as the sponsor of the collection via [Self::set_sponsor].226	pub fn confirm_sponsorship(&mut self, sender: &T::AccountId) -> Result<bool, DispatchError> {227		if self.collection.sponsorship.pending_sponsor() != Some(sender) {228			return Ok(false);229		}230231		self.collection.sponsorship = SponsorshipState::Confirmed(sender.clone());232		Ok(true)233	}234235	/// Checks that the collection was created with, and must be operated upon through **Unique API**.236	/// Now check only the `external_collection` flag and if it's **true**, then return [Error::CollectionIsExternal] error.237	pub fn check_is_internal(&self) -> DispatchResult {238		if self.external_collection {239			return Err(<Error<T>>::CollectionIsExternal)?;240		}241242		Ok(())243	}244245	/// Checks that the collection was created with, and must be operated upon through an **assimilated API**.246	/// Now check only the `external_collection` flag and if it's **false**, then return [Error::CollectionIsInternal] error.247	pub fn check_is_external(&self) -> DispatchResult {248		if !self.external_collection {249			return Err(<Error<T>>::CollectionIsInternal)?;250		}251252		Ok(())253	}254}255256impl<T: Config> Deref for CollectionHandle<T> {257	type Target = Collection<T::AccountId>;258259	fn deref(&self) -> &Self::Target {260		&self.collection261	}262}263264impl<T: Config> DerefMut for CollectionHandle<T> {265	fn deref_mut(&mut self) -> &mut Self::Target {266		&mut self.collection267	}268}269270impl<T: Config> CollectionHandle<T> {271	/// Checks if the `user` is the owner of the collection.272	pub fn check_is_owner(&self, user: &T::CrossAccountId) -> DispatchResult {273		ensure!(*user.as_sub() == self.owner, <Error<T>>::NoPermission);274		Ok(())275	}276277	/// Returns **true** if the `user` is the owner or administrator of the collection.278	pub fn is_owner_or_admin(&self, user: &T::CrossAccountId) -> bool {279		*user.as_sub() == self.owner || <IsAdmin<T>>::get((self.id, user))280	}281282	/// Checks if the `user` is the owner or administrator of the collection.283	pub fn check_is_owner_or_admin(&self, user: &T::CrossAccountId) -> DispatchResult {284		ensure!(self.is_owner_or_admin(user), <Error<T>>::NoPermission);285		Ok(())286	}287288	/// Return **true** if `user` was not allowed to have tokens, and he can ignore such restrictions.289	pub fn ignores_allowance(&self, user: &T::CrossAccountId) -> bool {290		self.limits.owner_can_transfer() && self.is_owner_or_admin(user)291	}292293	/// Return **true** if `user` does not have enough token parts, and he can ignore such restrictions.294	pub fn ignores_owned_amount(&self, user: &T::CrossAccountId) -> bool {295		self.limits.owner_can_transfer() && self.is_owner_or_admin(user)296	}297298	/// Checks if the user is in the allow list. If not [Error::AddressNotInAllowlist] returns.299	pub fn check_allowlist(&self, user: &T::CrossAccountId) -> DispatchResult {300		ensure!(301			<Allowlist<T>>::get((self.id, user)),302			<Error<T>>::AddressNotInAllowlist303		);304		Ok(())305	}306}307308#[frame_support::pallet]309pub mod pallet {310	use super::*;311	use pallet_evm::account;312	use dispatch::CollectionDispatch;313	use frame_support::{Blake2_128Concat, pallet_prelude::*, storage::Key, traits::StorageVersion};314	use frame_system::pallet_prelude::*;315	use frame_support::traits::Currency;316	use up_data_structs::{TokenId, mapping::TokenAddressMapping};317	use scale_info::TypeInfo;318	use weights::WeightInfo;319320	#[pallet::config]321	pub trait Config:322		frame_system::Config323		+ pallet_evm_coder_substrate::Config324		+ pallet_evm::Config325		+ TypeInfo326		+ account::Config327	{328		/// Weight info.329		type WeightInfo: WeightInfo;330331		/// Events compatible with [frame_system::Config::Event].332		type Event: IsType<<Self as frame_system::Config>::Event> + From<Event<Self>>;333334		/// Currency.335		type Currency: Currency<Self::AccountId>;336337		/// Price getter to create the collection.338		#[pallet::constant]339		type CollectionCreationPrice: Get<340			<<Self as Config>::Currency as Currency<Self::AccountId>>::Balance,341		>;342343		/// Collection dispatcher.344		type CollectionDispatch: CollectionDispatch<Self>;345346		/// Treasury account id getter.347		type TreasuryAccountId: Get<Self::AccountId>;348349		/// Contract address getter.350		type ContractAddress: Get<H160>;351352		/// Mapper for tokens to Etherium addresses.353		type EvmTokenAddressMapping: TokenAddressMapping<H160>;354355		/// Mapper for tokens to [CrossAccountId].356		type CrossTokenAddressMapping: TokenAddressMapping<Self::CrossAccountId>;357	}358359	const STORAGE_VERSION: StorageVersion = StorageVersion::new(1);360361	#[pallet::pallet]362	#[pallet::storage_version(STORAGE_VERSION)]363	#[pallet::generate_store(pub(super) trait Store)]364	pub struct Pallet<T>(_);365366	#[pallet::extra_constants]367	impl<T: Config> Pallet<T> {368		/// Maximum admins per collection.369		pub fn collection_admins_limit() -> u32 {370			COLLECTION_ADMINS_LIMIT371		}372	}373374	#[pallet::event]375	#[pallet::generate_deposit(pub fn deposit_event)]376	pub enum Event<T: Config> {377		/// New collection was created378		CollectionCreated(379			/// Globally unique identifier of newly created collection.380			CollectionId,381			/// [CollectionMode] converted into _u8_.382			u8,383			/// Collection owner.384			T::AccountId,385		),386387		/// New collection was destroyed388		CollectionDestroyed(389			/// Globally unique identifier of collection.390			CollectionId,391		),392393		/// New item was created.394		ItemCreated(395			/// Id of the collection where item was created.396			CollectionId,397			/// Id of an item. Unique within the collection.398			TokenId,399			/// Owner of newly created item400			T::CrossAccountId,401			/// Always 1 for NFT402			u128,403		),404405		/// Collection item was burned.406		ItemDestroyed(407			/// Id of the collection where item was destroyed.408			CollectionId,409			/// Identifier of burned NFT.410			TokenId,411			/// Which user has destroyed its tokens.412			T::CrossAccountId,413			/// Amount of token pieces destroed. Always 1 for NFT.414			u128,415		),416417		/// Item was transferred418		Transfer(419			/// Id of collection to which item is belong.420			CollectionId,421			/// Id of an item.422			TokenId,423			/// Original owner of item.424			T::CrossAccountId,425			/// New owner of item.426			T::CrossAccountId,427			/// Amount of token pieces transfered. Always 1 for NFT.428			u128,429		),430431		/// Amount pieces of token owned by `sender` was approved for `spender`.432		Approved(433			/// Id of collection to which item is belong.434			CollectionId,435			/// Id of an item.436			TokenId,437			/// Original owner of item.438			T::CrossAccountId,439			/// Id for which the approval was granted.440			T::CrossAccountId,441			/// Amount of token pieces transfered. Always 1 for NFT.442			u128,443		),444445		/// The colletion property has been set.446		CollectionPropertySet(447			/// Id of collection to which property has been set.448			CollectionId,449			/// The property that was set.450			PropertyKey,451		),452453		/// The property has been deleted.454		CollectionPropertyDeleted(455			/// Id of collection to which property has been deleted.456			CollectionId,457			/// The property that was deleted.458			PropertyKey,459		),460461		/// The token property has been set.462		TokenPropertySet(463			/// Identifier of the collection whose token has the property set.464			CollectionId,465			/// The token for which the property was set.466			TokenId,467			/// The property that was set.468			PropertyKey,469		),470471		/// The token property has been deleted.472		TokenPropertyDeleted(473			/// Identifier of the collection whose token has the property deleted.474			CollectionId,475			/// The token for which the property was deleted.476			TokenId,477			/// The property that was deleted.478			PropertyKey,479		),480481		/// The colletion property permission has been set.482		PropertyPermissionSet(483			/// Id of collection to which property permission has been set.484			CollectionId,485			/// The property permission that was set.486			PropertyKey,487		),488	}489490	#[pallet::error]491	pub enum Error<T> {492		/// This collection does not exist.493		CollectionNotFound,494		/// Sender parameter and item owner must be equal.495		MustBeTokenOwner,496		/// No permission to perform action497		NoPermission,498		/// Destroying only empty collections is allowed499		CantDestroyNotEmptyCollection,500		/// Collection is not in mint mode.501		PublicMintingNotAllowed,502		/// Address is not in allow list.503		AddressNotInAllowlist,504505		/// Collection name can not be longer than 63 char.506		CollectionNameLimitExceeded,507		/// Collection description can not be longer than 255 char.508		CollectionDescriptionLimitExceeded,509		/// Token prefix can not be longer than 15 char.510		CollectionTokenPrefixLimitExceeded,511		/// Total collections bound exceeded.512		TotalCollectionsLimitExceeded,513		/// Exceeded max admin count514		CollectionAdminCountExceeded,515		/// Collection limit bounds per collection exceeded516		CollectionLimitBoundsExceeded,517		/// Tried to enable permissions which are only permitted to be disabled518		OwnerPermissionsCantBeReverted,519		/// Collection settings not allowing items transferring520		TransferNotAllowed,521		/// Account token limit exceeded per collection522		AccountTokenLimitExceeded,523		/// Collection token limit exceeded524		CollectionTokenLimitExceeded,525		/// Metadata flag frozen526		MetadataFlagFrozen,527528		/// Item not exists.529		TokenNotFound,530		/// Item balance not enough.531		TokenValueTooLow,532		/// Requested value more than approved.533		ApprovedValueTooLow,534		/// Tried to approve more than owned535		CantApproveMoreThanOwned,536537		/// Can't transfer tokens to ethereum zero address538		AddressIsZero,539		/// Target collection doesn't supports this operation540		UnsupportedOperation,541542		/// Not sufficient funds to perform action543		NotSufficientFounds,544545		/// User not passed nesting rule546		UserIsNotAllowedToNest,547		/// Only tokens from specific collections may nest tokens under this548		SourceCollectionIsNotAllowedToNest,549550		/// Tried to store more data than allowed in collection field551		CollectionFieldSizeExceeded,552553		/// Tried to store more property data than allowed554		NoSpaceForProperty,555556		/// Tried to store more property keys than allowed557		PropertyLimitReached,558559		/// Property key is too long560		PropertyKeyIsTooLong,561562		/// Only ASCII letters, digits, and '_', '-' are allowed563		InvalidCharacterInPropertyKey,564565		/// Empty property keys are forbidden566		EmptyPropertyKey,567568		/// Tried to access an external collection with an internal API569		CollectionIsExternal,570571		/// Tried to access an internal collection with an external API572		CollectionIsInternal,573	}574575	/// Storage of the count of created collections.576	#[pallet::storage]577	pub type CreatedCollectionCount<T> = StorageValue<Value = CollectionId, QueryKind = ValueQuery>;578579	/// Storage of the count of deleted collections.580	#[pallet::storage]581	pub type DestroyedCollectionCount<T> =582		StorageValue<Value = CollectionId, QueryKind = ValueQuery>;583584	/// Storage of collection info.585	#[pallet::storage]586	pub type CollectionById<T> = StorageMap<587		Hasher = Blake2_128Concat,588		Key = CollectionId,589		Value = Collection<<T as frame_system::Config>::AccountId>,590		QueryKind = OptionQuery,591	>;592593	/// Storage of collection properties.594	#[pallet::storage]595	#[pallet::getter(fn collection_properties)]596	pub type CollectionProperties<T> = StorageMap<597		Hasher = Blake2_128Concat,598		Key = CollectionId,599		Value = Properties,600		QueryKind = ValueQuery,601		OnEmpty = up_data_structs::CollectionProperties,602	>;603604	/// Storage of collection properties permissions.605	#[pallet::storage]606	#[pallet::getter(fn property_permissions)]607	pub type CollectionPropertyPermissions<T> = StorageMap<608		Hasher = Blake2_128Concat,609		Key = CollectionId,610		Value = PropertiesPermissionMap,611		QueryKind = ValueQuery,612	>;613614	/// Storage of collection admins count.615	#[pallet::storage]616	pub type AdminAmount<T> = StorageMap<617		Hasher = Blake2_128Concat,618		Key = CollectionId,619		Value = u32,620		QueryKind = ValueQuery,621	>;622623	/// List of collection admins624	#[pallet::storage]625	pub type IsAdmin<T: Config> = StorageNMap<626		Key = (627			Key<Blake2_128Concat, CollectionId>,628			Key<Blake2_128Concat, T::CrossAccountId>,629		),630		Value = bool,631		QueryKind = ValueQuery,632	>;633634	/// Allowlisted collection users635	#[pallet::storage]636	pub type Allowlist<T: Config> = StorageNMap<637		Key = (638			Key<Blake2_128Concat, CollectionId>,639			Key<Blake2_128Concat, T::CrossAccountId>,640		),641		Value = bool,642		QueryKind = ValueQuery,643	>;644645	/// Not used by code, exists only to provide some types to metadata.646	#[pallet::storage]647	pub type DummyStorageValue<T: Config> = StorageValue<648		Value = (649			CollectionStats,650			CollectionId,651			TokenId,652			TokenChild,653			PhantomType<(654				TokenData<T::CrossAccountId>,655				RpcCollection<T::AccountId>,656				// RMRK657				RmrkCollectionInfo<T::AccountId>,658				RmrkInstanceInfo<T::AccountId>,659				RmrkResourceInfo,660				RmrkPropertyInfo,661				RmrkBaseInfo<T::AccountId>,662				RmrkPartType,663				RmrkBoundedTheme,664				RmrkNftChild,665			)>,666		),667		QueryKind = OptionQuery,668	>;669670	#[pallet::hooks]671	impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {672		fn on_runtime_upgrade() -> Weight {673			if StorageVersion::get::<Pallet<T>>() < StorageVersion::new(1) {674				use up_data_structs::{CollectionVersion1, CollectionVersion2};675				<CollectionById<T>>::translate::<CollectionVersion1<T::AccountId>, _>(|id, v| {676					let mut props = Vec::new();677					if !v.offchain_schema.is_empty() {678						props.push(Property {679							key: b"_old_offchainSchema".to_vec().try_into().unwrap(),680							value: v681								.offchain_schema682								.clone()683								.into_inner()684								.try_into()685								.expect("offchain schema too big"),686						});687					}688					if !v.variable_on_chain_schema.is_empty() {689						props.push(Property {690							key: b"_old_variableOnChainSchema".to_vec().try_into().unwrap(),691							value: v692								.variable_on_chain_schema693								.clone()694								.into_inner()695								.try_into()696								.expect("offchain schema too big"),697						});698					}699					if !v.const_on_chain_schema.is_empty() {700						props.push(Property {701							key: b"_old_constOnChainSchema".to_vec().try_into().unwrap(),702							value: v703								.const_on_chain_schema704								.clone()705								.into_inner()706								.try_into()707								.expect("offchain schema too big"),708						});709					}710					props.push(Property {711						key: b"_old_schemaVersion".to_vec().try_into().unwrap(),712						value: match v.schema_version {713							SchemaVersion::ImageURL => b"ImageUrl".as_slice(),714							SchemaVersion::Unique => b"Unique".as_slice(),715						}716						.to_vec()717						.try_into()718						.unwrap(),719					});720					Self::set_scoped_collection_properties(721						id,722						PropertyScope::None,723						props.into_iter(),724					)725					.expect("existing data larger than properties");726					let mut new = CollectionVersion2::from(v.clone());727					new.permissions.access = Some(v.access);728					new.permissions.mint_mode = Some(v.mint_mode);729					Some(new)730				});731			}732733			0734		}735	}736}737738impl<T: Config> Pallet<T> {739	/// Enshure that receiver address is correct.740	///741	/// Ethereum receiver 0x0000000000000000000000000000000000000000 is reserved, and shouldn't own tokens.742	pub fn ensure_correct_receiver(receiver: &T::CrossAccountId) -> DispatchResult {743		ensure!(744			&T::CrossAccountId::from_eth(H160([0; 20])) != receiver,745			<Error<T>>::AddressIsZero746		);747		Ok(())748	}749750	/// Get a vector of collection admins.751	pub fn adminlist(collection: CollectionId) -> Vec<T::CrossAccountId> {752		<IsAdmin<T>>::iter_prefix((collection,))753			.map(|(a, _)| a)754			.collect()755	}756757	/// Get a vector of users allowed to mint tokens.758	pub fn allowlist(collection: CollectionId) -> Vec<T::CrossAccountId> {759		<Allowlist<T>>::iter_prefix((collection,))760			.map(|(a, _)| a)761			.collect()762	}763764	/// Is `user` allowed to mint token in `collection`.765	pub fn allowed(collection: CollectionId, user: T::CrossAccountId) -> bool {766		<Allowlist<T>>::get((collection, user))767	}768769	/// Get statistics of collections.770	pub fn collection_stats() -> CollectionStats {771		let created = <CreatedCollectionCount<T>>::get();772		let destroyed = <DestroyedCollectionCount<T>>::get();773		CollectionStats {774			created: created.0,775			destroyed: destroyed.0,776			alive: created.0 - destroyed.0,777		}778	}779780	/// Get the effective limits for the collection.781	pub fn effective_collection_limits(collection: CollectionId) -> Option<CollectionLimits> {782		let collection = <CollectionById<T>>::get(collection);783		if collection.is_none() {784			return None;785		}786787		let collection = collection.unwrap();788		let limits = collection.limits;789		let effective_limits = CollectionLimits {790			account_token_ownership_limit: Some(limits.account_token_ownership_limit()),791			sponsored_data_size: Some(limits.sponsored_data_size()),792			sponsored_data_rate_limit: Some(793				limits794					.sponsored_data_rate_limit795					.unwrap_or(SponsoringRateLimit::SponsoringDisabled),796			),797			token_limit: Some(limits.token_limit()),798			sponsor_transfer_timeout: Some(limits.sponsor_transfer_timeout(799				match collection.mode {800					CollectionMode::NFT => NFT_SPONSOR_TRANSFER_TIMEOUT,801					CollectionMode::Fungible(_) => FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,802					CollectionMode::ReFungible => REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,803				},804			)),805			sponsor_approve_timeout: Some(limits.sponsor_approve_timeout()),806			owner_can_transfer: Some(limits.owner_can_transfer()),807			owner_can_destroy: Some(limits.owner_can_destroy()),808			transfers_enabled: Some(limits.transfers_enabled()),809		};810811		Some(effective_limits)812	}813814	/// Returns information about the `collection` adapted for rpc.815	pub fn rpc_collection(collection: CollectionId) -> Option<RpcCollection<T::AccountId>> {816		let Collection {817			name,818			description,819			owner,820			mode,821			token_prefix,822			sponsorship,823			limits,824			permissions,825			external_collection,826		} = <CollectionById<T>>::get(collection)?;827828		let token_property_permissions = <CollectionPropertyPermissions<T>>::get(collection)829			.into_iter()830			.map(|(key, permission)| PropertyKeyPermission { key, permission })831			.collect();832833		let properties = <CollectionProperties<T>>::get(collection)834			.into_iter()835			.map(|(key, value)| Property { key, value })836			.collect();837838		let permissions = CollectionPermissions {839			access: Some(permissions.access()),840			mint_mode: Some(permissions.mint_mode()),841			nesting: Some(permissions.nesting().clone()),842		};843844		Some(RpcCollection {845			name: name.into_inner(),846			description: description.into_inner(),847			owner,848			mode,849			token_prefix: token_prefix.into_inner(),850			sponsorship,851			limits,852			permissions,853			token_property_permissions,854			properties,855			read_only: external_collection,856		})857	}858}859860macro_rules! limit_default {861	($old:ident, $new:ident, $($field:ident $(($arg:expr))? => $check:expr),* $(,)?) => {{862		$(863			if let Some($new) = $new.$field {864				let $old = $old.$field($($arg)?);865				let _ = $new;866				let _ = $old;867				$check868			} else {869				$new.$field = $old.$field870			}871		)*872	}};873}874macro_rules! limit_default_clone {875	($old:ident, $new:ident, $($field:ident $(($arg:expr))? => $check:expr),* $(,)?) => {{876		$(877			if let Some($new) = $new.$field.clone() {878				let $old = $old.$field($($arg)?);879				let _ = $new;880				let _ = $old;881				$check882			} else {883				$new.$field = $old.$field.clone()884			}885		)*886	}};887}888889impl<T: Config> Pallet<T> {890	/// Create new collection.891	///892	/// * `owner` - The owner of the collection.893	/// * `data` - Description of the created collection.894	/// * `is_external` - Marks that collection managet by not "Unique network".895	pub fn init_collection(896		owner: T::CrossAccountId,897		data: CreateCollectionData<T::AccountId>,898		is_external: bool,899	) -> Result<CollectionId, DispatchError> {900		{901			ensure!(902				data.token_prefix.len() <= MAX_TOKEN_PREFIX_LENGTH as usize,903				Error::<T>::CollectionTokenPrefixLimitExceeded904			);905		}906907		let created_count = <CreatedCollectionCount<T>>::get()908			.0909			.checked_add(1)910			.ok_or(ArithmeticError::Overflow)?;911		let destroyed_count = <DestroyedCollectionCount<T>>::get().0;912		let id = CollectionId(created_count);913914		// bound Total number of collections915		ensure!(916			created_count - destroyed_count <= COLLECTION_NUMBER_LIMIT,917			<Error<T>>::TotalCollectionsLimitExceeded918		);919920		// =========921922		let collection = Collection {923			owner: owner.as_sub().clone(),924			name: data.name,925			mode: data.mode.clone(),926			description: data.description,927			token_prefix: data.token_prefix,928			sponsorship: data929				.pending_sponsor930				.map(SponsorshipState::Unconfirmed)931				.unwrap_or_default(),932			limits: data933				.limits934				.map(|limits| Self::clamp_limits(data.mode.clone(), &Default::default(), limits))935				.unwrap_or_else(|| Ok(CollectionLimits::default()))?,936			permissions: data937				.permissions938				.map(|permissions| {939					Self::clamp_permissions(data.mode.clone(), &Default::default(), permissions)940				})941				.unwrap_or_else(|| Ok(CollectionPermissions::default()))?,942			external_collection: is_external,943		};944945		let mut collection_properties = up_data_structs::CollectionProperties::get();946		collection_properties947			.try_set_from_iter(data.properties.into_iter())948			.map_err(<Error<T>>::from)?;949950		CollectionProperties::<T>::insert(id, collection_properties);951952		let mut token_props_permissions = PropertiesPermissionMap::new();953		token_props_permissions954			.try_set_from_iter(data.token_property_permissions.into_iter())955			.map_err(<Error<T>>::from)?;956957		CollectionPropertyPermissions::<T>::insert(id, token_props_permissions);958959		// Take a (non-refundable) deposit of collection creation960		{961			let mut imbalance =962				<<<T as Config>::Currency as Currency<T::AccountId>>::PositiveImbalance>::zero();963			imbalance.subsume(964				<<T as Config>::Currency as Currency<T::AccountId>>::deposit_creating(965					&T::TreasuryAccountId::get(),966					T::CollectionCreationPrice::get(),967				),968			);969			<T as Config>::Currency::settle(970				&owner.as_sub(),971				imbalance,972				WithdrawReasons::TRANSFER,973				ExistenceRequirement::KeepAlive,974			)975			.map_err(|_| Error::<T>::NotSufficientFounds)?;976		}977978		<CreatedCollectionCount<T>>::put(created_count);979		<Pallet<T>>::deposit_event(Event::CollectionCreated(980			id,981			data.mode.id(),982			owner.as_sub().clone(),983		));984		<PalletEvm<T>>::deposit_log(985			erc::CollectionHelpersEvents::CollectionCreated {986				owner: *owner.as_eth(),987				collection_id: eth::collection_id_to_address(id),988			}989			.to_log(T::ContractAddress::get()),990		);991		<CollectionById<T>>::insert(id, collection);992		Ok(id)993	}994995	/// Destroy collection.996	///997	/// * `collection` - Collection handler.998	/// * `sender` - The owner or administrator of the collection.999	pub fn destroy_collection(1000		collection: CollectionHandle<T>,1001		sender: &T::CrossAccountId,1002	) -> DispatchResult {1003		ensure!(1004			collection.limits.owner_can_destroy(),1005			<Error<T>>::NoPermission,1006		);1007		collection.check_is_owner(sender)?;10081009		let destroyed_collections = <DestroyedCollectionCount<T>>::get()1010			.01011			.checked_add(1)1012			.ok_or(ArithmeticError::Overflow)?;10131014		// =========10151016		<DestroyedCollectionCount<T>>::put(destroyed_collections);1017		<CollectionById<T>>::remove(collection.id);1018		<AdminAmount<T>>::remove(collection.id);1019		<IsAdmin<T>>::remove_prefix((collection.id,), None);1020		<Allowlist<T>>::remove_prefix((collection.id,), None);1021		<CollectionProperties<T>>::remove(collection.id);10221023		<Pallet<T>>::deposit_event(Event::CollectionDestroyed(collection.id));1024		Ok(())1025	}10261027	/// Set collection property.1028	///1029	/// * `collection` - Collection handler.1030	/// * `sender` - The owner or administrator of the collection.1031	/// * `property` - The property to set.1032	pub fn set_collection_property(1033		collection: &CollectionHandle<T>,1034		sender: &T::CrossAccountId,1035		property: Property,1036	) -> DispatchResult {1037		collection.check_is_owner_or_admin(sender)?;10381039		CollectionProperties::<T>::try_mutate(collection.id, |properties| {1040			let property = property.clone();1041			properties.try_set(property.key, property.value)1042		})1043		.map_err(<Error<T>>::from)?;10441045		Self::deposit_event(Event::CollectionPropertySet(collection.id, property.key));10461047		Ok(())1048	}10491050	/// Set scouped collection property.1051	///1052	/// * `collection_id` - ID of the collection for which the property is being set.1053	/// * `scope` - Property scope.1054	/// * `property` - The property to set.1055	pub fn set_scoped_collection_property(1056		collection_id: CollectionId,1057		scope: PropertyScope,1058		property: Property,1059	) -> DispatchResult {1060		CollectionProperties::<T>::try_mutate(collection_id, |properties| {1061			properties.try_scoped_set(scope, property.key, property.value)1062		})1063		.map_err(<Error<T>>::from)?;10641065		Ok(())1066	}10671068	/// Set scouped collection properties.1069	///1070	/// * `collection_id` - ID of the collection for which the properties is being set.1071	/// * `scope` - Property scope.1072	/// * `properties` - The properties to set.1073	pub fn set_scoped_collection_properties(1074		collection_id: CollectionId,1075		scope: PropertyScope,1076		properties: impl Iterator<Item = Property>,1077	) -> DispatchResult {1078		CollectionProperties::<T>::try_mutate(collection_id, |stored_properties| {1079			stored_properties.try_scoped_set_from_iter(scope, properties)1080		})1081		.map_err(<Error<T>>::from)?;10821083		Ok(())1084	}10851086	/// Set collection properties.1087	///1088	/// * `collection` - Collection handler.1089	/// * `sender` - The owner or administrator of the collection.1090	/// * `properties` - The properties to set.1091	#[transactional]1092	pub fn set_collection_properties(1093		collection: &CollectionHandle<T>,1094		sender: &T::CrossAccountId,1095		properties: Vec<Property>,1096	) -> DispatchResult {1097		for property in properties {1098			Self::set_collection_property(collection, sender, property)?;1099		}11001101		Ok(())1102	}11031104	/// Delete collection property.1105	///1106	/// * `collection` - Collection handler.1107	/// * `sender` - The owner or administrator of the collection.1108	/// * `property` - The property to delete.1109	pub fn delete_collection_property(1110		collection: &CollectionHandle<T>,1111		sender: &T::CrossAccountId,1112		property_key: PropertyKey,1113	) -> DispatchResult {1114		collection.check_is_owner_or_admin(sender)?;11151116		CollectionProperties::<T>::try_mutate(collection.id, |properties| {1117			properties.remove(&property_key)1118		})1119		.map_err(<Error<T>>::from)?;11201121		Self::deposit_event(Event::CollectionPropertyDeleted(1122			collection.id,1123			property_key,1124		));11251126		Ok(())1127	}11281129	/// Delete collection properties.1130	///1131	/// * `collection` - Collection handler.1132	/// * `sender` - The owner or administrator of the collection.1133	/// * `properties` - The properties to delete.1134	#[transactional]1135	pub fn delete_collection_properties(1136		collection: &CollectionHandle<T>,1137		sender: &T::CrossAccountId,1138		property_keys: Vec<PropertyKey>,1139	) -> DispatchResult {1140		for key in property_keys {1141			Self::delete_collection_property(collection, sender, key)?;1142		}11431144		Ok(())1145	}11461147	/// Set collection propetry permission without any checks.1148	///1149	/// Used for migrations.1150	///1151	/// * `collection` - Collection handler.1152	/// * `property_permissions` - Property permissions.1153	pub fn set_property_permission_unchecked(1154		collection: CollectionId,1155		property_permission: PropertyKeyPermission,1156	) -> DispatchResult {1157		<CollectionPropertyPermissions<T>>::try_mutate(collection, |permissions| {1158			permissions.try_set(property_permission.key, property_permission.permission)1159		})1160		.map_err(<Error<T>>::from)?;1161		Ok(())1162	}11631164	/// Set collection property permission.1165	///1166	/// * `collection` - Collection handler.1167	/// * `sender` - The owner or administrator of the collection.1168	/// * `property_permission` - Property permission.1169	pub fn set_property_permission(1170		collection: &CollectionHandle<T>,1171		sender: &T::CrossAccountId,1172		property_permission: PropertyKeyPermission,1173	) -> DispatchResult {1174		collection.check_is_owner_or_admin(sender)?;11751176		let all_permissions = CollectionPropertyPermissions::<T>::get(collection.id);1177		let current_permission = all_permissions.get(&property_permission.key);1178		if matches![1179			current_permission,1180			Some(PropertyPermission { mutable: false, .. })1181		] {1182			return Err(<Error<T>>::NoPermission.into());1183		}11841185		CollectionPropertyPermissions::<T>::try_mutate(collection.id, |permissions| {1186			let property_permission = property_permission.clone();1187			permissions.try_set(property_permission.key, property_permission.permission)1188		})1189		.map_err(<Error<T>>::from)?;11901191		Self::deposit_event(Event::PropertyPermissionSet(1192			collection.id,1193			property_permission.key,1194		));11951196		Ok(())1197	}11981199	/// Set token property permission.1200	///1201	/// * `collection` - Collection handler.1202	/// * `sender` - The owner or administrator of the collection.1203	/// * `property_permissions` - Property permissions.1204	#[transactional]1205	pub fn set_token_property_permissions(1206		collection: &CollectionHandle<T>,1207		sender: &T::CrossAccountId,1208		property_permissions: Vec<PropertyKeyPermission>,1209	) -> DispatchResult {1210		for prop_pemission in property_permissions {1211			Self::set_property_permission(collection, sender, prop_pemission)?;1212		}12131214		Ok(())1215	}12161217	/// Get collection property.1218	pub fn get_collection_property(1219		collection_id: CollectionId,1220		key: &PropertyKey,1221	) -> Option<PropertyValue> {1222		Self::collection_properties(collection_id).get(key).cloned()1223	}12241225	/// Convert byte vector to property key vector.1226	pub fn bytes_keys_to_property_keys(1227		keys: Vec<Vec<u8>>,1228	) -> Result<Vec<PropertyKey>, DispatchError> {1229		keys.into_iter()1230			.map(|key| -> Result<PropertyKey, DispatchError> {1231				key.try_into()1232					.map_err(|_| <Error<T>>::PropertyKeyIsTooLong.into())1233			})1234			.collect::<Result<Vec<PropertyKey>, DispatchError>>()1235	}12361237	/// Get properties according to given keys.1238	pub fn filter_collection_properties(1239		collection_id: CollectionId,1240		keys: Option<Vec<PropertyKey>>,1241	) -> Result<Vec<Property>, DispatchError> {1242		let properties = Self::collection_properties(collection_id);12431244		let properties = keys1245			.map(|keys| {1246				keys.into_iter()1247					.filter_map(|key| {1248						properties.get(&key).map(|value| Property {1249							key,1250							value: value.clone(),1251						})1252					})1253					.collect()1254			})1255			.unwrap_or_else(|| {1256				properties1257					.into_iter()1258					.map(|(key, value)| Property { key, value })1259					.collect()1260			});12611262		Ok(properties)1263	}12641265	/// Get property permissions according to given keys.1266	pub fn filter_property_permissions(1267		collection_id: CollectionId,1268		keys: Option<Vec<PropertyKey>>,1269	) -> Result<Vec<PropertyKeyPermission>, DispatchError> {1270		let permissions = Self::property_permissions(collection_id);12711272		let key_permissions = keys1273			.map(|keys| {1274				keys.into_iter()1275					.filter_map(|key| {1276						permissions1277							.get(&key)1278							.map(|permission| PropertyKeyPermission {1279								key,1280								permission: permission.clone(),1281							})1282					})1283					.collect()1284			})1285			.unwrap_or_else(|| {1286				permissions1287					.into_iter()1288					.map(|(key, permission)| PropertyKeyPermission { key, permission })1289					.collect()1290			});12911292		Ok(key_permissions)1293	}12941295	/// Toggle `user` participation in the `collection`'s allow list.1296	pub fn toggle_allowlist(1297		collection: &CollectionHandle<T>,1298		sender: &T::CrossAccountId,1299		user: &T::CrossAccountId,1300		allowed: bool,1301	) -> DispatchResult {1302		collection.check_is_owner_or_admin(sender)?;13031304		// =========13051306		if allowed {1307			<Allowlist<T>>::insert((collection.id, user), true);1308		} else {1309			<Allowlist<T>>::remove((collection.id, user));1310		}13111312		Ok(())1313	}13141315	/// Toggle `user` participation in the `collection`'s admin list.1316	pub fn toggle_admin(1317		collection: &CollectionHandle<T>,1318		sender: &T::CrossAccountId,1319		user: &T::CrossAccountId,1320		admin: bool,1321	) -> DispatchResult {1322		collection.check_is_owner(sender)?;13231324		let was_admin = <IsAdmin<T>>::get((collection.id, user));1325		if was_admin == admin {1326			return Ok(());1327		}1328		let amount = <AdminAmount<T>>::get(collection.id);13291330		if admin {1331			let amount = amount1332				.checked_add(1)1333				.ok_or(<Error<T>>::CollectionAdminCountExceeded)?;1334			ensure!(1335				amount <= Self::collection_admins_limit(),1336				<Error<T>>::CollectionAdminCountExceeded,1337			);13381339			// =========13401341			<AdminAmount<T>>::insert(collection.id, amount);1342			<IsAdmin<T>>::insert((collection.id, user), true);1343		} else {1344			<AdminAmount<T>>::insert(collection.id, amount.saturating_sub(1));1345			<IsAdmin<T>>::remove((collection.id, user));1346		}13471348		Ok(())1349	}13501351	/// Merge set fields from `new_limit` to `old_limit`.1352	pub fn clamp_limits(1353		mode: CollectionMode,1354		old_limit: &CollectionLimits,1355		mut new_limit: CollectionLimits,1356	) -> Result<CollectionLimits, DispatchError> {1357		let limits = old_limit;1358		limit_default!(old_limit, new_limit,1359			account_token_ownership_limit => ensure!(1360				new_limit <= MAX_TOKEN_OWNERSHIP,1361				<Error<T>>::CollectionLimitBoundsExceeded,1362			),1363			sponsored_data_size => ensure!(1364				new_limit <= CUSTOM_DATA_LIMIT,1365				<Error<T>>::CollectionLimitBoundsExceeded,1366			),13671368			sponsored_data_rate_limit => {},1369			token_limit => ensure!(1370				old_limit >= new_limit && new_limit > 0,1371				<Error<T>>::CollectionTokenLimitExceeded1372			),13731374			sponsor_transfer_timeout(match mode {1375				CollectionMode::NFT => NFT_SPONSOR_TRANSFER_TIMEOUT,1376				CollectionMode::Fungible(_) => FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,1377				CollectionMode::ReFungible => REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,1378			}) => ensure!(1379				new_limit <= MAX_SPONSOR_TIMEOUT,1380				<Error<T>>::CollectionLimitBoundsExceeded,1381			),1382			sponsor_approve_timeout => {},1383			owner_can_transfer => ensure!(1384				!limits.owner_can_transfer_instaled() ||1385				old_limit || !new_limit,1386				<Error<T>>::OwnerPermissionsCantBeReverted,1387			),1388			owner_can_destroy => ensure!(1389				old_limit || !new_limit,1390				<Error<T>>::OwnerPermissionsCantBeReverted,1391			),1392			transfers_enabled => {},1393		);1394		Ok(new_limit)1395	}13961397	/// Merge set fields from `new_permission` to `old_permission`.1398	pub fn clamp_permissions(1399		_mode: CollectionMode,1400		old_permission: &CollectionPermissions,1401		mut new_permission: CollectionPermissions,1402	) -> Result<CollectionPermissions, DispatchError> {1403		limit_default_clone!(old_permission, new_permission,1404			access => {},1405			mint_mode => {},1406			nesting => { /* todo check for permissive, if only it gets out of benchmarks */ },1407		);1408		Ok(new_permission)1409	}1410}14111412/// Indicates unsupported methods by returning [Error::UnsupportedOperation].1413#[macro_export]1414macro_rules! unsupported {1415	() => {1416		Err(<Error<T>>::UnsupportedOperation.into())1417	};1418}14191420/// Return weights for various worst-case operations.1421pub trait CommonWeightInfo<CrossAccountId> {1422	/// Weight of item creation.1423	fn create_item() -> Weight;14241425	/// Weight of items creation.1426	fn create_multiple_items(amount: &[CreateItemData]) -> Weight;14271428	/// Weight of items creation.1429	fn create_multiple_items_ex(cost: &CreateItemExData<CrossAccountId>) -> Weight;14301431	/// The weight of the burning item.1432	fn burn_item() -> Weight;14331434	/// Property setting weight.1435	///1436	/// * `amount`- The number of properties to set.1437	fn set_collection_properties(amount: u32) -> Weight;14381439	/// Collection property deletion weight.1440	///1441	/// * `amount`- The number of properties to set.1442	fn delete_collection_properties(amount: u32) -> Weight;14431444	/// Token property setting weight.1445	///1446	/// * `amount`- The number of properties to set.1447	fn set_token_properties(amount: u32) -> Weight;14481449	/// Token property deletion weight.1450	///1451	/// * `amount`- The number of properties to delete.1452	fn delete_token_properties(amount: u32) -> Weight;14531454	/// Token property permissions set weight.1455	///1456	/// * `amount`- The number of property permissions to set.1457	fn set_token_property_permissions(amount: u32) -> Weight;14581459	/// Transfer price of the token or its parts.1460	fn transfer() -> Weight;14611462	/// The price of setting the permission of the operation from another user.1463	fn approve() -> Weight;14641465	/// Transfer price from another user.1466	fn transfer_from() -> Weight;14671468	/// The price of burning a token from another user.1469	fn burn_from() -> Weight;14701471	/// Differs from burn_item in case of Fungible and Refungible, as it should burn1472	/// whole users's balance1473	///1474	/// This method shouldn't be used directly, as it doesn't count breadth price, use [burn_recursively](CommonWeightInfo::burn_recursively) instead1475	fn burn_recursively_self_raw() -> Weight;14761477	/// Cost of iterating over `amount` children while burning, without counting child burning itself1478	///1479	/// This method shouldn't be used directly, as it doesn't count depth price, use [burn_recursively](CommonWeightInfo::burn_recursively) instead1480	fn burn_recursively_breadth_raw(amount: u32) -> Weight;14811482	/// The price of recursive burning a token.1483	///1484	/// `max_selfs` -1485	fn burn_recursively(max_selfs: u32, max_breadth: u32) -> Weight {1486		Self::burn_recursively_self_raw()1487			.saturating_mul(max_selfs.max(1) as u64)1488			.saturating_add(Self::burn_recursively_breadth_raw(max_breadth))1489	}1490}14911492/// Weight info extension trait for refungible pallet.1493pub trait RefungibleExtensionsWeightInfo {1494	/// Weight of token repartition.1495	fn repartition() -> Weight;1496}14971498/// Common collection operations.1499///1500/// It wraps methods in Fungible, Nonfungible and Refungible pallets1501/// and adds weight info.1502pub trait CommonCollectionOperations<T: Config> {1503	/// Create token.1504	///1505	/// * `sender` - The user who mint the token and pays for the transaction.1506	/// * `to` - The user who will own the token.1507	/// * `data` - Token data.1508	/// * `nesting_budget` - A budget that can be spent on nesting tokens.1509	fn create_item(1510		&self,1511		sender: T::CrossAccountId,1512		to: T::CrossAccountId,1513		data: CreateItemData,1514		nesting_budget: &dyn Budget,1515	) -> DispatchResultWithPostInfo;15161517	/// Create multiple tokens.1518	///1519	/// * `sender` - The user who mint the token and pays for the transaction.1520	/// * `to` - The user who will own the token.1521	/// * `data` - Token data.1522	/// * `nesting_budget` - A budget that can be spent on nesting tokens.1523	fn create_multiple_items(1524		&self,1525		sender: T::CrossAccountId,1526		to: T::CrossAccountId,1527		data: Vec<CreateItemData>,1528		nesting_budget: &dyn Budget,1529	) -> DispatchResultWithPostInfo;15301531	/// Create multiple tokens.1532	///1533	/// * `sender` - The user who mint the token and pays for the transaction.1534	/// * `to` - The user who will own the token.1535	/// * `data` - Token data.1536	/// * `nesting_budget` - A budget that can be spent on nesting tokens.1537	fn create_multiple_items_ex(1538		&self,1539		sender: T::CrossAccountId,1540		data: CreateItemExData<T::CrossAccountId>,1541		nesting_budget: &dyn Budget,1542	) -> DispatchResultWithPostInfo;15431544	/// Burn token.1545	///1546	/// * `sender` - The user who owns the token.1547	/// * `token` - Token id that will burned.1548	/// * `amount` - The number of parts of the token that will be burned.1549	fn burn_item(1550		&self,1551		sender: T::CrossAccountId,1552		token: TokenId,1553		amount: u128,1554	) -> DispatchResultWithPostInfo;15551556	/// Burn token and all nested tokens recursievly.1557	///1558	/// * `sender` - The user who owns the token.1559	/// * `token` - Token id that will burned.1560	/// * `self_budget` - The budget that can be spent on burning tokens.1561	/// * `breadth_budget` - The budget that can be spent on burning nested tokens.1562	fn burn_item_recursively(1563		&self,1564		sender: T::CrossAccountId,1565		token: TokenId,1566		self_budget: &dyn Budget,1567		breadth_budget: &dyn Budget,1568	) -> DispatchResultWithPostInfo;15691570	/// Set collection properties.1571	///1572	/// * `sender` - Must be either the owner of the collection or its admin.1573	/// * `properties` - Properties to be set.1574	fn set_collection_properties(1575		&self,1576		sender: T::CrossAccountId,1577		properties: Vec<Property>,1578	) -> DispatchResultWithPostInfo;15791580	/// Delete collection properties.1581	///1582	/// * `sender` - Must be either the owner of the collection or its admin.1583	/// * `properties` - The properties to be removed.1584	fn delete_collection_properties(1585		&self,1586		sender: &T::CrossAccountId,1587		property_keys: Vec<PropertyKey>,1588	) -> DispatchResultWithPostInfo;15891590	/// Set token properties.1591	///1592	/// The appropriate [PropertyPermission] for the token property1593	/// must be set with [Self::set_token_property_permissions].1594	///1595	/// * `sender` - Must be either the owner of the token or its admin.1596	/// * `token_id` - The token for which the properties are being set.1597	/// * `properties` - Properties to be set.1598	/// * `budget` - Budget for setting properties.1599	fn set_token_properties(1600		&self,1601		sender: T::CrossAccountId,1602		token_id: TokenId,1603		properties: Vec<Property>,1604		budget: &dyn Budget,1605	) -> DispatchResultWithPostInfo;16061607	/// Remove token properties.1608	///1609	/// The appropriate [PropertyPermission] for the token property1610	/// must be set with [Self::set_token_property_permissions].1611	///1612	/// * `sender` - Must be either the owner of the token or its admin.1613	/// * `token_id` - The token for which the properties are being remove.1614	/// * `property_keys` - Keys to remove corresponding properties.1615	/// * `budget` - Budget for removing properties.1616	fn delete_token_properties(1617		&self,1618		sender: T::CrossAccountId,1619		token_id: TokenId,1620		property_keys: Vec<PropertyKey>,1621		budget: &dyn Budget,1622	) -> DispatchResultWithPostInfo;16231624	/// Set token property permissions.1625	///1626	/// * `sender` - Must be either the owner of the token or its admin.1627	/// * `token_id` - The token for which the properties are being set.1628	/// * `properties` - Properties to be set.1629	/// * `budget` - Budget for setting properties.1630	fn set_token_property_permissions(1631		&self,1632		sender: &T::CrossAccountId,1633		property_permissions: Vec<PropertyKeyPermission>,1634	) -> DispatchResultWithPostInfo;16351636	/// Transfer amount of token pieces.1637	///1638	/// * `sender` - Donor user.1639	/// * `to` - Recepient user.1640	/// * `token` - The token of which parts are being sent.1641	/// * `amount` - The number of parts of the token that will be transferred.1642	/// * `budget` - The maximum budget that can be spent on the transfer.1643	fn transfer(1644		&self,1645		sender: T::CrossAccountId,1646		to: T::CrossAccountId,1647		token: TokenId,1648		amount: u128,1649		budget: &dyn Budget,1650	) -> DispatchResultWithPostInfo;16511652	/// Grant access to another account to transfer parts of the token owned by the calling user via [Self::transfer_from].1653	///1654	/// * `sender` - The user who grants access to the token.1655	/// * `spender` - The user to whom the rights are granted.1656	/// * `token` - The token to which access is granted.1657	/// * `amount` - The amount of pieces that another user can dispose of.1658	fn approve(1659		&self,1660		sender: T::CrossAccountId,1661		spender: T::CrossAccountId,1662		token: TokenId,1663		amount: u128,1664	) -> DispatchResultWithPostInfo;16651666	/// Send parts of a token owned by another user.1667	///1668	/// Before calling this method, you must grant rights to the calling user via [Self::approve].1669	///1670	/// * `sender` - The user who has access to the token.1671	/// * `from` - The user who owns the token.1672	/// * `to` - Recepient user.1673	/// * `token` - The token of which parts are being sent.1674	/// * `amount` - The number of parts of the token that will be transferred.1675	/// * `budget` - The maximum budget that can be spent on the transfer.1676	fn transfer_from(1677		&self,1678		sender: T::CrossAccountId,1679		from: T::CrossAccountId,1680		to: T::CrossAccountId,1681		token: TokenId,1682		amount: u128,1683		budget: &dyn Budget,1684	) -> DispatchResultWithPostInfo;16851686	/// Burn parts of a token owned by another user.1687	///1688	/// Before calling this method, you must grant rights to the calling user via [Self::approve].1689	///1690	/// * `sender` - The user who has access to the token.1691	/// * `from` - The user who owns the token.1692	/// * `token` - The token of which parts are being sent.1693	/// * `amount` - The number of parts of the token that will be transferred.1694	/// * `budget` - The maximum budget that can be spent on the burn.1695	fn burn_from(1696		&self,1697		sender: T::CrossAccountId,1698		from: T::CrossAccountId,1699		token: TokenId,1700		amount: u128,1701		budget: &dyn Budget,1702	) -> DispatchResultWithPostInfo;17031704	/// Check permission to nest token.1705	///1706	/// * `sender` - The user who initiated the check.1707	/// * `from` - The token that is checked for embedding.1708	/// * `under` - Token under which to check.1709	/// * `budget` - The maximum budget that can be spent on the check.1710	fn check_nesting(1711		&self,1712		sender: T::CrossAccountId,1713		from: (CollectionId, TokenId),1714		under: TokenId,1715		budget: &dyn Budget,1716	) -> DispatchResult;17171718	/// Nest one token into another.1719	///1720	/// * `under` - Token holder.1721	/// * `to_nest` - Nested token.1722	fn nest(&self, under: TokenId, to_nest: (CollectionId, TokenId));17231724	/// Unnest token.1725	///1726	/// * `under` - Token holder.1727	/// * `to_nest` - Token to unnest.1728	fn unnest(&self, under: TokenId, to_nest: (CollectionId, TokenId));17291730	/// Get all user tokens.1731	///1732	/// * `account` - Account for which you need to get tokens.1733	fn account_tokens(&self, account: T::CrossAccountId) -> Vec<TokenId>;17341735	/// Get all the tokens in the collection.1736	fn collection_tokens(&self) -> Vec<TokenId>;17371738	/// Check if the token exists.1739	///1740	/// * `token` - Id token to check.1741	fn token_exists(&self, token: TokenId) -> bool;17421743	/// Get the id of the last minted token.1744	fn last_token_id(&self) -> TokenId;17451746	/// Get the owner of the token.1747	///1748	/// * `token` - The token for which you need to find out the owner.1749	fn token_owner(&self, token: TokenId) -> Option<T::CrossAccountId>;17501751	/// Get the value of the token property by key.1752	///1753	/// * `token` - Token property to get.1754	/// * `key` - Property name.1755	fn token_property(&self, token_id: TokenId, key: &PropertyKey) -> Option<PropertyValue>;17561757	/// Get a set of token properties by key vector.1758	///1759	/// * `token` - Token property to get.1760	/// * `keys` - Vector of keys. If this parameter is [None](sp_std::result::Result),1761	/// then all properties are returned.1762	fn token_properties(&self, token: TokenId, keys: Option<Vec<PropertyKey>>) -> Vec<Property>;17631764	/// Amount of unique collection tokens1765	fn total_supply(&self) -> u32;17661767	/// Amount of different tokens account has.1768	///1769	/// * `account` - The account for which need to get the balance.1770	fn account_balance(&self, account: T::CrossAccountId) -> u32;17711772	/// Amount of specific token account have.1773	fn balance(&self, account: T::CrossAccountId, token: TokenId) -> u128;17741775	/// Amount of token pieces1776	fn total_pieces(&self, token: TokenId) -> Option<u128>;17771778	/// Get the number of parts of the token that a trusted user can manage.1779	///1780	/// * `sender` - Trusted user.1781	/// * `spender` - Owner of the token.1782	/// * `token` - The token for which to get the value.1783	fn allowance(1784		&self,1785		sender: T::CrossAccountId,1786		spender: T::CrossAccountId,1787		token: TokenId,1788	) -> u128;17891790	/// Get extension for RFT collection.1791	fn refungible_extensions(&self) -> Option<&dyn RefungibleExtensions<T>>;1792}17931794/// Extension for RFT collection.1795pub trait RefungibleExtensions<T>1796where1797	T: Config,1798{1799	/// Change the number of parts of the token.1800	///1801	/// When the value changes down, this function is equivalent to burning parts of the token.1802	///1803	/// * `sender` - The user calling the repartition operation. Must be the owner of the token.1804	/// * `token` - The token for which you want to change the number of parts.1805	/// * `amount` - The new value of the parts of the token.1806	fn repartition(1807		&self,1808		sender: &T::CrossAccountId,1809		token: TokenId,1810		amount: u128,1811	) -> DispatchResultWithPostInfo;1812}18131814/// Merge [DispatchResult] with [Weight] into [DispatchResultWithPostInfo].1815///1816/// Used for [CommonCollectionOperations] implementations and flexible enough to do so.1817pub fn with_weight(res: DispatchResult, weight: Weight) -> DispatchResultWithPostInfo {1818	let post_info = PostDispatchInfo {1819		actual_weight: Some(weight),1820		pays_fee: Pays::Yes,1821	};1822	match res {1823		Ok(()) => Ok(post_info),1824		Err(error) => Err(DispatchErrorWithPostInfo { post_info, error }),1825	}1826}18271828impl<T: Config> From<PropertiesError> for Error<T> {1829	fn from(error: PropertiesError) -> Self {1830		match error {1831			PropertiesError::NoSpaceForProperty => Self::NoSpaceForProperty,1832			PropertiesError::PropertyLimitReached => Self::PropertyLimitReached,1833			PropertiesError::InvalidCharacterInPropertyKey => Self::InvalidCharacterInPropertyKey,1834			PropertiesError::PropertyKeyIsTooLong => Self::PropertyKeyIsTooLong,1835			PropertiesError::EmptyPropertyKey => Self::EmptyPropertyKey,1836		}1837	}1838}