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

difftreelog

remove warnings

Trubnikov Sergey2023-04-28parent: #5a3127a.patch.diff
in: master

8 files changed

modifiedpallets/balances-adapter/src/common.rsdiffbeforeafterboth
--- a/pallets/balances-adapter/src/common.rs
+++ b/pallets/balances-adapter/src/common.rs
@@ -12,12 +12,12 @@
 
 pub struct CommonWeights<T: Config>(PhantomData<T>);
 impl<T: Config> CommonWeightInfo<T::CrossAccountId> for CommonWeights<T> {
-	fn create_multiple_items(amount: &[up_data_structs::CreateItemData]) -> Weight {
+	fn create_multiple_items(_amount: &[up_data_structs::CreateItemData]) -> Weight {
 		Weight::default()
 	}
 
 	fn create_multiple_items_ex(
-		cost: &up_data_structs::CreateItemExData<T::CrossAccountId>,
+		_cost: &up_data_structs::CreateItemExData<T::CrossAccountId>,
 	) -> Weight {
 		Weight::default()
 	}
@@ -26,23 +26,23 @@
 		Weight::default()
 	}
 
-	fn set_collection_properties(amount: u32) -> Weight {
+	fn set_collection_properties(_amount: u32) -> Weight {
 		Weight::default()
 	}
 
-	fn delete_collection_properties(amount: u32) -> Weight {
+	fn delete_collection_properties(_amount: u32) -> Weight {
 		Weight::default()
 	}
 
-	fn set_token_properties(amount: u32) -> Weight {
+	fn set_token_properties(_amount: u32) -> Weight {
 		Weight::default()
 	}
 
-	fn delete_token_properties(amount: u32) -> Weight {
+	fn delete_token_properties(_amount: u32) -> Weight {
 		Weight::default()
 	}
 
-	fn set_token_property_permissions(amount: u32) -> Weight {
+	fn set_token_property_permissions(_amount: u32) -> Weight {
 		Weight::default()
 	}
 
@@ -70,7 +70,7 @@
 		Weight::default()
 	}
 
-	fn burn_recursively_breadth_raw(amount: u32) -> Weight {
+	fn burn_recursively_breadth_raw(_amount: u32) -> Weight {
 		Weight::default()
 	}
 
@@ -92,92 +92,92 @@
 impl<T: Config> CommonCollectionOperations<T> for NativeFungibleHandle<T> {
 	fn create_item(
 		&self,
-		sender: <T>::CrossAccountId,
-		to: <T>::CrossAccountId,
-		data: up_data_structs::CreateItemData,
-		nesting_budget: &dyn up_data_structs::budget::Budget,
+		_sender: <T>::CrossAccountId,
+		_to: <T>::CrossAccountId,
+		_data: up_data_structs::CreateItemData,
+		_nesting_budget: &dyn up_data_structs::budget::Budget,
 	) -> frame_support::pallet_prelude::DispatchResultWithPostInfo {
 		fail!(<pallet_common::Error<T>>::UnsupportedOperation);
 	}
 
 	fn create_multiple_items(
 		&self,
-		sender: <T>::CrossAccountId,
-		to: <T>::CrossAccountId,
-		data: Vec<up_data_structs::CreateItemData>,
-		nesting_budget: &dyn up_data_structs::budget::Budget,
+		_sender: <T>::CrossAccountId,
+		_to: <T>::CrossAccountId,
+		_data: Vec<up_data_structs::CreateItemData>,
+		_nesting_budget: &dyn up_data_structs::budget::Budget,
 	) -> frame_support::pallet_prelude::DispatchResultWithPostInfo {
 		fail!(<pallet_common::Error<T>>::UnsupportedOperation);
 	}
 
 	fn create_multiple_items_ex(
 		&self,
-		sender: <T>::CrossAccountId,
-		data: up_data_structs::CreateItemExData<<T>::CrossAccountId>,
-		nesting_budget: &dyn up_data_structs::budget::Budget,
+		_sender: <T>::CrossAccountId,
+		_data: up_data_structs::CreateItemExData<<T>::CrossAccountId>,
+		_nesting_budget: &dyn up_data_structs::budget::Budget,
 	) -> frame_support::pallet_prelude::DispatchResultWithPostInfo {
 		fail!(<pallet_common::Error<T>>::UnsupportedOperation);
 	}
 
 	fn burn_item(
 		&self,
-		sender: <T>::CrossAccountId,
-		token: TokenId,
-		amount: u128,
+		_sender: <T>::CrossAccountId,
+		_token: TokenId,
+		_amount: u128,
 	) -> frame_support::pallet_prelude::DispatchResultWithPostInfo {
 		fail!(<pallet_common::Error<T>>::UnsupportedOperation);
 	}
 
 	fn burn_item_recursively(
 		&self,
-		sender: <T>::CrossAccountId,
-		token: TokenId,
-		self_budget: &dyn up_data_structs::budget::Budget,
-		breadth_budget: &dyn up_data_structs::budget::Budget,
+		_sender: <T>::CrossAccountId,
+		_token: TokenId,
+		_self_budget: &dyn up_data_structs::budget::Budget,
+		_breadth_budget: &dyn up_data_structs::budget::Budget,
 	) -> frame_support::pallet_prelude::DispatchResultWithPostInfo {
 		fail!(<pallet_common::Error<T>>::UnsupportedOperation);
 	}
 
 	fn set_collection_properties(
 		&self,
-		sender: <T>::CrossAccountId,
-		properties: Vec<up_data_structs::Property>,
+		_sender: <T>::CrossAccountId,
+		_properties: Vec<up_data_structs::Property>,
 	) -> frame_support::pallet_prelude::DispatchResultWithPostInfo {
 		fail!(<pallet_common::Error<T>>::UnsupportedOperation);
 	}
 
 	fn delete_collection_properties(
 		&self,
-		sender: &<T>::CrossAccountId,
-		property_keys: Vec<up_data_structs::PropertyKey>,
+		_sender: &<T>::CrossAccountId,
+		_property_keys: Vec<up_data_structs::PropertyKey>,
 	) -> frame_support::pallet_prelude::DispatchResultWithPostInfo {
 		fail!(<pallet_common::Error<T>>::UnsupportedOperation);
 	}
 
 	fn set_token_properties(
 		&self,
-		sender: <T>::CrossAccountId,
-		token_id: TokenId,
-		properties: Vec<up_data_structs::Property>,
-		budget: &dyn up_data_structs::budget::Budget,
+		_sender: <T>::CrossAccountId,
+		_token_id: TokenId,
+		_properties: Vec<up_data_structs::Property>,
+		_budget: &dyn up_data_structs::budget::Budget,
 	) -> frame_support::pallet_prelude::DispatchResultWithPostInfo {
 		fail!(<pallet_common::Error<T>>::UnsupportedOperation);
 	}
 
 	fn delete_token_properties(
 		&self,
-		sender: <T>::CrossAccountId,
-		token_id: TokenId,
-		property_keys: Vec<up_data_structs::PropertyKey>,
-		budget: &dyn up_data_structs::budget::Budget,
+		_sender: <T>::CrossAccountId,
+		_token_id: TokenId,
+		_property_keys: Vec<up_data_structs::PropertyKey>,
+		_budget: &dyn up_data_structs::budget::Budget,
 	) -> frame_support::pallet_prelude::DispatchResultWithPostInfo {
 		fail!(<pallet_common::Error<T>>::UnsupportedOperation);
 	}
 
 	fn set_token_property_permissions(
 		&self,
-		sender: &<T>::CrossAccountId,
-		property_permissions: Vec<up_data_structs::PropertyKeyPermission>,
+		_sender: &<T>::CrossAccountId,
+		_property_permissions: Vec<up_data_structs::PropertyKeyPermission>,
 	) -> frame_support::pallet_prelude::DispatchResultWithPostInfo {
 		fail!(<pallet_common::Error<T>>::UnsupportedOperation);
 	}
@@ -186,9 +186,9 @@
 		&self,
 		sender: <T>::CrossAccountId,
 		to: <T>::CrossAccountId,
-		token: TokenId,
+		_token: TokenId,
 		amount: u128,
-		budget: &dyn up_data_structs::budget::Budget,
+		_budget: &dyn up_data_structs::budget::Budget,
 	) -> frame_support::pallet_prelude::DispatchResultWithPostInfo {
 		with_weight(
 			<T as Config>::Currency::transfer(
@@ -203,21 +203,21 @@
 
 	fn approve(
 		&self,
-		sender: <T>::CrossAccountId,
-		spender: <T>::CrossAccountId,
-		token: TokenId,
-		amount: u128,
+		_sender: <T>::CrossAccountId,
+		_spender: <T>::CrossAccountId,
+		_token: TokenId,
+		_amount: u128,
 	) -> frame_support::pallet_prelude::DispatchResultWithPostInfo {
 		fail!(<pallet_common::Error<T>>::UnsupportedOperation);
 	}
 
 	fn approve_from(
 		&self,
-		sender: <T>::CrossAccountId,
-		from: <T>::CrossAccountId,
-		to: <T>::CrossAccountId,
-		token: TokenId,
-		amount: u128,
+		_sender: <T>::CrossAccountId,
+		_from: <T>::CrossAccountId,
+		_to: <T>::CrossAccountId,
+		_token: TokenId,
+		_amount: u128,
 	) -> frame_support::pallet_prelude::DispatchResultWithPostInfo {
 		fail!(<pallet_common::Error<T>>::UnsupportedOperation);
 	}
@@ -227,9 +227,9 @@
 		sender: <T>::CrossAccountId,
 		from: <T>::CrossAccountId,
 		to: <T>::CrossAccountId,
-		token: TokenId,
+		_token: TokenId,
 		amount: u128,
-		budget: &dyn up_data_structs::budget::Budget,
+		_budget: &dyn up_data_structs::budget::Budget,
 	) -> frame_support::pallet_prelude::DispatchResultWithPostInfo {
 		if sender != from {
 			fail!(<pallet_common::Error<T>>::NoPermission);
@@ -247,28 +247,28 @@
 
 	fn burn_from(
 		&self,
-		sender: <T>::CrossAccountId,
-		from: <T>::CrossAccountId,
-		token: TokenId,
-		amount: u128,
-		budget: &dyn up_data_structs::budget::Budget,
+		_sender: <T>::CrossAccountId,
+		_from: <T>::CrossAccountId,
+		_token: TokenId,
+		_amount: u128,
+		_budget: &dyn up_data_structs::budget::Budget,
 	) -> frame_support::pallet_prelude::DispatchResultWithPostInfo {
 		fail!(<pallet_common::Error<T>>::UnsupportedOperation);
 	}
 
 	fn check_nesting(
 		&self,
-		sender: <T>::CrossAccountId,
-		from: (up_data_structs::CollectionId, TokenId),
-		under: TokenId,
-		budget: &dyn up_data_structs::budget::Budget,
+		_sender: <T>::CrossAccountId,
+		_from: (up_data_structs::CollectionId, TokenId),
+		_under: TokenId,
+		_budget: &dyn up_data_structs::budget::Budget,
 	) -> frame_support::sp_runtime::DispatchResult {
 		fail!(<pallet_common::Error<T>>::UnsupportedOperation);
 	}
 
-	fn nest(&self, under: TokenId, to_nest: (up_data_structs::CollectionId, TokenId)) {}
+	fn nest(&self, _under: TokenId, _to_nest: (up_data_structs::CollectionId, TokenId)) {}
 
-	fn unnest(&self, under: TokenId, to_nest: (up_data_structs::CollectionId, TokenId)) {}
+	fn unnest(&self, _under: TokenId, _to_nest: (up_data_structs::CollectionId, TokenId)) {}
 
 	fn account_tokens(&self, account: <T>::CrossAccountId) -> Vec<TokenId> {
 		let balance = <T as Config>::Currency::total_balance(account.as_sub());
@@ -293,27 +293,27 @@
 
 	fn token_owner(
 		&self,
-		token: TokenId,
+		_token: TokenId,
 	) -> Result<<T>::CrossAccountId, up_data_structs::TokenOwnerError> {
 		Err(up_data_structs::TokenOwnerError::MultipleOwners)
 	}
 
-	fn token_owners(&self, token: TokenId) -> Vec<<T>::CrossAccountId> {
+	fn token_owners(&self, _token: TokenId) -> Vec<<T>::CrossAccountId> {
 		vec![]
 	}
 
 	fn token_property(
 		&self,
-		token_id: TokenId,
-		key: &up_data_structs::PropertyKey,
+		_token_id: TokenId,
+		_key: &up_data_structs::PropertyKey,
 	) -> Option<up_data_structs::PropertyValue> {
 		None
 	}
 
 	fn token_properties(
 		&self,
-		token: TokenId,
-		keys: Option<Vec<up_data_structs::PropertyKey>>,
+		_token: TokenId,
+		_keys: Option<Vec<up_data_structs::PropertyKey>>,
 	) -> Vec<up_data_structs::Property> {
 		vec![]
 	}
@@ -344,9 +344,9 @@
 
 	fn allowance(
 		&self,
-		sender: <T>::CrossAccountId,
-		spender: <T>::CrossAccountId,
-		token: TokenId,
+		_sender: <T>::CrossAccountId,
+		_spender: <T>::CrossAccountId,
+		_token: TokenId,
 	) -> u128 {
 		0
 	}
@@ -357,20 +357,24 @@
 
 	fn set_allowance_for_all(
 		&self,
-		owner: <T>::CrossAccountId,
-		operator: <T>::CrossAccountId,
-		approve: bool,
+		_owner: <T>::CrossAccountId,
+		_operator: <T>::CrossAccountId,
+		_approve: bool,
 	) -> frame_support::pallet_prelude::DispatchResultWithPostInfo {
 		fail!(<pallet_common::Error<T>>::UnsupportedOperation);
 	}
 
-	fn allowance_for_all(&self, owner: <T>::CrossAccountId, operator: <T>::CrossAccountId) -> bool {
+	fn allowance_for_all(
+		&self,
+		_owner: <T>::CrossAccountId,
+		_operator: <T>::CrossAccountId,
+	) -> bool {
 		false
 	}
 
 	fn repair_item(
 		&self,
-		token: TokenId,
+		_token: TokenId,
 	) -> frame_support::pallet_prelude::DispatchResultWithPostInfo {
 		fail!(<pallet_common::Error<T>>::UnsupportedOperation);
 	}
modifiedpallets/balances-adapter/src/erc.rsdiffbeforeafterboth
--- a/pallets/balances-adapter/src/erc.rs
+++ b/pallets/balances-adapter/src/erc.rs
@@ -9,7 +9,7 @@
 use pallet_evm_coder_substrate::{
 	call, dispatch_to_evm,
 	execution::{PreDispatch, Result},
-	frontier_contract, WithRecorder, SubstrateRecorder,
+	frontier_contract,
 };
 use sp_core::{U256, Get};
 use sp_std::vec::Vec;
@@ -26,13 +26,6 @@
 		from: Address,
 		#[indexed]
 		to: Address,
-		value: U256,
-	},
-	Approval {
-		#[indexed]
-		owner: Address,
-		#[indexed]
-		spender: Address,
 		value: U256,
 	},
 }
modifiedpallets/balances-adapter/src/lib.rsdiffbeforeafterboth
--- a/pallets/balances-adapter/src/lib.rs
+++ b/pallets/balances-adapter/src/lib.rs
@@ -1,11 +1,9 @@
 // #![doc = include_str!("../README.md")]
 #![cfg_attr(not(feature = "std"), no_std)]
-#![warn(missing_docs)]
 
 extern crate alloc;
 use frame_support::sp_runtime::DispatchResult;
 pub use pallet::*;
-use pallet_common::CollectionHandle;
 use pallet_evm_coder_substrate::{WithRecorder, SubstrateRecorder};
 
 pub mod common;
@@ -13,12 +11,15 @@
 
 pub(crate) type SelfWeightOf<T> = <T as Config>::WeightInfo;
 
+/// Handle for native fungible collection
 pub struct NativeFungibleHandle<T: Config>(SubstrateRecorder<T>);
 impl<T: Config> NativeFungibleHandle<T> {
+	/// Creates a handle
 	pub fn new() -> NativeFungibleHandle<T> {
 		Self(SubstrateRecorder::new(u64::MAX))
 	}
 
+	/// Check if the collection is internal
 	pub fn check_is_internal(&self) -> DispatchResult {
 		Ok(())
 	}
@@ -35,7 +36,7 @@
 #[frame_support::pallet]
 pub mod pallet {
 	use alloc::string::String;
-	use frame_support::{traits::Get, sp_runtime::DispatchResult};
+	use frame_support::{traits::Get};
 	use pallet_balances::WeightInfo;
 	use sp_core::U256;
 
@@ -43,25 +44,24 @@
 	pub trait Config:
 		frame_system::Config + pallet_evm_coder_substrate::Config + pallet_common::Config
 	{
+		/// Currency from `pallet_balances`
 		type Currency: frame_support::traits::Currency<
 			Self::AccountId,
 			Balance = Self::CurrencyBalance,
 		>;
+		/// Balance type of chain
 		type CurrencyBalance: Into<U256> + TryFrom<U256> + PartialEq<u128> + From<u128> + Into<u128>;
 
+		/// Decimals of balance
 		type Decimals: Get<u8>;
+		/// Collection name
 		type Name: Get<String>;
+		/// Collection symbol
 		type Symbol: Get<String>;
 
+		/// Weight information
 		type WeightInfo: WeightInfo;
 	}
 	#[pallet::pallet]
 	pub struct Pallet<T>(_);
-
-	// #[pallet::call]
-	impl<T: Config> Pallet<T> {
-		pub fn dummy() -> DispatchResult {
-			Ok(())
-		}
-	}
 }
modifiedpallets/common/src/dispatch.rsdiffbeforeafterboth
--- a/pallets/common/src/dispatch.rs
+++ b/pallets/common/src/dispatch.rs
@@ -11,7 +11,7 @@
 use sp_runtime::DispatchError;
 use up_data_structs::{CollectionId, CreateCollectionData, CollectionFlags};
 
-use crate::{pallet::Config, CommonCollectionOperations, CollectionHandle};
+use crate::{pallet::Config, CommonCollectionOperations};
 
 // TODO: move to benchmarking
 /// Price of [`dispatch_tx`] call with noop `call` argument
@@ -66,6 +66,7 @@
 
 /// Interface for working with different collections through the dispatcher.
 pub trait CollectionDispatch<T: Config> {
+	/// Check if the collection is internal.
 	fn check_is_internal(&self) -> DispatchResult;
 
 	/// Create a collection. The collection will be created according to the value of [`data.mode`](CreateCollectionData::mode).
modifiedpallets/common/src/erc.rsdiffbeforeafterboth
--- a/pallets/common/src/erc.rs
+++ b/pallets/common/src/erc.rs
@@ -80,7 +80,7 @@
 impl CommonEvmHandler for () {
 	const CODE: &'static [u8] = &[];
 
-	fn call(self, handle: &mut impl PrecompileHandle) -> Option<PrecompileResult> {
+	fn call(self, _handle: &mut impl PrecompileHandle) -> Option<PrecompileResult> {
 		None
 	}
 }
modifiedpallets/common/src/lib.rsdiffbeforeafterboth
before · pallets/common/src/lib.rs
1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617//! # Common pallet18//!19//! The Common pallet provides functionality for handling collections.20//!21//! ## Overview22//!23//! The Common pallet provides an interface for common collection operations for different collection types24//! (see [CommonCollectionOperations]), as well as a generic dispatcher for these, see [dispatch] module.25//! It also provides this functionality to EVM, see [erc] and [eth] modules.26//!27//! The Common pallet provides functions for:28//!29//! - Setting and approving collection sponsor.30//! - Get\set\delete allow list.31//! - Get\set\delete collection properties.32//! - Get\set\delete collection property permissions.33//! - Get\set\delete token property permissions.34//! - Get\set\delete collection administrators.35//! - Checking access permissions.36//!37//! ### Terminology38//! **Collection sponsor** - For the collection, you can set a sponsor, at whose expense it will39//! be possible to mint tokens.40//!41//! **Allow list** - List of users who have the right to minting tokens.42//!43//! **Collection properties** - Collection properties are simply key-value stores where various44//! metadata can be placed.45//!46//! **Permissions on token properties** - For each property in the token can be set permission47//! to change, see [`PropertyPermission`].48//!49//! **Collection administrator** - For a collection, you can set administrators who have the right50//! to most actions on the collection.5152#![warn(missing_docs)]53#![cfg_attr(not(feature = "std"), no_std)]54extern crate alloc;5556use core::{57	ops::{Deref, DerefMut},58	slice::from_ref,59};60use pallet_evm_coder_substrate::{SubstrateRecorder, WithRecorder};61use sp_std::vec::Vec;62use pallet_evm::{account::CrossAccountId, Pallet as PalletEvm};63use evm_coder::ToLog;64use frame_support::{65	dispatch::{DispatchErrorWithPostInfo, DispatchResultWithPostInfo, Weight, PostDispatchInfo},66	ensure,67	traits::{Imbalance, Get, Currency, WithdrawReasons, ExistenceRequirement},68	dispatch::Pays,69	transactional, fail,70};71use pallet_evm::GasWeightMapping;72use up_data_structs::{73	AccessMode, COLLECTION_NUMBER_LIMIT, Collection, RpcCollection, CollectionFlags,74	RpcCollectionFlags, CollectionId, CreateItemData, MAX_TOKEN_PREFIX_LENGTH,75	COLLECTION_ADMINS_LIMIT, TokenId, TokenChild, CollectionStats, MAX_TOKEN_OWNERSHIP,76	CollectionMode, NFT_SPONSOR_TRANSFER_TIMEOUT, FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,77	REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT, MAX_SPONSOR_TIMEOUT, CUSTOM_DATA_LIMIT, CollectionLimits,78	CreateCollectionData, SponsorshipState, CreateItemExData, SponsoringRateLimit, budget::Budget,79	PhantomType, Property, CollectionProperties as CollectionPropertiesT, TokenProperties,80	PropertiesPermissionMap, PropertyKey, PropertyValue, PropertyPermission, PropertiesError,81	TokenOwnerError, PropertyKeyPermission, TokenData, TrySetProperty, PropertyScope,82	CollectionPermissions,83};84use up_pov_estimate_rpc::PovInfo;8586pub use pallet::*;87use sp_core::H160;88use sp_runtime::{ArithmeticError, DispatchError, DispatchResult};8990#[cfg(feature = "runtime-benchmarks")]91pub mod benchmarking;92pub mod dispatch;93pub mod erc;94pub mod eth;95pub mod helpers;96#[allow(missing_docs)]97pub mod weights;98/// Weight info.99pub type SelfWeightOf<T> = <T as Config>::WeightInfo;100101/// Collection handle contains information about collection data and id.102/// Also provides functionality to count consumed gas.103///104/// CollectionHandle is used as a generic wrapper for collections of all types.105/// It allows to perform common operations and queries on any collection type,106/// both completely general for all, as well as their respective implementations of [`CommonCollectionOperations`].107#[must_use = "Should call submit_logs or save, otherwise some data will be lost for evm side"]108pub struct CollectionHandle<T: Config> {109	/// Collection id110	pub id: CollectionId,111	collection: Collection<T::AccountId>,112	/// Substrate recorder for counting consumed gas113	pub recorder: SubstrateRecorder<T>,114}115116impl<T: Config> WithRecorder<T> for CollectionHandle<T> {117	fn recorder(&self) -> &SubstrateRecorder<T> {118		&self.recorder119	}120	fn into_recorder(self) -> SubstrateRecorder<T> {121		self.recorder122	}123}124125impl<T: Config> CollectionHandle<T> {126	/// Same as [CollectionHandle::new] but with an explicit gas limit.127	pub fn new_with_gas_limit(id: CollectionId, gas_limit: u64) -> Option<Self> {128		Self::new_with_recorder(id, SubstrateRecorder::new(gas_limit))129	}130131	/// Same as [CollectionHandle::new] but with an existed [`SubstrateRecorder`].132	pub fn new_with_recorder(id: CollectionId, recorder: SubstrateRecorder<T>) -> Option<Self> {133		<CollectionById<T>>::get(id).map(|collection| Self {134			id,135			collection,136			recorder,137		})138	}139140	/// Retrives collection data from storage and creates collection handle with default parameters.141	/// If collection not found return `None`142	pub fn new(id: CollectionId) -> Option<Self> {143		Self::new_with_gas_limit(id, u64::MAX)144	}145146	/// Same as [`CollectionHandle::new`] but if collection not found [CollectionNotFound](Error::CollectionNotFound) returned.147	pub fn try_get(id: CollectionId) -> Result<Self, DispatchError> {148		Ok(Self::new(id).ok_or(<Error<T>>::CollectionNotFound)?)149	}150151	/// Consume gas for reading.152	pub fn consume_store_reads(153		&self,154		reads: u64,155	) -> pallet_evm_coder_substrate::execution::Result<()> {156		self.recorder157			.consume_gas(T::GasWeightMapping::weight_to_gas(Weight::from_parts(158				<T as frame_system::Config>::DbWeight::get()159					.read160					.saturating_mul(reads),161				// TODO: measure proof162				0,163			)))164	}165166	/// Consume gas for writing.167	pub fn consume_store_writes(168		&self,169		writes: u64,170	) -> pallet_evm_coder_substrate::execution::Result<()> {171		self.recorder172			.consume_gas(T::GasWeightMapping::weight_to_gas(Weight::from_parts(173				<T as frame_system::Config>::DbWeight::get()174					.write175					.saturating_mul(writes),176				// TODO: measure proof177				0,178			)))179	}180181	/// Consume gas for reading and writing.182	pub fn consume_store_reads_and_writes(183		&self,184		reads: u64,185		writes: u64,186	) -> pallet_evm_coder_substrate::execution::Result<()> {187		let weight = <T as frame_system::Config>::DbWeight::get();188		let reads = weight.read.saturating_mul(reads);189		let writes = weight.read.saturating_mul(writes);190		self.recorder191			.consume_gas(T::GasWeightMapping::weight_to_gas(Weight::from_parts(192				reads.saturating_add(writes),193				// TODO: measure proof194				0,195			)))196	}197198	/// Save collection to storage.199	pub fn save(&self) -> DispatchResult {200		<CollectionById<T>>::insert(self.id, &self.collection);201		Ok(())202	}203204	/// Set collection sponsor.205	///206	/// Unique collections allows sponsoring for certain actions.207	/// This method allows you to set the sponsor of the collection.208	/// In order for sponsorship to become active, it must be confirmed through [`Self::confirm_sponsorship`].209	pub fn set_sponsor(210		&mut self,211		sender: &T::CrossAccountId,212		sponsor: T::AccountId,213	) -> DispatchResult {214		self.check_is_internal()?;215		self.check_is_owner_or_admin(sender)?;216217		self.collection.sponsorship = SponsorshipState::Unconfirmed(sponsor.clone());218219		<Pallet<T>>::deposit_event(Event::<T>::CollectionSponsorSet(self.id, sponsor));220		<PalletEvm<T>>::deposit_log(221			erc::CollectionHelpersEvents::CollectionChanged {222				collection_id: eth::collection_id_to_address(self.id),223			}224			.to_log(T::ContractAddress::get()),225		);226227		self.save()228	}229230	/// Force set `sponsor`.231	///232	/// Differs from [`set_sponsor`][`Self::set_sponsor`] in that confirmation233	/// from the `sponsor` is not required.234	///235	/// # Arguments236	///237	/// * `sender`: Caller's account.238	/// * `sponsor`: ID of the account of the sponsor-to-be.239	pub fn force_set_sponsor(&mut self, sponsor: T::AccountId) -> DispatchResult {240		self.check_is_internal()?;241242		self.collection.sponsorship = SponsorshipState::Confirmed(sponsor.clone());243244		<Pallet<T>>::deposit_event(Event::<T>::CollectionSponsorSet(self.id, sponsor.clone()));245		<Pallet<T>>::deposit_event(Event::<T>::SponsorshipConfirmed(self.id, sponsor));246		<PalletEvm<T>>::deposit_log(247			erc::CollectionHelpersEvents::CollectionChanged {248				collection_id: eth::collection_id_to_address(self.id),249			}250			.to_log(T::ContractAddress::get()),251		);252253		self.save()254	}255256	/// Confirm sponsorship257	///258	/// In order for the sponsorship to become active, the user set as the sponsor must confirm their participation.259	/// Before confirming sponsorship, the user must be specified as the sponsor of the collection via [`Self::set_sponsor`].260	pub fn confirm_sponsorship(&mut self, sender: &T::AccountId) -> DispatchResult {261		self.check_is_internal()?;262		ensure!(263			self.collection.sponsorship.pending_sponsor() == Some(sender),264			Error::<T>::ConfirmSponsorshipFail265		);266267		self.collection.sponsorship = SponsorshipState::Confirmed(sender.clone());268269		<Pallet<T>>::deposit_event(Event::<T>::SponsorshipConfirmed(self.id, sender.clone()));270		<PalletEvm<T>>::deposit_log(271			erc::CollectionHelpersEvents::CollectionChanged {272				collection_id: eth::collection_id_to_address(self.id),273			}274			.to_log(T::ContractAddress::get()),275		);276277		self.save()278	}279280	/// Remove collection sponsor.281	pub fn remove_sponsor(&mut self, sender: &T::CrossAccountId) -> DispatchResult {282		self.check_is_internal()?;283		self.check_is_owner_or_admin(sender)?;284285		self.collection.sponsorship = SponsorshipState::Disabled;286287		<Pallet<T>>::deposit_event(Event::<T>::CollectionSponsorRemoved(self.id));288		<PalletEvm<T>>::deposit_log(289			erc::CollectionHelpersEvents::CollectionChanged {290				collection_id: eth::collection_id_to_address(self.id),291			}292			.to_log(T::ContractAddress::get()),293		);294		self.save()295	}296297	/// Force remove `sponsor`.298	///299	/// Differs from `remove_sponsor` in that300	/// it doesn't require consent from the `owner` of the collection.301	pub fn force_remove_sponsor(&mut self) -> DispatchResult {302		self.check_is_internal()?;303304		self.collection.sponsorship = SponsorshipState::Disabled;305306		<Pallet<T>>::deposit_event(Event::<T>::CollectionSponsorRemoved(self.id));307		<PalletEvm<T>>::deposit_log(308			erc::CollectionHelpersEvents::CollectionChanged {309				collection_id: eth::collection_id_to_address(self.id),310			}311			.to_log(T::ContractAddress::get()),312		);313		self.save()314	}315316	/// Checks that the collection was created with, and must be operated upon through **Unique API**.317	/// Now check only the `external` flag and if it's **true**, then return [`Error::CollectionIsExternal`] error.318	pub fn check_is_internal(&self) -> DispatchResult {319		if self.flags.external {320			return Err(<Error<T>>::CollectionIsExternal)?;321		}322323		Ok(())324	}325326	/// Checks that the collection was created with, and must be operated upon through an **assimilated API**.327	/// Now check only the `external` flag and if it's **false**, then return [`Error::CollectionIsInternal`] error.328	pub fn check_is_external(&self) -> DispatchResult {329		if !self.flags.external {330			return Err(<Error<T>>::CollectionIsInternal)?;331		}332333		Ok(())334	}335}336337impl<T: Config> Deref for CollectionHandle<T> {338	type Target = Collection<T::AccountId>;339340	fn deref(&self) -> &Self::Target {341		&self.collection342	}343}344345impl<T: Config> DerefMut for CollectionHandle<T> {346	fn deref_mut(&mut self) -> &mut Self::Target {347		&mut self.collection348	}349}350351impl<T: Config> CollectionHandle<T> {352	/// Checks if the `user` is the owner of the collection.353	pub fn check_is_owner(&self, user: &T::CrossAccountId) -> DispatchResult {354		ensure!(*user.as_sub() == self.owner, <Error<T>>::NoPermission);355		Ok(())356	}357358	/// Returns **true** if the `user` is the owner or administrator of the collection.359	pub fn is_owner_or_admin(&self, user: &T::CrossAccountId) -> bool {360		*user.as_sub() == self.owner || <IsAdmin<T>>::get((self.id, user))361	}362363	/// Checks if the `user` is the owner or administrator of the collection.364	pub fn check_is_owner_or_admin(&self, user: &T::CrossAccountId) -> DispatchResult {365		ensure!(self.is_owner_or_admin(user), <Error<T>>::NoPermission);366		Ok(())367	}368369	/// Returns **true** if370	/// * the `user`is a collection owner or admin371	/// * the collection limits allow the owner/admins to transfer/burn any collection token372	pub fn ignores_token_restrictions(&self, user: &T::CrossAccountId) -> bool {373		self.limits.owner_can_transfer() && self.is_owner_or_admin(user)374	}375376	/// Return **true** if `user` does not have enough token parts, and he can ignore such restrictions.377	pub fn ignores_owned_amount(&self, user: &T::CrossAccountId) -> bool {378		self.limits.owner_can_transfer() && self.is_owner_or_admin(user)379	}380381	/// Checks if the user is in the allow list. If not [Error::AddressNotInAllowlist] returns.382	pub fn check_allowlist(&self, user: &T::CrossAccountId) -> DispatchResult {383		ensure!(384			<Allowlist<T>>::get((self.id, user)),385			<Error<T>>::AddressNotInAllowlist386		);387		Ok(())388	}389390	/// Changes collection owner to another account391	/// #### Store read/writes392	/// 1 writes393	pub fn change_owner(394		&mut self,395		caller: T::CrossAccountId,396		new_owner: T::CrossAccountId,397	) -> DispatchResult {398		self.check_is_internal()?;399		self.check_is_owner(&caller)?;400		self.collection.owner = new_owner.as_sub().clone();401402		<Pallet<T>>::deposit_event(Event::<T>::CollectionOwnerChanged(403			self.id,404			new_owner.as_sub().clone(),405		));406		<PalletEvm<T>>::deposit_log(407			erc::CollectionHelpersEvents::CollectionChanged {408				collection_id: eth::collection_id_to_address(self.id),409			}410			.to_log(T::ContractAddress::get()),411		);412413		self.save()414	}415}416417#[frame_support::pallet]418pub mod pallet {419420	use super::*;421	use dispatch::CollectionDispatch;422	use frame_support::{Blake2_128Concat, pallet_prelude::*, storage::Key, traits::StorageVersion};423	use frame_support::traits::Currency;424	use up_data_structs::{TokenId, mapping::TokenAddressMapping};425	use scale_info::TypeInfo;426	use weights::WeightInfo;427428	#[pallet::config]429	pub trait Config:430		frame_system::Config + pallet_evm_coder_substrate::Config + pallet_evm::Config + TypeInfo431	{432		/// Weight information for functions of this pallet.433		type WeightInfo: WeightInfo;434435		/// Events compatible with [`frame_system::Config::Event`].436		type RuntimeEvent: IsType<<Self as frame_system::Config>::RuntimeEvent> + From<Event<Self>>;437438		/// Handler of accounts and payment.439		type Currency: Currency<Self::AccountId>;440441		/// Set price to create a collection.442		#[pallet::constant]443		type CollectionCreationPrice: Get<444			<<Self as Config>::Currency as Currency<Self::AccountId>>::Balance,445		>;446447		/// Dispatcher of operations on collections.448		type CollectionDispatch: CollectionDispatch<Self>;449450		/// Account which holds the chain's treasury.451		type TreasuryAccountId: Get<Self::AccountId>;452453		/// Address under which the CollectionHelper contract would be available.454		#[pallet::constant]455		type ContractAddress: Get<H160>;456457		/// Mapper for token addresses to Ethereum addresses.458		type EvmTokenAddressMapping: TokenAddressMapping<H160>;459460		/// Mapper for token addresses to [`CrossAccountId`].461		type CrossTokenAddressMapping: TokenAddressMapping<Self::CrossAccountId>;462	}463464	const STORAGE_VERSION: StorageVersion = StorageVersion::new(1);465	pub const NATIVE_FINGIBLE_COLLECTION_ID: CollectionId = CollectionId(0);466467	#[pallet::pallet]468	#[pallet::storage_version(STORAGE_VERSION)]469	pub struct Pallet<T>(_);470471	#[pallet::extra_constants]472	impl<T: Config> Pallet<T> {473		/// Maximum admins per collection.474		pub fn collection_admins_limit() -> u32 {475			COLLECTION_ADMINS_LIMIT476		}477	}478479	#[pallet::genesis_config]480	pub struct GenesisConfig<T>(PhantomData<T>);481482	#[cfg(feature = "std")]483	impl<T: Config> Default for GenesisConfig<T> {484		fn default() -> Self {485			Self(Default::default())486		}487	}488489	#[pallet::genesis_build]490	impl<T: Config> GenesisBuild<T> for GenesisConfig<T> {491		fn build(&self) {492			StorageVersion::new(1).put::<Pallet<T>>();493		}494	}495496	impl<T: Config> Pallet<T> {497		/// Helper function that handles deposit events498		pub fn deposit_event(event: Event<T>) {499			let event = <T as Config>::RuntimeEvent::from(event);500			let event = event.into();501			<frame_system::Pallet<T>>::deposit_event(event)502		}503	}504505	#[pallet::event]506	pub enum Event<T: Config> {507		/// New collection was created508		CollectionCreated(509			/// Globally unique identifier of newly created collection.510			CollectionId,511			/// [`CollectionMode`] converted into _u8_.512			u8,513			/// Collection owner.514			T::AccountId,515		),516517		/// New collection was destroyed518		CollectionDestroyed(519			/// Globally unique identifier of collection.520			CollectionId,521		),522523		/// New item was created.524		ItemCreated(525			/// Id of the collection where item was created.526			CollectionId,527			/// Id of an item. Unique within the collection.528			TokenId,529			/// Owner of newly created item530			T::CrossAccountId,531			/// Always 1 for NFT532			u128,533		),534535		/// Collection item was burned.536		ItemDestroyed(537			/// Id of the collection where item was destroyed.538			CollectionId,539			/// Identifier of burned NFT.540			TokenId,541			/// Which user has destroyed its tokens.542			T::CrossAccountId,543			/// Amount of token pieces destroed. Always 1 for NFT.544			u128,545		),546547		/// Item was transferred548		Transfer(549			/// Id of collection to which item is belong.550			CollectionId,551			/// Id of an item.552			TokenId,553			/// Original owner of item.554			T::CrossAccountId,555			/// New owner of item.556			T::CrossAccountId,557			/// Amount of token pieces transfered. Always 1 for NFT.558			u128,559		),560561		/// Amount pieces of token owned by `sender` was approved for `spender`.562		Approved(563			/// Id of collection to which item is belong.564			CollectionId,565			/// Id of an item.566			TokenId,567			/// Original owner of item.568			T::CrossAccountId,569			/// Id for which the approval was granted.570			T::CrossAccountId,571			/// Amount of token pieces transfered. Always 1 for NFT.572			u128,573		),574575		/// A `sender` approves operations on all owned tokens for `spender`.576		ApprovedForAll(577			/// Id of collection to which item is belong.578			CollectionId,579			/// Owner of a wallet.580			T::CrossAccountId,581			/// Id for which operator status was granted or rewoked.582			T::CrossAccountId,583			/// Is operator status granted or revoked?584			bool,585		),586587		/// The colletion property has been added or edited.588		CollectionPropertySet(589			/// Id of collection to which property has been set.590			CollectionId,591			/// The property that was set.592			PropertyKey,593		),594595		/// The property has been deleted.596		CollectionPropertyDeleted(597			/// Id of collection to which property has been deleted.598			CollectionId,599			/// The property that was deleted.600			PropertyKey,601		),602603		/// The token property has been added or edited.604		TokenPropertySet(605			/// Identifier of the collection whose token has the property set.606			CollectionId,607			/// The token for which the property was set.608			TokenId,609			/// The property that was set.610			PropertyKey,611		),612613		/// The token property has been deleted.614		TokenPropertyDeleted(615			/// Identifier of the collection whose token has the property deleted.616			CollectionId,617			/// The token for which the property was deleted.618			TokenId,619			/// The property that was deleted.620			PropertyKey,621		),622623		/// The token property permission of a collection has been set.624		PropertyPermissionSet(625			/// ID of collection to which property permission has been set.626			CollectionId,627			/// The property permission that was set.628			PropertyKey,629		),630631		/// Address was added to the allow list.632		AllowListAddressAdded(633			/// ID of the affected collection.634			CollectionId,635			/// Address of the added account.636			T::CrossAccountId,637		),638639		/// Address was removed from the allow list.640		AllowListAddressRemoved(641			/// ID of the affected collection.642			CollectionId,643			/// Address of the removed account.644			T::CrossAccountId,645		),646647		/// Collection admin was added.648		CollectionAdminAdded(649			/// ID of the affected collection.650			CollectionId,651			/// Admin address.652			T::CrossAccountId,653		),654655		/// Collection admin was removed.656		CollectionAdminRemoved(657			/// ID of the affected collection.658			CollectionId,659			/// Removed admin address.660			T::CrossAccountId,661		),662663		/// Collection limits were set.664		CollectionLimitSet(665			/// ID of the affected collection.666			CollectionId,667		),668669		/// Collection owned was changed.670		CollectionOwnerChanged(671			/// ID of the affected collection.672			CollectionId,673			/// New owner address.674			T::AccountId,675		),676677		/// Collection permissions were set.678		CollectionPermissionSet(679			/// ID of the affected collection.680			CollectionId,681		),682683		/// Collection sponsor was set.684		CollectionSponsorSet(685			/// ID of the affected collection.686			CollectionId,687			/// New sponsor address.688			T::AccountId,689		),690691		/// New sponsor was confirm.692		SponsorshipConfirmed(693			/// ID of the affected collection.694			CollectionId,695			/// New sponsor address.696			T::AccountId,697		),698699		/// Collection sponsor was removed.700		CollectionSponsorRemoved(701			/// ID of the affected collection.702			CollectionId,703		),704	}705706	#[pallet::error]707	pub enum Error<T> {708		/// This collection does not exist.709		CollectionNotFound,710		/// Sender parameter and item owner must be equal.711		MustBeTokenOwner,712		/// No permission to perform action713		NoPermission,714		/// Destroying only empty collections is allowed715		CantDestroyNotEmptyCollection,716		/// Collection is not in mint mode.717		PublicMintingNotAllowed,718		/// Address is not in allow list.719		AddressNotInAllowlist,720721		/// Collection name can not be longer than 63 char.722		CollectionNameLimitExceeded,723		/// Collection description can not be longer than 255 char.724		CollectionDescriptionLimitExceeded,725		/// Token prefix can not be longer than 15 char.726		CollectionTokenPrefixLimitExceeded,727		/// Total collections bound exceeded.728		TotalCollectionsLimitExceeded,729		/// Exceeded max admin count730		CollectionAdminCountExceeded,731		/// Collection limit bounds per collection exceeded732		CollectionLimitBoundsExceeded,733		/// Tried to enable permissions which are only permitted to be disabled734		OwnerPermissionsCantBeReverted,735		/// Collection settings not allowing items transferring736		TransferNotAllowed,737		/// Account token limit exceeded per collection738		AccountTokenLimitExceeded,739		/// Collection token limit exceeded740		CollectionTokenLimitExceeded,741		/// Metadata flag frozen742		MetadataFlagFrozen,743744		/// Item does not exist745		TokenNotFound,746		/// Item is balance not enough747		TokenValueTooLow,748		/// Requested value is more than the approved749		ApprovedValueTooLow,750		/// Tried to approve more than owned751		CantApproveMoreThanOwned,752		/// Only spending from eth mirror could be approved753		AddressIsNotEthMirror,754755		/// Can't transfer tokens to ethereum zero address756		AddressIsZero,757758		/// The operation is not supported759		UnsupportedOperation,760761		/// Insufficient funds to perform an action762		NotSufficientFounds,763764		/// User does not satisfy the nesting rule765		UserIsNotAllowedToNest,766		/// Only tokens from specific collections may nest tokens under this one767		SourceCollectionIsNotAllowedToNest,768769		/// Tried to store more data than allowed in collection field770		CollectionFieldSizeExceeded,771772		/// Tried to store more property data than allowed773		NoSpaceForProperty,774775		/// Tried to store more property keys than allowed776		PropertyLimitReached,777778		/// Property key is too long779		PropertyKeyIsTooLong,780781		/// Only ASCII letters, digits, and symbols `_`, `-`, and `.` are allowed782		InvalidCharacterInPropertyKey,783784		/// Empty property keys are forbidden785		EmptyPropertyKey,786787		/// Tried to access an external collection with an internal API788		CollectionIsExternal,789790		/// Tried to access an internal collection with an external API791		CollectionIsInternal,792793		/// This address is not set as sponsor, use setCollectionSponsor first.794		ConfirmSponsorshipFail,795796		/// The user is not an administrator.797		UserIsNotCollectionAdmin,798	}799800	/// Storage of the count of created collections. Essentially contains the last collection ID.801	#[pallet::storage]802	pub type CreatedCollectionCount<T> = StorageValue<Value = CollectionId, QueryKind = ValueQuery>;803804	/// Storage of the count of deleted collections.805	#[pallet::storage]806	pub type DestroyedCollectionCount<T> =807		StorageValue<Value = CollectionId, QueryKind = ValueQuery>;808809	/// Storage of collection info.810	#[pallet::storage]811	pub type CollectionById<T> = StorageMap<812		Hasher = Blake2_128Concat,813		Key = CollectionId,814		Value = Collection<<T as frame_system::Config>::AccountId>,815		QueryKind = OptionQuery,816	>;817818	/// Storage of collection properties.819	#[pallet::storage]820	#[pallet::getter(fn collection_properties)]821	pub type CollectionProperties<T> = StorageMap<822		Hasher = Blake2_128Concat,823		Key = CollectionId,824		Value = CollectionPropertiesT,825		QueryKind = ValueQuery,826	>;827828	/// Storage of token property permissions of a collection.829	#[pallet::storage]830	#[pallet::getter(fn property_permissions)]831	pub type CollectionPropertyPermissions<T> = StorageMap<832		Hasher = Blake2_128Concat,833		Key = CollectionId,834		Value = PropertiesPermissionMap,835		QueryKind = ValueQuery,836	>;837838	/// Storage of the amount of collection admins.839	#[pallet::storage]840	pub type AdminAmount<T> = StorageMap<841		Hasher = Blake2_128Concat,842		Key = CollectionId,843		Value = u32,844		QueryKind = ValueQuery,845	>;846847	/// List of collection admins.848	#[pallet::storage]849	pub type IsAdmin<T: Config> = StorageNMap<850		Key = (851			Key<Blake2_128Concat, CollectionId>,852			Key<Blake2_128Concat, T::CrossAccountId>,853		),854		Value = bool,855		QueryKind = ValueQuery,856	>;857858	/// Allowlisted collection users.859	#[pallet::storage]860	pub type Allowlist<T: Config> = StorageNMap<861		Key = (862			Key<Blake2_128Concat, CollectionId>,863			Key<Blake2_128Concat, T::CrossAccountId>,864		),865		Value = bool,866		QueryKind = ValueQuery,867	>;868869	/// Not used by code, exists only to provide some types to metadata.870	#[pallet::storage]871	pub type DummyStorageValue<T: Config> = StorageValue<872		Value = (873			CollectionStats,874			CollectionId,875			TokenId,876			TokenChild,877			PhantomType<(878				TokenData<T::CrossAccountId>,879				RpcCollection<T::AccountId>,880				// PoV Estimate Info881				PovInfo,882			)>,883		),884		QueryKind = OptionQuery,885	>;886}887888impl<T: Config> Pallet<T> {889	/// Enshure that receiver address is correct.890	///891	/// Ethereum receiver 0x0000000000000000000000000000000000000000 is reserved, and shouldn't own tokens.892	pub fn ensure_correct_receiver(receiver: &T::CrossAccountId) -> DispatchResult {893		ensure!(894			&T::CrossAccountId::from_eth(H160([0; 20])) != receiver,895			<Error<T>>::AddressIsZero896		);897		Ok(())898	}899900	/// Get a vector of collection admins.901	pub fn adminlist(collection: CollectionId) -> Vec<T::CrossAccountId> {902		<IsAdmin<T>>::iter_prefix((collection,))903			.map(|(a, _)| a)904			.collect()905	}906907	/// Get a vector of users allowed to mint tokens.908	pub fn allowlist(collection: CollectionId) -> Vec<T::CrossAccountId> {909		<Allowlist<T>>::iter_prefix((collection,))910			.map(|(a, _)| a)911			.collect()912	}913914	/// Is `user` allowed to mint token in `collection`.915	pub fn allowed(collection: CollectionId, user: T::CrossAccountId) -> bool {916		<Allowlist<T>>::get((collection, user))917	}918919	/// Get statistics of collections.920	pub fn collection_stats() -> CollectionStats {921		let created = <CreatedCollectionCount<T>>::get();922		let destroyed = <DestroyedCollectionCount<T>>::get();923		CollectionStats {924			created: created.0,925			destroyed: destroyed.0,926			alive: created.0 - destroyed.0,927		}928	}929930	/// Get the effective limits for the collection.931	pub fn effective_collection_limits(collection: CollectionId) -> Option<CollectionLimits> {932		let collection = <CollectionById<T>>::get(collection)?;933		let limits = collection.limits;934		let effective_limits = CollectionLimits {935			account_token_ownership_limit: Some(limits.account_token_ownership_limit()),936			sponsored_data_size: Some(limits.sponsored_data_size()),937			sponsored_data_rate_limit: Some(938				limits939					.sponsored_data_rate_limit940					.unwrap_or(SponsoringRateLimit::SponsoringDisabled),941			),942			token_limit: Some(limits.token_limit()),943			sponsor_transfer_timeout: Some(limits.sponsor_transfer_timeout(944				match collection.mode {945					CollectionMode::NFT => NFT_SPONSOR_TRANSFER_TIMEOUT,946					CollectionMode::Fungible(_) => FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,947					CollectionMode::ReFungible => REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,948				},949			)),950			sponsor_approve_timeout: Some(limits.sponsor_approve_timeout()),951			owner_can_transfer: Some(limits.owner_can_transfer()),952			owner_can_destroy: Some(limits.owner_can_destroy()),953			transfers_enabled: Some(limits.transfers_enabled()),954		};955956		Some(effective_limits)957	}958959	/// Returns information about the `collection` adapted for rpc.960	pub fn rpc_collection(collection: CollectionId) -> Option<RpcCollection<T::AccountId>> {961		let Collection {962			name,963			description,964			owner,965			mode,966			token_prefix,967			sponsorship,968			limits,969			permissions,970			flags,971		} = <CollectionById<T>>::get(collection)?;972973		let token_property_permissions = <CollectionPropertyPermissions<T>>::get(collection)974			.into_iter()975			.map(|(key, permission)| PropertyKeyPermission { key, permission })976			.collect();977978		let properties = <CollectionProperties<T>>::get(collection)979			.into_iter()980			.map(|(key, value)| Property { key, value })981			.collect();982983		let permissions = CollectionPermissions {984			access: Some(permissions.access()),985			mint_mode: Some(permissions.mint_mode()),986			nesting: Some(permissions.nesting().clone()),987		};988989		Some(RpcCollection {990			name: name.into_inner(),991			description: description.into_inner(),992			owner,993			mode,994			token_prefix: token_prefix.into_inner(),995			sponsorship,996			limits,997			permissions,998			token_property_permissions,999			properties,1000			read_only: flags.external,10011002			flags: RpcCollectionFlags {1003				foreign: flags.foreign,1004				erc721metadata: flags.erc721metadata,1005			},1006		})1007	}1008}10091010macro_rules! limit_default {1011	($old:ident, $new:ident, $($field:ident $(($arg:expr))? => $check:expr),* $(,)?) => {{1012		$(1013			if let Some($new) = $new.$field {1014				let $old = $old.$field($($arg)?);1015				let _ = $new;1016				let _ = $old;1017				$check1018			} else {1019				$new.$field = $old.$field1020			}1021		)*1022	}};1023}1024macro_rules! limit_default_clone {1025	($old:ident, $new:ident, $($field:ident $(($arg:expr))? => $check:expr),* $(,)?) => {{1026		$(1027			if let Some($new) = $new.$field.clone() {1028				let $old = $old.$field($($arg)?);1029				let _ = $new;1030				let _ = $old;1031				$check1032			} else {1033				$new.$field = $old.$field.clone()1034			}1035		)*1036	}};1037}10381039impl<T: Config> Pallet<T> {1040	/// Create new collection.1041	///1042	/// * `owner` - The owner of the collection.1043	/// * `data` - Description of the created collection.1044	/// * `flags` - Extra flags to store.1045	pub fn init_collection(1046		owner: T::CrossAccountId,1047		payer: T::CrossAccountId,1048		data: CreateCollectionData<T::AccountId>,1049		flags: CollectionFlags,1050	) -> Result<CollectionId, DispatchError> {1051		{1052			ensure!(1053				data.token_prefix.len() <= MAX_TOKEN_PREFIX_LENGTH as usize,1054				Error::<T>::CollectionTokenPrefixLimitExceeded1055			);1056		}10571058		let created_count = <CreatedCollectionCount<T>>::get()1059			.01060			.checked_add(1)1061			.ok_or(ArithmeticError::Overflow)?;1062		let destroyed_count = <DestroyedCollectionCount<T>>::get().0;1063		let id = CollectionId(created_count);10641065		// bound Total number of collections1066		ensure!(1067			created_count - destroyed_count <= COLLECTION_NUMBER_LIMIT,1068			<Error<T>>::TotalCollectionsLimitExceeded1069		);10701071		// =========10721073		let collection = Collection {1074			owner: owner.as_sub().clone(),1075			name: data.name,1076			mode: data.mode.clone(),1077			description: data.description,1078			token_prefix: data.token_prefix,1079			sponsorship: data1080				.pending_sponsor1081				.map(SponsorshipState::Unconfirmed)1082				.unwrap_or_default(),1083			limits: data1084				.limits1085				.map(|limits| Self::clamp_limits(data.mode.clone(), &Default::default(), limits))1086				.unwrap_or_else(|| Ok(CollectionLimits::default()))?,1087			permissions: data1088				.permissions1089				.map(|permissions| {1090					Self::clamp_permissions(data.mode.clone(), &Default::default(), permissions)1091				})1092				.unwrap_or_else(|| Ok(CollectionPermissions::default()))?,1093			flags,1094		};10951096		let mut collection_properties = CollectionPropertiesT::new();1097		collection_properties1098			.try_set_from_iter(data.properties.into_iter())1099			.map_err(<Error<T>>::from)?;11001101		CollectionProperties::<T>::insert(id, collection_properties);11021103		let mut token_props_permissions = PropertiesPermissionMap::new();1104		token_props_permissions1105			.try_set_from_iter(data.token_property_permissions.into_iter())1106			.map_err(<Error<T>>::from)?;11071108		CollectionPropertyPermissions::<T>::insert(id, token_props_permissions);11091110		// Take a (non-refundable) deposit of collection creation1111		{1112			let mut imbalance =1113				<<<T as Config>::Currency as Currency<T::AccountId>>::PositiveImbalance>::zero();1114			imbalance.subsume(1115				<<T as Config>::Currency as Currency<T::AccountId>>::deposit_creating(1116					&T::TreasuryAccountId::get(),1117					T::CollectionCreationPrice::get(),1118				),1119			);1120			<T as Config>::Currency::settle(1121				payer.as_sub(),1122				imbalance,1123				WithdrawReasons::TRANSFER,1124				ExistenceRequirement::KeepAlive,1125			)1126			.map_err(|_| Error::<T>::NotSufficientFounds)?;1127		}11281129		<CreatedCollectionCount<T>>::put(created_count);1130		<Pallet<T>>::deposit_event(Event::CollectionCreated(1131			id,1132			data.mode.id(),1133			owner.as_sub().clone(),1134		));1135		<PalletEvm<T>>::deposit_log(1136			erc::CollectionHelpersEvents::CollectionCreated {1137				owner: *owner.as_eth(),1138				collection_id: eth::collection_id_to_address(id),1139			}1140			.to_log(T::ContractAddress::get()),1141		);1142		<CollectionById<T>>::insert(id, collection);1143		Ok(id)1144	}11451146	/// Destroy collection.1147	///1148	/// * `collection` - Collection handler.1149	/// * `sender` - The owner or administrator of the collection.1150	pub fn destroy_collection(1151		collection: CollectionHandle<T>,1152		sender: &T::CrossAccountId,1153	) -> DispatchResult {1154		ensure!(1155			collection.limits.owner_can_destroy(),1156			<Error<T>>::NoPermission,1157		);1158		collection.check_is_owner(sender)?;11591160		let destroyed_collections = <DestroyedCollectionCount<T>>::get()1161			.01162			.checked_add(1)1163			.ok_or(ArithmeticError::Overflow)?;11641165		// =========11661167		<DestroyedCollectionCount<T>>::put(destroyed_collections);1168		<CollectionById<T>>::remove(collection.id);1169		<AdminAmount<T>>::remove(collection.id);1170		let _ = <IsAdmin<T>>::clear_prefix((collection.id,), u32::MAX, None);1171		let _ = <Allowlist<T>>::clear_prefix((collection.id,), u32::MAX, None);1172		<CollectionProperties<T>>::remove(collection.id);11731174		<Pallet<T>>::deposit_event(Event::CollectionDestroyed(collection.id));11751176		<PalletEvm<T>>::deposit_log(1177			erc::CollectionHelpersEvents::CollectionDestroyed {1178				collection_id: eth::collection_id_to_address(collection.id),1179			}1180			.to_log(T::ContractAddress::get()),1181		);1182		Ok(())1183	}11841185	/// This function sets or removes a collection properties according to1186	/// `properties_updates` contents:1187	/// * sets a property under the <key> with the value provided `(<key>, Some(<value>))`1188	/// * removes a property under the <key> if the value is `None` `(<key>, None)`.1189	///1190	/// This function fires an event for each property change.1191	/// In case of an error, all the changes (including the events) will be reverted1192	/// since the function is transactional.1193	#[transactional]1194	fn modify_collection_properties(1195		collection: &CollectionHandle<T>,1196		sender: &T::CrossAccountId,1197		properties_updates: impl Iterator<Item = (PropertyKey, Option<PropertyValue>)>,1198	) -> DispatchResult {1199		collection.check_is_owner_or_admin(sender)?;12001201		let mut stored_properties = <CollectionProperties<T>>::get(collection.id);12021203		for (key, value) in properties_updates {1204			match value {1205				Some(value) => {1206					stored_properties1207						.try_set(key.clone(), value)1208						.map_err(<Error<T>>::from)?;12091210					Self::deposit_event(Event::CollectionPropertySet(collection.id, key));1211					<PalletEvm<T>>::deposit_log(1212						erc::CollectionHelpersEvents::CollectionChanged {1213							collection_id: eth::collection_id_to_address(collection.id),1214						}1215						.to_log(T::ContractAddress::get()),1216					);1217				}1218				None => {1219					stored_properties.remove(&key).map_err(<Error<T>>::from)?;12201221					Self::deposit_event(Event::CollectionPropertyDeleted(collection.id, key));1222					<PalletEvm<T>>::deposit_log(1223						erc::CollectionHelpersEvents::CollectionChanged {1224							collection_id: eth::collection_id_to_address(collection.id),1225						}1226						.to_log(T::ContractAddress::get()),1227					);1228				}1229			}1230		}12311232		<CollectionProperties<T>>::set(collection.id, stored_properties);12331234		Ok(())1235	}12361237	/// A batch operation to add, edit or remove properties for a token.1238	/// It sets or removes a token's properties according to1239	/// `properties_updates` contents:1240	/// * sets a property under the <key> with the value provided `(<key>, Some(<value>))`1241	/// * removes a property under the <key> if the value is `None` `(<key>, None)`.1242	///1243	/// - `nesting_budget`: Limit for searching parents in-depth to check ownership.1244	/// - `is_token_create`: Indicates that method is called during token initialization.1245	///   Allows to bypass ownership check.1246	///1247	/// All affected properties should have `mutable` permission1248	/// to be **deleted** or to be **set more than once**,1249	/// and the sender should have permission to edit those properties.1250	///1251	/// This function fires an event for each property change.1252	/// In case of an error, all the changes (including the events) will be reverted1253	/// since the function is transactional.1254	pub fn modify_token_properties(1255		collection: &CollectionHandle<T>,1256		sender: &T::CrossAccountId,1257		token_id: TokenId,1258		properties_updates: impl Iterator<Item = (PropertyKey, Option<PropertyValue>)>,1259		is_token_create: bool,1260		mut stored_properties: TokenProperties,1261		is_token_owner: impl Fn() -> Result<bool, DispatchError>,1262		set_token_properties: impl FnOnce(TokenProperties),1263		log: evm_coder::ethereum::Log,1264	) -> DispatchResult {1265		let is_collection_admin = collection.is_owner_or_admin(sender);1266		let permissions = Self::property_permissions(collection.id);12671268		let mut token_owner_result = None;1269		let mut is_token_owner = || -> Result<bool, DispatchError> {1270			*token_owner_result.get_or_insert_with(&is_token_owner)1271		};12721273		for (key, value) in properties_updates {1274			let permission = permissions1275				.get(&key)1276				.cloned()1277				.unwrap_or_else(PropertyPermission::none);12781279			let is_property_exists = stored_properties.get(&key).is_some();12801281			match permission {1282				PropertyPermission { mutable: false, .. } if is_property_exists => {1283					return Err(<Error<T>>::NoPermission.into());1284				}12851286				PropertyPermission {1287					collection_admin,1288					token_owner,1289					..1290				} => {1291					//TODO: investigate threats during public minting.1292					let is_token_create =1293						is_token_create && (collection_admin || token_owner) && value.is_some();1294					if !(is_token_create1295						|| (collection_admin && is_collection_admin)1296						|| (token_owner && is_token_owner()?))1297					{1298						fail!(<Error<T>>::NoPermission);1299					}1300				}1301			}13021303			match value {1304				Some(value) => {1305					stored_properties1306						.try_set(key.clone(), value)1307						.map_err(<Error<T>>::from)?;13081309					Self::deposit_event(Event::TokenPropertySet(collection.id, token_id, key));1310				}1311				None => {1312					stored_properties.remove(&key).map_err(<Error<T>>::from)?;13131314					Self::deposit_event(Event::TokenPropertyDeleted(collection.id, token_id, key));1315				}1316			}13171318			<PalletEvm<T>>::deposit_log(log.clone());1319		}13201321		set_token_properties(stored_properties);13221323		Ok(())1324	}13251326	/// Sets or unsets the approval of a given operator.1327	///1328	/// The `operator` is allowed to transfer all token pieces of the `owner` on their behalf.1329	/// - `owner`: Token owner1330	/// - `operator`: Operator1331	/// - `approve`: Should operator status be granted or revoked?1332	pub fn set_allowance_for_all(1333		collection: &CollectionHandle<T>,1334		owner: &T::CrossAccountId,1335		operator: &T::CrossAccountId,1336		approve: bool,1337		set_allowance: impl FnOnce(),1338		log: evm_coder::ethereum::Log,1339	) -> DispatchResult {1340		if collection.permissions.access() == AccessMode::AllowList {1341			collection.check_allowlist(owner)?;1342			collection.check_allowlist(operator)?;1343		}13441345		Self::ensure_correct_receiver(operator)?;13461347		set_allowance();13481349		<PalletEvm<T>>::deposit_log(log);1350		Self::deposit_event(Event::ApprovedForAll(1351			collection.id,1352			owner.clone(),1353			operator.clone(),1354			approve,1355		));1356		Ok(())1357	}13581359	/// Set collection property.1360	///1361	/// * `collection` - Collection handler.1362	/// * `sender` - The owner or administrator of the collection.1363	/// * `property` - The property to set.1364	pub fn set_collection_property(1365		collection: &CollectionHandle<T>,1366		sender: &T::CrossAccountId,1367		property: Property,1368	) -> DispatchResult {1369		Self::set_collection_properties(collection, sender, [property].into_iter())1370	}13711372	/// Set a scoped collection property, where the scope is a special prefix1373	/// prohibiting a user access to change the property directly.1374	///1375	/// * `collection_id` - ID of the collection for which the property is being set.1376	/// * `scope` - Property scope.1377	/// * `property` - The property to set.1378	pub fn set_scoped_collection_property(1379		collection_id: CollectionId,1380		scope: PropertyScope,1381		property: Property,1382	) -> DispatchResult {1383		CollectionProperties::<T>::try_mutate(collection_id, |properties| {1384			properties.try_scoped_set(scope, property.key, property.value)1385		})1386		.map_err(<Error<T>>::from)?;13871388		Ok(())1389	}13901391	/// Set scoped collection properties, where the scope is a special prefix1392	/// prohibiting a user access to change the properties directly.1393	///1394	/// * `collection_id` - ID of the collection for which the properties is being set.1395	/// * `scope` - Property scope.1396	/// * `properties` - The properties to set.1397	pub fn set_scoped_collection_properties(1398		collection_id: CollectionId,1399		scope: PropertyScope,1400		properties: impl Iterator<Item = Property>,1401	) -> DispatchResult {1402		CollectionProperties::<T>::try_mutate(collection_id, |stored_properties| {1403			stored_properties.try_scoped_set_from_iter(scope, properties)1404		})1405		.map_err(<Error<T>>::from)?;14061407		Ok(())1408	}14091410	/// Set collection properties.1411	///1412	/// * `collection` - Collection handler.1413	/// * `sender` - The owner or administrator of the collection.1414	/// * `properties` - The properties to set.1415	pub fn set_collection_properties(1416		collection: &CollectionHandle<T>,1417		sender: &T::CrossAccountId,1418		properties: impl Iterator<Item = Property>,1419	) -> DispatchResult {1420		Self::modify_collection_properties(1421			collection,1422			sender,1423			properties.map(|property| (property.key, Some(property.value))),1424		)1425	}14261427	/// Delete collection property.1428	///1429	/// * `collection` - Collection handler.1430	/// * `sender` - The owner or administrator of the collection.1431	/// * `property` - The property to delete.1432	pub fn delete_collection_property(1433		collection: &CollectionHandle<T>,1434		sender: &T::CrossAccountId,1435		property_key: PropertyKey,1436	) -> DispatchResult {1437		Self::delete_collection_properties(collection, sender, [property_key].into_iter())1438	}14391440	/// Delete collection properties.1441	///1442	/// * `collection` - Collection handler.1443	/// * `sender` - The owner or administrator of the collection.1444	/// * `properties` - The properties to delete.1445	pub fn delete_collection_properties(1446		collection: &CollectionHandle<T>,1447		sender: &T::CrossAccountId,1448		property_keys: impl Iterator<Item = PropertyKey>,1449	) -> DispatchResult {1450		Self::modify_collection_properties(collection, sender, property_keys.map(|key| (key, None)))1451	}14521453	/// Set collection propetry permission without any checks.1454	///1455	/// Used for migrations.1456	///1457	/// * `collection` - Collection handler.1458	/// * `property_permissions` - Property permissions.1459	pub fn set_property_permission_unchecked(1460		collection: CollectionId,1461		property_permission: PropertyKeyPermission,1462	) -> DispatchResult {1463		<CollectionPropertyPermissions<T>>::try_mutate(collection, |permissions| {1464			permissions.try_set(property_permission.key, property_permission.permission)1465		})1466		.map_err(<Error<T>>::from)?;1467		Ok(())1468	}14691470	/// Set collection property permission.1471	///1472	/// * `collection` - Collection handler.1473	/// * `sender` - The owner or administrator of the collection.1474	/// * `property_permission` - Property permission.1475	pub fn set_property_permission(1476		collection: &CollectionHandle<T>,1477		sender: &T::CrossAccountId,1478		property_permission: PropertyKeyPermission,1479	) -> DispatchResult {1480		Self::set_scoped_property_permission(1481			collection,1482			sender,1483			PropertyScope::None,1484			property_permission,1485		)1486	}14871488	/// Set collection property permission with scope.1489	///1490	/// * `collection` - Collection handler.1491	/// * `sender` - The owner or administrator of the collection.1492	/// * `scope` - Property scope.1493	/// * `property_permission` - Property permission.1494	pub fn set_scoped_property_permission(1495		collection: &CollectionHandle<T>,1496		sender: &T::CrossAccountId,1497		scope: PropertyScope,1498		property_permission: PropertyKeyPermission,1499	) -> DispatchResult {1500		collection.check_is_owner_or_admin(sender)?;15011502		let all_permissions = CollectionPropertyPermissions::<T>::get(collection.id);1503		let current_permission = all_permissions.get(&property_permission.key);1504		if matches![1505			current_permission,1506			Some(PropertyPermission { mutable: false, .. })1507		] {1508			return Err(<Error<T>>::NoPermission.into());1509		}15101511		CollectionPropertyPermissions::<T>::try_mutate(collection.id, |permissions| {1512			let property_permission = property_permission.clone();1513			permissions.try_scoped_set(1514				scope,1515				property_permission.key,1516				property_permission.permission,1517			)1518		})1519		.map_err(<Error<T>>::from)?;15201521		Self::deposit_event(Event::PropertyPermissionSet(1522			collection.id,1523			property_permission.key,1524		));1525		<PalletEvm<T>>::deposit_log(1526			erc::CollectionHelpersEvents::CollectionChanged {1527				collection_id: eth::collection_id_to_address(collection.id),1528			}1529			.to_log(T::ContractAddress::get()),1530		);15311532		Ok(())1533	}15341535	/// Set token property permission.1536	///1537	/// * `collection` - Collection handler.1538	/// * `sender` - The owner or administrator of the collection.1539	/// * `property_permissions` - Property permissions.1540	#[transactional]1541	pub fn set_token_property_permissions(1542		collection: &CollectionHandle<T>,1543		sender: &T::CrossAccountId,1544		property_permissions: Vec<PropertyKeyPermission>,1545	) -> DispatchResult {1546		Self::set_scoped_token_property_permissions(1547			collection,1548			sender,1549			PropertyScope::None,1550			property_permissions,1551		)1552	}15531554	/// Set token property permission with scope.1555	///1556	/// * `collection` - Collection handler.1557	/// * `sender` - The owner or administrator of the collection.1558	/// * `scope` - Property scope.1559	/// * `property_permissions` - Property permissions.1560	#[transactional]1561	pub fn set_scoped_token_property_permissions(1562		collection: &CollectionHandle<T>,1563		sender: &T::CrossAccountId,1564		scope: PropertyScope,1565		property_permissions: Vec<PropertyKeyPermission>,1566	) -> DispatchResult {1567		for prop_pemission in property_permissions {1568			Self::set_scoped_property_permission(collection, sender, scope, prop_pemission)?;1569		}15701571		Ok(())1572	}15731574	/// Get collection property.1575	pub fn get_collection_property(1576		collection_id: CollectionId,1577		key: &PropertyKey,1578	) -> Option<PropertyValue> {1579		Self::collection_properties(collection_id).get(key).cloned()1580	}15811582	/// Convert byte vector to property key vector.1583	pub fn bytes_keys_to_property_keys(1584		keys: Vec<Vec<u8>>,1585	) -> Result<Vec<PropertyKey>, DispatchError> {1586		keys.into_iter()1587			.map(|key| -> Result<PropertyKey, DispatchError> {1588				key.try_into()1589					.map_err(|_| <Error<T>>::PropertyKeyIsTooLong.into())1590			})1591			.collect::<Result<Vec<PropertyKey>, DispatchError>>()1592	}15931594	/// Get properties according to given keys.1595	pub fn filter_collection_properties(1596		collection_id: CollectionId,1597		keys: Option<Vec<PropertyKey>>,1598	) -> Result<Vec<Property>, DispatchError> {1599		let properties = Self::collection_properties(collection_id);16001601		let properties = keys1602			.map(|keys| {1603				keys.into_iter()1604					.filter_map(|key| {1605						properties.get(&key).map(|value| Property {1606							key,1607							value: value.clone(),1608						})1609					})1610					.collect()1611			})1612			.unwrap_or_else(|| {1613				properties1614					.into_iter()1615					.map(|(key, value)| Property { key, value })1616					.collect()1617			});16181619		Ok(properties)1620	}16211622	/// Get property permissions according to given keys.1623	pub fn filter_property_permissions(1624		collection_id: CollectionId,1625		keys: Option<Vec<PropertyKey>>,1626	) -> Result<Vec<PropertyKeyPermission>, DispatchError> {1627		let permissions = Self::property_permissions(collection_id);16281629		let key_permissions = keys1630			.map(|keys| {1631				keys.into_iter()1632					.filter_map(|key| {1633						permissions1634							.get(&key)1635							.map(|permission| PropertyKeyPermission {1636								key,1637								permission: permission.clone(),1638							})1639					})1640					.collect()1641			})1642			.unwrap_or_else(|| {1643				permissions1644					.into_iter()1645					.map(|(key, permission)| PropertyKeyPermission { key, permission })1646					.collect()1647			});16481649		Ok(key_permissions)1650	}16511652	/// Toggle `user` participation in the `collection`'s allow list.1653	/// #### Store read/writes1654	/// 1 writes1655	pub fn toggle_allowlist(1656		collection: &CollectionHandle<T>,1657		sender: &T::CrossAccountId,1658		user: &T::CrossAccountId,1659		allowed: bool,1660	) -> DispatchResult {1661		collection.check_is_owner_or_admin(sender)?;16621663		// =========16641665		if allowed {1666			<Allowlist<T>>::insert((collection.id, user), true);1667			Self::deposit_event(Event::<T>::AllowListAddressAdded(1668				collection.id,1669				user.clone(),1670			));1671		} else {1672			<Allowlist<T>>::remove((collection.id, user));1673			Self::deposit_event(Event::<T>::AllowListAddressRemoved(1674				collection.id,1675				user.clone(),1676			));1677		}16781679		<PalletEvm<T>>::deposit_log(1680			erc::CollectionHelpersEvents::CollectionChanged {1681				collection_id: eth::collection_id_to_address(collection.id),1682			}1683			.to_log(T::ContractAddress::get()),1684		);16851686		Ok(())1687	}16881689	/// Toggle `user` participation in the `collection`'s admin list.1690	/// #### Store read/writes1691	/// 2 reads, 2 writes1692	pub fn toggle_admin(1693		collection: &CollectionHandle<T>,1694		sender: &T::CrossAccountId,1695		user: &T::CrossAccountId,1696		admin: bool,1697	) -> DispatchResult {1698		collection.check_is_internal()?;1699		collection.check_is_owner(sender)?;17001701		let is_admin = <IsAdmin<T>>::get((collection.id, user));1702		if is_admin == admin {1703			if admin {1704				return Ok(());1705			} else {1706				return Err(Error::<T>::UserIsNotCollectionAdmin.into());1707			}1708		}1709		let amount = <AdminAmount<T>>::get(collection.id);17101711		// =========17121713		if admin {1714			let amount = amount1715				.checked_add(1)1716				.ok_or(<Error<T>>::CollectionAdminCountExceeded)?;1717			ensure!(1718				amount <= Self::collection_admins_limit(),1719				<Error<T>>::CollectionAdminCountExceeded,1720			);17211722			<AdminAmount<T>>::insert(collection.id, amount);1723			<IsAdmin<T>>::insert((collection.id, user), true);17241725			Self::deposit_event(Event::<T>::CollectionAdminAdded(1726				collection.id,1727				user.clone(),1728			));1729		} else {1730			<AdminAmount<T>>::insert(collection.id, amount.saturating_sub(1));1731			<IsAdmin<T>>::remove((collection.id, user));17321733			Self::deposit_event(Event::<T>::CollectionAdminRemoved(1734				collection.id,1735				user.clone(),1736			));1737		}17381739		<PalletEvm<T>>::deposit_log(1740			erc::CollectionHelpersEvents::CollectionChanged {1741				collection_id: eth::collection_id_to_address(collection.id),1742			}1743			.to_log(T::ContractAddress::get()),1744		);17451746		Ok(())1747	}17481749	/// Update collection limits.1750	pub fn update_limits(1751		user: &T::CrossAccountId,1752		collection: &mut CollectionHandle<T>,1753		new_limit: CollectionLimits,1754	) -> DispatchResult {1755		collection.check_is_internal()?;1756		collection.check_is_owner_or_admin(user)?;17571758		collection.limits =1759			Self::clamp_limits(collection.mode.clone(), &collection.limits, new_limit)?;17601761		Self::deposit_event(Event::<T>::CollectionLimitSet(collection.id));1762		<PalletEvm<T>>::deposit_log(1763			erc::CollectionHelpersEvents::CollectionChanged {1764				collection_id: eth::collection_id_to_address(collection.id),1765			}1766			.to_log(T::ContractAddress::get()),1767		);17681769		collection.save()1770	}17711772	/// Merge set fields from `new_limit` to `old_limit`.1773	fn clamp_limits(1774		mode: CollectionMode,1775		old_limit: &CollectionLimits,1776		mut new_limit: CollectionLimits,1777	) -> Result<CollectionLimits, DispatchError> {1778		let limits = old_limit;1779		limit_default!(old_limit, new_limit,1780			account_token_ownership_limit => ensure!(1781				new_limit <= MAX_TOKEN_OWNERSHIP,1782				<Error<T>>::CollectionLimitBoundsExceeded,1783			),1784			sponsored_data_size => ensure!(1785				new_limit <= CUSTOM_DATA_LIMIT,1786				<Error<T>>::CollectionLimitBoundsExceeded,1787			),17881789			sponsored_data_rate_limit => {},1790			token_limit => ensure!(1791				old_limit >= new_limit && new_limit > 0,1792				<Error<T>>::CollectionTokenLimitExceeded1793			),17941795			sponsor_transfer_timeout(match mode {1796				CollectionMode::NFT => NFT_SPONSOR_TRANSFER_TIMEOUT,1797				CollectionMode::Fungible(_) => FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,1798				CollectionMode::ReFungible => REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,1799			}) => ensure!(1800				new_limit <= MAX_SPONSOR_TIMEOUT,1801				<Error<T>>::CollectionLimitBoundsExceeded,1802			),1803			sponsor_approve_timeout => {},1804			owner_can_transfer => ensure!(1805				!limits.owner_can_transfer_instaled() ||1806				old_limit || !new_limit,1807				<Error<T>>::OwnerPermissionsCantBeReverted,1808			),1809			owner_can_destroy => ensure!(1810				old_limit || !new_limit,1811				<Error<T>>::OwnerPermissionsCantBeReverted,1812			),1813			transfers_enabled => {},1814		);1815		Ok(new_limit)1816	}18171818	/// Update collection permissions.1819	pub fn update_permissions(1820		user: &T::CrossAccountId,1821		collection: &mut CollectionHandle<T>,1822		new_permission: CollectionPermissions,1823	) -> DispatchResult {1824		collection.check_is_internal()?;1825		collection.check_is_owner_or_admin(user)?;1826		collection.permissions = Self::clamp_permissions(1827			collection.mode.clone(),1828			&collection.permissions,1829			new_permission,1830		)?;18311832		Self::deposit_event(Event::<T>::CollectionPermissionSet(collection.id));1833		<PalletEvm<T>>::deposit_log(1834			erc::CollectionHelpersEvents::CollectionChanged {1835				collection_id: eth::collection_id_to_address(collection.id),1836			}1837			.to_log(T::ContractAddress::get()),1838		);18391840		collection.save()1841	}18421843	/// Merge set fields from `new_permission` to `old_permission`.1844	fn clamp_permissions(1845		_mode: CollectionMode,1846		old_permission: &CollectionPermissions,1847		mut new_permission: CollectionPermissions,1848	) -> Result<CollectionPermissions, DispatchError> {1849		limit_default_clone!(old_permission, new_permission,1850			access => {},1851			mint_mode => {},1852			nesting => { /* todo check for permissive, if only it gets out of benchmarks */ },1853		);1854		Ok(new_permission)1855	}18561857	/// Repair possibly broken properties of a collection.1858	pub fn repair_collection(collection_id: CollectionId) -> DispatchResult {1859		CollectionProperties::<T>::mutate(collection_id, |properties| {1860			properties.recompute_consumed_space();1861		});18621863		Ok(())1864	}1865}18661867/// Indicates unsupported methods by returning [Error::UnsupportedOperation].1868#[macro_export]1869macro_rules! unsupported {1870	($runtime:path) => {1871		Err($crate::Error::<$runtime>::UnsupportedOperation.into())1872	};1873}18741875/// Return weights for various worst-case operations.1876pub trait CommonWeightInfo<CrossAccountId> {1877	/// Weight of item creation.1878	fn create_item(data: &CreateItemData) -> Weight {1879		Self::create_multiple_items(from_ref(data))1880	}18811882	/// Weight of items creation.1883	fn create_multiple_items(amount: &[CreateItemData]) -> Weight;18841885	/// Weight of items creation.1886	fn create_multiple_items_ex(cost: &CreateItemExData<CrossAccountId>) -> Weight;18871888	/// The weight of the burning item.1889	fn burn_item() -> Weight;18901891	/// Property setting weight.1892	///1893	/// * `amount`- The number of properties to set.1894	fn set_collection_properties(amount: u32) -> Weight;18951896	/// Collection property deletion weight.1897	///1898	/// * `amount`- The number of properties to set.1899	fn delete_collection_properties(amount: u32) -> Weight;19001901	/// Token property setting weight.1902	///1903	/// * `amount`- The number of properties to set.1904	fn set_token_properties(amount: u32) -> Weight;19051906	/// Token property deletion weight.1907	///1908	/// * `amount`- The number of properties to delete.1909	fn delete_token_properties(amount: u32) -> Weight;19101911	/// Token property permissions set weight.1912	///1913	/// * `amount`- The number of property permissions to set.1914	fn set_token_property_permissions(amount: u32) -> Weight;19151916	/// Transfer price of the token or its parts.1917	fn transfer() -> Weight;19181919	/// The price of setting the permission of the operation from another user.1920	fn approve() -> Weight;19211922	/// The price of setting the permission of the operation from another user for eth mirror.1923	fn approve_from() -> Weight;19241925	/// Transfer price from another user.1926	fn transfer_from() -> Weight;19271928	/// The price of burning a token from another user.1929	fn burn_from() -> Weight;19301931	/// Differs from burn_item in case of Fungible and Refungible, as it should burn1932	/// whole users's balance.1933	///1934	/// This method shouldn't be used directly, as it doesn't count breadth price, use [burn_recursively](CommonWeightInfo::burn_recursively) instead1935	fn burn_recursively_self_raw() -> Weight;19361937	/// Cost of iterating over `amount` children while burning, without counting child burning itself.1938	///1939	/// This method shouldn't be used directly, as it doesn't count depth price, use [burn_recursively](CommonWeightInfo::burn_recursively) instead1940	fn burn_recursively_breadth_raw(amount: u32) -> Weight;19411942	/// The price of recursive burning a token.1943	///1944	/// `max_selfs` - The maximum burning weight of the token itself.1945	/// `max_breadth` - The maximum number of nested tokens to burn.1946	fn burn_recursively(max_selfs: u32, max_breadth: u32) -> Weight {1947		Self::burn_recursively_self_raw()1948			.saturating_mul(max_selfs.max(1) as u64)1949			.saturating_add(Self::burn_recursively_breadth_raw(max_breadth))1950	}19511952	/// The price of retrieving token owner1953	fn token_owner() -> Weight;19541955	/// The price of setting approval for all1956	fn set_allowance_for_all() -> Weight;19571958	/// The price of repairing an item.1959	fn force_repair_item() -> Weight;1960}19611962/// Weight info extension trait for refungible pallet.1963pub trait RefungibleExtensionsWeightInfo {1964	/// Weight of token repartition.1965	fn repartition() -> Weight;1966}19671968/// Common collection operations.1969///1970/// It wraps methods in Fungible, Nonfungible and Refungible pallets1971/// and adds weight info.1972pub trait CommonCollectionOperations<T: Config> {1973	/// Create token.1974	///1975	/// * `sender` - The user who mint the token and pays for the transaction.1976	/// * `to` - The user who will own the token.1977	/// * `data` - Token data.1978	/// * `nesting_budget` - A budget that can be spent on nesting tokens.1979	fn create_item(1980		&self,1981		sender: T::CrossAccountId,1982		to: T::CrossAccountId,1983		data: CreateItemData,1984		nesting_budget: &dyn Budget,1985	) -> DispatchResultWithPostInfo;19861987	/// Create multiple tokens.1988	///1989	/// * `sender` - The user who mint the token and pays for the transaction.1990	/// * `to` - The user who will own the token.1991	/// * `data` - Token data.1992	/// * `nesting_budget` - A budget that can be spent on nesting tokens.1993	fn create_multiple_items(1994		&self,1995		sender: T::CrossAccountId,1996		to: T::CrossAccountId,1997		data: Vec<CreateItemData>,1998		nesting_budget: &dyn Budget,1999	) -> DispatchResultWithPostInfo;20002001	/// Create multiple tokens.2002	///2003	/// * `sender` - The user who mint the token and pays for the transaction.2004	/// * `to` - The user who will own the token.2005	/// * `data` - Token data.2006	/// * `nesting_budget` - A budget that can be spent on nesting tokens.2007	fn create_multiple_items_ex(2008		&self,2009		sender: T::CrossAccountId,2010		data: CreateItemExData<T::CrossAccountId>,2011		nesting_budget: &dyn Budget,2012	) -> DispatchResultWithPostInfo;20132014	/// Burn token.2015	///2016	/// * `sender` - The user who owns the token.2017	/// * `token` - Token id that will burned.2018	/// * `amount` - The number of parts of the token that will be burned.2019	fn burn_item(2020		&self,2021		sender: T::CrossAccountId,2022		token: TokenId,2023		amount: u128,2024	) -> DispatchResultWithPostInfo;20252026	/// Burn token and all nested tokens recursievly.2027	///2028	/// * `sender` - The user who owns the token.2029	/// * `token` - Token id that will burned.2030	/// * `self_budget` - The budget that can be spent on burning tokens.2031	/// * `breadth_budget` - The budget that can be spent on burning nested tokens.2032	fn burn_item_recursively(2033		&self,2034		sender: T::CrossAccountId,2035		token: TokenId,2036		self_budget: &dyn Budget,2037		breadth_budget: &dyn Budget,2038	) -> DispatchResultWithPostInfo;20392040	/// Set collection properties.2041	///2042	/// * `sender` - Must be either the owner of the collection or its admin.2043	/// * `properties` - Properties to be set.2044	fn set_collection_properties(2045		&self,2046		sender: T::CrossAccountId,2047		properties: Vec<Property>,2048	) -> DispatchResultWithPostInfo;20492050	/// Delete collection properties.2051	///2052	/// * `sender` - Must be either the owner of the collection or its admin.2053	/// * `properties` - The properties to be removed.2054	fn delete_collection_properties(2055		&self,2056		sender: &T::CrossAccountId,2057		property_keys: Vec<PropertyKey>,2058	) -> DispatchResultWithPostInfo;20592060	/// Set token properties.2061	///2062	/// The appropriate [`PropertyPermission`] for the token property2063	/// must be set with [`Self::set_token_property_permissions`].2064	///2065	/// * `sender` - Must be either the owner of the token or its admin.2066	/// * `token_id` - The token for which the properties are being set.2067	/// * `properties` - Properties to be set.2068	/// * `budget` - Budget for setting properties.2069	fn set_token_properties(2070		&self,2071		sender: T::CrossAccountId,2072		token_id: TokenId,2073		properties: Vec<Property>,2074		budget: &dyn Budget,2075	) -> DispatchResultWithPostInfo;20762077	/// Remove token properties.2078	///2079	/// The appropriate [`PropertyPermission`] for the token property2080	/// must be set with [`Self::set_token_property_permissions`].2081	///2082	/// * `sender` - Must be either the owner of the token or its admin.2083	/// * `token_id` - The token for which the properties are being remove.2084	/// * `property_keys` - Keys to remove corresponding properties.2085	/// * `budget` - Budget for removing properties.2086	fn delete_token_properties(2087		&self,2088		sender: T::CrossAccountId,2089		token_id: TokenId,2090		property_keys: Vec<PropertyKey>,2091		budget: &dyn Budget,2092	) -> DispatchResultWithPostInfo;20932094	/// Set token property permissions.2095	///2096	/// * `sender` - Must be either the owner of the token or its admin.2097	/// * `token_id` - The token for which the properties are being set.2098	/// * `property_permissions` - Property permissions to be set.2099	/// * `budget` - Budget for setting properties.2100	fn set_token_property_permissions(2101		&self,2102		sender: &T::CrossAccountId,2103		property_permissions: Vec<PropertyKeyPermission>,2104	) -> DispatchResultWithPostInfo;21052106	/// Transfer amount of token pieces.2107	///2108	/// * `sender` - Donor user.2109	/// * `to` - Recepient user.2110	/// * `token` - The token of which parts are being sent.2111	/// * `amount` - The number of parts of the token that will be transferred.2112	/// * `budget` - The maximum budget that can be spent on the transfer.2113	fn transfer(2114		&self,2115		sender: T::CrossAccountId,2116		to: T::CrossAccountId,2117		token: TokenId,2118		amount: u128,2119		budget: &dyn Budget,2120	) -> DispatchResultWithPostInfo;21212122	/// Grant access to another account to transfer parts of the token owned by the calling user via [Self::transfer_from].2123	///2124	/// * `sender` - The user who grants access to the token.2125	/// * `spender` - The user to whom the rights are granted.2126	/// * `token` - The token to which access is granted.2127	/// * `amount` - The amount of pieces that another user can dispose of.2128	fn approve(2129		&self,2130		sender: T::CrossAccountId,2131		spender: T::CrossAccountId,2132		token: TokenId,2133		amount: u128,2134	) -> DispatchResultWithPostInfo;21352136	/// Grant access to another account to transfer parts of the token owned by the calling user's eth mirror via [Self::transfer_from].2137	///2138	/// * `sender` - The user who grants access to the token.2139	/// * `from` - Spender's eth mirror.2140	/// * `to` - The user to whom the rights are granted.2141	/// * `token` - The token to which access is granted.2142	/// * `amount` - The amount of pieces that another user can dispose of.2143	fn approve_from(2144		&self,2145		sender: T::CrossAccountId,2146		from: T::CrossAccountId,2147		to: T::CrossAccountId,2148		token: TokenId,2149		amount: u128,2150	) -> DispatchResultWithPostInfo;21512152	/// Send parts of a token owned by another user.2153	///2154	/// Before calling this method, you must grant rights to the calling user via [`Self::approve`].2155	///2156	/// * `sender` - The user who must have access to the token (see [`Self::approve`]).2157	/// * `from` - The user who owns the token.2158	/// * `to` - Recepient user.2159	/// * `token` - The token of which parts are being sent.2160	/// * `amount` - The number of parts of the token that will be transferred.2161	/// * `budget` - The maximum budget that can be spent on the transfer.2162	fn transfer_from(2163		&self,2164		sender: T::CrossAccountId,2165		from: T::CrossAccountId,2166		to: T::CrossAccountId,2167		token: TokenId,2168		amount: u128,2169		budget: &dyn Budget,2170	) -> DispatchResultWithPostInfo;21712172	/// Burn parts of a token owned by another user.2173	///2174	/// Before calling this method, you must grant rights to the calling user via [`Self::approve`].2175	///2176	/// * `sender` - The user who must have access to the token (see [`Self::approve`]).2177	/// * `from` - The user who owns the token.2178	/// * `token` - The token of which parts are being sent.2179	/// * `amount` - The number of parts of the token that will be transferred.2180	/// * `budget` - The maximum budget that can be spent on the burn.2181	fn burn_from(2182		&self,2183		sender: T::CrossAccountId,2184		from: T::CrossAccountId,2185		token: TokenId,2186		amount: u128,2187		budget: &dyn Budget,2188	) -> DispatchResultWithPostInfo;21892190	/// Check permission to nest token.2191	///2192	/// * `sender` - The user who initiated the check.2193	/// * `from` - The token that is checked for embedding.2194	/// * `under` - Token under which to check.2195	/// * `budget` - The maximum budget that can be spent on the check.2196	fn check_nesting(2197		&self,2198		sender: T::CrossAccountId,2199		from: (CollectionId, TokenId),2200		under: TokenId,2201		budget: &dyn Budget,2202	) -> DispatchResult;22032204	/// Nest one token into another.2205	///2206	/// * `under` - Token holder.2207	/// * `to_nest` - Nested token.2208	fn nest(&self, under: TokenId, to_nest: (CollectionId, TokenId));22092210	/// Unnest token.2211	///2212	/// * `under` - Token holder.2213	/// * `to_nest` - Token to unnest.2214	fn unnest(&self, under: TokenId, to_nest: (CollectionId, TokenId));22152216	/// Get all user tokens.2217	///2218	/// * `account` - Account for which you need to get tokens.2219	fn account_tokens(&self, account: T::CrossAccountId) -> Vec<TokenId>;22202221	/// Get all the tokens in the collection.2222	fn collection_tokens(&self) -> Vec<TokenId>;22232224	/// Check if the token exists.2225	///2226	/// * `token` - Id token to check.2227	fn token_exists(&self, token: TokenId) -> bool;22282229	/// Get the id of the last minted token.2230	fn last_token_id(&self) -> TokenId;22312232	/// Get the owner of the token.2233	///2234	/// * `token` - The token for which you need to find out the owner.2235	fn token_owner(&self, token: TokenId) -> Result<T::CrossAccountId, TokenOwnerError>;22362237	/// Returns 10 tokens owners in no particular order.2238	///2239	/// * `token` - The token for which you need to find out the owners.2240	fn token_owners(&self, token: TokenId) -> Vec<T::CrossAccountId>;22412242	/// Get the value of the token property by key.2243	///2244	/// * `token` - Token with the property to get.2245	/// * `key` - Property name.2246	fn token_property(&self, token_id: TokenId, key: &PropertyKey) -> Option<PropertyValue>;22472248	/// Get a set of token properties by key vector.2249	///2250	/// * `token` - Token with the property to get.2251	/// * `keys` - Vector of property keys. If this parameter is [None](sp_std::result::Result),2252	/// then all properties are returned.2253	fn token_properties(&self, token: TokenId, keys: Option<Vec<PropertyKey>>) -> Vec<Property>;22542255	/// Amount of unique collection tokens2256	fn total_supply(&self) -> u32;22572258	/// Amount of different tokens account has.2259	///2260	/// * `account` - The account for which need to get the balance.2261	fn account_balance(&self, account: T::CrossAccountId) -> u32;22622263	/// Amount of specific token account have.2264	fn balance(&self, account: T::CrossAccountId, token: TokenId) -> u128;22652266	/// Amount of token pieces2267	fn total_pieces(&self, token: TokenId) -> Option<u128>;22682269	/// Get the number of parts of the token that a trusted user can manage.2270	///2271	/// * `sender` - Trusted user.2272	/// * `spender` - Owner of the token.2273	/// * `token` - The token for which to get the value.2274	fn allowance(2275		&self,2276		sender: T::CrossAccountId,2277		spender: T::CrossAccountId,2278		token: TokenId,2279	) -> u128;22802281	/// Get extension for RFT collection.2282	fn refungible_extensions(&self) -> Option<&dyn RefungibleExtensions<T>>;22832284	/// The `operator` is allowed to transfer all tokens of the `owner` on their behalf.2285	/// * `owner` - Token owner2286	/// * `operator` - Operator2287	/// * `approve` - Should operator status be granted or revoked?2288	fn set_allowance_for_all(2289		&self,2290		owner: T::CrossAccountId,2291		operator: T::CrossAccountId,2292		approve: bool,2293	) -> DispatchResultWithPostInfo;22942295	/// Tells whether the given `owner` approves the `operator`.2296	fn allowance_for_all(&self, owner: T::CrossAccountId, operator: T::CrossAccountId) -> bool;22972298	/// Repairs a possibly broken item.2299	fn repair_item(&self, token: TokenId) -> DispatchResultWithPostInfo;2300}23012302/// Extension for RFT collection.2303pub trait RefungibleExtensions<T>2304where2305	T: Config,2306{2307	/// Change the number of parts of the token.2308	///2309	/// When the value changes down, this function is equivalent to burning parts of the token.2310	///2311	/// * `sender` - The user calling the repartition operation. Must be the owner of the token.2312	/// * `token` - The token for which you want to change the number of parts.2313	/// * `amount` - The new value of the parts of the token.2314	fn repartition(2315		&self,2316		sender: &T::CrossAccountId,2317		token: TokenId,2318		amount: u128,2319	) -> DispatchResultWithPostInfo;2320}23212322/// Merge [`DispatchResult`] with [`Weight`] into [`DispatchResultWithPostInfo`].2323///2324/// Used for [`CommonCollectionOperations`] implementations and flexible enough to do so.2325pub fn with_weight(res: DispatchResult, weight: Weight) -> DispatchResultWithPostInfo {2326	let post_info = PostDispatchInfo {2327		actual_weight: Some(weight),2328		pays_fee: Pays::Yes,2329	};2330	match res {2331		Ok(()) => Ok(post_info),2332		Err(error) => Err(DispatchErrorWithPostInfo { post_info, error }),2333	}2334}23352336impl<T: Config> From<PropertiesError> for Error<T> {2337	fn from(error: PropertiesError) -> Self {2338		match error {2339			PropertiesError::NoSpaceForProperty => Self::NoSpaceForProperty,2340			PropertiesError::PropertyLimitReached => Self::PropertyLimitReached,2341			PropertiesError::InvalidCharacterInPropertyKey => Self::InvalidCharacterInPropertyKey,2342			PropertiesError::PropertyKeyIsTooLong => Self::PropertyKeyIsTooLong,2343			PropertiesError::EmptyPropertyKey => Self::EmptyPropertyKey,2344		}2345	}2346}
after · pallets/common/src/lib.rs
1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617//! # Common pallet18//!19//! The Common pallet provides functionality for handling collections.20//!21//! ## Overview22//!23//! The Common pallet provides an interface for common collection operations for different collection types24//! (see [CommonCollectionOperations]), as well as a generic dispatcher for these, see [dispatch] module.25//! It also provides this functionality to EVM, see [erc] and [eth] modules.26//!27//! The Common pallet provides functions for:28//!29//! - Setting and approving collection sponsor.30//! - Get\set\delete allow list.31//! - Get\set\delete collection properties.32//! - Get\set\delete collection property permissions.33//! - Get\set\delete token property permissions.34//! - Get\set\delete collection administrators.35//! - Checking access permissions.36//!37//! ### Terminology38//! **Collection sponsor** - For the collection, you can set a sponsor, at whose expense it will39//! be possible to mint tokens.40//!41//! **Allow list** - List of users who have the right to minting tokens.42//!43//! **Collection properties** - Collection properties are simply key-value stores where various44//! metadata can be placed.45//!46//! **Permissions on token properties** - For each property in the token can be set permission47//! to change, see [`PropertyPermission`].48//!49//! **Collection administrator** - For a collection, you can set administrators who have the right50//! to most actions on the collection.5152#![warn(missing_docs)]53#![cfg_attr(not(feature = "std"), no_std)]54extern crate alloc;5556use core::{57	ops::{Deref, DerefMut},58	slice::from_ref,59};60use pallet_evm_coder_substrate::{SubstrateRecorder, WithRecorder};61use sp_std::vec::Vec;62use pallet_evm::{account::CrossAccountId, Pallet as PalletEvm};63use evm_coder::ToLog;64use frame_support::{65	dispatch::{DispatchErrorWithPostInfo, DispatchResultWithPostInfo, Weight, PostDispatchInfo},66	ensure,67	traits::{Imbalance, Get, Currency, WithdrawReasons, ExistenceRequirement},68	dispatch::Pays,69	transactional, fail,70};71use pallet_evm::GasWeightMapping;72use up_data_structs::{73	AccessMode, COLLECTION_NUMBER_LIMIT, Collection, RpcCollection, CollectionFlags,74	RpcCollectionFlags, CollectionId, CreateItemData, MAX_TOKEN_PREFIX_LENGTH,75	COLLECTION_ADMINS_LIMIT, TokenId, TokenChild, CollectionStats, MAX_TOKEN_OWNERSHIP,76	CollectionMode, NFT_SPONSOR_TRANSFER_TIMEOUT, FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,77	REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT, MAX_SPONSOR_TIMEOUT, CUSTOM_DATA_LIMIT, CollectionLimits,78	CreateCollectionData, SponsorshipState, CreateItemExData, SponsoringRateLimit, budget::Budget,79	PhantomType, Property, CollectionProperties as CollectionPropertiesT, TokenProperties,80	PropertiesPermissionMap, PropertyKey, PropertyValue, PropertyPermission, PropertiesError,81	TokenOwnerError, PropertyKeyPermission, TokenData, TrySetProperty, PropertyScope,82	CollectionPermissions,83};84use up_pov_estimate_rpc::PovInfo;8586pub use pallet::*;87use sp_core::H160;88use sp_runtime::{ArithmeticError, DispatchError, DispatchResult};8990#[cfg(feature = "runtime-benchmarks")]91pub mod benchmarking;92pub mod dispatch;93pub mod erc;94pub mod eth;95pub mod helpers;96#[allow(missing_docs)]97pub mod weights;98/// Weight info.99pub type SelfWeightOf<T> = <T as Config>::WeightInfo;100101/// Collection handle contains information about collection data and id.102/// Also provides functionality to count consumed gas.103///104/// CollectionHandle is used as a generic wrapper for collections of all types.105/// It allows to perform common operations and queries on any collection type,106/// both completely general for all, as well as their respective implementations of [`CommonCollectionOperations`].107#[must_use = "Should call submit_logs or save, otherwise some data will be lost for evm side"]108pub struct CollectionHandle<T: Config> {109	/// Collection id110	pub id: CollectionId,111	collection: Collection<T::AccountId>,112	/// Substrate recorder for counting consumed gas113	pub recorder: SubstrateRecorder<T>,114}115116impl<T: Config> WithRecorder<T> for CollectionHandle<T> {117	fn recorder(&self) -> &SubstrateRecorder<T> {118		&self.recorder119	}120	fn into_recorder(self) -> SubstrateRecorder<T> {121		self.recorder122	}123}124125impl<T: Config> CollectionHandle<T> {126	/// Same as [CollectionHandle::new] but with an explicit gas limit.127	pub fn new_with_gas_limit(id: CollectionId, gas_limit: u64) -> Option<Self> {128		Self::new_with_recorder(id, SubstrateRecorder::new(gas_limit))129	}130131	/// Same as [CollectionHandle::new] but with an existed [`SubstrateRecorder`].132	pub fn new_with_recorder(id: CollectionId, recorder: SubstrateRecorder<T>) -> Option<Self> {133		<CollectionById<T>>::get(id).map(|collection| Self {134			id,135			collection,136			recorder,137		})138	}139140	/// Retrives collection data from storage and creates collection handle with default parameters.141	/// If collection not found return `None`142	pub fn new(id: CollectionId) -> Option<Self> {143		Self::new_with_gas_limit(id, u64::MAX)144	}145146	/// Same as [`CollectionHandle::new`] but if collection not found [CollectionNotFound](Error::CollectionNotFound) returned.147	pub fn try_get(id: CollectionId) -> Result<Self, DispatchError> {148		Ok(Self::new(id).ok_or(<Error<T>>::CollectionNotFound)?)149	}150151	/// Consume gas for reading.152	pub fn consume_store_reads(153		&self,154		reads: u64,155	) -> pallet_evm_coder_substrate::execution::Result<()> {156		self.recorder157			.consume_gas(T::GasWeightMapping::weight_to_gas(Weight::from_parts(158				<T as frame_system::Config>::DbWeight::get()159					.read160					.saturating_mul(reads),161				// TODO: measure proof162				0,163			)))164	}165166	/// Consume gas for writing.167	pub fn consume_store_writes(168		&self,169		writes: u64,170	) -> pallet_evm_coder_substrate::execution::Result<()> {171		self.recorder172			.consume_gas(T::GasWeightMapping::weight_to_gas(Weight::from_parts(173				<T as frame_system::Config>::DbWeight::get()174					.write175					.saturating_mul(writes),176				// TODO: measure proof177				0,178			)))179	}180181	/// Consume gas for reading and writing.182	pub fn consume_store_reads_and_writes(183		&self,184		reads: u64,185		writes: u64,186	) -> pallet_evm_coder_substrate::execution::Result<()> {187		let weight = <T as frame_system::Config>::DbWeight::get();188		let reads = weight.read.saturating_mul(reads);189		let writes = weight.read.saturating_mul(writes);190		self.recorder191			.consume_gas(T::GasWeightMapping::weight_to_gas(Weight::from_parts(192				reads.saturating_add(writes),193				// TODO: measure proof194				0,195			)))196	}197198	/// Save collection to storage.199	pub fn save(&self) -> DispatchResult {200		<CollectionById<T>>::insert(self.id, &self.collection);201		Ok(())202	}203204	/// Set collection sponsor.205	///206	/// Unique collections allows sponsoring for certain actions.207	/// This method allows you to set the sponsor of the collection.208	/// In order for sponsorship to become active, it must be confirmed through [`Self::confirm_sponsorship`].209	pub fn set_sponsor(210		&mut self,211		sender: &T::CrossAccountId,212		sponsor: T::AccountId,213	) -> DispatchResult {214		self.check_is_internal()?;215		self.check_is_owner_or_admin(sender)?;216217		self.collection.sponsorship = SponsorshipState::Unconfirmed(sponsor.clone());218219		<Pallet<T>>::deposit_event(Event::<T>::CollectionSponsorSet(self.id, sponsor));220		<PalletEvm<T>>::deposit_log(221			erc::CollectionHelpersEvents::CollectionChanged {222				collection_id: eth::collection_id_to_address(self.id),223			}224			.to_log(T::ContractAddress::get()),225		);226227		self.save()228	}229230	/// Force set `sponsor`.231	///232	/// Differs from [`set_sponsor`][`Self::set_sponsor`] in that confirmation233	/// from the `sponsor` is not required.234	///235	/// # Arguments236	///237	/// * `sender`: Caller's account.238	/// * `sponsor`: ID of the account of the sponsor-to-be.239	pub fn force_set_sponsor(&mut self, sponsor: T::AccountId) -> DispatchResult {240		self.check_is_internal()?;241242		self.collection.sponsorship = SponsorshipState::Confirmed(sponsor.clone());243244		<Pallet<T>>::deposit_event(Event::<T>::CollectionSponsorSet(self.id, sponsor.clone()));245		<Pallet<T>>::deposit_event(Event::<T>::SponsorshipConfirmed(self.id, sponsor));246		<PalletEvm<T>>::deposit_log(247			erc::CollectionHelpersEvents::CollectionChanged {248				collection_id: eth::collection_id_to_address(self.id),249			}250			.to_log(T::ContractAddress::get()),251		);252253		self.save()254	}255256	/// Confirm sponsorship257	///258	/// In order for the sponsorship to become active, the user set as the sponsor must confirm their participation.259	/// Before confirming sponsorship, the user must be specified as the sponsor of the collection via [`Self::set_sponsor`].260	pub fn confirm_sponsorship(&mut self, sender: &T::AccountId) -> DispatchResult {261		self.check_is_internal()?;262		ensure!(263			self.collection.sponsorship.pending_sponsor() == Some(sender),264			Error::<T>::ConfirmSponsorshipFail265		);266267		self.collection.sponsorship = SponsorshipState::Confirmed(sender.clone());268269		<Pallet<T>>::deposit_event(Event::<T>::SponsorshipConfirmed(self.id, sender.clone()));270		<PalletEvm<T>>::deposit_log(271			erc::CollectionHelpersEvents::CollectionChanged {272				collection_id: eth::collection_id_to_address(self.id),273			}274			.to_log(T::ContractAddress::get()),275		);276277		self.save()278	}279280	/// Remove collection sponsor.281	pub fn remove_sponsor(&mut self, sender: &T::CrossAccountId) -> DispatchResult {282		self.check_is_internal()?;283		self.check_is_owner_or_admin(sender)?;284285		self.collection.sponsorship = SponsorshipState::Disabled;286287		<Pallet<T>>::deposit_event(Event::<T>::CollectionSponsorRemoved(self.id));288		<PalletEvm<T>>::deposit_log(289			erc::CollectionHelpersEvents::CollectionChanged {290				collection_id: eth::collection_id_to_address(self.id),291			}292			.to_log(T::ContractAddress::get()),293		);294		self.save()295	}296297	/// Force remove `sponsor`.298	///299	/// Differs from `remove_sponsor` in that300	/// it doesn't require consent from the `owner` of the collection.301	pub fn force_remove_sponsor(&mut self) -> DispatchResult {302		self.check_is_internal()?;303304		self.collection.sponsorship = SponsorshipState::Disabled;305306		<Pallet<T>>::deposit_event(Event::<T>::CollectionSponsorRemoved(self.id));307		<PalletEvm<T>>::deposit_log(308			erc::CollectionHelpersEvents::CollectionChanged {309				collection_id: eth::collection_id_to_address(self.id),310			}311			.to_log(T::ContractAddress::get()),312		);313		self.save()314	}315316	/// Checks that the collection was created with, and must be operated upon through **Unique API**.317	/// Now check only the `external` flag and if it's **true**, then return [`Error::CollectionIsExternal`] error.318	pub fn check_is_internal(&self) -> DispatchResult {319		if self.flags.external {320			return Err(<Error<T>>::CollectionIsExternal)?;321		}322323		Ok(())324	}325326	/// Checks that the collection was created with, and must be operated upon through an **assimilated API**.327	/// Now check only the `external` flag and if it's **false**, then return [`Error::CollectionIsInternal`] error.328	pub fn check_is_external(&self) -> DispatchResult {329		if !self.flags.external {330			return Err(<Error<T>>::CollectionIsInternal)?;331		}332333		Ok(())334	}335}336337impl<T: Config> Deref for CollectionHandle<T> {338	type Target = Collection<T::AccountId>;339340	fn deref(&self) -> &Self::Target {341		&self.collection342	}343}344345impl<T: Config> DerefMut for CollectionHandle<T> {346	fn deref_mut(&mut self) -> &mut Self::Target {347		&mut self.collection348	}349}350351impl<T: Config> CollectionHandle<T> {352	/// Checks if the `user` is the owner of the collection.353	pub fn check_is_owner(&self, user: &T::CrossAccountId) -> DispatchResult {354		ensure!(*user.as_sub() == self.owner, <Error<T>>::NoPermission);355		Ok(())356	}357358	/// Returns **true** if the `user` is the owner or administrator of the collection.359	pub fn is_owner_or_admin(&self, user: &T::CrossAccountId) -> bool {360		*user.as_sub() == self.owner || <IsAdmin<T>>::get((self.id, user))361	}362363	/// Checks if the `user` is the owner or administrator of the collection.364	pub fn check_is_owner_or_admin(&self, user: &T::CrossAccountId) -> DispatchResult {365		ensure!(self.is_owner_or_admin(user), <Error<T>>::NoPermission);366		Ok(())367	}368369	/// Returns **true** if370	/// * the `user`is a collection owner or admin371	/// * the collection limits allow the owner/admins to transfer/burn any collection token372	pub fn ignores_token_restrictions(&self, user: &T::CrossAccountId) -> bool {373		self.limits.owner_can_transfer() && self.is_owner_or_admin(user)374	}375376	/// Return **true** if `user` does not have enough token parts, and he can ignore such restrictions.377	pub fn ignores_owned_amount(&self, user: &T::CrossAccountId) -> bool {378		self.limits.owner_can_transfer() && self.is_owner_or_admin(user)379	}380381	/// Checks if the user is in the allow list. If not [Error::AddressNotInAllowlist] returns.382	pub fn check_allowlist(&self, user: &T::CrossAccountId) -> DispatchResult {383		ensure!(384			<Allowlist<T>>::get((self.id, user)),385			<Error<T>>::AddressNotInAllowlist386		);387		Ok(())388	}389390	/// Changes collection owner to another account391	/// #### Store read/writes392	/// 1 writes393	pub fn change_owner(394		&mut self,395		caller: T::CrossAccountId,396		new_owner: T::CrossAccountId,397	) -> DispatchResult {398		self.check_is_internal()?;399		self.check_is_owner(&caller)?;400		self.collection.owner = new_owner.as_sub().clone();401402		<Pallet<T>>::deposit_event(Event::<T>::CollectionOwnerChanged(403			self.id,404			new_owner.as_sub().clone(),405		));406		<PalletEvm<T>>::deposit_log(407			erc::CollectionHelpersEvents::CollectionChanged {408				collection_id: eth::collection_id_to_address(self.id),409			}410			.to_log(T::ContractAddress::get()),411		);412413		self.save()414	}415}416417#[frame_support::pallet]418pub mod pallet {419420	use super::*;421	use dispatch::CollectionDispatch;422	use frame_support::{Blake2_128Concat, pallet_prelude::*, storage::Key, traits::StorageVersion};423	use frame_support::traits::Currency;424	use up_data_structs::{TokenId, mapping::TokenAddressMapping};425	use scale_info::TypeInfo;426	use weights::WeightInfo;427428	#[pallet::config]429	pub trait Config:430		frame_system::Config + pallet_evm_coder_substrate::Config + pallet_evm::Config + TypeInfo431	{432		/// Weight information for functions of this pallet.433		type WeightInfo: WeightInfo;434435		/// Events compatible with [`frame_system::Config::Event`].436		type RuntimeEvent: IsType<<Self as frame_system::Config>::RuntimeEvent> + From<Event<Self>>;437438		/// Handler of accounts and payment.439		type Currency: Currency<Self::AccountId>;440441		/// Set price to create a collection.442		#[pallet::constant]443		type CollectionCreationPrice: Get<444			<<Self as Config>::Currency as Currency<Self::AccountId>>::Balance,445		>;446447		/// Dispatcher of operations on collections.448		type CollectionDispatch: CollectionDispatch<Self>;449450		/// Account which holds the chain's treasury.451		type TreasuryAccountId: Get<Self::AccountId>;452453		/// Address under which the CollectionHelper contract would be available.454		#[pallet::constant]455		type ContractAddress: Get<H160>;456457		/// Mapper for token addresses to Ethereum addresses.458		type EvmTokenAddressMapping: TokenAddressMapping<H160>;459460		/// Mapper for token addresses to [`CrossAccountId`].461		type CrossTokenAddressMapping: TokenAddressMapping<Self::CrossAccountId>;462	}463464	const STORAGE_VERSION: StorageVersion = StorageVersion::new(1);465	/// Collection id for native fungible collction.466	pub const NATIVE_FINGIBLE_COLLECTION_ID: CollectionId = CollectionId(0);467468	#[pallet::pallet]469	#[pallet::storage_version(STORAGE_VERSION)]470	pub struct Pallet<T>(_);471472	#[pallet::extra_constants]473	impl<T: Config> Pallet<T> {474		/// Maximum admins per collection.475		pub fn collection_admins_limit() -> u32 {476			COLLECTION_ADMINS_LIMIT477		}478	}479480	#[pallet::genesis_config]481	pub struct GenesisConfig<T>(PhantomData<T>);482483	#[cfg(feature = "std")]484	impl<T: Config> Default for GenesisConfig<T> {485		fn default() -> Self {486			Self(Default::default())487		}488	}489490	#[pallet::genesis_build]491	impl<T: Config> GenesisBuild<T> for GenesisConfig<T> {492		fn build(&self) {493			StorageVersion::new(1).put::<Pallet<T>>();494		}495	}496497	impl<T: Config> Pallet<T> {498		/// Helper function that handles deposit events499		pub fn deposit_event(event: Event<T>) {500			let event = <T as Config>::RuntimeEvent::from(event);501			let event = event.into();502			<frame_system::Pallet<T>>::deposit_event(event)503		}504	}505506	#[pallet::event]507	pub enum Event<T: Config> {508		/// New collection was created509		CollectionCreated(510			/// Globally unique identifier of newly created collection.511			CollectionId,512			/// [`CollectionMode`] converted into _u8_.513			u8,514			/// Collection owner.515			T::AccountId,516		),517518		/// New collection was destroyed519		CollectionDestroyed(520			/// Globally unique identifier of collection.521			CollectionId,522		),523524		/// New item was created.525		ItemCreated(526			/// Id of the collection where item was created.527			CollectionId,528			/// Id of an item. Unique within the collection.529			TokenId,530			/// Owner of newly created item531			T::CrossAccountId,532			/// Always 1 for NFT533			u128,534		),535536		/// Collection item was burned.537		ItemDestroyed(538			/// Id of the collection where item was destroyed.539			CollectionId,540			/// Identifier of burned NFT.541			TokenId,542			/// Which user has destroyed its tokens.543			T::CrossAccountId,544			/// Amount of token pieces destroed. Always 1 for NFT.545			u128,546		),547548		/// Item was transferred549		Transfer(550			/// Id of collection to which item is belong.551			CollectionId,552			/// Id of an item.553			TokenId,554			/// Original owner of item.555			T::CrossAccountId,556			/// New owner of item.557			T::CrossAccountId,558			/// Amount of token pieces transfered. Always 1 for NFT.559			u128,560		),561562		/// Amount pieces of token owned by `sender` was approved for `spender`.563		Approved(564			/// Id of collection to which item is belong.565			CollectionId,566			/// Id of an item.567			TokenId,568			/// Original owner of item.569			T::CrossAccountId,570			/// Id for which the approval was granted.571			T::CrossAccountId,572			/// Amount of token pieces transfered. Always 1 for NFT.573			u128,574		),575576		/// A `sender` approves operations on all owned tokens for `spender`.577		ApprovedForAll(578			/// Id of collection to which item is belong.579			CollectionId,580			/// Owner of a wallet.581			T::CrossAccountId,582			/// Id for which operator status was granted or rewoked.583			T::CrossAccountId,584			/// Is operator status granted or revoked?585			bool,586		),587588		/// The colletion property has been added or edited.589		CollectionPropertySet(590			/// Id of collection to which property has been set.591			CollectionId,592			/// The property that was set.593			PropertyKey,594		),595596		/// The property has been deleted.597		CollectionPropertyDeleted(598			/// Id of collection to which property has been deleted.599			CollectionId,600			/// The property that was deleted.601			PropertyKey,602		),603604		/// The token property has been added or edited.605		TokenPropertySet(606			/// Identifier of the collection whose token has the property set.607			CollectionId,608			/// The token for which the property was set.609			TokenId,610			/// The property that was set.611			PropertyKey,612		),613614		/// The token property has been deleted.615		TokenPropertyDeleted(616			/// Identifier of the collection whose token has the property deleted.617			CollectionId,618			/// The token for which the property was deleted.619			TokenId,620			/// The property that was deleted.621			PropertyKey,622		),623624		/// The token property permission of a collection has been set.625		PropertyPermissionSet(626			/// ID of collection to which property permission has been set.627			CollectionId,628			/// The property permission that was set.629			PropertyKey,630		),631632		/// Address was added to the allow list.633		AllowListAddressAdded(634			/// ID of the affected collection.635			CollectionId,636			/// Address of the added account.637			T::CrossAccountId,638		),639640		/// Address was removed from the allow list.641		AllowListAddressRemoved(642			/// ID of the affected collection.643			CollectionId,644			/// Address of the removed account.645			T::CrossAccountId,646		),647648		/// Collection admin was added.649		CollectionAdminAdded(650			/// ID of the affected collection.651			CollectionId,652			/// Admin address.653			T::CrossAccountId,654		),655656		/// Collection admin was removed.657		CollectionAdminRemoved(658			/// ID of the affected collection.659			CollectionId,660			/// Removed admin address.661			T::CrossAccountId,662		),663664		/// Collection limits were set.665		CollectionLimitSet(666			/// ID of the affected collection.667			CollectionId,668		),669670		/// Collection owned was changed.671		CollectionOwnerChanged(672			/// ID of the affected collection.673			CollectionId,674			/// New owner address.675			T::AccountId,676		),677678		/// Collection permissions were set.679		CollectionPermissionSet(680			/// ID of the affected collection.681			CollectionId,682		),683684		/// Collection sponsor was set.685		CollectionSponsorSet(686			/// ID of the affected collection.687			CollectionId,688			/// New sponsor address.689			T::AccountId,690		),691692		/// New sponsor was confirm.693		SponsorshipConfirmed(694			/// ID of the affected collection.695			CollectionId,696			/// New sponsor address.697			T::AccountId,698		),699700		/// Collection sponsor was removed.701		CollectionSponsorRemoved(702			/// ID of the affected collection.703			CollectionId,704		),705	}706707	#[pallet::error]708	pub enum Error<T> {709		/// This collection does not exist.710		CollectionNotFound,711		/// Sender parameter and item owner must be equal.712		MustBeTokenOwner,713		/// No permission to perform action714		NoPermission,715		/// Destroying only empty collections is allowed716		CantDestroyNotEmptyCollection,717		/// Collection is not in mint mode.718		PublicMintingNotAllowed,719		/// Address is not in allow list.720		AddressNotInAllowlist,721722		/// Collection name can not be longer than 63 char.723		CollectionNameLimitExceeded,724		/// Collection description can not be longer than 255 char.725		CollectionDescriptionLimitExceeded,726		/// Token prefix can not be longer than 15 char.727		CollectionTokenPrefixLimitExceeded,728		/// Total collections bound exceeded.729		TotalCollectionsLimitExceeded,730		/// Exceeded max admin count731		CollectionAdminCountExceeded,732		/// Collection limit bounds per collection exceeded733		CollectionLimitBoundsExceeded,734		/// Tried to enable permissions which are only permitted to be disabled735		OwnerPermissionsCantBeReverted,736		/// Collection settings not allowing items transferring737		TransferNotAllowed,738		/// Account token limit exceeded per collection739		AccountTokenLimitExceeded,740		/// Collection token limit exceeded741		CollectionTokenLimitExceeded,742		/// Metadata flag frozen743		MetadataFlagFrozen,744745		/// Item does not exist746		TokenNotFound,747		/// Item is balance not enough748		TokenValueTooLow,749		/// Requested value is more than the approved750		ApprovedValueTooLow,751		/// Tried to approve more than owned752		CantApproveMoreThanOwned,753		/// Only spending from eth mirror could be approved754		AddressIsNotEthMirror,755756		/// Can't transfer tokens to ethereum zero address757		AddressIsZero,758759		/// The operation is not supported760		UnsupportedOperation,761762		/// Insufficient funds to perform an action763		NotSufficientFounds,764765		/// User does not satisfy the nesting rule766		UserIsNotAllowedToNest,767		/// Only tokens from specific collections may nest tokens under this one768		SourceCollectionIsNotAllowedToNest,769770		/// Tried to store more data than allowed in collection field771		CollectionFieldSizeExceeded,772773		/// Tried to store more property data than allowed774		NoSpaceForProperty,775776		/// Tried to store more property keys than allowed777		PropertyLimitReached,778779		/// Property key is too long780		PropertyKeyIsTooLong,781782		/// Only ASCII letters, digits, and symbols `_`, `-`, and `.` are allowed783		InvalidCharacterInPropertyKey,784785		/// Empty property keys are forbidden786		EmptyPropertyKey,787788		/// Tried to access an external collection with an internal API789		CollectionIsExternal,790791		/// Tried to access an internal collection with an external API792		CollectionIsInternal,793794		/// This address is not set as sponsor, use setCollectionSponsor first.795		ConfirmSponsorshipFail,796797		/// The user is not an administrator.798		UserIsNotCollectionAdmin,799	}800801	/// Storage of the count of created collections. Essentially contains the last collection ID.802	#[pallet::storage]803	pub type CreatedCollectionCount<T> = StorageValue<Value = CollectionId, QueryKind = ValueQuery>;804805	/// Storage of the count of deleted collections.806	#[pallet::storage]807	pub type DestroyedCollectionCount<T> =808		StorageValue<Value = CollectionId, QueryKind = ValueQuery>;809810	/// Storage of collection info.811	#[pallet::storage]812	pub type CollectionById<T> = StorageMap<813		Hasher = Blake2_128Concat,814		Key = CollectionId,815		Value = Collection<<T as frame_system::Config>::AccountId>,816		QueryKind = OptionQuery,817	>;818819	/// Storage of collection properties.820	#[pallet::storage]821	#[pallet::getter(fn collection_properties)]822	pub type CollectionProperties<T> = StorageMap<823		Hasher = Blake2_128Concat,824		Key = CollectionId,825		Value = CollectionPropertiesT,826		QueryKind = ValueQuery,827	>;828829	/// Storage of token property permissions of a collection.830	#[pallet::storage]831	#[pallet::getter(fn property_permissions)]832	pub type CollectionPropertyPermissions<T> = StorageMap<833		Hasher = Blake2_128Concat,834		Key = CollectionId,835		Value = PropertiesPermissionMap,836		QueryKind = ValueQuery,837	>;838839	/// Storage of the amount of collection admins.840	#[pallet::storage]841	pub type AdminAmount<T> = StorageMap<842		Hasher = Blake2_128Concat,843		Key = CollectionId,844		Value = u32,845		QueryKind = ValueQuery,846	>;847848	/// List of collection admins.849	#[pallet::storage]850	pub type IsAdmin<T: Config> = StorageNMap<851		Key = (852			Key<Blake2_128Concat, CollectionId>,853			Key<Blake2_128Concat, T::CrossAccountId>,854		),855		Value = bool,856		QueryKind = ValueQuery,857	>;858859	/// Allowlisted collection users.860	#[pallet::storage]861	pub type Allowlist<T: Config> = StorageNMap<862		Key = (863			Key<Blake2_128Concat, CollectionId>,864			Key<Blake2_128Concat, T::CrossAccountId>,865		),866		Value = bool,867		QueryKind = ValueQuery,868	>;869870	/// Not used by code, exists only to provide some types to metadata.871	#[pallet::storage]872	pub type DummyStorageValue<T: Config> = StorageValue<873		Value = (874			CollectionStats,875			CollectionId,876			TokenId,877			TokenChild,878			PhantomType<(879				TokenData<T::CrossAccountId>,880				RpcCollection<T::AccountId>,881				// PoV Estimate Info882				PovInfo,883			)>,884		),885		QueryKind = OptionQuery,886	>;887}888889impl<T: Config> Pallet<T> {890	/// Enshure that receiver address is correct.891	///892	/// Ethereum receiver 0x0000000000000000000000000000000000000000 is reserved, and shouldn't own tokens.893	pub fn ensure_correct_receiver(receiver: &T::CrossAccountId) -> DispatchResult {894		ensure!(895			&T::CrossAccountId::from_eth(H160([0; 20])) != receiver,896			<Error<T>>::AddressIsZero897		);898		Ok(())899	}900901	/// Get a vector of collection admins.902	pub fn adminlist(collection: CollectionId) -> Vec<T::CrossAccountId> {903		<IsAdmin<T>>::iter_prefix((collection,))904			.map(|(a, _)| a)905			.collect()906	}907908	/// Get a vector of users allowed to mint tokens.909	pub fn allowlist(collection: CollectionId) -> Vec<T::CrossAccountId> {910		<Allowlist<T>>::iter_prefix((collection,))911			.map(|(a, _)| a)912			.collect()913	}914915	/// Is `user` allowed to mint token in `collection`.916	pub fn allowed(collection: CollectionId, user: T::CrossAccountId) -> bool {917		<Allowlist<T>>::get((collection, user))918	}919920	/// Get statistics of collections.921	pub fn collection_stats() -> CollectionStats {922		let created = <CreatedCollectionCount<T>>::get();923		let destroyed = <DestroyedCollectionCount<T>>::get();924		CollectionStats {925			created: created.0,926			destroyed: destroyed.0,927			alive: created.0 - destroyed.0,928		}929	}930931	/// Get the effective limits for the collection.932	pub fn effective_collection_limits(collection: CollectionId) -> Option<CollectionLimits> {933		let collection = <CollectionById<T>>::get(collection)?;934		let limits = collection.limits;935		let effective_limits = CollectionLimits {936			account_token_ownership_limit: Some(limits.account_token_ownership_limit()),937			sponsored_data_size: Some(limits.sponsored_data_size()),938			sponsored_data_rate_limit: Some(939				limits940					.sponsored_data_rate_limit941					.unwrap_or(SponsoringRateLimit::SponsoringDisabled),942			),943			token_limit: Some(limits.token_limit()),944			sponsor_transfer_timeout: Some(limits.sponsor_transfer_timeout(945				match collection.mode {946					CollectionMode::NFT => NFT_SPONSOR_TRANSFER_TIMEOUT,947					CollectionMode::Fungible(_) => FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,948					CollectionMode::ReFungible => REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,949				},950			)),951			sponsor_approve_timeout: Some(limits.sponsor_approve_timeout()),952			owner_can_transfer: Some(limits.owner_can_transfer()),953			owner_can_destroy: Some(limits.owner_can_destroy()),954			transfers_enabled: Some(limits.transfers_enabled()),955		};956957		Some(effective_limits)958	}959960	/// Returns information about the `collection` adapted for rpc.961	pub fn rpc_collection(collection: CollectionId) -> Option<RpcCollection<T::AccountId>> {962		let Collection {963			name,964			description,965			owner,966			mode,967			token_prefix,968			sponsorship,969			limits,970			permissions,971			flags,972		} = <CollectionById<T>>::get(collection)?;973974		let token_property_permissions = <CollectionPropertyPermissions<T>>::get(collection)975			.into_iter()976			.map(|(key, permission)| PropertyKeyPermission { key, permission })977			.collect();978979		let properties = <CollectionProperties<T>>::get(collection)980			.into_iter()981			.map(|(key, value)| Property { key, value })982			.collect();983984		let permissions = CollectionPermissions {985			access: Some(permissions.access()),986			mint_mode: Some(permissions.mint_mode()),987			nesting: Some(permissions.nesting().clone()),988		};989990		Some(RpcCollection {991			name: name.into_inner(),992			description: description.into_inner(),993			owner,994			mode,995			token_prefix: token_prefix.into_inner(),996			sponsorship,997			limits,998			permissions,999			token_property_permissions,1000			properties,1001			read_only: flags.external,10021003			flags: RpcCollectionFlags {1004				foreign: flags.foreign,1005				erc721metadata: flags.erc721metadata,1006			},1007		})1008	}1009}10101011macro_rules! limit_default {1012	($old:ident, $new:ident, $($field:ident $(($arg:expr))? => $check:expr),* $(,)?) => {{1013		$(1014			if let Some($new) = $new.$field {1015				let $old = $old.$field($($arg)?);1016				let _ = $new;1017				let _ = $old;1018				$check1019			} else {1020				$new.$field = $old.$field1021			}1022		)*1023	}};1024}1025macro_rules! limit_default_clone {1026	($old:ident, $new:ident, $($field:ident $(($arg:expr))? => $check:expr),* $(,)?) => {{1027		$(1028			if let Some($new) = $new.$field.clone() {1029				let $old = $old.$field($($arg)?);1030				let _ = $new;1031				let _ = $old;1032				$check1033			} else {1034				$new.$field = $old.$field.clone()1035			}1036		)*1037	}};1038}10391040impl<T: Config> Pallet<T> {1041	/// Create new collection.1042	///1043	/// * `owner` - The owner of the collection.1044	/// * `data` - Description of the created collection.1045	/// * `flags` - Extra flags to store.1046	pub fn init_collection(1047		owner: T::CrossAccountId,1048		payer: T::CrossAccountId,1049		data: CreateCollectionData<T::AccountId>,1050		flags: CollectionFlags,1051	) -> Result<CollectionId, DispatchError> {1052		{1053			ensure!(1054				data.token_prefix.len() <= MAX_TOKEN_PREFIX_LENGTH as usize,1055				Error::<T>::CollectionTokenPrefixLimitExceeded1056			);1057		}10581059		let created_count = <CreatedCollectionCount<T>>::get()1060			.01061			.checked_add(1)1062			.ok_or(ArithmeticError::Overflow)?;1063		let destroyed_count = <DestroyedCollectionCount<T>>::get().0;1064		let id = CollectionId(created_count);10651066		// bound Total number of collections1067		ensure!(1068			created_count - destroyed_count <= COLLECTION_NUMBER_LIMIT,1069			<Error<T>>::TotalCollectionsLimitExceeded1070		);10711072		// =========10731074		let collection = Collection {1075			owner: owner.as_sub().clone(),1076			name: data.name,1077			mode: data.mode.clone(),1078			description: data.description,1079			token_prefix: data.token_prefix,1080			sponsorship: data1081				.pending_sponsor1082				.map(SponsorshipState::Unconfirmed)1083				.unwrap_or_default(),1084			limits: data1085				.limits1086				.map(|limits| Self::clamp_limits(data.mode.clone(), &Default::default(), limits))1087				.unwrap_or_else(|| Ok(CollectionLimits::default()))?,1088			permissions: data1089				.permissions1090				.map(|permissions| {1091					Self::clamp_permissions(data.mode.clone(), &Default::default(), permissions)1092				})1093				.unwrap_or_else(|| Ok(CollectionPermissions::default()))?,1094			flags,1095		};10961097		let mut collection_properties = CollectionPropertiesT::new();1098		collection_properties1099			.try_set_from_iter(data.properties.into_iter())1100			.map_err(<Error<T>>::from)?;11011102		CollectionProperties::<T>::insert(id, collection_properties);11031104		let mut token_props_permissions = PropertiesPermissionMap::new();1105		token_props_permissions1106			.try_set_from_iter(data.token_property_permissions.into_iter())1107			.map_err(<Error<T>>::from)?;11081109		CollectionPropertyPermissions::<T>::insert(id, token_props_permissions);11101111		// Take a (non-refundable) deposit of collection creation1112		{1113			let mut imbalance =1114				<<<T as Config>::Currency as Currency<T::AccountId>>::PositiveImbalance>::zero();1115			imbalance.subsume(1116				<<T as Config>::Currency as Currency<T::AccountId>>::deposit_creating(1117					&T::TreasuryAccountId::get(),1118					T::CollectionCreationPrice::get(),1119				),1120			);1121			<T as Config>::Currency::settle(1122				payer.as_sub(),1123				imbalance,1124				WithdrawReasons::TRANSFER,1125				ExistenceRequirement::KeepAlive,1126			)1127			.map_err(|_| Error::<T>::NotSufficientFounds)?;1128		}11291130		<CreatedCollectionCount<T>>::put(created_count);1131		<Pallet<T>>::deposit_event(Event::CollectionCreated(1132			id,1133			data.mode.id(),1134			owner.as_sub().clone(),1135		));1136		<PalletEvm<T>>::deposit_log(1137			erc::CollectionHelpersEvents::CollectionCreated {1138				owner: *owner.as_eth(),1139				collection_id: eth::collection_id_to_address(id),1140			}1141			.to_log(T::ContractAddress::get()),1142		);1143		<CollectionById<T>>::insert(id, collection);1144		Ok(id)1145	}11461147	/// Destroy collection.1148	///1149	/// * `collection` - Collection handler.1150	/// * `sender` - The owner or administrator of the collection.1151	pub fn destroy_collection(1152		collection: CollectionHandle<T>,1153		sender: &T::CrossAccountId,1154	) -> DispatchResult {1155		ensure!(1156			collection.limits.owner_can_destroy(),1157			<Error<T>>::NoPermission,1158		);1159		collection.check_is_owner(sender)?;11601161		let destroyed_collections = <DestroyedCollectionCount<T>>::get()1162			.01163			.checked_add(1)1164			.ok_or(ArithmeticError::Overflow)?;11651166		// =========11671168		<DestroyedCollectionCount<T>>::put(destroyed_collections);1169		<CollectionById<T>>::remove(collection.id);1170		<AdminAmount<T>>::remove(collection.id);1171		let _ = <IsAdmin<T>>::clear_prefix((collection.id,), u32::MAX, None);1172		let _ = <Allowlist<T>>::clear_prefix((collection.id,), u32::MAX, None);1173		<CollectionProperties<T>>::remove(collection.id);11741175		<Pallet<T>>::deposit_event(Event::CollectionDestroyed(collection.id));11761177		<PalletEvm<T>>::deposit_log(1178			erc::CollectionHelpersEvents::CollectionDestroyed {1179				collection_id: eth::collection_id_to_address(collection.id),1180			}1181			.to_log(T::ContractAddress::get()),1182		);1183		Ok(())1184	}11851186	/// This function sets or removes a collection properties according to1187	/// `properties_updates` contents:1188	/// * sets a property under the <key> with the value provided `(<key>, Some(<value>))`1189	/// * removes a property under the <key> if the value is `None` `(<key>, None)`.1190	///1191	/// This function fires an event for each property change.1192	/// In case of an error, all the changes (including the events) will be reverted1193	/// since the function is transactional.1194	#[transactional]1195	fn modify_collection_properties(1196		collection: &CollectionHandle<T>,1197		sender: &T::CrossAccountId,1198		properties_updates: impl Iterator<Item = (PropertyKey, Option<PropertyValue>)>,1199	) -> DispatchResult {1200		collection.check_is_owner_or_admin(sender)?;12011202		let mut stored_properties = <CollectionProperties<T>>::get(collection.id);12031204		for (key, value) in properties_updates {1205			match value {1206				Some(value) => {1207					stored_properties1208						.try_set(key.clone(), value)1209						.map_err(<Error<T>>::from)?;12101211					Self::deposit_event(Event::CollectionPropertySet(collection.id, key));1212					<PalletEvm<T>>::deposit_log(1213						erc::CollectionHelpersEvents::CollectionChanged {1214							collection_id: eth::collection_id_to_address(collection.id),1215						}1216						.to_log(T::ContractAddress::get()),1217					);1218				}1219				None => {1220					stored_properties.remove(&key).map_err(<Error<T>>::from)?;12211222					Self::deposit_event(Event::CollectionPropertyDeleted(collection.id, key));1223					<PalletEvm<T>>::deposit_log(1224						erc::CollectionHelpersEvents::CollectionChanged {1225							collection_id: eth::collection_id_to_address(collection.id),1226						}1227						.to_log(T::ContractAddress::get()),1228					);1229				}1230			}1231		}12321233		<CollectionProperties<T>>::set(collection.id, stored_properties);12341235		Ok(())1236	}12371238	/// A batch operation to add, edit or remove properties for a token.1239	/// It sets or removes a token's properties according to1240	/// `properties_updates` contents:1241	/// * sets a property under the <key> with the value provided `(<key>, Some(<value>))`1242	/// * removes a property under the <key> if the value is `None` `(<key>, None)`.1243	///1244	/// - `nesting_budget`: Limit for searching parents in-depth to check ownership.1245	/// - `is_token_create`: Indicates that method is called during token initialization.1246	///   Allows to bypass ownership check.1247	///1248	/// All affected properties should have `mutable` permission1249	/// to be **deleted** or to be **set more than once**,1250	/// and the sender should have permission to edit those properties.1251	///1252	/// This function fires an event for each property change.1253	/// In case of an error, all the changes (including the events) will be reverted1254	/// since the function is transactional.1255	pub fn modify_token_properties(1256		collection: &CollectionHandle<T>,1257		sender: &T::CrossAccountId,1258		token_id: TokenId,1259		properties_updates: impl Iterator<Item = (PropertyKey, Option<PropertyValue>)>,1260		is_token_create: bool,1261		mut stored_properties: TokenProperties,1262		is_token_owner: impl Fn() -> Result<bool, DispatchError>,1263		set_token_properties: impl FnOnce(TokenProperties),1264		log: evm_coder::ethereum::Log,1265	) -> DispatchResult {1266		let is_collection_admin = collection.is_owner_or_admin(sender);1267		let permissions = Self::property_permissions(collection.id);12681269		let mut token_owner_result = None;1270		let mut is_token_owner = || -> Result<bool, DispatchError> {1271			*token_owner_result.get_or_insert_with(&is_token_owner)1272		};12731274		for (key, value) in properties_updates {1275			let permission = permissions1276				.get(&key)1277				.cloned()1278				.unwrap_or_else(PropertyPermission::none);12791280			let is_property_exists = stored_properties.get(&key).is_some();12811282			match permission {1283				PropertyPermission { mutable: false, .. } if is_property_exists => {1284					return Err(<Error<T>>::NoPermission.into());1285				}12861287				PropertyPermission {1288					collection_admin,1289					token_owner,1290					..1291				} => {1292					//TODO: investigate threats during public minting.1293					let is_token_create =1294						is_token_create && (collection_admin || token_owner) && value.is_some();1295					if !(is_token_create1296						|| (collection_admin && is_collection_admin)1297						|| (token_owner && is_token_owner()?))1298					{1299						fail!(<Error<T>>::NoPermission);1300					}1301				}1302			}13031304			match value {1305				Some(value) => {1306					stored_properties1307						.try_set(key.clone(), value)1308						.map_err(<Error<T>>::from)?;13091310					Self::deposit_event(Event::TokenPropertySet(collection.id, token_id, key));1311				}1312				None => {1313					stored_properties.remove(&key).map_err(<Error<T>>::from)?;13141315					Self::deposit_event(Event::TokenPropertyDeleted(collection.id, token_id, key));1316				}1317			}13181319			<PalletEvm<T>>::deposit_log(log.clone());1320		}13211322		set_token_properties(stored_properties);13231324		Ok(())1325	}13261327	/// Sets or unsets the approval of a given operator.1328	///1329	/// The `operator` is allowed to transfer all token pieces of the `owner` on their behalf.1330	/// - `owner`: Token owner1331	/// - `operator`: Operator1332	/// - `approve`: Should operator status be granted or revoked?1333	pub fn set_allowance_for_all(1334		collection: &CollectionHandle<T>,1335		owner: &T::CrossAccountId,1336		operator: &T::CrossAccountId,1337		approve: bool,1338		set_allowance: impl FnOnce(),1339		log: evm_coder::ethereum::Log,1340	) -> DispatchResult {1341		if collection.permissions.access() == AccessMode::AllowList {1342			collection.check_allowlist(owner)?;1343			collection.check_allowlist(operator)?;1344		}13451346		Self::ensure_correct_receiver(operator)?;13471348		set_allowance();13491350		<PalletEvm<T>>::deposit_log(log);1351		Self::deposit_event(Event::ApprovedForAll(1352			collection.id,1353			owner.clone(),1354			operator.clone(),1355			approve,1356		));1357		Ok(())1358	}13591360	/// Set collection property.1361	///1362	/// * `collection` - Collection handler.1363	/// * `sender` - The owner or administrator of the collection.1364	/// * `property` - The property to set.1365	pub fn set_collection_property(1366		collection: &CollectionHandle<T>,1367		sender: &T::CrossAccountId,1368		property: Property,1369	) -> DispatchResult {1370		Self::set_collection_properties(collection, sender, [property].into_iter())1371	}13721373	/// Set a scoped collection property, where the scope is a special prefix1374	/// prohibiting a user access to change the property directly.1375	///1376	/// * `collection_id` - ID of the collection for which the property is being set.1377	/// * `scope` - Property scope.1378	/// * `property` - The property to set.1379	pub fn set_scoped_collection_property(1380		collection_id: CollectionId,1381		scope: PropertyScope,1382		property: Property,1383	) -> DispatchResult {1384		CollectionProperties::<T>::try_mutate(collection_id, |properties| {1385			properties.try_scoped_set(scope, property.key, property.value)1386		})1387		.map_err(<Error<T>>::from)?;13881389		Ok(())1390	}13911392	/// Set scoped collection properties, where the scope is a special prefix1393	/// prohibiting a user access to change the properties directly.1394	///1395	/// * `collection_id` - ID of the collection for which the properties is being set.1396	/// * `scope` - Property scope.1397	/// * `properties` - The properties to set.1398	pub fn set_scoped_collection_properties(1399		collection_id: CollectionId,1400		scope: PropertyScope,1401		properties: impl Iterator<Item = Property>,1402	) -> DispatchResult {1403		CollectionProperties::<T>::try_mutate(collection_id, |stored_properties| {1404			stored_properties.try_scoped_set_from_iter(scope, properties)1405		})1406		.map_err(<Error<T>>::from)?;14071408		Ok(())1409	}14101411	/// Set collection properties.1412	///1413	/// * `collection` - Collection handler.1414	/// * `sender` - The owner or administrator of the collection.1415	/// * `properties` - The properties to set.1416	pub fn set_collection_properties(1417		collection: &CollectionHandle<T>,1418		sender: &T::CrossAccountId,1419		properties: impl Iterator<Item = Property>,1420	) -> DispatchResult {1421		Self::modify_collection_properties(1422			collection,1423			sender,1424			properties.map(|property| (property.key, Some(property.value))),1425		)1426	}14271428	/// Delete collection property.1429	///1430	/// * `collection` - Collection handler.1431	/// * `sender` - The owner or administrator of the collection.1432	/// * `property` - The property to delete.1433	pub fn delete_collection_property(1434		collection: &CollectionHandle<T>,1435		sender: &T::CrossAccountId,1436		property_key: PropertyKey,1437	) -> DispatchResult {1438		Self::delete_collection_properties(collection, sender, [property_key].into_iter())1439	}14401441	/// Delete collection properties.1442	///1443	/// * `collection` - Collection handler.1444	/// * `sender` - The owner or administrator of the collection.1445	/// * `properties` - The properties to delete.1446	pub fn delete_collection_properties(1447		collection: &CollectionHandle<T>,1448		sender: &T::CrossAccountId,1449		property_keys: impl Iterator<Item = PropertyKey>,1450	) -> DispatchResult {1451		Self::modify_collection_properties(collection, sender, property_keys.map(|key| (key, None)))1452	}14531454	/// Set collection propetry permission without any checks.1455	///1456	/// Used for migrations.1457	///1458	/// * `collection` - Collection handler.1459	/// * `property_permissions` - Property permissions.1460	pub fn set_property_permission_unchecked(1461		collection: CollectionId,1462		property_permission: PropertyKeyPermission,1463	) -> DispatchResult {1464		<CollectionPropertyPermissions<T>>::try_mutate(collection, |permissions| {1465			permissions.try_set(property_permission.key, property_permission.permission)1466		})1467		.map_err(<Error<T>>::from)?;1468		Ok(())1469	}14701471	/// Set collection property permission.1472	///1473	/// * `collection` - Collection handler.1474	/// * `sender` - The owner or administrator of the collection.1475	/// * `property_permission` - Property permission.1476	pub fn set_property_permission(1477		collection: &CollectionHandle<T>,1478		sender: &T::CrossAccountId,1479		property_permission: PropertyKeyPermission,1480	) -> DispatchResult {1481		Self::set_scoped_property_permission(1482			collection,1483			sender,1484			PropertyScope::None,1485			property_permission,1486		)1487	}14881489	/// Set collection property permission with scope.1490	///1491	/// * `collection` - Collection handler.1492	/// * `sender` - The owner or administrator of the collection.1493	/// * `scope` - Property scope.1494	/// * `property_permission` - Property permission.1495	pub fn set_scoped_property_permission(1496		collection: &CollectionHandle<T>,1497		sender: &T::CrossAccountId,1498		scope: PropertyScope,1499		property_permission: PropertyKeyPermission,1500	) -> DispatchResult {1501		collection.check_is_owner_or_admin(sender)?;15021503		let all_permissions = CollectionPropertyPermissions::<T>::get(collection.id);1504		let current_permission = all_permissions.get(&property_permission.key);1505		if matches![1506			current_permission,1507			Some(PropertyPermission { mutable: false, .. })1508		] {1509			return Err(<Error<T>>::NoPermission.into());1510		}15111512		CollectionPropertyPermissions::<T>::try_mutate(collection.id, |permissions| {1513			let property_permission = property_permission.clone();1514			permissions.try_scoped_set(1515				scope,1516				property_permission.key,1517				property_permission.permission,1518			)1519		})1520		.map_err(<Error<T>>::from)?;15211522		Self::deposit_event(Event::PropertyPermissionSet(1523			collection.id,1524			property_permission.key,1525		));1526		<PalletEvm<T>>::deposit_log(1527			erc::CollectionHelpersEvents::CollectionChanged {1528				collection_id: eth::collection_id_to_address(collection.id),1529			}1530			.to_log(T::ContractAddress::get()),1531		);15321533		Ok(())1534	}15351536	/// Set token property permission.1537	///1538	/// * `collection` - Collection handler.1539	/// * `sender` - The owner or administrator of the collection.1540	/// * `property_permissions` - Property permissions.1541	#[transactional]1542	pub fn set_token_property_permissions(1543		collection: &CollectionHandle<T>,1544		sender: &T::CrossAccountId,1545		property_permissions: Vec<PropertyKeyPermission>,1546	) -> DispatchResult {1547		Self::set_scoped_token_property_permissions(1548			collection,1549			sender,1550			PropertyScope::None,1551			property_permissions,1552		)1553	}15541555	/// Set token property permission with scope.1556	///1557	/// * `collection` - Collection handler.1558	/// * `sender` - The owner or administrator of the collection.1559	/// * `scope` - Property scope.1560	/// * `property_permissions` - Property permissions.1561	#[transactional]1562	pub fn set_scoped_token_property_permissions(1563		collection: &CollectionHandle<T>,1564		sender: &T::CrossAccountId,1565		scope: PropertyScope,1566		property_permissions: Vec<PropertyKeyPermission>,1567	) -> DispatchResult {1568		for prop_pemission in property_permissions {1569			Self::set_scoped_property_permission(collection, sender, scope, prop_pemission)?;1570		}15711572		Ok(())1573	}15741575	/// Get collection property.1576	pub fn get_collection_property(1577		collection_id: CollectionId,1578		key: &PropertyKey,1579	) -> Option<PropertyValue> {1580		Self::collection_properties(collection_id).get(key).cloned()1581	}15821583	/// Convert byte vector to property key vector.1584	pub fn bytes_keys_to_property_keys(1585		keys: Vec<Vec<u8>>,1586	) -> Result<Vec<PropertyKey>, DispatchError> {1587		keys.into_iter()1588			.map(|key| -> Result<PropertyKey, DispatchError> {1589				key.try_into()1590					.map_err(|_| <Error<T>>::PropertyKeyIsTooLong.into())1591			})1592			.collect::<Result<Vec<PropertyKey>, DispatchError>>()1593	}15941595	/// Get properties according to given keys.1596	pub fn filter_collection_properties(1597		collection_id: CollectionId,1598		keys: Option<Vec<PropertyKey>>,1599	) -> Result<Vec<Property>, DispatchError> {1600		let properties = Self::collection_properties(collection_id);16011602		let properties = keys1603			.map(|keys| {1604				keys.into_iter()1605					.filter_map(|key| {1606						properties.get(&key).map(|value| Property {1607							key,1608							value: value.clone(),1609						})1610					})1611					.collect()1612			})1613			.unwrap_or_else(|| {1614				properties1615					.into_iter()1616					.map(|(key, value)| Property { key, value })1617					.collect()1618			});16191620		Ok(properties)1621	}16221623	/// Get property permissions according to given keys.1624	pub fn filter_property_permissions(1625		collection_id: CollectionId,1626		keys: Option<Vec<PropertyKey>>,1627	) -> Result<Vec<PropertyKeyPermission>, DispatchError> {1628		let permissions = Self::property_permissions(collection_id);16291630		let key_permissions = keys1631			.map(|keys| {1632				keys.into_iter()1633					.filter_map(|key| {1634						permissions1635							.get(&key)1636							.map(|permission| PropertyKeyPermission {1637								key,1638								permission: permission.clone(),1639							})1640					})1641					.collect()1642			})1643			.unwrap_or_else(|| {1644				permissions1645					.into_iter()1646					.map(|(key, permission)| PropertyKeyPermission { key, permission })1647					.collect()1648			});16491650		Ok(key_permissions)1651	}16521653	/// Toggle `user` participation in the `collection`'s allow list.1654	/// #### Store read/writes1655	/// 1 writes1656	pub fn toggle_allowlist(1657		collection: &CollectionHandle<T>,1658		sender: &T::CrossAccountId,1659		user: &T::CrossAccountId,1660		allowed: bool,1661	) -> DispatchResult {1662		collection.check_is_owner_or_admin(sender)?;16631664		// =========16651666		if allowed {1667			<Allowlist<T>>::insert((collection.id, user), true);1668			Self::deposit_event(Event::<T>::AllowListAddressAdded(1669				collection.id,1670				user.clone(),1671			));1672		} else {1673			<Allowlist<T>>::remove((collection.id, user));1674			Self::deposit_event(Event::<T>::AllowListAddressRemoved(1675				collection.id,1676				user.clone(),1677			));1678		}16791680		<PalletEvm<T>>::deposit_log(1681			erc::CollectionHelpersEvents::CollectionChanged {1682				collection_id: eth::collection_id_to_address(collection.id),1683			}1684			.to_log(T::ContractAddress::get()),1685		);16861687		Ok(())1688	}16891690	/// Toggle `user` participation in the `collection`'s admin list.1691	/// #### Store read/writes1692	/// 2 reads, 2 writes1693	pub fn toggle_admin(1694		collection: &CollectionHandle<T>,1695		sender: &T::CrossAccountId,1696		user: &T::CrossAccountId,1697		admin: bool,1698	) -> DispatchResult {1699		collection.check_is_internal()?;1700		collection.check_is_owner(sender)?;17011702		let is_admin = <IsAdmin<T>>::get((collection.id, user));1703		if is_admin == admin {1704			if admin {1705				return Ok(());1706			} else {1707				return Err(Error::<T>::UserIsNotCollectionAdmin.into());1708			}1709		}1710		let amount = <AdminAmount<T>>::get(collection.id);17111712		// =========17131714		if admin {1715			let amount = amount1716				.checked_add(1)1717				.ok_or(<Error<T>>::CollectionAdminCountExceeded)?;1718			ensure!(1719				amount <= Self::collection_admins_limit(),1720				<Error<T>>::CollectionAdminCountExceeded,1721			);17221723			<AdminAmount<T>>::insert(collection.id, amount);1724			<IsAdmin<T>>::insert((collection.id, user), true);17251726			Self::deposit_event(Event::<T>::CollectionAdminAdded(1727				collection.id,1728				user.clone(),1729			));1730		} else {1731			<AdminAmount<T>>::insert(collection.id, amount.saturating_sub(1));1732			<IsAdmin<T>>::remove((collection.id, user));17331734			Self::deposit_event(Event::<T>::CollectionAdminRemoved(1735				collection.id,1736				user.clone(),1737			));1738		}17391740		<PalletEvm<T>>::deposit_log(1741			erc::CollectionHelpersEvents::CollectionChanged {1742				collection_id: eth::collection_id_to_address(collection.id),1743			}1744			.to_log(T::ContractAddress::get()),1745		);17461747		Ok(())1748	}17491750	/// Update collection limits.1751	pub fn update_limits(1752		user: &T::CrossAccountId,1753		collection: &mut CollectionHandle<T>,1754		new_limit: CollectionLimits,1755	) -> DispatchResult {1756		collection.check_is_internal()?;1757		collection.check_is_owner_or_admin(user)?;17581759		collection.limits =1760			Self::clamp_limits(collection.mode.clone(), &collection.limits, new_limit)?;17611762		Self::deposit_event(Event::<T>::CollectionLimitSet(collection.id));1763		<PalletEvm<T>>::deposit_log(1764			erc::CollectionHelpersEvents::CollectionChanged {1765				collection_id: eth::collection_id_to_address(collection.id),1766			}1767			.to_log(T::ContractAddress::get()),1768		);17691770		collection.save()1771	}17721773	/// Merge set fields from `new_limit` to `old_limit`.1774	fn clamp_limits(1775		mode: CollectionMode,1776		old_limit: &CollectionLimits,1777		mut new_limit: CollectionLimits,1778	) -> Result<CollectionLimits, DispatchError> {1779		let limits = old_limit;1780		limit_default!(old_limit, new_limit,1781			account_token_ownership_limit => ensure!(1782				new_limit <= MAX_TOKEN_OWNERSHIP,1783				<Error<T>>::CollectionLimitBoundsExceeded,1784			),1785			sponsored_data_size => ensure!(1786				new_limit <= CUSTOM_DATA_LIMIT,1787				<Error<T>>::CollectionLimitBoundsExceeded,1788			),17891790			sponsored_data_rate_limit => {},1791			token_limit => ensure!(1792				old_limit >= new_limit && new_limit > 0,1793				<Error<T>>::CollectionTokenLimitExceeded1794			),17951796			sponsor_transfer_timeout(match mode {1797				CollectionMode::NFT => NFT_SPONSOR_TRANSFER_TIMEOUT,1798				CollectionMode::Fungible(_) => FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,1799				CollectionMode::ReFungible => REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,1800			}) => ensure!(1801				new_limit <= MAX_SPONSOR_TIMEOUT,1802				<Error<T>>::CollectionLimitBoundsExceeded,1803			),1804			sponsor_approve_timeout => {},1805			owner_can_transfer => ensure!(1806				!limits.owner_can_transfer_instaled() ||1807				old_limit || !new_limit,1808				<Error<T>>::OwnerPermissionsCantBeReverted,1809			),1810			owner_can_destroy => ensure!(1811				old_limit || !new_limit,1812				<Error<T>>::OwnerPermissionsCantBeReverted,1813			),1814			transfers_enabled => {},1815		);1816		Ok(new_limit)1817	}18181819	/// Update collection permissions.1820	pub fn update_permissions(1821		user: &T::CrossAccountId,1822		collection: &mut CollectionHandle<T>,1823		new_permission: CollectionPermissions,1824	) -> DispatchResult {1825		collection.check_is_internal()?;1826		collection.check_is_owner_or_admin(user)?;1827		collection.permissions = Self::clamp_permissions(1828			collection.mode.clone(),1829			&collection.permissions,1830			new_permission,1831		)?;18321833		Self::deposit_event(Event::<T>::CollectionPermissionSet(collection.id));1834		<PalletEvm<T>>::deposit_log(1835			erc::CollectionHelpersEvents::CollectionChanged {1836				collection_id: eth::collection_id_to_address(collection.id),1837			}1838			.to_log(T::ContractAddress::get()),1839		);18401841		collection.save()1842	}18431844	/// Merge set fields from `new_permission` to `old_permission`.1845	fn clamp_permissions(1846		_mode: CollectionMode,1847		old_permission: &CollectionPermissions,1848		mut new_permission: CollectionPermissions,1849	) -> Result<CollectionPermissions, DispatchError> {1850		limit_default_clone!(old_permission, new_permission,1851			access => {},1852			mint_mode => {},1853			nesting => { /* todo check for permissive, if only it gets out of benchmarks */ },1854		);1855		Ok(new_permission)1856	}18571858	/// Repair possibly broken properties of a collection.1859	pub fn repair_collection(collection_id: CollectionId) -> DispatchResult {1860		CollectionProperties::<T>::mutate(collection_id, |properties| {1861			properties.recompute_consumed_space();1862		});18631864		Ok(())1865	}1866}18671868/// Indicates unsupported methods by returning [Error::UnsupportedOperation].1869#[macro_export]1870macro_rules! unsupported {1871	($runtime:path) => {1872		Err($crate::Error::<$runtime>::UnsupportedOperation.into())1873	};1874}18751876/// Return weights for various worst-case operations.1877pub trait CommonWeightInfo<CrossAccountId> {1878	/// Weight of item creation.1879	fn create_item(data: &CreateItemData) -> Weight {1880		Self::create_multiple_items(from_ref(data))1881	}18821883	/// Weight of items creation.1884	fn create_multiple_items(amount: &[CreateItemData]) -> Weight;18851886	/// Weight of items creation.1887	fn create_multiple_items_ex(cost: &CreateItemExData<CrossAccountId>) -> Weight;18881889	/// The weight of the burning item.1890	fn burn_item() -> Weight;18911892	/// Property setting weight.1893	///1894	/// * `amount`- The number of properties to set.1895	fn set_collection_properties(amount: u32) -> Weight;18961897	/// Collection property deletion weight.1898	///1899	/// * `amount`- The number of properties to set.1900	fn delete_collection_properties(amount: u32) -> Weight;19011902	/// Token property setting weight.1903	///1904	/// * `amount`- The number of properties to set.1905	fn set_token_properties(amount: u32) -> Weight;19061907	/// Token property deletion weight.1908	///1909	/// * `amount`- The number of properties to delete.1910	fn delete_token_properties(amount: u32) -> Weight;19111912	/// Token property permissions set weight.1913	///1914	/// * `amount`- The number of property permissions to set.1915	fn set_token_property_permissions(amount: u32) -> Weight;19161917	/// Transfer price of the token or its parts.1918	fn transfer() -> Weight;19191920	/// The price of setting the permission of the operation from another user.1921	fn approve() -> Weight;19221923	/// The price of setting the permission of the operation from another user for eth mirror.1924	fn approve_from() -> Weight;19251926	/// Transfer price from another user.1927	fn transfer_from() -> Weight;19281929	/// The price of burning a token from another user.1930	fn burn_from() -> Weight;19311932	/// Differs from burn_item in case of Fungible and Refungible, as it should burn1933	/// whole users's balance.1934	///1935	/// This method shouldn't be used directly, as it doesn't count breadth price, use [burn_recursively](CommonWeightInfo::burn_recursively) instead1936	fn burn_recursively_self_raw() -> Weight;19371938	/// Cost of iterating over `amount` children while burning, without counting child burning itself.1939	///1940	/// This method shouldn't be used directly, as it doesn't count depth price, use [burn_recursively](CommonWeightInfo::burn_recursively) instead1941	fn burn_recursively_breadth_raw(amount: u32) -> Weight;19421943	/// The price of recursive burning a token.1944	///1945	/// `max_selfs` - The maximum burning weight of the token itself.1946	/// `max_breadth` - The maximum number of nested tokens to burn.1947	fn burn_recursively(max_selfs: u32, max_breadth: u32) -> Weight {1948		Self::burn_recursively_self_raw()1949			.saturating_mul(max_selfs.max(1) as u64)1950			.saturating_add(Self::burn_recursively_breadth_raw(max_breadth))1951	}19521953	/// The price of retrieving token owner1954	fn token_owner() -> Weight;19551956	/// The price of setting approval for all1957	fn set_allowance_for_all() -> Weight;19581959	/// The price of repairing an item.1960	fn force_repair_item() -> Weight;1961}19621963/// Weight info extension trait for refungible pallet.1964pub trait RefungibleExtensionsWeightInfo {1965	/// Weight of token repartition.1966	fn repartition() -> Weight;1967}19681969/// Common collection operations.1970///1971/// It wraps methods in Fungible, Nonfungible and Refungible pallets1972/// and adds weight info.1973pub trait CommonCollectionOperations<T: Config> {1974	/// Create token.1975	///1976	/// * `sender` - The user who mint the token and pays for the transaction.1977	/// * `to` - The user who will own the token.1978	/// * `data` - Token data.1979	/// * `nesting_budget` - A budget that can be spent on nesting tokens.1980	fn create_item(1981		&self,1982		sender: T::CrossAccountId,1983		to: T::CrossAccountId,1984		data: CreateItemData,1985		nesting_budget: &dyn Budget,1986	) -> DispatchResultWithPostInfo;19871988	/// Create multiple tokens.1989	///1990	/// * `sender` - The user who mint the token and pays for the transaction.1991	/// * `to` - The user who will own the token.1992	/// * `data` - Token data.1993	/// * `nesting_budget` - A budget that can be spent on nesting tokens.1994	fn create_multiple_items(1995		&self,1996		sender: T::CrossAccountId,1997		to: T::CrossAccountId,1998		data: Vec<CreateItemData>,1999		nesting_budget: &dyn Budget,2000	) -> DispatchResultWithPostInfo;20012002	/// Create multiple tokens.2003	///2004	/// * `sender` - The user who mint the token and pays for the transaction.2005	/// * `to` - The user who will own the token.2006	/// * `data` - Token data.2007	/// * `nesting_budget` - A budget that can be spent on nesting tokens.2008	fn create_multiple_items_ex(2009		&self,2010		sender: T::CrossAccountId,2011		data: CreateItemExData<T::CrossAccountId>,2012		nesting_budget: &dyn Budget,2013	) -> DispatchResultWithPostInfo;20142015	/// Burn token.2016	///2017	/// * `sender` - The user who owns the token.2018	/// * `token` - Token id that will burned.2019	/// * `amount` - The number of parts of the token that will be burned.2020	fn burn_item(2021		&self,2022		sender: T::CrossAccountId,2023		token: TokenId,2024		amount: u128,2025	) -> DispatchResultWithPostInfo;20262027	/// Burn token and all nested tokens recursievly.2028	///2029	/// * `sender` - The user who owns the token.2030	/// * `token` - Token id that will burned.2031	/// * `self_budget` - The budget that can be spent on burning tokens.2032	/// * `breadth_budget` - The budget that can be spent on burning nested tokens.2033	fn burn_item_recursively(2034		&self,2035		sender: T::CrossAccountId,2036		token: TokenId,2037		self_budget: &dyn Budget,2038		breadth_budget: &dyn Budget,2039	) -> DispatchResultWithPostInfo;20402041	/// Set collection properties.2042	///2043	/// * `sender` - Must be either the owner of the collection or its admin.2044	/// * `properties` - Properties to be set.2045	fn set_collection_properties(2046		&self,2047		sender: T::CrossAccountId,2048		properties: Vec<Property>,2049	) -> DispatchResultWithPostInfo;20502051	/// Delete collection properties.2052	///2053	/// * `sender` - Must be either the owner of the collection or its admin.2054	/// * `properties` - The properties to be removed.2055	fn delete_collection_properties(2056		&self,2057		sender: &T::CrossAccountId,2058		property_keys: Vec<PropertyKey>,2059	) -> DispatchResultWithPostInfo;20602061	/// Set token properties.2062	///2063	/// The appropriate [`PropertyPermission`] for the token property2064	/// must be set with [`Self::set_token_property_permissions`].2065	///2066	/// * `sender` - Must be either the owner of the token or its admin.2067	/// * `token_id` - The token for which the properties are being set.2068	/// * `properties` - Properties to be set.2069	/// * `budget` - Budget for setting properties.2070	fn set_token_properties(2071		&self,2072		sender: T::CrossAccountId,2073		token_id: TokenId,2074		properties: Vec<Property>,2075		budget: &dyn Budget,2076	) -> DispatchResultWithPostInfo;20772078	/// Remove token properties.2079	///2080	/// The appropriate [`PropertyPermission`] for the token property2081	/// must be set with [`Self::set_token_property_permissions`].2082	///2083	/// * `sender` - Must be either the owner of the token or its admin.2084	/// * `token_id` - The token for which the properties are being remove.2085	/// * `property_keys` - Keys to remove corresponding properties.2086	/// * `budget` - Budget for removing properties.2087	fn delete_token_properties(2088		&self,2089		sender: T::CrossAccountId,2090		token_id: TokenId,2091		property_keys: Vec<PropertyKey>,2092		budget: &dyn Budget,2093	) -> DispatchResultWithPostInfo;20942095	/// Set token property permissions.2096	///2097	/// * `sender` - Must be either the owner of the token or its admin.2098	/// * `token_id` - The token for which the properties are being set.2099	/// * `property_permissions` - Property permissions to be set.2100	/// * `budget` - Budget for setting properties.2101	fn set_token_property_permissions(2102		&self,2103		sender: &T::CrossAccountId,2104		property_permissions: Vec<PropertyKeyPermission>,2105	) -> DispatchResultWithPostInfo;21062107	/// Transfer amount of token pieces.2108	///2109	/// * `sender` - Donor user.2110	/// * `to` - Recepient user.2111	/// * `token` - The token of which parts are being sent.2112	/// * `amount` - The number of parts of the token that will be transferred.2113	/// * `budget` - The maximum budget that can be spent on the transfer.2114	fn transfer(2115		&self,2116		sender: T::CrossAccountId,2117		to: T::CrossAccountId,2118		token: TokenId,2119		amount: u128,2120		budget: &dyn Budget,2121	) -> DispatchResultWithPostInfo;21222123	/// Grant access to another account to transfer parts of the token owned by the calling user via [Self::transfer_from].2124	///2125	/// * `sender` - The user who grants access to the token.2126	/// * `spender` - The user to whom the rights are granted.2127	/// * `token` - The token to which access is granted.2128	/// * `amount` - The amount of pieces that another user can dispose of.2129	fn approve(2130		&self,2131		sender: T::CrossAccountId,2132		spender: T::CrossAccountId,2133		token: TokenId,2134		amount: u128,2135	) -> DispatchResultWithPostInfo;21362137	/// Grant access to another account to transfer parts of the token owned by the calling user's eth mirror via [Self::transfer_from].2138	///2139	/// * `sender` - The user who grants access to the token.2140	/// * `from` - Spender's eth mirror.2141	/// * `to` - The user to whom the rights are granted.2142	/// * `token` - The token to which access is granted.2143	/// * `amount` - The amount of pieces that another user can dispose of.2144	fn approve_from(2145		&self,2146		sender: T::CrossAccountId,2147		from: T::CrossAccountId,2148		to: T::CrossAccountId,2149		token: TokenId,2150		amount: u128,2151	) -> DispatchResultWithPostInfo;21522153	/// Send parts of a token owned by another user.2154	///2155	/// Before calling this method, you must grant rights to the calling user via [`Self::approve`].2156	///2157	/// * `sender` - The user who must have access to the token (see [`Self::approve`]).2158	/// * `from` - The user who owns the token.2159	/// * `to` - Recepient user.2160	/// * `token` - The token of which parts are being sent.2161	/// * `amount` - The number of parts of the token that will be transferred.2162	/// * `budget` - The maximum budget that can be spent on the transfer.2163	fn transfer_from(2164		&self,2165		sender: T::CrossAccountId,2166		from: T::CrossAccountId,2167		to: T::CrossAccountId,2168		token: TokenId,2169		amount: u128,2170		budget: &dyn Budget,2171	) -> DispatchResultWithPostInfo;21722173	/// Burn parts of a token owned by another user.2174	///2175	/// Before calling this method, you must grant rights to the calling user via [`Self::approve`].2176	///2177	/// * `sender` - The user who must have access to the token (see [`Self::approve`]).2178	/// * `from` - The user who owns the token.2179	/// * `token` - The token of which parts are being sent.2180	/// * `amount` - The number of parts of the token that will be transferred.2181	/// * `budget` - The maximum budget that can be spent on the burn.2182	fn burn_from(2183		&self,2184		sender: T::CrossAccountId,2185		from: T::CrossAccountId,2186		token: TokenId,2187		amount: u128,2188		budget: &dyn Budget,2189	) -> DispatchResultWithPostInfo;21902191	/// Check permission to nest token.2192	///2193	/// * `sender` - The user who initiated the check.2194	/// * `from` - The token that is checked for embedding.2195	/// * `under` - Token under which to check.2196	/// * `budget` - The maximum budget that can be spent on the check.2197	fn check_nesting(2198		&self,2199		sender: T::CrossAccountId,2200		from: (CollectionId, TokenId),2201		under: TokenId,2202		budget: &dyn Budget,2203	) -> DispatchResult;22042205	/// Nest one token into another.2206	///2207	/// * `under` - Token holder.2208	/// * `to_nest` - Nested token.2209	fn nest(&self, under: TokenId, to_nest: (CollectionId, TokenId));22102211	/// Unnest token.2212	///2213	/// * `under` - Token holder.2214	/// * `to_nest` - Token to unnest.2215	fn unnest(&self, under: TokenId, to_nest: (CollectionId, TokenId));22162217	/// Get all user tokens.2218	///2219	/// * `account` - Account for which you need to get tokens.2220	fn account_tokens(&self, account: T::CrossAccountId) -> Vec<TokenId>;22212222	/// Get all the tokens in the collection.2223	fn collection_tokens(&self) -> Vec<TokenId>;22242225	/// Check if the token exists.2226	///2227	/// * `token` - Id token to check.2228	fn token_exists(&self, token: TokenId) -> bool;22292230	/// Get the id of the last minted token.2231	fn last_token_id(&self) -> TokenId;22322233	/// Get the owner of the token.2234	///2235	/// * `token` - The token for which you need to find out the owner.2236	fn token_owner(&self, token: TokenId) -> Result<T::CrossAccountId, TokenOwnerError>;22372238	/// Returns 10 tokens owners in no particular order.2239	///2240	/// * `token` - The token for which you need to find out the owners.2241	fn token_owners(&self, token: TokenId) -> Vec<T::CrossAccountId>;22422243	/// Get the value of the token property by key.2244	///2245	/// * `token` - Token with the property to get.2246	/// * `key` - Property name.2247	fn token_property(&self, token_id: TokenId, key: &PropertyKey) -> Option<PropertyValue>;22482249	/// Get a set of token properties by key vector.2250	///2251	/// * `token` - Token with the property to get.2252	/// * `keys` - Vector of property keys. If this parameter is [None](sp_std::result::Result),2253	/// then all properties are returned.2254	fn token_properties(&self, token: TokenId, keys: Option<Vec<PropertyKey>>) -> Vec<Property>;22552256	/// Amount of unique collection tokens2257	fn total_supply(&self) -> u32;22582259	/// Amount of different tokens account has.2260	///2261	/// * `account` - The account for which need to get the balance.2262	fn account_balance(&self, account: T::CrossAccountId) -> u32;22632264	/// Amount of specific token account have.2265	fn balance(&self, account: T::CrossAccountId, token: TokenId) -> u128;22662267	/// Amount of token pieces2268	fn total_pieces(&self, token: TokenId) -> Option<u128>;22692270	/// Get the number of parts of the token that a trusted user can manage.2271	///2272	/// * `sender` - Trusted user.2273	/// * `spender` - Owner of the token.2274	/// * `token` - The token for which to get the value.2275	fn allowance(2276		&self,2277		sender: T::CrossAccountId,2278		spender: T::CrossAccountId,2279		token: TokenId,2280	) -> u128;22812282	/// Get extension for RFT collection.2283	fn refungible_extensions(&self) -> Option<&dyn RefungibleExtensions<T>>;22842285	/// The `operator` is allowed to transfer all tokens of the `owner` on their behalf.2286	/// * `owner` - Token owner2287	/// * `operator` - Operator2288	/// * `approve` - Should operator status be granted or revoked?2289	fn set_allowance_for_all(2290		&self,2291		owner: T::CrossAccountId,2292		operator: T::CrossAccountId,2293		approve: bool,2294	) -> DispatchResultWithPostInfo;22952296	/// Tells whether the given `owner` approves the `operator`.2297	fn allowance_for_all(&self, owner: T::CrossAccountId, operator: T::CrossAccountId) -> bool;22982299	/// Repairs a possibly broken item.2300	fn repair_item(&self, token: TokenId) -> DispatchResultWithPostInfo;2301}23022303/// Extension for RFT collection.2304pub trait RefungibleExtensions<T>2305where2306	T: Config,2307{2308	/// Change the number of parts of the token.2309	///2310	/// When the value changes down, this function is equivalent to burning parts of the token.2311	///2312	/// * `sender` - The user calling the repartition operation. Must be the owner of the token.2313	/// * `token` - The token for which you want to change the number of parts.2314	/// * `amount` - The new value of the parts of the token.2315	fn repartition(2316		&self,2317		sender: &T::CrossAccountId,2318		token: TokenId,2319		amount: u128,2320	) -> DispatchResultWithPostInfo;2321}23222323/// Merge [`DispatchResult`] with [`Weight`] into [`DispatchResultWithPostInfo`].2324///2325/// Used for [`CommonCollectionOperations`] implementations and flexible enough to do so.2326pub fn with_weight(res: DispatchResult, weight: Weight) -> DispatchResultWithPostInfo {2327	let post_info = PostDispatchInfo {2328		actual_weight: Some(weight),2329		pays_fee: Pays::Yes,2330	};2331	match res {2332		Ok(()) => Ok(post_info),2333		Err(error) => Err(DispatchErrorWithPostInfo { post_info, error }),2334	}2335}23362337impl<T: Config> From<PropertiesError> for Error<T> {2338	fn from(error: PropertiesError) -> Self {2339		match error {2340			PropertiesError::NoSpaceForProperty => Self::NoSpaceForProperty,2341			PropertiesError::PropertyLimitReached => Self::PropertyLimitReached,2342			PropertiesError::InvalidCharacterInPropertyKey => Self::InvalidCharacterInPropertyKey,2343			PropertiesError::PropertyKeyIsTooLong => Self::PropertyKeyIsTooLong,2344			PropertiesError::EmptyPropertyKey => Self::EmptyPropertyKey,2345		}2346	}2347}
modifiedpallets/structure/src/lib.rsdiffbeforeafterboth
--- a/pallets/structure/src/lib.rs
+++ b/pallets/structure/src/lib.rs
@@ -60,7 +60,7 @@
 use frame_support::dispatch::{DispatchError, DispatchResult, DispatchResultWithPostInfo};
 use frame_support::fail;
 pub use pallet::*;
-use pallet_common::{dispatch::CollectionDispatch, CollectionHandle};
+use pallet_common::{dispatch::CollectionDispatch};
 use up_data_structs::{
 	CollectionId, TokenId, mapping::TokenAddressMapping, budget::Budget, TokenOwnerError,
 };
modifiedruntime/common/dispatch.rsdiffbeforeafterboth
--- a/runtime/common/dispatch.rs
+++ b/runtime/common/dispatch.rs
@@ -25,7 +25,7 @@
 };
 pub use pallet_common::dispatch::CollectionDispatch;
 use pallet_fungible::{Pallet as PalletFungible, FungibleHandle};
-use pallet_balances_adapter::{Pallet as PalletNativeFungible, NativeFungibleHandle};
+use pallet_balances_adapter::{NativeFungibleHandle};
 use pallet_nonfungible::{Pallet as PalletNonfungible, NonfungibleHandle};
 use pallet_refungible::{
 	Pallet as PalletRefungible, RefungibleHandle, erc_token::RefungibleTokenHandle,