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

difftreelog

source

pallets/refungible/src/lib.rs35.9 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;9192use codec::{Encode, Decode, MaxEncodedLen};93use core::ops::Deref;94use evm_coder::ToLog;95use frame_support::{BoundedVec, ensure, fail, 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, Event as CommonEvent, Pallet as PalletCommon,100};101use pallet_structure::Pallet as PalletStructure;102use scale_info::TypeInfo;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, CreateCollectionData, CreateRefungibleExData,108	CustomDataLimit, mapping::TokenAddressMapping, MAX_REFUNGIBLE_PIECES, TokenId, Property,109	PropertyKey, PropertyKeyPermission, PropertyPermission, PropertyScope, PropertyValue,110	TrySetProperty,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;120pub(crate) type SelfWeightOf<T> = <T as Config>::WeightInfo;121122/// Token data, stored independently from other data used to describe it123/// for the convenience of database access. Notably contains the token metadata.124#[struct_versioning::versioned(version = 2, upper)]125#[derive(Encode, Decode, Default, TypeInfo, MaxEncodedLen)]126#[deprecated(since = "0.2.0", note = "ItemData is no more contains usefull data")]127pub struct ItemData {128	pub const_data: BoundedVec<u8, CustomDataLimit>,129130	#[version(..2)]131	pub variable_data: BoundedVec<u8, CustomDataLimit>,132}133134#[frame_support::pallet]135pub mod pallet {136	use super::*;137	use frame_support::{138		Blake2_128, Blake2_128Concat, Twox64Concat, pallet_prelude::*, storage::Key,139		traits::StorageVersion,140	};141	use frame_system::pallet_prelude::*;142	use up_data_structs::{CollectionId, TokenId};143	use super::weights::WeightInfo;144145	#[pallet::error]146	pub enum Error<T> {147		/// Not Refungible item data used to mint in Refungible collection.148		NotRefungibleDataUsedToMintFungibleCollectionToken,149		/// Maximum refungibility exceeded.150		WrongRefungiblePieces,151		/// Refungible token can't be repartitioned by user who isn't owns all pieces.152		RepartitionWhileNotOwningAllPieces,153		/// Refungible token can't nest other tokens.154		RefungibleDisallowsNesting,155		/// Setting item properties is not allowed.156		SettingPropertiesNotAllowed,157	}158159	#[pallet::config]160	pub trait Config:161		frame_system::Config + pallet_common::Config + pallet_structure::Config162	{163		type WeightInfo: WeightInfo;164	}165166	const STORAGE_VERSION: StorageVersion = StorageVersion::new(2);167168	#[pallet::pallet]169	#[pallet::storage_version(STORAGE_VERSION)]170	#[pallet::generate_store(pub(super) trait Store)]171	pub struct Pallet<T>(_);172173	/// Total amount of minted tokens in a collection.174	#[pallet::storage]175	pub type TokensMinted<T: Config> =176		StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;177178	/// Amount of tokens burnt in a collection.179	#[pallet::storage]180	pub type TokensBurnt<T: Config> =181		StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;182183	/// Token data, used to partially describe a token.184	// TODO: remove185	#[pallet::storage]186	#[deprecated(since = "0.2.0", note = "ItemData is no more contains usefull data")]187	pub type TokenData<T: Config> = StorageNMap<188		Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),189		Value = ItemData,190		QueryKind = ValueQuery,191	>;192193	/// Amount of pieces a refungible token is split into.194	#[pallet::storage]195	#[pallet::getter(fn token_properties)]196	pub type TokenProperties<T: Config> = StorageNMap<197		Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),198		Value = up_data_structs::Properties,199		QueryKind = ValueQuery,200		OnEmpty = up_data_structs::TokenProperties,201	>;202203	/// Total amount of pieces for token204	#[pallet::storage]205	pub type TotalSupply<T: Config> = StorageNMap<206		Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),207		Value = u128,208		QueryKind = ValueQuery,209	>;210211	/// Used to enumerate tokens owned by account.212	#[pallet::storage]213	pub type Owned<T: Config> = StorageNMap<214		Key = (215			Key<Twox64Concat, CollectionId>,216			Key<Blake2_128Concat, T::CrossAccountId>,217			Key<Twox64Concat, TokenId>,218		),219		Value = bool,220		QueryKind = ValueQuery,221	>;222223	/// Amount of tokens (not pieces) partially owned by an account within a collection.224	#[pallet::storage]225	pub type AccountBalance<T: Config> = StorageNMap<226		Key = (227			Key<Twox64Concat, CollectionId>,228			// Owner229			Key<Blake2_128Concat, T::CrossAccountId>,230		),231		Value = u32,232		QueryKind = ValueQuery,233	>;234235	/// Amount of token pieces owned by account.236	#[pallet::storage]237	pub type Balance<T: Config> = StorageNMap<238		Key = (239			Key<Twox64Concat, CollectionId>,240			Key<Twox64Concat, TokenId>,241			// Owner242			Key<Blake2_128Concat, T::CrossAccountId>,243		),244		Value = u128,245		QueryKind = ValueQuery,246	>;247248	/// Allowance set by a token owner for another user to perform one of certain transactions on a number of pieces of a token.249	#[pallet::storage]250	pub type Allowance<T: Config> = StorageNMap<251		Key = (252			Key<Twox64Concat, CollectionId>,253			Key<Twox64Concat, TokenId>,254			// Owner255			Key<Blake2_128, T::CrossAccountId>,256			// Spender257			Key<Blake2_128Concat, T::CrossAccountId>,258		),259		Value = u128,260		QueryKind = ValueQuery,261	>;262263	#[pallet::hooks]264	impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {265		fn on_runtime_upgrade() -> Weight {266			let storage_version = StorageVersion::get::<Pallet<T>>();267			if storage_version < StorageVersion::new(2) {268				<TokenData<T>>::remove_all(None);269			}270			StorageVersion::new(2).put::<Pallet<T>>();271272			0273		}274	}275}276277pub struct RefungibleHandle<T: Config>(pallet_common::CollectionHandle<T>);278impl<T: Config> RefungibleHandle<T> {279	pub fn cast(inner: pallet_common::CollectionHandle<T>) -> Self {280		Self(inner)281	}282	pub fn into_inner(self) -> pallet_common::CollectionHandle<T> {283		self.0284	}285	pub fn common_mut(&mut self) -> &mut pallet_common::CollectionHandle<T> {286		&mut self.0287	}288}289290impl<T: Config> Deref for RefungibleHandle<T> {291	type Target = pallet_common::CollectionHandle<T>;292293	fn deref(&self) -> &Self::Target {294		&self.0295	}296}297298impl<T: Config> WithRecorder<T> for RefungibleHandle<T> {299	fn recorder(&self) -> &pallet_evm_coder_substrate::SubstrateRecorder<T> {300		self.0.recorder()301	}302	fn into_recorder(self) -> pallet_evm_coder_substrate::SubstrateRecorder<T> {303		self.0.into_recorder()304	}305}306307impl<T: Config> Pallet<T> {308	/// Get number of RFT tokens in collection309	pub fn total_supply(collection: &RefungibleHandle<T>) -> u32 {310		<TokensMinted<T>>::get(collection.id) - <TokensBurnt<T>>::get(collection.id)311	}312313	/// Check that RFT token exists314	///315	/// - `token`: Token ID.316	pub fn token_exists(collection: &RefungibleHandle<T>, token: TokenId) -> bool {317		<TotalSupply<T>>::contains_key((collection.id, token))318	}319320	pub fn set_scoped_token_property(321		collection_id: CollectionId,322		token_id: TokenId,323		scope: PropertyScope,324		property: Property,325	) -> DispatchResult {326		TokenProperties::<T>::try_mutate((collection_id, token_id), |properties| {327			properties.try_scoped_set(scope, property.key, property.value)328		})329		.map_err(<CommonError<T>>::from)?;330331		Ok(())332	}333334	pub fn set_scoped_token_properties(335		collection_id: CollectionId,336		token_id: TokenId,337		scope: PropertyScope,338		properties: impl Iterator<Item = Property>,339	) -> DispatchResult {340		TokenProperties::<T>::try_mutate((collection_id, token_id), |stored_properties| {341			stored_properties.try_scoped_set_from_iter(scope, properties)342		})343		.map_err(<CommonError<T>>::from)?;344345		Ok(())346	}347}348349// unchecked calls skips any permission checks350impl<T: Config> Pallet<T> {351	/// Create RFT collection352	///353	/// `init_collection` will take non-refundable deposit for collection creation.354	///355	/// - `data`: Contains settings for collection limits and permissions.356	pub fn init_collection(357		owner: T::CrossAccountId,358		data: CreateCollectionData<T::AccountId>,359	) -> Result<CollectionId, DispatchError> {360		<PalletCommon<T>>::init_collection(owner, data, false)361	}362363	/// Destroy RFT collection364	///365	/// `destroy_collection` will throw error if collection contains any tokens.366	/// Only owner can destroy collection.367	pub fn destroy_collection(368		collection: RefungibleHandle<T>,369		sender: &T::CrossAccountId,370	) -> DispatchResult {371		let id = collection.id;372373		if Self::collection_has_tokens(id) {374			return Err(<CommonError<T>>::CantDestroyNotEmptyCollection.into());375		}376377		// =========378379		PalletCommon::destroy_collection(collection.0, sender)?;380381		<TokensMinted<T>>::remove(id);382		<TokensBurnt<T>>::remove(id);383		<TotalSupply<T>>::remove_prefix((id,), None);384		<Balance<T>>::remove_prefix((id,), None);385		<Allowance<T>>::remove_prefix((id,), None);386		<Owned<T>>::remove_prefix((id,), None);387		<AccountBalance<T>>::remove_prefix((id,), None);388		Ok(())389	}390391	fn collection_has_tokens(collection_id: CollectionId) -> bool {392		<TotalSupply<T>>::iter_prefix((collection_id,))393			.next()394			.is_some()395	}396397	pub fn burn_token_unchecked(398		collection: &RefungibleHandle<T>,399		token_id: TokenId,400	) -> DispatchResult {401		let burnt = <TokensBurnt<T>>::get(collection.id)402			.checked_add(1)403			.ok_or(ArithmeticError::Overflow)?;404405		<TokensBurnt<T>>::insert(collection.id, burnt);406		<TokenProperties<T>>::remove((collection.id, token_id));407		<TotalSupply<T>>::remove((collection.id, token_id));408		<Balance<T>>::remove_prefix((collection.id, token_id), None);409		<Allowance<T>>::remove_prefix((collection.id, token_id), None);410		// TODO: ERC721 transfer event411		Ok(())412	}413414	/// Burn RFT token pieces415	///416	/// `burn` will decrease total amount of token pieces and amount owned by sender.417	/// `burn` can be called even if there are multiple owners of the RFT token.418	/// If sender wouldn't have any pieces left after `burn` than she will stop being419	/// one of the owners of the token. If there is no account that owns any pieces of420	/// the token than token will be burned too.421	///422	/// - `amount`: Amount of token pieces to burn.423	/// - `token`: Token who's pieces should be burned424	/// - `collection`: Collection that contains the token425	pub fn burn(426		collection: &RefungibleHandle<T>,427		owner: &T::CrossAccountId,428		token: TokenId,429		amount: u128,430	) -> DispatchResult {431		let total_supply = <TotalSupply<T>>::get((collection.id, token))432			.checked_sub(amount)433			.ok_or(<CommonError<T>>::TokenValueTooLow)?;434435		// This was probally last owner of this token?436		if total_supply == 0 {437			// Ensure user actually owns this amount438			ensure!(439				<Balance<T>>::get((collection.id, token, owner)) == amount,440				<CommonError<T>>::TokenValueTooLow441			);442			let account_balance = <AccountBalance<T>>::get((collection.id, owner))443				.checked_sub(1)444				// Should not occur445				.ok_or(ArithmeticError::Underflow)?;446447			// =========448449			<Owned<T>>::remove((collection.id, owner, token));450			<PalletStructure<T>>::unnest_if_nested(owner, collection.id, token);451			<AccountBalance<T>>::insert((collection.id, owner), account_balance);452			Self::burn_token_unchecked(collection, token)?;453			<PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(454				collection.id,455				token,456				owner.clone(),457				amount,458			));459			return Ok(());460		}461462		let balance = <Balance<T>>::get((collection.id, token, owner))463			.checked_sub(amount)464			.ok_or(<CommonError<T>>::TokenValueTooLow)?;465		let account_balance = if balance == 0 {466			<AccountBalance<T>>::get((collection.id, owner))467				.checked_sub(1)468				// Should not occur469				.ok_or(ArithmeticError::Underflow)?470		} else {471			0472		};473474		// =========475476		if balance == 0 {477			<Owned<T>>::remove((collection.id, owner, token));478			<PalletStructure<T>>::unnest_if_nested(owner, collection.id, token);479			<Balance<T>>::remove((collection.id, token, owner));480			<AccountBalance<T>>::insert((collection.id, owner), account_balance);481		} else {482			<Balance<T>>::insert((collection.id, token, owner), balance);483		}484		<TotalSupply<T>>::insert((collection.id, token), total_supply);485486		<PalletEvm<T>>::deposit_log(487			ERC20Events::Transfer {488				from: *owner.as_eth(),489				to: H160::default(),490				value: amount.into(),491			}492			.to_log(T::EvmTokenAddressMapping::token_to_address(493				collection.id,494				token,495			)),496		);497		<PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(498			collection.id,499			token,500			owner.clone(),501			amount,502		));503		Ok(())504	}505506	#[transactional]507	fn modify_token_properties(508		collection: &RefungibleHandle<T>,509		sender: &T::CrossAccountId,510		token_id: TokenId,511		properties: impl Iterator<Item = (PropertyKey, Option<PropertyValue>)>,512		is_token_create: bool,513		nesting_budget: &dyn Budget,514	) -> DispatchResult {515		let is_collection_admin = || collection.is_owner_or_admin(sender);516		let is_token_owner = || -> Result<bool, DispatchError> {517			let balance = collection.balance(sender.clone(), token_id);518			let total_pieces: u128 =519				Self::total_pieces(collection.id, token_id).unwrap_or(u128::MAX);520			if balance != total_pieces {521				return Ok(false);522			}523524			let is_bundle_owner = <PalletStructure<T>>::check_indirectly_owned(525				sender.clone(),526				collection.id,527				token_id,528				None,529				nesting_budget,530			)?;531532			Ok(is_bundle_owner)533		};534535		for (key, value) in properties {536			let permission = <PalletCommon<T>>::property_permissions(collection.id)537				.get(&key)538				.cloned()539				.unwrap_or_else(PropertyPermission::none);540541			let is_property_exists = TokenProperties::<T>::get((collection.id, token_id))542				.get(&key)543				.is_some();544545			match permission {546				PropertyPermission { mutable: false, .. } if is_property_exists => {547					return Err(<CommonError<T>>::NoPermission.into());548				}549550				PropertyPermission {551					collection_admin,552					token_owner,553					..554				} => {555					//TODO: investigate threats during public minting.556					let is_token_create =557						is_token_create && (collection_admin || token_owner) && value.is_some();558					if !(is_token_create559						|| (collection_admin && is_collection_admin())560						|| (token_owner && is_token_owner()?))561					{562						fail!(<CommonError<T>>::NoPermission);563					}564				}565			}566567			match value {568				Some(value) => {569					<TokenProperties<T>>::try_mutate((collection.id, token_id), |properties| {570						properties.try_set(key.clone(), value)571					})572					.map_err(<CommonError<T>>::from)?;573574					<PalletCommon<T>>::deposit_event(CommonEvent::TokenPropertySet(575						collection.id,576						token_id,577						key,578					));579				}580				None => {581					<TokenProperties<T>>::try_mutate((collection.id, token_id), |properties| {582						properties.remove(&key)583					})584					.map_err(<CommonError<T>>::from)?;585586					<PalletCommon<T>>::deposit_event(CommonEvent::TokenPropertyDeleted(587						collection.id,588						token_id,589						key,590					));591				}592			}593		}594595		Ok(())596	}597598	pub fn set_token_properties(599		collection: &RefungibleHandle<T>,600		sender: &T::CrossAccountId,601		token_id: TokenId,602		properties: impl Iterator<Item = Property>,603		is_token_create: bool,604		nesting_budget: &dyn Budget,605	) -> DispatchResult {606		Self::modify_token_properties(607			collection,608			sender,609			token_id,610			properties.map(|p| (p.key, Some(p.value))),611			is_token_create,612			nesting_budget,613		)614	}615616	pub fn set_token_property(617		collection: &RefungibleHandle<T>,618		sender: &T::CrossAccountId,619		token_id: TokenId,620		property: Property,621		nesting_budget: &dyn Budget,622	) -> DispatchResult {623		let is_token_create = false;624625		Self::set_token_properties(626			collection,627			sender,628			token_id,629			[property].into_iter(),630			is_token_create,631			nesting_budget,632		)633	}634635	pub fn delete_token_properties(636		collection: &RefungibleHandle<T>,637		sender: &T::CrossAccountId,638		token_id: TokenId,639		property_keys: impl Iterator<Item = PropertyKey>,640		nesting_budget: &dyn Budget,641	) -> DispatchResult {642		let is_token_create = false;643644		Self::modify_token_properties(645			collection,646			sender,647			token_id,648			property_keys.into_iter().map(|key| (key, None)),649			is_token_create,650			nesting_budget,651		)652	}653654	pub fn delete_token_property(655		collection: &RefungibleHandle<T>,656		sender: &T::CrossAccountId,657		token_id: TokenId,658		property_key: PropertyKey,659		nesting_budget: &dyn Budget,660	) -> DispatchResult {661		Self::delete_token_properties(662			collection,663			sender,664			token_id,665			[property_key].into_iter(),666			nesting_budget,667		)668	}669670	/// Transfer RFT token pieces from one account to another.671	///672	/// If the sender is no longer owns any pieces after the `transfer` than she stops being an owner of the token.673	///674	/// - `from`: Owner of token pieces to transfer.675	/// - `to`: Recepient of transfered token pieces.676	/// - `amount`: Amount of token pieces to transfer.677	/// - `token`: Token whos pieces should be transfered678	/// - `collection`: Collection that contains the token679	pub fn transfer(680		collection: &RefungibleHandle<T>,681		from: &T::CrossAccountId,682		to: &T::CrossAccountId,683		token: TokenId,684		amount: u128,685		nesting_budget: &dyn Budget,686	) -> DispatchResult {687		ensure!(688			collection.limits.transfers_enabled(),689			<CommonError<T>>::TransferNotAllowed690		);691692		if collection.permissions.access() == AccessMode::AllowList {693			collection.check_allowlist(from)?;694			collection.check_allowlist(to)?;695		}696		<PalletCommon<T>>::ensure_correct_receiver(to)?;697698		let balance_from = <Balance<T>>::get((collection.id, token, from))699			.checked_sub(amount)700			.ok_or(<CommonError<T>>::TokenValueTooLow)?;701		let mut create_target = false;702		let from_to_differ = from != to;703		let balance_to = if from != to {704			let old_balance = <Balance<T>>::get((collection.id, token, to));705			if old_balance == 0 {706				create_target = true;707			}708			Some(709				old_balance710					.checked_add(amount)711					.ok_or(ArithmeticError::Overflow)?,712			)713		} else {714			None715		};716717		let account_balance_from = if balance_from == 0 {718			Some(719				<AccountBalance<T>>::get((collection.id, from))720					.checked_sub(1)721					// Should not occur722					.ok_or(ArithmeticError::Underflow)?,723			)724		} else {725			None726		};727		// Account data is created in token, AccountBalance should be increased728		// But only if from != to as we shouldn't check overflow in this case729		let account_balance_to = if create_target && from_to_differ {730			let account_balance_to = <AccountBalance<T>>::get((collection.id, to))731				.checked_add(1)732				.ok_or(ArithmeticError::Overflow)?;733			ensure!(734				account_balance_to < collection.limits.account_token_ownership_limit(),735				<CommonError<T>>::AccountTokenLimitExceeded,736			);737738			Some(account_balance_to)739		} else {740			None741		};742743		// =========744745		<PalletStructure<T>>::nest_if_sent_to_token(746			from.clone(),747			to,748			collection.id,749			token,750			nesting_budget,751		)?;752753		if let Some(balance_to) = balance_to {754			// from != to755			if balance_from == 0 {756				<Balance<T>>::remove((collection.id, token, from));757				<PalletStructure<T>>::unnest_if_nested(from, collection.id, token);758			} else {759				<Balance<T>>::insert((collection.id, token, from), balance_from);760			}761			<Balance<T>>::insert((collection.id, token, to), balance_to);762			if let Some(account_balance_from) = account_balance_from {763				<AccountBalance<T>>::insert((collection.id, from), account_balance_from);764				<Owned<T>>::remove((collection.id, from, token));765			}766			if let Some(account_balance_to) = account_balance_to {767				<AccountBalance<T>>::insert((collection.id, to), account_balance_to);768				<Owned<T>>::insert((collection.id, to, token), true);769			}770		}771772		<PalletEvm<T>>::deposit_log(773			ERC20Events::Transfer {774				from: *from.as_eth(),775				to: *to.as_eth(),776				value: amount.into(),777			}778			.to_log(T::EvmTokenAddressMapping::token_to_address(779				collection.id,780				token,781			)),782		);783		<PalletCommon<T>>::deposit_event(CommonEvent::Transfer(784			collection.id,785			token,786			from.clone(),787			to.clone(),788			amount,789		));790		Ok(())791	}792793	/// Batched operation to create multiple RFT tokens.794	///795	/// Same as `create_item` but creates multiple tokens.796	///797	/// - `data`: Same as 'data` in `create_item` but contains data for multiple tokens.798	pub fn create_multiple_items(799		collection: &RefungibleHandle<T>,800		sender: &T::CrossAccountId,801		data: Vec<CreateRefungibleExData<T::CrossAccountId>>,802		nesting_budget: &dyn Budget,803	) -> DispatchResult {804		if !collection.is_owner_or_admin(sender) {805			ensure!(806				collection.permissions.mint_mode(),807				<CommonError<T>>::PublicMintingNotAllowed808			);809			collection.check_allowlist(sender)?;810811			for item in data.iter() {812				for user in item.users.keys() {813					collection.check_allowlist(user)?;814				}815			}816		}817818		for item in data.iter() {819			for (owner, _) in item.users.iter() {820				<PalletCommon<T>>::ensure_correct_receiver(owner)?;821			}822		}823824		// Total pieces per tokens825		let totals = data826			.iter()827			.map(|data| {828				Ok(data829					.users830					.iter()831					.map(|u| u.1)832					.try_fold(0u128, |acc, v| acc.checked_add(*v))833					.ok_or(ArithmeticError::Overflow)?)834			})835			.collect::<Result<Vec<_>, DispatchError>>()?;836		for total in &totals {837			ensure!(838				*total <= MAX_REFUNGIBLE_PIECES,839				<Error<T>>::WrongRefungiblePieces840			);841		}842843		let first_token_id = <TokensMinted<T>>::get(collection.id);844		let tokens_minted = first_token_id845			.checked_add(data.len() as u32)846			.ok_or(ArithmeticError::Overflow)?;847		ensure!(848			tokens_minted < collection.limits.token_limit(),849			<CommonError<T>>::CollectionTokenLimitExceeded850		);851852		let mut balances = BTreeMap::new();853		for data in &data {854			for owner in data.users.keys() {855				let balance = balances856					.entry(owner)857					.or_insert_with(|| <AccountBalance<T>>::get((collection.id, owner)));858				*balance = balance.checked_add(1).ok_or(ArithmeticError::Overflow)?;859860				ensure!(861					*balance <= collection.limits.account_token_ownership_limit(),862					<CommonError<T>>::AccountTokenLimitExceeded,863				);864			}865		}866867		for (i, token) in data.iter().enumerate() {868			let token_id = TokenId(first_token_id + i as u32 + 1);869			for (to, _) in token.users.iter() {870				<PalletStructure<T>>::check_nesting(871					sender.clone(),872					to,873					collection.id,874					token_id,875					nesting_budget,876				)?;877			}878		}879880		// =========881882		with_transaction(|| {883			for (i, data) in data.iter().enumerate() {884				let token_id = first_token_id + i as u32 + 1;885				<TotalSupply<T>>::insert((collection.id, token_id), totals[i]);886887				for (user, amount) in data.users.iter() {888					if *amount == 0 {889						continue;890					}891					<Balance<T>>::insert((collection.id, token_id, &user), amount);892					<Owned<T>>::insert((collection.id, &user, TokenId(token_id)), true);893					<PalletStructure<T>>::nest_if_sent_to_token_unchecked(894						user,895						collection.id,896						TokenId(token_id),897					);898				}899900				if let Err(e) = Self::set_token_properties(901					collection,902					sender,903					TokenId(token_id),904					data.properties.clone().into_iter(),905					true,906					nesting_budget,907				) {908					return TransactionOutcome::Rollback(Err(e));909				}910			}911			TransactionOutcome::Commit(Ok(()))912		})?;913914		<TokensMinted<T>>::insert(collection.id, tokens_minted);915916		for (account, balance) in balances {917			<AccountBalance<T>>::insert((collection.id, account), balance);918		}919920		for (i, token) in data.into_iter().enumerate() {921			let token_id = first_token_id + i as u32 + 1;922923			for (user, amount) in token.users.into_iter() {924				if amount == 0 {925					continue;926				}927928				<PalletEvm<T>>::deposit_log(929					ERC20Events::Transfer {930						from: H160::default(),931						to: *user.as_eth(),932						value: amount.into(),933					}934					.to_log(T::EvmTokenAddressMapping::token_to_address(935						collection.id,936						TokenId(token_id),937					)),938				);939				<PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(940					collection.id,941					TokenId(token_id),942					user,943					amount,944				));945			}946		}947		Ok(())948	}949950	pub fn set_allowance_unchecked(951		collection: &RefungibleHandle<T>,952		sender: &T::CrossAccountId,953		spender: &T::CrossAccountId,954		token: TokenId,955		amount: u128,956	) {957		if amount == 0 {958			<Allowance<T>>::remove((collection.id, token, sender, spender));959		} else {960			<Allowance<T>>::insert((collection.id, token, sender, spender), amount);961		}962963		<PalletEvm<T>>::deposit_log(964			ERC20Events::Approval {965				owner: *sender.as_eth(),966				spender: *spender.as_eth(),967				value: amount.into(),968			}969			.to_log(T::EvmTokenAddressMapping::token_to_address(970				collection.id,971				token,972			)),973		);974		<PalletCommon<T>>::deposit_event(CommonEvent::Approved(975			collection.id,976			token,977			sender.clone(),978			spender.clone(),979			amount,980		))981	}982983	/// Set allowance for the spender to `transfer` or `burn` sender's token pieces.984	///985	/// - `amount`: Amount of token pieces the spender is allowed to `transfer` or `burn.986	pub fn set_allowance(987		collection: &RefungibleHandle<T>,988		sender: &T::CrossAccountId,989		spender: &T::CrossAccountId,990		token: TokenId,991		amount: u128,992	) -> DispatchResult {993		if collection.permissions.access() == AccessMode::AllowList {994			collection.check_allowlist(sender)?;995			collection.check_allowlist(spender)?;996		}997998		<PalletCommon<T>>::ensure_correct_receiver(spender)?;9991000		if <Balance<T>>::get((collection.id, token, sender)) < amount {1001			ensure!(1002				collection.ignores_owned_amount(sender) && Self::token_exists(collection, token),1003				<CommonError<T>>::CantApproveMoreThanOwned1004			);1005		}10061007		// =========10081009		Self::set_allowance_unchecked(collection, sender, spender, token, amount);1010		Ok(())1011	}10121013	/// Returns allowance, which should be set after transaction1014	fn check_allowed(1015		collection: &RefungibleHandle<T>,1016		spender: &T::CrossAccountId,1017		from: &T::CrossAccountId,1018		token: TokenId,1019		amount: u128,1020		nesting_budget: &dyn Budget,1021	) -> Result<Option<u128>, DispatchError> {1022		if spender.conv_eq(from) {1023			return Ok(None);1024		}1025		if collection.permissions.access() == AccessMode::AllowList {1026			// `from`, `to` checked in [`transfer`]1027			collection.check_allowlist(spender)?;1028		}1029		if let Some(source) = T::CrossTokenAddressMapping::address_to_token(from) {1030			// TODO: should collection owner be allowed to perform this transfer?1031			ensure!(1032				<PalletStructure<T>>::check_indirectly_owned(1033					spender.clone(),1034					source.0,1035					source.1,1036					None,1037					nesting_budget1038				)?,1039				<CommonError<T>>::ApprovedValueTooLow,1040			);1041			return Ok(None);1042		}1043		let allowance =1044			<Allowance<T>>::get((collection.id, token, from, &spender)).checked_sub(amount);1045		if allowance.is_none() {1046			ensure!(1047				collection.ignores_allowance(spender),1048				<CommonError<T>>::ApprovedValueTooLow1049			);1050		}1051		Ok(allowance)1052	}10531054	/// Transfer RFT token pieces from one account to another.1055	///1056	/// Same as the [`transfer`] but spender doesn't needs to be an owner of the token pieces.1057	/// The owner should set allowance for the spender to transfer pieces.1058	///1059	/// [`transfer`]: struct.Pallet.html#method.transfer1060	pub fn transfer_from(1061		collection: &RefungibleHandle<T>,1062		spender: &T::CrossAccountId,1063		from: &T::CrossAccountId,1064		to: &T::CrossAccountId,1065		token: TokenId,1066		amount: u128,1067		nesting_budget: &dyn Budget,1068	) -> DispatchResult {1069		let allowance =1070			Self::check_allowed(collection, spender, from, token, amount, nesting_budget)?;10711072		// =========10731074		Self::transfer(collection, from, to, token, amount, nesting_budget)?;1075		if let Some(allowance) = allowance {1076			Self::set_allowance_unchecked(collection, from, spender, token, allowance);1077		}1078		Ok(())1079	}10801081	/// Burn RFT token pieces from the account.1082	///1083	/// Same as the [`burn`] but spender doesn't need to be an owner of the token pieces. The owner should1084	/// set allowance for the spender to burn pieces1085	///1086	/// [`burn`]: struct.Pallet.html#method.burn1087	pub fn burn_from(1088		collection: &RefungibleHandle<T>,1089		spender: &T::CrossAccountId,1090		from: &T::CrossAccountId,1091		token: TokenId,1092		amount: u128,1093		nesting_budget: &dyn Budget,1094	) -> DispatchResult {1095		let allowance =1096			Self::check_allowed(collection, spender, from, token, amount, nesting_budget)?;10971098		// =========10991100		Self::burn(collection, from, token, amount)?;1101		if let Some(allowance) = allowance {1102			Self::set_allowance_unchecked(collection, from, spender, token, allowance);1103		}1104		Ok(())1105	}11061107	/// Create RFT token.1108	///1109	/// The sender should be the owner/admin of the collection or collection should be configured1110	/// to allow public minting.1111	///1112	/// - `data`: Contains list of users who will become the owners of the token pieces and amount1113	///   of token pieces they will receive.1114	pub fn create_item(1115		collection: &RefungibleHandle<T>,1116		sender: &T::CrossAccountId,1117		data: CreateRefungibleExData<T::CrossAccountId>,1118		nesting_budget: &dyn Budget,1119	) -> DispatchResult {1120		Self::create_multiple_items(collection, sender, vec![data], nesting_budget)1121	}11221123	/// Repartition RFT token.1124	///1125	/// `repartition` will set token balance of the sender and total amount of token pieces.1126	/// Sender should own all of the token pieces. `repartition' could be done even if some1127	/// token pieces were burned before.1128	///1129	/// - `amount`: Total amount of token pieces that the token will have after `repartition`.1130	pub fn repartition(1131		collection: &RefungibleHandle<T>,1132		owner: &T::CrossAccountId,1133		token: TokenId,1134		amount: u128,1135	) -> DispatchResult {1136		ensure!(1137			amount <= MAX_REFUNGIBLE_PIECES,1138			<Error<T>>::WrongRefungiblePieces1139		);1140		ensure!(amount > 0, <CommonError<T>>::TokenValueTooLow);1141		// Ensure user owns all pieces1142		let total_pieces = Self::total_pieces(collection.id, token).unwrap_or(u128::MAX);1143		let balance = <Balance<T>>::get((collection.id, token, owner));1144		ensure!(1145			total_pieces == balance,1146			<Error<T>>::RepartitionWhileNotOwningAllPieces1147		);11481149		<Balance<T>>::insert((collection.id, token, owner), amount);1150		<TotalSupply<T>>::insert((collection.id, token), amount);11511152		if amount > total_pieces {1153			let mint_amount = amount - total_pieces;1154			<PalletEvm<T>>::deposit_log(1155				ERC20Events::Transfer {1156					from: H160::default(),1157					to: *owner.as_eth(),1158					value: mint_amount.into(),1159				}1160				.to_log(T::EvmTokenAddressMapping::token_to_address(1161					collection.id,1162					token,1163				)),1164			);1165			<PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(1166				collection.id,1167				token,1168				owner.clone(),1169				mint_amount,1170			));1171		} else if total_pieces > amount {1172			let burn_amount = total_pieces - amount;1173			<PalletEvm<T>>::deposit_log(1174				ERC20Events::Transfer {1175					from: *owner.as_eth(),1176					to: H160::default(),1177					value: burn_amount.into(),1178				}1179				.to_log(T::EvmTokenAddressMapping::token_to_address(1180					collection.id,1181					token,1182				)),1183			);1184			<PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(1185				collection.id,1186				token,1187				owner.clone(),1188				burn_amount,1189			));1190		}11911192		Ok(())1193	}11941195	fn token_owner(collection_id: CollectionId, token_id: TokenId) -> Option<T::CrossAccountId> {1196		let mut owner = None;1197		let mut count = 0;1198		for key in Balance::<T>::iter_key_prefix((collection_id, token_id)) {1199			count += 1;1200			if count > 1 {1201				return None;1202			}1203			owner = Some(key);1204		}1205		owner1206	}12071208	fn total_pieces(collection_id: CollectionId, token_id: TokenId) -> Option<u128> {1209		<TotalSupply<T>>::try_get((collection_id, token_id)).ok()1210	}12111212	pub fn set_collection_properties(1213		collection: &RefungibleHandle<T>,1214		sender: &T::CrossAccountId,1215		properties: Vec<Property>,1216	) -> DispatchResult {1217		<PalletCommon<T>>::set_collection_properties(collection, sender, properties)1218	}12191220	pub fn delete_collection_properties(1221		collection: &RefungibleHandle<T>,1222		sender: &T::CrossAccountId,1223		property_keys: Vec<PropertyKey>,1224	) -> DispatchResult {1225		<PalletCommon<T>>::delete_collection_properties(collection, sender, property_keys)1226	}12271228	pub fn set_token_property_permissions(1229		collection: &RefungibleHandle<T>,1230		sender: &T::CrossAccountId,1231		property_permissions: Vec<PropertyKeyPermission>,1232	) -> DispatchResult {1233		<PalletCommon<T>>::set_token_property_permissions(collection, sender, property_permissions)1234	}12351236	/// Returns 10 token in no particular order.1237	///1238	/// There is no direct way to get token holders in ascending order,1239	/// since `iter_prefix` returns values in no particular order.1240	/// Therefore, getting the 10 largest holders with a large value of holders1241	/// can lead to impact memory allocation + sorting with  `n * log (n)`.1242	pub fn token_owners(1243		collection_id: CollectionId,1244		token: TokenId,1245	) -> Option<Vec<T::CrossAccountId>> {1246		let res: Vec<T::CrossAccountId> = <Balance<T>>::iter_prefix((collection_id, token))1247			.map(|(owner, _amount)| owner)1248			.take(10)1249			.collect();12501251		if res.is_empty() {1252			None1253		} else {1254			Some(res)1255		}1256	}1257}