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

difftreelog

chore add transfer event for `burn` and `create_multiple_items`

Grigoriy Simonov2022-08-03parent: #bb6d71b.patch.diff
in: master

3 files changed

modifiedpallets/refungible/src/lib.rsdiffbeforeafterboth
before · pallets/refungible/src/lib.rs
1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617//! # Refungible Pallet18//!19//! The Refungible pallet provides functionality for handling refungible collections and tokens.20//!21//! - [`Config`]22//! - [`RefungibleHandle`]23//! - [`Pallet`]24//! - [`CommonWeights`](common::CommonWeights)25//!26//! ## Overview27//!28//! The Refungible pallet provides functions for:29//!30//! - RFT collection creation and removal31//! - Minting and burning of RFT tokens32//! - Partition and repartition of RFT tokens33//! - Retrieving number of pieces of RFT token34//! - Retrieving account balances35//! - Transfering RFT token pieces36//! - Burning RFT token pieces37//! - Setting and checking allowance for RFT tokens38//!39//! ### Terminology40//!41//! - **RFT token:** Non fungible token that was partitioned to pieces. If an account owns all42//!   of the RFT token pieces than it owns the RFT token and can repartition it.43//!44//! - **RFT Collection:** A collection of RFT tokens. All RFT tokens are part of a collection.45//!   Each collection has its own settings and set of permissions.46//!47//! - **RFT token piece:** A fungible part of an RFT token.48//!49//! - **Balance:** RFT token pieces owned by an account50//!51//! - **Allowance:** Maximum number of RFT token pieces that one account is allowed to52//!   transfer from the balance of another account53//!54//! - **Burning:** The process of “deleting” a token from a collection or removing token pieces from55//!   an account balance.56//!57//! ### Implementations58//!59//! The Refungible pallet provides implementations for the following traits. If these traits provide60//! the functionality that you need, then you can avoid coupling with the Refungible pallet.61//!62//! - [`CommonWeightInfo`](pallet_common::CommonWeightInfo): Functions for retrieval of transaction weight63//! - [`CommonCollectionOperations`](pallet_common::CommonCollectionOperations): Functions for dealing64//!   with collections65//! - [`RefungibleExtensions`](pallet_common::RefungibleExtensions): Functions specific for refungible66//!   collection67//!68//! ## Interface69//!70//! ### Dispatchable Functions71//!72//! - `init_collection` - Create RFT collection. RFT collection can be configured to allow or deny access for73//!   some accounts.74//! - `destroy_collection` - Destroy exising RFT collection. There should be no tokens in the collection.75//! - `burn` - Burn some amount of RFT token pieces owned by account. Burns the RFT token if no pieces left.76//! - `transfer` - Transfer some amount of RFT token pieces. Transfers should be enabled for RFT collection.77//!   Nests the RFT token if RFT token pieces are sent to another token.78//! - `create_item` - Mint RFT token in collection. Sender should have permission to mint tokens.79//! - `set_allowance` - Set allowance for another account to transfer balance from sender's account.80//! - `repartition` - Repartition token to selected number of pieces. Sender should own all existing pieces.81//!82//! ## Assumptions83//!84//! * Total number of pieces for one token shouldn't exceed `up_data_structs::MAX_REFUNGIBLE_PIECES`.85//! * Total number of tokens of all types shouldn't be greater than `up_data_structs::MAX_TOKEN_PREFIX_LENGTH`.86//! * Sender should be in collection's allow list to perform operations on tokens.8788#![cfg_attr(not(feature = "std"), no_std)]8990use crate::erc_token::ERC20Events;91use crate::erc::ERC721Events;9293use codec::{Encode, Decode, MaxEncodedLen};94use core::ops::Deref;95use evm_coder::ToLog;96use frame_support::{BoundedVec, ensure, fail, storage::with_transaction, transactional};97use pallet_evm::{account::CrossAccountId, Pallet as PalletEvm};98use pallet_evm_coder_substrate::WithRecorder;99use pallet_common::{100	CommonCollectionOperations, Error as CommonError, Event as CommonEvent,101	eth::collection_id_to_address, Pallet as PalletCommon,102};103use pallet_structure::Pallet as PalletStructure;104use scale_info::TypeInfo;105use sp_core::H160;106use sp_runtime::{ArithmeticError, DispatchError, DispatchResult, TransactionOutcome};107use sp_std::{vec::Vec, vec, collections::btree_map::BTreeMap};108use up_data_structs::{109	AccessMode, budget::Budget, CollectionId, CreateCollectionData, CreateRefungibleExData,110	CustomDataLimit, mapping::TokenAddressMapping, MAX_REFUNGIBLE_PIECES, TokenId, Property,111	PropertyKey, PropertyKeyPermission, PropertyPermission, PropertyScope, PropertyValue,112	TrySetProperty,113};114115pub use pallet::*;116#[cfg(feature = "runtime-benchmarks")]117pub mod benchmarking;118pub mod common;119pub mod erc;120pub mod erc_token;121pub mod weights;122123pub type CreateItemData<T> =124	CreateRefungibleExData<<T as pallet_evm::account::Config>::CrossAccountId>;125pub(crate) type SelfWeightOf<T> = <T as Config>::WeightInfo;126127/// Token data, stored independently from other data used to describe it128/// for the convenience of database access. Notably contains the token metadata.129#[struct_versioning::versioned(version = 2, upper)]130#[derive(Encode, Decode, Default, TypeInfo, MaxEncodedLen)]131pub struct ItemData {132	pub const_data: BoundedVec<u8, CustomDataLimit>,133134	#[version(..2)]135	pub variable_data: BoundedVec<u8, CustomDataLimit>,136}137138#[frame_support::pallet]139pub mod pallet {140	use super::*;141	use frame_support::{142		Blake2_128, Blake2_128Concat, Twox64Concat, pallet_prelude::*, storage::Key,143		traits::StorageVersion,144	};145	use frame_system::pallet_prelude::*;146	use up_data_structs::{CollectionId, TokenId};147	use super::weights::WeightInfo;148149	#[pallet::error]150	pub enum Error<T> {151		/// Not Refungible item data used to mint in Refungible collection.152		NotRefungibleDataUsedToMintFungibleCollectionToken,153		/// Maximum refungibility exceeded.154		WrongRefungiblePieces,155		/// Refungible token can't be repartitioned by user who isn't owns all pieces.156		RepartitionWhileNotOwningAllPieces,157		/// Refungible token can't nest other tokens.158		RefungibleDisallowsNesting,159		/// Setting item properties is not allowed.160		SettingPropertiesNotAllowed,161	}162163	#[pallet::config]164	pub trait Config:165		frame_system::Config + pallet_common::Config + pallet_structure::Config166	{167		type WeightInfo: WeightInfo;168	}169170	const STORAGE_VERSION: StorageVersion = StorageVersion::new(1);171172	#[pallet::pallet]173	#[pallet::storage_version(STORAGE_VERSION)]174	#[pallet::generate_store(pub(super) trait Store)]175	pub struct Pallet<T>(_);176177	/// Total amount of minted tokens in a collection.178	#[pallet::storage]179	pub type TokensMinted<T: Config> =180		StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;181182	/// Amount of tokens burnt in a collection.183	#[pallet::storage]184	pub type TokensBurnt<T: Config> =185		StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;186187	/// Token data, used to partially describe a token.188	#[pallet::storage]189	pub type TokenData<T: Config> = StorageNMap<190		Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),191		Value = ItemData,192		QueryKind = ValueQuery,193	>;194195	/// Amount of pieces a refungible token is split into.196	#[pallet::storage]197	#[pallet::getter(fn token_properties)]198	pub type TokenProperties<T: Config> = StorageNMap<199		Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),200		Value = up_data_structs::Properties,201		QueryKind = ValueQuery,202		OnEmpty = up_data_structs::TokenProperties,203	>;204205	/// Total amount of pieces for token206	#[pallet::storage]207	pub type TotalSupply<T: Config> = StorageNMap<208		Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),209		Value = u128,210		QueryKind = ValueQuery,211	>;212213	/// Used to enumerate tokens owned by account.214	#[pallet::storage]215	pub type Owned<T: Config> = StorageNMap<216		Key = (217			Key<Twox64Concat, CollectionId>,218			Key<Blake2_128Concat, T::CrossAccountId>,219			Key<Twox64Concat, TokenId>,220		),221		Value = bool,222		QueryKind = ValueQuery,223	>;224225	/// Amount of tokens (not pieces) partially owned by an account within a collection.226	#[pallet::storage]227	pub type AccountBalance<T: Config> = StorageNMap<228		Key = (229			Key<Twox64Concat, CollectionId>,230			// Owner231			Key<Blake2_128Concat, T::CrossAccountId>,232		),233		Value = u32,234		QueryKind = ValueQuery,235	>;236237	/// Amount of token pieces owned by account.238	#[pallet::storage]239	pub type Balance<T: Config> = StorageNMap<240		Key = (241			Key<Twox64Concat, CollectionId>,242			Key<Twox64Concat, TokenId>,243			// Owner244			Key<Blake2_128Concat, T::CrossAccountId>,245		),246		Value = u128,247		QueryKind = ValueQuery,248	>;249250	/// Allowance set by a token owner for another user to perform one of certain transactions on a number of pieces of a token.251	#[pallet::storage]252	pub type Allowance<T: Config> = StorageNMap<253		Key = (254			Key<Twox64Concat, CollectionId>,255			Key<Twox64Concat, TokenId>,256			// Owner257			Key<Blake2_128, T::CrossAccountId>,258			// Spender259			Key<Blake2_128Concat, T::CrossAccountId>,260		),261		Value = u128,262		QueryKind = ValueQuery,263	>;264265	#[pallet::hooks]266	impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {267		fn on_runtime_upgrade() -> Weight {268			if StorageVersion::get::<Pallet<T>>() < StorageVersion::new(1) {269				<TokenData<T>>::translate_values::<ItemDataVersion1, _>(|v| {270					Some(<ItemDataVersion2>::from(v))271				})272			}273274			0275		}276	}277}278279pub struct RefungibleHandle<T: Config>(pallet_common::CollectionHandle<T>);280impl<T: Config> RefungibleHandle<T> {281	pub fn cast(inner: pallet_common::CollectionHandle<T>) -> Self {282		Self(inner)283	}284	pub fn into_inner(self) -> pallet_common::CollectionHandle<T> {285		self.0286	}287	pub fn common_mut(&mut self) -> &mut pallet_common::CollectionHandle<T> {288		&mut self.0289	}290}291292impl<T: Config> Deref for RefungibleHandle<T> {293	type Target = pallet_common::CollectionHandle<T>;294295	fn deref(&self) -> &Self::Target {296		&self.0297	}298}299300impl<T: Config> WithRecorder<T> for RefungibleHandle<T> {301	fn recorder(&self) -> &pallet_evm_coder_substrate::SubstrateRecorder<T> {302		self.0.recorder()303	}304	fn into_recorder(self) -> pallet_evm_coder_substrate::SubstrateRecorder<T> {305		self.0.into_recorder()306	}307}308309impl<T: Config> Pallet<T> {310	/// Get number of RFT tokens in collection311	pub fn total_supply(collection: &RefungibleHandle<T>) -> u32 {312		<TokensMinted<T>>::get(collection.id) - <TokensBurnt<T>>::get(collection.id)313	}314315	/// Check that RFT token exists316	///317	/// - `token`: Token ID.318	pub fn token_exists(collection: &RefungibleHandle<T>, token: TokenId) -> bool {319		<TotalSupply<T>>::contains_key((collection.id, token))320	}321322	pub fn set_scoped_token_property(323		collection_id: CollectionId,324		token_id: TokenId,325		scope: PropertyScope,326		property: Property,327	) -> DispatchResult {328		TokenProperties::<T>::try_mutate((collection_id, token_id), |properties| {329			properties.try_scoped_set(scope, property.key, property.value)330		})331		.map_err(<CommonError<T>>::from)?;332333		Ok(())334	}335336	pub fn set_scoped_token_properties(337		collection_id: CollectionId,338		token_id: TokenId,339		scope: PropertyScope,340		properties: impl Iterator<Item = Property>,341	) -> DispatchResult {342		TokenProperties::<T>::try_mutate((collection_id, token_id), |stored_properties| {343			stored_properties.try_scoped_set_from_iter(scope, properties)344		})345		.map_err(<CommonError<T>>::from)?;346347		Ok(())348	}349}350351// unchecked calls skips any permission checks352impl<T: Config> Pallet<T> {353	/// Create RFT collection354	///355	/// `init_collection` will take non-refundable deposit for collection creation.356	///357	/// - `data`: Contains settings for collection limits and permissions.358	pub fn init_collection(359		owner: T::CrossAccountId,360		data: CreateCollectionData<T::AccountId>,361	) -> Result<CollectionId, DispatchError> {362		<PalletCommon<T>>::init_collection(owner, data, false)363	}364365	/// Destroy RFT collection366	///367	/// `destroy_collection` will throw error if collection contains any tokens.368	/// Only owner can destroy collection.369	pub fn destroy_collection(370		collection: RefungibleHandle<T>,371		sender: &T::CrossAccountId,372	) -> DispatchResult {373		let id = collection.id;374375		if Self::collection_has_tokens(id) {376			return Err(<CommonError<T>>::CantDestroyNotEmptyCollection.into());377		}378379		// =========380381		PalletCommon::destroy_collection(collection.0, sender)?;382383		<TokensMinted<T>>::remove(id);384		<TokensBurnt<T>>::remove(id);385		<TokenData<T>>::remove_prefix((id,), None);386		<TotalSupply<T>>::remove_prefix((id,), None);387		<Balance<T>>::remove_prefix((id,), None);388		<Allowance<T>>::remove_prefix((id,), None);389		<Owned<T>>::remove_prefix((id,), None);390		<AccountBalance<T>>::remove_prefix((id,), None);391		Ok(())392	}393394	fn collection_has_tokens(collection_id: CollectionId) -> bool {395		<TokenData<T>>::iter_prefix((collection_id,))396			.next()397			.is_some()398	}399400	pub fn burn_token_unchecked(401		collection: &RefungibleHandle<T>,402		token_id: TokenId,403	) -> DispatchResult {404		let burnt = <TokensBurnt<T>>::get(collection.id)405			.checked_add(1)406			.ok_or(ArithmeticError::Overflow)?;407408		<TokensBurnt<T>>::insert(collection.id, burnt);409		<TokenData<T>>::remove((collection.id, token_id));410		<TokenProperties<T>>::remove((collection.id, token_id));411		<TotalSupply<T>>::remove((collection.id, token_id));412		<Balance<T>>::remove_prefix((collection.id, token_id), None);413		<Allowance<T>>::remove_prefix((collection.id, token_id), None);414		// TODO: ERC721 transfer event415		Ok(())416	}417418	/// Burn RFT token pieces419	///420	/// `burn` will decrease total amount of token pieces and amount owned by sender.421	/// `burn` can be called even if there are multiple owners of the RFT token.422	/// If sender wouldn't have any pieces left after `burn` than she will stop being423	/// one of the owners of the token. If there is no account that owns any pieces of424	/// the token than token will be burned too.425	///426	/// - `amount`: Amount of token pieces to burn.427	/// - `token`: Token who's pieces should be burned428	/// - `collection`: Collection that contains the token429	pub fn burn(430		collection: &RefungibleHandle<T>,431		owner: &T::CrossAccountId,432		token: TokenId,433		amount: u128,434	) -> DispatchResult {435		let total_supply = <TotalSupply<T>>::get((collection.id, token))436			.checked_sub(amount)437			.ok_or(<CommonError<T>>::TokenValueTooLow)?;438439		// This was probally last owner of this token?440		if total_supply == 0 {441			// Ensure user actually owns this amount442			ensure!(443				<Balance<T>>::get((collection.id, token, owner)) == amount,444				<CommonError<T>>::TokenValueTooLow445			);446			let account_balance = <AccountBalance<T>>::get((collection.id, owner))447				.checked_sub(1)448				// Should not occur449				.ok_or(ArithmeticError::Underflow)?;450451			// =========452453			<Owned<T>>::remove((collection.id, owner, token));454			<PalletStructure<T>>::unnest_if_nested(owner, collection.id, token);455			<AccountBalance<T>>::insert((collection.id, owner), account_balance);456			Self::burn_token_unchecked(collection, token)?;457			<PalletEvm<T>>::deposit_log(458				ERC721Events::Transfer {459					from: *owner.as_eth(),460					to: H160::default(),461					token_id: token.into(),462				}463				.to_log(collection_id_to_address(collection.id)),464			);465			<PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(466				collection.id,467				token,468				owner.clone(),469				amount,470			));471			return Ok(());472		}473474		let balance = <Balance<T>>::get((collection.id, token, owner))475			.checked_sub(amount)476			.ok_or(<CommonError<T>>::TokenValueTooLow)?;477		let account_balance = if balance == 0 {478			<AccountBalance<T>>::get((collection.id, owner))479				.checked_sub(1)480				// Should not occur481				.ok_or(ArithmeticError::Underflow)?482		} else {483			0484		};485486		// =========487488		if balance == 0 {489			<Owned<T>>::remove((collection.id, owner, token));490			<PalletStructure<T>>::unnest_if_nested(owner, collection.id, token);491			<Balance<T>>::remove((collection.id, token, owner));492			<AccountBalance<T>>::insert((collection.id, owner), account_balance);493		} else {494			<Balance<T>>::insert((collection.id, token, owner), balance);495		}496		<TotalSupply<T>>::insert((collection.id, token), total_supply);497498		<PalletEvm<T>>::deposit_log(499			ERC20Events::Transfer {500				from: *owner.as_eth(),501				to: H160::default(),502				value: amount.into(),503			}504			.to_log(T::EvmTokenAddressMapping::token_to_address(505				collection.id,506				token,507			)),508		);509		<PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(510			collection.id,511			token,512			owner.clone(),513			amount,514		));515		Ok(())516	}517518	#[transactional]519	fn modify_token_properties(520		collection: &RefungibleHandle<T>,521		sender: &T::CrossAccountId,522		token_id: TokenId,523		properties: impl Iterator<Item = (PropertyKey, Option<PropertyValue>)>,524		is_token_create: bool,525		nesting_budget: &dyn Budget,526	) -> DispatchResult {527		let is_collection_admin = || collection.is_owner_or_admin(sender);528		let is_token_owner = || -> Result<bool, DispatchError> {529			let balance = collection.balance(sender.clone(), token_id);530			let total_pieces: u128 =531				Self::total_pieces(collection.id, token_id).unwrap_or(u128::MAX);532			if balance != total_pieces {533				return Ok(false);534			}535536			let is_bundle_owner = <PalletStructure<T>>::check_indirectly_owned(537				sender.clone(),538				collection.id,539				token_id,540				None,541				nesting_budget,542			)?;543544			Ok(is_bundle_owner)545		};546547		for (key, value) in properties {548			let permission = <PalletCommon<T>>::property_permissions(collection.id)549				.get(&key)550				.cloned()551				.unwrap_or_else(PropertyPermission::none);552553			let is_property_exists = TokenProperties::<T>::get((collection.id, token_id))554				.get(&key)555				.is_some();556557			match permission {558				PropertyPermission { mutable: false, .. } if is_property_exists => {559					return Err(<CommonError<T>>::NoPermission.into());560				}561562				PropertyPermission {563					collection_admin,564					token_owner,565					..566				} => {567					//TODO: investigate threats during public minting.568					let is_token_create =569						is_token_create && (collection_admin || token_owner) && value.is_some();570					if !(is_token_create571						|| (collection_admin && is_collection_admin())572						|| (token_owner && is_token_owner()?))573					{574						fail!(<CommonError<T>>::NoPermission);575					}576				}577			}578579			match value {580				Some(value) => {581					<TokenProperties<T>>::try_mutate((collection.id, token_id), |properties| {582						properties.try_set(key.clone(), value)583					})584					.map_err(<CommonError<T>>::from)?;585586					<PalletCommon<T>>::deposit_event(CommonEvent::TokenPropertySet(587						collection.id,588						token_id,589						key,590					));591				}592				None => {593					<TokenProperties<T>>::try_mutate((collection.id, token_id), |properties| {594						properties.remove(&key)595					})596					.map_err(<CommonError<T>>::from)?;597598					<PalletCommon<T>>::deposit_event(CommonEvent::TokenPropertyDeleted(599						collection.id,600						token_id,601						key,602					));603				}604			}605		}606607		Ok(())608	}609610	pub fn set_token_properties(611		collection: &RefungibleHandle<T>,612		sender: &T::CrossAccountId,613		token_id: TokenId,614		properties: impl Iterator<Item = Property>,615		is_token_create: bool,616		nesting_budget: &dyn Budget,617	) -> DispatchResult {618		Self::modify_token_properties(619			collection,620			sender,621			token_id,622			properties.map(|p| (p.key, Some(p.value))),623			is_token_create,624			nesting_budget,625		)626	}627628	pub fn set_token_property(629		collection: &RefungibleHandle<T>,630		sender: &T::CrossAccountId,631		token_id: TokenId,632		property: Property,633		nesting_budget: &dyn Budget,634	) -> DispatchResult {635		let is_token_create = false;636637		Self::set_token_properties(638			collection,639			sender,640			token_id,641			[property].into_iter(),642			is_token_create,643			nesting_budget,644		)645	}646647	pub fn delete_token_properties(648		collection: &RefungibleHandle<T>,649		sender: &T::CrossAccountId,650		token_id: TokenId,651		property_keys: impl Iterator<Item = PropertyKey>,652		nesting_budget: &dyn Budget,653	) -> DispatchResult {654		let is_token_create = false;655656		Self::modify_token_properties(657			collection,658			sender,659			token_id,660			property_keys.into_iter().map(|key| (key, None)),661			is_token_create,662			nesting_budget,663		)664	}665666	pub fn delete_token_property(667		collection: &RefungibleHandle<T>,668		sender: &T::CrossAccountId,669		token_id: TokenId,670		property_key: PropertyKey,671		nesting_budget: &dyn Budget,672	) -> DispatchResult {673		Self::delete_token_properties(674			collection,675			sender,676			token_id,677			[property_key].into_iter(),678			nesting_budget,679		)680	}681682	/// Transfer RFT token pieces from one account to another.683	///684	/// If the sender is no longer owns any pieces after the `transfer` than she stops being an owner of the token.685	///686	/// - `from`: Owner of token pieces to transfer.687	/// - `to`: Recepient of transfered token pieces.688	/// - `amount`: Amount of token pieces to transfer.689	/// - `token`: Token whos pieces should be transfered690	/// - `collection`: Collection that contains the token691	pub fn transfer(692		collection: &RefungibleHandle<T>,693		from: &T::CrossAccountId,694		to: &T::CrossAccountId,695		token: TokenId,696		amount: u128,697		nesting_budget: &dyn Budget,698	) -> DispatchResult {699		ensure!(700			collection.limits.transfers_enabled(),701			<CommonError<T>>::TransferNotAllowed702		);703704		if collection.permissions.access() == AccessMode::AllowList {705			collection.check_allowlist(from)?;706			collection.check_allowlist(to)?;707		}708		<PalletCommon<T>>::ensure_correct_receiver(to)?;709710		let initial_balance_from = <Balance<T>>::get((collection.id, token, from));711		let updated_balance_from = initial_balance_from712			.checked_sub(amount)713			.ok_or(<CommonError<T>>::TokenValueTooLow)?;714		let mut create_target = false;715		let from_to_differ = from != to;716		let updated_balance_to = if from != to {717			let old_balance = <Balance<T>>::get((collection.id, token, to));718			if old_balance == 0 {719				create_target = true;720			}721			Some(722				old_balance723					.checked_add(amount)724					.ok_or(ArithmeticError::Overflow)?,725			)726		} else {727			None728		};729730		let account_balance_from = if updated_balance_from == 0 {731			Some(732				<AccountBalance<T>>::get((collection.id, from))733					.checked_sub(1)734					// Should not occur735					.ok_or(ArithmeticError::Underflow)?,736			)737		} else {738			None739		};740		// Account data is created in token, AccountBalance should be increased741		// But only if from != to as we shouldn't check overflow in this case742		let account_balance_to = if create_target && from_to_differ {743			let account_balance_to = <AccountBalance<T>>::get((collection.id, to))744				.checked_add(1)745				.ok_or(ArithmeticError::Overflow)?;746			ensure!(747				account_balance_to < collection.limits.account_token_ownership_limit(),748				<CommonError<T>>::AccountTokenLimitExceeded,749			);750751			Some(account_balance_to)752		} else {753			None754		};755756		// =========757758		<PalletStructure<T>>::nest_if_sent_to_token(759			from.clone(),760			to,761			collection.id,762			token,763			nesting_budget,764		)?;765766		if let Some(updated_balance_to) = updated_balance_to {767			// from != to768			if updated_balance_from == 0 {769				<Balance<T>>::remove((collection.id, token, from));770				<PalletStructure<T>>::unnest_if_nested(from, collection.id, token);771			} else {772				<Balance<T>>::insert((collection.id, token, from), updated_balance_from);773			}774			<Balance<T>>::insert((collection.id, token, to), updated_balance_to);775			if let Some(account_balance_from) = account_balance_from {776				<AccountBalance<T>>::insert((collection.id, from), account_balance_from);777				<Owned<T>>::remove((collection.id, from, token));778			}779			if let Some(account_balance_to) = account_balance_to {780				<AccountBalance<T>>::insert((collection.id, to), account_balance_to);781				<Owned<T>>::insert((collection.id, to, token), true);782			}783		}784785		<PalletEvm<T>>::deposit_log(786			ERC20Events::Transfer {787				from: *from.as_eth(),788				to: *to.as_eth(),789				value: amount.into(),790			}791			.to_log(T::EvmTokenAddressMapping::token_to_address(792				collection.id,793				token,794			)),795		);796797		<PalletCommon<T>>::deposit_event(CommonEvent::Transfer(798			collection.id,799			token,800			from.clone(),801			to.clone(),802			amount,803		));804805		let total_supply = <TotalSupply<T>>::get((collection.id, token));806807		if amount == total_supply {808			// if token was fully owned by `from` and will be fully owned by `to` after transfer809			<PalletEvm<T>>::deposit_log(810				ERC721Events::Transfer {811					from: *from.as_eth(),812					to: *to.as_eth(),813					token_id: token.into(),814				}815				.to_log(collection_id_to_address(collection.id)),816			);817		} else if let Some(updated_balance_to) = updated_balance_to {818			// if `from` not equals `to`. This condition is needed to avoid sending event819			// when `from` fully owns token and sends part of token pieces to itself.820			if initial_balance_from == total_supply {821				// if token was fully owned by `from` and will be only partially owned by `to`822				// and `from` after transfer823				<PalletEvm<T>>::deposit_log(824					ERC721Events::Transfer {825						from: *from.as_eth(),826						to: erc::ADDRESS_FOR_PARTIALLY_OWNED_TOKENS,827						token_id: token.into(),828					}829					.to_log(collection_id_to_address(collection.id)),830				);831			} else if updated_balance_to == total_supply {832				// if token was partially owned by `from` and will be fully owned by `to` after transfer833				<PalletEvm<T>>::deposit_log(834					ERC721Events::Transfer {835						from: erc::ADDRESS_FOR_PARTIALLY_OWNED_TOKENS,836						to: *to.as_eth(),837						token_id: token.into(),838					}839					.to_log(collection_id_to_address(collection.id)),840				);841			}842		}843844		Ok(())845	}846847	/// Batched operation to create multiple RFT tokens.848	///849	/// Same as `create_item` but creates multiple tokens.850	///851	/// - `data`: Same as 'data` in `create_item` but contains data for multiple tokens.852	pub fn create_multiple_items(853		collection: &RefungibleHandle<T>,854		sender: &T::CrossAccountId,855		data: Vec<CreateItemData<T>>,856		nesting_budget: &dyn Budget,857	) -> DispatchResult {858		if !collection.is_owner_or_admin(sender) {859			ensure!(860				collection.permissions.mint_mode(),861				<CommonError<T>>::PublicMintingNotAllowed862			);863			collection.check_allowlist(sender)?;864865			for item in data.iter() {866				for user in item.users.keys() {867					collection.check_allowlist(user)?;868				}869			}870		}871872		for item in data.iter() {873			for (owner, _) in item.users.iter() {874				<PalletCommon<T>>::ensure_correct_receiver(owner)?;875			}876		}877878		// Total pieces per tokens879		let totals = data880			.iter()881			.map(|data| {882				Ok(data883					.users884					.iter()885					.map(|u| u.1)886					.try_fold(0u128, |acc, v| acc.checked_add(*v))887					.ok_or(ArithmeticError::Overflow)?)888			})889			.collect::<Result<Vec<_>, DispatchError>>()?;890		for total in &totals {891			ensure!(892				*total <= MAX_REFUNGIBLE_PIECES,893				<Error<T>>::WrongRefungiblePieces894			);895		}896897		let first_token_id = <TokensMinted<T>>::get(collection.id);898		let tokens_minted = first_token_id899			.checked_add(data.len() as u32)900			.ok_or(ArithmeticError::Overflow)?;901		ensure!(902			tokens_minted < collection.limits.token_limit(),903			<CommonError<T>>::CollectionTokenLimitExceeded904		);905906		let mut balances = BTreeMap::new();907		for data in &data {908			for owner in data.users.keys() {909				let balance = balances910					.entry(owner)911					.or_insert_with(|| <AccountBalance<T>>::get((collection.id, owner)));912				*balance = balance.checked_add(1).ok_or(ArithmeticError::Overflow)?;913914				ensure!(915					*balance <= collection.limits.account_token_ownership_limit(),916					<CommonError<T>>::AccountTokenLimitExceeded,917				);918			}919		}920921		for (i, token) in data.iter().enumerate() {922			let token_id = TokenId(first_token_id + i as u32 + 1);923			for (to, _) in token.users.iter() {924				<PalletStructure<T>>::check_nesting(925					sender.clone(),926					to,927					collection.id,928					token_id,929					nesting_budget,930				)?;931			}932		}933934		// =========935936		with_transaction(|| {937			for (i, data) in data.iter().enumerate() {938				let token_id = first_token_id + i as u32 + 1;939				<TotalSupply<T>>::insert((collection.id, token_id), totals[i]);940941				<TokenData<T>>::insert(942					(collection.id, token_id),943					ItemData {944						const_data: data.const_data.clone(),945					},946				);947948				for (user, amount) in data.users.iter() {949					if *amount == 0 {950						continue;951					}952					<Balance<T>>::insert((collection.id, token_id, &user), amount);953					<Owned<T>>::insert((collection.id, &user, TokenId(token_id)), true);954					<PalletStructure<T>>::nest_if_sent_to_token_unchecked(955						user,956						collection.id,957						TokenId(token_id),958					);959				}960961				if let Err(e) = Self::set_token_properties(962					collection,963					sender,964					TokenId(token_id),965					data.properties.clone().into_iter(),966					true,967					nesting_budget,968				) {969					return TransactionOutcome::Rollback(Err(e));970				}971			}972			TransactionOutcome::Commit(Ok(()))973		})?;974975		<TokensMinted<T>>::insert(collection.id, tokens_minted);976977		for (account, balance) in balances {978			<AccountBalance<T>>::insert((collection.id, account), balance);979		}980981		for (i, token) in data.into_iter().enumerate() {982			let token_id = first_token_id + i as u32 + 1;983984			for (user, amount) in token.users.into_iter() {985				if amount == 0 {986					continue;987				}988989				<PalletEvm<T>>::deposit_log(990					ERC20Events::Transfer {991						from: H160::default(),992						to: *user.as_eth(),993						value: amount.into(),994					}995					.to_log(T::EvmTokenAddressMapping::token_to_address(996						collection.id,997						TokenId(token_id),998					)),999				);1000				<PalletEvm<T>>::deposit_log(1001					ERC721Events::Transfer {1002						from: H160::default(),1003						to: *user.as_eth(),1004						token_id: token_id.into(),1005					}1006					.to_log(collection_id_to_address(collection.id)),1007				);1008				<PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(1009					collection.id,1010					TokenId(token_id),1011					user,1012					amount,1013				));1014			}1015		}1016		Ok(())1017	}10181019	pub fn set_allowance_unchecked(1020		collection: &RefungibleHandle<T>,1021		sender: &T::CrossAccountId,1022		spender: &T::CrossAccountId,1023		token: TokenId,1024		amount: u128,1025	) {1026		if amount == 0 {1027			<Allowance<T>>::remove((collection.id, token, sender, spender));1028		} else {1029			<Allowance<T>>::insert((collection.id, token, sender, spender), amount);1030		}10311032		<PalletEvm<T>>::deposit_log(1033			ERC20Events::Approval {1034				owner: *sender.as_eth(),1035				spender: *spender.as_eth(),1036				value: amount.into(),1037			}1038			.to_log(T::EvmTokenAddressMapping::token_to_address(1039				collection.id,1040				token,1041			)),1042		);1043		<PalletCommon<T>>::deposit_event(CommonEvent::Approved(1044			collection.id,1045			token,1046			sender.clone(),1047			spender.clone(),1048			amount,1049		))1050	}10511052	/// Set allowance for the spender to `transfer` or `burn` sender's token pieces.1053	///1054	/// - `amount`: Amount of token pieces the spender is allowed to `transfer` or `burn.1055	pub fn set_allowance(1056		collection: &RefungibleHandle<T>,1057		sender: &T::CrossAccountId,1058		spender: &T::CrossAccountId,1059		token: TokenId,1060		amount: u128,1061	) -> DispatchResult {1062		if collection.permissions.access() == AccessMode::AllowList {1063			collection.check_allowlist(sender)?;1064			collection.check_allowlist(spender)?;1065		}10661067		<PalletCommon<T>>::ensure_correct_receiver(spender)?;10681069		if <Balance<T>>::get((collection.id, token, sender)) < amount {1070			ensure!(1071				collection.ignores_owned_amount(sender) && Self::token_exists(collection, token),1072				<CommonError<T>>::CantApproveMoreThanOwned1073			);1074		}10751076		// =========10771078		Self::set_allowance_unchecked(collection, sender, spender, token, amount);1079		Ok(())1080	}10811082	/// Returns allowance, which should be set after transaction1083	fn check_allowed(1084		collection: &RefungibleHandle<T>,1085		spender: &T::CrossAccountId,1086		from: &T::CrossAccountId,1087		token: TokenId,1088		amount: u128,1089		nesting_budget: &dyn Budget,1090	) -> Result<Option<u128>, DispatchError> {1091		if spender.conv_eq(from) {1092			return Ok(None);1093		}1094		if collection.permissions.access() == AccessMode::AllowList {1095			// `from`, `to` checked in [`transfer`]1096			collection.check_allowlist(spender)?;1097		}1098		if let Some(source) = T::CrossTokenAddressMapping::address_to_token(from) {1099			// TODO: should collection owner be allowed to perform this transfer?1100			ensure!(1101				<PalletStructure<T>>::check_indirectly_owned(1102					spender.clone(),1103					source.0,1104					source.1,1105					None,1106					nesting_budget1107				)?,1108				<CommonError<T>>::ApprovedValueTooLow,1109			);1110			return Ok(None);1111		}1112		let allowance =1113			<Allowance<T>>::get((collection.id, token, from, &spender)).checked_sub(amount);1114		if allowance.is_none() {1115			ensure!(1116				collection.ignores_allowance(spender),1117				<CommonError<T>>::ApprovedValueTooLow1118			);1119		}1120		Ok(allowance)1121	}11221123	/// Transfer RFT token pieces from one account to another.1124	///1125	/// Same as the [`transfer`] but spender doesn't needs to be an owner of the token pieces.1126	/// The owner should set allowance for the spender to transfer pieces.1127	///1128	/// [`transfer`]: struct.Pallet.html#method.transfer1129	pub fn transfer_from(1130		collection: &RefungibleHandle<T>,1131		spender: &T::CrossAccountId,1132		from: &T::CrossAccountId,1133		to: &T::CrossAccountId,1134		token: TokenId,1135		amount: u128,1136		nesting_budget: &dyn Budget,1137	) -> DispatchResult {1138		let allowance =1139			Self::check_allowed(collection, spender, from, token, amount, nesting_budget)?;11401141		// =========11421143		Self::transfer(collection, from, to, token, amount, nesting_budget)?;1144		if let Some(allowance) = allowance {1145			Self::set_allowance_unchecked(collection, from, spender, token, allowance);1146		}1147		Ok(())1148	}11491150	/// Burn RFT token pieces from the account.1151	///1152	/// Same as the [`burn`] but spender doesn't need to be an owner of the token pieces. The owner should1153	/// set allowance for the spender to burn pieces1154	///1155	/// [`burn`]: struct.Pallet.html#method.burn1156	pub fn burn_from(1157		collection: &RefungibleHandle<T>,1158		spender: &T::CrossAccountId,1159		from: &T::CrossAccountId,1160		token: TokenId,1161		amount: u128,1162		nesting_budget: &dyn Budget,1163	) -> DispatchResult {1164		let allowance =1165			Self::check_allowed(collection, spender, from, token, amount, nesting_budget)?;11661167		// =========11681169		Self::burn(collection, from, token, amount)?;1170		if let Some(allowance) = allowance {1171			Self::set_allowance_unchecked(collection, from, spender, token, allowance);1172		}1173		Ok(())1174	}11751176	/// Create RFT token.1177	///1178	/// The sender should be the owner/admin of the collection or collection should be configured1179	/// to allow public minting.1180	///1181	/// - `data`: Contains list of users who will become the owners of the token pieces and amount1182	///   of token pieces they will receive.1183	pub fn create_item(1184		collection: &RefungibleHandle<T>,1185		sender: &T::CrossAccountId,1186		data: CreateItemData<T>,1187		nesting_budget: &dyn Budget,1188	) -> DispatchResult {1189		Self::create_multiple_items(collection, sender, vec![data], nesting_budget)1190	}11911192	/// Repartition RFT token.1193	///1194	/// `repartition` will set token balance of the sender and total amount of token pieces.1195	/// Sender should own all of the token pieces. `repartition' could be done even if some1196	/// token pieces were burned before.1197	///1198	/// - `amount`: Total amount of token pieces that the token will have after `repartition`.1199	pub fn repartition(1200		collection: &RefungibleHandle<T>,1201		owner: &T::CrossAccountId,1202		token: TokenId,1203		amount: u128,1204	) -> DispatchResult {1205		ensure!(1206			amount <= MAX_REFUNGIBLE_PIECES,1207			<Error<T>>::WrongRefungiblePieces1208		);1209		ensure!(amount > 0, <CommonError<T>>::TokenValueTooLow);1210		// Ensure user owns all pieces1211		let total_pieces = Self::total_pieces(collection.id, token).unwrap_or(u128::MAX);1212		let balance = <Balance<T>>::get((collection.id, token, owner));1213		ensure!(1214			total_pieces == balance,1215			<Error<T>>::RepartitionWhileNotOwningAllPieces1216		);12171218		<Balance<T>>::insert((collection.id, token, owner), amount);1219		<TotalSupply<T>>::insert((collection.id, token), amount);12201221		if amount > total_pieces {1222			let mint_amount = amount - total_pieces;1223			<PalletEvm<T>>::deposit_log(1224				ERC20Events::Transfer {1225					from: H160::default(),1226					to: *owner.as_eth(),1227					value: mint_amount.into(),1228				}1229				.to_log(T::EvmTokenAddressMapping::token_to_address(1230					collection.id,1231					token,1232				)),1233			);1234			<PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(1235				collection.id,1236				token,1237				owner.clone(),1238				mint_amount,1239			));1240		} else if total_pieces > amount {1241			let burn_amount = total_pieces - amount;1242			<PalletEvm<T>>::deposit_log(1243				ERC20Events::Transfer {1244					from: *owner.as_eth(),1245					to: H160::default(),1246					value: burn_amount.into(),1247				}1248				.to_log(T::EvmTokenAddressMapping::token_to_address(1249					collection.id,1250					token,1251				)),1252			);1253			<PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(1254				collection.id,1255				token,1256				owner.clone(),1257				burn_amount,1258			));1259		}12601261		Ok(())1262	}12631264	fn token_owner(collection_id: CollectionId, token_id: TokenId) -> Option<T::CrossAccountId> {1265		let mut owner = None;1266		let mut count = 0;1267		for key in Balance::<T>::iter_key_prefix((collection_id, token_id)) {1268			count += 1;1269			if count > 1 {1270				return None;1271			}1272			owner = Some(key);1273		}1274		owner1275	}12761277	fn total_pieces(collection_id: CollectionId, token_id: TokenId) -> Option<u128> {1278		<TotalSupply<T>>::try_get((collection_id, token_id)).ok()1279	}12801281	pub fn set_collection_properties(1282		collection: &RefungibleHandle<T>,1283		sender: &T::CrossAccountId,1284		properties: Vec<Property>,1285	) -> DispatchResult {1286		<PalletCommon<T>>::set_collection_properties(collection, sender, properties)1287	}12881289	pub fn delete_collection_properties(1290		collection: &RefungibleHandle<T>,1291		sender: &T::CrossAccountId,1292		property_keys: Vec<PropertyKey>,1293	) -> DispatchResult {1294		<PalletCommon<T>>::delete_collection_properties(collection, sender, property_keys)1295	}12961297	pub fn set_token_property_permissions(1298		collection: &RefungibleHandle<T>,1299		sender: &T::CrossAccountId,1300		property_permissions: Vec<PropertyKeyPermission>,1301	) -> DispatchResult {1302		<PalletCommon<T>>::set_token_property_permissions(collection, sender, property_permissions)1303	}13041305	/// Returns 10 token in no particular order.1306	///1307	/// There is no direct way to get token holders in ascending order,1308	/// since `iter_prefix` returns values in no particular order.1309	/// Therefore, getting the 10 largest holders with a large value of holders1310	/// can lead to impact memory allocation + sorting with  `n * log (n)`.1311	pub fn token_owners(1312		collection_id: CollectionId,1313		token: TokenId,1314	) -> Option<Vec<T::CrossAccountId>> {1315		let res: Vec<T::CrossAccountId> = <Balance<T>>::iter_prefix((collection_id, token))1316			.map(|(owner, _amount)| owner)1317			.take(10)1318			.collect();13191320		if res.is_empty() {1321			None1322		} else {1323			Some(res)1324		}1325	}1326}
after · pallets/refungible/src/lib.rs
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}
modifiedtests/src/eth/reFungible.test.tsdiffbeforeafterboth
--- a/tests/src/eth/reFungible.test.ts
+++ b/tests/src/eth/reFungible.test.ts
@@ -15,7 +15,7 @@
 // along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
 
 import {createCollectionExpectSuccess, transfer, UNIQUE} from '../util/helpers';
-import {collectionIdToAddress, createEthAccount, createEthAccountWithBalance, evmCollection, evmCollectionHelpers, GAS_ARGS, getCollectionAddressFromResult, itWeb3, normalizeEvents, recordEthFee, tokenIdToAddress} from './util/helpers';
+import {collectionIdToAddress, createEthAccount, createEthAccountWithBalance, evmCollection, evmCollectionHelpers, GAS_ARGS, getCollectionAddressFromResult, itWeb3, normalizeEvents, recordEthFee, recordEvents, tokenIdToAddress} from './util/helpers';
 import reFungibleAbi from './reFungibleAbi.json';
 import reFungibleTokenAbi from './reFungibleTokenAbi.json';
 import {expect} from 'chai';
@@ -224,8 +224,7 @@
     {
       const result = await contract.methods.burn(tokenId).send();
       const events = normalizeEvents(result.events);
-
-      expect(events).to.be.deep.equal([
+      expect(events).to.include.deep.members([
         {
           address: collectionIdAddress,
           event: 'Transfer',
@@ -333,10 +332,8 @@
     await tokenContract.methods.repartition(2).send();
     await tokenContract.methods.transfer(receiver, 1).send();
 
-    let transfer;
-    contract.events.Transfer({}, function(_error: any, event: any){ transfer = event;});
-    await tokenContract.methods.transfer(receiver, 1).send();
-    const events = normalizeEvents([transfer]);
+    const events =  await recordEvents(contract, async () => 
+      await tokenContract.methods.transfer(receiver, 1).send());
     expect(events).to.deep.equal([
       {
         address: collectionIdAddress,
@@ -366,11 +363,9 @@
 
     await tokenContract.methods.repartition(2).send();
     
-    let transfer;
-    contract.events.Transfer({}, function(_error: any, event: any){ transfer = event;});
-    await tokenContract.methods.transfer(receiver, 1).send();
-
-    const events = normalizeEvents([transfer]);
+    const events =  await recordEvents(contract, async () => 
+      await tokenContract.methods.transfer(receiver, 1).send());
+      
     expect(events).to.deep.equal([
       {
         address: collectionIdAddress,
modifiedtests/src/eth/reFungibleToken.test.tsdiffbeforeafterboth
--- a/tests/src/eth/reFungibleToken.test.ts
+++ b/tests/src/eth/reFungibleToken.test.ts
@@ -277,7 +277,7 @@
     {
       const result = await contract.methods.transferFrom(owner, receiver, 49).send({from: spender});
       const events = normalizeEvents(result.events);
-      expect(events).to.be.deep.equal([
+      expect(events).to.include.deep.members([
         {
           address,
           event: 'Transfer',
@@ -329,7 +329,7 @@
     {
       const result = await contract.methods.transfer(receiver, 50).send({from: owner});
       const events = normalizeEvents(result.events);
-      expect(events).to.be.deep.equal([
+      expect(events).to.include.deep.members([
         {
           address,
           event: 'Transfer',
@@ -442,6 +442,38 @@
       },
     ]);
   });
+
+  itWeb3('Receiving Transfer event on burning into full ownership', async ({web3, api, privateKeyWrapper}) => {
+    const caller = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
+    const receiver = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
+    const helper = evmCollectionHelpers(web3, caller);
+    const result = await helper.methods.createRefungibleCollection('Mint collection', '6', '6').send();
+    const {collectionIdAddress, collectionId} = await getCollectionAddressFromResult(api, result);
+    const contract = evmCollection(web3, caller, collectionIdAddress, {type: 'ReFungible'});
+
+    const tokenId = await contract.methods.nextTokenId().call();
+    await contract.methods.mint(caller, tokenId).send();
+
+    const address = tokenIdToAddress(collectionId, tokenId);
+
+    const tokenContract =  new web3.eth.Contract(reFungibleTokenAbi as any, address, {from: caller, ...GAS_ARGS});
+    await tokenContract.methods.repartition(2).send();
+    await tokenContract.methods.transfer(receiver, 1).send();
+
+    const events =  await recordEvents(contract, async () => 
+      await tokenContract.methods.burnFrom(caller, 1).send());
+    expect(events).to.deep.equal([
+      {
+        address: collectionIdAddress,
+        event: 'Transfer',
+        args: {
+          from: '0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF',
+          to: receiver,
+          tokenId,
+        },
+      },
+    ]);
+  });
 });
 
 describe('Refungible: Fees', () => {