git.delta.rocks / unique-network / refs/commits / 263bc691fe1a

difftreelog

docs(pallet_common) Add general documentation.

Trubnikov Sergey2022-07-15parent: #12c8c8f.patch.diff
in: master

4 files changed

modifiedpallets/common/src/dispatch.rsdiffbeforeafterboth
--- a/pallets/common/src/dispatch.rs
+++ b/pallets/common/src/dispatch.rs
@@ -1,3 +1,5 @@
+//! Module with interfaces for dispatching collections.
+
 use frame_support::{
 	dispatch::{
 		DispatchResultWithPostInfo, PostDispatchInfo, Weight, DispatchErrorWithPostInfo,
@@ -20,7 +22,10 @@
 	// submit_logs is measured as part of collection pallets
 }
 
-/// Helper function to implement substrate calls for common collection methods
+/// Helper function to implement substrate calls for common collection methods.
+/// 
+/// * `collection` - The collection on which to call the method.
+/// * `call` - The function in which to call the corresponding method from [CommonCollectionOperations].
 pub fn dispatch_tx<
 	T: Config,
 	C: FnOnce(&dyn CommonCollectionOperations<T>) -> DispatchResultWithPostInfo,
@@ -64,15 +69,31 @@
 	result
 }
 
+/// Interface for working with different collections through the dispatcher.
 pub trait CollectionDispatch<T: Config> {
+	/// Create a collection. The collection will be created according to the value of [data.mode](CreateCollectionData::mode).
+	/// 
+	/// * `sender` - The user who will become the owner of the collection.
+	/// * `data` - Description of the created collection.
 	fn create(
 		sender: T::CrossAccountId,
 		data: CreateCollectionData<T::AccountId>,
 	) -> DispatchResult;
+
+	/// Delete the collection.
+	/// 
+	/// * `sender` - The owner of the collection.
+	/// * `handle` - Collection handle.
 	fn destroy(sender: T::CrossAccountId, handle: CollectionHandle<T>) -> DispatchResult;
 
+	/// Get a specialized collection from the handle.
+	/// 
+	/// * `handle` - Collection handle.
 	fn dispatch(handle: CollectionHandle<T>) -> Self;
+
+	/// Get the collection handle for the corresponding implementation.
 	fn into_inner(self) -> CollectionHandle<T>;
 
+	/// Получить реализацию [CommonCollectionOperations].
 	fn as_dyn(&self) -> &dyn CommonCollectionOperations<T>;
 }
modifiedpallets/common/src/erc.rsdiffbeforeafterboth
--- a/pallets/common/src/erc.rs
+++ b/pallets/common/src/erc.rs
@@ -14,6 +14,8 @@
 // You should have received a copy of the GNU General Public License
 // along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
 
+//! This module contains the implementation of pallet methods for evm.
+
 use evm_coder::{
 	solidity_interface, solidity, ToLog,
 	types::*,
@@ -29,29 +31,39 @@
 
 use crate::{Pallet, CollectionHandle, Config, CollectionProperties};
 
+/// Events for etherium collection helper.
 #[derive(ToLog)]
 pub enum CollectionHelpersEvents {
+	/// The collection has been created.
 	CollectionCreated {
+		/// Collection owner.
 		#[indexed]
 		owner: address,
+
+		/// Collection ID.
 		#[indexed]
 		collection_id: address,
 	},
 }
 
 /// Does not always represent a full collection, for RFT it is either
-/// collection (Implementing ERC721), or specific collection token (Implementing ERC20)
+/// collection (Implementing ERC721), or specific collection token (Implementing ERC20).
 pub trait CommonEvmHandler {
 	const CODE: &'static [u8];
 
 	fn call(self, handle: &mut impl PrecompileHandle) -> Option<PrecompileResult>;
 }
 
+/// @title A contract that allows you to work with collections.
 #[solidity_interface(name = "Collection")]
 impl<T: Config> CollectionHandle<T>
 where
 	T::AccountId: From<[u8; 32]>,
 {
+	/// Set collection property.
+	/// 
+	/// @param key Property key.
+	/// @param value Propery value.
 	fn set_collection_property(
 		&mut self,
 		caller: caller,
@@ -60,14 +72,17 @@
 	) -> Result<void> {
 		let caller = T::CrossAccountId::from_eth(caller);
 		let key = <Vec<u8>>::from(key)
-			.try_into()
-			.map_err(|_| "key too large")?;
+		.try_into()
+		.map_err(|_| "key too large")?;
 		let value = value.try_into().map_err(|_| "value too large")?;
-
+		
 		<Pallet<T>>::set_collection_property(self, &caller, Property { key, value })
-			.map_err(dispatch_to_evm::<T>)
+		.map_err(dispatch_to_evm::<T>)
 	}
-
+	
+	/// Delete collection property.
+	/// 
+	/// @param key Property key.
 	fn delete_collection_property(&mut self, caller: caller, key: string) -> Result<()> {
 		let caller = T::CrossAccountId::from_eth(caller);
 		let key = <Vec<u8>>::from(key)
@@ -77,7 +92,12 @@
 		<Pallet<T>>::delete_collection_property(self, &caller, key).map_err(dispatch_to_evm::<T>)
 	}
 
-	/// Throws error if key not found
+	/// Get collection property.
+	/// 
+	/// @dev Throws error if key not found.
+	/// 
+	/// @param key Property key.
+	/// @return bytes The property corresponding to the key.
 	fn collection_property(&self, key: string) -> Result<bytes> {
 		let key = <Vec<u8>>::from(key)
 			.try_into()
@@ -89,6 +109,11 @@
 		Ok(prop.to_vec())
 	}
 
+	/// Set the sponsor of the collection.
+	/// 
+	/// @dev In order for sponsorship to work, it must be confirmed on behalf of the sponsor.
+	/// 
+	/// @param sponsor Address of the sponsor from whose account funds will be debited for operations with the contract.
 	fn set_collection_sponsor(&mut self, caller: caller, sponsor: address) -> Result<void> {
 		check_is_owner_or_admin(caller, self)?;
 
@@ -98,6 +123,9 @@
 		save(self)
 	}
 
+	/// Collection sponsorship confirmation.
+	/// 
+	/// @dev After setting the sponsor for the collection, it must be confirmed with this function.
 	fn confirm_collection_sponsorship(&mut self, caller: caller) -> Result<void> {
 		let caller = T::CrossAccountId::from_eth(caller);
 		if !self
@@ -109,6 +137,16 @@
 		save(self)
 	}
 
+	/// Set limits for the collection.
+	/// @dev Throws error if limit not found.
+	/// @param limit Name of the limit. Valid names:
+	/// 	"accountTokenOwnershipLimit",
+	/// 	"sponsoredDataSize",
+	/// 	"sponsoredDataRateLimit",
+	/// 	"tokenLimit",
+	/// 	"sponsorTransferTimeout",
+	/// 	"sponsorApproveTimeout"
+	/// @param value Value of the limit.
 	#[solidity(rename_selector = "setCollectionLimit")]
 	fn set_int_limit(&mut self, caller: caller, limit: string, value: uint32) -> Result<void> {
 		check_is_owner_or_admin(caller, self)?;
@@ -145,6 +183,13 @@
 		save(self)
 	}
 
+	/// Set limits for the collection.
+	/// @dev Throws error if limit not found.
+	/// @param limit Name of the limit. Valid names:
+	/// 	"ownerCanTransfer",
+	/// 	"ownerCanDestroy",
+	/// 	"transfersEnabled"
+	/// @param value Value of the limit.
 	#[solidity(rename_selector = "setCollectionLimit")]
 	fn set_bool_limit(&mut self, caller: caller, limit: string, value: bool) -> Result<void> {
 		check_is_owner_or_admin(caller, self)?;
@@ -172,10 +217,13 @@
 		save(self)
 	}
 
+	/// Get contract address.
 	fn contract_address(&self, _caller: caller) -> Result<address> {
 		Ok(crate::eth::collection_id_to_address(self.id))
 	}
 
+	/// Add collection admin by substrate address.
+	/// @param new_admin Substrate administrator address.
 	fn add_collection_admin_substrate(&self, caller: caller, new_admin: uint256) -> Result<void> {
 		let caller = T::CrossAccountId::from_eth(caller);
 		let mut new_admin_arr: [u8; 32] = Default::default();
@@ -186,21 +234,25 @@
 		Ok(())
 	}
 
+	/// Remove collection admin by substrate address.
+	/// @param admin Substrate administrator address.
 	fn remove_collection_admin_substrate(
 		&self,
 		caller: caller,
-		new_admin: uint256,
+		admin: uint256,
 	) -> Result<void> {
 		let caller = T::CrossAccountId::from_eth(caller);
-		let mut new_admin_arr: [u8; 32] = Default::default();
-		new_admin.to_big_endian(&mut new_admin_arr);
-		let account_id = T::AccountId::from(new_admin_arr);
-		let new_admin = T::CrossAccountId::from_sub(account_id);
-		<Pallet<T>>::toggle_admin(self, &caller, &new_admin, false)
+		let mut admin_arr: [u8; 32] = Default::default();
+		admin.to_big_endian(&mut admin_arr);
+		let account_id = T::AccountId::from(admin_arr);
+		let admin = T::CrossAccountId::from_sub(account_id);
+		<Pallet<T>>::toggle_admin(self, &caller, &admin, false)
 			.map_err(dispatch_to_evm::<T>)?;
 		Ok(())
 	}
 
+	/// Add collection admin.
+	/// @param new_admin Address of the added administrator.
 	fn add_collection_admin(&self, caller: caller, new_admin: address) -> Result<void> {
 		let caller = T::CrossAccountId::from_eth(caller);
 		let new_admin = T::CrossAccountId::from_eth(new_admin);
@@ -208,6 +260,9 @@
 		Ok(())
 	}
 
+	/// Remove collection admin.
+	/// 
+	/// @param new_admin Address of the removed administrator.
 	fn remove_collection_admin(&self, caller: caller, admin: address) -> Result<void> {
 		let caller = T::CrossAccountId::from_eth(caller);
 		let admin = T::CrossAccountId::from_eth(admin);
@@ -215,6 +270,9 @@
 		Ok(())
 	}
 
+	/// Toggle accessibility of collection nesting.
+	/// 
+	/// @param enable If "true" degenerates to nesting: 'Owner' else to nesting: 'Disabled'
 	#[solidity(rename_selector = "setCollectionNesting")]
 	fn set_nesting_bool(&mut self, caller: caller, enable: bool) -> Result<void> {
 		check_is_owner_or_admin(caller, self)?;
@@ -235,6 +293,10 @@
 		save(self)
 	}
 
+	/// Toggle accessibility of collection nesting.
+	/// 
+	/// @param enable If "true" degenerates to nesting: {OwnerRestricted: [1, 2, 3]} else to nesting: 'Disabled'
+	/// @param collections Addresses of collections that will be available for nesting.
 	#[solidity(rename_selector = "setCollectionNesting")]
 	fn set_nesting(
 		&mut self,
@@ -280,6 +342,10 @@
 		save(self)
 	}
 
+	/// Set the collection access method.
+	/// @param mode Access mode
+	/// 	0 for Normal
+	/// 	1 for AllowList
 	fn set_collection_access(&mut self, caller: caller, mode: uint8) -> Result<void> {
 		check_is_owner_or_admin(caller, self)?;
 		let permissions = CollectionPermissions {
@@ -300,13 +366,19 @@
 		save(self)
 	}
 
+	/// Add the user to the allowed list.
+	/// 
+	/// @param user Address of a trusted user.
 	fn add_to_collection_allow_list(&self, caller: caller, user: address) -> Result<void> {
 		let caller = T::CrossAccountId::from_eth(caller);
 		let user = T::CrossAccountId::from_eth(user);
 		<Pallet<T>>::toggle_allowlist(self, &caller, &user, true).map_err(dispatch_to_evm::<T>)?;
 		Ok(())
 	}
-
+	
+	/// Remove the user from the allowed list.
+	/// 
+	/// @param user Address of a removed user.
 	fn remove_from_collection_allow_list(&self, caller: caller, user: address) -> Result<void> {
 		let caller = T::CrossAccountId::from_eth(caller);
 		let user = T::CrossAccountId::from_eth(user);
@@ -314,6 +386,9 @@
 		Ok(())
 	}
 
+	/// Switch permission for minting.
+	/// 
+	/// @param mode Enable if "true".
 	fn set_collection_mint_mode(&mut self, caller: caller, mode: bool) -> Result<void> {
 		check_is_owner_or_admin(caller, self)?;
 		let permissions = CollectionPermissions {
@@ -351,6 +426,7 @@
 	Ok(())
 }
 
+/// Get the "tokenURI" key as [PropertyKey](up_data_structs::PropertyKey).
 pub fn token_uri_key() -> up_data_structs::PropertyKey {
 	b"tokenURI"
 		.to_vec()
modifiedpallets/common/src/eth.rsdiffbeforeafterboth
--- a/pallets/common/src/eth.rs
+++ b/pallets/common/src/eth.rs
@@ -14,6 +14,8 @@
 // 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.
+
 use up_data_structs::CollectionId;
 use sp_core::H160;
 
@@ -23,6 +25,7 @@
 	0x17, 0xc4, 0xe6, 0x45, 0x3c, 0xc4, 0x9a, 0xaa, 0xae, 0xac, 0xa8, 0x94, 0xe6, 0xd9, 0x68, 0x3e,
 ];
 
+/// Maps the etherium address of the collection in substrate.
 pub fn map_eth_to_id(eth: &H160) -> Option<CollectionId> {
 	if eth[0..16] != ETH_COLLECTION_PREFIX {
 		return None;
@@ -31,6 +34,8 @@
 	id_bytes.copy_from_slice(&eth[16..20]);
 	Some(CollectionId(u32::from_be_bytes(id_bytes)))
 }
+
+/// Maps the substrate collection id in etherium.
 pub fn collection_id_to_address(id: CollectionId) -> H160 {
 	let mut out = [0; 20];
 	out[0..16].copy_from_slice(&ETH_COLLECTION_PREFIX);
@@ -38,6 +43,7 @@
 	H160(out)
 }
 
+/// Check if the etherium address is a collection.
 pub fn is_collection(address: &H160) -> bool {
 	address[0..16] == ETH_COLLECTION_PREFIX
 }
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#![cfg_attr(not(feature = "std"), no_std)]1819extern crate alloc;2021use core::ops::{Deref, DerefMut};22use pallet_evm_coder_substrate::{SubstrateRecorder, WithRecorder};23use sp_std::vec::Vec;24use pallet_evm::{account::CrossAccountId, Pallet as PalletEvm};25use evm_coder::ToLog;26use frame_support::{27	dispatch::{DispatchErrorWithPostInfo, DispatchResultWithPostInfo, Weight, PostDispatchInfo},28	ensure,29	traits::{Imbalance, Get, Currency, WithdrawReasons, ExistenceRequirement},30	weights::Pays,31	transactional,32};33use pallet_evm::GasWeightMapping;34use up_data_structs::{35	COLLECTION_NUMBER_LIMIT,36	Collection,37	RpcCollection,38	CollectionId,39	CreateItemData,40	MAX_TOKEN_PREFIX_LENGTH,41	COLLECTION_ADMINS_LIMIT,42	TokenId,43	TokenChild,44	CollectionStats,45	MAX_TOKEN_OWNERSHIP,46	CollectionMode,47	NFT_SPONSOR_TRANSFER_TIMEOUT,48	FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,49	REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,50	MAX_SPONSOR_TIMEOUT,51	CUSTOM_DATA_LIMIT,52	CollectionLimits,53	CreateCollectionData,54	SponsorshipState,55	CreateItemExData,56	SponsoringRateLimit,57	budget::Budget,58	PhantomType,59	Property,60	Properties,61	PropertiesPermissionMap,62	PropertyKey,63	PropertyValue,64	PropertyPermission,65	PropertiesError,66	PropertyKeyPermission,67	TokenData,68	TrySetProperty,69	PropertyScope,70	// RMRK71	RmrkCollectionInfo,72	RmrkInstanceInfo,73	RmrkResourceInfo,74	RmrkPropertyInfo,75	RmrkBaseInfo,76	RmrkPartType,77	RmrkBoundedTheme,78	RmrkNftChild,79	CollectionPermissions,80	SchemaVersion,81};8283pub use pallet::*;84use sp_core::H160;85use sp_runtime::{ArithmeticError, DispatchError, DispatchResult};86#[cfg(feature = "runtime-benchmarks")]87pub mod benchmarking;88pub mod dispatch;89pub mod erc;90pub mod eth;91pub mod weights;9293pub type SelfWeightOf<T> = <T as Config>::WeightInfo;9495#[must_use = "Should call submit_logs or save, otherwise some data will be lost for evm side"]96pub struct CollectionHandle<T: Config> {97	pub id: CollectionId,98	collection: Collection<T::AccountId>,99	pub recorder: SubstrateRecorder<T>,100}101impl<T: Config> WithRecorder<T> for CollectionHandle<T> {102	fn recorder(&self) -> &SubstrateRecorder<T> {103		&self.recorder104	}105	fn into_recorder(self) -> SubstrateRecorder<T> {106		self.recorder107	}108}109impl<T: Config> CollectionHandle<T> {110	pub fn new_with_gas_limit(id: CollectionId, gas_limit: u64) -> Option<Self> {111		<CollectionById<T>>::get(id).map(|collection| Self {112			id,113			collection,114			recorder: SubstrateRecorder::new(gas_limit),115		})116	}117118	pub fn new_with_recorder(id: CollectionId, recorder: SubstrateRecorder<T>) -> Option<Self> {119		<CollectionById<T>>::get(id).map(|collection| Self {120			id,121			collection,122			recorder,123		})124	}125126	pub fn new(id: CollectionId) -> Option<Self> {127		Self::new_with_gas_limit(id, u64::MAX)128	}129130	pub fn try_get(id: CollectionId) -> Result<Self, DispatchError> {131		Ok(Self::new(id).ok_or(<Error<T>>::CollectionNotFound)?)132	}133134	pub fn consume_store_reads(&self, reads: u64) -> evm_coder::execution::Result<()> {135		self.recorder136			.consume_gas(T::GasWeightMapping::weight_to_gas(137				<T as frame_system::Config>::DbWeight::get()138					.read139					.saturating_mul(reads),140			))141	}142143	pub fn consume_store_writes(&self, writes: u64) -> evm_coder::execution::Result<()> {144		self.recorder145			.consume_gas(T::GasWeightMapping::weight_to_gas(146				<T as frame_system::Config>::DbWeight::get()147					.write148					.saturating_mul(writes),149			))150	}151	pub fn save(self) -> DispatchResult {152		<CollectionById<T>>::insert(self.id, self.collection);153		Ok(())154	}155156	pub fn set_sponsor(&mut self, sponsor: T::AccountId) -> DispatchResult {157		self.collection.sponsorship = SponsorshipState::Unconfirmed(sponsor);158		Ok(())159	}160161	pub fn confirm_sponsorship(&mut self, sender: &T::AccountId) -> Result<bool, DispatchError> {162		if self.collection.sponsorship.pending_sponsor() != Some(sender) {163			return Ok(false);164		}165166		self.collection.sponsorship = SponsorshipState::Confirmed(sender.clone());167		Ok(true)168	}169170	/// Checks that the collection was created with, and must be operated upon through **Unique API**.171	/// Now check only the `external_collection` flag and if it's **true**, then return `CollectionIsExternal` error.172	pub fn check_is_internal(&self) -> DispatchResult {173		if self.external_collection {174			return Err(<Error<T>>::CollectionIsExternal)?;175		}176177		Ok(())178	}179180	/// Checks that the collection was created with, and must be operated upon through an **assimilated API**.181	/// Now check only the `external_collection` flag and if it's **false**, then return `CollectionIsInternal` error.182	pub fn check_is_external(&self) -> DispatchResult {183		if !self.external_collection {184			return Err(<Error<T>>::CollectionIsInternal)?;185		}186187		Ok(())188	}189}190191impl<T: Config> Deref for CollectionHandle<T> {192	type Target = Collection<T::AccountId>;193194	fn deref(&self) -> &Self::Target {195		&self.collection196	}197}198199impl<T: Config> DerefMut for CollectionHandle<T> {200	fn deref_mut(&mut self) -> &mut Self::Target {201		&mut self.collection202	}203}204205impl<T: Config> CollectionHandle<T> {206	pub fn check_is_owner(&self, subject: &T::CrossAccountId) -> DispatchResult {207		ensure!(*subject.as_sub() == self.owner, <Error<T>>::NoPermission);208		Ok(())209	}210	pub fn is_owner_or_admin(&self, subject: &T::CrossAccountId) -> bool {211		*subject.as_sub() == self.owner || <IsAdmin<T>>::get((self.id, subject))212	}213	pub fn check_is_owner_or_admin(&self, subject: &T::CrossAccountId) -> DispatchResult {214		ensure!(self.is_owner_or_admin(subject), <Error<T>>::NoPermission);215		Ok(())216	}217	pub fn ignores_allowance(&self, user: &T::CrossAccountId) -> bool {218		self.limits.owner_can_transfer() && self.is_owner_or_admin(user)219	}220	pub fn ignores_owned_amount(&self, user: &T::CrossAccountId) -> bool {221		self.limits.owner_can_transfer() && self.is_owner_or_admin(user)222	}223	pub fn check_allowlist(&self, user: &T::CrossAccountId) -> DispatchResult {224		ensure!(225			<Allowlist<T>>::get((self.id, user)),226			<Error<T>>::AddressNotInAllowlist227		);228		Ok(())229	}230}231232#[frame_support::pallet]233pub mod pallet {234	use super::*;235	use pallet_evm::account;236	use dispatch::CollectionDispatch;237	use frame_support::{Blake2_128Concat, pallet_prelude::*, storage::Key, traits::StorageVersion};238	use frame_system::pallet_prelude::*;239	use frame_support::traits::Currency;240	use up_data_structs::{TokenId, mapping::TokenAddressMapping};241	use scale_info::TypeInfo;242	use weights::WeightInfo;243244	#[pallet::config]245	pub trait Config:246		frame_system::Config247		+ pallet_evm_coder_substrate::Config248		+ pallet_evm::Config249		+ TypeInfo250		+ account::Config251	{252		type WeightInfo: WeightInfo;253		type Event: IsType<<Self as frame_system::Config>::Event> + From<Event<Self>>;254255		type Currency: Currency<Self::AccountId>;256257		#[pallet::constant]258		type CollectionCreationPrice: Get<259			<<Self as Config>::Currency as Currency<Self::AccountId>>::Balance,260		>;261		type CollectionDispatch: CollectionDispatch<Self>;262263		type TreasuryAccountId: Get<Self::AccountId>;264		type ContractAddress: Get<H160>;265266		type EvmTokenAddressMapping: TokenAddressMapping<H160>;267		type CrossTokenAddressMapping: TokenAddressMapping<Self::CrossAccountId>;268	}269270	const STORAGE_VERSION: StorageVersion = StorageVersion::new(1);271272	#[pallet::pallet]273	#[pallet::storage_version(STORAGE_VERSION)]274	#[pallet::generate_store(pub(super) trait Store)]275	pub struct Pallet<T>(_);276277	#[pallet::extra_constants]278	impl<T: Config> Pallet<T> {279		pub fn collection_admins_limit() -> u32 {280			COLLECTION_ADMINS_LIMIT281		}282	}283284	#[pallet::event]285	#[pallet::generate_deposit(pub fn deposit_event)]286	pub enum Event<T: Config> {287		/// New collection was created288		///289		/// # Arguments290		///291		/// * collection_id: Globally unique identifier of newly created collection.292		///293		/// * mode: [CollectionMode] converted into u8.294		///295		/// * account_id: Collection owner.296		CollectionCreated(CollectionId, u8, T::AccountId),297298		/// New collection was destroyed299		///300		/// # Arguments301		///302		/// * collection_id: Globally unique identifier of collection.303		CollectionDestroyed(CollectionId),304305		/// New item was created.306		///307		/// # Arguments308		///309		/// * collection_id: Id of the collection where item was created.310		///311		/// * item_id: Id of an item. Unique within the collection.312		///313		/// * recipient: Owner of newly created item314		///315		/// * amount: Always 1 for NFT316		ItemCreated(CollectionId, TokenId, T::CrossAccountId, u128),317318		/// Collection item was burned.319		///320		/// # Arguments321		///322		/// * collection_id.323		///324		/// * item_id: Identifier of burned NFT.325		///326		/// * owner: which user has destroyed its tokens327		///328		/// * amount: Always 1 for NFT329		ItemDestroyed(CollectionId, TokenId, T::CrossAccountId, u128),330331		/// Item was transferred332		///333		/// * collection_id: Id of collection to which item is belong334		///335		/// * item_id: Id of an item336		///337		/// * sender: Original owner of item338		///339		/// * recipient: New owner of item340		///341		/// * amount: Always 1 for NFT342		Transfer(343			CollectionId,344			TokenId,345			T::CrossAccountId,346			T::CrossAccountId,347			u128,348		),349350		/// * collection_id351		///352		/// * item_id353		///354		/// * sender355		///356		/// * spender357		///358		/// * amount359		Approved(360			CollectionId,361			TokenId,362			T::CrossAccountId,363			T::CrossAccountId,364			u128,365		),366367		CollectionPropertySet(CollectionId, PropertyKey),368369		CollectionPropertyDeleted(CollectionId, PropertyKey),370371		TokenPropertySet(CollectionId, TokenId, PropertyKey),372373		TokenPropertyDeleted(CollectionId, TokenId, PropertyKey),374375		PropertyPermissionSet(CollectionId, PropertyKey),376	}377378	#[pallet::error]379	pub enum Error<T> {380		/// This collection does not exist.381		CollectionNotFound,382		/// Sender parameter and item owner must be equal.383		MustBeTokenOwner,384		/// No permission to perform action385		NoPermission,386		/// Destroying only empty collections is allowed387		CantDestroyNotEmptyCollection,388		/// Collection is not in mint mode.389		PublicMintingNotAllowed,390		/// Address is not in allow list.391		AddressNotInAllowlist,392393		/// Collection name can not be longer than 63 char.394		CollectionNameLimitExceeded,395		/// Collection description can not be longer than 255 char.396		CollectionDescriptionLimitExceeded,397		/// Token prefix can not be longer than 15 char.398		CollectionTokenPrefixLimitExceeded,399		/// Total collections bound exceeded.400		TotalCollectionsLimitExceeded,401		/// Exceeded max admin count402		CollectionAdminCountExceeded,403		/// Collection limit bounds per collection exceeded404		CollectionLimitBoundsExceeded,405		/// Tried to enable permissions which are only permitted to be disabled406		OwnerPermissionsCantBeReverted,407		/// Collection settings not allowing items transferring408		TransferNotAllowed,409		/// Account token limit exceeded per collection410		AccountTokenLimitExceeded,411		/// Collection token limit exceeded412		CollectionTokenLimitExceeded,413		/// Metadata flag frozen414		MetadataFlagFrozen,415416		/// Item not exists.417		TokenNotFound,418		/// Item balance not enough.419		TokenValueTooLow,420		/// Requested value more than approved.421		ApprovedValueTooLow,422		/// Tried to approve more than owned423		CantApproveMoreThanOwned,424425		/// Can't transfer tokens to ethereum zero address426		AddressIsZero,427		/// Target collection doesn't supports this operation428		UnsupportedOperation,429430		/// Not sufficient funds to perform action431		NotSufficientFounds,432433		/// User not passed nesting rule434		UserIsNotAllowedToNest,435		/// Only tokens from specific collections may nest tokens under this436		SourceCollectionIsNotAllowedToNest,437438		/// Tried to store more data than allowed in collection field439		CollectionFieldSizeExceeded,440441		/// Tried to store more property data than allowed442		NoSpaceForProperty,443444		/// Tried to store more property keys than allowed445		PropertyLimitReached,446447		/// Property key is too long448		PropertyKeyIsTooLong,449450		/// Only ASCII letters, digits, and '_', '-' are allowed451		InvalidCharacterInPropertyKey,452453		/// Empty property keys are forbidden454		EmptyPropertyKey,455456		/// Tried to access an external collection with an internal API457		CollectionIsExternal,458459		/// Tried to access an internal collection with an external API460		CollectionIsInternal,461	}462463	#[pallet::storage]464	pub type CreatedCollectionCount<T> = StorageValue<Value = CollectionId, QueryKind = ValueQuery>;465	#[pallet::storage]466	pub type DestroyedCollectionCount<T> =467		StorageValue<Value = CollectionId, QueryKind = ValueQuery>;468469	/// Collection info470	#[pallet::storage]471	pub type CollectionById<T> = StorageMap<472		Hasher = Blake2_128Concat,473		Key = CollectionId,474		Value = Collection<<T as frame_system::Config>::AccountId>,475		QueryKind = OptionQuery,476	>;477478	/// Collection properties479	#[pallet::storage]480	#[pallet::getter(fn collection_properties)]481	pub type CollectionProperties<T> = StorageMap<482		Hasher = Blake2_128Concat,483		Key = CollectionId,484		Value = Properties,485		QueryKind = ValueQuery,486		OnEmpty = up_data_structs::CollectionProperties,487	>;488489	#[pallet::storage]490	#[pallet::getter(fn property_permissions)]491	pub type CollectionPropertyPermissions<T> = StorageMap<492		Hasher = Blake2_128Concat,493		Key = CollectionId,494		Value = PropertiesPermissionMap,495		QueryKind = ValueQuery,496	>;497498	#[pallet::storage]499	pub type AdminAmount<T> = StorageMap<500		Hasher = Blake2_128Concat,501		Key = CollectionId,502		Value = u32,503		QueryKind = ValueQuery,504	>;505506	/// List of collection admins507	#[pallet::storage]508	pub type IsAdmin<T: Config> = StorageNMap<509		Key = (510			Key<Blake2_128Concat, CollectionId>,511			Key<Blake2_128Concat, T::CrossAccountId>,512		),513		Value = bool,514		QueryKind = ValueQuery,515	>;516517	/// Allowlisted collection users518	#[pallet::storage]519	pub type Allowlist<T: Config> = StorageNMap<520		Key = (521			Key<Blake2_128Concat, CollectionId>,522			Key<Blake2_128Concat, T::CrossAccountId>,523		),524		Value = bool,525		QueryKind = ValueQuery,526	>;527528	/// Not used by code, exists only to provide some types to metadata529	#[pallet::storage]530	pub type DummyStorageValue<T: Config> = StorageValue<531		Value = (532			CollectionStats,533			CollectionId,534			TokenId,535			TokenChild,536			PhantomType<(537				TokenData<T::CrossAccountId>,538				RpcCollection<T::AccountId>,539				// RMRK540				RmrkCollectionInfo<T::AccountId>,541				RmrkInstanceInfo<T::AccountId>,542				RmrkResourceInfo,543				RmrkPropertyInfo,544				RmrkBaseInfo<T::AccountId>,545				RmrkPartType,546				RmrkBoundedTheme,547				RmrkNftChild,548			)>,549		),550		QueryKind = OptionQuery,551	>;552553	#[pallet::hooks]554	impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {555		fn on_runtime_upgrade() -> Weight {556			if StorageVersion::get::<Pallet<T>>() < StorageVersion::new(1) {557				use up_data_structs::{CollectionVersion1, CollectionVersion2};558				<CollectionById<T>>::translate::<CollectionVersion1<T::AccountId>, _>(|id, v| {559					let mut props = Vec::new();560					if !v.offchain_schema.is_empty() {561						props.push(Property {562							key: b"_old_offchainSchema".to_vec().try_into().unwrap(),563							value: v564								.offchain_schema565								.clone()566								.into_inner()567								.try_into()568								.expect("offchain schema too big"),569						});570					}571					if !v.variable_on_chain_schema.is_empty() {572						props.push(Property {573							key: b"_old_variableOnChainSchema".to_vec().try_into().unwrap(),574							value: v575								.variable_on_chain_schema576								.clone()577								.into_inner()578								.try_into()579								.expect("offchain schema too big"),580						});581					}582					if !v.const_on_chain_schema.is_empty() {583						props.push(Property {584							key: b"_old_constOnChainSchema".to_vec().try_into().unwrap(),585							value: v586								.const_on_chain_schema587								.clone()588								.into_inner()589								.try_into()590								.expect("offchain schema too big"),591						});592					}593					props.push(Property {594						key: b"_old_schemaVersion".to_vec().try_into().unwrap(),595						value: match v.schema_version {596							SchemaVersion::ImageURL => b"ImageUrl".as_slice(),597							SchemaVersion::Unique => b"Unique".as_slice(),598						}599						.to_vec()600						.try_into()601						.unwrap(),602					});603					Self::set_scoped_collection_properties(604						id,605						PropertyScope::None,606						props.into_iter(),607					)608					.expect("existing data larger than properties");609					let mut new = CollectionVersion2::from(v.clone());610					new.permissions.access = Some(v.access);611					new.permissions.mint_mode = Some(v.mint_mode);612					Some(new)613				});614			}615616			0617		}618	}619}620621impl<T: Config> Pallet<T> {622	/// Ethereum receiver 0x0000000000000000000000000000000000000000 is reserved, and shouldn't own tokens623	pub fn ensure_correct_receiver(receiver: &T::CrossAccountId) -> DispatchResult {624		ensure!(625			&T::CrossAccountId::from_eth(H160([0; 20])) != receiver,626			<Error<T>>::AddressIsZero627		);628		Ok(())629	}630	pub fn adminlist(collection: CollectionId) -> Vec<T::CrossAccountId> {631		<IsAdmin<T>>::iter_prefix((collection,))632			.map(|(a, _)| a)633			.collect()634	}635	pub fn allowlist(collection: CollectionId) -> Vec<T::CrossAccountId> {636		<Allowlist<T>>::iter_prefix((collection,))637			.map(|(a, _)| a)638			.collect()639	}640	pub fn allowed(collection: CollectionId, user: T::CrossAccountId) -> bool {641		<Allowlist<T>>::get((collection, user))642	}643	pub fn collection_stats() -> CollectionStats {644		let created = <CreatedCollectionCount<T>>::get();645		let destroyed = <DestroyedCollectionCount<T>>::get();646		CollectionStats {647			created: created.0,648			destroyed: destroyed.0,649			alive: created.0 - destroyed.0,650		}651	}652653	pub fn effective_collection_limits(collection: CollectionId) -> Option<CollectionLimits> {654		let collection = <CollectionById<T>>::get(collection);655		if collection.is_none() {656			return None;657		}658659		let collection = collection.unwrap();660		let limits = collection.limits;661		let effective_limits = CollectionLimits {662			account_token_ownership_limit: Some(limits.account_token_ownership_limit()),663			sponsored_data_size: Some(limits.sponsored_data_size()),664			sponsored_data_rate_limit: Some(665				limits666					.sponsored_data_rate_limit667					.unwrap_or(SponsoringRateLimit::SponsoringDisabled),668			),669			token_limit: Some(limits.token_limit()),670			sponsor_transfer_timeout: Some(limits.sponsor_transfer_timeout(671				match collection.mode {672					CollectionMode::NFT => NFT_SPONSOR_TRANSFER_TIMEOUT,673					CollectionMode::Fungible(_) => FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,674					CollectionMode::ReFungible => REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,675				},676			)),677			sponsor_approve_timeout: Some(limits.sponsor_approve_timeout()),678			owner_can_transfer: Some(limits.owner_can_transfer()),679			owner_can_destroy: Some(limits.owner_can_destroy()),680			transfers_enabled: Some(limits.transfers_enabled()),681		};682683		Some(effective_limits)684	}685686	pub fn rpc_collection(collection: CollectionId) -> Option<RpcCollection<T::AccountId>> {687		let Collection {688			name,689			description,690			owner,691			mode,692			token_prefix,693			sponsorship,694			limits,695			permissions,696			external_collection,697		} = <CollectionById<T>>::get(collection)?;698699		let token_property_permissions = <CollectionPropertyPermissions<T>>::get(collection)700			.into_iter()701			.map(|(key, permission)| PropertyKeyPermission { key, permission })702			.collect();703704		let properties = <CollectionProperties<T>>::get(collection)705			.into_iter()706			.map(|(key, value)| Property { key, value })707			.collect();708709		let permissions = CollectionPermissions {710			access: Some(permissions.access()),711			mint_mode: Some(permissions.mint_mode()),712			nesting: Some(permissions.nesting().clone()),713		};714715		Some(RpcCollection {716			name: name.into_inner(),717			description: description.into_inner(),718			owner,719			mode,720			token_prefix: token_prefix.into_inner(),721			sponsorship,722			limits,723			permissions,724			token_property_permissions,725			properties,726			read_only: external_collection,727		})728	}729}730731macro_rules! limit_default {732	($old:ident, $new:ident, $($field:ident $(($arg:expr))? => $check:expr),* $(,)?) => {{733		$(734			if let Some($new) = $new.$field {735				let $old = $old.$field($($arg)?);736				let _ = $new;737				let _ = $old;738				$check739			} else {740				$new.$field = $old.$field741			}742		)*743	}};744}745macro_rules! limit_default_clone {746	($old:ident, $new:ident, $($field:ident $(($arg:expr))? => $check:expr),* $(,)?) => {{747		$(748			if let Some($new) = $new.$field.clone() {749				let $old = $old.$field($($arg)?);750				let _ = $new;751				let _ = $old;752				$check753			} else {754				$new.$field = $old.$field.clone()755			}756		)*757	}};758}759760impl<T: Config> Pallet<T> {761	pub fn init_collection(762		owner: T::CrossAccountId,763		data: CreateCollectionData<T::AccountId>,764		is_external: bool,765	) -> Result<CollectionId, DispatchError> {766		{767			ensure!(768				data.token_prefix.len() <= MAX_TOKEN_PREFIX_LENGTH as usize,769				Error::<T>::CollectionTokenPrefixLimitExceeded770			);771		}772773		let created_count = <CreatedCollectionCount<T>>::get()774			.0775			.checked_add(1)776			.ok_or(ArithmeticError::Overflow)?;777		let destroyed_count = <DestroyedCollectionCount<T>>::get().0;778		let id = CollectionId(created_count);779780		// bound Total number of collections781		ensure!(782			created_count - destroyed_count <= COLLECTION_NUMBER_LIMIT,783			<Error<T>>::TotalCollectionsLimitExceeded784		);785786		// =========787788		let collection = Collection {789			owner: owner.as_sub().clone(),790			name: data.name,791			mode: data.mode.clone(),792			description: data.description,793			token_prefix: data.token_prefix,794			sponsorship: data795				.pending_sponsor796				.map(SponsorshipState::Unconfirmed)797				.unwrap_or_default(),798			limits: data799				.limits800				.map(|limits| Self::clamp_limits(data.mode.clone(), &Default::default(), limits))801				.unwrap_or_else(|| Ok(CollectionLimits::default()))?,802			permissions: data803				.permissions804				.map(|permissions| {805					Self::clamp_permissions(data.mode.clone(), &Default::default(), permissions)806				})807				.unwrap_or_else(|| Ok(CollectionPermissions::default()))?,808			external_collection: is_external,809		};810811		let mut collection_properties = up_data_structs::CollectionProperties::get();812		collection_properties813			.try_set_from_iter(data.properties.into_iter())814			.map_err(<Error<T>>::from)?;815816		CollectionProperties::<T>::insert(id, collection_properties);817818		let mut token_props_permissions = PropertiesPermissionMap::new();819		token_props_permissions820			.try_set_from_iter(data.token_property_permissions.into_iter())821			.map_err(<Error<T>>::from)?;822823		CollectionPropertyPermissions::<T>::insert(id, token_props_permissions);824825		// Take a (non-refundable) deposit of collection creation826		{827			let mut imbalance =828				<<<T as Config>::Currency as Currency<T::AccountId>>::PositiveImbalance>::zero();829			imbalance.subsume(830				<<T as Config>::Currency as Currency<T::AccountId>>::deposit_creating(831					&T::TreasuryAccountId::get(),832					T::CollectionCreationPrice::get(),833				),834			);835			<T as Config>::Currency::settle(836				&owner.as_sub(),837				imbalance,838				WithdrawReasons::TRANSFER,839				ExistenceRequirement::KeepAlive,840			)841			.map_err(|_| Error::<T>::NotSufficientFounds)?;842		}843844		<CreatedCollectionCount<T>>::put(created_count);845		<Pallet<T>>::deposit_event(Event::CollectionCreated(846			id,847			data.mode.id(),848			owner.as_sub().clone(),849		));850		<PalletEvm<T>>::deposit_log(851			erc::CollectionHelpersEvents::CollectionCreated {852				owner: *owner.as_eth(),853				collection_id: eth::collection_id_to_address(id),854			}855			.to_log(T::ContractAddress::get()),856		);857		<CollectionById<T>>::insert(id, collection);858		Ok(id)859	}860861	pub fn destroy_collection(862		collection: CollectionHandle<T>,863		sender: &T::CrossAccountId,864	) -> DispatchResult {865		ensure!(866			collection.limits.owner_can_destroy(),867			<Error<T>>::NoPermission,868		);869		collection.check_is_owner(sender)?;870871		let destroyed_collections = <DestroyedCollectionCount<T>>::get()872			.0873			.checked_add(1)874			.ok_or(ArithmeticError::Overflow)?;875876		// =========877878		<DestroyedCollectionCount<T>>::put(destroyed_collections);879		<CollectionById<T>>::remove(collection.id);880		<AdminAmount<T>>::remove(collection.id);881		<IsAdmin<T>>::remove_prefix((collection.id,), None);882		<Allowlist<T>>::remove_prefix((collection.id,), None);883		<CollectionProperties<T>>::remove(collection.id);884885		<Pallet<T>>::deposit_event(Event::CollectionDestroyed(collection.id));886		Ok(())887	}888889	pub fn set_collection_property(890		collection: &CollectionHandle<T>,891		sender: &T::CrossAccountId,892		property: Property,893	) -> DispatchResult {894		collection.check_is_owner_or_admin(sender)?;895896		CollectionProperties::<T>::try_mutate(collection.id, |properties| {897			let property = property.clone();898			properties.try_set(property.key, property.value)899		})900		.map_err(<Error<T>>::from)?;901902		Self::deposit_event(Event::CollectionPropertySet(collection.id, property.key));903904		Ok(())905	}906907	pub fn set_scoped_collection_property(908		collection_id: CollectionId,909		scope: PropertyScope,910		property: Property,911	) -> DispatchResult {912		CollectionProperties::<T>::try_mutate(collection_id, |properties| {913			properties.try_scoped_set(scope, property.key, property.value)914		})915		.map_err(<Error<T>>::from)?;916917		Ok(())918	}919920	pub fn set_scoped_collection_properties(921		collection_id: CollectionId,922		scope: PropertyScope,923		properties: impl Iterator<Item = Property>,924	) -> DispatchResult {925		CollectionProperties::<T>::try_mutate(collection_id, |stored_properties| {926			stored_properties.try_scoped_set_from_iter(scope, properties)927		})928		.map_err(<Error<T>>::from)?;929930		Ok(())931	}932933	#[transactional]934	pub fn set_collection_properties(935		collection: &CollectionHandle<T>,936		sender: &T::CrossAccountId,937		properties: Vec<Property>,938	) -> DispatchResult {939		for property in properties {940			Self::set_collection_property(collection, sender, property)?;941		}942943		Ok(())944	}945946	pub fn delete_collection_property(947		collection: &CollectionHandle<T>,948		sender: &T::CrossAccountId,949		property_key: PropertyKey,950	) -> DispatchResult {951		collection.check_is_owner_or_admin(sender)?;952953		CollectionProperties::<T>::try_mutate(collection.id, |properties| {954			properties.remove(&property_key)955		})956		.map_err(<Error<T>>::from)?;957958		Self::deposit_event(Event::CollectionPropertyDeleted(959			collection.id,960			property_key,961		));962963		Ok(())964	}965966	#[transactional]967	pub fn delete_collection_properties(968		collection: &CollectionHandle<T>,969		sender: &T::CrossAccountId,970		property_keys: Vec<PropertyKey>,971	) -> DispatchResult {972		for key in property_keys {973			Self::delete_collection_property(collection, sender, key)?;974		}975976		Ok(())977	}978979	// For migrations980	pub fn set_property_permission_unchecked(981		collection: CollectionId,982		property_permission: PropertyKeyPermission,983	) -> DispatchResult {984		<CollectionPropertyPermissions<T>>::try_mutate(collection, |permissions| {985			permissions.try_set(property_permission.key, property_permission.permission)986		})987		.map_err(<Error<T>>::from)?;988		Ok(())989	}990991	pub fn set_property_permission(992		collection: &CollectionHandle<T>,993		sender: &T::CrossAccountId,994		property_permission: PropertyKeyPermission,995	) -> DispatchResult {996		collection.check_is_owner_or_admin(sender)?;997998		let all_permissions = CollectionPropertyPermissions::<T>::get(collection.id);999		let current_permission = all_permissions.get(&property_permission.key);1000		if matches![1001			current_permission,1002			Some(PropertyPermission { mutable: false, .. })1003		] {1004			return Err(<Error<T>>::NoPermission.into());1005		}10061007		CollectionPropertyPermissions::<T>::try_mutate(collection.id, |permissions| {1008			let property_permission = property_permission.clone();1009			permissions.try_set(property_permission.key, property_permission.permission)1010		})1011		.map_err(<Error<T>>::from)?;10121013		Self::deposit_event(Event::PropertyPermissionSet(1014			collection.id,1015			property_permission.key,1016		));10171018		Ok(())1019	}10201021	#[transactional]1022	pub fn set_token_property_permissions(1023		collection: &CollectionHandle<T>,1024		sender: &T::CrossAccountId,1025		property_permissions: Vec<PropertyKeyPermission>,1026	) -> DispatchResult {1027		for prop_pemission in property_permissions {1028			Self::set_property_permission(collection, sender, prop_pemission)?;1029		}10301031		Ok(())1032	}10331034	pub fn get_collection_property(1035		collection_id: CollectionId,1036		key: &PropertyKey,1037	) -> Option<PropertyValue> {1038		Self::collection_properties(collection_id).get(key).cloned()1039	}10401041	pub fn bytes_keys_to_property_keys(1042		keys: Vec<Vec<u8>>,1043	) -> Result<Vec<PropertyKey>, DispatchError> {1044		keys.into_iter()1045			.map(|key| -> Result<PropertyKey, DispatchError> {1046				key.try_into()1047					.map_err(|_| <Error<T>>::PropertyKeyIsTooLong.into())1048			})1049			.collect::<Result<Vec<PropertyKey>, DispatchError>>()1050	}10511052	pub fn filter_collection_properties(1053		collection_id: CollectionId,1054		keys: Option<Vec<PropertyKey>>,1055	) -> Result<Vec<Property>, DispatchError> {1056		let properties = Self::collection_properties(collection_id);10571058		let properties = keys1059			.map(|keys| {1060				keys.into_iter()1061					.filter_map(|key| {1062						properties.get(&key).map(|value| Property {1063							key,1064							value: value.clone(),1065						})1066					})1067					.collect()1068			})1069			.unwrap_or_else(|| {1070				properties1071					.into_iter()1072					.map(|(key, value)| Property { key, value })1073					.collect()1074			});10751076		Ok(properties)1077	}10781079	pub fn filter_property_permissions(1080		collection_id: CollectionId,1081		keys: Option<Vec<PropertyKey>>,1082	) -> Result<Vec<PropertyKeyPermission>, DispatchError> {1083		let permissions = Self::property_permissions(collection_id);10841085		let key_permissions = keys1086			.map(|keys| {1087				keys.into_iter()1088					.filter_map(|key| {1089						permissions1090							.get(&key)1091							.map(|permission| PropertyKeyPermission {1092								key,1093								permission: permission.clone(),1094							})1095					})1096					.collect()1097			})1098			.unwrap_or_else(|| {1099				permissions1100					.into_iter()1101					.map(|(key, permission)| PropertyKeyPermission { key, permission })1102					.collect()1103			});11041105		Ok(key_permissions)1106	}11071108	pub fn toggle_allowlist(1109		collection: &CollectionHandle<T>,1110		sender: &T::CrossAccountId,1111		user: &T::CrossAccountId,1112		allowed: bool,1113	) -> DispatchResult {1114		collection.check_is_owner_or_admin(sender)?;11151116		// =========11171118		if allowed {1119			<Allowlist<T>>::insert((collection.id, user), true);1120		} else {1121			<Allowlist<T>>::remove((collection.id, user));1122		}11231124		Ok(())1125	}11261127	pub fn toggle_admin(1128		collection: &CollectionHandle<T>,1129		sender: &T::CrossAccountId,1130		user: &T::CrossAccountId,1131		admin: bool,1132	) -> DispatchResult {1133		collection.check_is_owner(sender)?;11341135		let was_admin = <IsAdmin<T>>::get((collection.id, user));1136		if was_admin == admin {1137			return Ok(());1138		}1139		let amount = <AdminAmount<T>>::get(collection.id);11401141		if admin {1142			let amount = amount1143				.checked_add(1)1144				.ok_or(<Error<T>>::CollectionAdminCountExceeded)?;1145			ensure!(1146				amount <= Self::collection_admins_limit(),1147				<Error<T>>::CollectionAdminCountExceeded,1148			);11491150			// =========11511152			<AdminAmount<T>>::insert(collection.id, amount);1153			<IsAdmin<T>>::insert((collection.id, user), true);1154		} else {1155			<AdminAmount<T>>::insert(collection.id, amount.saturating_sub(1));1156			<IsAdmin<T>>::remove((collection.id, user));1157		}11581159		Ok(())1160	}11611162	pub fn clamp_limits(1163		mode: CollectionMode,1164		old_limit: &CollectionLimits,1165		mut new_limit: CollectionLimits,1166	) -> Result<CollectionLimits, DispatchError> {1167		let limits = old_limit;1168		limit_default!(old_limit, new_limit,1169			account_token_ownership_limit => ensure!(1170				new_limit <= MAX_TOKEN_OWNERSHIP,1171				<Error<T>>::CollectionLimitBoundsExceeded,1172			),1173			sponsored_data_size => ensure!(1174				new_limit <= CUSTOM_DATA_LIMIT,1175				<Error<T>>::CollectionLimitBoundsExceeded,1176			),11771178			sponsored_data_rate_limit => {},1179			token_limit => ensure!(1180				old_limit >= new_limit && new_limit > 0,1181				<Error<T>>::CollectionTokenLimitExceeded1182			),11831184			sponsor_transfer_timeout(match mode {1185				CollectionMode::NFT => NFT_SPONSOR_TRANSFER_TIMEOUT,1186				CollectionMode::Fungible(_) => FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,1187				CollectionMode::ReFungible => REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,1188			}) => ensure!(1189				new_limit <= MAX_SPONSOR_TIMEOUT,1190				<Error<T>>::CollectionLimitBoundsExceeded,1191			),1192			sponsor_approve_timeout => {},1193			owner_can_transfer => ensure!(1194				!limits.owner_can_transfer_instaled() ||1195				old_limit || !new_limit,1196				<Error<T>>::OwnerPermissionsCantBeReverted,1197			),1198			owner_can_destroy => ensure!(1199				old_limit || !new_limit,1200				<Error<T>>::OwnerPermissionsCantBeReverted,1201			),1202			transfers_enabled => {},1203		);1204		Ok(new_limit)1205	}12061207	pub fn clamp_permissions(1208		_mode: CollectionMode,1209		old_limit: &CollectionPermissions,1210		mut new_limit: CollectionPermissions,1211	) -> Result<CollectionPermissions, DispatchError> {1212		limit_default_clone!(old_limit, new_limit,1213			access => {},1214			mint_mode => {},1215			nesting => { /* todo check for permissive, if only it gets out of benchmarks */ },1216		);1217		Ok(new_limit)1218	}1219}12201221#[macro_export]1222macro_rules! unsupported {1223	() => {1224		Err(<Error<T>>::UnsupportedOperation.into())1225	};1226}12271228/// Worst cases1229pub trait CommonWeightInfo<CrossAccountId> {1230	fn create_item() -> Weight;1231	fn create_multiple_items(amount: &[CreateItemData]) -> Weight;1232	fn create_multiple_items_ex(cost: &CreateItemExData<CrossAccountId>) -> Weight;1233	fn burn_item() -> Weight;1234	fn set_collection_properties(amount: u32) -> Weight;1235	fn delete_collection_properties(amount: u32) -> Weight;1236	fn set_token_properties(amount: u32) -> Weight;1237	fn delete_token_properties(amount: u32) -> Weight;1238	fn set_token_property_permissions(amount: u32) -> Weight;1239	fn transfer() -> Weight;1240	fn approve() -> Weight;1241	fn transfer_from() -> Weight;1242	fn burn_from() -> Weight;12431244	/// Differs from burn_item in case of Fungible and Refungible, as it should burn1245	/// whole users's balance1246	///1247	/// This method shouldn't be used directly, as it doesn't count breadth price, use `burn_recursively` instead1248	fn burn_recursively_self_raw() -> Weight;1249	/// Cost of iterating over `amount` children while burning, without counting child burning itself1250	///1251	/// This method shouldn't be used directly, as it doesn't count depth price, use `burn_recursively` instead1252	fn burn_recursively_breadth_raw(amount: u32) -> Weight;12531254	fn burn_recursively(max_selfs: u32, max_breadth: u32) -> Weight {1255		Self::burn_recursively_self_raw()1256			.saturating_mul(max_selfs.max(1) as u64)1257			.saturating_add(Self::burn_recursively_breadth_raw(max_breadth))1258	}1259}12601261pub trait RefungibleExtensionsWeightInfo {1262	fn repartition() -> Weight;1263}12641265pub trait CommonCollectionOperations<T: Config> {1266	fn create_item(1267		&self,1268		sender: T::CrossAccountId,1269		to: T::CrossAccountId,1270		data: CreateItemData,1271		nesting_budget: &dyn Budget,1272	) -> DispatchResultWithPostInfo;1273	fn create_multiple_items(1274		&self,1275		sender: T::CrossAccountId,1276		to: T::CrossAccountId,1277		data: Vec<CreateItemData>,1278		nesting_budget: &dyn Budget,1279	) -> DispatchResultWithPostInfo;1280	fn create_multiple_items_ex(1281		&self,1282		sender: T::CrossAccountId,1283		data: CreateItemExData<T::CrossAccountId>,1284		nesting_budget: &dyn Budget,1285	) -> DispatchResultWithPostInfo;1286	fn burn_item(1287		&self,1288		sender: T::CrossAccountId,1289		token: TokenId,1290		amount: u128,1291	) -> DispatchResultWithPostInfo;1292	fn burn_item_recursively(1293		&self,1294		sender: T::CrossAccountId,1295		token: TokenId,1296		self_budget: &dyn Budget,1297		breadth_budget: &dyn Budget,1298	) -> DispatchResultWithPostInfo;1299	fn set_collection_properties(1300		&self,1301		sender: T::CrossAccountId,1302		properties: Vec<Property>,1303	) -> DispatchResultWithPostInfo;1304	fn delete_collection_properties(1305		&self,1306		sender: &T::CrossAccountId,1307		property_keys: Vec<PropertyKey>,1308	) -> DispatchResultWithPostInfo;1309	fn set_token_properties(1310		&self,1311		sender: T::CrossAccountId,1312		token_id: TokenId,1313		property: Vec<Property>,1314		nesting_budget: &dyn Budget,1315	) -> DispatchResultWithPostInfo;1316	fn delete_token_properties(1317		&self,1318		sender: T::CrossAccountId,1319		token_id: TokenId,1320		property_keys: Vec<PropertyKey>,1321		nesting_budget: &dyn Budget,1322	) -> DispatchResultWithPostInfo;1323	fn set_token_property_permissions(1324		&self,1325		sender: &T::CrossAccountId,1326		property_permissions: Vec<PropertyKeyPermission>,1327	) -> DispatchResultWithPostInfo;1328	fn transfer(1329		&self,1330		sender: T::CrossAccountId,1331		to: T::CrossAccountId,1332		token: TokenId,1333		amount: u128,1334		nesting_budget: &dyn Budget,1335	) -> DispatchResultWithPostInfo;1336	fn approve(1337		&self,1338		sender: T::CrossAccountId,1339		spender: T::CrossAccountId,1340		token: TokenId,1341		amount: u128,1342	) -> DispatchResultWithPostInfo;1343	fn transfer_from(1344		&self,1345		sender: T::CrossAccountId,1346		from: T::CrossAccountId,1347		to: T::CrossAccountId,1348		token: TokenId,1349		amount: u128,1350		nesting_budget: &dyn Budget,1351	) -> DispatchResultWithPostInfo;1352	fn burn_from(1353		&self,1354		sender: T::CrossAccountId,1355		from: T::CrossAccountId,1356		token: TokenId,1357		amount: u128,1358		nesting_budget: &dyn Budget,1359	) -> DispatchResultWithPostInfo;13601361	fn check_nesting(1362		&self,1363		sender: T::CrossAccountId,1364		from: (CollectionId, TokenId),1365		under: TokenId,1366		nesting_budget: &dyn Budget,1367	) -> DispatchResult;13681369	fn nest(&self, under: TokenId, to_nest: (CollectionId, TokenId));13701371	fn unnest(&self, under: TokenId, to_nest: (CollectionId, TokenId));13721373	fn account_tokens(&self, account: T::CrossAccountId) -> Vec<TokenId>;1374	fn collection_tokens(&self) -> Vec<TokenId>;1375	fn token_exists(&self, token: TokenId) -> bool;1376	fn last_token_id(&self) -> TokenId;13771378	fn token_owner(&self, token: TokenId) -> Option<T::CrossAccountId>;1379	fn token_property(&self, token_id: TokenId, key: &PropertyKey) -> Option<PropertyValue>;1380	fn token_properties(&self, token_id: TokenId, keys: Option<Vec<PropertyKey>>) -> Vec<Property>;1381	/// Amount of unique collection tokens1382	fn total_supply(&self) -> u32;1383	/// Amount of different tokens account has (Applicable to nonfungible/refungible)1384	fn account_balance(&self, account: T::CrossAccountId) -> u32;1385	/// Amount of specific token account have (Applicable to fungible/refungible)1386	fn balance(&self, account: T::CrossAccountId, token: TokenId) -> u128;1387	/// Amount of token pieces1388	fn total_pieces(&self, token: TokenId) -> Option<u128>;1389	fn allowance(1390		&self,1391		sender: T::CrossAccountId,1392		spender: T::CrossAccountId,1393		token: TokenId,1394	) -> u128;1395	fn refungible_extensions(&self) -> Option<&dyn RefungibleExtensions<T>>;1396}13971398pub trait RefungibleExtensions<T>1399where1400	T: Config,1401{1402	fn repartition(1403		&self,1404		owner: &T::CrossAccountId,1405		token: TokenId,1406		amount: u128,1407	) -> DispatchResultWithPostInfo;1408}14091410// Flexible enough for implementing CommonCollectionOperations1411pub fn with_weight(res: DispatchResult, weight: Weight) -> DispatchResultWithPostInfo {1412	let post_info = PostDispatchInfo {1413		actual_weight: Some(weight),1414		pays_fee: Pays::Yes,1415	};1416	match res {1417		Ok(()) => Ok(post_info),1418		Err(error) => Err(DispatchErrorWithPostInfo { post_info, error }),1419	}1420}14211422impl<T: Config> From<PropertiesError> for Error<T> {1423	fn from(error: PropertiesError) -> Self {1424		match error {1425			PropertiesError::NoSpaceForProperty => Self::NoSpaceForProperty,1426			PropertiesError::PropertyLimitReached => Self::PropertyLimitReached,1427			PropertiesError::InvalidCharacterInPropertyKey => Self::InvalidCharacterInPropertyKey,1428			PropertiesError::PropertyKeyIsTooLong => Self::PropertyKeyIsTooLong,1429			PropertiesError::EmptyPropertyKey => Self::EmptyPropertyKey,1430		}1431	}1432}
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 will 38//! 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 various 43//! metadata can be placed.44//! 45//! **Collection property permissions** - For each property in the collection can be set permission 46//! 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 right 52//! to most actions on the collection.535455#![warn(missing_docs)]56#![cfg_attr(not(feature = "std"), no_std)]57extern crate alloc;5859use core::ops::{Deref, DerefMut};60use pallet_evm_coder_substrate::{SubstrateRecorder, WithRecorder};61use sp_std::vec::Vec;62use pallet_evm::{account::CrossAccountId, Pallet as PalletEvm};63use evm_coder::ToLog;64use frame_support::{65	dispatch::{DispatchErrorWithPostInfo, DispatchResultWithPostInfo, Weight, PostDispatchInfo},66	ensure,67	traits::{Imbalance, Get, Currency, WithdrawReasons, ExistenceRequirement},68	weights::Pays,69	transactional,70};71use pallet_evm::GasWeightMapping;72use up_data_structs::{73	COLLECTION_NUMBER_LIMIT,74	Collection,75	RpcCollection,76	CollectionId,77	CreateItemData,78	MAX_TOKEN_PREFIX_LENGTH,79	COLLECTION_ADMINS_LIMIT,80	TokenId,81	TokenChild,82	CollectionStats,83	MAX_TOKEN_OWNERSHIP,84	CollectionMode,85	NFT_SPONSOR_TRANSFER_TIMEOUT,86	FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,87	REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,88	MAX_SPONSOR_TIMEOUT,89	CUSTOM_DATA_LIMIT,90	CollectionLimits,91	CreateCollectionData,92	SponsorshipState,93	CreateItemExData,94	SponsoringRateLimit,95	budget::Budget,96	PhantomType,97	Property,98	Properties,99	PropertiesPermissionMap,100	PropertyKey,101	PropertyValue,102	PropertyPermission,103	PropertiesError,104	PropertyKeyPermission,105	TokenData,106	TrySetProperty,107	PropertyScope,108	// RMRK109	RmrkCollectionInfo,110	RmrkInstanceInfo,111	RmrkResourceInfo,112	RmrkPropertyInfo,113	RmrkBaseInfo,114	RmrkPartType,115	RmrkBoundedTheme,116	RmrkNftChild,117	CollectionPermissions,118	SchemaVersion,119};120121pub use pallet::*;122use sp_core::H160;123use sp_runtime::{ArithmeticError, DispatchError, DispatchResult};124#[cfg(feature = "runtime-benchmarks")]125pub mod benchmarking;126pub mod dispatch;127pub mod erc;128pub mod eth;129pub mod weights;130131/// Weight info.132pub type SelfWeightOf<T> = <T as Config>::WeightInfo;133134/// Collection handle contains information about collection data and id. 135/// Also provides functionality to count consumed gas.136#[must_use = "Should call submit_logs or save, otherwise some data will be lost for evm side"]137pub struct CollectionHandle<T: Config> {138	/// Collection id139	pub id: CollectionId,140	collection: Collection<T::AccountId>,141	/// Substrate recorder for counting consumed gas142	pub recorder: SubstrateRecorder<T>,143}144145impl<T: Config> WithRecorder<T> for CollectionHandle<T> {146	fn recorder(&self) -> &SubstrateRecorder<T> {147		&self.recorder148	}149	fn into_recorder(self) -> SubstrateRecorder<T> {150		self.recorder151	}152}153154impl<T: Config> CollectionHandle<T> {155	/// Same as [CollectionHandle::new] but with an explicit gas limit.156	pub fn new_with_gas_limit(id: CollectionId, gas_limit: u64) -> Option<Self> {157		<CollectionById<T>>::get(id).map(|collection| Self {158			id,159			collection,160			recorder: SubstrateRecorder::new(gas_limit),161		})162	}163164	/// Same as [CollectionHandle::new] but with an existed [SubstrateRecorder].165	pub fn new_with_recorder(id: CollectionId, recorder: SubstrateRecorder<T>) -> Option<Self> {166		<CollectionById<T>>::get(id).map(|collection| Self {167			id,168			collection,169			recorder,170		})171	}172173	/// Retrives collection data from storage and creates collection handle with default parameters.174	/// If collection not found return `None`175	pub fn new(id: CollectionId) -> Option<Self> {176		Self::new_with_gas_limit(id, u64::MAX)177	}178179	/// Same as [CollectionHandle::new] but if collection not found [Error::CollectionNotFound] returned.180	pub fn try_get(id: CollectionId) -> Result<Self, DispatchError> {181		Ok(Self::new(id).ok_or(<Error<T>>::CollectionNotFound)?)182	}183184	/// Consume gas for reading.185	pub fn consume_store_reads(&self, reads: u64) -> evm_coder::execution::Result<()> {186		self.recorder187			.consume_gas(T::GasWeightMapping::weight_to_gas(188				<T as frame_system::Config>::DbWeight::get()189					.read190					.saturating_mul(reads),191			))192	}193194	/// Consume gas for writing.195	pub fn consume_store_writes(&self, writes: u64) -> evm_coder::execution::Result<()> {196		self.recorder197			.consume_gas(T::GasWeightMapping::weight_to_gas(198				<T as frame_system::Config>::DbWeight::get()199					.write200					.saturating_mul(writes),201			))202	}203204	/// Save collection to storage.205	pub fn save(self) -> DispatchResult {206		<CollectionById<T>>::insert(self.id, self.collection);207		Ok(())208	}209210	/// Set collection sponsor.211	/// 212	/// Unique collections allows sponsoring for certain actions. 213	/// This method allows you to set the sponsor of the collection. 214	/// In order for sponsorship to become active, it must be confirmed through [Self::confirm_sponsorship].215	pub fn set_sponsor(&mut self, sponsor: T::AccountId) -> DispatchResult {216		self.collection.sponsorship = SponsorshipState::Unconfirmed(sponsor);217		Ok(())218	}219220	/// Confirm sponsorship221	/// 222	/// In order for the sponsorship to become active, the user set as the sponsor must confirm their participation.223	/// Before confirming sponsorship, the user must be specified as the sponsor of the collection via [Self::set_sponsor].224	pub fn confirm_sponsorship(&mut self, sender: &T::AccountId) -> Result<bool, DispatchError> {225		if self.collection.sponsorship.pending_sponsor() != Some(sender) {226			return Ok(false);227		}228229		self.collection.sponsorship = SponsorshipState::Confirmed(sender.clone());230		Ok(true)231	}232233	/// Checks that the collection was created with, and must be operated upon through **Unique API**.234	/// Now check only the `external_collection` flag and if it's **true**, then return [Error::CollectionIsExternal] error.235	pub fn check_is_internal(&self) -> DispatchResult {236		if self.external_collection {237			return Err(<Error<T>>::CollectionIsExternal)?;238		}239240		Ok(())241	}242243	/// Checks that the collection was created with, and must be operated upon through an **assimilated API**.244	/// Now check only the `external_collection` flag and if it's **false**, then return [Error::CollectionIsInternal] error.245	pub fn check_is_external(&self) -> DispatchResult {246		if !self.external_collection {247			return Err(<Error<T>>::CollectionIsInternal)?;248		}249250		Ok(())251	}252}253254impl<T: Config> Deref for CollectionHandle<T> {255	type Target = Collection<T::AccountId>;256257	fn deref(&self) -> &Self::Target {258		&self.collection259	}260}261262impl<T: Config> DerefMut for CollectionHandle<T> {263	fn deref_mut(&mut self) -> &mut Self::Target {264		&mut self.collection265	}266}267268impl<T: Config> CollectionHandle<T> {269	/// Checks if the `user` is the owner of the collection.270	pub fn check_is_owner(&self, user: &T::CrossAccountId) -> DispatchResult {271		ensure!(*user.as_sub() == self.owner, <Error<T>>::NoPermission);272		Ok(())273	}274275	/// Returns **true** if the `user` is the owner or administrator of the collection.276	pub fn is_owner_or_admin(&self, user: &T::CrossAccountId) -> bool {277		*user.as_sub() == self.owner || <IsAdmin<T>>::get((self.id, user))278	}279280	/// Checks if the `user` is the owner or administrator of the collection.281	pub fn check_is_owner_or_admin(&self, user: &T::CrossAccountId) -> DispatchResult {282		ensure!(self.is_owner_or_admin(user), <Error<T>>::NoPermission);283		Ok(())284	}285286	/// Return **true** if `user` was not allowed to have tokens, and he can ignore such restrictions.287	pub fn ignores_allowance(&self, user: &T::CrossAccountId) -> bool {288		self.limits.owner_can_transfer() && self.is_owner_or_admin(user)289	}290291	/// Return **true** if `user` does not have enough token parts, and he can ignore such restrictions.292	pub fn ignores_owned_amount(&self, user: &T::CrossAccountId) -> bool {293		self.limits.owner_can_transfer() && self.is_owner_or_admin(user)294	}295296	/// Checks if the user is in the allow list. If not [Error::AddressNotInAllowlist] returns.297	pub fn check_allowlist(&self, user: &T::CrossAccountId) -> DispatchResult {298		ensure!(299			<Allowlist<T>>::get((self.id, user)),300			<Error<T>>::AddressNotInAllowlist301		);302		Ok(())303	}304}305306#[frame_support::pallet]307pub mod pallet {308	use super::*;309	use pallet_evm::account;310	use dispatch::CollectionDispatch;311	use frame_support::{Blake2_128Concat, pallet_prelude::*, storage::Key, traits::StorageVersion};312	use frame_system::pallet_prelude::*;313	use frame_support::traits::Currency;314	use up_data_structs::{TokenId, mapping::TokenAddressMapping};315	use scale_info::TypeInfo;316	use weights::WeightInfo;317318	#[pallet::config]319	pub trait Config:320		frame_system::Config321		+ pallet_evm_coder_substrate::Config322		+ pallet_evm::Config323		+ TypeInfo324		+ account::Config325	{326		/// Weight info.327		type WeightInfo: WeightInfo;328329		/// Events compatible with [frame_system::Config::Event].330		type Event: IsType<<Self as frame_system::Config>::Event> + From<Event<Self>>;331332		/// Currency.333		type Currency: Currency<Self::AccountId>;334335		/// Price getter to create the collection.336		#[pallet::constant]337		type CollectionCreationPrice: Get<338			<<Self as Config>::Currency as Currency<Self::AccountId>>::Balance,339		>;340341		/// Collection dispatcher.342		type CollectionDispatch: CollectionDispatch<Self>;343344		/// Treasury account id getter.345		type TreasuryAccountId: Get<Self::AccountId>;346347		/// Contract address getter.348		type ContractAddress: Get<H160>;349350		/// Mapper for tokens to Etherium addresses.351		type EvmTokenAddressMapping: TokenAddressMapping<H160>;352353		/// Mapper for tokens to [CrossAccountId].354		type CrossTokenAddressMapping: TokenAddressMapping<Self::CrossAccountId>;355	}356357	const STORAGE_VERSION: StorageVersion = StorageVersion::new(1);358359	#[pallet::pallet]360	#[pallet::storage_version(STORAGE_VERSION)]361	#[pallet::generate_store(pub(super) trait Store)]362	pub struct Pallet<T>(_);363364	#[pallet::extra_constants]365	impl<T: Config> Pallet<T> {366		/// Maximum admins per collection.367		pub fn collection_admins_limit() -> u32 {368			COLLECTION_ADMINS_LIMIT369		}370	}371372	#[pallet::event]373	#[pallet::generate_deposit(pub fn deposit_event)]374	pub enum Event<T: Config> {375		/// New collection was created376		CollectionCreated(377			/// Globally unique identifier of newly created collection.378			CollectionId,379			/// [CollectionMode] converted into _u8_.380			u8,381			/// Collection owner.382			T::AccountId383		),384385		/// New collection was destroyed386		CollectionDestroyed(387			/// Globally unique identifier of collection.388			CollectionId389		),390391		/// New item was created.392		ItemCreated(393			/// Id of the collection where item was created.394			CollectionId,395			/// Id of an item. Unique within the collection.396			TokenId,397			/// Owner of newly created item398			T::CrossAccountId,399			/// Always 1 for NFT400			u128401		),402403		/// Collection item was burned.404		ItemDestroyed(405			/// Id of the collection where item was destroyed.406			CollectionId,407			/// Identifier of burned NFT.408			TokenId,409			/// Which user has destroyed its tokens.410			T::CrossAccountId,411			/// Amount of token pieces destroed. Always 1 for NFT.412			u128),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			PropertyKey448		),449		450		/// 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			PropertyKey456		),457		458		/// 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			PropertyKey466		),467		468		469		/// The token property has been deleted.470		TokenPropertyDeleted(471			/// Identifier of the collection whose token has the property deleted.472			CollectionId,473			/// The token for which the property was deleted.474			TokenId,475			/// The property that was deleted.476			PropertyKey477		),478		479		/// The colletion property permission has been set.480		PropertyPermissionSet(481			/// Id of collection to which property permission has been set.482			CollectionId,483			/// The property permission that was set.484			PropertyKey485		),486	}487488	#[pallet::error]489	pub enum Error<T> {490		/// This collection does not exist.491		CollectionNotFound,492		/// Sender parameter and item owner must be equal.493		MustBeTokenOwner,494		/// No permission to perform action495		NoPermission,496		/// Destroying only empty collections is allowed497		CantDestroyNotEmptyCollection,498		/// Collection is not in mint mode.499		PublicMintingNotAllowed,500		/// Address is not in allow list.501		AddressNotInAllowlist,502503		/// Collection name can not be longer than 63 char.504		CollectionNameLimitExceeded,505		/// Collection description can not be longer than 255 char.506		CollectionDescriptionLimitExceeded,507		/// Token prefix can not be longer than 15 char.508		CollectionTokenPrefixLimitExceeded,509		/// Total collections bound exceeded.510		TotalCollectionsLimitExceeded,511		/// Exceeded max admin count512		CollectionAdminCountExceeded,513		/// Collection limit bounds per collection exceeded514		CollectionLimitBoundsExceeded,515		/// Tried to enable permissions which are only permitted to be disabled516		OwnerPermissionsCantBeReverted,517		/// Collection settings not allowing items transferring518		TransferNotAllowed,519		/// Account token limit exceeded per collection520		AccountTokenLimitExceeded,521		/// Collection token limit exceeded522		CollectionTokenLimitExceeded,523		/// Metadata flag frozen524		MetadataFlagFrozen,525526		/// Item not exists.527		TokenNotFound,528		/// Item balance not enough.529		TokenValueTooLow,530		/// Requested value more than approved.531		ApprovedValueTooLow,532		/// Tried to approve more than owned533		CantApproveMoreThanOwned,534535		/// Can't transfer tokens to ethereum zero address536		AddressIsZero,537		/// Target collection doesn't supports this operation538		UnsupportedOperation,539540		/// Not sufficient funds to perform action541		NotSufficientFounds,542543		/// User not passed nesting rule544		UserIsNotAllowedToNest,545		/// Only tokens from specific collections may nest tokens under this546		SourceCollectionIsNotAllowedToNest,547548		/// Tried to store more data than allowed in collection field549		CollectionFieldSizeExceeded,550551		/// Tried to store more property data than allowed552		NoSpaceForProperty,553554		/// Tried to store more property keys than allowed555		PropertyLimitReached,556557		/// Property key is too long558		PropertyKeyIsTooLong,559560		/// Only ASCII letters, digits, and '_', '-' are allowed561		InvalidCharacterInPropertyKey,562563		/// Empty property keys are forbidden564		EmptyPropertyKey,565566		/// Tried to access an external collection with an internal API567		CollectionIsExternal,568569		/// Tried to access an internal collection with an external API570		CollectionIsInternal,571	}572573	/// Storage of the count of created collections.574	#[pallet::storage]575	pub type CreatedCollectionCount<T> = StorageValue<Value = CollectionId, QueryKind = ValueQuery>;576577	/// Storage of the count of deleted collections.578	#[pallet::storage]579	pub type DestroyedCollectionCount<T> =580		StorageValue<Value = CollectionId, QueryKind = ValueQuery>;581582	/// Storage of collection info.583	#[pallet::storage]584	pub type CollectionById<T> = StorageMap<585		Hasher = Blake2_128Concat,586		Key = CollectionId,587		Value = Collection<<T as frame_system::Config>::AccountId>,588		QueryKind = OptionQuery,589	>;590591	/// Storage of collection properties.592	#[pallet::storage]593	#[pallet::getter(fn collection_properties)]594	pub type CollectionProperties<T> = StorageMap<595		Hasher = Blake2_128Concat,596		Key = CollectionId,597		Value = Properties,598		QueryKind = ValueQuery,599		OnEmpty = up_data_structs::CollectionProperties,600	>;601602	/// Storage of collection properties permissions.603	#[pallet::storage]604	#[pallet::getter(fn property_permissions)]605	pub type CollectionPropertyPermissions<T> = StorageMap<606		Hasher = Blake2_128Concat,607		Key = CollectionId,608		Value = PropertiesPermissionMap,609		QueryKind = ValueQuery,610	>;611612	/// Storage of collection admins count.613	#[pallet::storage]614	pub type AdminAmount<T> = StorageMap<615		Hasher = Blake2_128Concat,616		Key = CollectionId,617		Value = u32,618		QueryKind = ValueQuery,619	>;620621	/// List of collection admins622	#[pallet::storage]623	pub type IsAdmin<T: Config> = StorageNMap<624		Key = (625			Key<Blake2_128Concat, CollectionId>,626			Key<Blake2_128Concat, T::CrossAccountId>,627		),628		Value = bool,629		QueryKind = ValueQuery,630	>;631632	/// Allowlisted collection users633	#[pallet::storage]634	pub type Allowlist<T: Config> = StorageNMap<635		Key = (636			Key<Blake2_128Concat, CollectionId>,637			Key<Blake2_128Concat, T::CrossAccountId>,638		),639		Value = bool,640		QueryKind = ValueQuery,641	>;642643	/// Not used by code, exists only to provide some types to metadata.644	#[pallet::storage]645	pub type DummyStorageValue<T: Config> = StorageValue<646		Value = (647			CollectionStats,648			CollectionId,649			TokenId,650			TokenChild,651			PhantomType<(652				TokenData<T::CrossAccountId>,653				RpcCollection<T::AccountId>,654				// RMRK655				RmrkCollectionInfo<T::AccountId>,656				RmrkInstanceInfo<T::AccountId>,657				RmrkResourceInfo,658				RmrkPropertyInfo,659				RmrkBaseInfo<T::AccountId>,660				RmrkPartType,661				RmrkBoundedTheme,662				RmrkNftChild,663			)>,664		),665		QueryKind = OptionQuery,666	>;667668	#[pallet::hooks]669	impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {670		fn on_runtime_upgrade() -> Weight {671			if StorageVersion::get::<Pallet<T>>() < StorageVersion::new(1) {672				use up_data_structs::{CollectionVersion1, CollectionVersion2};673				<CollectionById<T>>::translate::<CollectionVersion1<T::AccountId>, _>(|id, v| {674					let mut props = Vec::new();675					if !v.offchain_schema.is_empty() {676						props.push(Property {677							key: b"_old_offchainSchema".to_vec().try_into().unwrap(),678							value: v679								.offchain_schema680								.clone()681								.into_inner()682								.try_into()683								.expect("offchain schema too big"),684						});685					}686					if !v.variable_on_chain_schema.is_empty() {687						props.push(Property {688							key: b"_old_variableOnChainSchema".to_vec().try_into().unwrap(),689							value: v690								.variable_on_chain_schema691								.clone()692								.into_inner()693								.try_into()694								.expect("offchain schema too big"),695						});696					}697					if !v.const_on_chain_schema.is_empty() {698						props.push(Property {699							key: b"_old_constOnChainSchema".to_vec().try_into().unwrap(),700							value: v701								.const_on_chain_schema702								.clone()703								.into_inner()704								.try_into()705								.expect("offchain schema too big"),706						});707					}708					props.push(Property {709						key: b"_old_schemaVersion".to_vec().try_into().unwrap(),710						value: match v.schema_version {711							SchemaVersion::ImageURL => b"ImageUrl".as_slice(),712							SchemaVersion::Unique => b"Unique".as_slice(),713						}714						.to_vec()715						.try_into()716						.unwrap(),717					});718					Self::set_scoped_collection_properties(719						id,720						PropertyScope::None,721						props.into_iter(),722					)723					.expect("existing data larger than properties");724					let mut new = CollectionVersion2::from(v.clone());725					new.permissions.access = Some(v.access);726					new.permissions.mint_mode = Some(v.mint_mode);727					Some(new)728				});729			}730731			0732		}733	}734}735736impl<T: Config> Pallet<T> {737	/// Enshure that receiver address is correct.738	/// 739	/// Ethereum receiver 0x0000000000000000000000000000000000000000 is reserved, and shouldn't own tokens.740	pub fn ensure_correct_receiver(receiver: &T::CrossAccountId) -> DispatchResult {741		ensure!(742			&T::CrossAccountId::from_eth(H160([0; 20])) != receiver,743			<Error<T>>::AddressIsZero744		);745		Ok(())746	}747748	/// Get a vector of collection admins.749	pub fn adminlist(collection: CollectionId) -> Vec<T::CrossAccountId> {750		<IsAdmin<T>>::iter_prefix((collection,))751			.map(|(a, _)| a)752			.collect()753	}754755	/// Get a vector of users allowed to mint tokens.756	pub fn allowlist(collection: CollectionId) -> Vec<T::CrossAccountId> {757		<Allowlist<T>>::iter_prefix((collection,))758			.map(|(a, _)| a)759			.collect()760	}761762	/// Is `user` allowed to mint token in `collection`.763	pub fn allowed(collection: CollectionId, user: T::CrossAccountId) -> bool {764		<Allowlist<T>>::get((collection, user))765	}766767	/// Get statistics of collections.768	pub fn collection_stats() -> CollectionStats {769		let created = <CreatedCollectionCount<T>>::get();770		let destroyed = <DestroyedCollectionCount<T>>::get();771		CollectionStats {772			created: created.0,773			destroyed: destroyed.0,774			alive: created.0 - destroyed.0,775		}776	}777778	/// Get the effective limits for the collection.779	pub fn effective_collection_limits(collection: CollectionId) -> Option<CollectionLimits> {780		let collection = <CollectionById<T>>::get(collection);781		if collection.is_none() {782			return None;783		}784785		let collection = collection.unwrap();786		let limits = collection.limits;787		let effective_limits = CollectionLimits {788			account_token_ownership_limit: Some(limits.account_token_ownership_limit()),789			sponsored_data_size: Some(limits.sponsored_data_size()),790			sponsored_data_rate_limit: Some(791				limits792					.sponsored_data_rate_limit793					.unwrap_or(SponsoringRateLimit::SponsoringDisabled),794			),795			token_limit: Some(limits.token_limit()),796			sponsor_transfer_timeout: Some(limits.sponsor_transfer_timeout(797				match collection.mode {798					CollectionMode::NFT => NFT_SPONSOR_TRANSFER_TIMEOUT,799					CollectionMode::Fungible(_) => FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,800					CollectionMode::ReFungible => REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,801				},802			)),803			sponsor_approve_timeout: Some(limits.sponsor_approve_timeout()),804			owner_can_transfer: Some(limits.owner_can_transfer()),805			owner_can_destroy: Some(limits.owner_can_destroy()),806			transfers_enabled: Some(limits.transfers_enabled()),807		};808809		Some(effective_limits)810	}811812	/// Returns information about the `collection` adapted for rpc.813	pub fn rpc_collection(collection: CollectionId) -> Option<RpcCollection<T::AccountId>> {814		let Collection {815			name,816			description,817			owner,818			mode,819			token_prefix,820			sponsorship,821			limits,822			permissions,823			external_collection,824		} = <CollectionById<T>>::get(collection)?;825826		let token_property_permissions = <CollectionPropertyPermissions<T>>::get(collection)827			.into_iter()828			.map(|(key, permission)| PropertyKeyPermission { key, permission })829			.collect();830831		let properties = <CollectionProperties<T>>::get(collection)832			.into_iter()833			.map(|(key, value)| Property { key, value })834			.collect();835836		let permissions = CollectionPermissions {837			access: Some(permissions.access()),838			mint_mode: Some(permissions.mint_mode()),839			nesting: Some(permissions.nesting().clone()),840		};841842		Some(RpcCollection {843			name: name.into_inner(),844			description: description.into_inner(),845			owner,846			mode,847			token_prefix: token_prefix.into_inner(),848			sponsorship,849			limits,850			permissions,851			token_property_permissions,852			properties,853			read_only: external_collection,854		})855	}856}857858macro_rules! limit_default {859	($old:ident, $new:ident, $($field:ident $(($arg:expr))? => $check:expr),* $(,)?) => {{860		$(861			if let Some($new) = $new.$field {862				let $old = $old.$field($($arg)?);863				let _ = $new;864				let _ = $old;865				$check866			} else {867				$new.$field = $old.$field868			}869		)*870	}};871}872macro_rules! limit_default_clone {873	($old:ident, $new:ident, $($field:ident $(($arg:expr))? => $check:expr),* $(,)?) => {{874		$(875			if let Some($new) = $new.$field.clone() {876				let $old = $old.$field($($arg)?);877				let _ = $new;878				let _ = $old;879				$check880			} else {881				$new.$field = $old.$field.clone()882			}883		)*884	}};885}886887impl<T: Config> Pallet<T> {888	/// Create new collection.889	/// 890	/// * `owner` - The owner of the collection.891	/// * `data` - Description of the created collection.892	/// * `is_external` - Marks that collection managet by not "Unique network".893	pub fn init_collection(894		owner: T::CrossAccountId,895		data: CreateCollectionData<T::AccountId>, 896		is_external: bool,897	) -> Result<CollectionId, DispatchError> {898		{899			ensure!(900				data.token_prefix.len() <= MAX_TOKEN_PREFIX_LENGTH as usize,901				Error::<T>::CollectionTokenPrefixLimitExceeded902			);903		}904905		let created_count = <CreatedCollectionCount<T>>::get()906			.0907			.checked_add(1)908			.ok_or(ArithmeticError::Overflow)?;909		let destroyed_count = <DestroyedCollectionCount<T>>::get().0;910		let id = CollectionId(created_count);911912		// bound Total number of collections913		ensure!(914			created_count - destroyed_count <= COLLECTION_NUMBER_LIMIT,915			<Error<T>>::TotalCollectionsLimitExceeded916		);917918		// =========919920		let collection = Collection {921			owner: owner.as_sub().clone(),922			name: data.name,923			mode: data.mode.clone(),924			description: data.description,925			token_prefix: data.token_prefix,926			sponsorship: data927				.pending_sponsor928				.map(SponsorshipState::Unconfirmed)929				.unwrap_or_default(),930			limits: data931				.limits932				.map(|limits| Self::clamp_limits(data.mode.clone(), &Default::default(), limits))933				.unwrap_or_else(|| Ok(CollectionLimits::default()))?,934			permissions: data935				.permissions936				.map(|permissions| {937					Self::clamp_permissions(data.mode.clone(), &Default::default(), permissions)938				})939				.unwrap_or_else(|| Ok(CollectionPermissions::default()))?,940			external_collection: is_external,941		};942943		let mut collection_properties = up_data_structs::CollectionProperties::get();944		collection_properties945			.try_set_from_iter(data.properties.into_iter())946			.map_err(<Error<T>>::from)?;947948		CollectionProperties::<T>::insert(id, collection_properties);949950		let mut token_props_permissions = PropertiesPermissionMap::new();951		token_props_permissions952			.try_set_from_iter(data.token_property_permissions.into_iter())953			.map_err(<Error<T>>::from)?;954955		CollectionPropertyPermissions::<T>::insert(id, token_props_permissions);956957		// Take a (non-refundable) deposit of collection creation958		{959			let mut imbalance =960				<<<T as Config>::Currency as Currency<T::AccountId>>::PositiveImbalance>::zero();961			imbalance.subsume(962				<<T as Config>::Currency as Currency<T::AccountId>>::deposit_creating(963					&T::TreasuryAccountId::get(),964					T::CollectionCreationPrice::get(),965				),966			);967			<T as Config>::Currency::settle(968				&owner.as_sub(),969				imbalance,970				WithdrawReasons::TRANSFER,971				ExistenceRequirement::KeepAlive,972			)973			.map_err(|_| Error::<T>::NotSufficientFounds)?;974		}975976		<CreatedCollectionCount<T>>::put(created_count);977		<Pallet<T>>::deposit_event(Event::CollectionCreated(978			id,979			data.mode.id(),980			owner.as_sub().clone(),981		));982		<PalletEvm<T>>::deposit_log(983			erc::CollectionHelpersEvents::CollectionCreated {984				owner: *owner.as_eth(),985				collection_id: eth::collection_id_to_address(id),986			}987			.to_log(T::ContractAddress::get()),988		);989		<CollectionById<T>>::insert(id, collection);990		Ok(id)991	}992993	/// Destroy collection.994	/// 995	/// * `collection` - Collection handler.996	/// * `sender` - The owner or administrator of the collection.997	pub fn destroy_collection(998		collection: CollectionHandle<T>,999		sender: &T::CrossAccountId,1000	) -> DispatchResult {1001		ensure!(1002			collection.limits.owner_can_destroy(),1003			<Error<T>>::NoPermission,1004		);1005		collection.check_is_owner(sender)?;10061007		let destroyed_collections = <DestroyedCollectionCount<T>>::get()1008			.01009			.checked_add(1)1010			.ok_or(ArithmeticError::Overflow)?;10111012		// =========10131014		<DestroyedCollectionCount<T>>::put(destroyed_collections);1015		<CollectionById<T>>::remove(collection.id);1016		<AdminAmount<T>>::remove(collection.id);1017		<IsAdmin<T>>::remove_prefix((collection.id,), None);1018		<Allowlist<T>>::remove_prefix((collection.id,), None);1019		<CollectionProperties<T>>::remove(collection.id);10201021		<Pallet<T>>::deposit_event(Event::CollectionDestroyed(collection.id));1022		Ok(())1023	}10241025	/// Set collection property.1026	/// 1027	/// * `collection` - Collection handler.1028	/// * `sender` - The owner or administrator of the collection.1029	/// * `property` - The property to set.1030	pub fn set_collection_property(1031		collection: &CollectionHandle<T>,1032		sender: &T::CrossAccountId,1033		property: Property,1034	) -> DispatchResult {1035		collection.check_is_owner_or_admin(sender)?;10361037		CollectionProperties::<T>::try_mutate(collection.id, |properties| {1038			let property = property.clone();1039			properties.try_set(property.key, property.value)1040		})1041		.map_err(<Error<T>>::from)?;10421043		Self::deposit_event(Event::CollectionPropertySet(collection.id, property.key));10441045		Ok(())1046	}10471048	/// Set scouped collection property.1049	/// 1050	/// * `collection_id` - ID of the collection for which the property is being set.1051	/// * `scope` - Property scope.1052	/// * `property` - The property to set.1053	pub fn set_scoped_collection_property(1054		collection_id: CollectionId,1055		scope: PropertyScope,1056		property: Property,1057	) -> DispatchResult {1058		CollectionProperties::<T>::try_mutate(collection_id, |properties| {1059			properties.try_scoped_set(scope, property.key, property.value)1060		})1061		.map_err(<Error<T>>::from)?;1062		1063		Ok(())1064	}1065	1066	/// Set scouped collection properties.1067	/// 1068	/// * `collection_id` - ID of the collection for which the properties is being set.1069	/// * `scope` - Property scope.1070	/// * `properties` - The properties to set.1071	pub fn set_scoped_collection_properties(1072		collection_id: CollectionId,1073		scope: PropertyScope,1074		properties: impl Iterator<Item = Property>,1075	) -> DispatchResult {1076		CollectionProperties::<T>::try_mutate(collection_id, |stored_properties| {1077			stored_properties.try_scoped_set_from_iter(scope, properties)1078		})1079		.map_err(<Error<T>>::from)?;10801081		Ok(())1082	}10831084	/// Set collection properties.1085	/// 1086	/// * `collection` - Collection handler.1087	/// * `sender` - The owner or administrator of the collection.1088	/// * `properties` - The properties to set.1089	#[transactional]1090	pub fn set_collection_properties(1091		collection: &CollectionHandle<T>,1092		sender: &T::CrossAccountId,1093		properties: Vec<Property>,1094	) -> DispatchResult {1095		for property in properties {1096			Self::set_collection_property(collection, sender, property)?;1097		}1098		1099		Ok(())1100	}1101	1102	/// Delete collection property.1103	/// 1104	/// * `collection` - Collection handler.1105	/// * `sender` - The owner or administrator of the collection.1106	/// * `property` - The property to delete.1107	pub fn delete_collection_property(1108		collection: &CollectionHandle<T>,1109		sender: &T::CrossAccountId,1110		property_key: PropertyKey,1111	) -> DispatchResult {1112		collection.check_is_owner_or_admin(sender)?;1113		1114		CollectionProperties::<T>::try_mutate(collection.id, |properties| {1115			properties.remove(&property_key)1116		})1117		.map_err(<Error<T>>::from)?;1118		1119		Self::deposit_event(Event::CollectionPropertyDeleted(1120			collection.id,1121			property_key,1122		));1123		1124		Ok(())1125	}1126	1127	/// Delete collection properties.1128	/// 1129	/// * `collection` - Collection handler.1130	/// * `sender` - The owner or administrator of the collection.1131	/// * `properties` - The properties to delete.1132	#[transactional]1133	pub fn delete_collection_properties(1134		collection: &CollectionHandle<T>,1135		sender: &T::CrossAccountId,1136		property_keys: Vec<PropertyKey>,1137	) -> DispatchResult {1138		for key in property_keys {1139			Self::delete_collection_property(collection, sender, key)?;1140		}1141		1142		Ok(())1143	}1144	1145	/// Set collection propetry permission without any checks.1146	/// 1147	/// Used for migrations.1148	/// 1149	/// * `collection` - Collection handler.1150	/// * `property_permissions` - Property permissions.1151	pub fn set_property_permission_unchecked(1152		collection: CollectionId,1153		property_permission: PropertyKeyPermission,1154	) -> DispatchResult {1155		<CollectionPropertyPermissions<T>>::try_mutate(collection, |permissions| {1156			permissions.try_set(property_permission.key, property_permission.permission)1157		})1158		.map_err(<Error<T>>::from)?;1159		Ok(())1160	}11611162	/// Set collection property permission.1163	/// 1164	/// * `collection` - Collection handler.1165	/// * `sender` - The owner or administrator of the collection.1166	/// * `property_permission` - Property permission.1167	pub fn set_property_permission(1168		collection: &CollectionHandle<T>,1169		sender: &T::CrossAccountId,1170		property_permission: PropertyKeyPermission,1171	) -> DispatchResult {1172		collection.check_is_owner_or_admin(sender)?;11731174		let all_permissions = CollectionPropertyPermissions::<T>::get(collection.id);1175		let current_permission = all_permissions.get(&property_permission.key);1176		if matches![1177			current_permission,1178			Some(PropertyPermission { mutable: false, .. })1179		] {1180			return Err(<Error<T>>::NoPermission.into());1181		}11821183		CollectionPropertyPermissions::<T>::try_mutate(collection.id, |permissions| {1184			let property_permission = property_permission.clone();1185			permissions.try_set(property_permission.key, property_permission.permission)1186		})1187		.map_err(<Error<T>>::from)?;11881189		Self::deposit_event(Event::PropertyPermissionSet(1190			collection.id,1191			property_permission.key,1192		));11931194		Ok(())1195	}11961197	/// Set token property permission.1198	/// 1199	/// * `collection` - Collection handler.1200	/// * `sender` - The owner or administrator of the collection.1201	/// * `property_permissions` - Property permissions.1202	#[transactional]1203	pub fn set_token_property_permissions(1204		collection: &CollectionHandle<T>,1205		sender: &T::CrossAccountId,1206		property_permissions: Vec<PropertyKeyPermission>,1207	) -> DispatchResult {1208		for prop_pemission in property_permissions {1209			Self::set_property_permission(collection, sender, prop_pemission)?;1210		}12111212		Ok(())1213	}12141215	/// Get collection property.1216	pub fn get_collection_property(1217		collection_id: CollectionId,1218		key: &PropertyKey,1219	) -> Option<PropertyValue> {1220		Self::collection_properties(collection_id).get(key).cloned()1221	}12221223	/// Convert byte vector to property key vector.1224	pub fn bytes_keys_to_property_keys(1225		keys: Vec<Vec<u8>>,1226	) -> Result<Vec<PropertyKey>, DispatchError> {1227		keys.into_iter()1228			.map(|key| -> Result<PropertyKey, DispatchError> {1229				key.try_into()1230					.map_err(|_| <Error<T>>::PropertyKeyIsTooLong.into())1231			})1232			.collect::<Result<Vec<PropertyKey>, DispatchError>>()1233	}12341235	/// Get properties according to given keys.1236	pub fn filter_collection_properties(1237		collection_id: CollectionId,1238		keys: Option<Vec<PropertyKey>>,1239	) -> Result<Vec<Property>, DispatchError> {1240		let properties = Self::collection_properties(collection_id);12411242		let properties = keys1243			.map(|keys| {1244				keys.into_iter()1245					.filter_map(|key| {1246						properties.get(&key).map(|value| Property {1247							key,1248							value: value.clone(),1249						})1250					})1251					.collect()1252			})1253			.unwrap_or_else(|| {1254				properties1255					.into_iter()1256					.map(|(key, value)| Property { key, value })1257					.collect()1258			});12591260		Ok(properties)1261	}12621263	/// Get property permissions according to given keys.1264	pub fn filter_property_permissions(1265		collection_id: CollectionId,1266		keys: Option<Vec<PropertyKey>>,1267	) -> Result<Vec<PropertyKeyPermission>, DispatchError> {1268		let permissions = Self::property_permissions(collection_id);12691270		let key_permissions = keys1271			.map(|keys| {1272				keys.into_iter()1273					.filter_map(|key| {1274						permissions1275							.get(&key)1276							.map(|permission| PropertyKeyPermission {1277								key,1278								permission: permission.clone(),1279							})1280					})1281					.collect()1282			})1283			.unwrap_or_else(|| {1284				permissions1285					.into_iter()1286					.map(|(key, permission)| PropertyKeyPermission { key, permission })1287					.collect()1288			});12891290		Ok(key_permissions)1291	}12921293	/// Toggle `user` participation in the `collection`'s allow list.1294	pub fn toggle_allowlist(1295		collection: &CollectionHandle<T>,1296		sender: &T::CrossAccountId,1297		user: &T::CrossAccountId,1298		allowed: bool,1299	) -> DispatchResult {1300		collection.check_is_owner_or_admin(sender)?;13011302		// =========13031304		if allowed {1305			<Allowlist<T>>::insert((collection.id, user), true);1306		} else {1307			<Allowlist<T>>::remove((collection.id, user));1308		}13091310		Ok(())1311	}13121313	/// Toggle `user` participation in the `collection`'s admin list.1314	pub fn toggle_admin(1315		collection: &CollectionHandle<T>,1316		sender: &T::CrossAccountId,1317		user: &T::CrossAccountId,1318		admin: bool,1319	) -> DispatchResult {1320		collection.check_is_owner(sender)?;13211322		let was_admin = <IsAdmin<T>>::get((collection.id, user));1323		if was_admin == admin {1324			return Ok(());1325		}1326		let amount = <AdminAmount<T>>::get(collection.id);13271328		if admin {1329			let amount = amount1330				.checked_add(1)1331				.ok_or(<Error<T>>::CollectionAdminCountExceeded)?;1332			ensure!(1333				amount <= Self::collection_admins_limit(),1334				<Error<T>>::CollectionAdminCountExceeded,1335			);13361337			// =========13381339			<AdminAmount<T>>::insert(collection.id, amount);1340			<IsAdmin<T>>::insert((collection.id, user), true);1341		} else {1342			<AdminAmount<T>>::insert(collection.id, amount.saturating_sub(1));1343			<IsAdmin<T>>::remove((collection.id, user));1344		}13451346		Ok(())1347	}13481349	/// Merge set fields from `new_limit` to `old_limit`.1350	pub fn clamp_limits(1351		mode: CollectionMode,1352		old_limit: &CollectionLimits,1353		mut new_limit: CollectionLimits,1354	) -> Result<CollectionLimits, DispatchError> {1355		let limits = old_limit;1356		limit_default!(old_limit, new_limit,1357			account_token_ownership_limit => ensure!(1358				new_limit <= MAX_TOKEN_OWNERSHIP,1359				<Error<T>>::CollectionLimitBoundsExceeded,1360			),1361			sponsored_data_size => ensure!(1362				new_limit <= CUSTOM_DATA_LIMIT,1363				<Error<T>>::CollectionLimitBoundsExceeded,1364			),13651366			sponsored_data_rate_limit => {},1367			token_limit => ensure!(1368				old_limit >= new_limit && new_limit > 0,1369				<Error<T>>::CollectionTokenLimitExceeded1370			),13711372			sponsor_transfer_timeout(match mode {1373				CollectionMode::NFT => NFT_SPONSOR_TRANSFER_TIMEOUT,1374				CollectionMode::Fungible(_) => FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,1375				CollectionMode::ReFungible => REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,1376			}) => ensure!(1377				new_limit <= MAX_SPONSOR_TIMEOUT,1378				<Error<T>>::CollectionLimitBoundsExceeded,1379			),1380			sponsor_approve_timeout => {},1381			owner_can_transfer => ensure!(1382				!limits.owner_can_transfer_instaled() ||1383				old_limit || !new_limit,1384				<Error<T>>::OwnerPermissionsCantBeReverted,1385			),1386			owner_can_destroy => ensure!(1387				old_limit || !new_limit,1388				<Error<T>>::OwnerPermissionsCantBeReverted,1389			),1390			transfers_enabled => {},1391		);1392		Ok(new_limit)1393	}13941395	/// Merge set fields from `new_permission` to `old_permission`.1396	pub fn clamp_permissions(1397		_mode: CollectionMode,1398		old_permission: &CollectionPermissions,1399		mut new_permission: CollectionPermissions,1400	) -> Result<CollectionPermissions, DispatchError> {1401		limit_default_clone!(old_permission, new_permission,1402			access => {},1403			mint_mode => {},1404			nesting => { /* todo check for permissive, if only it gets out of benchmarks */ },1405		);1406		Ok(new_permission)1407	}1408}14091410/// Indicates unsupported methods by returning [Error::UnsupportedOperation].1411#[macro_export]1412macro_rules! unsupported {1413	() => {1414		Err(<Error<T>>::UnsupportedOperation.into())1415	};1416}14171418/// Return weights for various worst-case operations.1419pub trait CommonWeightInfo<CrossAccountId> {1420	/// Weight of item creation.1421	fn create_item() -> Weight;14221423	/// Weight of items creation.1424	fn create_multiple_items(amount: &[CreateItemData]) -> Weight;14251426	/// Weight of items creation.1427	fn create_multiple_items_ex(cost: &CreateItemExData<CrossAccountId>) -> Weight;14281429	/// The weight of the burning item.1430	fn burn_item() -> Weight;14311432	/// Property setting weight.1433	/// 1434	/// * `amount`- The number of properties to set.1435	fn set_collection_properties(amount: u32) -> Weight;14361437	/// Collection property deletion weight.1438	/// 1439	/// * `amount`- The number of properties to set.1440	fn delete_collection_properties(amount: u32) -> Weight;14411442	/// Token property setting weight.1443	///1444	/// * `amount`- The number of properties to set.1445	fn set_token_properties(amount: u32) -> Weight;14461447	/// Token property deletion weight.1448	/// 1449	/// * `amount`- The number of properties to delete.1450	fn delete_token_properties(amount: u32) -> Weight;1451	1452	1453	/// Token property permissions set weight.1454	/// 1455	/// * `amount`- The number of property permissions to set.1456	fn set_token_property_permissions(amount: u32) -> Weight;14571458	/// Transfer price of the token or its parts.1459	fn transfer() -> Weight;14601461	/// The price of setting the permission of the operation from another user.1462	fn approve() -> Weight;14631464	/// Transfer price from another user.1465	fn transfer_from() -> Weight;14661467	/// The price of burning a token from another user.1468	fn burn_from() -> Weight;1469	1470	/// Differs from burn_item in case of Fungible and Refungible, as it should burn1471	/// whole users's balance1472	///1473	/// This method shouldn't be used directly, as it doesn't count breadth price, use [burn_recursively](CommonWeightInfo::burn_recursively) instead1474	fn burn_recursively_self_raw() -> Weight;1475	1476	/// Cost of iterating over `amount` children while burning, without counting child burning itself1477	///1478	/// This method shouldn't be used directly, as it doesn't count depth price, use [burn_recursively](CommonWeightInfo::burn_recursively) instead1479	fn burn_recursively_breadth_raw(amount: u32) -> Weight;1480	1481	/// The price of recursive burning a token.1482	///1483	/// `max_selfs` - 1484	fn burn_recursively(max_selfs: u32, max_breadth: u32) -> Weight {1485		Self::burn_recursively_self_raw()1486			.saturating_mul(max_selfs.max(1) as u64)1487			.saturating_add(Self::burn_recursively_breadth_raw(max_breadth))1488	}1489}14901491/// Weight info extension trait for refungible pallet.1492pub trait RefungibleExtensionsWeightInfo {1493	/// Weight of token repartition.1494	fn repartition() -> Weight;1495}14961497/// Common collection operations.1498/// 1499/// It wraps methods in Fungible, Nonfungible and Refungible pallets1500/// and adds weight info.1501pub trait CommonCollectionOperations<T: Config> {1502	/// Create token.1503	/// 1504	/// * `sender` - The user who mint the token and pays for the transaction.1505	/// * `to` - The user who will own the token.1506	/// * `data` - Token data.1507	/// * `nesting_budget` - A budget that can be spent on nesting tokens.1508	fn create_item(1509		&self,1510		sender: T::CrossAccountId,1511		to: T::CrossAccountId,1512		data: CreateItemData,1513		nesting_budget: &dyn Budget,1514	) -> DispatchResultWithPostInfo;15151516	/// Create multiple tokens.1517	/// 1518	/// * `sender` - The user who mint the token and pays for the transaction.1519	/// * `to` - The user who will own the token.1520	/// * `data` - Token data.1521	/// * `nesting_budget` - A budget that can be spent on nesting tokens.1522	fn create_multiple_items(1523		&self,1524		sender: T::CrossAccountId,1525		to: T::CrossAccountId,1526		data: Vec<CreateItemData>,1527		nesting_budget: &dyn Budget,1528	) -> DispatchResultWithPostInfo;1529	1530	/// Create multiple tokens.1531	/// 1532	/// * `sender` - The user who mint the token and pays for the transaction.1533	/// * `to` - The user who will own the token.1534	/// * `data` - Token data.1535	/// * `nesting_budget` - A budget that can be spent on nesting tokens.1536	fn create_multiple_items_ex(1537		&self,1538		sender: T::CrossAccountId,1539		data: CreateItemExData<T::CrossAccountId>,1540		nesting_budget: &dyn Budget,1541	) -> DispatchResultWithPostInfo;15421543	/// Burn token.1544	/// 1545	/// * `sender` - The user who owns the token.1546	/// * `token` - Token id that will burned.1547	/// * `amount` - The number of parts of the token that will be burned.1548	fn burn_item(1549		&self,1550		sender: T::CrossAccountId,1551		token: TokenId,1552		amount: u128,1553	) -> DispatchResultWithPostInfo;1554	1555	/// Burn token and all nested tokens recursievly.1556	/// 1557	/// * `sender` - The user who owns the token.1558	/// * `token` - Token id that will burned.1559	/// * `self_budget` - The budget that can be spent on burning tokens.1560	/// * `breadth_budget` - The budget that can be spent on burning nested tokens.1561	fn burn_item_recursively(1562		&self,1563		sender: T::CrossAccountId,1564		token: TokenId,1565		self_budget: &dyn Budget,1566		breadth_budget: &dyn Budget,1567	) -> DispatchResultWithPostInfo;15681569	/// Set collection properties.1570	/// 1571	/// * `sender` - Must be either the owner of the collection or its admin.1572	/// * `properties` - Properties to be set.1573	fn set_collection_properties(1574		&self,1575		sender: T::CrossAccountId,1576		properties: Vec<Property>,1577	) -> DispatchResultWithPostInfo;15781579	/// Delete collection properties.1580	/// 1581	/// * `sender` - Must be either the owner of the collection or its admin.1582	/// * `properties` - The properties to be removed.1583	fn delete_collection_properties(1584		&self,1585		sender: &T::CrossAccountId,1586		property_keys: Vec<PropertyKey>,1587	) -> DispatchResultWithPostInfo;15881589	/// Set token properties.1590	/// 1591	/// The appropriate [PropertyPermission] for the token property 1592	/// must be set with [Self::set_token_property_permissions].1593	/// 1594	/// * `sender` - Must be either the owner of the token or its admin. 1595	/// * `token_id` - The token for which the properties are being set.1596	/// * `properties` - Properties to be set.1597	/// * `budget` - Budget for setting properties.1598	fn set_token_properties(1599		&self,1600		sender: T::CrossAccountId,1601		token_id: TokenId,1602		properties: Vec<Property>,1603		budget: &dyn Budget,1604	) -> DispatchResultWithPostInfo;16051606	/// Remove token properties.1607	/// 1608	/// The appropriate [PropertyPermission] for the token property 1609	/// must be set with [Self::set_token_property_permissions].1610	/// 1611	/// * `sender` - Must be either the owner of the token or its admin. 1612	/// * `token_id` - The token for which the properties are being remove.1613	/// * `property_keys` - Keys to remove corresponding properties.1614	/// * `budget` - Budget for removing properties.1615	fn delete_token_properties(1616		&self,1617		sender: T::CrossAccountId,1618		token_id: TokenId,1619		property_keys: Vec<PropertyKey>,1620		budget: &dyn Budget,1621	) -> DispatchResultWithPostInfo;16221623	/// Set token property permissions.1624	/// 1625	/// * `sender` - Must be either the owner of the token or its admin. 1626	/// * `token_id` - The token for which the properties are being set.1627	/// * `properties` - Properties to be set.1628	/// * `budget` - Budget for setting properties.1629	fn set_token_property_permissions(1630		&self,1631		sender: &T::CrossAccountId,1632		property_permissions: Vec<PropertyKeyPermission>,1633	) -> DispatchResultWithPostInfo;16341635	/// Transfer amount of token pieces.1636	/// 1637	/// * `sender` - Donor user.1638	/// * `to` - Recepient user.1639	/// * `token` - The token of which parts are being sent.1640	/// * `amount` - The number of parts of the token that will be transferred.1641	/// * `budget` - The maximum budget that can be spent on the transfer.1642	fn transfer(1643		&self,1644		sender: T::CrossAccountId,1645		to: T::CrossAccountId,1646		token: TokenId,1647		amount: u128,1648		budget: &dyn Budget,1649	) -> DispatchResultWithPostInfo;16501651	/// Grant access to another account to transfer parts of the token owned by the calling user via [Self::transfer_from].1652	/// 1653	/// * `sender` - The user who grants access to the token.1654	/// * `spender` - The user to whom the rights are granted.1655	/// * `token` - The token to which access is granted.1656	/// * `amount` - The amount of pieces that another user can dispose of.1657	fn approve(1658		&self,1659		sender: T::CrossAccountId,1660		spender: T::CrossAccountId,1661		token: TokenId,1662		amount: u128,1663	) -> DispatchResultWithPostInfo;1664	1665	/// Send parts of a token owned by another user.1666	/// 1667	/// Before calling this method, you must grant rights to the calling user via [Self::approve].1668	/// 1669	/// * `sender` - The user who has access to the token.1670	/// * `from` - The user who owns the token.1671	/// * `to` - Recepient user.1672	/// * `token` - The token of which parts are being sent.1673	/// * `amount` - The number of parts of the token that will be transferred.1674	/// * `budget` - The maximum budget that can be spent on the transfer.1675	fn transfer_from(1676		&self,1677		sender: T::CrossAccountId,1678		from: T::CrossAccountId,1679		to: T::CrossAccountId,1680		token: TokenId,1681		amount: u128,1682		budget: &dyn Budget,1683	) -> DispatchResultWithPostInfo;1684	1685	/// Burn parts of a token owned by another user.1686	/// 1687	/// Before calling this method, you must grant rights to the calling user via [Self::approve].1688	/// 1689	/// * `sender` - The user who has access to the token.1690	/// * `from` - The user who owns the token.1691	/// * `token` - The token of which parts are being sent.1692	/// * `amount` - The number of parts of the token that will be transferred.1693	/// * `budget` - The maximum budget that can be spent on the burn.1694	fn burn_from(1695		&self,1696		sender: T::CrossAccountId,1697		from: T::CrossAccountId,1698		token: TokenId,1699		amount: u128,1700		budget: &dyn Budget,1701	) -> DispatchResultWithPostInfo;17021703	/// Check permission to nest token.1704	/// 1705	/// * `sender` - The user who initiated the check.1706	/// * `from` - The token that is checked for embedding.1707	/// * `under` - Token under which to check.1708	/// * `budget` - The maximum budget that can be spent on the check.1709	fn check_nesting(1710		&self,1711		sender: T::CrossAccountId,1712		from: (CollectionId, TokenId),1713		under: TokenId,1714		budget: &dyn Budget,1715	) -> DispatchResult;17161717	/// Nest one token into another.1718	/// 1719	/// * `under` - Token holder.1720	/// * `to_nest` - Nested token.1721	fn nest(&self, under: TokenId, to_nest: (CollectionId, TokenId));17221723	/// Unnest token.1724	/// 1725	/// * `under` - Token holder.1726	/// * `to_nest` - Token to unnest.1727	fn unnest(&self, under: TokenId, to_nest: (CollectionId, TokenId));17281729	/// Get all user tokens.1730	/// 1731	/// * `account` - Account for which you need to get tokens.1732	fn account_tokens(&self, account: T::CrossAccountId) -> Vec<TokenId>;17331734	/// Get all the tokens in the collection.1735	fn collection_tokens(&self) -> Vec<TokenId>;17361737	/// Check if the token exists.1738	/// 1739	/// * `token` - Id token to check.1740	fn token_exists(&self, token: TokenId) -> bool;17411742	/// Get the id of the last minted token.1743	fn last_token_id(&self) -> TokenId;17441745	/// Get the owner of the token.1746	/// 1747	/// * `token` - The token for which you need to find out the owner.1748	fn token_owner(&self, token: TokenId) -> Option<T::CrossAccountId>;17491750	/// Get the value of the token property by key.1751	/// 1752	/// * `token` - Token property to get.1753	/// * `key` - Property name.1754	fn token_property(&self, token_id: TokenId, key: &PropertyKey) -> Option<PropertyValue>;17551756	/// Get a set of token properties by key vector.1757	/// 1758	/// * `token` - Token property to get.1759	/// * `keys` - Vector of keys. If this parameter is [None](sp_std::result::Result),1760	/// then all properties are returned.1761	fn token_properties(&self, token: TokenId, keys: Option<Vec<PropertyKey>>) -> Vec<Property>;17621763	/// Amount of unique collection tokens1764	fn total_supply(&self) -> u32;17651766	/// Amount of different tokens account has.1767	/// 1768	/// * `account` - The account for which need to get the balance.1769	fn account_balance(&self, account: T::CrossAccountId) -> u32;17701771	/// Amount of specific token account have.1772	fn balance(&self, account: T::CrossAccountId, token: TokenId) -> u128;17731774	/// Amount of token pieces1775	fn total_pieces(&self, token: TokenId) -> Option<u128>;17761777	/// Get the number of parts of the token that a trusted user can manage.1778	/// 1779	/// * `sender` - Trusted user.1780	/// * `spender` - Owner of the token.1781	/// * `token` - The token for which to get the value.1782	fn allowance(1783		&self,1784		sender: T::CrossAccountId,1785		spender: T::CrossAccountId,1786		token: TokenId,1787	) -> u128;17881789	/// Get extension for RFT collection.1790	fn refungible_extensions(&self) -> Option<&dyn RefungibleExtensions<T>>;1791}17921793/// Extension for RFT collection.1794pub trait RefungibleExtensions<T>1795where1796	T: Config,1797{1798	/// Change the number of parts of the token.1799	/// 1800	/// When the value changes down, this function is equivalent to burning parts of the token.1801	/// 1802	/// * `sender` - The user calling the repartition operation. Must be the owner of the token.1803	/// * `token` - The token for which you want to change the number of parts.1804	/// * `amount` - The new value of the parts of the token.1805	fn repartition(1806		&self,1807		sender: &T::CrossAccountId,1808		token: TokenId,1809		amount: u128,1810	) -> DispatchResultWithPostInfo;1811}18121813/// Merge [DispatchResult] with [Weight] into [DispatchResultWithPostInfo].1814/// 1815/// Used for [CommonCollectionOperations] implementations and flexible enough to do so.1816pub fn with_weight(res: DispatchResult, weight: Weight) -> DispatchResultWithPostInfo {1817	let post_info = PostDispatchInfo {1818		actual_weight: Some(weight),1819		pays_fee: Pays::Yes,1820	};1821	match res {1822		Ok(()) => Ok(post_info),1823		Err(error) => Err(DispatchErrorWithPostInfo { post_info, error }),1824	}1825}18261827impl<T: Config> From<PropertiesError> for Error<T> {1828	fn from(error: PropertiesError) -> Self {1829		match error {1830			PropertiesError::NoSpaceForProperty => Self::NoSpaceForProperty,1831			PropertiesError::PropertyLimitReached => Self::PropertyLimitReached,1832			PropertiesError::InvalidCharacterInPropertyKey => Self::InvalidCharacterInPropertyKey,1833			PropertiesError::PropertyKeyIsTooLong => Self::PropertyKeyIsTooLong,1834			PropertiesError::EmptyPropertyKey => Self::EmptyPropertyKey,1835		}1836	}1837}