git.delta.rocks / unique-network / refs/commits / 713b8d223b2f

difftreelog

Merge pull request #831 from UniqueNetwork/fix/rft-collection-admin-permissions

Yaroslav Bolyukin2023-01-16parents: #5c9ffb7 #c7a326d.patch.diff
in: master

5 files changed

modifiedpallets/common/src/lib.rsdiffbeforeafterboth
--- a/pallets/common/src/lib.rs
+++ b/pallets/common/src/lib.rs
@@ -390,8 +390,10 @@
 		Ok(())
 	}
 
-	/// Return **true** if `user` was not allowed to have tokens, and he can ignore such restrictions.
-	pub fn ignores_allowance(&self, user: &T::CrossAccountId) -> bool {
+	/// Returns **true** if
+	/// * the `user`is a collection owner or admin
+	/// * the collection limits allow the owner/admins to transfer/burn any collection token
+	pub fn ignores_token_restrictions(&self, user: &T::CrossAccountId) -> bool {
 		self.limits.owner_can_transfer() && self.is_owner_or_admin(user)
 	}
 
modifiedpallets/fungible/src/lib.rsdiffbeforeafterboth
before · pallets/fungible/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//! # Fungible Pallet18//!19//! The Fungible pallet provides functionality for dealing with fungible assets.20//!21//! - [`CreateItemData`]22//! - [`Config`]23//! - [`FungibleHandle`]24//! - [`Pallet`]25//! - [`TotalSupply`]26//! - [`Balance`]27//! - [`Allowance`]28//! - [`Error`]29//!30//! ## Fungible tokens31//!32//! Fungible tokens or assets are divisible and non-unique. For instance,33//! fiat currencies like the dollar are fungible: A $1 bill34//! in New York City has the same value as a $1 bill in Miami.35//! A fungible token can also be a cryptocurrency like Bitcoin: 1 BTC is worth 1 BTC,36//! no matter where it is issued. Thus, the fungibility refers to a specific currency’s37//! ability to maintain one standard value. As well, it needs to have uniform acceptance.38//! This means that a currency’s history should not be able to affect its value,39//! and this is due to the fact that each piece that is a part of the currency is equal40//! in value when compared to every other piece of that exact same currency.41//! In the world of cryptocurrencies, this is essentially a coin or a token42//! that can be replaced by another identical coin or token, and they are43//! both mutually interchangeable. A popular implementation of fungible tokens is44//! the ERC-20 token standard.45//!46//! ### ERC-2047//!48//! The [ERC-20](https://ethereum.org/en/developers/docs/standards/tokens/erc-20/) (Ethereum Request for Comments 20), proposed by Fabian Vogelsteller in November 2015,49//! is a Token Standard that implements an API for tokens within Smart Contracts.50//!51//! Example functionalities ERC-20 provides:52//!53//! * transfer tokens from one account to another54//! * get the current token balance of an account55//! * get the total supply of the token available on the network56//! * approve whether an amount of token from an account can be spent by a third-party account57//!58//! ## Overview59//!60//! The module provides functionality for asset management of fungible asset, supports ERC-20 standart, includes:61//!62//! * Asset Issuance63//! * Asset Transferal64//! * Asset Destruction65//! * Delegated Asset Transfers66//!67//! **NOTE:** The created fungible asset always has `token_id` = 0.68//! So `tokenA` and `tokenB` will have different `collection_id`.69//!70//! ### Implementations71//!72//! The Fungible pallet provides implementations for the following traits.73//!74//! - [`WithRecorder`](pallet_evm_coder_substrate::WithRecorder): Trait for EVM support75//! - [`CommonCollectionOperations`](pallet_common::CommonCollectionOperations): Functions for dealing with collections76//!	- [`CommonWeightInfo`](pallet_common::CommonWeightInfo): Functions for retrieval of transaction weight77//! - [`CommonEvmHandler`](pallet_common::erc::CommonEvmHandler): Function for handling EVM runtime calls7879#![cfg_attr(not(feature = "std"), no_std)]8081use core::ops::Deref;82use evm_coder::ToLog;83use frame_support::ensure;84use pallet_evm::account::CrossAccountId;85use up_data_structs::{86	AccessMode, CollectionId, CollectionFlags, TokenId, CreateCollectionData,87	mapping::TokenAddressMapping, budget::Budget, PropertyKey, Property,88};89use pallet_common::{90	Error as CommonError, Event as CommonEvent, Pallet as PalletCommon,91	eth::collection_id_to_address,92};93use pallet_evm::Pallet as PalletEvm;94use pallet_structure::Pallet as PalletStructure;95use pallet_evm_coder_substrate::WithRecorder;96use sp_core::H160;97use sp_runtime::{ArithmeticError, DispatchError, DispatchResult};98use sp_std::{collections::btree_map::BTreeMap, vec::Vec};99100pub use pallet::*;101102use crate::erc::ERC20Events;103#[cfg(feature = "runtime-benchmarks")]104pub mod benchmarking;105pub mod common;106pub mod erc;107pub mod weights;108109pub type CreateItemData<T> = (<T as pallet_evm::Config>::CrossAccountId, u128);110pub(crate) type SelfWeightOf<T> = <T as Config>::WeightInfo;111112#[frame_support::pallet]113pub mod pallet {114	use frame_support::{Blake2_128, Blake2_128Concat, Twox64Concat, pallet_prelude::*, storage::Key};115	use up_data_structs::CollectionId;116	use super::weights::WeightInfo;117118	#[pallet::error]119	pub enum Error<T> {120		/// Not Fungible item data used to mint in Fungible collection.121		NotFungibleDataUsedToMintFungibleCollectionToken,122		/// Fungible tokens hold no ID, and the default value of TokenId for Fungible collection is 0.123		FungibleItemsHaveNoId,124		/// Tried to set data for fungible item.125		FungibleItemsDontHaveData,126		/// Fungible token does not support nesting.127		FungibleDisallowsNesting,128		/// Setting item properties is not allowed.129		SettingPropertiesNotAllowed,130		/// Setting allowance for all is not allowed.131		SettingAllowanceForAllNotAllowed,132		/// Only a fungible collection could be possibly broken; any fungible token is valid.133		FungibleTokensAreAlwaysValid,134	}135136	#[pallet::config]137	pub trait Config:138		frame_system::Config + pallet_common::Config + pallet_structure::Config + pallet_evm::Config139	{140		type WeightInfo: WeightInfo;141	}142143	#[pallet::pallet]144	#[pallet::generate_store(pub(super) trait Store)]145	pub struct Pallet<T>(_);146147	/// Total amount of fungible tokens inside a collection.148	#[pallet::storage]149	pub type TotalSupply<T: Config> =150		StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u128, QueryKind = ValueQuery>;151152	/// Amount of tokens owned by an account inside a collection.153	#[pallet::storage]154	pub type Balance<T: Config> = StorageNMap<155		Key = (156			Key<Twox64Concat, CollectionId>,157			Key<Blake2_128Concat, T::CrossAccountId>,158		),159		Value = u128,160		QueryKind = ValueQuery,161	>;162163	/// Storage for assets delegated to a limited extent to other users.164	#[pallet::storage]165	pub type Allowance<T: Config> = StorageNMap<166		Key = (167			Key<Twox64Concat, CollectionId>,168			Key<Blake2_128, T::CrossAccountId>,169			Key<Blake2_128Concat, T::CrossAccountId>,170		),171		Value = u128,172		QueryKind = ValueQuery,173	>;174}175176/// Wrapper around untyped collection handle, asserting inner collection is of fungible type.177/// Required for interaction with Fungible collections, type safety and implementation [`solidity_interface`][`evm_coder::solidity_interface`].178pub struct FungibleHandle<T: Config>(pallet_common::CollectionHandle<T>);179180/// Implementation of methods required for dispatching during runtime.181impl<T: Config> FungibleHandle<T> {182	/// Casts [`CollectionHandle`][`pallet_common::CollectionHandle`] into [`FungibleHandle`].183	pub fn cast(inner: pallet_common::CollectionHandle<T>) -> Self {184		Self(inner)185	}186187	/// Casts [`FungibleHandle`] into [`CollectionHandle`][`pallet_common::CollectionHandle`].188	pub fn into_inner(self) -> pallet_common::CollectionHandle<T> {189		self.0190	}191	/// Returns a mutable reference to the internal [`CollectionHandle`][`pallet_common::CollectionHandle`].192	pub fn common_mut(&mut self) -> &mut pallet_common::CollectionHandle<T> {193		&mut self.0194	}195}196impl<T: Config> WithRecorder<T> for FungibleHandle<T> {197	fn recorder(&self) -> &pallet_evm_coder_substrate::SubstrateRecorder<T> {198		self.0.recorder()199	}200	fn into_recorder(self) -> pallet_evm_coder_substrate::SubstrateRecorder<T> {201		self.0.into_recorder()202	}203}204impl<T: Config> Deref for FungibleHandle<T> {205	type Target = pallet_common::CollectionHandle<T>;206207	fn deref(&self) -> &Self::Target {208		&self.0209	}210}211212/// Pallet implementation for fungible assets213impl<T: Config> Pallet<T> {214	/// Initializes the collection. Returns [CollectionId] on success, [DispatchError] otherwise.215	pub fn init_collection(216		owner: T::CrossAccountId,217		payer: T::CrossAccountId,218		data: CreateCollectionData<T::AccountId>,219		flags: CollectionFlags,220	) -> Result<CollectionId, DispatchError> {221		<PalletCommon<T>>::init_collection(owner, payer, data, flags)222	}223224	/// Initializes the collection with ForeignCollection flag. Returns [CollectionId] on success, [DispatchError] otherwise.225	pub fn init_foreign_collection(226		owner: T::CrossAccountId,227		payer: T::CrossAccountId,228		data: CreateCollectionData<T::AccountId>,229	) -> Result<CollectionId, DispatchError> {230		let id = <PalletCommon<T>>::init_collection(231			owner,232			payer,233			data,234			CollectionFlags {235				foreign: true,236				..Default::default()237			},238		)?;239		Ok(id)240	}241242	/// Destroys a collection.243	pub fn destroy_collection(244		collection: FungibleHandle<T>,245		sender: &T::CrossAccountId,246	) -> DispatchResult {247		let id = collection.id;248249		if Self::collection_has_tokens(id) {250			return Err(<CommonError<T>>::CantDestroyNotEmptyCollection.into());251		}252253		// =========254255		PalletCommon::destroy_collection(collection.0, sender)?;256257		<TotalSupply<T>>::remove(id);258		let _ = <Balance<T>>::clear_prefix((id,), u32::MAX, None);259		let _ = <Allowance<T>>::clear_prefix((id,), u32::MAX, None);260		Ok(())261	}262263	/// Add properties to the collection.264	pub fn set_collection_properties(265		collection: &FungibleHandle<T>,266		sender: &T::CrossAccountId,267		properties: Vec<Property>,268	) -> DispatchResult {269		<PalletCommon<T>>::set_collection_properties(collection, sender, properties.into_iter())270	}271272	/// Delete properties of the collection, associated with the provided keys.273	pub fn delete_collection_properties(274		collection: &FungibleHandle<T>,275		sender: &T::CrossAccountId,276		property_keys: Vec<PropertyKey>,277	) -> DispatchResult {278		<PalletCommon<T>>::delete_collection_properties(279			collection,280			sender,281			property_keys.into_iter(),282		)283	}284285	/// Checks if collection has tokens. Return `true` if it has.286	fn collection_has_tokens(collection_id: CollectionId) -> bool {287		<TotalSupply<T>>::get(collection_id) != 0288	}289290	/// Burns the specified amount of the token. If the token balance291	/// or total supply is less than the given value,292	/// it will return [DispatchError].293	pub fn burn(294		collection: &FungibleHandle<T>,295		owner: &T::CrossAccountId,296		amount: u128,297	) -> DispatchResult {298		let total_supply = <TotalSupply<T>>::get(collection.id)299			.checked_sub(amount)300			.ok_or(<CommonError<T>>::TokenValueTooLow)?;301302		let balance = <Balance<T>>::get((collection.id, owner))303			.checked_sub(amount)304			.ok_or(<CommonError<T>>::TokenValueTooLow)?;305306		// Foreign collection check307		ensure!(!collection.flags.foreign, <CommonError<T>>::NoPermission);308309		if collection.permissions.access() == AccessMode::AllowList {310			collection.check_allowlist(owner)?;311		}312313		// =========314315		if balance == 0 {316			<Balance<T>>::remove((collection.id, owner));317			<PalletStructure<T>>::unnest_if_nested(owner, collection.id, TokenId::default());318		} else {319			<Balance<T>>::insert((collection.id, owner), balance);320		}321		<TotalSupply<T>>::insert(collection.id, total_supply);322323		<PalletEvm<T>>::deposit_log(324			ERC20Events::Transfer {325				from: *owner.as_eth(),326				to: H160::default(),327				value: amount.into(),328			}329			.to_log(collection_id_to_address(collection.id)),330		);331		<PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(332			collection.id,333			TokenId::default(),334			owner.clone(),335			amount,336		));337		Ok(())338	}339340	/// Burns the specified amount of the token.341	pub fn burn_foreign(342		collection: &FungibleHandle<T>,343		owner: &T::CrossAccountId,344		amount: u128,345	) -> DispatchResult {346		let total_supply = <TotalSupply<T>>::get(collection.id)347			.checked_sub(amount)348			.ok_or(<CommonError<T>>::TokenValueTooLow)?;349350		let balance = <Balance<T>>::get((collection.id, owner))351			.checked_sub(amount)352			.ok_or(<CommonError<T>>::TokenValueTooLow)?;353		// =========354355		if balance == 0 {356			<Balance<T>>::remove((collection.id, owner));357			<PalletStructure<T>>::unnest_if_nested(owner, collection.id, TokenId::default());358		} else {359			<Balance<T>>::insert((collection.id, owner), balance);360		}361		<TotalSupply<T>>::insert(collection.id, total_supply);362363		<PalletEvm<T>>::deposit_log(364			ERC20Events::Transfer {365				from: *owner.as_eth(),366				to: H160::default(),367				value: amount.into(),368			}369			.to_log(collection_id_to_address(collection.id)),370		);371		<PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(372			collection.id,373			TokenId::default(),374			owner.clone(),375			amount,376		));377		Ok(())378	}379380	/// Transfers the specified amount of tokens. Will check that381	/// the transfer is allowed for the token.382	///383	/// - `from`: Owner of tokens to transfer.384	/// - `to`: Recepient of transfered tokens.385	/// - `amount`: Amount of tokens to transfer.386	/// - `collection`: Collection that contains the token387	pub fn transfer(388		collection: &FungibleHandle<T>,389		from: &T::CrossAccountId,390		to: &T::CrossAccountId,391		amount: u128,392		nesting_budget: &dyn Budget,393	) -> DispatchResult {394		ensure!(395			collection.limits.transfers_enabled(),396			<CommonError<T>>::TransferNotAllowed,397		);398399		if collection.permissions.access() == AccessMode::AllowList {400			collection.check_allowlist(from)?;401			collection.check_allowlist(to)?;402		}403		<PalletCommon<T>>::ensure_correct_receiver(to)?;404405		let balance_from = <Balance<T>>::get((collection.id, from))406			.checked_sub(amount)407			.ok_or(<CommonError<T>>::TokenValueTooLow)?;408		let balance_to = if from != to && amount != 0 {409			Some(410				<Balance<T>>::get((collection.id, to))411					.checked_add(amount)412					.ok_or(ArithmeticError::Overflow)?,413			)414		} else {415			None416		};417418		// =========419420		if let Some(balance_to) = balance_to {421			// from != to && amount != 0422423			<PalletStructure<T>>::nest_if_sent_to_token(424				from.clone(),425				to,426				collection.id,427				TokenId::default(),428				nesting_budget,429			)?;430431			if balance_from == 0 {432				<Balance<T>>::remove((collection.id, from));433				<PalletStructure<T>>::unnest_if_nested(from, collection.id, TokenId::default());434			} else {435				<Balance<T>>::insert((collection.id, from), balance_from);436			}437			<Balance<T>>::insert((collection.id, to), balance_to);438		}439440		<PalletEvm<T>>::deposit_log(441			ERC20Events::Transfer {442				from: *from.as_eth(),443				to: *to.as_eth(),444				value: amount.into(),445			}446			.to_log(collection_id_to_address(collection.id)),447		);448		<PalletCommon<T>>::deposit_event(CommonEvent::Transfer(449			collection.id,450			TokenId::default(),451			from.clone(),452			to.clone(),453			amount,454		));455		Ok(())456	}457458	/// Minting tokens for multiple IDs.459	/// It is a utility function used in [`create_multiple_items`][`Pallet::create_multiple_items`]460	/// and [`create_multiple_items_foreign`][`Pallet::create_multiple_items_foreign`]461	pub fn create_multiple_items_common(462		collection: &FungibleHandle<T>,463		sender: &T::CrossAccountId,464		data: BTreeMap<T::CrossAccountId, u128>,465		nesting_budget: &dyn Budget,466	) -> DispatchResult {467		let total_supply = data468			.iter()469			.map(|(_, v)| *v)470			.try_fold(<TotalSupply<T>>::get(collection.id), |acc, v| {471				acc.checked_add(v)472			})473			.ok_or(ArithmeticError::Overflow)?;474475		for (to, _) in data.iter() {476			<PalletStructure<T>>::check_nesting(477				sender.clone(),478				to,479				collection.id,480				TokenId::default(),481				nesting_budget,482			)?;483		}484485		let updated_balances = data486			.into_iter()487			.map(|(user, amount)| {488				let updated_balance = <Balance<T>>::get((collection.id, &user))489					.checked_add(amount)490					.ok_or(ArithmeticError::Overflow)?;491				Ok((user, amount, updated_balance))492			})493			.collect::<Result<Vec<_>, DispatchError>>()?;494495		// =========496497		<TotalSupply<T>>::insert(collection.id, total_supply);498		for (user, amount, updated_balance) in updated_balances {499			<Balance<T>>::insert((collection.id, &user), updated_balance);500			<PalletStructure<T>>::nest_if_sent_to_token_unchecked(501				&user,502				collection.id,503				TokenId::default(),504			);505			<PalletEvm<T>>::deposit_log(506				ERC20Events::Transfer {507					from: H160::default(),508					to: *user.as_eth(),509					value: amount.into(),510				}511				.to_log(collection_id_to_address(collection.id)),512			);513			<PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(514				collection.id,515				TokenId::default(),516				user.clone(),517				amount,518			));519		}520521		Ok(())522	}523524	/// Minting tokens for multiple IDs.525	/// See [`create_item`][`Pallet::create_item`] for more details.526	pub fn create_multiple_items(527		collection: &FungibleHandle<T>,528		sender: &T::CrossAccountId,529		data: BTreeMap<T::CrossAccountId, u128>,530		nesting_budget: &dyn Budget,531	) -> DispatchResult {532		// Foreign collection check533		ensure!(!collection.flags.foreign, <CommonError<T>>::NoPermission);534535		if !collection.is_owner_or_admin(sender) {536			ensure!(537				collection.permissions.mint_mode(),538				<CommonError<T>>::PublicMintingNotAllowed539			);540			collection.check_allowlist(sender)?;541542			for (owner, _) in data.iter() {543				collection.check_allowlist(owner)?;544			}545		}546547		Self::create_multiple_items_common(collection, sender, data, nesting_budget)548	}549550	/// Minting tokens for multiple IDs.551	/// See [`create_item_foreign`][`Pallet::create_item_foreign`] for more details.552	pub fn create_multiple_items_foreign(553		collection: &FungibleHandle<T>,554		sender: &T::CrossAccountId,555		data: BTreeMap<T::CrossAccountId, u128>,556		nesting_budget: &dyn Budget,557	) -> DispatchResult {558		Self::create_multiple_items_common(collection, sender, data, nesting_budget)559	}560561	fn set_allowance_unchecked(562		collection: &FungibleHandle<T>,563		owner: &T::CrossAccountId,564		spender: &T::CrossAccountId,565		amount: u128,566	) {567		if amount == 0 {568			<Allowance<T>>::remove((collection.id, owner, spender));569		} else {570			<Allowance<T>>::insert((collection.id, owner, spender), amount);571		}572573		<PalletEvm<T>>::deposit_log(574			ERC20Events::Approval {575				owner: *owner.as_eth(),576				spender: *spender.as_eth(),577				value: amount.into(),578			}579			.to_log(collection_id_to_address(collection.id)),580		);581		<PalletCommon<T>>::deposit_event(CommonEvent::Approved(582			collection.id,583			TokenId(0),584			owner.clone(),585			spender.clone(),586			amount,587		));588	}589590	/// Set allowance for the spender to `transfer` or `burn` owner's tokens.591	///592	/// - `collection`: Collection that contains the token593	/// - `owner`: Owner of tokens that sets the allowance.594	/// - `spender`: Recipient of the allowance rights.595	/// - `amount`: Amount of tokens the spender is allowed to `transfer` or `burn`.596	pub fn set_allowance(597		collection: &FungibleHandle<T>,598		owner: &T::CrossAccountId,599		spender: &T::CrossAccountId,600		amount: u128,601	) -> DispatchResult {602		if collection.permissions.access() == AccessMode::AllowList {603			collection.check_allowlist(owner)?;604			collection.check_allowlist(spender)?;605		}606607		if <Balance<T>>::get((collection.id, owner)) < amount {608			ensure!(609				collection.ignores_owned_amount(owner),610				<CommonError<T>>::CantApproveMoreThanOwned611			);612		}613614		// =========615616		Self::set_allowance_unchecked(collection, owner, spender, amount);617		Ok(())618	}619620	/// Set allowance for the spender to `transfer` or `burn` owner's tokens from eth mirror.621	///622	/// - `collection`: Collection that contains the token623	/// - `sender`: Owner of tokens that sets the allowance.624	/// - `from`: Owner's eth mirror.625	/// - `to`: Recipient of the allowance rights.626	/// - `amount`: Amount of tokens the spender is allowed to `transfer` or `burn`.627	pub fn set_allowance_from(628		collection: &FungibleHandle<T>,629		sender: &T::CrossAccountId,630		from: &T::CrossAccountId,631		to: &T::CrossAccountId,632		amount: u128,633	) -> DispatchResult {634		if collection.permissions.access() == AccessMode::AllowList {635			collection.check_allowlist(sender)?;636			collection.check_allowlist(from)?;637			collection.check_allowlist(to)?;638		}639640		ensure!(641			sender.conv_eq(from),642			<CommonError<T>>::AddressIsNotEthMirror643		);644645		if <Balance<T>>::get((collection.id, from)) < amount {646			ensure!(647				collection.limits.owner_can_transfer()648					&& (collection.is_owner_or_admin(sender) || collection.is_owner_or_admin(from)),649				<CommonError<T>>::CantApproveMoreThanOwned650			);651		}652653		// =========654655		Self::set_allowance_unchecked(collection, from, to, amount);656		Ok(())657	}658659	/// Checks if a non-owner has (enough) allowance from the owner to perform operations on the tokens.660	/// Returns the expected remaining allowance - it should be set manually if the transaction proceeds.661	///662	/// - `collection`: Collection that contains the token.663	/// - `spender`: CrossAccountId who has the allowance rights.664	/// - `from`: The owner of the tokens who sets the allowance.665	/// - `amount`: Amount of tokens by which the allowance sholud be reduced.666	fn check_allowed(667		collection: &FungibleHandle<T>,668		spender: &T::CrossAccountId,669		from: &T::CrossAccountId,670		amount: u128,671		nesting_budget: &dyn Budget,672	) -> Result<Option<u128>, DispatchError> {673		if spender.conv_eq(from) {674			return Ok(None);675		}676		if collection.permissions.access() == AccessMode::AllowList {677			// `from`, `to` checked in [`transfer`]678			collection.check_allowlist(spender)?;679		}680		if let Some(source) = T::CrossTokenAddressMapping::address_to_token(from) {681			// TODO: should collection owner be allowed to perform this transfer?682			ensure!(683				<PalletStructure<T>>::check_indirectly_owned(684					spender.clone(),685					source.0,686					source.1,687					None,688					nesting_budget689				)?,690				<CommonError<T>>::ApprovedValueTooLow,691			);692			return Ok(None);693		}694		let allowance = <Allowance<T>>::get((collection.id, from, spender)).checked_sub(amount);695		if allowance.is_none() {696			ensure!(697				collection.ignores_allowance(spender),698				<CommonError<T>>::ApprovedValueTooLow699			);700		}701702		Ok(allowance)703	}704705	/// Transfer fungible tokens from one account to another.706	/// Same as the [`transfer`][`Pallet::transfer`] but spender doesn't needs to be an owner of the token pieces.707	/// The owner should set allowance for the spender to transfer pieces.708	///	See [`set_allowance`][`Pallet::set_allowance`] for more details.709710	pub fn transfer_from(711		collection: &FungibleHandle<T>,712		spender: &T::CrossAccountId,713		from: &T::CrossAccountId,714		to: &T::CrossAccountId,715		amount: u128,716		nesting_budget: &dyn Budget,717	) -> DispatchResult {718		let allowance = Self::check_allowed(collection, spender, from, amount, nesting_budget)?;719720		// =========721722		Self::transfer(collection, from, to, amount, nesting_budget)?;723		if let Some(allowance) = allowance {724			Self::set_allowance_unchecked(collection, from, spender, allowance);725		}726		Ok(())727	}728729	/// Burn fungible tokens from the account.730	///731	/// Same as the [`burn`][`Pallet::burn`] but spender doesn't need to be an owner of the tokens. The `from` should732	/// set allowance for the spender to burn tokens.733	/// See [`set_allowance`][`Pallet::set_allowance`] for more details.734	pub fn burn_from(735		collection: &FungibleHandle<T>,736		spender: &T::CrossAccountId,737		from: &T::CrossAccountId,738		amount: u128,739		nesting_budget: &dyn Budget,740	) -> DispatchResult {741		let allowance = Self::check_allowed(collection, spender, from, amount, nesting_budget)?;742743		// =========744745		Self::burn(collection, from, amount)?;746		if let Some(allowance) = allowance {747			Self::set_allowance_unchecked(collection, from, spender, allowance);748		}749		Ok(())750	}751752	///	Creates fungible token.753	///754	/// The sender should be the owner/admin of the collection or collection should be configured755	/// to allow public minting.756	///757	/// - `data`: Contains user who will become the owners of the tokens and amount758	///   of tokens he will receive.759	pub fn create_item(760		collection: &FungibleHandle<T>,761		sender: &T::CrossAccountId,762		data: CreateItemData<T>,763		nesting_budget: &dyn Budget,764	) -> DispatchResult {765		Self::create_multiple_items(766			collection,767			sender,768			[(data.0, data.1)].into_iter().collect(),769			nesting_budget,770		)771	}772773	///	Creates fungible token.774	///775	/// - `data`: Contains user who will become the owners of the tokens and amount776	///   of tokens he will receive.777	pub fn create_item_foreign(778		collection: &FungibleHandle<T>,779		sender: &T::CrossAccountId,780		data: CreateItemData<T>,781		nesting_budget: &dyn Budget,782	) -> DispatchResult {783		Self::create_multiple_items_foreign(784			collection,785			sender,786			[(data.0, data.1)].into_iter().collect(),787			nesting_budget,788		)789	}790791	/// Returns 10 tokens owners in no particular order792	///793	/// There is no direct way to get token holders in ascending order,794	/// since `iter_prefix` returns values in no particular order.795	/// Therefore, getting the 10 largest holders with a large value of holders796	/// can lead to impact memory allocation + sorting with  `n * log (n)`.797	pub fn token_owners(798		collection: CollectionId,799		_token: TokenId,800	) -> Option<Vec<T::CrossAccountId>> {801		let res: Vec<T::CrossAccountId> = <Balance<T>>::iter_prefix((collection,))802			.map(|(owner, _amount)| owner)803			.take(10)804			.collect();805806		if res.is_empty() {807			None808		} else {809			Some(res)810		}811	}812}
after · pallets/fungible/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//! # Fungible Pallet18//!19//! The Fungible pallet provides functionality for dealing with fungible assets.20//!21//! - [`CreateItemData`]22//! - [`Config`]23//! - [`FungibleHandle`]24//! - [`Pallet`]25//! - [`TotalSupply`]26//! - [`Balance`]27//! - [`Allowance`]28//! - [`Error`]29//!30//! ## Fungible tokens31//!32//! Fungible tokens or assets are divisible and non-unique. For instance,33//! fiat currencies like the dollar are fungible: A $1 bill34//! in New York City has the same value as a $1 bill in Miami.35//! A fungible token can also be a cryptocurrency like Bitcoin: 1 BTC is worth 1 BTC,36//! no matter where it is issued. Thus, the fungibility refers to a specific currency’s37//! ability to maintain one standard value. As well, it needs to have uniform acceptance.38//! This means that a currency’s history should not be able to affect its value,39//! and this is due to the fact that each piece that is a part of the currency is equal40//! in value when compared to every other piece of that exact same currency.41//! In the world of cryptocurrencies, this is essentially a coin or a token42//! that can be replaced by another identical coin or token, and they are43//! both mutually interchangeable. A popular implementation of fungible tokens is44//! the ERC-20 token standard.45//!46//! ### ERC-2047//!48//! The [ERC-20](https://ethereum.org/en/developers/docs/standards/tokens/erc-20/) (Ethereum Request for Comments 20), proposed by Fabian Vogelsteller in November 2015,49//! is a Token Standard that implements an API for tokens within Smart Contracts.50//!51//! Example functionalities ERC-20 provides:52//!53//! * transfer tokens from one account to another54//! * get the current token balance of an account55//! * get the total supply of the token available on the network56//! * approve whether an amount of token from an account can be spent by a third-party account57//!58//! ## Overview59//!60//! The module provides functionality for asset management of fungible asset, supports ERC-20 standart, includes:61//!62//! * Asset Issuance63//! * Asset Transferal64//! * Asset Destruction65//! * Delegated Asset Transfers66//!67//! **NOTE:** The created fungible asset always has `token_id` = 0.68//! So `tokenA` and `tokenB` will have different `collection_id`.69//!70//! ### Implementations71//!72//! The Fungible pallet provides implementations for the following traits.73//!74//! - [`WithRecorder`](pallet_evm_coder_substrate::WithRecorder): Trait for EVM support75//! - [`CommonCollectionOperations`](pallet_common::CommonCollectionOperations): Functions for dealing with collections76//!	- [`CommonWeightInfo`](pallet_common::CommonWeightInfo): Functions for retrieval of transaction weight77//! - [`CommonEvmHandler`](pallet_common::erc::CommonEvmHandler): Function for handling EVM runtime calls7879#![cfg_attr(not(feature = "std"), no_std)]8081use core::ops::Deref;82use evm_coder::ToLog;83use frame_support::ensure;84use pallet_evm::account::CrossAccountId;85use up_data_structs::{86	AccessMode, CollectionId, CollectionFlags, TokenId, CreateCollectionData,87	mapping::TokenAddressMapping, budget::Budget, PropertyKey, Property,88};89use pallet_common::{90	Error as CommonError, Event as CommonEvent, Pallet as PalletCommon,91	eth::collection_id_to_address,92};93use pallet_evm::Pallet as PalletEvm;94use pallet_structure::Pallet as PalletStructure;95use pallet_evm_coder_substrate::WithRecorder;96use sp_core::H160;97use sp_runtime::{ArithmeticError, DispatchError, DispatchResult};98use sp_std::{collections::btree_map::BTreeMap, vec::Vec};99100pub use pallet::*;101102use crate::erc::ERC20Events;103#[cfg(feature = "runtime-benchmarks")]104pub mod benchmarking;105pub mod common;106pub mod erc;107pub mod weights;108109pub type CreateItemData<T> = (<T as pallet_evm::Config>::CrossAccountId, u128);110pub(crate) type SelfWeightOf<T> = <T as Config>::WeightInfo;111112#[frame_support::pallet]113pub mod pallet {114	use frame_support::{Blake2_128, Blake2_128Concat, Twox64Concat, pallet_prelude::*, storage::Key};115	use up_data_structs::CollectionId;116	use super::weights::WeightInfo;117118	#[pallet::error]119	pub enum Error<T> {120		/// Not Fungible item data used to mint in Fungible collection.121		NotFungibleDataUsedToMintFungibleCollectionToken,122		/// Fungible tokens hold no ID, and the default value of TokenId for Fungible collection is 0.123		FungibleItemsHaveNoId,124		/// Tried to set data for fungible item.125		FungibleItemsDontHaveData,126		/// Fungible token does not support nesting.127		FungibleDisallowsNesting,128		/// Setting item properties is not allowed.129		SettingPropertiesNotAllowed,130		/// Setting allowance for all is not allowed.131		SettingAllowanceForAllNotAllowed,132		/// Only a fungible collection could be possibly broken; any fungible token is valid.133		FungibleTokensAreAlwaysValid,134	}135136	#[pallet::config]137	pub trait Config:138		frame_system::Config + pallet_common::Config + pallet_structure::Config + pallet_evm::Config139	{140		type WeightInfo: WeightInfo;141	}142143	#[pallet::pallet]144	#[pallet::generate_store(pub(super) trait Store)]145	pub struct Pallet<T>(_);146147	/// Total amount of fungible tokens inside a collection.148	#[pallet::storage]149	pub type TotalSupply<T: Config> =150		StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u128, QueryKind = ValueQuery>;151152	/// Amount of tokens owned by an account inside a collection.153	#[pallet::storage]154	pub type Balance<T: Config> = StorageNMap<155		Key = (156			Key<Twox64Concat, CollectionId>,157			Key<Blake2_128Concat, T::CrossAccountId>,158		),159		Value = u128,160		QueryKind = ValueQuery,161	>;162163	/// Storage for assets delegated to a limited extent to other users.164	#[pallet::storage]165	pub type Allowance<T: Config> = StorageNMap<166		Key = (167			Key<Twox64Concat, CollectionId>,168			Key<Blake2_128, T::CrossAccountId>,169			Key<Blake2_128Concat, T::CrossAccountId>,170		),171		Value = u128,172		QueryKind = ValueQuery,173	>;174}175176/// Wrapper around untyped collection handle, asserting inner collection is of fungible type.177/// Required for interaction with Fungible collections, type safety and implementation [`solidity_interface`][`evm_coder::solidity_interface`].178pub struct FungibleHandle<T: Config>(pallet_common::CollectionHandle<T>);179180/// Implementation of methods required for dispatching during runtime.181impl<T: Config> FungibleHandle<T> {182	/// Casts [`CollectionHandle`][`pallet_common::CollectionHandle`] into [`FungibleHandle`].183	pub fn cast(inner: pallet_common::CollectionHandle<T>) -> Self {184		Self(inner)185	}186187	/// Casts [`FungibleHandle`] into [`CollectionHandle`][`pallet_common::CollectionHandle`].188	pub fn into_inner(self) -> pallet_common::CollectionHandle<T> {189		self.0190	}191	/// Returns a mutable reference to the internal [`CollectionHandle`][`pallet_common::CollectionHandle`].192	pub fn common_mut(&mut self) -> &mut pallet_common::CollectionHandle<T> {193		&mut self.0194	}195}196impl<T: Config> WithRecorder<T> for FungibleHandle<T> {197	fn recorder(&self) -> &pallet_evm_coder_substrate::SubstrateRecorder<T> {198		self.0.recorder()199	}200	fn into_recorder(self) -> pallet_evm_coder_substrate::SubstrateRecorder<T> {201		self.0.into_recorder()202	}203}204impl<T: Config> Deref for FungibleHandle<T> {205	type Target = pallet_common::CollectionHandle<T>;206207	fn deref(&self) -> &Self::Target {208		&self.0209	}210}211212/// Pallet implementation for fungible assets213impl<T: Config> Pallet<T> {214	/// Initializes the collection. Returns [CollectionId] on success, [DispatchError] otherwise.215	pub fn init_collection(216		owner: T::CrossAccountId,217		payer: T::CrossAccountId,218		data: CreateCollectionData<T::AccountId>,219		flags: CollectionFlags,220	) -> Result<CollectionId, DispatchError> {221		<PalletCommon<T>>::init_collection(owner, payer, data, flags)222	}223224	/// Initializes the collection with ForeignCollection flag. Returns [CollectionId] on success, [DispatchError] otherwise.225	pub fn init_foreign_collection(226		owner: T::CrossAccountId,227		payer: T::CrossAccountId,228		data: CreateCollectionData<T::AccountId>,229	) -> Result<CollectionId, DispatchError> {230		let id = <PalletCommon<T>>::init_collection(231			owner,232			payer,233			data,234			CollectionFlags {235				foreign: true,236				..Default::default()237			},238		)?;239		Ok(id)240	}241242	/// Destroys a collection.243	pub fn destroy_collection(244		collection: FungibleHandle<T>,245		sender: &T::CrossAccountId,246	) -> DispatchResult {247		let id = collection.id;248249		if Self::collection_has_tokens(id) {250			return Err(<CommonError<T>>::CantDestroyNotEmptyCollection.into());251		}252253		// =========254255		PalletCommon::destroy_collection(collection.0, sender)?;256257		<TotalSupply<T>>::remove(id);258		let _ = <Balance<T>>::clear_prefix((id,), u32::MAX, None);259		let _ = <Allowance<T>>::clear_prefix((id,), u32::MAX, None);260		Ok(())261	}262263	/// Add properties to the collection.264	pub fn set_collection_properties(265		collection: &FungibleHandle<T>,266		sender: &T::CrossAccountId,267		properties: Vec<Property>,268	) -> DispatchResult {269		<PalletCommon<T>>::set_collection_properties(collection, sender, properties.into_iter())270	}271272	/// Delete properties of the collection, associated with the provided keys.273	pub fn delete_collection_properties(274		collection: &FungibleHandle<T>,275		sender: &T::CrossAccountId,276		property_keys: Vec<PropertyKey>,277	) -> DispatchResult {278		<PalletCommon<T>>::delete_collection_properties(279			collection,280			sender,281			property_keys.into_iter(),282		)283	}284285	/// Checks if collection has tokens. Return `true` if it has.286	fn collection_has_tokens(collection_id: CollectionId) -> bool {287		<TotalSupply<T>>::get(collection_id) != 0288	}289290	/// Burns the specified amount of the token. If the token balance291	/// or total supply is less than the given value,292	/// it will return [DispatchError].293	pub fn burn(294		collection: &FungibleHandle<T>,295		owner: &T::CrossAccountId,296		amount: u128,297	) -> DispatchResult {298		let total_supply = <TotalSupply<T>>::get(collection.id)299			.checked_sub(amount)300			.ok_or(<CommonError<T>>::TokenValueTooLow)?;301302		let balance = <Balance<T>>::get((collection.id, owner))303			.checked_sub(amount)304			.ok_or(<CommonError<T>>::TokenValueTooLow)?;305306		// Foreign collection check307		ensure!(!collection.flags.foreign, <CommonError<T>>::NoPermission);308309		if collection.permissions.access() == AccessMode::AllowList {310			collection.check_allowlist(owner)?;311		}312313		// =========314315		if balance == 0 {316			<Balance<T>>::remove((collection.id, owner));317			<PalletStructure<T>>::unnest_if_nested(owner, collection.id, TokenId::default());318		} else {319			<Balance<T>>::insert((collection.id, owner), balance);320		}321		<TotalSupply<T>>::insert(collection.id, total_supply);322323		<PalletEvm<T>>::deposit_log(324			ERC20Events::Transfer {325				from: *owner.as_eth(),326				to: H160::default(),327				value: amount.into(),328			}329			.to_log(collection_id_to_address(collection.id)),330		);331		<PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(332			collection.id,333			TokenId::default(),334			owner.clone(),335			amount,336		));337		Ok(())338	}339340	/// Burns the specified amount of the token.341	pub fn burn_foreign(342		collection: &FungibleHandle<T>,343		owner: &T::CrossAccountId,344		amount: u128,345	) -> DispatchResult {346		let total_supply = <TotalSupply<T>>::get(collection.id)347			.checked_sub(amount)348			.ok_or(<CommonError<T>>::TokenValueTooLow)?;349350		let balance = <Balance<T>>::get((collection.id, owner))351			.checked_sub(amount)352			.ok_or(<CommonError<T>>::TokenValueTooLow)?;353		// =========354355		if balance == 0 {356			<Balance<T>>::remove((collection.id, owner));357			<PalletStructure<T>>::unnest_if_nested(owner, collection.id, TokenId::default());358		} else {359			<Balance<T>>::insert((collection.id, owner), balance);360		}361		<TotalSupply<T>>::insert(collection.id, total_supply);362363		<PalletEvm<T>>::deposit_log(364			ERC20Events::Transfer {365				from: *owner.as_eth(),366				to: H160::default(),367				value: amount.into(),368			}369			.to_log(collection_id_to_address(collection.id)),370		);371		<PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(372			collection.id,373			TokenId::default(),374			owner.clone(),375			amount,376		));377		Ok(())378	}379380	/// Transfers the specified amount of tokens. Will check that381	/// the transfer is allowed for the token.382	///383	/// - `from`: Owner of tokens to transfer.384	/// - `to`: Recepient of transfered tokens.385	/// - `amount`: Amount of tokens to transfer.386	/// - `collection`: Collection that contains the token387	pub fn transfer(388		collection: &FungibleHandle<T>,389		from: &T::CrossAccountId,390		to: &T::CrossAccountId,391		amount: u128,392		nesting_budget: &dyn Budget,393	) -> DispatchResult {394		ensure!(395			collection.limits.transfers_enabled(),396			<CommonError<T>>::TransferNotAllowed,397		);398399		if collection.permissions.access() == AccessMode::AllowList {400			collection.check_allowlist(from)?;401			collection.check_allowlist(to)?;402		}403		<PalletCommon<T>>::ensure_correct_receiver(to)?;404405		let balance_from = <Balance<T>>::get((collection.id, from))406			.checked_sub(amount)407			.ok_or(<CommonError<T>>::TokenValueTooLow)?;408		let balance_to = if from != to && amount != 0 {409			Some(410				<Balance<T>>::get((collection.id, to))411					.checked_add(amount)412					.ok_or(ArithmeticError::Overflow)?,413			)414		} else {415			None416		};417418		// =========419420		if let Some(balance_to) = balance_to {421			// from != to && amount != 0422423			<PalletStructure<T>>::nest_if_sent_to_token(424				from.clone(),425				to,426				collection.id,427				TokenId::default(),428				nesting_budget,429			)?;430431			if balance_from == 0 {432				<Balance<T>>::remove((collection.id, from));433				<PalletStructure<T>>::unnest_if_nested(from, collection.id, TokenId::default());434			} else {435				<Balance<T>>::insert((collection.id, from), balance_from);436			}437			<Balance<T>>::insert((collection.id, to), balance_to);438		}439440		<PalletEvm<T>>::deposit_log(441			ERC20Events::Transfer {442				from: *from.as_eth(),443				to: *to.as_eth(),444				value: amount.into(),445			}446			.to_log(collection_id_to_address(collection.id)),447		);448		<PalletCommon<T>>::deposit_event(CommonEvent::Transfer(449			collection.id,450			TokenId::default(),451			from.clone(),452			to.clone(),453			amount,454		));455		Ok(())456	}457458	/// Minting tokens for multiple IDs.459	/// It is a utility function used in [`create_multiple_items`][`Pallet::create_multiple_items`]460	/// and [`create_multiple_items_foreign`][`Pallet::create_multiple_items_foreign`]461	pub fn create_multiple_items_common(462		collection: &FungibleHandle<T>,463		sender: &T::CrossAccountId,464		data: BTreeMap<T::CrossAccountId, u128>,465		nesting_budget: &dyn Budget,466	) -> DispatchResult {467		let total_supply = data468			.iter()469			.map(|(_, v)| *v)470			.try_fold(<TotalSupply<T>>::get(collection.id), |acc, v| {471				acc.checked_add(v)472			})473			.ok_or(ArithmeticError::Overflow)?;474475		for (to, _) in data.iter() {476			<PalletStructure<T>>::check_nesting(477				sender.clone(),478				to,479				collection.id,480				TokenId::default(),481				nesting_budget,482			)?;483		}484485		let updated_balances = data486			.into_iter()487			.map(|(user, amount)| {488				let updated_balance = <Balance<T>>::get((collection.id, &user))489					.checked_add(amount)490					.ok_or(ArithmeticError::Overflow)?;491				Ok((user, amount, updated_balance))492			})493			.collect::<Result<Vec<_>, DispatchError>>()?;494495		// =========496497		<TotalSupply<T>>::insert(collection.id, total_supply);498		for (user, amount, updated_balance) in updated_balances {499			<Balance<T>>::insert((collection.id, &user), updated_balance);500			<PalletStructure<T>>::nest_if_sent_to_token_unchecked(501				&user,502				collection.id,503				TokenId::default(),504			);505			<PalletEvm<T>>::deposit_log(506				ERC20Events::Transfer {507					from: H160::default(),508					to: *user.as_eth(),509					value: amount.into(),510				}511				.to_log(collection_id_to_address(collection.id)),512			);513			<PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(514				collection.id,515				TokenId::default(),516				user.clone(),517				amount,518			));519		}520521		Ok(())522	}523524	/// Minting tokens for multiple IDs.525	/// See [`create_item`][`Pallet::create_item`] for more details.526	pub fn create_multiple_items(527		collection: &FungibleHandle<T>,528		sender: &T::CrossAccountId,529		data: BTreeMap<T::CrossAccountId, u128>,530		nesting_budget: &dyn Budget,531	) -> DispatchResult {532		// Foreign collection check533		ensure!(!collection.flags.foreign, <CommonError<T>>::NoPermission);534535		if !collection.is_owner_or_admin(sender) {536			ensure!(537				collection.permissions.mint_mode(),538				<CommonError<T>>::PublicMintingNotAllowed539			);540			collection.check_allowlist(sender)?;541542			for (owner, _) in data.iter() {543				collection.check_allowlist(owner)?;544			}545		}546547		Self::create_multiple_items_common(collection, sender, data, nesting_budget)548	}549550	/// Minting tokens for multiple IDs.551	/// See [`create_item_foreign`][`Pallet::create_item_foreign`] for more details.552	pub fn create_multiple_items_foreign(553		collection: &FungibleHandle<T>,554		sender: &T::CrossAccountId,555		data: BTreeMap<T::CrossAccountId, u128>,556		nesting_budget: &dyn Budget,557	) -> DispatchResult {558		Self::create_multiple_items_common(collection, sender, data, nesting_budget)559	}560561	fn set_allowance_unchecked(562		collection: &FungibleHandle<T>,563		owner: &T::CrossAccountId,564		spender: &T::CrossAccountId,565		amount: u128,566	) {567		if amount == 0 {568			<Allowance<T>>::remove((collection.id, owner, spender));569		} else {570			<Allowance<T>>::insert((collection.id, owner, spender), amount);571		}572573		<PalletEvm<T>>::deposit_log(574			ERC20Events::Approval {575				owner: *owner.as_eth(),576				spender: *spender.as_eth(),577				value: amount.into(),578			}579			.to_log(collection_id_to_address(collection.id)),580		);581		<PalletCommon<T>>::deposit_event(CommonEvent::Approved(582			collection.id,583			TokenId(0),584			owner.clone(),585			spender.clone(),586			amount,587		));588	}589590	/// Set allowance for the spender to `transfer` or `burn` owner's tokens.591	///592	/// - `collection`: Collection that contains the token593	/// - `owner`: Owner of tokens that sets the allowance.594	/// - `spender`: Recipient of the allowance rights.595	/// - `amount`: Amount of tokens the spender is allowed to `transfer` or `burn`.596	pub fn set_allowance(597		collection: &FungibleHandle<T>,598		owner: &T::CrossAccountId,599		spender: &T::CrossAccountId,600		amount: u128,601	) -> DispatchResult {602		if collection.permissions.access() == AccessMode::AllowList {603			collection.check_allowlist(owner)?;604			collection.check_allowlist(spender)?;605		}606607		if <Balance<T>>::get((collection.id, owner)) < amount {608			ensure!(609				collection.ignores_owned_amount(owner),610				<CommonError<T>>::CantApproveMoreThanOwned611			);612		}613614		// =========615616		Self::set_allowance_unchecked(collection, owner, spender, amount);617		Ok(())618	}619620	/// Set allowance for the spender to `transfer` or `burn` owner's tokens from eth mirror.621	///622	/// - `collection`: Collection that contains the token623	/// - `sender`: Owner of tokens that sets the allowance.624	/// - `from`: Owner's eth mirror.625	/// - `to`: Recipient of the allowance rights.626	/// - `amount`: Amount of tokens the spender is allowed to `transfer` or `burn`.627	pub fn set_allowance_from(628		collection: &FungibleHandle<T>,629		sender: &T::CrossAccountId,630		from: &T::CrossAccountId,631		to: &T::CrossAccountId,632		amount: u128,633	) -> DispatchResult {634		if collection.permissions.access() == AccessMode::AllowList {635			collection.check_allowlist(sender)?;636			collection.check_allowlist(from)?;637			collection.check_allowlist(to)?;638		}639640		ensure!(641			sender.conv_eq(from),642			<CommonError<T>>::AddressIsNotEthMirror643		);644645		if <Balance<T>>::get((collection.id, from)) < amount {646			ensure!(647				collection.limits.owner_can_transfer()648					&& (collection.is_owner_or_admin(sender) || collection.is_owner_or_admin(from)),649				<CommonError<T>>::CantApproveMoreThanOwned650			);651		}652653		// =========654655		Self::set_allowance_unchecked(collection, from, to, amount);656		Ok(())657	}658659	/// Checks if a non-owner has (enough) allowance from the owner to perform operations on the tokens.660	/// Returns the expected remaining allowance - it should be set manually if the transaction proceeds.661	///662	/// - `collection`: Collection that contains the token.663	/// - `spender`: CrossAccountId who has the allowance rights.664	/// - `from`: The owner of the tokens who sets the allowance.665	/// - `amount`: Amount of tokens by which the allowance sholud be reduced.666	fn check_allowed(667		collection: &FungibleHandle<T>,668		spender: &T::CrossAccountId,669		from: &T::CrossAccountId,670		amount: u128,671		nesting_budget: &dyn Budget,672	) -> Result<Option<u128>, DispatchError> {673		if spender.conv_eq(from) {674			return Ok(None);675		}676		if collection.permissions.access() == AccessMode::AllowList {677			// `from`, `to` checked in [`transfer`]678			collection.check_allowlist(spender)?;679		}680681		if collection.ignores_token_restrictions(spender) {682			return Ok(Self::compute_allowance_decrease(683				collection, from, spender, amount,684			));685		}686687		if let Some(source) = T::CrossTokenAddressMapping::address_to_token(from) {688			ensure!(689				<PalletStructure<T>>::check_indirectly_owned(690					spender.clone(),691					source.0,692					source.1,693					None,694					nesting_budget695				)?,696				<CommonError<T>>::ApprovedValueTooLow,697			);698			return Ok(None);699		}700701		let allowance = Self::compute_allowance_decrease(collection, from, spender, amount);702		ensure!(allowance.is_some(), <CommonError<T>>::ApprovedValueTooLow);703704		Ok(allowance)705	}706707	/// Returns `Some(amount)` if the `spender` have allowance to spend this amount.708	/// Otherwise, it returns `None`.709	fn compute_allowance_decrease(710		collection: &FungibleHandle<T>,711		from: &T::CrossAccountId,712		spender: &T::CrossAccountId,713		amount: u128,714	) -> Option<u128> {715		<Allowance<T>>::get((collection.id, from, spender)).checked_sub(amount)716	}717718	/// Transfer fungible tokens from one account to another.719	/// Same as the [`transfer`][`Pallet::transfer`] but spender doesn't needs to be an owner of the token pieces.720	/// The owner should set allowance for the spender to transfer pieces.721	///	See [`set_allowance`][`Pallet::set_allowance`] for more details.722723	pub fn transfer_from(724		collection: &FungibleHandle<T>,725		spender: &T::CrossAccountId,726		from: &T::CrossAccountId,727		to: &T::CrossAccountId,728		amount: u128,729		nesting_budget: &dyn Budget,730	) -> DispatchResult {731		let allowance = Self::check_allowed(collection, spender, from, amount, nesting_budget)?;732733		// =========734735		Self::transfer(collection, from, to, amount, nesting_budget)?;736		if let Some(allowance) = allowance {737			Self::set_allowance_unchecked(collection, from, spender, allowance);738		}739		Ok(())740	}741742	/// Burn fungible tokens from the account.743	///744	/// Same as the [`burn`][`Pallet::burn`] but spender doesn't need to be an owner of the tokens. The `from` should745	/// set allowance for the spender to burn tokens.746	/// See [`set_allowance`][`Pallet::set_allowance`] for more details.747	pub fn burn_from(748		collection: &FungibleHandle<T>,749		spender: &T::CrossAccountId,750		from: &T::CrossAccountId,751		amount: u128,752		nesting_budget: &dyn Budget,753	) -> DispatchResult {754		let allowance = Self::check_allowed(collection, spender, from, amount, nesting_budget)?;755756		// =========757758		Self::burn(collection, from, amount)?;759		if let Some(allowance) = allowance {760			Self::set_allowance_unchecked(collection, from, spender, allowance);761		}762		Ok(())763	}764765	///	Creates fungible token.766	///767	/// The sender should be the owner/admin of the collection or collection should be configured768	/// to allow public minting.769	///770	/// - `data`: Contains user who will become the owners of the tokens and amount771	///   of tokens he will receive.772	pub fn create_item(773		collection: &FungibleHandle<T>,774		sender: &T::CrossAccountId,775		data: CreateItemData<T>,776		nesting_budget: &dyn Budget,777	) -> DispatchResult {778		Self::create_multiple_items(779			collection,780			sender,781			[(data.0, data.1)].into_iter().collect(),782			nesting_budget,783		)784	}785786	///	Creates fungible token.787	///788	/// - `data`: Contains user who will become the owners of the tokens and amount789	///   of tokens he will receive.790	pub fn create_item_foreign(791		collection: &FungibleHandle<T>,792		sender: &T::CrossAccountId,793		data: CreateItemData<T>,794		nesting_budget: &dyn Budget,795	) -> DispatchResult {796		Self::create_multiple_items_foreign(797			collection,798			sender,799			[(data.0, data.1)].into_iter().collect(),800			nesting_budget,801		)802	}803804	/// Returns 10 tokens owners in no particular order805	///806	/// There is no direct way to get token holders in ascending order,807	/// since `iter_prefix` returns values in no particular order.808	/// Therefore, getting the 10 largest holders with a large value of holders809	/// can lead to impact memory allocation + sorting with  `n * log (n)`.810	pub fn token_owners(811		collection: CollectionId,812		_token: TokenId,813	) -> Option<Vec<T::CrossAccountId>> {814		let res: Vec<T::CrossAccountId> = <Balance<T>>::iter_prefix((collection,))815			.map(|(owner, _amount)| owner)816			.take(10)817			.collect();818819		if res.is_empty() {820			None821		} else {822			Some(res)823		}824	}825}
modifiedpallets/nonfungible/src/lib.rsdiffbeforeafterboth
--- a/pallets/nonfungible/src/lib.rs
+++ b/pallets/nonfungible/src/lib.rs
@@ -1246,7 +1246,7 @@
 			collection.check_allowlist(spender)?;
 		}
 
-		if collection.limits.owner_can_transfer() && collection.is_owner_or_admin(spender) {
+		if collection.ignores_token_restrictions(spender) {
 			return Ok(());
 		}
 
@@ -1269,11 +1269,8 @@
 		if <CollectionAllowance<T>>::get((collection.id, from, spender)) {
 			return Ok(());
 		}
-		ensure!(
-			collection.ignores_allowance(spender),
-			<CommonError<T>>::ApprovedValueTooLow
-		);
-		Ok(())
+
+		Err(<CommonError<T>>::ApprovedValueTooLow.into())
 	}
 
 	/// Transfer NFT token from one account to another.
modifiedpallets/refungible/src/lib.rsdiffbeforeafterboth
--- a/pallets/refungible/src/lib.rs
+++ b/pallets/refungible/src/lib.rs
@@ -1177,6 +1177,13 @@
 			// `from`, `to` checked in [`transfer`]
 			collection.check_allowlist(spender)?;
 		}
+
+		if collection.ignores_token_restrictions(spender) {
+			return Ok(Self::compute_allowance_decrease(
+				collection, token, from, &spender, amount,
+			));
+		}
+
 		if let Some(source) = T::CrossTokenAddressMapping::address_to_token(from) {
 			// TODO: should collection owner be allowed to perform this transfer?
 			ensure!(
@@ -1191,21 +1198,30 @@
 			);
 			return Ok(None);
 		}
-		let allowance =
-			<Allowance<T>>::get((collection.id, token, from, &spender)).checked_sub(amount);
 
+		let allowance = Self::compute_allowance_decrease(collection, token, from, &spender, amount);
+		if allowance.is_some() {
+			return Ok(allowance);
+		}
+
 		// Allowance (if any) would be reduced if spender is also wallet operator
 		if <CollectionAllowance<T>>::get((collection.id, from, spender)) {
 			return Ok(allowance);
 		}
 
-		if allowance.is_none() {
-			ensure!(
-				collection.ignores_allowance(spender),
-				<CommonError<T>>::ApprovedValueTooLow
-			);
-		}
-		Ok(allowance)
+		Err(<CommonError<T>>::ApprovedValueTooLow.into())
+	}
+
+	/// Returns `Some(amount)` if the `spender` have allowance to spend this amount.
+	/// Otherwise, it returns `None`.
+	fn compute_allowance_decrease(
+		collection: &RefungibleHandle<T>,
+		token: TokenId,
+		from: &T::CrossAccountId,
+		spender: &T::CrossAccountId,
+		amount: u128,
+	) -> Option<u128> {
+		<Allowance<T>>::get((collection.id, token, from, spender)).checked_sub(amount)
 	}
 
 	/// Transfer RFT token pieces from one account to another.
modifiedtests/src/nesting/unnest.test.tsdiffbeforeafterboth
--- a/tests/src/nesting/unnest.test.ts
+++ b/tests/src/nesting/unnest.test.ts
@@ -16,14 +16,17 @@
 
 import {IKeyringPair} from '@polkadot/types/types';
 import {expect, itSub, Pallets, usingPlaygrounds} from '../util';
+import {UniqueFTCollection, UniqueNFToken, UniqueRFToken} from '../util/playgrounds/unique';
 
 describe('Integration Test: Unnesting', () => {
   let alice: IKeyringPair;
+  let bob: IKeyringPair;
+  let charlie: IKeyringPair;
 
   before(async () => {
     await usingPlaygrounds(async (helper, privateKey) => {
       const donor = await privateKey({filename: __filename});
-      [alice] = await helper.arrange.createAccounts([50n], donor);
+      [alice, bob, charlie] = await helper.arrange.createAccounts([200n, 50n, 50n], donor);
     });
   });
 
@@ -83,6 +86,188 @@
     expect(await token.getBalance(targetToken.nestingAccount())).to.be.equal(0n);
     expect(await targetToken.getChildren()).to.be.length(0);
   });
+
+  async function checkNestedAmountState({
+    expectedBalance,
+    childrenShouldPresent,
+    nested,
+    targetNft,
+  }: {
+    expectedBalance: bigint,
+    childrenShouldPresent: boolean,
+    nested: UniqueFTCollection | UniqueRFToken,
+    targetNft: UniqueNFToken,
+  }) {
+    const balance = await nested.getBalance(targetNft.nestingAccount());
+    expect(balance).to.be.equal(expectedBalance);
+
+    const children = await targetNft.getChildren();
+
+    if (childrenShouldPresent) {
+      expect(children[0]).to.be.deep.equal({
+        collectionId: nested.collectionId,
+        tokenId: (nested instanceof UniqueFTCollection) ? 0 : nested.tokenId,
+      });
+    } else {
+      expect(children.length).to.be.equal(0);
+    }
+  }
+
+  function ownerOrAdminUnnestCases(modes: ('ft' | 'nft' | 'rft')[]): {
+    mode: 'ft' | 'nft' | 'rft',
+    sender: string,
+    op: 'transfer' | 'burn',
+    requiredPallets: Pallets[],
+  }[] {
+    const senders = ['owner', 'admin'];
+    const ops = ['transfer', 'burn'];
+
+    const cases = [];
+    for (const mode of modes) {
+      const requiredPallets = (mode === 'rft')
+        ? [Pallets.ReFungible]
+        : [];
+
+      for (const sender of senders) {
+        for (const op of ops) {
+          cases.push({
+            mode: mode as 'ft' | 'nft' | 'rft',
+            sender,
+            op: op as 'transfer' | 'burn',
+            requiredPallets,
+          });
+        }
+      }
+    }
+
+    return cases;
+  }
+
+  ownerOrAdminUnnestCases(['ft', 'rft']).map(testCase =>
+    itSub.ifWithPallets(`[${testCase.mode}]: allows a collection ${testCase.sender} to ${testCase.op} nested token`, testCase.requiredPallets, async({helper}) => {
+      const owner = alice;
+      const admin = bob;
+
+      const unnester = (testCase.sender === 'owner')
+        ? owner
+        : admin;
+
+      const collectionNFT = await helper.nft.mintCollection(owner);
+      await collectionNFT.setPermissions(owner, {nesting: {tokenOwner: true}});
+
+      const collectionNested = await helper[testCase.mode as 'ft' | 'rft'].mintCollection(owner, {
+        limits: {
+          ownerCanTransfer: true,
+        },
+      });
+      await collectionNested.addAdmin(owner, {Substrate: admin.address});
+
+      const targetNft = await collectionNFT.mintToken(owner, {Substrate: charlie.address});
+
+      let nested: UniqueFTCollection | UniqueRFToken;
+      const totalAmount = 5n;
+      const firstUnnestAmount = 2n;
+      const restUnnestAmount = totalAmount - firstUnnestAmount;
+
+      if (collectionNested instanceof UniqueFTCollection) {
+        await collectionNested.mint(owner, totalAmount, {Substrate: charlie.address});
+        nested = collectionNested;
+      } else {
+        nested = await collectionNested.mintToken(owner, totalAmount, {Substrate: charlie.address});
+      }
+
+      // transfer/burn `amount` of nested assets by `unnester`.
+      const doOperationAndCheck = async ({
+        amount,
+        shouldBeNestedAfterOp,
+      }: {
+        amount: bigint,
+        shouldBeNestedAfterOp: boolean,
+      }) => {
+        const nestedBalanceBeforeOp = await nested.getBalance(targetNft.nestingAccount());
+
+        if (testCase.op === 'transfer') {
+          const bobBalanceBeforeOp = await nested.getBalance({Substrate: bob.address});
+
+          await nested.transferFrom(unnester, targetNft.nestingAccount(), {Substrate: bob.address}, amount);
+          expect(await nested.getBalance({Substrate: bob.address})).to.be.equal(bobBalanceBeforeOp + amount);
+        } else {
+          if (nested instanceof UniqueFTCollection) {
+            await nested.burnTokensFrom(unnester, targetNft.nestingAccount(), amount);
+          } else {
+            await nested.burnFrom(unnester, targetNft.nestingAccount(), amount);
+          }
+        }
+
+        await checkNestedAmountState({
+          expectedBalance: nestedBalanceBeforeOp - amount,
+          childrenShouldPresent: shouldBeNestedAfterOp,
+          nested,
+          targetNft,
+        });
+      };
+
+      // Initial setup: nest (fungibles/rft parts).
+      // Check NFT's balance of nested assets and NFT's children.
+      await nested.transfer(charlie, targetNft.nestingAccount(), totalAmount);
+      await checkNestedAmountState({
+        expectedBalance: totalAmount,
+        childrenShouldPresent: true,
+        nested,
+        targetNft,
+      });
+
+      // Transfer/burn only a part of nested assets.
+      // Check that NFT's balance of the nested assets correctly decreased and NFT's children are not changed.
+      await doOperationAndCheck({
+        amount: firstUnnestAmount,
+        shouldBeNestedAfterOp: true,
+      });
+
+      // Transfer/burn all remaining nested assets.
+      // Check that NFT's balance of the nested assets is 0 and NFT has no more children.
+      await doOperationAndCheck({
+        amount: restUnnestAmount,
+        shouldBeNestedAfterOp: false,
+      });
+    }));
+
+  ownerOrAdminUnnestCases(['nft']).map(testCase =>
+    itSub(`[nft]: allows a collection ${testCase.sender} to ${testCase.op} nested token`, async ({helper}) => {
+      const owner = alice;
+      const admin = bob;
+
+      const unnester = (testCase.sender === 'owner')
+        ? owner
+        : admin;
+
+      const collectionNFT = await helper.nft.mintCollection(owner);
+      await collectionNFT.setPermissions(owner, {nesting: {tokenOwner: true}});
+
+      const collectionNested = await helper.nft.mintCollection(owner, {
+        limits: {
+          ownerCanTransfer: true,
+        },
+      });
+      await collectionNested.addAdmin(owner, {Substrate: admin.address});
+
+      const targetNft = await collectionNFT.mintToken(owner, {Substrate: charlie.address});
+      const nested = await collectionNested.mintToken(owner, {Substrate: charlie.address});
+
+      await nested.transfer(charlie, targetNft.nestingAccount());
+      expect(await targetNft.getChildren()).to.be.deep.equal([{
+        collectionId: nested.collectionId,
+        tokenId: nested.tokenId,
+      }]);
+
+      if (testCase.op === 'transfer') {
+        await nested.transferFrom(unnester, targetNft.nestingAccount(), {Substrate: bob.address});
+      } else {
+        await nested.burnFrom(unnester, targetNft.nestingAccount());
+      }
+
+      expect((await targetNft.getChildren()).length).to.be.equal(0);
+    }));
 });
 
 describe('Negative Test: Unnesting', () => {