git.delta.rocks / unique-network / refs/commits / 62d6042adc19

difftreelog

source

pallets/refungible/src/lib.rs42.1 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 derivative::Derivative;96use evm_coder::ToLog;97use frame_support::{98	BoundedBTreeMap, BoundedVec, ensure, fail, storage::with_transaction, transactional,99	pallet_prelude::ConstU32,100};101use pallet_evm::{account::CrossAccountId, Pallet as PalletEvm};102use pallet_evm_coder_substrate::WithRecorder;103use pallet_common::{104	CommonCollectionOperations, Error as CommonError, eth::collection_id_to_address,105	Event as CommonEvent, Pallet as PalletCommon, erc::CollectionHelpersEvents,106};107use pallet_structure::Pallet as PalletStructure;108use scale_info::TypeInfo;109use sp_core::{Get, H160};110use sp_runtime::{ArithmeticError, DispatchError, DispatchResult, TransactionOutcome};111use sp_std::{vec::Vec, vec, collections::btree_map::BTreeMap};112use up_data_structs::{113	AccessMode, budget::Budget, CollectionId, CollectionFlags, CollectionPropertiesVec,114	CreateCollectionData, CustomDataLimit, mapping::TokenAddressMapping, MAX_ITEMS_PER_BATCH,115	MAX_REFUNGIBLE_PIECES, Property, PropertyKey, PropertyKeyPermission, PropertyPermission,116	PropertyScope, PropertyValue, TokenId, TrySetProperty,117};118119pub use pallet::*;120#[cfg(feature = "runtime-benchmarks")]121pub mod benchmarking;122pub mod common;123pub mod erc;124pub mod erc_token;125pub mod weights;126127#[derive(Derivative, Clone)]128pub struct CreateItemData<CrossAccountId> {129	#[derivative(Debug(format_with = "bounded::map_debug"))]130	pub users: BoundedBTreeMap<CrossAccountId, u128, ConstU32<MAX_ITEMS_PER_BATCH>>,131	#[derivative(Debug(format_with = "bounded::vec_debug"))]132	pub properties: CollectionPropertiesVec,133}134pub(crate) type SelfWeightOf<T> = <T as Config>::WeightInfo;135136/// Token data, stored independently from other data used to describe it137/// for the convenience of database access. Notably contains the token metadata.138#[struct_versioning::versioned(version = 2, upper)]139#[derive(Encode, Decode, Default, TypeInfo, MaxEncodedLen)]140pub struct ItemData {141	pub const_data: BoundedVec<u8, CustomDataLimit>,142143	#[version(..2)]144	pub variable_data: BoundedVec<u8, CustomDataLimit>,145}146147#[frame_support::pallet]148pub mod pallet {149	use super::*;150	use frame_support::{151		Blake2_128, Blake2_128Concat, Twox64Concat, pallet_prelude::*, storage::Key,152		traits::StorageVersion,153	};154	use frame_system::pallet_prelude::*;155	use up_data_structs::{CollectionId, TokenId};156	use super::weights::WeightInfo;157158	#[pallet::error]159	pub enum Error<T> {160		/// Not Refungible item data used to mint in Refungible collection.161		NotRefungibleDataUsedToMintFungibleCollectionToken,162		/// Maximum refungibility exceeded.163		WrongRefungiblePieces,164		/// Refungible token can't be repartitioned by user who isn't owns all pieces.165		RepartitionWhileNotOwningAllPieces,166		/// Refungible token can't nest other tokens.167		RefungibleDisallowsNesting,168		/// Setting item properties is not allowed.169		SettingPropertiesNotAllowed,170	}171172	#[pallet::config]173	pub trait Config:174		frame_system::Config + pallet_common::Config + pallet_structure::Config175	{176		type WeightInfo: WeightInfo;177	}178179	const STORAGE_VERSION: StorageVersion = StorageVersion::new(2);180181	#[pallet::pallet]182	#[pallet::storage_version(STORAGE_VERSION)]183	#[pallet::generate_store(pub(super) trait Store)]184	pub struct Pallet<T>(_);185186	/// Total amount of minted tokens in a collection.187	#[pallet::storage]188	pub type TokensMinted<T: Config> =189		StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;190191	/// Amount of tokens burnt in a collection.192	#[pallet::storage]193	pub type TokensBurnt<T: Config> =194		StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;195196	/// Token data, used to partially describe a token.197	// TODO: remove198	#[pallet::storage]199	#[deprecated(since = "0.2.0", note = "ItemData is no more contains usefull data")]200	pub type TokenData<T: Config> = StorageNMap<201		Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),202		Value = ItemData,203		QueryKind = ValueQuery,204	>;205206	/// Amount of pieces a refungible token is split into.207	#[pallet::storage]208	#[pallet::getter(fn token_properties)]209	pub type TokenProperties<T: Config> = StorageNMap<210		Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),211		Value = up_data_structs::Properties,212		QueryKind = ValueQuery,213		OnEmpty = up_data_structs::TokenProperties,214	>;215216	/// Total amount of pieces for token217	#[pallet::storage]218	pub type TotalSupply<T: Config> = StorageNMap<219		Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),220		Value = u128,221		QueryKind = ValueQuery,222	>;223224	/// Used to enumerate tokens owned by account.225	#[pallet::storage]226	pub type Owned<T: Config> = StorageNMap<227		Key = (228			Key<Twox64Concat, CollectionId>,229			Key<Blake2_128Concat, T::CrossAccountId>,230			Key<Twox64Concat, TokenId>,231		),232		Value = bool,233		QueryKind = ValueQuery,234	>;235236	/// Amount of tokens (not pieces) partially owned by an account within a collection.237	#[pallet::storage]238	pub type AccountBalance<T: Config> = StorageNMap<239		Key = (240			Key<Twox64Concat, CollectionId>,241			// Owner242			Key<Blake2_128Concat, T::CrossAccountId>,243		),244		Value = u32,245		QueryKind = ValueQuery,246	>;247248	/// Amount of token pieces owned by account.249	#[pallet::storage]250	pub type Balance<T: Config> = StorageNMap<251		Key = (252			Key<Twox64Concat, CollectionId>,253			Key<Twox64Concat, TokenId>,254			// Owner255			Key<Blake2_128Concat, T::CrossAccountId>,256		),257		Value = u128,258		QueryKind = ValueQuery,259	>;260261	/// Allowance set by a token owner for another user to perform one of certain transactions on a number of pieces of a token.262	#[pallet::storage]263	pub type Allowance<T: Config> = StorageNMap<264		Key = (265			Key<Twox64Concat, CollectionId>,266			Key<Twox64Concat, TokenId>,267			// Owner268			Key<Blake2_128, T::CrossAccountId>,269			// Spender270			Key<Blake2_128Concat, T::CrossAccountId>,271		),272		Value = u128,273		QueryKind = ValueQuery,274	>;275276	/// Operator set by a wallet owner that could perform certain transactions on all tokens in the wallet.277	#[pallet::storage]278	pub type CollectionAllowance<T: Config> = StorageNMap<279		Key = (280			Key<Twox64Concat, CollectionId>,281			Key<Blake2_128Concat, T::CrossAccountId>,282			Key<Blake2_128Concat, T::CrossAccountId>,283		),284		Value = bool,285		QueryKind = ValueQuery,286	>;287288	#[pallet::hooks]289	impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {290		fn on_runtime_upgrade() -> Weight {291			let storage_version = StorageVersion::get::<Pallet<T>>();292			if storage_version < StorageVersion::new(2) {293				#[allow(deprecated)]294				let _ = <TokenData<T>>::clear(u32::MAX, None);295			}296			StorageVersion::new(2).put::<Pallet<T>>();297298			Weight::zero()299		}300	}301}302303pub struct RefungibleHandle<T: Config>(pallet_common::CollectionHandle<T>);304impl<T: Config> RefungibleHandle<T> {305	pub fn cast(inner: pallet_common::CollectionHandle<T>) -> Self {306		Self(inner)307	}308	pub fn into_inner(self) -> pallet_common::CollectionHandle<T> {309		self.0310	}311	pub fn common_mut(&mut self) -> &mut pallet_common::CollectionHandle<T> {312		&mut self.0313	}314}315316impl<T: Config> Deref for RefungibleHandle<T> {317	type Target = pallet_common::CollectionHandle<T>;318319	fn deref(&self) -> &Self::Target {320		&self.0321	}322}323324impl<T: Config> WithRecorder<T> for RefungibleHandle<T> {325	fn recorder(&self) -> &pallet_evm_coder_substrate::SubstrateRecorder<T> {326		self.0.recorder()327	}328	fn into_recorder(self) -> pallet_evm_coder_substrate::SubstrateRecorder<T> {329		self.0.into_recorder()330	}331}332333impl<T: Config> Pallet<T> {334	/// Get number of RFT tokens in collection335	pub fn total_supply(collection: &RefungibleHandle<T>) -> u32 {336		<TokensMinted<T>>::get(collection.id) - <TokensBurnt<T>>::get(collection.id)337	}338339	/// Check that RFT token exists340	///341	/// - `token`: Token ID.342	pub fn token_exists(collection: &RefungibleHandle<T>, token: TokenId) -> bool {343		<TotalSupply<T>>::contains_key((collection.id, token))344	}345346	pub fn set_scoped_token_property(347		collection_id: CollectionId,348		token_id: TokenId,349		scope: PropertyScope,350		property: Property,351	) -> DispatchResult {352		TokenProperties::<T>::try_mutate((collection_id, token_id), |properties| {353			properties.try_scoped_set(scope, property.key, property.value)354		})355		.map_err(<CommonError<T>>::from)?;356357		Ok(())358	}359360	pub fn set_scoped_token_properties(361		collection_id: CollectionId,362		token_id: TokenId,363		scope: PropertyScope,364		properties: impl Iterator<Item = Property>,365	) -> DispatchResult {366		TokenProperties::<T>::try_mutate((collection_id, token_id), |stored_properties| {367			stored_properties.try_scoped_set_from_iter(scope, properties)368		})369		.map_err(<CommonError<T>>::from)?;370371		Ok(())372	}373}374375// unchecked calls skips any permission checks376impl<T: Config> Pallet<T> {377	/// Create RFT collection378	///379	/// `init_collection` will take non-refundable deposit for collection creation.380	///381	/// - `data`: Contains settings for collection limits and permissions.382	pub fn init_collection(383		owner: T::CrossAccountId,384		payer: T::CrossAccountId,385		data: CreateCollectionData<T::AccountId>,386		flags: CollectionFlags,387	) -> Result<CollectionId, DispatchError> {388		<PalletCommon<T>>::init_collection(owner, payer, data, flags)389	}390391	/// Destroy RFT collection392	///393	/// `destroy_collection` will throw error if collection contains any tokens.394	/// Only owner can destroy collection.395	pub fn destroy_collection(396		collection: RefungibleHandle<T>,397		sender: &T::CrossAccountId,398	) -> DispatchResult {399		let id = collection.id;400401		if Self::collection_has_tokens(id) {402			return Err(<CommonError<T>>::CantDestroyNotEmptyCollection.into());403		}404405		// =========406407		PalletCommon::destroy_collection(collection.0, sender)?;408409		<TokensMinted<T>>::remove(id);410		<TokensBurnt<T>>::remove(id);411		let _ = <TotalSupply<T>>::clear_prefix((id,), u32::MAX, None);412		let _ = <Balance<T>>::clear_prefix((id,), u32::MAX, None);413		let _ = <Allowance<T>>::clear_prefix((id,), u32::MAX, None);414		let _ = <Owned<T>>::clear_prefix((id,), u32::MAX, None);415		let _ = <AccountBalance<T>>::clear_prefix((id,), u32::MAX, None);416		Ok(())417	}418419	fn collection_has_tokens(collection_id: CollectionId) -> bool {420		<TotalSupply<T>>::iter_prefix((collection_id,))421			.next()422			.is_some()423	}424425	pub fn burn_token_unchecked(426		collection: &RefungibleHandle<T>,427		owner: &T::CrossAccountId,428		token_id: TokenId,429	) -> DispatchResult {430		let burnt = <TokensBurnt<T>>::get(collection.id)431			.checked_add(1)432			.ok_or(ArithmeticError::Overflow)?;433434		<TokensBurnt<T>>::insert(collection.id, burnt);435		<TokenProperties<T>>::remove((collection.id, token_id));436		<TotalSupply<T>>::remove((collection.id, token_id));437		let _ = <Balance<T>>::clear_prefix((collection.id, token_id), u32::MAX, None);438		let _ = <Allowance<T>>::clear_prefix((collection.id, token_id), u32::MAX, None);439		<PalletEvm<T>>::deposit_log(440			ERC721Events::Transfer {441				from: *owner.as_eth(),442				to: H160::default(),443				token_id: token_id.into(),444			}445			.to_log(collection_id_to_address(collection.id)),446		);447		Ok(())448	}449450	/// Burn RFT token pieces451	///452	/// `burn` will decrease total amount of token pieces and amount owned by sender.453	/// `burn` can be called even if there are multiple owners of the RFT token.454	/// If sender wouldn't have any pieces left after `burn` than she will stop being455	/// one of the owners of the token. If there is no account that owns any pieces of456	/// the token than token will be burned too.457	///458	/// - `amount`: Amount of token pieces to burn.459	/// - `token`: Token who's pieces should be burned460	/// - `collection`: Collection that contains the token461	pub fn burn(462		collection: &RefungibleHandle<T>,463		owner: &T::CrossAccountId,464		token: TokenId,465		amount: u128,466	) -> DispatchResult {467		if <Balance<T>>::get((collection.id, token, owner)) == 0 {468			return Err(<CommonError<T>>::TokenValueTooLow.into());469		}470471		let total_supply = <TotalSupply<T>>::get((collection.id, token))472			.checked_sub(amount)473			.ok_or(<CommonError<T>>::TokenValueTooLow)?;474475		// This was probally last owner of this token?476		if total_supply == 0 {477			// Ensure user actually owns this amount478			ensure!(479				<Balance<T>>::get((collection.id, token, owner)) == amount,480				<CommonError<T>>::TokenValueTooLow481			);482			let account_balance = <AccountBalance<T>>::get((collection.id, owner))483				.checked_sub(1)484				// Should not occur485				.ok_or(ArithmeticError::Underflow)?;486487			// =========488489			<Owned<T>>::remove((collection.id, owner, token));490			<PalletStructure<T>>::unnest_if_nested(owner, collection.id, token);491			<AccountBalance<T>>::insert((collection.id, owner), account_balance);492			Self::burn_token_unchecked(collection, owner, token)?;493			<PalletEvm<T>>::deposit_log(494				ERC20Events::Transfer {495					from: *owner.as_eth(),496					to: H160::default(),497					value: amount.into(),498				}499				.to_log(collection_id_to_address(collection.id)),500			);501			<PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(502				collection.id,503				token,504				owner.clone(),505				amount,506			));507			return Ok(());508		}509510		let balance = <Balance<T>>::get((collection.id, token, owner))511			.checked_sub(amount)512			.ok_or(<CommonError<T>>::TokenValueTooLow)?;513		let account_balance = if balance == 0 {514			<AccountBalance<T>>::get((collection.id, owner))515				.checked_sub(1)516				// Should not occur517				.ok_or(ArithmeticError::Underflow)?518		} else {519			0520		};521522		// =========523524		if balance == 0 {525			<Owned<T>>::remove((collection.id, owner, token));526			<PalletStructure<T>>::unnest_if_nested(owner, collection.id, token);527			<Balance<T>>::remove((collection.id, token, owner));528			<AccountBalance<T>>::insert((collection.id, owner), account_balance);529530			if let Some(user) = Self::token_owner(collection.id, token) {531				<PalletEvm<T>>::deposit_log(532					ERC721Events::Transfer {533						from: erc::ADDRESS_FOR_PARTIALLY_OWNED_TOKENS,534						to: *user.as_eth(),535						token_id: token.into(),536					}537					.to_log(collection_id_to_address(collection.id)),538				);539			}540		} else {541			<Balance<T>>::insert((collection.id, token, owner), balance);542		}543		<TotalSupply<T>>::insert((collection.id, token), total_supply);544545		<PalletEvm<T>>::deposit_log(546			ERC20Events::Transfer {547				from: *owner.as_eth(),548				to: H160::default(),549				value: amount.into(),550			}551			.to_log(T::EvmTokenAddressMapping::token_to_address(552				collection.id,553				token,554			)),555		);556		<PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(557			collection.id,558			token,559			owner.clone(),560			amount,561		));562		Ok(())563	}564565	#[transactional]566	fn modify_token_properties(567		collection: &RefungibleHandle<T>,568		sender: &T::CrossAccountId,569		token_id: TokenId,570		properties: impl Iterator<Item = (PropertyKey, Option<PropertyValue>)>,571		is_token_create: bool,572		nesting_budget: &dyn Budget,573	) -> DispatchResult {574		let is_collection_admin = || collection.is_owner_or_admin(sender);575		let is_token_owner = || -> Result<bool, DispatchError> {576			let balance = collection.balance(sender.clone(), token_id);577			let total_pieces: u128 =578				Self::total_pieces(collection.id, token_id).unwrap_or(u128::MAX);579			if balance != total_pieces {580				return Ok(false);581			}582583			let is_bundle_owner = <PalletStructure<T>>::check_indirectly_owned(584				sender.clone(),585				collection.id,586				token_id,587				None,588				nesting_budget,589			)?;590591			Ok(is_bundle_owner)592		};593594		for (key, value) in properties {595			let permission = <PalletCommon<T>>::property_permissions(collection.id)596				.get(&key)597				.cloned()598				.unwrap_or_else(PropertyPermission::none);599600			let is_property_exists = TokenProperties::<T>::get((collection.id, token_id))601				.get(&key)602				.is_some();603604			match permission {605				PropertyPermission { mutable: false, .. } if is_property_exists => {606					return Err(<CommonError<T>>::NoPermission.into());607				}608609				PropertyPermission {610					collection_admin,611					token_owner,612					..613				} => {614					//TODO: investigate threats during public minting.615					let is_token_create =616						is_token_create && (collection_admin || token_owner) && value.is_some();617					if !(is_token_create618						|| (collection_admin && is_collection_admin())619						|| (token_owner && is_token_owner()?))620					{621						fail!(<CommonError<T>>::NoPermission);622					}623				}624			}625626			match value {627				Some(value) => {628					<TokenProperties<T>>::try_mutate((collection.id, token_id), |properties| {629						properties.try_set(key.clone(), value)630					})631					.map_err(<CommonError<T>>::from)?;632633					<PalletCommon<T>>::deposit_event(CommonEvent::TokenPropertySet(634						collection.id,635						token_id,636						key,637					));638				}639				None => {640					<TokenProperties<T>>::try_mutate((collection.id, token_id), |properties| {641						properties.remove(&key)642					})643					.map_err(<CommonError<T>>::from)?;644645					<PalletCommon<T>>::deposit_event(CommonEvent::TokenPropertyDeleted(646						collection.id,647						token_id,648						key,649					));650				}651			}652653			<PalletEvm<T>>::deposit_log(654				CollectionHelpersEvents::TokenChanged {655					collection_id: collection_id_to_address(collection.id),656					token_id: token_id.into(),657				}658				.to_log(T::ContractAddress::get()),659			);660		}661662		Ok(())663	}664665	pub fn set_token_properties(666		collection: &RefungibleHandle<T>,667		sender: &T::CrossAccountId,668		token_id: TokenId,669		properties: impl Iterator<Item = Property>,670		is_token_create: bool,671		nesting_budget: &dyn Budget,672	) -> DispatchResult {673		Self::modify_token_properties(674			collection,675			sender,676			token_id,677			properties.map(|p| (p.key, Some(p.value))),678			is_token_create,679			nesting_budget,680		)681	}682683	pub fn set_token_property(684		collection: &RefungibleHandle<T>,685		sender: &T::CrossAccountId,686		token_id: TokenId,687		property: Property,688		nesting_budget: &dyn Budget,689	) -> DispatchResult {690		let is_token_create = false;691692		Self::set_token_properties(693			collection,694			sender,695			token_id,696			[property].into_iter(),697			is_token_create,698			nesting_budget,699		)700	}701702	pub fn delete_token_properties(703		collection: &RefungibleHandle<T>,704		sender: &T::CrossAccountId,705		token_id: TokenId,706		property_keys: impl Iterator<Item = PropertyKey>,707		nesting_budget: &dyn Budget,708	) -> DispatchResult {709		let is_token_create = false;710711		Self::modify_token_properties(712			collection,713			sender,714			token_id,715			property_keys.into_iter().map(|key| (key, None)),716			is_token_create,717			nesting_budget,718		)719	}720721	pub fn delete_token_property(722		collection: &RefungibleHandle<T>,723		sender: &T::CrossAccountId,724		token_id: TokenId,725		property_key: PropertyKey,726		nesting_budget: &dyn Budget,727	) -> DispatchResult {728		Self::delete_token_properties(729			collection,730			sender,731			token_id,732			[property_key].into_iter(),733			nesting_budget,734		)735	}736737	/// Transfer RFT token pieces from one account to another.738	///739	/// If the sender is no longer owns any pieces after the `transfer` than she stops being an owner of the token.740	///741	/// - `from`: Owner of token pieces to transfer.742	/// - `to`: Recepient of transfered token pieces.743	/// - `amount`: Amount of token pieces to transfer.744	/// - `token`: Token whos pieces should be transfered745	/// - `collection`: Collection that contains the token746	pub fn transfer(747		collection: &RefungibleHandle<T>,748		from: &T::CrossAccountId,749		to: &T::CrossAccountId,750		token: TokenId,751		amount: u128,752		nesting_budget: &dyn Budget,753	) -> DispatchResult {754		ensure!(755			collection.limits.transfers_enabled(),756			<CommonError<T>>::TransferNotAllowed757		);758759		if collection.permissions.access() == AccessMode::AllowList {760			collection.check_allowlist(from)?;761			collection.check_allowlist(to)?;762		}763		<PalletCommon<T>>::ensure_correct_receiver(to)?;764765		let initial_balance_from = <Balance<T>>::get((collection.id, token, from));766767		if initial_balance_from == 0 {768			return Err(<CommonError<T>>::TokenValueTooLow.into());769		}770771		let updated_balance_from = initial_balance_from772			.checked_sub(amount)773			.ok_or(<CommonError<T>>::TokenValueTooLow)?;774		let mut create_target = false;775		let from_to_differ = from != to;776		let updated_balance_to = if from != to && amount != 0 {777			let old_balance = <Balance<T>>::get((collection.id, token, to));778			if old_balance == 0 {779				create_target = true;780			}781			Some(782				old_balance783					.checked_add(amount)784					.ok_or(ArithmeticError::Overflow)?,785			)786		} else {787			None788		};789790		let account_balance_from = if updated_balance_from == 0 {791			Some(792				<AccountBalance<T>>::get((collection.id, from))793					.checked_sub(1)794					// Should not occur795					.ok_or(ArithmeticError::Underflow)?,796			)797		} else {798			None799		};800		// Account data is created in token, AccountBalance should be increased801		// But only if from != to as we shouldn't check overflow in this case802		let account_balance_to = if create_target && from_to_differ {803			let account_balance_to = <AccountBalance<T>>::get((collection.id, to))804				.checked_add(1)805				.ok_or(ArithmeticError::Overflow)?;806			ensure!(807				account_balance_to < collection.limits.account_token_ownership_limit(),808				<CommonError<T>>::AccountTokenLimitExceeded,809			);810811			Some(account_balance_to)812		} else {813			None814		};815816		// =========817818		if let Some(updated_balance_to) = updated_balance_to {819			// from != to && amount != 0820821			<PalletStructure<T>>::nest_if_sent_to_token(822				from.clone(),823				to,824				collection.id,825				token,826				nesting_budget,827			)?;828829			if updated_balance_from == 0 {830				<Balance<T>>::remove((collection.id, token, from));831				<PalletStructure<T>>::unnest_if_nested(from, collection.id, token);832			} else {833				<Balance<T>>::insert((collection.id, token, from), updated_balance_from);834			}835			<Balance<T>>::insert((collection.id, token, to), updated_balance_to);836			if let Some(account_balance_from) = account_balance_from {837				<AccountBalance<T>>::insert((collection.id, from), account_balance_from);838				<Owned<T>>::remove((collection.id, from, token));839			}840			if let Some(account_balance_to) = account_balance_to {841				<AccountBalance<T>>::insert((collection.id, to), account_balance_to);842				<Owned<T>>::insert((collection.id, to, token), true);843			}844		}845846		<PalletEvm<T>>::deposit_log(847			ERC20Events::Transfer {848				from: *from.as_eth(),849				to: *to.as_eth(),850				value: amount.into(),851			}852			.to_log(T::EvmTokenAddressMapping::token_to_address(853				collection.id,854				token,855			)),856		);857858		<PalletCommon<T>>::deposit_event(CommonEvent::Transfer(859			collection.id,860			token,861			from.clone(),862			to.clone(),863			amount,864		));865866		let total_supply = <TotalSupply<T>>::get((collection.id, token));867868		if amount == total_supply {869			// if token was fully owned by `from` and will be fully owned by `to` after transfer870			<PalletEvm<T>>::deposit_log(871				ERC721Events::Transfer {872					from: *from.as_eth(),873					to: *to.as_eth(),874					token_id: token.into(),875				}876				.to_log(collection_id_to_address(collection.id)),877			);878		} else if let Some(updated_balance_to) = updated_balance_to {879			// if `from` not equals `to`. This condition is needed to avoid sending event880			// when `from` fully owns token and sends part of token pieces to itself.881			if initial_balance_from == total_supply {882				// if token was fully owned by `from` and will be only partially owned by `to`883				// and `from` after transfer884				<PalletEvm<T>>::deposit_log(885					ERC721Events::Transfer {886						from: *from.as_eth(),887						to: erc::ADDRESS_FOR_PARTIALLY_OWNED_TOKENS,888						token_id: token.into(),889					}890					.to_log(collection_id_to_address(collection.id)),891				);892			} else if updated_balance_to == total_supply {893				// if token was partially owned by `from` and will be fully owned by `to` after transfer894				<PalletEvm<T>>::deposit_log(895					ERC721Events::Transfer {896						from: erc::ADDRESS_FOR_PARTIALLY_OWNED_TOKENS,897						to: *to.as_eth(),898						token_id: token.into(),899					}900					.to_log(collection_id_to_address(collection.id)),901				);902			}903		}904905		Ok(())906	}907908	/// Batched operation to create multiple RFT tokens.909	///910	/// Same as `create_item` but creates multiple tokens.911	///912	/// - `data`: Same as 'data` in `create_item` but contains data for multiple tokens.913	pub fn create_multiple_items(914		collection: &RefungibleHandle<T>,915		sender: &T::CrossAccountId,916		data: Vec<CreateItemData<T::CrossAccountId>>,917		nesting_budget: &dyn Budget,918	) -> DispatchResult {919		if !collection.is_owner_or_admin(sender) {920			ensure!(921				collection.permissions.mint_mode(),922				<CommonError<T>>::PublicMintingNotAllowed923			);924			collection.check_allowlist(sender)?;925926			for item in data.iter() {927				for user in item.users.keys() {928					collection.check_allowlist(user)?;929				}930			}931		}932933		for item in data.iter() {934			for (owner, _) in item.users.iter() {935				<PalletCommon<T>>::ensure_correct_receiver(owner)?;936			}937		}938939		// Total pieces per tokens940		let totals = data941			.iter()942			.map(|data| {943				Ok(data944					.users945					.iter()946					.map(|u| u.1)947					.try_fold(0u128, |acc, v| acc.checked_add(*v))948					.ok_or(ArithmeticError::Overflow)?)949			})950			.collect::<Result<Vec<_>, DispatchError>>()?;951		for total in &totals {952			ensure!(953				*total <= MAX_REFUNGIBLE_PIECES,954				<Error<T>>::WrongRefungiblePieces955			);956		}957958		let first_token_id = <TokensMinted<T>>::get(collection.id);959		let tokens_minted = first_token_id960			.checked_add(data.len() as u32)961			.ok_or(ArithmeticError::Overflow)?;962		ensure!(963			tokens_minted < collection.limits.token_limit(),964			<CommonError<T>>::CollectionTokenLimitExceeded965		);966967		let mut balances = BTreeMap::new();968		for data in &data {969			for owner in data.users.keys() {970				let balance = balances971					.entry(owner)972					.or_insert_with(|| <AccountBalance<T>>::get((collection.id, owner)));973				*balance = balance.checked_add(1).ok_or(ArithmeticError::Overflow)?;974975				ensure!(976					*balance <= collection.limits.account_token_ownership_limit(),977					<CommonError<T>>::AccountTokenLimitExceeded,978				);979			}980		}981982		for (i, token) in data.iter().enumerate() {983			let token_id = TokenId(first_token_id + i as u32 + 1);984			for (to, _) in token.users.iter() {985				<PalletStructure<T>>::check_nesting(986					sender.clone(),987					to,988					collection.id,989					token_id,990					nesting_budget,991				)?;992			}993		}994995		// =========996997		with_transaction(|| {998			for (i, data) in data.iter().enumerate() {999				let token_id = first_token_id + i as u32 + 1;1000				<TotalSupply<T>>::insert((collection.id, token_id), totals[i]);10011002				for (user, amount) in data.users.iter() {1003					if *amount == 0 {1004						continue;1005					}1006					<Balance<T>>::insert((collection.id, token_id, &user), amount);1007					<Owned<T>>::insert((collection.id, &user, TokenId(token_id)), true);1008					<PalletStructure<T>>::nest_if_sent_to_token_unchecked(1009						user,1010						collection.id,1011						TokenId(token_id),1012					);1013				}10141015				if let Err(e) = Self::set_token_properties(1016					collection,1017					sender,1018					TokenId(token_id),1019					data.properties.clone().into_iter(),1020					true,1021					nesting_budget,1022				) {1023					return TransactionOutcome::Rollback(Err(e));1024				}1025			}1026			TransactionOutcome::Commit(Ok(()))1027		})?;10281029		<TokensMinted<T>>::insert(collection.id, tokens_minted);10301031		for (account, balance) in balances {1032			<AccountBalance<T>>::insert((collection.id, account), balance);1033		}10341035		for (i, token) in data.into_iter().enumerate() {1036			let token_id = first_token_id + i as u32 + 1;10371038			let receivers = token1039				.users1040				.into_iter()1041				.filter(|(_, amount)| *amount > 0)1042				.collect::<Vec<_>>();10431044			if let [(user, _)] = receivers.as_slice() {1045				// if there is exactly one receiver1046				<PalletEvm<T>>::deposit_log(1047					ERC721Events::Transfer {1048						from: H160::default(),1049						to: *user.as_eth(),1050						token_id: token_id.into(),1051					}1052					.to_log(collection_id_to_address(collection.id)),1053				);1054			} else if let [_, ..] = receivers.as_slice() {1055				// if there is more than one receiver1056				<PalletEvm<T>>::deposit_log(1057					ERC721Events::Transfer {1058						from: H160::default(),1059						to: erc::ADDRESS_FOR_PARTIALLY_OWNED_TOKENS,1060						token_id: token_id.into(),1061					}1062					.to_log(collection_id_to_address(collection.id)),1063				);1064			}10651066			for (user, amount) in receivers.into_iter() {1067				<PalletEvm<T>>::deposit_log(1068					ERC20Events::Transfer {1069						from: H160::default(),1070						to: *user.as_eth(),1071						value: amount.into(),1072					}1073					.to_log(T::EvmTokenAddressMapping::token_to_address(1074						collection.id,1075						TokenId(token_id),1076					)),1077				);1078				<PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(1079					collection.id,1080					TokenId(token_id),1081					user,1082					amount,1083				));1084			}1085		}1086		Ok(())1087	}10881089	pub fn set_allowance_unchecked(1090		collection: &RefungibleHandle<T>,1091		sender: &T::CrossAccountId,1092		spender: &T::CrossAccountId,1093		token: TokenId,1094		amount: u128,1095	) {1096		if amount == 0 {1097			<Allowance<T>>::remove((collection.id, token, sender, spender));1098		} else {1099			<Allowance<T>>::insert((collection.id, token, sender, spender), amount);1100		}11011102		<PalletEvm<T>>::deposit_log(1103			ERC20Events::Approval {1104				owner: *sender.as_eth(),1105				spender: *spender.as_eth(),1106				value: amount.into(),1107			}1108			.to_log(T::EvmTokenAddressMapping::token_to_address(1109				collection.id,1110				token,1111			)),1112		);1113		<PalletCommon<T>>::deposit_event(CommonEvent::Approved(1114			collection.id,1115			token,1116			sender.clone(),1117			spender.clone(),1118			amount,1119		))1120	}11211122	/// Set allowance for the spender to `transfer` or `burn` sender's token pieces.1123	///1124	/// - `amount`: Amount of token pieces the spender is allowed to `transfer` or `burn.1125	pub fn set_allowance(1126		collection: &RefungibleHandle<T>,1127		sender: &T::CrossAccountId,1128		spender: &T::CrossAccountId,1129		token: TokenId,1130		amount: u128,1131	) -> DispatchResult {1132		if collection.permissions.access() == AccessMode::AllowList {1133			collection.check_allowlist(sender)?;1134			collection.check_allowlist(spender)?;1135		}11361137		<PalletCommon<T>>::ensure_correct_receiver(spender)?;11381139		if <Balance<T>>::get((collection.id, token, sender)) < amount {1140			ensure!(1141				collection.ignores_owned_amount(sender) && Self::token_exists(collection, token),1142				<CommonError<T>>::CantApproveMoreThanOwned1143			);1144		}11451146		// =========11471148		Self::set_allowance_unchecked(collection, sender, spender, token, amount);1149		Ok(())1150	}11511152	/// Returns allowance, which should be set after transaction1153	fn check_allowed(1154		collection: &RefungibleHandle<T>,1155		spender: &T::CrossAccountId,1156		from: &T::CrossAccountId,1157		token: TokenId,1158		amount: u128,1159		nesting_budget: &dyn Budget,1160	) -> Result<Option<u128>, DispatchError> {1161		if spender.conv_eq(from) {1162			return Ok(None);1163		}1164		if collection.permissions.access() == AccessMode::AllowList {1165			// `from`, `to` checked in [`transfer`]1166			collection.check_allowlist(spender)?;1167		}1168		if let Some(source) = T::CrossTokenAddressMapping::address_to_token(from) {1169			// TODO: should collection owner be allowed to perform this transfer?1170			ensure!(1171				<PalletStructure<T>>::check_indirectly_owned(1172					spender.clone(),1173					source.0,1174					source.1,1175					None,1176					nesting_budget1177				)?,1178				<CommonError<T>>::ApprovedValueTooLow,1179			);1180			return Ok(None);1181		}1182		let allowance =1183			<Allowance<T>>::get((collection.id, token, from, &spender)).checked_sub(amount);11841185		// Allowance (if any) would be reduced if spender is also wallet operator1186		if <CollectionAllowance<T>>::get((collection.id, from, spender)) {1187			return Ok(allowance);1188		}11891190		if allowance.is_none() {1191			ensure!(1192				collection.ignores_allowance(spender),1193				<CommonError<T>>::ApprovedValueTooLow1194			);1195		}1196		Ok(allowance)1197	}11981199	/// Transfer RFT token pieces from one account to another.1200	///1201	/// Same as the [`transfer`] but spender doesn't needs to be an owner of the token pieces.1202	/// The owner should set allowance for the spender to transfer pieces.1203	///1204	/// [`transfer`]: struct.Pallet.html#method.transfer1205	pub fn transfer_from(1206		collection: &RefungibleHandle<T>,1207		spender: &T::CrossAccountId,1208		from: &T::CrossAccountId,1209		to: &T::CrossAccountId,1210		token: TokenId,1211		amount: u128,1212		nesting_budget: &dyn Budget,1213	) -> DispatchResult {1214		let allowance =1215			Self::check_allowed(collection, spender, from, token, amount, nesting_budget)?;12161217		// =========12181219		Self::transfer(collection, from, to, token, amount, nesting_budget)?;1220		if let Some(allowance) = allowance {1221			Self::set_allowance_unchecked(collection, from, spender, token, allowance);1222		}1223		Ok(())1224	}12251226	/// Burn RFT token pieces from the account.1227	///1228	/// Same as the [`burn`] but spender doesn't need to be an owner of the token pieces. The owner should1229	/// set allowance for the spender to burn pieces1230	///1231	/// [`burn`]: struct.Pallet.html#method.burn1232	pub fn burn_from(1233		collection: &RefungibleHandle<T>,1234		spender: &T::CrossAccountId,1235		from: &T::CrossAccountId,1236		token: TokenId,1237		amount: u128,1238		nesting_budget: &dyn Budget,1239	) -> DispatchResult {1240		let allowance =1241			Self::check_allowed(collection, spender, from, token, amount, nesting_budget)?;12421243		// =========12441245		Self::burn(collection, from, token, amount)?;1246		if let Some(allowance) = allowance {1247			Self::set_allowance_unchecked(collection, from, spender, token, allowance);1248		}1249		Ok(())1250	}12511252	/// Create RFT token.1253	///1254	/// The sender should be the owner/admin of the collection or collection should be configured1255	/// to allow public minting.1256	///1257	/// - `data`: Contains list of users who will become the owners of the token pieces and amount1258	///   of token pieces they will receive.1259	pub fn create_item(1260		collection: &RefungibleHandle<T>,1261		sender: &T::CrossAccountId,1262		data: CreateItemData<T::CrossAccountId>,1263		nesting_budget: &dyn Budget,1264	) -> DispatchResult {1265		Self::create_multiple_items(collection, sender, vec![data], nesting_budget)1266	}12671268	/// Repartition RFT token.1269	///1270	/// `repartition` will set token balance of the sender and total amount of token pieces.1271	/// Sender should own all of the token pieces. `repartition' could be done even if some1272	/// token pieces were burned before.1273	///1274	/// - `amount`: Total amount of token pieces that the token will have after `repartition`.1275	pub fn repartition(1276		collection: &RefungibleHandle<T>,1277		owner: &T::CrossAccountId,1278		token: TokenId,1279		amount: u128,1280	) -> DispatchResult {1281		ensure!(1282			amount <= MAX_REFUNGIBLE_PIECES,1283			<Error<T>>::WrongRefungiblePieces1284		);1285		ensure!(amount > 0, <CommonError<T>>::TokenValueTooLow);1286		// Ensure user owns all pieces1287		let total_pieces = Self::total_pieces(collection.id, token).unwrap_or(u128::MAX);1288		let balance = <Balance<T>>::get((collection.id, token, owner));1289		ensure!(1290			total_pieces == balance,1291			<Error<T>>::RepartitionWhileNotOwningAllPieces1292		);12931294		<Balance<T>>::insert((collection.id, token, owner), amount);1295		<TotalSupply<T>>::insert((collection.id, token), amount);12961297		if amount > total_pieces {1298			let mint_amount = amount - total_pieces;1299			<PalletEvm<T>>::deposit_log(1300				ERC20Events::Transfer {1301					from: H160::default(),1302					to: *owner.as_eth(),1303					value: mint_amount.into(),1304				}1305				.to_log(T::EvmTokenAddressMapping::token_to_address(1306					collection.id,1307					token,1308				)),1309			);1310			<PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(1311				collection.id,1312				token,1313				owner.clone(),1314				mint_amount,1315			));1316		} else if total_pieces > amount {1317			let burn_amount = total_pieces - amount;1318			<PalletEvm<T>>::deposit_log(1319				ERC20Events::Transfer {1320					from: *owner.as_eth(),1321					to: H160::default(),1322					value: burn_amount.into(),1323				}1324				.to_log(T::EvmTokenAddressMapping::token_to_address(1325					collection.id,1326					token,1327				)),1328			);1329			<PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(1330				collection.id,1331				token,1332				owner.clone(),1333				burn_amount,1334			));1335		}13361337		Ok(())1338	}13391340	fn token_owner(collection_id: CollectionId, token_id: TokenId) -> Option<T::CrossAccountId> {1341		let mut owner = None;1342		let mut count = 0;1343		for key in Balance::<T>::iter_key_prefix((collection_id, token_id)) {1344			count += 1;1345			if count > 1 {1346				return None;1347			}1348			owner = Some(key);1349		}1350		owner1351	}13521353	fn total_pieces(collection_id: CollectionId, token_id: TokenId) -> Option<u128> {1354		<TotalSupply<T>>::try_get((collection_id, token_id)).ok()1355	}13561357	pub fn set_collection_properties(1358		collection: &RefungibleHandle<T>,1359		sender: &T::CrossAccountId,1360		properties: Vec<Property>,1361	) -> DispatchResult {1362		<PalletCommon<T>>::set_collection_properties(collection, sender, properties)1363	}13641365	pub fn delete_collection_properties(1366		collection: &RefungibleHandle<T>,1367		sender: &T::CrossAccountId,1368		property_keys: Vec<PropertyKey>,1369	) -> DispatchResult {1370		<PalletCommon<T>>::delete_collection_properties(collection, sender, property_keys)1371	}13721373	pub fn set_token_property_permissions(1374		collection: &RefungibleHandle<T>,1375		sender: &T::CrossAccountId,1376		property_permissions: Vec<PropertyKeyPermission>,1377	) -> DispatchResult {1378		<PalletCommon<T>>::set_token_property_permissions(collection, sender, property_permissions)1379	}13801381	pub fn set_scoped_token_property_permissions(1382		collection: &RefungibleHandle<T>,1383		sender: &T::CrossAccountId,1384		scope: PropertyScope,1385		property_permissions: Vec<PropertyKeyPermission>,1386	) -> DispatchResult {1387		<PalletCommon<T>>::set_scoped_token_property_permissions(1388			collection,1389			sender,1390			scope,1391			property_permissions,1392		)1393	}13941395	/// Returns 10 token in no particular order.1396	///1397	/// There is no direct way to get token holders in ascending order,1398	/// since `iter_prefix` returns values in no particular order.1399	/// Therefore, getting the 10 largest holders with a large value of holders1400	/// can lead to impact memory allocation + sorting with  `n * log (n)`.1401	pub fn token_owners(1402		collection_id: CollectionId,1403		token: TokenId,1404	) -> Option<Vec<T::CrossAccountId>> {1405		let res: Vec<T::CrossAccountId> = <Balance<T>>::iter_prefix((collection_id, token))1406			.map(|(owner, _amount)| owner)1407			.take(10)1408			.collect();14091410		if res.is_empty() {1411			None1412		} else {1413			Some(res)1414		}1415	}14161417	/// Sets or unsets the approval of a given operator.1418	///1419	/// The `operator` is allowed to transfer all token pieces of the `owner` on their behalf.1420	/// - `owner`: Token owner1421	/// - `operator`: Operator1422	/// - `approve`: Should operator status be granted or revoked?1423	pub fn set_allowance_for_all(1424		collection: &RefungibleHandle<T>,1425		owner: &T::CrossAccountId,1426		operator: &T::CrossAccountId,1427		approve: bool,1428	) -> DispatchResult {1429		if collection.permissions.access() == AccessMode::AllowList {1430			collection.check_allowlist(owner)?;1431			collection.check_allowlist(operator)?;1432		}14331434		<PalletCommon<T>>::ensure_correct_receiver(operator)?;14351436		// =========14371438		<CollectionAllowance<T>>::insert((collection.id, owner, operator), approve);1439		<PalletEvm<T>>::deposit_log(1440			ERC721Events::ApprovalForAll {1441				owner: *owner.as_eth(),1442				operator: *operator.as_eth(),1443				approved: approve,1444			}1445			.to_log(collection_id_to_address(collection.id)),1446		);1447		<PalletCommon<T>>::deposit_event(CommonEvent::ApprovedForAll(1448			collection.id,1449			owner.clone(),1450			operator.clone(),1451			approve,1452		));1453		Ok(())1454	}14551456	/// Tells whether the given `owner` approves the `operator`.1457	pub fn allowance_for_all(1458		collection: &RefungibleHandle<T>,1459		owner: &T::CrossAccountId,1460		operator: &T::CrossAccountId,1461	) -> bool {1462		<CollectionAllowance<T>>::get((collection.id, owner, operator))1463	}1464}