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

difftreelog

source

pallets/refungible/src/lib.rs41.8 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 crate::erc_token::ERC20Events;91use crate::erc::ERC721Events;9293use core::ops::Deref;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,101};102use pallet_structure::Pallet as PalletStructure;103use sp_core::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, CollectionFlags, CreateCollectionData,108	mapping::TokenAddressMapping, MAX_REFUNGIBLE_PIECES, Property, PropertyKey,109	PropertyKeyPermission, PropertyScope, PropertyValue, TokenId, TrySetProperty,110	PropertiesPermissionMap, CreateRefungibleExMultipleOwners, TokenOwnerError,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	#[pallet::generate_store(pub(super) trait Store)]161	pub struct Pallet<T>(_);162163	/// Total amount of minted tokens in a collection.164	#[pallet::storage]165	pub type TokensMinted<T: Config> =166		StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;167168	/// Amount of tokens burnt in a collection.169	#[pallet::storage]170	pub type TokensBurnt<T: Config> =171		StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;172173	/// Amount of pieces a refungible token is split into.174	#[pallet::storage]175	#[pallet::getter(fn token_properties)]176	pub type TokenProperties<T: Config> = StorageNMap<177		Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),178		Value = up_data_structs::Properties,179		QueryKind = ValueQuery,180		OnEmpty = up_data_structs::TokenProperties,181	>;182183	/// Total amount of pieces for token184	#[pallet::storage]185	pub type TotalSupply<T: Config> = StorageNMap<186		Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),187		Value = u128,188		QueryKind = ValueQuery,189	>;190191	/// Used to enumerate tokens owned by account.192	#[pallet::storage]193	pub type Owned<T: Config> = StorageNMap<194		Key = (195			Key<Twox64Concat, CollectionId>,196			Key<Blake2_128Concat, T::CrossAccountId>,197			Key<Twox64Concat, TokenId>,198		),199		Value = bool,200		QueryKind = ValueQuery,201	>;202203	/// Amount of tokens (not pieces) partially owned by an account within a collection.204	#[pallet::storage]205	pub type AccountBalance<T: Config> = StorageNMap<206		Key = (207			Key<Twox64Concat, CollectionId>,208			// Owner209			Key<Blake2_128Concat, T::CrossAccountId>,210		),211		Value = u32,212		QueryKind = ValueQuery,213	>;214215	/// Amount of token pieces owned by account.216	#[pallet::storage]217	pub type Balance<T: Config> = StorageNMap<218		Key = (219			Key<Twox64Concat, CollectionId>,220			Key<Twox64Concat, TokenId>,221			// Owner222			Key<Blake2_128Concat, T::CrossAccountId>,223		),224		Value = u128,225		QueryKind = ValueQuery,226	>;227228	/// Allowance set by a token owner for another user to perform one of certain transactions on a number of pieces of a token.229	#[pallet::storage]230	pub type Allowance<T: Config> = StorageNMap<231		Key = (232			Key<Twox64Concat, CollectionId>,233			Key<Twox64Concat, TokenId>,234			// Owner235			Key<Blake2_128, T::CrossAccountId>,236			// Spender237			Key<Blake2_128Concat, T::CrossAccountId>,238		),239		Value = u128,240		QueryKind = ValueQuery,241	>;242243	/// Spender set by a wallet owner that could perform certain transactions on all tokens in the wallet.244	#[pallet::storage]245	pub type CollectionAllowance<T: Config> = StorageNMap<246		Key = (247			Key<Twox64Concat, CollectionId>,248			Key<Blake2_128Concat, T::CrossAccountId>, // Owner249			Key<Blake2_128Concat, T::CrossAccountId>, // Spender250		),251		Value = bool,252		QueryKind = ValueQuery,253	>;254}255256pub struct RefungibleHandle<T: Config>(pallet_common::CollectionHandle<T>);257impl<T: Config> RefungibleHandle<T> {258	pub fn cast(inner: pallet_common::CollectionHandle<T>) -> Self {259		Self(inner)260	}261	pub fn into_inner(self) -> pallet_common::CollectionHandle<T> {262		self.0263	}264	pub fn common_mut(&mut self) -> &mut pallet_common::CollectionHandle<T> {265		&mut self.0266	}267}268269impl<T: Config> Deref for RefungibleHandle<T> {270	type Target = pallet_common::CollectionHandle<T>;271272	fn deref(&self) -> &Self::Target {273		&self.0274	}275}276277impl<T: Config> WithRecorder<T> for RefungibleHandle<T> {278	fn recorder(&self) -> &pallet_evm_coder_substrate::SubstrateRecorder<T> {279		self.0.recorder()280	}281	fn into_recorder(self) -> pallet_evm_coder_substrate::SubstrateRecorder<T> {282		self.0.into_recorder()283	}284}285286impl<T: Config> Pallet<T> {287	/// Get number of RFT tokens in collection288	pub fn total_supply(collection: &RefungibleHandle<T>) -> u32 {289		<TokensMinted<T>>::get(collection.id) - <TokensBurnt<T>>::get(collection.id)290	}291292	/// Check that RFT token exists293	///294	/// - `token`: Token ID.295	pub fn token_exists(collection: &RefungibleHandle<T>, token: TokenId) -> bool {296		<TotalSupply<T>>::contains_key((collection.id, token))297	}298299	pub fn set_scoped_token_property(300		collection_id: CollectionId,301		token_id: TokenId,302		scope: PropertyScope,303		property: Property,304	) -> DispatchResult {305		TokenProperties::<T>::try_mutate((collection_id, token_id), |properties| {306			properties.try_scoped_set(scope, property.key, property.value)307		})308		.map_err(<CommonError<T>>::from)?;309310		Ok(())311	}312313	pub fn set_scoped_token_properties(314		collection_id: CollectionId,315		token_id: TokenId,316		scope: PropertyScope,317		properties: impl Iterator<Item = Property>,318	) -> DispatchResult {319		TokenProperties::<T>::try_mutate((collection_id, token_id), |stored_properties| {320			stored_properties.try_scoped_set_from_iter(scope, properties)321		})322		.map_err(<CommonError<T>>::from)?;323324		Ok(())325	}326}327328// unchecked calls skips any permission checks329impl<T: Config> Pallet<T> {330	/// Create RFT collection331	///332	/// `init_collection` will take non-refundable deposit for collection creation.333	///334	/// - `data`: Contains settings for collection limits and permissions.335	pub fn init_collection(336		owner: T::CrossAccountId,337		payer: T::CrossAccountId,338		data: CreateCollectionData<T::AccountId>,339		flags: CollectionFlags,340	) -> Result<CollectionId, DispatchError> {341		<PalletCommon<T>>::init_collection(owner, payer, data, flags)342	}343344	/// Destroy RFT collection345	///346	/// `destroy_collection` will throw error if collection contains any tokens.347	/// Only owner can destroy collection.348	pub fn destroy_collection(349		collection: RefungibleHandle<T>,350		sender: &T::CrossAccountId,351	) -> DispatchResult {352		let id = collection.id;353354		if Self::collection_has_tokens(id) {355			return Err(<CommonError<T>>::CantDestroyNotEmptyCollection.into());356		}357358		// =========359360		PalletCommon::destroy_collection(collection.0, sender)?;361362		<TokensMinted<T>>::remove(id);363		<TokensBurnt<T>>::remove(id);364		let _ = <TotalSupply<T>>::clear_prefix((id,), u32::MAX, None);365		let _ = <Balance<T>>::clear_prefix((id,), u32::MAX, None);366		let _ = <Allowance<T>>::clear_prefix((id,), u32::MAX, None);367		let _ = <Owned<T>>::clear_prefix((id,), u32::MAX, None);368		let _ = <AccountBalance<T>>::clear_prefix((id,), u32::MAX, None);369		Ok(())370	}371372	fn collection_has_tokens(collection_id: CollectionId) -> bool {373		<TotalSupply<T>>::iter_prefix((collection_id,))374			.next()375			.is_some()376	}377378	pub fn burn_token_unchecked(379		collection: &RefungibleHandle<T>,380		owner: &T::CrossAccountId,381		token_id: TokenId,382	) -> DispatchResult {383		let burnt = <TokensBurnt<T>>::get(collection.id)384			.checked_add(1)385			.ok_or(ArithmeticError::Overflow)?;386387		<TokensBurnt<T>>::insert(collection.id, burnt);388		<TokenProperties<T>>::remove((collection.id, token_id));389		<TotalSupply<T>>::remove((collection.id, token_id));390		let _ = <Balance<T>>::clear_prefix((collection.id, token_id), u32::MAX, None);391		let _ = <Allowance<T>>::clear_prefix((collection.id, token_id), u32::MAX, None);392		<PalletEvm<T>>::deposit_log(393			ERC721Events::Transfer {394				from: *owner.as_eth(),395				to: H160::default(),396				token_id: token_id.into(),397			}398			.to_log(collection_id_to_address(collection.id)),399		);400		Ok(())401	}402403	/// Burn RFT token pieces404	///405	/// `burn` will decrease total amount of token pieces and amount owned by sender.406	/// `burn` can be called even if there are multiple owners of the RFT token.407	/// If sender wouldn't have any pieces left after `burn` than she will stop being408	/// one of the owners of the token. If there is no account that owns any pieces of409	/// the token than token will be burned too.410	///411	/// - `amount`: Amount of token pieces to burn.412	/// - `token`: Token who's pieces should be burned413	/// - `collection`: Collection that contains the token414	pub fn burn(415		collection: &RefungibleHandle<T>,416		owner: &T::CrossAccountId,417		token: TokenId,418		amount: u128,419	) -> DispatchResult {420		if <Balance<T>>::get((collection.id, token, owner)) == 0 {421			return Err(<CommonError<T>>::TokenValueTooLow.into());422		}423424		let total_supply = <TotalSupply<T>>::get((collection.id, token))425			.checked_sub(amount)426			.ok_or(<CommonError<T>>::TokenValueTooLow)?;427428		// This was probally last owner of this token?429		if total_supply == 0 {430			// Ensure user actually owns this amount431			ensure!(432				<Balance<T>>::get((collection.id, token, owner)) == amount,433				<CommonError<T>>::TokenValueTooLow434			);435			let account_balance = <AccountBalance<T>>::get((collection.id, owner))436				.checked_sub(1)437				// Should not occur438				.ok_or(ArithmeticError::Underflow)?;439440			// =========441442			<Owned<T>>::remove((collection.id, owner, token));443			<PalletStructure<T>>::unnest_if_nested(owner, collection.id, token);444			<AccountBalance<T>>::insert((collection.id, owner), account_balance);445			Self::burn_token_unchecked(collection, owner, token)?;446			<PalletEvm<T>>::deposit_log(447				ERC20Events::Transfer {448					from: *owner.as_eth(),449					to: H160::default(),450					value: amount.into(),451				}452				.to_log(collection_id_to_address(collection.id)),453			);454			<PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(455				collection.id,456				token,457				owner.clone(),458				amount,459			));460			return Ok(());461		}462463		let balance = <Balance<T>>::get((collection.id, token, owner))464			.checked_sub(amount)465			.ok_or(<CommonError<T>>::TokenValueTooLow)?;466		let account_balance = if balance == 0 {467			<AccountBalance<T>>::get((collection.id, owner))468				.checked_sub(1)469				// Should not occur470				.ok_or(ArithmeticError::Underflow)?471		} else {472			0473		};474475		// =========476477		if balance == 0 {478			<Owned<T>>::remove((collection.id, owner, token));479			<PalletStructure<T>>::unnest_if_nested(owner, collection.id, token);480			<Balance<T>>::remove((collection.id, token, owner));481			<AccountBalance<T>>::insert((collection.id, owner), account_balance);482483			if let Ok(user) = Self::token_owner(collection.id, token) {484				<PalletEvm<T>>::deposit_log(485					ERC721Events::Transfer {486						from: erc::ADDRESS_FOR_PARTIALLY_OWNED_TOKENS,487						to: *user.as_eth(),488						token_id: token.into(),489					}490					.to_log(collection_id_to_address(collection.id)),491				);492			}493		} else {494			<Balance<T>>::insert((collection.id, token, owner), balance);495		}496		<TotalSupply<T>>::insert((collection.id, token), total_supply);497498		<PalletEvm<T>>::deposit_log(499			ERC20Events::Transfer {500				from: *owner.as_eth(),501				to: H160::default(),502				value: amount.into(),503			}504			.to_log(T::EvmTokenAddressMapping::token_to_address(505				collection.id,506				token,507			)),508		);509		<PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(510			collection.id,511			token,512			owner.clone(),513			amount,514		));515		Ok(())516	}517518	/// A batch operation to add, edit or remove properties for a token.519	/// It sets or removes a token's properties according to520	/// `properties_updates` contents:521	/// * sets a property under the <key> with the value provided `(<key>, Some(<value>))`522	/// * removes a property under the <key> if the value is `None` `(<key>, None)`.523	///524	/// - `nesting_budget`: Limit for searching parents in-depth to check ownership.525	/// - `is_token_create`: Indicates that method is called during token initialization.526	///   Allows to bypass ownership check.527	///528	/// All affected properties should have `mutable` permission529	/// to be **deleted** or to be **set more than once**,530	/// and the sender should have permission to edit those properties.531	///532	/// This function fires an event for each property change.533	/// In case of an error, all the changes (including the events) will be reverted534	/// since the function is transactional.535	#[transactional]536	fn modify_token_properties(537		collection: &RefungibleHandle<T>,538		sender: &T::CrossAccountId,539		token_id: TokenId,540		properties_updates: impl Iterator<Item = (PropertyKey, Option<PropertyValue>)>,541		is_token_create: bool,542		nesting_budget: &dyn Budget,543	) -> DispatchResult {544		let is_token_owner = || -> Result<bool, DispatchError> {545			let balance = collection.balance(sender.clone(), token_id);546			let total_pieces: u128 =547				Self::total_pieces(collection.id, token_id).unwrap_or(u128::MAX);548			if balance != total_pieces {549				return Ok(false);550			}551552			let is_bundle_owner = <PalletStructure<T>>::check_indirectly_owned(553				sender.clone(),554				collection.id,555				token_id,556				None,557				nesting_budget,558			)?;559560			Ok(is_bundle_owner)561		};562563		let stored_properties = <TokenProperties<T>>::get((collection.id, token_id));564565		<PalletCommon<T>>::modify_token_properties(566			collection,567			sender,568			token_id,569			properties_updates,570			is_token_create,571			stored_properties,572			is_token_owner,573			|properties| <TokenProperties<T>>::set((collection.id, token_id), properties),574		)575	}576577	pub fn set_token_properties(578		collection: &RefungibleHandle<T>,579		sender: &T::CrossAccountId,580		token_id: TokenId,581		properties: impl Iterator<Item = Property>,582		is_token_create: bool,583		nesting_budget: &dyn Budget,584	) -> DispatchResult {585		Self::modify_token_properties(586			collection,587			sender,588			token_id,589			properties.map(|p| (p.key, Some(p.value))),590			is_token_create,591			nesting_budget,592		)593	}594595	pub fn set_token_property(596		collection: &RefungibleHandle<T>,597		sender: &T::CrossAccountId,598		token_id: TokenId,599		property: Property,600		nesting_budget: &dyn Budget,601	) -> DispatchResult {602		let is_token_create = false;603604		Self::set_token_properties(605			collection,606			sender,607			token_id,608			[property].into_iter(),609			is_token_create,610			nesting_budget,611		)612	}613614	pub fn delete_token_properties(615		collection: &RefungibleHandle<T>,616		sender: &T::CrossAccountId,617		token_id: TokenId,618		property_keys: impl Iterator<Item = PropertyKey>,619		nesting_budget: &dyn Budget,620	) -> DispatchResult {621		let is_token_create = false;622623		Self::modify_token_properties(624			collection,625			sender,626			token_id,627			property_keys.into_iter().map(|key| (key, None)),628			is_token_create,629			nesting_budget,630		)631	}632633	pub fn delete_token_property(634		collection: &RefungibleHandle<T>,635		sender: &T::CrossAccountId,636		token_id: TokenId,637		property_key: PropertyKey,638		nesting_budget: &dyn Budget,639	) -> DispatchResult {640		Self::delete_token_properties(641			collection,642			sender,643			token_id,644			[property_key].into_iter(),645			nesting_budget,646		)647	}648649	/// Transfer RFT token pieces from one account to another.650	///651	/// If the sender is no longer owns any pieces after the `transfer` than she stops being an owner of the token.652	///653	/// - `from`: Owner of token pieces to transfer.654	/// - `to`: Recepient of transfered token pieces.655	/// - `amount`: Amount of token pieces to transfer.656	/// - `token`: Token whos pieces should be transfered657	/// - `collection`: Collection that contains the token658	pub fn transfer(659		collection: &RefungibleHandle<T>,660		from: &T::CrossAccountId,661		to: &T::CrossAccountId,662		token: TokenId,663		amount: u128,664		nesting_budget: &dyn Budget,665	) -> DispatchResult {666		ensure!(667			collection.limits.transfers_enabled(),668			<CommonError<T>>::TransferNotAllowed669		);670671		if collection.permissions.access() == AccessMode::AllowList {672			collection.check_allowlist(from)?;673			collection.check_allowlist(to)?;674		}675		<PalletCommon<T>>::ensure_correct_receiver(to)?;676677		let initial_balance_from = <Balance<T>>::get((collection.id, token, from));678679		if initial_balance_from == 0 {680			return Err(<CommonError<T>>::TokenValueTooLow.into());681		}682683		let updated_balance_from = initial_balance_from684			.checked_sub(amount)685			.ok_or(<CommonError<T>>::TokenValueTooLow)?;686		let mut create_target = false;687		let from_to_differ = from != to;688		let updated_balance_to = if from != to && amount != 0 {689			let old_balance = <Balance<T>>::get((collection.id, token, to));690			if old_balance == 0 {691				create_target = true;692			}693			Some(694				old_balance695					.checked_add(amount)696					.ok_or(ArithmeticError::Overflow)?,697			)698		} else {699			None700		};701702		let account_balance_from = if updated_balance_from == 0 {703			Some(704				<AccountBalance<T>>::get((collection.id, from))705					.checked_sub(1)706					// Should not occur707					.ok_or(ArithmeticError::Underflow)?,708			)709		} else {710			None711		};712		// Account data is created in token, AccountBalance should be increased713		// But only if from != to as we shouldn't check overflow in this case714		let account_balance_to = if create_target && from_to_differ {715			let account_balance_to = <AccountBalance<T>>::get((collection.id, to))716				.checked_add(1)717				.ok_or(ArithmeticError::Overflow)?;718			ensure!(719				account_balance_to < collection.limits.account_token_ownership_limit(),720				<CommonError<T>>::AccountTokenLimitExceeded,721			);722723			Some(account_balance_to)724		} else {725			None726		};727728		// =========729730		if let Some(updated_balance_to) = updated_balance_to {731			// from != to && amount != 0732733			<PalletStructure<T>>::nest_if_sent_to_token(734				from.clone(),735				to,736				collection.id,737				token,738				nesting_budget,739			)?;740741			if updated_balance_from == 0 {742				<Balance<T>>::remove((collection.id, token, from));743				<PalletStructure<T>>::unnest_if_nested(from, collection.id, token);744			} else {745				<Balance<T>>::insert((collection.id, token, from), updated_balance_from);746			}747			<Balance<T>>::insert((collection.id, token, to), updated_balance_to);748			if let Some(account_balance_from) = account_balance_from {749				<AccountBalance<T>>::insert((collection.id, from), account_balance_from);750				<Owned<T>>::remove((collection.id, from, token));751			}752			if let Some(account_balance_to) = account_balance_to {753				<AccountBalance<T>>::insert((collection.id, to), account_balance_to);754				<Owned<T>>::insert((collection.id, to, token), true);755			}756		}757758		<PalletEvm<T>>::deposit_log(759			ERC20Events::Transfer {760				from: *from.as_eth(),761				to: *to.as_eth(),762				value: amount.into(),763			}764			.to_log(T::EvmTokenAddressMapping::token_to_address(765				collection.id,766				token,767			)),768		);769770		<PalletCommon<T>>::deposit_event(CommonEvent::Transfer(771			collection.id,772			token,773			from.clone(),774			to.clone(),775			amount,776		));777778		let total_supply = <TotalSupply<T>>::get((collection.id, token));779780		if amount == total_supply {781			// if token was fully owned by `from` and will be fully owned by `to` after transfer782			<PalletEvm<T>>::deposit_log(783				ERC721Events::Transfer {784					from: *from.as_eth(),785					to: *to.as_eth(),786					token_id: token.into(),787				}788				.to_log(collection_id_to_address(collection.id)),789			);790		} else if let Some(updated_balance_to) = updated_balance_to {791			// if `from` not equals `to`. This condition is needed to avoid sending event792			// when `from` fully owns token and sends part of token pieces to itself.793			if initial_balance_from == total_supply {794				// if token was fully owned by `from` and will be only partially owned by `to`795				// and `from` after transfer796				<PalletEvm<T>>::deposit_log(797					ERC721Events::Transfer {798						from: *from.as_eth(),799						to: erc::ADDRESS_FOR_PARTIALLY_OWNED_TOKENS,800						token_id: token.into(),801					}802					.to_log(collection_id_to_address(collection.id)),803				);804			} else if updated_balance_to == total_supply {805				// if token was partially owned by `from` and will be fully owned by `to` after transfer806				<PalletEvm<T>>::deposit_log(807					ERC721Events::Transfer {808						from: erc::ADDRESS_FOR_PARTIALLY_OWNED_TOKENS,809						to: *to.as_eth(),810						token_id: token.into(),811					}812					.to_log(collection_id_to_address(collection.id)),813				);814			}815		}816817		Ok(())818	}819820	/// Batched operation to create multiple RFT tokens.821	///822	/// Same as `create_item` but creates multiple tokens.823	///824	/// - `data`: Same as 'data` in `create_item` but contains data for multiple tokens.825	pub fn create_multiple_items(826		collection: &RefungibleHandle<T>,827		sender: &T::CrossAccountId,828		data: Vec<CreateItemData<T>>,829		nesting_budget: &dyn Budget,830	) -> DispatchResult {831		if !collection.is_owner_or_admin(sender) {832			ensure!(833				collection.permissions.mint_mode(),834				<CommonError<T>>::PublicMintingNotAllowed835			);836			collection.check_allowlist(sender)?;837838			for item in data.iter() {839				for user in item.users.keys() {840					collection.check_allowlist(user)?;841				}842			}843		}844845		for item in data.iter() {846			for (owner, _) in item.users.iter() {847				<PalletCommon<T>>::ensure_correct_receiver(owner)?;848			}849		}850851		// Total pieces per tokens852		let totals = data853			.iter()854			.map(|data| {855				Ok(data856					.users857					.iter()858					.map(|u| u.1)859					.try_fold(0u128, |acc, v| acc.checked_add(*v))860					.ok_or(ArithmeticError::Overflow)?)861			})862			.collect::<Result<Vec<_>, DispatchError>>()?;863		for total in &totals {864			ensure!(865				*total <= MAX_REFUNGIBLE_PIECES,866				<Error<T>>::WrongRefungiblePieces867			);868		}869870		let first_token_id = <TokensMinted<T>>::get(collection.id);871		let tokens_minted = first_token_id872			.checked_add(data.len() as u32)873			.ok_or(ArithmeticError::Overflow)?;874		ensure!(875			tokens_minted < collection.limits.token_limit(),876			<CommonError<T>>::CollectionTokenLimitExceeded877		);878879		let mut balances = BTreeMap::new();880		for data in &data {881			for owner in data.users.keys() {882				let balance = balances883					.entry(owner)884					.or_insert_with(|| <AccountBalance<T>>::get((collection.id, owner)));885				*balance = balance.checked_add(1).ok_or(ArithmeticError::Overflow)?;886887				ensure!(888					*balance <= collection.limits.account_token_ownership_limit(),889					<CommonError<T>>::AccountTokenLimitExceeded,890				);891			}892		}893894		for (i, token) in data.iter().enumerate() {895			let token_id = TokenId(first_token_id + i as u32 + 1);896			for (to, _) in token.users.iter() {897				<PalletStructure<T>>::check_nesting(898					sender.clone(),899					to,900					collection.id,901					token_id,902					nesting_budget,903				)?;904			}905		}906907		// =========908909		with_transaction(|| {910			for (i, data) in data.iter().enumerate() {911				let token_id = first_token_id + i as u32 + 1;912				<TotalSupply<T>>::insert((collection.id, token_id), totals[i]);913914				for (user, amount) in data.users.iter() {915					if *amount == 0 {916						continue;917					}918					<Balance<T>>::insert((collection.id, token_id, &user), amount);919					<Owned<T>>::insert((collection.id, &user, TokenId(token_id)), true);920					<PalletStructure<T>>::nest_if_sent_to_token_unchecked(921						user,922						collection.id,923						TokenId(token_id),924					);925				}926927				if let Err(e) = Self::set_token_properties(928					collection,929					sender,930					TokenId(token_id),931					data.properties.clone().into_iter(),932					true,933					nesting_budget,934				) {935					return TransactionOutcome::Rollback(Err(e));936				}937			}938			TransactionOutcome::Commit(Ok(()))939		})?;940941		<TokensMinted<T>>::insert(collection.id, tokens_minted);942943		for (account, balance) in balances {944			<AccountBalance<T>>::insert((collection.id, account), balance);945		}946947		for (i, token) in data.into_iter().enumerate() {948			let token_id = first_token_id + i as u32 + 1;949950			let receivers = token951				.users952				.into_iter()953				.filter(|(_, amount)| *amount > 0)954				.collect::<Vec<_>>();955956			if let [(user, _)] = receivers.as_slice() {957				// if there is exactly one receiver958				<PalletEvm<T>>::deposit_log(959					ERC721Events::Transfer {960						from: H160::default(),961						to: *user.as_eth(),962						token_id: token_id.into(),963					}964					.to_log(collection_id_to_address(collection.id)),965				);966			} else if let [_, ..] = receivers.as_slice() {967				// if there is more than one receiver968				<PalletEvm<T>>::deposit_log(969					ERC721Events::Transfer {970						from: H160::default(),971						to: erc::ADDRESS_FOR_PARTIALLY_OWNED_TOKENS,972						token_id: token_id.into(),973					}974					.to_log(collection_id_to_address(collection.id)),975				);976			}977978			for (user, amount) in receivers.into_iter() {979				<PalletEvm<T>>::deposit_log(980					ERC20Events::Transfer {981						from: H160::default(),982						to: *user.as_eth(),983						value: amount.into(),984					}985					.to_log(T::EvmTokenAddressMapping::token_to_address(986						collection.id,987						TokenId(token_id),988					)),989				);990				<PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(991					collection.id,992					TokenId(token_id),993					user,994					amount,995				));996			}997		}998		Ok(())999	}10001001	pub fn set_allowance_unchecked(1002		collection: &RefungibleHandle<T>,1003		sender: &T::CrossAccountId,1004		spender: &T::CrossAccountId,1005		token: TokenId,1006		amount: u128,1007	) {1008		if amount == 0 {1009			<Allowance<T>>::remove((collection.id, token, sender, spender));1010		} else {1011			<Allowance<T>>::insert((collection.id, token, sender, spender), amount);1012		}10131014		<PalletEvm<T>>::deposit_log(1015			ERC20Events::Approval {1016				owner: *sender.as_eth(),1017				spender: *spender.as_eth(),1018				value: amount.into(),1019			}1020			.to_log(T::EvmTokenAddressMapping::token_to_address(1021				collection.id,1022				token,1023			)),1024		);1025		<PalletCommon<T>>::deposit_event(CommonEvent::Approved(1026			collection.id,1027			token,1028			sender.clone(),1029			spender.clone(),1030			amount,1031		))1032	}10331034	/// Set allowance for the spender to `transfer` or `burn` sender's token pieces.1035	///1036	/// - `amount`: Amount of token pieces the spender is allowed to `transfer` or `burn.1037	pub fn set_allowance(1038		collection: &RefungibleHandle<T>,1039		sender: &T::CrossAccountId,1040		spender: &T::CrossAccountId,1041		token: TokenId,1042		amount: u128,1043	) -> DispatchResult {1044		if collection.permissions.access() == AccessMode::AllowList {1045			collection.check_allowlist(sender)?;1046			collection.check_allowlist(spender)?;1047		}10481049		<PalletCommon<T>>::ensure_correct_receiver(spender)?;10501051		if <Balance<T>>::get((collection.id, token, sender)) < amount {1052			ensure!(1053				collection.ignores_owned_amount(sender) && Self::token_exists(collection, token),1054				<CommonError<T>>::CantApproveMoreThanOwned1055			);1056		}10571058		// =========10591060		Self::set_allowance_unchecked(collection, sender, spender, token, amount);1061		Ok(())1062	}10631064	/// Set allowance to spend from sender's eth mirror1065	///1066	/// - `from`: Address of sender's eth mirror.1067	/// - `to`: Adress of spender.1068	/// - `amount`: Amount of token pieces the spender is allowed to `transfer` or `burn.1069	pub fn set_allowance_from(1070		collection: &RefungibleHandle<T>,1071		sender: &T::CrossAccountId,1072		from: &T::CrossAccountId,1073		to: &T::CrossAccountId,1074		token_id: TokenId,1075		amount: u128,1076	) -> DispatchResult {1077		if collection.permissions.access() == AccessMode::AllowList {1078			collection.check_allowlist(sender)?;1079			collection.check_allowlist(from)?;1080			collection.check_allowlist(to)?;1081		}10821083		<PalletCommon<T>>::ensure_correct_receiver(to)?;10841085		ensure!(1086			sender.conv_eq(from),1087			<CommonError<T>>::AddressIsNotEthMirror1088		);10891090		if <Balance<T>>::get((collection.id, token_id, from)) < amount {1091			ensure!(1092				collection.limits.owner_can_transfer()1093					&& (collection.is_owner_or_admin(sender) || collection.is_owner_or_admin(from))1094					&& Self::token_exists(collection, token_id),1095				<CommonError<T>>::CantApproveMoreThanOwned1096			);1097		}10981099		// =========11001101		Self::set_allowance_unchecked(collection, from, to, token_id, amount);1102		Ok(())1103	}11041105	/// Returns allowance, which should be set after transaction1106	fn check_allowed(1107		collection: &RefungibleHandle<T>,1108		spender: &T::CrossAccountId,1109		from: &T::CrossAccountId,1110		token: TokenId,1111		amount: u128,1112		nesting_budget: &dyn Budget,1113	) -> Result<Option<u128>, DispatchError> {1114		if spender.conv_eq(from) {1115			return Ok(None);1116		}1117		if collection.permissions.access() == AccessMode::AllowList {1118			// `from`, `to` checked in [`transfer`]1119			collection.check_allowlist(spender)?;1120		}11211122		if collection.ignores_token_restrictions(spender) {1123			return Ok(Self::compute_allowance_decrease(1124				collection, token, from, &spender, amount,1125			));1126		}11271128		if let Some(source) = T::CrossTokenAddressMapping::address_to_token(from) {1129			// TODO: should collection owner be allowed to perform this transfer?1130			ensure!(1131				<PalletStructure<T>>::check_indirectly_owned(1132					spender.clone(),1133					source.0,1134					source.1,1135					None,1136					nesting_budget1137				)?,1138				<CommonError<T>>::ApprovedValueTooLow,1139			);1140			return Ok(None);1141		}11421143		let allowance = Self::compute_allowance_decrease(collection, token, from, &spender, amount);1144		if allowance.is_some() {1145			return Ok(allowance);1146		}11471148		// Allowance (if any) would be reduced if spender is also wallet operator1149		if <CollectionAllowance<T>>::get((collection.id, from, spender)) {1150			return Ok(allowance);1151		}11521153		Err(<CommonError<T>>::ApprovedValueTooLow.into())1154	}11551156	/// Returns `Some(amount)` if the `spender` have allowance to spend this amount.1157	/// Otherwise, it returns `None`.1158	fn compute_allowance_decrease(1159		collection: &RefungibleHandle<T>,1160		token: TokenId,1161		from: &T::CrossAccountId,1162		spender: &T::CrossAccountId,1163		amount: u128,1164	) -> Option<u128> {1165		<Allowance<T>>::get((collection.id, token, from, spender)).checked_sub(amount)1166	}11671168	/// Transfer RFT token pieces from one account to another.1169	///1170	/// Same as the [`transfer`] but spender doesn't needs to be an owner of the token pieces.1171	/// The owner should set allowance for the spender to transfer pieces.1172	///1173	/// [`transfer`]: struct.Pallet.html#method.transfer1174	pub fn transfer_from(1175		collection: &RefungibleHandle<T>,1176		spender: &T::CrossAccountId,1177		from: &T::CrossAccountId,1178		to: &T::CrossAccountId,1179		token: TokenId,1180		amount: u128,1181		nesting_budget: &dyn Budget,1182	) -> DispatchResult {1183		let allowance =1184			Self::check_allowed(collection, spender, from, token, amount, nesting_budget)?;11851186		// =========11871188		Self::transfer(collection, from, to, token, amount, nesting_budget)?;1189		if let Some(allowance) = allowance {1190			Self::set_allowance_unchecked(collection, from, spender, token, allowance);1191		}1192		Ok(())1193	}11941195	/// Burn RFT token pieces from the account.1196	///1197	/// Same as the [`burn`] but spender doesn't need to be an owner of the token pieces. The owner should1198	/// set allowance for the spender to burn pieces1199	///1200	/// [`burn`]: struct.Pallet.html#method.burn1201	pub fn burn_from(1202		collection: &RefungibleHandle<T>,1203		spender: &T::CrossAccountId,1204		from: &T::CrossAccountId,1205		token: TokenId,1206		amount: u128,1207		nesting_budget: &dyn Budget,1208	) -> DispatchResult {1209		let allowance =1210			Self::check_allowed(collection, spender, from, token, amount, nesting_budget)?;12111212		// =========12131214		Self::burn(collection, from, token, amount)?;1215		if let Some(allowance) = allowance {1216			Self::set_allowance_unchecked(collection, from, spender, token, allowance);1217		}1218		Ok(())1219	}12201221	/// Create RFT token.1222	///1223	/// The sender should be the owner/admin of the collection or collection should be configured1224	/// to allow public minting.1225	///1226	/// - `data`: Contains list of users who will become the owners of the token pieces and amount1227	///   of token pieces they will receive.1228	pub fn create_item(1229		collection: &RefungibleHandle<T>,1230		sender: &T::CrossAccountId,1231		data: CreateItemData<T>,1232		nesting_budget: &dyn Budget,1233	) -> DispatchResult {1234		Self::create_multiple_items(collection, sender, vec![data], nesting_budget)1235	}12361237	/// Repartition RFT token.1238	///1239	/// `repartition` will set token balance of the sender and total amount of token pieces.1240	/// Sender should own all of the token pieces. `repartition' could be done even if some1241	/// token pieces were burned before.1242	///1243	/// - `amount`: Total amount of token pieces that the token will have after `repartition`.1244	pub fn repartition(1245		collection: &RefungibleHandle<T>,1246		owner: &T::CrossAccountId,1247		token: TokenId,1248		amount: u128,1249	) -> DispatchResult {1250		ensure!(1251			amount <= MAX_REFUNGIBLE_PIECES,1252			<Error<T>>::WrongRefungiblePieces1253		);1254		ensure!(amount > 0, <CommonError<T>>::TokenValueTooLow);1255		// Ensure user owns all pieces1256		let total_pieces = Self::total_pieces(collection.id, token).unwrap_or(u128::MAX);1257		let balance = <Balance<T>>::get((collection.id, token, owner));1258		ensure!(1259			total_pieces == balance,1260			<Error<T>>::RepartitionWhileNotOwningAllPieces1261		);12621263		<Balance<T>>::insert((collection.id, token, owner), amount);1264		<TotalSupply<T>>::insert((collection.id, token), amount);12651266		if amount > total_pieces {1267			let mint_amount = amount - total_pieces;1268			<PalletEvm<T>>::deposit_log(1269				ERC20Events::Transfer {1270					from: H160::default(),1271					to: *owner.as_eth(),1272					value: mint_amount.into(),1273				}1274				.to_log(T::EvmTokenAddressMapping::token_to_address(1275					collection.id,1276					token,1277				)),1278			);1279			<PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(1280				collection.id,1281				token,1282				owner.clone(),1283				mint_amount,1284			));1285		} else if total_pieces > amount {1286			let burn_amount = total_pieces - amount;1287			<PalletEvm<T>>::deposit_log(1288				ERC20Events::Transfer {1289					from: *owner.as_eth(),1290					to: H160::default(),1291					value: burn_amount.into(),1292				}1293				.to_log(T::EvmTokenAddressMapping::token_to_address(1294					collection.id,1295					token,1296				)),1297			);1298			<PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(1299				collection.id,1300				token,1301				owner.clone(),1302				burn_amount,1303			));1304		}13051306		Ok(())1307	}13081309	fn token_owner(1310		collection_id: CollectionId,1311		token_id: TokenId,1312	) -> Result<T::CrossAccountId, TokenOwnerError> {1313		let mut owner = None;1314		let mut count = 0;1315		for key in Balance::<T>::iter_key_prefix((collection_id, token_id)) {1316			count += 1;1317			if count > 1 {1318				return Err(TokenOwnerError::MultipleOwners);1319			}1320			owner = Some(key);1321		}1322		owner.ok_or(TokenOwnerError::NotFound)1323	}13241325	fn total_pieces(collection_id: CollectionId, token_id: TokenId) -> Option<u128> {1326		<TotalSupply<T>>::try_get((collection_id, token_id)).ok()1327	}13281329	pub fn set_collection_properties(1330		collection: &RefungibleHandle<T>,1331		sender: &T::CrossAccountId,1332		properties: Vec<Property>,1333	) -> DispatchResult {1334		<PalletCommon<T>>::set_collection_properties(collection, sender, properties.into_iter())1335	}13361337	pub fn delete_collection_properties(1338		collection: &RefungibleHandle<T>,1339		sender: &T::CrossAccountId,1340		property_keys: Vec<PropertyKey>,1341	) -> DispatchResult {1342		<PalletCommon<T>>::delete_collection_properties(1343			collection,1344			sender,1345			property_keys.into_iter(),1346		)1347	}13481349	pub fn set_token_property_permissions(1350		collection: &RefungibleHandle<T>,1351		sender: &T::CrossAccountId,1352		property_permissions: Vec<PropertyKeyPermission>,1353	) -> DispatchResult {1354		<PalletCommon<T>>::set_token_property_permissions(collection, sender, property_permissions)1355	}13561357	pub fn token_property_permission(collection_id: CollectionId) -> PropertiesPermissionMap {1358		<PalletCommon<T>>::property_permissions(collection_id)1359	}13601361	pub fn set_scoped_token_property_permissions(1362		collection: &RefungibleHandle<T>,1363		sender: &T::CrossAccountId,1364		scope: PropertyScope,1365		property_permissions: Vec<PropertyKeyPermission>,1366	) -> DispatchResult {1367		<PalletCommon<T>>::set_scoped_token_property_permissions(1368			collection,1369			sender,1370			scope,1371			property_permissions,1372		)1373	}13741375	/// Returns 10 token in no particular order.1376	///1377	/// There is no direct way to get token holders in ascending order,1378	/// since `iter_prefix` returns values in no particular order.1379	/// Therefore, getting the 10 largest holders with a large value of holders1380	/// can lead to impact memory allocation + sorting with  `n * log (n)`.1381	pub fn token_owners(1382		collection_id: CollectionId,1383		token: TokenId,1384	) -> Option<Vec<T::CrossAccountId>> {1385		let res: Vec<T::CrossAccountId> = <Balance<T>>::iter_prefix((collection_id, token))1386			.map(|(owner, _amount)| owner)1387			.take(10)1388			.collect();13891390		if res.is_empty() {1391			None1392		} else {1393			Some(res)1394		}1395	}13961397	/// Sets or unsets the approval of a given operator.1398	///1399	/// The `operator` is allowed to transfer all token pieces of the `owner` on their behalf.1400	/// - `owner`: Token owner1401	/// - `operator`: Operator1402	/// - `approve`: Should operator status be granted or revoked?1403	pub fn set_allowance_for_all(1404		collection: &RefungibleHandle<T>,1405		owner: &T::CrossAccountId,1406		spender: &T::CrossAccountId,1407		approve: bool,1408	) -> DispatchResult {1409		<PalletCommon<T>>::set_allowance_for_all(1410			collection,1411			owner,1412			spender,1413			approve,1414			|| <CollectionAllowance<T>>::insert((collection.id, owner, spender), approve),1415			ERC721Events::ApprovalForAll {1416				owner: *owner.as_eth(),1417				operator: *spender.as_eth(),1418				approved: approve,1419			}1420			.to_log(collection_id_to_address(collection.id)),1421		)1422	}14231424	/// Tells whether the given `owner` approves the `operator`.1425	pub fn allowance_for_all(1426		collection: &RefungibleHandle<T>,1427		owner: &T::CrossAccountId,1428		spender: &T::CrossAccountId,1429	) -> bool {1430		<CollectionAllowance<T>>::get((collection.id, owner, spender))1431	}14321433	pub fn repair_item(collection: &RefungibleHandle<T>, token: TokenId) -> DispatchResult {1434		<TokenProperties<T>>::mutate((collection.id, token), |properties| {1435			properties.recompute_consumed_space();1436		});14371438		Ok(())1439	}1440}