git.delta.rocks / unique-network / refs/commits / 9d3564ef2b56

difftreelog

source

pallets/refungible/src/lib.rs38.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;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		owner: &T::CrossAccountId,403		token_id: TokenId,404	) -> DispatchResult {405		let burnt = <TokensBurnt<T>>::get(collection.id)406			.checked_add(1)407			.ok_or(ArithmeticError::Overflow)?;408409		<TokensBurnt<T>>::insert(collection.id, burnt);410		<TokenData<T>>::remove((collection.id, token_id));411		<TokenProperties<T>>::remove((collection.id, token_id));412		<TotalSupply<T>>::remove((collection.id, token_id));413		<Balance<T>>::remove_prefix((collection.id, token_id), None);414		<Allowance<T>>::remove_prefix((collection.id, token_id), None);415416		<PalletEvm<T>>::deposit_log(417			ERC721Events::Transfer {418				from: *owner.as_eth(),419				to: H160::default(),420				token_id: token_id.into(),421			}422			.to_log(collection_id_to_address(collection.id)),423		);424		Ok(())425	}426427	/// Burn RFT token pieces428	///429	/// `burn` will decrease total amount of token pieces and amount owned by sender.430	/// `burn` can be called even if there are multiple owners of the RFT token.431	/// If sender wouldn't have any pieces left after `burn` than she will stop being432	/// one of the owners of the token. If there is no account that owns any pieces of433	/// the token than token will be burned too.434	///435	/// - `amount`: Amount of token pieces to burn.436	/// - `token`: Token who's pieces should be burned437	/// - `collection`: Collection that contains the token438	pub fn burn(439		collection: &RefungibleHandle<T>,440		owner: &T::CrossAccountId,441		token: TokenId,442		amount: u128,443	) -> DispatchResult {444		let total_supply = <TotalSupply<T>>::get((collection.id, token))445			.checked_sub(amount)446			.ok_or(<CommonError<T>>::TokenValueTooLow)?;447448		// This was probally last owner of this token?449		if total_supply == 0 {450			// Ensure user actually owns this amount451			ensure!(452				<Balance<T>>::get((collection.id, token, owner)) == amount,453				<CommonError<T>>::TokenValueTooLow454			);455			let account_balance = <AccountBalance<T>>::get((collection.id, owner))456				.checked_sub(1)457				// Should not occur458				.ok_or(ArithmeticError::Underflow)?;459460			// =========461462			<Owned<T>>::remove((collection.id, owner, token));463			<PalletStructure<T>>::unnest_if_nested(owner, collection.id, token);464			<AccountBalance<T>>::insert((collection.id, owner), account_balance);465			Self::burn_token_unchecked(collection, owner, token)?;466			<PalletEvm<T>>::deposit_log(467				ERC20Events::Transfer {468					from: *owner.as_eth(),469					to: H160::default(),470					value: amount.into(),471				}472				.to_log(collection_id_to_address(collection.id)),473			);474			<PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(475				collection.id,476				token,477				owner.clone(),478				amount,479			));480			return Ok(());481		}482483		let balance = <Balance<T>>::get((collection.id, token, owner))484			.checked_sub(amount)485			.ok_or(<CommonError<T>>::TokenValueTooLow)?;486		let account_balance = if balance == 0 {487			<AccountBalance<T>>::get((collection.id, owner))488				.checked_sub(1)489				// Should not occur490				.ok_or(ArithmeticError::Underflow)?491		} else {492			0493		};494495		// =========496497		if balance == 0 {498			<Owned<T>>::remove((collection.id, owner, token));499			<PalletStructure<T>>::unnest_if_nested(owner, collection.id, token);500			<Balance<T>>::remove((collection.id, token, owner));501			<AccountBalance<T>>::insert((collection.id, owner), account_balance);502503			if let Some(user) = Self::token_owner(collection.id, token) {504				<PalletEvm<T>>::deposit_log(505					ERC721Events::Transfer {506						from: erc::ADDRESS_FOR_PARTIALLY_OWNED_TOKENS,507						to: *user.as_eth(),508						token_id: token.into(),509					}510					.to_log(collection_id_to_address(collection.id)),511				);512			}513		} else {514			<Balance<T>>::insert((collection.id, token, owner), balance);515		}516		<TotalSupply<T>>::insert((collection.id, token), total_supply);517518		<PalletEvm<T>>::deposit_log(519			ERC20Events::Transfer {520				from: *owner.as_eth(),521				to: H160::default(),522				value: amount.into(),523			}524			.to_log(T::EvmTokenAddressMapping::token_to_address(525				collection.id,526				token,527			)),528		);529		<PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(530			collection.id,531			token,532			owner.clone(),533			amount,534		));535		Ok(())536	}537538	#[transactional]539	fn modify_token_properties(540		collection: &RefungibleHandle<T>,541		sender: &T::CrossAccountId,542		token_id: TokenId,543		properties: impl Iterator<Item = (PropertyKey, Option<PropertyValue>)>,544		is_token_create: bool,545		nesting_budget: &dyn Budget,546	) -> DispatchResult {547		let is_collection_admin = || collection.is_owner_or_admin(sender);548		let is_token_owner = || -> Result<bool, DispatchError> {549			let balance = collection.balance(sender.clone(), token_id);550			let total_pieces: u128 =551				Self::total_pieces(collection.id, token_id).unwrap_or(u128::MAX);552			if balance != total_pieces {553				return Ok(false);554			}555556			let is_bundle_owner = <PalletStructure<T>>::check_indirectly_owned(557				sender.clone(),558				collection.id,559				token_id,560				None,561				nesting_budget,562			)?;563564			Ok(is_bundle_owner)565		};566567		for (key, value) in properties {568			let permission = <PalletCommon<T>>::property_permissions(collection.id)569				.get(&key)570				.cloned()571				.unwrap_or_else(PropertyPermission::none);572573			let is_property_exists = TokenProperties::<T>::get((collection.id, token_id))574				.get(&key)575				.is_some();576577			match permission {578				PropertyPermission { mutable: false, .. } if is_property_exists => {579					return Err(<CommonError<T>>::NoPermission.into());580				}581582				PropertyPermission {583					collection_admin,584					token_owner,585					..586				} => {587					//TODO: investigate threats during public minting.588					let is_token_create =589						is_token_create && (collection_admin || token_owner) && value.is_some();590					if !(is_token_create591						|| (collection_admin && is_collection_admin())592						|| (token_owner && is_token_owner()?))593					{594						fail!(<CommonError<T>>::NoPermission);595					}596				}597			}598599			match value {600				Some(value) => {601					<TokenProperties<T>>::try_mutate((collection.id, token_id), |properties| {602						properties.try_set(key.clone(), value)603					})604					.map_err(<CommonError<T>>::from)?;605606					<PalletCommon<T>>::deposit_event(CommonEvent::TokenPropertySet(607						collection.id,608						token_id,609						key,610					));611				}612				None => {613					<TokenProperties<T>>::try_mutate((collection.id, token_id), |properties| {614						properties.remove(&key)615					})616					.map_err(<CommonError<T>>::from)?;617618					<PalletCommon<T>>::deposit_event(CommonEvent::TokenPropertyDeleted(619						collection.id,620						token_id,621						key,622					));623				}624			}625		}626627		Ok(())628	}629630	pub fn set_token_properties(631		collection: &RefungibleHandle<T>,632		sender: &T::CrossAccountId,633		token_id: TokenId,634		properties: impl Iterator<Item = Property>,635		is_token_create: bool,636		nesting_budget: &dyn Budget,637	) -> DispatchResult {638		Self::modify_token_properties(639			collection,640			sender,641			token_id,642			properties.map(|p| (p.key, Some(p.value))),643			is_token_create,644			nesting_budget,645		)646	}647648	pub fn set_token_property(649		collection: &RefungibleHandle<T>,650		sender: &T::CrossAccountId,651		token_id: TokenId,652		property: Property,653		nesting_budget: &dyn Budget,654	) -> DispatchResult {655		let is_token_create = false;656657		Self::set_token_properties(658			collection,659			sender,660			token_id,661			[property].into_iter(),662			is_token_create,663			nesting_budget,664		)665	}666667	pub fn delete_token_properties(668		collection: &RefungibleHandle<T>,669		sender: &T::CrossAccountId,670		token_id: TokenId,671		property_keys: impl Iterator<Item = PropertyKey>,672		nesting_budget: &dyn Budget,673	) -> DispatchResult {674		let is_token_create = false;675676		Self::modify_token_properties(677			collection,678			sender,679			token_id,680			property_keys.into_iter().map(|key| (key, None)),681			is_token_create,682			nesting_budget,683		)684	}685686	pub fn delete_token_property(687		collection: &RefungibleHandle<T>,688		sender: &T::CrossAccountId,689		token_id: TokenId,690		property_key: PropertyKey,691		nesting_budget: &dyn Budget,692	) -> DispatchResult {693		Self::delete_token_properties(694			collection,695			sender,696			token_id,697			[property_key].into_iter(),698			nesting_budget,699		)700	}701702	/// Transfer RFT token pieces from one account to another.703	///704	/// If the sender is no longer owns any pieces after the `transfer` than she stops being an owner of the token.705	///706	/// - `from`: Owner of token pieces to transfer.707	/// - `to`: Recepient of transfered token pieces.708	/// - `amount`: Amount of token pieces to transfer.709	/// - `token`: Token whos pieces should be transfered710	/// - `collection`: Collection that contains the token711	pub fn transfer(712		collection: &RefungibleHandle<T>,713		from: &T::CrossAccountId,714		to: &T::CrossAccountId,715		token: TokenId,716		amount: u128,717		nesting_budget: &dyn Budget,718	) -> DispatchResult {719		ensure!(720			collection.limits.transfers_enabled(),721			<CommonError<T>>::TransferNotAllowed722		);723724		if collection.permissions.access() == AccessMode::AllowList {725			collection.check_allowlist(from)?;726			collection.check_allowlist(to)?;727		}728		<PalletCommon<T>>::ensure_correct_receiver(to)?;729730		let initial_balance_from = <Balance<T>>::get((collection.id, token, from));731		let updated_balance_from = initial_balance_from732			.checked_sub(amount)733			.ok_or(<CommonError<T>>::TokenValueTooLow)?;734		let mut create_target = false;735		let from_to_differ = from != to;736		let updated_balance_to = if from != to {737			let old_balance = <Balance<T>>::get((collection.id, token, to));738			if old_balance == 0 {739				create_target = true;740			}741			Some(742				old_balance743					.checked_add(amount)744					.ok_or(ArithmeticError::Overflow)?,745			)746		} else {747			None748		};749750		let account_balance_from = if updated_balance_from == 0 {751			Some(752				<AccountBalance<T>>::get((collection.id, from))753					.checked_sub(1)754					// Should not occur755					.ok_or(ArithmeticError::Underflow)?,756			)757		} else {758			None759		};760		// Account data is created in token, AccountBalance should be increased761		// But only if from != to as we shouldn't check overflow in this case762		let account_balance_to = if create_target && from_to_differ {763			let account_balance_to = <AccountBalance<T>>::get((collection.id, to))764				.checked_add(1)765				.ok_or(ArithmeticError::Overflow)?;766			ensure!(767				account_balance_to < collection.limits.account_token_ownership_limit(),768				<CommonError<T>>::AccountTokenLimitExceeded,769			);770771			Some(account_balance_to)772		} else {773			None774		};775776		// =========777778		<PalletStructure<T>>::nest_if_sent_to_token(779			from.clone(),780			to,781			collection.id,782			token,783			nesting_budget,784		)?;785786		if let Some(updated_balance_to) = updated_balance_to {787			// from != to788			if updated_balance_from == 0 {789				<Balance<T>>::remove((collection.id, token, from));790				<PalletStructure<T>>::unnest_if_nested(from, collection.id, token);791			} else {792				<Balance<T>>::insert((collection.id, token, from), updated_balance_from);793			}794			<Balance<T>>::insert((collection.id, token, to), updated_balance_to);795			if let Some(account_balance_from) = account_balance_from {796				<AccountBalance<T>>::insert((collection.id, from), account_balance_from);797				<Owned<T>>::remove((collection.id, from, token));798			}799			if let Some(account_balance_to) = account_balance_to {800				<AccountBalance<T>>::insert((collection.id, to), account_balance_to);801				<Owned<T>>::insert((collection.id, to, token), true);802			}803		}804805		<PalletEvm<T>>::deposit_log(806			ERC20Events::Transfer {807				from: *from.as_eth(),808				to: *to.as_eth(),809				value: amount.into(),810			}811			.to_log(T::EvmTokenAddressMapping::token_to_address(812				collection.id,813				token,814			)),815		);816817		<PalletCommon<T>>::deposit_event(CommonEvent::Transfer(818			collection.id,819			token,820			from.clone(),821			to.clone(),822			amount,823		));824825		let total_supply = <TotalSupply<T>>::get((collection.id, token));826827		if amount == total_supply {828			// if token was fully owned by `from` and will be fully owned by `to` after transfer829			<PalletEvm<T>>::deposit_log(830				ERC721Events::Transfer {831					from: *from.as_eth(),832					to: *to.as_eth(),833					token_id: token.into(),834				}835				.to_log(collection_id_to_address(collection.id)),836			);837		} else if let Some(updated_balance_to) = updated_balance_to {838			// if `from` not equals `to`. This condition is needed to avoid sending event839			// when `from` fully owns token and sends part of token pieces to itself.840			if initial_balance_from == total_supply {841				// if token was fully owned by `from` and will be only partially owned by `to`842				// and `from` after transfer843				<PalletEvm<T>>::deposit_log(844					ERC721Events::Transfer {845						from: *from.as_eth(),846						to: erc::ADDRESS_FOR_PARTIALLY_OWNED_TOKENS,847						token_id: token.into(),848					}849					.to_log(collection_id_to_address(collection.id)),850				);851			} else if updated_balance_to == total_supply {852				// if token was partially owned by `from` and will be fully owned by `to` after transfer853				<PalletEvm<T>>::deposit_log(854					ERC721Events::Transfer {855						from: erc::ADDRESS_FOR_PARTIALLY_OWNED_TOKENS,856						to: *to.as_eth(),857						token_id: token.into(),858					}859					.to_log(collection_id_to_address(collection.id)),860				);861			}862		}863864		Ok(())865	}866867	/// Batched operation to create multiple RFT tokens.868	///869	/// Same as `create_item` but creates multiple tokens.870	///871	/// - `data`: Same as 'data` in `create_item` but contains data for multiple tokens.872	pub fn create_multiple_items(873		collection: &RefungibleHandle<T>,874		sender: &T::CrossAccountId,875		data: Vec<CreateItemData<T>>,876		nesting_budget: &dyn Budget,877	) -> DispatchResult {878		if !collection.is_owner_or_admin(sender) {879			ensure!(880				collection.permissions.mint_mode(),881				<CommonError<T>>::PublicMintingNotAllowed882			);883			collection.check_allowlist(sender)?;884885			for item in data.iter() {886				for user in item.users.keys() {887					collection.check_allowlist(user)?;888				}889			}890		}891892		for item in data.iter() {893			for (owner, _) in item.users.iter() {894				<PalletCommon<T>>::ensure_correct_receiver(owner)?;895			}896		}897898		// Total pieces per tokens899		let totals = data900			.iter()901			.map(|data| {902				Ok(data903					.users904					.iter()905					.map(|u| u.1)906					.try_fold(0u128, |acc, v| acc.checked_add(*v))907					.ok_or(ArithmeticError::Overflow)?)908			})909			.collect::<Result<Vec<_>, DispatchError>>()?;910		for total in &totals {911			ensure!(912				*total <= MAX_REFUNGIBLE_PIECES,913				<Error<T>>::WrongRefungiblePieces914			);915		}916917		let first_token_id = <TokensMinted<T>>::get(collection.id);918		let tokens_minted = first_token_id919			.checked_add(data.len() as u32)920			.ok_or(ArithmeticError::Overflow)?;921		ensure!(922			tokens_minted < collection.limits.token_limit(),923			<CommonError<T>>::CollectionTokenLimitExceeded924		);925926		let mut balances = BTreeMap::new();927		for data in &data {928			for owner in data.users.keys() {929				let balance = balances930					.entry(owner)931					.or_insert_with(|| <AccountBalance<T>>::get((collection.id, owner)));932				*balance = balance.checked_add(1).ok_or(ArithmeticError::Overflow)?;933934				ensure!(935					*balance <= collection.limits.account_token_ownership_limit(),936					<CommonError<T>>::AccountTokenLimitExceeded,937				);938			}939		}940941		for (i, token) in data.iter().enumerate() {942			let token_id = TokenId(first_token_id + i as u32 + 1);943			for (to, _) in token.users.iter() {944				<PalletStructure<T>>::check_nesting(945					sender.clone(),946					to,947					collection.id,948					token_id,949					nesting_budget,950				)?;951			}952		}953954		// =========955956		with_transaction(|| {957			for (i, data) in data.iter().enumerate() {958				let token_id = first_token_id + i as u32 + 1;959				<TotalSupply<T>>::insert((collection.id, token_id), totals[i]);960961				<TokenData<T>>::insert(962					(collection.id, token_id),963					ItemData {964						const_data: data.const_data.clone(),965					},966				);967968				for (user, amount) in data.users.iter() {969					if *amount == 0 {970						continue;971					}972					<Balance<T>>::insert((collection.id, token_id, &user), amount);973					<Owned<T>>::insert((collection.id, &user, TokenId(token_id)), true);974					<PalletStructure<T>>::nest_if_sent_to_token_unchecked(975						user,976						collection.id,977						TokenId(token_id),978					);979				}980981				if let Err(e) = Self::set_token_properties(982					collection,983					sender,984					TokenId(token_id),985					data.properties.clone().into_iter(),986					true,987					nesting_budget,988				) {989					return TransactionOutcome::Rollback(Err(e));990				}991			}992			TransactionOutcome::Commit(Ok(()))993		})?;994995		<TokensMinted<T>>::insert(collection.id, tokens_minted);996997		for (account, balance) in balances {998			<AccountBalance<T>>::insert((collection.id, account), balance);999		}10001001		for (i, token) in data.into_iter().enumerate() {1002			let token_id = first_token_id + i as u32 + 1;10031004			let receivers = token1005				.users1006				.into_iter()1007				.filter(|(_, amount)| *amount > 0)1008				.collect::<Vec<_>>();10091010			if let [(user, _)] = receivers.as_slice() {1011				// if there is exactly one receiver1012				<PalletEvm<T>>::deposit_log(1013					ERC721Events::Transfer {1014						from: H160::default(),1015						to: *user.as_eth(),1016						token_id: token_id.into(),1017					}1018					.to_log(collection_id_to_address(collection.id)),1019				);1020			} else if let [_, ..] = receivers.as_slice() {1021				// if there is more than one receiver1022				<PalletEvm<T>>::deposit_log(1023					ERC721Events::Transfer {1024						from: H160::default(),1025						to: erc::ADDRESS_FOR_PARTIALLY_OWNED_TOKENS,1026						token_id: token_id.into(),1027					}1028					.to_log(collection_id_to_address(collection.id)),1029				);1030			}10311032			for (user, amount) in receivers.into_iter() {1033				<PalletEvm<T>>::deposit_log(1034					ERC20Events::Transfer {1035						from: H160::default(),1036						to: *user.as_eth(),1037						value: amount.into(),1038					}1039					.to_log(T::EvmTokenAddressMapping::token_to_address(1040						collection.id,1041						TokenId(token_id),1042					)),1043				);1044				<PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(1045					collection.id,1046					TokenId(token_id),1047					user,1048					amount,1049				));1050			}1051		}1052		Ok(())1053	}10541055	pub fn set_allowance_unchecked(1056		collection: &RefungibleHandle<T>,1057		sender: &T::CrossAccountId,1058		spender: &T::CrossAccountId,1059		token: TokenId,1060		amount: u128,1061	) {1062		if amount == 0 {1063			<Allowance<T>>::remove((collection.id, token, sender, spender));1064		} else {1065			<Allowance<T>>::insert((collection.id, token, sender, spender), amount);1066		}10671068		<PalletEvm<T>>::deposit_log(1069			ERC20Events::Approval {1070				owner: *sender.as_eth(),1071				spender: *spender.as_eth(),1072				value: amount.into(),1073			}1074			.to_log(T::EvmTokenAddressMapping::token_to_address(1075				collection.id,1076				token,1077			)),1078		);1079		<PalletCommon<T>>::deposit_event(CommonEvent::Approved(1080			collection.id,1081			token,1082			sender.clone(),1083			spender.clone(),1084			amount,1085		))1086	}10871088	/// Set allowance for the spender to `transfer` or `burn` sender's token pieces.1089	///1090	/// - `amount`: Amount of token pieces the spender is allowed to `transfer` or `burn.1091	pub fn set_allowance(1092		collection: &RefungibleHandle<T>,1093		sender: &T::CrossAccountId,1094		spender: &T::CrossAccountId,1095		token: TokenId,1096		amount: u128,1097	) -> DispatchResult {1098		if collection.permissions.access() == AccessMode::AllowList {1099			collection.check_allowlist(sender)?;1100			collection.check_allowlist(spender)?;1101		}11021103		<PalletCommon<T>>::ensure_correct_receiver(spender)?;11041105		if <Balance<T>>::get((collection.id, token, sender)) < amount {1106			ensure!(1107				collection.ignores_owned_amount(sender) && Self::token_exists(collection, token),1108				<CommonError<T>>::CantApproveMoreThanOwned1109			);1110		}11111112		// =========11131114		Self::set_allowance_unchecked(collection, sender, spender, token, amount);1115		Ok(())1116	}11171118	/// Returns allowance, which should be set after transaction1119	fn check_allowed(1120		collection: &RefungibleHandle<T>,1121		spender: &T::CrossAccountId,1122		from: &T::CrossAccountId,1123		token: TokenId,1124		amount: u128,1125		nesting_budget: &dyn Budget,1126	) -> Result<Option<u128>, DispatchError> {1127		if spender.conv_eq(from) {1128			return Ok(None);1129		}1130		if collection.permissions.access() == AccessMode::AllowList {1131			// `from`, `to` checked in [`transfer`]1132			collection.check_allowlist(spender)?;1133		}1134		if let Some(source) = T::CrossTokenAddressMapping::address_to_token(from) {1135			// TODO: should collection owner be allowed to perform this transfer?1136			ensure!(1137				<PalletStructure<T>>::check_indirectly_owned(1138					spender.clone(),1139					source.0,1140					source.1,1141					None,1142					nesting_budget1143				)?,1144				<CommonError<T>>::ApprovedValueTooLow,1145			);1146			return Ok(None);1147		}1148		let allowance =1149			<Allowance<T>>::get((collection.id, token, from, &spender)).checked_sub(amount);1150		if allowance.is_none() {1151			ensure!(1152				collection.ignores_allowance(spender),1153				<CommonError<T>>::ApprovedValueTooLow1154			);1155		}1156		Ok(allowance)1157	}11581159	/// Transfer RFT token pieces from one account to another.1160	///1161	/// Same as the [`transfer`] but spender doesn't needs to be an owner of the token pieces.1162	/// The owner should set allowance for the spender to transfer pieces.1163	///1164	/// [`transfer`]: struct.Pallet.html#method.transfer1165	pub fn transfer_from(1166		collection: &RefungibleHandle<T>,1167		spender: &T::CrossAccountId,1168		from: &T::CrossAccountId,1169		to: &T::CrossAccountId,1170		token: TokenId,1171		amount: u128,1172		nesting_budget: &dyn Budget,1173	) -> DispatchResult {1174		let allowance =1175			Self::check_allowed(collection, spender, from, token, amount, nesting_budget)?;11761177		// =========11781179		Self::transfer(collection, from, to, token, amount, nesting_budget)?;1180		if let Some(allowance) = allowance {1181			Self::set_allowance_unchecked(collection, from, spender, token, allowance);1182		}1183		Ok(())1184	}11851186	/// Burn RFT token pieces from the account.1187	///1188	/// Same as the [`burn`] but spender doesn't need to be an owner of the token pieces. The owner should1189	/// set allowance for the spender to burn pieces1190	///1191	/// [`burn`]: struct.Pallet.html#method.burn1192	pub fn burn_from(1193		collection: &RefungibleHandle<T>,1194		spender: &T::CrossAccountId,1195		from: &T::CrossAccountId,1196		token: TokenId,1197		amount: u128,1198		nesting_budget: &dyn Budget,1199	) -> DispatchResult {1200		let allowance =1201			Self::check_allowed(collection, spender, from, token, amount, nesting_budget)?;12021203		// =========12041205		Self::burn(collection, from, token, amount)?;1206		if let Some(allowance) = allowance {1207			Self::set_allowance_unchecked(collection, from, spender, token, allowance);1208		}1209		Ok(())1210	}12111212	/// Create RFT token.1213	///1214	/// The sender should be the owner/admin of the collection or collection should be configured1215	/// to allow public minting.1216	///1217	/// - `data`: Contains list of users who will become the owners of the token pieces and amount1218	///   of token pieces they will receive.1219	pub fn create_item(1220		collection: &RefungibleHandle<T>,1221		sender: &T::CrossAccountId,1222		data: CreateItemData<T>,1223		nesting_budget: &dyn Budget,1224	) -> DispatchResult {1225		Self::create_multiple_items(collection, sender, vec![data], nesting_budget)1226	}12271228	/// Repartition RFT token.1229	///1230	/// `repartition` will set token balance of the sender and total amount of token pieces.1231	/// Sender should own all of the token pieces. `repartition' could be done even if some1232	/// token pieces were burned before.1233	///1234	/// - `amount`: Total amount of token pieces that the token will have after `repartition`.1235	pub fn repartition(1236		collection: &RefungibleHandle<T>,1237		owner: &T::CrossAccountId,1238		token: TokenId,1239		amount: u128,1240	) -> DispatchResult {1241		ensure!(1242			amount <= MAX_REFUNGIBLE_PIECES,1243			<Error<T>>::WrongRefungiblePieces1244		);1245		ensure!(amount > 0, <CommonError<T>>::TokenValueTooLow);1246		// Ensure user owns all pieces1247		let total_pieces = Self::total_pieces(collection.id, token).unwrap_or(u128::MAX);1248		let balance = <Balance<T>>::get((collection.id, token, owner));1249		ensure!(1250			total_pieces == balance,1251			<Error<T>>::RepartitionWhileNotOwningAllPieces1252		);12531254		<Balance<T>>::insert((collection.id, token, owner), amount);1255		<TotalSupply<T>>::insert((collection.id, token), amount);12561257		if amount > total_pieces {1258			let mint_amount = amount - total_pieces;1259			<PalletEvm<T>>::deposit_log(1260				ERC20Events::Transfer {1261					from: H160::default(),1262					to: *owner.as_eth(),1263					value: mint_amount.into(),1264				}1265				.to_log(T::EvmTokenAddressMapping::token_to_address(1266					collection.id,1267					token,1268				)),1269			);1270			<PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(1271				collection.id,1272				token,1273				owner.clone(),1274				mint_amount,1275			));1276		} else if total_pieces > amount {1277			let burn_amount = total_pieces - amount;1278			<PalletEvm<T>>::deposit_log(1279				ERC20Events::Transfer {1280					from: *owner.as_eth(),1281					to: H160::default(),1282					value: burn_amount.into(),1283				}1284				.to_log(T::EvmTokenAddressMapping::token_to_address(1285					collection.id,1286					token,1287				)),1288			);1289			<PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(1290				collection.id,1291				token,1292				owner.clone(),1293				burn_amount,1294			));1295		}12961297		Ok(())1298	}12991300	fn token_owner(collection_id: CollectionId, token_id: TokenId) -> Option<T::CrossAccountId> {1301		let mut owner = None;1302		let mut count = 0;1303		for key in Balance::<T>::iter_key_prefix((collection_id, token_id)) {1304			count += 1;1305			if count > 1 {1306				return None;1307			}1308			owner = Some(key);1309		}1310		owner1311	}13121313	fn total_pieces(collection_id: CollectionId, token_id: TokenId) -> Option<u128> {1314		<TotalSupply<T>>::try_get((collection_id, token_id)).ok()1315	}13161317	pub fn set_collection_properties(1318		collection: &RefungibleHandle<T>,1319		sender: &T::CrossAccountId,1320		properties: Vec<Property>,1321	) -> DispatchResult {1322		<PalletCommon<T>>::set_collection_properties(collection, sender, properties)1323	}13241325	pub fn delete_collection_properties(1326		collection: &RefungibleHandle<T>,1327		sender: &T::CrossAccountId,1328		property_keys: Vec<PropertyKey>,1329	) -> DispatchResult {1330		<PalletCommon<T>>::delete_collection_properties(collection, sender, property_keys)1331	}13321333	pub fn set_token_property_permissions(1334		collection: &RefungibleHandle<T>,1335		sender: &T::CrossAccountId,1336		property_permissions: Vec<PropertyKeyPermission>,1337	) -> DispatchResult {1338		<PalletCommon<T>>::set_token_property_permissions(collection, sender, property_permissions)1339	}13401341	/// Returns 10 token in no particular order.1342	///1343	/// There is no direct way to get token holders in ascending order,1344	/// since `iter_prefix` returns values in no particular order.1345	/// Therefore, getting the 10 largest holders with a large value of holders1346	/// can lead to impact memory allocation + sorting with  `n * log (n)`.1347	pub fn token_owners(1348		collection_id: CollectionId,1349		token: TokenId,1350	) -> Option<Vec<T::CrossAccountId>> {1351		let res: Vec<T::CrossAccountId> = <Balance<T>>::iter_prefix((collection_id, token))1352			.map(|(owner, _amount)| owner)1353			.take(10)1354			.collect();13551356		if res.is_empty() {1357			None1358		} else {1359			Some(res)1360		}1361	}1362}