git.delta.rocks / unique-network / refs/commits / c6354cf493a0

difftreelog

feat add ApproveForAll to Eth and Sub

Grigoriy Simonov2022-12-06parent: #e7f81f3.patch.diff
in: master

39 files changed

modifiedclient/rpc/src/lib.rsdiffbeforeafterboth
--- a/client/rpc/src/lib.rs
+++ b/client/rpc/src/lib.rs
@@ -246,6 +246,16 @@
 		token_id: TokenId,
 		at: Option<BlockHash>,
 	) -> Result<Option<String>>;
+
+	/// Get whether an operator is approved by a given owner.
+	#[method(name = "unique_isApprovedForAll")]
+	fn is_approved_for_all(
+		&self,
+		collection: CollectionId,
+		owner: CrossAccountId,
+		operator: CrossAccountId,
+		at: Option<BlockHash>,
+	) -> Result<bool>;
 }
 
 mod app_promotion_unique_rpc {
@@ -569,6 +579,7 @@
 	pass_method!(effective_collection_limits(collection_id: CollectionId) -> Option<CollectionLimits>, unique_api);
 	pass_method!(total_pieces(collection_id: CollectionId, token_id: TokenId) -> Option<String> => |o| o.map(|number| number.to_string()) , unique_api);
 	pass_method!(token_owners(collection: CollectionId, token: TokenId) -> Vec<CrossAccountId>, unique_api);
+	pass_method!(is_approved_for_all(collection: CollectionId, owner: CrossAccountId, operator: CrossAccountId) -> bool, unique_api);
 }
 
 impl<C, Block, BlockNumber, CrossAccountId, AccountId>
modifiedpallets/common/src/lib.rsdiffbeforeafterboth
--- a/pallets/common/src/lib.rs
+++ b/pallets/common/src/lib.rs
@@ -472,6 +472,18 @@
 			u128,
 		),
 
+		/// Amount pieces of token owned by `sender` was approved for `spender`.
+		ApprovedForAll(
+			/// Id of collection to which item is belong.
+			CollectionId,
+			/// Owner of a wallet.
+			T::CrossAccountId,
+			/// Id for which operator status was granted or rewoked.
+			T::CrossAccountId,
+			/// Is operator status was granted or rewoked.
+			bool,
+		),
+
 		/// The colletion property has been added or edited.
 		CollectionPropertySet(
 			/// Id of collection to which property has been set.
@@ -1521,6 +1533,9 @@
 
 	/// The price of retrieving token owner
 	fn token_owner() -> Weight;
+
+	/// The price of setting approval for all
+	fn set_approval_for_all() -> Weight;
 }
 
 /// Weight info extension trait for refungible pallet.
@@ -1828,6 +1843,20 @@
 
 	/// Get extension for RFT collection.
 	fn refungible_extensions(&self) -> Option<&dyn RefungibleExtensions<T>>;
+
+	/// An operator is allowed to transfer all tokens of the sender on their behalf.
+	/// * `owner` - Token owner
+	/// * `operator` - Operator
+	/// * `approve` - Is operator enabled or disabled
+	fn set_approval_for_all(
+		&self,
+		owner: T::CrossAccountId,
+		operator: T::CrossAccountId,
+		approve: bool,
+	) -> DispatchResultWithPostInfo;
+
+	/// Tells whether an operator is approved by a given owner.
+	fn is_approved_for_all(&self, owner: T::CrossAccountId, operator: T::CrossAccountId) -> bool;
 }
 
 /// Extension for RFT collection.
modifiedpallets/fungible/src/common.rsdiffbeforeafterboth
--- a/pallets/fungible/src/common.rs
+++ b/pallets/fungible/src/common.rs
@@ -107,6 +107,10 @@
 	fn token_owner() -> Weight {
 		Weight::zero()
 	}
+
+	fn set_approval_for_all() -> Weight {
+		Weight::zero()
+	}
 }
 
 /// Implementation of `CommonCollectionOperations` for `FungibleHandle`. It wraps FungibleHandle Pallete
@@ -424,4 +428,17 @@
 		}
 		<TotalSupply<T>>::try_get(self.id).ok()
 	}
+
+	fn set_approval_for_all(
+		&self,
+		_owner: T::CrossAccountId,
+		_operator: T::CrossAccountId,
+		_approve: bool,
+	) -> DispatchResultWithPostInfo {
+		fail!(<Error<T>>::SettingApprovalForAllNotAllowed)
+	}
+
+	fn is_approved_for_all(&self, _owner: T::CrossAccountId, _operator: T::CrossAccountId) -> bool {
+		false
+	}
 }
modifiedpallets/fungible/src/lib.rsdiffbeforeafterboth
--- a/pallets/fungible/src/lib.rs
+++ b/pallets/fungible/src/lib.rs
@@ -127,6 +127,8 @@
 		FungibleDisallowsNesting,
 		/// Setting item properties is not allowed.
 		SettingPropertiesNotAllowed,
+		/// Setting approval for all is not allowed.
+		SettingApprovalForAllNotAllowed,
 	}
 
 	#[pallet::config]
modifiedpallets/nonfungible/src/benchmarking.rsdiffbeforeafterboth
--- a/pallets/nonfungible/src/benchmarking.rs
+++ b/pallets/nonfungible/src/benchmarking.rs
@@ -222,4 +222,18 @@
 		let item = create_max_item(&collection, &owner, owner.clone())?;
 
 	}: {collection.token_owner(item)}
+
+	set_approval_for_all {
+		bench_init!{
+			owner: sub; collection: collection(owner);
+			operator: cross_from_sub(owner); owner: cross_sub;
+		};
+	}: {<Pallet<T>>::set_approval_for_all(&collection, &owner, &operator, true)}
+
+	is_approved_for_all {
+		bench_init!{
+			owner: sub; collection: collection(owner);
+			operator: cross_from_sub(owner); owner: cross_sub;
+		};
+	}: {<Pallet<T>>::is_approved_for_all(&collection, &owner, &operator)}
 }
modifiedpallets/nonfungible/src/common.rsdiffbeforeafterboth
--- a/pallets/nonfungible/src/common.rs
+++ b/pallets/nonfungible/src/common.rs
@@ -122,6 +122,10 @@
 	fn token_owner() -> Weight {
 		<SelfWeightOf<T>>::token_owner()
 	}
+
+	fn set_approval_for_all() -> Weight {
+		<SelfWeightOf<T>>::set_approval_for_all()
+	}
 }
 
 fn map_create_data<T: Config>(
@@ -512,4 +516,20 @@
 			None
 		}
 	}
+
+	fn set_approval_for_all(
+		&self,
+		owner: T::CrossAccountId,
+		operator: T::CrossAccountId,
+		approve: bool,
+	) -> DispatchResultWithPostInfo {
+		with_weight(
+			<Pallet<T>>::set_approval_for_all(self, &owner, &operator, approve),
+			<CommonWeights<T>>::set_approval_for_all(),
+		)
+	}
+
+	fn is_approved_for_all(&self, owner: T::CrossAccountId, operator: T::CrossAccountId) -> bool {
+		<Pallet<T>>::is_approved_for_all(self, &owner, &operator)
+	}
 }
modifiedpallets/nonfungible/src/erc.rsdiffbeforeafterboth
--- a/pallets/nonfungible/src/erc.rs
+++ b/pallets/nonfungible/src/erc.rs
@@ -469,15 +469,23 @@
 		Ok(())
 	}
 
-	/// @dev Not implemented
+	/// @notice Sets or unsets the approval of a given operator.
+	///  An operator is allowed to transfer all tokens of the sender on their behalf.
+	/// @param operator Operator
+	/// @param approved Is operator enabled or disabled
+	#[weight(<SelfWeightOf<T>>::set_approval_for_all())]
 	fn set_approval_for_all(
 		&mut self,
-		_caller: caller,
-		_operator: address,
-		_approved: bool,
+		caller: caller,
+		operator: address,
+		approved: bool,
 	) -> Result<void> {
-		// TODO: Not implemetable
-		Err("not implemented".into())
+		let caller = T::CrossAccountId::from_eth(caller);
+		let operator = T::CrossAccountId::from_eth(operator);
+
+		<Pallet<T>>::set_approval_for_all(self, &caller, &operator, approved)
+			.map_err(dispatch_to_evm::<T>)?;
+		Ok(())
 	}
 
 	/// @dev Not implemented
@@ -486,10 +494,13 @@
 		Err("not implemented".into())
 	}
 
-	/// @dev Not implemented
-	fn is_approved_for_all(&self, _owner: address, _operator: address) -> Result<address> {
-		// TODO: Not implemetable
-		Err("not implemented".into())
+	/// @notice Tells whether an operator is approved by a given owner.
+	#[weight(<SelfWeightOf<T>>::is_approved_for_all())]
+	fn is_approved_for_all(&self, owner: address, operator: address) -> Result<bool> {
+		let owner = T::CrossAccountId::from_eth(owner);
+		let operator = T::CrossAccountId::from_eth(operator);
+
+		Ok(<Pallet<T>>::is_approved_for_all(self, &owner, &operator))
 	}
 
 	/// @notice Returns collection helper contract address
modifiedpallets/nonfungible/src/lib.rsdiffbeforeafterboth
--- a/pallets/nonfungible/src/lib.rs
+++ b/pallets/nonfungible/src/lib.rs
@@ -272,6 +272,18 @@
 		QueryKind = OptionQuery,
 	>;
 
+	/// Operator set by a wallet owner that could perform certain transactions on all tokens in the wallet.
+	#[pallet::storage]
+	pub type WalletOperator<T: Config> = StorageNMap<
+		Key = (
+			Key<Twox64Concat, CollectionId>,
+			Key<Blake2_128Concat, T::CrossAccountId>,
+			Key<Blake2_128Concat, T::CrossAccountId>,
+		),
+		Value = bool,
+		QueryKind = OptionQuery,
+	>;
+
 	/// Upgrade from the old schema to properties.
 	#[pallet::hooks]
 	impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {
@@ -438,6 +450,7 @@
 		<TokensBurnt<T>>::remove(id);
 		let _ = <Allowance<T>>::clear_prefix((id,), u32::MAX, None);
 		let _ = <AccountBalance<T>>::clear_prefix((id,), u32::MAX, None);
+		let _ = <WalletOperator<T>>::clear_prefix((id,), u32::MAX, None);
 		Ok(())
 	}
 
@@ -1193,6 +1206,9 @@
 		if <Allowance<T>>::get((collection.id, token)).as_ref() == Some(spender) {
 			return Ok(());
 		}
+		if <WalletOperator<T>>::get((collection.id, from, spender)) == Some(true) {
+			return Ok(());
+		}
 		ensure!(
 			collection.ignores_allowance(spender),
 			<CommonError<T>>::ApprovedValueTooLow
@@ -1326,4 +1342,52 @@
 	) -> DispatchResult {
 		Self::create_multiple_items(collection, sender, vec![data], nesting_budget)
 	}
+
+	/// Sets or unsets the approval of a given operator.
+	///
+	/// An operator is allowed to transfer all token pieces of the sender on their behalf.
+	/// - `owner`: Token owner
+	/// - `operator`: Operator
+	/// - `approve`: Is operator enabled or disabled
+	pub fn set_approval_for_all(
+		collection: &NonfungibleHandle<T>,
+		owner: &T::CrossAccountId,
+		operator: &T::CrossAccountId,
+		approve: bool,
+	) -> DispatchResult {
+		if collection.permissions.access() == AccessMode::AllowList {
+			collection.check_allowlist(owner)?;
+			collection.check_allowlist(operator)?;
+		}
+
+		<PalletCommon<T>>::ensure_correct_receiver(operator)?;
+
+		// =========
+
+		<WalletOperator<T>>::insert((collection.id, owner, operator), approve);
+		<PalletEvm<T>>::deposit_log(
+			ERC721Events::ApprovalForAll {
+				owner: *owner.as_eth(),
+				operator: *operator.as_eth(),
+				approved: approve,
+			}
+			.to_log(collection_id_to_address(collection.id)),
+		);
+		<PalletCommon<T>>::deposit_event(CommonEvent::ApprovedForAll(
+			collection.id,
+			owner.clone(),
+			operator.clone(),
+			approve,
+		));
+		Ok(())
+	}
+
+	/// Tells whether an operator is approved by a given owner.
+	pub fn is_approved_for_all(
+		collection: &NonfungibleHandle<T>,
+		owner: &T::CrossAccountId,
+		operator: &T::CrossAccountId,
+	) -> bool {
+		<WalletOperator<T>>::get((collection.id, owner, operator)).unwrap_or(false)
+	}
 }
modifiedpallets/nonfungible/src/stubs/UniqueNFT.rawdiffbeforeafterboth

binary blob — no preview

modifiedpallets/nonfungible/src/stubs/UniqueNFT.soldiffbeforeafterboth
--- a/pallets/nonfungible/src/stubs/UniqueNFT.sol
+++ b/pallets/nonfungible/src/stubs/UniqueNFT.sol
@@ -1020,7 +1020,10 @@
 		dummy = 0;
 	}
 
-	/// @dev Not implemented
+	/// @notice Sets or unsets the approval of a given operator.
+	///  An operator is allowed to transfer all tokens of the sender on their behalf.
+	/// @param operator Operator
+	/// @param approved Is operator enabled or disabled
 	/// @dev EVM selector for this function is: 0xa22cb465,
 	///  or in textual repr: setApprovalForAll(address,bool)
 	function setApprovalForAll(address operator, bool approved) public {
@@ -1040,15 +1043,15 @@
 		return 0x0000000000000000000000000000000000000000;
 	}
 
-	/// @dev Not implemented
+	/// @notice Tells whether an operator is approved by a given owner.
 	/// @dev EVM selector for this function is: 0xe985e9c5,
 	///  or in textual repr: isApprovedForAll(address,address)
-	function isApprovedForAll(address owner, address operator) public view returns (address) {
+	function isApprovedForAll(address owner, address operator) public view returns (bool) {
 		require(false, stub_error);
 		owner;
 		operator;
 		dummy;
-		return 0x0000000000000000000000000000000000000000;
+		return false;
 	}
 
 	/// @notice Returns collection helper contract address
modifiedpallets/nonfungible/src/weights.rsdiffbeforeafterboth
--- a/pallets/nonfungible/src/weights.rs
+++ b/pallets/nonfungible/src/weights.rs
@@ -26,6 +26,7 @@
 #![cfg_attr(rustfmt, rustfmt_skip)]
 #![allow(unused_parens)]
 #![allow(unused_imports)]
+#![allow(missing_docs)]
 #![allow(clippy::unnecessary_cast)]
 
 use frame_support::{traits::Get, weights::{Weight, constants::RocksDbWeight}};
@@ -47,6 +48,8 @@
 	fn set_token_properties(b: u32, ) -> Weight;
 	fn delete_token_properties(b: u32, ) -> Weight;
 	fn token_owner() -> Weight;
+	fn set_approval_for_all() -> Weight;
+	fn is_approved_for_all() -> Weight;
 }
 
 /// Weights for pallet_nonfungible using the Substrate node and recommended hardware.
@@ -195,6 +198,16 @@
 		Weight::from_ref_time(4_366_000)
 			.saturating_add(T::DbWeight::get().reads(1 as u64))
 	}
+	// Storage: Nonfungible WalletOperator (r:0 w:1)
+	fn set_approval_for_all() -> Weight {
+		Weight::from_ref_time(16_231_000 as u64)
+			.saturating_add(T::DbWeight::get().writes(1 as u64))
+	}
+	// Storage: Nonfungible WalletOperator (r:1 w:0)
+	fn is_approved_for_all() -> Weight {
+		Weight::from_ref_time(6_161_000 as u64)
+			.saturating_add(T::DbWeight::get().reads(1 as u64))
+	}
 }
 
 // For backwards compatibility and tests
@@ -342,4 +355,14 @@
 		Weight::from_ref_time(4_366_000)
 			.saturating_add(RocksDbWeight::get().reads(1 as u64))
 	}
+	// Storage: Nonfungible WalletOperator (r:0 w:1)
+	fn set_approval_for_all() -> Weight {
+		Weight::from_ref_time(16_231_000 as u64)
+			.saturating_add(RocksDbWeight::get().writes(1 as u64))
+	}
+	// Storage: Nonfungible WalletOperator (r:1 w:0)
+	fn is_approved_for_all() -> Weight {
+		Weight::from_ref_time(6_161_000 as u64)
+			.saturating_add(RocksDbWeight::get().reads(1 as u64))
+	}
 }
modifiedpallets/refungible/src/benchmarking.rsdiffbeforeafterboth
--- a/pallets/refungible/src/benchmarking.rs
+++ b/pallets/refungible/src/benchmarking.rs
@@ -290,4 +290,18 @@
 		};
 		let item = create_max_item(&collection, &sender, [(owner.clone(), 100)])?;
 	}: {<Pallet<T>>::token_owner(collection.id, item)}
+
+	set_approval_for_all {
+		bench_init!{
+			owner: sub; collection: collection(owner);
+			operator: cross_from_sub(owner); owner: cross_sub;
+		};
+	}: {<Pallet<T>>::set_approval_for_all(&collection, &owner, &operator, true)}
+
+	is_approved_for_all {
+		bench_init!{
+			owner: sub; collection: collection(owner);
+			operator: cross_from_sub(owner); owner: cross_sub;
+		};
+	}: {<Pallet<T>>::is_approved_for_all(&collection, &owner, &operator)}
 }
modifiedpallets/refungible/src/common.rsdiffbeforeafterboth
--- a/pallets/refungible/src/common.rs
+++ b/pallets/refungible/src/common.rs
@@ -152,6 +152,10 @@
 	fn token_owner() -> Weight {
 		<SelfWeightOf<T>>::token_owner()
 	}
+
+	fn set_approval_for_all() -> Weight {
+		<SelfWeightOf<T>>::set_approval_for_all()
+	}
 }
 
 fn map_create_data<T: Config>(
@@ -516,6 +520,22 @@
 	fn total_pieces(&self, token: TokenId) -> Option<u128> {
 		<Pallet<T>>::total_pieces(self.id, token)
 	}
+
+	fn set_approval_for_all(
+		&self,
+		owner: T::CrossAccountId,
+		operator: T::CrossAccountId,
+		approve: bool,
+	) -> DispatchResultWithPostInfo {
+		with_weight(
+			<Pallet<T>>::set_approval_for_all(self, &owner, &operator, approve),
+			<CommonWeights<T>>::set_approval_for_all(),
+		)
+	}
+
+	fn is_approved_for_all(&self, owner: T::CrossAccountId, operator: T::CrossAccountId) -> bool {
+		<Pallet<T>>::is_approved_for_all(self, &owner, &operator)
+	}
 }
 
 impl<T: Config> RefungibleExtensions<T> for RefungibleHandle<T> {
modifiedpallets/refungible/src/erc.rsdiffbeforeafterboth
--- a/pallets/refungible/src/erc.rs
+++ b/pallets/refungible/src/erc.rs
@@ -461,15 +461,23 @@
 		Err("not implemented".into())
 	}
 
-	/// @dev Not implemented
+	/// @notice Sets or unsets the approval of a given operator.
+	///  An operator is allowed to transfer all tokens of the sender on their behalf.
+	/// @param operator Operator
+	/// @param approved Is operator enabled or disabled
+	#[weight(<SelfWeightOf<T>>::set_approval_for_all())]
 	fn set_approval_for_all(
 		&mut self,
-		_caller: caller,
-		_operator: address,
-		_approved: bool,
+		caller: caller,
+		operator: address,
+		approved: bool,
 	) -> Result<void> {
-		// TODO: Not implemetable
-		Err("not implemented".into())
+		let caller = T::CrossAccountId::from_eth(caller);
+		let operator = T::CrossAccountId::from_eth(operator);
+
+		<Pallet<T>>::set_approval_for_all(self, &caller, &operator, approved)
+			.map_err(dispatch_to_evm::<T>)?;
+		Ok(())
 	}
 
 	/// @dev Not implemented
@@ -478,10 +486,13 @@
 		Err("not implemented".into())
 	}
 
-	/// @dev Not implemented
-	fn is_approved_for_all(&self, _owner: address, _operator: address) -> Result<address> {
-		// TODO: Not implemetable
-		Err("not implemented".into())
+	/// @notice Tells whether an operator is approved by a given owner.
+	#[weight(<SelfWeightOf<T>>::is_approved_for_all())]
+	fn is_approved_for_all(&self, owner: address, operator: address) -> Result<bool> {
+		let owner = T::CrossAccountId::from_eth(owner);
+		let operator = T::CrossAccountId::from_eth(operator);
+
+		Ok(<Pallet<T>>::is_approved_for_all(self, &owner, &operator))
 	}
 
 	/// @notice Returns collection helper contract address
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 derivative::Derivative;96use evm_coder::ToLog;97use frame_support::{98	BoundedBTreeMap, BoundedVec, ensure, fail, storage::with_transaction, transactional,99	pallet_prelude::ConstU32,100};101use pallet_evm::{account::CrossAccountId, Pallet as PalletEvm};102use pallet_evm_coder_substrate::WithRecorder;103use pallet_common::{104	CommonCollectionOperations, Error as CommonError, eth::collection_id_to_address,105	Event as CommonEvent, Pallet as PalletCommon,106};107use pallet_structure::Pallet as PalletStructure;108use scale_info::TypeInfo;109use sp_core::H160;110use sp_runtime::{ArithmeticError, DispatchError, DispatchResult, TransactionOutcome};111use sp_std::{vec::Vec, vec, collections::btree_map::BTreeMap};112use up_data_structs::{113	AccessMode, budget::Budget, CollectionId, CollectionFlags, CollectionPropertiesVec,114	CreateCollectionData, CustomDataLimit, mapping::TokenAddressMapping, MAX_ITEMS_PER_BATCH,115	MAX_REFUNGIBLE_PIECES, Property, PropertyKey, PropertyKeyPermission, PropertyPermission,116	PropertyScope, PropertyValue, TokenId, TrySetProperty,117};118119pub use pallet::*;120#[cfg(feature = "runtime-benchmarks")]121pub mod benchmarking;122pub mod common;123pub mod erc;124pub mod erc_token;125pub mod weights;126127#[derive(Derivative, Clone)]128pub struct CreateItemData<CrossAccountId> {129	#[derivative(Debug(format_with = "bounded::map_debug"))]130	pub users: BoundedBTreeMap<CrossAccountId, u128, ConstU32<MAX_ITEMS_PER_BATCH>>,131	#[derivative(Debug(format_with = "bounded::vec_debug"))]132	pub properties: CollectionPropertiesVec,133}134pub(crate) type SelfWeightOf<T> = <T as Config>::WeightInfo;135136/// Token data, stored independently from other data used to describe it137/// for the convenience of database access. Notably contains the token metadata.138#[struct_versioning::versioned(version = 2, upper)]139#[derive(Encode, Decode, Default, TypeInfo, MaxEncodedLen)]140pub struct ItemData {141	pub const_data: BoundedVec<u8, CustomDataLimit>,142143	#[version(..2)]144	pub variable_data: BoundedVec<u8, CustomDataLimit>,145}146147#[frame_support::pallet]148pub mod pallet {149	use super::*;150	use frame_support::{151		Blake2_128, Blake2_128Concat, Twox64Concat, pallet_prelude::*, storage::Key,152		traits::StorageVersion,153	};154	use frame_system::pallet_prelude::*;155	use up_data_structs::{CollectionId, TokenId};156	use super::weights::WeightInfo;157158	#[pallet::error]159	pub enum Error<T> {160		/// Not Refungible item data used to mint in Refungible collection.161		NotRefungibleDataUsedToMintFungibleCollectionToken,162		/// Maximum refungibility exceeded.163		WrongRefungiblePieces,164		/// Refungible token can't be repartitioned by user who isn't owns all pieces.165		RepartitionWhileNotOwningAllPieces,166		/// Refungible token can't nest other tokens.167		RefungibleDisallowsNesting,168		/// Setting item properties is not allowed.169		SettingPropertiesNotAllowed,170	}171172	#[pallet::config]173	pub trait Config:174		frame_system::Config + pallet_common::Config + pallet_structure::Config175	{176		type WeightInfo: WeightInfo;177	}178179	const STORAGE_VERSION: StorageVersion = StorageVersion::new(2);180181	#[pallet::pallet]182	#[pallet::storage_version(STORAGE_VERSION)]183	#[pallet::generate_store(pub(super) trait Store)]184	pub struct Pallet<T>(_);185186	/// Total amount of minted tokens in a collection.187	#[pallet::storage]188	pub type TokensMinted<T: Config> =189		StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;190191	/// Amount of tokens burnt in a collection.192	#[pallet::storage]193	pub type TokensBurnt<T: Config> =194		StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;195196	/// Token data, used to partially describe a token.197	// TODO: remove198	#[pallet::storage]199	#[deprecated(since = "0.2.0", note = "ItemData is no more contains usefull data")]200	pub type TokenData<T: Config> = StorageNMap<201		Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),202		Value = ItemData,203		QueryKind = ValueQuery,204	>;205206	/// Amount of pieces a refungible token is split into.207	#[pallet::storage]208	#[pallet::getter(fn token_properties)]209	pub type TokenProperties<T: Config> = StorageNMap<210		Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),211		Value = up_data_structs::Properties,212		QueryKind = ValueQuery,213		OnEmpty = up_data_structs::TokenProperties,214	>;215216	/// Total amount of pieces for token217	#[pallet::storage]218	pub type TotalSupply<T: Config> = StorageNMap<219		Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),220		Value = u128,221		QueryKind = ValueQuery,222	>;223224	/// Used to enumerate tokens owned by account.225	#[pallet::storage]226	pub type Owned<T: Config> = StorageNMap<227		Key = (228			Key<Twox64Concat, CollectionId>,229			Key<Blake2_128Concat, T::CrossAccountId>,230			Key<Twox64Concat, TokenId>,231		),232		Value = bool,233		QueryKind = ValueQuery,234	>;235236	/// Amount of tokens (not pieces) partially owned by an account within a collection.237	#[pallet::storage]238	pub type AccountBalance<T: Config> = StorageNMap<239		Key = (240			Key<Twox64Concat, CollectionId>,241			// Owner242			Key<Blake2_128Concat, T::CrossAccountId>,243		),244		Value = u32,245		QueryKind = ValueQuery,246	>;247248	/// Amount of token pieces owned by account.249	#[pallet::storage]250	pub type Balance<T: Config> = StorageNMap<251		Key = (252			Key<Twox64Concat, CollectionId>,253			Key<Twox64Concat, TokenId>,254			// Owner255			Key<Blake2_128Concat, T::CrossAccountId>,256		),257		Value = u128,258		QueryKind = ValueQuery,259	>;260261	/// Allowance set by a token owner for another user to perform one of certain transactions on a number of pieces of a token.262	#[pallet::storage]263	pub type Allowance<T: Config> = StorageNMap<264		Key = (265			Key<Twox64Concat, CollectionId>,266			Key<Twox64Concat, TokenId>,267			// Owner268			Key<Blake2_128, T::CrossAccountId>,269			// Spender270			Key<Blake2_128Concat, T::CrossAccountId>,271		),272		Value = u128,273		QueryKind = ValueQuery,274	>;275276	#[pallet::hooks]277	impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {278		fn on_runtime_upgrade() -> Weight {279			let storage_version = StorageVersion::get::<Pallet<T>>();280			if storage_version < StorageVersion::new(2) {281				#[allow(deprecated)]282				let _ = <TokenData<T>>::clear(u32::MAX, None);283			}284			StorageVersion::new(2).put::<Pallet<T>>();285286			Weight::zero()287		}288	}289}290291pub struct RefungibleHandle<T: Config>(pallet_common::CollectionHandle<T>);292impl<T: Config> RefungibleHandle<T> {293	pub fn cast(inner: pallet_common::CollectionHandle<T>) -> Self {294		Self(inner)295	}296	pub fn into_inner(self) -> pallet_common::CollectionHandle<T> {297		self.0298	}299	pub fn common_mut(&mut self) -> &mut pallet_common::CollectionHandle<T> {300		&mut self.0301	}302}303304impl<T: Config> Deref for RefungibleHandle<T> {305	type Target = pallet_common::CollectionHandle<T>;306307	fn deref(&self) -> &Self::Target {308		&self.0309	}310}311312impl<T: Config> WithRecorder<T> for RefungibleHandle<T> {313	fn recorder(&self) -> &pallet_evm_coder_substrate::SubstrateRecorder<T> {314		self.0.recorder()315	}316	fn into_recorder(self) -> pallet_evm_coder_substrate::SubstrateRecorder<T> {317		self.0.into_recorder()318	}319}320321impl<T: Config> Pallet<T> {322	/// Get number of RFT tokens in collection323	pub fn total_supply(collection: &RefungibleHandle<T>) -> u32 {324		<TokensMinted<T>>::get(collection.id) - <TokensBurnt<T>>::get(collection.id)325	}326327	/// Check that RFT token exists328	///329	/// - `token`: Token ID.330	pub fn token_exists(collection: &RefungibleHandle<T>, token: TokenId) -> bool {331		<TotalSupply<T>>::contains_key((collection.id, token))332	}333334	pub fn set_scoped_token_property(335		collection_id: CollectionId,336		token_id: TokenId,337		scope: PropertyScope,338		property: Property,339	) -> DispatchResult {340		TokenProperties::<T>::try_mutate((collection_id, token_id), |properties| {341			properties.try_scoped_set(scope, property.key, property.value)342		})343		.map_err(<CommonError<T>>::from)?;344345		Ok(())346	}347348	pub fn set_scoped_token_properties(349		collection_id: CollectionId,350		token_id: TokenId,351		scope: PropertyScope,352		properties: impl Iterator<Item = Property>,353	) -> DispatchResult {354		TokenProperties::<T>::try_mutate((collection_id, token_id), |stored_properties| {355			stored_properties.try_scoped_set_from_iter(scope, properties)356		})357		.map_err(<CommonError<T>>::from)?;358359		Ok(())360	}361}362363// unchecked calls skips any permission checks364impl<T: Config> Pallet<T> {365	/// Create RFT collection366	///367	/// `init_collection` will take non-refundable deposit for collection creation.368	///369	/// - `data`: Contains settings for collection limits and permissions.370	pub fn init_collection(371		owner: T::CrossAccountId,372		payer: T::CrossAccountId,373		data: CreateCollectionData<T::AccountId>,374		flags: CollectionFlags,375	) -> Result<CollectionId, DispatchError> {376		<PalletCommon<T>>::init_collection(owner, payer, data, flags)377	}378379	/// Destroy RFT collection380	///381	/// `destroy_collection` will throw error if collection contains any tokens.382	/// Only owner can destroy collection.383	pub fn destroy_collection(384		collection: RefungibleHandle<T>,385		sender: &T::CrossAccountId,386	) -> DispatchResult {387		let id = collection.id;388389		if Self::collection_has_tokens(id) {390			return Err(<CommonError<T>>::CantDestroyNotEmptyCollection.into());391		}392393		// =========394395		PalletCommon::destroy_collection(collection.0, sender)?;396397		<TokensMinted<T>>::remove(id);398		<TokensBurnt<T>>::remove(id);399		let _ = <TotalSupply<T>>::clear_prefix((id,), u32::MAX, None);400		let _ = <Balance<T>>::clear_prefix((id,), u32::MAX, None);401		let _ = <Allowance<T>>::clear_prefix((id,), u32::MAX, None);402		let _ = <Owned<T>>::clear_prefix((id,), u32::MAX, None);403		let _ = <AccountBalance<T>>::clear_prefix((id,), u32::MAX, None);404		Ok(())405	}406407	fn collection_has_tokens(collection_id: CollectionId) -> bool {408		<TotalSupply<T>>::iter_prefix((collection_id,))409			.next()410			.is_some()411	}412413	pub fn burn_token_unchecked(414		collection: &RefungibleHandle<T>,415		owner: &T::CrossAccountId,416		token_id: TokenId,417	) -> DispatchResult {418		let burnt = <TokensBurnt<T>>::get(collection.id)419			.checked_add(1)420			.ok_or(ArithmeticError::Overflow)?;421422		<TokensBurnt<T>>::insert(collection.id, burnt);423		<TokenProperties<T>>::remove((collection.id, token_id));424		<TotalSupply<T>>::remove((collection.id, token_id));425		let _ = <Balance<T>>::clear_prefix((collection.id, token_id), u32::MAX, None);426		let _ = <Allowance<T>>::clear_prefix((collection.id, token_id), u32::MAX, None);427		<PalletEvm<T>>::deposit_log(428			ERC721Events::Transfer {429				from: *owner.as_eth(),430				to: H160::default(),431				token_id: token_id.into(),432			}433			.to_log(collection_id_to_address(collection.id)),434		);435		Ok(())436	}437438	/// Burn RFT token pieces439	///440	/// `burn` will decrease total amount of token pieces and amount owned by sender.441	/// `burn` can be called even if there are multiple owners of the RFT token.442	/// If sender wouldn't have any pieces left after `burn` than she will stop being443	/// one of the owners of the token. If there is no account that owns any pieces of444	/// the token than token will be burned too.445	///446	/// - `amount`: Amount of token pieces to burn.447	/// - `token`: Token who's pieces should be burned448	/// - `collection`: Collection that contains the token449	pub fn burn(450		collection: &RefungibleHandle<T>,451		owner: &T::CrossAccountId,452		token: TokenId,453		amount: u128,454	) -> DispatchResult {455		if <Balance<T>>::get((collection.id, token, owner)) == 0 {456			return Err(<CommonError<T>>::TokenValueTooLow.into());457		}458459		let total_supply = <TotalSupply<T>>::get((collection.id, token))460			.checked_sub(amount)461			.ok_or(<CommonError<T>>::TokenValueTooLow)?;462463		// This was probally last owner of this token?464		if total_supply == 0 {465			// Ensure user actually owns this amount466			ensure!(467				<Balance<T>>::get((collection.id, token, owner)) == amount,468				<CommonError<T>>::TokenValueTooLow469			);470			let account_balance = <AccountBalance<T>>::get((collection.id, owner))471				.checked_sub(1)472				// Should not occur473				.ok_or(ArithmeticError::Underflow)?;474475			// =========476477			<Owned<T>>::remove((collection.id, owner, token));478			<PalletStructure<T>>::unnest_if_nested(owner, collection.id, token);479			<AccountBalance<T>>::insert((collection.id, owner), account_balance);480			Self::burn_token_unchecked(collection, owner, token)?;481			<PalletEvm<T>>::deposit_log(482				ERC20Events::Transfer {483					from: *owner.as_eth(),484					to: H160::default(),485					value: amount.into(),486				}487				.to_log(collection_id_to_address(collection.id)),488			);489			<PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(490				collection.id,491				token,492				owner.clone(),493				amount,494			));495			return Ok(());496		}497498		let balance = <Balance<T>>::get((collection.id, token, owner))499			.checked_sub(amount)500			.ok_or(<CommonError<T>>::TokenValueTooLow)?;501		let account_balance = if balance == 0 {502			<AccountBalance<T>>::get((collection.id, owner))503				.checked_sub(1)504				// Should not occur505				.ok_or(ArithmeticError::Underflow)?506		} else {507			0508		};509510		// =========511512		if balance == 0 {513			<Owned<T>>::remove((collection.id, owner, token));514			<PalletStructure<T>>::unnest_if_nested(owner, collection.id, token);515			<Balance<T>>::remove((collection.id, token, owner));516			<AccountBalance<T>>::insert((collection.id, owner), account_balance);517518			if let Some(user) = Self::token_owner(collection.id, token) {519				<PalletEvm<T>>::deposit_log(520					ERC721Events::Transfer {521						from: erc::ADDRESS_FOR_PARTIALLY_OWNED_TOKENS,522						to: *user.as_eth(),523						token_id: token.into(),524					}525					.to_log(collection_id_to_address(collection.id)),526				);527			}528		} else {529			<Balance<T>>::insert((collection.id, token, owner), balance);530		}531		<TotalSupply<T>>::insert((collection.id, token), total_supply);532533		<PalletEvm<T>>::deposit_log(534			ERC20Events::Transfer {535				from: *owner.as_eth(),536				to: H160::default(),537				value: amount.into(),538			}539			.to_log(T::EvmTokenAddressMapping::token_to_address(540				collection.id,541				token,542			)),543		);544		<PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(545			collection.id,546			token,547			owner.clone(),548			amount,549		));550		Ok(())551	}552553	#[transactional]554	fn modify_token_properties(555		collection: &RefungibleHandle<T>,556		sender: &T::CrossAccountId,557		token_id: TokenId,558		properties: impl Iterator<Item = (PropertyKey, Option<PropertyValue>)>,559		is_token_create: bool,560		nesting_budget: &dyn Budget,561	) -> DispatchResult {562		let is_collection_admin = || collection.is_owner_or_admin(sender);563		let is_token_owner = || -> Result<bool, DispatchError> {564			let balance = collection.balance(sender.clone(), token_id);565			let total_pieces: u128 =566				Self::total_pieces(collection.id, token_id).unwrap_or(u128::MAX);567			if balance != total_pieces {568				return Ok(false);569			}570571			let is_bundle_owner = <PalletStructure<T>>::check_indirectly_owned(572				sender.clone(),573				collection.id,574				token_id,575				None,576				nesting_budget,577			)?;578579			Ok(is_bundle_owner)580		};581582		for (key, value) in properties {583			let permission = <PalletCommon<T>>::property_permissions(collection.id)584				.get(&key)585				.cloned()586				.unwrap_or_else(PropertyPermission::none);587588			let is_property_exists = TokenProperties::<T>::get((collection.id, token_id))589				.get(&key)590				.is_some();591592			match permission {593				PropertyPermission { mutable: false, .. } if is_property_exists => {594					return Err(<CommonError<T>>::NoPermission.into());595				}596597				PropertyPermission {598					collection_admin,599					token_owner,600					..601				} => {602					//TODO: investigate threats during public minting.603					let is_token_create =604						is_token_create && (collection_admin || token_owner) && value.is_some();605					if !(is_token_create606						|| (collection_admin && is_collection_admin())607						|| (token_owner && is_token_owner()?))608					{609						fail!(<CommonError<T>>::NoPermission);610					}611				}612			}613614			match value {615				Some(value) => {616					<TokenProperties<T>>::try_mutate((collection.id, token_id), |properties| {617						properties.try_set(key.clone(), value)618					})619					.map_err(<CommonError<T>>::from)?;620621					<PalletCommon<T>>::deposit_event(CommonEvent::TokenPropertySet(622						collection.id,623						token_id,624						key,625					));626				}627				None => {628					<TokenProperties<T>>::try_mutate((collection.id, token_id), |properties| {629						properties.remove(&key)630					})631					.map_err(<CommonError<T>>::from)?;632633					<PalletCommon<T>>::deposit_event(CommonEvent::TokenPropertyDeleted(634						collection.id,635						token_id,636						key,637					));638				}639			}640		}641642		Ok(())643	}644645	pub fn set_token_properties(646		collection: &RefungibleHandle<T>,647		sender: &T::CrossAccountId,648		token_id: TokenId,649		properties: impl Iterator<Item = Property>,650		is_token_create: bool,651		nesting_budget: &dyn Budget,652	) -> DispatchResult {653		Self::modify_token_properties(654			collection,655			sender,656			token_id,657			properties.map(|p| (p.key, Some(p.value))),658			is_token_create,659			nesting_budget,660		)661	}662663	pub fn set_token_property(664		collection: &RefungibleHandle<T>,665		sender: &T::CrossAccountId,666		token_id: TokenId,667		property: Property,668		nesting_budget: &dyn Budget,669	) -> DispatchResult {670		let is_token_create = false;671672		Self::set_token_properties(673			collection,674			sender,675			token_id,676			[property].into_iter(),677			is_token_create,678			nesting_budget,679		)680	}681682	pub fn delete_token_properties(683		collection: &RefungibleHandle<T>,684		sender: &T::CrossAccountId,685		token_id: TokenId,686		property_keys: impl Iterator<Item = PropertyKey>,687		nesting_budget: &dyn Budget,688	) -> DispatchResult {689		let is_token_create = false;690691		Self::modify_token_properties(692			collection,693			sender,694			token_id,695			property_keys.into_iter().map(|key| (key, None)),696			is_token_create,697			nesting_budget,698		)699	}700701	pub fn delete_token_property(702		collection: &RefungibleHandle<T>,703		sender: &T::CrossAccountId,704		token_id: TokenId,705		property_key: PropertyKey,706		nesting_budget: &dyn Budget,707	) -> DispatchResult {708		Self::delete_token_properties(709			collection,710			sender,711			token_id,712			[property_key].into_iter(),713			nesting_budget,714		)715	}716717	/// Transfer RFT token pieces from one account to another.718	///719	/// If the sender is no longer owns any pieces after the `transfer` than she stops being an owner of the token.720	///721	/// - `from`: Owner of token pieces to transfer.722	/// - `to`: Recepient of transfered token pieces.723	/// - `amount`: Amount of token pieces to transfer.724	/// - `token`: Token whos pieces should be transfered725	/// - `collection`: Collection that contains the token726	pub fn transfer(727		collection: &RefungibleHandle<T>,728		from: &T::CrossAccountId,729		to: &T::CrossAccountId,730		token: TokenId,731		amount: u128,732		nesting_budget: &dyn Budget,733	) -> DispatchResult {734		ensure!(735			collection.limits.transfers_enabled(),736			<CommonError<T>>::TransferNotAllowed737		);738739		if collection.permissions.access() == AccessMode::AllowList {740			collection.check_allowlist(from)?;741			collection.check_allowlist(to)?;742		}743		<PalletCommon<T>>::ensure_correct_receiver(to)?;744745		let initial_balance_from = <Balance<T>>::get((collection.id, token, from));746747		if initial_balance_from == 0 {748			return Err(<CommonError<T>>::TokenValueTooLow.into());749		}750751		let updated_balance_from = initial_balance_from752			.checked_sub(amount)753			.ok_or(<CommonError<T>>::TokenValueTooLow)?;754		let mut create_target = false;755		let from_to_differ = from != to;756		let updated_balance_to = if from != to && amount != 0 {757			let old_balance = <Balance<T>>::get((collection.id, token, to));758			if old_balance == 0 {759				create_target = true;760			}761			Some(762				old_balance763					.checked_add(amount)764					.ok_or(ArithmeticError::Overflow)?,765			)766		} else {767			None768		};769770		let account_balance_from = if updated_balance_from == 0 {771			Some(772				<AccountBalance<T>>::get((collection.id, from))773					.checked_sub(1)774					// Should not occur775					.ok_or(ArithmeticError::Underflow)?,776			)777		} else {778			None779		};780		// Account data is created in token, AccountBalance should be increased781		// But only if from != to as we shouldn't check overflow in this case782		let account_balance_to = if create_target && from_to_differ {783			let account_balance_to = <AccountBalance<T>>::get((collection.id, to))784				.checked_add(1)785				.ok_or(ArithmeticError::Overflow)?;786			ensure!(787				account_balance_to < collection.limits.account_token_ownership_limit(),788				<CommonError<T>>::AccountTokenLimitExceeded,789			);790791			Some(account_balance_to)792		} else {793			None794		};795796		// =========797798		if let Some(updated_balance_to) = updated_balance_to {799			// from != to && amount != 0800801			<PalletStructure<T>>::nest_if_sent_to_token(802				from.clone(),803				to,804				collection.id,805				token,806				nesting_budget,807			)?;808809			if updated_balance_from == 0 {810				<Balance<T>>::remove((collection.id, token, from));811				<PalletStructure<T>>::unnest_if_nested(from, collection.id, token);812			} else {813				<Balance<T>>::insert((collection.id, token, from), updated_balance_from);814			}815			<Balance<T>>::insert((collection.id, token, to), updated_balance_to);816			if let Some(account_balance_from) = account_balance_from {817				<AccountBalance<T>>::insert((collection.id, from), account_balance_from);818				<Owned<T>>::remove((collection.id, from, token));819			}820			if let Some(account_balance_to) = account_balance_to {821				<AccountBalance<T>>::insert((collection.id, to), account_balance_to);822				<Owned<T>>::insert((collection.id, to, token), true);823			}824		}825826		<PalletEvm<T>>::deposit_log(827			ERC20Events::Transfer {828				from: *from.as_eth(),829				to: *to.as_eth(),830				value: amount.into(),831			}832			.to_log(T::EvmTokenAddressMapping::token_to_address(833				collection.id,834				token,835			)),836		);837838		<PalletCommon<T>>::deposit_event(CommonEvent::Transfer(839			collection.id,840			token,841			from.clone(),842			to.clone(),843			amount,844		));845846		let total_supply = <TotalSupply<T>>::get((collection.id, token));847848		if amount == total_supply {849			// if token was fully owned by `from` and will be fully owned by `to` after transfer850			<PalletEvm<T>>::deposit_log(851				ERC721Events::Transfer {852					from: *from.as_eth(),853					to: *to.as_eth(),854					token_id: token.into(),855				}856				.to_log(collection_id_to_address(collection.id)),857			);858		} else if let Some(updated_balance_to) = updated_balance_to {859			// if `from` not equals `to`. This condition is needed to avoid sending event860			// when `from` fully owns token and sends part of token pieces to itself.861			if initial_balance_from == total_supply {862				// if token was fully owned by `from` and will be only partially owned by `to`863				// and `from` after transfer864				<PalletEvm<T>>::deposit_log(865					ERC721Events::Transfer {866						from: *from.as_eth(),867						to: erc::ADDRESS_FOR_PARTIALLY_OWNED_TOKENS,868						token_id: token.into(),869					}870					.to_log(collection_id_to_address(collection.id)),871				);872			} else if updated_balance_to == total_supply {873				// if token was partially owned by `from` and will be fully owned by `to` after transfer874				<PalletEvm<T>>::deposit_log(875					ERC721Events::Transfer {876						from: erc::ADDRESS_FOR_PARTIALLY_OWNED_TOKENS,877						to: *to.as_eth(),878						token_id: token.into(),879					}880					.to_log(collection_id_to_address(collection.id)),881				);882			}883		}884885		Ok(())886	}887888	/// Batched operation to create multiple RFT tokens.889	///890	/// Same as `create_item` but creates multiple tokens.891	///892	/// - `data`: Same as 'data` in `create_item` but contains data for multiple tokens.893	pub fn create_multiple_items(894		collection: &RefungibleHandle<T>,895		sender: &T::CrossAccountId,896		data: Vec<CreateItemData<T::CrossAccountId>>,897		nesting_budget: &dyn Budget,898	) -> DispatchResult {899		if !collection.is_owner_or_admin(sender) {900			ensure!(901				collection.permissions.mint_mode(),902				<CommonError<T>>::PublicMintingNotAllowed903			);904			collection.check_allowlist(sender)?;905906			for item in data.iter() {907				for user in item.users.keys() {908					collection.check_allowlist(user)?;909				}910			}911		}912913		for item in data.iter() {914			for (owner, _) in item.users.iter() {915				<PalletCommon<T>>::ensure_correct_receiver(owner)?;916			}917		}918919		// Total pieces per tokens920		let totals = data921			.iter()922			.map(|data| {923				Ok(data924					.users925					.iter()926					.map(|u| u.1)927					.try_fold(0u128, |acc, v| acc.checked_add(*v))928					.ok_or(ArithmeticError::Overflow)?)929			})930			.collect::<Result<Vec<_>, DispatchError>>()?;931		for total in &totals {932			ensure!(933				*total <= MAX_REFUNGIBLE_PIECES,934				<Error<T>>::WrongRefungiblePieces935			);936		}937938		let first_token_id = <TokensMinted<T>>::get(collection.id);939		let tokens_minted = first_token_id940			.checked_add(data.len() as u32)941			.ok_or(ArithmeticError::Overflow)?;942		ensure!(943			tokens_minted < collection.limits.token_limit(),944			<CommonError<T>>::CollectionTokenLimitExceeded945		);946947		let mut balances = BTreeMap::new();948		for data in &data {949			for owner in data.users.keys() {950				let balance = balances951					.entry(owner)952					.or_insert_with(|| <AccountBalance<T>>::get((collection.id, owner)));953				*balance = balance.checked_add(1).ok_or(ArithmeticError::Overflow)?;954955				ensure!(956					*balance <= collection.limits.account_token_ownership_limit(),957					<CommonError<T>>::AccountTokenLimitExceeded,958				);959			}960		}961962		for (i, token) in data.iter().enumerate() {963			let token_id = TokenId(first_token_id + i as u32 + 1);964			for (to, _) in token.users.iter() {965				<PalletStructure<T>>::check_nesting(966					sender.clone(),967					to,968					collection.id,969					token_id,970					nesting_budget,971				)?;972			}973		}974975		// =========976977		with_transaction(|| {978			for (i, data) in data.iter().enumerate() {979				let token_id = first_token_id + i as u32 + 1;980				<TotalSupply<T>>::insert((collection.id, token_id), totals[i]);981982				for (user, amount) in data.users.iter() {983					if *amount == 0 {984						continue;985					}986					<Balance<T>>::insert((collection.id, token_id, &user), amount);987					<Owned<T>>::insert((collection.id, &user, TokenId(token_id)), true);988					<PalletStructure<T>>::nest_if_sent_to_token_unchecked(989						user,990						collection.id,991						TokenId(token_id),992					);993				}994995				if let Err(e) = Self::set_token_properties(996					collection,997					sender,998					TokenId(token_id),999					data.properties.clone().into_iter(),1000					true,1001					nesting_budget,1002				) {1003					return TransactionOutcome::Rollback(Err(e));1004				}1005			}1006			TransactionOutcome::Commit(Ok(()))1007		})?;10081009		<TokensMinted<T>>::insert(collection.id, tokens_minted);10101011		for (account, balance) in balances {1012			<AccountBalance<T>>::insert((collection.id, account), balance);1013		}10141015		for (i, token) in data.into_iter().enumerate() {1016			let token_id = first_token_id + i as u32 + 1;10171018			let receivers = token1019				.users1020				.into_iter()1021				.filter(|(_, amount)| *amount > 0)1022				.collect::<Vec<_>>();10231024			if let [(user, _)] = receivers.as_slice() {1025				// if there is exactly one receiver1026				<PalletEvm<T>>::deposit_log(1027					ERC721Events::Transfer {1028						from: H160::default(),1029						to: *user.as_eth(),1030						token_id: token_id.into(),1031					}1032					.to_log(collection_id_to_address(collection.id)),1033				);1034			} else if let [_, ..] = receivers.as_slice() {1035				// if there is more than one receiver1036				<PalletEvm<T>>::deposit_log(1037					ERC721Events::Transfer {1038						from: H160::default(),1039						to: erc::ADDRESS_FOR_PARTIALLY_OWNED_TOKENS,1040						token_id: token_id.into(),1041					}1042					.to_log(collection_id_to_address(collection.id)),1043				);1044			}10451046			for (user, amount) in receivers.into_iter() {1047				<PalletEvm<T>>::deposit_log(1048					ERC20Events::Transfer {1049						from: H160::default(),1050						to: *user.as_eth(),1051						value: amount.into(),1052					}1053					.to_log(T::EvmTokenAddressMapping::token_to_address(1054						collection.id,1055						TokenId(token_id),1056					)),1057				);1058				<PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(1059					collection.id,1060					TokenId(token_id),1061					user,1062					amount,1063				));1064			}1065		}1066		Ok(())1067	}10681069	pub fn set_allowance_unchecked(1070		collection: &RefungibleHandle<T>,1071		sender: &T::CrossAccountId,1072		spender: &T::CrossAccountId,1073		token: TokenId,1074		amount: u128,1075	) {1076		if amount == 0 {1077			<Allowance<T>>::remove((collection.id, token, sender, spender));1078		} else {1079			<Allowance<T>>::insert((collection.id, token, sender, spender), amount);1080		}10811082		<PalletEvm<T>>::deposit_log(1083			ERC20Events::Approval {1084				owner: *sender.as_eth(),1085				spender: *spender.as_eth(),1086				value: amount.into(),1087			}1088			.to_log(T::EvmTokenAddressMapping::token_to_address(1089				collection.id,1090				token,1091			)),1092		);1093		<PalletCommon<T>>::deposit_event(CommonEvent::Approved(1094			collection.id,1095			token,1096			sender.clone(),1097			spender.clone(),1098			amount,1099		))1100	}11011102	/// Set allowance for the spender to `transfer` or `burn` sender's token pieces.1103	///1104	/// - `amount`: Amount of token pieces the spender is allowed to `transfer` or `burn.1105	pub fn set_allowance(1106		collection: &RefungibleHandle<T>,1107		sender: &T::CrossAccountId,1108		spender: &T::CrossAccountId,1109		token: TokenId,1110		amount: u128,1111	) -> DispatchResult {1112		if collection.permissions.access() == AccessMode::AllowList {1113			collection.check_allowlist(sender)?;1114			collection.check_allowlist(spender)?;1115		}11161117		<PalletCommon<T>>::ensure_correct_receiver(spender)?;11181119		if <Balance<T>>::get((collection.id, token, sender)) < amount {1120			ensure!(1121				collection.ignores_owned_amount(sender) && Self::token_exists(collection, token),1122				<CommonError<T>>::CantApproveMoreThanOwned1123			);1124		}11251126		// =========11271128		Self::set_allowance_unchecked(collection, sender, spender, token, amount);1129		Ok(())1130	}11311132	/// Returns allowance, which should be set after transaction1133	fn check_allowed(1134		collection: &RefungibleHandle<T>,1135		spender: &T::CrossAccountId,1136		from: &T::CrossAccountId,1137		token: TokenId,1138		amount: u128,1139		nesting_budget: &dyn Budget,1140	) -> Result<Option<u128>, DispatchError> {1141		if spender.conv_eq(from) {1142			return Ok(None);1143		}1144		if collection.permissions.access() == AccessMode::AllowList {1145			// `from`, `to` checked in [`transfer`]1146			collection.check_allowlist(spender)?;1147		}1148		if let Some(source) = T::CrossTokenAddressMapping::address_to_token(from) {1149			// TODO: should collection owner be allowed to perform this transfer?1150			ensure!(1151				<PalletStructure<T>>::check_indirectly_owned(1152					spender.clone(),1153					source.0,1154					source.1,1155					None,1156					nesting_budget1157				)?,1158				<CommonError<T>>::ApprovedValueTooLow,1159			);1160			return Ok(None);1161		}1162		let allowance =1163			<Allowance<T>>::get((collection.id, token, from, &spender)).checked_sub(amount);1164		if allowance.is_none() {1165			ensure!(1166				collection.ignores_allowance(spender),1167				<CommonError<T>>::ApprovedValueTooLow1168			);1169		}1170		Ok(allowance)1171	}11721173	/// Transfer RFT token pieces from one account to another.1174	///1175	/// Same as the [`transfer`] but spender doesn't needs to be an owner of the token pieces.1176	/// The owner should set allowance for the spender to transfer pieces.1177	///1178	/// [`transfer`]: struct.Pallet.html#method.transfer1179	pub fn transfer_from(1180		collection: &RefungibleHandle<T>,1181		spender: &T::CrossAccountId,1182		from: &T::CrossAccountId,1183		to: &T::CrossAccountId,1184		token: TokenId,1185		amount: u128,1186		nesting_budget: &dyn Budget,1187	) -> DispatchResult {1188		let allowance =1189			Self::check_allowed(collection, spender, from, token, amount, nesting_budget)?;11901191		// =========11921193		Self::transfer(collection, from, to, token, amount, nesting_budget)?;1194		if let Some(allowance) = allowance {1195			Self::set_allowance_unchecked(collection, from, spender, token, allowance);1196		}1197		Ok(())1198	}11991200	/// Burn RFT token pieces from the account.1201	///1202	/// Same as the [`burn`] but spender doesn't need to be an owner of the token pieces. The owner should1203	/// set allowance for the spender to burn pieces1204	///1205	/// [`burn`]: struct.Pallet.html#method.burn1206	pub fn burn_from(1207		collection: &RefungibleHandle<T>,1208		spender: &T::CrossAccountId,1209		from: &T::CrossAccountId,1210		token: TokenId,1211		amount: u128,1212		nesting_budget: &dyn Budget,1213	) -> DispatchResult {1214		let allowance =1215			Self::check_allowed(collection, spender, from, token, amount, nesting_budget)?;12161217		// =========12181219		Self::burn(collection, from, token, amount)?;1220		if let Some(allowance) = allowance {1221			Self::set_allowance_unchecked(collection, from, spender, token, allowance);1222		}1223		Ok(())1224	}12251226	/// Create RFT token.1227	///1228	/// The sender should be the owner/admin of the collection or collection should be configured1229	/// to allow public minting.1230	///1231	/// - `data`: Contains list of users who will become the owners of the token pieces and amount1232	///   of token pieces they will receive.1233	pub fn create_item(1234		collection: &RefungibleHandle<T>,1235		sender: &T::CrossAccountId,1236		data: CreateItemData<T::CrossAccountId>,1237		nesting_budget: &dyn Budget,1238	) -> DispatchResult {1239		Self::create_multiple_items(collection, sender, vec![data], nesting_budget)1240	}12411242	/// Repartition RFT token.1243	///1244	/// `repartition` will set token balance of the sender and total amount of token pieces.1245	/// Sender should own all of the token pieces. `repartition' could be done even if some1246	/// token pieces were burned before.1247	///1248	/// - `amount`: Total amount of token pieces that the token will have after `repartition`.1249	pub fn repartition(1250		collection: &RefungibleHandle<T>,1251		owner: &T::CrossAccountId,1252		token: TokenId,1253		amount: u128,1254	) -> DispatchResult {1255		ensure!(1256			amount <= MAX_REFUNGIBLE_PIECES,1257			<Error<T>>::WrongRefungiblePieces1258		);1259		ensure!(amount > 0, <CommonError<T>>::TokenValueTooLow);1260		// Ensure user owns all pieces1261		let total_pieces = Self::total_pieces(collection.id, token).unwrap_or(u128::MAX);1262		let balance = <Balance<T>>::get((collection.id, token, owner));1263		ensure!(1264			total_pieces == balance,1265			<Error<T>>::RepartitionWhileNotOwningAllPieces1266		);12671268		<Balance<T>>::insert((collection.id, token, owner), amount);1269		<TotalSupply<T>>::insert((collection.id, token), amount);12701271		if amount > total_pieces {1272			let mint_amount = amount - total_pieces;1273			<PalletEvm<T>>::deposit_log(1274				ERC20Events::Transfer {1275					from: H160::default(),1276					to: *owner.as_eth(),1277					value: mint_amount.into(),1278				}1279				.to_log(T::EvmTokenAddressMapping::token_to_address(1280					collection.id,1281					token,1282				)),1283			);1284			<PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(1285				collection.id,1286				token,1287				owner.clone(),1288				mint_amount,1289			));1290		} else if total_pieces > amount {1291			let burn_amount = total_pieces - amount;1292			<PalletEvm<T>>::deposit_log(1293				ERC20Events::Transfer {1294					from: *owner.as_eth(),1295					to: H160::default(),1296					value: burn_amount.into(),1297				}1298				.to_log(T::EvmTokenAddressMapping::token_to_address(1299					collection.id,1300					token,1301				)),1302			);1303			<PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(1304				collection.id,1305				token,1306				owner.clone(),1307				burn_amount,1308			));1309		}13101311		Ok(())1312	}13131314	fn token_owner(collection_id: CollectionId, token_id: TokenId) -> Option<T::CrossAccountId> {1315		let mut owner = None;1316		let mut count = 0;1317		for key in Balance::<T>::iter_key_prefix((collection_id, token_id)) {1318			count += 1;1319			if count > 1 {1320				return None;1321			}1322			owner = Some(key);1323		}1324		owner1325	}13261327	fn total_pieces(collection_id: CollectionId, token_id: TokenId) -> Option<u128> {1328		<TotalSupply<T>>::try_get((collection_id, token_id)).ok()1329	}13301331	pub fn set_collection_properties(1332		collection: &RefungibleHandle<T>,1333		sender: &T::CrossAccountId,1334		properties: Vec<Property>,1335	) -> DispatchResult {1336		<PalletCommon<T>>::set_collection_properties(collection, sender, properties)1337	}13381339	pub fn delete_collection_properties(1340		collection: &RefungibleHandle<T>,1341		sender: &T::CrossAccountId,1342		property_keys: Vec<PropertyKey>,1343	) -> DispatchResult {1344		<PalletCommon<T>>::delete_collection_properties(collection, sender, property_keys)1345	}13461347	pub fn set_token_property_permissions(1348		collection: &RefungibleHandle<T>,1349		sender: &T::CrossAccountId,1350		property_permissions: Vec<PropertyKeyPermission>,1351	) -> DispatchResult {1352		<PalletCommon<T>>::set_token_property_permissions(collection, sender, property_permissions)1353	}13541355	pub fn set_scoped_token_property_permissions(1356		collection: &RefungibleHandle<T>,1357		sender: &T::CrossAccountId,1358		scope: PropertyScope,1359		property_permissions: Vec<PropertyKeyPermission>,1360	) -> DispatchResult {1361		<PalletCommon<T>>::set_scoped_token_property_permissions(1362			collection,1363			sender,1364			scope,1365			property_permissions,1366		)1367	}13681369	/// Returns 10 token in no particular order.1370	///1371	/// There is no direct way to get token holders in ascending order,1372	/// since `iter_prefix` returns values in no particular order.1373	/// Therefore, getting the 10 largest holders with a large value of holders1374	/// can lead to impact memory allocation + sorting with  `n * log (n)`.1375	pub fn token_owners(1376		collection_id: CollectionId,1377		token: TokenId,1378	) -> Option<Vec<T::CrossAccountId>> {1379		let res: Vec<T::CrossAccountId> = <Balance<T>>::iter_prefix((collection_id, token))1380			.map(|(owner, _amount)| owner)1381			.take(10)1382			.collect();13831384		if res.is_empty() {1385			None1386		} else {1387			Some(res)1388		}1389	}1390}
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 derivative::Derivative;96use evm_coder::ToLog;97use frame_support::{98	BoundedBTreeMap, BoundedVec, ensure, fail, storage::with_transaction, transactional,99	pallet_prelude::ConstU32,100};101use pallet_evm::{account::CrossAccountId, Pallet as PalletEvm};102use pallet_evm_coder_substrate::WithRecorder;103use pallet_common::{104	CommonCollectionOperations, Error as CommonError, eth::collection_id_to_address,105	Event as CommonEvent, Pallet as PalletCommon,106};107use pallet_structure::Pallet as PalletStructure;108use scale_info::TypeInfo;109use sp_core::H160;110use sp_runtime::{ArithmeticError, DispatchError, DispatchResult, TransactionOutcome};111use sp_std::{vec::Vec, vec, collections::btree_map::BTreeMap};112use up_data_structs::{113	AccessMode, budget::Budget, CollectionId, CollectionFlags, CollectionPropertiesVec,114	CreateCollectionData, CustomDataLimit, mapping::TokenAddressMapping, MAX_ITEMS_PER_BATCH,115	MAX_REFUNGIBLE_PIECES, Property, PropertyKey, PropertyKeyPermission, PropertyPermission,116	PropertyScope, PropertyValue, TokenId, TrySetProperty,117};118119pub use pallet::*;120#[cfg(feature = "runtime-benchmarks")]121pub mod benchmarking;122pub mod common;123pub mod erc;124pub mod erc_token;125pub mod weights;126127#[derive(Derivative, Clone)]128pub struct CreateItemData<CrossAccountId> {129	#[derivative(Debug(format_with = "bounded::map_debug"))]130	pub users: BoundedBTreeMap<CrossAccountId, u128, ConstU32<MAX_ITEMS_PER_BATCH>>,131	#[derivative(Debug(format_with = "bounded::vec_debug"))]132	pub properties: CollectionPropertiesVec,133}134pub(crate) type SelfWeightOf<T> = <T as Config>::WeightInfo;135136/// Token data, stored independently from other data used to describe it137/// for the convenience of database access. Notably contains the token metadata.138#[struct_versioning::versioned(version = 2, upper)]139#[derive(Encode, Decode, Default, TypeInfo, MaxEncodedLen)]140pub struct ItemData {141	pub const_data: BoundedVec<u8, CustomDataLimit>,142143	#[version(..2)]144	pub variable_data: BoundedVec<u8, CustomDataLimit>,145}146147#[frame_support::pallet]148pub mod pallet {149	use super::*;150	use frame_support::{151		Blake2_128, Blake2_128Concat, Twox64Concat, pallet_prelude::*, storage::Key,152		traits::StorageVersion,153	};154	use frame_system::pallet_prelude::*;155	use up_data_structs::{CollectionId, TokenId};156	use super::weights::WeightInfo;157158	#[pallet::error]159	pub enum Error<T> {160		/// Not Refungible item data used to mint in Refungible collection.161		NotRefungibleDataUsedToMintFungibleCollectionToken,162		/// Maximum refungibility exceeded.163		WrongRefungiblePieces,164		/// Refungible token can't be repartitioned by user who isn't owns all pieces.165		RepartitionWhileNotOwningAllPieces,166		/// Refungible token can't nest other tokens.167		RefungibleDisallowsNesting,168		/// Setting item properties is not allowed.169		SettingPropertiesNotAllowed,170	}171172	#[pallet::config]173	pub trait Config:174		frame_system::Config + pallet_common::Config + pallet_structure::Config175	{176		type WeightInfo: WeightInfo;177	}178179	const STORAGE_VERSION: StorageVersion = StorageVersion::new(2);180181	#[pallet::pallet]182	#[pallet::storage_version(STORAGE_VERSION)]183	#[pallet::generate_store(pub(super) trait Store)]184	pub struct Pallet<T>(_);185186	/// Total amount of minted tokens in a collection.187	#[pallet::storage]188	pub type TokensMinted<T: Config> =189		StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;190191	/// Amount of tokens burnt in a collection.192	#[pallet::storage]193	pub type TokensBurnt<T: Config> =194		StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;195196	/// Token data, used to partially describe a token.197	// TODO: remove198	#[pallet::storage]199	#[deprecated(since = "0.2.0", note = "ItemData is no more contains usefull data")]200	pub type TokenData<T: Config> = StorageNMap<201		Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),202		Value = ItemData,203		QueryKind = ValueQuery,204	>;205206	/// Amount of pieces a refungible token is split into.207	#[pallet::storage]208	#[pallet::getter(fn token_properties)]209	pub type TokenProperties<T: Config> = StorageNMap<210		Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),211		Value = up_data_structs::Properties,212		QueryKind = ValueQuery,213		OnEmpty = up_data_structs::TokenProperties,214	>;215216	/// Total amount of pieces for token217	#[pallet::storage]218	pub type TotalSupply<T: Config> = StorageNMap<219		Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),220		Value = u128,221		QueryKind = ValueQuery,222	>;223224	/// Used to enumerate tokens owned by account.225	#[pallet::storage]226	pub type Owned<T: Config> = StorageNMap<227		Key = (228			Key<Twox64Concat, CollectionId>,229			Key<Blake2_128Concat, T::CrossAccountId>,230			Key<Twox64Concat, TokenId>,231		),232		Value = bool,233		QueryKind = ValueQuery,234	>;235236	/// Amount of tokens (not pieces) partially owned by an account within a collection.237	#[pallet::storage]238	pub type AccountBalance<T: Config> = StorageNMap<239		Key = (240			Key<Twox64Concat, CollectionId>,241			// Owner242			Key<Blake2_128Concat, T::CrossAccountId>,243		),244		Value = u32,245		QueryKind = ValueQuery,246	>;247248	/// Amount of token pieces owned by account.249	#[pallet::storage]250	pub type Balance<T: Config> = StorageNMap<251		Key = (252			Key<Twox64Concat, CollectionId>,253			Key<Twox64Concat, TokenId>,254			// Owner255			Key<Blake2_128Concat, T::CrossAccountId>,256		),257		Value = u128,258		QueryKind = ValueQuery,259	>;260261	/// Allowance set by a token owner for another user to perform one of certain transactions on a number of pieces of a token.262	#[pallet::storage]263	pub type Allowance<T: Config> = StorageNMap<264		Key = (265			Key<Twox64Concat, CollectionId>,266			Key<Twox64Concat, TokenId>,267			// Owner268			Key<Blake2_128, T::CrossAccountId>,269			// Spender270			Key<Blake2_128Concat, T::CrossAccountId>,271		),272		Value = u128,273		QueryKind = ValueQuery,274	>;275276	/// Operator set by a wallet owner that could perform certain transactions on all tokens in the wallet.277	#[pallet::storage]278	pub type WalletOperator<T: Config> = StorageNMap<279		Key = (280			Key<Twox64Concat, CollectionId>,281			Key<Blake2_128Concat, T::CrossAccountId>,282			Key<Blake2_128Concat, T::CrossAccountId>,283		),284		Value = bool,285		QueryKind = OptionQuery,286	>;287288	#[pallet::hooks]289	impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {290		fn on_runtime_upgrade() -> Weight {291			let storage_version = StorageVersion::get::<Pallet<T>>();292			if storage_version < StorageVersion::new(2) {293				#[allow(deprecated)]294				let _ = <TokenData<T>>::clear(u32::MAX, None);295			}296			StorageVersion::new(2).put::<Pallet<T>>();297298			Weight::zero()299		}300	}301}302303pub struct RefungibleHandle<T: Config>(pallet_common::CollectionHandle<T>);304impl<T: Config> RefungibleHandle<T> {305	pub fn cast(inner: pallet_common::CollectionHandle<T>) -> Self {306		Self(inner)307	}308	pub fn into_inner(self) -> pallet_common::CollectionHandle<T> {309		self.0310	}311	pub fn common_mut(&mut self) -> &mut pallet_common::CollectionHandle<T> {312		&mut self.0313	}314}315316impl<T: Config> Deref for RefungibleHandle<T> {317	type Target = pallet_common::CollectionHandle<T>;318319	fn deref(&self) -> &Self::Target {320		&self.0321	}322}323324impl<T: Config> WithRecorder<T> for RefungibleHandle<T> {325	fn recorder(&self) -> &pallet_evm_coder_substrate::SubstrateRecorder<T> {326		self.0.recorder()327	}328	fn into_recorder(self) -> pallet_evm_coder_substrate::SubstrateRecorder<T> {329		self.0.into_recorder()330	}331}332333impl<T: Config> Pallet<T> {334	/// Get number of RFT tokens in collection335	pub fn total_supply(collection: &RefungibleHandle<T>) -> u32 {336		<TokensMinted<T>>::get(collection.id) - <TokensBurnt<T>>::get(collection.id)337	}338339	/// Check that RFT token exists340	///341	/// - `token`: Token ID.342	pub fn token_exists(collection: &RefungibleHandle<T>, token: TokenId) -> bool {343		<TotalSupply<T>>::contains_key((collection.id, token))344	}345346	pub fn set_scoped_token_property(347		collection_id: CollectionId,348		token_id: TokenId,349		scope: PropertyScope,350		property: Property,351	) -> DispatchResult {352		TokenProperties::<T>::try_mutate((collection_id, token_id), |properties| {353			properties.try_scoped_set(scope, property.key, property.value)354		})355		.map_err(<CommonError<T>>::from)?;356357		Ok(())358	}359360	pub fn set_scoped_token_properties(361		collection_id: CollectionId,362		token_id: TokenId,363		scope: PropertyScope,364		properties: impl Iterator<Item = Property>,365	) -> DispatchResult {366		TokenProperties::<T>::try_mutate((collection_id, token_id), |stored_properties| {367			stored_properties.try_scoped_set_from_iter(scope, properties)368		})369		.map_err(<CommonError<T>>::from)?;370371		Ok(())372	}373}374375// unchecked calls skips any permission checks376impl<T: Config> Pallet<T> {377	/// Create RFT collection378	///379	/// `init_collection` will take non-refundable deposit for collection creation.380	///381	/// - `data`: Contains settings for collection limits and permissions.382	pub fn init_collection(383		owner: T::CrossAccountId,384		payer: T::CrossAccountId,385		data: CreateCollectionData<T::AccountId>,386		flags: CollectionFlags,387	) -> Result<CollectionId, DispatchError> {388		<PalletCommon<T>>::init_collection(owner, payer, data, flags)389	}390391	/// Destroy RFT collection392	///393	/// `destroy_collection` will throw error if collection contains any tokens.394	/// Only owner can destroy collection.395	pub fn destroy_collection(396		collection: RefungibleHandle<T>,397		sender: &T::CrossAccountId,398	) -> DispatchResult {399		let id = collection.id;400401		if Self::collection_has_tokens(id) {402			return Err(<CommonError<T>>::CantDestroyNotEmptyCollection.into());403		}404405		// =========406407		PalletCommon::destroy_collection(collection.0, sender)?;408409		<TokensMinted<T>>::remove(id);410		<TokensBurnt<T>>::remove(id);411		let _ = <TotalSupply<T>>::clear_prefix((id,), u32::MAX, None);412		let _ = <Balance<T>>::clear_prefix((id,), u32::MAX, None);413		let _ = <Allowance<T>>::clear_prefix((id,), u32::MAX, None);414		let _ = <Owned<T>>::clear_prefix((id,), u32::MAX, None);415		let _ = <AccountBalance<T>>::clear_prefix((id,), u32::MAX, None);416		Ok(())417	}418419	fn collection_has_tokens(collection_id: CollectionId) -> bool {420		<TotalSupply<T>>::iter_prefix((collection_id,))421			.next()422			.is_some()423	}424425	pub fn burn_token_unchecked(426		collection: &RefungibleHandle<T>,427		owner: &T::CrossAccountId,428		token_id: TokenId,429	) -> DispatchResult {430		let burnt = <TokensBurnt<T>>::get(collection.id)431			.checked_add(1)432			.ok_or(ArithmeticError::Overflow)?;433434		<TokensBurnt<T>>::insert(collection.id, burnt);435		<TokenProperties<T>>::remove((collection.id, token_id));436		<TotalSupply<T>>::remove((collection.id, token_id));437		let _ = <Balance<T>>::clear_prefix((collection.id, token_id), u32::MAX, None);438		let _ = <Allowance<T>>::clear_prefix((collection.id, token_id), u32::MAX, None);439		<PalletEvm<T>>::deposit_log(440			ERC721Events::Transfer {441				from: *owner.as_eth(),442				to: H160::default(),443				token_id: token_id.into(),444			}445			.to_log(collection_id_to_address(collection.id)),446		);447		Ok(())448	}449450	/// Burn RFT token pieces451	///452	/// `burn` will decrease total amount of token pieces and amount owned by sender.453	/// `burn` can be called even if there are multiple owners of the RFT token.454	/// If sender wouldn't have any pieces left after `burn` than she will stop being455	/// one of the owners of the token. If there is no account that owns any pieces of456	/// the token than token will be burned too.457	///458	/// - `amount`: Amount of token pieces to burn.459	/// - `token`: Token who's pieces should be burned460	/// - `collection`: Collection that contains the token461	pub fn burn(462		collection: &RefungibleHandle<T>,463		owner: &T::CrossAccountId,464		token: TokenId,465		amount: u128,466	) -> DispatchResult {467		if <Balance<T>>::get((collection.id, token, owner)) == 0 {468			return Err(<CommonError<T>>::TokenValueTooLow.into());469		}470471		let total_supply = <TotalSupply<T>>::get((collection.id, token))472			.checked_sub(amount)473			.ok_or(<CommonError<T>>::TokenValueTooLow)?;474475		// This was probally last owner of this token?476		if total_supply == 0 {477			// Ensure user actually owns this amount478			ensure!(479				<Balance<T>>::get((collection.id, token, owner)) == amount,480				<CommonError<T>>::TokenValueTooLow481			);482			let account_balance = <AccountBalance<T>>::get((collection.id, owner))483				.checked_sub(1)484				// Should not occur485				.ok_or(ArithmeticError::Underflow)?;486487			// =========488489			<Owned<T>>::remove((collection.id, owner, token));490			<PalletStructure<T>>::unnest_if_nested(owner, collection.id, token);491			<AccountBalance<T>>::insert((collection.id, owner), account_balance);492			Self::burn_token_unchecked(collection, owner, token)?;493			<PalletEvm<T>>::deposit_log(494				ERC20Events::Transfer {495					from: *owner.as_eth(),496					to: H160::default(),497					value: amount.into(),498				}499				.to_log(collection_id_to_address(collection.id)),500			);501			<PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(502				collection.id,503				token,504				owner.clone(),505				amount,506			));507			return Ok(());508		}509510		let balance = <Balance<T>>::get((collection.id, token, owner))511			.checked_sub(amount)512			.ok_or(<CommonError<T>>::TokenValueTooLow)?;513		let account_balance = if balance == 0 {514			<AccountBalance<T>>::get((collection.id, owner))515				.checked_sub(1)516				// Should not occur517				.ok_or(ArithmeticError::Underflow)?518		} else {519			0520		};521522		// =========523524		if balance == 0 {525			<Owned<T>>::remove((collection.id, owner, token));526			<PalletStructure<T>>::unnest_if_nested(owner, collection.id, token);527			<Balance<T>>::remove((collection.id, token, owner));528			<AccountBalance<T>>::insert((collection.id, owner), account_balance);529530			if let Some(user) = Self::token_owner(collection.id, token) {531				<PalletEvm<T>>::deposit_log(532					ERC721Events::Transfer {533						from: erc::ADDRESS_FOR_PARTIALLY_OWNED_TOKENS,534						to: *user.as_eth(),535						token_id: token.into(),536					}537					.to_log(collection_id_to_address(collection.id)),538				);539			}540		} else {541			<Balance<T>>::insert((collection.id, token, owner), balance);542		}543		<TotalSupply<T>>::insert((collection.id, token), total_supply);544545		<PalletEvm<T>>::deposit_log(546			ERC20Events::Transfer {547				from: *owner.as_eth(),548				to: H160::default(),549				value: amount.into(),550			}551			.to_log(T::EvmTokenAddressMapping::token_to_address(552				collection.id,553				token,554			)),555		);556		<PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(557			collection.id,558			token,559			owner.clone(),560			amount,561		));562		Ok(())563	}564565	#[transactional]566	fn modify_token_properties(567		collection: &RefungibleHandle<T>,568		sender: &T::CrossAccountId,569		token_id: TokenId,570		properties: impl Iterator<Item = (PropertyKey, Option<PropertyValue>)>,571		is_token_create: bool,572		nesting_budget: &dyn Budget,573	) -> DispatchResult {574		let is_collection_admin = || collection.is_owner_or_admin(sender);575		let is_token_owner = || -> Result<bool, DispatchError> {576			let balance = collection.balance(sender.clone(), token_id);577			let total_pieces: u128 =578				Self::total_pieces(collection.id, token_id).unwrap_or(u128::MAX);579			if balance != total_pieces {580				return Ok(false);581			}582583			let is_bundle_owner = <PalletStructure<T>>::check_indirectly_owned(584				sender.clone(),585				collection.id,586				token_id,587				None,588				nesting_budget,589			)?;590591			Ok(is_bundle_owner)592		};593594		for (key, value) in properties {595			let permission = <PalletCommon<T>>::property_permissions(collection.id)596				.get(&key)597				.cloned()598				.unwrap_or_else(PropertyPermission::none);599600			let is_property_exists = TokenProperties::<T>::get((collection.id, token_id))601				.get(&key)602				.is_some();603604			match permission {605				PropertyPermission { mutable: false, .. } if is_property_exists => {606					return Err(<CommonError<T>>::NoPermission.into());607				}608609				PropertyPermission {610					collection_admin,611					token_owner,612					..613				} => {614					//TODO: investigate threats during public minting.615					let is_token_create =616						is_token_create && (collection_admin || token_owner) && value.is_some();617					if !(is_token_create618						|| (collection_admin && is_collection_admin())619						|| (token_owner && is_token_owner()?))620					{621						fail!(<CommonError<T>>::NoPermission);622					}623				}624			}625626			match value {627				Some(value) => {628					<TokenProperties<T>>::try_mutate((collection.id, token_id), |properties| {629						properties.try_set(key.clone(), value)630					})631					.map_err(<CommonError<T>>::from)?;632633					<PalletCommon<T>>::deposit_event(CommonEvent::TokenPropertySet(634						collection.id,635						token_id,636						key,637					));638				}639				None => {640					<TokenProperties<T>>::try_mutate((collection.id, token_id), |properties| {641						properties.remove(&key)642					})643					.map_err(<CommonError<T>>::from)?;644645					<PalletCommon<T>>::deposit_event(CommonEvent::TokenPropertyDeleted(646						collection.id,647						token_id,648						key,649					));650				}651			}652		}653654		Ok(())655	}656657	pub fn set_token_properties(658		collection: &RefungibleHandle<T>,659		sender: &T::CrossAccountId,660		token_id: TokenId,661		properties: impl Iterator<Item = Property>,662		is_token_create: bool,663		nesting_budget: &dyn Budget,664	) -> DispatchResult {665		Self::modify_token_properties(666			collection,667			sender,668			token_id,669			properties.map(|p| (p.key, Some(p.value))),670			is_token_create,671			nesting_budget,672		)673	}674675	pub fn set_token_property(676		collection: &RefungibleHandle<T>,677		sender: &T::CrossAccountId,678		token_id: TokenId,679		property: Property,680		nesting_budget: &dyn Budget,681	) -> DispatchResult {682		let is_token_create = false;683684		Self::set_token_properties(685			collection,686			sender,687			token_id,688			[property].into_iter(),689			is_token_create,690			nesting_budget,691		)692	}693694	pub fn delete_token_properties(695		collection: &RefungibleHandle<T>,696		sender: &T::CrossAccountId,697		token_id: TokenId,698		property_keys: impl Iterator<Item = PropertyKey>,699		nesting_budget: &dyn Budget,700	) -> DispatchResult {701		let is_token_create = false;702703		Self::modify_token_properties(704			collection,705			sender,706			token_id,707			property_keys.into_iter().map(|key| (key, None)),708			is_token_create,709			nesting_budget,710		)711	}712713	pub fn delete_token_property(714		collection: &RefungibleHandle<T>,715		sender: &T::CrossAccountId,716		token_id: TokenId,717		property_key: PropertyKey,718		nesting_budget: &dyn Budget,719	) -> DispatchResult {720		Self::delete_token_properties(721			collection,722			sender,723			token_id,724			[property_key].into_iter(),725			nesting_budget,726		)727	}728729	/// Transfer RFT token pieces from one account to another.730	///731	/// If the sender is no longer owns any pieces after the `transfer` than she stops being an owner of the token.732	///733	/// - `from`: Owner of token pieces to transfer.734	/// - `to`: Recepient of transfered token pieces.735	/// - `amount`: Amount of token pieces to transfer.736	/// - `token`: Token whos pieces should be transfered737	/// - `collection`: Collection that contains the token738	pub fn transfer(739		collection: &RefungibleHandle<T>,740		from: &T::CrossAccountId,741		to: &T::CrossAccountId,742		token: TokenId,743		amount: u128,744		nesting_budget: &dyn Budget,745	) -> DispatchResult {746		ensure!(747			collection.limits.transfers_enabled(),748			<CommonError<T>>::TransferNotAllowed749		);750751		if collection.permissions.access() == AccessMode::AllowList {752			collection.check_allowlist(from)?;753			collection.check_allowlist(to)?;754		}755		<PalletCommon<T>>::ensure_correct_receiver(to)?;756757		let initial_balance_from = <Balance<T>>::get((collection.id, token, from));758759		if initial_balance_from == 0 {760			return Err(<CommonError<T>>::TokenValueTooLow.into());761		}762763		let updated_balance_from = initial_balance_from764			.checked_sub(amount)765			.ok_or(<CommonError<T>>::TokenValueTooLow)?;766		let mut create_target = false;767		let from_to_differ = from != to;768		let updated_balance_to = if from != to && amount != 0 {769			let old_balance = <Balance<T>>::get((collection.id, token, to));770			if old_balance == 0 {771				create_target = true;772			}773			Some(774				old_balance775					.checked_add(amount)776					.ok_or(ArithmeticError::Overflow)?,777			)778		} else {779			None780		};781782		let account_balance_from = if updated_balance_from == 0 {783			Some(784				<AccountBalance<T>>::get((collection.id, from))785					.checked_sub(1)786					// Should not occur787					.ok_or(ArithmeticError::Underflow)?,788			)789		} else {790			None791		};792		// Account data is created in token, AccountBalance should be increased793		// But only if from != to as we shouldn't check overflow in this case794		let account_balance_to = if create_target && from_to_differ {795			let account_balance_to = <AccountBalance<T>>::get((collection.id, to))796				.checked_add(1)797				.ok_or(ArithmeticError::Overflow)?;798			ensure!(799				account_balance_to < collection.limits.account_token_ownership_limit(),800				<CommonError<T>>::AccountTokenLimitExceeded,801			);802803			Some(account_balance_to)804		} else {805			None806		};807808		// =========809810		if let Some(updated_balance_to) = updated_balance_to {811			// from != to && amount != 0812813			<PalletStructure<T>>::nest_if_sent_to_token(814				from.clone(),815				to,816				collection.id,817				token,818				nesting_budget,819			)?;820821			if updated_balance_from == 0 {822				<Balance<T>>::remove((collection.id, token, from));823				<PalletStructure<T>>::unnest_if_nested(from, collection.id, token);824			} else {825				<Balance<T>>::insert((collection.id, token, from), updated_balance_from);826			}827			<Balance<T>>::insert((collection.id, token, to), updated_balance_to);828			if let Some(account_balance_from) = account_balance_from {829				<AccountBalance<T>>::insert((collection.id, from), account_balance_from);830				<Owned<T>>::remove((collection.id, from, token));831			}832			if let Some(account_balance_to) = account_balance_to {833				<AccountBalance<T>>::insert((collection.id, to), account_balance_to);834				<Owned<T>>::insert((collection.id, to, token), true);835			}836		}837838		<PalletEvm<T>>::deposit_log(839			ERC20Events::Transfer {840				from: *from.as_eth(),841				to: *to.as_eth(),842				value: amount.into(),843			}844			.to_log(T::EvmTokenAddressMapping::token_to_address(845				collection.id,846				token,847			)),848		);849850		<PalletCommon<T>>::deposit_event(CommonEvent::Transfer(851			collection.id,852			token,853			from.clone(),854			to.clone(),855			amount,856		));857858		let total_supply = <TotalSupply<T>>::get((collection.id, token));859860		if amount == total_supply {861			// if token was fully owned by `from` and will be fully owned by `to` after transfer862			<PalletEvm<T>>::deposit_log(863				ERC721Events::Transfer {864					from: *from.as_eth(),865					to: *to.as_eth(),866					token_id: token.into(),867				}868				.to_log(collection_id_to_address(collection.id)),869			);870		} else if let Some(updated_balance_to) = updated_balance_to {871			// if `from` not equals `to`. This condition is needed to avoid sending event872			// when `from` fully owns token and sends part of token pieces to itself.873			if initial_balance_from == total_supply {874				// if token was fully owned by `from` and will be only partially owned by `to`875				// and `from` after transfer876				<PalletEvm<T>>::deposit_log(877					ERC721Events::Transfer {878						from: *from.as_eth(),879						to: erc::ADDRESS_FOR_PARTIALLY_OWNED_TOKENS,880						token_id: token.into(),881					}882					.to_log(collection_id_to_address(collection.id)),883				);884			} else if updated_balance_to == total_supply {885				// if token was partially owned by `from` and will be fully owned by `to` after transfer886				<PalletEvm<T>>::deposit_log(887					ERC721Events::Transfer {888						from: erc::ADDRESS_FOR_PARTIALLY_OWNED_TOKENS,889						to: *to.as_eth(),890						token_id: token.into(),891					}892					.to_log(collection_id_to_address(collection.id)),893				);894			}895		}896897		Ok(())898	}899900	/// Batched operation to create multiple RFT tokens.901	///902	/// Same as `create_item` but creates multiple tokens.903	///904	/// - `data`: Same as 'data` in `create_item` but contains data for multiple tokens.905	pub fn create_multiple_items(906		collection: &RefungibleHandle<T>,907		sender: &T::CrossAccountId,908		data: Vec<CreateItemData<T::CrossAccountId>>,909		nesting_budget: &dyn Budget,910	) -> DispatchResult {911		if !collection.is_owner_or_admin(sender) {912			ensure!(913				collection.permissions.mint_mode(),914				<CommonError<T>>::PublicMintingNotAllowed915			);916			collection.check_allowlist(sender)?;917918			for item in data.iter() {919				for user in item.users.keys() {920					collection.check_allowlist(user)?;921				}922			}923		}924925		for item in data.iter() {926			for (owner, _) in item.users.iter() {927				<PalletCommon<T>>::ensure_correct_receiver(owner)?;928			}929		}930931		// Total pieces per tokens932		let totals = data933			.iter()934			.map(|data| {935				Ok(data936					.users937					.iter()938					.map(|u| u.1)939					.try_fold(0u128, |acc, v| acc.checked_add(*v))940					.ok_or(ArithmeticError::Overflow)?)941			})942			.collect::<Result<Vec<_>, DispatchError>>()?;943		for total in &totals {944			ensure!(945				*total <= MAX_REFUNGIBLE_PIECES,946				<Error<T>>::WrongRefungiblePieces947			);948		}949950		let first_token_id = <TokensMinted<T>>::get(collection.id);951		let tokens_minted = first_token_id952			.checked_add(data.len() as u32)953			.ok_or(ArithmeticError::Overflow)?;954		ensure!(955			tokens_minted < collection.limits.token_limit(),956			<CommonError<T>>::CollectionTokenLimitExceeded957		);958959		let mut balances = BTreeMap::new();960		for data in &data {961			for owner in data.users.keys() {962				let balance = balances963					.entry(owner)964					.or_insert_with(|| <AccountBalance<T>>::get((collection.id, owner)));965				*balance = balance.checked_add(1).ok_or(ArithmeticError::Overflow)?;966967				ensure!(968					*balance <= collection.limits.account_token_ownership_limit(),969					<CommonError<T>>::AccountTokenLimitExceeded,970				);971			}972		}973974		for (i, token) in data.iter().enumerate() {975			let token_id = TokenId(first_token_id + i as u32 + 1);976			for (to, _) in token.users.iter() {977				<PalletStructure<T>>::check_nesting(978					sender.clone(),979					to,980					collection.id,981					token_id,982					nesting_budget,983				)?;984			}985		}986987		// =========988989		with_transaction(|| {990			for (i, data) in data.iter().enumerate() {991				let token_id = first_token_id + i as u32 + 1;992				<TotalSupply<T>>::insert((collection.id, token_id), totals[i]);993994				for (user, amount) in data.users.iter() {995					if *amount == 0 {996						continue;997					}998					<Balance<T>>::insert((collection.id, token_id, &user), amount);999					<Owned<T>>::insert((collection.id, &user, TokenId(token_id)), true);1000					<PalletStructure<T>>::nest_if_sent_to_token_unchecked(1001						user,1002						collection.id,1003						TokenId(token_id),1004					);1005				}10061007				if let Err(e) = Self::set_token_properties(1008					collection,1009					sender,1010					TokenId(token_id),1011					data.properties.clone().into_iter(),1012					true,1013					nesting_budget,1014				) {1015					return TransactionOutcome::Rollback(Err(e));1016				}1017			}1018			TransactionOutcome::Commit(Ok(()))1019		})?;10201021		<TokensMinted<T>>::insert(collection.id, tokens_minted);10221023		for (account, balance) in balances {1024			<AccountBalance<T>>::insert((collection.id, account), balance);1025		}10261027		for (i, token) in data.into_iter().enumerate() {1028			let token_id = first_token_id + i as u32 + 1;10291030			let receivers = token1031				.users1032				.into_iter()1033				.filter(|(_, amount)| *amount > 0)1034				.collect::<Vec<_>>();10351036			if let [(user, _)] = receivers.as_slice() {1037				// if there is exactly one receiver1038				<PalletEvm<T>>::deposit_log(1039					ERC721Events::Transfer {1040						from: H160::default(),1041						to: *user.as_eth(),1042						token_id: token_id.into(),1043					}1044					.to_log(collection_id_to_address(collection.id)),1045				);1046			} else if let [_, ..] = receivers.as_slice() {1047				// if there is more than one receiver1048				<PalletEvm<T>>::deposit_log(1049					ERC721Events::Transfer {1050						from: H160::default(),1051						to: erc::ADDRESS_FOR_PARTIALLY_OWNED_TOKENS,1052						token_id: token_id.into(),1053					}1054					.to_log(collection_id_to_address(collection.id)),1055				);1056			}10571058			for (user, amount) in receivers.into_iter() {1059				<PalletEvm<T>>::deposit_log(1060					ERC20Events::Transfer {1061						from: H160::default(),1062						to: *user.as_eth(),1063						value: amount.into(),1064					}1065					.to_log(T::EvmTokenAddressMapping::token_to_address(1066						collection.id,1067						TokenId(token_id),1068					)),1069				);1070				<PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(1071					collection.id,1072					TokenId(token_id),1073					user,1074					amount,1075				));1076			}1077		}1078		Ok(())1079	}10801081	pub fn set_allowance_unchecked(1082		collection: &RefungibleHandle<T>,1083		sender: &T::CrossAccountId,1084		spender: &T::CrossAccountId,1085		token: TokenId,1086		amount: u128,1087	) {1088		if amount == 0 {1089			<Allowance<T>>::remove((collection.id, token, sender, spender));1090		} else {1091			<Allowance<T>>::insert((collection.id, token, sender, spender), amount);1092		}10931094		<PalletEvm<T>>::deposit_log(1095			ERC20Events::Approval {1096				owner: *sender.as_eth(),1097				spender: *spender.as_eth(),1098				value: amount.into(),1099			}1100			.to_log(T::EvmTokenAddressMapping::token_to_address(1101				collection.id,1102				token,1103			)),1104		);1105		<PalletCommon<T>>::deposit_event(CommonEvent::Approved(1106			collection.id,1107			token,1108			sender.clone(),1109			spender.clone(),1110			amount,1111		))1112	}11131114	/// Set allowance for the spender to `transfer` or `burn` sender's token pieces.1115	///1116	/// - `amount`: Amount of token pieces the spender is allowed to `transfer` or `burn.1117	pub fn set_allowance(1118		collection: &RefungibleHandle<T>,1119		sender: &T::CrossAccountId,1120		spender: &T::CrossAccountId,1121		token: TokenId,1122		amount: u128,1123	) -> DispatchResult {1124		if collection.permissions.access() == AccessMode::AllowList {1125			collection.check_allowlist(sender)?;1126			collection.check_allowlist(spender)?;1127		}11281129		<PalletCommon<T>>::ensure_correct_receiver(spender)?;11301131		if <Balance<T>>::get((collection.id, token, sender)) < amount {1132			ensure!(1133				collection.ignores_owned_amount(sender) && Self::token_exists(collection, token),1134				<CommonError<T>>::CantApproveMoreThanOwned1135			);1136		}11371138		// =========11391140		Self::set_allowance_unchecked(collection, sender, spender, token, amount);1141		Ok(())1142	}11431144	/// Returns allowance, which should be set after transaction1145	fn check_allowed(1146		collection: &RefungibleHandle<T>,1147		spender: &T::CrossAccountId,1148		from: &T::CrossAccountId,1149		token: TokenId,1150		amount: u128,1151		nesting_budget: &dyn Budget,1152	) -> Result<Option<u128>, DispatchError> {1153		if spender.conv_eq(from) {1154			return Ok(None);1155		}1156		if collection.permissions.access() == AccessMode::AllowList {1157			// `from`, `to` checked in [`transfer`]1158			collection.check_allowlist(spender)?;1159		}1160		if let Some(source) = T::CrossTokenAddressMapping::address_to_token(from) {1161			// TODO: should collection owner be allowed to perform this transfer?1162			ensure!(1163				<PalletStructure<T>>::check_indirectly_owned(1164					spender.clone(),1165					source.0,1166					source.1,1167					None,1168					nesting_budget1169				)?,1170				<CommonError<T>>::ApprovedValueTooLow,1171			);1172			return Ok(None);1173		}1174		let allowance =1175			<Allowance<T>>::get((collection.id, token, from, &spender)).checked_sub(amount);11761177		// Allowance if any would be reduced if spender is also wallet operator1178		if <WalletOperator<T>>::get((collection.id, from, spender)) == Some(true) {1179			return Ok(allowance);1180		}11811182		if allowance.is_none() {1183			ensure!(1184				collection.ignores_allowance(spender),1185				<CommonError<T>>::ApprovedValueTooLow1186			);1187		}1188		Ok(allowance)1189	}11901191	/// Transfer RFT token pieces from one account to another.1192	///1193	/// Same as the [`transfer`] but spender doesn't needs to be an owner of the token pieces.1194	/// The owner should set allowance for the spender to transfer pieces.1195	///1196	/// [`transfer`]: struct.Pallet.html#method.transfer1197	pub fn transfer_from(1198		collection: &RefungibleHandle<T>,1199		spender: &T::CrossAccountId,1200		from: &T::CrossAccountId,1201		to: &T::CrossAccountId,1202		token: TokenId,1203		amount: u128,1204		nesting_budget: &dyn Budget,1205	) -> DispatchResult {1206		let allowance =1207			Self::check_allowed(collection, spender, from, token, amount, nesting_budget)?;12081209		// =========12101211		Self::transfer(collection, from, to, token, amount, nesting_budget)?;1212		if let Some(allowance) = allowance {1213			Self::set_allowance_unchecked(collection, from, spender, token, allowance);1214		}1215		Ok(())1216	}12171218	/// Burn RFT token pieces from the account.1219	///1220	/// Same as the [`burn`] but spender doesn't need to be an owner of the token pieces. The owner should1221	/// set allowance for the spender to burn pieces1222	///1223	/// [`burn`]: struct.Pallet.html#method.burn1224	pub fn burn_from(1225		collection: &RefungibleHandle<T>,1226		spender: &T::CrossAccountId,1227		from: &T::CrossAccountId,1228		token: TokenId,1229		amount: u128,1230		nesting_budget: &dyn Budget,1231	) -> DispatchResult {1232		let allowance =1233			Self::check_allowed(collection, spender, from, token, amount, nesting_budget)?;12341235		// =========12361237		Self::burn(collection, from, token, amount)?;1238		if let Some(allowance) = allowance {1239			Self::set_allowance_unchecked(collection, from, spender, token, allowance);1240		}1241		Ok(())1242	}12431244	/// Create RFT token.1245	///1246	/// The sender should be the owner/admin of the collection or collection should be configured1247	/// to allow public minting.1248	///1249	/// - `data`: Contains list of users who will become the owners of the token pieces and amount1250	///   of token pieces they will receive.1251	pub fn create_item(1252		collection: &RefungibleHandle<T>,1253		sender: &T::CrossAccountId,1254		data: CreateItemData<T::CrossAccountId>,1255		nesting_budget: &dyn Budget,1256	) -> DispatchResult {1257		Self::create_multiple_items(collection, sender, vec![data], nesting_budget)1258	}12591260	/// Repartition RFT token.1261	///1262	/// `repartition` will set token balance of the sender and total amount of token pieces.1263	/// Sender should own all of the token pieces. `repartition' could be done even if some1264	/// token pieces were burned before.1265	///1266	/// - `amount`: Total amount of token pieces that the token will have after `repartition`.1267	pub fn repartition(1268		collection: &RefungibleHandle<T>,1269		owner: &T::CrossAccountId,1270		token: TokenId,1271		amount: u128,1272	) -> DispatchResult {1273		ensure!(1274			amount <= MAX_REFUNGIBLE_PIECES,1275			<Error<T>>::WrongRefungiblePieces1276		);1277		ensure!(amount > 0, <CommonError<T>>::TokenValueTooLow);1278		// Ensure user owns all pieces1279		let total_pieces = Self::total_pieces(collection.id, token).unwrap_or(u128::MAX);1280		let balance = <Balance<T>>::get((collection.id, token, owner));1281		ensure!(1282			total_pieces == balance,1283			<Error<T>>::RepartitionWhileNotOwningAllPieces1284		);12851286		<Balance<T>>::insert((collection.id, token, owner), amount);1287		<TotalSupply<T>>::insert((collection.id, token), amount);12881289		if amount > total_pieces {1290			let mint_amount = amount - total_pieces;1291			<PalletEvm<T>>::deposit_log(1292				ERC20Events::Transfer {1293					from: H160::default(),1294					to: *owner.as_eth(),1295					value: mint_amount.into(),1296				}1297				.to_log(T::EvmTokenAddressMapping::token_to_address(1298					collection.id,1299					token,1300				)),1301			);1302			<PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(1303				collection.id,1304				token,1305				owner.clone(),1306				mint_amount,1307			));1308		} else if total_pieces > amount {1309			let burn_amount = total_pieces - amount;1310			<PalletEvm<T>>::deposit_log(1311				ERC20Events::Transfer {1312					from: *owner.as_eth(),1313					to: H160::default(),1314					value: burn_amount.into(),1315				}1316				.to_log(T::EvmTokenAddressMapping::token_to_address(1317					collection.id,1318					token,1319				)),1320			);1321			<PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(1322				collection.id,1323				token,1324				owner.clone(),1325				burn_amount,1326			));1327		}13281329		Ok(())1330	}13311332	fn token_owner(collection_id: CollectionId, token_id: TokenId) -> Option<T::CrossAccountId> {1333		let mut owner = None;1334		let mut count = 0;1335		for key in Balance::<T>::iter_key_prefix((collection_id, token_id)) {1336			count += 1;1337			if count > 1 {1338				return None;1339			}1340			owner = Some(key);1341		}1342		owner1343	}13441345	fn total_pieces(collection_id: CollectionId, token_id: TokenId) -> Option<u128> {1346		<TotalSupply<T>>::try_get((collection_id, token_id)).ok()1347	}13481349	pub fn set_collection_properties(1350		collection: &RefungibleHandle<T>,1351		sender: &T::CrossAccountId,1352		properties: Vec<Property>,1353	) -> DispatchResult {1354		<PalletCommon<T>>::set_collection_properties(collection, sender, properties)1355	}13561357	pub fn delete_collection_properties(1358		collection: &RefungibleHandle<T>,1359		sender: &T::CrossAccountId,1360		property_keys: Vec<PropertyKey>,1361	) -> DispatchResult {1362		<PalletCommon<T>>::delete_collection_properties(collection, sender, property_keys)1363	}13641365	pub fn set_token_property_permissions(1366		collection: &RefungibleHandle<T>,1367		sender: &T::CrossAccountId,1368		property_permissions: Vec<PropertyKeyPermission>,1369	) -> DispatchResult {1370		<PalletCommon<T>>::set_token_property_permissions(collection, sender, property_permissions)1371	}13721373	pub fn set_scoped_token_property_permissions(1374		collection: &RefungibleHandle<T>,1375		sender: &T::CrossAccountId,1376		scope: PropertyScope,1377		property_permissions: Vec<PropertyKeyPermission>,1378	) -> DispatchResult {1379		<PalletCommon<T>>::set_scoped_token_property_permissions(1380			collection,1381			sender,1382			scope,1383			property_permissions,1384		)1385	}13861387	/// Returns 10 token in no particular order.1388	///1389	/// There is no direct way to get token holders in ascending order,1390	/// since `iter_prefix` returns values in no particular order.1391	/// Therefore, getting the 10 largest holders with a large value of holders1392	/// can lead to impact memory allocation + sorting with  `n * log (n)`.1393	pub fn token_owners(1394		collection_id: CollectionId,1395		token: TokenId,1396	) -> Option<Vec<T::CrossAccountId>> {1397		let res: Vec<T::CrossAccountId> = <Balance<T>>::iter_prefix((collection_id, token))1398			.map(|(owner, _amount)| owner)1399			.take(10)1400			.collect();14011402		if res.is_empty() {1403			None1404		} else {1405			Some(res)1406		}1407	}14081409	/// Sets or unsets the approval of a given operator.1410	///1411	/// An operator is allowed to transfer all tokens of the sender on their behalf.1412	/// - `owner`: Token owner1413	/// - `operator`: Operator1414	/// - `approve`: Is operator enabled or disabled1415	pub fn set_approval_for_all(1416		collection: &RefungibleHandle<T>,1417		owner: &T::CrossAccountId,1418		operator: &T::CrossAccountId,1419		approve: bool,1420	) -> DispatchResult {1421		if collection.permissions.access() == AccessMode::AllowList {1422			collection.check_allowlist(owner)?;1423			collection.check_allowlist(operator)?;1424		}14251426		<PalletCommon<T>>::ensure_correct_receiver(operator)?;14271428		// =========14291430		<WalletOperator<T>>::insert((collection.id, owner, operator), approve);1431		<PalletEvm<T>>::deposit_log(1432			ERC721Events::ApprovalForAll {1433				owner: *owner.as_eth(),1434				operator: *operator.as_eth(),1435				approved: approve,1436			}1437			.to_log(collection_id_to_address(collection.id)),1438		);1439		<PalletCommon<T>>::deposit_event(CommonEvent::ApprovedForAll(1440			collection.id,1441			owner.clone(),1442			operator.clone(),1443			approve,1444		));1445		Ok(())1446	}14471448	/// Tells whether an operator is approved by a given owner.1449	pub fn is_approved_for_all(1450		collection: &RefungibleHandle<T>,1451		owner: &T::CrossAccountId,1452		operator: &T::CrossAccountId,1453	) -> bool {1454		<WalletOperator<T>>::get((collection.id, owner, operator)).unwrap_or(false)1455	}1456}
modifiedpallets/refungible/src/stubs/UniqueRefungible.rawdiffbeforeafterboth

binary blob — no preview

modifiedpallets/refungible/src/stubs/UniqueRefungible.soldiffbeforeafterboth
--- a/pallets/refungible/src/stubs/UniqueRefungible.sol
+++ b/pallets/refungible/src/stubs/UniqueRefungible.sol
@@ -1017,7 +1017,10 @@
 		dummy = 0;
 	}
 
-	/// @dev Not implemented
+	/// @notice Sets or unsets the approval of a given operator.
+	///  An operator is allowed to transfer all tokens of the sender on their behalf.
+	/// @param operator Operator
+	/// @param approved Is operator enabled or disabled
 	/// @dev EVM selector for this function is: 0xa22cb465,
 	///  or in textual repr: setApprovalForAll(address,bool)
 	function setApprovalForAll(address operator, bool approved) public {
@@ -1037,15 +1040,15 @@
 		return 0x0000000000000000000000000000000000000000;
 	}
 
-	/// @dev Not implemented
+	/// @notice Tells whether an operator is approved by a given owner.
 	/// @dev EVM selector for this function is: 0xe985e9c5,
 	///  or in textual repr: isApprovedForAll(address,address)
-	function isApprovedForAll(address owner, address operator) public view returns (address) {
+	function isApprovedForAll(address owner, address operator) public view returns (bool) {
 		require(false, stub_error);
 		owner;
 		operator;
 		dummy;
-		return 0x0000000000000000000000000000000000000000;
+		return false;
 	}
 
 	/// @notice Returns collection helper contract address
modifiedpallets/refungible/src/weights.rsdiffbeforeafterboth
--- a/pallets/refungible/src/weights.rs
+++ b/pallets/refungible/src/weights.rs
@@ -3,7 +3,7 @@
 //! Autogenerated weights for pallet_refungible
 //!
 //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev
-//! DATE: 2022-08-15, STEPS: `50`, REPEAT: 80, LOW RANGE: `[]`, HIGH RANGE: `[]`
+//! DATE: 2022-11-25, STEPS: `50`, REPEAT: 80, LOW RANGE: `[]`, HIGH RANGE: `[]`
 //! EXECUTION: None, WASM-EXECUTION: Compiled, CHAIN: None, DB CACHE: 1024
 
 // Executed Command:
@@ -26,6 +26,7 @@
 #![cfg_attr(rustfmt, rustfmt_skip)]
 #![allow(unused_parens)]
 #![allow(unused_imports)]
+#![allow(missing_docs)]
 #![allow(clippy::unnecessary_cast)]
 
 use frame_support::{traits::Get, weights::{Weight, constants::RocksDbWeight}};
@@ -54,6 +55,8 @@
 	fn delete_token_properties(b: u32, ) -> Weight;
 	fn repartition_item() -> Weight;
 	fn token_owner() -> Weight;
+	fn set_approval_for_all() -> Weight;
+	fn is_approved_for_all() -> Weight;
 }
 
 /// Weights for pallet_refungible using the Substrate node and recommended hardware.
@@ -259,6 +262,16 @@
 		Weight::from_ref_time(9_431_000)
 			.saturating_add(T::DbWeight::get().reads(2 as u64))
 	}
+	// Storage: Refungible WalletOperator (r:0 w:1)
+	fn set_approval_for_all() -> Weight {
+		Weight::from_ref_time(16_150_000 as u64)
+			.saturating_add(T::DbWeight::get().writes(1 as u64))
+	}
+	// Storage: Refungible WalletOperator (r:1 w:0)
+	fn is_approved_for_all() -> Weight {
+		Weight::from_ref_time(5_901_000 as u64)
+			.saturating_add(T::DbWeight::get().reads(1 as u64))
+	}
 }
 
 // For backwards compatibility and tests
@@ -463,4 +476,14 @@
 		Weight::from_ref_time(9_431_000)
 			.saturating_add(RocksDbWeight::get().reads(2 as u64))
 	}
+	// Storage: Refungible WalletOperator (r:0 w:1)
+	fn set_approval_for_all() -> Weight {
+		Weight::from_ref_time(16_150_000 as u64)
+			.saturating_add(RocksDbWeight::get().writes(1 as u64))
+	}
+	// Storage: Refungible WalletOperator (r:1 w:0)
+	fn is_approved_for_all() -> Weight {
+		Weight::from_ref_time(5_901_000 as u64)
+			.saturating_add(RocksDbWeight::get().reads(1 as u64))
+	}
 }
modifiedpallets/unique/src/lib.rsdiffbeforeafterboth
--- a/pallets/unique/src/lib.rs
+++ b/pallets/unique/src/lib.rs
@@ -1126,6 +1126,28 @@
 				}
 			})
 		}
+
+		/// Sets or unsets the approval of a given operator.
+		///
+		/// An operator is allowed to transfer all tokens of the sender on their behalf.
+		///
+		/// # Arguments
+		///
+		/// * `owner`: Token owner
+		/// * `operator`: Operator
+		/// * `approve`: Is operator enabled or disabled
+		#[weight = T::CommonWeightInfo::set_approval_for_all()]
+		pub fn set_approval_for_all(
+			origin,
+			collection_id: CollectionId,
+			operator: T::CrossAccountId,
+			approve: bool,
+		) -> DispatchResultWithPostInfo {
+			let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);
+			dispatch_tx::<T, _>(collection_id, |d| {
+				d.set_approval_for_all(sender, operator, approve)
+			})
+		}
 	}
 }
 
modifiedprimitives/rpc/src/lib.rsdiffbeforeafterboth
--- a/primitives/rpc/src/lib.rs
+++ b/primitives/rpc/src/lib.rs
@@ -132,5 +132,8 @@
 		fn total_pieces(collection_id: CollectionId, token_id: TokenId) -> Result<Option<u128>>;
 
 		fn token_owners(collection: CollectionId, token: TokenId) -> Result<Vec<CrossAccountId>>;
+
+		/// Get whether an operator is approved by a given owner.
+		fn is_approved_for_all(collection: CollectionId, owner: CrossAccountId, operator: CrossAccountId) -> Result<bool>;
 	}
 }
modifiedruntime/common/runtime_apis.rsdiffbeforeafterboth
--- a/runtime/common/runtime_apis.rs
+++ b/runtime/common/runtime_apis.rs
@@ -187,6 +187,10 @@
                 fn total_pieces(collection: CollectionId, token_id: TokenId) -> Result<Option<u128>, DispatchError> {
                     dispatch_unique_runtime!(collection.total_pieces(token_id))
                 }
+
+		        fn is_approved_for_all(collection: CollectionId, owner: CrossAccountId, operator: CrossAccountId) -> Result<bool, DispatchError> {
+                    dispatch_unique_runtime!(collection.is_approved_for_all(owner, operator))
+                }
             }
 
             impl app_promotion_rpc::AppPromotionApi<Block, BlockNumber, CrossAccountId, AccountId> for Runtime {
modifiedruntime/common/weights.rsdiffbeforeafterboth
--- a/runtime/common/weights.rs
+++ b/runtime/common/weights.rs
@@ -120,6 +120,10 @@
 	fn token_owner() -> Weight {
 		max_weight_of!(token_owner())
 	}
+
+	fn set_approval_for_all() -> Weight {
+		max_weight_of!(set_approval_for_all())
+	}
 }
 
 #[cfg(feature = "refungible")]
modifiedtests/src/approve.test.tsdiffbeforeafterboth
--- a/tests/src/approve.test.ts
+++ b/tests/src/approve.test.ts
@@ -603,3 +603,40 @@
     await expect(approveTx()).to.be.rejected;
   });
 });
+
+describe('Normal user can approve other users to be wallet operator:', () => {
+  let alice: IKeyringPair;
+  let bob: IKeyringPair;
+
+  before(async () => {
+    await usingPlaygrounds(async (helper, privateKey) => {
+      const donor = await privateKey({filename: __filename});
+      [alice, bob] = await helper.arrange.createAccounts([100n, 100n], donor);
+    });
+  });
+
+  itSub('[nft] Enable and disable approval', async ({helper}) => {
+    const {collectionId} = await helper.nft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});
+    await helper.nft.mintToken(alice, {collectionId: collectionId, owner: alice.address});
+    const checkBeforeApprovalTx = () => helper.nft.isApprovedForAll(collectionId, {Substrate: alice.address}, {Substrate: bob.address});
+    expect(await checkBeforeApprovalTx()).to.be.false;
+    await helper.nft.setApprovalForAll(alice, collectionId, {Substrate: bob.address}, true);
+    const checkAfterApprovalTx = () => helper.nft.isApprovedForAll(collectionId, {Substrate: alice.address}, {Substrate: bob.address});
+    expect(await checkAfterApprovalTx()).to.be.true;
+    await helper.nft.setApprovalForAll(alice, collectionId, {Substrate: bob.address}, false);
+    const checkAfterDisapprovalTx = () => helper.nft.isApprovedForAll(collectionId, {Substrate: alice.address}, {Substrate: bob.address});
+    expect(await checkAfterDisapprovalTx()).to.be.false;
+  });
+
+  itSub.ifWithPallets('[rft] Enable and disable approval', [Pallets.ReFungible], async ({helper}) => {
+    const {collectionId} = await helper.rft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});
+    const checkBeforeApprovalTx = () => helper.rft.isApprovedForAll(collectionId, {Substrate: alice.address}, {Substrate: bob.address});
+    expect(await checkBeforeApprovalTx()).to.be.false;
+    await helper.rft.setApprovalForAll(alice, collectionId, {Substrate: bob.address}, true);
+    const checkAfterApprovalTx = () => helper.rft.isApprovedForAll(collectionId, {Substrate: alice.address}, {Substrate: bob.address});
+    expect(await checkAfterApprovalTx()).to.be.true;
+    await helper.rft.setApprovalForAll(alice, collectionId, {Substrate: bob.address}, false);
+    const checkAfterDisapprovalTx = () => helper.rft.isApprovedForAll(collectionId, {Substrate: alice.address}, {Substrate: bob.address});
+    expect(await checkAfterDisapprovalTx()).to.be.false;
+  });
+});
modifiedtests/src/eth/abi/nonFungible.jsondiffbeforeafterboth
--- a/tests/src/eth/abi/nonFungible.json
+++ b/tests/src/eth/abi/nonFungible.json
@@ -384,7 +384,7 @@
       { "internalType": "address", "name": "operator", "type": "address" }
     ],
     "name": "isApprovedForAll",
-    "outputs": [{ "internalType": "address", "name": "", "type": "address" }],
+    "outputs": [{ "internalType": "bool", "name": "", "type": "bool" }],
     "stateMutability": "view",
     "type": "function"
   },
modifiedtests/src/eth/abi/reFungible.jsondiffbeforeafterboth
--- a/tests/src/eth/abi/reFungible.json
+++ b/tests/src/eth/abi/reFungible.json
@@ -366,7 +366,7 @@
       { "internalType": "address", "name": "operator", "type": "address" }
     ],
     "name": "isApprovedForAll",
-    "outputs": [{ "internalType": "address", "name": "", "type": "address" }],
+    "outputs": [{ "internalType": "bool", "name": "", "type": "bool" }],
     "stateMutability": "view",
     "type": "function"
   },
modifiedtests/src/eth/api/UniqueNFT.soldiffbeforeafterboth
--- a/tests/src/eth/api/UniqueNFT.sol
+++ b/tests/src/eth/api/UniqueNFT.sol
@@ -671,7 +671,10 @@
 	///  or in textual repr: approve(address,uint256)
 	function approve(address approved, uint256 tokenId) external;
 
-	/// @dev Not implemented
+	/// @notice Sets or unsets the approval of a given operator.
+	///  An operator is allowed to transfer all tokens of the sender on their behalf.
+	/// @param operator Operator
+	/// @param approved Is operator enabled or disabled
 	/// @dev EVM selector for this function is: 0xa22cb465,
 	///  or in textual repr: setApprovalForAll(address,bool)
 	function setApprovalForAll(address operator, bool approved) external;
@@ -681,10 +684,10 @@
 	///  or in textual repr: getApproved(uint256)
 	function getApproved(uint256 tokenId) external view returns (address);
 
-	/// @dev Not implemented
+	/// @notice Tells whether an operator is approved by a given owner.
 	/// @dev EVM selector for this function is: 0xe985e9c5,
 	///  or in textual repr: isApprovedForAll(address,address)
-	function isApprovedForAll(address owner, address operator) external view returns (address);
+	function isApprovedForAll(address owner, address operator) external view returns (bool);
 
 	/// @notice Returns collection helper contract address
 	/// @dev EVM selector for this function is: 0x1896cce6,
modifiedtests/src/eth/api/UniqueRefungible.soldiffbeforeafterboth
--- a/tests/src/eth/api/UniqueRefungible.sol
+++ b/tests/src/eth/api/UniqueRefungible.sol
@@ -668,7 +668,10 @@
 	///  or in textual repr: approve(address,uint256)
 	function approve(address approved, uint256 tokenId) external;
 
-	/// @dev Not implemented
+	/// @notice Sets or unsets the approval of a given operator.
+	///  An operator is allowed to transfer all tokens of the sender on their behalf.
+	/// @param operator Operator
+	/// @param approved Is operator enabled or disabled
 	/// @dev EVM selector for this function is: 0xa22cb465,
 	///  or in textual repr: setApprovalForAll(address,bool)
 	function setApprovalForAll(address operator, bool approved) external;
@@ -678,10 +681,10 @@
 	///  or in textual repr: getApproved(uint256)
 	function getApproved(uint256 tokenId) external view returns (address);
 
-	/// @dev Not implemented
+	/// @notice Tells whether an operator is approved by a given owner.
 	/// @dev EVM selector for this function is: 0xe985e9c5,
 	///  or in textual repr: isApprovedForAll(address,address)
-	function isApprovedForAll(address owner, address operator) external view returns (address);
+	function isApprovedForAll(address owner, address operator) external view returns (bool);
 
 	/// @notice Returns collection helper contract address
 	/// @dev EVM selector for this function is: 0x1896cce6,
modifiedtests/src/eth/nonFungible.test.tsdiffbeforeafterboth
--- a/tests/src/eth/nonFungible.test.ts
+++ b/tests/src/eth/nonFungible.test.ts
@@ -249,6 +249,114 @@
     }
   });
 
+  itEth('Can perform setApprovalForAll()', async ({helper}) => {
+    const owner = await helper.eth.createAccountWithBalance(donor);
+    const operator = helper.eth.createAccount();
+
+    const collection = await helper.nft.mintCollection(minter, {});
+
+    const collectionAddress = helper.ethAddress.fromCollectionId(collection.collectionId);
+    const contract = helper.ethNativeContract.collection(collectionAddress, 'nft', owner);
+
+    const approvedBefore = await contract.methods.isApprovedForAll(owner, operator).call();
+    expect(approvedBefore).to.be.equal(false);
+
+    {
+      const result = await contract.methods.setApprovalForAll(operator, true).send({from: owner});
+
+      expect(result.events.ApprovalForAll).to.be.like({
+        address: collectionAddress,
+        event: 'ApprovalForAll',
+        returnValues: {
+          owner,
+          operator,
+          approved: true,
+        },
+      });
+
+      const approvedAfter = await contract.methods.isApprovedForAll(owner, operator).call();
+      expect(approvedAfter).to.be.equal(true);
+    }
+
+    {
+      const result = await contract.methods.setApprovalForAll(operator, false).send({from: owner});
+
+      expect(result.events.ApprovalForAll).to.be.like({
+        address: collectionAddress,
+        event: 'ApprovalForAll',
+        returnValues: {
+          owner,
+          operator,
+          approved: false,
+        },
+      });
+
+      const approvedAfter = await contract.methods.isApprovedForAll(owner, operator).call();
+      expect(approvedAfter).to.be.equal(false);
+    }
+  });
+
+  itEth('Can perform burn with ApprovalForAll', async ({helper}) => {
+    const collection = await helper.nft.mintCollection(minter, {name: 'A', description: 'B', tokenPrefix: 'C'});
+
+    const owner = await helper.eth.createAccountWithBalance(donor);
+    const operator = await helper.eth.createAccountWithBalance(donor, 100n);
+
+    const token = await collection.mintToken(minter, {Ethereum: owner});
+
+    const address = helper.ethAddress.fromCollectionId(collection.collectionId);
+    const contract = helper.ethNativeContract.collection(address, 'nft');
+
+    {
+      await contract.methods.setApprovalForAll(operator, true).send({from: owner});
+      const ownerCross = helper.ethCrossAccount.fromAddress(owner);
+      const result = await contract.methods.burnFromCross(ownerCross, token.tokenId).send({from: operator});
+      const events = result.events.Transfer;
+
+      expect(events).to.be.like({
+        address,
+        event: 'Transfer',
+        returnValues: {
+          from: owner,
+          to: '0x0000000000000000000000000000000000000000',
+          tokenId: token.tokenId.toString(),
+        },
+      });
+    }
+  });
+  
+  itEth('Can perform transfer with ApprovalForAll', async ({helper}) => {
+    const collection = await helper.nft.mintCollection(minter, {name: 'A', description: 'B', tokenPrefix: 'C'});
+
+    const owner = await helper.eth.createAccountWithBalance(donor);
+    const operator = await helper.eth.createAccountWithBalance(donor);
+    const receiver = charlie;
+
+    const token = await collection.mintToken(minter, {Ethereum: owner});
+
+    const address = helper.ethAddress.fromCollectionId(collection.collectionId);
+    const contract = helper.ethNativeContract.collection(address, 'nft');
+
+    {
+      await contract.methods.setApprovalForAll(operator, true).send({from: owner});
+      const ownerCross = helper.ethCrossAccount.fromAddress(owner);
+      const recieverCross = helper.ethCrossAccount.fromKeyringPair(receiver);
+      const result = await contract.methods.transferFromCross(ownerCross, recieverCross, token.tokenId).send({from: operator});
+      const event = result.events.Transfer;
+      expect(event).to.be.like({
+        address: helper.ethAddress.fromCollectionId(collection.collectionId),
+        event: 'Transfer',
+        returnValues: {
+          from: owner,
+          to: helper.address.substrateToEth(receiver.address),
+          tokenId: token.tokenId.toString(),
+        },
+      });
+    }
+
+    expect(await token.getOwner()).to.be.like({Substrate: receiver.address});
+  });
+
   itEth('Can perform burnFromCross()', async ({helper}) => {
     const collection = await helper.nft.mintCollection(minter, {name: 'A', description: 'B', tokenPrefix: 'C'});
     const ownerSub = bob;
@@ -822,3 +930,53 @@
     expect(symbol).to.equal('CHANGE');
   });
 });
+
+describe('Negative tests', () => {
+  let donor: IKeyringPair;
+  let minter: IKeyringPair;
+  let alice: IKeyringPair;
+  let bob: IKeyringPair;
+
+  before(async function() {
+    await usingEthPlaygrounds(async (helper, privateKey) => {
+      donor = await privateKey({filename: __filename});
+      [minter, alice, bob] = await helper.arrange.createAccounts([100n, 100n, 100n], donor);
+    });
+  });
+
+  itEth('[negative] Cant perform burn without approval', async ({helper}) => {
+    const collection = await helper.nft.mintCollection(minter, {name: 'A', description: 'B', tokenPrefix: 'C'});
+
+    const owner = bob;
+    const spender = await helper.eth.createAccountWithBalance(donor, 100n);
+
+    const token = await collection.mintToken(minter, {Substrate: owner.address});
+
+    const address = helper.ethAddress.fromCollectionId(collection.collectionId);
+    const contract = helper.ethNativeContract.collection(address, 'nft');
+
+    {
+      const ownerCross = helper.ethCrossAccount.fromKeyringPair(owner);
+      await expect(contract.methods.burnFromCross(ownerCross, token.tokenId).send({from: spender})).to.be.rejected;
+    }
+  });
+
+  itEth('[negative] Cant perform transfer without approval', async ({helper}) => {
+    const collection = await helper.nft.mintCollection(minter, {name: 'A', description: 'B', tokenPrefix: 'C'});
+    const owner = bob;
+    const receiver = alice;
+
+    const spender = await helper.eth.createAccountWithBalance(donor, 100n);
+
+    const token = await collection.mintToken(minter, {Substrate: owner.address});
+
+    const address = helper.ethAddress.fromCollectionId(collection.collectionId);
+    const contract = helper.ethNativeContract.collection(address, 'nft');
+
+    {
+      const ownerCross = helper.ethCrossAccount.fromKeyringPair(owner);
+      const recieverCross = helper.ethCrossAccount.fromKeyringPair(receiver);
+      await expect(contract.methods.transferFromCross(ownerCross, recieverCross, token.tokenId).send({from: spender})).to.be.rejected;
+    }
+  });
+});
modifiedtests/src/eth/reFungible.test.tsdiffbeforeafterboth
--- a/tests/src/eth/reFungible.test.ts
+++ b/tests/src/eth/reFungible.test.ts
@@ -169,6 +169,136 @@
     }
   });
 
+  itEth('Can perform setApprovalForAll()', async ({helper}) => {
+    const owner = await helper.eth.createAccountWithBalance(donor);
+    const operator = helper.eth.createAccount();
+
+    const collection = await helper.rft.mintCollection(minter, {});
+
+    const collectionAddress = helper.ethAddress.fromCollectionId(collection.collectionId);
+    const contract = helper.ethNativeContract.collection(collectionAddress, 'rft', owner);
+
+    const approvedBefore = await contract.methods.isApprovedForAll(owner, operator).call();
+    expect(approvedBefore).to.be.equal(false);
+
+    {
+      const result = await contract.methods.setApprovalForAll(operator, true).send({from: owner});
+
+      expect(result.events.ApprovalForAll).to.be.like({
+        address: collectionAddress,
+        event: 'ApprovalForAll',
+        returnValues: {
+          owner,
+          operator,
+          approved: true,
+        },
+      });
+
+      const approvedAfter = await contract.methods.isApprovedForAll(owner, operator).call();
+      expect(approvedAfter).to.be.equal(true);
+    }
+
+    {
+      const result = await contract.methods.setApprovalForAll(operator, false).send({from: owner});
+
+      expect(result.events.ApprovalForAll).to.be.like({
+        address: collectionAddress,
+        event: 'ApprovalForAll',
+        returnValues: {
+          owner,
+          operator,
+          approved: false,
+        },
+      });
+
+      const approvedAfter = await contract.methods.isApprovedForAll(owner, operator).call();
+      expect(approvedAfter).to.be.equal(false);
+    }
+  });
+
+  itEth('Can perform burn with ApprovalForAll', async ({helper}) => {
+    const collection = await helper.rft.mintCollection(minter, {name: 'A', description: 'B', tokenPrefix: 'C'});
+
+    const owner = await helper.eth.createAccountWithBalance(donor);
+    const operator = await helper.eth.createAccountWithBalance(donor, 100n);
+
+    const token = await collection.mintToken(minter, 100n, {Ethereum: owner});
+
+    const address = helper.ethAddress.fromCollectionId(collection.collectionId);
+    const contract = helper.ethNativeContract.collection(address, 'rft');
+
+    {
+      await contract.methods.setApprovalForAll(operator, true).send({from: owner});
+      const ownerCross = helper.ethCrossAccount.fromAddress(owner);
+      const result = await contract.methods.burnFromCross(ownerCross, token.tokenId).send({from: operator});
+      const events = result.events.Transfer;
+
+      expect(events).to.be.like({
+        address,
+        event: 'Transfer',
+        returnValues: {
+          from: owner,
+          to: '0x0000000000000000000000000000000000000000',
+          tokenId: token.tokenId.toString(),
+        },
+      });
+    }
+  });
+
+  itEth('Can perform burn with approve and approvalForAll', async ({helper}) => {
+    const collection = await helper.rft.mintCollection(minter, {name: 'A', description: 'B', tokenPrefix: 'C'});
+
+    const owner = await helper.eth.createAccountWithBalance(donor);
+    const operator = await helper.eth.createAccountWithBalance(donor, 100n);
+
+    const token = await collection.mintToken(minter, 100n, {Ethereum: owner});
+
+    const address = helper.ethAddress.fromCollectionId(collection.collectionId);
+    const contract = helper.ethNativeContract.collection(address, 'rft');
+
+    const rftToken = helper.ethNativeContract.rftTokenById(token.collectionId, token.tokenId, owner);
+
+    {
+      await rftToken.methods.approve(operator, 15n).send({from: owner});
+      await contract.methods.setApprovalForAll(operator, true).send({from: owner});
+      await rftToken.methods.burnFrom(owner, 10n).send({from: operator});
+      const allowance = await rftToken.methods.allowance(owner, operator).call();
+      expect(allowance).to.be.equal('5');
+    }
+  });
+  
+  itEth('Can perform transfer with ApprovalForAll', async ({helper}) => {
+    const collection = await helper.rft.mintCollection(minter, {name: 'A', description: 'B', tokenPrefix: 'C'});
+
+    const owner = await helper.eth.createAccountWithBalance(donor);
+    const operator = await helper.eth.createAccountWithBalance(donor);
+    const receiver = charlie;
+
+    const token = await collection.mintToken(minter, 100n, {Ethereum: owner});
+
+    const address = helper.ethAddress.fromCollectionId(collection.collectionId);
+    const contract = helper.ethNativeContract.collection(address, 'rft');
+
+    {
+      await contract.methods.setApprovalForAll(operator, true).send({from: owner});
+      const ownerCross = helper.ethCrossAccount.fromAddress(owner);
+      const recieverCross = helper.ethCrossAccount.fromKeyringPair(receiver);
+      const result = await contract.methods.transferFromCross(ownerCross, recieverCross, token.tokenId).send({from: operator});
+      const event = result.events.Transfer;
+      expect(event).to.be.like({
+        address: helper.ethAddress.fromCollectionId(collection.collectionId),
+        event: 'Transfer',
+        returnValues: {
+          from: owner,
+          to: helper.address.substrateToEth(receiver.address),
+          tokenId: token.tokenId.toString(),
+        },
+      });
+    }
+
+    expect(await token.getTop10Owners()).to.be.like([{Substrate: receiver.address}]);
+  });
+
   itEth('Can perform burn()', async ({helper}) => {
     const caller = await helper.eth.createAccountWithBalance(donor);
     const {collectionAddress} = await helper.eth.createRFTCollection(caller, 'Burny', '6', '6');
@@ -594,3 +724,52 @@
     expect(symbol).to.equal('12');
   });
 });
+
+describe('Negative tests', () => {
+  let donor: IKeyringPair;
+  let minter: IKeyringPair;
+  let alice: IKeyringPair;
+
+  before(async function() {
+    await usingEthPlaygrounds(async (helper, privateKey) => {
+      donor = await privateKey({filename: __filename});
+      [minter, alice] = await helper.arrange.createAccounts([100n, 100n], donor);
+    });
+  });
+
+  itEth('[negative] Cant perform burn without approval', async ({helper}) => {
+    const collection = await helper.rft.mintCollection(minter, {name: 'A', description: 'B', tokenPrefix: 'C'});
+
+    const owner = await helper.eth.createAccountWithBalance(donor, 100n);
+    const spender = await helper.eth.createAccountWithBalance(donor, 100n);
+
+    const token = await collection.mintToken(minter, 100n, {Ethereum: owner});
+
+    const address = helper.ethAddress.fromCollectionId(collection.collectionId);
+    const contract = helper.ethNativeContract.collection(address, 'rft');
+
+    {
+      const ownerCross = helper.ethCrossAccount.fromAddress(owner);
+      await expect(contract.methods.burnFromCross(ownerCross, token.tokenId).send({from: spender})).to.be.rejected;
+    }
+  });
+
+  itEth('[negative] Cant perform transfer without approval', async ({helper}) => {
+    const collection = await helper.rft.mintCollection(minter, {name: 'A', description: 'B', tokenPrefix: 'C'});
+    const owner = await helper.eth.createAccountWithBalance(donor, 100n);
+    const receiver = alice;
+
+    const spender = await helper.eth.createAccountWithBalance(donor, 100n);
+
+    const token = await collection.mintToken(minter, 100n, {Ethereum: owner});
+
+    const address = helper.ethAddress.fromCollectionId(collection.collectionId);
+    const contract = helper.ethNativeContract.collection(address, 'rft');
+
+    {
+      const ownerCross = helper.ethCrossAccount.fromAddress(owner);
+      const recieverCross = helper.ethCrossAccount.fromKeyringPair(receiver);
+      await expect(contract.methods.transferFromCross(ownerCross, recieverCross, token.tokenId).send({from: spender})).to.be.rejected;
+    }
+  });
+});
modifiedtests/src/interfaces/augment-api-errors.tsdiffbeforeafterboth
--- a/tests/src/interfaces/augment-api-errors.ts
+++ b/tests/src/interfaces/augment-api-errors.ts
@@ -386,6 +386,10 @@
        **/
       NotFungibleDataUsedToMintFungibleCollectionToken: AugmentedError<ApiType>;
       /**
+       * Setting approval for all is not allowed.
+       **/
+      SettingApprovalForAllNotAllowed: AugmentedError<ApiType>;
+      /**
        * Setting item properties is not allowed.
        **/
       SettingPropertiesNotAllowed: AugmentedError<ApiType>;
modifiedtests/src/interfaces/augment-api-events.tsdiffbeforeafterboth
--- a/tests/src/interfaces/augment-api-events.ts
+++ b/tests/src/interfaces/augment-api-events.ts
@@ -107,6 +107,10 @@
        **/
       Approved: AugmentedEvent<ApiType, [u32, u32, PalletEvmAccountBasicCrossAccountIdRepr, PalletEvmAccountBasicCrossAccountIdRepr, u128]>;
       /**
+       * Amount pieces of token owned by `sender` was approved for `spender`.
+       **/
+      ApprovedForAll: AugmentedEvent<ApiType, [u32, PalletEvmAccountBasicCrossAccountIdRepr, PalletEvmAccountBasicCrossAccountIdRepr, bool]>;
+      /**
        * New collection was created
        **/
       CollectionCreated: AugmentedEvent<ApiType, [u32, u8, AccountId32]>;
modifiedtests/src/interfaces/augment-api-query.tsdiffbeforeafterboth
--- a/tests/src/interfaces/augment-api-query.ts
+++ b/tests/src/interfaces/augment-api-query.ts
@@ -442,6 +442,10 @@
        **/
       tokensMinted: AugmentedQuery<ApiType, (arg: u32 | AnyNumber | Uint8Array) => Observable<u32>, [u32]> & QueryableStorageEntry<ApiType, [u32]>;
       /**
+       * Operator set by a wallet owner that could perform certain transactions on all tokens in the wallet.
+       **/
+      walletOperator: AugmentedQuery<ApiType, (arg1: u32 | AnyNumber | Uint8Array, arg2: PalletEvmAccountBasicCrossAccountIdRepr | { Substrate: any } | { Ethereum: any } | string | Uint8Array, arg3: PalletEvmAccountBasicCrossAccountIdRepr | { Substrate: any } | { Ethereum: any } | string | Uint8Array) => Observable<Option<bool>>, [u32, PalletEvmAccountBasicCrossAccountIdRepr, PalletEvmAccountBasicCrossAccountIdRepr]> & QueryableStorageEntry<ApiType, [u32, PalletEvmAccountBasicCrossAccountIdRepr, PalletEvmAccountBasicCrossAccountIdRepr]>;
+      /**
        * Generic query
        **/
       [key: string]: QueryableStorageEntry<ApiType>;
@@ -645,6 +649,10 @@
        **/
       totalSupply: AugmentedQuery<ApiType, (arg1: u32 | AnyNumber | Uint8Array, arg2: u32 | AnyNumber | Uint8Array) => Observable<u128>, [u32, u32]> & QueryableStorageEntry<ApiType, [u32, u32]>;
       /**
+       * Operator set by a wallet owner that could perform certain transactions on all tokens in the wallet.
+       **/
+      walletOperator: AugmentedQuery<ApiType, (arg1: u32 | AnyNumber | Uint8Array, arg2: PalletEvmAccountBasicCrossAccountIdRepr | { Substrate: any } | { Ethereum: any } | string | Uint8Array, arg3: PalletEvmAccountBasicCrossAccountIdRepr | { Substrate: any } | { Ethereum: any } | string | Uint8Array) => Observable<Option<bool>>, [u32, PalletEvmAccountBasicCrossAccountIdRepr, PalletEvmAccountBasicCrossAccountIdRepr]> & QueryableStorageEntry<ApiType, [u32, PalletEvmAccountBasicCrossAccountIdRepr, PalletEvmAccountBasicCrossAccountIdRepr]>;
+      /**
        * Generic query
        **/
       [key: string]: QueryableStorageEntry<ApiType>;
modifiedtests/src/interfaces/augment-api-rpc.tsdiffbeforeafterboth
--- a/tests/src/interfaces/augment-api-rpc.ts
+++ b/tests/src/interfaces/augment-api-rpc.ts
@@ -720,6 +720,10 @@
        **/
       effectiveCollectionLimits: AugmentedRpc<(collection: u32 | AnyNumber | Uint8Array, at?: Hash | string | Uint8Array) => Observable<Option<UpDataStructsCollectionLimits>>>;
       /**
+       * Tells whether an operator is approved by a given owner.
+       **/
+      isApprovedForAll: AugmentedRpc<(collection: u32 | AnyNumber | Uint8Array, owner: PalletEvmAccountBasicCrossAccountIdRepr | { Substrate: any } | { Ethereum: any } | string | Uint8Array, operator: PalletEvmAccountBasicCrossAccountIdRepr | { Substrate: any } | { Ethereum: any } | string | Uint8Array, at?: Hash | string | Uint8Array) => Observable<Option<bool>>>;
+      /**
        * Get the last token ID created in a collection
        **/
       lastTokenId: AugmentedRpc<(collection: u32 | AnyNumber | Uint8Array, at?: Hash | string | Uint8Array) => Observable<u32>>;
modifiedtests/src/interfaces/augment-api-tx.tsdiffbeforeafterboth
--- a/tests/src/interfaces/augment-api-tx.ts
+++ b/tests/src/interfaces/augment-api-tx.ts
@@ -1545,6 +1545,18 @@
        **/
       repartition: AugmentedSubmittable<(collectionId: u32 | AnyNumber | Uint8Array, tokenId: u32 | AnyNumber | Uint8Array, amount: u128 | AnyNumber | Uint8Array) => SubmittableExtrinsic<ApiType>, [u32, u32, u128]>;
       /**
+       * Sets or unsets the approval of a given operator.
+       * 
+       * An operator is allowed to transfer all tokens of the sender on their behalf.
+       * 
+       * # Arguments
+       * 
+       * * `owner`: Token owner
+       * * `operator`: Operator
+       * * `approve`: Is operator enabled or disabled
+       **/
+      setApprovalForAll: AugmentedSubmittable<(collectionId: u32 | AnyNumber | Uint8Array, operator: PalletEvmAccountBasicCrossAccountIdRepr | { Substrate: any } | { Ethereum: any } | string | Uint8Array, approve: bool | boolean | Uint8Array) => SubmittableExtrinsic<ApiType>, [u32, PalletEvmAccountBasicCrossAccountIdRepr, bool]>;
+      /**
        * Set specific limits of a collection. Empty, or None fields mean chain default.
        * 
        * # Permissions
modifiedtests/src/interfaces/default/types.tsdiffbeforeafterboth
--- a/tests/src/interfaces/default/types.ts
+++ b/tests/src/interfaces/default/types.ts
@@ -1286,6 +1286,8 @@
   readonly asTransfer: ITuple<[u32, u32, PalletEvmAccountBasicCrossAccountIdRepr, PalletEvmAccountBasicCrossAccountIdRepr, u128]>;
   readonly isApproved: boolean;
   readonly asApproved: ITuple<[u32, u32, PalletEvmAccountBasicCrossAccountIdRepr, PalletEvmAccountBasicCrossAccountIdRepr, u128]>;
+  readonly isApprovedForAll: boolean;
+  readonly asApprovedForAll: ITuple<[u32, PalletEvmAccountBasicCrossAccountIdRepr, PalletEvmAccountBasicCrossAccountIdRepr, bool]>;
   readonly isCollectionPropertySet: boolean;
   readonly asCollectionPropertySet: ITuple<[u32, Bytes]>;
   readonly isCollectionPropertyDeleted: boolean;
@@ -1296,7 +1298,7 @@
   readonly asTokenPropertyDeleted: ITuple<[u32, u32, Bytes]>;
   readonly isPropertyPermissionSet: boolean;
   readonly asPropertyPermissionSet: ITuple<[u32, Bytes]>;
-  readonly type: 'CollectionCreated' | 'CollectionDestroyed' | 'ItemCreated' | 'ItemDestroyed' | 'Transfer' | 'Approved' | 'CollectionPropertySet' | 'CollectionPropertyDeleted' | 'TokenPropertySet' | 'TokenPropertyDeleted' | 'PropertyPermissionSet';
+  readonly type: 'CollectionCreated' | 'CollectionDestroyed' | 'ItemCreated' | 'ItemDestroyed' | 'Transfer' | 'Approved' | 'ApprovedForAll' | 'CollectionPropertySet' | 'CollectionPropertyDeleted' | 'TokenPropertySet' | 'TokenPropertyDeleted' | 'PropertyPermissionSet';
 }
 
 /** @name PalletConfigurationCall */
@@ -1603,7 +1605,8 @@
   readonly isFungibleItemsDontHaveData: boolean;
   readonly isFungibleDisallowsNesting: boolean;
   readonly isSettingPropertiesNotAllowed: boolean;
-  readonly type: 'NotFungibleDataUsedToMintFungibleCollectionToken' | 'FungibleItemsHaveNoId' | 'FungibleItemsDontHaveData' | 'FungibleDisallowsNesting' | 'SettingPropertiesNotAllowed';
+  readonly isSettingApprovalForAllNotAllowed: boolean;
+  readonly type: 'NotFungibleDataUsedToMintFungibleCollectionToken' | 'FungibleItemsHaveNoId' | 'FungibleItemsDontHaveData' | 'FungibleDisallowsNesting' | 'SettingPropertiesNotAllowed' | 'SettingApprovalForAllNotAllowed';
 }
 
 /** @name PalletInflationCall */
@@ -2309,7 +2312,13 @@
     readonly tokenId: u32;
     readonly amount: u128;
   } & Struct;
-  readonly type: 'CreateCollection' | 'CreateCollectionEx' | 'DestroyCollection' | 'AddToAllowList' | 'RemoveFromAllowList' | 'ChangeCollectionOwner' | 'AddCollectionAdmin' | 'RemoveCollectionAdmin' | 'SetCollectionSponsor' | 'ConfirmSponsorship' | 'RemoveCollectionSponsor' | 'CreateItem' | 'CreateMultipleItems' | 'SetCollectionProperties' | 'DeleteCollectionProperties' | 'SetTokenProperties' | 'DeleteTokenProperties' | 'SetTokenPropertyPermissions' | 'CreateMultipleItemsEx' | 'SetTransfersEnabledFlag' | 'BurnItem' | 'BurnFrom' | 'Transfer' | 'Approve' | 'TransferFrom' | 'SetCollectionLimits' | 'SetCollectionPermissions' | 'Repartition';
+  readonly isSetApprovalForAll: boolean;
+  readonly asSetApprovalForAll: {
+    readonly collectionId: u32;
+    readonly operator: PalletEvmAccountBasicCrossAccountIdRepr;
+    readonly approve: bool;
+  } & Struct;
+  readonly type: 'CreateCollection' | 'CreateCollectionEx' | 'DestroyCollection' | 'AddToAllowList' | 'RemoveFromAllowList' | 'ChangeCollectionOwner' | 'AddCollectionAdmin' | 'RemoveCollectionAdmin' | 'SetCollectionSponsor' | 'ConfirmSponsorship' | 'RemoveCollectionSponsor' | 'CreateItem' | 'CreateMultipleItems' | 'SetCollectionProperties' | 'DeleteCollectionProperties' | 'SetTokenProperties' | 'DeleteTokenProperties' | 'SetTokenPropertyPermissions' | 'CreateMultipleItemsEx' | 'SetTransfersEnabledFlag' | 'BurnItem' | 'BurnFrom' | 'Transfer' | 'Approve' | 'TransferFrom' | 'SetCollectionLimits' | 'SetCollectionPermissions' | 'Repartition' | 'SetApprovalForAll';
 }
 
 /** @name PalletUniqueError */
modifiedtests/src/interfaces/lookup.tsdiffbeforeafterboth
--- a/tests/src/interfaces/lookup.ts
+++ b/tests/src/interfaces/lookup.ts
@@ -1046,6 +1046,7 @@
       ItemDestroyed: '(u32,u32,PalletEvmAccountBasicCrossAccountIdRepr,u128)',
       Transfer: '(u32,u32,PalletEvmAccountBasicCrossAccountIdRepr,PalletEvmAccountBasicCrossAccountIdRepr,u128)',
       Approved: '(u32,u32,PalletEvmAccountBasicCrossAccountIdRepr,PalletEvmAccountBasicCrossAccountIdRepr,u128)',
+      ApprovedForAll: '(u32,PalletEvmAccountBasicCrossAccountIdRepr,PalletEvmAccountBasicCrossAccountIdRepr,bool)',
       CollectionPropertySet: '(u32,Bytes)',
       CollectionPropertyDeleted: '(u32,Bytes)',
       TokenPropertySet: '(u32,u32,Bytes)',
@@ -1054,7 +1055,7 @@
     }
   },
   /**
-   * Lookup99: pallet_structure::pallet::Event<T>
+   * Lookup100: pallet_structure::pallet::Event<T>
    **/
   PalletStructureEvent: {
     _enum: {
@@ -1062,7 +1063,7 @@
     }
   },
   /**
-   * Lookup100: pallet_rmrk_core::pallet::Event<T>
+   * Lookup101: pallet_rmrk_core::pallet::Event<T>
    **/
   PalletRmrkCoreEvent: {
     _enum: {
@@ -1139,7 +1140,7 @@
     }
   },
   /**
-   * Lookup101: rmrk_traits::nft::AccountIdOrCollectionNftTuple<sp_core::crypto::AccountId32>
+   * Lookup102: rmrk_traits::nft::AccountIdOrCollectionNftTuple<sp_core::crypto::AccountId32>
    **/
   RmrkTraitsNftAccountIdOrCollectionNftTuple: {
     _enum: {
@@ -2302,7 +2303,12 @@
       repartition: {
         collectionId: 'u32',
         tokenId: 'u32',
-        amount: 'u128'
+        amount: 'u128',
+      },
+      set_approval_for_all: {
+        collectionId: 'u32',
+        operator: 'PalletEvmAccountBasicCrossAccountIdRepr',
+        approve: 'bool'
       }
     }
   },
@@ -3445,7 +3451,7 @@
    * Lookup430: pallet_fungible::pallet::Error<T>
    **/
   PalletFungibleError: {
-    _enum: ['NotFungibleDataUsedToMintFungibleCollectionToken', 'FungibleItemsHaveNoId', 'FungibleItemsDontHaveData', 'FungibleDisallowsNesting', 'SettingPropertiesNotAllowed']
+    _enum: ['NotFungibleDataUsedToMintFungibleCollectionToken', 'FungibleItemsHaveNoId', 'FungibleItemsDontHaveData', 'FungibleDisallowsNesting', 'SettingPropertiesNotAllowed', 'SettingApprovalForAllNotAllowed']
   },
   /**
    * Lookup431: pallet_refungible::ItemData
modifiedtests/src/interfaces/types-lookup.tsdiffbeforeafterboth
--- a/tests/src/interfaces/types-lookup.ts
+++ b/tests/src/interfaces/types-lookup.ts
@@ -1182,6 +1182,8 @@
     readonly asTransfer: ITuple<[u32, u32, PalletEvmAccountBasicCrossAccountIdRepr, PalletEvmAccountBasicCrossAccountIdRepr, u128]>;
     readonly isApproved: boolean;
     readonly asApproved: ITuple<[u32, u32, PalletEvmAccountBasicCrossAccountIdRepr, PalletEvmAccountBasicCrossAccountIdRepr, u128]>;
+    readonly isApprovedForAll: boolean;
+    readonly asApprovedForAll: ITuple<[u32, PalletEvmAccountBasicCrossAccountIdRepr, PalletEvmAccountBasicCrossAccountIdRepr, bool]>;
     readonly isCollectionPropertySet: boolean;
     readonly asCollectionPropertySet: ITuple<[u32, Bytes]>;
     readonly isCollectionPropertyDeleted: boolean;
@@ -1192,17 +1194,17 @@
     readonly asTokenPropertyDeleted: ITuple<[u32, u32, Bytes]>;
     readonly isPropertyPermissionSet: boolean;
     readonly asPropertyPermissionSet: ITuple<[u32, Bytes]>;
-    readonly type: 'CollectionCreated' | 'CollectionDestroyed' | 'ItemCreated' | 'ItemDestroyed' | 'Transfer' | 'Approved' | 'CollectionPropertySet' | 'CollectionPropertyDeleted' | 'TokenPropertySet' | 'TokenPropertyDeleted' | 'PropertyPermissionSet';
+    readonly type: 'CollectionCreated' | 'CollectionDestroyed' | 'ItemCreated' | 'ItemDestroyed' | 'Transfer' | 'Approved' | 'ApprovedForAll' | 'CollectionPropertySet' | 'CollectionPropertyDeleted' | 'TokenPropertySet' | 'TokenPropertyDeleted' | 'PropertyPermissionSet';
   }
 
-  /** @name PalletStructureEvent (99) */
+  /** @name PalletStructureEvent (100) */
   interface PalletStructureEvent extends Enum {
     readonly isExecuted: boolean;
     readonly asExecuted: Result<Null, SpRuntimeDispatchError>;
     readonly type: 'Executed';
   }
 
-  /** @name PalletRmrkCoreEvent (100) */
+  /** @name PalletRmrkCoreEvent (101) */
   interface PalletRmrkCoreEvent extends Enum {
     readonly isCollectionCreated: boolean;
     readonly asCollectionCreated: {
@@ -1292,7 +1294,7 @@
     readonly type: 'CollectionCreated' | 'CollectionDestroyed' | 'IssuerChanged' | 'CollectionLocked' | 'NftMinted' | 'NftBurned' | 'NftSent' | 'NftAccepted' | 'NftRejected' | 'PropertySet' | 'ResourceAdded' | 'ResourceRemoval' | 'ResourceAccepted' | 'ResourceRemovalAccepted' | 'PrioritySet';
   }
 
-  /** @name RmrkTraitsNftAccountIdOrCollectionNftTuple (101) */
+  /** @name RmrkTraitsNftAccountIdOrCollectionNftTuple (102) */
   interface RmrkTraitsNftAccountIdOrCollectionNftTuple extends Enum {
     readonly isAccountId: boolean;
     readonly asAccountId: AccountId32;
@@ -2539,7 +2541,13 @@
       readonly tokenId: u32;
       readonly amount: u128;
     } & Struct;
-    readonly type: 'CreateCollection' | 'CreateCollectionEx' | 'DestroyCollection' | 'AddToAllowList' | 'RemoveFromAllowList' | 'ChangeCollectionOwner' | 'AddCollectionAdmin' | 'RemoveCollectionAdmin' | 'SetCollectionSponsor' | 'ConfirmSponsorship' | 'RemoveCollectionSponsor' | 'CreateItem' | 'CreateMultipleItems' | 'SetCollectionProperties' | 'DeleteCollectionProperties' | 'SetTokenProperties' | 'DeleteTokenProperties' | 'SetTokenPropertyPermissions' | 'CreateMultipleItemsEx' | 'SetTransfersEnabledFlag' | 'BurnItem' | 'BurnFrom' | 'Transfer' | 'Approve' | 'TransferFrom' | 'SetCollectionLimits' | 'SetCollectionPermissions' | 'Repartition';
+    readonly isSetApprovalForAll: boolean;
+    readonly asSetApprovalForAll: {
+      readonly collectionId: u32;
+      readonly operator: PalletEvmAccountBasicCrossAccountIdRepr;
+      readonly approve: bool;
+    } & Struct;
+    readonly type: 'CreateCollection' | 'CreateCollectionEx' | 'DestroyCollection' | 'AddToAllowList' | 'RemoveFromAllowList' | 'ChangeCollectionOwner' | 'AddCollectionAdmin' | 'RemoveCollectionAdmin' | 'SetCollectionSponsor' | 'ConfirmSponsorship' | 'RemoveCollectionSponsor' | 'CreateItem' | 'CreateMultipleItems' | 'SetCollectionProperties' | 'DeleteCollectionProperties' | 'SetTokenProperties' | 'DeleteTokenProperties' | 'SetTokenPropertyPermissions' | 'CreateMultipleItemsEx' | 'SetTransfersEnabledFlag' | 'BurnItem' | 'BurnFrom' | 'Transfer' | 'Approve' | 'TransferFrom' | 'SetCollectionLimits' | 'SetCollectionPermissions' | 'Repartition' | 'SetApprovalForAll';
   }
 
   /** @name UpDataStructsCollectionMode (240) */
@@ -3655,7 +3663,8 @@
     readonly isFungibleItemsDontHaveData: boolean;
     readonly isFungibleDisallowsNesting: boolean;
     readonly isSettingPropertiesNotAllowed: boolean;
-    readonly type: 'NotFungibleDataUsedToMintFungibleCollectionToken' | 'FungibleItemsHaveNoId' | 'FungibleItemsDontHaveData' | 'FungibleDisallowsNesting' | 'SettingPropertiesNotAllowed';
+    readonly isSettingApprovalForAllNotAllowed: boolean;
+    readonly type: 'NotFungibleDataUsedToMintFungibleCollectionToken' | 'FungibleItemsHaveNoId' | 'FungibleItemsDontHaveData' | 'FungibleDisallowsNesting' | 'SettingPropertiesNotAllowed' | 'SettingApprovalForAllNotAllowed';
   }
 
   /** @name PalletRefungibleItemData (431) */
modifiedtests/src/interfaces/unique/definitions.tsdiffbeforeafterboth
--- a/tests/src/interfaces/unique/definitions.ts
+++ b/tests/src/interfaces/unique/definitions.ts
@@ -175,5 +175,10 @@
       [collectionParam, tokenParam], 
       'Option<u128>',
     ),
+    isApprovedForAll: fun(
+      'Tells whether an operator is approved by a given owner.', 
+      [collectionParam, crossAccountParam('owner'), crossAccountParam('operator')], 
+      'Option<bool>',
+    ),
   },
 };
modifiedtests/src/util/playgrounds/unique.tsdiffbeforeafterboth
--- a/tests/src/util/playgrounds/unique.ts
+++ b/tests/src/util/playgrounds/unique.ts
@@ -1413,6 +1413,32 @@
   getTokenObject(_collectionId: number, _tokenId: number): any {
     return null;
   }
+
+  /**
+   * Tells whether an operator is approved by a given owner.
+   * @param collectionId ID of collection
+   * @param owner owner address
+	 * @param operator operator addrees
+   * @returns true if operator is enabled
+   */
+  async isApprovedForAll(collectionId: number, owner: ICrossAccountId, operator: ICrossAccountId): Promise<boolean> {
+    return (await this.helper.callRpc('api.rpc.unique.isApprovedForAll', [collectionId, owner, operator])).toJSON();
+  }
+
+  /** Sets or unsets the approval of a given operator.
+	 *  An operator is allowed to transfer all tokens of the sender on their behalf.
+	 *  @param operator Operator
+	 *  @param approved Is operator enabled or disabled
+   *  @returns ```true``` if extrinsic success, otherwise ```false```
+   */
+  async setApprovalForAll(signer: TSigner, collectionId: number, operator: ICrossAccountId, approved: boolean): Promise<boolean> {
+    const result = await this.helper.executeExtrinsic(
+      signer,
+      'api.tx.unique.setApprovalForAll', [collectionId, operator, approved],
+      true,
+    );
+    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'ApprovedForAll');
+  }
 }