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

difftreelog

Merge remote-tracking branch 'origin/feature/fractionalizer-contract' into develop

Yaroslav Bolyukin2022-08-11parents: #bc60087 #0265731.patch.diff
in: master

50 files changed

modifiedpallets/common/src/erc.rsdiffbeforeafterboth
--- a/pallets/common/src/erc.rs
+++ b/pallets/common/src/erc.rs
@@ -25,7 +25,8 @@
 use pallet_evm_coder_substrate::dispatch_to_evm;
 use sp_std::vec::Vec;
 use up_data_structs::{
-	Property, SponsoringRateLimit, OwnerRestrictedSet, AccessMode, CollectionPermissions,
+	AccessMode, CollectionMode, CollectionPermissions, OwnerRestrictedSet, Property,
+	SponsoringRateLimit,
 };
 use alloc::format;
 
@@ -408,6 +409,28 @@
 
 		save(self)
 	}
+
+	/// Check that account is the owner or admin of the collection
+	///
+	/// @param user account to verify
+	/// @return "true" if account is the owner or admin
+	fn verify_owner_or_admin(&self, user: address) -> Result<bool> {
+		Ok(check_is_owner_or_admin(user, self)
+			.map(|_| true)
+			.unwrap_or(false))
+	}
+
+	/// Returns collection type
+	///
+	/// @return `Fungible` or `NFT` or `ReFungible`
+	fn unique_collection_type(&mut self) -> Result<string> {
+		let mode = match self.collection.mode {
+			CollectionMode::Fungible(_) => "Fungible",
+			CollectionMode::NFT => "NFT",
+			CollectionMode::ReFungible => "ReFungible",
+		};
+		Ok(mode.into())
+	}
 }
 
 fn check_is_owner_or_admin<T: Config>(
@@ -462,6 +485,11 @@
 		pub fn suffix() -> up_data_structs::PropertyKey {
 			property_key_from_bytes(b"suffix").expect(EXPECT_CONVERT_ERROR)
 		}
+
+		/// Key "parentNft".
+		pub fn parent_nft() -> up_data_structs::PropertyKey {
+			property_key_from_bytes(b"parentNft").expect(EXPECT_CONVERT_ERROR)
+		}
 	}
 
 	/// Values.
modifiedpallets/common/src/lib.rsdiffbeforeafterboth
before · pallets/common/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//! # Common pallet18//!19//! The Common pallet provides functionality for handling collections.20//!21//! ## Overview22//!23//! The Common pallet provides an interface for common collection operations for different collection types24//! (see [CommonCollectionOperations]), as well as a generic dispatcher for these, see [dispatch] module.25//! It also provides this functionality to EVM, see [erc] and [eth] modules.26//!27//! The Common pallet provides functions for:28//!29//! - Setting and approving collection sponsor.30//! - Get\set\delete allow list.31//! - Get\set\delete collection properties.32//! - Get\set\delete collection property permissions.33//! - Get\set\delete token property permissions.34//! - Get\set\delete collection administrators.35//! - Checking access permissions.36//!37//! ### Terminology38//! **Collection sponsor** - For the collection, you can set a sponsor, at whose expense it will39//! be possible to mint tokens.40//!41//! **Allow list** - List of users who have the right to minting tokens.42//!43//! **Collection properties** - Collection properties are simply key-value stores where various44//! metadata can be placed.45//!46//! **Permissions on token properties** - For each property in the token can be set permission47//! to change, see [`PropertyPermission`].48//!49//! **Collection administrator** - For a collection, you can set administrators who have the right50//! to most actions on the collection.5152#![warn(missing_docs)]53#![cfg_attr(not(feature = "std"), no_std)]54extern crate alloc;5556use core::ops::{Deref, DerefMut};57use pallet_evm_coder_substrate::{SubstrateRecorder, WithRecorder};58use sp_std::vec::Vec;59use pallet_evm::{account::CrossAccountId, Pallet as PalletEvm};60use evm_coder::ToLog;61use frame_support::{62	dispatch::{DispatchErrorWithPostInfo, DispatchResultWithPostInfo, Weight, PostDispatchInfo},63	ensure,64	traits::{Imbalance, Get, Currency, WithdrawReasons, ExistenceRequirement},65	weights::Pays,66	transactional,67};68use pallet_evm::GasWeightMapping;69use up_data_structs::{70	COLLECTION_NUMBER_LIMIT,71	Collection,72	RpcCollection,73	CollectionId,74	CreateItemData,75	MAX_TOKEN_PREFIX_LENGTH,76	COLLECTION_ADMINS_LIMIT,77	TokenId,78	TokenChild,79	CollectionStats,80	MAX_TOKEN_OWNERSHIP,81	CollectionMode,82	NFT_SPONSOR_TRANSFER_TIMEOUT,83	FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,84	REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,85	MAX_SPONSOR_TIMEOUT,86	CUSTOM_DATA_LIMIT,87	CollectionLimits,88	CreateCollectionData,89	SponsorshipState,90	CreateItemExData,91	SponsoringRateLimit,92	budget::Budget,93	PhantomType,94	Property,95	Properties,96	PropertiesPermissionMap,97	PropertyKey,98	PropertyValue,99	PropertyPermission,100	PropertiesError,101	PropertyKeyPermission,102	TokenData,103	TrySetProperty,104	PropertyScope,105	// RMRK106	RmrkCollectionInfo,107	RmrkInstanceInfo,108	RmrkResourceInfo,109	RmrkPropertyInfo,110	RmrkBaseInfo,111	RmrkPartType,112	RmrkBoundedTheme,113	RmrkNftChild,114	CollectionPermissions,115	SchemaVersion,116};117118pub use pallet::*;119use sp_core::H160;120use sp_runtime::{ArithmeticError, DispatchError, DispatchResult};121#[cfg(feature = "runtime-benchmarks")]122pub mod benchmarking;123pub mod dispatch;124pub mod erc;125pub mod eth;126pub mod weights;127128/// Weight info.129pub type SelfWeightOf<T> = <T as Config>::WeightInfo;130131/// Collection handle contains information about collection data and id.132/// Also provides functionality to count consumed gas.133///134/// CollectionHandle is used as a generic wrapper for collections of all types.135/// It allows to perform common operations and queries on any collection type,136/// both completely general for all, as well as their respective implementations of [`CommonCollectionOperations`].137#[must_use = "Should call submit_logs or save, otherwise some data will be lost for evm side"]138pub struct CollectionHandle<T: Config> {139	/// Collection id140	pub id: CollectionId,141	collection: Collection<T::AccountId>,142	/// Substrate recorder for counting consumed gas143	pub recorder: SubstrateRecorder<T>,144}145146impl<T: Config> WithRecorder<T> for CollectionHandle<T> {147	fn recorder(&self) -> &SubstrateRecorder<T> {148		&self.recorder149	}150	fn into_recorder(self) -> SubstrateRecorder<T> {151		self.recorder152	}153}154155impl<T: Config> CollectionHandle<T> {156	/// Same as [CollectionHandle::new] but with an explicit gas limit.157	pub fn new_with_gas_limit(id: CollectionId, gas_limit: u64) -> Option<Self> {158		<CollectionById<T>>::get(id).map(|collection| Self {159			id,160			collection,161			recorder: SubstrateRecorder::new(gas_limit),162		})163	}164165	/// Same as [CollectionHandle::new] but with an existed [`SubstrateRecorder`].166	pub fn new_with_recorder(id: CollectionId, recorder: SubstrateRecorder<T>) -> Option<Self> {167		<CollectionById<T>>::get(id).map(|collection| Self {168			id,169			collection,170			recorder,171		})172	}173174	/// Retrives collection data from storage and creates collection handle with default parameters.175	/// If collection not found return `None`176	pub fn new(id: CollectionId) -> Option<Self> {177		Self::new_with_gas_limit(id, u64::MAX)178	}179180	/// Same as [`CollectionHandle::new`] but if collection not found [CollectionNotFound](Error::CollectionNotFound) returned.181	pub fn try_get(id: CollectionId) -> Result<Self, DispatchError> {182		Ok(Self::new(id).ok_or(<Error<T>>::CollectionNotFound)?)183	}184185	/// Consume gas for reading.186	pub fn consume_store_reads(&self, reads: u64) -> evm_coder::execution::Result<()> {187		self.recorder188			.consume_gas(T::GasWeightMapping::weight_to_gas(189				<T as frame_system::Config>::DbWeight::get()190					.read191					.saturating_mul(reads),192			))193	}194195	/// Consume gas for writing.196	pub fn consume_store_writes(&self, writes: u64) -> evm_coder::execution::Result<()> {197		self.recorder198			.consume_gas(T::GasWeightMapping::weight_to_gas(199				<T as frame_system::Config>::DbWeight::get()200					.write201					.saturating_mul(writes),202			))203	}204205	/// Save collection to storage.206	pub fn save(self) -> DispatchResult {207		<CollectionById<T>>::insert(self.id, self.collection);208		Ok(())209	}210211	/// Set collection sponsor.212	///213	/// Unique collections allows sponsoring for certain actions.214	/// This method allows you to set the sponsor of the collection.215	/// In order for sponsorship to become active, it must be confirmed through [`Self::confirm_sponsorship`].216	pub fn set_sponsor(&mut self, sponsor: T::AccountId) -> DispatchResult {217		self.collection.sponsorship = SponsorshipState::Unconfirmed(sponsor);218		Ok(())219	}220221	/// Confirm sponsorship222	///223	/// In order for the sponsorship to become active, the user set as the sponsor must confirm their participation.224	/// Before confirming sponsorship, the user must be specified as the sponsor of the collection via [`Self::set_sponsor`].225	pub fn confirm_sponsorship(&mut self, sender: &T::AccountId) -> Result<bool, DispatchError> {226		if self.collection.sponsorship.pending_sponsor() != Some(sender) {227			return Ok(false);228		}229230		self.collection.sponsorship = SponsorshipState::Confirmed(sender.clone());231		Ok(true)232	}233234	/// Checks that the collection was created with, and must be operated upon through **Unique API**.235	/// Now check only the `external_collection` flag and if it's **true**, then return [`Error::CollectionIsExternal`] error.236	pub fn check_is_internal(&self) -> DispatchResult {237		if self.external_collection {238			return Err(<Error<T>>::CollectionIsExternal)?;239		}240241		Ok(())242	}243244	/// Checks that the collection was created with, and must be operated upon through an **assimilated API**.245	/// Now check only the `external_collection` flag and if it's **false**, then return [`Error::CollectionIsInternal`] error.246	pub fn check_is_external(&self) -> DispatchResult {247		if !self.external_collection {248			return Err(<Error<T>>::CollectionIsInternal)?;249		}250251		Ok(())252	}253}254255impl<T: Config> Deref for CollectionHandle<T> {256	type Target = Collection<T::AccountId>;257258	fn deref(&self) -> &Self::Target {259		&self.collection260	}261}262263impl<T: Config> DerefMut for CollectionHandle<T> {264	fn deref_mut(&mut self) -> &mut Self::Target {265		&mut self.collection266	}267}268269impl<T: Config> CollectionHandle<T> {270	/// Checks if the `user` is the owner of the collection.271	pub fn check_is_owner(&self, user: &T::CrossAccountId) -> DispatchResult {272		ensure!(*user.as_sub() == self.owner, <Error<T>>::NoPermission);273		Ok(())274	}275276	/// Returns **true** if the `user` is the owner or administrator of the collection.277	pub fn is_owner_or_admin(&self, user: &T::CrossAccountId) -> bool {278		*user.as_sub() == self.owner || <IsAdmin<T>>::get((self.id, user))279	}280281	/// Checks if the `user` is the owner or administrator of the collection.282	pub fn check_is_owner_or_admin(&self, user: &T::CrossAccountId) -> DispatchResult {283		ensure!(self.is_owner_or_admin(user), <Error<T>>::NoPermission);284		Ok(())285	}286287	/// Return **true** if `user` was not allowed to have tokens, and he can ignore such restrictions.288	pub fn ignores_allowance(&self, user: &T::CrossAccountId) -> bool {289		self.limits.owner_can_transfer() && self.is_owner_or_admin(user)290	}291292	/// Return **true** if `user` does not have enough token parts, and he can ignore such restrictions.293	pub fn ignores_owned_amount(&self, user: &T::CrossAccountId) -> bool {294		self.limits.owner_can_transfer() && self.is_owner_or_admin(user)295	}296297	/// Checks if the user is in the allow list. If not [Error::AddressNotInAllowlist] returns.298	pub fn check_allowlist(&self, user: &T::CrossAccountId) -> DispatchResult {299		ensure!(300			<Allowlist<T>>::get((self.id, user)),301			<Error<T>>::AddressNotInAllowlist302		);303		Ok(())304	}305}306307#[frame_support::pallet]308pub mod pallet {309	use super::*;310	use pallet_evm::account;311	use dispatch::CollectionDispatch;312	use frame_support::{Blake2_128Concat, pallet_prelude::*, storage::Key, traits::StorageVersion};313	use frame_system::pallet_prelude::*;314	use frame_support::traits::Currency;315	use up_data_structs::{TokenId, mapping::TokenAddressMapping};316	use scale_info::TypeInfo;317	use weights::WeightInfo;318319	#[pallet::config]320	pub trait Config:321		frame_system::Config322		+ pallet_evm_coder_substrate::Config323		+ pallet_evm::Config324		+ TypeInfo325		+ account::Config326	{327		/// Weight information for functions of this pallet.328		type WeightInfo: WeightInfo;329330		/// Events compatible with [`frame_system::Config::Event`].331		type Event: IsType<<Self as frame_system::Config>::Event> + From<Event<Self>>;332333		/// Handler of accounts and payment.334		type Currency: Currency<Self::AccountId>;335336		/// Set price to create a collection.337		#[pallet::constant]338		type CollectionCreationPrice: Get<339			<<Self as Config>::Currency as Currency<Self::AccountId>>::Balance,340		>;341342		/// Dispatcher of operations on collections.343		type CollectionDispatch: CollectionDispatch<Self>;344345		/// Account which holds the chain's treasury.346		type TreasuryAccountId: Get<Self::AccountId>;347348		/// Address under which the CollectionHelper contract would be available.349		type ContractAddress: Get<H160>;350351		/// Mapper for token addresses to Ethereum addresses.352		type EvmTokenAddressMapping: TokenAddressMapping<H160>;353354		/// Mapper for token addresses to [`CrossAccountId`].355		type CrossTokenAddressMapping: TokenAddressMapping<Self::CrossAccountId>;356	}357358	const STORAGE_VERSION: StorageVersion = StorageVersion::new(1);359360	#[pallet::pallet]361	#[pallet::storage_version(STORAGE_VERSION)]362	#[pallet::generate_store(pub(super) trait Store)]363	pub struct Pallet<T>(_);364365	#[pallet::extra_constants]366	impl<T: Config> Pallet<T> {367		/// Maximum admins per collection.368		pub fn collection_admins_limit() -> u32 {369			COLLECTION_ADMINS_LIMIT370		}371	}372373	#[pallet::event]374	#[pallet::generate_deposit(pub fn deposit_event)]375	pub enum Event<T: Config> {376		/// New collection was created377		CollectionCreated(378			/// Globally unique identifier of newly created collection.379			CollectionId,380			/// [`CollectionMode`] converted into _u8_.381			u8,382			/// Collection owner.383			T::AccountId,384		),385386		/// New collection was destroyed387		CollectionDestroyed(388			/// Globally unique identifier of collection.389			CollectionId,390		),391392		/// New item was created.393		ItemCreated(394			/// Id of the collection where item was created.395			CollectionId,396			/// Id of an item. Unique within the collection.397			TokenId,398			/// Owner of newly created item399			T::CrossAccountId,400			/// Always 1 for NFT401			u128,402		),403404		/// Collection item was burned.405		ItemDestroyed(406			/// Id of the collection where item was destroyed.407			CollectionId,408			/// Identifier of burned NFT.409			TokenId,410			/// Which user has destroyed its tokens.411			T::CrossAccountId,412			/// Amount of token pieces destroed. Always 1 for NFT.413			u128,414		),415416		/// Item was transferred417		Transfer(418			/// Id of collection to which item is belong.419			CollectionId,420			/// Id of an item.421			TokenId,422			/// Original owner of item.423			T::CrossAccountId,424			/// New owner of item.425			T::CrossAccountId,426			/// Amount of token pieces transfered. Always 1 for NFT.427			u128,428		),429430		/// Amount pieces of token owned by `sender` was approved for `spender`.431		Approved(432			/// Id of collection to which item is belong.433			CollectionId,434			/// Id of an item.435			TokenId,436			/// Original owner of item.437			T::CrossAccountId,438			/// Id for which the approval was granted.439			T::CrossAccountId,440			/// Amount of token pieces transfered. Always 1 for NFT.441			u128,442		),443444		/// The colletion property has been added or edited.445		CollectionPropertySet(446			/// Id of collection to which property has been set.447			CollectionId,448			/// The property that was set.449			PropertyKey,450		),451452		/// The property has been deleted.453		CollectionPropertyDeleted(454			/// Id of collection to which property has been deleted.455			CollectionId,456			/// The property that was deleted.457			PropertyKey,458		),459460		/// The token property has been added or edited.461		TokenPropertySet(462			/// Identifier of the collection whose token has the property set.463			CollectionId,464			/// The token for which the property was set.465			TokenId,466			/// The property that was set.467			PropertyKey,468		),469470		/// The token property has been deleted.471		TokenPropertyDeleted(472			/// Identifier of the collection whose token has the property deleted.473			CollectionId,474			/// The token for which the property was deleted.475			TokenId,476			/// The property that was deleted.477			PropertyKey,478		),479480		/// The token property permission of a collection has been set.481		PropertyPermissionSet(482			/// ID of collection to which property permission has been set.483			CollectionId,484			/// The property permission that was set.485			PropertyKey,486		),487	}488489	#[pallet::error]490	pub enum Error<T> {491		/// This collection does not exist.492		CollectionNotFound,493		/// Sender parameter and item owner must be equal.494		MustBeTokenOwner,495		/// No permission to perform action496		NoPermission,497		/// Destroying only empty collections is allowed498		CantDestroyNotEmptyCollection,499		/// Collection is not in mint mode.500		PublicMintingNotAllowed,501		/// Address is not in allow list.502		AddressNotInAllowlist,503504		/// Collection name can not be longer than 63 char.505		CollectionNameLimitExceeded,506		/// Collection description can not be longer than 255 char.507		CollectionDescriptionLimitExceeded,508		/// Token prefix can not be longer than 15 char.509		CollectionTokenPrefixLimitExceeded,510		/// Total collections bound exceeded.511		TotalCollectionsLimitExceeded,512		/// Exceeded max admin count513		CollectionAdminCountExceeded,514		/// Collection limit bounds per collection exceeded515		CollectionLimitBoundsExceeded,516		/// Tried to enable permissions which are only permitted to be disabled517		OwnerPermissionsCantBeReverted,518		/// Collection settings not allowing items transferring519		TransferNotAllowed,520		/// Account token limit exceeded per collection521		AccountTokenLimitExceeded,522		/// Collection token limit exceeded523		CollectionTokenLimitExceeded,524		/// Metadata flag frozen525		MetadataFlagFrozen,526527		/// Item does not exist528		TokenNotFound,529		/// Item is balance not enough530		TokenValueTooLow,531		/// Requested value is more than the approved532		ApprovedValueTooLow,533		/// Tried to approve more than owned534		CantApproveMoreThanOwned,535536		/// Can't transfer tokens to ethereum zero address537		AddressIsZero,538539		/// The oprtation is not supported540		UnsupportedOperation,541542		/// Insufficient funds to perform an action543		NotSufficientFounds,544545		/// User does not satisfy the nesting rule546		UserIsNotAllowedToNest,547		/// Only tokens from specific collections may nest tokens under this one548		SourceCollectionIsNotAllowedToNest,549550		/// Tried to store more data than allowed in collection field551		CollectionFieldSizeExceeded,552553		/// Tried to store more property data than allowed554		NoSpaceForProperty,555556		/// Tried to store more property keys than allowed557		PropertyLimitReached,558559		/// Property key is too long560		PropertyKeyIsTooLong,561562		/// Only ASCII letters, digits, and symbols `_`, `-`, and `.` are allowed563		InvalidCharacterInPropertyKey,564565		/// Empty property keys are forbidden566		EmptyPropertyKey,567568		/// Tried to access an external collection with an internal API569		CollectionIsExternal,570571		/// Tried to access an internal collection with an external API572		CollectionIsInternal,573	}574575	/// Storage of the count of created collections. Essentially contains the last collection ID.576	#[pallet::storage]577	pub type CreatedCollectionCount<T> = StorageValue<Value = CollectionId, QueryKind = ValueQuery>;578579	/// Storage of the count of deleted collections.580	#[pallet::storage]581	pub type DestroyedCollectionCount<T> =582		StorageValue<Value = CollectionId, QueryKind = ValueQuery>;583584	/// Storage of collection info.585	#[pallet::storage]586	pub type CollectionById<T> = StorageMap<587		Hasher = Blake2_128Concat,588		Key = CollectionId,589		Value = Collection<<T as frame_system::Config>::AccountId>,590		QueryKind = OptionQuery,591	>;592593	/// Storage of collection properties.594	#[pallet::storage]595	#[pallet::getter(fn collection_properties)]596	pub type CollectionProperties<T> = StorageMap<597		Hasher = Blake2_128Concat,598		Key = CollectionId,599		Value = Properties,600		QueryKind = ValueQuery,601		OnEmpty = up_data_structs::CollectionProperties,602	>;603604	/// Storage of token property permissions of a collection.605	#[pallet::storage]606	#[pallet::getter(fn property_permissions)]607	pub type CollectionPropertyPermissions<T> = StorageMap<608		Hasher = Blake2_128Concat,609		Key = CollectionId,610		Value = PropertiesPermissionMap,611		QueryKind = ValueQuery,612	>;613614	/// Storage of the amount of collection admins.615	#[pallet::storage]616	pub type AdminAmount<T> = StorageMap<617		Hasher = Blake2_128Concat,618		Key = CollectionId,619		Value = u32,620		QueryKind = ValueQuery,621	>;622623	/// List of collection admins.624	#[pallet::storage]625	pub type IsAdmin<T: Config> = StorageNMap<626		Key = (627			Key<Blake2_128Concat, CollectionId>,628			Key<Blake2_128Concat, T::CrossAccountId>,629		),630		Value = bool,631		QueryKind = ValueQuery,632	>;633634	/// Allowlisted collection users.635	#[pallet::storage]636	pub type Allowlist<T: Config> = StorageNMap<637		Key = (638			Key<Blake2_128Concat, CollectionId>,639			Key<Blake2_128Concat, T::CrossAccountId>,640		),641		Value = bool,642		QueryKind = ValueQuery,643	>;644645	/// Not used by code, exists only to provide some types to metadata.646	#[pallet::storage]647	pub type DummyStorageValue<T: Config> = StorageValue<648		Value = (649			CollectionStats,650			CollectionId,651			TokenId,652			TokenChild,653			PhantomType<(654				TokenData<T::CrossAccountId>,655				RpcCollection<T::AccountId>,656				// RMRK657				RmrkCollectionInfo<T::AccountId>,658				RmrkInstanceInfo<T::AccountId>,659				RmrkResourceInfo,660				RmrkPropertyInfo,661				RmrkBaseInfo<T::AccountId>,662				RmrkPartType,663				RmrkBoundedTheme,664				RmrkNftChild,665			)>,666		),667		QueryKind = OptionQuery,668	>;669670	#[pallet::hooks]671	impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {672		fn on_runtime_upgrade() -> Weight {673			StorageVersion::new(1).put::<Pallet<T>>();674675			0676		}677	}678}679680impl<T: Config> Pallet<T> {681	/// Enshure that receiver address is correct.682	///683	/// Ethereum receiver 0x0000000000000000000000000000000000000000 is reserved, and shouldn't own tokens.684	pub fn ensure_correct_receiver(receiver: &T::CrossAccountId) -> DispatchResult {685		ensure!(686			&T::CrossAccountId::from_eth(H160([0; 20])) != receiver,687			<Error<T>>::AddressIsZero688		);689		Ok(())690	}691692	/// Get a vector of collection admins.693	pub fn adminlist(collection: CollectionId) -> Vec<T::CrossAccountId> {694		<IsAdmin<T>>::iter_prefix((collection,))695			.map(|(a, _)| a)696			.collect()697	}698699	/// Get a vector of users allowed to mint tokens.700	pub fn allowlist(collection: CollectionId) -> Vec<T::CrossAccountId> {701		<Allowlist<T>>::iter_prefix((collection,))702			.map(|(a, _)| a)703			.collect()704	}705706	/// Is `user` allowed to mint token in `collection`.707	pub fn allowed(collection: CollectionId, user: T::CrossAccountId) -> bool {708		<Allowlist<T>>::get((collection, user))709	}710711	/// Get statistics of collections.712	pub fn collection_stats() -> CollectionStats {713		let created = <CreatedCollectionCount<T>>::get();714		let destroyed = <DestroyedCollectionCount<T>>::get();715		CollectionStats {716			created: created.0,717			destroyed: destroyed.0,718			alive: created.0 - destroyed.0,719		}720	}721722	/// Get the effective limits for the collection.723	pub fn effective_collection_limits(collection: CollectionId) -> Option<CollectionLimits> {724		let collection = <CollectionById<T>>::get(collection);725		if collection.is_none() {726			return None;727		}728729		let collection = collection.unwrap();730		let limits = collection.limits;731		let effective_limits = CollectionLimits {732			account_token_ownership_limit: Some(limits.account_token_ownership_limit()),733			sponsored_data_size: Some(limits.sponsored_data_size()),734			sponsored_data_rate_limit: Some(735				limits736					.sponsored_data_rate_limit737					.unwrap_or(SponsoringRateLimit::SponsoringDisabled),738			),739			token_limit: Some(limits.token_limit()),740			sponsor_transfer_timeout: Some(limits.sponsor_transfer_timeout(741				match collection.mode {742					CollectionMode::NFT => NFT_SPONSOR_TRANSFER_TIMEOUT,743					CollectionMode::Fungible(_) => FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,744					CollectionMode::ReFungible => REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,745				},746			)),747			sponsor_approve_timeout: Some(limits.sponsor_approve_timeout()),748			owner_can_transfer: Some(limits.owner_can_transfer()),749			owner_can_destroy: Some(limits.owner_can_destroy()),750			transfers_enabled: Some(limits.transfers_enabled()),751		};752753		Some(effective_limits)754	}755756	/// Returns information about the `collection` adapted for rpc.757	pub fn rpc_collection(collection: CollectionId) -> Option<RpcCollection<T::AccountId>> {758		let Collection {759			name,760			description,761			owner,762			mode,763			token_prefix,764			sponsorship,765			limits,766			permissions,767			external_collection,768		} = <CollectionById<T>>::get(collection)?;769770		let token_property_permissions = <CollectionPropertyPermissions<T>>::get(collection)771			.into_iter()772			.map(|(key, permission)| PropertyKeyPermission { key, permission })773			.collect();774775		let properties = <CollectionProperties<T>>::get(collection)776			.into_iter()777			.map(|(key, value)| Property { key, value })778			.collect();779780		let permissions = CollectionPermissions {781			access: Some(permissions.access()),782			mint_mode: Some(permissions.mint_mode()),783			nesting: Some(permissions.nesting().clone()),784		};785786		Some(RpcCollection {787			name: name.into_inner(),788			description: description.into_inner(),789			owner,790			mode,791			token_prefix: token_prefix.into_inner(),792			sponsorship,793			limits,794			permissions,795			token_property_permissions,796			properties,797			read_only: external_collection,798		})799	}800}801802macro_rules! limit_default {803	($old:ident, $new:ident, $($field:ident $(($arg:expr))? => $check:expr),* $(,)?) => {{804		$(805			if let Some($new) = $new.$field {806				let $old = $old.$field($($arg)?);807				let _ = $new;808				let _ = $old;809				$check810			} else {811				$new.$field = $old.$field812			}813		)*814	}};815}816macro_rules! limit_default_clone {817	($old:ident, $new:ident, $($field:ident $(($arg:expr))? => $check:expr),* $(,)?) => {{818		$(819			if let Some($new) = $new.$field.clone() {820				let $old = $old.$field($($arg)?);821				let _ = $new;822				let _ = $old;823				$check824			} else {825				$new.$field = $old.$field.clone()826			}827		)*828	}};829}830831impl<T: Config> Pallet<T> {832	/// Create new collection.833	///834	/// * `owner` - The owner of the collection.835	/// * `data` - Description of the created collection.836	/// * `is_external` - Marks that collection managet by not "Unique network".837	pub fn init_collection(838		owner: T::CrossAccountId,839		data: CreateCollectionData<T::AccountId>,840		is_external: bool,841	) -> Result<CollectionId, DispatchError> {842		{843			ensure!(844				data.token_prefix.len() <= MAX_TOKEN_PREFIX_LENGTH as usize,845				Error::<T>::CollectionTokenPrefixLimitExceeded846			);847		}848849		let created_count = <CreatedCollectionCount<T>>::get()850			.0851			.checked_add(1)852			.ok_or(ArithmeticError::Overflow)?;853		let destroyed_count = <DestroyedCollectionCount<T>>::get().0;854		let id = CollectionId(created_count);855856		// bound Total number of collections857		ensure!(858			created_count - destroyed_count <= COLLECTION_NUMBER_LIMIT,859			<Error<T>>::TotalCollectionsLimitExceeded860		);861862		// =========863864		let collection = Collection {865			owner: owner.as_sub().clone(),866			name: data.name,867			mode: data.mode.clone(),868			description: data.description,869			token_prefix: data.token_prefix,870			sponsorship: data871				.pending_sponsor872				.map(SponsorshipState::Unconfirmed)873				.unwrap_or_default(),874			limits: data875				.limits876				.map(|limits| Self::clamp_limits(data.mode.clone(), &Default::default(), limits))877				.unwrap_or_else(|| Ok(CollectionLimits::default()))?,878			permissions: data879				.permissions880				.map(|permissions| {881					Self::clamp_permissions(data.mode.clone(), &Default::default(), permissions)882				})883				.unwrap_or_else(|| Ok(CollectionPermissions::default()))?,884			external_collection: is_external,885		};886887		let mut collection_properties = up_data_structs::CollectionProperties::get();888		collection_properties889			.try_set_from_iter(data.properties.into_iter())890			.map_err(<Error<T>>::from)?;891892		CollectionProperties::<T>::insert(id, collection_properties);893894		let mut token_props_permissions = PropertiesPermissionMap::new();895		token_props_permissions896			.try_set_from_iter(data.token_property_permissions.into_iter())897			.map_err(<Error<T>>::from)?;898899		CollectionPropertyPermissions::<T>::insert(id, token_props_permissions);900901		// Take a (non-refundable) deposit of collection creation902		{903			let mut imbalance =904				<<<T as Config>::Currency as Currency<T::AccountId>>::PositiveImbalance>::zero();905			imbalance.subsume(906				<<T as Config>::Currency as Currency<T::AccountId>>::deposit_creating(907					&T::TreasuryAccountId::get(),908					T::CollectionCreationPrice::get(),909				),910			);911			<T as Config>::Currency::settle(912				owner.as_sub(),913				imbalance,914				WithdrawReasons::TRANSFER,915				ExistenceRequirement::KeepAlive,916			)917			.map_err(|_| Error::<T>::NotSufficientFounds)?;918		}919920		<CreatedCollectionCount<T>>::put(created_count);921		<Pallet<T>>::deposit_event(Event::CollectionCreated(922			id,923			data.mode.id(),924			owner.as_sub().clone(),925		));926		<PalletEvm<T>>::deposit_log(927			erc::CollectionHelpersEvents::CollectionCreated {928				owner: *owner.as_eth(),929				collection_id: eth::collection_id_to_address(id),930			}931			.to_log(T::ContractAddress::get()),932		);933		<CollectionById<T>>::insert(id, collection);934		Ok(id)935	}936937	/// Destroy collection.938	///939	/// * `collection` - Collection handler.940	/// * `sender` - The owner or administrator of the collection.941	pub fn destroy_collection(942		collection: CollectionHandle<T>,943		sender: &T::CrossAccountId,944	) -> DispatchResult {945		ensure!(946			collection.limits.owner_can_destroy(),947			<Error<T>>::NoPermission,948		);949		collection.check_is_owner(sender)?;950951		let destroyed_collections = <DestroyedCollectionCount<T>>::get()952			.0953			.checked_add(1)954			.ok_or(ArithmeticError::Overflow)?;955956		// =========957958		<DestroyedCollectionCount<T>>::put(destroyed_collections);959		<CollectionById<T>>::remove(collection.id);960		<AdminAmount<T>>::remove(collection.id);961		<IsAdmin<T>>::remove_prefix((collection.id,), None);962		<Allowlist<T>>::remove_prefix((collection.id,), None);963		<CollectionProperties<T>>::remove(collection.id);964965		<Pallet<T>>::deposit_event(Event::CollectionDestroyed(collection.id));966		Ok(())967	}968969	/// Set collection property.970	///971	/// * `collection` - Collection handler.972	/// * `sender` - The owner or administrator of the collection.973	/// * `property` - The property to set.974	pub fn set_collection_property(975		collection: &CollectionHandle<T>,976		sender: &T::CrossAccountId,977		property: Property,978	) -> DispatchResult {979		collection.check_is_owner_or_admin(sender)?;980981		CollectionProperties::<T>::try_mutate(collection.id, |properties| {982			let property = property.clone();983			properties.try_set(property.key, property.value)984		})985		.map_err(<Error<T>>::from)?;986987		Self::deposit_event(Event::CollectionPropertySet(collection.id, property.key));988989		Ok(())990	}991992	/// Set scouped collection property.993	///994	/// * `collection_id` - ID of the collection for which the property is being set.995	/// * `scope` - Property scope.996	/// * `property` - The property to set.997	pub fn set_scoped_collection_property(998		collection_id: CollectionId,999		scope: PropertyScope,1000		property: Property,1001	) -> DispatchResult {1002		CollectionProperties::<T>::try_mutate(collection_id, |properties| {1003			properties.try_scoped_set(scope, property.key, property.value)1004		})1005		.map_err(<Error<T>>::from)?;10061007		Ok(())1008	}10091010	/// Set scouped collection properties.1011	///1012	/// * `collection_id` - ID of the collection for which the properties is being set.1013	/// * `scope` - Property scope.1014	/// * `properties` - The properties to set.1015	pub fn set_scoped_collection_properties(1016		collection_id: CollectionId,1017		scope: PropertyScope,1018		properties: impl Iterator<Item = Property>,1019	) -> DispatchResult {1020		CollectionProperties::<T>::try_mutate(collection_id, |stored_properties| {1021			stored_properties.try_scoped_set_from_iter(scope, properties)1022		})1023		.map_err(<Error<T>>::from)?;10241025		Ok(())1026	}10271028	/// Set collection properties.1029	///1030	/// * `collection` - Collection handler.1031	/// * `sender` - The owner or administrator of the collection.1032	/// * `properties` - The properties to set.1033	#[transactional]1034	pub fn set_collection_properties(1035		collection: &CollectionHandle<T>,1036		sender: &T::CrossAccountId,1037		properties: Vec<Property>,1038	) -> DispatchResult {1039		for property in properties {1040			Self::set_collection_property(collection, sender, property)?;1041		}10421043		Ok(())1044	}10451046	/// Delete collection property.1047	///1048	/// * `collection` - Collection handler.1049	/// * `sender` - The owner or administrator of the collection.1050	/// * `property` - The property to delete.1051	pub fn delete_collection_property(1052		collection: &CollectionHandle<T>,1053		sender: &T::CrossAccountId,1054		property_key: PropertyKey,1055	) -> DispatchResult {1056		collection.check_is_owner_or_admin(sender)?;10571058		CollectionProperties::<T>::try_mutate(collection.id, |properties| {1059			properties.remove(&property_key)1060		})1061		.map_err(<Error<T>>::from)?;10621063		Self::deposit_event(Event::CollectionPropertyDeleted(1064			collection.id,1065			property_key,1066		));10671068		Ok(())1069	}10701071	/// Delete collection properties.1072	///1073	/// * `collection` - Collection handler.1074	/// * `sender` - The owner or administrator of the collection.1075	/// * `properties` - The properties to delete.1076	#[transactional]1077	pub fn delete_collection_properties(1078		collection: &CollectionHandle<T>,1079		sender: &T::CrossAccountId,1080		property_keys: Vec<PropertyKey>,1081	) -> DispatchResult {1082		for key in property_keys {1083			Self::delete_collection_property(collection, sender, key)?;1084		}10851086		Ok(())1087	}10881089	/// Set collection propetry permission without any checks.1090	///1091	/// Used for migrations.1092	///1093	/// * `collection` - Collection handler.1094	/// * `property_permissions` - Property permissions.1095	pub fn set_property_permission_unchecked(1096		collection: CollectionId,1097		property_permission: PropertyKeyPermission,1098	) -> DispatchResult {1099		<CollectionPropertyPermissions<T>>::try_mutate(collection, |permissions| {1100			permissions.try_set(property_permission.key, property_permission.permission)1101		})1102		.map_err(<Error<T>>::from)?;1103		Ok(())1104	}11051106	/// Set collection property permission.1107	///1108	/// * `collection` - Collection handler.1109	/// * `sender` - The owner or administrator of the collection.1110	/// * `property_permission` - Property permission.1111	pub fn set_property_permission(1112		collection: &CollectionHandle<T>,1113		sender: &T::CrossAccountId,1114		property_permission: PropertyKeyPermission,1115	) -> DispatchResult {1116		collection.check_is_owner_or_admin(sender)?;11171118		let all_permissions = CollectionPropertyPermissions::<T>::get(collection.id);1119		let current_permission = all_permissions.get(&property_permission.key);1120		if matches![1121			current_permission,1122			Some(PropertyPermission { mutable: false, .. })1123		] {1124			return Err(<Error<T>>::NoPermission.into());1125		}11261127		CollectionPropertyPermissions::<T>::try_mutate(collection.id, |permissions| {1128			let property_permission = property_permission.clone();1129			permissions.try_set(property_permission.key, property_permission.permission)1130		})1131		.map_err(<Error<T>>::from)?;11321133		Self::deposit_event(Event::PropertyPermissionSet(1134			collection.id,1135			property_permission.key,1136		));11371138		Ok(())1139	}11401141	/// Set token property permission.1142	///1143	/// * `collection` - Collection handler.1144	/// * `sender` - The owner or administrator of the collection.1145	/// * `property_permissions` - Property permissions.1146	#[transactional]1147	pub fn set_token_property_permissions(1148		collection: &CollectionHandle<T>,1149		sender: &T::CrossAccountId,1150		property_permissions: Vec<PropertyKeyPermission>,1151	) -> DispatchResult {1152		for prop_pemission in property_permissions {1153			Self::set_property_permission(collection, sender, prop_pemission)?;1154		}11551156		Ok(())1157	}11581159	/// Get collection property.1160	pub fn get_collection_property(1161		collection_id: CollectionId,1162		key: &PropertyKey,1163	) -> Option<PropertyValue> {1164		Self::collection_properties(collection_id).get(key).cloned()1165	}11661167	/// Convert byte vector to property key vector.1168	pub fn bytes_keys_to_property_keys(1169		keys: Vec<Vec<u8>>,1170	) -> Result<Vec<PropertyKey>, DispatchError> {1171		keys.into_iter()1172			.map(|key| -> Result<PropertyKey, DispatchError> {1173				key.try_into()1174					.map_err(|_| <Error<T>>::PropertyKeyIsTooLong.into())1175			})1176			.collect::<Result<Vec<PropertyKey>, DispatchError>>()1177	}11781179	/// Get properties according to given keys.1180	pub fn filter_collection_properties(1181		collection_id: CollectionId,1182		keys: Option<Vec<PropertyKey>>,1183	) -> Result<Vec<Property>, DispatchError> {1184		let properties = Self::collection_properties(collection_id);11851186		let properties = keys1187			.map(|keys| {1188				keys.into_iter()1189					.filter_map(|key| {1190						properties.get(&key).map(|value| Property {1191							key,1192							value: value.clone(),1193						})1194					})1195					.collect()1196			})1197			.unwrap_or_else(|| {1198				properties1199					.into_iter()1200					.map(|(key, value)| Property { key, value })1201					.collect()1202			});12031204		Ok(properties)1205	}12061207	/// Get property permissions according to given keys.1208	pub fn filter_property_permissions(1209		collection_id: CollectionId,1210		keys: Option<Vec<PropertyKey>>,1211	) -> Result<Vec<PropertyKeyPermission>, DispatchError> {1212		let permissions = Self::property_permissions(collection_id);12131214		let key_permissions = keys1215			.map(|keys| {1216				keys.into_iter()1217					.filter_map(|key| {1218						permissions1219							.get(&key)1220							.map(|permission| PropertyKeyPermission {1221								key,1222								permission: permission.clone(),1223							})1224					})1225					.collect()1226			})1227			.unwrap_or_else(|| {1228				permissions1229					.into_iter()1230					.map(|(key, permission)| PropertyKeyPermission { key, permission })1231					.collect()1232			});12331234		Ok(key_permissions)1235	}12361237	/// Toggle `user` participation in the `collection`'s allow list.1238	pub fn toggle_allowlist(1239		collection: &CollectionHandle<T>,1240		sender: &T::CrossAccountId,1241		user: &T::CrossAccountId,1242		allowed: bool,1243	) -> DispatchResult {1244		collection.check_is_owner_or_admin(sender)?;12451246		// =========12471248		if allowed {1249			<Allowlist<T>>::insert((collection.id, user), true);1250		} else {1251			<Allowlist<T>>::remove((collection.id, user));1252		}12531254		Ok(())1255	}12561257	/// Toggle `user` participation in the `collection`'s admin list.1258	pub fn toggle_admin(1259		collection: &CollectionHandle<T>,1260		sender: &T::CrossAccountId,1261		user: &T::CrossAccountId,1262		admin: bool,1263	) -> DispatchResult {1264		collection.check_is_owner(sender)?;12651266		let was_admin = <IsAdmin<T>>::get((collection.id, user));1267		if was_admin == admin {1268			return Ok(());1269		}1270		let amount = <AdminAmount<T>>::get(collection.id);12711272		if admin {1273			let amount = amount1274				.checked_add(1)1275				.ok_or(<Error<T>>::CollectionAdminCountExceeded)?;1276			ensure!(1277				amount <= Self::collection_admins_limit(),1278				<Error<T>>::CollectionAdminCountExceeded,1279			);12801281			// =========12821283			<AdminAmount<T>>::insert(collection.id, amount);1284			<IsAdmin<T>>::insert((collection.id, user), true);1285		} else {1286			<AdminAmount<T>>::insert(collection.id, amount.saturating_sub(1));1287			<IsAdmin<T>>::remove((collection.id, user));1288		}12891290		Ok(())1291	}12921293	/// Merge set fields from `new_limit` to `old_limit`.1294	pub fn clamp_limits(1295		mode: CollectionMode,1296		old_limit: &CollectionLimits,1297		mut new_limit: CollectionLimits,1298	) -> Result<CollectionLimits, DispatchError> {1299		let limits = old_limit;1300		limit_default!(old_limit, new_limit,1301			account_token_ownership_limit => ensure!(1302				new_limit <= MAX_TOKEN_OWNERSHIP,1303				<Error<T>>::CollectionLimitBoundsExceeded,1304			),1305			sponsored_data_size => ensure!(1306				new_limit <= CUSTOM_DATA_LIMIT,1307				<Error<T>>::CollectionLimitBoundsExceeded,1308			),13091310			sponsored_data_rate_limit => {},1311			token_limit => ensure!(1312				old_limit >= new_limit && new_limit > 0,1313				<Error<T>>::CollectionTokenLimitExceeded1314			),13151316			sponsor_transfer_timeout(match mode {1317				CollectionMode::NFT => NFT_SPONSOR_TRANSFER_TIMEOUT,1318				CollectionMode::Fungible(_) => FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,1319				CollectionMode::ReFungible => REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,1320			}) => ensure!(1321				new_limit <= MAX_SPONSOR_TIMEOUT,1322				<Error<T>>::CollectionLimitBoundsExceeded,1323			),1324			sponsor_approve_timeout => {},1325			owner_can_transfer => ensure!(1326				!limits.owner_can_transfer_instaled() ||1327				old_limit || !new_limit,1328				<Error<T>>::OwnerPermissionsCantBeReverted,1329			),1330			owner_can_destroy => ensure!(1331				old_limit || !new_limit,1332				<Error<T>>::OwnerPermissionsCantBeReverted,1333			),1334			transfers_enabled => {},1335		);1336		Ok(new_limit)1337	}13381339	/// Merge set fields from `new_permission` to `old_permission`.1340	pub fn clamp_permissions(1341		_mode: CollectionMode,1342		old_permission: &CollectionPermissions,1343		mut new_permission: CollectionPermissions,1344	) -> Result<CollectionPermissions, DispatchError> {1345		limit_default_clone!(old_permission, new_permission,1346			access => {},1347			mint_mode => {},1348			nesting => { /* todo check for permissive, if only it gets out of benchmarks */ },1349		);1350		Ok(new_permission)1351	}1352}13531354/// Indicates unsupported methods by returning [Error::UnsupportedOperation].1355#[macro_export]1356macro_rules! unsupported {1357	($runtime:path) => {1358		Err($crate::Error::<$runtime>::UnsupportedOperation.into())1359	};1360}13611362/// Return weights for various worst-case operations.1363pub trait CommonWeightInfo<CrossAccountId> {1364	/// Weight of item creation.1365	fn create_item() -> Weight;13661367	/// Weight of items creation.1368	fn create_multiple_items(amount: &[CreateItemData]) -> Weight;13691370	/// Weight of items creation.1371	fn create_multiple_items_ex(cost: &CreateItemExData<CrossAccountId>) -> Weight;13721373	/// The weight of the burning item.1374	fn burn_item() -> Weight;13751376	/// Property setting weight.1377	///1378	/// * `amount`- The number of properties to set.1379	fn set_collection_properties(amount: u32) -> Weight;13801381	/// Collection property deletion weight.1382	///1383	/// * `amount`- The number of properties to set.1384	fn delete_collection_properties(amount: u32) -> Weight;13851386	/// Token property setting weight.1387	///1388	/// * `amount`- The number of properties to set.1389	fn set_token_properties(amount: u32) -> Weight;13901391	/// Token property deletion weight.1392	///1393	/// * `amount`- The number of properties to delete.1394	fn delete_token_properties(amount: u32) -> Weight;13951396	/// Token property permissions set weight.1397	///1398	/// * `amount`- The number of property permissions to set.1399	fn set_token_property_permissions(amount: u32) -> Weight;14001401	/// Transfer price of the token or its parts.1402	fn transfer() -> Weight;14031404	/// The price of setting the permission of the operation from another user.1405	fn approve() -> Weight;14061407	/// Transfer price from another user.1408	fn transfer_from() -> Weight;14091410	/// The price of burning a token from another user.1411	fn burn_from() -> Weight;14121413	/// Differs from burn_item in case of Fungible and Refungible, as it should burn1414	/// whole users's balance.1415	///1416	/// This method shouldn't be used directly, as it doesn't count breadth price, use [burn_recursively](CommonWeightInfo::burn_recursively) instead1417	fn burn_recursively_self_raw() -> Weight;14181419	/// Cost of iterating over `amount` children while burning, without counting child burning itself.1420	///1421	/// This method shouldn't be used directly, as it doesn't count depth price, use [burn_recursively](CommonWeightInfo::burn_recursively) instead1422	fn burn_recursively_breadth_raw(amount: u32) -> Weight;14231424	/// The price of recursive burning a token.1425	///1426	/// `max_selfs` - The maximum burning weight of the token itself.1427	/// `max_breadth` - The maximum number of nested tokens to burn.1428	fn burn_recursively(max_selfs: u32, max_breadth: u32) -> Weight {1429		Self::burn_recursively_self_raw()1430			.saturating_mul(max_selfs.max(1) as u64)1431			.saturating_add(Self::burn_recursively_breadth_raw(max_breadth))1432	}1433}14341435/// Weight info extension trait for refungible pallet.1436pub trait RefungibleExtensionsWeightInfo {1437	/// Weight of token repartition.1438	fn repartition() -> Weight;1439}14401441/// Common collection operations.1442///1443/// It wraps methods in Fungible, Nonfungible and Refungible pallets1444/// and adds weight info.1445pub trait CommonCollectionOperations<T: Config> {1446	/// Create token.1447	///1448	/// * `sender` - The user who mint the token and pays for the transaction.1449	/// * `to` - The user who will own the token.1450	/// * `data` - Token data.1451	/// * `nesting_budget` - A budget that can be spent on nesting tokens.1452	fn create_item(1453		&self,1454		sender: T::CrossAccountId,1455		to: T::CrossAccountId,1456		data: CreateItemData,1457		nesting_budget: &dyn Budget,1458	) -> DispatchResultWithPostInfo;14591460	/// Create multiple tokens.1461	///1462	/// * `sender` - The user who mint the token and pays for the transaction.1463	/// * `to` - The user who will own the token.1464	/// * `data` - Token data.1465	/// * `nesting_budget` - A budget that can be spent on nesting tokens.1466	fn create_multiple_items(1467		&self,1468		sender: T::CrossAccountId,1469		to: T::CrossAccountId,1470		data: Vec<CreateItemData>,1471		nesting_budget: &dyn Budget,1472	) -> DispatchResultWithPostInfo;14731474	/// Create multiple tokens.1475	///1476	/// * `sender` - The user who mint the token and pays for the transaction.1477	/// * `to` - The user who will own the token.1478	/// * `data` - Token data.1479	/// * `nesting_budget` - A budget that can be spent on nesting tokens.1480	fn create_multiple_items_ex(1481		&self,1482		sender: T::CrossAccountId,1483		data: CreateItemExData<T::CrossAccountId>,1484		nesting_budget: &dyn Budget,1485	) -> DispatchResultWithPostInfo;14861487	/// Burn token.1488	///1489	/// * `sender` - The user who owns the token.1490	/// * `token` - Token id that will burned.1491	/// * `amount` - The number of parts of the token that will be burned.1492	fn burn_item(1493		&self,1494		sender: T::CrossAccountId,1495		token: TokenId,1496		amount: u128,1497	) -> DispatchResultWithPostInfo;14981499	/// Burn token and all nested tokens recursievly.1500	///1501	/// * `sender` - The user who owns the token.1502	/// * `token` - Token id that will burned.1503	/// * `self_budget` - The budget that can be spent on burning tokens.1504	/// * `breadth_budget` - The budget that can be spent on burning nested tokens.1505	fn burn_item_recursively(1506		&self,1507		sender: T::CrossAccountId,1508		token: TokenId,1509		self_budget: &dyn Budget,1510		breadth_budget: &dyn Budget,1511	) -> DispatchResultWithPostInfo;15121513	/// Set collection properties.1514	///1515	/// * `sender` - Must be either the owner of the collection or its admin.1516	/// * `properties` - Properties to be set.1517	fn set_collection_properties(1518		&self,1519		sender: T::CrossAccountId,1520		properties: Vec<Property>,1521	) -> DispatchResultWithPostInfo;15221523	/// Delete collection properties.1524	///1525	/// * `sender` - Must be either the owner of the collection or its admin.1526	/// * `properties` - The properties to be removed.1527	fn delete_collection_properties(1528		&self,1529		sender: &T::CrossAccountId,1530		property_keys: Vec<PropertyKey>,1531	) -> DispatchResultWithPostInfo;15321533	/// Set token properties.1534	///1535	/// The appropriate [`PropertyPermission`] for the token property1536	/// must be set with [`Self::set_token_property_permissions`].1537	///1538	/// * `sender` - Must be either the owner of the token or its admin.1539	/// * `token_id` - The token for which the properties are being set.1540	/// * `properties` - Properties to be set.1541	/// * `budget` - Budget for setting properties.1542	fn set_token_properties(1543		&self,1544		sender: T::CrossAccountId,1545		token_id: TokenId,1546		properties: Vec<Property>,1547		budget: &dyn Budget,1548	) -> DispatchResultWithPostInfo;15491550	/// Remove token properties.1551	///1552	/// The appropriate [`PropertyPermission`] for the token property1553	/// must be set with [`Self::set_token_property_permissions`].1554	///1555	/// * `sender` - Must be either the owner of the token or its admin.1556	/// * `token_id` - The token for which the properties are being remove.1557	/// * `property_keys` - Keys to remove corresponding properties.1558	/// * `budget` - Budget for removing properties.1559	fn delete_token_properties(1560		&self,1561		sender: T::CrossAccountId,1562		token_id: TokenId,1563		property_keys: Vec<PropertyKey>,1564		budget: &dyn Budget,1565	) -> DispatchResultWithPostInfo;15661567	/// Set token property permissions.1568	///1569	/// * `sender` - Must be either the owner of the token or its admin.1570	/// * `token_id` - The token for which the properties are being set.1571	/// * `properties` - Properties to be set.1572	/// * `budget` - Budget for setting properties.1573	fn set_token_property_permissions(1574		&self,1575		sender: &T::CrossAccountId,1576		property_permissions: Vec<PropertyKeyPermission>,1577	) -> DispatchResultWithPostInfo;15781579	/// Transfer amount of token pieces.1580	///1581	/// * `sender` - Donor user.1582	/// * `to` - Recepient user.1583	/// * `token` - The token of which parts are being sent.1584	/// * `amount` - The number of parts of the token that will be transferred.1585	/// * `budget` - The maximum budget that can be spent on the transfer.1586	fn transfer(1587		&self,1588		sender: T::CrossAccountId,1589		to: T::CrossAccountId,1590		token: TokenId,1591		amount: u128,1592		budget: &dyn Budget,1593	) -> DispatchResultWithPostInfo;15941595	/// Grant access to another account to transfer parts of the token owned by the calling user via [Self::transfer_from].1596	///1597	/// * `sender` - The user who grants access to the token.1598	/// * `spender` - The user to whom the rights are granted.1599	/// * `token` - The token to which access is granted.1600	/// * `amount` - The amount of pieces that another user can dispose of.1601	fn approve(1602		&self,1603		sender: T::CrossAccountId,1604		spender: T::CrossAccountId,1605		token: TokenId,1606		amount: u128,1607	) -> DispatchResultWithPostInfo;16081609	/// Send parts of a token owned by another user.1610	///1611	/// Before calling this method, you must grant rights to the calling user via [`Self::approve`].1612	///1613	/// * `sender` - The user who must have access to the token (see [`Self::approve`]).1614	/// * `from` - The user who owns the token.1615	/// * `to` - Recepient user.1616	/// * `token` - The token of which parts are being sent.1617	/// * `amount` - The number of parts of the token that will be transferred.1618	/// * `budget` - The maximum budget that can be spent on the transfer.1619	fn transfer_from(1620		&self,1621		sender: T::CrossAccountId,1622		from: T::CrossAccountId,1623		to: T::CrossAccountId,1624		token: TokenId,1625		amount: u128,1626		budget: &dyn Budget,1627	) -> DispatchResultWithPostInfo;16281629	/// Burn parts of a token owned by another user.1630	///1631	/// Before calling this method, you must grant rights to the calling user via [`Self::approve`].1632	///1633	/// * `sender` - The user who must have access to the token (see [`Self::approve`]).1634	/// * `from` - The user who owns the token.1635	/// * `token` - The token of which parts are being sent.1636	/// * `amount` - The number of parts of the token that will be transferred.1637	/// * `budget` - The maximum budget that can be spent on the burn.1638	fn burn_from(1639		&self,1640		sender: T::CrossAccountId,1641		from: T::CrossAccountId,1642		token: TokenId,1643		amount: u128,1644		budget: &dyn Budget,1645	) -> DispatchResultWithPostInfo;16461647	/// Check permission to nest token.1648	///1649	/// * `sender` - The user who initiated the check.1650	/// * `from` - The token that is checked for embedding.1651	/// * `under` - Token under which to check.1652	/// * `budget` - The maximum budget that can be spent on the check.1653	fn check_nesting(1654		&self,1655		sender: T::CrossAccountId,1656		from: (CollectionId, TokenId),1657		under: TokenId,1658		budget: &dyn Budget,1659	) -> DispatchResult;16601661	/// Nest one token into another.1662	///1663	/// * `under` - Token holder.1664	/// * `to_nest` - Nested token.1665	fn nest(&self, under: TokenId, to_nest: (CollectionId, TokenId));16661667	/// Unnest token.1668	///1669	/// * `under` - Token holder.1670	/// * `to_nest` - Token to unnest.1671	fn unnest(&self, under: TokenId, to_nest: (CollectionId, TokenId));16721673	/// Get all user tokens.1674	///1675	/// * `account` - Account for which you need to get tokens.1676	fn account_tokens(&self, account: T::CrossAccountId) -> Vec<TokenId>;16771678	/// Get all the tokens in the collection.1679	fn collection_tokens(&self) -> Vec<TokenId>;16801681	/// Check if the token exists.1682	///1683	/// * `token` - Id token to check.1684	fn token_exists(&self, token: TokenId) -> bool;16851686	/// Get the id of the last minted token.1687	fn last_token_id(&self) -> TokenId;16881689	/// Get the owner of the token.1690	///1691	/// * `token` - The token for which you need to find out the owner.1692	fn token_owner(&self, token: TokenId) -> Option<T::CrossAccountId>;16931694	/// Returns 10 tokens owners in no particular order.1695	///1696	/// * `token` - The token for which you need to find out the owners.1697	fn token_owners(&self, token: TokenId) -> Vec<T::CrossAccountId>;16981699	/// Get the value of the token property by key.1700	///1701	/// * `token` - Token with the property to get.1702	/// * `key` - Property name.1703	fn token_property(&self, token_id: TokenId, key: &PropertyKey) -> Option<PropertyValue>;17041705	/// Get a set of token properties by key vector.1706	///1707	/// * `token` - Token with the property to get.1708	/// * `keys` - Vector of property keys. If this parameter is [None](sp_std::result::Result),1709	/// then all properties are returned.1710	fn token_properties(&self, token: TokenId, keys: Option<Vec<PropertyKey>>) -> Vec<Property>;17111712	/// Amount of unique collection tokens1713	fn total_supply(&self) -> u32;17141715	/// Amount of different tokens account has.1716	///1717	/// * `account` - The account for which need to get the balance.1718	fn account_balance(&self, account: T::CrossAccountId) -> u32;17191720	/// Amount of specific token account have.1721	fn balance(&self, account: T::CrossAccountId, token: TokenId) -> u128;17221723	/// Amount of token pieces1724	fn total_pieces(&self, token: TokenId) -> Option<u128>;17251726	/// Get the number of parts of the token that a trusted user can manage.1727	///1728	/// * `sender` - Trusted user.1729	/// * `spender` - Owner of the token.1730	/// * `token` - The token for which to get the value.1731	fn allowance(1732		&self,1733		sender: T::CrossAccountId,1734		spender: T::CrossAccountId,1735		token: TokenId,1736	) -> u128;17371738	/// Get extension for RFT collection.1739	fn refungible_extensions(&self) -> Option<&dyn RefungibleExtensions<T>>;1740}17411742/// Extension for RFT collection.1743pub trait RefungibleExtensions<T>1744where1745	T: Config,1746{1747	/// Change the number of parts of the token.1748	///1749	/// When the value changes down, this function is equivalent to burning parts of the token.1750	///1751	/// * `sender` - The user calling the repartition operation. Must be the owner of the token.1752	/// * `token` - The token for which you want to change the number of parts.1753	/// * `amount` - The new value of the parts of the token.1754	fn repartition(1755		&self,1756		sender: &T::CrossAccountId,1757		token: TokenId,1758		amount: u128,1759	) -> DispatchResultWithPostInfo;1760}17611762/// Merge [`DispatchResult`] with [`Weight`] into [`DispatchResultWithPostInfo`].1763///1764/// Used for [`CommonCollectionOperations`] implementations and flexible enough to do so.1765pub fn with_weight(res: DispatchResult, weight: Weight) -> DispatchResultWithPostInfo {1766	let post_info = PostDispatchInfo {1767		actual_weight: Some(weight),1768		pays_fee: Pays::Yes,1769	};1770	match res {1771		Ok(()) => Ok(post_info),1772		Err(error) => Err(DispatchErrorWithPostInfo { post_info, error }),1773	}1774}17751776impl<T: Config> From<PropertiesError> for Error<T> {1777	fn from(error: PropertiesError) -> Self {1778		match error {1779			PropertiesError::NoSpaceForProperty => Self::NoSpaceForProperty,1780			PropertiesError::PropertyLimitReached => Self::PropertyLimitReached,1781			PropertiesError::InvalidCharacterInPropertyKey => Self::InvalidCharacterInPropertyKey,1782			PropertiesError::PropertyKeyIsTooLong => Self::PropertyKeyIsTooLong,1783			PropertiesError::EmptyPropertyKey => Self::EmptyPropertyKey,1784		}1785	}1786}
after · pallets/common/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//! # Common pallet18//!19//! The Common pallet provides functionality for handling collections.20//!21//! ## Overview22//!23//! The Common pallet provides an interface for common collection operations for different collection types24//! (see [CommonCollectionOperations]), as well as a generic dispatcher for these, see [dispatch] module.25//! It also provides this functionality to EVM, see [erc] and [eth] modules.26//!27//! The Common pallet provides functions for:28//!29//! - Setting and approving collection sponsor.30//! - Get\set\delete allow list.31//! - Get\set\delete collection properties.32//! - Get\set\delete collection property permissions.33//! - Get\set\delete token property permissions.34//! - Get\set\delete collection administrators.35//! - Checking access permissions.36//!37//! ### Terminology38//! **Collection sponsor** - For the collection, you can set a sponsor, at whose expense it will39//! be possible to mint tokens.40//!41//! **Allow list** - List of users who have the right to minting tokens.42//!43//! **Collection properties** - Collection properties are simply key-value stores where various44//! metadata can be placed.45//!46//! **Permissions on token properties** - For each property in the token can be set permission47//! to change, see [`PropertyPermission`].48//!49//! **Collection administrator** - For a collection, you can set administrators who have the right50//! to most actions on the collection.5152#![warn(missing_docs)]53#![cfg_attr(not(feature = "std"), no_std)]54extern crate alloc;5556use core::ops::{Deref, DerefMut};57use pallet_evm_coder_substrate::{SubstrateRecorder, WithRecorder};58use sp_std::vec::Vec;59use pallet_evm::{account::CrossAccountId, Pallet as PalletEvm};60use evm_coder::ToLog;61use frame_support::{62	dispatch::{DispatchErrorWithPostInfo, DispatchResultWithPostInfo, Weight, PostDispatchInfo},63	ensure,64	traits::{Imbalance, Get, Currency, WithdrawReasons, ExistenceRequirement},65	weights::Pays,66	transactional,67};68use pallet_evm::GasWeightMapping;69use up_data_structs::{70	COLLECTION_NUMBER_LIMIT,71	Collection,72	RpcCollection,73	CollectionId,74	CreateItemData,75	MAX_TOKEN_PREFIX_LENGTH,76	COLLECTION_ADMINS_LIMIT,77	TokenId,78	TokenChild,79	CollectionStats,80	MAX_TOKEN_OWNERSHIP,81	CollectionMode,82	NFT_SPONSOR_TRANSFER_TIMEOUT,83	FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,84	REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,85	MAX_SPONSOR_TIMEOUT,86	CUSTOM_DATA_LIMIT,87	CollectionLimits,88	CreateCollectionData,89	SponsorshipState,90	CreateItemExData,91	SponsoringRateLimit,92	budget::Budget,93	PhantomType,94	Property,95	Properties,96	PropertiesPermissionMap,97	PropertyKey,98	PropertyValue,99	PropertyPermission,100	PropertiesError,101	PropertyKeyPermission,102	TokenData,103	TrySetProperty,104	PropertyScope,105	// RMRK106	RmrkCollectionInfo,107	RmrkInstanceInfo,108	RmrkResourceInfo,109	RmrkPropertyInfo,110	RmrkBaseInfo,111	RmrkPartType,112	RmrkBoundedTheme,113	RmrkNftChild,114	CollectionPermissions,115	SchemaVersion,116};117118pub use pallet::*;119use sp_core::H160;120use sp_runtime::{ArithmeticError, DispatchError, DispatchResult};121#[cfg(feature = "runtime-benchmarks")]122pub mod benchmarking;123pub mod dispatch;124pub mod erc;125pub mod eth;126pub mod weights;127128/// Weight info.129pub type SelfWeightOf<T> = <T as Config>::WeightInfo;130131/// Collection handle contains information about collection data and id.132/// Also provides functionality to count consumed gas.133///134/// CollectionHandle is used as a generic wrapper for collections of all types.135/// It allows to perform common operations and queries on any collection type,136/// both completely general for all, as well as their respective implementations of [`CommonCollectionOperations`].137#[must_use = "Should call submit_logs or save, otherwise some data will be lost for evm side"]138pub struct CollectionHandle<T: Config> {139	/// Collection id140	pub id: CollectionId,141	collection: Collection<T::AccountId>,142	/// Substrate recorder for counting consumed gas143	pub recorder: SubstrateRecorder<T>,144}145146impl<T: Config> WithRecorder<T> for CollectionHandle<T> {147	fn recorder(&self) -> &SubstrateRecorder<T> {148		&self.recorder149	}150	fn into_recorder(self) -> SubstrateRecorder<T> {151		self.recorder152	}153}154155impl<T: Config> CollectionHandle<T> {156	/// Same as [CollectionHandle::new] but with an explicit gas limit.157	pub fn new_with_gas_limit(id: CollectionId, gas_limit: u64) -> Option<Self> {158		<CollectionById<T>>::get(id).map(|collection| Self {159			id,160			collection,161			recorder: SubstrateRecorder::new(gas_limit),162		})163	}164165	/// Same as [CollectionHandle::new] but with an existed [`SubstrateRecorder`].166	pub fn new_with_recorder(id: CollectionId, recorder: SubstrateRecorder<T>) -> Option<Self> {167		<CollectionById<T>>::get(id).map(|collection| Self {168			id,169			collection,170			recorder,171		})172	}173174	/// Retrives collection data from storage and creates collection handle with default parameters.175	/// If collection not found return `None`176	pub fn new(id: CollectionId) -> Option<Self> {177		Self::new_with_gas_limit(id, u64::MAX)178	}179180	/// Same as [`CollectionHandle::new`] but if collection not found [CollectionNotFound](Error::CollectionNotFound) returned.181	pub fn try_get(id: CollectionId) -> Result<Self, DispatchError> {182		Ok(Self::new(id).ok_or(<Error<T>>::CollectionNotFound)?)183	}184185	/// Consume gas for reading.186	pub fn consume_store_reads(&self, reads: u64) -> evm_coder::execution::Result<()> {187		self.recorder188			.consume_gas(T::GasWeightMapping::weight_to_gas(189				<T as frame_system::Config>::DbWeight::get()190					.read191					.saturating_mul(reads),192			))193	}194195	/// Consume gas for writing.196	pub fn consume_store_writes(&self, writes: u64) -> evm_coder::execution::Result<()> {197		self.recorder198			.consume_gas(T::GasWeightMapping::weight_to_gas(199				<T as frame_system::Config>::DbWeight::get()200					.write201					.saturating_mul(writes),202			))203	}204205	/// Save collection to storage.206	pub fn save(self) -> DispatchResult {207		<CollectionById<T>>::insert(self.id, self.collection);208		Ok(())209	}210211	/// Set collection sponsor.212	///213	/// Unique collections allows sponsoring for certain actions.214	/// This method allows you to set the sponsor of the collection.215	/// In order for sponsorship to become active, it must be confirmed through [`Self::confirm_sponsorship`].216	pub fn set_sponsor(&mut self, sponsor: T::AccountId) -> DispatchResult {217		self.collection.sponsorship = SponsorshipState::Unconfirmed(sponsor);218		Ok(())219	}220221	/// Confirm sponsorship222	///223	/// In order for the sponsorship to become active, the user set as the sponsor must confirm their participation.224	/// Before confirming sponsorship, the user must be specified as the sponsor of the collection via [`Self::set_sponsor`].225	pub fn confirm_sponsorship(&mut self, sender: &T::AccountId) -> Result<bool, DispatchError> {226		if self.collection.sponsorship.pending_sponsor() != Some(sender) {227			return Ok(false);228		}229230		self.collection.sponsorship = SponsorshipState::Confirmed(sender.clone());231		Ok(true)232	}233234	/// Checks that the collection was created with, and must be operated upon through **Unique API**.235	/// Now check only the `external_collection` flag and if it's **true**, then return [`Error::CollectionIsExternal`] error.236	pub fn check_is_internal(&self) -> DispatchResult {237		if self.external_collection {238			return Err(<Error<T>>::CollectionIsExternal)?;239		}240241		Ok(())242	}243244	/// Checks that the collection was created with, and must be operated upon through an **assimilated API**.245	/// Now check only the `external_collection` flag and if it's **false**, then return [`Error::CollectionIsInternal`] error.246	pub fn check_is_external(&self) -> DispatchResult {247		if !self.external_collection {248			return Err(<Error<T>>::CollectionIsInternal)?;249		}250251		Ok(())252	}253}254255impl<T: Config> Deref for CollectionHandle<T> {256	type Target = Collection<T::AccountId>;257258	fn deref(&self) -> &Self::Target {259		&self.collection260	}261}262263impl<T: Config> DerefMut for CollectionHandle<T> {264	fn deref_mut(&mut self) -> &mut Self::Target {265		&mut self.collection266	}267}268269impl<T: Config> CollectionHandle<T> {270	/// Checks if the `user` is the owner of the collection.271	pub fn check_is_owner(&self, user: &T::CrossAccountId) -> DispatchResult {272		ensure!(*user.as_sub() == self.owner, <Error<T>>::NoPermission);273		Ok(())274	}275276	/// Returns **true** if the `user` is the owner or administrator of the collection.277	pub fn is_owner_or_admin(&self, user: &T::CrossAccountId) -> bool {278		*user.as_sub() == self.owner || <IsAdmin<T>>::get((self.id, user))279	}280281	/// Checks if the `user` is the owner or administrator of the collection.282	pub fn check_is_owner_or_admin(&self, user: &T::CrossAccountId) -> DispatchResult {283		ensure!(self.is_owner_or_admin(user), <Error<T>>::NoPermission);284		Ok(())285	}286287	/// Return **true** if `user` was not allowed to have tokens, and he can ignore such restrictions.288	pub fn ignores_allowance(&self, user: &T::CrossAccountId) -> bool {289		self.limits.owner_can_transfer() && self.is_owner_or_admin(user)290	}291292	/// Return **true** if `user` does not have enough token parts, and he can ignore such restrictions.293	pub fn ignores_owned_amount(&self, user: &T::CrossAccountId) -> bool {294		self.limits.owner_can_transfer() && self.is_owner_or_admin(user)295	}296297	/// Checks if the user is in the allow list. If not [Error::AddressNotInAllowlist] returns.298	pub fn check_allowlist(&self, user: &T::CrossAccountId) -> DispatchResult {299		ensure!(300			<Allowlist<T>>::get((self.id, user)),301			<Error<T>>::AddressNotInAllowlist302		);303		Ok(())304	}305}306307#[frame_support::pallet]308pub mod pallet {309	use super::*;310	use pallet_evm::account;311	use dispatch::CollectionDispatch;312	use frame_support::{Blake2_128Concat, pallet_prelude::*, storage::Key, traits::StorageVersion};313	use frame_system::pallet_prelude::*;314	use frame_support::traits::Currency;315	use up_data_structs::{TokenId, mapping::TokenAddressMapping};316	use scale_info::TypeInfo;317	use weights::WeightInfo;318319	#[pallet::config]320	pub trait Config:321		frame_system::Config322		+ pallet_evm_coder_substrate::Config323		+ pallet_evm::Config324		+ TypeInfo325		+ account::Config326	{327		/// Weight information for functions of this pallet.328		type WeightInfo: WeightInfo;329330		/// Events compatible with [`frame_system::Config::Event`].331		type Event: IsType<<Self as frame_system::Config>::Event> + From<Event<Self>>;332333		/// Handler of accounts and payment.334		type Currency: Currency<Self::AccountId>;335336		/// Set price to create a collection.337		#[pallet::constant]338		type CollectionCreationPrice: Get<339			<<Self as Config>::Currency as Currency<Self::AccountId>>::Balance,340		>;341342		/// Dispatcher of operations on collections.343		type CollectionDispatch: CollectionDispatch<Self>;344345		/// Account which holds the chain's treasury.346		type TreasuryAccountId: Get<Self::AccountId>;347348		/// Address under which the CollectionHelper contract would be available.349		type ContractAddress: Get<H160>;350351		/// Mapper for token addresses to Ethereum addresses.352		type EvmTokenAddressMapping: TokenAddressMapping<H160>;353354		/// Mapper for token addresses to [`CrossAccountId`].355		type CrossTokenAddressMapping: TokenAddressMapping<Self::CrossAccountId>;356	}357358	const STORAGE_VERSION: StorageVersion = StorageVersion::new(1);359360	#[pallet::pallet]361	#[pallet::storage_version(STORAGE_VERSION)]362	#[pallet::generate_store(pub(super) trait Store)]363	pub struct Pallet<T>(_);364365	#[pallet::extra_constants]366	impl<T: Config> Pallet<T> {367		/// Maximum admins per collection.368		pub fn collection_admins_limit() -> u32 {369			COLLECTION_ADMINS_LIMIT370		}371	}372373	#[pallet::event]374	#[pallet::generate_deposit(pub fn deposit_event)]375	pub enum Event<T: Config> {376		/// New collection was created377		CollectionCreated(378			/// Globally unique identifier of newly created collection.379			CollectionId,380			/// [`CollectionMode`] converted into _u8_.381			u8,382			/// Collection owner.383			T::AccountId,384		),385386		/// New collection was destroyed387		CollectionDestroyed(388			/// Globally unique identifier of collection.389			CollectionId,390		),391392		/// New item was created.393		ItemCreated(394			/// Id of the collection where item was created.395			CollectionId,396			/// Id of an item. Unique within the collection.397			TokenId,398			/// Owner of newly created item399			T::CrossAccountId,400			/// Always 1 for NFT401			u128,402		),403404		/// Collection item was burned.405		ItemDestroyed(406			/// Id of the collection where item was destroyed.407			CollectionId,408			/// Identifier of burned NFT.409			TokenId,410			/// Which user has destroyed its tokens.411			T::CrossAccountId,412			/// Amount of token pieces destroed. Always 1 for NFT.413			u128,414		),415416		/// Item was transferred417		Transfer(418			/// Id of collection to which item is belong.419			CollectionId,420			/// Id of an item.421			TokenId,422			/// Original owner of item.423			T::CrossAccountId,424			/// New owner of item.425			T::CrossAccountId,426			/// Amount of token pieces transfered. Always 1 for NFT.427			u128,428		),429430		/// Amount pieces of token owned by `sender` was approved for `spender`.431		Approved(432			/// Id of collection to which item is belong.433			CollectionId,434			/// Id of an item.435			TokenId,436			/// Original owner of item.437			T::CrossAccountId,438			/// Id for which the approval was granted.439			T::CrossAccountId,440			/// Amount of token pieces transfered. Always 1 for NFT.441			u128,442		),443444		/// The colletion property has been added or edited.445		CollectionPropertySet(446			/// Id of collection to which property has been set.447			CollectionId,448			/// The property that was set.449			PropertyKey,450		),451452		/// The property has been deleted.453		CollectionPropertyDeleted(454			/// Id of collection to which property has been deleted.455			CollectionId,456			/// The property that was deleted.457			PropertyKey,458		),459460		/// The token property has been added or edited.461		TokenPropertySet(462			/// Identifier of the collection whose token has the property set.463			CollectionId,464			/// The token for which the property was set.465			TokenId,466			/// The property that was set.467			PropertyKey,468		),469470		/// The token property has been deleted.471		TokenPropertyDeleted(472			/// Identifier of the collection whose token has the property deleted.473			CollectionId,474			/// The token for which the property was deleted.475			TokenId,476			/// The property that was deleted.477			PropertyKey,478		),479480		/// The token property permission of a collection has been set.481		PropertyPermissionSet(482			/// ID of collection to which property permission has been set.483			CollectionId,484			/// The property permission that was set.485			PropertyKey,486		),487	}488489	#[pallet::error]490	pub enum Error<T> {491		/// This collection does not exist.492		CollectionNotFound,493		/// Sender parameter and item owner must be equal.494		MustBeTokenOwner,495		/// No permission to perform action496		NoPermission,497		/// Destroying only empty collections is allowed498		CantDestroyNotEmptyCollection,499		/// Collection is not in mint mode.500		PublicMintingNotAllowed,501		/// Address is not in allow list.502		AddressNotInAllowlist,503504		/// Collection name can not be longer than 63 char.505		CollectionNameLimitExceeded,506		/// Collection description can not be longer than 255 char.507		CollectionDescriptionLimitExceeded,508		/// Token prefix can not be longer than 15 char.509		CollectionTokenPrefixLimitExceeded,510		/// Total collections bound exceeded.511		TotalCollectionsLimitExceeded,512		/// Exceeded max admin count513		CollectionAdminCountExceeded,514		/// Collection limit bounds per collection exceeded515		CollectionLimitBoundsExceeded,516		/// Tried to enable permissions which are only permitted to be disabled517		OwnerPermissionsCantBeReverted,518		/// Collection settings not allowing items transferring519		TransferNotAllowed,520		/// Account token limit exceeded per collection521		AccountTokenLimitExceeded,522		/// Collection token limit exceeded523		CollectionTokenLimitExceeded,524		/// Metadata flag frozen525		MetadataFlagFrozen,526527		/// Item does not exist528		TokenNotFound,529		/// Item is balance not enough530		TokenValueTooLow,531		/// Requested value is more than the approved532		ApprovedValueTooLow,533		/// Tried to approve more than owned534		CantApproveMoreThanOwned,535536		/// Can't transfer tokens to ethereum zero address537		AddressIsZero,538539		/// The oprtation is not supported540		UnsupportedOperation,541542		/// Insufficient funds to perform an action543		NotSufficientFounds,544545		/// User does not satisfy the nesting rule546		UserIsNotAllowedToNest,547		/// Only tokens from specific collections may nest tokens under this one548		SourceCollectionIsNotAllowedToNest,549550		/// Tried to store more data than allowed in collection field551		CollectionFieldSizeExceeded,552553		/// Tried to store more property data than allowed554		NoSpaceForProperty,555556		/// Tried to store more property keys than allowed557		PropertyLimitReached,558559		/// Property key is too long560		PropertyKeyIsTooLong,561562		/// Only ASCII letters, digits, and symbols `_`, `-`, and `.` are allowed563		InvalidCharacterInPropertyKey,564565		/// Empty property keys are forbidden566		EmptyPropertyKey,567568		/// Tried to access an external collection with an internal API569		CollectionIsExternal,570571		/// Tried to access an internal collection with an external API572		CollectionIsInternal,573	}574575	/// Storage of the count of created collections. Essentially contains the last collection ID.576	#[pallet::storage]577	pub type CreatedCollectionCount<T> = StorageValue<Value = CollectionId, QueryKind = ValueQuery>;578579	/// Storage of the count of deleted collections.580	#[pallet::storage]581	pub type DestroyedCollectionCount<T> =582		StorageValue<Value = CollectionId, QueryKind = ValueQuery>;583584	/// Storage of collection info.585	#[pallet::storage]586	pub type CollectionById<T> = StorageMap<587		Hasher = Blake2_128Concat,588		Key = CollectionId,589		Value = Collection<<T as frame_system::Config>::AccountId>,590		QueryKind = OptionQuery,591	>;592593	/// Storage of collection properties.594	#[pallet::storage]595	#[pallet::getter(fn collection_properties)]596	pub type CollectionProperties<T> = StorageMap<597		Hasher = Blake2_128Concat,598		Key = CollectionId,599		Value = Properties,600		QueryKind = ValueQuery,601		OnEmpty = up_data_structs::CollectionProperties,602	>;603604	/// Storage of token property permissions of a collection.605	#[pallet::storage]606	#[pallet::getter(fn property_permissions)]607	pub type CollectionPropertyPermissions<T> = StorageMap<608		Hasher = Blake2_128Concat,609		Key = CollectionId,610		Value = PropertiesPermissionMap,611		QueryKind = ValueQuery,612	>;613614	/// Storage of the amount of collection admins.615	#[pallet::storage]616	pub type AdminAmount<T> = StorageMap<617		Hasher = Blake2_128Concat,618		Key = CollectionId,619		Value = u32,620		QueryKind = ValueQuery,621	>;622623	/// List of collection admins.624	#[pallet::storage]625	pub type IsAdmin<T: Config> = StorageNMap<626		Key = (627			Key<Blake2_128Concat, CollectionId>,628			Key<Blake2_128Concat, T::CrossAccountId>,629		),630		Value = bool,631		QueryKind = ValueQuery,632	>;633634	/// Allowlisted collection users.635	#[pallet::storage]636	pub type Allowlist<T: Config> = StorageNMap<637		Key = (638			Key<Blake2_128Concat, CollectionId>,639			Key<Blake2_128Concat, T::CrossAccountId>,640		),641		Value = bool,642		QueryKind = ValueQuery,643	>;644645	/// Not used by code, exists only to provide some types to metadata.646	#[pallet::storage]647	pub type DummyStorageValue<T: Config> = StorageValue<648		Value = (649			CollectionStats,650			CollectionId,651			TokenId,652			TokenChild,653			PhantomType<(654				TokenData<T::CrossAccountId>,655				RpcCollection<T::AccountId>,656				// RMRK657				RmrkCollectionInfo<T::AccountId>,658				RmrkInstanceInfo<T::AccountId>,659				RmrkResourceInfo,660				RmrkPropertyInfo,661				RmrkBaseInfo<T::AccountId>,662				RmrkPartType,663				RmrkBoundedTheme,664				RmrkNftChild,665			)>,666		),667		QueryKind = OptionQuery,668	>;669670	#[pallet::hooks]671	impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {672		fn on_runtime_upgrade() -> Weight {673			StorageVersion::new(1).put::<Pallet<T>>();674675			0676		}677	}678}679680impl<T: Config> Pallet<T> {681	/// Enshure that receiver address is correct.682	///683	/// Ethereum receiver 0x0000000000000000000000000000000000000000 is reserved, and shouldn't own tokens.684	pub fn ensure_correct_receiver(receiver: &T::CrossAccountId) -> DispatchResult {685		ensure!(686			&T::CrossAccountId::from_eth(H160([0; 20])) != receiver,687			<Error<T>>::AddressIsZero688		);689		Ok(())690	}691692	/// Get a vector of collection admins.693	pub fn adminlist(collection: CollectionId) -> Vec<T::CrossAccountId> {694		<IsAdmin<T>>::iter_prefix((collection,))695			.map(|(a, _)| a)696			.collect()697	}698699	/// Get a vector of users allowed to mint tokens.700	pub fn allowlist(collection: CollectionId) -> Vec<T::CrossAccountId> {701		<Allowlist<T>>::iter_prefix((collection,))702			.map(|(a, _)| a)703			.collect()704	}705706	/// Is `user` allowed to mint token in `collection`.707	pub fn allowed(collection: CollectionId, user: T::CrossAccountId) -> bool {708		<Allowlist<T>>::get((collection, user))709	}710711	/// Get statistics of collections.712	pub fn collection_stats() -> CollectionStats {713		let created = <CreatedCollectionCount<T>>::get();714		let destroyed = <DestroyedCollectionCount<T>>::get();715		CollectionStats {716			created: created.0,717			destroyed: destroyed.0,718			alive: created.0 - destroyed.0,719		}720	}721722	/// Get the effective limits for the collection.723	pub fn effective_collection_limits(collection: CollectionId) -> Option<CollectionLimits> {724		let collection = <CollectionById<T>>::get(collection);725		if collection.is_none() {726			return None;727		}728729		let collection = collection.unwrap();730		let limits = collection.limits;731		let effective_limits = CollectionLimits {732			account_token_ownership_limit: Some(limits.account_token_ownership_limit()),733			sponsored_data_size: Some(limits.sponsored_data_size()),734			sponsored_data_rate_limit: Some(735				limits736					.sponsored_data_rate_limit737					.unwrap_or(SponsoringRateLimit::SponsoringDisabled),738			),739			token_limit: Some(limits.token_limit()),740			sponsor_transfer_timeout: Some(limits.sponsor_transfer_timeout(741				match collection.mode {742					CollectionMode::NFT => NFT_SPONSOR_TRANSFER_TIMEOUT,743					CollectionMode::Fungible(_) => FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,744					CollectionMode::ReFungible => REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,745				},746			)),747			sponsor_approve_timeout: Some(limits.sponsor_approve_timeout()),748			owner_can_transfer: Some(limits.owner_can_transfer()),749			owner_can_destroy: Some(limits.owner_can_destroy()),750			transfers_enabled: Some(limits.transfers_enabled()),751		};752753		Some(effective_limits)754	}755756	/// Returns information about the `collection` adapted for rpc.757	pub fn rpc_collection(collection: CollectionId) -> Option<RpcCollection<T::AccountId>> {758		let Collection {759			name,760			description,761			owner,762			mode,763			token_prefix,764			sponsorship,765			limits,766			permissions,767			external_collection,768		} = <CollectionById<T>>::get(collection)?;769770		let token_property_permissions = <CollectionPropertyPermissions<T>>::get(collection)771			.into_iter()772			.map(|(key, permission)| PropertyKeyPermission { key, permission })773			.collect();774775		let properties = <CollectionProperties<T>>::get(collection)776			.into_iter()777			.map(|(key, value)| Property { key, value })778			.collect();779780		let permissions = CollectionPermissions {781			access: Some(permissions.access()),782			mint_mode: Some(permissions.mint_mode()),783			nesting: Some(permissions.nesting().clone()),784		};785786		Some(RpcCollection {787			name: name.into_inner(),788			description: description.into_inner(),789			owner,790			mode,791			token_prefix: token_prefix.into_inner(),792			sponsorship,793			limits,794			permissions,795			token_property_permissions,796			properties,797			read_only: external_collection,798		})799	}800}801802macro_rules! limit_default {803	($old:ident, $new:ident, $($field:ident $(($arg:expr))? => $check:expr),* $(,)?) => {{804		$(805			if let Some($new) = $new.$field {806				let $old = $old.$field($($arg)?);807				let _ = $new;808				let _ = $old;809				$check810			} else {811				$new.$field = $old.$field812			}813		)*814	}};815}816macro_rules! limit_default_clone {817	($old:ident, $new:ident, $($field:ident $(($arg:expr))? => $check:expr),* $(,)?) => {{818		$(819			if let Some($new) = $new.$field.clone() {820				let $old = $old.$field($($arg)?);821				let _ = $new;822				let _ = $old;823				$check824			} else {825				$new.$field = $old.$field.clone()826			}827		)*828	}};829}830831impl<T: Config> Pallet<T> {832	/// Create new collection.833	///834	/// * `owner` - The owner of the collection.835	/// * `data` - Description of the created collection.836	/// * `is_external` - Marks that collection managet by not "Unique network".837	pub fn init_collection(838		owner: T::CrossAccountId,839		data: CreateCollectionData<T::AccountId>,840		is_external: bool,841	) -> Result<CollectionId, DispatchError> {842		{843			ensure!(844				data.token_prefix.len() <= MAX_TOKEN_PREFIX_LENGTH as usize,845				Error::<T>::CollectionTokenPrefixLimitExceeded846			);847		}848849		let created_count = <CreatedCollectionCount<T>>::get()850			.0851			.checked_add(1)852			.ok_or(ArithmeticError::Overflow)?;853		let destroyed_count = <DestroyedCollectionCount<T>>::get().0;854		let id = CollectionId(created_count);855856		// bound Total number of collections857		ensure!(858			created_count - destroyed_count <= COLLECTION_NUMBER_LIMIT,859			<Error<T>>::TotalCollectionsLimitExceeded860		);861862		// =========863864		let collection = Collection {865			owner: owner.as_sub().clone(),866			name: data.name,867			mode: data.mode.clone(),868			description: data.description,869			token_prefix: data.token_prefix,870			sponsorship: data871				.pending_sponsor872				.map(SponsorshipState::Unconfirmed)873				.unwrap_or_default(),874			limits: data875				.limits876				.map(|limits| Self::clamp_limits(data.mode.clone(), &Default::default(), limits))877				.unwrap_or_else(|| Ok(CollectionLimits::default()))?,878			permissions: data879				.permissions880				.map(|permissions| {881					Self::clamp_permissions(data.mode.clone(), &Default::default(), permissions)882				})883				.unwrap_or_else(|| Ok(CollectionPermissions::default()))?,884			external_collection: is_external,885		};886887		let mut collection_properties = up_data_structs::CollectionProperties::get();888		collection_properties889			.try_set_from_iter(data.properties.into_iter())890			.map_err(<Error<T>>::from)?;891892		CollectionProperties::<T>::insert(id, collection_properties);893894		let mut token_props_permissions = PropertiesPermissionMap::new();895		token_props_permissions896			.try_set_from_iter(data.token_property_permissions.into_iter())897			.map_err(<Error<T>>::from)?;898899		CollectionPropertyPermissions::<T>::insert(id, token_props_permissions);900901		// Take a (non-refundable) deposit of collection creation902		{903			let mut imbalance =904				<<<T as Config>::Currency as Currency<T::AccountId>>::PositiveImbalance>::zero();905			imbalance.subsume(906				<<T as Config>::Currency as Currency<T::AccountId>>::deposit_creating(907					&T::TreasuryAccountId::get(),908					T::CollectionCreationPrice::get(),909				),910			);911			<T as Config>::Currency::settle(912				owner.as_sub(),913				imbalance,914				WithdrawReasons::TRANSFER,915				ExistenceRequirement::KeepAlive,916			)917			.map_err(|_| Error::<T>::NotSufficientFounds)?;918		}919920		<CreatedCollectionCount<T>>::put(created_count);921		<Pallet<T>>::deposit_event(Event::CollectionCreated(922			id,923			data.mode.id(),924			owner.as_sub().clone(),925		));926		<PalletEvm<T>>::deposit_log(927			erc::CollectionHelpersEvents::CollectionCreated {928				owner: *owner.as_eth(),929				collection_id: eth::collection_id_to_address(id),930			}931			.to_log(T::ContractAddress::get()),932		);933		<CollectionById<T>>::insert(id, collection);934		Ok(id)935	}936937	/// Destroy collection.938	///939	/// * `collection` - Collection handler.940	/// * `sender` - The owner or administrator of the collection.941	pub fn destroy_collection(942		collection: CollectionHandle<T>,943		sender: &T::CrossAccountId,944	) -> DispatchResult {945		ensure!(946			collection.limits.owner_can_destroy(),947			<Error<T>>::NoPermission,948		);949		collection.check_is_owner(sender)?;950951		let destroyed_collections = <DestroyedCollectionCount<T>>::get()952			.0953			.checked_add(1)954			.ok_or(ArithmeticError::Overflow)?;955956		// =========957958		<DestroyedCollectionCount<T>>::put(destroyed_collections);959		<CollectionById<T>>::remove(collection.id);960		<AdminAmount<T>>::remove(collection.id);961		<IsAdmin<T>>::remove_prefix((collection.id,), None);962		<Allowlist<T>>::remove_prefix((collection.id,), None);963		<CollectionProperties<T>>::remove(collection.id);964965		<Pallet<T>>::deposit_event(Event::CollectionDestroyed(collection.id));966		Ok(())967	}968969	/// Set collection property.970	///971	/// * `collection` - Collection handler.972	/// * `sender` - The owner or administrator of the collection.973	/// * `property` - The property to set.974	pub fn set_collection_property(975		collection: &CollectionHandle<T>,976		sender: &T::CrossAccountId,977		property: Property,978	) -> DispatchResult {979		collection.check_is_owner_or_admin(sender)?;980981		CollectionProperties::<T>::try_mutate(collection.id, |properties| {982			let property = property.clone();983			properties.try_set(property.key, property.value)984		})985		.map_err(<Error<T>>::from)?;986987		Self::deposit_event(Event::CollectionPropertySet(collection.id, property.key));988989		Ok(())990	}991992	/// Set scouped collection property.993	///994	/// * `collection_id` - ID of the collection for which the property is being set.995	/// * `scope` - Property scope.996	/// * `property` - The property to set.997	pub fn set_scoped_collection_property(998		collection_id: CollectionId,999		scope: PropertyScope,1000		property: Property,1001	) -> DispatchResult {1002		CollectionProperties::<T>::try_mutate(collection_id, |properties| {1003			properties.try_scoped_set(scope, property.key, property.value)1004		})1005		.map_err(<Error<T>>::from)?;10061007		Ok(())1008	}10091010	/// Set scouped collection properties.1011	///1012	/// * `collection_id` - ID of the collection for which the properties is being set.1013	/// * `scope` - Property scope.1014	/// * `properties` - The properties to set.1015	pub fn set_scoped_collection_properties(1016		collection_id: CollectionId,1017		scope: PropertyScope,1018		properties: impl Iterator<Item = Property>,1019	) -> DispatchResult {1020		CollectionProperties::<T>::try_mutate(collection_id, |stored_properties| {1021			stored_properties.try_scoped_set_from_iter(scope, properties)1022		})1023		.map_err(<Error<T>>::from)?;10241025		Ok(())1026	}10271028	/// Set collection properties.1029	///1030	/// * `collection` - Collection handler.1031	/// * `sender` - The owner or administrator of the collection.1032	/// * `properties` - The properties to set.1033	#[transactional]1034	pub fn set_collection_properties(1035		collection: &CollectionHandle<T>,1036		sender: &T::CrossAccountId,1037		properties: Vec<Property>,1038	) -> DispatchResult {1039		for property in properties {1040			Self::set_collection_property(collection, sender, property)?;1041		}10421043		Ok(())1044	}10451046	/// Delete collection property.1047	///1048	/// * `collection` - Collection handler.1049	/// * `sender` - The owner or administrator of the collection.1050	/// * `property` - The property to delete.1051	pub fn delete_collection_property(1052		collection: &CollectionHandle<T>,1053		sender: &T::CrossAccountId,1054		property_key: PropertyKey,1055	) -> DispatchResult {1056		collection.check_is_owner_or_admin(sender)?;10571058		CollectionProperties::<T>::try_mutate(collection.id, |properties| {1059			properties.remove(&property_key)1060		})1061		.map_err(<Error<T>>::from)?;10621063		Self::deposit_event(Event::CollectionPropertyDeleted(1064			collection.id,1065			property_key,1066		));10671068		Ok(())1069	}10701071	/// Delete collection properties.1072	///1073	/// * `collection` - Collection handler.1074	/// * `sender` - The owner or administrator of the collection.1075	/// * `properties` - The properties to delete.1076	#[transactional]1077	pub fn delete_collection_properties(1078		collection: &CollectionHandle<T>,1079		sender: &T::CrossAccountId,1080		property_keys: Vec<PropertyKey>,1081	) -> DispatchResult {1082		for key in property_keys {1083			Self::delete_collection_property(collection, sender, key)?;1084		}10851086		Ok(())1087	}10881089	/// Set collection propetry permission without any checks.1090	///1091	/// Used for migrations.1092	///1093	/// * `collection` - Collection handler.1094	/// * `property_permissions` - Property permissions.1095	pub fn set_property_permission_unchecked(1096		collection: CollectionId,1097		property_permission: PropertyKeyPermission,1098	) -> DispatchResult {1099		<CollectionPropertyPermissions<T>>::try_mutate(collection, |permissions| {1100			permissions.try_set(property_permission.key, property_permission.permission)1101		})1102		.map_err(<Error<T>>::from)?;1103		Ok(())1104	}11051106	/// Set collection property permission.1107	///1108	/// * `collection` - Collection handler.1109	/// * `sender` - The owner or administrator of the collection.1110	/// * `property_permission` - Property permission.1111	pub fn set_property_permission(1112		collection: &CollectionHandle<T>,1113		sender: &T::CrossAccountId,1114		property_permission: PropertyKeyPermission,1115	) -> DispatchResult {1116		Self::set_scoped_property_permission(1117			collection,1118			sender,1119			PropertyScope::None,1120			property_permission,1121		)1122	}11231124	/// Set collection property permission with scope.1125	///1126	/// * `collection` - Collection handler.1127	/// * `sender` - The owner or administrator of the collection.1128	/// * `scope` - Property scope.1129	/// * `property_permission` - Property permission.1130	pub fn set_scoped_property_permission(1131		collection: &CollectionHandle<T>,1132		sender: &T::CrossAccountId,1133		scope: PropertyScope,1134		property_permission: PropertyKeyPermission,1135	) -> DispatchResult {1136		collection.check_is_owner_or_admin(sender)?;11371138		let all_permissions = CollectionPropertyPermissions::<T>::get(collection.id);1139		let current_permission = all_permissions.get(&property_permission.key);1140		if matches![1141			current_permission,1142			Some(PropertyPermission { mutable: false, .. })1143		] {1144			return Err(<Error<T>>::NoPermission.into());1145		}11461147		CollectionPropertyPermissions::<T>::try_mutate(collection.id, |permissions| {1148			let property_permission = property_permission.clone();1149			permissions.try_scoped_set(1150				scope,1151				property_permission.key,1152				property_permission.permission,1153			)1154		})1155		.map_err(<Error<T>>::from)?;11561157		Self::deposit_event(Event::PropertyPermissionSet(1158			collection.id,1159			property_permission.key,1160		));11611162		Ok(())1163	}11641165	/// Set token property permission.1166	///1167	/// * `collection` - Collection handler.1168	/// * `sender` - The owner or administrator of the collection.1169	/// * `property_permissions` - Property permissions.1170	#[transactional]1171	pub fn set_token_property_permissions(1172		collection: &CollectionHandle<T>,1173		sender: &T::CrossAccountId,1174		property_permissions: Vec<PropertyKeyPermission>,1175	) -> DispatchResult {1176		Self::set_scoped_token_property_permissions(1177			collection,1178			sender,1179			PropertyScope::None,1180			property_permissions,1181		)1182	}11831184	/// Set token property permission with scope.1185	///1186	/// * `collection` - Collection handler.1187	/// * `sender` - The owner or administrator of the collection.1188	/// * `scope` - Property scope.1189	/// * `property_permissions` - Property permissions.1190	#[transactional]1191	pub fn set_scoped_token_property_permissions(1192		collection: &CollectionHandle<T>,1193		sender: &T::CrossAccountId,1194		scope: PropertyScope,1195		property_permissions: Vec<PropertyKeyPermission>,1196	) -> DispatchResult {1197		for prop_pemission in property_permissions {1198			Self::set_scoped_property_permission(collection, sender, scope, prop_pemission)?;1199		}12001201		Ok(())1202	}12031204	/// Get collection property.1205	pub fn get_collection_property(1206		collection_id: CollectionId,1207		key: &PropertyKey,1208	) -> Option<PropertyValue> {1209		Self::collection_properties(collection_id).get(key).cloned()1210	}12111212	/// Convert byte vector to property key vector.1213	pub fn bytes_keys_to_property_keys(1214		keys: Vec<Vec<u8>>,1215	) -> Result<Vec<PropertyKey>, DispatchError> {1216		keys.into_iter()1217			.map(|key| -> Result<PropertyKey, DispatchError> {1218				key.try_into()1219					.map_err(|_| <Error<T>>::PropertyKeyIsTooLong.into())1220			})1221			.collect::<Result<Vec<PropertyKey>, DispatchError>>()1222	}12231224	/// Get properties according to given keys.1225	pub fn filter_collection_properties(1226		collection_id: CollectionId,1227		keys: Option<Vec<PropertyKey>>,1228	) -> Result<Vec<Property>, DispatchError> {1229		let properties = Self::collection_properties(collection_id);12301231		let properties = keys1232			.map(|keys| {1233				keys.into_iter()1234					.filter_map(|key| {1235						properties.get(&key).map(|value| Property {1236							key,1237							value: value.clone(),1238						})1239					})1240					.collect()1241			})1242			.unwrap_or_else(|| {1243				properties1244					.into_iter()1245					.map(|(key, value)| Property { key, value })1246					.collect()1247			});12481249		Ok(properties)1250	}12511252	/// Get property permissions according to given keys.1253	pub fn filter_property_permissions(1254		collection_id: CollectionId,1255		keys: Option<Vec<PropertyKey>>,1256	) -> Result<Vec<PropertyKeyPermission>, DispatchError> {1257		let permissions = Self::property_permissions(collection_id);12581259		let key_permissions = keys1260			.map(|keys| {1261				keys.into_iter()1262					.filter_map(|key| {1263						permissions1264							.get(&key)1265							.map(|permission| PropertyKeyPermission {1266								key,1267								permission: permission.clone(),1268							})1269					})1270					.collect()1271			})1272			.unwrap_or_else(|| {1273				permissions1274					.into_iter()1275					.map(|(key, permission)| PropertyKeyPermission { key, permission })1276					.collect()1277			});12781279		Ok(key_permissions)1280	}12811282	/// Toggle `user` participation in the `collection`'s allow list.1283	pub fn toggle_allowlist(1284		collection: &CollectionHandle<T>,1285		sender: &T::CrossAccountId,1286		user: &T::CrossAccountId,1287		allowed: bool,1288	) -> DispatchResult {1289		collection.check_is_owner_or_admin(sender)?;12901291		// =========12921293		if allowed {1294			<Allowlist<T>>::insert((collection.id, user), true);1295		} else {1296			<Allowlist<T>>::remove((collection.id, user));1297		}12981299		Ok(())1300	}13011302	/// Toggle `user` participation in the `collection`'s admin list.1303	pub fn toggle_admin(1304		collection: &CollectionHandle<T>,1305		sender: &T::CrossAccountId,1306		user: &T::CrossAccountId,1307		admin: bool,1308	) -> DispatchResult {1309		collection.check_is_owner(sender)?;13101311		let was_admin = <IsAdmin<T>>::get((collection.id, user));1312		if was_admin == admin {1313			return Ok(());1314		}1315		let amount = <AdminAmount<T>>::get(collection.id);13161317		if admin {1318			let amount = amount1319				.checked_add(1)1320				.ok_or(<Error<T>>::CollectionAdminCountExceeded)?;1321			ensure!(1322				amount <= Self::collection_admins_limit(),1323				<Error<T>>::CollectionAdminCountExceeded,1324			);13251326			// =========13271328			<AdminAmount<T>>::insert(collection.id, amount);1329			<IsAdmin<T>>::insert((collection.id, user), true);1330		} else {1331			<AdminAmount<T>>::insert(collection.id, amount.saturating_sub(1));1332			<IsAdmin<T>>::remove((collection.id, user));1333		}13341335		Ok(())1336	}13371338	/// Merge set fields from `new_limit` to `old_limit`.1339	pub fn clamp_limits(1340		mode: CollectionMode,1341		old_limit: &CollectionLimits,1342		mut new_limit: CollectionLimits,1343	) -> Result<CollectionLimits, DispatchError> {1344		let limits = old_limit;1345		limit_default!(old_limit, new_limit,1346			account_token_ownership_limit => ensure!(1347				new_limit <= MAX_TOKEN_OWNERSHIP,1348				<Error<T>>::CollectionLimitBoundsExceeded,1349			),1350			sponsored_data_size => ensure!(1351				new_limit <= CUSTOM_DATA_LIMIT,1352				<Error<T>>::CollectionLimitBoundsExceeded,1353			),13541355			sponsored_data_rate_limit => {},1356			token_limit => ensure!(1357				old_limit >= new_limit && new_limit > 0,1358				<Error<T>>::CollectionTokenLimitExceeded1359			),13601361			sponsor_transfer_timeout(match mode {1362				CollectionMode::NFT => NFT_SPONSOR_TRANSFER_TIMEOUT,1363				CollectionMode::Fungible(_) => FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,1364				CollectionMode::ReFungible => REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,1365			}) => ensure!(1366				new_limit <= MAX_SPONSOR_TIMEOUT,1367				<Error<T>>::CollectionLimitBoundsExceeded,1368			),1369			sponsor_approve_timeout => {},1370			owner_can_transfer => ensure!(1371				!limits.owner_can_transfer_instaled() ||1372				old_limit || !new_limit,1373				<Error<T>>::OwnerPermissionsCantBeReverted,1374			),1375			owner_can_destroy => ensure!(1376				old_limit || !new_limit,1377				<Error<T>>::OwnerPermissionsCantBeReverted,1378			),1379			transfers_enabled => {},1380		);1381		Ok(new_limit)1382	}13831384	/// Merge set fields from `new_permission` to `old_permission`.1385	pub fn clamp_permissions(1386		_mode: CollectionMode,1387		old_permission: &CollectionPermissions,1388		mut new_permission: CollectionPermissions,1389	) -> Result<CollectionPermissions, DispatchError> {1390		limit_default_clone!(old_permission, new_permission,1391			access => {},1392			mint_mode => {},1393			nesting => { /* todo check for permissive, if only it gets out of benchmarks */ },1394		);1395		Ok(new_permission)1396	}1397}13981399/// Indicates unsupported methods by returning [Error::UnsupportedOperation].1400#[macro_export]1401macro_rules! unsupported {1402	($runtime:path) => {1403		Err($crate::Error::<$runtime>::UnsupportedOperation.into())1404	};1405}14061407/// Return weights for various worst-case operations.1408pub trait CommonWeightInfo<CrossAccountId> {1409	/// Weight of item creation.1410	fn create_item() -> Weight;14111412	/// Weight of items creation.1413	fn create_multiple_items(amount: &[CreateItemData]) -> Weight;14141415	/// Weight of items creation.1416	fn create_multiple_items_ex(cost: &CreateItemExData<CrossAccountId>) -> Weight;14171418	/// The weight of the burning item.1419	fn burn_item() -> Weight;14201421	/// Property setting weight.1422	///1423	/// * `amount`- The number of properties to set.1424	fn set_collection_properties(amount: u32) -> Weight;14251426	/// Collection property deletion weight.1427	///1428	/// * `amount`- The number of properties to set.1429	fn delete_collection_properties(amount: u32) -> Weight;14301431	/// Token property setting weight.1432	///1433	/// * `amount`- The number of properties to set.1434	fn set_token_properties(amount: u32) -> Weight;14351436	/// Token property deletion weight.1437	///1438	/// * `amount`- The number of properties to delete.1439	fn delete_token_properties(amount: u32) -> Weight;14401441	/// Token property permissions set weight.1442	///1443	/// * `amount`- The number of property permissions to set.1444	fn set_token_property_permissions(amount: u32) -> Weight;14451446	/// Transfer price of the token or its parts.1447	fn transfer() -> Weight;14481449	/// The price of setting the permission of the operation from another user.1450	fn approve() -> Weight;14511452	/// Transfer price from another user.1453	fn transfer_from() -> Weight;14541455	/// The price of burning a token from another user.1456	fn burn_from() -> Weight;14571458	/// Differs from burn_item in case of Fungible and Refungible, as it should burn1459	/// whole users's balance.1460	///1461	/// This method shouldn't be used directly, as it doesn't count breadth price, use [burn_recursively](CommonWeightInfo::burn_recursively) instead1462	fn burn_recursively_self_raw() -> Weight;14631464	/// Cost of iterating over `amount` children while burning, without counting child burning itself.1465	///1466	/// This method shouldn't be used directly, as it doesn't count depth price, use [burn_recursively](CommonWeightInfo::burn_recursively) instead1467	fn burn_recursively_breadth_raw(amount: u32) -> Weight;14681469	/// The price of recursive burning a token.1470	///1471	/// `max_selfs` - The maximum burning weight of the token itself.1472	/// `max_breadth` - The maximum number of nested tokens to burn.1473	fn burn_recursively(max_selfs: u32, max_breadth: u32) -> Weight {1474		Self::burn_recursively_self_raw()1475			.saturating_mul(max_selfs.max(1) as u64)1476			.saturating_add(Self::burn_recursively_breadth_raw(max_breadth))1477	}14781479	/// The price of retrieving token owner1480	fn token_owner() -> Weight;1481}14821483/// Weight info extension trait for refungible pallet.1484pub trait RefungibleExtensionsWeightInfo {1485	/// Weight of token repartition.1486	fn repartition() -> Weight;1487}14881489/// Common collection operations.1490///1491/// It wraps methods in Fungible, Nonfungible and Refungible pallets1492/// and adds weight info.1493pub trait CommonCollectionOperations<T: Config> {1494	/// Create token.1495	///1496	/// * `sender` - The user who mint the token and pays for the transaction.1497	/// * `to` - The user who will own the token.1498	/// * `data` - Token data.1499	/// * `nesting_budget` - A budget that can be spent on nesting tokens.1500	fn create_item(1501		&self,1502		sender: T::CrossAccountId,1503		to: T::CrossAccountId,1504		data: CreateItemData,1505		nesting_budget: &dyn Budget,1506	) -> DispatchResultWithPostInfo;15071508	/// Create multiple tokens.1509	///1510	/// * `sender` - The user who mint the token and pays for the transaction.1511	/// * `to` - The user who will own the token.1512	/// * `data` - Token data.1513	/// * `nesting_budget` - A budget that can be spent on nesting tokens.1514	fn create_multiple_items(1515		&self,1516		sender: T::CrossAccountId,1517		to: T::CrossAccountId,1518		data: Vec<CreateItemData>,1519		nesting_budget: &dyn Budget,1520	) -> DispatchResultWithPostInfo;15211522	/// Create multiple tokens.1523	///1524	/// * `sender` - The user who mint the token and pays for the transaction.1525	/// * `to` - The user who will own the token.1526	/// * `data` - Token data.1527	/// * `nesting_budget` - A budget that can be spent on nesting tokens.1528	fn create_multiple_items_ex(1529		&self,1530		sender: T::CrossAccountId,1531		data: CreateItemExData<T::CrossAccountId>,1532		nesting_budget: &dyn Budget,1533	) -> DispatchResultWithPostInfo;15341535	/// Burn token.1536	///1537	/// * `sender` - The user who owns the token.1538	/// * `token` - Token id that will burned.1539	/// * `amount` - The number of parts of the token that will be burned.1540	fn burn_item(1541		&self,1542		sender: T::CrossAccountId,1543		token: TokenId,1544		amount: u128,1545	) -> DispatchResultWithPostInfo;15461547	/// Burn token and all nested tokens recursievly.1548	///1549	/// * `sender` - The user who owns the token.1550	/// * `token` - Token id that will burned.1551	/// * `self_budget` - The budget that can be spent on burning tokens.1552	/// * `breadth_budget` - The budget that can be spent on burning nested tokens.1553	fn burn_item_recursively(1554		&self,1555		sender: T::CrossAccountId,1556		token: TokenId,1557		self_budget: &dyn Budget,1558		breadth_budget: &dyn Budget,1559	) -> DispatchResultWithPostInfo;15601561	/// Set collection properties.1562	///1563	/// * `sender` - Must be either the owner of the collection or its admin.1564	/// * `properties` - Properties to be set.1565	fn set_collection_properties(1566		&self,1567		sender: T::CrossAccountId,1568		properties: Vec<Property>,1569	) -> DispatchResultWithPostInfo;15701571	/// Delete collection properties.1572	///1573	/// * `sender` - Must be either the owner of the collection or its admin.1574	/// * `properties` - The properties to be removed.1575	fn delete_collection_properties(1576		&self,1577		sender: &T::CrossAccountId,1578		property_keys: Vec<PropertyKey>,1579	) -> DispatchResultWithPostInfo;15801581	/// Set token properties.1582	///1583	/// The appropriate [`PropertyPermission`] for the token property1584	/// must be set with [`Self::set_token_property_permissions`].1585	///1586	/// * `sender` - Must be either the owner of the token or its admin.1587	/// * `token_id` - The token for which the properties are being set.1588	/// * `properties` - Properties to be set.1589	/// * `budget` - Budget for setting properties.1590	fn set_token_properties(1591		&self,1592		sender: T::CrossAccountId,1593		token_id: TokenId,1594		properties: Vec<Property>,1595		budget: &dyn Budget,1596	) -> DispatchResultWithPostInfo;15971598	/// Remove token properties.1599	///1600	/// The appropriate [`PropertyPermission`] for the token property1601	/// must be set with [`Self::set_token_property_permissions`].1602	///1603	/// * `sender` - Must be either the owner of the token or its admin.1604	/// * `token_id` - The token for which the properties are being remove.1605	/// * `property_keys` - Keys to remove corresponding properties.1606	/// * `budget` - Budget for removing properties.1607	fn delete_token_properties(1608		&self,1609		sender: T::CrossAccountId,1610		token_id: TokenId,1611		property_keys: Vec<PropertyKey>,1612		budget: &dyn Budget,1613	) -> DispatchResultWithPostInfo;16141615	/// Set token property permissions.1616	///1617	/// * `sender` - Must be either the owner of the token or its admin.1618	/// * `token_id` - The token for which the properties are being set.1619	/// * `property_permissions` - Property permissions to be set.1620	/// * `budget` - Budget for setting properties.1621	fn set_token_property_permissions(1622		&self,1623		sender: &T::CrossAccountId,1624		property_permissions: Vec<PropertyKeyPermission>,1625	) -> DispatchResultWithPostInfo;16261627	/// Transfer amount of token pieces.1628	///1629	/// * `sender` - Donor user.1630	/// * `to` - Recepient user.1631	/// * `token` - The token of which parts are being sent.1632	/// * `amount` - The number of parts of the token that will be transferred.1633	/// * `budget` - The maximum budget that can be spent on the transfer.1634	fn transfer(1635		&self,1636		sender: T::CrossAccountId,1637		to: T::CrossAccountId,1638		token: TokenId,1639		amount: u128,1640		budget: &dyn Budget,1641	) -> DispatchResultWithPostInfo;16421643	/// Grant access to another account to transfer parts of the token owned by the calling user via [Self::transfer_from].1644	///1645	/// * `sender` - The user who grants access to the token.1646	/// * `spender` - The user to whom the rights are granted.1647	/// * `token` - The token to which access is granted.1648	/// * `amount` - The amount of pieces that another user can dispose of.1649	fn approve(1650		&self,1651		sender: T::CrossAccountId,1652		spender: T::CrossAccountId,1653		token: TokenId,1654		amount: u128,1655	) -> DispatchResultWithPostInfo;16561657	/// Send parts of a token owned by another user.1658	///1659	/// Before calling this method, you must grant rights to the calling user via [`Self::approve`].1660	///1661	/// * `sender` - The user who must have access to the token (see [`Self::approve`]).1662	/// * `from` - The user who owns the token.1663	/// * `to` - Recepient user.1664	/// * `token` - The token of which parts are being sent.1665	/// * `amount` - The number of parts of the token that will be transferred.1666	/// * `budget` - The maximum budget that can be spent on the transfer.1667	fn transfer_from(1668		&self,1669		sender: T::CrossAccountId,1670		from: T::CrossAccountId,1671		to: T::CrossAccountId,1672		token: TokenId,1673		amount: u128,1674		budget: &dyn Budget,1675	) -> DispatchResultWithPostInfo;16761677	/// Burn parts of a token owned by another user.1678	///1679	/// Before calling this method, you must grant rights to the calling user via [`Self::approve`].1680	///1681	/// * `sender` - The user who must have access to the token (see [`Self::approve`]).1682	/// * `from` - The user who owns the token.1683	/// * `token` - The token of which parts are being sent.1684	/// * `amount` - The number of parts of the token that will be transferred.1685	/// * `budget` - The maximum budget that can be spent on the burn.1686	fn burn_from(1687		&self,1688		sender: T::CrossAccountId,1689		from: T::CrossAccountId,1690		token: TokenId,1691		amount: u128,1692		budget: &dyn Budget,1693	) -> DispatchResultWithPostInfo;16941695	/// Check permission to nest token.1696	///1697	/// * `sender` - The user who initiated the check.1698	/// * `from` - The token that is checked for embedding.1699	/// * `under` - Token under which to check.1700	/// * `budget` - The maximum budget that can be spent on the check.1701	fn check_nesting(1702		&self,1703		sender: T::CrossAccountId,1704		from: (CollectionId, TokenId),1705		under: TokenId,1706		budget: &dyn Budget,1707	) -> DispatchResult;17081709	/// Nest one token into another.1710	///1711	/// * `under` - Token holder.1712	/// * `to_nest` - Nested token.1713	fn nest(&self, under: TokenId, to_nest: (CollectionId, TokenId));17141715	/// Unnest token.1716	///1717	/// * `under` - Token holder.1718	/// * `to_nest` - Token to unnest.1719	fn unnest(&self, under: TokenId, to_nest: (CollectionId, TokenId));17201721	/// Get all user tokens.1722	///1723	/// * `account` - Account for which you need to get tokens.1724	fn account_tokens(&self, account: T::CrossAccountId) -> Vec<TokenId>;17251726	/// Get all the tokens in the collection.1727	fn collection_tokens(&self) -> Vec<TokenId>;17281729	/// Check if the token exists.1730	///1731	/// * `token` - Id token to check.1732	fn token_exists(&self, token: TokenId) -> bool;17331734	/// Get the id of the last minted token.1735	fn last_token_id(&self) -> TokenId;17361737	/// Get the owner of the token.1738	///1739	/// * `token` - The token for which you need to find out the owner.1740	fn token_owner(&self, token: TokenId) -> Option<T::CrossAccountId>;17411742	/// Returns 10 tokens owners in no particular order.1743	///1744	/// * `token` - The token for which you need to find out the owners.1745	fn token_owners(&self, token: TokenId) -> Vec<T::CrossAccountId>;17461747	/// Get the value of the token property by key.1748	///1749	/// * `token` - Token with the property to get.1750	/// * `key` - Property name.1751	fn token_property(&self, token_id: TokenId, key: &PropertyKey) -> Option<PropertyValue>;17521753	/// Get a set of token properties by key vector.1754	///1755	/// * `token` - Token with the property to get.1756	/// * `keys` - Vector of property keys. If this parameter is [None](sp_std::result::Result),1757	/// then all properties are returned.1758	fn token_properties(&self, token: TokenId, keys: Option<Vec<PropertyKey>>) -> Vec<Property>;17591760	/// Amount of unique collection tokens1761	fn total_supply(&self) -> u32;17621763	/// Amount of different tokens account has.1764	///1765	/// * `account` - The account for which need to get the balance.1766	fn account_balance(&self, account: T::CrossAccountId) -> u32;17671768	/// Amount of specific token account have.1769	fn balance(&self, account: T::CrossAccountId, token: TokenId) -> u128;17701771	/// Amount of token pieces1772	fn total_pieces(&self, token: TokenId) -> Option<u128>;17731774	/// Get the number of parts of the token that a trusted user can manage.1775	///1776	/// * `sender` - Trusted user.1777	/// * `spender` - Owner of the token.1778	/// * `token` - The token for which to get the value.1779	fn allowance(1780		&self,1781		sender: T::CrossAccountId,1782		spender: T::CrossAccountId,1783		token: TokenId,1784	) -> u128;17851786	/// Get extension for RFT collection.1787	fn refungible_extensions(&self) -> Option<&dyn RefungibleExtensions<T>>;1788}17891790/// Extension for RFT collection.1791pub trait RefungibleExtensions<T>1792where1793	T: Config,1794{1795	/// Change the number of parts of the token.1796	///1797	/// When the value changes down, this function is equivalent to burning parts of the token.1798	///1799	/// * `sender` - The user calling the repartition operation. Must be the owner of the token.1800	/// * `token` - The token for which you want to change the number of parts.1801	/// * `amount` - The new value of the parts of the token.1802	fn repartition(1803		&self,1804		sender: &T::CrossAccountId,1805		token: TokenId,1806		amount: u128,1807	) -> DispatchResultWithPostInfo;1808}18091810/// Merge [`DispatchResult`] with [`Weight`] into [`DispatchResultWithPostInfo`].1811///1812/// Used for [`CommonCollectionOperations`] implementations and flexible enough to do so.1813pub fn with_weight(res: DispatchResult, weight: Weight) -> DispatchResultWithPostInfo {1814	let post_info = PostDispatchInfo {1815		actual_weight: Some(weight),1816		pays_fee: Pays::Yes,1817	};1818	match res {1819		Ok(()) => Ok(post_info),1820		Err(error) => Err(DispatchErrorWithPostInfo { post_info, error }),1821	}1822}18231824impl<T: Config> From<PropertiesError> for Error<T> {1825	fn from(error: PropertiesError) -> Self {1826		match error {1827			PropertiesError::NoSpaceForProperty => Self::NoSpaceForProperty,1828			PropertiesError::PropertyLimitReached => Self::PropertyLimitReached,1829			PropertiesError::InvalidCharacterInPropertyKey => Self::InvalidCharacterInPropertyKey,1830			PropertiesError::PropertyKeyIsTooLong => Self::PropertyKeyIsTooLong,1831			PropertiesError::EmptyPropertyKey => Self::EmptyPropertyKey,1832		}1833	}1834}
modifiedpallets/fungible/src/common.rsdiffbeforeafterboth
--- a/pallets/fungible/src/common.rs
+++ b/pallets/fungible/src/common.rs
@@ -103,6 +103,10 @@
 		// Fungible tokens can't have children
 		0
 	}
+
+	fn token_owner() -> Weight {
+		0
+	}
 }
 
 /// Implementation of `CommonCollectionOperations` for `FungibleHandle`. It wraps FungibleHandle Pallete
modifiedpallets/fungible/src/stubs/UniqueFungible.rawdiffbeforeafterboth

binary blob — no preview

modifiedpallets/fungible/src/stubs/UniqueFungible.soldiffbeforeafterboth
--- a/pallets/fungible/src/stubs/UniqueFungible.sol
+++ b/pallets/fungible/src/stubs/UniqueFungible.sol
@@ -31,19 +31,7 @@
 	);
 }
 
-// Selector: 79cc6790
-contract ERC20UniqueExtensions is Dummy, ERC165 {
-	// Selector: burnFrom(address,uint256) 79cc6790
-	function burnFrom(address from, uint256 amount) public returns (bool) {
-		require(false, stub_error);
-		from;
-		amount;
-		dummy = 0;
-		return false;
-	}
-}
-
-// Selector: 7d9262e6
+// Selector: 6cf113cd
 contract Collection is Dummy, ERC165 {
 	// Set collection property.
 	//
@@ -268,6 +256,42 @@
 		mode;
 		dummy = 0;
 	}
+
+	// Check that account is the owner or admin of the collection
+	//
+	// @param user account to verify
+	// @return "true" if account is the owner or admin
+	//
+	// Selector: verifyOwnerOrAdmin(address) c2282493
+	function verifyOwnerOrAdmin(address user) public view returns (bool) {
+		require(false, stub_error);
+		user;
+		dummy;
+		return false;
+	}
+
+	// Returns collection type
+	//
+	// @return `Fungible` or `NFT` or `ReFungible`
+	//
+	// Selector: uniqueCollectionType() d34b55b8
+	function uniqueCollectionType() public returns (string memory) {
+		require(false, stub_error);
+		dummy = 0;
+		return "";
+	}
+}
+
+// Selector: 79cc6790
+contract ERC20UniqueExtensions is Dummy, ERC165 {
+	// Selector: burnFrom(address,uint256) 79cc6790
+	function burnFrom(address from, uint256 amount) public returns (bool) {
+		require(false, stub_error);
+		from;
+		amount;
+		dummy = 0;
+		return false;
+	}
 }
 
 // Selector: 942e8b22
modifiedpallets/nonfungible/src/benchmarking.rsdiffbeforeafterboth
--- a/pallets/nonfungible/src/benchmarking.rs
+++ b/pallets/nonfungible/src/benchmarking.rs
@@ -17,11 +17,14 @@
 use super::*;
 use crate::{Pallet, Config, NonfungibleHandle};
 
-use sp_std::prelude::*;
-use pallet_common::benchmarking::{create_collection_raw, property_key, property_value};
 use frame_benchmarking::{benchmarks, account};
+use pallet_common::{
+	bench_init,
+	benchmarking::{create_collection_raw, property_key, property_value},
+	CommonCollectionOperations,
+};
+use sp_std::prelude::*;
 use up_data_structs::{CollectionMode, MAX_ITEMS_PER_BATCH, MAX_PROPERTIES_PER_ITEM, budget::Unlimited};
-use pallet_common::bench_init;
 
 const SEED: u32 = 1;
 
@@ -208,4 +211,13 @@
 		<Pallet<T>>::set_token_properties(&collection, &owner, item, props.into_iter(), false, &Unlimited)?;
 		let to_delete = (0..b).map(|k| property_key(k as usize)).collect::<Vec<_>>();
 	}: {<Pallet<T>>::delete_token_properties(&collection, &owner, item, to_delete.into_iter(), &Unlimited)?}
+
+	token_owner {
+		bench_init!{
+			owner: sub; collection: collection(owner);
+			owner: cross_from_sub;
+		};
+		let item = create_max_item(&collection, &owner, owner.clone())?;
+
+	}: {collection.token_owner(item)}
 }
modifiedpallets/nonfungible/src/common.rsdiffbeforeafterboth
--- a/pallets/nonfungible/src/common.rs
+++ b/pallets/nonfungible/src/common.rs
@@ -118,6 +118,10 @@
 		<SelfWeightOf<T>>::burn_recursively_breadth_plus_self_plus_self_per_each_raw(amount)
 			.saturating_sub(Self::burn_recursively_self_raw().saturating_mul(amount as u64 + 1))
 	}
+
+	fn token_owner() -> Weight {
+		<SelfWeightOf<T>>::token_owner()
+	}
 }
 
 fn map_create_data<T: Config>(
modifiedpallets/nonfungible/src/lib.rsdiffbeforeafterboth
--- a/pallets/nonfungible/src/lib.rs
+++ b/pallets/nonfungible/src/lib.rs
@@ -784,6 +784,23 @@
 		<PalletCommon<T>>::set_token_property_permissions(collection, sender, property_permissions)
 	}
 
+	/// Set property permissions for the token with scope.
+	///
+	/// Sender should be the owner or admin of token's collection.
+	pub fn set_scoped_token_property_permissions(
+		collection: &CollectionHandle<T>,
+		sender: &T::CrossAccountId,
+		scope: PropertyScope,
+		property_permissions: Vec<PropertyKeyPermission>,
+	) -> DispatchResult {
+		<PalletCommon<T>>::set_scoped_token_property_permissions(
+			collection,
+			sender,
+			scope,
+			property_permissions,
+		)
+	}
+
 	/// Set property permissions for the collection.
 	///
 	/// Sender should be the owner or admin of the collection.
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
@@ -373,49 +373,7 @@
 	}
 }
 
-// Selector: 780e9d63
-contract ERC721Enumerable is Dummy, ERC165 {
-	// @notice Enumerate valid NFTs
-	// @param index A counter less than `totalSupply()`
-	// @return The token identifier for the `index`th NFT,
-	//  (sort order not specified)
-	//
-	// Selector: tokenByIndex(uint256) 4f6ccce7
-	function tokenByIndex(uint256 index) public view returns (uint256) {
-		require(false, stub_error);
-		index;
-		dummy;
-		return 0;
-	}
-
-	// @dev Not implemented
-	//
-	// Selector: tokenOfOwnerByIndex(address,uint256) 2f745c59
-	function tokenOfOwnerByIndex(address owner, uint256 index)
-		public
-		view
-		returns (uint256)
-	{
-		require(false, stub_error);
-		owner;
-		index;
-		dummy;
-		return 0;
-	}
-
-	// @notice Count NFTs tracked by this contract
-	// @return A count of valid NFTs tracked by this contract, where each one of
-	//  them has an assigned and queryable owner not equal to the zero address
-	//
-	// Selector: totalSupply() 18160ddd
-	function totalSupply() public view returns (uint256) {
-		require(false, stub_error);
-		dummy;
-		return 0;
-	}
-}
-
-// Selector: 7d9262e6
+// Selector: 6cf113cd
 contract Collection is Dummy, ERC165 {
 	// Set collection property.
 	//
@@ -640,6 +598,72 @@
 		mode;
 		dummy = 0;
 	}
+
+	// Check that account is the owner or admin of the collection
+	//
+	// @param user account to verify
+	// @return "true" if account is the owner or admin
+	//
+	// Selector: verifyOwnerOrAdmin(address) c2282493
+	function verifyOwnerOrAdmin(address user) public view returns (bool) {
+		require(false, stub_error);
+		user;
+		dummy;
+		return false;
+	}
+
+	// Returns collection type
+	//
+	// @return `Fungible` or `NFT` or `ReFungible`
+	//
+	// Selector: uniqueCollectionType() d34b55b8
+	function uniqueCollectionType() public returns (string memory) {
+		require(false, stub_error);
+		dummy = 0;
+		return "";
+	}
+}
+
+// Selector: 780e9d63
+contract ERC721Enumerable is Dummy, ERC165 {
+	// @notice Enumerate valid NFTs
+	// @param index A counter less than `totalSupply()`
+	// @return The token identifier for the `index`th NFT,
+	//  (sort order not specified)
+	//
+	// Selector: tokenByIndex(uint256) 4f6ccce7
+	function tokenByIndex(uint256 index) public view returns (uint256) {
+		require(false, stub_error);
+		index;
+		dummy;
+		return 0;
+	}
+
+	// @dev Not implemented
+	//
+	// Selector: tokenOfOwnerByIndex(address,uint256) 2f745c59
+	function tokenOfOwnerByIndex(address owner, uint256 index)
+		public
+		view
+		returns (uint256)
+	{
+		require(false, stub_error);
+		owner;
+		index;
+		dummy;
+		return 0;
+	}
+
+	// @notice Count NFTs tracked by this contract
+	// @return A count of valid NFTs tracked by this contract, where each one of
+	//  them has an assigned and queryable owner not equal to the zero address
+	//
+	// Selector: totalSupply() 18160ddd
+	function totalSupply() public view returns (uint256) {
+		require(false, stub_error);
+		dummy;
+		return 0;
+	}
 }
 
 // Selector: d74d154f
modifiedpallets/nonfungible/src/weights.rsdiffbeforeafterboth
--- a/pallets/nonfungible/src/weights.rs
+++ b/pallets/nonfungible/src/weights.rs
@@ -3,7 +3,7 @@
 //! Autogenerated weights for pallet_nonfungible
 //!
 //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev
-//! DATE: 2022-07-20, STEPS: `50`, REPEAT: 80, LOW RANGE: `[]`, HIGH RANGE: `[]`
+//! DATE: 2022-08-01, STEPS: `50`, REPEAT: 80, LOW RANGE: `[]`, HIGH RANGE: `[]`
 //! EXECUTION: None, WASM-EXECUTION: Compiled, CHAIN: None, DB CACHE: 1024
 
 // Executed Command:
@@ -46,6 +46,7 @@
 	fn set_token_property_permissions(b: u32, ) -> Weight;
 	fn set_token_properties(b: u32, ) -> Weight;
 	fn delete_token_properties(b: u32, ) -> Weight;
+	fn token_owner() -> Weight;
 }
 
 /// Weights for pallet_nonfungible using the Substrate node and recommended hardware.
@@ -56,7 +57,7 @@
 	// Storage: Nonfungible TokenData (r:0 w:1)
 	// Storage: Nonfungible Owned (r:0 w:1)
 	fn create_item() -> Weight {
-		(20_328_000 as Weight)
+		(20_909_000 as Weight)
 			.saturating_add(T::DbWeight::get().reads(2 as Weight))
 			.saturating_add(T::DbWeight::get().writes(4 as Weight))
 	}
@@ -65,9 +66,9 @@
 	// Storage: Nonfungible TokenData (r:0 w:4)
 	// Storage: Nonfungible Owned (r:0 w:4)
 	fn create_multiple_items(b: u32, ) -> Weight {
-		(10_134_000 as Weight)
-			// Standard Error: 3_000
-			.saturating_add((4_927_000 as Weight).saturating_mul(b as Weight))
+		(12_601_000 as Weight)
+			// Standard Error: 1_000
+			.saturating_add((4_920_000 as Weight).saturating_mul(b as Weight))
 			.saturating_add(T::DbWeight::get().reads(2 as Weight))
 			.saturating_add(T::DbWeight::get().writes(2 as Weight))
 			.saturating_add(T::DbWeight::get().writes((2 as Weight).saturating_mul(b as Weight)))
@@ -77,9 +78,9 @@
 	// Storage: Nonfungible TokenData (r:0 w:4)
 	// Storage: Nonfungible Owned (r:0 w:4)
 	fn create_multiple_items_ex(b: u32, ) -> Weight {
-		(5_710_000 as Weight)
-			// Standard Error: 4_000
-			.saturating_add((7_578_000 as Weight).saturating_mul(b as Weight))
+		(0 as Weight)
+			// Standard Error: 3_000
+			.saturating_add((7_734_000 as Weight).saturating_mul(b as Weight))
 			.saturating_add(T::DbWeight::get().reads(1 as Weight))
 			.saturating_add(T::DbWeight::get().reads((1 as Weight).saturating_mul(b as Weight)))
 			.saturating_add(T::DbWeight::get().writes(1 as Weight))
@@ -93,7 +94,7 @@
 	// Storage: Nonfungible Owned (r:0 w:1)
 	// Storage: Nonfungible TokenProperties (r:0 w:1)
 	fn burn_item() -> Weight {
-		(28_433_000 as Weight)
+		(29_746_000 as Weight)
 			.saturating_add(T::DbWeight::get().reads(5 as Weight))
 			.saturating_add(T::DbWeight::get().writes(5 as Weight))
 	}
@@ -105,7 +106,7 @@
 	// Storage: Nonfungible Owned (r:0 w:1)
 	// Storage: Nonfungible TokenProperties (r:0 w:1)
 	fn burn_recursively_self_raw() -> Weight {
-		(34_435_000 as Weight)
+		(36_077_000 as Weight)
 			.saturating_add(T::DbWeight::get().reads(5 as Weight))
 			.saturating_add(T::DbWeight::get().writes(5 as Weight))
 	}
@@ -119,8 +120,8 @@
 	// Storage: Common CollectionById (r:1 w:0)
 	fn burn_recursively_breadth_plus_self_plus_self_per_each_raw(b: u32, ) -> Weight {
 		(0 as Weight)
-			// Standard Error: 1_539_000
-			.saturating_add((304_456_000 as Weight).saturating_mul(b as Weight))
+			// Standard Error: 1_605_000
+			.saturating_add((312_391_000 as Weight).saturating_mul(b as Weight))
 			.saturating_add(T::DbWeight::get().reads(7 as Weight))
 			.saturating_add(T::DbWeight::get().reads((4 as Weight).saturating_mul(b as Weight)))
 			.saturating_add(T::DbWeight::get().writes(6 as Weight))
@@ -131,14 +132,14 @@
 	// Storage: Nonfungible Allowance (r:1 w:0)
 	// Storage: Nonfungible Owned (r:0 w:2)
 	fn transfer() -> Weight {
-		(24_376_000 as Weight)
+		(25_248_000 as Weight)
 			.saturating_add(T::DbWeight::get().reads(4 as Weight))
 			.saturating_add(T::DbWeight::get().writes(5 as Weight))
 	}
 	// Storage: Nonfungible TokenData (r:1 w:0)
 	// Storage: Nonfungible Allowance (r:1 w:1)
 	fn approve() -> Weight {
-		(15_890_000 as Weight)
+		(16_321_000 as Weight)
 			.saturating_add(T::DbWeight::get().reads(2 as Weight))
 			.saturating_add(T::DbWeight::get().writes(1 as Weight))
 	}
@@ -147,7 +148,7 @@
 	// Storage: Nonfungible AccountBalance (r:2 w:2)
 	// Storage: Nonfungible Owned (r:0 w:2)
 	fn transfer_from() -> Weight {
-		(28_634_000 as Weight)
+		(29_325_000 as Weight)
 			.saturating_add(T::DbWeight::get().reads(4 as Weight))
 			.saturating_add(T::DbWeight::get().writes(6 as Weight))
 	}
@@ -159,15 +160,15 @@
 	// Storage: Nonfungible Owned (r:0 w:1)
 	// Storage: Nonfungible TokenProperties (r:0 w:1)
 	fn burn_from() -> Weight {
-		(32_201_000 as Weight)
+		(33_323_000 as Weight)
 			.saturating_add(T::DbWeight::get().reads(5 as Weight))
 			.saturating_add(T::DbWeight::get().writes(6 as Weight))
 	}
 	// Storage: Common CollectionPropertyPermissions (r:1 w:1)
 	fn set_token_property_permissions(b: u32, ) -> Weight {
 		(0 as Weight)
-			// Standard Error: 57_000
-			.saturating_add((15_232_000 as Weight).saturating_mul(b as Weight))
+			// Standard Error: 62_000
+			.saturating_add((16_222_000 as Weight).saturating_mul(b as Weight))
 			.saturating_add(T::DbWeight::get().reads(1 as Weight))
 			.saturating_add(T::DbWeight::get().writes(1 as Weight))
 	}
@@ -175,8 +176,8 @@
 	// Storage: Nonfungible TokenProperties (r:1 w:1)
 	fn set_token_properties(b: u32, ) -> Weight {
 		(0 as Weight)
-			// Standard Error: 1_648_000
-			.saturating_add((288_654_000 as Weight).saturating_mul(b as Weight))
+			// Standard Error: 1_750_000
+			.saturating_add((304_476_000 as Weight).saturating_mul(b as Weight))
 			.saturating_add(T::DbWeight::get().reads(2 as Weight))
 			.saturating_add(T::DbWeight::get().writes(1 as Weight))
 	}
@@ -184,11 +185,16 @@
 	// Storage: Nonfungible TokenProperties (r:1 w:1)
 	fn delete_token_properties(b: u32, ) -> Weight {
 		(0 as Weight)
-			// Standard Error: 1_632_000
-			.saturating_add((289_190_000 as Weight).saturating_mul(b as Weight))
+			// Standard Error: 1_638_000
+			.saturating_add((294_096_000 as Weight).saturating_mul(b as Weight))
 			.saturating_add(T::DbWeight::get().reads(2 as Weight))
 			.saturating_add(T::DbWeight::get().writes(1 as Weight))
 	}
+	// Storage: Nonfungible TokenData (r:1 w:0)
+	fn token_owner() -> Weight {
+		(2_986_000 as Weight)
+			.saturating_add(T::DbWeight::get().reads(1 as Weight))
+	}
 }
 
 // For backwards compatibility and tests
@@ -198,7 +204,7 @@
 	// Storage: Nonfungible TokenData (r:0 w:1)
 	// Storage: Nonfungible Owned (r:0 w:1)
 	fn create_item() -> Weight {
-		(20_328_000 as Weight)
+		(20_909_000 as Weight)
 			.saturating_add(RocksDbWeight::get().reads(2 as Weight))
 			.saturating_add(RocksDbWeight::get().writes(4 as Weight))
 	}
@@ -207,9 +213,9 @@
 	// Storage: Nonfungible TokenData (r:0 w:4)
 	// Storage: Nonfungible Owned (r:0 w:4)
 	fn create_multiple_items(b: u32, ) -> Weight {
-		(10_134_000 as Weight)
-			// Standard Error: 3_000
-			.saturating_add((4_927_000 as Weight).saturating_mul(b as Weight))
+		(12_601_000 as Weight)
+			// Standard Error: 1_000
+			.saturating_add((4_920_000 as Weight).saturating_mul(b as Weight))
 			.saturating_add(RocksDbWeight::get().reads(2 as Weight))
 			.saturating_add(RocksDbWeight::get().writes(2 as Weight))
 			.saturating_add(RocksDbWeight::get().writes((2 as Weight).saturating_mul(b as Weight)))
@@ -219,9 +225,9 @@
 	// Storage: Nonfungible TokenData (r:0 w:4)
 	// Storage: Nonfungible Owned (r:0 w:4)
 	fn create_multiple_items_ex(b: u32, ) -> Weight {
-		(5_710_000 as Weight)
-			// Standard Error: 4_000
-			.saturating_add((7_578_000 as Weight).saturating_mul(b as Weight))
+		(0 as Weight)
+			// Standard Error: 3_000
+			.saturating_add((7_734_000 as Weight).saturating_mul(b as Weight))
 			.saturating_add(RocksDbWeight::get().reads(1 as Weight))
 			.saturating_add(RocksDbWeight::get().reads((1 as Weight).saturating_mul(b as Weight)))
 			.saturating_add(RocksDbWeight::get().writes(1 as Weight))
@@ -235,7 +241,7 @@
 	// Storage: Nonfungible Owned (r:0 w:1)
 	// Storage: Nonfungible TokenProperties (r:0 w:1)
 	fn burn_item() -> Weight {
-		(28_433_000 as Weight)
+		(29_746_000 as Weight)
 			.saturating_add(RocksDbWeight::get().reads(5 as Weight))
 			.saturating_add(RocksDbWeight::get().writes(5 as Weight))
 	}
@@ -247,7 +253,7 @@
 	// Storage: Nonfungible Owned (r:0 w:1)
 	// Storage: Nonfungible TokenProperties (r:0 w:1)
 	fn burn_recursively_self_raw() -> Weight {
-		(34_435_000 as Weight)
+		(36_077_000 as Weight)
 			.saturating_add(RocksDbWeight::get().reads(5 as Weight))
 			.saturating_add(RocksDbWeight::get().writes(5 as Weight))
 	}
@@ -261,8 +267,8 @@
 	// Storage: Common CollectionById (r:1 w:0)
 	fn burn_recursively_breadth_plus_self_plus_self_per_each_raw(b: u32, ) -> Weight {
 		(0 as Weight)
-			// Standard Error: 1_539_000
-			.saturating_add((304_456_000 as Weight).saturating_mul(b as Weight))
+			// Standard Error: 1_605_000
+			.saturating_add((312_391_000 as Weight).saturating_mul(b as Weight))
 			.saturating_add(RocksDbWeight::get().reads(7 as Weight))
 			.saturating_add(RocksDbWeight::get().reads((4 as Weight).saturating_mul(b as Weight)))
 			.saturating_add(RocksDbWeight::get().writes(6 as Weight))
@@ -273,14 +279,14 @@
 	// Storage: Nonfungible Allowance (r:1 w:0)
 	// Storage: Nonfungible Owned (r:0 w:2)
 	fn transfer() -> Weight {
-		(24_376_000 as Weight)
+		(25_248_000 as Weight)
 			.saturating_add(RocksDbWeight::get().reads(4 as Weight))
 			.saturating_add(RocksDbWeight::get().writes(5 as Weight))
 	}
 	// Storage: Nonfungible TokenData (r:1 w:0)
 	// Storage: Nonfungible Allowance (r:1 w:1)
 	fn approve() -> Weight {
-		(15_890_000 as Weight)
+		(16_321_000 as Weight)
 			.saturating_add(RocksDbWeight::get().reads(2 as Weight))
 			.saturating_add(RocksDbWeight::get().writes(1 as Weight))
 	}
@@ -289,7 +295,7 @@
 	// Storage: Nonfungible AccountBalance (r:2 w:2)
 	// Storage: Nonfungible Owned (r:0 w:2)
 	fn transfer_from() -> Weight {
-		(28_634_000 as Weight)
+		(29_325_000 as Weight)
 			.saturating_add(RocksDbWeight::get().reads(4 as Weight))
 			.saturating_add(RocksDbWeight::get().writes(6 as Weight))
 	}
@@ -301,15 +307,15 @@
 	// Storage: Nonfungible Owned (r:0 w:1)
 	// Storage: Nonfungible TokenProperties (r:0 w:1)
 	fn burn_from() -> Weight {
-		(32_201_000 as Weight)
+		(33_323_000 as Weight)
 			.saturating_add(RocksDbWeight::get().reads(5 as Weight))
 			.saturating_add(RocksDbWeight::get().writes(6 as Weight))
 	}
 	// Storage: Common CollectionPropertyPermissions (r:1 w:1)
 	fn set_token_property_permissions(b: u32, ) -> Weight {
 		(0 as Weight)
-			// Standard Error: 57_000
-			.saturating_add((15_232_000 as Weight).saturating_mul(b as Weight))
+			// Standard Error: 62_000
+			.saturating_add((16_222_000 as Weight).saturating_mul(b as Weight))
 			.saturating_add(RocksDbWeight::get().reads(1 as Weight))
 			.saturating_add(RocksDbWeight::get().writes(1 as Weight))
 	}
@@ -317,8 +323,8 @@
 	// Storage: Nonfungible TokenProperties (r:1 w:1)
 	fn set_token_properties(b: u32, ) -> Weight {
 		(0 as Weight)
-			// Standard Error: 1_648_000
-			.saturating_add((288_654_000 as Weight).saturating_mul(b as Weight))
+			// Standard Error: 1_750_000
+			.saturating_add((304_476_000 as Weight).saturating_mul(b as Weight))
 			.saturating_add(RocksDbWeight::get().reads(2 as Weight))
 			.saturating_add(RocksDbWeight::get().writes(1 as Weight))
 	}
@@ -326,9 +332,14 @@
 	// Storage: Nonfungible TokenProperties (r:1 w:1)
 	fn delete_token_properties(b: u32, ) -> Weight {
 		(0 as Weight)
-			// Standard Error: 1_632_000
-			.saturating_add((289_190_000 as Weight).saturating_mul(b as Weight))
+			// Standard Error: 1_638_000
+			.saturating_add((294_096_000 as Weight).saturating_mul(b as Weight))
 			.saturating_add(RocksDbWeight::get().reads(2 as Weight))
 			.saturating_add(RocksDbWeight::get().writes(1 as Weight))
 	}
+	// Storage: Nonfungible TokenData (r:1 w:0)
+	fn token_owner() -> Weight {
+		(2_986_000 as Weight)
+			.saturating_add(RocksDbWeight::get().reads(1 as Weight))
+	}
 }
modifiedpallets/refungible/src/benchmarking.rsdiffbeforeafterboth
--- a/pallets/refungible/src/benchmarking.rs
+++ b/pallets/refungible/src/benchmarking.rs
@@ -17,25 +17,26 @@
 use super::*;
 use crate::{Pallet, Config, RefungibleHandle};
 
+use core::convert::TryInto;
+use core::iter::IntoIterator;
+use frame_benchmarking::{benchmarks, account};
+use pallet_common::{
+	bench_init,
+	benchmarking::{create_collection_raw, property_key, property_value, create_data},
+};
+use sp_core::H160;
 use sp_std::prelude::*;
-use pallet_common::benchmarking::{create_collection_raw, property_key, property_value, create_data};
-use frame_benchmarking::{benchmarks, account};
 use up_data_structs::{
 	CollectionMode, MAX_ITEMS_PER_BATCH, MAX_PROPERTIES_PER_ITEM, CUSTOM_DATA_LIMIT,
 	budget::Unlimited,
 };
-use pallet_common::bench_init;
-use core::convert::TryInto;
-use core::iter::IntoIterator;
 
 const SEED: u32 = 1;
 
 fn create_max_item_data<CrossAccountId: Ord>(
 	users: impl IntoIterator<Item = (CrossAccountId, u128)>,
 ) -> CreateRefungibleExData<CrossAccountId> {
-	let const_data = create_data::<CUSTOM_DATA_LIMIT>();
 	CreateRefungibleExData {
-		const_data,
 		users: users
 			.into_iter()
 			.collect::<BTreeMap<_, _>>()
@@ -44,6 +45,7 @@
 		properties: Default::default(),
 	}
 }
+
 fn create_max_item<T: Config>(
 	collection: &RefungibleHandle<T>,
 	sender: &T::CrossAccountId,
@@ -59,11 +61,12 @@
 ) -> Result<RefungibleHandle<T>, DispatchError> {
 	create_collection_raw(
 		owner,
-		CollectionMode::NFT,
+		CollectionMode::ReFungible,
 		<Pallet<T>>::init_collection,
 		RefungibleHandle::cast,
 	)
 }
+
 benchmarks! {
 	create_item {
 		bench_init!{
@@ -277,4 +280,21 @@
 		};
 		let item = create_max_item(&collection, &sender, [(owner.clone(), 100)])?;
 	}: {<Pallet<T>>::repartition(&collection, &owner, item, 200)?}
+
+	set_parent_nft_unchecked {
+		bench_init!{
+			owner: sub; collection: collection(owner);
+			sender: cross_from_sub(owner); owner: cross_sub;
+		};
+		let item = create_max_item(&collection, &sender, [(owner.clone(), 100)])?;
+
+	}: {<Pallet<T>>::set_parent_nft_unchecked(&collection, item, owner,  T::CrossAccountId::from_eth(H160::default()))?}
+
+	token_owner {
+		bench_init!{
+			owner: sub; collection: collection(owner);
+			sender: cross_from_sub(owner); owner: cross_sub;
+		};
+		let item = create_max_item(&collection, &sender, [(owner.clone(), 100)])?;
+	}: {<Pallet<T>>::token_owner(collection.id, item)}
 }
modifiedpallets/refungible/src/common.rsdiffbeforeafterboth
--- a/pallets/refungible/src/common.rs
+++ b/pallets/refungible/src/common.rs
@@ -148,6 +148,10 @@
 		// Refungible token can't have children
 		0
 	}
+
+	fn token_owner() -> Weight {
+		<SelfWeightOf<T>>::token_owner()
+	}
 }
 
 fn map_create_data<T: Config>(
modifiedpallets/refungible/src/erc.rsdiffbeforeafterboth
--- a/pallets/refungible/src/erc.rs
+++ b/pallets/refungible/src/erc.rs
@@ -41,8 +41,8 @@
 use sp_core::H160;
 use sp_std::{collections::btree_map::BTreeMap, vec::Vec, vec};
 use up_data_structs::{
-	CollectionId, CollectionPropertiesVec, Property, PropertyKey, PropertyKeyPermission,
-	PropertyPermission, TokenId,
+	CollectionId, CollectionPropertiesVec, mapping::TokenAddressMapping, Property, PropertyKey,
+	PropertyKeyPermission, PropertyPermission, TokenId,
 };
 
 use crate::{
@@ -413,7 +413,7 @@
 }
 
 /// Returns amount of pieces of `token` that `owner` have
-fn balance<T: Config>(
+pub fn balance<T: Config>(
 	collection: &RefungibleHandle<T>,
 	token: TokenId,
 	owner: &T::CrossAccountId,
@@ -424,7 +424,7 @@
 }
 
 /// Throws if `owner_balance` is lower than total amount of `token` pieces
-fn ensure_single_owner<T: Config>(
+pub fn ensure_single_owner<T: Config>(
 	collection: &RefungibleHandle<T>,
 	token: TokenId,
 	owner_balance: u128,
@@ -788,6 +788,16 @@
 			.map_err(dispatch_to_evm::<T>)?;
 		Ok(true)
 	}
+
+	/// Returns EVM address for refungible token
+	///
+	/// @param token ID of the token
+	fn token_contract_address(&self, token: uint256) -> Result<address> {
+		Ok(T::EvmTokenAddressMapping::token_to_address(
+			self.id,
+			token.try_into().map_err(|_| "token id overflow")?,
+		))
+	}
 }
 
 #[solidity_interface(
modifiedpallets/refungible/src/erc_token.rsdiffbeforeafterboth
--- a/pallets/refungible/src/erc_token.rs
+++ b/pallets/refungible/src/erc_token.rs
@@ -20,29 +20,95 @@
 //! Method implementations are mostly doing parameter conversion and calling Nonfungible Pallet methods.
 
 extern crate alloc;
+
+#[cfg(not(feature = "std"))]
+use alloc::format;
+
 use core::{
 	char::{REPLACEMENT_CHARACTER, decode_utf16},
 	convert::TryInto,
 	ops::Deref,
 };
-use evm_coder::{ToLog, execution::*, generate_stubgen, solidity_interface, types::*, weight};
+use evm_coder::{ToLog, execution::*, generate_stubgen, solidity, solidity_interface, types::*, weight};
 use pallet_common::{
 	CommonWeightInfo,
-	erc::{CommonEvmHandler, PrecompileResult},
+	erc::{CommonEvmHandler, PrecompileResult, static_property::key},
+	eth::map_eth_to_id,
 };
 use pallet_evm::{account::CrossAccountId, PrecompileHandle};
 use pallet_evm_coder_substrate::{call, dispatch_to_evm, WithRecorder};
 use pallet_structure::{SelfWeightOf as StructureWeight, weights::WeightInfo as _};
+use sp_core::H160;
 use sp_std::vec::Vec;
-use up_data_structs::TokenId;
+use up_data_structs::{mapping::TokenAddressMapping, PropertyScope, TokenId};
 
 use crate::{
 	Allowance, Balance, common::CommonWeights, Config, Pallet, RefungibleHandle, SelfWeightOf,
-	weights::WeightInfo, TotalSupply,
+	TokenProperties, TotalSupply, weights::WeightInfo,
 };
 
 pub struct RefungibleTokenHandle<T: Config>(pub RefungibleHandle<T>, pub TokenId);
 
+#[solidity_interface(name = "ERC1633")]
+impl<T: Config> RefungibleTokenHandle<T> {
+	fn parent_token(&self) -> Result<address> {
+		self.consume_store_reads(2)?;
+		let props = <TokenProperties<T>>::get((self.id, self.1));
+		let key = key::parent_nft();
+
+		let key_scoped = PropertyScope::Eth
+			.apply(key)
+			.expect("property key shouldn't exceed length limit");
+		if let Some(value) = props.get(&key_scoped) {
+			Ok(H160::from_slice(value.as_slice()))
+		} else {
+			Ok(*T::CrossTokenAddressMapping::token_to_address(self.id, self.1).as_eth())
+		}
+	}
+
+	fn parent_token_id(&self) -> Result<uint256> {
+		self.consume_store_reads(2)?;
+		let props = <TokenProperties<T>>::get((self.id, self.1));
+		let key = key::parent_nft();
+
+		let key_scoped = PropertyScope::Eth
+			.apply(key)
+			.expect("property key shouldn't exceed length limit");
+		if let Some(value) = props.get(&key_scoped) {
+			let nft_token_address = H160::from_slice(value.as_slice());
+			let nft_token_account = T::CrossAccountId::from_eth(nft_token_address);
+			let (_, token_id) = T::CrossTokenAddressMapping::address_to_token(&nft_token_account)
+				.ok_or("parent NFT should contain NFT token address")?;
+
+			Ok(token_id.into())
+		} else {
+			Ok(self.1.into())
+		}
+	}
+}
+
+#[solidity_interface(name = "ERC1633UniqueExtensions")]
+impl<T: Config> RefungibleTokenHandle<T> {
+	#[solidity(rename_selector = "setParentNFT")]
+	#[weight(<CommonWeights<T>>::token_owner() + <SelfWeightOf<T>>::set_parent_nft_unchecked())]
+	fn set_parent_nft(
+		&mut self,
+		caller: caller,
+		collection: address,
+		nft_id: uint256,
+	) -> Result<bool> {
+		self.consume_store_reads(1)?;
+		let caller = T::CrossAccountId::from_eth(caller);
+		let nft_collection = map_eth_to_id(&collection).ok_or("collection not found")?;
+		let nft_token = nft_id.try_into()?;
+
+		<Pallet<T>>::set_parent_nft(&self.0, self.1, caller, nft_collection, nft_token)
+			.map_err(dispatch_to_evm::<T>)?;
+
+		Ok(true)
+	}
+}
+
 #[derive(ToLog)]
 pub enum ERC20Events {
 	/// @dev This event is emitted when the amount of tokens (value) is sent
@@ -120,7 +186,7 @@
 			.weight_calls_budget(<StructureWeight<T>>::find_parent());
 
 		<Pallet<T>>::transfer(self, &caller, &to, self.1, amount, &budget)
-			.map_err(|_| "transfer error")?;
+			.map_err(dispatch_to_evm::<T>)?;
 		Ok(true)
 	}
 
@@ -239,7 +305,10 @@
 	}
 }
 
-#[solidity_interface(name = "UniqueRefungibleToken", is(ERC20, ERC20UniqueExtensions,))]
+#[solidity_interface(
+	name = "UniqueRefungibleToken",
+	is(ERC20, ERC20UniqueExtensions, ERC1633, ERC1633UniqueExtensions)
+)]
 impl<T: Config> RefungibleTokenHandle<T> where T::AccountId: From<[u8; 32]> {}
 
 generate_stubgen!(gen_impl, UniqueRefungibleTokenCall<()>, true);
modifiedpallets/refungible/src/lib.rsdiffbeforeafterboth
--- a/pallets/refungible/src/lib.rs
+++ b/pallets/refungible/src/lib.rs
@@ -99,8 +99,12 @@
 use pallet_evm::{account::CrossAccountId, Pallet as PalletEvm};
 use pallet_evm_coder_substrate::WithRecorder;
 use pallet_common::{
-	CommonCollectionOperations, Error as CommonError, Event as CommonEvent,
-	eth::collection_id_to_address, Pallet as PalletCommon,
+	CollectionHandle, CommonCollectionOperations,
+	dispatch::CollectionDispatch,
+	erc::static_property::{key, property_value_from_bytes},
+	Error as CommonError,
+	eth::collection_id_to_address,
+	Event as CommonEvent, Pallet as PalletCommon,
 };
 use pallet_structure::Pallet as PalletStructure;
 use scale_info::TypeInfo;
@@ -108,10 +112,10 @@
 use sp_runtime::{ArithmeticError, DispatchError, DispatchResult, TransactionOutcome};
 use sp_std::{vec::Vec, vec, collections::btree_map::BTreeMap};
 use up_data_structs::{
-	AccessMode, budget::Budget, CollectionId, CreateCollectionData, CustomDataLimit,
-	mapping::TokenAddressMapping, MAX_REFUNGIBLE_PIECES, MAX_ITEMS_PER_BATCH, TokenId, Property,
-	PropertyKey, PropertyKeyPermission, PropertyPermission, PropertyScope, PropertyValue,
-	TrySetProperty, CollectionPropertiesVec,
+	AccessMode, budget::Budget, CollectionId, CollectionMode, CollectionPropertiesVec,
+	CreateCollectionData, CustomDataLimit, mapping::TokenAddressMapping, MAX_ITEMS_PER_BATCH,
+	MAX_REFUNGIBLE_PIECES, Property, PropertyKey, PropertyKeyPermission, PropertyPermission,
+	PropertyScope, PropertyValue, TokenId, TrySetProperty,
 };
 use frame_support::BoundedBTreeMap;
 use derivative::Derivative;
@@ -1341,6 +1345,20 @@
 		<PalletCommon<T>>::set_token_property_permissions(collection, sender, property_permissions)
 	}
 
+	pub fn set_scoped_token_property_permissions(
+		collection: &RefungibleHandle<T>,
+		sender: &T::CrossAccountId,
+		scope: PropertyScope,
+		property_permissions: Vec<PropertyKeyPermission>,
+	) -> DispatchResult {
+		<PalletCommon<T>>::set_scoped_token_property_permissions(
+			collection,
+			sender,
+			scope,
+			property_permissions,
+		)
+	}
+
 	/// Returns 10 token in no particular order.
 	///
 	/// There is no direct way to get token holders in ascending order,
@@ -1362,4 +1380,68 @@
 			Some(res)
 		}
 	}
+
+	/// Sets the NFT token as a parent for the RFT token
+	///
+	/// Throws if `sender` is not the owner of the NFT token.
+	/// Throws if `sender` is not the owner of all of the RFT token pieces.
+	pub fn set_parent_nft(
+		collection: &RefungibleHandle<T>,
+		rft_token_id: TokenId,
+		sender: T::CrossAccountId,
+		nft_collection: CollectionId,
+		nft_token: TokenId,
+	) -> DispatchResult {
+		let handle = <CollectionHandle<T>>::try_get(nft_collection)?;
+		if handle.mode != CollectionMode::NFT {
+			return Err("Only NFT token could be parent to RFT".into());
+		}
+		let dispatch = T::CollectionDispatch::dispatch(handle);
+		let dispatch = dispatch.as_dyn();
+
+		let owner = dispatch.token_owner(nft_token).ok_or("owner not found")?;
+		if owner != sender {
+			return Err("Only owned token could be set as parent".into());
+		}
+
+		let nft_token_address =
+			T::CrossTokenAddressMapping::token_to_address(nft_collection, nft_token);
+
+		Self::set_parent_nft_unchecked(collection, rft_token_id, sender, nft_token_address)
+	}
+
+	/// Sets the NFT token as a parent for the RFT token
+	///
+	/// `sender` should be the owner of the NFT token.
+	/// Throws if `sender` is not the owner of all of the RFT token pieces.
+	pub fn set_parent_nft_unchecked(
+		collection: &RefungibleHandle<T>,
+		rft_token_id: TokenId,
+		sender: T::CrossAccountId,
+		nft_token_address: T::CrossAccountId,
+	) -> DispatchResult {
+		let owner_balance = <Balance<T>>::get((collection.id, rft_token_id, &sender));
+		let total_supply = <TotalSupply<T>>::get((collection.id, rft_token_id));
+		if total_supply != owner_balance {
+			return Err("token has multiple owners".into());
+		}
+
+		let parent_nft_property_key = key::parent_nft();
+
+		let parent_nft_property_value =
+			property_value_from_bytes(&nft_token_address.as_eth().to_fixed_bytes())
+				.expect("address should fit in value length limit");
+
+		<Pallet<T>>::set_scoped_token_property(
+			collection.id,
+			rft_token_id,
+			PropertyScope::Eth,
+			Property {
+				key: parent_nft_property_key,
+				value: parent_nft_property_value,
+			},
+		)?;
+
+		Ok(())
+	}
 }
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
@@ -371,49 +371,7 @@
 	}
 }
 
-// Selector: 780e9d63
-contract ERC721Enumerable is Dummy, ERC165 {
-	// @notice Enumerate valid RFTs
-	// @param index A counter less than `totalSupply()`
-	// @return The token identifier for the `index`th NFT,
-	//  (sort order not specified)
-	//
-	// Selector: tokenByIndex(uint256) 4f6ccce7
-	function tokenByIndex(uint256 index) public view returns (uint256) {
-		require(false, stub_error);
-		index;
-		dummy;
-		return 0;
-	}
-
-	// Not implemented
-	//
-	// Selector: tokenOfOwnerByIndex(address,uint256) 2f745c59
-	function tokenOfOwnerByIndex(address owner, uint256 index)
-		public
-		view
-		returns (uint256)
-	{
-		require(false, stub_error);
-		owner;
-		index;
-		dummy;
-		return 0;
-	}
-
-	// @notice Count RFTs tracked by this contract
-	// @return A count of valid RFTs tracked by this contract, where each one of
-	//  them has an assigned and queryable owner not equal to the zero address
-	//
-	// Selector: totalSupply() 18160ddd
-	function totalSupply() public view returns (uint256) {
-		require(false, stub_error);
-		dummy;
-		return 0;
-	}
-}
-
-// Selector: 7d9262e6
+// Selector: 6cf113cd
 contract Collection is Dummy, ERC165 {
 	// Set collection property.
 	//
@@ -638,9 +596,75 @@
 		mode;
 		dummy = 0;
 	}
+
+	// Check that account is the owner or admin of the collection
+	//
+	// @param user account to verify
+	// @return "true" if account is the owner or admin
+	//
+	// Selector: verifyOwnerOrAdmin(address) c2282493
+	function verifyOwnerOrAdmin(address user) public view returns (bool) {
+		require(false, stub_error);
+		user;
+		dummy;
+		return false;
+	}
+
+	// Returns collection type
+	//
+	// @return `Fungible` or `NFT` or `ReFungible`
+	//
+	// Selector: uniqueCollectionType() d34b55b8
+	function uniqueCollectionType() public returns (string memory) {
+		require(false, stub_error);
+		dummy = 0;
+		return "";
+	}
+}
+
+// Selector: 780e9d63
+contract ERC721Enumerable is Dummy, ERC165 {
+	// @notice Enumerate valid RFTs
+	// @param index A counter less than `totalSupply()`
+	// @return The token identifier for the `index`th NFT,
+	//  (sort order not specified)
+	//
+	// Selector: tokenByIndex(uint256) 4f6ccce7
+	function tokenByIndex(uint256 index) public view returns (uint256) {
+		require(false, stub_error);
+		index;
+		dummy;
+		return 0;
+	}
+
+	// Not implemented
+	//
+	// Selector: tokenOfOwnerByIndex(address,uint256) 2f745c59
+	function tokenOfOwnerByIndex(address owner, uint256 index)
+		public
+		view
+		returns (uint256)
+	{
+		require(false, stub_error);
+		owner;
+		index;
+		dummy;
+		return 0;
+	}
+
+	// @notice Count RFTs tracked by this contract
+	// @return A count of valid RFTs tracked by this contract, where each one of
+	//  them has an assigned and queryable owner not equal to the zero address
+	//
+	// Selector: totalSupply() 18160ddd
+	function totalSupply() public view returns (uint256) {
+		require(false, stub_error);
+		dummy;
+		return 0;
+	}
 }
 
-// Selector: d74d154f
+// Selector: 7c3bef89
 contract ERC721UniqueExtensions is Dummy, ERC165 {
 	// @notice Transfer ownership of an RFT
 	// @dev Throws unless `msg.sender` is the current owner. Throws if `to`
@@ -719,6 +743,18 @@
 		dummy = 0;
 		return false;
 	}
+
+	// Returns EVM address for refungible token
+	//
+	// @param token ID of the token
+	//
+	// Selector: tokenContractAddress(uint256) ab76fac6
+	function tokenContractAddress(uint256 token) public view returns (address) {
+		require(false, stub_error);
+		token;
+		dummy;
+		return 0x0000000000000000000000000000000000000000;
+	}
 }
 
 contract UniqueRefungible is
modifiedpallets/refungible/src/stubs/UniqueRefungibleToken.rawdiffbeforeafterboth

binary blob — no preview

modifiedpallets/refungible/src/stubs/UniqueRefungibleToken.soldiffbeforeafterboth
--- a/pallets/refungible/src/stubs/UniqueRefungibleToken.sol
+++ b/pallets/refungible/src/stubs/UniqueRefungibleToken.sol
@@ -31,6 +31,38 @@
 	);
 }
 
+// Selector: 042f1106
+contract ERC1633UniqueExtensions is Dummy, ERC165 {
+	// Selector: setParentNFT(address,uint256) 042f1106
+	function setParentNFT(address collection, uint256 nftId)
+		public
+		returns (bool)
+	{
+		require(false, stub_error);
+		collection;
+		nftId;
+		dummy = 0;
+		return false;
+	}
+}
+
+// Selector: 5755c3f2
+contract ERC1633 is Dummy, ERC165 {
+	// Selector: parentToken() 80a54001
+	function parentToken() public view returns (address) {
+		require(false, stub_error);
+		dummy;
+		return 0x0000000000000000000000000000000000000000;
+	}
+
+	// Selector: parentTokenId() d7f083f3
+	function parentTokenId() public view returns (uint256) {
+		require(false, stub_error);
+		dummy;
+		return 0;
+	}
+}
+
 // Selector: 942e8b22
 contract ERC20 is Dummy, ERC165, ERC20Events {
 	// @return the name of the token.
@@ -178,4 +210,11 @@
 	}
 }
 
-contract UniqueRefungibleToken is Dummy, ERC165, ERC20, ERC20UniqueExtensions {}
+contract UniqueRefungibleToken is
+	Dummy,
+	ERC165,
+	ERC20,
+	ERC20UniqueExtensions,
+	ERC1633,
+	ERC1633UniqueExtensions
+{}
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-07-20, STEPS: `50`, REPEAT: 80, LOW RANGE: `[]`, HIGH RANGE: `[]`
+//! DATE: 2022-08-01, STEPS: `50`, REPEAT: 80, LOW RANGE: `[]`, HIGH RANGE: `[]`
 //! EXECUTION: None, WASM-EXECUTION: Compiled, CHAIN: None, DB CACHE: 1024
 
 // Executed Command:
@@ -53,6 +53,8 @@
 	fn set_token_properties(b: u32, ) -> Weight;
 	fn delete_token_properties(b: u32, ) -> Weight;
 	fn repartition_item() -> Weight;
+	fn set_parent_nft_unchecked() -> Weight;
+	fn token_owner() -> Weight;
 }
 
 /// Weights for pallet_refungible using the Substrate node and recommended hardware.
@@ -65,7 +67,7 @@
 	// Storage: Refungible TokenData (r:0 w:1)
 	// Storage: Refungible Owned (r:0 w:1)
 	fn create_item() -> Weight {
-		(21_310_000 as Weight)
+		(25_197_000 as Weight)
 			.saturating_add(T::DbWeight::get().reads(2 as Weight))
 			.saturating_add(T::DbWeight::get().writes(6 as Weight))
 	}
@@ -76,9 +78,9 @@
 	// Storage: Refungible TokenData (r:0 w:4)
 	// Storage: Refungible Owned (r:0 w:4)
 	fn create_multiple_items(b: u32, ) -> Weight {
-		(9_552_000 as Weight)
+		(10_852_000 as Weight)
 			// Standard Error: 2_000
-			.saturating_add((7_056_000 as Weight).saturating_mul(b as Weight))
+			.saturating_add((8_087_000 as Weight).saturating_mul(b as Weight))
 			.saturating_add(T::DbWeight::get().reads(2 as Weight))
 			.saturating_add(T::DbWeight::get().writes(2 as Weight))
 			.saturating_add(T::DbWeight::get().writes((4 as Weight).saturating_mul(b as Weight)))
@@ -90,9 +92,9 @@
 	// Storage: Refungible TokenData (r:0 w:4)
 	// Storage: Refungible Owned (r:0 w:4)
 	fn create_multiple_items_ex_multiple_items(b: u32, ) -> Weight {
-		(4_857_000 as Weight)
+		(9_978_000 as Weight)
 			// Standard Error: 2_000
-			.saturating_add((9_838_000 as Weight).saturating_mul(b as Weight))
+			.saturating_add((10_848_000 as Weight).saturating_mul(b as Weight))
 			.saturating_add(T::DbWeight::get().reads(1 as Weight))
 			.saturating_add(T::DbWeight::get().reads((1 as Weight).saturating_mul(b as Weight)))
 			.saturating_add(T::DbWeight::get().writes(1 as Weight))
@@ -105,9 +107,9 @@
 	// Storage: Refungible Balance (r:0 w:4)
 	// Storage: Refungible Owned (r:0 w:4)
 	fn create_multiple_items_ex_multiple_owners(b: u32, ) -> Weight {
-		(11_335_000 as Weight)
+		(15_419_000 as Weight)
 			// Standard Error: 2_000
-			.saturating_add((6_784_000 as Weight).saturating_mul(b as Weight))
+			.saturating_add((7_813_000 as Weight).saturating_mul(b as Weight))
 			.saturating_add(T::DbWeight::get().reads(1 as Weight))
 			.saturating_add(T::DbWeight::get().reads((1 as Weight).saturating_mul(b as Weight)))
 			.saturating_add(T::DbWeight::get().writes(3 as Weight))
@@ -118,7 +120,7 @@
 	// Storage: Refungible AccountBalance (r:1 w:1)
 	// Storage: Refungible Owned (r:0 w:1)
 	fn burn_item_partial() -> Weight {
-		(21_239_000 as Weight)
+		(25_578_000 as Weight)
 			.saturating_add(T::DbWeight::get().reads(3 as Weight))
 			.saturating_add(T::DbWeight::get().writes(4 as Weight))
 	}
@@ -130,13 +132,13 @@
 	// Storage: Refungible Owned (r:0 w:1)
 	// Storage: Refungible TokenProperties (r:0 w:1)
 	fn burn_item_fully() -> Weight {
-		(29_426_000 as Weight)
+		(33_593_000 as Weight)
 			.saturating_add(T::DbWeight::get().reads(4 as Weight))
 			.saturating_add(T::DbWeight::get().writes(7 as Weight))
 	}
 	// Storage: Refungible Balance (r:2 w:2)
 	fn transfer_normal() -> Weight {
-		(17_743_000 as Weight)
+		(21_049_000 as Weight)
 			.saturating_add(T::DbWeight::get().reads(2 as Weight))
 			.saturating_add(T::DbWeight::get().writes(2 as Weight))
 	}
@@ -144,7 +146,7 @@
 	// Storage: Refungible AccountBalance (r:1 w:1)
 	// Storage: Refungible Owned (r:0 w:1)
 	fn transfer_creating() -> Weight {
-		(20_699_000 as Weight)
+		(24_646_000 as Weight)
 			.saturating_add(T::DbWeight::get().reads(3 as Weight))
 			.saturating_add(T::DbWeight::get().writes(4 as Weight))
 	}
@@ -152,7 +154,7 @@
 	// Storage: Refungible AccountBalance (r:1 w:1)
 	// Storage: Refungible Owned (r:0 w:1)
 	fn transfer_removing() -> Weight {
-		(22_833_000 as Weight)
+		(26_570_000 as Weight)
 			.saturating_add(T::DbWeight::get().reads(3 as Weight))
 			.saturating_add(T::DbWeight::get().writes(4 as Weight))
 	}
@@ -160,21 +162,21 @@
 	// Storage: Refungible AccountBalance (r:2 w:2)
 	// Storage: Refungible Owned (r:0 w:2)
 	fn transfer_creating_removing() -> Weight {
-		(24_936_000 as Weight)
+		(28_906_000 as Weight)
 			.saturating_add(T::DbWeight::get().reads(4 as Weight))
 			.saturating_add(T::DbWeight::get().writes(6 as Weight))
 	}
 	// Storage: Refungible Balance (r:1 w:0)
 	// Storage: Refungible Allowance (r:0 w:1)
 	fn approve() -> Weight {
-		(13_446_000 as Weight)
+		(16_451_000 as Weight)
 			.saturating_add(T::DbWeight::get().reads(1 as Weight))
 			.saturating_add(T::DbWeight::get().writes(1 as Weight))
 	}
 	// Storage: Refungible Allowance (r:1 w:1)
 	// Storage: Refungible Balance (r:2 w:2)
 	fn transfer_from_normal() -> Weight {
-		(24_777_000 as Weight)
+		(29_545_000 as Weight)
 			.saturating_add(T::DbWeight::get().reads(3 as Weight))
 			.saturating_add(T::DbWeight::get().writes(3 as Weight))
 	}
@@ -183,7 +185,7 @@
 	// Storage: Refungible AccountBalance (r:1 w:1)
 	// Storage: Refungible Owned (r:0 w:1)
 	fn transfer_from_creating() -> Weight {
-		(28_483_000 as Weight)
+		(33_392_000 as Weight)
 			.saturating_add(T::DbWeight::get().reads(4 as Weight))
 			.saturating_add(T::DbWeight::get().writes(5 as Weight))
 	}
@@ -192,7 +194,7 @@
 	// Storage: Refungible AccountBalance (r:1 w:1)
 	// Storage: Refungible Owned (r:0 w:1)
 	fn transfer_from_removing() -> Weight {
-		(29_896_000 as Weight)
+		(35_446_000 as Weight)
 			.saturating_add(T::DbWeight::get().reads(4 as Weight))
 			.saturating_add(T::DbWeight::get().writes(5 as Weight))
 	}
@@ -201,7 +203,7 @@
 	// Storage: Refungible AccountBalance (r:2 w:2)
 	// Storage: Refungible Owned (r:0 w:2)
 	fn transfer_from_creating_removing() -> Weight {
-		(32_070_000 as Weight)
+		(37_762_000 as Weight)
 			.saturating_add(T::DbWeight::get().reads(5 as Weight))
 			.saturating_add(T::DbWeight::get().writes(7 as Weight))
 	}
@@ -214,15 +216,15 @@
 	// Storage: Refungible Owned (r:0 w:1)
 	// Storage: Refungible TokenProperties (r:0 w:1)
 	fn burn_from() -> Weight {
-		(36_789_000 as Weight)
+		(42_620_000 as Weight)
 			.saturating_add(T::DbWeight::get().reads(5 as Weight))
 			.saturating_add(T::DbWeight::get().writes(8 as Weight))
 	}
 	// Storage: Common CollectionPropertyPermissions (r:1 w:1)
 	fn set_token_property_permissions(b: u32, ) -> Weight {
 		(0 as Weight)
-			// Standard Error: 62_000
-			.saturating_add((15_803_000 as Weight).saturating_mul(b as Weight))
+			// Standard Error: 65_000
+			.saturating_add((16_513_000 as Weight).saturating_mul(b as Weight))
 			.saturating_add(T::DbWeight::get().reads(1 as Weight))
 			.saturating_add(T::DbWeight::get().writes(1 as Weight))
 	}
@@ -230,8 +232,8 @@
 	// Storage: Refungible TokenProperties (r:1 w:1)
 	fn set_token_properties(b: u32, ) -> Weight {
 		(0 as Weight)
-			// Standard Error: 1_668_000
-			.saturating_add((302_308_000 as Weight).saturating_mul(b as Weight))
+			// Standard Error: 1_583_000
+			.saturating_add((291_392_000 as Weight).saturating_mul(b as Weight))
 			.saturating_add(T::DbWeight::get().reads(2 as Weight))
 			.saturating_add(T::DbWeight::get().writes(1 as Weight))
 	}
@@ -239,18 +241,31 @@
 	// Storage: Refungible TokenProperties (r:1 w:1)
 	fn delete_token_properties(b: u32, ) -> Weight {
 		(0 as Weight)
-			// Standard Error: 1_619_000
-			.saturating_add((294_574_000 as Weight).saturating_mul(b as Weight))
+			// Standard Error: 1_699_000
+			.saturating_add((293_270_000 as Weight).saturating_mul(b as Weight))
 			.saturating_add(T::DbWeight::get().reads(2 as Weight))
 			.saturating_add(T::DbWeight::get().writes(1 as Weight))
 	}
 	// Storage: Refungible TotalSupply (r:1 w:1)
 	// Storage: Refungible Balance (r:1 w:1)
 	fn repartition_item() -> Weight {
-		(8_325_000 as Weight)
+		(19_206_000 as Weight)
 			.saturating_add(T::DbWeight::get().reads(2 as Weight))
 			.saturating_add(T::DbWeight::get().writes(2 as Weight))
 	}
+	// Storage: Refungible Balance (r:1 w:0)
+	// Storage: Refungible TotalSupply (r:1 w:0)
+	// Storage: Refungible TokenProperties (r:1 w:1)
+	fn set_parent_nft_unchecked() -> Weight {
+		(10_189_000 as Weight)
+			.saturating_add(T::DbWeight::get().reads(3 as Weight))
+			.saturating_add(T::DbWeight::get().writes(1 as Weight))
+	}
+	// Storage: Refungible Balance (r:2 w:0)
+	fn token_owner() -> Weight {
+		(8_205_000 as Weight)
+			.saturating_add(T::DbWeight::get().reads(2 as Weight))
+	}
 }
 
 // For backwards compatibility and tests
@@ -262,7 +277,7 @@
 	// Storage: Refungible TokenData (r:0 w:1)
 	// Storage: Refungible Owned (r:0 w:1)
 	fn create_item() -> Weight {
-		(21_310_000 as Weight)
+		(25_197_000 as Weight)
 			.saturating_add(RocksDbWeight::get().reads(2 as Weight))
 			.saturating_add(RocksDbWeight::get().writes(6 as Weight))
 	}
@@ -273,9 +288,9 @@
 	// Storage: Refungible TokenData (r:0 w:4)
 	// Storage: Refungible Owned (r:0 w:4)
 	fn create_multiple_items(b: u32, ) -> Weight {
-		(9_552_000 as Weight)
+		(10_852_000 as Weight)
 			// Standard Error: 2_000
-			.saturating_add((7_056_000 as Weight).saturating_mul(b as Weight))
+			.saturating_add((8_087_000 as Weight).saturating_mul(b as Weight))
 			.saturating_add(RocksDbWeight::get().reads(2 as Weight))
 			.saturating_add(RocksDbWeight::get().writes(2 as Weight))
 			.saturating_add(RocksDbWeight::get().writes((4 as Weight).saturating_mul(b as Weight)))
@@ -287,9 +302,9 @@
 	// Storage: Refungible TokenData (r:0 w:4)
 	// Storage: Refungible Owned (r:0 w:4)
 	fn create_multiple_items_ex_multiple_items(b: u32, ) -> Weight {
-		(4_857_000 as Weight)
+		(9_978_000 as Weight)
 			// Standard Error: 2_000
-			.saturating_add((9_838_000 as Weight).saturating_mul(b as Weight))
+			.saturating_add((10_848_000 as Weight).saturating_mul(b as Weight))
 			.saturating_add(RocksDbWeight::get().reads(1 as Weight))
 			.saturating_add(RocksDbWeight::get().reads((1 as Weight).saturating_mul(b as Weight)))
 			.saturating_add(RocksDbWeight::get().writes(1 as Weight))
@@ -302,9 +317,9 @@
 	// Storage: Refungible Balance (r:0 w:4)
 	// Storage: Refungible Owned (r:0 w:4)
 	fn create_multiple_items_ex_multiple_owners(b: u32, ) -> Weight {
-		(11_335_000 as Weight)
+		(15_419_000 as Weight)
 			// Standard Error: 2_000
-			.saturating_add((6_784_000 as Weight).saturating_mul(b as Weight))
+			.saturating_add((7_813_000 as Weight).saturating_mul(b as Weight))
 			.saturating_add(RocksDbWeight::get().reads(1 as Weight))
 			.saturating_add(RocksDbWeight::get().reads((1 as Weight).saturating_mul(b as Weight)))
 			.saturating_add(RocksDbWeight::get().writes(3 as Weight))
@@ -315,7 +330,7 @@
 	// Storage: Refungible AccountBalance (r:1 w:1)
 	// Storage: Refungible Owned (r:0 w:1)
 	fn burn_item_partial() -> Weight {
-		(21_239_000 as Weight)
+		(25_578_000 as Weight)
 			.saturating_add(RocksDbWeight::get().reads(3 as Weight))
 			.saturating_add(RocksDbWeight::get().writes(4 as Weight))
 	}
@@ -327,13 +342,13 @@
 	// Storage: Refungible Owned (r:0 w:1)
 	// Storage: Refungible TokenProperties (r:0 w:1)
 	fn burn_item_fully() -> Weight {
-		(29_426_000 as Weight)
+		(33_593_000 as Weight)
 			.saturating_add(RocksDbWeight::get().reads(4 as Weight))
 			.saturating_add(RocksDbWeight::get().writes(7 as Weight))
 	}
 	// Storage: Refungible Balance (r:2 w:2)
 	fn transfer_normal() -> Weight {
-		(17_743_000 as Weight)
+		(21_049_000 as Weight)
 			.saturating_add(RocksDbWeight::get().reads(2 as Weight))
 			.saturating_add(RocksDbWeight::get().writes(2 as Weight))
 	}
@@ -341,7 +356,7 @@
 	// Storage: Refungible AccountBalance (r:1 w:1)
 	// Storage: Refungible Owned (r:0 w:1)
 	fn transfer_creating() -> Weight {
-		(20_699_000 as Weight)
+		(24_646_000 as Weight)
 			.saturating_add(RocksDbWeight::get().reads(3 as Weight))
 			.saturating_add(RocksDbWeight::get().writes(4 as Weight))
 	}
@@ -349,7 +364,7 @@
 	// Storage: Refungible AccountBalance (r:1 w:1)
 	// Storage: Refungible Owned (r:0 w:1)
 	fn transfer_removing() -> Weight {
-		(22_833_000 as Weight)
+		(26_570_000 as Weight)
 			.saturating_add(RocksDbWeight::get().reads(3 as Weight))
 			.saturating_add(RocksDbWeight::get().writes(4 as Weight))
 	}
@@ -357,21 +372,21 @@
 	// Storage: Refungible AccountBalance (r:2 w:2)
 	// Storage: Refungible Owned (r:0 w:2)
 	fn transfer_creating_removing() -> Weight {
-		(24_936_000 as Weight)
+		(28_906_000 as Weight)
 			.saturating_add(RocksDbWeight::get().reads(4 as Weight))
 			.saturating_add(RocksDbWeight::get().writes(6 as Weight))
 	}
 	// Storage: Refungible Balance (r:1 w:0)
 	// Storage: Refungible Allowance (r:0 w:1)
 	fn approve() -> Weight {
-		(13_446_000 as Weight)
+		(16_451_000 as Weight)
 			.saturating_add(RocksDbWeight::get().reads(1 as Weight))
 			.saturating_add(RocksDbWeight::get().writes(1 as Weight))
 	}
 	// Storage: Refungible Allowance (r:1 w:1)
 	// Storage: Refungible Balance (r:2 w:2)
 	fn transfer_from_normal() -> Weight {
-		(24_777_000 as Weight)
+		(29_545_000 as Weight)
 			.saturating_add(RocksDbWeight::get().reads(3 as Weight))
 			.saturating_add(RocksDbWeight::get().writes(3 as Weight))
 	}
@@ -380,7 +395,7 @@
 	// Storage: Refungible AccountBalance (r:1 w:1)
 	// Storage: Refungible Owned (r:0 w:1)
 	fn transfer_from_creating() -> Weight {
-		(28_483_000 as Weight)
+		(33_392_000 as Weight)
 			.saturating_add(RocksDbWeight::get().reads(4 as Weight))
 			.saturating_add(RocksDbWeight::get().writes(5 as Weight))
 	}
@@ -389,7 +404,7 @@
 	// Storage: Refungible AccountBalance (r:1 w:1)
 	// Storage: Refungible Owned (r:0 w:1)
 	fn transfer_from_removing() -> Weight {
-		(29_896_000 as Weight)
+		(35_446_000 as Weight)
 			.saturating_add(RocksDbWeight::get().reads(4 as Weight))
 			.saturating_add(RocksDbWeight::get().writes(5 as Weight))
 	}
@@ -398,7 +413,7 @@
 	// Storage: Refungible AccountBalance (r:2 w:2)
 	// Storage: Refungible Owned (r:0 w:2)
 	fn transfer_from_creating_removing() -> Weight {
-		(32_070_000 as Weight)
+		(37_762_000 as Weight)
 			.saturating_add(RocksDbWeight::get().reads(5 as Weight))
 			.saturating_add(RocksDbWeight::get().writes(7 as Weight))
 	}
@@ -411,15 +426,15 @@
 	// Storage: Refungible Owned (r:0 w:1)
 	// Storage: Refungible TokenProperties (r:0 w:1)
 	fn burn_from() -> Weight {
-		(36_789_000 as Weight)
+		(42_620_000 as Weight)
 			.saturating_add(RocksDbWeight::get().reads(5 as Weight))
 			.saturating_add(RocksDbWeight::get().writes(8 as Weight))
 	}
 	// Storage: Common CollectionPropertyPermissions (r:1 w:1)
 	fn set_token_property_permissions(b: u32, ) -> Weight {
 		(0 as Weight)
-			// Standard Error: 62_000
-			.saturating_add((15_803_000 as Weight).saturating_mul(b as Weight))
+			// Standard Error: 65_000
+			.saturating_add((16_513_000 as Weight).saturating_mul(b as Weight))
 			.saturating_add(RocksDbWeight::get().reads(1 as Weight))
 			.saturating_add(RocksDbWeight::get().writes(1 as Weight))
 	}
@@ -427,8 +442,8 @@
 	// Storage: Refungible TokenProperties (r:1 w:1)
 	fn set_token_properties(b: u32, ) -> Weight {
 		(0 as Weight)
-			// Standard Error: 1_668_000
-			.saturating_add((302_308_000 as Weight).saturating_mul(b as Weight))
+			// Standard Error: 1_583_000
+			.saturating_add((291_392_000 as Weight).saturating_mul(b as Weight))
 			.saturating_add(RocksDbWeight::get().reads(2 as Weight))
 			.saturating_add(RocksDbWeight::get().writes(1 as Weight))
 	}
@@ -436,16 +451,29 @@
 	// Storage: Refungible TokenProperties (r:1 w:1)
 	fn delete_token_properties(b: u32, ) -> Weight {
 		(0 as Weight)
-			// Standard Error: 1_619_000
-			.saturating_add((294_574_000 as Weight).saturating_mul(b as Weight))
+			// Standard Error: 1_699_000
+			.saturating_add((293_270_000 as Weight).saturating_mul(b as Weight))
 			.saturating_add(RocksDbWeight::get().reads(2 as Weight))
 			.saturating_add(RocksDbWeight::get().writes(1 as Weight))
 	}
 	// Storage: Refungible TotalSupply (r:1 w:1)
 	// Storage: Refungible Balance (r:1 w:1)
 	fn repartition_item() -> Weight {
-		(8_325_000 as Weight)
+		(19_206_000 as Weight)
 			.saturating_add(RocksDbWeight::get().reads(2 as Weight))
 			.saturating_add(RocksDbWeight::get().writes(2 as Weight))
 	}
+	// Storage: Refungible Balance (r:1 w:0)
+	// Storage: Refungible TotalSupply (r:1 w:0)
+	// Storage: Refungible TokenProperties (r:1 w:1)
+	fn set_parent_nft_unchecked() -> Weight {
+		(10_189_000 as Weight)
+			.saturating_add(RocksDbWeight::get().reads(3 as Weight))
+			.saturating_add(RocksDbWeight::get().writes(1 as Weight))
+	}
+	// Storage: Refungible Balance (r:2 w:0)
+	fn token_owner() -> Weight {
+		(8_205_000 as Weight)
+			.saturating_add(RocksDbWeight::get().reads(2 as Weight))
+	}
 }
modifiedpallets/unique/src/eth/mod.rsdiffbeforeafterboth
--- a/pallets/unique/src/eth/mod.rs
+++ b/pallets/unique/src/eth/mod.rs
@@ -17,26 +17,29 @@
 //! Implementation of CollectionHelpers contract.
 
 use core::marker::PhantomData;
-use evm_coder::{execution::*, generate_stubgen, solidity_interface, solidity, weight, types::*};
 use ethereum as _;
-use pallet_evm_coder_substrate::{SubstrateRecorder, WithRecorder};
-use pallet_evm::{OnMethodCall, PrecompileResult, account::CrossAccountId, PrecompileHandle};
-use up_data_structs::{
-	CollectionName, CollectionDescription, CollectionTokenPrefix, CreateCollectionData,
-	CollectionMode, PropertyValue,
-};
+use evm_coder::{execution::*, generate_stubgen, solidity_interface, solidity, weight, types::*};
 use frame_support::traits::Get;
 use pallet_common::{
-	CollectionById,
+	CollectionById, CollectionHandle,
+	dispatch::CollectionDispatch,
 	erc::{
+		CollectionHelpersEvents,
 		static_property::{key, value as property_value},
-		CollectionHelpersEvents,
 	},
-	dispatch::CollectionDispatch,
+	Pallet as PalletCommon,
 };
-use crate::{SelfWeightOf, Config, weights::WeightInfo};
+use pallet_evm_coder_substrate::{SubstrateRecorder, WithRecorder};
+use pallet_evm::{account::CrossAccountId, OnMethodCall, PrecompileHandle, PrecompileResult};
+use pallet_evm_coder_substrate::dispatch_to_evm;
+use up_data_structs::{
+	CollectionName, CollectionDescription, CollectionTokenPrefix, CreateCollectionData,
+	CollectionMode, PropertyKeyPermission, PropertyPermission, PropertyScope, PropertyValue,
+};
+
+use crate::{Config, SelfWeightOf, weights::WeightInfo};
 
-use sp_std::vec::Vec;
+use sp_std::{vec, vec::Vec};
 use alloc::format;
 
 /// See [`CollectionHelpersCall`]
@@ -151,6 +154,54 @@
 	Ok(data)
 }
 
+fn parent_nft_property_permissions() -> PropertyKeyPermission {
+	PropertyKeyPermission {
+		key: key::parent_nft(),
+		permission: PropertyPermission {
+			mutable: false,
+			collection_admin: false,
+			token_owner: true,
+		},
+	}
+}
+
+fn create_refungible_collection_internal<
+	T: Config + pallet_nonfungible::Config + pallet_refungible::Config,
+>(
+	caller: caller,
+	name: string,
+	description: string,
+	token_prefix: string,
+	base_uri: string,
+	add_properties: bool,
+) -> Result<address> {
+	let (caller, name, description, token_prefix, base_uri_value) =
+		convert_data::<T>(caller, name, description, token_prefix, base_uri)?;
+	let data = make_data::<T>(
+		name,
+		CollectionMode::ReFungible,
+		description,
+		token_prefix,
+		base_uri_value,
+		add_properties,
+	)?;
+
+	let collection_id = T::CollectionDispatch::create(caller.clone(), data)
+		.map_err(pallet_evm_coder_substrate::dispatch_to_evm::<T>)?;
+
+	let handle = <CollectionHandle<T>>::try_get(collection_id).map_err(dispatch_to_evm::<T>)?;
+	<PalletCommon<T>>::set_scoped_token_property_permissions(
+		&handle,
+		&caller,
+		PropertyScope::Eth,
+		vec![parent_nft_property_permissions()],
+	)
+	.map_err(dispatch_to_evm::<T>)?;
+
+	let address = pallet_common::eth::collection_id_to_address(collection_id);
+	Ok(address)
+}
+
 /// @title Contract, which allows users to operate with collections
 #[solidity_interface(name = "CollectionHelpers", events(CollectionHelpersEvents))]
 impl<T> EvmCollectionHelpers<T>
@@ -216,27 +267,20 @@
 
 	#[weight(<SelfWeightOf<T>>::create_collection())]
 	fn create_refungible_collection(
-		&self,
+		&mut self,
 		caller: caller,
 		name: string,
 		description: string,
 		token_prefix: string,
 	) -> Result<address> {
-		let (caller, name, description, token_prefix, _base_uri) =
-			convert_data::<T>(caller, name, description, token_prefix, "".into())?;
-		let data = make_data::<T>(
+		create_refungible_collection_internal::<T>(
+			caller,
 			name,
-			CollectionMode::ReFungible,
 			description,
 			token_prefix,
 			Default::default(),
 			false,
-		)?;
-		let collection_id = T::CollectionDispatch::create(caller, data)
-			.map_err(pallet_evm_coder_substrate::dispatch_to_evm::<T>)?;
-
-		let address = pallet_common::eth::collection_id_to_address(collection_id);
-		Ok(address)
+		)
 	}
 
 	#[weight(<SelfWeightOf<T>>::create_collection())]
@@ -249,21 +293,14 @@
 		token_prefix: string,
 		base_uri: string,
 	) -> Result<address> {
-		let (caller, name, description, token_prefix, base_uri_value) =
-			convert_data::<T>(caller, name, description, token_prefix, base_uri)?;
-		let data = make_data::<T>(
+		create_refungible_collection_internal::<T>(
+			caller,
 			name,
-			CollectionMode::NFT,
 			description,
 			token_prefix,
-			base_uri_value,
+			base_uri,
 			true,
-		)?;
-		let collection_id = T::CollectionDispatch::create(caller, data)
-			.map_err(pallet_evm_coder_substrate::dispatch_to_evm::<T>)?;
-
-		let address = pallet_common::eth::collection_id_to_address(collection_id);
-		Ok(address)
+		)
 	}
 
 	/// Check if a collection exists
modifiedpallets/unique/src/eth/stubs/CollectionHelpers.rawdiffbeforeafterboth

binary blob — no preview

modifiedpallets/unique/src/eth/stubs/CollectionHelpers.soldiffbeforeafterboth
--- a/pallets/unique/src/eth/stubs/CollectionHelpers.sol
+++ b/pallets/unique/src/eth/stubs/CollectionHelpers.sol
@@ -72,12 +72,12 @@
 		string memory name,
 		string memory description,
 		string memory tokenPrefix
-	) public view returns (address) {
+	) public returns (address) {
 		require(false, stub_error);
 		name;
 		description;
 		tokenPrefix;
-		dummy;
+		dummy = 0;
 		return 0x0000000000000000000000000000000000000000;
 	}
 
modifiedprimitives/data-structs/src/lib.rsdiffbeforeafterboth
--- a/primitives/data-structs/src/lib.rs
+++ b/primitives/data-structs/src/lib.rs
@@ -1050,6 +1050,7 @@
 pub enum PropertyScope {
 	None,
 	Rmrk,
+	Eth,
 }
 
 impl PropertyScope {
@@ -1058,6 +1059,7 @@
 		let scope_str: &[u8] = match self {
 			Self::None => return Ok(key),
 			Self::Rmrk => b"rmrk",
+			Self::Eth => b"eth",
 		};
 
 		[scope_str, b":", key.as_slice()]
modifiedruntime/common/weights.rsdiffbeforeafterboth
--- a/runtime/common/weights.rs
+++ b/runtime/common/weights.rs
@@ -116,6 +116,10 @@
 	fn burn_recursively_breadth_raw(amount: u32) -> Weight {
 		max_weight_of!(burn_recursively_breadth_raw(amount))
 	}
+
+	fn token_owner() -> Weight {
+		max_weight_of!(token_owner())
+	}
 }
 
 #[cfg(feature = "refungible")]
modifiedtests/package.jsondiffbeforeafterboth
--- a/tests/package.json
+++ b/tests/package.json
@@ -8,6 +8,7 @@
     "@polkadot/typegen": "8.7.2-15",
     "@types/chai": "^4.3.1",
     "@types/chai-as-promised": "^7.1.5",
+    "@types/chai-like": "^1.1.1",
     "@types/mocha": "^9.1.1",
     "@types/node": "^17.0.35",
     "@typescript-eslint/eslint-plugin": "^5.26.0",
@@ -96,6 +97,7 @@
     "@polkadot/util-crypto": "9.4.1",
     "bignumber.js": "^9.0.2",
     "chai-as-promised": "^7.1.1",
+    "chai-like": "^1.1.1",
     "find-process": "^1.4.7",
     "solc": "0.8.14-fixed",
     "web3": "^1.7.3"
modifiedtests/src/eth/api/CollectionHelpers.soldiffbeforeafterboth
--- a/tests/src/eth/api/CollectionHelpers.sol
+++ b/tests/src/eth/api/CollectionHelpers.sol
@@ -48,7 +48,7 @@
 		string memory name,
 		string memory description,
 		string memory tokenPrefix
-	) external view returns (address);
+	) external returns (address);
 
 	// Selector: createERC721MetadataCompatibleRFTCollection(string,string,string,string) a5596388
 	function createERC721MetadataCompatibleRFTCollection(
modifiedtests/src/eth/api/UniqueFungible.soldiffbeforeafterboth
--- a/tests/src/eth/api/UniqueFungible.sol
+++ b/tests/src/eth/api/UniqueFungible.sol
@@ -22,13 +22,7 @@
 	);
 }
 
-// Selector: 79cc6790
-interface ERC20UniqueExtensions is Dummy, ERC165 {
-	// Selector: burnFrom(address,uint256) 79cc6790
-	function burnFrom(address from, uint256 amount) external returns (bool);
-}
-
-// Selector: 7d9262e6
+// Selector: 6cf113cd
 interface Collection is Dummy, ERC165 {
 	// Set collection property.
 	//
@@ -174,6 +168,27 @@
 	//
 	// Selector: setCollectionMintMode(bool) 00018e84
 	function setCollectionMintMode(bool mode) external;
+
+	// Check that account is the owner or admin of the collection
+	//
+	// @param user account to verify
+	// @return "true" if account is the owner or admin
+	//
+	// Selector: verifyOwnerOrAdmin(address) c2282493
+	function verifyOwnerOrAdmin(address user) external view returns (bool);
+
+	// Returns collection type
+	//
+	// @return `Fungible` or `NFT` or `ReFungible`
+	//
+	// Selector: uniqueCollectionType() d34b55b8
+	function uniqueCollectionType() external returns (string memory);
+}
+
+// Selector: 79cc6790
+interface ERC20UniqueExtensions is Dummy, ERC165 {
+	// Selector: burnFrom(address,uint256) 79cc6790
+	function burnFrom(address from, uint256 amount) external returns (bool);
 }
 
 // Selector: 942e8b22
modifiedtests/src/eth/api/UniqueNFT.soldiffbeforeafterboth
--- a/tests/src/eth/api/UniqueNFT.sol
+++ b/tests/src/eth/api/UniqueNFT.sol
@@ -250,33 +250,7 @@
 	function finishMinting() external returns (bool);
 }
 
-// Selector: 780e9d63
-interface ERC721Enumerable is Dummy, ERC165 {
-	// @notice Enumerate valid NFTs
-	// @param index A counter less than `totalSupply()`
-	// @return The token identifier for the `index`th NFT,
-	//  (sort order not specified)
-	//
-	// Selector: tokenByIndex(uint256) 4f6ccce7
-	function tokenByIndex(uint256 index) external view returns (uint256);
-
-	// @dev Not implemented
-	//
-	// Selector: tokenOfOwnerByIndex(address,uint256) 2f745c59
-	function tokenOfOwnerByIndex(address owner, uint256 index)
-		external
-		view
-		returns (uint256);
-
-	// @notice Count NFTs tracked by this contract
-	// @return A count of valid NFTs tracked by this contract, where each one of
-	//  them has an assigned and queryable owner not equal to the zero address
-	//
-	// Selector: totalSupply() 18160ddd
-	function totalSupply() external view returns (uint256);
-}
-
-// Selector: 7d9262e6
+// Selector: 6cf113cd
 interface Collection is Dummy, ERC165 {
 	// Set collection property.
 	//
@@ -422,6 +396,47 @@
 	//
 	// Selector: setCollectionMintMode(bool) 00018e84
 	function setCollectionMintMode(bool mode) external;
+
+	// Check that account is the owner or admin of the collection
+	//
+	// @param user account to verify
+	// @return "true" if account is the owner or admin
+	//
+	// Selector: verifyOwnerOrAdmin(address) c2282493
+	function verifyOwnerOrAdmin(address user) external view returns (bool);
+
+	// Returns collection type
+	//
+	// @return `Fungible` or `NFT` or `ReFungible`
+	//
+	// Selector: uniqueCollectionType() d34b55b8
+	function uniqueCollectionType() external returns (string memory);
+}
+
+// Selector: 780e9d63
+interface ERC721Enumerable is Dummy, ERC165 {
+	// @notice Enumerate valid NFTs
+	// @param index A counter less than `totalSupply()`
+	// @return The token identifier for the `index`th NFT,
+	//  (sort order not specified)
+	//
+	// Selector: tokenByIndex(uint256) 4f6ccce7
+	function tokenByIndex(uint256 index) external view returns (uint256);
+
+	// @dev Not implemented
+	//
+	// Selector: tokenOfOwnerByIndex(address,uint256) 2f745c59
+	function tokenOfOwnerByIndex(address owner, uint256 index)
+		external
+		view
+		returns (uint256);
+
+	// @notice Count NFTs tracked by this contract
+	// @return A count of valid NFTs tracked by this contract, where each one of
+	//  them has an assigned and queryable owner not equal to the zero address
+	//
+	// Selector: totalSupply() 18160ddd
+	function totalSupply() external view returns (uint256);
 }
 
 // Selector: d74d154f
modifiedtests/src/eth/api/UniqueRefungible.soldiffbeforeafterboth
--- a/tests/src/eth/api/UniqueRefungible.sol
+++ b/tests/src/eth/api/UniqueRefungible.sol
@@ -248,33 +248,7 @@
 	function finishMinting() external returns (bool);
 }
 
-// Selector: 780e9d63
-interface ERC721Enumerable is Dummy, ERC165 {
-	// @notice Enumerate valid RFTs
-	// @param index A counter less than `totalSupply()`
-	// @return The token identifier for the `index`th NFT,
-	//  (sort order not specified)
-	//
-	// Selector: tokenByIndex(uint256) 4f6ccce7
-	function tokenByIndex(uint256 index) external view returns (uint256);
-
-	// Not implemented
-	//
-	// Selector: tokenOfOwnerByIndex(address,uint256) 2f745c59
-	function tokenOfOwnerByIndex(address owner, uint256 index)
-		external
-		view
-		returns (uint256);
-
-	// @notice Count RFTs tracked by this contract
-	// @return A count of valid RFTs tracked by this contract, where each one of
-	//  them has an assigned and queryable owner not equal to the zero address
-	//
-	// Selector: totalSupply() 18160ddd
-	function totalSupply() external view returns (uint256);
-}
-
-// Selector: 7d9262e6
+// Selector: 6cf113cd
 interface Collection is Dummy, ERC165 {
 	// Set collection property.
 	//
@@ -420,9 +394,50 @@
 	//
 	// Selector: setCollectionMintMode(bool) 00018e84
 	function setCollectionMintMode(bool mode) external;
+
+	// Check that account is the owner or admin of the collection
+	//
+	// @param user account to verify
+	// @return "true" if account is the owner or admin
+	//
+	// Selector: verifyOwnerOrAdmin(address) c2282493
+	function verifyOwnerOrAdmin(address user) external view returns (bool);
+
+	// Returns collection type
+	//
+	// @return `Fungible` or `NFT` or `ReFungible`
+	//
+	// Selector: uniqueCollectionType() d34b55b8
+	function uniqueCollectionType() external returns (string memory);
+}
+
+// Selector: 780e9d63
+interface ERC721Enumerable is Dummy, ERC165 {
+	// @notice Enumerate valid RFTs
+	// @param index A counter less than `totalSupply()`
+	// @return The token identifier for the `index`th NFT,
+	//  (sort order not specified)
+	//
+	// Selector: tokenByIndex(uint256) 4f6ccce7
+	function tokenByIndex(uint256 index) external view returns (uint256);
+
+	// Not implemented
+	//
+	// Selector: tokenOfOwnerByIndex(address,uint256) 2f745c59
+	function tokenOfOwnerByIndex(address owner, uint256 index)
+		external
+		view
+		returns (uint256);
+
+	// @notice Count RFTs tracked by this contract
+	// @return A count of valid RFTs tracked by this contract, where each one of
+	//  them has an assigned and queryable owner not equal to the zero address
+	//
+	// Selector: totalSupply() 18160ddd
+	function totalSupply() external view returns (uint256);
 }
 
-// Selector: d74d154f
+// Selector: 7c3bef89
 interface ERC721UniqueExtensions is Dummy, ERC165 {
 	// @notice Transfer ownership of an RFT
 	// @dev Throws unless `msg.sender` is the current owner. Throws if `to`
@@ -473,6 +488,16 @@
 	function mintBulkWithTokenURI(address to, Tuple0[] memory tokens)
 		external
 		returns (bool);
+
+	// Returns EVM address for refungible token
+	//
+	// @param token ID of the token
+	//
+	// Selector: tokenContractAddress(uint256) ab76fac6
+	function tokenContractAddress(uint256 token)
+		external
+		view
+		returns (address);
 }
 
 interface UniqueRefungible is
modifiedtests/src/eth/api/UniqueRefungibleToken.soldiffbeforeafterboth
--- a/tests/src/eth/api/UniqueRefungibleToken.sol
+++ b/tests/src/eth/api/UniqueRefungibleToken.sol
@@ -22,6 +22,23 @@
 	);
 }
 
+// Selector: 042f1106
+interface ERC1633UniqueExtensions is Dummy, ERC165 {
+	// Selector: setParentNFT(address,uint256) 042f1106
+	function setParentNFT(address collection, uint256 nftId)
+		external
+		returns (bool);
+}
+
+// Selector: 5755c3f2
+interface ERC1633 is Dummy, ERC165 {
+	// Selector: parentToken() 80a54001
+	function parentToken() external view returns (address);
+
+	// Selector: parentTokenId() d7f083f3
+	function parentTokenId() external view returns (uint256);
+}
+
 // Selector: 942e8b22
 interface ERC20 is Dummy, ERC165, ERC20Events {
 	// @return the name of the token.
@@ -115,5 +132,7 @@
 	Dummy,
 	ERC165,
 	ERC20,
-	ERC20UniqueExtensions
+	ERC20UniqueExtensions,
+	ERC1633,
+	ERC1633UniqueExtensions
 {}
modifiedtests/src/eth/collectionAdmin.test.tsdiffbeforeafterboth
--- a/tests/src/eth/collectionAdmin.test.ts
+++ b/tests/src/eth/collectionAdmin.test.ts
@@ -59,6 +59,22 @@
     expect(adminList[0].asSubstrate.toString().toLocaleLowerCase())
       .to.be.eq(newAdmin.address.toLocaleLowerCase());
   });
+  
+  itWeb3('Verify owner or admin', async ({api, web3, privateKeyWrapper}) => {
+    const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
+    const collectionHelper = evmCollectionHelpers(web3, owner);
+        
+    const result = await collectionHelper.methods
+      .createNonfungibleCollection('A', 'B', 'C')
+      .send();
+    const {collectionIdAddress} = await getCollectionAddressFromResult(api, result);
+
+    const newAdmin = createEthAccount(web3);
+    const collectionEvm = evmCollection(web3, owner, collectionIdAddress);
+    expect(await collectionEvm.methods.verifyOwnerOrAdmin(newAdmin).call()).to.be.false;
+    await collectionEvm.methods.addCollectionAdmin(newAdmin).send();
+    expect(await collectionEvm.methods.verifyOwnerOrAdmin(newAdmin).call()).to.be.true;
+  });
 
   itWeb3('(!negative tests!) Add admin by ADMIN is not allowed', async ({api, web3, privateKeyWrapper}) => {
     const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
modifiedtests/src/eth/collectionHelpersAbi.jsondiffbeforeafterboth
--- a/tests/src/eth/collectionHelpersAbi.json
+++ b/tests/src/eth/collectionHelpersAbi.json
@@ -61,7 +61,7 @@
     ],
     "name": "createRefungibleCollection",
     "outputs": [{ "internalType": "address", "name": "", "type": "address" }],
-    "stateMutability": "view",
+    "stateMutability": "nonpayable",
     "type": "function"
   },
   {
addedtests/src/eth/fractionalizer/Fractionalizer.bindiffbeforeafterboth
--- /dev/null
+++ b/tests/src/eth/fractionalizer/Fractionalizer.bin
@@ -0,0 +1 @@
+60c0604052600a60805269526546756e6769626c6560b01b60a0527fcdb72fd4e1d0d6d4eebd7ab142113ec2b4b06ddb24324db5c287ef01ab484d6b60055534801561004a57600080fd5b50600480546001600160a01b0319163317905561137a8061006c6000396000f3fe608060405234801561001057600080fd5b50600436106100575760003560e01c8063115091401461005c5780631b191ea214610071578063d470e60f14610084578063dbc38ad214610097578063eb292412146100aa575b600080fd5b61006f61006a366004610f85565b6100bd565b005b61006f61007f366004610ff2565b61035b565b61006f61009236600461108c565b6104c0565b61006f6100a53660046110b8565b61089d565b61006f6100b8366004611114565b610ee0565b6004546001600160a01b031633146100f05760405162461bcd60e51b81526004016100e79061114d565b60405180910390fd5b6000546001600160a01b0316156101495760405162461bcd60e51b815260206004820152601d60248201527f52465420636f6c6c656374696f6e20697320616c72656164792073657400000060448201526064016100e7565b60008190506000816001600160a01b031663d34b55b86040518163ffffffff1660e01b81526004016000604051808303816000875af1158015610190573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f191682016040526101b8919081019061118b565b905060055481805190602001201461022f5760405162461bcd60e51b815260206004820152603460248201527f57726f6e6720636f6c6c656374696f6e20747970652e20436f6c6c656374696f604482015273371034b9903737ba103932b33ab733b4b136329760611b60648201526084016100e7565b816001600160a01b03166304a460536040518163ffffffff1660e01b81526004016020604051808303816000875af115801561026f573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610293919061125b565b6103055760405162461bcd60e51b815260206004820152603c60248201527f4672616374696f6e616c697a657220636f6e74726163742073686f756c64206260448201527f6520616e2061646d696e206f662074686520636f6c6c656374696f6e0000000060648201526084016100e7565b600080546001600160a01b0319166001600160a01b0385169081179091556040519081527f7186a599bf2297b1f4c8957d30b0965291eee0021a5f9a0aeb54dcbd1ffdceef9060200160405180910390a1505050565b6004546001600160a01b031633146103855760405162461bcd60e51b81526004016100e79061114d565b6000546001600160a01b0316156103de5760405162461bcd60e51b815260206004820152601d60248201527f52465420636f6c6c656374696f6e20697320616c72656164792073657400000060448201526064016100e7565b6040516344a68ad560e01b8152736c4e9fe1ae37a41e93cee429e8e1881abdcbb54f9081906344a68ad590610421908a908a908a908a908a908a906004016112a1565b6020604051808303816000875af1158015610440573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061046491906112ea565b600080546001600160a01b0319166001600160a01b039290921691821790556040519081527f7186a599bf2297b1f4c8957d30b0965291eee0021a5f9a0aeb54dcbd1ffdceef906020015b60405180910390a150505050505050565b6000546001600160a01b03166105145760405162461bcd60e51b81526020600482015260196024820152781491950818dbdb1b1958dd1a5bdb881a5cc81b9bdd081cd95d603a1b60448201526064016100e7565b6000546001600160a01b038381169116146105685760405162461bcd60e51b81526020600482015260146024820152732bb937b7339029232a1031b7b63632b1ba34b7b760611b60448201526064016100e7565b600080546040516355bb7d6360e11b8152600481018490526001600160a01b039091169190829063ab76fac690602401602060405180830381865afa1580156105b5573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906105d991906112ea565b6001600160a01b03808216600090815260036020908152604091829020825180840190935280549093168083526001909301549082015291925061065f5760405162461bcd60e51b815260206004820181905260248201527f4e6f20636f72726573706f6e64696e67204e465420746f6b656e20666f756e6460448201526064016100e7565b6000829050806001600160a01b03166318160ddd6040518163ffffffff1660e01b8152600401602060405180830381865afa1580156106a2573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906106c69190611307565b6040516370a0823160e01b81523360048201526001600160a01b038316906370a0823190602401602060405180830381865afa15801561070a573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061072e9190611307565b1461078a5760405162461bcd60e51b815260206004820152602660248201527f4e6f7420616c6c2070696563657320617265206f776e6564206279207468652060448201526531b0b63632b960d11b60648201526084016100e7565b6040516323b872dd60e01b81526001600160a01b038516906323b872dd906107ba90339030908a90600401611320565b600060405180830381600087803b1580156107d457600080fd5b505af11580156107e8573d6000803e3d6000fd5b5050835160208501516040516323b872dd60e01b81526001600160a01b0390921693506323b872dd92506108229130913391600401611320565b600060405180830381600087803b15801561083c57600080fd5b505af1158015610850573d6000803e3d6000fd5b5050835160208501516040517fe9e9808d24ff79ccc3b1ecf48be7b2d11591adccc452150d0d7947cb48eb0d53945061088d935087929190611320565b60405180910390a1505050505050565b6000546001600160a01b03166108f15760405162461bcd60e51b81526020600482015260196024820152781491950818dbdb1b1958dd1a5bdb881a5cc81b9bdd081cd95d603a1b60448201526064016100e7565b600080546001600160a01b0385811683526001602081905260409093205491169160ff90911615151461098c5760405162461bcd60e51b815260206004820152603c60248201527f4672616374696f6e616c697a6174696f6e206f66207468697320636f6c6c656360448201527f74696f6e206973206e6f7420616c6c6f7765642062792061646d696e0000000060648201526084016100e7565b6040516331a9108f60e11b81526004810184905233906001600160a01b03861690636352211e90602401602060405180830381865afa1580156109d3573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906109f791906112ea565b6001600160a01b031614610a5d5760405162461bcd60e51b815260206004820152602760248201527f4f6e6c7920746f6b656e206f776e657220636f756c64206672616374696f6e616044820152661b1a5e99481a5d60ca1b60648201526084016100e7565b6040516323b872dd60e01b81526001600160a01b038516906323b872dd90610a8d90339030908890600401611320565b600060405180830381600087803b158015610aa757600080fd5b505af1158015610abb573d6000803e3d6000fd5b505050506001600160a01b0384166000908152600260209081526040808320868452909152812054819081908103610d0757836001600160a01b03166375794a3c6040518163ffffffff1660e01b8152600401602060405180830381865afa158015610b2b573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610b4f9190611307565b6040516340c10f1960e01b8152306004820152602481018290529093506001600160a01b038516906340c10f19906044016020604051808303816000875af1158015610b9f573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610bc3919061125b565b506040516355bb7d6360e11b8152600481018490526001600160a01b0385169063ab76fac690602401602060405180830381865afa158015610c09573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610c2d91906112ea565b6001600160a01b0388811660008181526002602090815260408083208c84528252808320899055805180820182528481528083018d8152878716808652600390945293829020905181546001600160a01b0319169616959095178555915160019094019390935551630217888360e11b81526004810191909152602481018990529193508392509063042f1106906044016020604051808303816000875af1158015610cdd573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610d01919061125b565b50610d98565b6001600160a01b0387811660009081526002602090815260408083208a8452909152908190205490516355bb7d6360e11b8152600481018290529094509085169063ab76fac690602401602060405180830381865afa158015610d6e573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610d9291906112ea565b91508190505b60405163d2418ca760e01b81526001600160801b03861660048201526001600160a01b0382169063d2418ca7906024016020604051808303816000875af1158015610de7573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610e0b919061125b565b5060405163a9059cbb60e01b81523360048201526001600160801b03861660248201526001600160a01b0382169063a9059cbb906044016020604051808303816000875af1158015610e61573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610e85919061125b565b50604080516001600160a01b03808a168252602082018990528416918101919091526001600160801b03861660608201527f29f372538523984f33874da1b50e596ce0f180a6eb04d7ff22bb2ce80e1576b6906080016104af565b6004546001600160a01b03163314610f0a5760405162461bcd60e51b81526004016100e79061114d565b6001600160a01b038216600081815260016020908152604091829020805460ff19168515159081179091558251938452908301527f6dad0aed33f4b7f07095619b668698e17943fd9f4c83e7cfcc7f6dd880a11588910160405180910390a15050565b6001600160a01b0381168114610f8257600080fd5b50565b600060208284031215610f9757600080fd5b8135610fa281610f6d565b9392505050565b60008083601f840112610fbb57600080fd5b50813567ffffffffffffffff811115610fd357600080fd5b602083019150836020828501011115610feb57600080fd5b9250929050565b6000806000806000806060878903121561100b57600080fd5b863567ffffffffffffffff8082111561102357600080fd5b61102f8a838b01610fa9565b9098509650602089013591508082111561104857600080fd5b6110548a838b01610fa9565b9096509450604089013591508082111561106d57600080fd5b5061107a89828a01610fa9565b979a9699509497509295939492505050565b6000806040838503121561109f57600080fd5b82356110aa81610f6d565b946020939093013593505050565b6000806000606084860312156110cd57600080fd5b83356110d881610f6d565b92506020840135915060408401356001600160801b03811681146110fb57600080fd5b809150509250925092565b8015158114610f8257600080fd5b6000806040838503121561112757600080fd5b823561113281610f6d565b9150602083013561114281611106565b809150509250929050565b6020808252600e908201526d27b7363c9037bbb732b91031b0b760911b604082015260600190565b634e487b7160e01b600052604160045260246000fd5b6000602080838503121561119e57600080fd5b825167ffffffffffffffff808211156111b657600080fd5b818501915085601f8301126111ca57600080fd5b8151818111156111dc576111dc611175565b604051601f8201601f19908116603f0116810190838211818310171561120457611204611175565b81604052828152888684870101111561121c57600080fd5b600093505b8284101561123e5784840186015181850187015292850192611221565b8284111561124f5760008684830101525b98975050505050505050565b60006020828403121561126d57600080fd5b8151610fa281611106565b81835281816020850137506000828201602090810191909152601f909101601f19169091010190565b6060815260006112b560608301888a611278565b82810360208401526112c8818789611278565b905082810360408401526112dd818587611278565b9998505050505050505050565b6000602082840312156112fc57600080fd5b8151610fa281610f6d565b60006020828403121561131957600080fd5b5051919050565b6001600160a01b03938416815291909216602082015260408101919091526060019056fea2646970667358221220a118fe8c3b83b3933baa7bfe084ed165a014ec509367252e5c99e1a3332d000364736f6c634300080f0033
\ No newline at end of file
addedtests/src/eth/fractionalizer/Fractionalizer.soldiffbeforeafterboth
--- /dev/null
+++ b/tests/src/eth/fractionalizer/Fractionalizer.sol
@@ -0,0 +1,189 @@
+// SPDX-License-Identifier:  Apache License
+pragma solidity >=0.8.0;
+import {CollectionHelpers} from "../api/CollectionHelpers.sol";
+import {ContractHelpers} from "../api/ContractHelpers.sol";
+import {UniqueRefungibleToken} from "../api/UniqueRefungibleToken.sol";
+import {UniqueRefungible} from "../api/UniqueRefungible.sol";
+import {UniqueNFT} from "../api/UniqueNFT.sol";
+
+/// @dev Fractionalization contract. It stores mappings between NFT and RFT tokens,
+///  stores allowlist of NFT tokens available for fractionalization, has methods
+///  for fractionalization and defractionalization of NFT tokens.
+contract Fractionalizer {
+    struct Token {
+        address _collection;
+        uint256 _tokenId;
+    }
+    address rftCollection;
+    mapping(address => bool) nftCollectionAllowList;
+    mapping(address => mapping(uint256 => uint256)) nft2rftMapping;
+    mapping(address => Token) rft2nftMapping;
+    bytes32 refungibleCollectionType = keccak256(bytes("ReFungible"));
+
+    receive() external payable onlyOwner {}
+
+    /// @dev Method modifier to only allow contract owner to call it.
+    modifier onlyOwner() {
+        address contracthelpersAddress = 0x842899ECF380553E8a4de75bF534cdf6fBF64049;
+        ContractHelpers contractHelpers = ContractHelpers(contracthelpersAddress);
+        address contractOwner = contractHelpers.contractOwner(address(this));
+        require(msg.sender == contractOwner, "Only owner can");
+        _;
+    }
+
+    /// @dev This emits when RFT collection setting is changed.
+    event RFTCollectionSet(address _collection);
+
+    /// @dev This emits when NFT collection is allowed or disallowed.
+    event AllowListSet(address _collection, bool _status);
+
+    /// @dev This emits when NFT token is fractionalized by contract.
+    event Fractionalized(address _collection, uint256 _tokenId, address _rftToken, uint128 _amount);
+
+    /// @dev This emits when NFT token is defractionalized by contract.
+    event Defractionalized(address _rftToken, address _nftCollection, uint256 _nftTokenId);
+
+    /// Set RFT collection that contract will work with. RFT tokens for fractionalized NFT tokens
+    /// would be created in this collection.
+    /// @dev Throws if RFT collection is already configured for this contract.
+    ///  Throws if collection of wrong type (NFT, Fungible) is provided instead
+    ///  of RFT collection.
+    ///  Throws if `msg.sender` is not owner or admin of provided RFT collection.
+    ///  Can only be called by contract owner.
+    /// @param _collection address of RFT collection.
+    function setRFTCollection(address _collection) public onlyOwner {
+        require(
+            rftCollection == address(0),
+            "RFT collection is already set"
+        );
+        UniqueRefungible refungibleContract = UniqueRefungible(_collection);
+        string memory collectionType = refungibleContract.uniqueCollectionType();
+        
+        require(
+            keccak256(bytes(collectionType)) == refungibleCollectionType,
+            "Wrong collection type. Collection is not refungible."
+        );
+        require(
+            refungibleContract.verifyOwnerOrAdmin(address(this)),
+            "Fractionalizer contract should be an admin of the collection"
+        );
+        rftCollection = _collection;
+        emit RFTCollectionSet(rftCollection);
+    }
+
+    /// Creates and sets RFT collection that contract will work with. RFT tokens for fractionalized NFT tokens
+    /// would be created in this collection.
+    /// @dev Throws if RFT collection is already configured for this contract.
+    ///  Can only be called by contract owner.
+    /// @param _name name for created RFT collection.
+    /// @param _description description for created RFT collection.
+    /// @param _tokenPrefix token prefix for created RFT collection.
+    function createAndSetRFTCollection(string calldata _name, string calldata _description, string calldata _tokenPrefix) public onlyOwner {
+        require(
+            rftCollection == address(0),
+            "RFT collection is already set"
+        );
+        address collectionHelpers = 0x6C4E9fE1AE37a41E93CEE429e8E1881aBdcbb54F;
+        rftCollection = CollectionHelpers(collectionHelpers).createRefungibleCollection(_name, _description, _tokenPrefix);
+        emit RFTCollectionSet(rftCollection);
+    }
+
+    /// Allow or disallow NFT collection tokens from being fractionalized by this contract.
+    /// @dev Can only be called by contract owner.
+    /// @param collection NFT token address.
+    /// @param status `true` to allow and `false` to disallow NFT token.
+    function setNftCollectionIsAllowed(address collection, bool status) public onlyOwner {
+        nftCollectionAllowList[collection] = status;
+        emit AllowListSet(collection, status);
+    }
+
+    /// Fractionilize NFT token.
+    /// @dev Takes NFT token from `msg.sender` and transfers RFT token to `msg.sender`
+    ///  instead. Creates new RFT token if provided NFT token never was fractionalized
+    ///  by this contract or existing RFT token if it was.
+    ///  Throws if RFT collection isn't configured for this contract.
+    ///  Throws if fractionalization of provided NFT token is not allowed
+    ///  Throws if `msg.sender` is not owner of provided NFT token
+    /// @param  _collection NFT collection address
+    /// @param  _token id of NFT token to be fractionalized
+    /// @param  _pieces number of pieces new RFT token would have
+    function nft2rft(address _collection, uint256 _token, uint128 _pieces) public {
+        require(
+            rftCollection != address(0),
+            "RFT collection is not set"
+        );
+        UniqueRefungible rftCollectionContract = UniqueRefungible(rftCollection);
+        require(
+            nftCollectionAllowList[_collection] == true,
+            "Fractionalization of this collection is not allowed by admin"
+        );
+        require(
+            UniqueNFT(_collection).ownerOf(_token) == msg.sender,
+            "Only token owner could fractionalize it"
+        );
+        UniqueNFT(_collection).transferFrom(
+            msg.sender,
+            address(this),
+            _token
+        );
+        uint256 rftTokenId;
+        address rftTokenAddress;
+        UniqueRefungibleToken rftTokenContract;
+        if (nft2rftMapping[_collection][_token] == 0) {
+            rftTokenId = rftCollectionContract.nextTokenId();
+            rftCollectionContract.mint(address(this), rftTokenId);
+            rftTokenAddress = rftCollectionContract.tokenContractAddress(rftTokenId);
+            nft2rftMapping[_collection][_token] = rftTokenId;
+            rft2nftMapping[rftTokenAddress] = Token(_collection, _token);
+
+            rftTokenContract = UniqueRefungibleToken(rftTokenAddress);
+            rftTokenContract.setParentNFT(_collection, _token);
+        } else {
+            rftTokenId = nft2rftMapping[_collection][_token];
+            rftTokenAddress = rftCollectionContract.tokenContractAddress(rftTokenId);
+            rftTokenContract = UniqueRefungibleToken(rftTokenAddress);
+        }
+        rftTokenContract.repartition(_pieces);
+        rftTokenContract.transfer(msg.sender, _pieces);
+        emit Fractionalized(_collection, _token, rftTokenAddress, _pieces);
+    }
+
+    /// Defrationalize NFT token.
+    /// @dev Takes RFT token from `msg.sender` and transfers corresponding NFT token
+    ///  to `msg.sender` instead.
+    ///  Throws if RFT collection isn't configured for this contract.
+    ///  Throws if provided RFT token is no from configured RFT collection.
+    ///  Throws if RFT token was not created by this contract.
+    ///  Throws if `msg.sender` isn't owner of all RFT token pieces.
+    /// @param _collection RFT collection address
+    /// @param _token id of RFT token
+    function rft2nft(address _collection, uint256 _token) public {
+        require(
+            rftCollection != address(0),
+            "RFT collection is not set"
+        );
+        require(
+            rftCollection == _collection,
+            "Wrong RFT collection"
+        );
+        UniqueRefungible rftCollectionContract = UniqueRefungible(rftCollection);
+        address rftTokenAddress = rftCollectionContract.tokenContractAddress(_token);
+        Token memory nftToken = rft2nftMapping[rftTokenAddress];
+        require(
+            nftToken._collection != address(0),
+            "No corresponding NFT token found"
+        );
+        UniqueRefungibleToken rftTokenContract = UniqueRefungibleToken(rftTokenAddress);
+        require(
+            rftTokenContract.balanceOf(msg.sender) == rftTokenContract.totalSupply(),
+            "Not all pieces are owned by the caller"
+        );
+        rftCollectionContract.transferFrom(msg.sender, address(this), _token);
+        UniqueNFT(nftToken._collection).transferFrom(
+            address(this),
+            msg.sender,
+            nftToken._tokenId
+        );
+        emit Defractionalized(rftTokenAddress, nftToken._collection, nftToken._tokenId);
+    }
+}
\ No newline at end of file
addedtests/src/eth/fractionalizer/FractionalizerAbi.jsondiffbeforeafterboth
--- /dev/null
+++ b/tests/src/eth/fractionalizer/FractionalizerAbi.json
@@ -0,0 +1,142 @@
+[
+  { "inputs": [], "stateMutability": "nonpayable", "type": "constructor" },
+  {
+    "anonymous": false,
+    "inputs": [
+      {
+        "indexed": false,
+        "internalType": "address",
+        "name": "_collection",
+        "type": "address"
+      },
+      {
+        "indexed": false,
+        "internalType": "bool",
+        "name": "_status",
+        "type": "bool"
+      }
+    ],
+    "name": "AllowListSet",
+    "type": "event"
+  },
+  {
+    "anonymous": false,
+    "inputs": [
+      {
+        "indexed": false,
+        "internalType": "address",
+        "name": "_rftToken",
+        "type": "address"
+      },
+      {
+        "indexed": false,
+        "internalType": "address",
+        "name": "_nftCollection",
+        "type": "address"
+      },
+      {
+        "indexed": false,
+        "internalType": "uint256",
+        "name": "_nftTokenId",
+        "type": "uint256"
+      }
+    ],
+    "name": "Defractionalized",
+    "type": "event"
+  },
+  {
+    "anonymous": false,
+    "inputs": [
+      {
+        "indexed": false,
+        "internalType": "address",
+        "name": "_collection",
+        "type": "address"
+      },
+      {
+        "indexed": false,
+        "internalType": "uint256",
+        "name": "_tokenId",
+        "type": "uint256"
+      },
+      {
+        "indexed": false,
+        "internalType": "address",
+        "name": "_rftToken",
+        "type": "address"
+      },
+      {
+        "indexed": false,
+        "internalType": "uint128",
+        "name": "_amount",
+        "type": "uint128"
+      }
+    ],
+    "name": "Fractionalized",
+    "type": "event"
+  },
+  {
+    "anonymous": false,
+    "inputs": [
+      {
+        "indexed": false,
+        "internalType": "address",
+        "name": "_collection",
+        "type": "address"
+      }
+    ],
+    "name": "RFTCollectionSet",
+    "type": "event"
+  },
+  {
+    "inputs": [
+      { "internalType": "string", "name": "_name", "type": "string" },
+      { "internalType": "string", "name": "_description", "type": "string" },
+      { "internalType": "string", "name": "_tokenPrefix", "type": "string" }
+    ],
+    "name": "createAndSetRFTCollection",
+    "outputs": [],
+    "stateMutability": "nonpayable",
+    "type": "function"
+  },
+  {
+    "inputs": [
+      { "internalType": "address", "name": "_collection", "type": "address" },
+      { "internalType": "uint256", "name": "_token", "type": "uint256" },
+      { "internalType": "uint128", "name": "_pieces", "type": "uint128" }
+    ],
+    "name": "nft2rft",
+    "outputs": [],
+    "stateMutability": "nonpayable",
+    "type": "function"
+  },
+  {
+    "inputs": [
+      { "internalType": "address", "name": "_collection", "type": "address" },
+      { "internalType": "uint256", "name": "_token", "type": "uint256" }
+    ],
+    "name": "rft2nft",
+    "outputs": [],
+    "stateMutability": "nonpayable",
+    "type": "function"
+  },
+  {
+    "inputs": [
+      { "internalType": "address", "name": "collection", "type": "address" },
+      { "internalType": "bool", "name": "status", "type": "bool" }
+    ],
+    "name": "setNftCollectionIsAllowed",
+    "outputs": [],
+    "stateMutability": "nonpayable",
+    "type": "function"
+  },
+  {
+    "inputs": [
+      { "internalType": "address", "name": "_collection", "type": "address" }
+    ],
+    "name": "setRFTCollection",
+    "outputs": [],
+    "stateMutability": "nonpayable",
+    "type": "function"
+  }
+]
addedtests/src/eth/fractionalizer/fractionalizer.test.tsdiffbeforeafterboth
--- /dev/null
+++ b/tests/src/eth/fractionalizer/fractionalizer.test.ts
@@ -0,0 +1,470 @@
+// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.
+// This file is part of Unique Network.
+
+// Unique Network is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+
+// Unique Network is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+// GNU General Public License for more details.
+
+// You should have received a copy of the GNU General Public License
+// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
+
+
+import Web3 from 'web3';
+import {ApiPromise} from '@polkadot/api';
+import {evmToAddress} from '@polkadot/util-crypto';
+import {readFile} from 'fs/promises';
+import {executeTransaction, submitTransactionAsync} from '../../substrate/substrate-api';
+import {getCreateCollectionResult, getCreateItemResult, UNIQUE} from '../../util/helpers';
+import {collectionIdToAddress, CompiledContract, createEthAccountWithBalance, createNonfungibleCollection, createRefungibleCollection, GAS_ARGS, itWeb3, tokenIdFromAddress, uniqueNFT, uniqueRefungible, uniqueRefungibleToken} from '../util/helpers';
+import {Contract} from 'web3-eth-contract';
+import * as solc from 'solc';
+
+import chai from 'chai';
+import chaiLike from 'chai-like';
+import {IKeyringPair} from '@polkadot/types/types';
+chai.use(chaiLike);
+const expect = chai.expect;
+let fractionalizer: CompiledContract;
+
+async function compileFractionalizer() {
+  if (!fractionalizer) {
+    const input = {
+      language: 'Solidity',
+      sources: {
+        ['Fractionalizer.sol']: {
+          content: (await readFile(`${__dirname}/Fractionalizer.sol`)).toString(),
+        },
+      },
+      settings: {
+        outputSelection: {
+          '*': {
+            '*': ['*'],
+          },
+        },
+      },
+    };
+    const json = JSON.parse(solc.compile(JSON.stringify(input), {import: await findImports()}));
+    const out = json.contracts['Fractionalizer.sol']['Fractionalizer'];
+
+    fractionalizer = {
+      abi: out.abi,
+      object: '0x' + out.evm.bytecode.object,
+    };
+  }
+  return fractionalizer;
+}
+
+async function findImports() {
+  const collectionHelpers = (await readFile(`${__dirname}/../api/CollectionHelpers.sol`)).toString();
+  const contractHelpers = (await readFile(`${__dirname}/../api/ContractHelpers.sol`)).toString();
+  const uniqueRefungibleToken = (await readFile(`${__dirname}/../api/UniqueRefungibleToken.sol`)).toString();
+  const uniqueRefungible = (await readFile(`${__dirname}/../api/UniqueRefungible.sol`)).toString();
+  const uniqueNFT = (await readFile(`${__dirname}/../api/UniqueNFT.sol`)).toString();
+
+  return function(path: string) {
+    switch (path) {
+      case 'api/CollectionHelpers.sol': return {contents: `${collectionHelpers}`};
+      case 'api/ContractHelpers.sol': return {contents: `${contractHelpers}`};
+      case 'api/UniqueRefungibleToken.sol': return {contents: `${uniqueRefungibleToken}`};
+      case 'api/UniqueRefungible.sol': return {contents: `${uniqueRefungible}`};
+      case 'api/UniqueNFT.sol': return {contents: `${uniqueNFT}`};
+      default: return {error: 'File not found'};
+    }
+  };
+}
+
+async function deployFractionalizer(web3: Web3, owner: string) {
+  const compiled = await compileFractionalizer();
+  const fractionalizerContract = new web3.eth.Contract(compiled.abi, undefined, {
+    data: compiled.object,
+    from: owner,
+    ...GAS_ARGS,
+  });
+  return await fractionalizerContract.deploy({data: compiled.object}).send({from: owner});
+}
+
+async function initFractionalizer(api: ApiPromise, web3: Web3, privateKeyWrapper: (account: string) => IKeyringPair, owner: string) {
+  const fractionalizer = await deployFractionalizer(web3, owner);
+  const amount = 10n * UNIQUE;
+  await web3.eth.sendTransaction({from: owner, to: fractionalizer.options.address, value: `${amount}`, ...GAS_ARGS});
+  const result = await fractionalizer.methods.createAndSetRFTCollection('A', 'B', 'C').send();
+  const rftCollectionAddress = result.events.RFTCollectionSet.returnValues._collection;
+  return {fractionalizer, rftCollectionAddress};
+}
+
+async function createRFTToken(api: ApiPromise, web3: Web3, owner: string, fractionalizer: Contract, amount: bigint) {
+  const {collectionIdAddress: nftCollectionAddress} = await createNonfungibleCollection(api, web3, owner);
+  const nftContract = uniqueNFT(web3, nftCollectionAddress, owner);
+  const nftTokenId = await nftContract.methods.nextTokenId().call();
+  await nftContract.methods.mint(owner, nftTokenId).send();
+
+  await fractionalizer.methods.setNftCollectionIsAllowed(nftCollectionAddress, true).send();
+  await nftContract.methods.approve(fractionalizer.options.address, nftTokenId).send();
+  const result = await fractionalizer.methods.nft2rft(nftCollectionAddress, nftTokenId, amount).send();
+  const {_collection, _tokenId, _rftToken} = result.events.Fractionalized.returnValues;
+  return {
+    nftCollectionAddress: _collection,
+    nftTokenId: _tokenId,
+    rftTokenAddress: _rftToken,
+  };
+}
+
+describe('Fractionalizer contract usage', () => {
+  itWeb3('Set RFT collection', async ({api, web3, privateKeyWrapper}) => {
+    const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
+    const fractionalizer = await deployFractionalizer(web3, owner);
+    const {collectionIdAddress} = await createRefungibleCollection(api, web3, owner);
+    const refungibleContract = uniqueRefungible(web3, collectionIdAddress, owner);
+    await refungibleContract.methods.addCollectionAdmin(fractionalizer.options.address).send();
+    const result = await fractionalizer.methods.setRFTCollection(collectionIdAddress).send();
+    expect(result.events).to.be.like({
+      RFTCollectionSet: {
+        returnValues: {
+          _collection: collectionIdAddress,
+        },
+      },
+    });
+  });
+
+  itWeb3('Mint RFT collection', async ({api, web3, privateKeyWrapper}) => {
+    const alice = privateKeyWrapper('//Alice');
+    const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
+    const fractionalizer = await deployFractionalizer(web3, owner);
+    const tx = api.tx.balances.transfer(evmToAddress(fractionalizer.options.address), 10n * UNIQUE);
+    await submitTransactionAsync(alice, tx);
+
+    const result = await fractionalizer.methods.createAndSetRFTCollection('A', 'B', 'C').send({from: owner});
+    expect(result.events).to.be.like({
+      RFTCollectionSet: {},
+    });
+    expect(result.events.RFTCollectionSet.returnValues._collection).to.be.ok;
+  });
+
+  itWeb3('Set Allowlist', async ({api, web3, privateKeyWrapper}) => {
+    const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
+    const {fractionalizer} = await initFractionalizer(api, web3, privateKeyWrapper, owner);
+    const {collectionIdAddress: nftCollectionAddress} = await createNonfungibleCollection(api, web3, owner);
+    const result1 = await fractionalizer.methods.setNftCollectionIsAllowed(nftCollectionAddress, true).send({from: owner});
+    expect(result1.events).to.be.like({
+      AllowListSet: {
+        returnValues: {
+          _collection: nftCollectionAddress,
+          _status: true,
+        },
+      },
+    });
+    const result2 = await fractionalizer.methods.setNftCollectionIsAllowed(nftCollectionAddress, false).send({from: owner});
+    expect(result2.events).to.be.like({
+      AllowListSet: {
+        returnValues: {
+          _collection: nftCollectionAddress,
+          _status: false,
+        },
+      },
+    });
+  });
+
+  itWeb3('NFT to RFT', async ({api, web3, privateKeyWrapper}) => {
+    const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
+
+    const {collectionIdAddress: nftCollectionAddress} = await createNonfungibleCollection(api, web3, owner);
+    const nftContract = uniqueNFT(web3, nftCollectionAddress, owner);
+    const nftTokenId = await nftContract.methods.nextTokenId().call();
+    await nftContract.methods.mint(owner, nftTokenId).send();
+
+    const {fractionalizer} = await initFractionalizer(api, web3, privateKeyWrapper, owner);
+
+    await fractionalizer.methods.setNftCollectionIsAllowed(nftCollectionAddress, true).send();
+    await nftContract.methods.approve(fractionalizer.options.address, nftTokenId).send();
+    const result = await fractionalizer.methods.nft2rft(nftCollectionAddress, nftTokenId, 100).send();
+    expect(result.events).to.be.like({
+      Fractionalized: {
+        returnValues: {
+          _collection: nftCollectionAddress,
+          _tokenId: nftTokenId,
+          _amount: '100',
+        },
+      },
+    });
+    const rftTokenAddress = result.events.Fractionalized.returnValues._rftToken;
+    const rftTokenContract = uniqueRefungibleToken(web3, rftTokenAddress, owner);
+    expect(await rftTokenContract.methods.balanceOf(owner).call()).to.equal('100');
+  });
+
+  itWeb3('RFT to NFT', async ({api, web3, privateKeyWrapper}) => {
+    const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
+
+    const {fractionalizer, rftCollectionAddress} = await initFractionalizer(api, web3, privateKeyWrapper, owner);
+    const {rftTokenAddress, nftCollectionAddress, nftTokenId} = await createRFTToken(api, web3, owner, fractionalizer, 100n);
+
+    const {collectionId, tokenId} = tokenIdFromAddress(rftTokenAddress);
+    const refungibleAddress = collectionIdToAddress(collectionId);
+    expect(rftCollectionAddress).to.be.equal(refungibleAddress);
+    const refungibleTokenContract = uniqueRefungibleToken(web3, rftTokenAddress, owner);
+    await refungibleTokenContract.methods.approve(fractionalizer.options.address, 100).send();
+    const result = await fractionalizer.methods.rft2nft(refungibleAddress, tokenId).send();
+    expect(result.events).to.be.like({
+      Defractionalized: {
+        returnValues: {
+          _rftToken: rftTokenAddress,
+          _nftCollection: nftCollectionAddress,
+          _nftTokenId: nftTokenId,
+        },
+      },
+    });
+  });
+});
+
+
+
+describe('Negative Integration Tests for fractionalizer', () => {
+  itWeb3('call setRFTCollection twice', async ({api, web3, privateKeyWrapper}) => {
+    const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
+    const {collectionIdAddress} = await createRefungibleCollection(api, web3, owner);
+    const refungibleContract = uniqueRefungible(web3, collectionIdAddress, owner);
+
+    const fractionalizer = await deployFractionalizer(web3, owner);
+    await refungibleContract.methods.addCollectionAdmin(fractionalizer.options.address).send();
+    await fractionalizer.methods.setRFTCollection(collectionIdAddress).send();
+
+    await expect(fractionalizer.methods.setRFTCollection(collectionIdAddress).call())
+      .to.be.rejectedWith(/RFT collection is already set$/g);
+  });
+
+  itWeb3('call setRFTCollection with NFT collection', async ({api, web3, privateKeyWrapper}) => {
+    const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
+    const {collectionIdAddress} = await createNonfungibleCollection(api, web3, owner);
+    const nftContract = uniqueNFT(web3, collectionIdAddress, owner);
+
+    const fractionalizer = await deployFractionalizer(web3, owner);
+    await nftContract.methods.addCollectionAdmin(fractionalizer.options.address).send();
+
+    await expect(fractionalizer.methods.setRFTCollection(collectionIdAddress).call())
+      .to.be.rejectedWith(/Wrong collection type. Collection is not refungible.$/g);
+  });
+
+  itWeb3('call setRFTCollection while not collection admin', async ({api, web3, privateKeyWrapper}) => {
+    const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
+    const fractionalizer = await deployFractionalizer(web3, owner);
+    const {collectionIdAddress} = await createRefungibleCollection(api, web3, owner);
+
+    await expect(fractionalizer.methods.setRFTCollection(collectionIdAddress).call())
+      .to.be.rejectedWith(/Fractionalizer contract should be an admin of the collection$/g);
+  });
+
+  itWeb3('call setRFTCollection after createAndSetRFTCollection', async ({api, web3, privateKeyWrapper}) => {
+    const alice = privateKeyWrapper('//Alice');
+    const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
+    const fractionalizer = await deployFractionalizer(web3, owner);
+    const tx = api.tx.balances.transfer(evmToAddress(fractionalizer.options.address), 10n * UNIQUE);
+    await submitTransactionAsync(alice, tx);
+
+    const result = await fractionalizer.methods.createAndSetRFTCollection('A', 'B', 'C').send({from: owner});
+    const collectionIdAddress = result.events.RFTCollectionSet.returnValues._collection;
+
+    await expect(fractionalizer.methods.setRFTCollection(collectionIdAddress).call())
+      .to.be.rejectedWith(/RFT collection is already set$/g);
+  });
+
+  itWeb3('call nft2rft without setting RFT collection for contract', async ({api, web3, privateKeyWrapper}) => {
+    const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
+
+    const {collectionIdAddress: nftCollectionAddress} = await createNonfungibleCollection(api, web3, owner);
+    const nftContract = uniqueNFT(web3, nftCollectionAddress, owner);
+    const nftTokenId = await nftContract.methods.nextTokenId().call();
+    await nftContract.methods.mint(owner, nftTokenId).send();
+
+    const fractionalizer = await deployFractionalizer(web3, owner);
+
+    await expect(fractionalizer.methods.nft2rft(nftCollectionAddress, nftTokenId, 100).call())
+      .to.be.rejectedWith(/RFT collection is not set$/g);
+  });
+
+  itWeb3('call nft2rft while not owner of NFT token', async ({api, web3, privateKeyWrapper}) => {
+    const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
+    const nftOwner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
+
+    const {collectionIdAddress: nftCollectionAddress} = await createNonfungibleCollection(api, web3, owner);
+    const nftContract = uniqueNFT(web3, nftCollectionAddress, owner);
+    const nftTokenId = await nftContract.methods.nextTokenId().call();
+    await nftContract.methods.mint(owner, nftTokenId).send();
+    await nftContract.methods.transfer(nftOwner, 1).send();
+
+
+    const {fractionalizer} = await initFractionalizer(api, web3, privateKeyWrapper, owner);
+    await fractionalizer.methods.setNftCollectionIsAllowed(nftCollectionAddress, true).send();
+
+    await expect(fractionalizer.methods.nft2rft(nftCollectionAddress, nftTokenId, 100).call())
+      .to.be.rejectedWith(/Only token owner could fractionalize it$/g);
+  });
+
+  itWeb3('call nft2rft while not in list of allowed accounts', async ({api, web3, privateKeyWrapper}) => {
+    const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
+
+    const {collectionIdAddress: nftCollectionAddress} = await createNonfungibleCollection(api, web3, owner);
+    const nftContract = uniqueNFT(web3, nftCollectionAddress, owner);
+    const nftTokenId = await nftContract.methods.nextTokenId().call();
+    await nftContract.methods.mint(owner, nftTokenId).send();
+
+    const {fractionalizer} = await initFractionalizer(api, web3, privateKeyWrapper, owner);
+
+    await nftContract.methods.approve(fractionalizer.options.address, nftTokenId).send();
+    await expect(fractionalizer.methods.nft2rft(nftCollectionAddress, nftTokenId, 100).call())
+      .to.be.rejectedWith(/Fractionalization of this collection is not allowed by admin$/g);
+  });
+
+  itWeb3('call nft2rft while fractionalizer doesnt have approval for nft token', async ({api, web3, privateKeyWrapper}) => {
+    const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
+
+    const {collectionIdAddress: nftCollectionAddress} = await createNonfungibleCollection(api, web3, owner);
+    const nftContract = uniqueNFT(web3, nftCollectionAddress, owner);
+    const nftTokenId = await nftContract.methods.nextTokenId().call();
+    await nftContract.methods.mint(owner, nftTokenId).send();
+
+    const {fractionalizer} = await initFractionalizer(api, web3, privateKeyWrapper, owner);
+
+    await fractionalizer.methods.setNftCollectionIsAllowed(nftCollectionAddress, true).send();
+    await expect(fractionalizer.methods.nft2rft(nftCollectionAddress, nftTokenId, 100).call())
+      .to.be.rejectedWith(/ApprovedValueTooLow$/g);
+  });
+
+  itWeb3('call rft2nft without setting RFT collection for contract', async ({api, web3, privateKeyWrapper}) => {
+    const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
+
+    const fractionalizer = await deployFractionalizer(web3, owner);
+    const {collectionIdAddress: rftCollectionAddress} = await createRefungibleCollection(api, web3, owner);
+    const refungibleContract = uniqueRefungible(web3, rftCollectionAddress, owner);
+    const rftTokenId = await refungibleContract.methods.nextTokenId().call();
+    await refungibleContract.methods.mint(owner, rftTokenId).send();
+    
+    await expect(fractionalizer.methods.rft2nft(rftCollectionAddress, rftTokenId).call())
+      .to.be.rejectedWith(/RFT collection is not set$/g);
+  });
+
+  itWeb3('call rft2nft for RFT token that is not from configured RFT collection', async ({api, web3, privateKeyWrapper}) => {
+    const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
+
+    const {fractionalizer} = await initFractionalizer(api, web3, privateKeyWrapper, owner);
+    const {collectionIdAddress: rftCollectionAddress} = await createRefungibleCollection(api, web3, owner);
+    const refungibleContract = uniqueRefungible(web3, rftCollectionAddress, owner);
+    const rftTokenId = await refungibleContract.methods.nextTokenId().call();
+    await refungibleContract.methods.mint(owner, rftTokenId).send();
+    
+    await expect(fractionalizer.methods.rft2nft(rftCollectionAddress, rftTokenId).call())
+      .to.be.rejectedWith(/Wrong RFT collection$/g);
+  });
+
+  itWeb3('call rft2nft for RFT token that was not minted by fractionalizer contract', async ({api, web3, privateKeyWrapper}) => {
+    const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
+    const {collectionIdAddress: rftCollectionAddress} = await createRefungibleCollection(api, web3, owner);
+
+    const fractionalizer = await deployFractionalizer(web3, owner);
+    const refungibleContract = uniqueRefungible(web3, rftCollectionAddress, owner);
+
+    await refungibleContract.methods.addCollectionAdmin(fractionalizer.options.address).send();
+    await fractionalizer.methods.setRFTCollection(rftCollectionAddress).send();
+
+    const rftTokenId = await refungibleContract.methods.nextTokenId().call();
+    await refungibleContract.methods.mint(owner, rftTokenId).send();
+    
+    await expect(fractionalizer.methods.rft2nft(rftCollectionAddress, rftTokenId).call())
+      .to.be.rejectedWith(/No corresponding NFT token found$/g);
+  });
+
+  itWeb3('call rft2nft without owning all RFT pieces', async ({api, web3, privateKeyWrapper}) => {
+    const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
+    const receiver = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
+
+    const {fractionalizer, rftCollectionAddress} = await initFractionalizer(api, web3, privateKeyWrapper, owner);
+    const {rftTokenAddress} = await createRFTToken(api, web3, owner, fractionalizer, 100n);
+    
+    const {tokenId} = tokenIdFromAddress(rftTokenAddress);
+    const refungibleTokenContract = uniqueRefungibleToken(web3, rftTokenAddress, owner);
+    await refungibleTokenContract.methods.transfer(receiver, 50).send();
+    await refungibleTokenContract.methods.approve(fractionalizer.options.address, 50).send();
+    await expect(fractionalizer.methods.rft2nft(rftCollectionAddress, tokenId).call())
+      .to.be.rejectedWith(/Not all pieces are owned by the caller$/g);
+  });
+
+  itWeb3('send QTZ/UNQ to contract from non owner', async ({api, web3, privateKeyWrapper}) => {
+    const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
+    const payer = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
+
+    const fractionalizer = await deployFractionalizer(web3, owner);
+    const amount = 10n * UNIQUE;
+    await expect(web3.eth.sendTransaction({from: payer, to: fractionalizer.options.address, value: `${amount}`, ...GAS_ARGS})).to.be.rejected;
+  });
+
+  itWeb3('fractionalize NFT with NFT transfers disallowed', async ({api, web3, privateKeyWrapper}) => {
+    const alice = privateKeyWrapper('//Alice');
+    let collectionId;
+    {
+      const tx = api.tx.unique.createCollectionEx({name: 'A', description: 'B', tokenPrefix: 'C', mode: 'NFT'});
+      const events = await submitTransactionAsync(alice, tx);
+      const result = getCreateCollectionResult(events);
+      collectionId = result.collectionId;
+    }
+    const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
+    let nftTokenId;
+    {
+      const createData = {nft: {}};
+      const tx = api.tx.unique.createItem(collectionId, {Ethereum: owner}, createData as any);
+      const events = await executeTransaction(api, alice, tx);
+      const result = getCreateItemResult(events);
+      nftTokenId = result.itemId;
+    }
+    {
+      const tx = api.tx.unique.setTransfersEnabledFlag(collectionId, false);
+      await executeTransaction(api, alice, tx);
+    }
+    const nftCollectionAddress = collectionIdToAddress(collectionId);
+    const {fractionalizer} = await initFractionalizer(api, web3, privateKeyWrapper, owner);
+    await fractionalizer.methods.setNftCollectionIsAllowed(nftCollectionAddress, true).send();
+
+    const nftContract = uniqueNFT(web3, nftCollectionAddress, owner);
+    await nftContract.methods.approve(fractionalizer.options.address, nftTokenId).send();
+    await expect(fractionalizer.methods.nft2rft(nftCollectionAddress, nftTokenId, 100).call())
+      .to.be.rejectedWith(/TransferNotAllowed$/g);
+  });
+  
+  itWeb3('fractionalize NFT with RFT transfers disallowed', async ({api, web3, privateKeyWrapper}) => {
+    const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
+    const alice = privateKeyWrapper('//Alice');
+
+    let collectionId;
+    {
+      const tx = api.tx.unique.createCollectionEx({name: 'A', description: 'B', tokenPrefix: 'C', mode: 'ReFungible'});
+      const events = await submitTransactionAsync(alice, tx);
+      const result = getCreateCollectionResult(events);
+      collectionId = result.collectionId;
+    }
+    const rftCollectionAddress = collectionIdToAddress(collectionId);
+    const fractionalizer = await deployFractionalizer(web3, owner);
+    {
+      const changeAdminTx = api.tx.unique.addCollectionAdmin(collectionId, {Ethereum: fractionalizer.options.address});
+      await submitTransactionAsync(alice, changeAdminTx);
+    }
+    await fractionalizer.methods.setRFTCollection(rftCollectionAddress).send();
+    {
+      const tx = api.tx.unique.setTransfersEnabledFlag(collectionId, false);
+      await executeTransaction(api, alice, tx);
+    }
+
+    const {collectionIdAddress: nftCollectionAddress} = await createNonfungibleCollection(api, web3, owner);
+    const nftContract = uniqueNFT(web3, nftCollectionAddress, owner);
+    const nftTokenId = await nftContract.methods.nextTokenId().call();
+    await nftContract.methods.mint(owner, nftTokenId).send();
+
+    await fractionalizer.methods.setNftCollectionIsAllowed(nftCollectionAddress, true).send();
+    await nftContract.methods.approve(fractionalizer.options.address, nftTokenId).send();
+
+    await expect(fractionalizer.methods.nft2rft(nftCollectionAddress, nftTokenId, 100n).call())
+      .to.be.rejectedWith(/TransferNotAllowed$/g);
+  });
+});
\ No newline at end of file
modifiedtests/src/eth/fungibleAbi.jsondiffbeforeafterboth
--- a/tests/src/eth/fungibleAbi.json
+++ b/tests/src/eth/fungibleAbi.json
@@ -301,5 +301,21 @@
     "outputs": [{ "internalType": "bool", "name": "", "type": "bool" }],
     "stateMutability": "nonpayable",
     "type": "function"
+  },
+  {
+    "inputs": [],
+    "name": "uniqueCollectionType",
+    "outputs": [{ "internalType": "string", "name": "", "type": "string" }],
+    "stateMutability": "nonpayable",
+    "type": "function"
+  },
+  {
+    "inputs": [
+      { "internalType": "address", "name": "user", "type": "address" }
+    ],
+    "name": "verifyOwnerOrAdmin",
+    "outputs": [{ "internalType": "bool", "name": "", "type": "bool" }],
+    "stateMutability": "view",
+    "type": "function"
   }
 ]
modifiedtests/src/eth/nonFungibleAbi.jsondiffbeforeafterboth
--- a/tests/src/eth/nonFungibleAbi.json
+++ b/tests/src/eth/nonFungibleAbi.json
@@ -526,5 +526,21 @@
     "outputs": [],
     "stateMutability": "nonpayable",
     "type": "function"
+  },
+  {
+    "inputs": [],
+    "name": "uniqueCollectionType",
+    "outputs": [{ "internalType": "string", "name": "", "type": "string" }],
+    "stateMutability": "nonpayable",
+    "type": "function"
+  },
+  {
+    "inputs": [
+      { "internalType": "address", "name": "user", "type": "address" }
+    ],
+    "name": "verifyOwnerOrAdmin",
+    "outputs": [{ "internalType": "bool", "name": "", "type": "bool" }],
+    "stateMutability": "view",
+    "type": "function"
   }
 ]
modifiedtests/src/eth/reFungible.test.tsdiffbeforeafterboth
--- a/tests/src/eth/reFungible.test.ts
+++ b/tests/src/eth/reFungible.test.ts
@@ -15,8 +15,7 @@
 // along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
 
 import {createCollectionExpectSuccess, UNIQUE, requirePallets, Pallets} from '../util/helpers';
-import {collectionIdToAddress, createEthAccount, createEthAccountWithBalance, evmCollection, evmCollectionHelpers, GAS_ARGS, getCollectionAddressFromResult, itWeb3, normalizeEvents, recordEthFee, recordEvents, tokenIdToAddress} from './util/helpers';
-import reFungibleTokenAbi from './reFungibleTokenAbi.json';
+import {collectionIdToAddress, createEthAccount, createEthAccountWithBalance, evmCollection, evmCollectionHelpers, getCollectionAddressFromResult, itWeb3, normalizeEvents, recordEthFee, recordEvents, tokenIdToAddress, uniqueRefungibleToken} from './util/helpers';
 import {expect} from 'chai';
 
 describe('Refungible: Information getting', () => {
@@ -88,7 +87,7 @@
     await contract.methods.mint(caller, tokenId).send();
 
     const tokenAddress = tokenIdToAddress(collectionId, tokenId);
-    const tokenContract = new web3.eth.Contract(reFungibleTokenAbi as any, tokenAddress, {from: caller, ...GAS_ARGS});
+    const tokenContract = uniqueRefungibleToken(web3, tokenAddress, caller);
 
     await tokenContract.methods.repartition(2).send();
     await tokenContract.methods.transfer(receiver, 1).send();
@@ -112,7 +111,7 @@
     await contract.methods.mint(caller, tokenId).send();
 
     const tokenAddress = tokenIdToAddress(collectionId, tokenId);
-    const tokenContract = new web3.eth.Contract(reFungibleTokenAbi as any, tokenAddress, {from: caller, ...GAS_ARGS});
+    const tokenContract = uniqueRefungibleToken(web3, tokenAddress, caller);
 
     await tokenContract.methods.repartition(2).send();
     await tokenContract.methods.transfer(receiver, 1).send();
@@ -258,7 +257,7 @@
     await contract.methods.mint(caller, tokenId).send();
 
     const address = tokenIdToAddress(collectionId, tokenId);
-    const tokenContract = new web3.eth.Contract(reFungibleTokenAbi as any, address, {from: caller, ...GAS_ARGS});
+    const tokenContract = uniqueRefungibleToken(web3, address, caller);
     await tokenContract.methods.repartition(15).send();
 
     {
@@ -277,7 +276,7 @@
           },
         ]);
       });
-      
+
       expect(erc20Events).to.include.deep.members([
         {
           address,
@@ -353,12 +352,12 @@
     await contract.methods.mint(caller, tokenId).send();
 
     const tokenAddress = tokenIdToAddress(collectionId, tokenId);
-    const tokenContract = new web3.eth.Contract(reFungibleTokenAbi as any, tokenAddress, {from: caller, ...GAS_ARGS});
+    const tokenContract = uniqueRefungibleToken(web3, tokenAddress, caller);
 
     await tokenContract.methods.repartition(2).send();
     await tokenContract.methods.transfer(receiver, 1).send();
 
-    const events =  await recordEvents(contract, async () => 
+    const events =  await recordEvents(contract, async () =>
       await tokenContract.methods.transfer(receiver, 1).send());
     expect(events).to.deep.equal([
       {
@@ -385,13 +384,13 @@
     await contract.methods.mint(caller, tokenId).send();
 
     const tokenAddress = tokenIdToAddress(collectionId, tokenId);
-    const tokenContract = new web3.eth.Contract(reFungibleTokenAbi as any, tokenAddress, {from: caller, ...GAS_ARGS});
+    const tokenContract = uniqueRefungibleToken(web3, tokenAddress, caller);
 
     await tokenContract.methods.repartition(2).send();
-    
-    const events =  await recordEvents(contract, async () => 
+
+    const events =  await recordEvents(contract, async () =>
       await tokenContract.methods.transfer(receiver, 1).send());
-      
+
     expect(events).to.deep.equal([
       {
         address: collectionIdAddress,
modifiedtests/src/eth/reFungibleAbi.jsondiffbeforeafterboth
--- a/tests/src/eth/reFungibleAbi.json
+++ b/tests/src/eth/reFungibleAbi.json
@@ -482,6 +482,15 @@
   },
   {
     "inputs": [
+      { "internalType": "uint256", "name": "token", "type": "uint256" }
+    ],
+    "name": "tokenContractAddress",
+    "outputs": [{ "internalType": "address", "name": "", "type": "address" }],
+    "stateMutability": "view",
+    "type": "function"
+  },
+  {
+    "inputs": [
       { "internalType": "address", "name": "owner", "type": "address" },
       { "internalType": "uint256", "name": "index", "type": "uint256" }
     ],
@@ -526,5 +535,21 @@
     "outputs": [],
     "stateMutability": "nonpayable",
     "type": "function"
+  },
+  {
+    "inputs": [],
+    "name": "uniqueCollectionType",
+    "outputs": [{ "internalType": "string", "name": "", "type": "string" }],
+    "stateMutability": "nonpayable",
+    "type": "function"
+  },
+  {
+    "inputs": [
+      { "internalType": "address", "name": "user", "type": "address" }
+    ],
+    "name": "verifyOwnerOrAdmin",
+    "outputs": [{ "internalType": "bool", "name": "", "type": "bool" }],
+    "stateMutability": "view",
+    "type": "function"
   }
 ]
modifiedtests/src/eth/reFungibleToken.test.tsdiffbeforeafterboth
--- a/tests/src/eth/reFungibleToken.test.ts
+++ b/tests/src/eth/reFungibleToken.test.ts
@@ -15,8 +15,7 @@
 // along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
 
 import {approve, createCollection, createRefungibleToken, transfer, transferFrom, UNIQUE, requirePallets, Pallets} from '../util/helpers';
-import {collectionIdToAddress, createEthAccount, createEthAccountWithBalance, evmCollection, evmCollectionHelpers, GAS_ARGS, getCollectionAddressFromResult, itWeb3, normalizeEvents, recordEthFee, recordEvents, subToEth, tokenIdToAddress, transferBalanceToEth} from './util/helpers';
-import reFungibleTokenAbi from './reFungibleTokenAbi.json';
+import {collectionIdFromAddress, collectionIdToAddress, createEthAccount, createEthAccountWithBalance, createNonfungibleCollection, createRefungibleCollection, evmCollection, evmCollectionHelpers, getCollectionAddressFromResult, itWeb3, normalizeEvents, recordEthFee, recordEvents, subToEth, tokenIdToAddress, transferBalanceToEth, uniqueNFT, uniqueRefungible, uniqueRefungibleToken} from './util/helpers';
 
 import chai from 'chai';
 import chaiAsPromised from 'chai-as-promised';
@@ -38,7 +37,7 @@
     const tokenId = (await createRefungibleToken(api, alice, collectionId, 200n, {Ethereum: caller})).itemId;
 
     const address = tokenIdToAddress(collectionId, tokenId);
-    const contract = new web3.eth.Contract(reFungibleTokenAbi as any, address, {from: caller, ...GAS_ARGS});
+    const contract = uniqueRefungibleToken(web3, address, caller);
     const totalSupply = await contract.methods.totalSupply().call();
 
     expect(totalSupply).to.equal('200');
@@ -54,7 +53,7 @@
     const tokenId = (await createRefungibleToken(api, alice, collectionId, 200n, {Ethereum: caller})).itemId;
 
     const address = tokenIdToAddress(collectionId, tokenId);
-    const contract = new web3.eth.Contract(reFungibleTokenAbi as any, address, {from: caller, ...GAS_ARGS});
+    const contract = uniqueRefungibleToken(web3, address, caller);
     const balance = await contract.methods.balanceOf(caller).call();
 
     expect(balance).to.equal('200');
@@ -70,7 +69,7 @@
     const tokenId = (await createRefungibleToken(api, alice, collectionId, 200n, {Ethereum: caller})).itemId;
 
     const address = tokenIdToAddress(collectionId, tokenId);
-    const contract = new web3.eth.Contract(reFungibleTokenAbi as any, address, {from: caller, ...GAS_ARGS});
+    const contract = uniqueRefungibleToken(web3, address, caller);
     const decimals = await contract.methods.decimals().call();
 
     expect(decimals).to.equal('0');
@@ -90,7 +89,7 @@
     const {collectionIdAddress, collectionId} = await getCollectionAddressFromResult(api, result);
     const receiver = createEthAccount(web3);
     const contract = evmCollection(web3, owner, collectionIdAddress, {type: 'ReFungible'});
-    
+
     const nextTokenId = await contract.methods.nextTokenId().call();
     expect(nextTokenId).to.be.equal('1');
     result = await contract.methods.mint(
@@ -123,17 +122,17 @@
     const {collectionIdAddress, collectionId} = await getCollectionAddressFromResult(api, result);
     const receiver = createEthAccount(web3);
     const contract = evmCollection(web3, owner, collectionIdAddress, {type: 'ReFungible'});
-    
+
     const nextTokenId = await contract.methods.nextTokenId().call();
     expect(nextTokenId).to.be.equal('1');
     result = await contract.methods.mint(
       receiver,
       nextTokenId,
     ).send();
-    
+
     // Set URL
     await contract.methods.setProperty(nextTokenId, 'url', Buffer.from('Token URI')).send();
-      
+
     const events = normalizeEvents(result.events);
     const address = collectionIdToAddress(collectionId);
 
@@ -159,14 +158,14 @@
     const {collectionIdAddress, collectionId} = await getCollectionAddressFromResult(api, result);
     const receiver = createEthAccount(web3);
     const contract = evmCollection(web3, owner, collectionIdAddress, {type: 'ReFungible'});
-    
+
     const nextTokenId = await contract.methods.nextTokenId().call();
     expect(nextTokenId).to.be.equal('1');
     result = await contract.methods.mint(
       receiver,
       nextTokenId,
     ).send();
-          
+
     const events = normalizeEvents(result.events);
     const address = collectionIdToAddress(collectionId);
 
@@ -192,14 +191,14 @@
     const {collectionIdAddress, collectionId} = await getCollectionAddressFromResult(api, result);
     const receiver = createEthAccount(web3);
     const contract = evmCollection(web3, owner, collectionIdAddress, {type: 'ReFungible'});
-    
+
     const nextTokenId = await contract.methods.nextTokenId().call();
     expect(nextTokenId).to.be.equal('1');
     result = await contract.methods.mint(
       receiver,
       nextTokenId,
     ).send();
-          
+
     // Set suffix
     const suffix = '/some/suffix';
     await contract.methods.setProperty(nextTokenId, 'suffix', Buffer.from(suffix)).send();
@@ -241,7 +240,7 @@
 
     const spender = createEthAccount(web3);
 
-    const contract = new web3.eth.Contract(reFungibleTokenAbi as any, address, {from: owner, ...GAS_ARGS});
+    const contract = uniqueRefungibleToken(web3, address, owner);
 
     {
       const result = await contract.methods.approve(spender, 100).send({from: owner});
@@ -282,7 +281,7 @@
     const receiver = createEthAccount(web3);
 
     const address = tokenIdToAddress(collectionId, tokenId);
-    const contract = new web3.eth.Contract(reFungibleTokenAbi as any, address, {from: owner, ...GAS_ARGS});
+    const contract = uniqueRefungibleToken(web3, address, owner);
 
     await contract.methods.approve(spender, 100).send();
 
@@ -336,7 +335,7 @@
     await transferBalanceToEth(api, alice, receiver);
 
     const address = tokenIdToAddress(collectionId, tokenId);
-    const contract = new web3.eth.Contract(reFungibleTokenAbi as any, address, {from: owner, ...GAS_ARGS});
+    const contract = uniqueRefungibleToken(web3, address, owner);
 
     {
       const result = await contract.methods.transfer(receiver, 50).send({from: owner});
@@ -379,14 +378,14 @@
     const tokenId = (await createRefungibleToken(api, alice, collectionId, 100n, {Ethereum: owner})).itemId;
 
     const address = tokenIdToAddress(collectionId, tokenId);
-    const contract = new web3.eth.Contract(reFungibleTokenAbi as any, address, {from: owner, ...GAS_ARGS});
+    const contract = uniqueRefungibleToken(web3, address, owner);
 
     await contract.methods.repartition(200).send({from: owner});
     expect(+await contract.methods.balanceOf(owner).call()).to.be.equal(200);
     await contract.methods.transfer(receiver, 110).send({from: owner});
     expect(+await contract.methods.balanceOf(owner).call()).to.be.equal(90);
     expect(+await contract.methods.balanceOf(receiver).call()).to.be.equal(110);
-    
+
     await expect(contract.methods.repartition(80).send({from: owner})).to.eventually.be.rejected;
 
     await contract.methods.transfer(receiver, 90).send({from: owner});
@@ -409,7 +408,7 @@
     const tokenId = (await createRefungibleToken(api, alice, collectionId, 100n, {Ethereum: owner})).itemId;
 
     const address = tokenIdToAddress(collectionId, tokenId);
-    const contract = new web3.eth.Contract(reFungibleTokenAbi as any, address, {from: owner, ...GAS_ARGS});
+    const contract = uniqueRefungibleToken(web3, address, owner);
 
     const result = await contract.methods.repartition(200).send();
     const events = normalizeEvents(result.events);
@@ -438,7 +437,7 @@
     const tokenId = (await createRefungibleToken(api, alice, collectionId, 100n, {Ethereum: owner})).itemId;
 
     const address = tokenIdToAddress(collectionId, tokenId);
-    const contract = new web3.eth.Contract(reFungibleTokenAbi as any, address, {from: owner, ...GAS_ARGS});
+    const contract = uniqueRefungibleToken(web3, address, owner);
 
     const result = await contract.methods.repartition(50).send();
     const events = normalizeEvents(result.events);
@@ -468,11 +467,11 @@
 
     const address = tokenIdToAddress(collectionId, tokenId);
 
-    const tokenContract =  new web3.eth.Contract(reFungibleTokenAbi as any, address, {from: caller, ...GAS_ARGS});
+    const tokenContract =  uniqueRefungibleToken(web3, address, caller);
     await tokenContract.methods.repartition(2).send();
     await tokenContract.methods.transfer(receiver, 1).send();
 
-    const events =  await recordEvents(contract, async () => 
+    const events =  await recordEvents(contract, async () =>
       await tokenContract.methods.burnFrom(caller, 1).send());
     expect(events).to.deep.equal([
       {
@@ -504,7 +503,7 @@
     const tokenId = (await createRefungibleToken(api, alice, collectionId, 200n, {Ethereum: owner})).itemId;
 
     const address = tokenIdToAddress(collectionId, tokenId);
-    const contract = new web3.eth.Contract(reFungibleTokenAbi as any, address, {from: owner, ...GAS_ARGS});
+    const contract = uniqueRefungibleToken(web3, address, owner);
 
     const cost = await recordEthFee(api, owner, () => contract.methods.approve(spender, 100).send({from: owner}));
     expect(cost < BigInt(0.2 * Number(UNIQUE)));
@@ -521,7 +520,7 @@
     const tokenId = (await createRefungibleToken(api, alice, collectionId, 200n, {Ethereum: owner})).itemId;
 
     const address = tokenIdToAddress(collectionId, tokenId);
-    const contract = new web3.eth.Contract(reFungibleTokenAbi as any, address, {from: owner, ...GAS_ARGS});
+    const contract = uniqueRefungibleToken(web3, address, owner);
 
     await contract.methods.approve(spender, 100).send({from: owner});
 
@@ -540,7 +539,7 @@
     const tokenId = (await createRefungibleToken(api, alice, collectionId, 200n, {Ethereum: owner})).itemId;
 
     const address = tokenIdToAddress(collectionId, tokenId);
-    const contract = new web3.eth.Contract(reFungibleTokenAbi as any, address, {from: owner, ...GAS_ARGS});
+    const contract = uniqueRefungibleToken(web3, address, owner);
 
     const cost = await recordEthFee(api, owner, () => contract.methods.transfer(receiver, 100).send({from: owner}));
     expect(cost < BigInt(0.2 * Number(UNIQUE)));
@@ -562,7 +561,7 @@
     const tokenId = (await createRefungibleToken(api, alice, collectionId, 200n)).itemId;
 
     const address = tokenIdToAddress(collectionId, tokenId);
-    const contract = new web3.eth.Contract(reFungibleTokenAbi as any, address);
+    const contract = uniqueRefungibleToken(web3, address);
 
     const events = await recordEvents(contract, async () => {
       expect(await approve(api, collectionId, tokenId, alice, {Ethereum: receiver}, 100n)).to.be.true;
@@ -593,7 +592,7 @@
     expect(await approve(api, collectionId, tokenId, alice, bob.address, 100n)).to.be.true;
 
     const address = tokenIdToAddress(collectionId, tokenId);
-    const contract = new web3.eth.Contract(reFungibleTokenAbi as any, address);
+    const contract = uniqueRefungibleToken(web3, address);
 
     const events = await recordEvents(contract, async () => {
       expect(await transferFrom(api, collectionId, tokenId, bob, alice, {Ethereum: receiver},  51n)).to.be.true;
@@ -631,7 +630,7 @@
     const tokenId = (await createRefungibleToken(api, alice, collectionId, 200n)).itemId;
 
     const address = tokenIdToAddress(collectionId, tokenId);
-    const contract = new web3.eth.Contract(reFungibleTokenAbi as any, address);
+    const contract = uniqueRefungibleToken(web3, address);
 
     const events = await recordEvents(contract, async () => {
       expect(await transfer(api, collectionId, tokenId, alice, {Ethereum: receiver},  51n)).to.be.true;
@@ -650,3 +649,47 @@
     ]);
   });
 });
+
+describe('ERC 1633 implementation', () => {
+  itWeb3('Parent NFT token address and id', async ({api, web3, privateKeyWrapper}) => {
+    const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
+
+    const {collectionIdAddress:  nftCollectionAddress} = await createNonfungibleCollection(api, web3, owner);
+    const nftContract = uniqueNFT(web3, nftCollectionAddress, owner);
+    const nftTokenId = await nftContract.methods.nextTokenId().call();
+    await nftContract.methods.mint(owner, nftTokenId).send();
+    const nftCollectionId = collectionIdFromAddress(nftCollectionAddress);
+
+    const {collectionIdAddress, collectionId} = await createRefungibleCollection(api, web3, owner);
+    const refungibleContract = uniqueRefungible(web3, collectionIdAddress, owner);
+    const refungibleTokenId = await refungibleContract.methods.nextTokenId().call();
+    await refungibleContract.methods.mint(owner, refungibleTokenId).send();
+
+    const rftTokenAddress = tokenIdToAddress(collectionId, refungibleTokenId);
+    const refungibleTokenContract = uniqueRefungibleToken(web3, rftTokenAddress, owner);
+    await refungibleTokenContract.methods.setParentNFT(nftCollectionAddress, nftTokenId).send();
+
+    const tokenAddress = await refungibleTokenContract.methods.parentToken().call();
+    const tokenId = await refungibleTokenContract.methods.parentTokenId().call();
+    const nftTokenAddress = tokenIdToAddress(nftCollectionId, nftTokenId);
+    expect(tokenAddress).to.be.equal(nftTokenAddress);
+    expect(tokenId).to.be.equal(nftTokenId);
+  });
+
+  itWeb3('Default parent token address and id', async ({api, web3, privateKeyWrapper}) => {
+    const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
+
+    const {collectionIdAddress, collectionId} = await createRefungibleCollection(api, web3, owner);
+    const refungibleContract = uniqueRefungible(web3, collectionIdAddress, owner);
+    const refungibleTokenId = await refungibleContract.methods.nextTokenId().call();
+    await refungibleContract.methods.mint(owner, refungibleTokenId).send();
+
+    const rftTokenAddress = tokenIdToAddress(collectionId, refungibleTokenId);
+    const refungibleTokenContract = uniqueRefungibleToken(web3, rftTokenAddress, owner);
+
+    const tokenAddress = await refungibleTokenContract.methods.parentToken().call();
+    const tokenId = await refungibleTokenContract.methods.parentTokenId().call();
+    expect(tokenAddress).to.be.equal(rftTokenAddress);
+    expect(tokenId).to.be.equal(refungibleTokenId);
+  });
+});
modifiedtests/src/eth/reFungibleTokenAbi.jsondiffbeforeafterboth
--- a/tests/src/eth/reFungibleTokenAbi.json
+++ b/tests/src/eth/reFungibleTokenAbi.json
@@ -103,6 +103,20 @@
     "type": "function"
   },
   {
+    "inputs": [],
+    "name": "parentToken",
+    "outputs": [{ "internalType": "address", "name": "", "type": "address" }],
+    "stateMutability": "view",
+    "type": "function"
+  },
+  {
+    "inputs": [],
+    "name": "parentTokenId",
+    "outputs": [{ "internalType": "uint256", "name": "", "type": "uint256" }],
+    "stateMutability": "view",
+    "type": "function"
+  },
+  {
     "inputs": [
       { "internalType": "uint256", "name": "amount", "type": "uint256" }
     ],
@@ -113,6 +127,16 @@
   },
   {
     "inputs": [
+      { "internalType": "address", "name": "collection", "type": "address" },
+      { "internalType": "uint256", "name": "nftId", "type": "uint256" }
+    ],
+    "name": "setParentNFT",
+    "outputs": [{ "internalType": "bool", "name": "", "type": "bool" }],
+    "stateMutability": "nonpayable",
+    "type": "function"
+  },
+  {
+    "inputs": [
       { "internalType": "bytes4", "name": "interfaceID", "type": "bytes4" }
     ],
     "name": "supportsInterface",
modifiedtests/src/eth/util/helpers.tsdiffbeforeafterboth
--- a/tests/src/eth/util/helpers.ts
+++ b/tests/src/eth/util/helpers.ts
@@ -32,6 +32,7 @@
 import fungibleAbi from '../fungibleAbi.json';
 import nonFungibleAbi from '../nonFungibleAbi.json';
 import refungibleAbi from '../reFungibleAbi.json';
+import refungibleTokenAbi from '../reFungibleTokenAbi.json';
 import contractHelpersAbi from './contractHelpersAbi.json';
 
 export const GAS_ARGS = {gas: 2500000};
@@ -101,6 +102,18 @@
   ]);
   return Web3.utils.toChecksumAddress('0x' + buf.toString('hex'));
 }
+
+export function tokenIdFromAddress(address: string) {
+  if (!address.startsWith('0x'))
+    throw 'address not starts with "0x"';
+  if (address.length > 42)
+    throw 'address length is more than 20 bytes';
+  return {
+    collectionId: Number('0x' + address.substring(address.length - 16, address.length - 8)),
+    tokenId: Number('0x' + address.substring(address.length - 8)),
+  };
+}
+
 export function tokenIdToCross(collection: number, token: number): CrossAccountId {
   return {
     Ethereum: tokenIdToAddress(collection, token),
@@ -128,6 +141,44 @@
   expect(result.success).to.be.true;
 }
 
+export async function createRefungibleCollection(api: ApiPromise, web3: Web3, owner: string) {
+  const collectionHelper = evmCollectionHelpers(web3, owner);
+  const result = await collectionHelper.methods
+    .createRefungibleCollection('A', 'B', 'C')
+    .send();
+  return await getCollectionAddressFromResult(api, result);
+}
+
+
+export async function createNonfungibleCollection(api: ApiPromise, web3: Web3, owner: string) {
+  const collectionHelper = evmCollectionHelpers(web3, owner);
+  const result = await collectionHelper.methods
+    .createNonfungibleCollection('A', 'B', 'C')
+    .send();
+  return await getCollectionAddressFromResult(api, result);
+}
+
+export function uniqueNFT(web3: Web3, address: string, owner: string) {
+  return new web3.eth.Contract(nonFungibleAbi as any, address, {
+    from: owner,
+    ...GAS_ARGS,
+  });
+}
+
+export function uniqueRefungible(web3: Web3, collectionAddress: string, owner: string) {
+  return new web3.eth.Contract(refungibleAbi as any, collectionAddress, {
+    from: owner,
+    ...GAS_ARGS,
+  });
+}
+
+export function uniqueRefungibleToken(web3: Web3, tokenAddress: string, owner: string | undefined = undefined) {
+  return new web3.eth.Contract(refungibleTokenAbi as any, tokenAddress, {
+    from: owner,
+    ...GAS_ARGS,
+  });
+}
+
 export async function itWeb3(name: string, cb: (apis: { web3: Web3, api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair }) => any, opts: { only?: boolean, skip?: boolean } = {}) {
   let i: any = it;
   if (opts.only) i = i.only;
@@ -199,7 +250,12 @@
   return Web3.utils.toChecksumAddress(subToEthLowercase(eth));
 }
 
-export function compileContract(name: string, src: string) {
+export interface CompiledContract {
+  abi: any,
+  object: string,
+}
+
+export function compileContract(name: string, src: string) : CompiledContract {
   const out = JSON.parse(solc.compile(JSON.stringify({
     language: 'Solidity',
     sources: {
modifiedtests/src/interfaces/augment-api-query.tsdiffbeforeafterboth
--- a/tests/src/interfaces/augment-api-query.ts
+++ b/tests/src/interfaces/augment-api-query.ts
@@ -266,7 +266,7 @@
        * 
        * Currently used to store RMRK data.
        **/
-      tokenAuxProperties: AugmentedQuery<ApiType, (arg1: u32 | AnyNumber | Uint8Array, arg2: u32 | AnyNumber | Uint8Array, arg3: UpDataStructsPropertyScope | 'None' | 'Rmrk' | number | Uint8Array, arg4: Bytes | string | Uint8Array) => Observable<Option<Bytes>>, [u32, u32, UpDataStructsPropertyScope, Bytes]> & QueryableStorageEntry<ApiType, [u32, u32, UpDataStructsPropertyScope, Bytes]>;
+      tokenAuxProperties: AugmentedQuery<ApiType, (arg1: u32 | AnyNumber | Uint8Array, arg2: u32 | AnyNumber | Uint8Array, arg3: UpDataStructsPropertyScope | 'None' | 'Rmrk' | 'Eth' | number | Uint8Array, arg4: Bytes | string | Uint8Array) => Observable<Option<Bytes>>, [u32, u32, UpDataStructsPropertyScope, Bytes]> & QueryableStorageEntry<ApiType, [u32, u32, UpDataStructsPropertyScope, Bytes]>;
       /**
        * Used to enumerate token's children.
        **/
modifiedtests/src/interfaces/default/types.tsdiffbeforeafterboth
--- a/tests/src/interfaces/default/types.ts
+++ b/tests/src/interfaces/default/types.ts
@@ -2521,7 +2521,8 @@
 export interface UpDataStructsPropertyScope extends Enum {
   readonly isNone: boolean;
   readonly isRmrk: boolean;
-  readonly type: 'None' | 'Rmrk';
+  readonly isEth: boolean;
+  readonly type: 'None' | 'Rmrk' | 'Eth';
 }
 
 /** @name UpDataStructsRpcCollection */
modifiedtests/src/interfaces/lookup.tsdiffbeforeafterboth
--- a/tests/src/interfaces/lookup.ts
+++ b/tests/src/interfaces/lookup.ts
@@ -2978,7 +2978,7 @@
    * Lookup397: up_data_structs::PropertyScope
    **/
   UpDataStructsPropertyScope: {
-    _enum: ['None', 'Rmrk']
+    _enum: ['None', 'Rmrk', 'Eth']
   },
   /**
    * Lookup399: pallet_nonfungible::pallet::Error<T>
modifiedtests/src/interfaces/types-lookup.tsdiffbeforeafterboth
--- a/tests/src/interfaces/types-lookup.ts
+++ b/tests/src/interfaces/types-lookup.ts
@@ -3126,7 +3126,8 @@
   export interface UpDataStructsPropertyScope extends Enum {
     readonly isNone: boolean;
     readonly isRmrk: boolean;
-    readonly type: 'None' | 'Rmrk';
+    readonly isEth: boolean;
+    readonly type: 'None' | 'Rmrk' | 'Eth';
   }
 
   /** @name PalletNonfungibleError (399) */
modifiedtests/yarn.lockdiffbeforeafterboth
--- a/tests/yarn.lock
+++ b/tests/yarn.lock
@@ -963,6 +963,20 @@
   dependencies:
     "@types/chai" "*"
 
+"@types/chai-like@^1.1.1":
+  version "1.1.1"
+  resolved "https://registry.yarnpkg.com/@types/chai-like/-/chai-like-1.1.1.tgz#c454039b0a2f92664fb5b7b7a2a66c3358783ae7"
+  integrity sha512-s46EZsupBuVhLn66DbRee5B0SELLmL4nFXVrBiV29BxLGm9Sh7Bful623j3AfiQRu2zAP4cnlZ3ETWB3eWc4bA==
+  dependencies:
+    "@types/chai" "*"
+
+"@types/chai-things@^0.0.35":
+  version "0.0.35"
+  resolved "https://registry.yarnpkg.com/@types/chai-things/-/chai-things-0.0.35.tgz#4b5d9ec032067faa62b3bf7bb40dc0bec941945f"
+  integrity sha512-BC8FwMf9FHj87XT4dgTwbdb8dNRilGqYWGmwLPdJ54YNk6K2PlcFTt68NGHjgPDnms8zIYcOtmPePd0mPNTo/Q==
+  dependencies:
+    "@types/chai" "*"
+
 "@types/chai@*", "@types/chai@^4.3.1":
   version "4.3.1"
   resolved "https://registry.yarnpkg.com/@types/chai/-/chai-4.3.1.tgz#e2c6e73e0bdeb2521d00756d099218e9f5d90a04"
@@ -1545,6 +1559,16 @@
   dependencies:
     check-error "^1.0.2"
 
+chai-like@^1.1.1:
+  version "1.1.1"
+  resolved "https://registry.yarnpkg.com/chai-like/-/chai-like-1.1.1.tgz#8c558a414c34514e814d497c772547ceb7958f64"
+  integrity sha512-VKa9z/SnhXhkT1zIjtPACFWSoWsqVoaz1Vg+ecrKo5DCKVlgL30F/pEyEvXPBOVwCgLZcWUleCM/C1okaKdTTA==
+
+chai-things@^0.2.0:
+  version "0.2.0"
+  resolved "https://registry.yarnpkg.com/chai-things/-/chai-things-0.2.0.tgz#c55128378f9bb399e994f00052151984ed6ebe70"
+  integrity sha512-6ns0SU21xdRCoEXVKH3HGbwnsgfVMXQ+sU5V8PI9rfxaITos8lss1vUxbF1FAcJKjfqmmmLVlr/z3sLes00w+A==
+
 chai@^4.3.6:
   version "4.3.6"
   resolved "https://registry.yarnpkg.com/chai/-/chai-4.3.6.tgz#ffe4ba2d9fa9d6680cc0b370adae709ec9011e9c"