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

difftreelog

fix use OptionQuery for TokenProperties

Daniel Shiposha2023-10-02parent: #5ef5e6b.patch.diff
in: master

9 files changed

modifiedpallets/balances-adapter/src/common.rsdiffbeforeafterboth
--- a/pallets/balances-adapter/src/common.rs
+++ b/pallets/balances-adapter/src/common.rs
@@ -172,18 +172,16 @@
 		fail!(<pallet_common::Error<T>>::UnsupportedOperation);
 	}
 
-	fn get_token_properties_map(&self, _token_id: TokenId) -> up_data_structs::TokenProperties {
+	fn get_token_properties_raw(
+		&self,
+		_token_id: TokenId,
+	) -> Option<up_data_structs::TokenProperties> {
 		// No token properties are defined on fungibles
-		up_data_structs::TokenProperties::new()
+		None
 	}
 
-	fn set_token_properties_map(&self, _token_id: TokenId, _map: up_data_structs::TokenProperties) {
-		// No token properties are defined on fungibles
-	}
-
-	fn properties_exist(&self, _token: TokenId) -> bool {
+	fn set_token_properties_raw(&self, _token_id: TokenId, _map: up_data_structs::TokenProperties) {
 		// No token properties are defined on fungibles
-		false
 	}
 
 	fn set_token_property_permissions(
modifiedpallets/common/src/lib.rsdiffbeforeafterboth
--- a/pallets/common/src/lib.rs
+++ b/pallets/common/src/lib.rs
@@ -2098,18 +2098,13 @@
 	/// Get token properties raw map.
 	///
 	/// * `token_id` - The token which properties are needed.
-	fn get_token_properties_map(&self, token_id: TokenId) -> TokenProperties;
+	fn get_token_properties_raw(&self, token_id: TokenId) -> Option<TokenProperties>;
 
 	/// Set token properties raw map.
 	///
 	/// * `token_id` - The token for which the properties are being set.
 	/// * `map` - The raw map containing the token's properties.
-	fn set_token_properties_map(&self, token_id: TokenId, map: TokenProperties);
-
-	/// Whether the given token has properties.
-	///
-	/// * `token_id` - The token in question.
-	fn properties_exist(&self, token: TokenId) -> bool;
+	fn set_token_properties_raw(&self, token_id: TokenId, map: TokenProperties);
 
 	/// Set token property permissions.
 	///
@@ -2590,7 +2585,7 @@
 			<PalletEvm<T>>::deposit_log(log);
 
 			self.collection
-				.set_token_properties_map(token_id, stored_properties.into_inner());
+				.set_token_properties_raw(token_id, stored_properties.into_inner());
 		}
 
 		Ok(())
@@ -2624,7 +2619,7 @@
 			true
 		},
 		get_properties: |token_id| {
-			debug_assert!(!collection.properties_exist(token_id));
+			debug_assert!(collection.get_token_properties_raw(token_id).is_none());
 			TokenProperties::new()
 		},
 		_phantom: PhantomData,
@@ -2686,7 +2681,11 @@
 		is_collection_admin: LazyValue::new(|| collection.is_owner_or_admin(sender)),
 		property_permissions: LazyValue::new(|| <Pallet<T>>::property_permissions(collection.id)),
 		check_token_exist: |token_id| collection.token_exists(token_id),
-		get_properties: |token_id| collection.get_token_properties_map(token_id),
+		get_properties: |token_id| {
+			collection
+				.get_token_properties_raw(token_id)
+				.unwrap_or_default()
+		},
 		_phantom: PhantomData,
 	}
 }
modifiedpallets/fungible/src/common.rsdiffbeforeafterboth
--- a/pallets/fungible/src/common.rs
+++ b/pallets/fungible/src/common.rs
@@ -364,18 +364,16 @@
 		fail!(<Error<T>>::SettingPropertiesNotAllowed)
 	}
 
-	fn get_token_properties_map(&self, _token_id: TokenId) -> up_data_structs::TokenProperties {
+	fn get_token_properties_raw(
+		&self,
+		_token_id: TokenId,
+	) -> Option<up_data_structs::TokenProperties> {
 		// No token properties are defined on fungibles
-		up_data_structs::TokenProperties::new()
+		None
 	}
 
-	fn set_token_properties_map(&self, _token_id: TokenId, _map: up_data_structs::TokenProperties) {
-		// No token properties are defined on fungibles
-	}
-
-	fn properties_exist(&self, _token: TokenId) -> bool {
+	fn set_token_properties_raw(&self, _token_id: TokenId, _map: up_data_structs::TokenProperties) {
 		// No token properties are defined on fungibles
-		false
 	}
 
 	fn check_nesting(
modifiedpallets/nonfungible/src/common.rsdiffbeforeafterboth
--- a/pallets/nonfungible/src/common.rs
+++ b/pallets/nonfungible/src/common.rs
@@ -265,12 +265,15 @@
 		)
 	}
 
-	fn get_token_properties_map(&self, token_id: TokenId) -> up_data_structs::TokenProperties {
+	fn get_token_properties_raw(
+		&self,
+		token_id: TokenId,
+	) -> Option<up_data_structs::TokenProperties> {
 		<TokenProperties<T>>::get((self.id, token_id))
 	}
 
-	fn set_token_properties_map(&self, token_id: TokenId, map: up_data_structs::TokenProperties) {
-		<TokenProperties<T>>::set((self.id, token_id), map)
+	fn set_token_properties_raw(&self, token_id: TokenId, map: up_data_structs::TokenProperties) {
+		<TokenProperties<T>>::insert((self.id, token_id), map)
 	}
 
 	fn set_token_property_permissions(
@@ -287,10 +290,6 @@
 		)
 	}
 
-	fn properties_exist(&self, token: TokenId) -> bool {
-		<TokenProperties<T>>::contains_key((self.id, token))
-	}
-
 	fn burn_item(
 		&self,
 		sender: T::CrossAccountId,
@@ -482,13 +481,15 @@
 	}
 
 	fn token_property(&self, token_id: TokenId, key: &PropertyKey) -> Option<PropertyValue> {
-		<Pallet<T>>::token_properties((self.id, token_id))
+		<Pallet<T>>::token_properties((self.id, token_id))?
 			.get(key)
 			.cloned()
 	}
 
 	fn token_properties(&self, token_id: TokenId, keys: Option<Vec<PropertyKey>>) -> Vec<Property> {
-		let properties = <Pallet<T>>::token_properties((self.id, token_id));
+		let Some(properties) = <Pallet<T>>::token_properties((self.id, token_id)) else {
+			return vec![];
+		};
 
 		keys.map(|keys| {
 			keys.into_iter()
modifiedpallets/nonfungible/src/erc.rsdiffbeforeafterboth
--- a/pallets/nonfungible/src/erc.rs
+++ b/pallets/nonfungible/src/erc.rs
@@ -272,7 +272,8 @@
 			.try_into()
 			.map_err(|_| "key too long")?;
 
-		let props = <TokenProperties<T>>::get((self.id, token_id));
+		let props =
+			<TokenProperties<T>>::get((self.id, token_id)).ok_or("Token properties not found")?;
 		let prop = props.get(&key).ok_or("key not found")?;
 
 		Ok(prop.to_vec().into())
modifiedpallets/nonfungible/src/lib.rsdiffbeforeafterboth
--- a/pallets/nonfungible/src/lib.rs
+++ b/pallets/nonfungible/src/lib.rs
@@ -102,8 +102,8 @@
 use up_data_structs::{
 	AccessMode, CollectionId, CustomDataLimit, TokenId, CreateCollectionData, CreateNftExData,
 	mapping::TokenAddressMapping, budget::Budget, Property, PropertyKey, PropertyValue,
-	PropertyKeyPermission, PropertyScope, TrySetProperty, TokenChild, AuxPropertyValue,
-	PropertiesPermissionMap, TokenProperties as TokenPropertiesT,
+	PropertyKeyPermission, PropertyScope, TokenChild, AuxPropertyValue, PropertiesPermissionMap,
+	TokenProperties as TokenPropertiesT,
 };
 use pallet_evm::{account::CrossAccountId, Pallet as PalletEvm};
 use pallet_common::{
@@ -201,7 +201,7 @@
 	pub type TokenProperties<T: Config> = StorageNMap<
 		Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),
 		Value = TokenPropertiesT,
-		QueryKind = ValueQuery,
+		QueryKind = OptionQuery,
 	>;
 
 	/// Custom data of a token that is serialized to bytes,
@@ -340,40 +340,8 @@
 	/// - `token`: Token ID.
 	pub fn token_exists(collection: &NonfungibleHandle<T>, token: TokenId) -> bool {
 		<TokenData<T>>::contains_key((collection.id, token))
-	}
-
-	/// Set the token property with the scope.
-	///
-	/// - `property`: Contains key-value pair.
-	pub fn set_scoped_token_property(
-		collection_id: CollectionId,
-		token_id: TokenId,
-		scope: PropertyScope,
-		property: Property,
-	) -> DispatchResult {
-		TokenProperties::<T>::try_mutate((collection_id, token_id), |properties| {
-			properties.try_scoped_set(scope, property.key, property.value)
-		})
-		.map_err(<CommonError<T>>::from)?;
-
-		Ok(())
 	}
 
-	/// Batch operation to set multiple properties with the same scope.
-	pub fn set_scoped_token_properties(
-		collection_id: CollectionId,
-		token_id: TokenId,
-		scope: PropertyScope,
-		properties: impl Iterator<Item = Property>,
-	) -> DispatchResult {
-		TokenProperties::<T>::try_mutate((collection_id, token_id), |stored_properties| {
-			stored_properties.try_scoped_set_from_iter(scope, properties)
-		})
-		.map_err(<CommonError<T>>::from)?;
-
-		Ok(())
-	}
-
 	/// Add or edit auxiliary data for the property.
 	///
 	/// - `f`: function that adds or edits auxiliary data.
@@ -1394,7 +1362,9 @@
 
 	pub fn repair_item(collection: &NonfungibleHandle<T>, token: TokenId) -> DispatchResult {
 		<TokenProperties<T>>::mutate((collection.id, token), |properties| {
-			properties.recompute_consumed_space();
+			if let Some(properties) = properties {
+				properties.recompute_consumed_space();
+			}
 		});
 
 		Ok(())
modifiedpallets/refungible/src/common.rsdiffbeforeafterboth
--- a/pallets/refungible/src/common.rs
+++ b/pallets/refungible/src/common.rs
@@ -435,16 +435,15 @@
 		)
 	}
 
-	fn get_token_properties_map(&self, token_id: TokenId) -> up_data_structs::TokenProperties {
+	fn get_token_properties_raw(
+		&self,
+		token_id: TokenId,
+	) -> Option<up_data_structs::TokenProperties> {
 		<TokenProperties<T>>::get((self.id, token_id))
 	}
 
-	fn set_token_properties_map(&self, token_id: TokenId, map: up_data_structs::TokenProperties) {
-		<TokenProperties<T>>::set((self.id, token_id), map)
-	}
-
-	fn properties_exist(&self, token: TokenId) -> bool {
-		<TokenProperties<T>>::contains_key((self.id, token))
+	fn set_token_properties_raw(&self, token_id: TokenId, map: up_data_structs::TokenProperties) {
+		<TokenProperties<T>>::insert((self.id, token_id), map)
 	}
 
 	fn check_nesting(
@@ -514,13 +513,15 @@
 	}
 
 	fn token_property(&self, token_id: TokenId, key: &PropertyKey) -> Option<PropertyValue> {
-		<Pallet<T>>::token_properties((self.id, token_id))
+		<Pallet<T>>::token_properties((self.id, token_id))?
 			.get(key)
 			.cloned()
 	}
 
 	fn token_properties(&self, token_id: TokenId, keys: Option<Vec<PropertyKey>>) -> Vec<Property> {
-		let properties = <Pallet<T>>::token_properties((self.id, token_id));
+		let Some(properties) = <Pallet<T>>::token_properties((self.id, token_id)) else {
+			return vec![];
+		};
 
 		keys.map(|keys| {
 			keys.into_iter()
modifiedpallets/refungible/src/erc.rsdiffbeforeafterboth
--- a/pallets/refungible/src/erc.rs
+++ b/pallets/refungible/src/erc.rs
@@ -283,7 +283,8 @@
 			.try_into()
 			.map_err(|_| "key too long")?;
 
-		let props = <TokenProperties<T>>::get((self.id, token_id));
+		let props =
+			<TokenProperties<T>>::get((self.id, token_id)).ok_or("Token properties not found")?;
 		let prop = props.get(&key).ok_or("key not found")?;
 
 		Ok(prop.to_vec().into())
modifiedpallets/refungible/src/lib.rsdiffbeforeafterboth
before · pallets/refungible/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//! # Refungible Pallet18//!19//! The Refungible pallet provides functionality for handling refungible collections and tokens.20//!21//! - [`Config`]22//! - [`RefungibleHandle`]23//! - [`Pallet`]24//! - [`CommonWeights`](common::CommonWeights)25//!26//! ## Overview27//!28//! The Refungible pallet provides functions for:29//!30//! - RFT collection creation and removal31//! - Minting and burning of RFT tokens32//! - Partition and repartition of RFT tokens33//! - Retrieving number of pieces of RFT token34//! - Retrieving account balances35//! - Transfering RFT token pieces36//! - Burning RFT token pieces37//! - Setting and checking allowance for RFT tokens38//!39//! ### Terminology40//!41//! - **RFT token:** Non fungible token that was partitioned to pieces. If an account owns all42//!   of the RFT token pieces than it owns the RFT token and can repartition it.43//!44//! - **RFT Collection:** A collection of RFT tokens. All RFT tokens are part of a collection.45//!   Each collection has its own settings and set of permissions.46//!47//! - **RFT token piece:** A fungible part of an RFT token.48//!49//! - **Balance:** RFT token pieces owned by an account50//!51//! - **Allowance:** Maximum number of RFT token pieces that one account is allowed to52//!   transfer from the balance of another account53//!54//! - **Burning:** The process of “deleting” a token from a collection or removing token pieces from55//!   an account balance.56//!57//! ### Implementations58//!59//! The Refungible pallet provides implementations for the following traits. If these traits provide60//! the functionality that you need, then you can avoid coupling with the Refungible pallet.61//!62//! - [`CommonWeightInfo`](pallet_common::CommonWeightInfo): Functions for retrieval of transaction weight63//! - [`CommonCollectionOperations`](pallet_common::CommonCollectionOperations): Functions for dealing64//!   with collections65//! - [`RefungibleExtensions`](pallet_common::RefungibleExtensions): Functions specific for refungible66//!   collection67//!68//! ## Interface69//!70//! ### Dispatchable Functions71//!72//! - `init_collection` - Create RFT collection. RFT collection can be configured to allow or deny access for73//!   some accounts.74//! - `destroy_collection` - Destroy exising RFT collection. There should be no tokens in the collection.75//! - `burn` - Burn some amount of RFT token pieces owned by account. Burns the RFT token if no pieces left.76//! - `transfer` - Transfer some amount of RFT token pieces. Transfers should be enabled for RFT collection.77//!   Nests the RFT token if RFT token pieces are sent to another token.78//! - `create_item` - Mint RFT token in collection. Sender should have permission to mint tokens.79//! - `set_allowance` - Set allowance for another account to transfer balance from sender's account.80//! - `repartition` - Repartition token to selected number of pieces. Sender should own all existing pieces.81//!82//! ## Assumptions83//!84//! * Total number of pieces for one token shouldn't exceed `up_data_structs::MAX_REFUNGIBLE_PIECES`.85//! * Total number of tokens of all types shouldn't be greater than `up_data_structs::MAX_TOKEN_PREFIX_LENGTH`.86//! * Sender should be in collection's allow list to perform operations on tokens.8788#![cfg_attr(not(feature = "std"), no_std)]8990use crate::erc_token::ERC20Events;91use crate::erc::ERC721Events;9293use core::{ops::Deref, cmp::Ordering};94use evm_coder::ToLog;95use frame_support::{ensure, storage::with_transaction, transactional};96use pallet_evm::{account::CrossAccountId, Pallet as PalletEvm};97use pallet_evm_coder_substrate::WithRecorder;98use pallet_common::{99	Error as CommonError, eth::collection_id_to_address, Event as CommonEvent,100	Pallet as PalletCommon,101};102use pallet_structure::Pallet as PalletStructure;103use sp_core::{Get, H160};104use sp_runtime::{ArithmeticError, DispatchError, DispatchResult, TransactionOutcome};105use sp_std::{vec::Vec, vec, collections::btree_map::BTreeMap};106use up_data_structs::{107	AccessMode, budget::Budget, CollectionId, CreateCollectionData, mapping::TokenAddressMapping,108	MAX_REFUNGIBLE_PIECES, Property, PropertyKey, PropertyKeyPermission, PropertyScope,109	PropertyValue, TokenId, TrySetProperty, PropertiesPermissionMap,110	CreateRefungibleExMultipleOwners, TokenOwnerError, TokenProperties as TokenPropertiesT,111};112113pub use pallet::*;114#[cfg(feature = "runtime-benchmarks")]115pub mod benchmarking;116pub mod common;117pub mod erc;118pub mod erc_token;119pub mod weights;120121pub type CreateItemData<T> =122	CreateRefungibleExMultipleOwners<<T as pallet_evm::Config>::CrossAccountId>;123pub(crate) type SelfWeightOf<T> = <T as Config>::WeightInfo;124125#[frame_support::pallet]126pub mod pallet {127	use super::*;128	use frame_support::{129		Blake2_128, Blake2_128Concat, Twox64Concat, pallet_prelude::*, storage::Key,130		traits::StorageVersion,131	};132	use up_data_structs::{CollectionId, TokenId};133	use super::weights::WeightInfo;134135	#[pallet::error]136	pub enum Error<T> {137		/// Not Refungible item data used to mint in Refungible collection.138		NotRefungibleDataUsedToMintFungibleCollectionToken,139		/// Maximum refungibility exceeded.140		WrongRefungiblePieces,141		/// Refungible token can't be repartitioned by user who isn't owns all pieces.142		RepartitionWhileNotOwningAllPieces,143		/// Refungible token can't nest other tokens.144		RefungibleDisallowsNesting,145		/// Setting item properties is not allowed.146		SettingPropertiesNotAllowed,147	}148149	#[pallet::config]150	pub trait Config:151		frame_system::Config + pallet_common::Config + pallet_structure::Config152	{153		type WeightInfo: WeightInfo;154	}155156	const STORAGE_VERSION: StorageVersion = StorageVersion::new(2);157158	#[pallet::pallet]159	#[pallet::storage_version(STORAGE_VERSION)]160	pub struct Pallet<T>(_);161162	/// Total amount of minted tokens in a collection.163	#[pallet::storage]164	pub type TokensMinted<T: Config> =165		StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;166167	/// Amount of tokens burnt in a collection.168	#[pallet::storage]169	pub type TokensBurnt<T: Config> =170		StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;171172	/// Amount of pieces a refungible token is split into.173	#[pallet::storage]174	#[pallet::getter(fn token_properties)]175	pub type TokenProperties<T: Config> = StorageNMap<176		Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),177		Value = TokenPropertiesT,178		QueryKind = ValueQuery,179	>;180181	/// Total amount of pieces for token182	#[pallet::storage]183	pub type TotalSupply<T: Config> = StorageNMap<184		Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),185		Value = u128,186		QueryKind = ValueQuery,187	>;188189	/// Used to enumerate tokens owned by account.190	#[pallet::storage]191	pub type Owned<T: Config> = StorageNMap<192		Key = (193			Key<Twox64Concat, CollectionId>,194			Key<Blake2_128Concat, T::CrossAccountId>,195			Key<Twox64Concat, TokenId>,196		),197		Value = bool,198		QueryKind = ValueQuery,199	>;200201	/// Amount of tokens (not pieces) partially owned by an account within a collection.202	#[pallet::storage]203	pub type AccountBalance<T: Config> = StorageNMap<204		Key = (205			Key<Twox64Concat, CollectionId>,206			// Owner207			Key<Blake2_128Concat, T::CrossAccountId>,208		),209		Value = u32,210		QueryKind = ValueQuery,211	>;212213	/// Amount of token pieces owned by account.214	#[pallet::storage]215	pub type Balance<T: Config> = StorageNMap<216		Key = (217			Key<Twox64Concat, CollectionId>,218			Key<Twox64Concat, TokenId>,219			// Owner220			Key<Blake2_128Concat, T::CrossAccountId>,221		),222		Value = u128,223		QueryKind = ValueQuery,224	>;225226	/// Allowance set by a token owner for another user to perform one of certain transactions on a number of pieces of a token.227	#[pallet::storage]228	pub type Allowance<T: Config> = StorageNMap<229		Key = (230			Key<Twox64Concat, CollectionId>,231			Key<Twox64Concat, TokenId>,232			// Owner233			Key<Blake2_128, T::CrossAccountId>,234			// Spender235			Key<Blake2_128Concat, T::CrossAccountId>,236		),237		Value = u128,238		QueryKind = ValueQuery,239	>;240241	/// Spender set by a wallet owner that could perform certain transactions on all tokens in the wallet.242	#[pallet::storage]243	pub type CollectionAllowance<T: Config> = StorageNMap<244		Key = (245			Key<Twox64Concat, CollectionId>,246			Key<Blake2_128Concat, T::CrossAccountId>, // Owner247			Key<Blake2_128Concat, T::CrossAccountId>, // Spender248		),249		Value = bool,250		QueryKind = ValueQuery,251	>;252}253254pub struct RefungibleHandle<T: Config>(pallet_common::CollectionHandle<T>);255impl<T: Config> RefungibleHandle<T> {256	pub fn cast(inner: pallet_common::CollectionHandle<T>) -> Self {257		Self(inner)258	}259	pub fn into_inner(self) -> pallet_common::CollectionHandle<T> {260		self.0261	}262	pub fn common_mut(&mut self) -> &mut pallet_common::CollectionHandle<T> {263		&mut self.0264	}265}266267impl<T: Config> Deref for RefungibleHandle<T> {268	type Target = pallet_common::CollectionHandle<T>;269270	fn deref(&self) -> &Self::Target {271		&self.0272	}273}274275impl<T: Config> WithRecorder<T> for RefungibleHandle<T> {276	fn recorder(&self) -> &pallet_evm_coder_substrate::SubstrateRecorder<T> {277		self.0.recorder()278	}279	fn into_recorder(self) -> pallet_evm_coder_substrate::SubstrateRecorder<T> {280		self.0.into_recorder()281	}282}283284impl<T: Config> Pallet<T> {285	/// Get number of RFT tokens in collection286	pub fn total_supply(collection: &RefungibleHandle<T>) -> u32 {287		<TokensMinted<T>>::get(collection.id) - <TokensBurnt<T>>::get(collection.id)288	}289290	/// Check that RFT token exists291	///292	/// - `token`: Token ID.293	pub fn token_exists(collection: &RefungibleHandle<T>, token: TokenId) -> bool {294		<TotalSupply<T>>::contains_key((collection.id, token))295	}296297	pub fn set_scoped_token_property(298		collection_id: CollectionId,299		token_id: TokenId,300		scope: PropertyScope,301		property: Property,302	) -> DispatchResult {303		TokenProperties::<T>::try_mutate((collection_id, token_id), |properties| {304			properties.try_scoped_set(scope, property.key, property.value)305		})306		.map_err(<CommonError<T>>::from)?;307308		Ok(())309	}310311	pub fn set_scoped_token_properties(312		collection_id: CollectionId,313		token_id: TokenId,314		scope: PropertyScope,315		properties: impl Iterator<Item = Property>,316	) -> DispatchResult {317		TokenProperties::<T>::try_mutate((collection_id, token_id), |stored_properties| {318			stored_properties.try_scoped_set_from_iter(scope, properties)319		})320		.map_err(<CommonError<T>>::from)?;321322		Ok(())323	}324}325326// unchecked calls skips any permission checks327impl<T: Config> Pallet<T> {328	/// Create RFT collection329	///330	/// `init_collection` will take non-refundable deposit for collection creation.331	///332	/// - `data`: Contains settings for collection limits and permissions.333	pub fn init_collection(334		owner: T::CrossAccountId,335		payer: T::CrossAccountId,336		data: CreateCollectionData<T::CrossAccountId>,337	) -> Result<CollectionId, DispatchError> {338		<PalletCommon<T>>::init_collection(owner, payer, data)339	}340341	/// Destroy RFT collection342	///343	/// `destroy_collection` will throw error if collection contains any tokens.344	/// Only owner can destroy collection.345	pub fn destroy_collection(346		collection: RefungibleHandle<T>,347		sender: &T::CrossAccountId,348	) -> DispatchResult {349		let id = collection.id;350351		if Self::collection_has_tokens(id) {352			return Err(<CommonError<T>>::CantDestroyNotEmptyCollection.into());353		}354355		// =========356357		PalletCommon::destroy_collection(collection.0, sender)?;358359		<TokensMinted<T>>::remove(id);360		<TokensBurnt<T>>::remove(id);361		let _ = <TotalSupply<T>>::clear_prefix((id,), u32::MAX, None);362		let _ = <Balance<T>>::clear_prefix((id,), u32::MAX, None);363		let _ = <Allowance<T>>::clear_prefix((id,), u32::MAX, None);364		let _ = <Owned<T>>::clear_prefix((id,), u32::MAX, None);365		let _ = <AccountBalance<T>>::clear_prefix((id,), u32::MAX, None);366		Ok(())367	}368369	fn collection_has_tokens(collection_id: CollectionId) -> bool {370		<TotalSupply<T>>::iter_prefix((collection_id,))371			.next()372			.is_some()373	}374375	pub fn burn_token_unchecked(376		collection: &RefungibleHandle<T>,377		owner: &T::CrossAccountId,378		token_id: TokenId,379	) -> DispatchResult {380		let burnt = <TokensBurnt<T>>::get(collection.id)381			.checked_add(1)382			.ok_or(ArithmeticError::Overflow)?;383384		<TokensBurnt<T>>::insert(collection.id, burnt);385		<TokenProperties<T>>::remove((collection.id, token_id));386		<TotalSupply<T>>::remove((collection.id, token_id));387		let _ = <Balance<T>>::clear_prefix((collection.id, token_id), u32::MAX, None);388		let _ = <Allowance<T>>::clear_prefix((collection.id, token_id), u32::MAX, None);389		<PalletEvm<T>>::deposit_log(390			ERC721Events::Transfer {391				from: *owner.as_eth(),392				to: H160::default(),393				token_id: token_id.into(),394			}395			.to_log(collection_id_to_address(collection.id)),396		);397		Ok(())398	}399400	/// Burn RFT token pieces401	///402	/// `burn` will decrease total amount of token pieces and amount owned by sender.403	/// `burn` can be called even if there are multiple owners of the RFT token.404	/// If sender wouldn't have any pieces left after `burn` than she will stop being405	/// one of the owners of the token. If there is no account that owns any pieces of406	/// the token than token will be burned too.407	///408	/// - `amount`: Amount of token pieces to burn.409	/// - `token`: Token who's pieces should be burned410	/// - `collection`: Collection that contains the token411	pub fn burn(412		collection: &RefungibleHandle<T>,413		owner: &T::CrossAccountId,414		token: TokenId,415		amount: u128,416	) -> DispatchResult {417		if <Balance<T>>::get((collection.id, token, owner)) == 0 {418			return Err(<CommonError<T>>::TokenValueTooLow.into());419		}420421		let total_supply = <TotalSupply<T>>::get((collection.id, token))422			.checked_sub(amount)423			.ok_or(<CommonError<T>>::TokenValueTooLow)?;424425		// This was probally last owner of this token?426		if total_supply == 0 {427			// Ensure user actually owns this amount428			ensure!(429				<Balance<T>>::get((collection.id, token, owner)) == amount,430				<CommonError<T>>::TokenValueTooLow431			);432			let account_balance = <AccountBalance<T>>::get((collection.id, owner))433				.checked_sub(1)434				// Should not occur435				.ok_or(ArithmeticError::Underflow)?;436437			// =========438439			<Owned<T>>::remove((collection.id, owner, token));440			<PalletStructure<T>>::unnest_if_nested(owner, collection.id, token);441			<AccountBalance<T>>::insert((collection.id, owner), account_balance);442			Self::burn_token_unchecked(collection, owner, token)?;443			<PalletEvm<T>>::deposit_log(444				ERC20Events::Transfer {445					from: *owner.as_eth(),446					to: H160::default(),447					value: amount.into(),448				}449				.to_log(collection_id_to_address(collection.id)),450			);451			<PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(452				collection.id,453				token,454				owner.clone(),455				amount,456			));457			return Ok(());458		}459460		let balance = <Balance<T>>::get((collection.id, token, owner))461			.checked_sub(amount)462			.ok_or(<CommonError<T>>::TokenValueTooLow)?;463		let account_balance = if balance == 0 {464			<AccountBalance<T>>::get((collection.id, owner))465				.checked_sub(1)466				// Should not occur467				.ok_or(ArithmeticError::Underflow)?468		} else {469			0470		};471472		// =========473474		if balance == 0 {475			<Owned<T>>::remove((collection.id, owner, token));476			<PalletStructure<T>>::unnest_if_nested(owner, collection.id, token);477			<Balance<T>>::remove((collection.id, token, owner));478			<AccountBalance<T>>::insert((collection.id, owner), account_balance);479480			if let Ok(user) = Self::token_owner(collection.id, token) {481				<PalletEvm<T>>::deposit_log(482					ERC721Events::Transfer {483						from: erc::ADDRESS_FOR_PARTIALLY_OWNED_TOKENS,484						to: *user.as_eth(),485						token_id: token.into(),486					}487					.to_log(collection_id_to_address(collection.id)),488				);489			}490		} else {491			<Balance<T>>::insert((collection.id, token, owner), balance);492		}493		<TotalSupply<T>>::insert((collection.id, token), total_supply);494495		<PalletEvm<T>>::deposit_log(496			ERC20Events::Transfer {497				from: *owner.as_eth(),498				to: H160::default(),499				value: amount.into(),500			}501			.to_log(T::EvmTokenAddressMapping::token_to_address(502				collection.id,503				token,504			)),505		);506		<PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(507			collection.id,508			token,509			owner.clone(),510			amount,511		));512		Ok(())513	}514515	/// A batch operation to add, edit or remove properties for a token.516	/// It sets or removes a token's properties according to517	/// `properties_updates` contents:518	/// * sets a property under the <key> with the value provided `(<key>, Some(<value>))`519	/// * removes a property under the <key> if the value is `None` `(<key>, None)`.520	///521	/// - `nesting_budget`: Limit for searching parents in-depth to check ownership.522	///523	/// All affected properties should have `mutable` permission524	/// to be **deleted** or to be **set more than once**,525	/// and the sender should have permission to edit those properties.526	///527	/// This function fires an event for each property change.528	/// In case of an error, all the changes (including the events) will be reverted529	/// since the function is transactional.530	#[transactional]531	fn modify_token_properties(532		collection: &RefungibleHandle<T>,533		sender: &T::CrossAccountId,534		token_id: TokenId,535		properties_updates: impl Iterator<Item = (PropertyKey, Option<PropertyValue>)>,536		nesting_budget: &dyn Budget,537	) -> DispatchResult {538		let mut property_writer =539			pallet_common::property_writer_for_existing_token(collection, sender);540541		property_writer.write_token_properties(542			sender,543			token_id,544			properties_updates,545			nesting_budget,546			erc::ERC721TokenEvent::TokenChanged {547				token_id: token_id.into(),548			}549			.to_log(T::ContractAddress::get()),550		)551	}552553	pub fn next_token_id(collection: &RefungibleHandle<T>) -> Result<TokenId, DispatchError> {554		let next_token_id = <TokensMinted<T>>::get(collection.id)555			.checked_add(1)556			.ok_or(<CommonError<T>>::CollectionTokenLimitExceeded)?;557558		ensure!(559			collection.limits.token_limit() >= next_token_id,560			<CommonError<T>>::CollectionTokenLimitExceeded561		);562563		Ok(TokenId(next_token_id))564	}565566	pub fn set_token_properties(567		collection: &RefungibleHandle<T>,568		sender: &T::CrossAccountId,569		token_id: TokenId,570		properties: impl Iterator<Item = Property>,571		nesting_budget: &dyn Budget,572	) -> DispatchResult {573		Self::modify_token_properties(574			collection,575			sender,576			token_id,577			properties.map(|p| (p.key, Some(p.value))),578			nesting_budget,579		)580	}581582	pub fn set_token_property(583		collection: &RefungibleHandle<T>,584		sender: &T::CrossAccountId,585		token_id: TokenId,586		property: Property,587		nesting_budget: &dyn Budget,588	) -> DispatchResult {589		Self::set_token_properties(590			collection,591			sender,592			token_id,593			[property].into_iter(),594			nesting_budget,595		)596	}597598	pub fn delete_token_properties(599		collection: &RefungibleHandle<T>,600		sender: &T::CrossAccountId,601		token_id: TokenId,602		property_keys: impl Iterator<Item = PropertyKey>,603		nesting_budget: &dyn Budget,604	) -> DispatchResult {605		Self::modify_token_properties(606			collection,607			sender,608			token_id,609			property_keys.into_iter().map(|key| (key, None)),610			nesting_budget,611		)612	}613614	pub fn delete_token_property(615		collection: &RefungibleHandle<T>,616		sender: &T::CrossAccountId,617		token_id: TokenId,618		property_key: PropertyKey,619		nesting_budget: &dyn Budget,620	) -> DispatchResult {621		Self::delete_token_properties(622			collection,623			sender,624			token_id,625			[property_key].into_iter(),626			nesting_budget,627		)628	}629630	/// Transfer RFT token pieces from one account to another.631	///632	/// If the sender is no longer owns any pieces after the `transfer` than she stops being an owner of the token.633	///634	/// - `from`: Owner of token pieces to transfer.635	/// - `to`: Recepient of transfered token pieces.636	/// - `amount`: Amount of token pieces to transfer.637	/// - `token`: Token whos pieces should be transfered638	/// - `collection`: Collection that contains the token639	pub fn transfer(640		collection: &RefungibleHandle<T>,641		from: &T::CrossAccountId,642		to: &T::CrossAccountId,643		token: TokenId,644		amount: u128,645		nesting_budget: &dyn Budget,646	) -> DispatchResult {647		ensure!(648			collection.limits.transfers_enabled(),649			<CommonError<T>>::TransferNotAllowed650		);651652		if collection.permissions.access() == AccessMode::AllowList {653			collection.check_allowlist(from)?;654			collection.check_allowlist(to)?;655		}656		<PalletCommon<T>>::ensure_correct_receiver(to)?;657658		let initial_balance_from = <Balance<T>>::get((collection.id, token, from));659660		if initial_balance_from == 0 {661			return Err(<CommonError<T>>::TokenValueTooLow.into());662		}663664		let updated_balance_from = initial_balance_from665			.checked_sub(amount)666			.ok_or(<CommonError<T>>::TokenValueTooLow)?;667		let mut create_target = false;668		let from_to_differ = from != to;669		let updated_balance_to = if from != to && amount != 0 {670			let old_balance = <Balance<T>>::get((collection.id, token, to));671			if old_balance == 0 {672				create_target = true;673			}674			Some(675				old_balance676					.checked_add(amount)677					.ok_or(ArithmeticError::Overflow)?,678			)679		} else {680			None681		};682683		let account_balance_from = if updated_balance_from == 0 {684			Some(685				<AccountBalance<T>>::get((collection.id, from))686					.checked_sub(1)687					// Should not occur688					.ok_or(ArithmeticError::Underflow)?,689			)690		} else {691			None692		};693		// Account data is created in token, AccountBalance should be increased694		// But only if from != to as we shouldn't check overflow in this case695		let account_balance_to = if create_target && from_to_differ {696			let account_balance_to = <AccountBalance<T>>::get((collection.id, to))697				.checked_add(1)698				.ok_or(ArithmeticError::Overflow)?;699			ensure!(700				account_balance_to < collection.limits.account_token_ownership_limit(),701				<CommonError<T>>::AccountTokenLimitExceeded,702			);703704			Some(account_balance_to)705		} else {706			None707		};708709		// =========710711		if let Some(updated_balance_to) = updated_balance_to {712			// from != to && amount != 0713714			<PalletStructure<T>>::nest_if_sent_to_token(715				from.clone(),716				to,717				collection.id,718				token,719				nesting_budget,720			)?;721722			if updated_balance_from == 0 {723				<Balance<T>>::remove((collection.id, token, from));724				<PalletStructure<T>>::unnest_if_nested(from, collection.id, token);725			} else {726				<Balance<T>>::insert((collection.id, token, from), updated_balance_from);727			}728			<Balance<T>>::insert((collection.id, token, to), updated_balance_to);729			if let Some(account_balance_from) = account_balance_from {730				<AccountBalance<T>>::insert((collection.id, from), account_balance_from);731				<Owned<T>>::remove((collection.id, from, token));732			}733			if let Some(account_balance_to) = account_balance_to {734				<AccountBalance<T>>::insert((collection.id, to), account_balance_to);735				<Owned<T>>::insert((collection.id, to, token), true);736			}737		}738739		<PalletEvm<T>>::deposit_log(740			ERC20Events::Transfer {741				from: *from.as_eth(),742				to: *to.as_eth(),743				value: amount.into(),744			}745			.to_log(T::EvmTokenAddressMapping::token_to_address(746				collection.id,747				token,748			)),749		);750751		<PalletCommon<T>>::deposit_event(CommonEvent::Transfer(752			collection.id,753			token,754			from.clone(),755			to.clone(),756			amount,757		));758759		let total_supply = <TotalSupply<T>>::get((collection.id, token));760761		if amount == total_supply {762			// if token was fully owned by `from` and will be fully owned by `to` after transfer763			<PalletEvm<T>>::deposit_log(764				ERC721Events::Transfer {765					from: *from.as_eth(),766					to: *to.as_eth(),767					token_id: token.into(),768				}769				.to_log(collection_id_to_address(collection.id)),770			);771		} else if let Some(updated_balance_to) = updated_balance_to {772			// if `from` not equals `to`. This condition is needed to avoid sending event773			// when `from` fully owns token and sends part of token pieces to itself.774			if initial_balance_from == total_supply {775				// if token was fully owned by `from` and will be only partially owned by `to`776				// and `from` after transfer777				<PalletEvm<T>>::deposit_log(778					ERC721Events::Transfer {779						from: *from.as_eth(),780						to: erc::ADDRESS_FOR_PARTIALLY_OWNED_TOKENS,781						token_id: token.into(),782					}783					.to_log(collection_id_to_address(collection.id)),784				);785			} else if updated_balance_to == total_supply {786				// if token was partially owned by `from` and will be fully owned by `to` after transfer787				<PalletEvm<T>>::deposit_log(788					ERC721Events::Transfer {789						from: erc::ADDRESS_FOR_PARTIALLY_OWNED_TOKENS,790						to: *to.as_eth(),791						token_id: token.into(),792					}793					.to_log(collection_id_to_address(collection.id)),794				);795			}796		}797798		Ok(())799	}800801	/// Batched operation to create multiple RFT tokens.802	///803	/// Same as `create_item` but creates multiple tokens.804	///805	/// - `data`: Same as 'data` in `create_item` but contains data for multiple tokens.806	pub fn create_multiple_items(807		collection: &RefungibleHandle<T>,808		sender: &T::CrossAccountId,809		data: Vec<CreateItemData<T>>,810		nesting_budget: &dyn Budget,811	) -> DispatchResult {812		if !collection.is_owner_or_admin(sender) {813			ensure!(814				collection.permissions.mint_mode(),815				<CommonError<T>>::PublicMintingNotAllowed816			);817			collection.check_allowlist(sender)?;818819			for item in data.iter() {820				for user in item.users.keys() {821					collection.check_allowlist(user)?;822				}823			}824		}825826		for item in data.iter() {827			for (owner, _) in item.users.iter() {828				<PalletCommon<T>>::ensure_correct_receiver(owner)?;829			}830		}831832		// Total pieces per tokens833		let totals = data834			.iter()835			.map(|data| {836				Ok(data837					.users838					.iter()839					.map(|u| u.1)840					.try_fold(0u128, |acc, v| acc.checked_add(*v))841					.ok_or(ArithmeticError::Overflow)?)842			})843			.collect::<Result<Vec<_>, DispatchError>>()?;844		for total in &totals {845			ensure!(846				*total <= MAX_REFUNGIBLE_PIECES,847				<Error<T>>::WrongRefungiblePieces848			);849		}850851		let first_token_id = <TokensMinted<T>>::get(collection.id);852		let tokens_minted = first_token_id853			.checked_add(data.len() as u32)854			.ok_or(ArithmeticError::Overflow)?;855		ensure!(856			tokens_minted < collection.limits.token_limit(),857			<CommonError<T>>::CollectionTokenLimitExceeded858		);859860		let mut balances = BTreeMap::new();861		for data in &data {862			for owner in data.users.keys() {863				let balance = balances864					.entry(owner)865					.or_insert_with(|| <AccountBalance<T>>::get((collection.id, owner)));866				*balance = balance.checked_add(1).ok_or(ArithmeticError::Overflow)?;867868				ensure!(869					*balance <= collection.limits.account_token_ownership_limit(),870					<CommonError<T>>::AccountTokenLimitExceeded,871				);872			}873		}874875		for (i, token) in data.iter().enumerate() {876			let token_id = TokenId(first_token_id + i as u32 + 1);877			for (to, _) in token.users.iter() {878				<PalletStructure<T>>::check_nesting(879					sender.clone(),880					to,881					collection.id,882					token_id,883					nesting_budget,884				)?;885			}886		}887888		// =========889890		let mut property_writer = pallet_common::property_writer_for_new_token(collection, sender);891892		with_transaction(|| {893			for (i, data) in data.iter().enumerate() {894				let token_id = first_token_id + i as u32 + 1;895				<TotalSupply<T>>::insert((collection.id, token_id), totals[i]);896897				let token = TokenId(token_id);898899				let mut mint_target_is_sender = true;900				for (user, amount) in data.users.iter() {901					if *amount == 0 {902						continue;903					}904905					mint_target_is_sender = mint_target_is_sender && sender.conv_eq(user);906907					<Balance<T>>::insert((collection.id, token_id, &user), amount);908					<Owned<T>>::insert((collection.id, &user, token), true);909					<PalletStructure<T>>::nest_if_sent_to_token_unchecked(910						user,911						collection.id,912						token,913					);914				}915916				if let Err(e) = property_writer.write_token_properties(917					mint_target_is_sender,918					token,919					data.properties.clone().into_iter(),920					erc::ERC721TokenEvent::TokenChanged {921						token_id: token.into(),922					}923					.to_log(T::ContractAddress::get()),924				) {925					return TransactionOutcome::Rollback(Err(e));926				}927			}928			TransactionOutcome::Commit(Ok(()))929		})?;930931		<TokensMinted<T>>::insert(collection.id, tokens_minted);932933		for (account, balance) in balances {934			<AccountBalance<T>>::insert((collection.id, account), balance);935		}936937		for (i, token) in data.into_iter().enumerate() {938			let token_id = first_token_id + i as u32 + 1;939940			let receivers = token941				.users942				.into_iter()943				.filter(|(_, amount)| *amount > 0)944				.collect::<Vec<_>>();945946			if let [(user, _)] = receivers.as_slice() {947				// if there is exactly one receiver948				<PalletEvm<T>>::deposit_log(949					ERC721Events::Transfer {950						from: H160::default(),951						to: *user.as_eth(),952						token_id: token_id.into(),953					}954					.to_log(collection_id_to_address(collection.id)),955				);956			} else if let [_, ..] = receivers.as_slice() {957				// if there is more than one receiver958				<PalletEvm<T>>::deposit_log(959					ERC721Events::Transfer {960						from: H160::default(),961						to: erc::ADDRESS_FOR_PARTIALLY_OWNED_TOKENS,962						token_id: token_id.into(),963					}964					.to_log(collection_id_to_address(collection.id)),965				);966			}967968			for (user, amount) in receivers.into_iter() {969				<PalletEvm<T>>::deposit_log(970					ERC20Events::Transfer {971						from: H160::default(),972						to: *user.as_eth(),973						value: amount.into(),974					}975					.to_log(T::EvmTokenAddressMapping::token_to_address(976						collection.id,977						TokenId(token_id),978					)),979				);980				<PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(981					collection.id,982					TokenId(token_id),983					user,984					amount,985				));986			}987		}988		Ok(())989	}990991	pub fn set_allowance_unchecked(992		collection: &RefungibleHandle<T>,993		sender: &T::CrossAccountId,994		spender: &T::CrossAccountId,995		token: TokenId,996		amount: u128,997	) {998		if amount == 0 {999			<Allowance<T>>::remove((collection.id, token, sender, spender));1000		} else {1001			<Allowance<T>>::insert((collection.id, token, sender, spender), amount);1002		}10031004		<PalletEvm<T>>::deposit_log(1005			ERC20Events::Approval {1006				owner: *sender.as_eth(),1007				spender: *spender.as_eth(),1008				value: amount.into(),1009			}1010			.to_log(T::EvmTokenAddressMapping::token_to_address(1011				collection.id,1012				token,1013			)),1014		);1015		<PalletCommon<T>>::deposit_event(CommonEvent::Approved(1016			collection.id,1017			token,1018			sender.clone(),1019			spender.clone(),1020			amount,1021		))1022	}10231024	/// Set allowance for the spender to `transfer` or `burn` sender's token pieces.1025	///1026	/// - `amount`: Amount of token pieces the spender is allowed to `transfer` or `burn.1027	pub fn set_allowance(1028		collection: &RefungibleHandle<T>,1029		sender: &T::CrossAccountId,1030		spender: &T::CrossAccountId,1031		token: TokenId,1032		amount: u128,1033	) -> DispatchResult {1034		if collection.permissions.access() == AccessMode::AllowList {1035			collection.check_allowlist(sender)?;1036			collection.check_allowlist(spender)?;1037		}10381039		<PalletCommon<T>>::ensure_correct_receiver(spender)?;10401041		if <Balance<T>>::get((collection.id, token, sender)) < amount {1042			ensure!(1043				collection.ignores_owned_amount(sender) && Self::token_exists(collection, token),1044				<CommonError<T>>::CantApproveMoreThanOwned1045			);1046		}10471048		// =========10491050		Self::set_allowance_unchecked(collection, sender, spender, token, amount);1051		Ok(())1052	}10531054	/// Set allowance to spend from sender's eth mirror1055	///1056	/// - `from`: Address of sender's eth mirror.1057	/// - `to`: Adress of spender.1058	/// - `amount`: Amount of token pieces the spender is allowed to `transfer` or `burn.1059	pub fn set_allowance_from(1060		collection: &RefungibleHandle<T>,1061		sender: &T::CrossAccountId,1062		from: &T::CrossAccountId,1063		to: &T::CrossAccountId,1064		token_id: TokenId,1065		amount: u128,1066	) -> DispatchResult {1067		if collection.permissions.access() == AccessMode::AllowList {1068			collection.check_allowlist(sender)?;1069			collection.check_allowlist(from)?;1070			collection.check_allowlist(to)?;1071		}10721073		<PalletCommon<T>>::ensure_correct_receiver(to)?;10741075		ensure!(1076			sender.conv_eq(from),1077			<CommonError<T>>::AddressIsNotEthMirror1078		);10791080		if <Balance<T>>::get((collection.id, token_id, from)) < amount {1081			ensure!(1082				collection.limits.owner_can_transfer()1083					&& (collection.is_owner_or_admin(sender) || collection.is_owner_or_admin(from))1084					&& Self::token_exists(collection, token_id),1085				<CommonError<T>>::CantApproveMoreThanOwned1086			);1087		}10881089		// =========10901091		Self::set_allowance_unchecked(collection, from, to, token_id, amount);1092		Ok(())1093	}10941095	/// Returns allowance, which should be set after transaction1096	fn check_allowed(1097		collection: &RefungibleHandle<T>,1098		spender: &T::CrossAccountId,1099		from: &T::CrossAccountId,1100		token: TokenId,1101		amount: u128,1102		nesting_budget: &dyn Budget,1103	) -> Result<Option<u128>, DispatchError> {1104		if spender.conv_eq(from) {1105			return Ok(None);1106		}1107		if collection.permissions.access() == AccessMode::AllowList {1108			// `from`, `to` checked in [`transfer`]1109			collection.check_allowlist(spender)?;1110		}11111112		if collection.ignores_token_restrictions(spender) {1113			return Ok(Self::compute_allowance_decrease(1114				collection, token, from, spender, amount,1115			));1116		}11171118		if let Some(source) = T::CrossTokenAddressMapping::address_to_token(from) {1119			// TODO: should collection owner be allowed to perform this transfer?1120			ensure!(1121				<PalletStructure<T>>::check_indirectly_owned(1122					spender.clone(),1123					source.0,1124					source.1,1125					None,1126					nesting_budget1127				)?,1128				<CommonError<T>>::ApprovedValueTooLow,1129			);1130			return Ok(None);1131		}11321133		let allowance = Self::compute_allowance_decrease(collection, token, from, spender, amount);1134		if allowance.is_some() {1135			return Ok(allowance);1136		}11371138		// Allowance (if any) would be reduced if spender is also wallet operator1139		if <CollectionAllowance<T>>::get((collection.id, from, spender)) {1140			return Ok(allowance);1141		}11421143		Err(<CommonError<T>>::ApprovedValueTooLow.into())1144	}11451146	/// Returns `Some(amount)` if the `spender` have allowance to spend this amount.1147	/// Otherwise, it returns `None`.1148	fn compute_allowance_decrease(1149		collection: &RefungibleHandle<T>,1150		token: TokenId,1151		from: &T::CrossAccountId,1152		spender: &T::CrossAccountId,1153		amount: u128,1154	) -> Option<u128> {1155		<Allowance<T>>::get((collection.id, token, from, spender)).checked_sub(amount)1156	}11571158	/// Transfer RFT token pieces from one account to another.1159	///1160	/// Same as the [`transfer`] but spender doesn't needs to be an owner of the token pieces.1161	/// The owner should set allowance for the spender to transfer pieces.1162	///1163	/// [`transfer`]: struct.Pallet.html#method.transfer1164	pub fn transfer_from(1165		collection: &RefungibleHandle<T>,1166		spender: &T::CrossAccountId,1167		from: &T::CrossAccountId,1168		to: &T::CrossAccountId,1169		token: TokenId,1170		amount: u128,1171		nesting_budget: &dyn Budget,1172	) -> DispatchResult {1173		let allowance =1174			Self::check_allowed(collection, spender, from, token, amount, nesting_budget)?;11751176		// =========11771178		Self::transfer(collection, from, to, token, amount, nesting_budget)?;1179		if let Some(allowance) = allowance {1180			Self::set_allowance_unchecked(collection, from, spender, token, allowance);1181		}1182		Ok(())1183	}11841185	/// Burn RFT token pieces from the account.1186	///1187	/// Same as the [`burn`] but spender doesn't need to be an owner of the token pieces. The owner should1188	/// set allowance for the spender to burn pieces1189	///1190	/// [`burn`]: struct.Pallet.html#method.burn1191	pub fn burn_from(1192		collection: &RefungibleHandle<T>,1193		spender: &T::CrossAccountId,1194		from: &T::CrossAccountId,1195		token: TokenId,1196		amount: u128,1197		nesting_budget: &dyn Budget,1198	) -> DispatchResult {1199		let allowance =1200			Self::check_allowed(collection, spender, from, token, amount, nesting_budget)?;12011202		// =========12031204		Self::burn(collection, from, token, amount)?;1205		if let Some(allowance) = allowance {1206			Self::set_allowance_unchecked(collection, from, spender, token, allowance);1207		}1208		Ok(())1209	}12101211	/// Create RFT token.1212	///1213	/// The sender should be the owner/admin of the collection or collection should be configured1214	/// to allow public minting.1215	///1216	/// - `data`: Contains list of users who will become the owners of the token pieces and amount1217	///   of token pieces they will receive.1218	pub fn create_item(1219		collection: &RefungibleHandle<T>,1220		sender: &T::CrossAccountId,1221		data: CreateItemData<T>,1222		nesting_budget: &dyn Budget,1223	) -> DispatchResult {1224		Self::create_multiple_items(collection, sender, vec![data], nesting_budget)1225	}12261227	/// Repartition RFT token.1228	///1229	/// `repartition` will set token balance of the sender and total amount of token pieces.1230	/// Sender should own all of the token pieces. `repartition' could be done even if some1231	/// token pieces were burned before.1232	///1233	/// - `amount`: Total amount of token pieces that the token will have after `repartition`.1234	pub fn repartition(1235		collection: &RefungibleHandle<T>,1236		owner: &T::CrossAccountId,1237		token: TokenId,1238		amount: u128,1239	) -> DispatchResult {1240		ensure!(1241			amount <= MAX_REFUNGIBLE_PIECES,1242			<Error<T>>::WrongRefungiblePieces1243		);1244		ensure!(amount > 0, <CommonError<T>>::TokenValueTooLow);1245		// Ensure user owns all pieces1246		let total_pieces = Self::total_pieces(collection.id, token).unwrap_or(u128::MAX);1247		let balance = <Balance<T>>::get((collection.id, token, owner));1248		ensure!(1249			total_pieces == balance,1250			<Error<T>>::RepartitionWhileNotOwningAllPieces1251		);12521253		<Balance<T>>::insert((collection.id, token, owner), amount);1254		<TotalSupply<T>>::insert((collection.id, token), amount);12551256		match total_pieces.cmp(&amount) {1257			Ordering::Less => {1258				let mint_amount = amount - total_pieces;1259				<PalletEvm<T>>::deposit_log(1260					ERC20Events::Transfer {1261						from: H160::default(),1262						to: *owner.as_eth(),1263						value: mint_amount.into(),1264					}1265					.to_log(T::EvmTokenAddressMapping::token_to_address(1266						collection.id,1267						token,1268					)),1269				);1270				<PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(1271					collection.id,1272					token,1273					owner.clone(),1274					mint_amount,1275				));1276			}1277			Ordering::Greater => {1278				let burn_amount = total_pieces - amount;1279				<PalletEvm<T>>::deposit_log(1280					ERC20Events::Transfer {1281						from: *owner.as_eth(),1282						to: H160::default(),1283						value: burn_amount.into(),1284					}1285					.to_log(T::EvmTokenAddressMapping::token_to_address(1286						collection.id,1287						token,1288					)),1289				);1290				<PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(1291					collection.id,1292					token,1293					owner.clone(),1294					burn_amount,1295				));1296			}1297			Ordering::Equal => {}1298		}12991300		Ok(())1301	}13021303	fn token_owner(1304		collection_id: CollectionId,1305		token_id: TokenId,1306	) -> Result<T::CrossAccountId, TokenOwnerError> {1307		let mut owner = None;1308		let mut count = 0;1309		for key in Balance::<T>::iter_key_prefix((collection_id, token_id)) {1310			count += 1;1311			if count > 1 {1312				return Err(TokenOwnerError::MultipleOwners);1313			}1314			owner = Some(key);1315		}1316		owner.ok_or(TokenOwnerError::NotFound)1317	}13181319	fn total_pieces(collection_id: CollectionId, token_id: TokenId) -> Option<u128> {1320		<TotalSupply<T>>::try_get((collection_id, token_id)).ok()1321	}13221323	pub fn set_collection_properties(1324		collection: &RefungibleHandle<T>,1325		sender: &T::CrossAccountId,1326		properties: Vec<Property>,1327	) -> DispatchResult {1328		<PalletCommon<T>>::set_collection_properties(collection, sender, properties.into_iter())1329	}13301331	pub fn delete_collection_properties(1332		collection: &RefungibleHandle<T>,1333		sender: &T::CrossAccountId,1334		property_keys: Vec<PropertyKey>,1335	) -> DispatchResult {1336		<PalletCommon<T>>::delete_collection_properties(1337			collection,1338			sender,1339			property_keys.into_iter(),1340		)1341	}13421343	pub fn set_token_property_permissions(1344		collection: &RefungibleHandle<T>,1345		sender: &T::CrossAccountId,1346		property_permissions: Vec<PropertyKeyPermission>,1347	) -> DispatchResult {1348		<PalletCommon<T>>::set_token_property_permissions(collection, sender, property_permissions)1349	}13501351	pub fn token_property_permission(collection_id: CollectionId) -> PropertiesPermissionMap {1352		<PalletCommon<T>>::property_permissions(collection_id)1353	}13541355	pub fn set_scoped_token_property_permissions(1356		collection: &RefungibleHandle<T>,1357		sender: &T::CrossAccountId,1358		scope: PropertyScope,1359		property_permissions: Vec<PropertyKeyPermission>,1360	) -> DispatchResult {1361		<PalletCommon<T>>::set_scoped_token_property_permissions(1362			collection,1363			sender,1364			scope,1365			property_permissions,1366		)1367	}13681369	/// Returns 10 token in no particular order.1370	///1371	/// There is no direct way to get token holders in ascending order,1372	/// since `iter_prefix` returns values in no particular order.1373	/// Therefore, getting the 10 largest holders with a large value of holders1374	/// can lead to impact memory allocation + sorting with  `n * log (n)`.1375	pub fn token_owners(1376		collection_id: CollectionId,1377		token: TokenId,1378	) -> Option<Vec<T::CrossAccountId>> {1379		let res: Vec<T::CrossAccountId> = <Balance<T>>::iter_prefix((collection_id, token))1380			.map(|(owner, _amount)| owner)1381			.take(10)1382			.collect();13831384		if res.is_empty() {1385			None1386		} else {1387			Some(res)1388		}1389	}13901391	/// Sets or unsets the approval of a given operator.1392	///1393	/// The `operator` is allowed to transfer all token pieces of the `owner` on their behalf.1394	/// - `owner`: Token owner1395	/// - `operator`: Operator1396	/// - `approve`: Should operator status be granted or revoked?1397	pub fn set_allowance_for_all(1398		collection: &RefungibleHandle<T>,1399		owner: &T::CrossAccountId,1400		spender: &T::CrossAccountId,1401		approve: bool,1402	) -> DispatchResult {1403		<PalletCommon<T>>::set_allowance_for_all(1404			collection,1405			owner,1406			spender,1407			approve,1408			|| <CollectionAllowance<T>>::insert((collection.id, owner, spender), approve),1409			ERC721Events::ApprovalForAll {1410				owner: *owner.as_eth(),1411				operator: *spender.as_eth(),1412				approved: approve,1413			}1414			.to_log(collection_id_to_address(collection.id)),1415		)1416	}14171418	/// Tells whether the given `owner` approves the `operator`.1419	pub fn allowance_for_all(1420		collection: &RefungibleHandle<T>,1421		owner: &T::CrossAccountId,1422		spender: &T::CrossAccountId,1423	) -> bool {1424		<CollectionAllowance<T>>::get((collection.id, owner, spender))1425	}14261427	pub fn repair_item(collection: &RefungibleHandle<T>, token: TokenId) -> DispatchResult {1428		<TokenProperties<T>>::mutate((collection.id, token), |properties| {1429			properties.recompute_consumed_space();1430		});14311432		Ok(())1433	}1434}
after · pallets/refungible/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//! # Refungible Pallet18//!19//! The Refungible pallet provides functionality for handling refungible collections and tokens.20//!21//! - [`Config`]22//! - [`RefungibleHandle`]23//! - [`Pallet`]24//! - [`CommonWeights`](common::CommonWeights)25//!26//! ## Overview27//!28//! The Refungible pallet provides functions for:29//!30//! - RFT collection creation and removal31//! - Minting and burning of RFT tokens32//! - Partition and repartition of RFT tokens33//! - Retrieving number of pieces of RFT token34//! - Retrieving account balances35//! - Transfering RFT token pieces36//! - Burning RFT token pieces37//! - Setting and checking allowance for RFT tokens38//!39//! ### Terminology40//!41//! - **RFT token:** Non fungible token that was partitioned to pieces. If an account owns all42//!   of the RFT token pieces than it owns the RFT token and can repartition it.43//!44//! - **RFT Collection:** A collection of RFT tokens. All RFT tokens are part of a collection.45//!   Each collection has its own settings and set of permissions.46//!47//! - **RFT token piece:** A fungible part of an RFT token.48//!49//! - **Balance:** RFT token pieces owned by an account50//!51//! - **Allowance:** Maximum number of RFT token pieces that one account is allowed to52//!   transfer from the balance of another account53//!54//! - **Burning:** The process of “deleting” a token from a collection or removing token pieces from55//!   an account balance.56//!57//! ### Implementations58//!59//! The Refungible pallet provides implementations for the following traits. If these traits provide60//! the functionality that you need, then you can avoid coupling with the Refungible pallet.61//!62//! - [`CommonWeightInfo`](pallet_common::CommonWeightInfo): Functions for retrieval of transaction weight63//! - [`CommonCollectionOperations`](pallet_common::CommonCollectionOperations): Functions for dealing64//!   with collections65//! - [`RefungibleExtensions`](pallet_common::RefungibleExtensions): Functions specific for refungible66//!   collection67//!68//! ## Interface69//!70//! ### Dispatchable Functions71//!72//! - `init_collection` - Create RFT collection. RFT collection can be configured to allow or deny access for73//!   some accounts.74//! - `destroy_collection` - Destroy exising RFT collection. There should be no tokens in the collection.75//! - `burn` - Burn some amount of RFT token pieces owned by account. Burns the RFT token if no pieces left.76//! - `transfer` - Transfer some amount of RFT token pieces. Transfers should be enabled for RFT collection.77//!   Nests the RFT token if RFT token pieces are sent to another token.78//! - `create_item` - Mint RFT token in collection. Sender should have permission to mint tokens.79//! - `set_allowance` - Set allowance for another account to transfer balance from sender's account.80//! - `repartition` - Repartition token to selected number of pieces. Sender should own all existing pieces.81//!82//! ## Assumptions83//!84//! * Total number of pieces for one token shouldn't exceed `up_data_structs::MAX_REFUNGIBLE_PIECES`.85//! * Total number of tokens of all types shouldn't be greater than `up_data_structs::MAX_TOKEN_PREFIX_LENGTH`.86//! * Sender should be in collection's allow list to perform operations on tokens.8788#![cfg_attr(not(feature = "std"), no_std)]8990use crate::erc_token::ERC20Events;91use crate::erc::ERC721Events;9293use core::{ops::Deref, cmp::Ordering};94use evm_coder::ToLog;95use frame_support::{ensure, storage::with_transaction, transactional};96use pallet_evm::{account::CrossAccountId, Pallet as PalletEvm};97use pallet_evm_coder_substrate::WithRecorder;98use pallet_common::{99	Error as CommonError, eth::collection_id_to_address, Event as CommonEvent,100	Pallet as PalletCommon,101};102use pallet_structure::Pallet as PalletStructure;103use sp_core::{Get, H160};104use sp_runtime::{ArithmeticError, DispatchError, DispatchResult, TransactionOutcome};105use sp_std::{vec::Vec, vec, collections::btree_map::BTreeMap};106use up_data_structs::{107	AccessMode, budget::Budget, CollectionId, CreateCollectionData, mapping::TokenAddressMapping,108	MAX_REFUNGIBLE_PIECES, Property, PropertyKey, PropertyKeyPermission, PropertyScope,109	PropertyValue, TokenId, PropertiesPermissionMap, CreateRefungibleExMultipleOwners,110	TokenOwnerError, TokenProperties as TokenPropertiesT,111};112113pub use pallet::*;114#[cfg(feature = "runtime-benchmarks")]115pub mod benchmarking;116pub mod common;117pub mod erc;118pub mod erc_token;119pub mod weights;120121pub type CreateItemData<T> =122	CreateRefungibleExMultipleOwners<<T as pallet_evm::Config>::CrossAccountId>;123pub(crate) type SelfWeightOf<T> = <T as Config>::WeightInfo;124125#[frame_support::pallet]126pub mod pallet {127	use super::*;128	use frame_support::{129		Blake2_128, Blake2_128Concat, Twox64Concat, pallet_prelude::*, storage::Key,130		traits::StorageVersion,131	};132	use up_data_structs::{CollectionId, TokenId};133	use super::weights::WeightInfo;134135	#[pallet::error]136	pub enum Error<T> {137		/// Not Refungible item data used to mint in Refungible collection.138		NotRefungibleDataUsedToMintFungibleCollectionToken,139		/// Maximum refungibility exceeded.140		WrongRefungiblePieces,141		/// Refungible token can't be repartitioned by user who isn't owns all pieces.142		RepartitionWhileNotOwningAllPieces,143		/// Refungible token can't nest other tokens.144		RefungibleDisallowsNesting,145		/// Setting item properties is not allowed.146		SettingPropertiesNotAllowed,147	}148149	#[pallet::config]150	pub trait Config:151		frame_system::Config + pallet_common::Config + pallet_structure::Config152	{153		type WeightInfo: WeightInfo;154	}155156	const STORAGE_VERSION: StorageVersion = StorageVersion::new(2);157158	#[pallet::pallet]159	#[pallet::storage_version(STORAGE_VERSION)]160	pub struct Pallet<T>(_);161162	/// Total amount of minted tokens in a collection.163	#[pallet::storage]164	pub type TokensMinted<T: Config> =165		StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;166167	/// Amount of tokens burnt in a collection.168	#[pallet::storage]169	pub type TokensBurnt<T: Config> =170		StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;171172	/// Amount of pieces a refungible token is split into.173	#[pallet::storage]174	#[pallet::getter(fn token_properties)]175	pub type TokenProperties<T: Config> = StorageNMap<176		Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),177		Value = TokenPropertiesT,178		QueryKind = OptionQuery,179	>;180181	/// Total amount of pieces for token182	#[pallet::storage]183	pub type TotalSupply<T: Config> = StorageNMap<184		Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),185		Value = u128,186		QueryKind = ValueQuery,187	>;188189	/// Used to enumerate tokens owned by account.190	#[pallet::storage]191	pub type Owned<T: Config> = StorageNMap<192		Key = (193			Key<Twox64Concat, CollectionId>,194			Key<Blake2_128Concat, T::CrossAccountId>,195			Key<Twox64Concat, TokenId>,196		),197		Value = bool,198		QueryKind = ValueQuery,199	>;200201	/// Amount of tokens (not pieces) partially owned by an account within a collection.202	#[pallet::storage]203	pub type AccountBalance<T: Config> = StorageNMap<204		Key = (205			Key<Twox64Concat, CollectionId>,206			// Owner207			Key<Blake2_128Concat, T::CrossAccountId>,208		),209		Value = u32,210		QueryKind = ValueQuery,211	>;212213	/// Amount of token pieces owned by account.214	#[pallet::storage]215	pub type Balance<T: Config> = StorageNMap<216		Key = (217			Key<Twox64Concat, CollectionId>,218			Key<Twox64Concat, TokenId>,219			// Owner220			Key<Blake2_128Concat, T::CrossAccountId>,221		),222		Value = u128,223		QueryKind = ValueQuery,224	>;225226	/// Allowance set by a token owner for another user to perform one of certain transactions on a number of pieces of a token.227	#[pallet::storage]228	pub type Allowance<T: Config> = StorageNMap<229		Key = (230			Key<Twox64Concat, CollectionId>,231			Key<Twox64Concat, TokenId>,232			// Owner233			Key<Blake2_128, T::CrossAccountId>,234			// Spender235			Key<Blake2_128Concat, T::CrossAccountId>,236		),237		Value = u128,238		QueryKind = ValueQuery,239	>;240241	/// Spender set by a wallet owner that could perform certain transactions on all tokens in the wallet.242	#[pallet::storage]243	pub type CollectionAllowance<T: Config> = StorageNMap<244		Key = (245			Key<Twox64Concat, CollectionId>,246			Key<Blake2_128Concat, T::CrossAccountId>, // Owner247			Key<Blake2_128Concat, T::CrossAccountId>, // Spender248		),249		Value = bool,250		QueryKind = ValueQuery,251	>;252}253254pub struct RefungibleHandle<T: Config>(pallet_common::CollectionHandle<T>);255impl<T: Config> RefungibleHandle<T> {256	pub fn cast(inner: pallet_common::CollectionHandle<T>) -> Self {257		Self(inner)258	}259	pub fn into_inner(self) -> pallet_common::CollectionHandle<T> {260		self.0261	}262	pub fn common_mut(&mut self) -> &mut pallet_common::CollectionHandle<T> {263		&mut self.0264	}265}266267impl<T: Config> Deref for RefungibleHandle<T> {268	type Target = pallet_common::CollectionHandle<T>;269270	fn deref(&self) -> &Self::Target {271		&self.0272	}273}274275impl<T: Config> WithRecorder<T> for RefungibleHandle<T> {276	fn recorder(&self) -> &pallet_evm_coder_substrate::SubstrateRecorder<T> {277		self.0.recorder()278	}279	fn into_recorder(self) -> pallet_evm_coder_substrate::SubstrateRecorder<T> {280		self.0.into_recorder()281	}282}283284impl<T: Config> Pallet<T> {285	/// Get number of RFT tokens in collection286	pub fn total_supply(collection: &RefungibleHandle<T>) -> u32 {287		<TokensMinted<T>>::get(collection.id) - <TokensBurnt<T>>::get(collection.id)288	}289290	/// Check that RFT token exists291	///292	/// - `token`: Token ID.293	pub fn token_exists(collection: &RefungibleHandle<T>, token: TokenId) -> bool {294		<TotalSupply<T>>::contains_key((collection.id, token))295	}296}297298// unchecked calls skips any permission checks299impl<T: Config> Pallet<T> {300	/// Create RFT collection301	///302	/// `init_collection` will take non-refundable deposit for collection creation.303	///304	/// - `data`: Contains settings for collection limits and permissions.305	pub fn init_collection(306		owner: T::CrossAccountId,307		payer: T::CrossAccountId,308		data: CreateCollectionData<T::CrossAccountId>,309	) -> Result<CollectionId, DispatchError> {310		<PalletCommon<T>>::init_collection(owner, payer, data)311	}312313	/// Destroy RFT collection314	///315	/// `destroy_collection` will throw error if collection contains any tokens.316	/// Only owner can destroy collection.317	pub fn destroy_collection(318		collection: RefungibleHandle<T>,319		sender: &T::CrossAccountId,320	) -> DispatchResult {321		let id = collection.id;322323		if Self::collection_has_tokens(id) {324			return Err(<CommonError<T>>::CantDestroyNotEmptyCollection.into());325		}326327		// =========328329		PalletCommon::destroy_collection(collection.0, sender)?;330331		<TokensMinted<T>>::remove(id);332		<TokensBurnt<T>>::remove(id);333		let _ = <TotalSupply<T>>::clear_prefix((id,), u32::MAX, None);334		let _ = <Balance<T>>::clear_prefix((id,), u32::MAX, None);335		let _ = <Allowance<T>>::clear_prefix((id,), u32::MAX, None);336		let _ = <Owned<T>>::clear_prefix((id,), u32::MAX, None);337		let _ = <AccountBalance<T>>::clear_prefix((id,), u32::MAX, None);338		Ok(())339	}340341	fn collection_has_tokens(collection_id: CollectionId) -> bool {342		<TotalSupply<T>>::iter_prefix((collection_id,))343			.next()344			.is_some()345	}346347	pub fn burn_token_unchecked(348		collection: &RefungibleHandle<T>,349		owner: &T::CrossAccountId,350		token_id: TokenId,351	) -> DispatchResult {352		let burnt = <TokensBurnt<T>>::get(collection.id)353			.checked_add(1)354			.ok_or(ArithmeticError::Overflow)?;355356		<TokensBurnt<T>>::insert(collection.id, burnt);357		<TokenProperties<T>>::remove((collection.id, token_id));358		<TotalSupply<T>>::remove((collection.id, token_id));359		let _ = <Balance<T>>::clear_prefix((collection.id, token_id), u32::MAX, None);360		let _ = <Allowance<T>>::clear_prefix((collection.id, token_id), u32::MAX, None);361		<PalletEvm<T>>::deposit_log(362			ERC721Events::Transfer {363				from: *owner.as_eth(),364				to: H160::default(),365				token_id: token_id.into(),366			}367			.to_log(collection_id_to_address(collection.id)),368		);369		Ok(())370	}371372	/// Burn RFT token pieces373	///374	/// `burn` will decrease total amount of token pieces and amount owned by sender.375	/// `burn` can be called even if there are multiple owners of the RFT token.376	/// If sender wouldn't have any pieces left after `burn` than she will stop being377	/// one of the owners of the token. If there is no account that owns any pieces of378	/// the token than token will be burned too.379	///380	/// - `amount`: Amount of token pieces to burn.381	/// - `token`: Token who's pieces should be burned382	/// - `collection`: Collection that contains the token383	pub fn burn(384		collection: &RefungibleHandle<T>,385		owner: &T::CrossAccountId,386		token: TokenId,387		amount: u128,388	) -> DispatchResult {389		if <Balance<T>>::get((collection.id, token, owner)) == 0 {390			return Err(<CommonError<T>>::TokenValueTooLow.into());391		}392393		let total_supply = <TotalSupply<T>>::get((collection.id, token))394			.checked_sub(amount)395			.ok_or(<CommonError<T>>::TokenValueTooLow)?;396397		// This was probally last owner of this token?398		if total_supply == 0 {399			// Ensure user actually owns this amount400			ensure!(401				<Balance<T>>::get((collection.id, token, owner)) == amount,402				<CommonError<T>>::TokenValueTooLow403			);404			let account_balance = <AccountBalance<T>>::get((collection.id, owner))405				.checked_sub(1)406				// Should not occur407				.ok_or(ArithmeticError::Underflow)?;408409			// =========410411			<Owned<T>>::remove((collection.id, owner, token));412			<PalletStructure<T>>::unnest_if_nested(owner, collection.id, token);413			<AccountBalance<T>>::insert((collection.id, owner), account_balance);414			Self::burn_token_unchecked(collection, owner, token)?;415			<PalletEvm<T>>::deposit_log(416				ERC20Events::Transfer {417					from: *owner.as_eth(),418					to: H160::default(),419					value: amount.into(),420				}421				.to_log(collection_id_to_address(collection.id)),422			);423			<PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(424				collection.id,425				token,426				owner.clone(),427				amount,428			));429			return Ok(());430		}431432		let balance = <Balance<T>>::get((collection.id, token, owner))433			.checked_sub(amount)434			.ok_or(<CommonError<T>>::TokenValueTooLow)?;435		let account_balance = if balance == 0 {436			<AccountBalance<T>>::get((collection.id, owner))437				.checked_sub(1)438				// Should not occur439				.ok_or(ArithmeticError::Underflow)?440		} else {441			0442		};443444		// =========445446		if balance == 0 {447			<Owned<T>>::remove((collection.id, owner, token));448			<PalletStructure<T>>::unnest_if_nested(owner, collection.id, token);449			<Balance<T>>::remove((collection.id, token, owner));450			<AccountBalance<T>>::insert((collection.id, owner), account_balance);451452			if let Ok(user) = Self::token_owner(collection.id, token) {453				<PalletEvm<T>>::deposit_log(454					ERC721Events::Transfer {455						from: erc::ADDRESS_FOR_PARTIALLY_OWNED_TOKENS,456						to: *user.as_eth(),457						token_id: token.into(),458					}459					.to_log(collection_id_to_address(collection.id)),460				);461			}462		} else {463			<Balance<T>>::insert((collection.id, token, owner), balance);464		}465		<TotalSupply<T>>::insert((collection.id, token), total_supply);466467		<PalletEvm<T>>::deposit_log(468			ERC20Events::Transfer {469				from: *owner.as_eth(),470				to: H160::default(),471				value: amount.into(),472			}473			.to_log(T::EvmTokenAddressMapping::token_to_address(474				collection.id,475				token,476			)),477		);478		<PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(479			collection.id,480			token,481			owner.clone(),482			amount,483		));484		Ok(())485	}486487	/// A batch operation to add, edit or remove properties for a token.488	/// It sets or removes a token's properties according to489	/// `properties_updates` contents:490	/// * sets a property under the <key> with the value provided `(<key>, Some(<value>))`491	/// * removes a property under the <key> if the value is `None` `(<key>, None)`.492	///493	/// - `nesting_budget`: Limit for searching parents in-depth to check ownership.494	///495	/// All affected properties should have `mutable` permission496	/// to be **deleted** or to be **set more than once**,497	/// and the sender should have permission to edit those properties.498	///499	/// This function fires an event for each property change.500	/// In case of an error, all the changes (including the events) will be reverted501	/// since the function is transactional.502	#[transactional]503	fn modify_token_properties(504		collection: &RefungibleHandle<T>,505		sender: &T::CrossAccountId,506		token_id: TokenId,507		properties_updates: impl Iterator<Item = (PropertyKey, Option<PropertyValue>)>,508		nesting_budget: &dyn Budget,509	) -> DispatchResult {510		let mut property_writer =511			pallet_common::property_writer_for_existing_token(collection, sender);512513		property_writer.write_token_properties(514			sender,515			token_id,516			properties_updates,517			nesting_budget,518			erc::ERC721TokenEvent::TokenChanged {519				token_id: token_id.into(),520			}521			.to_log(T::ContractAddress::get()),522		)523	}524525	pub fn next_token_id(collection: &RefungibleHandle<T>) -> Result<TokenId, DispatchError> {526		let next_token_id = <TokensMinted<T>>::get(collection.id)527			.checked_add(1)528			.ok_or(<CommonError<T>>::CollectionTokenLimitExceeded)?;529530		ensure!(531			collection.limits.token_limit() >= next_token_id,532			<CommonError<T>>::CollectionTokenLimitExceeded533		);534535		Ok(TokenId(next_token_id))536	}537538	pub fn set_token_properties(539		collection: &RefungibleHandle<T>,540		sender: &T::CrossAccountId,541		token_id: TokenId,542		properties: impl Iterator<Item = Property>,543		nesting_budget: &dyn Budget,544	) -> DispatchResult {545		Self::modify_token_properties(546			collection,547			sender,548			token_id,549			properties.map(|p| (p.key, Some(p.value))),550			nesting_budget,551		)552	}553554	pub fn set_token_property(555		collection: &RefungibleHandle<T>,556		sender: &T::CrossAccountId,557		token_id: TokenId,558		property: Property,559		nesting_budget: &dyn Budget,560	) -> DispatchResult {561		Self::set_token_properties(562			collection,563			sender,564			token_id,565			[property].into_iter(),566			nesting_budget,567		)568	}569570	pub fn delete_token_properties(571		collection: &RefungibleHandle<T>,572		sender: &T::CrossAccountId,573		token_id: TokenId,574		property_keys: impl Iterator<Item = PropertyKey>,575		nesting_budget: &dyn Budget,576	) -> DispatchResult {577		Self::modify_token_properties(578			collection,579			sender,580			token_id,581			property_keys.into_iter().map(|key| (key, None)),582			nesting_budget,583		)584	}585586	pub fn delete_token_property(587		collection: &RefungibleHandle<T>,588		sender: &T::CrossAccountId,589		token_id: TokenId,590		property_key: PropertyKey,591		nesting_budget: &dyn Budget,592	) -> DispatchResult {593		Self::delete_token_properties(594			collection,595			sender,596			token_id,597			[property_key].into_iter(),598			nesting_budget,599		)600	}601602	/// Transfer RFT token pieces from one account to another.603	///604	/// If the sender is no longer owns any pieces after the `transfer` than she stops being an owner of the token.605	///606	/// - `from`: Owner of token pieces to transfer.607	/// - `to`: Recepient of transfered token pieces.608	/// - `amount`: Amount of token pieces to transfer.609	/// - `token`: Token whos pieces should be transfered610	/// - `collection`: Collection that contains the token611	pub fn transfer(612		collection: &RefungibleHandle<T>,613		from: &T::CrossAccountId,614		to: &T::CrossAccountId,615		token: TokenId,616		amount: u128,617		nesting_budget: &dyn Budget,618	) -> DispatchResult {619		ensure!(620			collection.limits.transfers_enabled(),621			<CommonError<T>>::TransferNotAllowed622		);623624		if collection.permissions.access() == AccessMode::AllowList {625			collection.check_allowlist(from)?;626			collection.check_allowlist(to)?;627		}628		<PalletCommon<T>>::ensure_correct_receiver(to)?;629630		let initial_balance_from = <Balance<T>>::get((collection.id, token, from));631632		if initial_balance_from == 0 {633			return Err(<CommonError<T>>::TokenValueTooLow.into());634		}635636		let updated_balance_from = initial_balance_from637			.checked_sub(amount)638			.ok_or(<CommonError<T>>::TokenValueTooLow)?;639		let mut create_target = false;640		let from_to_differ = from != to;641		let updated_balance_to = if from != to && amount != 0 {642			let old_balance = <Balance<T>>::get((collection.id, token, to));643			if old_balance == 0 {644				create_target = true;645			}646			Some(647				old_balance648					.checked_add(amount)649					.ok_or(ArithmeticError::Overflow)?,650			)651		} else {652			None653		};654655		let account_balance_from = if updated_balance_from == 0 {656			Some(657				<AccountBalance<T>>::get((collection.id, from))658					.checked_sub(1)659					// Should not occur660					.ok_or(ArithmeticError::Underflow)?,661			)662		} else {663			None664		};665		// Account data is created in token, AccountBalance should be increased666		// But only if from != to as we shouldn't check overflow in this case667		let account_balance_to = if create_target && from_to_differ {668			let account_balance_to = <AccountBalance<T>>::get((collection.id, to))669				.checked_add(1)670				.ok_or(ArithmeticError::Overflow)?;671			ensure!(672				account_balance_to < collection.limits.account_token_ownership_limit(),673				<CommonError<T>>::AccountTokenLimitExceeded,674			);675676			Some(account_balance_to)677		} else {678			None679		};680681		// =========682683		if let Some(updated_balance_to) = updated_balance_to {684			// from != to && amount != 0685686			<PalletStructure<T>>::nest_if_sent_to_token(687				from.clone(),688				to,689				collection.id,690				token,691				nesting_budget,692			)?;693694			if updated_balance_from == 0 {695				<Balance<T>>::remove((collection.id, token, from));696				<PalletStructure<T>>::unnest_if_nested(from, collection.id, token);697			} else {698				<Balance<T>>::insert((collection.id, token, from), updated_balance_from);699			}700			<Balance<T>>::insert((collection.id, token, to), updated_balance_to);701			if let Some(account_balance_from) = account_balance_from {702				<AccountBalance<T>>::insert((collection.id, from), account_balance_from);703				<Owned<T>>::remove((collection.id, from, token));704			}705			if let Some(account_balance_to) = account_balance_to {706				<AccountBalance<T>>::insert((collection.id, to), account_balance_to);707				<Owned<T>>::insert((collection.id, to, token), true);708			}709		}710711		<PalletEvm<T>>::deposit_log(712			ERC20Events::Transfer {713				from: *from.as_eth(),714				to: *to.as_eth(),715				value: amount.into(),716			}717			.to_log(T::EvmTokenAddressMapping::token_to_address(718				collection.id,719				token,720			)),721		);722723		<PalletCommon<T>>::deposit_event(CommonEvent::Transfer(724			collection.id,725			token,726			from.clone(),727			to.clone(),728			amount,729		));730731		let total_supply = <TotalSupply<T>>::get((collection.id, token));732733		if amount == total_supply {734			// if token was fully owned by `from` and will be fully owned by `to` after transfer735			<PalletEvm<T>>::deposit_log(736				ERC721Events::Transfer {737					from: *from.as_eth(),738					to: *to.as_eth(),739					token_id: token.into(),740				}741				.to_log(collection_id_to_address(collection.id)),742			);743		} else if let Some(updated_balance_to) = updated_balance_to {744			// if `from` not equals `to`. This condition is needed to avoid sending event745			// when `from` fully owns token and sends part of token pieces to itself.746			if initial_balance_from == total_supply {747				// if token was fully owned by `from` and will be only partially owned by `to`748				// and `from` after transfer749				<PalletEvm<T>>::deposit_log(750					ERC721Events::Transfer {751						from: *from.as_eth(),752						to: erc::ADDRESS_FOR_PARTIALLY_OWNED_TOKENS,753						token_id: token.into(),754					}755					.to_log(collection_id_to_address(collection.id)),756				);757			} else if updated_balance_to == total_supply {758				// if token was partially owned by `from` and will be fully owned by `to` after transfer759				<PalletEvm<T>>::deposit_log(760					ERC721Events::Transfer {761						from: erc::ADDRESS_FOR_PARTIALLY_OWNED_TOKENS,762						to: *to.as_eth(),763						token_id: token.into(),764					}765					.to_log(collection_id_to_address(collection.id)),766				);767			}768		}769770		Ok(())771	}772773	/// Batched operation to create multiple RFT tokens.774	///775	/// Same as `create_item` but creates multiple tokens.776	///777	/// - `data`: Same as 'data` in `create_item` but contains data for multiple tokens.778	pub fn create_multiple_items(779		collection: &RefungibleHandle<T>,780		sender: &T::CrossAccountId,781		data: Vec<CreateItemData<T>>,782		nesting_budget: &dyn Budget,783	) -> DispatchResult {784		if !collection.is_owner_or_admin(sender) {785			ensure!(786				collection.permissions.mint_mode(),787				<CommonError<T>>::PublicMintingNotAllowed788			);789			collection.check_allowlist(sender)?;790791			for item in data.iter() {792				for user in item.users.keys() {793					collection.check_allowlist(user)?;794				}795			}796		}797798		for item in data.iter() {799			for (owner, _) in item.users.iter() {800				<PalletCommon<T>>::ensure_correct_receiver(owner)?;801			}802		}803804		// Total pieces per tokens805		let totals = data806			.iter()807			.map(|data| {808				Ok(data809					.users810					.iter()811					.map(|u| u.1)812					.try_fold(0u128, |acc, v| acc.checked_add(*v))813					.ok_or(ArithmeticError::Overflow)?)814			})815			.collect::<Result<Vec<_>, DispatchError>>()?;816		for total in &totals {817			ensure!(818				*total <= MAX_REFUNGIBLE_PIECES,819				<Error<T>>::WrongRefungiblePieces820			);821		}822823		let first_token_id = <TokensMinted<T>>::get(collection.id);824		let tokens_minted = first_token_id825			.checked_add(data.len() as u32)826			.ok_or(ArithmeticError::Overflow)?;827		ensure!(828			tokens_minted < collection.limits.token_limit(),829			<CommonError<T>>::CollectionTokenLimitExceeded830		);831832		let mut balances = BTreeMap::new();833		for data in &data {834			for owner in data.users.keys() {835				let balance = balances836					.entry(owner)837					.or_insert_with(|| <AccountBalance<T>>::get((collection.id, owner)));838				*balance = balance.checked_add(1).ok_or(ArithmeticError::Overflow)?;839840				ensure!(841					*balance <= collection.limits.account_token_ownership_limit(),842					<CommonError<T>>::AccountTokenLimitExceeded,843				);844			}845		}846847		for (i, token) in data.iter().enumerate() {848			let token_id = TokenId(first_token_id + i as u32 + 1);849			for (to, _) in token.users.iter() {850				<PalletStructure<T>>::check_nesting(851					sender.clone(),852					to,853					collection.id,854					token_id,855					nesting_budget,856				)?;857			}858		}859860		// =========861862		let mut property_writer = pallet_common::property_writer_for_new_token(collection, sender);863864		with_transaction(|| {865			for (i, data) in data.iter().enumerate() {866				let token_id = first_token_id + i as u32 + 1;867				<TotalSupply<T>>::insert((collection.id, token_id), totals[i]);868869				let token = TokenId(token_id);870871				let mut mint_target_is_sender = true;872				for (user, amount) in data.users.iter() {873					if *amount == 0 {874						continue;875					}876877					mint_target_is_sender = mint_target_is_sender && sender.conv_eq(user);878879					<Balance<T>>::insert((collection.id, token_id, &user), amount);880					<Owned<T>>::insert((collection.id, &user, token), true);881					<PalletStructure<T>>::nest_if_sent_to_token_unchecked(882						user,883						collection.id,884						token,885					);886				}887888				if let Err(e) = property_writer.write_token_properties(889					mint_target_is_sender,890					token,891					data.properties.clone().into_iter(),892					erc::ERC721TokenEvent::TokenChanged {893						token_id: token.into(),894					}895					.to_log(T::ContractAddress::get()),896				) {897					return TransactionOutcome::Rollback(Err(e));898				}899			}900			TransactionOutcome::Commit(Ok(()))901		})?;902903		<TokensMinted<T>>::insert(collection.id, tokens_minted);904905		for (account, balance) in balances {906			<AccountBalance<T>>::insert((collection.id, account), balance);907		}908909		for (i, token) in data.into_iter().enumerate() {910			let token_id = first_token_id + i as u32 + 1;911912			let receivers = token913				.users914				.into_iter()915				.filter(|(_, amount)| *amount > 0)916				.collect::<Vec<_>>();917918			if let [(user, _)] = receivers.as_slice() {919				// if there is exactly one receiver920				<PalletEvm<T>>::deposit_log(921					ERC721Events::Transfer {922						from: H160::default(),923						to: *user.as_eth(),924						token_id: token_id.into(),925					}926					.to_log(collection_id_to_address(collection.id)),927				);928			} else if let [_, ..] = receivers.as_slice() {929				// if there is more than one receiver930				<PalletEvm<T>>::deposit_log(931					ERC721Events::Transfer {932						from: H160::default(),933						to: erc::ADDRESS_FOR_PARTIALLY_OWNED_TOKENS,934						token_id: token_id.into(),935					}936					.to_log(collection_id_to_address(collection.id)),937				);938			}939940			for (user, amount) in receivers.into_iter() {941				<PalletEvm<T>>::deposit_log(942					ERC20Events::Transfer {943						from: H160::default(),944						to: *user.as_eth(),945						value: amount.into(),946					}947					.to_log(T::EvmTokenAddressMapping::token_to_address(948						collection.id,949						TokenId(token_id),950					)),951				);952				<PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(953					collection.id,954					TokenId(token_id),955					user,956					amount,957				));958			}959		}960		Ok(())961	}962963	pub fn set_allowance_unchecked(964		collection: &RefungibleHandle<T>,965		sender: &T::CrossAccountId,966		spender: &T::CrossAccountId,967		token: TokenId,968		amount: u128,969	) {970		if amount == 0 {971			<Allowance<T>>::remove((collection.id, token, sender, spender));972		} else {973			<Allowance<T>>::insert((collection.id, token, sender, spender), amount);974		}975976		<PalletEvm<T>>::deposit_log(977			ERC20Events::Approval {978				owner: *sender.as_eth(),979				spender: *spender.as_eth(),980				value: amount.into(),981			}982			.to_log(T::EvmTokenAddressMapping::token_to_address(983				collection.id,984				token,985			)),986		);987		<PalletCommon<T>>::deposit_event(CommonEvent::Approved(988			collection.id,989			token,990			sender.clone(),991			spender.clone(),992			amount,993		))994	}995996	/// Set allowance for the spender to `transfer` or `burn` sender's token pieces.997	///998	/// - `amount`: Amount of token pieces the spender is allowed to `transfer` or `burn.999	pub fn set_allowance(1000		collection: &RefungibleHandle<T>,1001		sender: &T::CrossAccountId,1002		spender: &T::CrossAccountId,1003		token: TokenId,1004		amount: u128,1005	) -> DispatchResult {1006		if collection.permissions.access() == AccessMode::AllowList {1007			collection.check_allowlist(sender)?;1008			collection.check_allowlist(spender)?;1009		}10101011		<PalletCommon<T>>::ensure_correct_receiver(spender)?;10121013		if <Balance<T>>::get((collection.id, token, sender)) < amount {1014			ensure!(1015				collection.ignores_owned_amount(sender) && Self::token_exists(collection, token),1016				<CommonError<T>>::CantApproveMoreThanOwned1017			);1018		}10191020		// =========10211022		Self::set_allowance_unchecked(collection, sender, spender, token, amount);1023		Ok(())1024	}10251026	/// Set allowance to spend from sender's eth mirror1027	///1028	/// - `from`: Address of sender's eth mirror.1029	/// - `to`: Adress of spender.1030	/// - `amount`: Amount of token pieces the spender is allowed to `transfer` or `burn.1031	pub fn set_allowance_from(1032		collection: &RefungibleHandle<T>,1033		sender: &T::CrossAccountId,1034		from: &T::CrossAccountId,1035		to: &T::CrossAccountId,1036		token_id: TokenId,1037		amount: u128,1038	) -> DispatchResult {1039		if collection.permissions.access() == AccessMode::AllowList {1040			collection.check_allowlist(sender)?;1041			collection.check_allowlist(from)?;1042			collection.check_allowlist(to)?;1043		}10441045		<PalletCommon<T>>::ensure_correct_receiver(to)?;10461047		ensure!(1048			sender.conv_eq(from),1049			<CommonError<T>>::AddressIsNotEthMirror1050		);10511052		if <Balance<T>>::get((collection.id, token_id, from)) < amount {1053			ensure!(1054				collection.limits.owner_can_transfer()1055					&& (collection.is_owner_or_admin(sender) || collection.is_owner_or_admin(from))1056					&& Self::token_exists(collection, token_id),1057				<CommonError<T>>::CantApproveMoreThanOwned1058			);1059		}10601061		// =========10621063		Self::set_allowance_unchecked(collection, from, to, token_id, amount);1064		Ok(())1065	}10661067	/// Returns allowance, which should be set after transaction1068	fn check_allowed(1069		collection: &RefungibleHandle<T>,1070		spender: &T::CrossAccountId,1071		from: &T::CrossAccountId,1072		token: TokenId,1073		amount: u128,1074		nesting_budget: &dyn Budget,1075	) -> Result<Option<u128>, DispatchError> {1076		if spender.conv_eq(from) {1077			return Ok(None);1078		}1079		if collection.permissions.access() == AccessMode::AllowList {1080			// `from`, `to` checked in [`transfer`]1081			collection.check_allowlist(spender)?;1082		}10831084		if collection.ignores_token_restrictions(spender) {1085			return Ok(Self::compute_allowance_decrease(1086				collection, token, from, spender, amount,1087			));1088		}10891090		if let Some(source) = T::CrossTokenAddressMapping::address_to_token(from) {1091			// TODO: should collection owner be allowed to perform this transfer?1092			ensure!(1093				<PalletStructure<T>>::check_indirectly_owned(1094					spender.clone(),1095					source.0,1096					source.1,1097					None,1098					nesting_budget1099				)?,1100				<CommonError<T>>::ApprovedValueTooLow,1101			);1102			return Ok(None);1103		}11041105		let allowance = Self::compute_allowance_decrease(collection, token, from, spender, amount);1106		if allowance.is_some() {1107			return Ok(allowance);1108		}11091110		// Allowance (if any) would be reduced if spender is also wallet operator1111		if <CollectionAllowance<T>>::get((collection.id, from, spender)) {1112			return Ok(allowance);1113		}11141115		Err(<CommonError<T>>::ApprovedValueTooLow.into())1116	}11171118	/// Returns `Some(amount)` if the `spender` have allowance to spend this amount.1119	/// Otherwise, it returns `None`.1120	fn compute_allowance_decrease(1121		collection: &RefungibleHandle<T>,1122		token: TokenId,1123		from: &T::CrossAccountId,1124		spender: &T::CrossAccountId,1125		amount: u128,1126	) -> Option<u128> {1127		<Allowance<T>>::get((collection.id, token, from, spender)).checked_sub(amount)1128	}11291130	/// Transfer RFT token pieces from one account to another.1131	///1132	/// Same as the [`transfer`] but spender doesn't needs to be an owner of the token pieces.1133	/// The owner should set allowance for the spender to transfer pieces.1134	///1135	/// [`transfer`]: struct.Pallet.html#method.transfer1136	pub fn transfer_from(1137		collection: &RefungibleHandle<T>,1138		spender: &T::CrossAccountId,1139		from: &T::CrossAccountId,1140		to: &T::CrossAccountId,1141		token: TokenId,1142		amount: u128,1143		nesting_budget: &dyn Budget,1144	) -> DispatchResult {1145		let allowance =1146			Self::check_allowed(collection, spender, from, token, amount, nesting_budget)?;11471148		// =========11491150		Self::transfer(collection, from, to, token, amount, nesting_budget)?;1151		if let Some(allowance) = allowance {1152			Self::set_allowance_unchecked(collection, from, spender, token, allowance);1153		}1154		Ok(())1155	}11561157	/// Burn RFT token pieces from the account.1158	///1159	/// Same as the [`burn`] but spender doesn't need to be an owner of the token pieces. The owner should1160	/// set allowance for the spender to burn pieces1161	///1162	/// [`burn`]: struct.Pallet.html#method.burn1163	pub fn burn_from(1164		collection: &RefungibleHandle<T>,1165		spender: &T::CrossAccountId,1166		from: &T::CrossAccountId,1167		token: TokenId,1168		amount: u128,1169		nesting_budget: &dyn Budget,1170	) -> DispatchResult {1171		let allowance =1172			Self::check_allowed(collection, spender, from, token, amount, nesting_budget)?;11731174		// =========11751176		Self::burn(collection, from, token, amount)?;1177		if let Some(allowance) = allowance {1178			Self::set_allowance_unchecked(collection, from, spender, token, allowance);1179		}1180		Ok(())1181	}11821183	/// Create RFT token.1184	///1185	/// The sender should be the owner/admin of the collection or collection should be configured1186	/// to allow public minting.1187	///1188	/// - `data`: Contains list of users who will become the owners of the token pieces and amount1189	///   of token pieces they will receive.1190	pub fn create_item(1191		collection: &RefungibleHandle<T>,1192		sender: &T::CrossAccountId,1193		data: CreateItemData<T>,1194		nesting_budget: &dyn Budget,1195	) -> DispatchResult {1196		Self::create_multiple_items(collection, sender, vec![data], nesting_budget)1197	}11981199	/// Repartition RFT token.1200	///1201	/// `repartition` will set token balance of the sender and total amount of token pieces.1202	/// Sender should own all of the token pieces. `repartition' could be done even if some1203	/// token pieces were burned before.1204	///1205	/// - `amount`: Total amount of token pieces that the token will have after `repartition`.1206	pub fn repartition(1207		collection: &RefungibleHandle<T>,1208		owner: &T::CrossAccountId,1209		token: TokenId,1210		amount: u128,1211	) -> DispatchResult {1212		ensure!(1213			amount <= MAX_REFUNGIBLE_PIECES,1214			<Error<T>>::WrongRefungiblePieces1215		);1216		ensure!(amount > 0, <CommonError<T>>::TokenValueTooLow);1217		// Ensure user owns all pieces1218		let total_pieces = Self::total_pieces(collection.id, token).unwrap_or(u128::MAX);1219		let balance = <Balance<T>>::get((collection.id, token, owner));1220		ensure!(1221			total_pieces == balance,1222			<Error<T>>::RepartitionWhileNotOwningAllPieces1223		);12241225		<Balance<T>>::insert((collection.id, token, owner), amount);1226		<TotalSupply<T>>::insert((collection.id, token), amount);12271228		match total_pieces.cmp(&amount) {1229			Ordering::Less => {1230				let mint_amount = amount - total_pieces;1231				<PalletEvm<T>>::deposit_log(1232					ERC20Events::Transfer {1233						from: H160::default(),1234						to: *owner.as_eth(),1235						value: mint_amount.into(),1236					}1237					.to_log(T::EvmTokenAddressMapping::token_to_address(1238						collection.id,1239						token,1240					)),1241				);1242				<PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(1243					collection.id,1244					token,1245					owner.clone(),1246					mint_amount,1247				));1248			}1249			Ordering::Greater => {1250				let burn_amount = total_pieces - amount;1251				<PalletEvm<T>>::deposit_log(1252					ERC20Events::Transfer {1253						from: *owner.as_eth(),1254						to: H160::default(),1255						value: burn_amount.into(),1256					}1257					.to_log(T::EvmTokenAddressMapping::token_to_address(1258						collection.id,1259						token,1260					)),1261				);1262				<PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(1263					collection.id,1264					token,1265					owner.clone(),1266					burn_amount,1267				));1268			}1269			Ordering::Equal => {}1270		}12711272		Ok(())1273	}12741275	fn token_owner(1276		collection_id: CollectionId,1277		token_id: TokenId,1278	) -> Result<T::CrossAccountId, TokenOwnerError> {1279		let mut owner = None;1280		let mut count = 0;1281		for key in Balance::<T>::iter_key_prefix((collection_id, token_id)) {1282			count += 1;1283			if count > 1 {1284				return Err(TokenOwnerError::MultipleOwners);1285			}1286			owner = Some(key);1287		}1288		owner.ok_or(TokenOwnerError::NotFound)1289	}12901291	fn total_pieces(collection_id: CollectionId, token_id: TokenId) -> Option<u128> {1292		<TotalSupply<T>>::try_get((collection_id, token_id)).ok()1293	}12941295	pub fn set_collection_properties(1296		collection: &RefungibleHandle<T>,1297		sender: &T::CrossAccountId,1298		properties: Vec<Property>,1299	) -> DispatchResult {1300		<PalletCommon<T>>::set_collection_properties(collection, sender, properties.into_iter())1301	}13021303	pub fn delete_collection_properties(1304		collection: &RefungibleHandle<T>,1305		sender: &T::CrossAccountId,1306		property_keys: Vec<PropertyKey>,1307	) -> DispatchResult {1308		<PalletCommon<T>>::delete_collection_properties(1309			collection,1310			sender,1311			property_keys.into_iter(),1312		)1313	}13141315	pub fn set_token_property_permissions(1316		collection: &RefungibleHandle<T>,1317		sender: &T::CrossAccountId,1318		property_permissions: Vec<PropertyKeyPermission>,1319	) -> DispatchResult {1320		<PalletCommon<T>>::set_token_property_permissions(collection, sender, property_permissions)1321	}13221323	pub fn token_property_permission(collection_id: CollectionId) -> PropertiesPermissionMap {1324		<PalletCommon<T>>::property_permissions(collection_id)1325	}13261327	pub fn set_scoped_token_property_permissions(1328		collection: &RefungibleHandle<T>,1329		sender: &T::CrossAccountId,1330		scope: PropertyScope,1331		property_permissions: Vec<PropertyKeyPermission>,1332	) -> DispatchResult {1333		<PalletCommon<T>>::set_scoped_token_property_permissions(1334			collection,1335			sender,1336			scope,1337			property_permissions,1338		)1339	}13401341	/// Returns 10 token in no particular order.1342	///1343	/// There is no direct way to get token holders in ascending order,1344	/// since `iter_prefix` returns values in no particular order.1345	/// Therefore, getting the 10 largest holders with a large value of holders1346	/// can lead to impact memory allocation + sorting with  `n * log (n)`.1347	pub fn token_owners(1348		collection_id: CollectionId,1349		token: TokenId,1350	) -> Option<Vec<T::CrossAccountId>> {1351		let res: Vec<T::CrossAccountId> = <Balance<T>>::iter_prefix((collection_id, token))1352			.map(|(owner, _amount)| owner)1353			.take(10)1354			.collect();13551356		if res.is_empty() {1357			None1358		} else {1359			Some(res)1360		}1361	}13621363	/// Sets or unsets the approval of a given operator.1364	///1365	/// The `operator` is allowed to transfer all token pieces of the `owner` on their behalf.1366	/// - `owner`: Token owner1367	/// - `operator`: Operator1368	/// - `approve`: Should operator status be granted or revoked?1369	pub fn set_allowance_for_all(1370		collection: &RefungibleHandle<T>,1371		owner: &T::CrossAccountId,1372		spender: &T::CrossAccountId,1373		approve: bool,1374	) -> DispatchResult {1375		<PalletCommon<T>>::set_allowance_for_all(1376			collection,1377			owner,1378			spender,1379			approve,1380			|| <CollectionAllowance<T>>::insert((collection.id, owner, spender), approve),1381			ERC721Events::ApprovalForAll {1382				owner: *owner.as_eth(),1383				operator: *spender.as_eth(),1384				approved: approve,1385			}1386			.to_log(collection_id_to_address(collection.id)),1387		)1388	}13891390	/// Tells whether the given `owner` approves the `operator`.1391	pub fn allowance_for_all(1392		collection: &RefungibleHandle<T>,1393		owner: &T::CrossAccountId,1394		spender: &T::CrossAccountId,1395	) -> bool {1396		<CollectionAllowance<T>>::get((collection.id, owner, spender))1397	}13981399	pub fn repair_item(collection: &RefungibleHandle<T>, token: TokenId) -> DispatchResult {1400		<TokenProperties<T>>::mutate((collection.id, token), |properties| {1401			if let Some(properties) = properties {1402				properties.recompute_consumed_space();1403			}1404		});14051406		Ok(())1407	}1408}