git.delta.rocks / unique-network / refs/commits / 7b9f08ee7324

difftreelog

source

pallets/refungible/src/lib.rs40.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 core::ops::Deref;94use derivative::Derivative;95use evm_coder::ToLog;96use frame_support::{97	BoundedBTreeMap, ensure, fail, storage::with_transaction, transactional,98	pallet_prelude::ConstU32,99};100use pallet_evm::{account::CrossAccountId, Pallet as PalletEvm};101use pallet_evm_coder_substrate::WithRecorder;102use pallet_common::{103	CommonCollectionOperations, Error as CommonError, eth::collection_id_to_address,104	Event as CommonEvent, Pallet as PalletCommon, erc::CollectionHelpersEvents,105};106use pallet_structure::Pallet as PalletStructure;107use sp_core::{Get, H160};108use sp_runtime::{ArithmeticError, DispatchError, DispatchResult, TransactionOutcome};109use sp_std::{vec::Vec, vec, collections::btree_map::BTreeMap};110use up_data_structs::{111	AccessMode, budget::Budget, CollectionId, CollectionFlags, CollectionPropertiesVec,112	CreateCollectionData, mapping::TokenAddressMapping, MAX_ITEMS_PER_BATCH, MAX_REFUNGIBLE_PIECES,113	Property, PropertyKey, PropertyKeyPermission, PropertyPermission, PropertyScope, PropertyValue,114	TokenId, TrySetProperty,115};116117pub use pallet::*;118#[cfg(feature = "runtime-benchmarks")]119pub mod benchmarking;120pub mod common;121pub mod erc;122pub mod erc_token;123pub mod weights;124125#[derive(Derivative, Clone)]126pub struct CreateItemData<CrossAccountId> {127	#[derivative(Debug(format_with = "bounded::map_debug"))]128	pub users: BoundedBTreeMap<CrossAccountId, u128, ConstU32<MAX_ITEMS_PER_BATCH>>,129	#[derivative(Debug(format_with = "bounded::vec_debug"))]130	pub properties: CollectionPropertiesVec,131}132pub(crate) type SelfWeightOf<T> = <T as Config>::WeightInfo;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 up_data_structs::{CollectionId, TokenId};142	use super::weights::WeightInfo;143144	#[pallet::error]145	pub enum Error<T> {146		/// Not Refungible item data used to mint in Refungible collection.147		NotRefungibleDataUsedToMintFungibleCollectionToken,148		/// Maximum refungibility exceeded.149		WrongRefungiblePieces,150		/// Refungible token can't be repartitioned by user who isn't owns all pieces.151		RepartitionWhileNotOwningAllPieces,152		/// Refungible token can't nest other tokens.153		RefungibleDisallowsNesting,154		/// Setting item properties is not allowed.155		SettingPropertiesNotAllowed,156	}157158	#[pallet::config]159	pub trait Config:160		frame_system::Config + pallet_common::Config + pallet_structure::Config161	{162		type WeightInfo: WeightInfo;163	}164165	const STORAGE_VERSION: StorageVersion = StorageVersion::new(2);166167	#[pallet::pallet]168	#[pallet::storage_version(STORAGE_VERSION)]169	#[pallet::generate_store(pub(super) trait Store)]170	pub struct Pallet<T>(_);171172	/// Total amount of minted tokens in a collection.173	#[pallet::storage]174	pub type TokensMinted<T: Config> =175		StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;176177	/// Amount of tokens burnt in a collection.178	#[pallet::storage]179	pub type TokensBurnt<T: Config> =180		StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;181182	/// Amount of pieces a refungible token is split into.183	#[pallet::storage]184	#[pallet::getter(fn token_properties)]185	pub type TokenProperties<T: Config> = StorageNMap<186		Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),187		Value = up_data_structs::Properties,188		QueryKind = ValueQuery,189		OnEmpty = up_data_structs::TokenProperties,190	>;191192	/// Total amount of pieces for token193	#[pallet::storage]194	pub type TotalSupply<T: Config> = StorageNMap<195		Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),196		Value = u128,197		QueryKind = ValueQuery,198	>;199200	/// Used to enumerate tokens owned by account.201	#[pallet::storage]202	pub type Owned<T: Config> = StorageNMap<203		Key = (204			Key<Twox64Concat, CollectionId>,205			Key<Blake2_128Concat, T::CrossAccountId>,206			Key<Twox64Concat, TokenId>,207		),208		Value = bool,209		QueryKind = ValueQuery,210	>;211212	/// Amount of tokens (not pieces) partially owned by an account within a collection.213	#[pallet::storage]214	pub type AccountBalance<T: Config> = StorageNMap<215		Key = (216			Key<Twox64Concat, CollectionId>,217			// Owner218			Key<Blake2_128Concat, T::CrossAccountId>,219		),220		Value = u32,221		QueryKind = ValueQuery,222	>;223224	/// Amount of token pieces owned by account.225	#[pallet::storage]226	pub type Balance<T: Config> = StorageNMap<227		Key = (228			Key<Twox64Concat, CollectionId>,229			Key<Twox64Concat, TokenId>,230			// Owner231			Key<Blake2_128Concat, T::CrossAccountId>,232		),233		Value = u128,234		QueryKind = ValueQuery,235	>;236237	/// Allowance set by a token owner for another user to perform one of certain transactions on a number of pieces of a token.238	#[pallet::storage]239	pub type Allowance<T: Config> = StorageNMap<240		Key = (241			Key<Twox64Concat, CollectionId>,242			Key<Twox64Concat, TokenId>,243			// Owner244			Key<Blake2_128, T::CrossAccountId>,245			// Spender246			Key<Blake2_128Concat, T::CrossAccountId>,247		),248		Value = u128,249		QueryKind = ValueQuery,250	>;251252	/// Operator set by a wallet owner that could perform certain transactions on all tokens in the wallet.253	#[pallet::storage]254	pub type CollectionAllowance<T: Config> = StorageNMap<255		Key = (256			Key<Twox64Concat, CollectionId>,257			Key<Blake2_128Concat, T::CrossAccountId>,258			Key<Blake2_128Concat, T::CrossAccountId>,259		),260		Value = bool,261		QueryKind = ValueQuery,262	>;263}264265pub struct RefungibleHandle<T: Config>(pallet_common::CollectionHandle<T>);266impl<T: Config> RefungibleHandle<T> {267	pub fn cast(inner: pallet_common::CollectionHandle<T>) -> Self {268		Self(inner)269	}270	pub fn into_inner(self) -> pallet_common::CollectionHandle<T> {271		self.0272	}273	pub fn common_mut(&mut self) -> &mut pallet_common::CollectionHandle<T> {274		&mut self.0275	}276}277278impl<T: Config> Deref for RefungibleHandle<T> {279	type Target = pallet_common::CollectionHandle<T>;280281	fn deref(&self) -> &Self::Target {282		&self.0283	}284}285286impl<T: Config> WithRecorder<T> for RefungibleHandle<T> {287	fn recorder(&self) -> &pallet_evm_coder_substrate::SubstrateRecorder<T> {288		self.0.recorder()289	}290	fn into_recorder(self) -> pallet_evm_coder_substrate::SubstrateRecorder<T> {291		self.0.into_recorder()292	}293}294295impl<T: Config> Pallet<T> {296	/// Get number of RFT tokens in collection297	pub fn total_supply(collection: &RefungibleHandle<T>) -> u32 {298		<TokensMinted<T>>::get(collection.id) - <TokensBurnt<T>>::get(collection.id)299	}300301	/// Check that RFT token exists302	///303	/// - `token`: Token ID.304	pub fn token_exists(collection: &RefungibleHandle<T>, token: TokenId) -> bool {305		<TotalSupply<T>>::contains_key((collection.id, token))306	}307308	pub fn set_scoped_token_property(309		collection_id: CollectionId,310		token_id: TokenId,311		scope: PropertyScope,312		property: Property,313	) -> DispatchResult {314		TokenProperties::<T>::try_mutate((collection_id, token_id), |properties| {315			properties.try_scoped_set(scope, property.key, property.value)316		})317		.map_err(<CommonError<T>>::from)?;318319		Ok(())320	}321322	pub fn set_scoped_token_properties(323		collection_id: CollectionId,324		token_id: TokenId,325		scope: PropertyScope,326		properties: impl Iterator<Item = Property>,327	) -> DispatchResult {328		TokenProperties::<T>::try_mutate((collection_id, token_id), |stored_properties| {329			stored_properties.try_scoped_set_from_iter(scope, properties)330		})331		.map_err(<CommonError<T>>::from)?;332333		Ok(())334	}335}336337// unchecked calls skips any permission checks338impl<T: Config> Pallet<T> {339	/// Create RFT collection340	///341	/// `init_collection` will take non-refundable deposit for collection creation.342	///343	/// - `data`: Contains settings for collection limits and permissions.344	pub fn init_collection(345		owner: T::CrossAccountId,346		payer: T::CrossAccountId,347		data: CreateCollectionData<T::AccountId>,348		flags: CollectionFlags,349	) -> Result<CollectionId, DispatchError> {350		<PalletCommon<T>>::init_collection(owner, payer, data, flags)351	}352353	/// Destroy RFT collection354	///355	/// `destroy_collection` will throw error if collection contains any tokens.356	/// Only owner can destroy collection.357	pub fn destroy_collection(358		collection: RefungibleHandle<T>,359		sender: &T::CrossAccountId,360	) -> DispatchResult {361		let id = collection.id;362363		if Self::collection_has_tokens(id) {364			return Err(<CommonError<T>>::CantDestroyNotEmptyCollection.into());365		}366367		// =========368369		PalletCommon::destroy_collection(collection.0, sender)?;370371		<TokensMinted<T>>::remove(id);372		<TokensBurnt<T>>::remove(id);373		let _ = <TotalSupply<T>>::clear_prefix((id,), u32::MAX, None);374		let _ = <Balance<T>>::clear_prefix((id,), u32::MAX, None);375		let _ = <Allowance<T>>::clear_prefix((id,), u32::MAX, None);376		let _ = <Owned<T>>::clear_prefix((id,), u32::MAX, None);377		let _ = <AccountBalance<T>>::clear_prefix((id,), u32::MAX, None);378		Ok(())379	}380381	fn collection_has_tokens(collection_id: CollectionId) -> bool {382		<TotalSupply<T>>::iter_prefix((collection_id,))383			.next()384			.is_some()385	}386387	pub fn burn_token_unchecked(388		collection: &RefungibleHandle<T>,389		owner: &T::CrossAccountId,390		token_id: TokenId,391	) -> DispatchResult {392		let burnt = <TokensBurnt<T>>::get(collection.id)393			.checked_add(1)394			.ok_or(ArithmeticError::Overflow)?;395396		<TokensBurnt<T>>::insert(collection.id, burnt);397		<TokenProperties<T>>::remove((collection.id, token_id));398		<TotalSupply<T>>::remove((collection.id, token_id));399		let _ = <Balance<T>>::clear_prefix((collection.id, token_id), u32::MAX, None);400		let _ = <Allowance<T>>::clear_prefix((collection.id, token_id), u32::MAX, None);401		<PalletEvm<T>>::deposit_log(402			ERC721Events::Transfer {403				from: *owner.as_eth(),404				to: H160::default(),405				token_id: token_id.into(),406			}407			.to_log(collection_id_to_address(collection.id)),408		);409		Ok(())410	}411412	/// Burn RFT token pieces413	///414	/// `burn` will decrease total amount of token pieces and amount owned by sender.415	/// `burn` can be called even if there are multiple owners of the RFT token.416	/// If sender wouldn't have any pieces left after `burn` than she will stop being417	/// one of the owners of the token. If there is no account that owns any pieces of418	/// the token than token will be burned too.419	///420	/// - `amount`: Amount of token pieces to burn.421	/// - `token`: Token who's pieces should be burned422	/// - `collection`: Collection that contains the token423	pub fn burn(424		collection: &RefungibleHandle<T>,425		owner: &T::CrossAccountId,426		token: TokenId,427		amount: u128,428	) -> DispatchResult {429		if <Balance<T>>::get((collection.id, token, owner)) == 0 {430			return Err(<CommonError<T>>::TokenValueTooLow.into());431		}432433		let total_supply = <TotalSupply<T>>::get((collection.id, token))434			.checked_sub(amount)435			.ok_or(<CommonError<T>>::TokenValueTooLow)?;436437		// This was probally last owner of this token?438		if total_supply == 0 {439			// Ensure user actually owns this amount440			ensure!(441				<Balance<T>>::get((collection.id, token, owner)) == amount,442				<CommonError<T>>::TokenValueTooLow443			);444			let account_balance = <AccountBalance<T>>::get((collection.id, owner))445				.checked_sub(1)446				// Should not occur447				.ok_or(ArithmeticError::Underflow)?;448449			// =========450451			<Owned<T>>::remove((collection.id, owner, token));452			<PalletStructure<T>>::unnest_if_nested(owner, collection.id, token);453			<AccountBalance<T>>::insert((collection.id, owner), account_balance);454			Self::burn_token_unchecked(collection, owner, token)?;455			<PalletEvm<T>>::deposit_log(456				ERC20Events::Transfer {457					from: *owner.as_eth(),458					to: H160::default(),459					value: amount.into(),460				}461				.to_log(collection_id_to_address(collection.id)),462			);463			<PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(464				collection.id,465				token,466				owner.clone(),467				amount,468			));469			return Ok(());470		}471472		let balance = <Balance<T>>::get((collection.id, token, owner))473			.checked_sub(amount)474			.ok_or(<CommonError<T>>::TokenValueTooLow)?;475		let account_balance = if balance == 0 {476			<AccountBalance<T>>::get((collection.id, owner))477				.checked_sub(1)478				// Should not occur479				.ok_or(ArithmeticError::Underflow)?480		} else {481			0482		};483484		// =========485486		if balance == 0 {487			<Owned<T>>::remove((collection.id, owner, token));488			<PalletStructure<T>>::unnest_if_nested(owner, collection.id, token);489			<Balance<T>>::remove((collection.id, token, owner));490			<AccountBalance<T>>::insert((collection.id, owner), account_balance);491492			if let Some(user) = Self::token_owner(collection.id, token) {493				<PalletEvm<T>>::deposit_log(494					ERC721Events::Transfer {495						from: erc::ADDRESS_FOR_PARTIALLY_OWNED_TOKENS,496						to: *user.as_eth(),497						token_id: token.into(),498					}499					.to_log(collection_id_to_address(collection.id)),500				);501			}502		} else {503			<Balance<T>>::insert((collection.id, token, owner), balance);504		}505		<TotalSupply<T>>::insert((collection.id, token), total_supply);506507		<PalletEvm<T>>::deposit_log(508			ERC20Events::Transfer {509				from: *owner.as_eth(),510				to: H160::default(),511				value: amount.into(),512			}513			.to_log(T::EvmTokenAddressMapping::token_to_address(514				collection.id,515				token,516			)),517		);518		<PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(519			collection.id,520			token,521			owner.clone(),522			amount,523		));524		Ok(())525	}526527	#[transactional]528	fn modify_token_properties(529		collection: &RefungibleHandle<T>,530		sender: &T::CrossAccountId,531		token_id: TokenId,532		properties: impl Iterator<Item = (PropertyKey, Option<PropertyValue>)>,533		is_token_create: bool,534		nesting_budget: &dyn Budget,535	) -> DispatchResult {536		let is_collection_admin = || collection.is_owner_or_admin(sender);537		let is_token_owner = || -> Result<bool, DispatchError> {538			let balance = collection.balance(sender.clone(), token_id);539			let total_pieces: u128 =540				Self::total_pieces(collection.id, token_id).unwrap_or(u128::MAX);541			if balance != total_pieces {542				return Ok(false);543			}544545			let is_bundle_owner = <PalletStructure<T>>::check_indirectly_owned(546				sender.clone(),547				collection.id,548				token_id,549				None,550				nesting_budget,551			)?;552553			Ok(is_bundle_owner)554		};555556		for (key, value) in properties {557			let permission = <PalletCommon<T>>::property_permissions(collection.id)558				.get(&key)559				.cloned()560				.unwrap_or_else(PropertyPermission::none);561562			let is_property_exists = TokenProperties::<T>::get((collection.id, token_id))563				.get(&key)564				.is_some();565566			match permission {567				PropertyPermission { mutable: false, .. } if is_property_exists => {568					return Err(<CommonError<T>>::NoPermission.into());569				}570571				PropertyPermission {572					collection_admin,573					token_owner,574					..575				} => {576					//TODO: investigate threats during public minting.577					let is_token_create =578						is_token_create && (collection_admin || token_owner) && value.is_some();579					if !(is_token_create580						|| (collection_admin && is_collection_admin())581						|| (token_owner && is_token_owner()?))582					{583						fail!(<CommonError<T>>::NoPermission);584					}585				}586			}587588			match value {589				Some(value) => {590					<TokenProperties<T>>::try_mutate((collection.id, token_id), |properties| {591						properties.try_set(key.clone(), value)592					})593					.map_err(<CommonError<T>>::from)?;594595					<PalletCommon<T>>::deposit_event(CommonEvent::TokenPropertySet(596						collection.id,597						token_id,598						key,599					));600				}601				None => {602					<TokenProperties<T>>::try_mutate((collection.id, token_id), |properties| {603						properties.remove(&key)604					})605					.map_err(<CommonError<T>>::from)?;606607					<PalletCommon<T>>::deposit_event(CommonEvent::TokenPropertyDeleted(608						collection.id,609						token_id,610						key,611					));612				}613			}614615			<PalletEvm<T>>::deposit_log(616				CollectionHelpersEvents::TokenChanged {617					collection_id: collection_id_to_address(collection.id),618					token_id: token_id.into(),619				}620				.to_log(T::ContractAddress::get()),621			);622		}623624		Ok(())625	}626627	pub fn set_token_properties(628		collection: &RefungibleHandle<T>,629		sender: &T::CrossAccountId,630		token_id: TokenId,631		properties: impl Iterator<Item = Property>,632		is_token_create: bool,633		nesting_budget: &dyn Budget,634	) -> DispatchResult {635		Self::modify_token_properties(636			collection,637			sender,638			token_id,639			properties.map(|p| (p.key, Some(p.value))),640			is_token_create,641			nesting_budget,642		)643	}644645	pub fn set_token_property(646		collection: &RefungibleHandle<T>,647		sender: &T::CrossAccountId,648		token_id: TokenId,649		property: Property,650		nesting_budget: &dyn Budget,651	) -> DispatchResult {652		let is_token_create = false;653654		Self::set_token_properties(655			collection,656			sender,657			token_id,658			[property].into_iter(),659			is_token_create,660			nesting_budget,661		)662	}663664	pub fn delete_token_properties(665		collection: &RefungibleHandle<T>,666		sender: &T::CrossAccountId,667		token_id: TokenId,668		property_keys: impl Iterator<Item = PropertyKey>,669		nesting_budget: &dyn Budget,670	) -> DispatchResult {671		let is_token_create = false;672673		Self::modify_token_properties(674			collection,675			sender,676			token_id,677			property_keys.into_iter().map(|key| (key, None)),678			is_token_create,679			nesting_budget,680		)681	}682683	pub fn delete_token_property(684		collection: &RefungibleHandle<T>,685		sender: &T::CrossAccountId,686		token_id: TokenId,687		property_key: PropertyKey,688		nesting_budget: &dyn Budget,689	) -> DispatchResult {690		Self::delete_token_properties(691			collection,692			sender,693			token_id,694			[property_key].into_iter(),695			nesting_budget,696		)697	}698699	/// Transfer RFT token pieces from one account to another.700	///701	/// If the sender is no longer owns any pieces after the `transfer` than she stops being an owner of the token.702	///703	/// - `from`: Owner of token pieces to transfer.704	/// - `to`: Recepient of transfered token pieces.705	/// - `amount`: Amount of token pieces to transfer.706	/// - `token`: Token whos pieces should be transfered707	/// - `collection`: Collection that contains the token708	pub fn transfer(709		collection: &RefungibleHandle<T>,710		from: &T::CrossAccountId,711		to: &T::CrossAccountId,712		token: TokenId,713		amount: u128,714		nesting_budget: &dyn Budget,715	) -> DispatchResult {716		ensure!(717			collection.limits.transfers_enabled(),718			<CommonError<T>>::TransferNotAllowed719		);720721		if collection.permissions.access() == AccessMode::AllowList {722			collection.check_allowlist(from)?;723			collection.check_allowlist(to)?;724		}725		<PalletCommon<T>>::ensure_correct_receiver(to)?;726727		let initial_balance_from = <Balance<T>>::get((collection.id, token, from));728729		if initial_balance_from == 0 {730			return Err(<CommonError<T>>::TokenValueTooLow.into());731		}732733		let updated_balance_from = initial_balance_from734			.checked_sub(amount)735			.ok_or(<CommonError<T>>::TokenValueTooLow)?;736		let mut create_target = false;737		let from_to_differ = from != to;738		let updated_balance_to = if from != to && amount != 0 {739			let old_balance = <Balance<T>>::get((collection.id, token, to));740			if old_balance == 0 {741				create_target = true;742			}743			Some(744				old_balance745					.checked_add(amount)746					.ok_or(ArithmeticError::Overflow)?,747			)748		} else {749			None750		};751752		let account_balance_from = if updated_balance_from == 0 {753			Some(754				<AccountBalance<T>>::get((collection.id, from))755					.checked_sub(1)756					// Should not occur757					.ok_or(ArithmeticError::Underflow)?,758			)759		} else {760			None761		};762		// Account data is created in token, AccountBalance should be increased763		// But only if from != to as we shouldn't check overflow in this case764		let account_balance_to = if create_target && from_to_differ {765			let account_balance_to = <AccountBalance<T>>::get((collection.id, to))766				.checked_add(1)767				.ok_or(ArithmeticError::Overflow)?;768			ensure!(769				account_balance_to < collection.limits.account_token_ownership_limit(),770				<CommonError<T>>::AccountTokenLimitExceeded,771			);772773			Some(account_balance_to)774		} else {775			None776		};777778		// =========779780		if let Some(updated_balance_to) = updated_balance_to {781			// from != to && amount != 0782783			<PalletStructure<T>>::nest_if_sent_to_token(784				from.clone(),785				to,786				collection.id,787				token,788				nesting_budget,789			)?;790791			if updated_balance_from == 0 {792				<Balance<T>>::remove((collection.id, token, from));793				<PalletStructure<T>>::unnest_if_nested(from, collection.id, token);794			} else {795				<Balance<T>>::insert((collection.id, token, from), updated_balance_from);796			}797			<Balance<T>>::insert((collection.id, token, to), updated_balance_to);798			if let Some(account_balance_from) = account_balance_from {799				<AccountBalance<T>>::insert((collection.id, from), account_balance_from);800				<Owned<T>>::remove((collection.id, from, token));801			}802			if let Some(account_balance_to) = account_balance_to {803				<AccountBalance<T>>::insert((collection.id, to), account_balance_to);804				<Owned<T>>::insert((collection.id, to, token), true);805			}806		}807808		<PalletEvm<T>>::deposit_log(809			ERC20Events::Transfer {810				from: *from.as_eth(),811				to: *to.as_eth(),812				value: amount.into(),813			}814			.to_log(T::EvmTokenAddressMapping::token_to_address(815				collection.id,816				token,817			)),818		);819820		<PalletCommon<T>>::deposit_event(CommonEvent::Transfer(821			collection.id,822			token,823			from.clone(),824			to.clone(),825			amount,826		));827828		let total_supply = <TotalSupply<T>>::get((collection.id, token));829830		if amount == total_supply {831			// if token was fully owned by `from` and will be fully owned by `to` after transfer832			<PalletEvm<T>>::deposit_log(833				ERC721Events::Transfer {834					from: *from.as_eth(),835					to: *to.as_eth(),836					token_id: token.into(),837				}838				.to_log(collection_id_to_address(collection.id)),839			);840		} else if let Some(updated_balance_to) = updated_balance_to {841			// if `from` not equals `to`. This condition is needed to avoid sending event842			// when `from` fully owns token and sends part of token pieces to itself.843			if initial_balance_from == total_supply {844				// if token was fully owned by `from` and will be only partially owned by `to`845				// and `from` after transfer846				<PalletEvm<T>>::deposit_log(847					ERC721Events::Transfer {848						from: *from.as_eth(),849						to: erc::ADDRESS_FOR_PARTIALLY_OWNED_TOKENS,850						token_id: token.into(),851					}852					.to_log(collection_id_to_address(collection.id)),853				);854			} else if updated_balance_to == total_supply {855				// if token was partially owned by `from` and will be fully owned by `to` after transfer856				<PalletEvm<T>>::deposit_log(857					ERC721Events::Transfer {858						from: erc::ADDRESS_FOR_PARTIALLY_OWNED_TOKENS,859						to: *to.as_eth(),860						token_id: token.into(),861					}862					.to_log(collection_id_to_address(collection.id)),863				);864			}865		}866867		Ok(())868	}869870	/// Batched operation to create multiple RFT tokens.871	///872	/// Same as `create_item` but creates multiple tokens.873	///874	/// - `data`: Same as 'data` in `create_item` but contains data for multiple tokens.875	pub fn create_multiple_items(876		collection: &RefungibleHandle<T>,877		sender: &T::CrossAccountId,878		data: Vec<CreateItemData<T::CrossAccountId>>,879		nesting_budget: &dyn Budget,880	) -> DispatchResult {881		if !collection.is_owner_or_admin(sender) {882			ensure!(883				collection.permissions.mint_mode(),884				<CommonError<T>>::PublicMintingNotAllowed885			);886			collection.check_allowlist(sender)?;887888			for item in data.iter() {889				for user in item.users.keys() {890					collection.check_allowlist(user)?;891				}892			}893		}894895		for item in data.iter() {896			for (owner, _) in item.users.iter() {897				<PalletCommon<T>>::ensure_correct_receiver(owner)?;898			}899		}900901		// Total pieces per tokens902		let totals = data903			.iter()904			.map(|data| {905				Ok(data906					.users907					.iter()908					.map(|u| u.1)909					.try_fold(0u128, |acc, v| acc.checked_add(*v))910					.ok_or(ArithmeticError::Overflow)?)911			})912			.collect::<Result<Vec<_>, DispatchError>>()?;913		for total in &totals {914			ensure!(915				*total <= MAX_REFUNGIBLE_PIECES,916				<Error<T>>::WrongRefungiblePieces917			);918		}919920		let first_token_id = <TokensMinted<T>>::get(collection.id);921		let tokens_minted = first_token_id922			.checked_add(data.len() as u32)923			.ok_or(ArithmeticError::Overflow)?;924		ensure!(925			tokens_minted < collection.limits.token_limit(),926			<CommonError<T>>::CollectionTokenLimitExceeded927		);928929		let mut balances = BTreeMap::new();930		for data in &data {931			for owner in data.users.keys() {932				let balance = balances933					.entry(owner)934					.or_insert_with(|| <AccountBalance<T>>::get((collection.id, owner)));935				*balance = balance.checked_add(1).ok_or(ArithmeticError::Overflow)?;936937				ensure!(938					*balance <= collection.limits.account_token_ownership_limit(),939					<CommonError<T>>::AccountTokenLimitExceeded,940				);941			}942		}943944		for (i, token) in data.iter().enumerate() {945			let token_id = TokenId(first_token_id + i as u32 + 1);946			for (to, _) in token.users.iter() {947				<PalletStructure<T>>::check_nesting(948					sender.clone(),949					to,950					collection.id,951					token_id,952					nesting_budget,953				)?;954			}955		}956957		// =========958959		with_transaction(|| {960			for (i, data) in data.iter().enumerate() {961				let token_id = first_token_id + i as u32 + 1;962				<TotalSupply<T>>::insert((collection.id, token_id), totals[i]);963964				for (user, amount) in data.users.iter() {965					if *amount == 0 {966						continue;967					}968					<Balance<T>>::insert((collection.id, token_id, &user), amount);969					<Owned<T>>::insert((collection.id, &user, TokenId(token_id)), true);970					<PalletStructure<T>>::nest_if_sent_to_token_unchecked(971						user,972						collection.id,973						TokenId(token_id),974					);975				}976977				if let Err(e) = Self::set_token_properties(978					collection,979					sender,980					TokenId(token_id),981					data.properties.clone().into_iter(),982					true,983					nesting_budget,984				) {985					return TransactionOutcome::Rollback(Err(e));986				}987			}988			TransactionOutcome::Commit(Ok(()))989		})?;990991		<TokensMinted<T>>::insert(collection.id, tokens_minted);992993		for (account, balance) in balances {994			<AccountBalance<T>>::insert((collection.id, account), balance);995		}996997		for (i, token) in data.into_iter().enumerate() {998			let token_id = first_token_id + i as u32 + 1;9991000			let receivers = token1001				.users1002				.into_iter()1003				.filter(|(_, amount)| *amount > 0)1004				.collect::<Vec<_>>();10051006			if let [(user, _)] = receivers.as_slice() {1007				// if there is exactly one receiver1008				<PalletEvm<T>>::deposit_log(1009					ERC721Events::Transfer {1010						from: H160::default(),1011						to: *user.as_eth(),1012						token_id: token_id.into(),1013					}1014					.to_log(collection_id_to_address(collection.id)),1015				);1016			} else if let [_, ..] = receivers.as_slice() {1017				// if there is more than one receiver1018				<PalletEvm<T>>::deposit_log(1019					ERC721Events::Transfer {1020						from: H160::default(),1021						to: erc::ADDRESS_FOR_PARTIALLY_OWNED_TOKENS,1022						token_id: token_id.into(),1023					}1024					.to_log(collection_id_to_address(collection.id)),1025				);1026			}10271028			for (user, amount) in receivers.into_iter() {1029				<PalletEvm<T>>::deposit_log(1030					ERC20Events::Transfer {1031						from: H160::default(),1032						to: *user.as_eth(),1033						value: amount.into(),1034					}1035					.to_log(T::EvmTokenAddressMapping::token_to_address(1036						collection.id,1037						TokenId(token_id),1038					)),1039				);1040				<PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(1041					collection.id,1042					TokenId(token_id),1043					user,1044					amount,1045				));1046			}1047		}1048		Ok(())1049	}10501051	pub fn set_allowance_unchecked(1052		collection: &RefungibleHandle<T>,1053		sender: &T::CrossAccountId,1054		spender: &T::CrossAccountId,1055		token: TokenId,1056		amount: u128,1057	) {1058		if amount == 0 {1059			<Allowance<T>>::remove((collection.id, token, sender, spender));1060		} else {1061			<Allowance<T>>::insert((collection.id, token, sender, spender), amount);1062		}10631064		<PalletEvm<T>>::deposit_log(1065			ERC20Events::Approval {1066				owner: *sender.as_eth(),1067				spender: *spender.as_eth(),1068				value: amount.into(),1069			}1070			.to_log(T::EvmTokenAddressMapping::token_to_address(1071				collection.id,1072				token,1073			)),1074		);1075		<PalletCommon<T>>::deposit_event(CommonEvent::Approved(1076			collection.id,1077			token,1078			sender.clone(),1079			spender.clone(),1080			amount,1081		))1082	}10831084	/// Set allowance for the spender to `transfer` or `burn` sender's token pieces.1085	///1086	/// - `amount`: Amount of token pieces the spender is allowed to `transfer` or `burn.1087	pub fn set_allowance(1088		collection: &RefungibleHandle<T>,1089		sender: &T::CrossAccountId,1090		spender: &T::CrossAccountId,1091		token: TokenId,1092		amount: u128,1093	) -> DispatchResult {1094		if collection.permissions.access() == AccessMode::AllowList {1095			collection.check_allowlist(sender)?;1096			collection.check_allowlist(spender)?;1097		}10981099		<PalletCommon<T>>::ensure_correct_receiver(spender)?;11001101		if <Balance<T>>::get((collection.id, token, sender)) < amount {1102			ensure!(1103				collection.ignores_owned_amount(sender) && Self::token_exists(collection, token),1104				<CommonError<T>>::CantApproveMoreThanOwned1105			);1106		}11071108		// =========11091110		Self::set_allowance_unchecked(collection, sender, spender, token, amount);1111		Ok(())1112	}11131114	/// Returns allowance, which should be set after transaction1115	fn check_allowed(1116		collection: &RefungibleHandle<T>,1117		spender: &T::CrossAccountId,1118		from: &T::CrossAccountId,1119		token: TokenId,1120		amount: u128,1121		nesting_budget: &dyn Budget,1122	) -> Result<Option<u128>, DispatchError> {1123		if spender.conv_eq(from) {1124			return Ok(None);1125		}1126		if collection.permissions.access() == AccessMode::AllowList {1127			// `from`, `to` checked in [`transfer`]1128			collection.check_allowlist(spender)?;1129		}1130		if let Some(source) = T::CrossTokenAddressMapping::address_to_token(from) {1131			// TODO: should collection owner be allowed to perform this transfer?1132			ensure!(1133				<PalletStructure<T>>::check_indirectly_owned(1134					spender.clone(),1135					source.0,1136					source.1,1137					None,1138					nesting_budget1139				)?,1140				<CommonError<T>>::ApprovedValueTooLow,1141			);1142			return Ok(None);1143		}1144		let allowance =1145			<Allowance<T>>::get((collection.id, token, from, &spender)).checked_sub(amount);11461147		// Allowance (if any) would be reduced if spender is also wallet operator1148		if <CollectionAllowance<T>>::get((collection.id, from, spender)) {1149			return Ok(allowance);1150		}11511152		if allowance.is_none() {1153			ensure!(1154				collection.ignores_allowance(spender),1155				<CommonError<T>>::ApprovedValueTooLow1156			);1157		}1158		Ok(allowance)1159	}11601161	/// Transfer RFT token pieces from one account to another.1162	///1163	/// Same as the [`transfer`] but spender doesn't needs to be an owner of the token pieces.1164	/// The owner should set allowance for the spender to transfer pieces.1165	///1166	/// [`transfer`]: struct.Pallet.html#method.transfer1167	pub fn transfer_from(1168		collection: &RefungibleHandle<T>,1169		spender: &T::CrossAccountId,1170		from: &T::CrossAccountId,1171		to: &T::CrossAccountId,1172		token: TokenId,1173		amount: u128,1174		nesting_budget: &dyn Budget,1175	) -> DispatchResult {1176		let allowance =1177			Self::check_allowed(collection, spender, from, token, amount, nesting_budget)?;11781179		// =========11801181		Self::transfer(collection, from, to, token, amount, nesting_budget)?;1182		if let Some(allowance) = allowance {1183			Self::set_allowance_unchecked(collection, from, spender, token, allowance);1184		}1185		Ok(())1186	}11871188	/// Burn RFT token pieces from the account.1189	///1190	/// Same as the [`burn`] but spender doesn't need to be an owner of the token pieces. The owner should1191	/// set allowance for the spender to burn pieces1192	///1193	/// [`burn`]: struct.Pallet.html#method.burn1194	pub fn burn_from(1195		collection: &RefungibleHandle<T>,1196		spender: &T::CrossAccountId,1197		from: &T::CrossAccountId,1198		token: TokenId,1199		amount: u128,1200		nesting_budget: &dyn Budget,1201	) -> DispatchResult {1202		let allowance =1203			Self::check_allowed(collection, spender, from, token, amount, nesting_budget)?;12041205		// =========12061207		Self::burn(collection, from, token, amount)?;1208		if let Some(allowance) = allowance {1209			Self::set_allowance_unchecked(collection, from, spender, token, allowance);1210		}1211		Ok(())1212	}12131214	/// Create RFT token.1215	///1216	/// The sender should be the owner/admin of the collection or collection should be configured1217	/// to allow public minting.1218	///1219	/// - `data`: Contains list of users who will become the owners of the token pieces and amount1220	///   of token pieces they will receive.1221	pub fn create_item(1222		collection: &RefungibleHandle<T>,1223		sender: &T::CrossAccountId,1224		data: CreateItemData<T::CrossAccountId>,1225		nesting_budget: &dyn Budget,1226	) -> DispatchResult {1227		Self::create_multiple_items(collection, sender, vec![data], nesting_budget)1228	}12291230	/// Repartition RFT token.1231	///1232	/// `repartition` will set token balance of the sender and total amount of token pieces.1233	/// Sender should own all of the token pieces. `repartition' could be done even if some1234	/// token pieces were burned before.1235	///1236	/// - `amount`: Total amount of token pieces that the token will have after `repartition`.1237	pub fn repartition(1238		collection: &RefungibleHandle<T>,1239		owner: &T::CrossAccountId,1240		token: TokenId,1241		amount: u128,1242	) -> DispatchResult {1243		ensure!(1244			amount <= MAX_REFUNGIBLE_PIECES,1245			<Error<T>>::WrongRefungiblePieces1246		);1247		ensure!(amount > 0, <CommonError<T>>::TokenValueTooLow);1248		// Ensure user owns all pieces1249		let total_pieces = Self::total_pieces(collection.id, token).unwrap_or(u128::MAX);1250		let balance = <Balance<T>>::get((collection.id, token, owner));1251		ensure!(1252			total_pieces == balance,1253			<Error<T>>::RepartitionWhileNotOwningAllPieces1254		);12551256		<Balance<T>>::insert((collection.id, token, owner), amount);1257		<TotalSupply<T>>::insert((collection.id, token), amount);12581259		if amount > total_pieces {1260			let mint_amount = amount - total_pieces;1261			<PalletEvm<T>>::deposit_log(1262				ERC20Events::Transfer {1263					from: H160::default(),1264					to: *owner.as_eth(),1265					value: mint_amount.into(),1266				}1267				.to_log(T::EvmTokenAddressMapping::token_to_address(1268					collection.id,1269					token,1270				)),1271			);1272			<PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(1273				collection.id,1274				token,1275				owner.clone(),1276				mint_amount,1277			));1278		} else if total_pieces > amount {1279			let burn_amount = total_pieces - amount;1280			<PalletEvm<T>>::deposit_log(1281				ERC20Events::Transfer {1282					from: *owner.as_eth(),1283					to: H160::default(),1284					value: burn_amount.into(),1285				}1286				.to_log(T::EvmTokenAddressMapping::token_to_address(1287					collection.id,1288					token,1289				)),1290			);1291			<PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(1292				collection.id,1293				token,1294				owner.clone(),1295				burn_amount,1296			));1297		}12981299		Ok(())1300	}13011302	fn token_owner(collection_id: CollectionId, token_id: TokenId) -> Option<T::CrossAccountId> {1303		let mut owner = None;1304		let mut count = 0;1305		for key in Balance::<T>::iter_key_prefix((collection_id, token_id)) {1306			count += 1;1307			if count > 1 {1308				return None;1309			}1310			owner = Some(key);1311		}1312		owner1313	}13141315	fn total_pieces(collection_id: CollectionId, token_id: TokenId) -> Option<u128> {1316		<TotalSupply<T>>::try_get((collection_id, token_id)).ok()1317	}13181319	pub fn set_collection_properties(1320		collection: &RefungibleHandle<T>,1321		sender: &T::CrossAccountId,1322		properties: Vec<Property>,1323	) -> DispatchResult {1324		<PalletCommon<T>>::set_collection_properties(collection, sender, properties)1325	}13261327	pub fn delete_collection_properties(1328		collection: &RefungibleHandle<T>,1329		sender: &T::CrossAccountId,1330		property_keys: Vec<PropertyKey>,1331	) -> DispatchResult {1332		<PalletCommon<T>>::delete_collection_properties(collection, sender, property_keys)1333	}13341335	pub fn set_token_property_permissions(1336		collection: &RefungibleHandle<T>,1337		sender: &T::CrossAccountId,1338		property_permissions: Vec<PropertyKeyPermission>,1339	) -> DispatchResult {1340		<PalletCommon<T>>::set_token_property_permissions(collection, sender, property_permissions)1341	}13421343	pub fn set_scoped_token_property_permissions(1344		collection: &RefungibleHandle<T>,1345		sender: &T::CrossAccountId,1346		scope: PropertyScope,1347		property_permissions: Vec<PropertyKeyPermission>,1348	) -> DispatchResult {1349		<PalletCommon<T>>::set_scoped_token_property_permissions(1350			collection,1351			sender,1352			scope,1353			property_permissions,1354		)1355	}13561357	/// Returns 10 token in no particular order.1358	///1359	/// There is no direct way to get token holders in ascending order,1360	/// since `iter_prefix` returns values in no particular order.1361	/// Therefore, getting the 10 largest holders with a large value of holders1362	/// can lead to impact memory allocation + sorting with  `n * log (n)`.1363	pub fn token_owners(1364		collection_id: CollectionId,1365		token: TokenId,1366	) -> Option<Vec<T::CrossAccountId>> {1367		let res: Vec<T::CrossAccountId> = <Balance<T>>::iter_prefix((collection_id, token))1368			.map(|(owner, _amount)| owner)1369			.take(10)1370			.collect();13711372		if res.is_empty() {1373			None1374		} else {1375			Some(res)1376		}1377	}13781379	/// Sets or unsets the approval of a given operator.1380	///1381	/// The `operator` is allowed to transfer all token pieces of the `owner` on their behalf.1382	/// - `owner`: Token owner1383	/// - `operator`: Operator1384	/// - `approve`: Should operator status be granted or revoked?1385	pub fn set_allowance_for_all(1386		collection: &RefungibleHandle<T>,1387		owner: &T::CrossAccountId,1388		operator: &T::CrossAccountId,1389		approve: bool,1390	) -> DispatchResult {1391		if collection.permissions.access() == AccessMode::AllowList {1392			collection.check_allowlist(owner)?;1393			collection.check_allowlist(operator)?;1394		}13951396		<PalletCommon<T>>::ensure_correct_receiver(operator)?;13971398		// =========13991400		<CollectionAllowance<T>>::insert((collection.id, owner, operator), approve);1401		<PalletEvm<T>>::deposit_log(1402			ERC721Events::ApprovalForAll {1403				owner: *owner.as_eth(),1404				operator: *operator.as_eth(),1405				approved: approve,1406			}1407			.to_log(collection_id_to_address(collection.id)),1408		);1409		<PalletCommon<T>>::deposit_event(CommonEvent::ApprovedForAll(1410			collection.id,1411			owner.clone(),1412			operator.clone(),1413			approve,1414		));1415		Ok(())1416	}14171418	/// Tells whether the given `owner` approves the `operator`.1419	pub fn allowance_for_all(1420		collection: &RefungibleHandle<T>,1421		owner: &T::CrossAccountId,1422		operator: &T::CrossAccountId,1423	) -> bool {1424		<CollectionAllowance<T>>::get((collection.id, owner, operator))1425	}1426}