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

difftreelog

fix debug check if new token doesnt have any properties

Daniel Shiposha2023-09-26parent: #9b4620c.patch.diff
in: master

2 files changed

modifiedpallets/nonfungible/src/lib.rsdiffbeforeafterboth
--- a/pallets/nonfungible/src/lib.rs
+++ b/pallets/nonfungible/src/lib.rs
@@ -632,6 +632,10 @@
 		});
 
 		let stored_properties = if is_new_token {
+			debug_assert!(!<TokenProperties<T>>::contains_key((
+				collection.id,
+				token_id
+			)));
 			TokenPropertiesT::new()
 		} else {
 			<TokenProperties<T>>::get((collection.id, token_id))
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	CommonCollectionOperations, Error as CommonError, eth::collection_id_to_address,100	Event as CommonEvent, Pallet as PalletCommon, SetPropertyMode,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		mode: SetPropertyMode,537		nesting_budget: &dyn Budget,538	) -> DispatchResult {539		let mut is_token_owner =540			pallet_common::LazyValue::new(|| -> Result<bool, DispatchError> {541				if let SetPropertyMode::NewToken {542					mint_target_is_sender,543				} = mode544				{545					return Ok(mint_target_is_sender);546				}547548				let balance = collection.balance(sender.clone(), token_id);549				let total_pieces: u128 =550					Self::total_pieces(collection.id, token_id).unwrap_or(u128::MAX);551				if balance != total_pieces {552					return Ok(false);553				}554555				let is_bundle_owner = <PalletStructure<T>>::check_indirectly_owned(556					sender.clone(),557					collection.id,558					token_id,559					None,560					nesting_budget,561				)?;562563				Ok(is_bundle_owner)564			});565566		let is_new_token = matches!(mode, SetPropertyMode::NewToken { .. });567568		let mut is_token_exist = pallet_common::LazyValue::new(|| {569			if is_new_token {570				debug_assert!(Self::token_exists(collection, token_id));571				true572			} else {573				Self::token_exists(collection, token_id)574			}575		});576577		let stored_properties = if is_new_token {578			TokenPropertiesT::new()579		} else {580			<TokenProperties<T>>::get((collection.id, token_id))581		};582583		<PalletCommon<T>>::modify_token_properties(584			collection,585			sender,586			token_id,587			&mut is_token_exist,588			properties_updates,589			stored_properties,590			&mut is_token_owner,591			|properties| <TokenProperties<T>>::set((collection.id, token_id), properties),592			erc::ERC721TokenEvent::TokenChanged {593				token_id: token_id.into(),594			}595			.to_log(T::ContractAddress::get()),596		)597	}598599	pub fn next_token_id(collection: &RefungibleHandle<T>) -> Result<TokenId, DispatchError> {600		let next_token_id = <TokensMinted<T>>::get(collection.id)601			.checked_add(1)602			.ok_or(<CommonError<T>>::CollectionTokenLimitExceeded)?;603604		ensure!(605			collection.limits.token_limit() >= next_token_id,606			<CommonError<T>>::CollectionTokenLimitExceeded607		);608609		Ok(TokenId(next_token_id))610	}611612	pub fn set_token_properties(613		collection: &RefungibleHandle<T>,614		sender: &T::CrossAccountId,615		token_id: TokenId,616		properties: impl Iterator<Item = Property>,617		mode: SetPropertyMode,618		nesting_budget: &dyn Budget,619	) -> DispatchResult {620		Self::modify_token_properties(621			collection,622			sender,623			token_id,624			properties.map(|p| (p.key, Some(p.value))),625			mode,626			nesting_budget,627		)628	}629630	pub fn set_token_property(631		collection: &RefungibleHandle<T>,632		sender: &T::CrossAccountId,633		token_id: TokenId,634		property: Property,635		nesting_budget: &dyn Budget,636	) -> DispatchResult {637		Self::set_token_properties(638			collection,639			sender,640			token_id,641			[property].into_iter(),642			SetPropertyMode::ExistingToken,643			nesting_budget,644		)645	}646647	pub fn delete_token_properties(648		collection: &RefungibleHandle<T>,649		sender: &T::CrossAccountId,650		token_id: TokenId,651		property_keys: impl Iterator<Item = PropertyKey>,652		nesting_budget: &dyn Budget,653	) -> DispatchResult {654		Self::modify_token_properties(655			collection,656			sender,657			token_id,658			property_keys.into_iter().map(|key| (key, None)),659			SetPropertyMode::ExistingToken,660			nesting_budget,661		)662	}663664	pub fn delete_token_property(665		collection: &RefungibleHandle<T>,666		sender: &T::CrossAccountId,667		token_id: TokenId,668		property_key: PropertyKey,669		nesting_budget: &dyn Budget,670	) -> DispatchResult {671		Self::delete_token_properties(672			collection,673			sender,674			token_id,675			[property_key].into_iter(),676			nesting_budget,677		)678	}679680	/// Transfer RFT token pieces from one account to another.681	///682	/// If the sender is no longer owns any pieces after the `transfer` than she stops being an owner of the token.683	///684	/// - `from`: Owner of token pieces to transfer.685	/// - `to`: Recepient of transfered token pieces.686	/// - `amount`: Amount of token pieces to transfer.687	/// - `token`: Token whos pieces should be transfered688	/// - `collection`: Collection that contains the token689	pub fn transfer(690		collection: &RefungibleHandle<T>,691		from: &T::CrossAccountId,692		to: &T::CrossAccountId,693		token: TokenId,694		amount: u128,695		nesting_budget: &dyn Budget,696	) -> DispatchResult {697		ensure!(698			collection.limits.transfers_enabled(),699			<CommonError<T>>::TransferNotAllowed700		);701702		if collection.permissions.access() == AccessMode::AllowList {703			collection.check_allowlist(from)?;704			collection.check_allowlist(to)?;705		}706		<PalletCommon<T>>::ensure_correct_receiver(to)?;707708		let initial_balance_from = <Balance<T>>::get((collection.id, token, from));709710		if initial_balance_from == 0 {711			return Err(<CommonError<T>>::TokenValueTooLow.into());712		}713714		let updated_balance_from = initial_balance_from715			.checked_sub(amount)716			.ok_or(<CommonError<T>>::TokenValueTooLow)?;717		let mut create_target = false;718		let from_to_differ = from != to;719		let updated_balance_to = if from != to && amount != 0 {720			let old_balance = <Balance<T>>::get((collection.id, token, to));721			if old_balance == 0 {722				create_target = true;723			}724			Some(725				old_balance726					.checked_add(amount)727					.ok_or(ArithmeticError::Overflow)?,728			)729		} else {730			None731		};732733		let account_balance_from = if updated_balance_from == 0 {734			Some(735				<AccountBalance<T>>::get((collection.id, from))736					.checked_sub(1)737					// Should not occur738					.ok_or(ArithmeticError::Underflow)?,739			)740		} else {741			None742		};743		// Account data is created in token, AccountBalance should be increased744		// But only if from != to as we shouldn't check overflow in this case745		let account_balance_to = if create_target && from_to_differ {746			let account_balance_to = <AccountBalance<T>>::get((collection.id, to))747				.checked_add(1)748				.ok_or(ArithmeticError::Overflow)?;749			ensure!(750				account_balance_to < collection.limits.account_token_ownership_limit(),751				<CommonError<T>>::AccountTokenLimitExceeded,752			);753754			Some(account_balance_to)755		} else {756			None757		};758759		// =========760761		if let Some(updated_balance_to) = updated_balance_to {762			// from != to && amount != 0763764			<PalletStructure<T>>::nest_if_sent_to_token(765				from.clone(),766				to,767				collection.id,768				token,769				nesting_budget,770			)?;771772			if updated_balance_from == 0 {773				<Balance<T>>::remove((collection.id, token, from));774				<PalletStructure<T>>::unnest_if_nested(from, collection.id, token);775			} else {776				<Balance<T>>::insert((collection.id, token, from), updated_balance_from);777			}778			<Balance<T>>::insert((collection.id, token, to), updated_balance_to);779			if let Some(account_balance_from) = account_balance_from {780				<AccountBalance<T>>::insert((collection.id, from), account_balance_from);781				<Owned<T>>::remove((collection.id, from, token));782			}783			if let Some(account_balance_to) = account_balance_to {784				<AccountBalance<T>>::insert((collection.id, to), account_balance_to);785				<Owned<T>>::insert((collection.id, to, token), true);786			}787		}788789		<PalletEvm<T>>::deposit_log(790			ERC20Events::Transfer {791				from: *from.as_eth(),792				to: *to.as_eth(),793				value: amount.into(),794			}795			.to_log(T::EvmTokenAddressMapping::token_to_address(796				collection.id,797				token,798			)),799		);800801		<PalletCommon<T>>::deposit_event(CommonEvent::Transfer(802			collection.id,803			token,804			from.clone(),805			to.clone(),806			amount,807		));808809		let total_supply = <TotalSupply<T>>::get((collection.id, token));810811		if amount == total_supply {812			// if token was fully owned by `from` and will be fully owned by `to` after transfer813			<PalletEvm<T>>::deposit_log(814				ERC721Events::Transfer {815					from: *from.as_eth(),816					to: *to.as_eth(),817					token_id: token.into(),818				}819				.to_log(collection_id_to_address(collection.id)),820			);821		} else if let Some(updated_balance_to) = updated_balance_to {822			// if `from` not equals `to`. This condition is needed to avoid sending event823			// when `from` fully owns token and sends part of token pieces to itself.824			if initial_balance_from == total_supply {825				// if token was fully owned by `from` and will be only partially owned by `to`826				// and `from` after transfer827				<PalletEvm<T>>::deposit_log(828					ERC721Events::Transfer {829						from: *from.as_eth(),830						to: erc::ADDRESS_FOR_PARTIALLY_OWNED_TOKENS,831						token_id: token.into(),832					}833					.to_log(collection_id_to_address(collection.id)),834				);835			} else if updated_balance_to == total_supply {836				// if token was partially owned by `from` and will be fully owned by `to` after transfer837				<PalletEvm<T>>::deposit_log(838					ERC721Events::Transfer {839						from: erc::ADDRESS_FOR_PARTIALLY_OWNED_TOKENS,840						to: *to.as_eth(),841						token_id: token.into(),842					}843					.to_log(collection_id_to_address(collection.id)),844				);845			}846		}847848		Ok(())849	}850851	/// Batched operation to create multiple RFT tokens.852	///853	/// Same as `create_item` but creates multiple tokens.854	///855	/// - `data`: Same as 'data` in `create_item` but contains data for multiple tokens.856	pub fn create_multiple_items(857		collection: &RefungibleHandle<T>,858		sender: &T::CrossAccountId,859		data: Vec<CreateItemData<T>>,860		nesting_budget: &dyn Budget,861	) -> DispatchResult {862		if !collection.is_owner_or_admin(sender) {863			ensure!(864				collection.permissions.mint_mode(),865				<CommonError<T>>::PublicMintingNotAllowed866			);867			collection.check_allowlist(sender)?;868869			for item in data.iter() {870				for user in item.users.keys() {871					collection.check_allowlist(user)?;872				}873			}874		}875876		for item in data.iter() {877			for (owner, _) in item.users.iter() {878				<PalletCommon<T>>::ensure_correct_receiver(owner)?;879			}880		}881882		// Total pieces per tokens883		let totals = data884			.iter()885			.map(|data| {886				Ok(data887					.users888					.iter()889					.map(|u| u.1)890					.try_fold(0u128, |acc, v| acc.checked_add(*v))891					.ok_or(ArithmeticError::Overflow)?)892			})893			.collect::<Result<Vec<_>, DispatchError>>()?;894		for total in &totals {895			ensure!(896				*total <= MAX_REFUNGIBLE_PIECES,897				<Error<T>>::WrongRefungiblePieces898			);899		}900901		let first_token_id = <TokensMinted<T>>::get(collection.id);902		let tokens_minted = first_token_id903			.checked_add(data.len() as u32)904			.ok_or(ArithmeticError::Overflow)?;905		ensure!(906			tokens_minted < collection.limits.token_limit(),907			<CommonError<T>>::CollectionTokenLimitExceeded908		);909910		let mut balances = BTreeMap::new();911		for data in &data {912			for owner in data.users.keys() {913				let balance = balances914					.entry(owner)915					.or_insert_with(|| <AccountBalance<T>>::get((collection.id, owner)));916				*balance = balance.checked_add(1).ok_or(ArithmeticError::Overflow)?;917918				ensure!(919					*balance <= collection.limits.account_token_ownership_limit(),920					<CommonError<T>>::AccountTokenLimitExceeded,921				);922			}923		}924925		for (i, token) in data.iter().enumerate() {926			let token_id = TokenId(first_token_id + i as u32 + 1);927			for (to, _) in token.users.iter() {928				<PalletStructure<T>>::check_nesting(929					sender.clone(),930					to,931					collection.id,932					token_id,933					nesting_budget,934				)?;935			}936		}937938		// =========939940		with_transaction(|| {941			for (i, data) in data.iter().enumerate() {942				let token_id = first_token_id + i as u32 + 1;943				<TotalSupply<T>>::insert((collection.id, token_id), totals[i]);944945				let mut mint_target_is_sender = true;946				for (user, amount) in data.users.iter() {947					if *amount == 0 {948						continue;949					}950951					mint_target_is_sender = mint_target_is_sender && sender.conv_eq(user);952953					<Balance<T>>::insert((collection.id, token_id, &user), amount);954					<Owned<T>>::insert((collection.id, &user, TokenId(token_id)), true);955					<PalletStructure<T>>::nest_if_sent_to_token_unchecked(956						user,957						collection.id,958						TokenId(token_id),959					);960				}961962				if let Err(e) = Self::set_token_properties(963					collection,964					sender,965					TokenId(token_id),966					data.properties.clone().into_iter(),967					SetPropertyMode::NewToken {968						mint_target_is_sender,969					},970					nesting_budget,971				) {972					return TransactionOutcome::Rollback(Err(e));973				}974			}975			TransactionOutcome::Commit(Ok(()))976		})?;977978		<TokensMinted<T>>::insert(collection.id, tokens_minted);979980		for (account, balance) in balances {981			<AccountBalance<T>>::insert((collection.id, account), balance);982		}983984		for (i, token) in data.into_iter().enumerate() {985			let token_id = first_token_id + i as u32 + 1;986987			let receivers = token988				.users989				.into_iter()990				.filter(|(_, amount)| *amount > 0)991				.collect::<Vec<_>>();992993			if let [(user, _)] = receivers.as_slice() {994				// if there is exactly one receiver995				<PalletEvm<T>>::deposit_log(996					ERC721Events::Transfer {997						from: H160::default(),998						to: *user.as_eth(),999						token_id: token_id.into(),1000					}1001					.to_log(collection_id_to_address(collection.id)),1002				);1003			} else if let [_, ..] = receivers.as_slice() {1004				// if there is more than one receiver1005				<PalletEvm<T>>::deposit_log(1006					ERC721Events::Transfer {1007						from: H160::default(),1008						to: erc::ADDRESS_FOR_PARTIALLY_OWNED_TOKENS,1009						token_id: token_id.into(),1010					}1011					.to_log(collection_id_to_address(collection.id)),1012				);1013			}10141015			for (user, amount) in receivers.into_iter() {1016				<PalletEvm<T>>::deposit_log(1017					ERC20Events::Transfer {1018						from: H160::default(),1019						to: *user.as_eth(),1020						value: amount.into(),1021					}1022					.to_log(T::EvmTokenAddressMapping::token_to_address(1023						collection.id,1024						TokenId(token_id),1025					)),1026				);1027				<PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(1028					collection.id,1029					TokenId(token_id),1030					user,1031					amount,1032				));1033			}1034		}1035		Ok(())1036	}10371038	pub fn set_allowance_unchecked(1039		collection: &RefungibleHandle<T>,1040		sender: &T::CrossAccountId,1041		spender: &T::CrossAccountId,1042		token: TokenId,1043		amount: u128,1044	) {1045		if amount == 0 {1046			<Allowance<T>>::remove((collection.id, token, sender, spender));1047		} else {1048			<Allowance<T>>::insert((collection.id, token, sender, spender), amount);1049		}10501051		<PalletEvm<T>>::deposit_log(1052			ERC20Events::Approval {1053				owner: *sender.as_eth(),1054				spender: *spender.as_eth(),1055				value: amount.into(),1056			}1057			.to_log(T::EvmTokenAddressMapping::token_to_address(1058				collection.id,1059				token,1060			)),1061		);1062		<PalletCommon<T>>::deposit_event(CommonEvent::Approved(1063			collection.id,1064			token,1065			sender.clone(),1066			spender.clone(),1067			amount,1068		))1069	}10701071	/// Set allowance for the spender to `transfer` or `burn` sender's token pieces.1072	///1073	/// - `amount`: Amount of token pieces the spender is allowed to `transfer` or `burn.1074	pub fn set_allowance(1075		collection: &RefungibleHandle<T>,1076		sender: &T::CrossAccountId,1077		spender: &T::CrossAccountId,1078		token: TokenId,1079		amount: u128,1080	) -> DispatchResult {1081		if collection.permissions.access() == AccessMode::AllowList {1082			collection.check_allowlist(sender)?;1083			collection.check_allowlist(spender)?;1084		}10851086		<PalletCommon<T>>::ensure_correct_receiver(spender)?;10871088		if <Balance<T>>::get((collection.id, token, sender)) < amount {1089			ensure!(1090				collection.ignores_owned_amount(sender) && Self::token_exists(collection, token),1091				<CommonError<T>>::CantApproveMoreThanOwned1092			);1093		}10941095		// =========10961097		Self::set_allowance_unchecked(collection, sender, spender, token, amount);1098		Ok(())1099	}11001101	/// Set allowance to spend from sender's eth mirror1102	///1103	/// - `from`: Address of sender's eth mirror.1104	/// - `to`: Adress of spender.1105	/// - `amount`: Amount of token pieces the spender is allowed to `transfer` or `burn.1106	pub fn set_allowance_from(1107		collection: &RefungibleHandle<T>,1108		sender: &T::CrossAccountId,1109		from: &T::CrossAccountId,1110		to: &T::CrossAccountId,1111		token_id: TokenId,1112		amount: u128,1113	) -> DispatchResult {1114		if collection.permissions.access() == AccessMode::AllowList {1115			collection.check_allowlist(sender)?;1116			collection.check_allowlist(from)?;1117			collection.check_allowlist(to)?;1118		}11191120		<PalletCommon<T>>::ensure_correct_receiver(to)?;11211122		ensure!(1123			sender.conv_eq(from),1124			<CommonError<T>>::AddressIsNotEthMirror1125		);11261127		if <Balance<T>>::get((collection.id, token_id, from)) < amount {1128			ensure!(1129				collection.limits.owner_can_transfer()1130					&& (collection.is_owner_or_admin(sender) || collection.is_owner_or_admin(from))1131					&& Self::token_exists(collection, token_id),1132				<CommonError<T>>::CantApproveMoreThanOwned1133			);1134		}11351136		// =========11371138		Self::set_allowance_unchecked(collection, from, to, token_id, amount);1139		Ok(())1140	}11411142	/// Returns allowance, which should be set after transaction1143	fn check_allowed(1144		collection: &RefungibleHandle<T>,1145		spender: &T::CrossAccountId,1146		from: &T::CrossAccountId,1147		token: TokenId,1148		amount: u128,1149		nesting_budget: &dyn Budget,1150	) -> Result<Option<u128>, DispatchError> {1151		if spender.conv_eq(from) {1152			return Ok(None);1153		}1154		if collection.permissions.access() == AccessMode::AllowList {1155			// `from`, `to` checked in [`transfer`]1156			collection.check_allowlist(spender)?;1157		}11581159		if collection.ignores_token_restrictions(spender) {1160			return Ok(Self::compute_allowance_decrease(1161				collection, token, from, spender, amount,1162			));1163		}11641165		if let Some(source) = T::CrossTokenAddressMapping::address_to_token(from) {1166			// TODO: should collection owner be allowed to perform this transfer?1167			ensure!(1168				<PalletStructure<T>>::check_indirectly_owned(1169					spender.clone(),1170					source.0,1171					source.1,1172					None,1173					nesting_budget1174				)?,1175				<CommonError<T>>::ApprovedValueTooLow,1176			);1177			return Ok(None);1178		}11791180		let allowance = Self::compute_allowance_decrease(collection, token, from, spender, amount);1181		if allowance.is_some() {1182			return Ok(allowance);1183		}11841185		// Allowance (if any) would be reduced if spender is also wallet operator1186		if <CollectionAllowance<T>>::get((collection.id, from, spender)) {1187			return Ok(allowance);1188		}11891190		Err(<CommonError<T>>::ApprovedValueTooLow.into())1191	}11921193	/// Returns `Some(amount)` if the `spender` have allowance to spend this amount.1194	/// Otherwise, it returns `None`.1195	fn compute_allowance_decrease(1196		collection: &RefungibleHandle<T>,1197		token: TokenId,1198		from: &T::CrossAccountId,1199		spender: &T::CrossAccountId,1200		amount: u128,1201	) -> Option<u128> {1202		<Allowance<T>>::get((collection.id, token, from, spender)).checked_sub(amount)1203	}12041205	/// Transfer RFT token pieces from one account to another.1206	///1207	/// Same as the [`transfer`] but spender doesn't needs to be an owner of the token pieces.1208	/// The owner should set allowance for the spender to transfer pieces.1209	///1210	/// [`transfer`]: struct.Pallet.html#method.transfer1211	pub fn transfer_from(1212		collection: &RefungibleHandle<T>,1213		spender: &T::CrossAccountId,1214		from: &T::CrossAccountId,1215		to: &T::CrossAccountId,1216		token: TokenId,1217		amount: u128,1218		nesting_budget: &dyn Budget,1219	) -> DispatchResult {1220		let allowance =1221			Self::check_allowed(collection, spender, from, token, amount, nesting_budget)?;12221223		// =========12241225		Self::transfer(collection, from, to, token, amount, nesting_budget)?;1226		if let Some(allowance) = allowance {1227			Self::set_allowance_unchecked(collection, from, spender, token, allowance);1228		}1229		Ok(())1230	}12311232	/// Burn RFT token pieces from the account.1233	///1234	/// Same as the [`burn`] but spender doesn't need to be an owner of the token pieces. The owner should1235	/// set allowance for the spender to burn pieces1236	///1237	/// [`burn`]: struct.Pallet.html#method.burn1238	pub fn burn_from(1239		collection: &RefungibleHandle<T>,1240		spender: &T::CrossAccountId,1241		from: &T::CrossAccountId,1242		token: TokenId,1243		amount: u128,1244		nesting_budget: &dyn Budget,1245	) -> DispatchResult {1246		let allowance =1247			Self::check_allowed(collection, spender, from, token, amount, nesting_budget)?;12481249		// =========12501251		Self::burn(collection, from, token, amount)?;1252		if let Some(allowance) = allowance {1253			Self::set_allowance_unchecked(collection, from, spender, token, allowance);1254		}1255		Ok(())1256	}12571258	/// Create RFT token.1259	///1260	/// The sender should be the owner/admin of the collection or collection should be configured1261	/// to allow public minting.1262	///1263	/// - `data`: Contains list of users who will become the owners of the token pieces and amount1264	///   of token pieces they will receive.1265	pub fn create_item(1266		collection: &RefungibleHandle<T>,1267		sender: &T::CrossAccountId,1268		data: CreateItemData<T>,1269		nesting_budget: &dyn Budget,1270	) -> DispatchResult {1271		Self::create_multiple_items(collection, sender, vec![data], nesting_budget)1272	}12731274	/// Repartition RFT token.1275	///1276	/// `repartition` will set token balance of the sender and total amount of token pieces.1277	/// Sender should own all of the token pieces. `repartition' could be done even if some1278	/// token pieces were burned before.1279	///1280	/// - `amount`: Total amount of token pieces that the token will have after `repartition`.1281	pub fn repartition(1282		collection: &RefungibleHandle<T>,1283		owner: &T::CrossAccountId,1284		token: TokenId,1285		amount: u128,1286	) -> DispatchResult {1287		ensure!(1288			amount <= MAX_REFUNGIBLE_PIECES,1289			<Error<T>>::WrongRefungiblePieces1290		);1291		ensure!(amount > 0, <CommonError<T>>::TokenValueTooLow);1292		// Ensure user owns all pieces1293		let total_pieces = Self::total_pieces(collection.id, token).unwrap_or(u128::MAX);1294		let balance = <Balance<T>>::get((collection.id, token, owner));1295		ensure!(1296			total_pieces == balance,1297			<Error<T>>::RepartitionWhileNotOwningAllPieces1298		);12991300		<Balance<T>>::insert((collection.id, token, owner), amount);1301		<TotalSupply<T>>::insert((collection.id, token), amount);13021303		match total_pieces.cmp(&amount) {1304			Ordering::Less => {1305				let mint_amount = amount - total_pieces;1306				<PalletEvm<T>>::deposit_log(1307					ERC20Events::Transfer {1308						from: H160::default(),1309						to: *owner.as_eth(),1310						value: mint_amount.into(),1311					}1312					.to_log(T::EvmTokenAddressMapping::token_to_address(1313						collection.id,1314						token,1315					)),1316				);1317				<PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(1318					collection.id,1319					token,1320					owner.clone(),1321					mint_amount,1322				));1323			}1324			Ordering::Greater => {1325				let burn_amount = total_pieces - amount;1326				<PalletEvm<T>>::deposit_log(1327					ERC20Events::Transfer {1328						from: *owner.as_eth(),1329						to: H160::default(),1330						value: burn_amount.into(),1331					}1332					.to_log(T::EvmTokenAddressMapping::token_to_address(1333						collection.id,1334						token,1335					)),1336				);1337				<PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(1338					collection.id,1339					token,1340					owner.clone(),1341					burn_amount,1342				));1343			}1344			Ordering::Equal => {}1345		}13461347		Ok(())1348	}13491350	fn token_owner(1351		collection_id: CollectionId,1352		token_id: TokenId,1353	) -> Result<T::CrossAccountId, TokenOwnerError> {1354		let mut owner = None;1355		let mut count = 0;1356		for key in Balance::<T>::iter_key_prefix((collection_id, token_id)) {1357			count += 1;1358			if count > 1 {1359				return Err(TokenOwnerError::MultipleOwners);1360			}1361			owner = Some(key);1362		}1363		owner.ok_or(TokenOwnerError::NotFound)1364	}13651366	fn total_pieces(collection_id: CollectionId, token_id: TokenId) -> Option<u128> {1367		<TotalSupply<T>>::try_get((collection_id, token_id)).ok()1368	}13691370	pub fn set_collection_properties(1371		collection: &RefungibleHandle<T>,1372		sender: &T::CrossAccountId,1373		properties: Vec<Property>,1374	) -> DispatchResult {1375		<PalletCommon<T>>::set_collection_properties(collection, sender, properties.into_iter())1376	}13771378	pub fn delete_collection_properties(1379		collection: &RefungibleHandle<T>,1380		sender: &T::CrossAccountId,1381		property_keys: Vec<PropertyKey>,1382	) -> DispatchResult {1383		<PalletCommon<T>>::delete_collection_properties(1384			collection,1385			sender,1386			property_keys.into_iter(),1387		)1388	}13891390	pub fn set_token_property_permissions(1391		collection: &RefungibleHandle<T>,1392		sender: &T::CrossAccountId,1393		property_permissions: Vec<PropertyKeyPermission>,1394	) -> DispatchResult {1395		<PalletCommon<T>>::set_token_property_permissions(collection, sender, property_permissions)1396	}13971398	pub fn token_property_permission(collection_id: CollectionId) -> PropertiesPermissionMap {1399		<PalletCommon<T>>::property_permissions(collection_id)1400	}14011402	pub fn set_scoped_token_property_permissions(1403		collection: &RefungibleHandle<T>,1404		sender: &T::CrossAccountId,1405		scope: PropertyScope,1406		property_permissions: Vec<PropertyKeyPermission>,1407	) -> DispatchResult {1408		<PalletCommon<T>>::set_scoped_token_property_permissions(1409			collection,1410			sender,1411			scope,1412			property_permissions,1413		)1414	}14151416	/// Returns 10 token in no particular order.1417	///1418	/// There is no direct way to get token holders in ascending order,1419	/// since `iter_prefix` returns values in no particular order.1420	/// Therefore, getting the 10 largest holders with a large value of holders1421	/// can lead to impact memory allocation + sorting with  `n * log (n)`.1422	pub fn token_owners(1423		collection_id: CollectionId,1424		token: TokenId,1425	) -> Option<Vec<T::CrossAccountId>> {1426		let res: Vec<T::CrossAccountId> = <Balance<T>>::iter_prefix((collection_id, token))1427			.map(|(owner, _amount)| owner)1428			.take(10)1429			.collect();14301431		if res.is_empty() {1432			None1433		} else {1434			Some(res)1435		}1436	}14371438	/// Sets or unsets the approval of a given operator.1439	///1440	/// The `operator` is allowed to transfer all token pieces of the `owner` on their behalf.1441	/// - `owner`: Token owner1442	/// - `operator`: Operator1443	/// - `approve`: Should operator status be granted or revoked?1444	pub fn set_allowance_for_all(1445		collection: &RefungibleHandle<T>,1446		owner: &T::CrossAccountId,1447		spender: &T::CrossAccountId,1448		approve: bool,1449	) -> DispatchResult {1450		<PalletCommon<T>>::set_allowance_for_all(1451			collection,1452			owner,1453			spender,1454			approve,1455			|| <CollectionAllowance<T>>::insert((collection.id, owner, spender), approve),1456			ERC721Events::ApprovalForAll {1457				owner: *owner.as_eth(),1458				operator: *spender.as_eth(),1459				approved: approve,1460			}1461			.to_log(collection_id_to_address(collection.id)),1462		)1463	}14641465	/// Tells whether the given `owner` approves the `operator`.1466	pub fn allowance_for_all(1467		collection: &RefungibleHandle<T>,1468		owner: &T::CrossAccountId,1469		spender: &T::CrossAccountId,1470	) -> bool {1471		<CollectionAllowance<T>>::get((collection.id, owner, spender))1472	}14731474	pub fn repair_item(collection: &RefungibleHandle<T>, token: TokenId) -> DispatchResult {1475		<TokenProperties<T>>::mutate((collection.id, token), |properties| {1476			properties.recompute_consumed_space();1477		});14781479		Ok(())1480	}1481}
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	CommonCollectionOperations, Error as CommonError, eth::collection_id_to_address,100	Event as CommonEvent, Pallet as PalletCommon, SetPropertyMode,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		mode: SetPropertyMode,537		nesting_budget: &dyn Budget,538	) -> DispatchResult {539		let mut is_token_owner =540			pallet_common::LazyValue::new(|| -> Result<bool, DispatchError> {541				if let SetPropertyMode::NewToken {542					mint_target_is_sender,543				} = mode544				{545					return Ok(mint_target_is_sender);546				}547548				let balance = collection.balance(sender.clone(), token_id);549				let total_pieces: u128 =550					Self::total_pieces(collection.id, token_id).unwrap_or(u128::MAX);551				if balance != total_pieces {552					return Ok(false);553				}554555				let is_bundle_owner = <PalletStructure<T>>::check_indirectly_owned(556					sender.clone(),557					collection.id,558					token_id,559					None,560					nesting_budget,561				)?;562563				Ok(is_bundle_owner)564			});565566		let is_new_token = matches!(mode, SetPropertyMode::NewToken { .. });567568		let mut is_token_exist = pallet_common::LazyValue::new(|| {569			if is_new_token {570				debug_assert!(Self::token_exists(collection, token_id));571				true572			} else {573				Self::token_exists(collection, token_id)574			}575		});576577		let stored_properties = if is_new_token {578			debug_assert!(!<TokenProperties<T>>::contains_key((579				collection.id,580				token_id581			)));582			TokenPropertiesT::new()583		} else {584			<TokenProperties<T>>::get((collection.id, token_id))585		};586587		<PalletCommon<T>>::modify_token_properties(588			collection,589			sender,590			token_id,591			&mut is_token_exist,592			properties_updates,593			stored_properties,594			&mut is_token_owner,595			|properties| <TokenProperties<T>>::set((collection.id, token_id), properties),596			erc::ERC721TokenEvent::TokenChanged {597				token_id: token_id.into(),598			}599			.to_log(T::ContractAddress::get()),600		)601	}602603	pub fn next_token_id(collection: &RefungibleHandle<T>) -> Result<TokenId, DispatchError> {604		let next_token_id = <TokensMinted<T>>::get(collection.id)605			.checked_add(1)606			.ok_or(<CommonError<T>>::CollectionTokenLimitExceeded)?;607608		ensure!(609			collection.limits.token_limit() >= next_token_id,610			<CommonError<T>>::CollectionTokenLimitExceeded611		);612613		Ok(TokenId(next_token_id))614	}615616	pub fn set_token_properties(617		collection: &RefungibleHandle<T>,618		sender: &T::CrossAccountId,619		token_id: TokenId,620		properties: impl Iterator<Item = Property>,621		mode: SetPropertyMode,622		nesting_budget: &dyn Budget,623	) -> DispatchResult {624		Self::modify_token_properties(625			collection,626			sender,627			token_id,628			properties.map(|p| (p.key, Some(p.value))),629			mode,630			nesting_budget,631		)632	}633634	pub fn set_token_property(635		collection: &RefungibleHandle<T>,636		sender: &T::CrossAccountId,637		token_id: TokenId,638		property: Property,639		nesting_budget: &dyn Budget,640	) -> DispatchResult {641		Self::set_token_properties(642			collection,643			sender,644			token_id,645			[property].into_iter(),646			SetPropertyMode::ExistingToken,647			nesting_budget,648		)649	}650651	pub fn delete_token_properties(652		collection: &RefungibleHandle<T>,653		sender: &T::CrossAccountId,654		token_id: TokenId,655		property_keys: impl Iterator<Item = PropertyKey>,656		nesting_budget: &dyn Budget,657	) -> DispatchResult {658		Self::modify_token_properties(659			collection,660			sender,661			token_id,662			property_keys.into_iter().map(|key| (key, None)),663			SetPropertyMode::ExistingToken,664			nesting_budget,665		)666	}667668	pub fn delete_token_property(669		collection: &RefungibleHandle<T>,670		sender: &T::CrossAccountId,671		token_id: TokenId,672		property_key: PropertyKey,673		nesting_budget: &dyn Budget,674	) -> DispatchResult {675		Self::delete_token_properties(676			collection,677			sender,678			token_id,679			[property_key].into_iter(),680			nesting_budget,681		)682	}683684	/// Transfer RFT token pieces from one account to another.685	///686	/// If the sender is no longer owns any pieces after the `transfer` than she stops being an owner of the token.687	///688	/// - `from`: Owner of token pieces to transfer.689	/// - `to`: Recepient of transfered token pieces.690	/// - `amount`: Amount of token pieces to transfer.691	/// - `token`: Token whos pieces should be transfered692	/// - `collection`: Collection that contains the token693	pub fn transfer(694		collection: &RefungibleHandle<T>,695		from: &T::CrossAccountId,696		to: &T::CrossAccountId,697		token: TokenId,698		amount: u128,699		nesting_budget: &dyn Budget,700	) -> DispatchResult {701		ensure!(702			collection.limits.transfers_enabled(),703			<CommonError<T>>::TransferNotAllowed704		);705706		if collection.permissions.access() == AccessMode::AllowList {707			collection.check_allowlist(from)?;708			collection.check_allowlist(to)?;709		}710		<PalletCommon<T>>::ensure_correct_receiver(to)?;711712		let initial_balance_from = <Balance<T>>::get((collection.id, token, from));713714		if initial_balance_from == 0 {715			return Err(<CommonError<T>>::TokenValueTooLow.into());716		}717718		let updated_balance_from = initial_balance_from719			.checked_sub(amount)720			.ok_or(<CommonError<T>>::TokenValueTooLow)?;721		let mut create_target = false;722		let from_to_differ = from != to;723		let updated_balance_to = if from != to && amount != 0 {724			let old_balance = <Balance<T>>::get((collection.id, token, to));725			if old_balance == 0 {726				create_target = true;727			}728			Some(729				old_balance730					.checked_add(amount)731					.ok_or(ArithmeticError::Overflow)?,732			)733		} else {734			None735		};736737		let account_balance_from = if updated_balance_from == 0 {738			Some(739				<AccountBalance<T>>::get((collection.id, from))740					.checked_sub(1)741					// Should not occur742					.ok_or(ArithmeticError::Underflow)?,743			)744		} else {745			None746		};747		// Account data is created in token, AccountBalance should be increased748		// But only if from != to as we shouldn't check overflow in this case749		let account_balance_to = if create_target && from_to_differ {750			let account_balance_to = <AccountBalance<T>>::get((collection.id, to))751				.checked_add(1)752				.ok_or(ArithmeticError::Overflow)?;753			ensure!(754				account_balance_to < collection.limits.account_token_ownership_limit(),755				<CommonError<T>>::AccountTokenLimitExceeded,756			);757758			Some(account_balance_to)759		} else {760			None761		};762763		// =========764765		if let Some(updated_balance_to) = updated_balance_to {766			// from != to && amount != 0767768			<PalletStructure<T>>::nest_if_sent_to_token(769				from.clone(),770				to,771				collection.id,772				token,773				nesting_budget,774			)?;775776			if updated_balance_from == 0 {777				<Balance<T>>::remove((collection.id, token, from));778				<PalletStructure<T>>::unnest_if_nested(from, collection.id, token);779			} else {780				<Balance<T>>::insert((collection.id, token, from), updated_balance_from);781			}782			<Balance<T>>::insert((collection.id, token, to), updated_balance_to);783			if let Some(account_balance_from) = account_balance_from {784				<AccountBalance<T>>::insert((collection.id, from), account_balance_from);785				<Owned<T>>::remove((collection.id, from, token));786			}787			if let Some(account_balance_to) = account_balance_to {788				<AccountBalance<T>>::insert((collection.id, to), account_balance_to);789				<Owned<T>>::insert((collection.id, to, token), true);790			}791		}792793		<PalletEvm<T>>::deposit_log(794			ERC20Events::Transfer {795				from: *from.as_eth(),796				to: *to.as_eth(),797				value: amount.into(),798			}799			.to_log(T::EvmTokenAddressMapping::token_to_address(800				collection.id,801				token,802			)),803		);804805		<PalletCommon<T>>::deposit_event(CommonEvent::Transfer(806			collection.id,807			token,808			from.clone(),809			to.clone(),810			amount,811		));812813		let total_supply = <TotalSupply<T>>::get((collection.id, token));814815		if amount == total_supply {816			// if token was fully owned by `from` and will be fully owned by `to` after transfer817			<PalletEvm<T>>::deposit_log(818				ERC721Events::Transfer {819					from: *from.as_eth(),820					to: *to.as_eth(),821					token_id: token.into(),822				}823				.to_log(collection_id_to_address(collection.id)),824			);825		} else if let Some(updated_balance_to) = updated_balance_to {826			// if `from` not equals `to`. This condition is needed to avoid sending event827			// when `from` fully owns token and sends part of token pieces to itself.828			if initial_balance_from == total_supply {829				// if token was fully owned by `from` and will be only partially owned by `to`830				// and `from` after transfer831				<PalletEvm<T>>::deposit_log(832					ERC721Events::Transfer {833						from: *from.as_eth(),834						to: erc::ADDRESS_FOR_PARTIALLY_OWNED_TOKENS,835						token_id: token.into(),836					}837					.to_log(collection_id_to_address(collection.id)),838				);839			} else if updated_balance_to == total_supply {840				// if token was partially owned by `from` and will be fully owned by `to` after transfer841				<PalletEvm<T>>::deposit_log(842					ERC721Events::Transfer {843						from: erc::ADDRESS_FOR_PARTIALLY_OWNED_TOKENS,844						to: *to.as_eth(),845						token_id: token.into(),846					}847					.to_log(collection_id_to_address(collection.id)),848				);849			}850		}851852		Ok(())853	}854855	/// Batched operation to create multiple RFT tokens.856	///857	/// Same as `create_item` but creates multiple tokens.858	///859	/// - `data`: Same as 'data` in `create_item` but contains data for multiple tokens.860	pub fn create_multiple_items(861		collection: &RefungibleHandle<T>,862		sender: &T::CrossAccountId,863		data: Vec<CreateItemData<T>>,864		nesting_budget: &dyn Budget,865	) -> DispatchResult {866		if !collection.is_owner_or_admin(sender) {867			ensure!(868				collection.permissions.mint_mode(),869				<CommonError<T>>::PublicMintingNotAllowed870			);871			collection.check_allowlist(sender)?;872873			for item in data.iter() {874				for user in item.users.keys() {875					collection.check_allowlist(user)?;876				}877			}878		}879880		for item in data.iter() {881			for (owner, _) in item.users.iter() {882				<PalletCommon<T>>::ensure_correct_receiver(owner)?;883			}884		}885886		// Total pieces per tokens887		let totals = data888			.iter()889			.map(|data| {890				Ok(data891					.users892					.iter()893					.map(|u| u.1)894					.try_fold(0u128, |acc, v| acc.checked_add(*v))895					.ok_or(ArithmeticError::Overflow)?)896			})897			.collect::<Result<Vec<_>, DispatchError>>()?;898		for total in &totals {899			ensure!(900				*total <= MAX_REFUNGIBLE_PIECES,901				<Error<T>>::WrongRefungiblePieces902			);903		}904905		let first_token_id = <TokensMinted<T>>::get(collection.id);906		let tokens_minted = first_token_id907			.checked_add(data.len() as u32)908			.ok_or(ArithmeticError::Overflow)?;909		ensure!(910			tokens_minted < collection.limits.token_limit(),911			<CommonError<T>>::CollectionTokenLimitExceeded912		);913914		let mut balances = BTreeMap::new();915		for data in &data {916			for owner in data.users.keys() {917				let balance = balances918					.entry(owner)919					.or_insert_with(|| <AccountBalance<T>>::get((collection.id, owner)));920				*balance = balance.checked_add(1).ok_or(ArithmeticError::Overflow)?;921922				ensure!(923					*balance <= collection.limits.account_token_ownership_limit(),924					<CommonError<T>>::AccountTokenLimitExceeded,925				);926			}927		}928929		for (i, token) in data.iter().enumerate() {930			let token_id = TokenId(first_token_id + i as u32 + 1);931			for (to, _) in token.users.iter() {932				<PalletStructure<T>>::check_nesting(933					sender.clone(),934					to,935					collection.id,936					token_id,937					nesting_budget,938				)?;939			}940		}941942		// =========943944		with_transaction(|| {945			for (i, data) in data.iter().enumerate() {946				let token_id = first_token_id + i as u32 + 1;947				<TotalSupply<T>>::insert((collection.id, token_id), totals[i]);948949				let mut mint_target_is_sender = true;950				for (user, amount) in data.users.iter() {951					if *amount == 0 {952						continue;953					}954955					mint_target_is_sender = mint_target_is_sender && sender.conv_eq(user);956957					<Balance<T>>::insert((collection.id, token_id, &user), amount);958					<Owned<T>>::insert((collection.id, &user, TokenId(token_id)), true);959					<PalletStructure<T>>::nest_if_sent_to_token_unchecked(960						user,961						collection.id,962						TokenId(token_id),963					);964				}965966				if let Err(e) = Self::set_token_properties(967					collection,968					sender,969					TokenId(token_id),970					data.properties.clone().into_iter(),971					SetPropertyMode::NewToken {972						mint_target_is_sender,973					},974					nesting_budget,975				) {976					return TransactionOutcome::Rollback(Err(e));977				}978			}979			TransactionOutcome::Commit(Ok(()))980		})?;981982		<TokensMinted<T>>::insert(collection.id, tokens_minted);983984		for (account, balance) in balances {985			<AccountBalance<T>>::insert((collection.id, account), balance);986		}987988		for (i, token) in data.into_iter().enumerate() {989			let token_id = first_token_id + i as u32 + 1;990991			let receivers = token992				.users993				.into_iter()994				.filter(|(_, amount)| *amount > 0)995				.collect::<Vec<_>>();996997			if let [(user, _)] = receivers.as_slice() {998				// if there is exactly one receiver999				<PalletEvm<T>>::deposit_log(1000					ERC721Events::Transfer {1001						from: H160::default(),1002						to: *user.as_eth(),1003						token_id: token_id.into(),1004					}1005					.to_log(collection_id_to_address(collection.id)),1006				);1007			} else if let [_, ..] = receivers.as_slice() {1008				// if there is more than one receiver1009				<PalletEvm<T>>::deposit_log(1010					ERC721Events::Transfer {1011						from: H160::default(),1012						to: erc::ADDRESS_FOR_PARTIALLY_OWNED_TOKENS,1013						token_id: token_id.into(),1014					}1015					.to_log(collection_id_to_address(collection.id)),1016				);1017			}10181019			for (user, amount) in receivers.into_iter() {1020				<PalletEvm<T>>::deposit_log(1021					ERC20Events::Transfer {1022						from: H160::default(),1023						to: *user.as_eth(),1024						value: amount.into(),1025					}1026					.to_log(T::EvmTokenAddressMapping::token_to_address(1027						collection.id,1028						TokenId(token_id),1029					)),1030				);1031				<PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(1032					collection.id,1033					TokenId(token_id),1034					user,1035					amount,1036				));1037			}1038		}1039		Ok(())1040	}10411042	pub fn set_allowance_unchecked(1043		collection: &RefungibleHandle<T>,1044		sender: &T::CrossAccountId,1045		spender: &T::CrossAccountId,1046		token: TokenId,1047		amount: u128,1048	) {1049		if amount == 0 {1050			<Allowance<T>>::remove((collection.id, token, sender, spender));1051		} else {1052			<Allowance<T>>::insert((collection.id, token, sender, spender), amount);1053		}10541055		<PalletEvm<T>>::deposit_log(1056			ERC20Events::Approval {1057				owner: *sender.as_eth(),1058				spender: *spender.as_eth(),1059				value: amount.into(),1060			}1061			.to_log(T::EvmTokenAddressMapping::token_to_address(1062				collection.id,1063				token,1064			)),1065		);1066		<PalletCommon<T>>::deposit_event(CommonEvent::Approved(1067			collection.id,1068			token,1069			sender.clone(),1070			spender.clone(),1071			amount,1072		))1073	}10741075	/// Set allowance for the spender to `transfer` or `burn` sender's token pieces.1076	///1077	/// - `amount`: Amount of token pieces the spender is allowed to `transfer` or `burn.1078	pub fn set_allowance(1079		collection: &RefungibleHandle<T>,1080		sender: &T::CrossAccountId,1081		spender: &T::CrossAccountId,1082		token: TokenId,1083		amount: u128,1084	) -> DispatchResult {1085		if collection.permissions.access() == AccessMode::AllowList {1086			collection.check_allowlist(sender)?;1087			collection.check_allowlist(spender)?;1088		}10891090		<PalletCommon<T>>::ensure_correct_receiver(spender)?;10911092		if <Balance<T>>::get((collection.id, token, sender)) < amount {1093			ensure!(1094				collection.ignores_owned_amount(sender) && Self::token_exists(collection, token),1095				<CommonError<T>>::CantApproveMoreThanOwned1096			);1097		}10981099		// =========11001101		Self::set_allowance_unchecked(collection, sender, spender, token, amount);1102		Ok(())1103	}11041105	/// Set allowance to spend from sender's eth mirror1106	///1107	/// - `from`: Address of sender's eth mirror.1108	/// - `to`: Adress of spender.1109	/// - `amount`: Amount of token pieces the spender is allowed to `transfer` or `burn.1110	pub fn set_allowance_from(1111		collection: &RefungibleHandle<T>,1112		sender: &T::CrossAccountId,1113		from: &T::CrossAccountId,1114		to: &T::CrossAccountId,1115		token_id: TokenId,1116		amount: u128,1117	) -> DispatchResult {1118		if collection.permissions.access() == AccessMode::AllowList {1119			collection.check_allowlist(sender)?;1120			collection.check_allowlist(from)?;1121			collection.check_allowlist(to)?;1122		}11231124		<PalletCommon<T>>::ensure_correct_receiver(to)?;11251126		ensure!(1127			sender.conv_eq(from),1128			<CommonError<T>>::AddressIsNotEthMirror1129		);11301131		if <Balance<T>>::get((collection.id, token_id, from)) < amount {1132			ensure!(1133				collection.limits.owner_can_transfer()1134					&& (collection.is_owner_or_admin(sender) || collection.is_owner_or_admin(from))1135					&& Self::token_exists(collection, token_id),1136				<CommonError<T>>::CantApproveMoreThanOwned1137			);1138		}11391140		// =========11411142		Self::set_allowance_unchecked(collection, from, to, token_id, amount);1143		Ok(())1144	}11451146	/// Returns allowance, which should be set after transaction1147	fn check_allowed(1148		collection: &RefungibleHandle<T>,1149		spender: &T::CrossAccountId,1150		from: &T::CrossAccountId,1151		token: TokenId,1152		amount: u128,1153		nesting_budget: &dyn Budget,1154	) -> Result<Option<u128>, DispatchError> {1155		if spender.conv_eq(from) {1156			return Ok(None);1157		}1158		if collection.permissions.access() == AccessMode::AllowList {1159			// `from`, `to` checked in [`transfer`]1160			collection.check_allowlist(spender)?;1161		}11621163		if collection.ignores_token_restrictions(spender) {1164			return Ok(Self::compute_allowance_decrease(1165				collection, token, from, spender, amount,1166			));1167		}11681169		if let Some(source) = T::CrossTokenAddressMapping::address_to_token(from) {1170			// TODO: should collection owner be allowed to perform this transfer?1171			ensure!(1172				<PalletStructure<T>>::check_indirectly_owned(1173					spender.clone(),1174					source.0,1175					source.1,1176					None,1177					nesting_budget1178				)?,1179				<CommonError<T>>::ApprovedValueTooLow,1180			);1181			return Ok(None);1182		}11831184		let allowance = Self::compute_allowance_decrease(collection, token, from, spender, amount);1185		if allowance.is_some() {1186			return Ok(allowance);1187		}11881189		// Allowance (if any) would be reduced if spender is also wallet operator1190		if <CollectionAllowance<T>>::get((collection.id, from, spender)) {1191			return Ok(allowance);1192		}11931194		Err(<CommonError<T>>::ApprovedValueTooLow.into())1195	}11961197	/// Returns `Some(amount)` if the `spender` have allowance to spend this amount.1198	/// Otherwise, it returns `None`.1199	fn compute_allowance_decrease(1200		collection: &RefungibleHandle<T>,1201		token: TokenId,1202		from: &T::CrossAccountId,1203		spender: &T::CrossAccountId,1204		amount: u128,1205	) -> Option<u128> {1206		<Allowance<T>>::get((collection.id, token, from, spender)).checked_sub(amount)1207	}12081209	/// Transfer RFT token pieces from one account to another.1210	///1211	/// Same as the [`transfer`] but spender doesn't needs to be an owner of the token pieces.1212	/// The owner should set allowance for the spender to transfer pieces.1213	///1214	/// [`transfer`]: struct.Pallet.html#method.transfer1215	pub fn transfer_from(1216		collection: &RefungibleHandle<T>,1217		spender: &T::CrossAccountId,1218		from: &T::CrossAccountId,1219		to: &T::CrossAccountId,1220		token: TokenId,1221		amount: u128,1222		nesting_budget: &dyn Budget,1223	) -> DispatchResult {1224		let allowance =1225			Self::check_allowed(collection, spender, from, token, amount, nesting_budget)?;12261227		// =========12281229		Self::transfer(collection, from, to, token, amount, nesting_budget)?;1230		if let Some(allowance) = allowance {1231			Self::set_allowance_unchecked(collection, from, spender, token, allowance);1232		}1233		Ok(())1234	}12351236	/// Burn RFT token pieces from the account.1237	///1238	/// Same as the [`burn`] but spender doesn't need to be an owner of the token pieces. The owner should1239	/// set allowance for the spender to burn pieces1240	///1241	/// [`burn`]: struct.Pallet.html#method.burn1242	pub fn burn_from(1243		collection: &RefungibleHandle<T>,1244		spender: &T::CrossAccountId,1245		from: &T::CrossAccountId,1246		token: TokenId,1247		amount: u128,1248		nesting_budget: &dyn Budget,1249	) -> DispatchResult {1250		let allowance =1251			Self::check_allowed(collection, spender, from, token, amount, nesting_budget)?;12521253		// =========12541255		Self::burn(collection, from, token, amount)?;1256		if let Some(allowance) = allowance {1257			Self::set_allowance_unchecked(collection, from, spender, token, allowance);1258		}1259		Ok(())1260	}12611262	/// Create RFT token.1263	///1264	/// The sender should be the owner/admin of the collection or collection should be configured1265	/// to allow public minting.1266	///1267	/// - `data`: Contains list of users who will become the owners of the token pieces and amount1268	///   of token pieces they will receive.1269	pub fn create_item(1270		collection: &RefungibleHandle<T>,1271		sender: &T::CrossAccountId,1272		data: CreateItemData<T>,1273		nesting_budget: &dyn Budget,1274	) -> DispatchResult {1275		Self::create_multiple_items(collection, sender, vec![data], nesting_budget)1276	}12771278	/// Repartition RFT token.1279	///1280	/// `repartition` will set token balance of the sender and total amount of token pieces.1281	/// Sender should own all of the token pieces. `repartition' could be done even if some1282	/// token pieces were burned before.1283	///1284	/// - `amount`: Total amount of token pieces that the token will have after `repartition`.1285	pub fn repartition(1286		collection: &RefungibleHandle<T>,1287		owner: &T::CrossAccountId,1288		token: TokenId,1289		amount: u128,1290	) -> DispatchResult {1291		ensure!(1292			amount <= MAX_REFUNGIBLE_PIECES,1293			<Error<T>>::WrongRefungiblePieces1294		);1295		ensure!(amount > 0, <CommonError<T>>::TokenValueTooLow);1296		// Ensure user owns all pieces1297		let total_pieces = Self::total_pieces(collection.id, token).unwrap_or(u128::MAX);1298		let balance = <Balance<T>>::get((collection.id, token, owner));1299		ensure!(1300			total_pieces == balance,1301			<Error<T>>::RepartitionWhileNotOwningAllPieces1302		);13031304		<Balance<T>>::insert((collection.id, token, owner), amount);1305		<TotalSupply<T>>::insert((collection.id, token), amount);13061307		match total_pieces.cmp(&amount) {1308			Ordering::Less => {1309				let mint_amount = amount - total_pieces;1310				<PalletEvm<T>>::deposit_log(1311					ERC20Events::Transfer {1312						from: H160::default(),1313						to: *owner.as_eth(),1314						value: mint_amount.into(),1315					}1316					.to_log(T::EvmTokenAddressMapping::token_to_address(1317						collection.id,1318						token,1319					)),1320				);1321				<PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(1322					collection.id,1323					token,1324					owner.clone(),1325					mint_amount,1326				));1327			}1328			Ordering::Greater => {1329				let burn_amount = total_pieces - amount;1330				<PalletEvm<T>>::deposit_log(1331					ERC20Events::Transfer {1332						from: *owner.as_eth(),1333						to: H160::default(),1334						value: burn_amount.into(),1335					}1336					.to_log(T::EvmTokenAddressMapping::token_to_address(1337						collection.id,1338						token,1339					)),1340				);1341				<PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(1342					collection.id,1343					token,1344					owner.clone(),1345					burn_amount,1346				));1347			}1348			Ordering::Equal => {}1349		}13501351		Ok(())1352	}13531354	fn token_owner(1355		collection_id: CollectionId,1356		token_id: TokenId,1357	) -> Result<T::CrossAccountId, TokenOwnerError> {1358		let mut owner = None;1359		let mut count = 0;1360		for key in Balance::<T>::iter_key_prefix((collection_id, token_id)) {1361			count += 1;1362			if count > 1 {1363				return Err(TokenOwnerError::MultipleOwners);1364			}1365			owner = Some(key);1366		}1367		owner.ok_or(TokenOwnerError::NotFound)1368	}13691370	fn total_pieces(collection_id: CollectionId, token_id: TokenId) -> Option<u128> {1371		<TotalSupply<T>>::try_get((collection_id, token_id)).ok()1372	}13731374	pub fn set_collection_properties(1375		collection: &RefungibleHandle<T>,1376		sender: &T::CrossAccountId,1377		properties: Vec<Property>,1378	) -> DispatchResult {1379		<PalletCommon<T>>::set_collection_properties(collection, sender, properties.into_iter())1380	}13811382	pub fn delete_collection_properties(1383		collection: &RefungibleHandle<T>,1384		sender: &T::CrossAccountId,1385		property_keys: Vec<PropertyKey>,1386	) -> DispatchResult {1387		<PalletCommon<T>>::delete_collection_properties(1388			collection,1389			sender,1390			property_keys.into_iter(),1391		)1392	}13931394	pub fn set_token_property_permissions(1395		collection: &RefungibleHandle<T>,1396		sender: &T::CrossAccountId,1397		property_permissions: Vec<PropertyKeyPermission>,1398	) -> DispatchResult {1399		<PalletCommon<T>>::set_token_property_permissions(collection, sender, property_permissions)1400	}14011402	pub fn token_property_permission(collection_id: CollectionId) -> PropertiesPermissionMap {1403		<PalletCommon<T>>::property_permissions(collection_id)1404	}14051406	pub fn set_scoped_token_property_permissions(1407		collection: &RefungibleHandle<T>,1408		sender: &T::CrossAccountId,1409		scope: PropertyScope,1410		property_permissions: Vec<PropertyKeyPermission>,1411	) -> DispatchResult {1412		<PalletCommon<T>>::set_scoped_token_property_permissions(1413			collection,1414			sender,1415			scope,1416			property_permissions,1417		)1418	}14191420	/// Returns 10 token in no particular order.1421	///1422	/// There is no direct way to get token holders in ascending order,1423	/// since `iter_prefix` returns values in no particular order.1424	/// Therefore, getting the 10 largest holders with a large value of holders1425	/// can lead to impact memory allocation + sorting with  `n * log (n)`.1426	pub fn token_owners(1427		collection_id: CollectionId,1428		token: TokenId,1429	) -> Option<Vec<T::CrossAccountId>> {1430		let res: Vec<T::CrossAccountId> = <Balance<T>>::iter_prefix((collection_id, token))1431			.map(|(owner, _amount)| owner)1432			.take(10)1433			.collect();14341435		if res.is_empty() {1436			None1437		} else {1438			Some(res)1439		}1440	}14411442	/// Sets or unsets the approval of a given operator.1443	///1444	/// The `operator` is allowed to transfer all token pieces of the `owner` on their behalf.1445	/// - `owner`: Token owner1446	/// - `operator`: Operator1447	/// - `approve`: Should operator status be granted or revoked?1448	pub fn set_allowance_for_all(1449		collection: &RefungibleHandle<T>,1450		owner: &T::CrossAccountId,1451		spender: &T::CrossAccountId,1452		approve: bool,1453	) -> DispatchResult {1454		<PalletCommon<T>>::set_allowance_for_all(1455			collection,1456			owner,1457			spender,1458			approve,1459			|| <CollectionAllowance<T>>::insert((collection.id, owner, spender), approve),1460			ERC721Events::ApprovalForAll {1461				owner: *owner.as_eth(),1462				operator: *spender.as_eth(),1463				approved: approve,1464			}1465			.to_log(collection_id_to_address(collection.id)),1466		)1467	}14681469	/// Tells whether the given `owner` approves the `operator`.1470	pub fn allowance_for_all(1471		collection: &RefungibleHandle<T>,1472		owner: &T::CrossAccountId,1473		spender: &T::CrossAccountId,1474	) -> bool {1475		<CollectionAllowance<T>>::get((collection.id, owner, spender))1476	}14771478	pub fn repair_item(collection: &RefungibleHandle<T>, token: TokenId) -> DispatchResult {1479		<TokenProperties<T>>::mutate((collection.id, token), |properties| {1480			properties.recompute_consumed_space();1481		});14821483		Ok(())1484	}1485}