git.delta.rocks / unique-network / refs/commits / 67ee4bedd37d

difftreelog

source

pallets/refungible/src/lib.rs41.1 KiBsourcehistory
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 core::{cmp::Ordering, ops::Deref};9192use evm_coder::ToLog;93use frame_support::{ensure, storage::with_transaction, transactional};94pub use pallet::*;95use pallet_common::{96	eth::collection_id_to_address, Error as CommonError, Event as CommonEvent,97	Pallet as PalletCommon,98};99use pallet_evm::{account::CrossAccountId, Pallet as PalletEvm};100use pallet_evm_coder_substrate::WithRecorder;101use pallet_structure::Pallet as PalletStructure;102use sp_core::{Get, H160};103use sp_runtime::{ArithmeticError, DispatchError, DispatchResult, TransactionOutcome};104use sp_std::{collections::btree_map::BTreeMap, vec, vec::Vec};105use up_data_structs::{106	budget::Budget, mapping::TokenAddressMapping, AccessMode, CollectionId,107	CreateRefungibleExMultipleOwners, PropertiesPermissionMap, Property, PropertyKey,108	PropertyKeyPermission, PropertyScope, PropertyValue, TokenId, TokenOwnerError,109	TokenProperties as TokenPropertiesT, MAX_REFUNGIBLE_PIECES,110};111112use crate::{erc::ERC721Events, erc_token::ERC20Events};113#[cfg(feature = "runtime-benchmarks")]114pub mod benchmarking;115pub mod common;116pub mod erc;117pub mod erc_token;118pub mod weights;119120pub type CreateItemData<T> =121	CreateRefungibleExMultipleOwners<<T as pallet_evm::Config>::CrossAccountId>;122pub(crate) type SelfWeightOf<T> = <T as Config>::WeightInfo;123124#[frame_support::pallet]125pub mod pallet {126	use frame_support::{127		pallet_prelude::*, storage::Key, traits::StorageVersion, Blake2_128, Blake2_128Concat,128		Twox64Concat,129	};130	use up_data_structs::{CollectionId, TokenId};131132	use super::{weights::WeightInfo, *};133134	#[pallet::error]135	pub enum Error<T> {136		/// Not Refungible item data used to mint in Refungible collection.137		NotRefungibleDataUsedToMintFungibleCollectionToken,138		/// Maximum refungibility exceeded.139		WrongRefungiblePieces,140		/// Refungible token can't be repartitioned by user who isn't owns all pieces.141		RepartitionWhileNotOwningAllPieces,142		/// Refungible token can't nest other tokens.143		RefungibleDisallowsNesting,144		/// Setting item properties is not allowed.145		SettingPropertiesNotAllowed,146	}147148	#[pallet::config]149	pub trait Config:150		frame_system::Config + pallet_common::Config + pallet_structure::Config151	{152		type WeightInfo: WeightInfo;153	}154155	const STORAGE_VERSION: StorageVersion = StorageVersion::new(2);156157	#[pallet::pallet]158	#[pallet::storage_version(STORAGE_VERSION)]159	pub struct Pallet<T>(_);160161	/// Total amount of minted tokens in a collection.162	#[pallet::storage]163	pub type TokensMinted<T: Config> =164		StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;165166	/// Amount of tokens burnt in a collection.167	#[pallet::storage]168	pub type TokensBurnt<T: Config> =169		StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;170171	/// Amount of pieces a refungible token is split into.172	#[pallet::storage]173	#[pallet::getter(fn token_properties)]174	pub type TokenProperties<T: Config> = StorageNMap<175		Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),176		Value = TokenPropertiesT,177		QueryKind = OptionQuery,178	>;179180	/// Total amount of pieces for token181	#[pallet::storage]182	pub type TotalSupply<T: Config> = StorageNMap<183		Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),184		Value = u128,185		QueryKind = ValueQuery,186	>;187188	/// Used to enumerate tokens owned by account.189	#[pallet::storage]190	pub type Owned<T: Config> = StorageNMap<191		Key = (192			Key<Twox64Concat, CollectionId>,193			Key<Blake2_128Concat, T::CrossAccountId>,194			Key<Twox64Concat, TokenId>,195		),196		Value = bool,197		QueryKind = ValueQuery,198	>;199200	/// Amount of tokens (not pieces) partially owned by an account within a collection.201	#[pallet::storage]202	pub type AccountBalance<T: Config> = StorageNMap<203		Key = (204			Key<Twox64Concat, CollectionId>,205			// Owner206			Key<Blake2_128Concat, T::CrossAccountId>,207		),208		Value = u32,209		QueryKind = ValueQuery,210	>;211212	/// Amount of token pieces owned by account.213	#[pallet::storage]214	pub type Balance<T: Config> = StorageNMap<215		Key = (216			Key<Twox64Concat, CollectionId>,217			Key<Twox64Concat, TokenId>,218			// Owner219			Key<Blake2_128Concat, T::CrossAccountId>,220		),221		Value = u128,222		QueryKind = ValueQuery,223	>;224225	/// Allowance set by a token owner for another user to perform one of certain transactions on a number of pieces of a token.226	#[pallet::storage]227	pub type Allowance<T: Config> = StorageNMap<228		Key = (229			Key<Twox64Concat, CollectionId>,230			Key<Twox64Concat, TokenId>,231			// Owner232			Key<Blake2_128, T::CrossAccountId>,233			// Spender234			Key<Blake2_128Concat, T::CrossAccountId>,235		),236		Value = u128,237		QueryKind = ValueQuery,238	>;239240	/// Spender set by a wallet owner that could perform certain transactions on all tokens in the wallet.241	#[pallet::storage]242	pub type CollectionAllowance<T: Config> = StorageNMap<243		Key = (244			Key<Twox64Concat, CollectionId>,245			Key<Blake2_128Concat, T::CrossAccountId>, // Owner246			Key<Blake2_128Concat, T::CrossAccountId>, // Spender247		),248		Value = bool,249		QueryKind = ValueQuery,250	>;251}252253pub struct RefungibleHandle<T: Config>(pallet_common::CollectionHandle<T>);254impl<T: Config> RefungibleHandle<T> {255	pub fn cast(inner: pallet_common::CollectionHandle<T>) -> Self {256		Self(inner)257	}258	pub fn into_inner(self) -> pallet_common::CollectionHandle<T> {259		self.0260	}261	pub fn common_mut(&mut self) -> &mut pallet_common::CollectionHandle<T> {262		&mut self.0263	}264}265266impl<T: Config> Deref for RefungibleHandle<T> {267	type Target = pallet_common::CollectionHandle<T>;268269	fn deref(&self) -> &Self::Target {270		&self.0271	}272}273274impl<T: Config> WithRecorder<T> for RefungibleHandle<T> {275	fn recorder(&self) -> &pallet_evm_coder_substrate::SubstrateRecorder<T> {276		self.0.recorder()277	}278	fn into_recorder(self) -> pallet_evm_coder_substrate::SubstrateRecorder<T> {279		self.0.into_recorder()280	}281}282283impl<T: Config> Pallet<T> {284	/// Get number of RFT tokens in collection285	pub fn total_supply(collection: &RefungibleHandle<T>) -> u32 {286		<TokensMinted<T>>::get(collection.id) - <TokensBurnt<T>>::get(collection.id)287	}288289	/// Check that RFT token exists290	///291	/// - `token`: Token ID.292	pub fn token_exists(collection: &RefungibleHandle<T>, token: TokenId) -> bool {293		<TotalSupply<T>>::contains_key((collection.id, token))294	}295}296297// unchecked calls skips any permission checks298impl<T: Config> Pallet<T> {299	/// Destroy RFT collection300	///301	/// `destroy_collection` will throw error if collection contains any tokens.302	/// Only owner can destroy collection.303	pub fn destroy_collection(304		collection: RefungibleHandle<T>,305		sender: &T::CrossAccountId,306	) -> DispatchResult {307		let id = collection.id;308309		if Self::collection_has_tokens(id) {310			return Err(<CommonError<T>>::CantDestroyNotEmptyCollection.into());311		}312313		// =========314315		PalletCommon::destroy_collection(collection.0, sender)?;316317		<TokensMinted<T>>::remove(id);318		<TokensBurnt<T>>::remove(id);319		let _ = <TotalSupply<T>>::clear_prefix((id,), u32::MAX, None);320		let _ = <Balance<T>>::clear_prefix((id,), u32::MAX, None);321		let _ = <Allowance<T>>::clear_prefix((id,), u32::MAX, None);322		let _ = <Owned<T>>::clear_prefix((id,), u32::MAX, None);323		let _ = <AccountBalance<T>>::clear_prefix((id,), u32::MAX, None);324		Ok(())325	}326327	fn collection_has_tokens(collection_id: CollectionId) -> bool {328		<TotalSupply<T>>::iter_prefix((collection_id,))329			.next()330			.is_some()331	}332333	pub fn burn_token_unchecked(334		collection: &RefungibleHandle<T>,335		owner: &T::CrossAccountId,336		token_id: TokenId,337	) -> DispatchResult {338		let burnt = <TokensBurnt<T>>::get(collection.id)339			.checked_add(1)340			.ok_or(ArithmeticError::Overflow)?;341342		<TokensBurnt<T>>::insert(collection.id, burnt);343		<TokenProperties<T>>::remove((collection.id, token_id));344		<TotalSupply<T>>::remove((collection.id, token_id));345		let _ = <Balance<T>>::clear_prefix((collection.id, token_id), u32::MAX, None);346		let _ = <Allowance<T>>::clear_prefix((collection.id, token_id), u32::MAX, None);347		<PalletEvm<T>>::deposit_log(348			ERC721Events::Transfer {349				from: *owner.as_eth(),350				to: H160::default(),351				token_id: token_id.into(),352			}353			.to_log(collection_id_to_address(collection.id)),354		);355		Ok(())356	}357358	/// Burn RFT token pieces359	///360	/// `burn` will decrease total amount of token pieces and amount owned by sender.361	/// `burn` can be called even if there are multiple owners of the RFT token.362	/// If sender wouldn't have any pieces left after `burn` than she will stop being363	/// one of the owners of the token. If there is no account that owns any pieces of364	/// the token than token will be burned too.365	///366	/// - `amount`: Amount of token pieces to burn.367	/// - `token`: Token who's pieces should be burned368	/// - `collection`: Collection that contains the token369	pub fn burn(370		collection: &RefungibleHandle<T>,371		owner: &T::CrossAccountId,372		token: TokenId,373		amount: u128,374	) -> DispatchResult {375		if <Balance<T>>::get((collection.id, token, owner)) == 0 {376			return Err(<CommonError<T>>::TokenValueTooLow.into());377		}378379		let total_supply = <TotalSupply<T>>::get((collection.id, token))380			.checked_sub(amount)381			.ok_or(<CommonError<T>>::TokenValueTooLow)?;382383		// This was probally last owner of this token?384		if total_supply == 0 {385			// Ensure user actually owns this amount386			ensure!(387				<Balance<T>>::get((collection.id, token, owner)) == amount,388				<CommonError<T>>::TokenValueTooLow389			);390			let account_balance = <AccountBalance<T>>::get((collection.id, owner))391				.checked_sub(1)392				// Should not occur393				.ok_or(ArithmeticError::Underflow)?;394395			// =========396397			<Owned<T>>::remove((collection.id, owner, token));398			<PalletStructure<T>>::unnest_if_nested(owner, collection.id, token);399			<AccountBalance<T>>::insert((collection.id, owner), account_balance);400			Self::burn_token_unchecked(collection, owner, token)?;401			<PalletEvm<T>>::deposit_log(402				ERC20Events::Transfer {403					from: *owner.as_eth(),404					to: H160::default(),405					value: amount.into(),406				}407				.to_log(collection_id_to_address(collection.id)),408			);409			<PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(410				collection.id,411				token,412				owner.clone(),413				amount,414			));415			return Ok(());416		}417418		let balance = <Balance<T>>::get((collection.id, token, owner))419			.checked_sub(amount)420			.ok_or(<CommonError<T>>::TokenValueTooLow)?;421		let account_balance = if balance == 0 {422			<AccountBalance<T>>::get((collection.id, owner))423				.checked_sub(1)424				// Should not occur425				.ok_or(ArithmeticError::Underflow)?426		} else {427			0428		};429430		// =========431432		if balance == 0 {433			<Owned<T>>::remove((collection.id, owner, token));434			<PalletStructure<T>>::unnest_if_nested(owner, collection.id, token);435			<Balance<T>>::remove((collection.id, token, owner));436			<AccountBalance<T>>::insert((collection.id, owner), account_balance);437438			if let Ok(user) = Self::token_owner(collection.id, token) {439				<PalletEvm<T>>::deposit_log(440					ERC721Events::Transfer {441						from: erc::ADDRESS_FOR_PARTIALLY_OWNED_TOKENS,442						to: *user.as_eth(),443						token_id: token.into(),444					}445					.to_log(collection_id_to_address(collection.id)),446				);447			}448		} else {449			<Balance<T>>::insert((collection.id, token, owner), balance);450		}451		<TotalSupply<T>>::insert((collection.id, token), total_supply);452453		<PalletEvm<T>>::deposit_log(454			ERC20Events::Transfer {455				from: *owner.as_eth(),456				to: H160::default(),457				value: amount.into(),458			}459			.to_log(T::EvmTokenAddressMapping::token_to_address(460				collection.id,461				token,462			)),463		);464		<PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(465			collection.id,466			token,467			owner.clone(),468			amount,469		));470		Ok(())471	}472473	/// A batch operation to add, edit or remove properties for a token.474	/// It sets or removes a token's properties according to475	/// `properties_updates` contents:476	/// * sets a property under the <key> with the value provided `(<key>, Some(<value>))`477	/// * removes a property under the <key> if the value is `None` `(<key>, None)`.478	///479	/// - `nesting_budget`: Limit for searching parents in-depth to check ownership.480	///481	/// All affected properties should have `mutable` permission482	/// to be **deleted** or to be **set more than once**,483	/// and the sender should have permission to edit those properties.484	///485	/// This function fires an event for each property change.486	/// In case of an error, all the changes (including the events) will be reverted487	/// since the function is transactional.488	#[transactional]489	fn modify_token_properties(490		collection: &RefungibleHandle<T>,491		sender: &T::CrossAccountId,492		token_id: TokenId,493		properties_updates: impl Iterator<Item = (PropertyKey, Option<PropertyValue>)>,494		nesting_budget: &dyn Budget,495	) -> DispatchResult {496		let mut property_writer =497			pallet_common::ExistingTokenPropertyWriter::new(collection, sender);498499		property_writer.write_token_properties(500			sender,501			token_id,502			properties_updates,503			nesting_budget,504			erc::ERC721TokenEvent::TokenChanged {505				token_id: token_id.into(),506			}507			.to_log(T::ContractAddress::get()),508		)509	}510511	pub fn next_token_id(collection: &RefungibleHandle<T>) -> Result<TokenId, DispatchError> {512		let next_token_id = <TokensMinted<T>>::get(collection.id)513			.checked_add(1)514			.ok_or(<CommonError<T>>::CollectionTokenLimitExceeded)?;515516		ensure!(517			collection.limits.token_limit() >= next_token_id,518			<CommonError<T>>::CollectionTokenLimitExceeded519		);520521		Ok(TokenId(next_token_id))522	}523524	pub fn set_token_properties(525		collection: &RefungibleHandle<T>,526		sender: &T::CrossAccountId,527		token_id: TokenId,528		properties: impl Iterator<Item = Property>,529		nesting_budget: &dyn Budget,530	) -> DispatchResult {531		Self::modify_token_properties(532			collection,533			sender,534			token_id,535			properties.map(|p| (p.key, Some(p.value))),536			nesting_budget,537		)538	}539540	pub fn set_token_property(541		collection: &RefungibleHandle<T>,542		sender: &T::CrossAccountId,543		token_id: TokenId,544		property: Property,545		nesting_budget: &dyn Budget,546	) -> DispatchResult {547		Self::set_token_properties(548			collection,549			sender,550			token_id,551			[property].into_iter(),552			nesting_budget,553		)554	}555556	pub fn delete_token_properties(557		collection: &RefungibleHandle<T>,558		sender: &T::CrossAccountId,559		token_id: TokenId,560		property_keys: impl Iterator<Item = PropertyKey>,561		nesting_budget: &dyn Budget,562	) -> DispatchResult {563		Self::modify_token_properties(564			collection,565			sender,566			token_id,567			property_keys.into_iter().map(|key| (key, None)),568			nesting_budget,569		)570	}571572	pub fn delete_token_property(573		collection: &RefungibleHandle<T>,574		sender: &T::CrossAccountId,575		token_id: TokenId,576		property_key: PropertyKey,577		nesting_budget: &dyn Budget,578	) -> DispatchResult {579		Self::delete_token_properties(580			collection,581			sender,582			token_id,583			[property_key].into_iter(),584			nesting_budget,585		)586	}587588	/// Transfer RFT token pieces from one account to another.589	///590	/// If the sender is no longer owns any pieces after the `transfer` than she stops being an owner of the token.591	///592	/// - `from`: Owner of token pieces to transfer.593	/// - `to`: Recepient of transfered token pieces.594	/// - `amount`: Amount of token pieces to transfer.595	/// - `token`: Token whos pieces should be transfered596	/// - `collection`: Collection that contains the token597	pub fn transfer(598		collection: &RefungibleHandle<T>,599		from: &T::CrossAccountId,600		to: &T::CrossAccountId,601		token: TokenId,602		amount: u128,603		nesting_budget: &dyn Budget,604	) -> DispatchResult {605		let depositor = from;606		Self::transfer_internal(607			collection,608			depositor,609			from,610			to,611			token,612			amount,613			nesting_budget,614		)615	}616617	/// Transfers RFT tokens from the `from` account to the `to` account.618	/// The `depositor` is the account who deposits the tokens.619	/// For instance, the nesting rules will be checked against the `depositor`'s permissions.620	pub fn transfer_internal(621		collection: &RefungibleHandle<T>,622		depositor: &T::CrossAccountId,623		from: &T::CrossAccountId,624		to: &T::CrossAccountId,625		token: TokenId,626		amount: u128,627		nesting_budget: &dyn Budget,628	) -> DispatchResult {629		ensure!(630			collection.limits.transfers_enabled(),631			<CommonError<T>>::TransferNotAllowed632		);633634		if collection.permissions.access() == AccessMode::AllowList {635			collection.check_allowlist(from)?;636			collection.check_allowlist(to)?;637		}638		<PalletCommon<T>>::ensure_correct_receiver(to)?;639640		let initial_balance_from = <Balance<T>>::get((collection.id, token, from));641642		if initial_balance_from == 0 {643			return Err(<CommonError<T>>::TokenValueTooLow.into());644		}645646		let updated_balance_from = initial_balance_from647			.checked_sub(amount)648			.ok_or(<CommonError<T>>::TokenValueTooLow)?;649		let mut create_target = false;650		let from_to_differ = from != to;651		let updated_balance_to = if from != to && amount != 0 {652			let old_balance = <Balance<T>>::get((collection.id, token, to));653			if old_balance == 0 {654				create_target = true;655			}656			Some(657				old_balance658					.checked_add(amount)659					.ok_or(ArithmeticError::Overflow)?,660			)661		} else {662			None663		};664665		let account_balance_from = if updated_balance_from == 0 {666			Some(667				<AccountBalance<T>>::get((collection.id, from))668					.checked_sub(1)669					// Should not occur670					.ok_or(ArithmeticError::Underflow)?,671			)672		} else {673			None674		};675		// Account data is created in token, AccountBalance should be increased676		// But only if from != to as we shouldn't check overflow in this case677		let account_balance_to = if create_target && from_to_differ {678			let account_balance_to = <AccountBalance<T>>::get((collection.id, to))679				.checked_add(1)680				.ok_or(ArithmeticError::Overflow)?;681			ensure!(682				account_balance_to < collection.limits.account_token_ownership_limit(),683				<CommonError<T>>::AccountTokenLimitExceeded,684			);685686			Some(account_balance_to)687		} else {688			None689		};690691		// =========692693		if let Some(updated_balance_to) = updated_balance_to {694			// from != to && amount != 0695696			<PalletStructure<T>>::nest_if_sent_to_token(697				depositor,698				to,699				collection.id,700				token,701				nesting_budget,702			)?;703704			if updated_balance_from == 0 {705				<Balance<T>>::remove((collection.id, token, from));706				<PalletStructure<T>>::unnest_if_nested(from, collection.id, token);707			} else {708				<Balance<T>>::insert((collection.id, token, from), updated_balance_from);709			}710			<Balance<T>>::insert((collection.id, token, to), updated_balance_to);711			if let Some(account_balance_from) = account_balance_from {712				<AccountBalance<T>>::insert((collection.id, from), account_balance_from);713				<Owned<T>>::remove((collection.id, from, token));714			}715			if let Some(account_balance_to) = account_balance_to {716				<AccountBalance<T>>::insert((collection.id, to), account_balance_to);717				<Owned<T>>::insert((collection.id, to, token), true);718			}719		}720721		<PalletEvm<T>>::deposit_log(722			ERC20Events::Transfer {723				from: *from.as_eth(),724				to: *to.as_eth(),725				value: amount.into(),726			}727			.to_log(T::EvmTokenAddressMapping::token_to_address(728				collection.id,729				token,730			)),731		);732733		<PalletCommon<T>>::deposit_event(CommonEvent::Transfer(734			collection.id,735			token,736			from.clone(),737			to.clone(),738			amount,739		));740741		let total_supply = <TotalSupply<T>>::get((collection.id, token));742743		if amount == total_supply {744			// if token was fully owned by `from` and will be fully owned by `to` after transfer745			<PalletEvm<T>>::deposit_log(746				ERC721Events::Transfer {747					from: *from.as_eth(),748					to: *to.as_eth(),749					token_id: token.into(),750				}751				.to_log(collection_id_to_address(collection.id)),752			);753		} else if let Some(updated_balance_to) = updated_balance_to {754			// if `from` not equals `to`. This condition is needed to avoid sending event755			// when `from` fully owns token and sends part of token pieces to itself.756			if initial_balance_from == total_supply {757				// if token was fully owned by `from` and will be only partially owned by `to`758				// and `from` after transfer759				<PalletEvm<T>>::deposit_log(760					ERC721Events::Transfer {761						from: *from.as_eth(),762						to: erc::ADDRESS_FOR_PARTIALLY_OWNED_TOKENS,763						token_id: token.into(),764					}765					.to_log(collection_id_to_address(collection.id)),766				);767			} else if updated_balance_to == total_supply {768				// if token was partially owned by `from` and will be fully owned by `to` after transfer769				<PalletEvm<T>>::deposit_log(770					ERC721Events::Transfer {771						from: erc::ADDRESS_FOR_PARTIALLY_OWNED_TOKENS,772						to: *to.as_eth(),773						token_id: token.into(),774					}775					.to_log(collection_id_to_address(collection.id)),776				);777			}778		}779780		Ok(())781	}782783	/// Batched operation to create multiple RFT tokens.784	///785	/// Same as `create_item` but creates multiple tokens.786	///787	/// - `data`: Same as 'data` in `create_item` but contains data for multiple tokens.788	pub fn create_multiple_items(789		collection: &RefungibleHandle<T>,790		sender: &T::CrossAccountId,791		data: Vec<CreateItemData<T>>,792		nesting_budget: &dyn Budget,793	) -> DispatchResult {794		if !collection.is_owner_or_admin(sender) {795			ensure!(796				collection.permissions.mint_mode(),797				<CommonError<T>>::PublicMintingNotAllowed798			);799			collection.check_allowlist(sender)?;800801			for item in data.iter() {802				for user in item.users.keys() {803					collection.check_allowlist(user)?;804				}805			}806		}807808		for item in data.iter() {809			for (owner, _) in item.users.iter() {810				<PalletCommon<T>>::ensure_correct_receiver(owner)?;811			}812		}813814		// Total pieces per tokens815		let totals = data816			.iter()817			.map(|data| {818				Ok(data819					.users820					.iter()821					.map(|u| u.1)822					.try_fold(0u128, |acc, v| acc.checked_add(*v))823					.ok_or(ArithmeticError::Overflow)?)824			})825			.collect::<Result<Vec<_>, DispatchError>>()?;826		for total in &totals {827			ensure!(828				*total <= MAX_REFUNGIBLE_PIECES,829				<Error<T>>::WrongRefungiblePieces830			);831		}832833		let first_token_id = <TokensMinted<T>>::get(collection.id);834		let tokens_minted = first_token_id835			.checked_add(data.len() as u32)836			.ok_or(ArithmeticError::Overflow)?;837		ensure!(838			tokens_minted < collection.limits.token_limit(),839			<CommonError<T>>::CollectionTokenLimitExceeded840		);841842		let mut balances = BTreeMap::new();843		for data in &data {844			for owner in data.users.keys() {845				let balance = balances846					.entry(owner)847					.or_insert_with(|| <AccountBalance<T>>::get((collection.id, owner)));848				*balance = balance.checked_add(1).ok_or(ArithmeticError::Overflow)?;849850				ensure!(851					*balance <= collection.limits.account_token_ownership_limit(),852					<CommonError<T>>::AccountTokenLimitExceeded,853				);854			}855		}856857		for (i, token) in data.iter().enumerate() {858			let token_id = TokenId(first_token_id + i as u32 + 1);859			for (to, _) in token.users.iter() {860				<PalletStructure<T>>::check_nesting(861					sender,862					to,863					collection.id,864					token_id,865					nesting_budget,866				)?;867			}868		}869870		// =========871872		let mut property_writer = pallet_common::NewTokenPropertyWriter::new(collection, sender);873874		with_transaction(|| {875			for (i, data) in data.iter().enumerate() {876				let token_id = first_token_id + i as u32 + 1;877				<TotalSupply<T>>::insert((collection.id, token_id), totals[i]);878879				let token = TokenId(token_id);880881				let mut mint_target_is_sender = true;882				for (user, amount) in data.users.iter() {883					if *amount == 0 {884						continue;885					}886887					mint_target_is_sender = mint_target_is_sender && sender.conv_eq(user);888889					<Balance<T>>::insert((collection.id, token_id, &user), amount);890					<Owned<T>>::insert((collection.id, &user, token), true);891					<PalletStructure<T>>::nest_if_sent_to_token_unchecked(892						user,893						collection.id,894						token,895					);896				}897898				if let Err(e) = property_writer.write_token_properties(899					mint_target_is_sender,900					token,901					data.properties.clone().into_iter(),902					erc::ERC721TokenEvent::TokenChanged {903						token_id: token.into(),904					}905					.to_log(T::ContractAddress::get()),906				) {907					return TransactionOutcome::Rollback(Err(e));908				}909			}910			TransactionOutcome::Commit(Ok(()))911		})?;912913		<TokensMinted<T>>::insert(collection.id, tokens_minted);914915		for (account, balance) in balances {916			<AccountBalance<T>>::insert((collection.id, account), balance);917		}918919		for (i, token) in data.into_iter().enumerate() {920			let token_id = first_token_id + i as u32 + 1;921922			let receivers = token923				.users924				.into_iter()925				.filter(|(_, amount)| *amount > 0)926				.collect::<Vec<_>>();927928			if let [(user, _)] = receivers.as_slice() {929				// if there is exactly one receiver930				<PalletEvm<T>>::deposit_log(931					ERC721Events::Transfer {932						from: H160::default(),933						to: *user.as_eth(),934						token_id: token_id.into(),935					}936					.to_log(collection_id_to_address(collection.id)),937				);938			} else if let [_, ..] = receivers.as_slice() {939				// if there is more than one receiver940				<PalletEvm<T>>::deposit_log(941					ERC721Events::Transfer {942						from: H160::default(),943						to: erc::ADDRESS_FOR_PARTIALLY_OWNED_TOKENS,944						token_id: token_id.into(),945					}946					.to_log(collection_id_to_address(collection.id)),947				);948			}949950			for (user, amount) in receivers.into_iter() {951				<PalletEvm<T>>::deposit_log(952					ERC20Events::Transfer {953						from: H160::default(),954						to: *user.as_eth(),955						value: amount.into(),956					}957					.to_log(T::EvmTokenAddressMapping::token_to_address(958						collection.id,959						TokenId(token_id),960					)),961				);962				<PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(963					collection.id,964					TokenId(token_id),965					user,966					amount,967				));968			}969		}970		Ok(())971	}972973	pub fn set_allowance_unchecked(974		collection: &RefungibleHandle<T>,975		sender: &T::CrossAccountId,976		spender: &T::CrossAccountId,977		token: TokenId,978		amount: u128,979	) {980		if amount == 0 {981			<Allowance<T>>::remove((collection.id, token, sender, spender));982		} else {983			<Allowance<T>>::insert((collection.id, token, sender, spender), amount);984		}985986		<PalletEvm<T>>::deposit_log(987			ERC20Events::Approval {988				owner: *sender.as_eth(),989				spender: *spender.as_eth(),990				value: amount.into(),991			}992			.to_log(T::EvmTokenAddressMapping::token_to_address(993				collection.id,994				token,995			)),996		);997		<PalletCommon<T>>::deposit_event(CommonEvent::Approved(998			collection.id,999			token,1000			sender.clone(),1001			spender.clone(),1002			amount,1003		))1004	}10051006	/// Set allowance for the spender to `transfer` or `burn` sender's token pieces.1007	///1008	/// - `amount`: Amount of token pieces the spender is allowed to `transfer` or `burn.1009	pub fn set_allowance(1010		collection: &RefungibleHandle<T>,1011		sender: &T::CrossAccountId,1012		spender: &T::CrossAccountId,1013		token: TokenId,1014		amount: u128,1015	) -> DispatchResult {1016		if collection.permissions.access() == AccessMode::AllowList {1017			collection.check_allowlist(sender)?;1018			collection.check_allowlist(spender)?;1019		}10201021		<PalletCommon<T>>::ensure_correct_receiver(spender)?;10221023		if <Balance<T>>::get((collection.id, token, sender)) < amount {1024			ensure!(1025				collection.ignores_owned_amount(sender) && Self::token_exists(collection, token),1026				<CommonError<T>>::CantApproveMoreThanOwned1027			);1028		}10291030		// =========10311032		Self::set_allowance_unchecked(collection, sender, spender, token, amount);1033		Ok(())1034	}10351036	/// Set allowance to spend from sender's eth mirror1037	///1038	/// - `from`: Address of sender's eth mirror.1039	/// - `to`: Adress of spender.1040	/// - `amount`: Amount of token pieces the spender is allowed to `transfer` or `burn.1041	pub fn set_allowance_from(1042		collection: &RefungibleHandle<T>,1043		sender: &T::CrossAccountId,1044		from: &T::CrossAccountId,1045		to: &T::CrossAccountId,1046		token_id: TokenId,1047		amount: u128,1048	) -> DispatchResult {1049		if collection.permissions.access() == AccessMode::AllowList {1050			collection.check_allowlist(sender)?;1051			collection.check_allowlist(from)?;1052			collection.check_allowlist(to)?;1053		}10541055		<PalletCommon<T>>::ensure_correct_receiver(to)?;10561057		ensure!(1058			sender.conv_eq(from),1059			<CommonError<T>>::AddressIsNotEthMirror1060		);10611062		if <Balance<T>>::get((collection.id, token_id, from)) < amount {1063			ensure!(1064				collection.limits.owner_can_transfer()1065					&& (collection.is_owner_or_admin(sender) || collection.is_owner_or_admin(from))1066					&& Self::token_exists(collection, token_id),1067				<CommonError<T>>::CantApproveMoreThanOwned1068			);1069		}10701071		// =========10721073		Self::set_allowance_unchecked(collection, from, to, token_id, amount);1074		Ok(())1075	}10761077	/// Returns allowance, which should be set after transaction1078	fn check_allowed(1079		collection: &RefungibleHandle<T>,1080		spender: &T::CrossAccountId,1081		from: &T::CrossAccountId,1082		token: TokenId,1083		amount: u128,1084		nesting_budget: &dyn Budget,1085	) -> Result<Option<u128>, DispatchError> {1086		if spender.conv_eq(from) {1087			return Ok(None);1088		}1089		if collection.permissions.access() == AccessMode::AllowList {1090			// `from`, `to` checked in [`transfer`]1091			collection.check_allowlist(spender)?;1092		}10931094		if collection.ignores_token_restrictions(spender) {1095			return Ok(Self::compute_allowance_decrease(1096				collection, token, from, spender, amount,1097			));1098		}10991100		if let Some(source) = T::CrossTokenAddressMapping::address_to_token(from) {1101			// TODO: should collection owner be allowed to perform this transfer?1102			ensure!(1103				<PalletStructure<T>>::check_indirectly_owned(1104					spender.clone(),1105					source.0,1106					source.1,1107					None,1108					nesting_budget1109				)?,1110				<CommonError<T>>::ApprovedValueTooLow,1111			);1112			return Ok(None);1113		}11141115		let allowance = Self::compute_allowance_decrease(collection, token, from, spender, amount);1116		if allowance.is_some() {1117			return Ok(allowance);1118		}11191120		// Allowance (if any) would be reduced if spender is also wallet operator1121		if <CollectionAllowance<T>>::get((collection.id, from, spender)) {1122			return Ok(allowance);1123		}11241125		Err(<CommonError<T>>::ApprovedValueTooLow.into())1126	}11271128	/// Returns `Some(amount)` if the `spender` have allowance to spend this amount.1129	/// Otherwise, it returns `None`.1130	fn compute_allowance_decrease(1131		collection: &RefungibleHandle<T>,1132		token: TokenId,1133		from: &T::CrossAccountId,1134		spender: &T::CrossAccountId,1135		amount: u128,1136	) -> Option<u128> {1137		<Allowance<T>>::get((collection.id, token, from, spender)).checked_sub(amount)1138	}11391140	/// Transfer RFT token pieces from one account to another.1141	///1142	/// Same as the [`transfer`] but spender doesn't needs to be an owner of the token pieces.1143	/// The owner should set allowance for the spender to transfer pieces.1144	///1145	/// [`transfer`]: struct.Pallet.html#method.transfer1146	pub fn transfer_from(1147		collection: &RefungibleHandle<T>,1148		spender: &T::CrossAccountId,1149		from: &T::CrossAccountId,1150		to: &T::CrossAccountId,1151		token: TokenId,1152		amount: u128,1153		nesting_budget: &dyn Budget,1154	) -> DispatchResult {1155		let allowance =1156			Self::check_allowed(collection, spender, from, token, amount, nesting_budget)?;11571158		// =========11591160		Self::transfer_internal(collection, spender, from, to, token, amount, nesting_budget)?;1161		if let Some(allowance) = allowance {1162			Self::set_allowance_unchecked(collection, from, spender, token, allowance);1163		}1164		Ok(())1165	}11661167	/// Burn RFT token pieces from the account.1168	///1169	/// Same as the [`burn`] but spender doesn't need to be an owner of the token pieces. The owner should1170	/// set allowance for the spender to burn pieces1171	///1172	/// [`burn`]: struct.Pallet.html#method.burn1173	pub fn burn_from(1174		collection: &RefungibleHandle<T>,1175		spender: &T::CrossAccountId,1176		from: &T::CrossAccountId,1177		token: TokenId,1178		amount: u128,1179		nesting_budget: &dyn Budget,1180	) -> DispatchResult {1181		let allowance =1182			Self::check_allowed(collection, spender, from, token, amount, nesting_budget)?;11831184		// =========11851186		Self::burn(collection, from, token, amount)?;1187		if let Some(allowance) = allowance {1188			Self::set_allowance_unchecked(collection, from, spender, token, allowance);1189		}1190		Ok(())1191	}11921193	/// Create RFT token.1194	///1195	/// The sender should be the owner/admin of the collection or collection should be configured1196	/// to allow public minting.1197	///1198	/// - `data`: Contains list of users who will become the owners of the token pieces and amount1199	///   of token pieces they will receive.1200	pub fn create_item(1201		collection: &RefungibleHandle<T>,1202		sender: &T::CrossAccountId,1203		data: CreateItemData<T>,1204		nesting_budget: &dyn Budget,1205	) -> DispatchResult {1206		Self::create_multiple_items(collection, sender, vec![data], nesting_budget)1207	}12081209	/// Repartition RFT token.1210	///1211	/// `repartition` will set token balance of the sender and total amount of token pieces.1212	/// Sender should own all of the token pieces. `repartition' could be done even if some1213	/// token pieces were burned before.1214	///1215	/// - `amount`: Total amount of token pieces that the token will have after `repartition`.1216	pub fn repartition(1217		collection: &RefungibleHandle<T>,1218		owner: &T::CrossAccountId,1219		token: TokenId,1220		amount: u128,1221	) -> DispatchResult {1222		ensure!(1223			amount <= MAX_REFUNGIBLE_PIECES,1224			<Error<T>>::WrongRefungiblePieces1225		);1226		ensure!(amount > 0, <CommonError<T>>::TokenValueTooLow);1227		// Ensure user owns all pieces1228		let total_pieces = Self::total_pieces(collection.id, token).unwrap_or(u128::MAX);1229		let balance = <Balance<T>>::get((collection.id, token, owner));1230		ensure!(1231			total_pieces == balance,1232			<Error<T>>::RepartitionWhileNotOwningAllPieces1233		);12341235		<Balance<T>>::insert((collection.id, token, owner), amount);1236		<TotalSupply<T>>::insert((collection.id, token), amount);12371238		match total_pieces.cmp(&amount) {1239			Ordering::Less => {1240				let mint_amount = amount - total_pieces;1241				<PalletEvm<T>>::deposit_log(1242					ERC20Events::Transfer {1243						from: H160::default(),1244						to: *owner.as_eth(),1245						value: mint_amount.into(),1246					}1247					.to_log(T::EvmTokenAddressMapping::token_to_address(1248						collection.id,1249						token,1250					)),1251				);1252				<PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(1253					collection.id,1254					token,1255					owner.clone(),1256					mint_amount,1257				));1258			}1259			Ordering::Greater => {1260				let burn_amount = total_pieces - amount;1261				<PalletEvm<T>>::deposit_log(1262					ERC20Events::Transfer {1263						from: *owner.as_eth(),1264						to: H160::default(),1265						value: burn_amount.into(),1266					}1267					.to_log(T::EvmTokenAddressMapping::token_to_address(1268						collection.id,1269						token,1270					)),1271				);1272				<PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(1273					collection.id,1274					token,1275					owner.clone(),1276					burn_amount,1277				));1278			}1279			Ordering::Equal => {}1280		}12811282		Ok(())1283	}12841285	fn token_owner(1286		collection_id: CollectionId,1287		token_id: TokenId,1288	) -> Result<T::CrossAccountId, TokenOwnerError> {1289		let mut owner = None;1290		let mut count = 0;1291		for key in Balance::<T>::iter_key_prefix((collection_id, token_id)) {1292			count += 1;1293			if count > 1 {1294				return Err(TokenOwnerError::MultipleOwners);1295			}1296			owner = Some(key);1297		}1298		owner.ok_or(TokenOwnerError::NotFound)1299	}13001301	fn total_pieces(collection_id: CollectionId, token_id: TokenId) -> Option<u128> {1302		<TotalSupply<T>>::try_get((collection_id, token_id)).ok()1303	}13041305	pub fn set_collection_properties(1306		collection: &RefungibleHandle<T>,1307		sender: &T::CrossAccountId,1308		properties: Vec<Property>,1309	) -> DispatchResult {1310		<PalletCommon<T>>::set_collection_properties(collection, sender, properties.into_iter())1311	}13121313	pub fn delete_collection_properties(1314		collection: &RefungibleHandle<T>,1315		sender: &T::CrossAccountId,1316		property_keys: Vec<PropertyKey>,1317	) -> DispatchResult {1318		<PalletCommon<T>>::delete_collection_properties(1319			collection,1320			sender,1321			property_keys.into_iter(),1322		)1323	}13241325	pub fn set_token_property_permissions(1326		collection: &RefungibleHandle<T>,1327		sender: &T::CrossAccountId,1328		property_permissions: Vec<PropertyKeyPermission>,1329	) -> DispatchResult {1330		<PalletCommon<T>>::set_token_property_permissions(collection, sender, property_permissions)1331	}13321333	pub fn token_property_permission(collection_id: CollectionId) -> PropertiesPermissionMap {1334		<PalletCommon<T>>::property_permissions(collection_id)1335	}13361337	pub fn set_scoped_token_property_permissions(1338		collection: &RefungibleHandle<T>,1339		sender: &T::CrossAccountId,1340		scope: PropertyScope,1341		property_permissions: Vec<PropertyKeyPermission>,1342	) -> DispatchResult {1343		<PalletCommon<T>>::set_scoped_token_property_permissions(1344			collection,1345			sender,1346			scope,1347			property_permissions,1348		)1349	}13501351	/// Returns 10 token in no particular order.1352	///1353	/// There is no direct way to get token holders in ascending order,1354	/// since `iter_prefix` returns values in no particular order.1355	/// Therefore, getting the 10 largest holders with a large value of holders1356	/// can lead to impact memory allocation + sorting with  `n * log (n)`.1357	pub fn token_owners(1358		collection_id: CollectionId,1359		token: TokenId,1360	) -> Option<Vec<T::CrossAccountId>> {1361		let res: Vec<T::CrossAccountId> = <Balance<T>>::iter_prefix((collection_id, token))1362			.map(|(owner, _amount)| owner)1363			.take(10)1364			.collect();13651366		if res.is_empty() {1367			None1368		} else {1369			Some(res)1370		}1371	}13721373	/// Sets or unsets the approval of a given operator.1374	///1375	/// The `operator` is allowed to transfer all token pieces of the `owner` on their behalf.1376	/// - `owner`: Token owner1377	/// - `operator`: Operator1378	/// - `approve`: Should operator status be granted or revoked?1379	pub fn set_allowance_for_all(1380		collection: &RefungibleHandle<T>,1381		owner: &T::CrossAccountId,1382		spender: &T::CrossAccountId,1383		approve: bool,1384	) -> DispatchResult {1385		<PalletCommon<T>>::set_allowance_for_all(1386			collection,1387			owner,1388			spender,1389			approve,1390			|| <CollectionAllowance<T>>::insert((collection.id, owner, spender), approve),1391			ERC721Events::ApprovalForAll {1392				owner: *owner.as_eth(),1393				operator: *spender.as_eth(),1394				approved: approve,1395			}1396			.to_log(collection_id_to_address(collection.id)),1397		)1398	}13991400	/// Tells whether the given `owner` approves the `operator`.1401	pub fn allowance_for_all(1402		collection: &RefungibleHandle<T>,1403		owner: &T::CrossAccountId,1404		spender: &T::CrossAccountId,1405	) -> bool {1406		<CollectionAllowance<T>>::get((collection.id, owner, spender))1407	}14081409	pub fn repair_item(collection: &RefungibleHandle<T>, token: TokenId) -> DispatchResult {1410		<TokenProperties<T>>::mutate((collection.id, token), |properties| {1411			if let Some(properties) = properties {1412				properties.recompute_consumed_space();1413			}1414		});14151416		Ok(())1417	}1418}