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

difftreelog

source

pallets/refungible/src/lib.rs36.5 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 codec::{Encode, Decode, MaxEncodedLen};94use core::ops::Deref;95use evm_coder::ToLog;96use frame_support::{BoundedVec, ensure, fail, storage::with_transaction, transactional};97use pallet_evm::{account::CrossAccountId, Pallet as PalletEvm};98use pallet_evm_coder_substrate::WithRecorder;99use pallet_common::{100	CommonCollectionOperations, Error as CommonError, Event as CommonEvent,101	eth::collection_id_to_address, Pallet as PalletCommon,102};103use pallet_structure::Pallet as PalletStructure;104use scale_info::TypeInfo;105use sp_core::H160;106use sp_runtime::{ArithmeticError, DispatchError, DispatchResult, TransactionOutcome};107use sp_std::{vec::Vec, vec, collections::btree_map::BTreeMap};108use up_data_structs::{109	AccessMode, budget::Budget, CollectionId, CreateCollectionData, CreateRefungibleExData,110	CustomDataLimit, mapping::TokenAddressMapping, MAX_REFUNGIBLE_PIECES, TokenId, Property,111	PropertyKey, PropertyKeyPermission, PropertyPermission, PropertyScope, PropertyValue,112	TrySetProperty,113};114115pub use pallet::*;116#[cfg(feature = "runtime-benchmarks")]117pub mod benchmarking;118pub mod common;119pub mod erc;120pub mod erc_token;121pub mod weights;122123pub type CreateItemData<T> =124	CreateRefungibleExData<<T as pallet_evm::account::Config>::CrossAccountId>;125pub(crate) type SelfWeightOf<T> = <T as Config>::WeightInfo;126127/// Token data, stored independently from other data used to describe it128/// for the convenience of database access. Notably contains the token metadata.129#[struct_versioning::versioned(version = 2, upper)]130#[derive(Encode, Decode, Default, TypeInfo, MaxEncodedLen)]131pub struct ItemData {132	pub const_data: BoundedVec<u8, CustomDataLimit>,133134	#[version(..2)]135	pub variable_data: BoundedVec<u8, CustomDataLimit>,136}137138#[frame_support::pallet]139pub mod pallet {140	use super::*;141	use frame_support::{142		Blake2_128, Blake2_128Concat, Twox64Concat, pallet_prelude::*, storage::Key,143		traits::StorageVersion,144	};145	use frame_system::pallet_prelude::*;146	use up_data_structs::{CollectionId, TokenId};147	use super::weights::WeightInfo;148149	#[pallet::error]150	pub enum Error<T> {151		/// Not Refungible item data used to mint in Refungible collection.152		NotRefungibleDataUsedToMintFungibleCollectionToken,153		/// Maximum refungibility exceeded.154		WrongRefungiblePieces,155		/// Refungible token can't be repartitioned by user who isn't owns all pieces.156		RepartitionWhileNotOwningAllPieces,157		/// Refungible token can't nest other tokens.158		RefungibleDisallowsNesting,159		/// Setting item properties is not allowed.160		SettingPropertiesNotAllowed,161	}162163	#[pallet::config]164	pub trait Config:165		frame_system::Config + pallet_common::Config + pallet_structure::Config166	{167		type WeightInfo: WeightInfo;168	}169170	const STORAGE_VERSION: StorageVersion = StorageVersion::new(1);171172	#[pallet::pallet]173	#[pallet::storage_version(STORAGE_VERSION)]174	#[pallet::generate_store(pub(super) trait Store)]175	pub struct Pallet<T>(_);176177	/// Total amount of minted tokens in a collection.178	#[pallet::storage]179	pub type TokensMinted<T: Config> =180		StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;181182	/// Amount of tokens burnt in a collection.183	#[pallet::storage]184	pub type TokensBurnt<T: Config> =185		StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;186187	/// Token data, used to partially describe a token.188	#[pallet::storage]189	pub type TokenData<T: Config> = StorageNMap<190		Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),191		Value = ItemData,192		QueryKind = ValueQuery,193	>;194195	/// Amount of pieces a refungible token is split into.196	#[pallet::storage]197	#[pallet::getter(fn token_properties)]198	pub type TokenProperties<T: Config> = StorageNMap<199		Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),200		Value = up_data_structs::Properties,201		QueryKind = ValueQuery,202		OnEmpty = up_data_structs::TokenProperties,203	>;204205	/// Total amount of pieces for token206	#[pallet::storage]207	pub type TotalSupply<T: Config> = StorageNMap<208		Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),209		Value = u128,210		QueryKind = ValueQuery,211	>;212213	/// Used to enumerate tokens owned by account.214	#[pallet::storage]215	pub type Owned<T: Config> = StorageNMap<216		Key = (217			Key<Twox64Concat, CollectionId>,218			Key<Blake2_128Concat, T::CrossAccountId>,219			Key<Twox64Concat, TokenId>,220		),221		Value = bool,222		QueryKind = ValueQuery,223	>;224225	/// Amount of tokens (not pieces) partially owned by an account within a collection.226	#[pallet::storage]227	pub type AccountBalance<T: Config> = StorageNMap<228		Key = (229			Key<Twox64Concat, CollectionId>,230			// Owner231			Key<Blake2_128Concat, T::CrossAccountId>,232		),233		Value = u32,234		QueryKind = ValueQuery,235	>;236237	/// Amount of token pieces owned by account.238	#[pallet::storage]239	pub type Balance<T: Config> = StorageNMap<240		Key = (241			Key<Twox64Concat, CollectionId>,242			Key<Twox64Concat, TokenId>,243			// Owner244			Key<Blake2_128Concat, T::CrossAccountId>,245		),246		Value = u128,247		QueryKind = ValueQuery,248	>;249250	/// Allowance set by a token owner for another user to perform one of certain transactions on a number of pieces of a token.251	#[pallet::storage]252	pub type Allowance<T: Config> = StorageNMap<253		Key = (254			Key<Twox64Concat, CollectionId>,255			Key<Twox64Concat, TokenId>,256			// Owner257			Key<Blake2_128, T::CrossAccountId>,258			// Spender259			Key<Blake2_128Concat, T::CrossAccountId>,260		),261		Value = u128,262		QueryKind = ValueQuery,263	>;264265	#[pallet::hooks]266	impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {267		fn on_runtime_upgrade() -> Weight {268			if StorageVersion::get::<Pallet<T>>() < StorageVersion::new(1) {269				<TokenData<T>>::translate_values::<ItemDataVersion1, _>(|v| {270					Some(<ItemDataVersion2>::from(v))271				})272			}273274			0275		}276	}277}278279pub struct RefungibleHandle<T: Config>(pallet_common::CollectionHandle<T>);280impl<T: Config> RefungibleHandle<T> {281	pub fn cast(inner: pallet_common::CollectionHandle<T>) -> Self {282		Self(inner)283	}284	pub fn into_inner(self) -> pallet_common::CollectionHandle<T> {285		self.0286	}287	pub fn common_mut(&mut self) -> &mut pallet_common::CollectionHandle<T> {288		&mut self.0289	}290}291292impl<T: Config> Deref for RefungibleHandle<T> {293	type Target = pallet_common::CollectionHandle<T>;294295	fn deref(&self) -> &Self::Target {296		&self.0297	}298}299300impl<T: Config> WithRecorder<T> for RefungibleHandle<T> {301	fn recorder(&self) -> &pallet_evm_coder_substrate::SubstrateRecorder<T> {302		self.0.recorder()303	}304	fn into_recorder(self) -> pallet_evm_coder_substrate::SubstrateRecorder<T> {305		self.0.into_recorder()306	}307}308309impl<T: Config> Pallet<T> {310	/// Get number of RFT tokens in collection311	pub fn total_supply(collection: &RefungibleHandle<T>) -> u32 {312		<TokensMinted<T>>::get(collection.id) - <TokensBurnt<T>>::get(collection.id)313	}314315	/// Check that RFT token exists316	///317	/// - `token`: Token ID.318	pub fn token_exists(collection: &RefungibleHandle<T>, token: TokenId) -> bool {319		<TotalSupply<T>>::contains_key((collection.id, token))320	}321322	pub fn set_scoped_token_property(323		collection_id: CollectionId,324		token_id: TokenId,325		scope: PropertyScope,326		property: Property,327	) -> DispatchResult {328		TokenProperties::<T>::try_mutate((collection_id, token_id), |properties| {329			properties.try_scoped_set(scope, property.key, property.value)330		})331		.map_err(<CommonError<T>>::from)?;332333		Ok(())334	}335336	pub fn set_scoped_token_properties(337		collection_id: CollectionId,338		token_id: TokenId,339		scope: PropertyScope,340		properties: impl Iterator<Item = Property>,341	) -> DispatchResult {342		TokenProperties::<T>::try_mutate((collection_id, token_id), |stored_properties| {343			stored_properties.try_scoped_set_from_iter(scope, properties)344		})345		.map_err(<CommonError<T>>::from)?;346347		Ok(())348	}349}350351// unchecked calls skips any permission checks352impl<T: Config> Pallet<T> {353	/// Create RFT collection354	///355	/// `init_collection` will take non-refundable deposit for collection creation.356	///357	/// - `data`: Contains settings for collection limits and permissions.358	pub fn init_collection(359		owner: T::CrossAccountId,360		data: CreateCollectionData<T::AccountId>,361	) -> Result<CollectionId, DispatchError> {362		<PalletCommon<T>>::init_collection(owner, data, false)363	}364365	/// Destroy RFT collection366	///367	/// `destroy_collection` will throw error if collection contains any tokens.368	/// Only owner can destroy collection.369	pub fn destroy_collection(370		collection: RefungibleHandle<T>,371		sender: &T::CrossAccountId,372	) -> DispatchResult {373		let id = collection.id;374375		if Self::collection_has_tokens(id) {376			return Err(<CommonError<T>>::CantDestroyNotEmptyCollection.into());377		}378379		// =========380381		PalletCommon::destroy_collection(collection.0, sender)?;382383		<TokensMinted<T>>::remove(id);384		<TokensBurnt<T>>::remove(id);385		<TokenData<T>>::remove_prefix((id,), None);386		<TotalSupply<T>>::remove_prefix((id,), None);387		<Balance<T>>::remove_prefix((id,), None);388		<Allowance<T>>::remove_prefix((id,), None);389		<Owned<T>>::remove_prefix((id,), None);390		<AccountBalance<T>>::remove_prefix((id,), None);391		Ok(())392	}393394	fn collection_has_tokens(collection_id: CollectionId) -> bool {395		<TokenData<T>>::iter_prefix((collection_id,))396			.next()397			.is_some()398	}399400	pub fn burn_token_unchecked(401		collection: &RefungibleHandle<T>,402		token_id: TokenId,403	) -> DispatchResult {404		let burnt = <TokensBurnt<T>>::get(collection.id)405			.checked_add(1)406			.ok_or(ArithmeticError::Overflow)?;407408		<TokensBurnt<T>>::insert(collection.id, burnt);409		<TokenData<T>>::remove((collection.id, token_id));410		<TokenProperties<T>>::remove((collection.id, token_id));411		<TotalSupply<T>>::remove((collection.id, token_id));412		<Balance<T>>::remove_prefix((collection.id, token_id), None);413		<Allowance<T>>::remove_prefix((collection.id, token_id), None);414		// TODO: ERC721 transfer event415		Ok(())416	}417418	/// Burn RFT token pieces419	///420	/// `burn` will decrease total amount of token pieces and amount owned by sender.421	/// `burn` can be called even if there are multiple owners of the RFT token.422	/// If sender wouldn't have any pieces left after `burn` than she will stop being423	/// one of the owners of the token. If there is no account that owns any pieces of424	/// the token than token will be burned too.425	///426	/// - `amount`: Amount of token pieces to burn.427	/// - `token`: Token who's pieces should be burned428	/// - `collection`: Collection that contains the token429	pub fn burn(430		collection: &RefungibleHandle<T>,431		owner: &T::CrossAccountId,432		token: TokenId,433		amount: u128,434	) -> DispatchResult {435		let total_supply = <TotalSupply<T>>::get((collection.id, token))436			.checked_sub(amount)437			.ok_or(<CommonError<T>>::TokenValueTooLow)?;438439		// This was probally last owner of this token?440		if total_supply == 0 {441			// Ensure user actually owns this amount442			ensure!(443				<Balance<T>>::get((collection.id, token, owner)) == amount,444				<CommonError<T>>::TokenValueTooLow445			);446			let account_balance = <AccountBalance<T>>::get((collection.id, owner))447				.checked_sub(1)448				// Should not occur449				.ok_or(ArithmeticError::Underflow)?;450451			// =========452453			<Owned<T>>::remove((collection.id, owner, token));454			<PalletStructure<T>>::unnest_if_nested(owner, collection.id, token);455			<AccountBalance<T>>::insert((collection.id, owner), account_balance);456			Self::burn_token_unchecked(collection, token)?;457			<PalletEvm<T>>::deposit_log(458				ERC721Events::Transfer {459					from: *owner.as_eth(),460					to: H160::default(),461					token_id: token.into(),462				}463				.to_log(collection_id_to_address(collection.id)),464			);465			<PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(466				collection.id,467				token,468				owner.clone(),469				amount,470			));471			return Ok(());472		}473474		let balance = <Balance<T>>::get((collection.id, token, owner))475			.checked_sub(amount)476			.ok_or(<CommonError<T>>::TokenValueTooLow)?;477		let account_balance = if balance == 0 {478			<AccountBalance<T>>::get((collection.id, owner))479				.checked_sub(1)480				// Should not occur481				.ok_or(ArithmeticError::Underflow)?482		} else {483			0484		};485486		// =========487488		if balance == 0 {489			<Owned<T>>::remove((collection.id, owner, token));490			<PalletStructure<T>>::unnest_if_nested(owner, collection.id, token);491			<Balance<T>>::remove((collection.id, token, owner));492			<AccountBalance<T>>::insert((collection.id, owner), account_balance);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	#[transactional]519	fn modify_token_properties(520		collection: &RefungibleHandle<T>,521		sender: &T::CrossAccountId,522		token_id: TokenId,523		properties: impl Iterator<Item = (PropertyKey, Option<PropertyValue>)>,524		is_token_create: bool,525		nesting_budget: &dyn Budget,526	) -> DispatchResult {527		let is_collection_admin = || collection.is_owner_or_admin(sender);528		let is_token_owner = || -> Result<bool, DispatchError> {529			let balance = collection.balance(sender.clone(), token_id);530			let total_pieces: u128 =531				Self::total_pieces(collection.id, token_id).unwrap_or(u128::MAX);532			if balance != total_pieces {533				return Ok(false);534			}535536			let is_bundle_owner = <PalletStructure<T>>::check_indirectly_owned(537				sender.clone(),538				collection.id,539				token_id,540				None,541				nesting_budget,542			)?;543544			Ok(is_bundle_owner)545		};546547		for (key, value) in properties {548			let permission = <PalletCommon<T>>::property_permissions(collection.id)549				.get(&key)550				.cloned()551				.unwrap_or_else(PropertyPermission::none);552553			let is_property_exists = TokenProperties::<T>::get((collection.id, token_id))554				.get(&key)555				.is_some();556557			match permission {558				PropertyPermission { mutable: false, .. } if is_property_exists => {559					return Err(<CommonError<T>>::NoPermission.into());560				}561562				PropertyPermission {563					collection_admin,564					token_owner,565					..566				} => {567					//TODO: investigate threats during public minting.568					let is_token_create =569						is_token_create && (collection_admin || token_owner) && value.is_some();570					if !(is_token_create571						|| (collection_admin && is_collection_admin())572						|| (token_owner && is_token_owner()?))573					{574						fail!(<CommonError<T>>::NoPermission);575					}576				}577			}578579			match value {580				Some(value) => {581					<TokenProperties<T>>::try_mutate((collection.id, token_id), |properties| {582						properties.try_set(key.clone(), value)583					})584					.map_err(<CommonError<T>>::from)?;585586					<PalletCommon<T>>::deposit_event(CommonEvent::TokenPropertySet(587						collection.id,588						token_id,589						key,590					));591				}592				None => {593					<TokenProperties<T>>::try_mutate((collection.id, token_id), |properties| {594						properties.remove(&key)595					})596					.map_err(<CommonError<T>>::from)?;597598					<PalletCommon<T>>::deposit_event(CommonEvent::TokenPropertyDeleted(599						collection.id,600						token_id,601						key,602					));603				}604			}605		}606607		Ok(())608	}609610	pub fn set_token_properties(611		collection: &RefungibleHandle<T>,612		sender: &T::CrossAccountId,613		token_id: TokenId,614		properties: impl Iterator<Item = Property>,615		is_token_create: bool,616		nesting_budget: &dyn Budget,617	) -> DispatchResult {618		Self::modify_token_properties(619			collection,620			sender,621			token_id,622			properties.map(|p| (p.key, Some(p.value))),623			is_token_create,624			nesting_budget,625		)626	}627628	pub fn set_token_property(629		collection: &RefungibleHandle<T>,630		sender: &T::CrossAccountId,631		token_id: TokenId,632		property: Property,633		nesting_budget: &dyn Budget,634	) -> DispatchResult {635		let is_token_create = false;636637		Self::set_token_properties(638			collection,639			sender,640			token_id,641			[property].into_iter(),642			is_token_create,643			nesting_budget,644		)645	}646647	pub fn delete_token_properties(648		collection: &RefungibleHandle<T>,649		sender: &T::CrossAccountId,650		token_id: TokenId,651		property_keys: impl Iterator<Item = PropertyKey>,652		nesting_budget: &dyn Budget,653	) -> DispatchResult {654		let is_token_create = false;655656		Self::modify_token_properties(657			collection,658			sender,659			token_id,660			property_keys.into_iter().map(|key| (key, None)),661			is_token_create,662			nesting_budget,663		)664	}665666	pub fn delete_token_property(667		collection: &RefungibleHandle<T>,668		sender: &T::CrossAccountId,669		token_id: TokenId,670		property_key: PropertyKey,671		nesting_budget: &dyn Budget,672	) -> DispatchResult {673		Self::delete_token_properties(674			collection,675			sender,676			token_id,677			[property_key].into_iter(),678			nesting_budget,679		)680	}681682	/// Transfer RFT token pieces from one account to another.683	///684	/// If the sender is no longer owns any pieces after the `transfer` than she stops being an owner of the token.685	///686	/// - `from`: Owner of token pieces to transfer.687	/// - `to`: Recepient of transfered token pieces.688	/// - `amount`: Amount of token pieces to transfer.689	/// - `token`: Token whos pieces should be transfered690	/// - `collection`: Collection that contains the token691	pub fn transfer(692		collection: &RefungibleHandle<T>,693		from: &T::CrossAccountId,694		to: &T::CrossAccountId,695		token: TokenId,696		amount: u128,697		nesting_budget: &dyn Budget,698	) -> DispatchResult {699		ensure!(700			collection.limits.transfers_enabled(),701			<CommonError<T>>::TransferNotAllowed702		);703704		if collection.permissions.access() == AccessMode::AllowList {705			collection.check_allowlist(from)?;706			collection.check_allowlist(to)?;707		}708		<PalletCommon<T>>::ensure_correct_receiver(to)?;709710		let balance_from = <Balance<T>>::get((collection.id, token, from))711			.checked_sub(amount)712			.ok_or(<CommonError<T>>::TokenValueTooLow)?;713		let mut create_target = false;714		let from_to_differ = from != to;715		let balance_to = if from != to {716			let old_balance = <Balance<T>>::get((collection.id, token, to));717			if old_balance == 0 {718				create_target = true;719			}720			Some(721				old_balance722					.checked_add(amount)723					.ok_or(ArithmeticError::Overflow)?,724			)725		} else {726			None727		};728729		let account_balance_from = if balance_from == 0 {730			Some(731				<AccountBalance<T>>::get((collection.id, from))732					.checked_sub(1)733					// Should not occur734					.ok_or(ArithmeticError::Underflow)?,735			)736		} else {737			None738		};739		// Account data is created in token, AccountBalance should be increased740		// But only if from != to as we shouldn't check overflow in this case741		let account_balance_to = if create_target && from_to_differ {742			let account_balance_to = <AccountBalance<T>>::get((collection.id, to))743				.checked_add(1)744				.ok_or(ArithmeticError::Overflow)?;745			ensure!(746				account_balance_to < collection.limits.account_token_ownership_limit(),747				<CommonError<T>>::AccountTokenLimitExceeded,748			);749750			Some(account_balance_to)751		} else {752			None753		};754755		// =========756757		<PalletStructure<T>>::nest_if_sent_to_token(758			from.clone(),759			to,760			collection.id,761			token,762			nesting_budget,763		)?;764765		if let Some(balance_to) = balance_to {766			// from != to767			if balance_from == 0 {768				<Balance<T>>::remove((collection.id, token, from));769				<PalletStructure<T>>::unnest_if_nested(from, collection.id, token);770			} else {771				<Balance<T>>::insert((collection.id, token, from), balance_from);772			}773			<Balance<T>>::insert((collection.id, token, to), balance_to);774			if let Some(account_balance_from) = account_balance_from {775				<AccountBalance<T>>::insert((collection.id, from), account_balance_from);776				<Owned<T>>::remove((collection.id, from, token));777			}778			if let Some(account_balance_to) = account_balance_to {779				<AccountBalance<T>>::insert((collection.id, to), account_balance_to);780				<Owned<T>>::insert((collection.id, to, token), true);781			}782		}783784		<PalletEvm<T>>::deposit_log(785			ERC20Events::Transfer {786				from: *from.as_eth(),787				to: *to.as_eth(),788				value: amount.into(),789			}790			.to_log(T::EvmTokenAddressMapping::token_to_address(791				collection.id,792				token,793			)),794		);795796		<PalletCommon<T>>::deposit_event(CommonEvent::Transfer(797			collection.id,798			token,799			from.clone(),800			to.clone(),801			amount,802		));803		Ok(())804	}805806	/// Batched operation to create multiple RFT tokens.807	///808	/// Same as `create_item` but creates multiple tokens.809	///810	/// - `data`: Same as 'data` in `create_item` but contains data for multiple tokens.811	pub fn create_multiple_items(812		collection: &RefungibleHandle<T>,813		sender: &T::CrossAccountId,814		data: Vec<CreateItemData<T>>,815		nesting_budget: &dyn Budget,816	) -> DispatchResult {817		if !collection.is_owner_or_admin(sender) {818			ensure!(819				collection.permissions.mint_mode(),820				<CommonError<T>>::PublicMintingNotAllowed821			);822			collection.check_allowlist(sender)?;823824			for item in data.iter() {825				for user in item.users.keys() {826					collection.check_allowlist(user)?;827				}828			}829		}830831		for item in data.iter() {832			for (owner, _) in item.users.iter() {833				<PalletCommon<T>>::ensure_correct_receiver(owner)?;834			}835		}836837		// Total pieces per tokens838		let totals = data839			.iter()840			.map(|data| {841				Ok(data842					.users843					.iter()844					.map(|u| u.1)845					.try_fold(0u128, |acc, v| acc.checked_add(*v))846					.ok_or(ArithmeticError::Overflow)?)847			})848			.collect::<Result<Vec<_>, DispatchError>>()?;849		for total in &totals {850			ensure!(851				*total <= MAX_REFUNGIBLE_PIECES,852				<Error<T>>::WrongRefungiblePieces853			);854		}855856		let first_token_id = <TokensMinted<T>>::get(collection.id);857		let tokens_minted = first_token_id858			.checked_add(data.len() as u32)859			.ok_or(ArithmeticError::Overflow)?;860		ensure!(861			tokens_minted < collection.limits.token_limit(),862			<CommonError<T>>::CollectionTokenLimitExceeded863		);864865		let mut balances = BTreeMap::new();866		for data in &data {867			for owner in data.users.keys() {868				let balance = balances869					.entry(owner)870					.or_insert_with(|| <AccountBalance<T>>::get((collection.id, owner)));871				*balance = balance.checked_add(1).ok_or(ArithmeticError::Overflow)?;872873				ensure!(874					*balance <= collection.limits.account_token_ownership_limit(),875					<CommonError<T>>::AccountTokenLimitExceeded,876				);877			}878		}879880		for (i, token) in data.iter().enumerate() {881			let token_id = TokenId(first_token_id + i as u32 + 1);882			for (to, _) in token.users.iter() {883				<PalletStructure<T>>::check_nesting(884					sender.clone(),885					to,886					collection.id,887					token_id,888					nesting_budget,889				)?;890			}891		}892893		// =========894895		with_transaction(|| {896			for (i, data) in data.iter().enumerate() {897				let token_id = first_token_id + i as u32 + 1;898				<TotalSupply<T>>::insert((collection.id, token_id), totals[i]);899900				<TokenData<T>>::insert(901					(collection.id, token_id),902					ItemData {903						const_data: data.const_data.clone(),904					},905				);906907				for (user, amount) in data.users.iter() {908					if *amount == 0 {909						continue;910					}911					<Balance<T>>::insert((collection.id, token_id, &user), amount);912					<Owned<T>>::insert((collection.id, &user, TokenId(token_id)), true);913					<PalletStructure<T>>::nest_if_sent_to_token_unchecked(914						user,915						collection.id,916						TokenId(token_id),917					);918				}919920				if let Err(e) = Self::set_token_properties(921					collection,922					sender,923					TokenId(token_id),924					data.properties.clone().into_iter(),925					true,926					nesting_budget,927				) {928					return TransactionOutcome::Rollback(Err(e));929				}930			}931			TransactionOutcome::Commit(Ok(()))932		})?;933934		<TokensMinted<T>>::insert(collection.id, tokens_minted);935936		for (account, balance) in balances {937			<AccountBalance<T>>::insert((collection.id, account), balance);938		}939940		for (i, token) in data.into_iter().enumerate() {941			let token_id = first_token_id + i as u32 + 1;942943			for (user, amount) in token.users.into_iter() {944				if amount == 0 {945					continue;946				}947948				<PalletEvm<T>>::deposit_log(949					ERC20Events::Transfer {950						from: H160::default(),951						to: *user.as_eth(),952						value: amount.into(),953					}954					.to_log(T::EvmTokenAddressMapping::token_to_address(955						collection.id,956						TokenId(token_id),957					)),958				);959				<PalletEvm<T>>::deposit_log(960					ERC721Events::Transfer {961						from: H160::default(),962						to: *user.as_eth(),963						token_id: token_id.into(),964					}965					.to_log(collection_id_to_address(collection.id)),966				);967				<PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(968					collection.id,969					TokenId(token_id),970					user,971					amount,972				));973			}974		}975		Ok(())976	}977978	pub fn set_allowance_unchecked(979		collection: &RefungibleHandle<T>,980		sender: &T::CrossAccountId,981		spender: &T::CrossAccountId,982		token: TokenId,983		amount: u128,984	) {985		if amount == 0 {986			<Allowance<T>>::remove((collection.id, token, sender, spender));987		} else {988			<Allowance<T>>::insert((collection.id, token, sender, spender), amount);989		}990991		<PalletEvm<T>>::deposit_log(992			ERC20Events::Approval {993				owner: *sender.as_eth(),994				spender: *spender.as_eth(),995				value: amount.into(),996			}997			.to_log(T::EvmTokenAddressMapping::token_to_address(998				collection.id,999				token,1000			)),1001		);1002		<PalletCommon<T>>::deposit_event(CommonEvent::Approved(1003			collection.id,1004			token,1005			sender.clone(),1006			spender.clone(),1007			amount,1008		))1009	}10101011	/// Set allowance for the spender to `transfer` or `burn` sender's token pieces.1012	///1013	/// - `amount`: Amount of token pieces the spender is allowed to `transfer` or `burn.1014	pub fn set_allowance(1015		collection: &RefungibleHandle<T>,1016		sender: &T::CrossAccountId,1017		spender: &T::CrossAccountId,1018		token: TokenId,1019		amount: u128,1020	) -> DispatchResult {1021		if collection.permissions.access() == AccessMode::AllowList {1022			collection.check_allowlist(sender)?;1023			collection.check_allowlist(spender)?;1024		}10251026		<PalletCommon<T>>::ensure_correct_receiver(spender)?;10271028		if <Balance<T>>::get((collection.id, token, sender)) < amount {1029			ensure!(1030				collection.ignores_owned_amount(sender) && Self::token_exists(collection, token),1031				<CommonError<T>>::CantApproveMoreThanOwned1032			);1033		}10341035		// =========10361037		Self::set_allowance_unchecked(collection, sender, spender, token, amount);1038		Ok(())1039	}10401041	/// Returns allowance, which should be set after transaction1042	fn check_allowed(1043		collection: &RefungibleHandle<T>,1044		spender: &T::CrossAccountId,1045		from: &T::CrossAccountId,1046		token: TokenId,1047		amount: u128,1048		nesting_budget: &dyn Budget,1049	) -> Result<Option<u128>, DispatchError> {1050		if spender.conv_eq(from) {1051			return Ok(None);1052		}1053		if collection.permissions.access() == AccessMode::AllowList {1054			// `from`, `to` checked in [`transfer`]1055			collection.check_allowlist(spender)?;1056		}1057		if let Some(source) = T::CrossTokenAddressMapping::address_to_token(from) {1058			// TODO: should collection owner be allowed to perform this transfer?1059			ensure!(1060				<PalletStructure<T>>::check_indirectly_owned(1061					spender.clone(),1062					source.0,1063					source.1,1064					None,1065					nesting_budget1066				)?,1067				<CommonError<T>>::ApprovedValueTooLow,1068			);1069			return Ok(None);1070		}1071		let allowance =1072			<Allowance<T>>::get((collection.id, token, from, &spender)).checked_sub(amount);1073		if allowance.is_none() {1074			ensure!(1075				collection.ignores_allowance(spender),1076				<CommonError<T>>::ApprovedValueTooLow1077			);1078		}1079		Ok(allowance)1080	}10811082	/// Transfer RFT token pieces from one account to another.1083	///1084	/// Same as the [`transfer`] but spender doesn't needs to be an owner of the token pieces.1085	/// The owner should set allowance for the spender to transfer pieces.1086	///1087	/// [`transfer`]: struct.Pallet.html#method.transfer1088	pub fn transfer_from(1089		collection: &RefungibleHandle<T>,1090		spender: &T::CrossAccountId,1091		from: &T::CrossAccountId,1092		to: &T::CrossAccountId,1093		token: TokenId,1094		amount: u128,1095		nesting_budget: &dyn Budget,1096	) -> DispatchResult {1097		let allowance =1098			Self::check_allowed(collection, spender, from, token, amount, nesting_budget)?;10991100		// =========11011102		Self::transfer(collection, from, to, token, amount, nesting_budget)?;1103		if let Some(allowance) = allowance {1104			Self::set_allowance_unchecked(collection, from, spender, token, allowance);1105		}1106		Ok(())1107	}11081109	/// Burn RFT token pieces from the account.1110	///1111	/// Same as the [`burn`] but spender doesn't need to be an owner of the token pieces. The owner should1112	/// set allowance for the spender to burn pieces1113	///1114	/// [`burn`]: struct.Pallet.html#method.burn1115	pub fn burn_from(1116		collection: &RefungibleHandle<T>,1117		spender: &T::CrossAccountId,1118		from: &T::CrossAccountId,1119		token: TokenId,1120		amount: u128,1121		nesting_budget: &dyn Budget,1122	) -> DispatchResult {1123		let allowance =1124			Self::check_allowed(collection, spender, from, token, amount, nesting_budget)?;11251126		// =========11271128		Self::burn(collection, from, token, amount)?;1129		if let Some(allowance) = allowance {1130			Self::set_allowance_unchecked(collection, from, spender, token, allowance);1131		}1132		Ok(())1133	}11341135	/// Create RFT token.1136	///1137	/// The sender should be the owner/admin of the collection or collection should be configured1138	/// to allow public minting.1139	///1140	/// - `data`: Contains list of users who will become the owners of the token pieces and amount1141	///   of token pieces they will receive.1142	pub fn create_item(1143		collection: &RefungibleHandle<T>,1144		sender: &T::CrossAccountId,1145		data: CreateItemData<T>,1146		nesting_budget: &dyn Budget,1147	) -> DispatchResult {1148		Self::create_multiple_items(collection, sender, vec![data], nesting_budget)1149	}11501151	/// Repartition RFT token.1152	///1153	/// `repartition` will set token balance of the sender and total amount of token pieces.1154	/// Sender should own all of the token pieces. `repartition' could be done even if some1155	/// token pieces were burned before.1156	///1157	/// - `amount`: Total amount of token pieces that the token will have after `repartition`.1158	pub fn repartition(1159		collection: &RefungibleHandle<T>,1160		owner: &T::CrossAccountId,1161		token: TokenId,1162		amount: u128,1163	) -> DispatchResult {1164		ensure!(1165			amount <= MAX_REFUNGIBLE_PIECES,1166			<Error<T>>::WrongRefungiblePieces1167		);1168		ensure!(amount > 0, <CommonError<T>>::TokenValueTooLow);1169		// Ensure user owns all pieces1170		let total_pieces = Self::total_pieces(collection.id, token).unwrap_or(u128::MAX);1171		let balance = <Balance<T>>::get((collection.id, token, owner));1172		ensure!(1173			total_pieces == balance,1174			<Error<T>>::RepartitionWhileNotOwningAllPieces1175		);11761177		<Balance<T>>::insert((collection.id, token, owner), amount);1178		<TotalSupply<T>>::insert((collection.id, token), amount);11791180		if amount > total_pieces {1181			let mint_amount = amount - total_pieces;1182			<PalletEvm<T>>::deposit_log(1183				ERC20Events::Transfer {1184					from: H160::default(),1185					to: *owner.as_eth(),1186					value: mint_amount.into(),1187				}1188				.to_log(T::EvmTokenAddressMapping::token_to_address(1189					collection.id,1190					token,1191				)),1192			);1193			<PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(1194				collection.id,1195				token,1196				owner.clone(),1197				mint_amount,1198			));1199		} else if total_pieces > amount {1200			let burn_amount = total_pieces - amount;1201			<PalletEvm<T>>::deposit_log(1202				ERC20Events::Transfer {1203					from: *owner.as_eth(),1204					to: H160::default(),1205					value: burn_amount.into(),1206				}1207				.to_log(T::EvmTokenAddressMapping::token_to_address(1208					collection.id,1209					token,1210				)),1211			);1212			<PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(1213				collection.id,1214				token,1215				owner.clone(),1216				burn_amount,1217			));1218		}12191220		Ok(())1221	}12221223	fn token_owner(collection_id: CollectionId, token_id: TokenId) -> Option<T::CrossAccountId> {1224		let mut owner = None;1225		let mut count = 0;1226		for key in Balance::<T>::iter_key_prefix((collection_id, token_id)) {1227			count += 1;1228			if count > 1 {1229				return None;1230			}1231			owner = Some(key);1232		}1233		owner1234	}12351236	fn total_pieces(collection_id: CollectionId, token_id: TokenId) -> Option<u128> {1237		<TotalSupply<T>>::try_get((collection_id, token_id)).ok()1238	}12391240	pub fn set_collection_properties(1241		collection: &RefungibleHandle<T>,1242		sender: &T::CrossAccountId,1243		properties: Vec<Property>,1244	) -> DispatchResult {1245		<PalletCommon<T>>::set_collection_properties(collection, sender, properties)1246	}12471248	pub fn delete_collection_properties(1249		collection: &RefungibleHandle<T>,1250		sender: &T::CrossAccountId,1251		property_keys: Vec<PropertyKey>,1252	) -> DispatchResult {1253		<PalletCommon<T>>::delete_collection_properties(collection, sender, property_keys)1254	}12551256	pub fn set_token_property_permissions(1257		collection: &RefungibleHandle<T>,1258		sender: &T::CrossAccountId,1259		property_permissions: Vec<PropertyKeyPermission>,1260	) -> DispatchResult {1261		<PalletCommon<T>>::set_token_property_permissions(collection, sender, property_permissions)1262	}12631264	/// Returns 10 token in no particular order.1265	///1266	/// There is no direct way to get token holders in ascending order,1267	/// since `iter_prefix` returns values in no particular order.1268	/// Therefore, getting the 10 largest holders with a large value of holders1269	/// can lead to impact memory allocation + sorting with  `n * log (n)`.1270	pub fn token_owners(1271		collection_id: CollectionId,1272		token: TokenId,1273	) -> Option<Vec<T::CrossAccountId>> {1274		let res: Vec<T::CrossAccountId> = <Balance<T>>::iter_prefix((collection_id, token))1275			.map(|(owner, _amount)| owner)1276			.take(10)1277			.collect();12781279		if res.is_empty() {1280			None1281		} else {1282			Some(res)1283		}1284	}1285}