git.delta.rocks / unique-network / refs/commits / 2e3c4de7682f

difftreelog

Merge pull request #647 from UniqueNetwork/feature/supports-interface-for-erc721-metadata

Yaroslav Bolyukin2022-10-18parents: #764e4a6 #7e2fc0e.patch.diff
in: master

57 files changed

modified.maintain/scripts/generate_sol.shdiffbeforeafterboth
--- a/.maintain/scripts/generate_sol.sh
+++ b/.maintain/scripts/generate_sol.sh
@@ -11,4 +11,6 @@
 formatted=$(mktemp)
 prettier --config $PRETTIER_CONFIG $raw > $formatted
 
+sed -i -E -e "s/.+\/\/ FORMATTING: FORCE NEWLINE//g" $formatted
+
 mv $formatted $OUTPUT
modifiedcrates/evm-coder/procedural/src/solidity_interface.rsdiffbeforeafterboth
--- a/crates/evm-coder/procedural/src/solidity_interface.rs
+++ b/crates/evm-coder/procedural/src/solidity_interface.rs
@@ -291,22 +291,40 @@
 
 struct MethodInfo {
 	rename_selector: Option<String>,
+	hide: bool,
 }
 impl Parse for MethodInfo {
 	fn parse(input: ParseStream) -> syn::Result<Self> {
 		let mut rename_selector = None;
-		let lookahead = input.lookahead1();
-		if lookahead.peek(kw::rename_selector) {
-			let k = input.parse::<kw::rename_selector>()?;
-			input.parse::<Token![=]>()?;
-			if rename_selector
-				.replace(input.parse::<LitStr>()?.value())
-				.is_some()
-			{
-				return Err(syn::Error::new(k.span(), "rename_selector is already set"));
+		let mut hide = false;
+		while !input.is_empty() {
+			let lookahead = input.lookahead1();
+			if lookahead.peek(kw::rename_selector) {
+				let k = input.parse::<kw::rename_selector>()?;
+				input.parse::<Token![=]>()?;
+				if rename_selector
+					.replace(input.parse::<LitStr>()?.value())
+					.is_some()
+				{
+					return Err(syn::Error::new(k.span(), "rename_selector is already set"));
+				}
+			} else if lookahead.peek(kw::hide) {
+				input.parse::<kw::hide>()?;
+				hide = true;
+			} else {
+				return Err(lookahead.error());
+			}
+
+			if input.peek(Token![,]) {
+				input.parse::<Token![,]>()?;
+			} else if !input.is_empty() {
+				return Err(syn::Error::new(input.span(), "expected end"));
 			}
 		}
-		Ok(Self { rename_selector })
+		Ok(Self {
+			rename_selector,
+			hide,
+		})
 	}
 }
 
@@ -548,6 +566,7 @@
 	syn::custom_keyword!(expect_selector);
 
 	syn::custom_keyword!(rename_selector);
+	syn::custom_keyword!(hide);
 }
 
 /// Rust methods are parsed into this structure when Solidity code is generated
@@ -558,6 +577,7 @@
 	screaming_name: Ident,
 	selector_str: String,
 	selector: u32,
+	hide: bool,
 	args: Vec<MethodArg>,
 	has_normal_args: bool,
 	has_value_args: bool,
@@ -570,6 +590,7 @@
 	fn try_from(value: &ImplItemMethod) -> syn::Result<Self> {
 		let mut info = MethodInfo {
 			rename_selector: None,
+			hide: false,
 		};
 		let mut docs = Vec::new();
 		let mut weight = None;
@@ -667,6 +688,7 @@
 			screaming_name: snake_ident_to_screaming(ident),
 			selector_str,
 			selector,
+			hide: info.hide,
 			args,
 			has_normal_args,
 			has_value_args,
@@ -826,12 +848,14 @@
 		let docs = &self.docs;
 		let selector_str = &self.selector_str;
 		let selector = self.selector;
+		let hide = self.hide;
 		let is_payable = self.has_value_args;
 		quote! {
 			SolidityFunction {
 				docs: &[#(#docs),*],
 				selector_str: #selector_str,
 				selector: #selector,
+				hide: #hide,
 				name: #camel_name,
 				mutability: #mutability,
 				is_payable: #is_payable,
modifiedcrates/evm-coder/src/solidity.rsdiffbeforeafterboth
--- a/crates/evm-coder/src/solidity.rs
+++ b/crates/evm-coder/src/solidity.rs
@@ -225,7 +225,7 @@
 
 pub trait SolidityArguments {
 	fn solidity_name(&self, writer: &mut impl fmt::Write, tc: &TypeCollector) -> fmt::Result;
-	fn solidity_get(&self, writer: &mut impl fmt::Write) -> fmt::Result;
+	fn solidity_get(&self, prefix: &str, writer: &mut impl fmt::Write) -> fmt::Result;
 	fn solidity_default(&self, writer: &mut impl fmt::Write, tc: &TypeCollector) -> fmt::Result;
 	fn is_empty(&self) -> bool {
 		self.len() == 0
@@ -248,7 +248,7 @@
 			Ok(())
 		}
 	}
-	fn solidity_get(&self, _writer: &mut impl fmt::Write) -> fmt::Result {
+	fn solidity_get(&self, _prefix: &str, _writer: &mut impl fmt::Write) -> fmt::Result {
 		Ok(())
 	}
 	fn solidity_default(&self, writer: &mut impl fmt::Write, tc: &TypeCollector) -> fmt::Result {
@@ -283,8 +283,8 @@
 			Ok(())
 		}
 	}
-	fn solidity_get(&self, writer: &mut impl fmt::Write) -> fmt::Result {
-		writeln!(writer, "\t\t{};", self.0)
+	fn solidity_get(&self, prefix: &str, writer: &mut impl fmt::Write) -> fmt::Result {
+		writeln!(writer, "\t{prefix}\t{};", self.0)
 	}
 	fn solidity_default(&self, writer: &mut impl fmt::Write, tc: &TypeCollector) -> fmt::Result {
 		T::solidity_default(writer, tc)
@@ -318,8 +318,8 @@
 			Ok(())
 		}
 	}
-	fn solidity_get(&self, writer: &mut impl fmt::Write) -> fmt::Result {
-		writeln!(writer, "\t\t{};", self.1)
+	fn solidity_get(&self, prefix: &str, writer: &mut impl fmt::Write) -> fmt::Result {
+		writeln!(writer, "\t{prefix}\t{};", self.1)
 	}
 	fn solidity_default(&self, writer: &mut impl fmt::Write, tc: &TypeCollector) -> fmt::Result {
 		T::solidity_default(writer, tc)
@@ -337,7 +337,7 @@
 	fn solidity_name(&self, _writer: &mut impl fmt::Write, _tc: &TypeCollector) -> fmt::Result {
 		Ok(())
 	}
-	fn solidity_get(&self, _writer: &mut impl fmt::Write) -> fmt::Result {
+	fn solidity_get(&self, _prefix: &str, _writer: &mut impl fmt::Write) -> fmt::Result {
 		Ok(())
 	}
 	fn solidity_default(&self, _writer: &mut impl fmt::Write, _tc: &TypeCollector) -> fmt::Result {
@@ -365,9 +365,9 @@
         )* );
 		Ok(())
 	}
-	fn solidity_get(&self, writer: &mut impl fmt::Write) -> fmt::Result {
+	fn solidity_get(&self, prefix: &str, writer: &mut impl fmt::Write) -> fmt::Result {
 		for_tuples!( #(
-            Tuple.solidity_get(writer)?;
+            Tuple.solidity_get(prefix, writer)?;
         )* );
 		Ok(())
 	}
@@ -418,6 +418,7 @@
 	pub docs: &'static [&'static str],
 	pub selector_str: &'static str,
 	pub selector: u32,
+	pub hide: bool,
 	pub name: &'static str,
 	pub args: A,
 	pub result: R,
@@ -431,16 +432,21 @@
 		writer: &mut impl fmt::Write,
 		tc: &TypeCollector,
 	) -> fmt::Result {
+		let hide_comment = self.hide.then(|| "// ").unwrap_or("");
 		for doc in self.docs {
-			writeln!(writer, "\t///{}", doc)?;
+			writeln!(writer, "\t{hide_comment}///{}", doc)?;
 		}
 		writeln!(
 			writer,
-			"\t/// @dev EVM selector for this function is: 0x{:0>8x},",
+			"\t{hide_comment}/// @dev EVM selector for this function is: 0x{:0>8x},",
 			self.selector
 		)?;
-		writeln!(writer, "\t///  or in textual repr: {}", self.selector_str)?;
-		write!(writer, "\tfunction {}(", self.name)?;
+		writeln!(
+			writer,
+			"\t{hide_comment}///  or in textual repr: {}",
+			self.selector_str
+		)?;
+		write!(writer, "\t{hide_comment}function {}(", self.name)?;
 		self.args.solidity_name(writer, tc)?;
 		write!(writer, ")")?;
 		if is_impl {
@@ -463,22 +469,25 @@
 		}
 		if is_impl {
 			writeln!(writer, " {{")?;
-			writeln!(writer, "\t\trequire(false, stub_error);")?;
-			self.args.solidity_get(writer)?;
+			writeln!(writer, "\t{hide_comment}\trequire(false, stub_error);")?;
+			self.args.solidity_get(hide_comment, writer)?;
 			match &self.mutability {
 				SolidityMutability::Pure => {}
-				SolidityMutability::View => writeln!(writer, "\t\tdummy;")?,
-				SolidityMutability::Mutable => writeln!(writer, "\t\tdummy = 0;")?,
+				SolidityMutability::View => writeln!(writer, "\t{hide_comment}\tdummy;")?,
+				SolidityMutability::Mutable => writeln!(writer, "\t{hide_comment}\tdummy = 0;")?,
 			}
 			if !self.result.is_empty() {
-				write!(writer, "\t\treturn ")?;
+				write!(writer, "\t{hide_comment}\treturn ")?;
 				self.result.solidity_default(writer, tc)?;
 				writeln!(writer, ";")?;
 			}
-			writeln!(writer, "\t}}")?;
+			writeln!(writer, "\t{hide_comment}}}")?;
 		} else {
 			writeln!(writer, ";")?;
 		}
+		if self.hide {
+			writeln!(writer, "// FORMATTING: FORCE NEWLINE")?;
+		}
 		Ok(())
 	}
 }
modifiedpallets/common/src/dispatch.rsdiffbeforeafterboth
--- a/pallets/common/src/dispatch.rs
+++ b/pallets/common/src/dispatch.rs
@@ -9,7 +9,7 @@
 	traits::Get,
 };
 use sp_runtime::DispatchError;
-use up_data_structs::{CollectionId, CreateCollectionData};
+use up_data_structs::{CollectionId, CreateCollectionData, CollectionFlags};
 
 use crate::{pallet::Config, CommonCollectionOperations, CollectionHandle};
 
@@ -80,6 +80,7 @@
 		sender: T::CrossAccountId,
 		payer: T::CrossAccountId,
 		data: CreateCollectionData<T::AccountId>,
+		flags: CollectionFlags,
 	) -> Result<CollectionId, DispatchError>;
 
 	/// Delete the collection.
modifiedpallets/common/src/erc.rsdiffbeforeafterboth
--- a/pallets/common/src/erc.rs
+++ b/pallets/common/src/erc.rs
@@ -592,6 +592,7 @@
 	///
 	/// @dev Owner can be changed only by current owner
 	/// @param newOwner new owner account
+	#[solidity(rename_selector = "changeCollectionOwner")]
 	fn set_owner(&mut self, caller: caller, new_owner: address) -> Result<void> {
 		self.consume_store_writes(1)?;
 
@@ -659,11 +660,6 @@
 	/// Keys.
 	pub mod key {
 		use super::*;
-
-		/// Key "schemaName".
-		pub fn schema_name() -> up_data_structs::PropertyKey {
-			property_key_from_bytes(b"schemaName").expect(EXPECT_CONVERT_ERROR)
-		}
 
 		/// Key "baseURI".
 		pub fn base_uri() -> up_data_structs::PropertyKey {
@@ -672,30 +668,17 @@
 
 		/// Key "url".
 		pub fn url() -> up_data_structs::PropertyKey {
-			property_key_from_bytes(b"url").expect(EXPECT_CONVERT_ERROR)
+			property_key_from_bytes(b"URI").expect(EXPECT_CONVERT_ERROR)
 		}
 
 		/// Key "suffix".
 		pub fn suffix() -> up_data_structs::PropertyKey {
-			property_key_from_bytes(b"suffix").expect(EXPECT_CONVERT_ERROR)
+			property_key_from_bytes(b"URISuffix").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.
-	pub mod value {
-		use super::*;
-
-		/// Value "ERC721Metadata".
-		pub const ERC721_METADATA: &[u8] = b"ERC721Metadata";
-
-		/// Value for [`ERC721_METADATA`].
-		pub fn erc721() -> up_data_structs::PropertyValue {
-			property_value_from_bytes(ERC721_METADATA).expect(EXPECT_CONVERT_ERROR)
 		}
 	}
 
modifiedpallets/common/src/lib.rsdiffbeforeafterboth
--- a/pallets/common/src/lib.rs
+++ b/pallets/common/src/lib.rs
@@ -71,6 +71,7 @@
 	Collection,
 	RpcCollection,
 	CollectionFlags,
+	RpcCollectionFlags,
 	CollectionId,
 	CreateItemData,
 	MAX_TOKEN_PREFIX_LENGTH,
@@ -824,7 +825,11 @@
 			token_property_permissions,
 			properties,
 			read_only: flags.external,
-			foreign: flags.foreign,
+
+			flags: RpcCollectionFlags {
+				foreign: flags.foreign,
+				erc721metadata: flags.erc721metadata,
+			},
 		})
 	}
 }
modifiedpallets/evm-contract-helpers/src/stubs/ContractHelpers.rawdiffbeforeafterboth

binary blob — no preview

modifiedpallets/fungible/src/lib.rsdiffbeforeafterboth
--- a/pallets/fungible/src/lib.rs
+++ b/pallets/fungible/src/lib.rs
@@ -212,8 +212,9 @@
 		owner: T::CrossAccountId,
 		payer: T::CrossAccountId,
 		data: CreateCollectionData<T::AccountId>,
+		flags: CollectionFlags,
 	) -> Result<CollectionId, DispatchError> {
-		<PalletCommon<T>>::init_collection(owner, payer, data, CollectionFlags::default())
+		<PalletCommon<T>>::init_collection(owner, payer, data, flags)
 	}
 
 	/// Initializes the collection with ForeignCollection flag. Returns [CollectionId] on success, [DispatchError] otherwise.
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
@@ -18,7 +18,7 @@
 }
 
 /// @title A contract that allows you to work with collections.
-/// @dev the ERC-165 identifier for this interface is 0x3e1e8083
+/// @dev the ERC-165 identifier for this interface is 0x62e22290
 contract Collection is Dummy, ERC165 {
 	/// Set collection property.
 	///
@@ -296,9 +296,9 @@
 	///
 	/// @dev Owner can be changed only by current owner
 	/// @param newOwner new owner account
-	/// @dev EVM selector for this function is: 0x13af4035,
-	///  or in textual repr: setOwner(address)
-	function setOwner(address newOwner) public {
+	/// @dev EVM selector for this function is: 0x4f53e226,
+	///  or in textual repr: changeCollectionOwner(address)
+	function changeCollectionOwner(address newOwner) public {
 		require(false, stub_error);
 		newOwner;
 		dummy = 0;
modifiedpallets/nonfungible/src/benchmarking.rsdiffbeforeafterboth
--- a/pallets/nonfungible/src/benchmarking.rs
+++ b/pallets/nonfungible/src/benchmarking.rs
@@ -55,7 +55,7 @@
 		owner,
 		CollectionMode::NFT,
 		|owner: T::CrossAccountId, data| {
-			<Pallet<T>>::init_collection(owner.clone(), owner, data, true)
+			<Pallet<T>>::init_collection(owner.clone(), owner, data, Default::default())
 		},
 		NonfungibleHandle::cast,
 	)
modifiedpallets/nonfungible/src/erc.rsdiffbeforeafterboth
--- a/pallets/nonfungible/src/erc.rs
+++ b/pallets/nonfungible/src/erc.rs
@@ -33,16 +33,12 @@
 use pallet_evm_coder_substrate::dispatch_to_evm;
 use sp_std::vec::Vec;
 use pallet_common::{
-	erc::{
-		CommonEvmHandler, PrecompileResult, CollectionCall,
-		static_property::{key, value as property_value},
-	},
+	erc::{CommonEvmHandler, PrecompileResult, CollectionCall, static_property::key},
 	CollectionHandle, CollectionPropertyPermissions,
 };
 use pallet_evm::{account::CrossAccountId, PrecompileHandle};
 use pallet_evm_coder_substrate::call;
 use pallet_structure::{SelfWeightOf as StructureWeight, weights::WeightInfo as _};
-use alloc::string::ToString;
 
 use crate::{
 	AccountBalance, Config, CreateItemData, NonfungibleHandle, Pallet, TokenData, TokensMinted,
@@ -194,7 +190,7 @@
 }
 
 #[derive(ToLog)]
-pub enum ERC721MintableEvents {
+pub enum ERC721UniqueMintableEvents {
 	#[allow(dead_code)]
 	MintingFinished {},
 }
@@ -204,15 +200,17 @@
 #[solidity_interface(name = ERC721Metadata, expect_selector = 0x5b5e139f)]
 impl<T: Config> NonfungibleHandle<T> {
 	/// @notice A descriptive name for a collection of NFTs in this contract
-	fn name(&self) -> Result<string> {
-		Ok(decode_utf16(self.name.iter().copied())
-			.map(|r| r.unwrap_or(REPLACEMENT_CHARACTER))
-			.collect::<string>())
+	/// @dev real implementation of this function lies in `ERC721UniqueExtensions`
+	#[solidity(hide, rename_selector = "name")]
+	fn name_proxy(&self) -> Result<string> {
+		self.name()
 	}
 
 	/// @notice An abbreviated name for NFTs in this contract
-	fn symbol(&self) -> Result<string> {
-		Ok(string::from_utf8_lossy(&self.token_prefix).into())
+	/// @dev real implementation of this function lies in `ERC721UniqueExtensions`
+	#[solidity(hide, rename_selector = "symbol")]
+	fn symbol_proxy(&self) -> Result<string> {
+		self.symbol()
 	}
 
 	/// @notice A distinct Uniform Resource Identifier (URI) for a given asset.
@@ -228,35 +226,38 @@
 	fn token_uri(&self, token_id: uint256) -> Result<string> {
 		let token_id_u32: u32 = token_id.try_into().map_err(|_| "token id overflow")?;
 
-		if let Ok(url) = get_token_property(self, token_id_u32, &key::url()) {
-			if !url.is_empty() {
-				return Ok(url);
+		match get_token_property(self, token_id_u32, &key::url()).as_deref() {
+			Err(_) | Ok("") => (),
+			Ok(url) => {
+				return Ok(url.into());
 			}
-		} else if !is_erc721_metadata_compatible::<T>(self.id) {
-			return Err("tokenURI not set".into());
-		}
+		};
 
-		if let Some(base_uri) =
+		let base_uri =
 			pallet_common::Pallet::<T>::get_collection_property(self.id, &key::base_uri())
-		{
-			if !base_uri.is_empty() {
-				let base_uri = string::from_utf8(base_uri.into_inner()).map_err(|e| {
+				.map(BoundedVec::into_inner)
+				.map(string::from_utf8)
+				.transpose()
+				.map_err(|e| {
 					Error::Revert(alloc::format!(
 						"Can not convert value \"baseURI\" to string with error \"{}\"",
 						e
 					))
 				})?;
-				if let Ok(suffix) = get_token_property(self, token_id_u32, &key::suffix()) {
-					if !suffix.is_empty() {
-						return Ok(base_uri + suffix.as_str());
-					}
-				}
 
-				return Ok(base_uri + token_id.to_string().as_str());
+		let base_uri = match base_uri.as_deref() {
+			None | Some("") => {
+				return Ok("".into());
 			}
-		}
+			Some(base_uri) => base_uri.into(),
+		};
 
-		Ok("".into())
+		Ok(
+			match get_token_property(self, token_id_u32, &key::suffix()).as_deref() {
+				Err(_) | Ok("") => base_uri,
+				Ok(suffix) => base_uri + suffix,
+			},
+		)
 	}
 }
 
@@ -427,19 +428,33 @@
 }
 
 /// @title ERC721 minting logic.
-#[solidity_interface(name = ERC721Mintable, events(ERC721MintableEvents))]
+#[solidity_interface(name = ERC721UniqueMintable, events(ERC721UniqueMintableEvents))]
 impl<T: Config> NonfungibleHandle<T> {
 	fn minting_finished(&self) -> Result<bool> {
 		Ok(false)
 	}
 
 	/// @notice Function to mint token.
+	/// @param to The new owner
+	/// @return uint256 The id of the newly minted token
+	#[weight(<SelfWeightOf<T>>::create_item())]
+	fn mint(&mut self, caller: caller, to: address) -> Result<uint256> {
+		let token_id: uint256 = <TokensMinted<T>>::get(self.id)
+			.checked_add(1)
+			.ok_or("item id overflow")?
+			.into();
+		self.mint_check_id(caller, to, token_id)?;
+		Ok(token_id)
+	}
+
+	/// @notice Function to mint token.
 	/// @dev `tokenId` should be obtained with `nextTokenId` method,
 	///  unlike standard, you can't specify it manually
 	/// @param to The new owner
 	/// @param tokenId ID of the minted NFT
+	#[solidity(hide, rename_selector = "mint")]
 	#[weight(<SelfWeightOf<T>>::create_item())]
-	fn mint(&mut self, caller: caller, to: address, token_id: uint256) -> Result<bool> {
+	fn mint_check_id(&mut self, caller: caller, to: address, token_id: uint256) -> Result<bool> {
 		let caller = T::CrossAccountId::from_eth(caller);
 		let to = T::CrossAccountId::from_eth(to);
 		let token_id: u32 = token_id.try_into()?;
@@ -470,14 +485,34 @@
 	}
 
 	/// @notice Function to mint token with the given tokenUri.
+	/// @param to The new owner
+	/// @param tokenUri Token URI that would be stored in the NFT properties
+	/// @return uint256 The id of the newly minted token
+	#[solidity(rename_selector = "mintWithTokenURI")]
+	#[weight(<SelfWeightOf<T>>::create_item())]
+	fn mint_with_token_uri(
+		&mut self,
+		caller: caller,
+		to: address,
+		token_uri: string,
+	) -> Result<uint256> {
+		let token_id: uint256 = <TokensMinted<T>>::get(self.id)
+			.checked_add(1)
+			.ok_or("item id overflow")?
+			.into();
+		self.mint_with_token_uri_check_id(caller, to, token_id, token_uri)?;
+		Ok(token_id)
+	}
+
+	/// @notice Function to mint token with the given tokenUri.
 	/// @dev `tokenId` should be obtained with `nextTokenId` method,
 	///  unlike standard, you can't specify it manually
 	/// @param to The new owner
 	/// @param tokenId ID of the minted NFT
 	/// @param tokenUri Token URI that would be stored in the NFT properties
-	#[solidity(rename_selector = "mintWithTokenURI")]
+	#[solidity(hide, rename_selector = "mintWithTokenURI")]
 	#[weight(<SelfWeightOf<T>>::create_item())]
-	fn mint_with_token_uri(
+	fn mint_with_token_uri_check_id(
 		&mut self,
 		caller: caller,
 		to: address,
@@ -550,17 +585,6 @@
 	Err("Property tokenURI not found".into())
 }
 
-fn is_erc721_metadata_compatible<T: Config>(collection_id: CollectionId) -> bool {
-	if let Some(shema_name) =
-		pallet_common::Pallet::<T>::get_collection_property(collection_id, &key::schema_name())
-	{
-		let shema_name = shema_name.into_inner();
-		shema_name == property_value::ERC721_METADATA
-	} else {
-		false
-	}
-}
-
 fn get_token_permission<T: Config>(
 	collection_id: CollectionId,
 	key: &PropertyKey,
@@ -575,21 +599,23 @@
 			Error::Revert(alloc::format!("No permission for key {}", key))
 		})?;
 	Ok(a)
-}
-
-fn has_token_permission<T: Config>(collection_id: CollectionId, key: &PropertyKey) -> bool {
-	if let Ok(token_property_permissions) =
-		CollectionPropertyPermissions::<T>::try_get(collection_id)
-	{
-		return token_property_permissions.contains_key(key);
-	}
-
-	false
 }
 
 /// @title Unique extensions for ERC721.
 #[solidity_interface(name = ERC721UniqueExtensions)]
 impl<T: Config> NonfungibleHandle<T> {
+	/// @notice A descriptive name for a collection of NFTs in this contract
+	fn name(&self) -> Result<string> {
+		Ok(decode_utf16(self.name.iter().copied())
+			.map(|r| r.unwrap_or(REPLACEMENT_CHARACTER))
+			.collect::<string>())
+	}
+
+	/// @notice An abbreviated name for NFTs in this contract
+	fn symbol(&self) -> Result<string> {
+		Ok(string::from_utf8_lossy(&self.token_prefix).into())
+	}
+
 	/// @notice Transfer ownership of an NFT
 	/// @dev Throws unless `msg.sender` is the current owner. Throws if `to`
 	///  is the zero address. Throws if `tokenId` is not a valid NFT.
@@ -642,6 +668,7 @@
 	///  should be obtained with `nextTokenId` method
 	/// @param to The new owner
 	/// @param tokenIds IDs of the minted NFTs
+	// #[solidity(hide)]
 	#[weight(<SelfWeightOf<T>>::create_multiple_items(token_ids.len() as u32))]
 	fn mint_bulk(&mut self, caller: caller, to: address, token_ids: Vec<uint256>) -> Result<bool> {
 		let caller = T::CrossAccountId::from_eth(caller);
@@ -678,7 +705,7 @@
 	///  numbers and first number should be obtained with `nextTokenId` method
 	/// @param to The new owner
 	/// @param tokens array of pairs of token ID and token URI for minted tokens
-	#[solidity(rename_selector = "mintBulkWithTokenURI")]
+	#[solidity(/*hide,*/ rename_selector = "mintBulkWithTokenURI")]
 	#[weight(<SelfWeightOf<T>>::create_multiple_items(tokens.len() as u32))]
 	fn mint_bulk_with_token_uri(
 		&mut self,
@@ -731,11 +758,11 @@
 	name = UniqueNFT,
 	is(
 		ERC721,
-		ERC721Metadata,
 		ERC721Enumerable,
 		ERC721UniqueExtensions,
-		ERC721Mintable,
+		ERC721UniqueMintable,
 		ERC721Burnable,
+		ERC721Metadata(if(this.flags.erc721metadata)),
 		Collection(via(common_mut returns CollectionHandle<T>)),
 		TokenProperties,
 	)
modifiedpallets/nonfungible/src/lib.rsdiffbeforeafterboth
--- a/pallets/nonfungible/src/lib.rs
+++ b/pallets/nonfungible/src/lib.rs
@@ -295,6 +295,7 @@
 		&mut self.0
 	}
 }
+
 impl<T: Config> WithRecorder<T> for NonfungibleHandle<T> {
 	fn recorder(&self) -> &SubstrateRecorder<T> {
 		self.0.recorder()
@@ -407,17 +408,9 @@
 		owner: T::CrossAccountId,
 		payer: T::CrossAccountId,
 		data: CreateCollectionData<T::AccountId>,
-		is_external: bool,
+		flags: CollectionFlags,
 	) -> Result<CollectionId, DispatchError> {
-		<PalletCommon<T>>::init_collection(
-			owner,
-			payer,
-			data,
-			CollectionFlags {
-				external: is_external,
-				..Default::default()
-			},
-		)
+		<PalletCommon<T>>::init_collection(owner, payer, data, flags)
 	}
 
 	/// Destroy NFT 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
@@ -91,7 +91,7 @@
 }
 
 /// @title A contract that allows you to work with collections.
-/// @dev the ERC-165 identifier for this interface is 0x3e1e8083
+/// @dev the ERC-165 identifier for this interface is 0x62e22290
 contract Collection is Dummy, ERC165 {
 	/// Set collection property.
 	///
@@ -369,9 +369,9 @@
 	///
 	/// @dev Owner can be changed only by current owner
 	/// @param newOwner new owner account
-	/// @dev EVM selector for this function is: 0x13af4035,
-	///  or in textual repr: setOwner(address)
-	function setOwner(address newOwner) public {
+	/// @dev EVM selector for this function is: 0x4f53e226,
+	///  or in textual repr: changeCollectionOwner(address)
+	function changeCollectionOwner(address newOwner) public {
 		require(false, stub_error);
 		newOwner;
 		dummy = 0;
@@ -384,6 +384,49 @@
 	uint256 field_1;
 }
 
+/// @title ERC-721 Non-Fungible Token Standard, optional metadata extension
+/// @dev See https://eips.ethereum.org/EIPS/eip-721
+/// @dev the ERC-165 identifier for this interface is 0x5b5e139f
+contract ERC721Metadata is Dummy, ERC165 {
+	// /// @notice A descriptive name for a collection of NFTs in this contract
+	// /// @dev real implementation of this function lies in `ERC721UniqueExtensions`
+	// /// @dev EVM selector for this function is: 0x06fdde03,
+	// ///  or in textual repr: name()
+	// function name() public view returns (string memory) {
+	// 	require(false, stub_error);
+	// 	dummy;
+	// 	return "";
+	// }
+
+	// /// @notice An abbreviated name for NFTs in this contract
+	// /// @dev real implementation of this function lies in `ERC721UniqueExtensions`
+	// /// @dev EVM selector for this function is: 0x95d89b41,
+	// ///  or in textual repr: symbol()
+	// function symbol() public view returns (string memory) {
+	// 	require(false, stub_error);
+	// 	dummy;
+	// 	return "";
+	// }
+
+	/// @notice A distinct Uniform Resource Identifier (URI) for a given asset.
+	///
+	/// @dev If the token has a `url` property and it is not empty, it is returned.
+	///  Else If the collection does not have a property with key `schemaName` or its value is not equal to `ERC721Metadata`, it return an error `tokenURI not set`.
+	///  If the collection property `baseURI` is empty or absent, return "" (empty string)
+	///  otherwise, if token property `suffix` present and is non-empty, return concatenation of baseURI and suffix
+	///  otherwise, return concatenation of `baseURI` and stringified token id (decimal stringifying, without paddings).
+	///
+	/// @return token's const_metadata
+	/// @dev EVM selector for this function is: 0xc87b56dd,
+	///  or in textual repr: tokenURI(uint256)
+	function tokenURI(uint256 tokenId) public view returns (string memory) {
+		require(false, stub_error);
+		tokenId;
+		dummy;
+		return "";
+	}
+}
+
 /// @title ERC721 Token that can be irreversibly burned (destroyed).
 /// @dev the ERC-165 identifier for this interface is 0x42966c68
 contract ERC721Burnable is Dummy, ERC165 {
@@ -401,13 +444,13 @@
 }
 
 /// @dev inlined interface
-contract ERC721MintableEvents {
+contract ERC721UniqueMintableEvents {
 	event MintingFinished();
 }
 
 /// @title ERC721 minting logic.
-/// @dev the ERC-165 identifier for this interface is 0x68ccfe89
-contract ERC721Mintable is Dummy, ERC165, ERC721MintableEvents {
+/// @dev the ERC-165 identifier for this interface is 0x476ff149
+contract ERC721UniqueMintable is Dummy, ERC165, ERC721UniqueMintableEvents {
 	/// @dev EVM selector for this function is: 0x05d2035b,
 	///  or in textual repr: mintingFinished()
 	function mintingFinished() public view returns (bool) {
@@ -417,41 +460,63 @@
 	}
 
 	/// @notice Function to mint token.
-	/// @dev `tokenId` should be obtained with `nextTokenId` method,
-	///  unlike standard, you can't specify it manually
 	/// @param to The new owner
-	/// @param tokenId ID of the minted NFT
-	/// @dev EVM selector for this function is: 0x40c10f19,
-	///  or in textual repr: mint(address,uint256)
-	function mint(address to, uint256 tokenId) public returns (bool) {
+	/// @return uint256 The id of the newly minted token
+	/// @dev EVM selector for this function is: 0x6a627842,
+	///  or in textual repr: mint(address)
+	function mint(address to) public returns (uint256) {
 		require(false, stub_error);
 		to;
-		tokenId;
 		dummy = 0;
-		return false;
+		return 0;
 	}
 
+	// /// @notice Function to mint token.
+	// /// @dev `tokenId` should be obtained with `nextTokenId` method,
+	// ///  unlike standard, you can't specify it manually
+	// /// @param to The new owner
+	// /// @param tokenId ID of the minted NFT
+	// /// @dev EVM selector for this function is: 0x40c10f19,
+	// ///  or in textual repr: mint(address,uint256)
+	// function mint(address to, uint256 tokenId) public returns (bool) {
+	// 	require(false, stub_error);
+	// 	to;
+	// 	tokenId;
+	// 	dummy = 0;
+	// 	return false;
+	// }
+
 	/// @notice Function to mint token with the given tokenUri.
-	/// @dev `tokenId` should be obtained with `nextTokenId` method,
-	///  unlike standard, you can't specify it manually
 	/// @param to The new owner
-	/// @param tokenId ID of the minted NFT
 	/// @param tokenUri Token URI that would be stored in the NFT properties
-	/// @dev EVM selector for this function is: 0x50bb4e7f,
-	///  or in textual repr: mintWithTokenURI(address,uint256,string)
-	function mintWithTokenURI(
-		address to,
-		uint256 tokenId,
-		string memory tokenUri
-	) public returns (bool) {
+	/// @return uint256 The id of the newly minted token
+	/// @dev EVM selector for this function is: 0x45c17782,
+	///  or in textual repr: mintWithTokenURI(address,string)
+	function mintWithTokenURI(address to, string memory tokenUri) public returns (uint256) {
 		require(false, stub_error);
 		to;
-		tokenId;
 		tokenUri;
 		dummy = 0;
-		return false;
+		return 0;
 	}
 
+	// /// @notice Function to mint token with the given tokenUri.
+	// /// @dev `tokenId` should be obtained with `nextTokenId` method,
+	// ///  unlike standard, you can't specify it manually
+	// /// @param to The new owner
+	// /// @param tokenId ID of the minted NFT
+	// /// @param tokenUri Token URI that would be stored in the NFT properties
+	// /// @dev EVM selector for this function is: 0x50bb4e7f,
+	// ///  or in textual repr: mintWithTokenURI(address,uint256,string)
+	// function mintWithTokenURI(address to, uint256 tokenId, string memory tokenUri) public returns (bool) {
+	// 	require(false, stub_error);
+	// 	to;
+	// 	tokenId;
+	// 	tokenUri;
+	// 	dummy = 0;
+	// 	return false;
+	// }
+
 	/// @dev Not implemented
 	/// @dev EVM selector for this function is: 0x7d64bcb4,
 	///  or in textual repr: finishMinting()
@@ -463,8 +528,26 @@
 }
 
 /// @title Unique extensions for ERC721.
-/// @dev the ERC-165 identifier for this interface is 0xd74d154f
+/// @dev the ERC-165 identifier for this interface is 0x4468500d
 contract ERC721UniqueExtensions is Dummy, ERC165 {
+	/// @notice A descriptive name for a collection of NFTs in this contract
+	/// @dev EVM selector for this function is: 0x06fdde03,
+	///  or in textual repr: name()
+	function name() public view returns (string memory) {
+		require(false, stub_error);
+		dummy;
+		return "";
+	}
+
+	/// @notice An abbreviated name for NFTs in this contract
+	/// @dev EVM selector for this function is: 0x95d89b41,
+	///  or in textual repr: symbol()
+	function symbol() public view returns (string memory) {
+		require(false, stub_error);
+		dummy;
+		return "";
+	}
+
 	/// @notice Transfer ownership of an NFT
 	/// @dev Throws unless `msg.sender` is the current owner. Throws if `to`
 	///  is the zero address. Throws if `tokenId` is not a valid NFT.
@@ -525,7 +608,7 @@
 	/// @param tokens array of pairs of token ID and token URI for minted tokens
 	/// @dev EVM selector for this function is: 0x36543006,
 	///  or in textual repr: mintBulkWithTokenURI(address,(uint256,string)[])
-	function mintBulkWithTokenURI(address to, Tuple8[] memory tokens) public returns (bool) {
+	function mintBulkWithTokenURI(address to, Tuple6[] memory tokens) public returns (bool) {
 		require(false, stub_error);
 		to;
 		tokens;
@@ -535,7 +618,7 @@
 }
 
 /// @dev anonymous struct
-struct Tuple8 {
+struct Tuple6 {
 	uint256 field_0;
 	string field_1;
 }
@@ -579,48 +662,7 @@
 		return 0;
 	}
 }
-
-/// @title ERC-721 Non-Fungible Token Standard, optional metadata extension
-/// @dev See https://eips.ethereum.org/EIPS/eip-721
-/// @dev the ERC-165 identifier for this interface is 0x5b5e139f
-contract ERC721Metadata is Dummy, ERC165 {
-	/// @notice A descriptive name for a collection of NFTs in this contract
-	/// @dev EVM selector for this function is: 0x06fdde03,
-	///  or in textual repr: name()
-	function name() public view returns (string memory) {
-		require(false, stub_error);
-		dummy;
-		return "";
-	}
-
-	/// @notice An abbreviated name for NFTs in this contract
-	/// @dev EVM selector for this function is: 0x95d89b41,
-	///  or in textual repr: symbol()
-	function symbol() public view returns (string memory) {
-		require(false, stub_error);
-		dummy;
-		return "";
-	}
 
-	/// @notice A distinct Uniform Resource Identifier (URI) for a given asset.
-	///
-	/// @dev If the token has a `url` property and it is not empty, it is returned.
-	///  Else If the collection does not have a property with key `schemaName` or its value is not equal to `ERC721Metadata`, it return an error `tokenURI not set`.
-	///  If the collection property `baseURI` is empty or absent, return "" (empty string)
-	///  otherwise, if token property `suffix` present and is non-empty, return concatenation of baseURI and suffix
-	///  otherwise, return concatenation of `baseURI` and stringified token id (decimal stringifying, without paddings).
-	///
-	/// @return token's const_metadata
-	/// @dev EVM selector for this function is: 0xc87b56dd,
-	///  or in textual repr: tokenURI(uint256)
-	function tokenURI(uint256 tokenId) public view returns (string memory) {
-		require(false, stub_error);
-		tokenId;
-		dummy;
-		return "";
-	}
-}
-
 /// @dev inlined interface
 contract ERC721Events {
 	event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
@@ -766,11 +808,11 @@
 	Dummy,
 	ERC165,
 	ERC721,
-	ERC721Metadata,
 	ERC721Enumerable,
 	ERC721UniqueExtensions,
-	ERC721Mintable,
+	ERC721UniqueMintable,
 	ERC721Burnable,
+	ERC721Metadata,
 	Collection,
 	TokenProperties
 {}
modifiedpallets/proxy-rmrk-core/src/lib.rsdiffbeforeafterboth
--- a/pallets/proxy-rmrk-core/src/lib.rs
+++ b/pallets/proxy-rmrk-core/src/lib.rs
@@ -1448,7 +1448,15 @@
 		data: CreateCollectionData<T::AccountId>,
 		properties: impl Iterator<Item = Property>,
 	) -> Result<CollectionId, DispatchError> {
-		let collection_id = <PalletNft<T>>::init_collection(sender.clone(), sender, data, true);
+		let collection_id = <PalletNft<T>>::init_collection(
+			sender.clone(),
+			sender,
+			data,
+			up_data_structs::CollectionFlags {
+				external: true,
+				..Default::default()
+			},
+		);
 
 		if let Err(DispatchError::Arithmetic(_)) = &collection_id {
 			return Err(<Error<T>>::NoAvailableCollectionId.into());
modifiedpallets/proxy-rmrk-equip/src/lib.rsdiffbeforeafterboth
--- a/pallets/proxy-rmrk-equip/src/lib.rs
+++ b/pallets/proxy-rmrk-equip/src/lib.rs
@@ -254,7 +254,10 @@
 				cross_sender.clone(),
 				cross_sender.clone(),
 				data,
-				true,
+				up_data_structs::CollectionFlags {
+					external: true,
+					..Default::default()
+				},
 			);
 
 			if let Err(DispatchError::Arithmetic(_)) = &collection_id_res {
modifiedpallets/refungible/src/erc.rsdiffbeforeafterboth
--- a/pallets/refungible/src/erc.rs
+++ b/pallets/refungible/src/erc.rs
@@ -21,19 +21,15 @@
 
 extern crate alloc;
 
-use alloc::string::ToString;
 use core::{
 	char::{REPLACEMENT_CHARACTER, decode_utf16},
 	convert::TryInto,
 };
 use evm_coder::{ToLog, execution::*, generate_stubgen, solidity, solidity_interface, types::*, weight};
-use frame_support::BoundedBTreeMap;
+use frame_support::{BoundedBTreeMap, BoundedVec};
 use pallet_common::{
 	CollectionHandle, CollectionPropertyPermissions,
-	erc::{
-		CommonEvmHandler, CollectionCall,
-		static_property::{key, value as property_value},
-	},
+	erc::{CommonEvmHandler, CollectionCall, static_property::key},
 };
 use pallet_evm::{account::CrossAccountId, PrecompileHandle};
 use pallet_evm_coder_substrate::{call, dispatch_to_evm};
@@ -191,7 +187,7 @@
 }
 
 #[derive(ToLog)]
-pub enum ERC721MintableEvents {
+pub enum ERC721UniqueMintableEvents {
 	/// @dev Not supported
 	#[allow(dead_code)]
 	MintingFinished {},
@@ -199,16 +195,18 @@
 
 #[solidity_interface(name = ERC721Metadata)]
 impl<T: Config> RefungibleHandle<T> {
-	/// @notice A descriptive name for a collection of RFTs in this contract
-	fn name(&self) -> Result<string> {
-		Ok(decode_utf16(self.name.iter().copied())
-			.map(|r| r.unwrap_or(REPLACEMENT_CHARACTER))
-			.collect::<string>())
+	/// @notice A descriptive name for a collection of NFTs in this contract
+	/// @dev real implementation of this function lies in `ERC721UniqueExtensions`
+	#[solidity(hide, rename_selector = "name")]
+	fn name_proxy(&self) -> Result<string> {
+		self.name()
 	}
 
-	/// @notice An abbreviated name for RFTs in this contract
-	fn symbol(&self) -> Result<string> {
-		Ok(string::from_utf8_lossy(&self.token_prefix).into())
+	/// @notice An abbreviated name for NFTs in this contract
+	/// @dev real implementation of this function lies in `ERC721UniqueExtensions`
+	#[solidity(hide, rename_selector = "symbol")]
+	fn symbol_proxy(&self) -> Result<string> {
+		self.symbol()
 	}
 
 	/// @notice A distinct Uniform Resource Identifier (URI) for a given asset.
@@ -224,35 +222,38 @@
 	fn token_uri(&self, token_id: uint256) -> Result<string> {
 		let token_id_u32: u32 = token_id.try_into().map_err(|_| "token id overflow")?;
 
-		if let Ok(url) = get_token_property(self, token_id_u32, &key::url()) {
-			if !url.is_empty() {
-				return Ok(url);
+		match get_token_property(self, token_id_u32, &key::url()).as_deref() {
+			Err(_) | Ok("") => (),
+			Ok(url) => {
+				return Ok(url.into());
 			}
-		} else if !is_erc721_metadata_compatible::<T>(self.id) {
-			return Err("tokenURI not set".into());
-		}
+		};
 
-		if let Some(base_uri) =
+		let base_uri =
 			pallet_common::Pallet::<T>::get_collection_property(self.id, &key::base_uri())
-		{
-			if !base_uri.is_empty() {
-				let base_uri = string::from_utf8(base_uri.into_inner()).map_err(|e| {
+				.map(BoundedVec::into_inner)
+				.map(string::from_utf8)
+				.transpose()
+				.map_err(|e| {
 					Error::Revert(alloc::format!(
 						"Can not convert value \"baseURI\" to string with error \"{}\"",
 						e
 					))
 				})?;
-				if let Ok(suffix) = get_token_property(self, token_id_u32, &key::suffix()) {
-					if !suffix.is_empty() {
-						return Ok(base_uri + suffix.as_str());
-					}
-				}
 
-				return Ok(base_uri + token_id.to_string().as_str());
+		let base_uri = match base_uri.as_deref() {
+			None | Some("") => {
+				return Ok("".into());
 			}
-		}
+			Some(base_uri) => base_uri.into(),
+		};
 
-		Ok("".into())
+		Ok(
+			match get_token_property(self, token_id_u32, &key::suffix()).as_deref() {
+				Err(_) | Ok("") => base_uri,
+				Ok(suffix) => base_uri + suffix,
+			},
+		)
 	}
 }
 
@@ -448,19 +449,33 @@
 }
 
 /// @title ERC721 minting logic.
-#[solidity_interface(name = ERC721Mintable, events(ERC721MintableEvents))]
+#[solidity_interface(name = ERC721UniqueMintable, events(ERC721UniqueMintableEvents))]
 impl<T: Config> RefungibleHandle<T> {
 	fn minting_finished(&self) -> Result<bool> {
 		Ok(false)
 	}
 
 	/// @notice Function to mint token.
+	/// @param to The new owner
+	/// @return uint256 The id of the newly minted token
+	#[weight(<SelfWeightOf<T>>::create_item())]
+	fn mint(&mut self, caller: caller, to: address) -> Result<uint256> {
+		let token_id: uint256 = <TokensMinted<T>>::get(self.id)
+			.checked_add(1)
+			.ok_or("item id overflow")?
+			.into();
+		self.mint_check_id(caller, to, token_id)?;
+		Ok(token_id)
+	}
+
+	/// @notice Function to mint token.
 	/// @dev `tokenId` should be obtained with `nextTokenId` method,
 	///  unlike standard, you can't specify it manually
 	/// @param to The new owner
 	/// @param tokenId ID of the minted RFT
+	#[solidity(hide, rename_selector = "mint")]
 	#[weight(<SelfWeightOf<T>>::create_item())]
-	fn mint(&mut self, caller: caller, to: address, token_id: uint256) -> Result<bool> {
+	fn mint_check_id(&mut self, caller: caller, to: address, token_id: uint256) -> Result<bool> {
 		let caller = T::CrossAccountId::from_eth(caller);
 		let to = T::CrossAccountId::from_eth(to);
 		let token_id: u32 = token_id.try_into()?;
@@ -496,14 +511,34 @@
 	}
 
 	/// @notice Function to mint token with the given tokenUri.
+	/// @param to The new owner
+	/// @param tokenUri Token URI that would be stored in the NFT properties
+	/// @return uint256 The id of the newly minted token
+	#[solidity(rename_selector = "mintWithTokenURI")]
+	#[weight(<SelfWeightOf<T>>::create_item())]
+	fn mint_with_token_uri(
+		&mut self,
+		caller: caller,
+		to: address,
+		token_uri: string,
+	) -> Result<uint256> {
+		let token_id: uint256 = <TokensMinted<T>>::get(self.id)
+			.checked_add(1)
+			.ok_or("item id overflow")?
+			.into();
+		self.mint_with_token_uri_check_id(caller, to, token_id, token_uri)?;
+		Ok(token_id)
+	}
+
+	/// @notice Function to mint token with the given tokenUri.
 	/// @dev `tokenId` should be obtained with `nextTokenId` method,
 	///  unlike standard, you can't specify it manually
 	/// @param to The new owner
 	/// @param tokenId ID of the minted RFT
 	/// @param tokenUri Token URI that would be stored in the RFT properties
-	#[solidity(rename_selector = "mintWithTokenURI")]
+	#[solidity(hide, rename_selector = "mintWithTokenURI")]
 	#[weight(<SelfWeightOf<T>>::create_item())]
-	fn mint_with_token_uri(
+	fn mint_with_token_uri_check_id(
 		&mut self,
 		caller: caller,
 		to: address,
@@ -578,17 +613,6 @@
 	Err("Property tokenURI not found".into())
 }
 
-fn is_erc721_metadata_compatible<T: Config>(collection_id: CollectionId) -> bool {
-	if let Some(shema_name) =
-		pallet_common::Pallet::<T>::get_collection_property(collection_id, &key::schema_name())
-	{
-		let shema_name = shema_name.into_inner();
-		shema_name == property_value::ERC721_METADATA
-	} else {
-		false
-	}
-}
-
 fn get_token_permission<T: Config>(
 	collection_id: CollectionId,
 	key: &PropertyKey,
@@ -608,6 +632,18 @@
 /// @title Unique extensions for ERC721.
 #[solidity_interface(name = ERC721UniqueExtensions)]
 impl<T: Config> RefungibleHandle<T> {
+	/// @notice A descriptive name for a collection of NFTs in this contract
+	fn name(&self) -> Result<string> {
+		Ok(decode_utf16(self.name.iter().copied())
+			.map(|r| r.unwrap_or(REPLACEMENT_CHARACTER))
+			.collect::<string>())
+	}
+
+	/// @notice An abbreviated name for NFTs in this contract
+	fn symbol(&self) -> Result<string> {
+		Ok(string::from_utf8_lossy(&self.token_prefix).into())
+	}
+
 	/// @notice Transfer ownership of an RFT
 	/// @dev Throws unless `msg.sender` is the current owner. Throws if `to`
 	///  is the zero address. Throws if `tokenId` is not a valid RFT.
@@ -669,6 +705,7 @@
 	///  should be obtained with `nextTokenId` method
 	/// @param to The new owner
 	/// @param tokenIds IDs of the minted RFTs
+	// #[solidity(hide)]
 	#[weight(<SelfWeightOf<T>>::create_multiple_items(token_ids.len() as u32))]
 	fn mint_bulk(&mut self, caller: caller, to: address, token_ids: Vec<uint256>) -> Result<bool> {
 		let caller = T::CrossAccountId::from_eth(caller);
@@ -711,7 +748,7 @@
 	///  numbers and first number should be obtained with `nextTokenId` method
 	/// @param to The new owner
 	/// @param tokens array of pairs of token ID and token URI for minted tokens
-	#[solidity(rename_selector = "mintBulkWithTokenURI")]
+	#[solidity(/*hide,*/ rename_selector = "mintBulkWithTokenURI")]
 	#[weight(<SelfWeightOf<T>>::create_multiple_items(tokens.len() as u32))]
 	fn mint_bulk_with_token_uri(
 		&mut self,
@@ -780,11 +817,11 @@
 	name = UniqueRefungible,
 	is(
 		ERC721,
-		ERC721Metadata,
 		ERC721Enumerable,
 		ERC721UniqueExtensions,
-		ERC721Mintable,
+		ERC721UniqueMintable,
 		ERC721Burnable,
+		ERC721Metadata(if(this.flags.erc721metadata)),
 		Collection(via(common_mut returns CollectionHandle<T>)),
 		TokenProperties,
 	)
modifiedpallets/refungible/src/lib.rsdiffbeforeafterboth
--- a/pallets/refungible/src/lib.rs
+++ b/pallets/refungible/src/lib.rs
@@ -92,9 +92,11 @@
 
 use codec::{Encode, Decode, MaxEncodedLen};
 use core::ops::Deref;
+use derivative::Derivative;
 use evm_coder::ToLog;
 use frame_support::{
-	BoundedVec, ensure, fail, storage::with_transaction, transactional, pallet_prelude::ConstU32,
+	BoundedBTreeMap, BoundedVec, ensure, fail, storage::with_transaction, transactional,
+	pallet_prelude::ConstU32,
 };
 use pallet_evm::{account::CrossAccountId, Pallet as PalletEvm};
 use pallet_evm_coder_substrate::WithRecorder;
@@ -113,8 +115,6 @@
 	MAX_REFUNGIBLE_PIECES, Property, PropertyKey, PropertyKeyPermission, PropertyPermission,
 	PropertyScope, PropertyValue, TokenId, TrySetProperty,
 };
-use frame_support::BoundedBTreeMap;
-use derivative::Derivative;
 
 pub use pallet::*;
 #[cfg(feature = "runtime-benchmarks")]
@@ -371,8 +371,9 @@
 		owner: T::CrossAccountId,
 		payer: T::CrossAccountId,
 		data: CreateCollectionData<T::AccountId>,
+		flags: CollectionFlags,
 	) -> Result<CollectionId, DispatchError> {
-		<PalletCommon<T>>::init_collection(owner, payer, data, CollectionFlags::default())
+		<PalletCommon<T>>::init_collection(owner, payer, data, flags)
 	}
 
 	/// Destroy RFT collection
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
@@ -91,7 +91,7 @@
 }
 
 /// @title A contract that allows you to work with collections.
-/// @dev the ERC-165 identifier for this interface is 0x3e1e8083
+/// @dev the ERC-165 identifier for this interface is 0x62e22290
 contract Collection is Dummy, ERC165 {
 	/// Set collection property.
 	///
@@ -369,9 +369,9 @@
 	///
 	/// @dev Owner can be changed only by current owner
 	/// @param newOwner new owner account
-	/// @dev EVM selector for this function is: 0x13af4035,
-	///  or in textual repr: setOwner(address)
-	function setOwner(address newOwner) public {
+	/// @dev EVM selector for this function is: 0x4f53e226,
+	///  or in textual repr: changeCollectionOwner(address)
+	function changeCollectionOwner(address newOwner) public {
 		require(false, stub_error);
 		newOwner;
 		dummy = 0;
@@ -384,6 +384,47 @@
 	uint256 field_1;
 }
 
+/// @dev the ERC-165 identifier for this interface is 0x5b5e139f
+contract ERC721Metadata is Dummy, ERC165 {
+	// /// @notice A descriptive name for a collection of NFTs in this contract
+	// /// @dev real implementation of this function lies in `ERC721UniqueExtensions`
+	// /// @dev EVM selector for this function is: 0x06fdde03,
+	// ///  or in textual repr: name()
+	// function name() public view returns (string memory) {
+	// 	require(false, stub_error);
+	// 	dummy;
+	// 	return "";
+	// }
+
+	// /// @notice An abbreviated name for NFTs in this contract
+	// /// @dev real implementation of this function lies in `ERC721UniqueExtensions`
+	// /// @dev EVM selector for this function is: 0x95d89b41,
+	// ///  or in textual repr: symbol()
+	// function symbol() public view returns (string memory) {
+	// 	require(false, stub_error);
+	// 	dummy;
+	// 	return "";
+	// }
+
+	/// @notice A distinct Uniform Resource Identifier (URI) for a given asset.
+	///
+	/// @dev If the token has a `url` property and it is not empty, it is returned.
+	///  Else If the collection does not have a property with key `schemaName` or its value is not equal to `ERC721Metadata`, it return an error `tokenURI not set`.
+	///  If the collection property `baseURI` is empty or absent, return "" (empty string)
+	///  otherwise, if token property `suffix` present and is non-empty, return concatenation of baseURI and suffix
+	///  otherwise, return concatenation of `baseURI` and stringified token id (decimal stringifying, without paddings).
+	///
+	/// @return token's const_metadata
+	/// @dev EVM selector for this function is: 0xc87b56dd,
+	///  or in textual repr: tokenURI(uint256)
+	function tokenURI(uint256 tokenId) public view returns (string memory) {
+		require(false, stub_error);
+		tokenId;
+		dummy;
+		return "";
+	}
+}
+
 /// @title ERC721 Token that can be irreversibly burned (destroyed).
 /// @dev the ERC-165 identifier for this interface is 0x42966c68
 contract ERC721Burnable is Dummy, ERC165 {
@@ -401,13 +442,13 @@
 }
 
 /// @dev inlined interface
-contract ERC721MintableEvents {
+contract ERC721UniqueMintableEvents {
 	event MintingFinished();
 }
 
 /// @title ERC721 minting logic.
-/// @dev the ERC-165 identifier for this interface is 0x68ccfe89
-contract ERC721Mintable is Dummy, ERC165, ERC721MintableEvents {
+/// @dev the ERC-165 identifier for this interface is 0x476ff149
+contract ERC721UniqueMintable is Dummy, ERC165, ERC721UniqueMintableEvents {
 	/// @dev EVM selector for this function is: 0x05d2035b,
 	///  or in textual repr: mintingFinished()
 	function mintingFinished() public view returns (bool) {
@@ -417,41 +458,63 @@
 	}
 
 	/// @notice Function to mint token.
-	/// @dev `tokenId` should be obtained with `nextTokenId` method,
-	///  unlike standard, you can't specify it manually
 	/// @param to The new owner
-	/// @param tokenId ID of the minted RFT
-	/// @dev EVM selector for this function is: 0x40c10f19,
-	///  or in textual repr: mint(address,uint256)
-	function mint(address to, uint256 tokenId) public returns (bool) {
+	/// @return uint256 The id of the newly minted token
+	/// @dev EVM selector for this function is: 0x6a627842,
+	///  or in textual repr: mint(address)
+	function mint(address to) public returns (uint256) {
 		require(false, stub_error);
 		to;
-		tokenId;
 		dummy = 0;
-		return false;
+		return 0;
 	}
 
+	// /// @notice Function to mint token.
+	// /// @dev `tokenId` should be obtained with `nextTokenId` method,
+	// ///  unlike standard, you can't specify it manually
+	// /// @param to The new owner
+	// /// @param tokenId ID of the minted RFT
+	// /// @dev EVM selector for this function is: 0x40c10f19,
+	// ///  or in textual repr: mint(address,uint256)
+	// function mint(address to, uint256 tokenId) public returns (bool) {
+	// 	require(false, stub_error);
+	// 	to;
+	// 	tokenId;
+	// 	dummy = 0;
+	// 	return false;
+	// }
+
 	/// @notice Function to mint token with the given tokenUri.
-	/// @dev `tokenId` should be obtained with `nextTokenId` method,
-	///  unlike standard, you can't specify it manually
 	/// @param to The new owner
-	/// @param tokenId ID of the minted RFT
-	/// @param tokenUri Token URI that would be stored in the RFT properties
-	/// @dev EVM selector for this function is: 0x50bb4e7f,
-	///  or in textual repr: mintWithTokenURI(address,uint256,string)
-	function mintWithTokenURI(
-		address to,
-		uint256 tokenId,
-		string memory tokenUri
-	) public returns (bool) {
+	/// @param tokenUri Token URI that would be stored in the NFT properties
+	/// @return uint256 The id of the newly minted token
+	/// @dev EVM selector for this function is: 0x45c17782,
+	///  or in textual repr: mintWithTokenURI(address,string)
+	function mintWithTokenURI(address to, string memory tokenUri) public returns (uint256) {
 		require(false, stub_error);
 		to;
-		tokenId;
 		tokenUri;
 		dummy = 0;
-		return false;
+		return 0;
 	}
 
+	// /// @notice Function to mint token with the given tokenUri.
+	// /// @dev `tokenId` should be obtained with `nextTokenId` method,
+	// ///  unlike standard, you can't specify it manually
+	// /// @param to The new owner
+	// /// @param tokenId ID of the minted RFT
+	// /// @param tokenUri Token URI that would be stored in the RFT properties
+	// /// @dev EVM selector for this function is: 0x50bb4e7f,
+	// ///  or in textual repr: mintWithTokenURI(address,uint256,string)
+	// function mintWithTokenURI(address to, uint256 tokenId, string memory tokenUri) public returns (bool) {
+	// 	require(false, stub_error);
+	// 	to;
+	// 	tokenId;
+	// 	tokenUri;
+	// 	dummy = 0;
+	// 	return false;
+	// }
+
 	/// @dev Not implemented
 	/// @dev EVM selector for this function is: 0x7d64bcb4,
 	///  or in textual repr: finishMinting()
@@ -463,8 +526,26 @@
 }
 
 /// @title Unique extensions for ERC721.
-/// @dev the ERC-165 identifier for this interface is 0x7c3bef89
+/// @dev the ERC-165 identifier for this interface is 0xef1eaacb
 contract ERC721UniqueExtensions is Dummy, ERC165 {
+	/// @notice A descriptive name for a collection of NFTs in this contract
+	/// @dev EVM selector for this function is: 0x06fdde03,
+	///  or in textual repr: name()
+	function name() public view returns (string memory) {
+		require(false, stub_error);
+		dummy;
+		return "";
+	}
+
+	/// @notice An abbreviated name for NFTs in this contract
+	/// @dev EVM selector for this function is: 0x95d89b41,
+	///  or in textual repr: symbol()
+	function symbol() public view returns (string memory) {
+		require(false, stub_error);
+		dummy;
+		return "";
+	}
+
 	/// @notice Transfer ownership of an RFT
 	/// @dev Throws unless `msg.sender` is the current owner. Throws if `to`
 	///  is the zero address. Throws if `tokenId` is not a valid RFT.
@@ -527,7 +608,7 @@
 	/// @param tokens array of pairs of token ID and token URI for minted tokens
 	/// @dev EVM selector for this function is: 0x36543006,
 	///  or in textual repr: mintBulkWithTokenURI(address,(uint256,string)[])
-	function mintBulkWithTokenURI(address to, Tuple8[] memory tokens) public returns (bool) {
+	function mintBulkWithTokenURI(address to, Tuple6[] memory tokens) public returns (bool) {
 		require(false, stub_error);
 		to;
 		tokens;
@@ -549,7 +630,7 @@
 }
 
 /// @dev anonymous struct
-struct Tuple8 {
+struct Tuple6 {
 	uint256 field_0;
 	string field_1;
 }
@@ -591,46 +672,7 @@
 		require(false, stub_error);
 		dummy;
 		return 0;
-	}
-}
-
-/// @dev the ERC-165 identifier for this interface is 0x5b5e139f
-contract ERC721Metadata is Dummy, ERC165 {
-	/// @notice A descriptive name for a collection of RFTs in this contract
-	/// @dev EVM selector for this function is: 0x06fdde03,
-	///  or in textual repr: name()
-	function name() public view returns (string memory) {
-		require(false, stub_error);
-		dummy;
-		return "";
-	}
-
-	/// @notice An abbreviated name for RFTs in this contract
-	/// @dev EVM selector for this function is: 0x95d89b41,
-	///  or in textual repr: symbol()
-	function symbol() public view returns (string memory) {
-		require(false, stub_error);
-		dummy;
-		return "";
 	}
-
-	/// @notice A distinct Uniform Resource Identifier (URI) for a given asset.
-	///
-	/// @dev If the token has a `url` property and it is not empty, it is returned.
-	///  Else If the collection does not have a property with key `schemaName` or its value is not equal to `ERC721Metadata`, it return an error `tokenURI not set`.
-	///  If the collection property `baseURI` is empty or absent, return "" (empty string)
-	///  otherwise, if token property `suffix` present and is non-empty, return concatenation of baseURI and suffix
-	///  otherwise, return concatenation of `baseURI` and stringified token id (decimal stringifying, without paddings).
-	///
-	/// @return token's const_metadata
-	/// @dev EVM selector for this function is: 0xc87b56dd,
-	///  or in textual repr: tokenURI(uint256)
-	function tokenURI(uint256 tokenId) public view returns (string memory) {
-		require(false, stub_error);
-		tokenId;
-		dummy;
-		return "";
-	}
 }
 
 /// @dev inlined interface
@@ -776,11 +818,11 @@
 	Dummy,
 	ERC165,
 	ERC721,
-	ERC721Metadata,
 	ERC721Enumerable,
 	ERC721UniqueExtensions,
-	ERC721Mintable,
+	ERC721UniqueMintable,
 	ERC721Burnable,
+	ERC721Metadata,
 	Collection,
 	TokenProperties
 {}
modifiedpallets/refungible/src/stubs/UniqueRefungibleToken.rawdiffbeforeafterboth

binary blob — no preview

modifiedpallets/unique/src/eth/mod.rsdiffbeforeafterboth
--- a/pallets/unique/src/eth/mod.rs
+++ b/pallets/unique/src/eth/mod.rs
@@ -25,14 +25,16 @@
 	dispatch::CollectionDispatch,
 	erc::{
 		CollectionHelpersEvents,
-		static_property::{key, value as property_value},
+		static_property::{key},
 	},
+	Pallet as PalletCommon,
 };
 use pallet_evm_coder_substrate::{dispatch_to_evm, SubstrateRecorder, WithRecorder};
 use pallet_evm::{account::CrossAccountId, OnMethodCall, PrecompileHandle, PrecompileResult};
+use sp_std::vec;
 use up_data_structs::{
 	CollectionName, CollectionDescription, CollectionTokenPrefix, CreateCollectionData,
-	CollectionMode, PropertyValue,
+	CollectionMode, PropertyValue, CollectionFlags,
 };
 
 use crate::{Config, SelfWeightOf, weights::WeightInfo};
@@ -57,13 +59,11 @@
 	name: string,
 	description: string,
 	token_prefix: string,
-	base_uri: string,
 ) -> Result<(
 	T::CrossAccountId,
 	CollectionName,
 	CollectionDescription,
 	CollectionTokenPrefix,
-	PropertyValue,
 )> {
 	let caller = T::CrossAccountId::from_eth(caller);
 	let name = name
@@ -81,75 +81,7 @@
 	let token_prefix = token_prefix.into_bytes().try_into().map_err(|_| {
 		error_field_too_long(stringify!(token_prefix), CollectionTokenPrefix::bound())
 	})?;
-	let base_uri_value = base_uri
-		.into_bytes()
-		.try_into()
-		.map_err(|_| error_field_too_long(stringify!(token_prefix), PropertyValue::bound()))?;
-	Ok((caller, name, description, token_prefix, base_uri_value))
-}
-
-fn make_data<T: Config>(
-	name: CollectionName,
-	mode: CollectionMode,
-	description: CollectionDescription,
-	token_prefix: CollectionTokenPrefix,
-	base_uri_value: PropertyValue,
-	add_properties: bool,
-) -> Result<CreateCollectionData<T::AccountId>> {
-	let mut properties = up_data_structs::CollectionPropertiesVec::default();
-	let mut token_property_permissions =
-		up_data_structs::CollectionPropertiesPermissionsVec::default();
-
-	token_property_permissions
-		.try_push(up_data_structs::PropertyKeyPermission {
-			key: key::url(),
-			permission: up_data_structs::PropertyPermission {
-				mutable: false,
-				collection_admin: true,
-				token_owner: false,
-			},
-		})
-		.map_err(|e| Error::Revert(format!("{:?}", e)))?;
-
-	if add_properties {
-		token_property_permissions
-			.try_push(up_data_structs::PropertyKeyPermission {
-				key: key::suffix(),
-				permission: up_data_structs::PropertyPermission {
-					mutable: false,
-					collection_admin: true,
-					token_owner: false,
-				},
-			})
-			.map_err(|e| Error::Revert(format!("{:?}", e)))?;
-
-		properties
-			.try_push(up_data_structs::Property {
-				key: key::schema_name(),
-				value: property_value::erc721(),
-			})
-			.map_err(|e| Error::Revert(format!("{:?}", e)))?;
-
-		if !base_uri_value.is_empty() {
-			properties
-				.try_push(up_data_structs::Property {
-					key: key::base_uri(),
-					value: base_uri_value,
-				})
-				.map_err(|e| Error::Revert(format!("{:?}", e)))?;
-		}
-	}
-
-	let data = CreateCollectionData {
-		name,
-		mode,
-		description,
-		token_prefix,
-		token_property_permissions,
-		properties,
-		..Default::default()
-	};
-	Ok(data)
+	Ok((caller, name, description, token_prefix))
 }
 
 fn create_refungible_collection_internal<
@@ -160,26 +92,27 @@
 	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>(
+	let (caller, name, description, token_prefix) =
+		convert_data::<T>(caller, name, description, token_prefix)?;
+	let data = CreateCollectionData {
 		name,
-		CollectionMode::ReFungible,
+		mode: CollectionMode::ReFungible,
 		description,
 		token_prefix,
-		base_uri_value,
-		add_properties,
-	)?;
+		..Default::default()
+	};
 	check_sent_amount_equals_collection_creation_price::<T>(value)?;
 	let collection_helpers_address =
 		T::CrossAccountId::from_eth(<T as pallet_common::Config>::ContractAddress::get());
 
-	let collection_id =
-		T::CollectionDispatch::create(caller.clone(), collection_helpers_address, data)
-			.map_err(pallet_evm_coder_substrate::dispatch_to_evm::<T>)?;
+	let collection_id = T::CollectionDispatch::create(
+		caller.clone(),
+		collection_helpers_address,
+		data,
+		Default::default(),
+	)
+	.map_err(pallet_evm_coder_substrate::dispatch_to_evm::<T>)?;
 	let address = pallet_common::eth::collection_id_to_address(collection_id);
 	Ok(address)
 }
@@ -212,7 +145,8 @@
 	/// @param tokenPrefix Token prefix to represent the collection tokens in UI and user applications
 	/// @return address Address of the newly created collection
 	#[weight(<SelfWeightOf<T>>::create_collection())]
-	fn create_nonfungible_collection(
+	#[solidity(rename_selector = "createNFTCollection")]
+	fn create_nft_collection(
 		&mut self,
 		caller: caller,
 		value: value,
@@ -220,60 +154,51 @@
 		description: string,
 		token_prefix: string,
 	) -> Result<address> {
-		let (caller, name, description, token_prefix, _base_uri_value) =
-			convert_data::<T>(caller, name, description, token_prefix, "".into())?;
-		let data = make_data::<T>(
+		let (caller, name, description, token_prefix) =
+			convert_data::<T>(caller, name, description, token_prefix)?;
+		let data = CreateCollectionData {
 			name,
-			CollectionMode::NFT,
+			mode: CollectionMode::NFT,
 			description,
 			token_prefix,
-			Default::default(),
-			false,
-		)?;
+			..Default::default()
+		};
 		check_sent_amount_equals_collection_creation_price::<T>(value)?;
 		let collection_helpers_address =
 			T::CrossAccountId::from_eth(<T as pallet_common::Config>::ContractAddress::get());
-		let collection_id = T::CollectionDispatch::create(caller, collection_helpers_address, data)
-			.map_err(dispatch_to_evm::<T>)?;
+		let collection_id = T::CollectionDispatch::create(
+			caller,
+			collection_helpers_address,
+			data,
+			Default::default(),
+		)
+		.map_err(dispatch_to_evm::<T>)?;
 
 		let address = pallet_common::eth::collection_id_to_address(collection_id);
 		Ok(address)
 	}
-
+	/// Create an NFT collection
+	/// @param name Name of the collection
+	/// @param description Informative description of the collection
+	/// @param tokenPrefix Token prefix to represent the collection tokens in UI and user applications
+	/// @return address Address of the newly created collection
 	#[weight(<SelfWeightOf<T>>::create_collection())]
-	#[solidity(rename_selector = "createERC721MetadataCompatibleCollection")]
-	fn create_nonfungible_collection_with_properties(
+	#[deprecated(note = "mathod was renamed to `create_nft_collection`, prefer it instead")]
+	#[solidity(hide)]
+	fn create_nonfungible_collection(
 		&mut self,
 		caller: caller,
 		value: value,
 		name: string,
 		description: string,
 		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>(
-			name,
-			CollectionMode::NFT,
-			description,
-			token_prefix,
-			base_uri_value,
-			true,
-		)?;
-		check_sent_amount_equals_collection_creation_price::<T>(value)?;
-		let collection_helpers_address =
-			T::CrossAccountId::from_eth(<T as pallet_common::Config>::ContractAddress::get());
-		let collection_id = T::CollectionDispatch::create(caller, collection_helpers_address, data)
-			.map_err(pallet_evm_coder_substrate::dispatch_to_evm::<T>)?;
-
-		let address = pallet_common::eth::collection_id_to_address(collection_id);
-		Ok(address)
+		self.create_nft_collection(caller, value, name, description, token_prefix)
 	}
 
 	#[weight(<SelfWeightOf<T>>::create_collection())]
 	#[solidity(rename_selector = "createRFTCollection")]
-	fn create_refungible_collection(
+	fn create_rft_collection(
 		&mut self,
 		caller: caller,
 		value: value,
@@ -281,37 +206,94 @@
 		description: string,
 		token_prefix: string,
 	) -> Result<address> {
-		create_refungible_collection_internal::<T>(
-			caller,
-			value,
-			name,
-			description,
-			token_prefix,
-			Default::default(),
-			false,
-		)
+		create_refungible_collection_internal::<T>(caller, value, name, description, token_prefix)
 	}
 
-	#[weight(<SelfWeightOf<T>>::create_collection())]
-	#[solidity(rename_selector = "createERC721MetadataCompatibleRFTCollection")]
-	fn create_refungible_collection_with_properties(
+	#[solidity(rename_selector = "makeCollectionERC721MetadataCompatible")]
+	fn make_collection_metadata_compatible(
 		&mut self,
 		caller: caller,
-		value: value,
-		name: string,
-		description: string,
-		token_prefix: string,
+		collection: address,
 		base_uri: string,
-	) -> Result<address> {
-		create_refungible_collection_internal::<T>(
-			caller,
-			value,
-			name,
-			description,
-			token_prefix,
-			base_uri,
-			true,
-		)
+	) -> Result<()> {
+		let caller = T::CrossAccountId::from_eth(caller);
+		let collection =
+			pallet_common::eth::map_eth_to_id(&collection).ok_or("not a collection address")?;
+		let mut collection =
+			<crate::CollectionHandle<T>>::new(collection).ok_or("collection not found")?;
+
+		if !matches!(
+			collection.mode,
+			CollectionMode::NFT | CollectionMode::ReFungible
+		) {
+			return Err("target collection should be either NFT or Refungible".into());
+		}
+
+		self.recorder().consume_sstore()?;
+		collection
+			.check_is_owner_or_admin(&caller)
+			.map_err(dispatch_to_evm::<T>)?;
+
+		if collection.flags.erc721metadata {
+			return Err("target collection is already Erc721Metadata compatible".into());
+		}
+		collection.flags.erc721metadata = true;
+
+		let all_permissions = <pallet_common::CollectionPropertyPermissions<T>>::get(collection.id);
+		if all_permissions.get(&key::url()).is_none() {
+			self.recorder().consume_sstore()?;
+			<PalletCommon<T>>::set_property_permission(
+				&collection,
+				&caller,
+				up_data_structs::PropertyKeyPermission {
+					key: key::url(),
+					permission: up_data_structs::PropertyPermission {
+						mutable: true,
+						collection_admin: true,
+						token_owner: false,
+					},
+				},
+			)
+			.map_err(dispatch_to_evm::<T>)?;
+		}
+		if all_permissions.get(&key::suffix()).is_none() {
+			self.recorder().consume_sstore()?;
+			<PalletCommon<T>>::set_property_permission(
+				&collection,
+				&caller,
+				up_data_structs::PropertyKeyPermission {
+					key: key::suffix(),
+					permission: up_data_structs::PropertyPermission {
+						mutable: true,
+						collection_admin: true,
+						token_owner: false,
+					},
+				},
+			)
+			.map_err(dispatch_to_evm::<T>)?;
+		}
+
+		let all_properties = <pallet_common::CollectionProperties<T>>::get(collection.id);
+		if all_properties.get(&key::base_uri()).is_none() && !base_uri.is_empty() {
+			self.recorder().consume_sstore()?;
+			<PalletCommon<T>>::set_collection_properties(
+				&collection,
+				&caller,
+				vec![up_data_structs::Property {
+					key: key::base_uri(),
+					value: base_uri
+						.into_bytes()
+						.try_into()
+						.map_err(|_| "base uri is too large")?,
+				}],
+			)
+			.map_err(dispatch_to_evm::<T>)?;
+		}
+
+		self.recorder().consume_sstore()?;
+		collection.save().map_err(dispatch_to_evm::<T>)?;
+
+		Ok(())
 	}
 
 	/// 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
@@ -23,16 +23,16 @@
 }
 
 /// @title Contract, which allows users to operate with collections
-/// @dev the ERC-165 identifier for this interface is 0x5ad4f440
+/// @dev the ERC-165 identifier for this interface is 0x58918631
 contract CollectionHelpers is Dummy, ERC165, CollectionHelpersEvents {
 	/// Create an NFT collection
 	/// @param name Name of the collection
 	/// @param description Informative description of the collection
 	/// @param tokenPrefix Token prefix to represent the collection tokens in UI and user applications
 	/// @return address Address of the newly created collection
-	/// @dev EVM selector for this function is: 0xe34a6844,
-	///  or in textual repr: createNonfungibleCollection(string,string,string)
-	function createNonfungibleCollection(
+	/// @dev EVM selector for this function is: 0x844af658,
+	///  or in textual repr: createNFTCollection(string,string,string)
+	function createNFTCollection(
 		string memory name,
 		string memory description,
 		string memory tokenPrefix
@@ -45,22 +45,21 @@
 		return 0x0000000000000000000000000000000000000000;
 	}
 
-	/// @dev EVM selector for this function is: 0xa634a5f9,
-	///  or in textual repr: createERC721MetadataCompatibleCollection(string,string,string,string)
-	function createERC721MetadataCompatibleCollection(
-		string memory name,
-		string memory description,
-		string memory tokenPrefix,
-		string memory baseUri
-	) public payable returns (address) {
-		require(false, stub_error);
-		name;
-		description;
-		tokenPrefix;
-		baseUri;
-		dummy = 0;
-		return 0x0000000000000000000000000000000000000000;
-	}
+	// /// Create an NFT collection
+	// /// @param name Name of the collection
+	// /// @param description Informative description of the collection
+	// /// @param tokenPrefix Token prefix to represent the collection tokens in UI and user applications
+	// /// @return address Address of the newly created collection
+	// /// @dev EVM selector for this function is: 0xe34a6844,
+	// ///  or in textual repr: createNonfungibleCollection(string,string,string)
+	// function createNonfungibleCollection(string memory name, string memory description, string memory tokenPrefix) public payable returns (address) {
+	// 	require(false, stub_error);
+	// 	name;
+	// 	description;
+	// 	tokenPrefix;
+	// 	dummy = 0;
+	// 	return 0x0000000000000000000000000000000000000000;
+	// }
 
 	/// @dev EVM selector for this function is: 0xab173450,
 	///  or in textual repr: createRFTCollection(string,string,string)
@@ -77,21 +76,13 @@
 		return 0x0000000000000000000000000000000000000000;
 	}
 
-	/// @dev EVM selector for this function is: 0xa5596388,
-	///  or in textual repr: createERC721MetadataCompatibleRFTCollection(string,string,string,string)
-	function createERC721MetadataCompatibleRFTCollection(
-		string memory name,
-		string memory description,
-		string memory tokenPrefix,
-		string memory baseUri
-	) public payable returns (address) {
+	/// @dev EVM selector for this function is: 0x85624258,
+	///  or in textual repr: makeCollectionERC721MetadataCompatible(address,string)
+	function makeCollectionERC721MetadataCompatible(address collection, string memory baseUri) public {
 		require(false, stub_error);
-		name;
-		description;
-		tokenPrefix;
+		collection;
 		baseUri;
 		dummy = 0;
-		return 0x0000000000000000000000000000000000000000;
 	}
 
 	/// Check if a collection exists
modifiedpallets/unique/src/lib.rsdiffbeforeafterboth
--- a/pallets/unique/src/lib.rs
+++ b/pallets/unique/src/lib.rs
@@ -345,7 +345,7 @@
 
 			// =========
 			let sender = T::CrossAccountId::from_sub(sender);
-			let _id = T::CollectionDispatch::create(sender.clone(), sender, data)?;
+			let _id = T::CollectionDispatch::create(sender.clone(), sender, data, Default::default())?;
 
 			Ok(())
 		}
modifiedprimitives/data-structs/src/lib.rsdiffbeforeafterboth
--- a/primitives/data-structs/src/lib.rs
+++ b/primitives/data-structs/src/lib.rs
@@ -365,11 +365,14 @@
 	/// Tokens in foreign collections can be transferred, but not burnt
 	#[bondrewd(bits = "0..1")]
 	pub foreign: bool,
+	/// Supports ERC721Metadata
+	#[bondrewd(bits = "1..2")]
+	pub erc721metadata: bool,
 	/// External collections can't be managed using `unique` api
 	#[bondrewd(bits = "7..8")]
 	pub external: bool,
 
-	#[bondrewd(reserve, bits = "1..7")]
+	#[bondrewd(reserve, bits = "2..7")]
 	pub reserved: u8,
 }
 bondrewd_codec!(CollectionFlags);
@@ -434,6 +437,15 @@
 	pub meta_update_permission: MetaUpdatePermission,
 }
 
+#[derive(Encode, Decode, Clone, PartialEq, TypeInfo)]
+#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
+pub struct RpcCollectionFlags {
+	/// Is collection is foreign.
+	pub foreign: bool,
+	/// Collection supports ERC721Metadata.
+	pub erc721metadata: bool,
+}
+
 /// Collection parameters, used in RPC calls (see [`Collection`] for the storage version).
 #[derive(Encode, Decode, Clone, PartialEq, TypeInfo)]
 #[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
@@ -471,8 +483,8 @@
 	/// Is collection read only.
 	pub read_only: bool,
 
-	/// Is collection is foreign.
-	pub foreign: bool,
+	/// Extra collection flags
+	pub flags: RpcCollectionFlags,
 }
 
 /// Data used for create collection.
modifiedruntime/common/dispatch.rsdiffbeforeafterboth
--- a/runtime/common/dispatch.rs
+++ b/runtime/common/dispatch.rs
@@ -31,7 +31,7 @@
 };
 use up_data_structs::{
 	CollectionMode, CreateCollectionData, MAX_DECIMAL_POINTS, mapping::TokenAddressMapping,
-	CollectionId,
+	CollectionId, CollectionFlags,
 };
 
 #[cfg(not(feature = "refungible"))]
@@ -57,10 +57,11 @@
 		sender: T::CrossAccountId,
 		payer: T::CrossAccountId,
 		data: CreateCollectionData<T::AccountId>,
+		flags: CollectionFlags,
 	) -> Result<CollectionId, DispatchError> {
 		let id = match data.mode {
 			CollectionMode::NFT => {
-				<PalletNonfungible<T>>::init_collection(sender, payer, data, false)?
+				<PalletNonfungible<T>>::init_collection(sender, payer, data, flags)?
 			}
 			CollectionMode::Fungible(decimal_points) => {
 				// check params
@@ -68,11 +69,13 @@
 					decimal_points <= MAX_DECIMAL_POINTS,
 					pallet_unique::Error::<T>::CollectionDecimalPointLimitExceeded
 				);
-				<PalletFungible<T>>::init_collection(sender, payer, data)?
+				<PalletFungible<T>>::init_collection(sender, payer, data, flags)?
 			}
 
 			#[cfg(feature = "refungible")]
-			CollectionMode::ReFungible => <PalletRefungible<T>>::init_collection(sender, payer, data)?,
+			CollectionMode::ReFungible => {
+				<PalletRefungible<T>>::init_collection(sender, payer, data, flags)?
+			}
 
 			#[cfg(not(feature = "refungible"))]
 			CollectionMode::ReFungible => return unsupported!(T),
modifiedruntime/common/ethereum/sponsoring.rsdiffbeforeafterboth
--- a/runtime/common/ethereum/sponsoring.rs
+++ b/runtime/common/ethereum/sponsoring.rs
@@ -24,7 +24,7 @@
 use pallet_nonfungible::{
 	Config as NonfungibleConfig,
 	erc::{
-		UniqueNFTCall, ERC721UniqueExtensionsCall, ERC721MintableCall, ERC721Call,
+		UniqueNFTCall, ERC721UniqueExtensionsCall, ERC721UniqueMintableCall, ERC721Call,
 		TokenPropertiesCall,
 	},
 };
@@ -82,18 +82,17 @@
 						let token_id: TokenId = token_id.try_into().ok()?;
 						withdraw_transfer::<T>(&collection, &who, &token_id).map(|()| sponsor)
 					}
-					UniqueNFTCall::ERC721Mintable(
-						ERC721MintableCall::Mint { token_id, .. }
-						| ERC721MintableCall::MintWithTokenUri { token_id, .. },
-					) => {
-						let _token_id: TokenId = token_id.try_into().ok()?;
-						withdraw_create_item::<T>(
-							&collection,
-							&who,
-							&CreateItemData::NFT(CreateNftData::default()),
-						)
-						.map(|()| sponsor)
-					}
+					UniqueNFTCall::ERC721UniqueMintable(
+						ERC721UniqueMintableCall::Mint { .. }
+						| ERC721UniqueMintableCall::MintCheckId { .. }
+						| ERC721UniqueMintableCall::MintWithTokenUri { .. }
+						| ERC721UniqueMintableCall::MintWithTokenUriCheckId { .. },
+					) => withdraw_create_item::<T>(
+						&collection,
+						&who,
+						&CreateItemData::NFT(CreateNftData::default()),
+					)
+					.map(|()| sponsor),
 					UniqueNFTCall::ERC721(ERC721Call::TransferFrom { token_id, from, .. }) => {
 						let token_id: TokenId = token_id.try_into().ok()?;
 						let from = T::CrossAccountId::from_eth(from);
modifiedtests/src/eth/allowlist.test.tsdiffbeforeafterboth
--- a/tests/src/eth/allowlist.test.ts
+++ b/tests/src/eth/allowlist.test.ts
@@ -78,7 +78,7 @@
     const owner = await helper.eth.createAccountWithBalance(donor);
     const user = helper.eth.createAccount();
 
-    const {collectionAddress} = await helper.eth.createNonfungibleCollection(owner, 'A', 'B', 'C');
+    const {collectionAddress} = await helper.eth.createNFTCollection(owner, 'A', 'B', 'C');
     const collectionEvm = helper.ethNativeContract.collection(collectionAddress, 'nft', owner);
 
     expect(await collectionEvm.methods.allowed(user).call({from: owner})).to.be.false;
@@ -94,7 +94,7 @@
   //   const owner = await helper.eth.createAccountWithBalance(donor);
   //   const user = donor;
 
-  //   const {collectionAddress, collectionId} = await helper.eth.createNonfungibleCollection(owner, 'A', 'B', 'C');
+  //   const {collectionAddress, collectionId} = await helper.eth.createNFTCollection(owner, 'A', 'B', 'C');
   //   const collectionEvm = helper.ethNativeContract.collection(collectionAddress, 'nft', owner);
 
   //   expect(await helper.collection.allowed(collectionId, {Substrate: user.address})).to.be.false;
@@ -110,7 +110,7 @@
     const notOwner = await helper.eth.createAccountWithBalance(donor);
     const user = helper.eth.createAccount();
 
-    const {collectionAddress} = await helper.eth.createNonfungibleCollection(owner, 'A', 'B', 'C');
+    const {collectionAddress} = await helper.eth.createNFTCollection(owner, 'A', 'B', 'C');
     const collectionEvm = helper.ethNativeContract.collection(collectionAddress, 'nft', owner);
 
     expect(await collectionEvm.methods.allowed(user).call({from: owner})).to.be.false;
@@ -129,7 +129,7 @@
   //   const notOwner = await helper.eth.createAccountWithBalance(donor);
   //   const user = donor;
 
-  //   const {collectionAddress, collectionId} = await helper.eth.createNonfungibleCollection(owner, 'A', 'B', 'C');
+  //   const {collectionAddress, collectionId} = await helper.eth.createNFTCollection(owner, 'A', 'B', 'C');
   //   const collectionEvm = helper.ethNativeContract.collection(collectionAddress, 'nft', owner);
 
   //   expect(await helper.collection.allowed(collectionId, {Substrate: user.address})).to.be.false;
modifiedtests/src/eth/api/CollectionHelpers.soldiffbeforeafterboth
--- a/tests/src/eth/api/CollectionHelpers.sol
+++ b/tests/src/eth/api/CollectionHelpers.sol
@@ -18,29 +18,29 @@
 }
 
 /// @title Contract, which allows users to operate with collections
-/// @dev the ERC-165 identifier for this interface is 0x5ad4f440
+/// @dev the ERC-165 identifier for this interface is 0x58918631
 interface CollectionHelpers is Dummy, ERC165, CollectionHelpersEvents {
 	/// Create an NFT collection
 	/// @param name Name of the collection
 	/// @param description Informative description of the collection
 	/// @param tokenPrefix Token prefix to represent the collection tokens in UI and user applications
 	/// @return address Address of the newly created collection
-	/// @dev EVM selector for this function is: 0xe34a6844,
-	///  or in textual repr: createNonfungibleCollection(string,string,string)
-	function createNonfungibleCollection(
+	/// @dev EVM selector for this function is: 0x844af658,
+	///  or in textual repr: createNFTCollection(string,string,string)
+	function createNFTCollection(
 		string memory name,
 		string memory description,
 		string memory tokenPrefix
 	) external payable returns (address);
 
-	/// @dev EVM selector for this function is: 0xa634a5f9,
-	///  or in textual repr: createERC721MetadataCompatibleCollection(string,string,string,string)
-	function createERC721MetadataCompatibleCollection(
-		string memory name,
-		string memory description,
-		string memory tokenPrefix,
-		string memory baseUri
-	) external payable returns (address);
+	// /// Create an NFT collection
+	// /// @param name Name of the collection
+	// /// @param description Informative description of the collection
+	// /// @param tokenPrefix Token prefix to represent the collection tokens in UI and user applications
+	// /// @return address Address of the newly created collection
+	// /// @dev EVM selector for this function is: 0xe34a6844,
+	// ///  or in textual repr: createNonfungibleCollection(string,string,string)
+	// function createNonfungibleCollection(string memory name, string memory description, string memory tokenPrefix) external payable returns (address);
 
 	/// @dev EVM selector for this function is: 0xab173450,
 	///  or in textual repr: createRFTCollection(string,string,string)
@@ -50,14 +50,9 @@
 		string memory tokenPrefix
 	) external payable returns (address);
 
-	/// @dev EVM selector for this function is: 0xa5596388,
-	///  or in textual repr: createERC721MetadataCompatibleRFTCollection(string,string,string,string)
-	function createERC721MetadataCompatibleRFTCollection(
-		string memory name,
-		string memory description,
-		string memory tokenPrefix,
-		string memory baseUri
-	) external payable returns (address);
+	/// @dev EVM selector for this function is: 0x85624258,
+	///  or in textual repr: makeCollectionERC721MetadataCompatible(address,string)
+	function makeCollectionERC721MetadataCompatible(address collection, string memory baseUri) external;
 
 	/// Check if a collection exists
 	/// @param collectionAddress Address of the collection in question
modifiedtests/src/eth/api/UniqueFungible.soldiffbeforeafterboth
--- a/tests/src/eth/api/UniqueFungible.sol
+++ b/tests/src/eth/api/UniqueFungible.sol
@@ -13,7 +13,7 @@
 }
 
 /// @title A contract that allows you to work with collections.
-/// @dev the ERC-165 identifier for this interface is 0x3e1e8083
+/// @dev the ERC-165 identifier for this interface is 0x62e22290
 interface Collection is Dummy, ERC165 {
 	/// Set collection property.
 	///
@@ -194,9 +194,9 @@
 	///
 	/// @dev Owner can be changed only by current owner
 	/// @param newOwner new owner account
-	/// @dev EVM selector for this function is: 0x13af4035,
-	///  or in textual repr: setOwner(address)
-	function setOwner(address newOwner) external;
+	/// @dev EVM selector for this function is: 0x4f53e226,
+	///  or in textual repr: changeCollectionOwner(address)
+	function changeCollectionOwner(address newOwner) external;
 }
 
 /// @dev the ERC-165 identifier for this interface is 0x63034ac5
modifiedtests/src/eth/api/UniqueNFT.soldiffbeforeafterboth
--- a/tests/src/eth/api/UniqueNFT.sol
+++ b/tests/src/eth/api/UniqueNFT.sol
@@ -62,7 +62,7 @@
 }
 
 /// @title A contract that allows you to work with collections.
-/// @dev the ERC-165 identifier for this interface is 0x3e1e8083
+/// @dev the ERC-165 identifier for this interface is 0x62e22290
 interface Collection is Dummy, ERC165 {
 	/// Set collection property.
 	///
@@ -243,9 +243,9 @@
 	///
 	/// @dev Owner can be changed only by current owner
 	/// @param newOwner new owner account
-	/// @dev EVM selector for this function is: 0x13af4035,
-	///  or in textual repr: setOwner(address)
-	function setOwner(address newOwner) external;
+	/// @dev EVM selector for this function is: 0x4f53e226,
+	///  or in textual repr: changeCollectionOwner(address)
+	function changeCollectionOwner(address newOwner) external;
 }
 
 /// @dev anonymous struct
@@ -254,6 +254,36 @@
 	uint256 field_1;
 }
 
+/// @title ERC-721 Non-Fungible Token Standard, optional metadata extension
+/// @dev See https://eips.ethereum.org/EIPS/eip-721
+/// @dev the ERC-165 identifier for this interface is 0x5b5e139f
+interface ERC721Metadata is Dummy, ERC165 {
+	// /// @notice A descriptive name for a collection of NFTs in this contract
+	// /// @dev real implementation of this function lies in `ERC721UniqueExtensions`
+	// /// @dev EVM selector for this function is: 0x06fdde03,
+	// ///  or in textual repr: name()
+	// function name() external view returns (string memory);
+
+	// /// @notice An abbreviated name for NFTs in this contract
+	// /// @dev real implementation of this function lies in `ERC721UniqueExtensions`
+	// /// @dev EVM selector for this function is: 0x95d89b41,
+	// ///  or in textual repr: symbol()
+	// function symbol() external view returns (string memory);
+
+	/// @notice A distinct Uniform Resource Identifier (URI) for a given asset.
+	///
+	/// @dev If the token has a `url` property and it is not empty, it is returned.
+	///  Else If the collection does not have a property with key `schemaName` or its value is not equal to `ERC721Metadata`, it return an error `tokenURI not set`.
+	///  If the collection property `baseURI` is empty or absent, return "" (empty string)
+	///  otherwise, if token property `suffix` present and is non-empty, return concatenation of baseURI and suffix
+	///  otherwise, return concatenation of `baseURI` and stringified token id (decimal stringifying, without paddings).
+	///
+	/// @return token's const_metadata
+	/// @dev EVM selector for this function is: 0xc87b56dd,
+	///  or in textual repr: tokenURI(uint256)
+	function tokenURI(uint256 tokenId) external view returns (string memory);
+}
+
 /// @title ERC721 Token that can be irreversibly burned (destroyed).
 /// @dev the ERC-165 identifier for this interface is 0x42966c68
 interface ERC721Burnable is Dummy, ERC165 {
@@ -267,39 +297,50 @@
 }
 
 /// @dev inlined interface
-interface ERC721MintableEvents {
+interface ERC721UniqueMintableEvents {
 	event MintingFinished();
 }
 
 /// @title ERC721 minting logic.
-/// @dev the ERC-165 identifier for this interface is 0x68ccfe89
-interface ERC721Mintable is Dummy, ERC165, ERC721MintableEvents {
+/// @dev the ERC-165 identifier for this interface is 0x476ff149
+interface ERC721UniqueMintable is Dummy, ERC165, ERC721UniqueMintableEvents {
 	/// @dev EVM selector for this function is: 0x05d2035b,
 	///  or in textual repr: mintingFinished()
 	function mintingFinished() external view returns (bool);
 
 	/// @notice Function to mint token.
-	/// @dev `tokenId` should be obtained with `nextTokenId` method,
-	///  unlike standard, you can't specify it manually
 	/// @param to The new owner
-	/// @param tokenId ID of the minted NFT
-	/// @dev EVM selector for this function is: 0x40c10f19,
-	///  or in textual repr: mint(address,uint256)
-	function mint(address to, uint256 tokenId) external returns (bool);
+	/// @return uint256 The id of the newly minted token
+	/// @dev EVM selector for this function is: 0x6a627842,
+	///  or in textual repr: mint(address)
+	function mint(address to) external returns (uint256);
+
+	// /// @notice Function to mint token.
+	// /// @dev `tokenId` should be obtained with `nextTokenId` method,
+	// ///  unlike standard, you can't specify it manually
+	// /// @param to The new owner
+	// /// @param tokenId ID of the minted NFT
+	// /// @dev EVM selector for this function is: 0x40c10f19,
+	// ///  or in textual repr: mint(address,uint256)
+	// function mint(address to, uint256 tokenId) external returns (bool);
 
 	/// @notice Function to mint token with the given tokenUri.
-	/// @dev `tokenId` should be obtained with `nextTokenId` method,
-	///  unlike standard, you can't specify it manually
 	/// @param to The new owner
-	/// @param tokenId ID of the minted NFT
 	/// @param tokenUri Token URI that would be stored in the NFT properties
-	/// @dev EVM selector for this function is: 0x50bb4e7f,
-	///  or in textual repr: mintWithTokenURI(address,uint256,string)
-	function mintWithTokenURI(
-		address to,
-		uint256 tokenId,
-		string memory tokenUri
-	) external returns (bool);
+	/// @return uint256 The id of the newly minted token
+	/// @dev EVM selector for this function is: 0x45c17782,
+	///  or in textual repr: mintWithTokenURI(address,string)
+	function mintWithTokenURI(address to, string memory tokenUri) external returns (uint256);
+
+	// /// @notice Function to mint token with the given tokenUri.
+	// /// @dev `tokenId` should be obtained with `nextTokenId` method,
+	// ///  unlike standard, you can't specify it manually
+	// /// @param to The new owner
+	// /// @param tokenId ID of the minted NFT
+	// /// @param tokenUri Token URI that would be stored in the NFT properties
+	// /// @dev EVM selector for this function is: 0x50bb4e7f,
+	// ///  or in textual repr: mintWithTokenURI(address,uint256,string)
+	// function mintWithTokenURI(address to, uint256 tokenId, string memory tokenUri) external returns (bool);
 
 	/// @dev Not implemented
 	/// @dev EVM selector for this function is: 0x7d64bcb4,
@@ -308,8 +349,18 @@
 }
 
 /// @title Unique extensions for ERC721.
-/// @dev the ERC-165 identifier for this interface is 0xd74d154f
+/// @dev the ERC-165 identifier for this interface is 0x4468500d
 interface ERC721UniqueExtensions is Dummy, ERC165 {
+	/// @notice A descriptive name for a collection of NFTs in this contract
+	/// @dev EVM selector for this function is: 0x06fdde03,
+	///  or in textual repr: name()
+	function name() external view returns (string memory);
+
+	/// @notice An abbreviated name for NFTs in this contract
+	/// @dev EVM selector for this function is: 0x95d89b41,
+	///  or in textual repr: symbol()
+	function symbol() external view returns (string memory);
+
 	/// @notice Transfer ownership of an NFT
 	/// @dev Throws unless `msg.sender` is the current owner. Throws if `to`
 	///  is the zero address. Throws if `tokenId` is not a valid NFT.
@@ -350,11 +401,11 @@
 	/// @param tokens array of pairs of token ID and token URI for minted tokens
 	/// @dev EVM selector for this function is: 0x36543006,
 	///  or in textual repr: mintBulkWithTokenURI(address,(uint256,string)[])
-	function mintBulkWithTokenURI(address to, Tuple8[] memory tokens) external returns (bool);
+	function mintBulkWithTokenURI(address to, Tuple6[] memory tokens) external returns (bool);
 }
 
 /// @dev anonymous struct
-struct Tuple8 {
+struct Tuple6 {
 	uint256 field_0;
 	string field_1;
 }
@@ -384,34 +435,6 @@
 	function totalSupply() external view returns (uint256);
 }
 
-/// @title ERC-721 Non-Fungible Token Standard, optional metadata extension
-/// @dev See https://eips.ethereum.org/EIPS/eip-721
-/// @dev the ERC-165 identifier for this interface is 0x5b5e139f
-interface ERC721Metadata is Dummy, ERC165 {
-	/// @notice A descriptive name for a collection of NFTs in this contract
-	/// @dev EVM selector for this function is: 0x06fdde03,
-	///  or in textual repr: name()
-	function name() external view returns (string memory);
-
-	/// @notice An abbreviated name for NFTs in this contract
-	/// @dev EVM selector for this function is: 0x95d89b41,
-	///  or in textual repr: symbol()
-	function symbol() external view returns (string memory);
-
-	/// @notice A distinct Uniform Resource Identifier (URI) for a given asset.
-	///
-	/// @dev If the token has a `url` property and it is not empty, it is returned.
-	///  Else If the collection does not have a property with key `schemaName` or its value is not equal to `ERC721Metadata`, it return an error `tokenURI not set`.
-	///  If the collection property `baseURI` is empty or absent, return "" (empty string)
-	///  otherwise, if token property `suffix` present and is non-empty, return concatenation of baseURI and suffix
-	///  otherwise, return concatenation of `baseURI` and stringified token id (decimal stringifying, without paddings).
-	///
-	/// @return token's const_metadata
-	/// @dev EVM selector for this function is: 0xc87b56dd,
-	///  or in textual repr: tokenURI(uint256)
-	function tokenURI(uint256 tokenId) external view returns (string memory);
-}
-
 /// @dev inlined interface
 interface ERC721Events {
 	event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
@@ -507,11 +530,11 @@
 	Dummy,
 	ERC165,
 	ERC721,
-	ERC721Metadata,
 	ERC721Enumerable,
 	ERC721UniqueExtensions,
-	ERC721Mintable,
+	ERC721UniqueMintable,
 	ERC721Burnable,
+	ERC721Metadata,
 	Collection,
 	TokenProperties
 {}
deletedtests/src/eth/api/UniqueRFT.soldiffbeforeafterboth
--- a/tests/src/eth/api/UniqueRFT.sol
+++ /dev/null
@@ -1,163 +0,0 @@
-// SPDX-License-Identifier: OTHER
-// This code is automatically generated
-
-pragma solidity >=0.8.0 <0.9.0;
-
-// Common stubs holder
-interface Dummy {
-
-}
-
-interface ERC165 is Dummy {
-	function supportsInterface(bytes4 interfaceID) external view returns (bool);
-}
-
-// Selector: 7d9262e6
-interface Collection is Dummy, ERC165 {
-	// Set collection property.
-	//
-	// @param key Property key.
-	// @param value Propery value.
-	//
-	// Selector: setCollectionProperty(string,bytes) 2f073f66
-	function setCollectionProperty(string memory key, bytes memory value)
-		external;
-
-	// Delete collection property.
-	//
-	// @param key Property key.
-	//
-	// Selector: deleteCollectionProperty(string) 7b7debce
-	function deleteCollectionProperty(string memory key) external;
-
-	// Get collection property.
-	//
-	// @dev Throws error if key not found.
-	//
-	// @param key Property key.
-	// @return bytes The property corresponding to the key.
-	//
-	// Selector: collectionProperty(string) cf24fd6d
-	function collectionProperty(string memory key)
-		external
-		view
-		returns (bytes memory);
-
-	// Set the sponsor of the collection.
-	//
-	// @dev In order for sponsorship to work, it must be confirmed on behalf of the sponsor.
-	//
-	// @param sponsor Address of the sponsor from whose account funds will be debited for operations with the contract.
-	//
-	// Selector: setCollectionSponsor(address) 7623402e
-	function setCollectionSponsor(address sponsor) external;
-
-	// Collection sponsorship confirmation.
-	//
-	// @dev After setting the sponsor for the collection, it must be confirmed with this function.
-	//
-	// Selector: confirmCollectionSponsorship() 3c50e97a
-	function confirmCollectionSponsorship() external;
-
-	// Set limits for the collection.
-	// @dev Throws error if limit not found.
-	// @param limit Name of the limit. Valid names:
-	// 	"accountTokenOwnershipLimit",
-	// 	"sponsoredDataSize",
-	// 	"sponsoredDataRateLimit",
-	// 	"tokenLimit",
-	// 	"sponsorTransferTimeout",
-	// 	"sponsorApproveTimeout"
-	// @param value Value of the limit.
-	//
-	// Selector: setCollectionLimit(string,uint32) 6a3841db
-	function setCollectionLimit(string memory limit, uint32 value) external;
-
-	// Set limits for the collection.
-	// @dev Throws error if limit not found.
-	// @param limit Name of the limit. Valid names:
-	// 	"ownerCanTransfer",
-	// 	"ownerCanDestroy",
-	// 	"transfersEnabled"
-	// @param value Value of the limit.
-	//
-	// Selector: setCollectionLimit(string,bool) 993b7fba
-	function setCollectionLimit(string memory limit, bool value) external;
-
-	// Get contract address.
-	//
-	// Selector: contractAddress() f6b4dfb4
-	function contractAddress() external view returns (address);
-
-	// Add collection admin by substrate address.
-	// @param new_admin Substrate administrator address.
-	//
-	// Selector: addCollectionAdminSubstrate(uint256) 5730062b
-	function addCollectionAdminSubstrate(uint256 newAdmin) external;
-
-	// Remove collection admin by substrate address.
-	// @param admin Substrate administrator address.
-	//
-	// Selector: removeCollectionAdminSubstrate(uint256) 4048fcf9
-	function removeCollectionAdminSubstrate(uint256 admin) external;
-
-	// Add collection admin.
-	// @param new_admin Address of the added administrator.
-	//
-	// Selector: addCollectionAdmin(address) 92e462c7
-	function addCollectionAdmin(address newAdmin) external;
-
-	// Remove collection admin.
-	//
-	// @param new_admin Address of the removed administrator.
-	//
-	// Selector: removeCollectionAdmin(address) fafd7b42
-	function removeCollectionAdmin(address admin) external;
-
-	// Toggle accessibility of collection nesting.
-	//
-	// @param enable If "true" degenerates to nesting: 'Owner' else to nesting: 'Disabled'
-	//
-	// Selector: setCollectionNesting(bool) 112d4586
-	function setCollectionNesting(bool enable) external;
-
-	// Toggle accessibility of collection nesting.
-	//
-	// @param enable If "true" degenerates to nesting: {OwnerRestricted: [1, 2, 3]} else to nesting: 'Disabled'
-	// @param collections Addresses of collections that will be available for nesting.
-	//
-	// Selector: setCollectionNesting(bool,address[]) 64872396
-	function setCollectionNesting(bool enable, address[] memory collections)
-		external;
-
-	// Set the collection access method.
-	// @param mode Access mode
-	// 	0 for Normal
-	// 	1 for AllowList
-	//
-	// Selector: setCollectionAccess(uint8) 41835d4c
-	function setCollectionAccess(uint8 mode) external;
-
-	// Add the user to the allowed list.
-	//
-	// @param user Address of a trusted user.
-	//
-	// Selector: addToCollectionAllowList(address) 67844fe6
-	function addToCollectionAllowList(address user) external;
-
-	// Remove the user from the allowed list.
-	//
-	// @param user Address of a removed user.
-	//
-	// Selector: removeFromCollectionAllowList(address) 85c51acb
-	function removeFromCollectionAllowList(address user) external;
-
-	// Switch permission for minting.
-	//
-	// @param mode Enable if "true".
-	//
-	// Selector: setCollectionMintMode(bool) 00018e84
-	function setCollectionMintMode(bool mode) external;
-}
-
-interface UniqueRFT is Dummy, ERC165, Collection {}
modifiedtests/src/eth/api/UniqueRefungible.soldiffbeforeafterboth
--- a/tests/src/eth/api/UniqueRefungible.sol
+++ b/tests/src/eth/api/UniqueRefungible.sol
@@ -62,7 +62,7 @@
 }
 
 /// @title A contract that allows you to work with collections.
-/// @dev the ERC-165 identifier for this interface is 0x3e1e8083
+/// @dev the ERC-165 identifier for this interface is 0x62e22290
 interface Collection is Dummy, ERC165 {
 	/// Set collection property.
 	///
@@ -243,9 +243,9 @@
 	///
 	/// @dev Owner can be changed only by current owner
 	/// @param newOwner new owner account
-	/// @dev EVM selector for this function is: 0x13af4035,
-	///  or in textual repr: setOwner(address)
-	function setOwner(address newOwner) external;
+	/// @dev EVM selector for this function is: 0x4f53e226,
+	///  or in textual repr: changeCollectionOwner(address)
+	function changeCollectionOwner(address newOwner) external;
 }
 
 /// @dev anonymous struct
@@ -254,6 +254,34 @@
 	uint256 field_1;
 }
 
+/// @dev the ERC-165 identifier for this interface is 0x5b5e139f
+interface ERC721Metadata is Dummy, ERC165 {
+	// /// @notice A descriptive name for a collection of NFTs in this contract
+	// /// @dev real implementation of this function lies in `ERC721UniqueExtensions`
+	// /// @dev EVM selector for this function is: 0x06fdde03,
+	// ///  or in textual repr: name()
+	// function name() external view returns (string memory);
+
+	// /// @notice An abbreviated name for NFTs in this contract
+	// /// @dev real implementation of this function lies in `ERC721UniqueExtensions`
+	// /// @dev EVM selector for this function is: 0x95d89b41,
+	// ///  or in textual repr: symbol()
+	// function symbol() external view returns (string memory);
+
+	/// @notice A distinct Uniform Resource Identifier (URI) for a given asset.
+	///
+	/// @dev If the token has a `url` property and it is not empty, it is returned.
+	///  Else If the collection does not have a property with key `schemaName` or its value is not equal to `ERC721Metadata`, it return an error `tokenURI not set`.
+	///  If the collection property `baseURI` is empty or absent, return "" (empty string)
+	///  otherwise, if token property `suffix` present and is non-empty, return concatenation of baseURI and suffix
+	///  otherwise, return concatenation of `baseURI` and stringified token id (decimal stringifying, without paddings).
+	///
+	/// @return token's const_metadata
+	/// @dev EVM selector for this function is: 0xc87b56dd,
+	///  or in textual repr: tokenURI(uint256)
+	function tokenURI(uint256 tokenId) external view returns (string memory);
+}
+
 /// @title ERC721 Token that can be irreversibly burned (destroyed).
 /// @dev the ERC-165 identifier for this interface is 0x42966c68
 interface ERC721Burnable is Dummy, ERC165 {
@@ -267,40 +295,51 @@
 }
 
 /// @dev inlined interface
-interface ERC721MintableEvents {
+interface ERC721UniqueMintableEvents {
 	event MintingFinished();
 }
 
 /// @title ERC721 minting logic.
-/// @dev the ERC-165 identifier for this interface is 0x68ccfe89
-interface ERC721Mintable is Dummy, ERC165, ERC721MintableEvents {
+/// @dev the ERC-165 identifier for this interface is 0x476ff149
+interface ERC721UniqueMintable is Dummy, ERC165, ERC721UniqueMintableEvents {
 	/// @dev EVM selector for this function is: 0x05d2035b,
 	///  or in textual repr: mintingFinished()
 	function mintingFinished() external view returns (bool);
 
 	/// @notice Function to mint token.
-	/// @dev `tokenId` should be obtained with `nextTokenId` method,
-	///  unlike standard, you can't specify it manually
 	/// @param to The new owner
-	/// @param tokenId ID of the minted RFT
-	/// @dev EVM selector for this function is: 0x40c10f19,
-	///  or in textual repr: mint(address,uint256)
-	function mint(address to, uint256 tokenId) external returns (bool);
+	/// @return uint256 The id of the newly minted token
+	/// @dev EVM selector for this function is: 0x6a627842,
+	///  or in textual repr: mint(address)
+	function mint(address to) external returns (uint256);
+
+	// /// @notice Function to mint token.
+	// /// @dev `tokenId` should be obtained with `nextTokenId` method,
+	// ///  unlike standard, you can't specify it manually
+	// /// @param to The new owner
+	// /// @param tokenId ID of the minted RFT
+	// /// @dev EVM selector for this function is: 0x40c10f19,
+	// ///  or in textual repr: mint(address,uint256)
+	// function mint(address to, uint256 tokenId) external returns (bool);
 
 	/// @notice Function to mint token with the given tokenUri.
-	/// @dev `tokenId` should be obtained with `nextTokenId` method,
-	///  unlike standard, you can't specify it manually
 	/// @param to The new owner
-	/// @param tokenId ID of the minted RFT
-	/// @param tokenUri Token URI that would be stored in the RFT properties
-	/// @dev EVM selector for this function is: 0x50bb4e7f,
-	///  or in textual repr: mintWithTokenURI(address,uint256,string)
-	function mintWithTokenURI(
-		address to,
-		uint256 tokenId,
-		string memory tokenUri
-	) external returns (bool);
+	/// @param tokenUri Token URI that would be stored in the NFT properties
+	/// @return uint256 The id of the newly minted token
+	/// @dev EVM selector for this function is: 0x45c17782,
+	///  or in textual repr: mintWithTokenURI(address,string)
+	function mintWithTokenURI(address to, string memory tokenUri) external returns (uint256);
 
+	// /// @notice Function to mint token with the given tokenUri.
+	// /// @dev `tokenId` should be obtained with `nextTokenId` method,
+	// ///  unlike standard, you can't specify it manually
+	// /// @param to The new owner
+	// /// @param tokenId ID of the minted RFT
+	// /// @param tokenUri Token URI that would be stored in the RFT properties
+	// /// @dev EVM selector for this function is: 0x50bb4e7f,
+	// ///  or in textual repr: mintWithTokenURI(address,uint256,string)
+	// function mintWithTokenURI(address to, uint256 tokenId, string memory tokenUri) external returns (bool);
+
 	/// @dev Not implemented
 	/// @dev EVM selector for this function is: 0x7d64bcb4,
 	///  or in textual repr: finishMinting()
@@ -308,8 +347,18 @@
 }
 
 /// @title Unique extensions for ERC721.
-/// @dev the ERC-165 identifier for this interface is 0x7c3bef89
+/// @dev the ERC-165 identifier for this interface is 0xef1eaacb
 interface ERC721UniqueExtensions is Dummy, ERC165 {
+	/// @notice A descriptive name for a collection of NFTs in this contract
+	/// @dev EVM selector for this function is: 0x06fdde03,
+	///  or in textual repr: name()
+	function name() external view returns (string memory);
+
+	/// @notice An abbreviated name for NFTs in this contract
+	/// @dev EVM selector for this function is: 0x95d89b41,
+	///  or in textual repr: symbol()
+	function symbol() external view returns (string memory);
+
 	/// @notice Transfer ownership of an RFT
 	/// @dev Throws unless `msg.sender` is the current owner. Throws if `to`
 	///  is the zero address. Throws if `tokenId` is not a valid RFT.
@@ -352,7 +401,7 @@
 	/// @param tokens array of pairs of token ID and token URI for minted tokens
 	/// @dev EVM selector for this function is: 0x36543006,
 	///  or in textual repr: mintBulkWithTokenURI(address,(uint256,string)[])
-	function mintBulkWithTokenURI(address to, Tuple8[] memory tokens) external returns (bool);
+	function mintBulkWithTokenURI(address to, Tuple6[] memory tokens) external returns (bool);
 
 	/// Returns EVM address for refungible token
 	///
@@ -363,7 +412,7 @@
 }
 
 /// @dev anonymous struct
-struct Tuple8 {
+struct Tuple6 {
 	uint256 field_0;
 	string field_1;
 }
@@ -393,32 +442,6 @@
 	function totalSupply() external view returns (uint256);
 }
 
-/// @dev the ERC-165 identifier for this interface is 0x5b5e139f
-interface ERC721Metadata is Dummy, ERC165 {
-	/// @notice A descriptive name for a collection of RFTs in this contract
-	/// @dev EVM selector for this function is: 0x06fdde03,
-	///  or in textual repr: name()
-	function name() external view returns (string memory);
-
-	/// @notice An abbreviated name for RFTs in this contract
-	/// @dev EVM selector for this function is: 0x95d89b41,
-	///  or in textual repr: symbol()
-	function symbol() external view returns (string memory);
-
-	/// @notice A distinct Uniform Resource Identifier (URI) for a given asset.
-	///
-	/// @dev If the token has a `url` property and it is not empty, it is returned.
-	///  Else If the collection does not have a property with key `schemaName` or its value is not equal to `ERC721Metadata`, it return an error `tokenURI not set`.
-	///  If the collection property `baseURI` is empty or absent, return "" (empty string)
-	///  otherwise, if token property `suffix` present and is non-empty, return concatenation of baseURI and suffix
-	///  otherwise, return concatenation of `baseURI` and stringified token id (decimal stringifying, without paddings).
-	///
-	/// @return token's const_metadata
-	/// @dev EVM selector for this function is: 0xc87b56dd,
-	///  or in textual repr: tokenURI(uint256)
-	function tokenURI(uint256 tokenId) external view returns (string memory);
-}
-
 /// @dev inlined interface
 interface ERC721Events {
 	event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
@@ -512,11 +535,11 @@
 	Dummy,
 	ERC165,
 	ERC721,
-	ERC721Metadata,
 	ERC721Enumerable,
 	ERC721UniqueExtensions,
-	ERC721Mintable,
+	ERC721UniqueMintable,
 	ERC721Burnable,
+	ERC721Metadata,
 	Collection,
 	TokenProperties
 {}
modifiedtests/src/eth/base.test.tsdiffbeforeafterboth
--- a/tests/src/eth/base.test.ts
+++ b/tests/src/eth/base.test.ts
@@ -23,7 +23,7 @@
 describe('Contract calls', () => {
   let donor: IKeyringPair;
 
-  before(async function() {
+  before(async function () {
     await usingEthPlaygrounds(async (_helper, privateKey) => {
       donor = await privateKey({filename: __filename});
     });
@@ -40,7 +40,12 @@
   itEth('Balance transfer fee is less than 0.2 UNQ', async ({helper}) => {
     const userA = await helper.eth.createAccountWithBalance(donor);
     const userB = helper.eth.createAccount();
-    const cost = await helper.eth.calculateFee({Ethereum: userA}, () => helper.getWeb3().eth.sendTransaction({from: userA, to: userB, value: '1000000', gas: helper.eth.DEFAULT_GAS}));
+    const cost = await helper.eth.calculateFee({Ethereum: userA}, () => helper.getWeb3().eth.sendTransaction({
+      from: userA,
+      to: userB,
+      value: '1000000',
+      gas: helper.eth.DEFAULT_GAS
+    }));
     const balanceB = await helper.balance.getEthereum(userB);
     expect(cost - balanceB < BigInt(0.2 * Number(helper.balance.getOneTokenNominal()))).to.be.true;
   });
@@ -69,51 +74,59 @@
 describe('ERC165 tests', async () => {
   // https://eips.ethereum.org/EIPS/eip-165
 
-  let collection: number;
+  let erc721MetadataCompatibleNftCollectionId: number;
+  let simpleNftCollectionId: number;
   let minter: string;
 
-  function contract(helper: EthUniqueHelper): Contract {
-    return helper.ethNativeContract.collection(helper.ethAddress.fromCollectionId(collection), 'nft', minter);
+  const BASE_URI = 'base/';
+
+  async function checkInterface(helper: EthUniqueHelper, interfaceId: string, simpleResult: boolean, compatibleResult: boolean) {
+    const simple = helper.ethNativeContract.collection(helper.ethAddress.fromCollectionId(simpleNftCollectionId), 'nft', minter);
+    const compatible = helper.ethNativeContract.collection(helper.ethAddress.fromCollectionId(erc721MetadataCompatibleNftCollectionId), 'nft', minter);
+
+    expect(await simple.methods.supportsInterface(interfaceId).call()).to.equal(simpleResult, `empty (not ERC721Metadata compatible) NFT collection returns not ${simpleResult}`);
+    expect(await compatible.methods.supportsInterface(interfaceId).call()).to.equal(compatibleResult, `ERC721Metadata compatible NFT collection returns not ${compatibleResult}`);
   }
 
   before(async () => {
     await usingEthPlaygrounds(async (helper, privateKey) => {
       const donor = await privateKey({filename: __filename});
       const [alice] = await helper.arrange.createAccounts([10n], donor);
-      ({collectionId: collection} = await helper.nft.mintCollection(alice, {name: 'test', description: 'test', tokenPrefix: 'test'}));
+      ({collectionId: simpleNftCollectionId} = await helper.nft.mintCollection(alice, {name: 'test', description: 'test', tokenPrefix: 'test'}));
       minter = helper.eth.createAccount();
+      ({collectionId: erc721MetadataCompatibleNftCollectionId} = await helper.eth.createERC721MetadataCompatibleNFTCollection(minter, 'n', 'd', 'p', BASE_URI));
     });
   });
 
-  itEth('interfaceID == 0xffffffff always false', async ({helper}) => {
-    expect(await contract(helper).methods.supportsInterface('0xffffffff').call()).to.be.false;
+  itEth('nonexistent interfaceID - 0xffffffff - always false', async ({helper}) => {
+    await checkInterface(helper, '0xffffffff', false, false);
   });
 
-  itEth('ERC721 support', async ({helper}) => {
-    expect(await contract(helper).methods.supportsInterface('0x780e9d63').call()).to.be.true;
+  itEth('ERC721 - 0x780e9d63 - support', async ({helper}) => {
+    await checkInterface(helper, '0x780e9d63', true, true);
   });
 
-  itEth('ERC721Metadata support', async ({helper}) => {
-    expect(await contract(helper).methods.supportsInterface('0x5b5e139f').call()).to.be.true;
+  itEth('ERC721Metadata - 0x5b5e139f - support', async ({helper}) => {
+    await checkInterface(helper, '0x5b5e139f', false, true);
   });
 
-  itEth('ERC721Mintable support', async ({helper}) => {
-    expect(await contract(helper).methods.supportsInterface('0x68ccfe89').call()).to.be.true;
+  itEth('ERC721UniqueMintable - 0x476ff149 - support', async ({helper}) => {
+    await checkInterface(helper, '0x476ff149', true, true);
   });
 
-  itEth('ERC721Enumerable support', async ({helper}) => {
-    expect(await contract(helper).methods.supportsInterface('0x780e9d63').call()).to.be.true;
+  itEth('ERC721Enumerable - 0x780e9d63 - support', async ({helper}) => {
+    await checkInterface(helper, '0x780e9d63', true, true);
   });
 
-  itEth('ERC721UniqueExtensions support', async ({helper}) => {
-    expect(await contract(helper).methods.supportsInterface('0xd74d154f').call()).to.be.true;
+  itEth('ERC721UniqueExtensions - 0x4468500d - support', async ({helper}) => {
+    await checkInterface(helper, '0x4468500d', true, true);
   });
 
-  itEth('ERC721Burnable support', async ({helper}) => {
-    expect(await contract(helper).methods.supportsInterface('0x42966c68').call()).to.be.true;
+  itEth('ERC721Burnable - 0x42966c68 - support', async ({helper}) => {
+    await checkInterface(helper, '0x42966c68', true, true);
   });
 
-  itEth('ERC165 support', async ({helper}) => {
-    expect(await contract(helper).methods.supportsInterface('0x01ffc9a7').call()).to.be.true;
+  itEth('ERC165 - 0x01ffc9a7 - support', async ({helper}) => {
+    await checkInterface(helper, '0x01ffc9a7', true, true);
   });
 });
modifiedtests/src/eth/collectionAdmin.test.tsdiffbeforeafterboth
--- a/tests/src/eth/collectionAdmin.test.ts
+++ b/tests/src/eth/collectionAdmin.test.ts
@@ -38,7 +38,7 @@
 
   itEth('Add admin by owner', async ({helper}) => {
     const owner = await helper.eth.createAccountWithBalance(donor);
-    const {collectionAddress, collectionId} = await helper.eth.createNonfungibleCollection(owner, 'A', 'B', 'C');
+    const {collectionAddress, collectionId} = await helper.eth.createNFTCollection(owner, 'A', 'B', 'C');
     const collectionEvm = helper.ethNativeContract.collection(collectionAddress, 'nft', owner);
 
     const newAdmin = helper.eth.createAccount();
@@ -51,7 +51,7 @@
 
   itEth.skip('Add substrate admin by owner', async ({helper}) => {
     const owner = await helper.eth.createAccountWithBalance(donor);
-    const {collectionAddress, collectionId} = await helper.eth.createNonfungibleCollection(owner, 'A', 'B', 'C');
+    const {collectionAddress, collectionId} = await helper.eth.createNFTCollection(owner, 'A', 'B', 'C');
     const collectionEvm = helper.ethNativeContract.collection(collectionAddress, 'nft', owner);
 
     const [newAdmin] = await helper.arrange.createAccounts([10n], donor);
@@ -64,7 +64,7 @@
 
   itEth('Verify owner or admin', async ({helper}) => {
     const owner = await helper.eth.createAccountWithBalance(donor);
-    const {collectionAddress} = await helper.eth.createNonfungibleCollection(owner, 'A', 'B', 'C');
+    const {collectionAddress} = await helper.eth.createNFTCollection(owner, 'A', 'B', 'C');
 
     const newAdmin = helper.eth.createAccount();
     const collectionEvm = helper.ethNativeContract.collection(collectionAddress, 'nft', owner);
@@ -75,7 +75,7 @@
 
   itEth('(!negative tests!) Add admin by ADMIN is not allowed', async ({helper}) => {
     const owner = await helper.eth.createAccountWithBalance(donor);
-    const {collectionAddress, collectionId} = await helper.eth.createNonfungibleCollection(owner, 'A', 'B', 'C');
+    const {collectionAddress, collectionId} = await helper.eth.createNFTCollection(owner, 'A', 'B', 'C');
 
     const admin = await helper.eth.createAccountWithBalance(donor);
     const collectionEvm = helper.ethNativeContract.collection(collectionAddress, 'nft', owner);
@@ -93,7 +93,7 @@
 
   itEth('(!negative tests!) Add admin by USER is not allowed', async ({helper}) => {
     const owner = await helper.eth.createAccountWithBalance(donor);
-    const {collectionAddress, collectionId} = await helper.eth.createNonfungibleCollection(owner, 'A', 'B', 'C');
+    const {collectionAddress, collectionId} = await helper.eth.createNFTCollection(owner, 'A', 'B', 'C');
 
     const notAdmin = await helper.eth.createAccountWithBalance(donor);
     const collectionEvm = helper.ethNativeContract.collection(collectionAddress, 'nft', owner);
@@ -108,7 +108,7 @@
 
   itEth.skip('(!negative tests!) Add substrate admin by ADMIN is not allowed', async ({helper}) => {
     const owner = await helper.eth.createAccountWithBalance(donor);
-    const {collectionAddress, collectionId} = await helper.eth.createNonfungibleCollection(owner, 'A', 'B', 'C');
+    const {collectionAddress, collectionId} = await helper.eth.createNFTCollection(owner, 'A', 'B', 'C');
 
     const admin = await helper.eth.createAccountWithBalance(donor);
     const collectionEvm = helper.ethNativeContract.collection(collectionAddress, 'nft', owner);
@@ -126,7 +126,7 @@
 
   itEth.skip('(!negative tests!) Add substrate admin by USER is not allowed', async ({helper}) => {
     const owner = await helper.eth.createAccountWithBalance(donor);
-    const {collectionAddress, collectionId} = await helper.eth.createNonfungibleCollection(owner, 'A', 'B', 'C');
+    const {collectionAddress, collectionId} = await helper.eth.createNFTCollection(owner, 'A', 'B', 'C');
 
     const notAdmin0 = await helper.eth.createAccountWithBalance(donor);
     const collectionEvm = helper.ethNativeContract.collection(collectionAddress, 'nft', owner);
@@ -150,7 +150,7 @@
 
   itEth('Remove admin by owner', async ({helper}) => {
     const owner = await helper.eth.createAccountWithBalance(donor);
-    const {collectionAddress, collectionId} = await helper.eth.createNonfungibleCollection(owner, 'A', 'B', 'C');
+    const {collectionAddress, collectionId} = await helper.eth.createNFTCollection(owner, 'A', 'B', 'C');
 
     const newAdmin = helper.eth.createAccount();
     const collectionEvm = helper.ethNativeContract.collection(collectionAddress, 'nft', owner);
@@ -170,7 +170,7 @@
 
   itEth.skip('Remove substrate admin by owner', async ({helper}) => {
     const owner = await helper.eth.createAccountWithBalance(donor);
-    const {collectionAddress, collectionId} = await helper.eth.createNonfungibleCollection(owner, 'A', 'B', 'C');
+    const {collectionAddress, collectionId} = await helper.eth.createNFTCollection(owner, 'A', 'B', 'C');
 
     const [newAdmin] = await helper.arrange.createAccounts([10n], donor);
     const collectionEvm = helper.ethNativeContract.collection(collectionAddress, 'nft', owner);
@@ -188,7 +188,7 @@
 
   itEth('(!negative tests!) Remove admin by ADMIN is not allowed', async ({helper}) => {
     const owner = await helper.eth.createAccountWithBalance(donor);
-    const {collectionAddress, collectionId} = await helper.eth.createNonfungibleCollection(owner, 'A', 'B', 'C');
+    const {collectionAddress, collectionId} = await helper.eth.createNFTCollection(owner, 'A', 'B', 'C');
 
     const collectionEvm = helper.ethNativeContract.collection(collectionAddress, 'nft', owner);
 
@@ -210,7 +210,7 @@
 
   itEth('(!negative tests!) Remove admin by USER is not allowed', async ({helper}) => {
     const owner = await helper.eth.createAccountWithBalance(donor);
-    const {collectionAddress, collectionId} = await helper.eth.createNonfungibleCollection(owner, 'A', 'B', 'C');
+    const {collectionAddress, collectionId} = await helper.eth.createNFTCollection(owner, 'A', 'B', 'C');
 
     const collectionEvm = helper.ethNativeContract.collection(collectionAddress, 'nft', owner);
 
@@ -230,7 +230,7 @@
 
   itEth.skip('(!negative tests!) Remove substrate admin by ADMIN is not allowed', async ({helper}) => {
     const owner = await helper.eth.createAccountWithBalance(donor);
-    const {collectionAddress, collectionId} = await helper.eth.createNonfungibleCollection(owner, 'A', 'B', 'C');
+    const {collectionAddress, collectionId} = await helper.eth.createNFTCollection(owner, 'A', 'B', 'C');
 
     const [adminSub] = await helper.arrange.createAccounts([10n], donor);
     const collectionEvm = helper.ethNativeContract.collection(collectionAddress, 'nft', owner);
@@ -250,7 +250,7 @@
 
   itEth.skip('(!negative tests!) Remove substrate admin by USER is not allowed', async ({helper}) => {
     const owner = await helper.eth.createAccountWithBalance(donor);
-    const {collectionAddress, collectionId} = await helper.eth.createNonfungibleCollection(owner, 'A', 'B', 'C');
+    const {collectionAddress, collectionId} = await helper.eth.createNFTCollection(owner, 'A', 'B', 'C');
 
     const [adminSub] = await helper.arrange.createAccounts([10n], donor);
     const collectionEvm = helper.ethNativeContract.collection(collectionAddress, 'nft', owner);
@@ -279,10 +279,10 @@
   itEth('Change owner', async ({helper}) => {
     const owner = await helper.eth.createAccountWithBalance(donor);
     const newOwner = await helper.eth.createAccountWithBalance(donor);
-    const {collectionAddress} = await helper.eth.createNonfungibleCollection(owner, 'A', 'B', 'C');
+    const {collectionAddress} = await helper.eth.createNFTCollection(owner, 'A', 'B', 'C');
     const collectionEvm = helper.ethNativeContract.collection(collectionAddress, 'nft', owner);
 
-    await collectionEvm.methods.setOwner(newOwner).send();
+    await collectionEvm.methods.changeCollectionOwner(newOwner).send();
 
     expect(await collectionEvm.methods.isOwnerOrAdmin(owner).call()).to.be.false;
     expect(await collectionEvm.methods.isOwnerOrAdmin(newOwner).call()).to.be.true;
@@ -291,9 +291,9 @@
   itEth('change owner call fee', async ({helper}) => {
     const owner = await helper.eth.createAccountWithBalance(donor);
     const newOwner = await helper.eth.createAccountWithBalance(donor);
-    const {collectionAddress} = await helper.eth.createNonfungibleCollection(owner, 'A', 'B', 'C');
+    const {collectionAddress} = await helper.eth.createNFTCollection(owner, 'A', 'B', 'C');
     const collectionEvm = helper.ethNativeContract.collection(collectionAddress, 'nft', owner);
-    const cost = await recordEthFee(helper, owner, () => collectionEvm.methods.setOwner(newOwner).send());
+    const cost = await recordEthFee(helper, owner, () => collectionEvm.methods.changeCollectionOwner(newOwner).send());
     expect(cost < BigInt(0.2 * Number(helper.balance.getOneTokenNominal())));
     expect(cost > 0);
   });
@@ -301,10 +301,10 @@
   itEth('(!negative tests!) call setOwner by non owner', async ({helper}) => {
     const owner = await helper.eth.createAccountWithBalance(donor);
     const newOwner = await helper.eth.createAccountWithBalance(donor);
-    const {collectionAddress} = await helper.eth.createNonfungibleCollection(owner, 'A', 'B', 'C');
+    const {collectionAddress} = await helper.eth.createNFTCollection(owner, 'A', 'B', 'C');
     const collectionEvm = helper.ethNativeContract.collection(collectionAddress, 'nft', owner);
 
-    await expect(collectionEvm.methods.setOwner(newOwner).send({from: newOwner})).to.be.rejected;
+    await expect(collectionEvm.methods.changeCollectionOwner(newOwner).send({from: newOwner})).to.be.rejected;
     expect(await collectionEvm.methods.isOwnerOrAdmin(newOwner).call()).to.be.false;
   });
 });
@@ -321,7 +321,7 @@
   itEth.skip('Change owner', async ({helper}) => {
     const owner = await helper.eth.createAccountWithBalance(donor);
     const [newOwner] = await helper.arrange.createAccounts([10n], donor);
-    const {collectionAddress} = await helper.eth.createNonfungibleCollection(owner, 'A', 'B', 'C');
+    const {collectionAddress} = await helper.eth.createNFTCollection(owner, 'A', 'B', 'C');
     const collectionEvm = helper.ethNativeContract.collection(collectionAddress, 'nft', owner);
 
     expect(await collectionEvm.methods.isOwnerOrAdmin(owner).call()).to.be.true;
@@ -336,7 +336,7 @@
   itEth.skip('change owner call fee', async ({helper}) => {
     const owner = await helper.eth.createAccountWithBalance(donor);
     const [newOwner] = await helper.arrange.createAccounts([10n], donor);
-    const {collectionAddress} = await helper.eth.createNonfungibleCollection(owner, 'A', 'B', 'C');
+    const {collectionAddress} = await helper.eth.createNFTCollection(owner, 'A', 'B', 'C');
     const collectionEvm = helper.ethNativeContract.collection(collectionAddress, 'nft', owner);
 
     const cost = await recordEthFee(helper, owner, () => collectionEvm.methods.setOwnerSubstrate(newOwner.addressRaw).send());
@@ -348,7 +348,7 @@
     const owner = await helper.eth.createAccountWithBalance(donor);
     const otherReceiver = await helper.eth.createAccountWithBalance(donor);
     const [newOwner] = await helper.arrange.createAccounts([10n], donor);
-    const {collectionAddress} = await helper.eth.createNonfungibleCollection(owner, 'A', 'B', 'C');
+    const {collectionAddress} = await helper.eth.createNFTCollection(owner, 'A', 'B', 'C');
     const collectionEvm = helper.ethNativeContract.collection(collectionAddress, 'nft', owner);
 
     await expect(collectionEvm.methods.setOwnerSubstrate(newOwner.addressRaw).send({from: otherReceiver})).to.be.rejected;
modifiedtests/src/eth/collectionHelpersAbi.jsondiffbeforeafterboth
--- a/tests/src/eth/collectionHelpersAbi.json
+++ b/tests/src/eth/collectionHelpersAbi.json
@@ -29,33 +29,9 @@
     "inputs": [
       { "internalType": "string", "name": "name", "type": "string" },
       { "internalType": "string", "name": "description", "type": "string" },
-      { "internalType": "string", "name": "tokenPrefix", "type": "string" },
-      { "internalType": "string", "name": "baseUri", "type": "string" }
-    ],
-    "name": "createERC721MetadataCompatibleCollection",
-    "outputs": [{ "internalType": "address", "name": "", "type": "address" }],
-    "stateMutability": "payable",
-    "type": "function"
-  },
-  {
-    "inputs": [
-      { "internalType": "string", "name": "name", "type": "string" },
-      { "internalType": "string", "name": "description", "type": "string" },
-      { "internalType": "string", "name": "tokenPrefix", "type": "string" },
-      { "internalType": "string", "name": "baseUri", "type": "string" }
-    ],
-    "name": "createERC721MetadataCompatibleRFTCollection",
-    "outputs": [{ "internalType": "address", "name": "", "type": "address" }],
-    "stateMutability": "payable",
-    "type": "function"
-  },
-  {
-    "inputs": [
-      { "internalType": "string", "name": "name", "type": "string" },
-      { "internalType": "string", "name": "description", "type": "string" },
       { "internalType": "string", "name": "tokenPrefix", "type": "string" }
     ],
-    "name": "createNonfungibleCollection",
+    "name": "createNFTCollection",
     "outputs": [{ "internalType": "address", "name": "", "type": "address" }],
     "stateMutability": "payable",
     "type": "function"
@@ -86,6 +62,16 @@
   },
   {
     "inputs": [
+      { "internalType": "address", "name": "collection", "type": "address" },
+      { "internalType": "string", "name": "baseUri", "type": "string" }
+    ],
+    "name": "makeCollectionERC721MetadataCompatible",
+    "outputs": [],
+    "stateMutability": "nonpayable",
+    "type": "function"
+  },
+  {
+    "inputs": [
       { "internalType": "bytes4", "name": "interfaceID", "type": "bytes4" }
     ],
     "name": "supportsInterface",
modifiedtests/src/eth/collectionProperties.test.tsdiffbeforeafterboth
--- a/tests/src/eth/collectionProperties.test.ts
+++ b/tests/src/eth/collectionProperties.test.ts
@@ -14,8 +14,11 @@
 // 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 {itEth, usingEthPlaygrounds, expect} from './util';
+import {itEth, usingEthPlaygrounds, expect, EthUniqueHelper} from './util';
+import {Pallets} from '../util';
+import {IProperty, ITokenPropertyPermission} from '../util/playgrounds/types';
 import {IKeyringPair} from '@polkadot/types/types';
+import {Contract} from 'web3-eth-contract';
 
 describe('EVM collection properties', () => {
   let donor: IKeyringPair;
@@ -30,7 +33,7 @@
 
   itEth('Can be set', async({helper}) => {
     const caller = await helper.eth.createAccountWithBalance(donor);
-    const collection = await helper.nft.mintCollection(alice, {name: 'name', description: 'test', tokenPrefix: 'test'});
+    const collection = await helper.nft.mintCollection(alice, {name: 'name', description: 'test', tokenPrefix: 'test', properties: []});
     await collection.addAdmin(alice, {Ethereum: caller});
 
     const address = helper.ethAddress.fromCollectionId(collection.collectionId);
@@ -70,3 +73,92 @@
     expect(value).to.equal(helper.getWeb3().utils.toHex('testValue'));
   });
 });
+
+describe('Supports ERC721Metadata', () => {
+  let donor: IKeyringPair;
+
+  before(async function() {
+    await usingEthPlaygrounds(async (_helper, privateKey) => {
+      donor = await privateKey({filename: __filename});
+    });
+  });
+
+  const checkERC721Metadata = async (helper: EthUniqueHelper, mode: 'nft' | 'rft') => {
+    const caller = await helper.eth.createAccountWithBalance(donor);
+    const bruh = await helper.eth.createAccountWithBalance(donor);
+
+    const BASE_URI = 'base/'
+    const SUFFIX = 'suffix1'
+    const URI = 'uri1'
+
+    const collectionHelpers = helper.ethNativeContract.collectionHelpers(caller);
+    const creatorMethod = mode === 'rft' ? 'createRFTCollection' : 'createNFTCollection'
+
+    const {collectionId, collectionAddress} = await helper.eth[creatorMethod](caller, 'n', 'd', 'p')
+
+    const contract = helper.ethNativeContract.collectionById(collectionId, mode, caller);
+    await contract.methods.addCollectionAdmin(bruh).send(); // to check that admin will work too
+
+    const collection1 = await helper.nft.getCollectionObject(collectionId);
+    const data1 = await collection1.getData()
+    expect(data1?.raw.flags.erc721metadata).to.be.false;
+    expect(await contract.methods.supportsInterface('0x5b5e139f').call()).to.be.false;
+
+    await collectionHelpers.methods.makeCollectionERC721MetadataCompatible(collectionAddress, BASE_URI)
+      .send({from: bruh});
+
+    expect(await contract.methods.supportsInterface('0x5b5e139f').call()).to.be.true;
+
+    const collection2 = await helper.nft.getCollectionObject(collectionId);
+    const data2 = await collection2.getData()
+    expect(data2?.raw.flags.erc721metadata).to.be.true;
+
+    const TPPs = data2?.raw.tokenPropertyPermissions
+    expect(TPPs?.length).to.equal(2);
+
+    expect(TPPs.find((tpp: ITokenPropertyPermission) => {
+      return tpp.key === "URI" && tpp.permission.mutable && tpp.permission.collectionAdmin && !tpp.permission.tokenOwner
+    })).to.be.not.null
+
+    expect(TPPs.find((tpp: ITokenPropertyPermission) => {
+      return tpp.key === "URISuffix" && tpp.permission.mutable && tpp.permission.collectionAdmin && !tpp.permission.tokenOwner
+    })).to.be.not.null
+
+    expect(data2?.raw.properties?.find((property: IProperty) => {
+      return property.key === "baseURI" && property.value === BASE_URI
+    })).to.be.not.null
+
+    const token1Result = await contract.methods.mint(bruh).send();
+    const tokenId1 = token1Result.events.Transfer.returnValues.tokenId;
+
+    expect(await contract.methods.tokenURI(tokenId1).call()).to.equal(BASE_URI);
+
+    await contract.methods.setProperty(tokenId1, "URISuffix", Buffer.from(SUFFIX)).send();
+    expect(await contract.methods.tokenURI(tokenId1).call()).to.equal(BASE_URI + SUFFIX);
+
+    await contract.methods.setProperty(tokenId1, "URI", Buffer.from(URI)).send();
+    expect(await contract.methods.tokenURI(tokenId1).call()).to.equal(URI);
+
+    await contract.methods.deleteProperty(tokenId1, "URI").send();
+    expect(await contract.methods.tokenURI(tokenId1).call()).to.equal(BASE_URI + SUFFIX);
+
+    const token2Result = await contract.methods.mintWithTokenURI(bruh, URI).send();
+    const tokenId2 = token2Result.events.Transfer.returnValues.tokenId;
+
+    expect(await contract.methods.tokenURI(tokenId2).call()).to.equal(URI);
+
+    await contract.methods.deleteProperty(tokenId2, "URI").send();
+    expect(await contract.methods.tokenURI(tokenId2).call()).to.equal(BASE_URI);
+
+    await contract.methods.setProperty(tokenId2, "URISuffix", Buffer.from(SUFFIX)).send();
+    expect(await contract.methods.tokenURI(tokenId2).call()).to.equal(BASE_URI + SUFFIX);
+  }
+
+  itEth('ERC721Metadata property can be set for NFT collection', async({helper}) => {
+    await checkERC721Metadata(helper, 'nft');
+  });
+
+  itEth.ifWithPallets('ERC721Metadata property can be set for RFT collection', [Pallets.ReFungible], async({helper}) => {
+    await checkERC721Metadata(helper, 'rft');
+  });
+});
modifiedtests/src/eth/collectionSponsoring.test.tsdiffbeforeafterboth
--- a/tests/src/eth/collectionSponsoring.test.ts
+++ b/tests/src/eth/collectionSponsoring.test.ts
@@ -44,9 +44,8 @@
 
     await collection.addToAllowList(alice, {Ethereum: minter});
 
-    const nextTokenId = await contract.methods.nextTokenId().call();
-    expect(nextTokenId).to.equal('1');
-    const result = await contract.methods.mint(minter, nextTokenId).send();
+    const result = await contract.methods.mint(minter).send();
+
     const events = helper.eth.normalizeEvents(result.events);
     expect(events).to.be.deep.equal([
       {
@@ -55,7 +54,7 @@
         args: {
           from: '0x0000000000000000000000000000000000000000',
           to: minter,
-          tokenId: nextTokenId,
+          tokenId: '1',
         },
       },
     ]);
@@ -65,7 +64,7 @@
   // itWeb3('Set substrate sponsor', async ({api, web3, privateKeyWrapper}) => {
   //   const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
   //   const collectionHelpers = evmCollectionHelpers(web3, owner);
-  //   let result = await collectionHelpers.methods.createNonfungibleCollection('Sponsor collection', '1', '1').send();
+  //   let result = await collectionHelpers.methods.createNFTCollection('Sponsor collection', '1', '1').send();
   //   const {collectionIdAddress, collectionId} = await getCollectionAddressFromResult(api, result);
   //   const sponsor = privateKeyWrapper('//Alice');
   //   const collectionEvm = evmCollection(web3, owner, collectionIdAddress);
@@ -73,11 +72,11 @@
   //   expect(await collectionEvm.methods.hasCollectionPendingSponsor().call({from: owner})).to.be.false;
   //   result = await collectionEvm.methods.setCollectionSponsorSubstrate(sponsor.addressRaw).send({from: owner});
   //   expect(await collectionEvm.methods.hasCollectionPendingSponsor().call({from: owner})).to.be.true;
-    
+
   //   const confirmTx = await api.tx.unique.confirmSponsorship(collectionId);
   //   await submitTransactionAsync(sponsor, confirmTx);
   //   expect(await collectionEvm.methods.hasCollectionPendingSponsor().call({from: owner})).to.be.false;
-    
+
   //   const sponsorTuple = await collectionEvm.methods.collectionSponsor().call({from: owner});
   //   expect(bigIntToSub(api, BigInt(sponsorTuple[1]))).to.be.eq(sponsor.address);
   // });
@@ -86,7 +85,7 @@
     const owner = await helper.eth.createAccountWithBalance(donor);
     const collectionHelpers = helper.ethNativeContract.collectionHelpers(owner);
 
-    let result = await collectionHelpers.methods.createNonfungibleCollection('Sponsor collection', '1', '1').send({value: Number(2n * nominal)});
+    let result = await collectionHelpers.methods.createNFTCollection('Sponsor collection', '1', '1').send({value: Number(2n * nominal)});
     const collectionIdAddress = helper.ethAddress.normalizeAddress(result.events.CollectionCreated.returnValues.collectionId);
     const sponsor = await helper.eth.createAccountWithBalance(donor);
     const collectionEvm = helper.ethNativeContract.collection(collectionIdAddress, 'nft', owner);
@@ -94,28 +93,26 @@
     expect(await collectionEvm.methods.hasCollectionPendingSponsor().call({from: owner})).to.be.false;
     result = await collectionEvm.methods.setCollectionSponsor(sponsor).send({from: owner});
     expect(await collectionEvm.methods.hasCollectionPendingSponsor().call({from: owner})).to.be.true;
-    
+
     await collectionEvm.methods.confirmCollectionSponsorship().send({from: sponsor});
     expect(await collectionEvm.methods.hasCollectionPendingSponsor().call({from: owner})).to.be.false;
-    
+
     await collectionEvm.methods.removeCollectionSponsor().send({from: owner});
-    
+
     const sponsorTuple = await collectionEvm.methods.collectionSponsor().call({from: owner});
     expect(sponsorTuple.field_0).to.be.eq('0x0000000000000000000000000000000000000000');
   });
 
   itEth('Sponsoring collection from evm address via access list', async ({helper}) => {
     const owner = await helper.eth.createAccountWithBalance(donor);
-    const collectionHelpers = helper.ethNativeContract.collectionHelpers(owner);
 
-    let result = await collectionHelpers.methods.createNonfungibleCollection('Sponsor collection', '1', '1').send({value: Number(2n * nominal)});
-    const collectionIdAddress = helper.ethAddress.normalizeAddress(result.events.CollectionCreated.returnValues.collectionId);
-    const collectionId = helper.ethAddress.extractCollectionId(collectionIdAddress);
+    const {collectionId, collectionAddress} = await helper.eth.createERC721MetadataCompatibleNFTCollection(owner, 'Sponsor collection', '1', '1', '');
+
     const collection = helper.nft.getCollectionObject(collectionId);
     const sponsor = await helper.eth.createAccountWithBalance(donor);
-    const collectionEvm = helper.ethNativeContract.collection(collectionIdAddress, 'nft', owner);
+    const collectionEvm = helper.ethNativeContract.collection(collectionAddress, 'nft', owner);
 
-    result = await collectionEvm.methods.setCollectionSponsor(sponsor).send({from: owner});
+    await collectionEvm.methods.setCollectionSponsor(sponsor).send({from: owner});
     let collectionData = (await collection.getData())!;
     expect(collectionData.raw.sponsorship.Unconfirmed).to.be.eq(helper.address.ethToSubstrate(sponsor, true));
     await expect(collectionEvm.methods.confirmCollectionSponsorship().call()).to.be.rejectedWith('caller is not set as sponsor');
@@ -144,23 +141,17 @@
     const sponsorBalanceBefore = await helper.balance.getSubstrate(helper.address.ethToSubstrate(sponsor));
 
     {
-      const nextTokenId = await collectionEvm.methods.nextTokenId().call();
-      expect(nextTokenId).to.be.equal('1');
-      const result = await collectionEvm.methods.mintWithTokenURI(
-        user,
-        nextTokenId,
-        'Test URI',
-      ).send({from: user});
+      const result = await collectionEvm.methods.mintWithTokenURI(user, 'Test URI').send({from: user});
       const events = helper.eth.normalizeEvents(result.events);
 
       expect(events).to.be.deep.equal([
         {
-          address: collectionIdAddress,
+          address: collectionAddress,
           event: 'Transfer',
           args: {
             from: '0x0000000000000000000000000000000000000000',
             to: user,
-            tokenId: nextTokenId,
+            tokenId: '1',
           },
         },
       ]);
@@ -178,16 +169,16 @@
   // itWeb3('Sponsoring collection from substrate address via access list', async ({api, web3, privateKeyWrapper}) => {
   //   const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
   //   const collectionHelpers = evmCollectionHelpers(web3, owner);
-  //   const result = await collectionHelpers.methods.createNonfungibleCollection('Sponsor collection', '1', '1').send();
+  //   const result = await collectionHelpers.methods.createERC721MetadataCompatibleNFTCollection('Sponsor collection', '1', '1', '').send();
   //   const {collectionIdAddress, collectionId} = await getCollectionAddressFromResult(api, result);
   //   const sponsor = privateKeyWrapper('//Alice');
   //   const collectionEvm = evmCollection(web3, owner, collectionIdAddress);
 
   //   await collectionEvm.methods.setCollectionSponsorSubstrate(sponsor.addressRaw).send({from: owner});
-    
+
   //   const confirmTx = await api.tx.unique.confirmSponsorship(collectionId);
   //   await submitTransactionAsync(sponsor, confirmTx);
-    
+
   //   const user = createEthAccount(web3);
   //   const nextTokenId = await collectionEvm.methods.nextTokenId().call();
   //   expect(nextTokenId).to.be.equal('1');
@@ -232,39 +223,32 @@
 
   itEth('Check that transaction via EVM spend money from sponsor address', async ({helper}) => {
     const owner = await helper.eth.createAccountWithBalance(donor);
-    const collectionHelpers = helper.ethNativeContract.collectionHelpers(owner);
 
-    let result = await collectionHelpers.methods.createNonfungibleCollection('Sponsor collection', '1', '1').send({value: Number(2n * nominal)});
-    const collectionIdAddress = helper.ethAddress.normalizeAddress(result.events.CollectionCreated.returnValues.collectionId);
-    const collectionId = helper.ethAddress.extractCollectionId(collectionIdAddress);
+    const {collectionAddress, collectionId} = await helper.eth.createERC721MetadataCompatibleNFTCollection(owner,'Sponsor collection', '1', '1', '');
     const collection = helper.nft.getCollectionObject(collectionId);
     const sponsor = await helper.eth.createAccountWithBalance(donor);
-    const collectionEvm = helper.ethNativeContract.collection(collectionIdAddress, 'nft', owner);
+    const collectionEvm = helper.ethNativeContract.collection(collectionAddress, 'nft', owner);
 
-    result = await collectionEvm.methods.setCollectionSponsor(sponsor).send();
+    await collectionEvm.methods.setCollectionSponsor(sponsor).send();
     let collectionData = (await collection.getData())!;
     expect(collectionData.raw.sponsorship.Unconfirmed).to.be.eq(helper.address.ethToSubstrate(sponsor, true));
     await expect(collectionEvm.methods.confirmCollectionSponsorship().call()).to.be.rejectedWith('caller is not set as sponsor');
 
-    const sponsorCollection = helper.ethNativeContract.collection(collectionIdAddress, 'nft', sponsor);
+    const sponsorCollection = helper.ethNativeContract.collection(collectionAddress, 'nft', sponsor);
     await sponsorCollection.methods.confirmCollectionSponsorship().send();
     collectionData = (await collection.getData())!;
     expect(collectionData.raw.sponsorship.Confirmed).to.be.eq(helper.address.ethToSubstrate(sponsor, true));
 
     const user = helper.eth.createAccount();
     await collectionEvm.methods.addCollectionAdmin(user).send();
-    
+
     const ownerBalanceBefore = await helper.balance.getSubstrate(helper.address.ethToSubstrate(owner));
     const sponsorBalanceBefore = await helper.balance.getSubstrate(helper.address.ethToSubstrate(sponsor));
 
-    const userCollectionEvm = helper.ethNativeContract.collection(collectionIdAddress, 'nft', user);
-    const nextTokenId = await userCollectionEvm.methods.nextTokenId().call();
-    expect(nextTokenId).to.be.equal('1');
-    result = await userCollectionEvm.methods.mintWithTokenURI(
-      user,
-      nextTokenId,
-      'Test URI',
-    ).send();
+    const userCollectionEvm = helper.ethNativeContract.collection(collectionAddress, 'nft', user);
+
+    let result = await userCollectionEvm.methods.mintWithTokenURI(user, 'Test URI',).send();
+    const tokenId = result.events.Transfer.returnValues.tokenId;
 
     const events = helper.eth.normalizeEvents(result.events);
     const address = helper.ethAddress.fromCollectionId(collectionId);
@@ -276,12 +260,12 @@
         args: {
           from: '0x0000000000000000000000000000000000000000',
           to: user,
-          tokenId: nextTokenId,
+          tokenId: '1',
         },
       },
     ]);
-    expect(await userCollectionEvm.methods.tokenURI(nextTokenId).call()).to.be.equal('Test URI');
-  
+    expect(await userCollectionEvm.methods.tokenURI(tokenId).call()).to.be.equal('Test URI');
+
     const ownerBalanceAfter = await helper.balance.getSubstrate(helper.address.ethToSubstrate(owner));
     expect(ownerBalanceAfter).to.be.eq(ownerBalanceBefore);
     const sponsorBalanceAfter = await helper.balance.getSubstrate(helper.address.ethToSubstrate(sponsor));
modifiedtests/src/eth/createNFTCollection.test.tsdiffbeforeafterboth
--- a/tests/src/eth/createNFTCollection.test.ts
+++ b/tests/src/eth/createNFTCollection.test.ts
@@ -35,13 +35,49 @@
     const description = 'Some description';
     const prefix = 'token prefix';
 
-    const {collectionId} = await helper.eth.createNonfungibleCollection(owner, name, description, prefix);
+    const {collectionId} = await helper.eth.createNFTCollection(owner, name, description, prefix);
     const data = (await helper.rft.getData(collectionId))!;
+    const collection = helper.nft.getCollectionObject(collectionId);
+    
+    expect(data.name).to.be.eq(name);
+    expect(data.description).to.be.eq(description);
+    expect(data.raw.tokenPrefix).to.be.eq(prefix);
+    expect(data.raw.mode).to.be.eq('NFT');
+
+    const options = await collection.getOptions();
+
+    expect(options.tokenPropertyPermissions).to.be.empty;
+  });
+
+  itEth('Create collection with properties', async ({helper}) => {
+    const owner = await helper.eth.createAccountWithBalance(donor);
+
+    const name = 'CollectionEVM';
+    const description = 'Some description';
+    const prefix = 'token prefix';
+    const baseUri = 'BaseURI';
+
+    const {collectionId} = await helper.eth.createERC721MetadataCompatibleNFTCollection(owner, name, description, prefix, baseUri);
+
+    const collection = helper.nft.getCollectionObject(collectionId);
+    const data = (await collection.getData())!;
     
     expect(data.name).to.be.eq(name);
     expect(data.description).to.be.eq(description);
     expect(data.raw.tokenPrefix).to.be.eq(prefix);
     expect(data.raw.mode).to.be.eq('NFT');
+
+    const options = await collection.getOptions();
+    expect(options.tokenPropertyPermissions).to.be.deep.equal([
+      {
+        key: 'URI',
+        permission: {mutable: true, collectionAdmin: true, tokenOwner: false},
+      },
+      {
+        key: 'URISuffix',
+        permission: {mutable: true, collectionAdmin: true, tokenOwner: false},
+      },
+    ]);
   });
 
   // this test will occasionally fail when in async environment.
@@ -57,7 +93,7 @@
       .call()).to.be.false;
 
     await collectionHelpers.methods
-      .createNonfungibleCollection('A', 'A', 'A')
+      .createNFTCollection('A', 'A', 'A')
       .send({value: Number(2n * helper.balance.getOneTokenNominal())});
     
     expect(await collectionHelpers.methods
@@ -69,7 +105,7 @@
     const owner = await helper.eth.createAccountWithBalance(donor);
     const sponsor = await helper.eth.createAccountWithBalance(donor);
     const ss58Format = helper.chain.getChainProperties().ss58Format;
-    const {collectionId, collectionAddress} = await helper.eth.createNonfungibleCollection(owner, 'Sponsor', 'absolutely anything', 'ROC');
+    const {collectionId, collectionAddress} = await helper.eth.createNFTCollection(owner, 'Sponsor', 'absolutely anything', 'ROC');
 
     const collection = helper.ethNativeContract.collection(collectionAddress, 'nft', owner);
     await collection.methods.setCollectionSponsor(sponsor).send();
@@ -88,7 +124,7 @@
 
   itEth('Set limits', async ({helper}) => {
     const owner = await helper.eth.createAccountWithBalance(donor);
-    const {collectionId, collectionAddress} = await helper.eth.createNonfungibleCollection(owner, 'Limits', 'absolutely anything', 'FLO');
+    const {collectionId, collectionAddress} = await helper.eth.createNFTCollection(owner, 'Limits', 'absolutely anything', 'FLO');
     const limits = {
       accountTokenOwnershipLimit: 1000,
       sponsoredDataSize: 1024,
@@ -131,7 +167,7 @@
       .methods.isCollectionExist(collectionAddressForNonexistentCollection).call())
       .to.be.false;
     
-    const {collectionAddress} = await helper.eth.createNonfungibleCollection(owner, 'Exister', 'absolutely anything', 'EVC');
+    const {collectionAddress} = await helper.eth.createNFTCollection(owner, 'Exister', 'absolutely anything', 'EVC');
     expect(await helper.ethNativeContract.collectionHelpers(collectionAddress)
       .methods.isCollectionExist(collectionAddress).call())
       .to.be.true;
@@ -159,7 +195,7 @@
       const tokenPrefix = 'A';
 
       await expect(collectionHelper.methods
-        .createNonfungibleCollection(collectionName, description, tokenPrefix)
+        .createNFTCollection(collectionName, description, tokenPrefix)
         .call({value: Number(2n * nominal)})).to.be.rejectedWith('name is too long. Max length is ' + MAX_NAME_LENGTH);
       
     }
@@ -169,7 +205,7 @@
       const description = 'A'.repeat(MAX_DESCRIPTION_LENGTH + 1);
       const tokenPrefix = 'A';
       await expect(collectionHelper.methods
-        .createNonfungibleCollection(collectionName, description, tokenPrefix)
+        .createNFTCollection(collectionName, description, tokenPrefix)
         .call({value: Number(2n * nominal)})).to.be.rejectedWith('description is too long. Max length is ' + MAX_DESCRIPTION_LENGTH);
     }
     {
@@ -178,7 +214,7 @@
       const description = 'A';
       const tokenPrefix = 'A'.repeat(MAX_TOKEN_PREFIX_LENGTH + 1);
       await expect(collectionHelper.methods
-        .createNonfungibleCollection(collectionName, description, tokenPrefix)
+        .createNFTCollection(collectionName, description, tokenPrefix)
         .call({value: Number(2n * nominal)})).to.be.rejectedWith('token_prefix is too long. Max length is ' + MAX_TOKEN_PREFIX_LENGTH);
     }
   });
@@ -187,14 +223,14 @@
     const owner = await helper.eth.createAccountWithBalance(donor);
     const collectionHelper = helper.ethNativeContract.collectionHelpers(owner);
     await expect(collectionHelper.methods
-      .createNonfungibleCollection('Peasantry', 'absolutely anything', 'CVE')
+      .createNFTCollection('Peasantry', 'absolutely anything', 'CVE')
       .call({value: Number(1n * nominal)})).to.be.rejectedWith('Sent amount not equals to collection creation price (2000000000000000000)');
   });
 
   itEth('(!negative test!) Check owner', async ({helper}) => {
     const owner = await helper.eth.createAccountWithBalance(donor);
     const malfeasant = helper.eth.createAccount();
-    const {collectionAddress} = await helper.eth.createNonfungibleCollection(owner, 'Transgressed', 'absolutely anything', 'COR');
+    const {collectionAddress} = await helper.eth.createNFTCollection(owner, 'Transgressed', 'absolutely anything', 'COR');
     const malfeasantCollection = helper.ethNativeContract.collection(collectionAddress, 'nft', malfeasant);
     const EXPECTED_ERROR = 'NoPermission';
     {
@@ -217,10 +253,10 @@
 
   itEth('(!negative test!) Set limits', async ({helper}) => {
     const owner = await helper.eth.createAccountWithBalance(donor);
-    const {collectionAddress} = await helper.eth.createNonfungibleCollection(owner, 'Limits', 'absolutely anything', 'OLF');
+    const {collectionAddress} = await helper.eth.createNFTCollection(owner, 'Limits', 'absolutely anything', 'OLF');
     const collectionEvm = helper.ethNativeContract.collection(collectionAddress, 'nft', owner);
     await expect(collectionEvm.methods
       .setCollectionLimit('badLimit', 'true')
       .call()).to.be.rejectedWith('unknown boolean limit "badLimit"');
   });
-});
\ No newline at end of file
+});
modifiedtests/src/eth/createRFTCollection.test.tsdiffbeforeafterboth
--- a/tests/src/eth/createRFTCollection.test.ts
+++ b/tests/src/eth/createRFTCollection.test.ts
@@ -37,13 +37,51 @@
     const description = 'Some description';
     const prefix = 'token prefix';
   
-    const {collectionId} = await helper.eth.createRefungibleCollection(owner, name, description, prefix);
+    const {collectionId} = await helper.eth.createRFTCollection(owner, name, description, prefix);
     const data = (await helper.rft.getData(collectionId))!;
+    const collection = helper.rft.getCollectionObject(collectionId);
+
+    expect(data.name).to.be.eq(name);
+    expect(data.description).to.be.eq(description);
+    expect(data.raw.tokenPrefix).to.be.eq(prefix);
+    expect(data.raw.mode).to.be.eq('ReFungible');
+
+    const options = await collection.getOptions();
+
+    expect(options.tokenPropertyPermissions).to.be.empty;
+  });
+
+  
+
+  itEth('Create collection with properties', async ({helper}) => {
+    const owner = await helper.eth.createAccountWithBalance(donor);
+
+    const name = 'CollectionEVM';
+    const description = 'Some description';
+    const prefix = 'token prefix';
+    const baseUri = 'BaseURI';
+
+    const {collectionId} = await helper.eth.createERC721MetadataCompatibleRFTCollection(owner, name, description, prefix, baseUri);
 
+    const collection = helper.rft.getCollectionObject(collectionId);
+    const data = (await collection.getData())!;
+    
     expect(data.name).to.be.eq(name);
     expect(data.description).to.be.eq(description);
     expect(data.raw.tokenPrefix).to.be.eq(prefix);
     expect(data.raw.mode).to.be.eq('ReFungible');
+
+    const options = await collection.getOptions();
+    expect(options.tokenPropertyPermissions).to.be.deep.equal([
+      {
+        key: 'URI',
+        permission: {mutable: true, collectionAdmin: true, tokenOwner: false},
+      },
+      {
+        key: 'URISuffix',
+        permission: {mutable: true, collectionAdmin: true, tokenOwner: false},
+      },
+    ]);
   });
   
   // this test will occasionally fail when in async environment.
@@ -71,7 +109,7 @@
     const owner = await helper.eth.createAccountWithBalance(donor);
     const sponsor = await helper.eth.createAccountWithBalance(donor);
     const ss58Format = helper.chain.getChainProperties().ss58Format;
-    const {collectionId, collectionAddress} = await helper.eth.createRefungibleCollection(owner, 'Sponsor', 'absolutely anything', 'ENVY');
+    const {collectionId, collectionAddress} = await helper.eth.createRFTCollection(owner, 'Sponsor', 'absolutely anything', 'ENVY');
 
     const collection = helper.ethNativeContract.collection(collectionAddress, 'rft', owner);
     await collection.methods.setCollectionSponsor(sponsor).send();
@@ -90,7 +128,7 @@
 
   itEth('Set limits', async ({helper}) => {
     const owner = await helper.eth.createAccountWithBalance(donor);
-    const {collectionId, collectionAddress} = await helper.eth.createRefungibleCollection(owner, 'Limits', 'absolutely anything', 'INSI');
+    const {collectionId, collectionAddress} = await helper.eth.createRFTCollection(owner, 'Limits', 'absolutely anything', 'INSI');
     const limits = {
       accountTokenOwnershipLimit: 1000,
       sponsoredDataSize: 1024,
@@ -133,7 +171,7 @@
       .methods.isCollectionExist(collectionAddressForNonexistentCollection).call())
       .to.be.false;
     
-    const {collectionAddress} = await helper.eth.createRefungibleCollection(owner, 'Exister', 'absolutely anything', 'WIWT');
+    const {collectionAddress} = await helper.eth.createRFTCollection(owner, 'Exister', 'absolutely anything', 'WIWT');
     expect(await helper.ethNativeContract.collectionHelpers(collectionAddress)
       .methods.isCollectionExist(collectionAddress).call())
       .to.be.true;
@@ -196,7 +234,7 @@
   itEth('(!negative test!) Check owner', async ({helper}) => {
     const owner = await helper.eth.createAccountWithBalance(donor);
     const peasant = helper.eth.createAccount();
-    const {collectionAddress} = await helper.eth.createRefungibleCollection(owner, 'Transgressed', 'absolutely anything', 'YVNE');
+    const {collectionAddress} = await helper.eth.createRFTCollection(owner, 'Transgressed', 'absolutely anything', 'YVNE');
     const peasantCollection = helper.ethNativeContract.collection(collectionAddress, 'rft', peasant);
     const EXPECTED_ERROR = 'NoPermission';
     {
@@ -219,7 +257,7 @@
 
   itEth('(!negative test!) Set limits', async ({helper}) => {
     const owner = await helper.eth.createAccountWithBalance(donor);
-    const {collectionAddress} = await helper.eth.createRefungibleCollection(owner, 'Limits', 'absolutely anything', 'ISNI');
+    const {collectionAddress} = await helper.eth.createRFTCollection(owner, 'Limits', 'absolutely anything', 'ISNI');
     const collectionEvm = helper.ethNativeContract.collection(collectionAddress, 'rft', owner);
     await expect(collectionEvm.methods
       .setCollectionLimit('badLimit', 'true')
modifiedtests/src/eth/evmCoder.test.tsdiffbeforeafterboth
--- a/tests/src/eth/evmCoder.test.ts
+++ b/tests/src/eth/evmCoder.test.ts
@@ -65,7 +65,7 @@
   
   itEth('Call non-existing function', async ({helper}) => {
     const owner = await helper.eth.createAccountWithBalance(donor);
-    const collection = await helper.eth.createNonfungibleCollection(owner, 'EVMCODER', '', 'TEST');
+    const collection = await helper.eth.createNFTCollection(owner, 'EVMCODER', '', 'TEST');
     const contract = await helper.ethContract.deployByCode(owner, 'Test', getContractSource(collection.collectionAddress, '0x1bfed5D614b886b9Ab2eA4CBAc22A96B7EC29c9c'));
     const testContract = await helper.ethContract.deployByCode(owner, 'Test', getContractSource(collection.collectionAddress, contract.options.address));
     {
modifiedtests/src/eth/fractionalizer/Fractionalizer.soldiffbeforeafterboth
--- a/tests/src/eth/fractionalizer/Fractionalizer.sol
+++ b/tests/src/eth/fractionalizer/Fractionalizer.sol
@@ -124,8 +124,7 @@
 		address rftTokenAddress;
 		UniqueRefungibleToken rftTokenContract;
 		if (nft2rftMapping[_collection][_token] == 0) {
-			rftTokenId = rftCollectionContract.nextTokenId();
-			rftCollectionContract.mint(address(this), rftTokenId);
+            rftTokenId = rftCollectionContract.mint(address(this));
 			rftTokenAddress = rftCollectionContract.tokenContractAddress(rftTokenId);
 			nft2rftMapping[_collection][_token] = rftTokenId;
 			rft2nftMapping[rftTokenAddress] = Token(_collection, _token);
modifiedtests/src/eth/fractionalizer/fractionalizer.test.tsdiffbeforeafterboth
--- a/tests/src/eth/fractionalizer/fractionalizer.test.ts
+++ b/tests/src/eth/fractionalizer/fractionalizer.test.ts
@@ -62,10 +62,10 @@
 const mintRFTToken = async (helper: EthUniqueHelper, owner: string, fractionalizer: Contract, amount: bigint): Promise<{
   nftCollectionAddress: string, nftTokenId: number, rftTokenAddress: string
 }> => {
-  const nftCollection = await helper.eth.createNonfungibleCollection(owner, 'nft', 'NFT collection', 'NFT');
+  const nftCollection = await helper.eth.createNFTCollection(owner, 'nft', 'NFT collection', 'NFT');
   const nftContract = helper.ethNativeContract.collection(nftCollection.collectionAddress, 'nft', owner);
-  const nftTokenId = await nftContract.methods.nextTokenId().call();
-  await nftContract.methods.mint(owner, nftTokenId).send({from: owner});
+  const mintResult = await nftContract.methods.mint(owner).send({from: owner});
+  const nftTokenId = mintResult.events.Transfer.returnValues.tokenId;
 
   await fractionalizer.methods.setNftCollectionIsAllowed(nftCollection.collectionAddress, true).send({from: owner});
   await nftContract.methods.approve(fractionalizer.options.address, nftTokenId).send({from: owner});
@@ -92,7 +92,7 @@
   itEth('Set RFT collection', async ({helper}) => {
     const owner = await helper.eth.createAccountWithBalance(donor, 10n);
     const fractionalizer = await deployContract(helper, owner);
-    const rftCollection = await helper.eth.createRefungibleCollection(owner, 'rft', 'RFT collection', 'RFT');
+    const rftCollection = await helper.eth.createRFTCollection(owner, 'rft', 'RFT collection', 'RFT');
     const rftContract = helper.ethNativeContract.collection(rftCollection.collectionAddress, 'rft', owner);
 
     await rftContract.methods.addCollectionAdmin(fractionalizer.options.address).send({from: owner});
@@ -121,7 +121,7 @@
   itEth('Set Allowlist', async ({helper}) => {
     const owner = await helper.eth.createAccountWithBalance(donor, 20n);
     const {contract: fractionalizer} = await initContract(helper, owner);
-    const nftCollection = await helper.eth.createNonfungibleCollection(owner, 'nft', 'NFT collection', 'NFT');
+    const nftCollection = await helper.eth.createNFTCollection(owner, 'nft', 'NFT collection', 'NFT');
 
     const result1 = await fractionalizer.methods.setNftCollectionIsAllowed(nftCollection.collectionAddress, true).send({from: owner});
     expect(result1.events).to.be.like({
@@ -146,10 +146,10 @@
   itEth('NFT to RFT', async ({helper}) => {
     const owner = await helper.eth.createAccountWithBalance(donor, 20n);
 
-    const nftCollection = await helper.eth.createNonfungibleCollection(owner, 'nft', 'NFT collection', 'NFT');
+    const nftCollection = await helper.eth.createNFTCollection(owner, 'nft', 'NFT collection', 'NFT');
     const nftContract = helper.ethNativeContract.collection(nftCollection.collectionAddress, 'nft', owner);
-    const nftTokenId = await nftContract.methods.nextTokenId().call();
-    await nftContract.methods.mint(owner, nftTokenId).send({from: owner});
+    const mintResult = await nftContract.methods.mint(owner).send({from: owner});
+    const nftTokenId = mintResult.events.Transfer.returnValues.tokenId;
 
     const {contract: fractionalizer} = await initContract(helper, owner);
 
@@ -231,7 +231,7 @@
 
   itEth('call setRFTCollection twice', async ({helper}) => {
     const owner = await helper.eth.createAccountWithBalance(donor, 20n);
-    const rftCollection = await helper.eth.createRefungibleCollection(owner, 'rft', 'RFT collection', 'RFT');
+    const rftCollection = await helper.eth.createRFTCollection(owner, 'rft', 'RFT collection', 'RFT');
     const refungibleContract = helper.ethNativeContract.collection(rftCollection.collectionAddress, 'rft', owner);
 
     const fractionalizer = await deployContract(helper, owner);
@@ -244,7 +244,7 @@
 
   itEth('call setRFTCollection with NFT collection', async ({helper}) => {
     const owner = await helper.eth.createAccountWithBalance(donor, 20n);
-    const nftCollection = await helper.eth.createNonfungibleCollection(owner, 'nft', 'NFT collection', 'NFT');
+    const nftCollection = await helper.eth.createNFTCollection(owner, 'nft', 'NFT collection', 'NFT');
     const nftContract = helper.ethNativeContract.collection(nftCollection.collectionAddress, 'nft', owner);
 
     const fractionalizer = await deployContract(helper, owner);
@@ -257,7 +257,7 @@
   itEth('call setRFTCollection while not collection admin', async ({helper}) => {
     const owner = await helper.eth.createAccountWithBalance(donor, 20n);
     const fractionalizer = await deployContract(helper, owner);
-    const rftCollection = await helper.eth.createRefungibleCollection(owner, 'rft', 'RFT collection', 'RFT');
+    const rftCollection = await helper.eth.createRFTCollection(owner, 'rft', 'RFT collection', 'RFT');
 
     await expect(fractionalizer.methods.setRFTCollection(rftCollection.collectionAddress).call())
       .to.be.rejectedWith(/Fractionalizer contract should be an admin of the collection$/g);
@@ -278,10 +278,10 @@
   itEth('call nft2rft without setting RFT collection for contract', async ({helper}) => {
     const owner = await helper.eth.createAccountWithBalance(donor, 20n);
 
-    const nftCollection = await helper.eth.createNonfungibleCollection(owner, 'nft', 'NFT collection', 'NFT');
+    const nftCollection = await helper.eth.createNFTCollection(owner, 'nft', 'NFT collection', 'NFT');
     const nftContract = helper.ethNativeContract.collection(nftCollection.collectionAddress, 'nft', owner);
-    const nftTokenId = await nftContract.methods.nextTokenId().call();
-    await nftContract.methods.mint(owner, nftTokenId).send({from: owner});
+    const mintResult = await nftContract.methods.mint(owner).send({from: owner});
+    const nftTokenId = mintResult.events.Transfer.returnValues.tokenId;
 
     const fractionalizer = await deployContract(helper, owner);
 
@@ -293,10 +293,10 @@
     const owner = await helper.eth.createAccountWithBalance(donor, 20n);
     const nftOwner = await helper.eth.createAccountWithBalance(donor, 10n);
 
-    const nftCollection = await helper.eth.createNonfungibleCollection(owner, 'nft', 'NFT collection', 'NFT');
+    const nftCollection = await helper.eth.createNFTCollection(owner, 'nft', 'NFT collection', 'NFT');
     const nftContract = helper.ethNativeContract.collection(nftCollection.collectionAddress, 'nft', owner);
-    const nftTokenId = await nftContract.methods.nextTokenId().call();
-    await nftContract.methods.mint(owner, nftTokenId).send({from: owner});
+    const mintResult = await nftContract.methods.mint(owner).send({from: owner});
+    const nftTokenId = mintResult.events.Transfer.returnValues.tokenId;
     await nftContract.methods.transfer(nftOwner, 1).send({from: owner});
 
 
@@ -310,10 +310,10 @@
   itEth('call nft2rft while not in list of allowed accounts', async ({helper}) => {
     const owner = await helper.eth.createAccountWithBalance(donor, 20n);
 
-    const nftCollection = await helper.eth.createNonfungibleCollection(owner, 'nft', 'NFT collection', 'NFT');
+    const nftCollection = await helper.eth.createNFTCollection(owner, 'nft', 'NFT collection', 'NFT');
     const nftContract = helper.ethNativeContract.collection(nftCollection.collectionAddress, 'nft', owner);
-    const nftTokenId = await nftContract.methods.nextTokenId().call();
-    await nftContract.methods.mint(owner, nftTokenId).send({from: owner});
+    const mintResult = await nftContract.methods.mint(owner).send({from: owner});
+    const nftTokenId = mintResult.events.Transfer.returnValues.tokenId;
 
     const {contract: fractionalizer} = await initContract(helper, owner);
 
@@ -325,10 +325,10 @@
   itEth('call nft2rft while fractionalizer doesnt have approval for nft token', async ({helper}) => {
     const owner = await helper.eth.createAccountWithBalance(donor, 20n);
 
-    const nftCollection = await helper.eth.createNonfungibleCollection(owner, 'nft', 'NFT collection', 'NFT');
+    const nftCollection = await helper.eth.createNFTCollection(owner, 'nft', 'NFT collection', 'NFT');
     const nftContract = helper.ethNativeContract.collection(nftCollection.collectionAddress, 'nft', owner);
-    const nftTokenId = await nftContract.methods.nextTokenId().call();
-    await nftContract.methods.mint(owner, nftTokenId).send({from: owner});
+    const mintResult = await nftContract.methods.mint(owner).send({from: owner});
+    const nftTokenId = mintResult.events.Transfer.returnValues.tokenId;
 
     const {contract: fractionalizer} = await initContract(helper, owner);
 
@@ -341,11 +341,11 @@
     const owner = await helper.eth.createAccountWithBalance(donor, 20n);
 
     const fractionalizer = await deployContract(helper, owner);
-    const rftCollection = await helper.eth.createRefungibleCollection(owner, 'rft', 'RFT collection', 'RFT');
+    const rftCollection = await helper.eth.createRFTCollection(owner, 'rft', 'RFT collection', 'RFT');
     const refungibleContract = helper.ethNativeContract.collection(rftCollection.collectionAddress, 'rft', owner);
-    const rftTokenId = await refungibleContract.methods.nextTokenId().call();
-    await refungibleContract.methods.mint(owner, rftTokenId).send({from: owner});
-    
+    const mintResult = await refungibleContract.methods.mint(owner).send({from: owner});
+    const rftTokenId = mintResult.events.Transfer.returnValues.tokenId;
+
     await expect(fractionalizer.methods.rft2nft(rftCollection.collectionAddress, rftTokenId).call({from: owner}))
       .to.be.rejectedWith(/RFT collection is not set$/g);
   });
@@ -354,18 +354,18 @@
     const owner = await helper.eth.createAccountWithBalance(donor, 20n);
 
     const {contract: fractionalizer} = await initContract(helper, owner);
-    const rftCollection = await helper.eth.createRefungibleCollection(owner, 'rft', 'RFT collection', 'RFT');
+    const rftCollection = await helper.eth.createRFTCollection(owner, 'rft', 'RFT collection', 'RFT');
     const refungibleContract = helper.ethNativeContract.collection(rftCollection.collectionAddress, 'rft', owner);
-    const rftTokenId = await refungibleContract.methods.nextTokenId().call();
-    await refungibleContract.methods.mint(owner, rftTokenId).send({from: owner});
-    
+    const mintResult = await refungibleContract.methods.mint(owner).send({from: owner});
+    const rftTokenId = mintResult.events.Transfer.returnValues.tokenId;
+
     await expect(fractionalizer.methods.rft2nft(rftCollection.collectionAddress, rftTokenId).call())
       .to.be.rejectedWith(/Wrong RFT collection$/g);
   });
 
   itEth('call rft2nft for RFT token that was not minted by fractionalizer contract', async ({helper}) => {
     const owner = await helper.eth.createAccountWithBalance(donor, 20n);
-    const rftCollection = await helper.eth.createRefungibleCollection(owner, 'rft', 'RFT collection', 'RFT');
+    const rftCollection = await helper.eth.createRFTCollection(owner, 'rft', 'RFT collection', 'RFT');
     const refungibleContract = helper.ethNativeContract.collection(rftCollection.collectionAddress, 'rft', owner);
 
     const fractionalizer = await deployContract(helper, owner);
@@ -373,9 +373,9 @@
     await refungibleContract.methods.addCollectionAdmin(fractionalizer.options.address).send({from: owner});
     await fractionalizer.methods.setRFTCollection(rftCollection.collectionAddress).send({from: owner});
 
-    const rftTokenId = await refungibleContract.methods.nextTokenId().call();
-    await refungibleContract.methods.mint(owner, rftTokenId).send({from: owner});
-    
+    const mintResult = await refungibleContract.methods.mint(owner).send({from: owner});
+    const rftTokenId = mintResult.events.Transfer.returnValues.tokenId;
+
     await expect(fractionalizer.methods.rft2nft(rftCollection.collectionAddress, rftTokenId).call())
       .to.be.rejectedWith(/No corresponding NFT token found$/g);
   });
@@ -386,7 +386,7 @@
 
     const {contract: fractionalizer, rftCollectionAddress} = await initContract(helper, owner);
     const {rftTokenAddress} = await mintRFTToken(helper, owner, fractionalizer, 100n);
-    
+
     const {tokenId} = helper.ethAddress.extractTokenId(rftTokenAddress);
     const refungibleTokenContract = helper.ethNativeContract.rftToken(rftTokenAddress, owner);
     await refungibleTokenContract.methods.transfer(receiver, 50).send({from: owner});
@@ -420,7 +420,7 @@
     await expect(fractionalizer.methods.nft2rft(nftCollectionAddress, nftToken.tokenId, 100).call())
       .to.be.rejectedWith(/TransferNotAllowed$/g);
   });
-  
+
   itEth('fractionalize NFT with RFT transfers disallowed', async ({helper}) => {
     const owner = await helper.eth.createAccountWithBalance(donor, 20n);
 
@@ -432,10 +432,10 @@
     await fractionalizer.methods.setRFTCollection(rftCollectionAddress).send({from: owner});
     await helper.executeExtrinsic(donor, 'api.tx.unique.setTransfersEnabledFlag', [rftCollection.collectionId, false], true);
 
-    const nftCollection = await helper.eth.createNonfungibleCollection(owner, 'nft', 'NFT collection', 'NFT');
+    const nftCollection = await helper.eth.createNFTCollection(owner, 'nft', 'NFT collection', 'NFT');
     const nftContract = helper.ethNativeContract.collection(nftCollection.collectionAddress, 'nft', owner);
-    const nftTokenId = await nftContract.methods.nextTokenId().call();
-    await nftContract.methods.mint(owner, nftTokenId).send({from: owner});
+    const mintResult = await nftContract.methods.mint(owner).send({from: owner});
+    const nftTokenId = mintResult.events.Transfer.returnValues.tokenId;
 
     await fractionalizer.methods.setNftCollectionIsAllowed(nftCollection.collectionAddress, true).send({from: owner});
     await nftContract.methods.approve(fractionalizer.options.address, nftTokenId).send({from: owner});
modifiedtests/src/eth/fungibleAbi.jsondiffbeforeafterboth
--- a/tests/src/eth/fungibleAbi.json
+++ b/tests/src/eth/fungibleAbi.json
@@ -116,6 +116,15 @@
     "type": "function"
   },
   {
+    "inputs": [
+      { "internalType": "address", "name": "newOwner", "type": "address" }
+    ],
+    "name": "changeCollectionOwner",
+    "outputs": [],
+    "stateMutability": "nonpayable",
+    "type": "function"
+  },
+  {
     "inputs": [],
     "name": "collectionOwner",
     "outputs": [
@@ -329,15 +338,6 @@
       { "internalType": "address", "name": "sponsor", "type": "address" }
     ],
     "name": "setCollectionSponsor",
-    "outputs": [],
-    "stateMutability": "nonpayable",
-    "type": "function"
-  },
-  {
-    "inputs": [
-      { "internalType": "address", "name": "newOwner", "type": "address" }
-    ],
-    "name": "setOwner",
     "outputs": [],
     "stateMutability": "nonpayable",
     "type": "function"
modifiedtests/src/eth/nesting/nest.test.tsdiffbeforeafterboth
--- a/tests/src/eth/nesting/nest.test.ts
+++ b/tests/src/eth/nesting/nest.test.ts
@@ -7,7 +7,7 @@
   helper: EthUniqueHelper,
   owner: string,
 ): Promise<{ collectionId: number, collectionAddress: string, contract: Contract }> => {
-  const {collectionAddress, collectionId} = await helper.eth.createNonfungibleCollection(owner, 'A', 'B', 'C');
+  const {collectionAddress, collectionId} = await helper.eth.createNFTCollection(owner, 'A', 'B', 'C');
 
   const contract = helper.ethNativeContract.collection(collectionAddress, 'nft', owner);
   await contract.methods.setCollectionNesting(true).send({from: owner});
@@ -29,74 +29,53 @@
     itEth('NFT: allows an Owner to nest/unnest their token', async ({helper}) => {
       const owner = await helper.eth.createAccountWithBalance(donor);
       const {collectionId, contract} = await createNestingCollection(helper, owner);
-  
-      // Create a token to be nested
-      const targetNFTTokenId = await contract.methods.nextTokenId().call();
-      await contract.methods.mint(
-        owner,
-        targetNFTTokenId,
-      ).send({from: owner});
-  
+
+      // Create a token to be nested to
+      const mintingTargetNFTTokenIdResult = await contract.methods.mint(owner).send({from: owner});
+      const targetNFTTokenId = mintingTargetNFTTokenIdResult.events.Transfer.returnValues.tokenId;
       const targetNftTokenAddress = helper.ethAddress.fromTokenId(collectionId, targetNFTTokenId);
-  
+
       // Create a nested token
-      const firstTokenId = await contract.methods.nextTokenId().call();
-      await contract.methods.mint(
-        targetNftTokenAddress,
-        firstTokenId,
-      ).send({from: owner});
-  
+      const mintingFirstTokenIdResult = await contract.methods.mint(targetNftTokenAddress).send({from: owner});
+      const firstTokenId = mintingFirstTokenIdResult.events.Transfer.returnValues.tokenId;
       expect(await contract.methods.ownerOf(firstTokenId).call()).to.be.equal(targetNftTokenAddress);
-  
+
       // Create a token to be nested and nest
-      const secondTokenId = await contract.methods.nextTokenId().call();
-      await contract.methods.mint(
-        owner,
-        secondTokenId,
-      ).send({from: owner});
-  
+      const mintingSecondTokenIdResult = await contract.methods.mint(owner).send({from: owner});
+      const secondTokenId = mintingSecondTokenIdResult.events.Transfer.returnValues.tokenId;
+
       await contract.methods.transfer(targetNftTokenAddress, secondTokenId).send({from: owner});
-  
       expect(await contract.methods.ownerOf(secondTokenId).call()).to.be.equal(targetNftTokenAddress);
-  
+
       // Unnest token back
       await contract.methods.transferFrom(targetNftTokenAddress, owner, secondTokenId).send({from: owner});
       expect(await contract.methods.ownerOf(secondTokenId).call()).to.be.equal(owner);
     });
-  
+
     itEth('NFT: allows an Owner to nest/unnest their token (Restricted nesting)', async ({helper}) => {
       const owner = await helper.eth.createAccountWithBalance(donor);
-  
+
       const {collectionId: collectionIdA, collectionAddress: collectionAddressA, contract: contractA} = await createNestingCollection(helper, owner);
       const {collectionAddress: collectionAddressB, contract: contractB} = await createNestingCollection(helper, owner);
       await contractA.methods.setCollectionNesting(true, [collectionAddressA, collectionAddressB]).send({from: owner});
-  
+
       // Create a token to nest into
-      const targetNftTokenId = await contractA.methods.nextTokenId().call();
-      await contractA.methods.mint(
-        owner,
-        targetNftTokenId,
-      ).send({from: owner});
+      const mintingtargetNftTokenIdResult = await contractA.methods.mint(owner).send({from: owner});
+      const targetNftTokenId = mintingtargetNftTokenIdResult.events.Transfer.returnValues.tokenId;
       const nftTokenAddressA1 = helper.ethAddress.fromTokenId(collectionIdA, targetNftTokenId);
-  
+
       // Create a token for nesting in the same collection as the target
-      const nftTokenIdA = await contractA.methods.nextTokenId().call();
-      await contractA.methods.mint(
-        owner,
-        nftTokenIdA,
-      ).send({from: owner});
-  
+      const mintingTokenIdAResult = await contractA.methods.mint(owner).send({from: owner});
+      const nftTokenIdA = mintingTokenIdAResult.events.Transfer.returnValues.tokenId;
+
       // Create a token for nesting in a different collection
-      const nftTokenIdB = await contractB.methods.nextTokenId().call();
-      await contractB.methods.mint(
-        owner,
-        nftTokenIdB,
-      ).send({from: owner});
-  
+      const mintingTokenIdBResult = await contractB.methods.mint(owner).send({from: owner});
+      const nftTokenIdB = mintingTokenIdBResult.events.Transfer.returnValues.tokenId;
+
       // Nest
       await contractA.methods.transfer(nftTokenAddressA1, nftTokenIdA).send({from: owner});
       expect(await contractA.methods.ownerOf(nftTokenIdA).call()).to.be.equal(nftTokenAddressA1);
-  
+
       await contractB.methods.transfer(nftTokenAddressA1, nftTokenIdB).send({from: owner});
       expect(await contractB.methods.ownerOf(nftTokenIdB).call()).to.be.equal(nftTokenAddressA1);
     });
@@ -105,112 +84,88 @@
   describe('Negative Test: EVM Nesting', async() => {
     itEth('NFT: disallows to nest token if nesting is disabled', async ({helper}) => {
       const owner = await helper.eth.createAccountWithBalance(donor);
-  
+
       const {collectionId, contract} = await createNestingCollection(helper, owner);
       await contract.methods.setCollectionNesting(false).send({from: owner});
-  
+
       // Create a token to nest into
-      const targetNftTokenId = await contract.methods.nextTokenId().call();
-      await contract.methods.mint(
-        owner,
-        targetNftTokenId,
-      ).send({from: owner});
-  
-      const targetNftTokenAddress = helper.ethAddress.fromTokenId(collectionId, targetNftTokenId);
-  
+      const mintingTargetTokenIdResult = await contract.methods.mint(owner).send({from: owner});
+      const targetTokenId = mintingTargetTokenIdResult.events.Transfer.returnValues.tokenId;
+      const targetNftTokenAddress = helper.ethAddress.fromTokenId(collectionId, targetTokenId);
+
       // Create a token to nest
-      const nftTokenId = await contract.methods.nextTokenId().call();
-      await contract.methods.mint(
-        owner,
-        nftTokenId,
-      ).send({from: owner});
-  
+      const mintingNftTokenIdResult = await contract.methods.mint(owner).send({from: owner});
+      const nftTokenId = mintingNftTokenIdResult.events.Transfer.returnValues.tokenId;
+
       // Try to nest
       await expect(contract.methods
         .transfer(targetNftTokenAddress, nftTokenId)
         .call({from: owner})).to.be.rejectedWith('UserIsNotAllowedToNest');
     });
-  
+
     itEth('NFT: disallows a non-Owner to nest someone else\'s token', async ({helper}) => {
       const owner = await helper.eth.createAccountWithBalance(donor);
       const malignant = await helper.eth.createAccountWithBalance(donor);
-  
+
       const {collectionId, contract} = await createNestingCollection(helper, owner);
-  
+
       // Mint a token
-      const targetTokenId = await contract.methods.nextTokenId().call();
-      await contract.methods.mint(
-        owner,
-        targetTokenId,
-      ).send({from: owner});
+      const mintingTargetTokenIdResult = await contract.methods.mint(owner).send({from: owner});
+      const targetTokenId = mintingTargetTokenIdResult.events.Transfer.returnValues.tokenId;
       const targetTokenAddress = helper.ethAddress.fromTokenId(collectionId, targetTokenId);
-  
+
       // Mint a token belonging to a different account
-      const tokenId = await contract.methods.nextTokenId().call();
-      await contract.methods.mint(
-        malignant,
-        tokenId,
-      ).send({from: owner});
-  
+      const mintingTokenIdResult = await contract.methods.mint(malignant).send({from: owner});
+      const tokenId = mintingTokenIdResult.events.Transfer.returnValues.tokenId;
+
       // Try to nest one token in another as a non-owner account
       await expect(contract.methods
         .transfer(targetTokenAddress, tokenId)
         .call({from: malignant})).to.be.rejectedWith('UserIsNotAllowedToNest');
     });
-  
+
     itEth('NFT: disallows a non-Owner to nest someone else\'s token (Restricted nesting)', async ({helper}) => {
       const owner = await helper.eth.createAccountWithBalance(donor);
       const malignant = await helper.eth.createAccountWithBalance(donor);
-  
+
       const {collectionId: collectionIdA, collectionAddress: collectionAddressA, contract: contractA} = await createNestingCollection(helper, owner);
       const {collectionAddress: collectionAddressB, contract: contractB} = await createNestingCollection(helper, owner);
-  
+
       await contractA.methods.setCollectionNesting(true, [collectionAddressA, collectionAddressB]).send({from: owner});
-  
+
       // Create a token in one collection
-      const nftTokenIdA = await contractA.methods.nextTokenId().call();
-      await contractA.methods.mint(
-        owner,
-        nftTokenIdA,
-      ).send({from: owner});
+      const mintingTokenIdAResult = await contractA.methods.mint(owner).send({from: owner});
+      const nftTokenIdA = mintingTokenIdAResult.events.Transfer.returnValues.tokenId;
       const nftTokenAddressA = helper.ethAddress.fromTokenId(collectionIdA, nftTokenIdA);
-  
-      // Create a token in another collection belonging to someone else
-      const nftTokenIdB = await contractB.methods.nextTokenId().call();
-      await contractB.methods.mint(
-        malignant,
-        nftTokenIdB,
-      ).send({from: owner});
-  
+
+      // Create a token in another collection
+      const mintingTokenIdBResult = await contractB.methods.mint(malignant).send({from: owner});
+      const nftTokenIdB = mintingTokenIdBResult.events.Transfer.returnValues.tokenId;
+
       // Try to drag someone else's token into the other collection and nest
       await expect(contractB.methods
         .transfer(nftTokenAddressA, nftTokenIdB)
         .call({from: malignant})).to.be.rejectedWith('UserIsNotAllowedToNest');
     });
-  
+
     itEth('NFT: disallows to nest token in an unlisted collection', async ({helper}) => {
       const owner = await helper.eth.createAccountWithBalance(donor);
-  
+
       const {collectionId: collectionIdA, collectionAddress: collectionAddressA, contract: contractA} = await createNestingCollection(helper, owner);
       const {contract: contractB} = await createNestingCollection(helper, owner);
-  
+
       await contractA.methods.setCollectionNesting(true, [collectionAddressA]).send({from: owner});
-  
+
       // Create a token in one collection
-      const nftTokenIdA = await contractA.methods.nextTokenId().call();
-      await contractA.methods.mint(
-        owner,
-        nftTokenIdA,
-      ).send({from: owner});
+      const mintingTokenIdAResult = await contractA.methods.mint(owner).send({from: owner});
+      const nftTokenIdA = mintingTokenIdAResult.events.Transfer.returnValues.tokenId;
       const nftTokenAddressA = helper.ethAddress.fromTokenId(collectionIdA, nftTokenIdA);
-  
+
       // Create a token in another collection
-      const nftTokenIdB = await contractB.methods.nextTokenId().call();
-      await contractB.methods.mint(
-        owner,
-        nftTokenIdB,
-      ).send({from: owner});
-  
+      const mintingTokenIdBResult = await contractB.methods.mint(owner).send({from: owner});
+      const nftTokenIdB = mintingTokenIdBResult.events.Transfer.returnValues.tokenId;
+
+
       // Try to nest into a token in the other collection, disallowed in the first
       await expect(contractB.methods
         .transfer(nftTokenAddressA, nftTokenIdB)
modifiedtests/src/eth/nonFungible.test.tsdiffbeforeafterboth
--- a/tests/src/eth/nonFungible.test.ts
+++ b/tests/src/eth/nonFungible.test.ts
@@ -29,7 +29,7 @@
       [alice] = await helper.arrange.createAccounts([10n], donor);
     });
   });
-  
+
   itEth('totalSupply', async ({helper}) => {
     const collection = await helper.nft.mintCollection(alice, {});
     await collection.mintToken(alice);
@@ -68,6 +68,16 @@
 
     expect(owner).to.equal(caller);
   });
+
+  itEth('name/symbol is available regardless of ERC721Metadata support', async ({helper}) => {
+    const collection = await helper.nft.mintCollection(alice, {name: 'test', tokenPrefix: 'TEST'});
+    const caller = helper.eth.createAccount();
+
+    const contract = helper.ethNativeContract.collectionById(collection.collectionId, 'nft', caller);
+
+    expect(await contract.methods.name().call()).to.equal('test');
+    expect(await contract.methods.symbol().call()).to.equal('TEST');
+  });
 });
 
 describe('Check ERC721 token URI for NFT', () => {
@@ -79,34 +89,29 @@
     });
   });
 
-  async function setup(helper: EthUniqueHelper, tokenPrefix: string, propertyKey?: string, propertyValue?: string): Promise<{contract: Contract, nextTokenId: string}> {
+  async function setup(helper: EthUniqueHelper, baseUri: string, propertyKey?: string, propertyValue?: string): Promise<{contract: Contract, nextTokenId: string}> {
     const owner = await helper.eth.createAccountWithBalance(donor);
     const receiver = helper.eth.createAccount();
 
-    const collectionHelper = helper.ethNativeContract.collectionHelpers(owner);
-    let result = await collectionHelper.methods.createERC721MetadataCompatibleCollection('Mint collection', 'a', 'b', tokenPrefix).send({value: Number(2n * helper.balance.getOneTokenNominal())});
-    const collectionAddress = helper.ethAddress.normalizeAddress(result.events.CollectionCreated.returnValues.collectionId);
+    const {collectionAddress} = await helper.eth.createERC721MetadataCompatibleNFTCollection(owner, 'Mint collection', 'a', 'b', baseUri);
     const contract = helper.ethNativeContract.collection(collectionAddress, 'nft', owner);
-    
-    const nextTokenId = await contract.methods.nextTokenId().call();
-    expect(nextTokenId).to.be.equal('1');
-    result = await contract.methods.mint(
-      receiver,
-      nextTokenId,
-    ).send();
 
+    const result = await contract.methods.mint(receiver).send();
+    const tokenId = result.events.Transfer.returnValues.tokenId;
+    expect(tokenId).to.be.equal('1');
+
     if (propertyKey && propertyValue) {
       // Set URL or suffix
-      await contract.methods.setProperty(nextTokenId, propertyKey, Buffer.from(propertyValue)).send();
+      await contract.methods.setProperty(tokenId, propertyKey, Buffer.from(propertyValue)).send();
     }
 
     const event = result.events.Transfer;
     expect(event.address).to.be.equal(collectionAddress);
     expect(event.returnValues.from).to.be.equal('0x0000000000000000000000000000000000000000');
     expect(event.returnValues.to).to.be.equal(receiver);
-    expect(event.returnValues.tokenId).to.be.equal(nextTokenId);
+    expect(event.returnValues.tokenId).to.be.equal(tokenId);
 
-    return {contract, nextTokenId};
+    return {contract, nextTokenId: tokenId};
   }
 
   itEth('Empty tokenURI', async ({helper}) => {
@@ -115,18 +120,18 @@
   });
 
   itEth('TokenURI from url', async ({helper}) => {
-    const {contract, nextTokenId} = await setup(helper, 'BaseURI_', 'url', 'Token URI');
+    const {contract, nextTokenId} = await setup(helper, 'BaseURI_', 'URI', 'Token URI');
     expect(await contract.methods.tokenURI(nextTokenId).call()).to.be.equal('Token URI');
   });
 
-  itEth('TokenURI from baseURI + tokenId', async ({helper}) => {
+  itEth('TokenURI from baseURI', async ({helper}) => {
     const {contract, nextTokenId} = await setup(helper, 'BaseURI_');
-    expect(await contract.methods.tokenURI(nextTokenId).call()).to.be.equal('BaseURI_' + nextTokenId);
+    expect(await contract.methods.tokenURI(nextTokenId).call()).to.be.equal('BaseURI_');
   });
 
   itEth('TokenURI from baseURI + suffix', async ({helper}) => {
     const suffix = '/some/suffix';
-    const {contract, nextTokenId} = await setup(helper, 'BaseURI_', 'suffix', suffix);
+    const {contract, nextTokenId} = await setup(helper, 'BaseURI_', 'URISuffix', suffix);
     expect(await contract.methods.tokenURI(nextTokenId).call()).to.be.equal('BaseURI_' + suffix);
   });
 });
@@ -146,24 +151,19 @@
     const owner = await helper.eth.createAccountWithBalance(donor);
     const receiver = helper.eth.createAccount();
 
-    const {collectionAddress} = await helper.eth.createNonfungibleCollection(owner, 'Minty', '6', '6');
+    const {collectionAddress} = await helper.eth.createERC721MetadataCompatibleNFTCollection(owner, 'Mint collection', '6', '6', '');
     const contract = helper.ethNativeContract.collection(collectionAddress, 'nft', owner);
-    const nextTokenId = await contract.methods.nextTokenId().call();
 
-    expect(nextTokenId).to.be.equal('1');
-    const result = await contract.methods.mintWithTokenURI(
-      receiver,
-      nextTokenId,
-      'Test URI',
-    ).send();
+    const result = await contract.methods.mintWithTokenURI(receiver, 'Test URI').send();
+    const tokenId = result.events.Transfer.returnValues.tokenId;
+    expect(tokenId).to.be.equal('1');
 
     const event = result.events.Transfer;
     expect(event.address).to.be.equal(collectionAddress);
     expect(event.returnValues.from).to.be.equal('0x0000000000000000000000000000000000000000');
     expect(event.returnValues.to).to.be.equal(receiver);
-    expect(event.returnValues.tokenId).to.be.equal(nextTokenId);
 
-    expect(await contract.methods.tokenURI(nextTokenId).call()).to.be.equal('Test URI');
+    expect(await contract.methods.tokenURI(tokenId).call()).to.be.equal('Test URI');
 
     // TODO: this wont work right now, need release 919000 first
     // await helper.methods.setOffchainSchema(collectionIdAddress, 'https://offchain-service.local/token-info/{id}').send();
@@ -216,7 +216,7 @@
 
     {
       const result = await contract.methods.burn(tokenId).send({from: caller});
-      
+
       const event = result.events.Transfer;
       expect(event.address).to.be.equal(collectionAddress);
       expect(event.returnValues.from).to.be.equal(caller);
@@ -322,7 +322,7 @@
       [alice] = await helper.arrange.createAccounts([10n], donor);
     });
   });
-  
+
   itEth('approve() call fee is less than 0.2UNQ', async ({helper}) => {
     const owner = await helper.eth.createAccountWithBalance(donor);
     const spender = helper.eth.createAccount();
@@ -403,7 +403,7 @@
 
     const collectionAddress = helper.ethAddress.fromCollectionId(collection.collectionId);
     const contract = helper.ethNativeContract.collection(collectionAddress, 'nft');
-    
+
     const events: any = [];
     contract.events.allEvents((_: any, event: any) => {
       events.push(event);
@@ -428,7 +428,7 @@
 
     const collectionAddress = helper.ethAddress.fromCollectionId(collection.collectionId);
     const contract = helper.ethNativeContract.collection(collectionAddress, 'nft');
-    
+
     const events: any = [];
     contract.events.allEvents((_: any, event: any) => {
       events.push(event);
@@ -455,13 +455,14 @@
 
     const collectionAddress = helper.ethAddress.fromCollectionId(collection.collectionId);
     const contract = helper.ethNativeContract.collection(collectionAddress, 'nft');
-    
+
     const events: any = [];
     contract.events.allEvents((_: any, event: any) => {
       events.push(event);
     });
 
     await token.transferFrom(bob, {Substrate: alice.address}, {Ethereum: receiver});
+
     if (events.length == 0) await helper.wait.newBlocks(1);
     const event = events[0];
 
@@ -479,13 +480,14 @@
 
     const collectionAddress = helper.ethAddress.fromCollectionId(collection.collectionId);
     const contract = helper.ethNativeContract.collection(collectionAddress, 'nft');
-    
+
     const events: any = [];
     contract.events.allEvents((_: any, event: any) => {
       events.push(event);
     });
 
     await token.transfer(alice, {Ethereum: receiver});
+
     if (events.length == 0) await helper.wait.newBlocks(1);
     const event = events[0];
 
@@ -509,7 +511,23 @@
 
   itEth('Returns collection name', async ({helper}) => {
     const caller = await helper.eth.createAccountWithBalance(donor);
-    const collection = await helper.nft.mintCollection(alice, {name: 'oh River', tokenPrefix: 'CHANGE'});
+    const tokenPropertyPermissions = [{
+      key: 'URI',
+      permission: {
+        mutable: true,
+        collectionAdmin: true,
+        tokenOwner: false,
+      },
+    }];
+    const collection = await helper.nft.mintCollection(
+      alice,
+      {
+        name: 'oh River',
+        tokenPrefix: 'CHANGE',
+        properties: [{key: 'ERC721Metadata', value: '1'}],
+        tokenPropertyPermissions,
+      },
+    );
 
     const contract = helper.ethNativeContract.collectionById(collection.collectionId, 'nft', caller);
     const name = await contract.methods.name().call();
@@ -518,10 +536,26 @@
 
   itEth('Returns symbol name', async ({helper}) => {
     const caller = await helper.eth.createAccountWithBalance(donor);
-    const collection = await helper.nft.mintCollection(alice, {name: 'oh River', tokenPrefix: 'CHANGE'});
+    const tokenPropertyPermissions = [{
+      key: 'URI',
+      permission: {
+        mutable: true,
+        collectionAdmin: true,
+        tokenOwner: false,
+      },
+    }];
+    const collection = await helper.nft.mintCollection(
+      alice,
+      {
+        name: 'oh River',
+        tokenPrefix: 'CHANGE',
+        properties: [{key: 'ERC721Metadata', value: '1'}],
+        tokenPropertyPermissions,
+      },
+    );
 
     const contract = helper.ethNativeContract.collectionById(collection.collectionId, 'nft', caller);
     const symbol = await contract.methods.symbol().call();
     expect(symbol).to.equal('CHANGE');
   });
-});
\ No newline at end of file
+});
modifiedtests/src/eth/nonFungibleAbi.jsondiffbeforeafterboth
--- a/tests/src/eth/nonFungibleAbi.json
+++ b/tests/src/eth/nonFungibleAbi.json
@@ -146,6 +146,15 @@
     "type": "function"
   },
   {
+    "inputs": [
+      { "internalType": "address", "name": "newOwner", "type": "address" }
+    ],
+    "name": "changeCollectionOwner",
+    "outputs": [],
+    "stateMutability": "nonpayable",
+    "type": "function"
+  },
+  {
     "inputs": [],
     "name": "collectionOwner",
     "outputs": [
@@ -260,12 +269,9 @@
     "type": "function"
   },
   {
-    "inputs": [
-      { "internalType": "address", "name": "to", "type": "address" },
-      { "internalType": "uint256", "name": "tokenId", "type": "uint256" }
-    ],
+    "inputs": [{ "internalType": "address", "name": "to", "type": "address" }],
     "name": "mint",
-    "outputs": [{ "internalType": "bool", "name": "", "type": "bool" }],
+    "outputs": [{ "internalType": "uint256", "name": "", "type": "uint256" }],
     "stateMutability": "nonpayable",
     "type": "function"
   },
@@ -287,7 +293,7 @@
           { "internalType": "uint256", "name": "field_0", "type": "uint256" },
           { "internalType": "string", "name": "field_1", "type": "string" }
         ],
-        "internalType": "struct Tuple8[]",
+        "internalType": "struct Tuple6[]",
         "name": "tokens",
         "type": "tuple[]"
       }
@@ -300,11 +306,10 @@
   {
     "inputs": [
       { "internalType": "address", "name": "to", "type": "address" },
-      { "internalType": "uint256", "name": "tokenId", "type": "uint256" },
       { "internalType": "string", "name": "tokenUri", "type": "string" }
     ],
     "name": "mintWithTokenURI",
-    "outputs": [{ "internalType": "bool", "name": "", "type": "bool" }],
+    "outputs": [{ "internalType": "uint256", "name": "", "type": "uint256" }],
     "stateMutability": "nonpayable",
     "type": "function"
   },
@@ -476,15 +481,6 @@
       { "internalType": "address", "name": "sponsor", "type": "address" }
     ],
     "name": "setCollectionSponsor",
-    "outputs": [],
-    "stateMutability": "nonpayable",
-    "type": "function"
-  },
-  {
-    "inputs": [
-      { "internalType": "address", "name": "newOwner", "type": "address" }
-    ],
-    "name": "setOwner",
     "outputs": [],
     "stateMutability": "nonpayable",
     "type": "function"
modifiedtests/src/eth/payable.test.tsdiffbeforeafterboth
--- a/tests/src/eth/payable.test.ts
+++ b/tests/src/eth/payable.test.ts
@@ -118,7 +118,7 @@
     const deployer = await helper.eth.createAccountWithBalance(donor);
     const caller = await helper.eth.createAccountWithBalance(donor);
     const contract = await helper.eth.deployFlipper(deployer);
-    
+
     const initialCallerBalance = await helper.balance.getEthereum(caller);
     await contract.methods.flip().send({from: caller});
     const finalCallerBalance = await helper.balance.getEthereum(caller);
@@ -129,7 +129,7 @@
     const deployer = await helper.eth.createAccountWithBalance(donor);
     const caller = await helper.eth.createAccountWithBalance(donor);
     const contract = await deployProxyContract(helper, deployer);
-    
+
     const initialCallerBalance = await helper.balance.getEthereum(caller);
     const initialContractBalance = await helper.balance.getEthereum(contract.options.address);
     await contract.methods.flip().send({from: caller});
@@ -138,7 +138,7 @@
     expect(finalCallerBalance < initialCallerBalance).to.be.true;
     expect(finalContractBalance == initialContractBalance).to.be.true;
   });
-  
+
   itEth('Fee for nested calls to native methods is withdrawn from the user', async({helper}) => {
     const CONTRACT_BALANCE = 2n * helper.balance.getOneTokenNominal();
 
@@ -146,7 +146,7 @@
     const caller = await helper.eth.createAccountWithBalance(donor);
     const contract = await deployProxyContract(helper, deployer);
 
-    const collectionAddress = (await contract.methods.createNonfungibleCollection().send({from: caller, value: Number(CONTRACT_BALANCE)})).events.CollectionCreated.returnValues.collection;
+    const collectionAddress = (await contract.methods.createNFTCollection().send({from: caller, value: Number(CONTRACT_BALANCE)})).events.CollectionCreated.returnValues.collection;
     const initialCallerBalance = await helper.balance.getEthereum(caller);
     const initialContractBalance = await helper.balance.getEthereum(contract.options.address);
     await contract.methods.mintNftToken(collectionAddress).send({from: caller});
@@ -155,7 +155,7 @@
     expect(finalCallerBalance < initialCallerBalance).to.be.true;
     expect(finalContractBalance == initialContractBalance).to.be.true;
   });
-  
+
   itEth('Fee for nested calls to create*Collection methods is withdrawn from the user and from the contract', async({helper}) => {
     const CONTRACT_BALANCE = 2n * helper.balance.getOneTokenNominal();
     const deployer = await helper.eth.createAccountWithBalance(donor);
@@ -164,7 +164,7 @@
 
     const initialCallerBalance = await helper.balance.getEthereum(caller);
     const initialContractBalance = await helper.balance.getEthereum(contract.options.address);
-    await contract.methods.createNonfungibleCollection().send({from: caller, value: Number(CONTRACT_BALANCE)});
+    await contract.methods.createNFTCollection().send({from: caller, value: Number(CONTRACT_BALANCE)});
     const finalCallerBalance = await helper.balance.getEthereum(caller);
     const finalContractBalance = await helper.balance.getEthereum(contract.options.address);
     expect(finalCallerBalance < initialCallerBalance).to.be.true;
@@ -176,9 +176,9 @@
     const BIG_FEE = 3n * helper.balance.getOneTokenNominal();
     const caller = await helper.eth.createAccountWithBalance(donor);
     const collectionHelper = helper.ethNativeContract.collectionHelpers(caller);
-        
-    await expect(collectionHelper.methods.createNonfungibleCollection('A', 'B', 'C').call({value: Number(SMALL_FEE)})).to.be.rejectedWith('Sent amount not equals to collection creation price (2000000000000000000)');
-    await expect(collectionHelper.methods.createNonfungibleCollection('A', 'B', 'C').call({value: Number(BIG_FEE)})).to.be.rejectedWith('Sent amount not equals to collection creation price (2000000000000000000)');
+
+    await expect(collectionHelper.methods.createNFTCollection('A', 'B', 'C').call({value: Number(SMALL_FEE)})).to.be.rejectedWith('Sent amount not equals to collection creation price (2000000000000000000)');
+    await expect(collectionHelper.methods.createNFTCollection('A', 'B', 'C').call({value: Number(BIG_FEE)})).to.be.rejectedWith('Sent amount not equals to collection creation price (2000000000000000000)');
   });
 
   itEth('Negative test: call createRFTCollection with wrong fee', async({helper}) => {
@@ -186,7 +186,7 @@
     const BIG_FEE = 3n * helper.balance.getOneTokenNominal();
     const caller = await helper.eth.createAccountWithBalance(donor);
     const collectionHelper = helper.ethNativeContract.collectionHelpers(caller);
-        
+
     await expect(collectionHelper.methods.createRFTCollection('A', 'B', 'C').call({value: Number(SMALL_FEE)})).to.be.rejectedWith('Sent amount not equals to collection creation price (2000000000000000000)');
     await expect(collectionHelper.methods.createRFTCollection('A', 'B', 'C').call({value: Number(BIG_FEE)})).to.be.rejectedWith('Sent amount not equals to collection creation price (2000000000000000000)');
   });
@@ -227,16 +227,15 @@
           InnerContract(innerContract).flip();
         }
 
-        function createNonfungibleCollection() external payable {
+        function createNFTCollection() external payable {
           address collectionHelpers = 0x6C4E9fE1AE37a41E93CEE429e8E1881aBdcbb54F;
-		      address nftCollection = CollectionHelpers(collectionHelpers).createNonfungibleCollection{value: msg.value}("A", "B", "C");
+		      address nftCollection = CollectionHelpers(collectionHelpers).createNFTCollection{value: msg.value}("A", "B", "C");
           emit CollectionCreated(nftCollection);
         }
 
         function mintNftToken(address collectionAddress) external  {
           UniqueNFT collection = UniqueNFT(collectionAddress);
-          uint256 tokenId = collection.nextTokenId();
-          collection.mint(msg.sender, tokenId);
+          uint256 tokenId = collection.mint(msg.sender);
           emit TokenMinted(tokenId);
         }
 
modifiedtests/src/eth/proxy/UniqueNFTProxy.soldiffbeforeafterboth
--- a/tests/src/eth/proxy/UniqueNFTProxy.sol
+++ b/tests/src/eth/proxy/UniqueNFTProxy.sol
@@ -120,20 +120,19 @@
         return proxied.mintingFinished();
     }
 
-    function mint(address to, uint256 tokenId)
+    function mint(address to)
         external
         override
-        returns (bool)
+        returns (uint256)
     {
-        return proxied.mint(to, tokenId);
+        return proxied.mint(to);
     }
 
     function mintWithTokenURI(
         address to,
-        uint256 tokenId,
         string memory tokenUri
-    ) external override returns (bool) {
-        return proxied.mintWithTokenURI(to, tokenId, tokenUri);
+    ) external override returns (uint256) {
+        return proxied.mintWithTokenURI(to, tokenUri);
     }
 
     function finishMinting() external override returns (bool) {
@@ -169,7 +168,7 @@
         return proxied.mintBulk(to, tokenIds);
     }
 
-    function mintBulkWithTokenURI(address to, Tuple0[] memory tokens)
+    function mintBulkWithTokenURI(address to, Tuple6[] memory tokens)
         external
         override
         returns (bool)
modifiedtests/src/eth/proxy/nonFungibleProxy.test.tsdiffbeforeafterboth
--- a/tests/src/eth/proxy/nonFungibleProxy.test.ts
+++ b/tests/src/eth/proxy/nonFungibleProxy.test.ts
@@ -101,7 +101,7 @@
 
   itEth('Can perform mint()', async ({helper}) => {
     const owner = await helper.eth.createAccountWithBalance(donor);
-    const {collectionAddress} = await helper.eth.createNonfungibleCollection(owner, 'A', 'A', 'A');
+    const {collectionAddress} = await helper.eth.createERC721MetadataCompatibleNFTCollection(owner, 'A', 'A', 'A', '');
     const caller = await helper.eth.createAccountWithBalance(donor);
     const receiver = helper.eth.createAccount();
 
@@ -111,13 +111,11 @@
     await collectionEvmOwned.methods.addCollectionAdmin(contract.options.address).send();
 
     {
-      const nextTokenId = await contract.methods.nextTokenId().call();
-      expect(nextTokenId).to.be.equal('1');
-      const result = await contract.methods.mintWithTokenURI(
-        receiver,
-        nextTokenId,
-        'Test URI',
-      ).send({from: caller});
+      const nextTokenId = await contract.methods.nextTokenId().call()
+      const result = await contract.methods.mintWithTokenURI(receiver, nextTokenId, 'Test URI').send({from: caller});
+      const tokenId = result.events.Transfer.returnValues.tokenId;
+      expect(tokenId).to.be.equal('1');
+
       const events = helper.eth.normalizeEvents(result.events);
       events[0].address = events[0].address.toLocaleLowerCase();
 
@@ -128,12 +126,12 @@
           args: {
             from: '0x0000000000000000000000000000000000000000',
             to: receiver,
-            tokenId: nextTokenId,
+            tokenId,
           },
         },
       ]);
 
-      expect(await contract.methods.tokenURI(nextTokenId).call()).to.be.equal('Test URI');
+      expect(await contract.methods.tokenURI(tokenId).call()).to.be.equal('Test URI');
     }
   });
 
modifiedtests/src/eth/reFungible.test.tsdiffbeforeafterboth
--- a/tests/src/eth/reFungible.test.ts
+++ b/tests/src/eth/reFungible.test.ts
@@ -31,31 +31,23 @@
 
   itEth('totalSupply', async ({helper}) => {
     const caller = await helper.eth.createAccountWithBalance(donor);
-    const {collectionAddress} = await helper.eth.createRefungibleCollection(caller, 'TotalSupply', '6', '6');
+    const {collectionAddress} = await helper.eth.createRFTCollection(caller, 'TotalSupply', '6', '6');
     const contract = helper.ethNativeContract.collection(collectionAddress, 'rft', caller);
-    const nextTokenId = await contract.methods.nextTokenId().call();
-    await contract.methods.mint(caller, nextTokenId).send();
+
+    await contract.methods.mint(caller).send();
+
     const totalSupply = await contract.methods.totalSupply().call();
     expect(totalSupply).to.equal('1');
   });
 
   itEth('balanceOf', async ({helper}) => {
     const caller = await helper.eth.createAccountWithBalance(donor);
-    const {collectionAddress} = await helper.eth.createRefungibleCollection(caller, 'BalanceOf', '6', '6');
+    const {collectionAddress} = await helper.eth.createRFTCollection(caller, 'BalanceOf', '6', '6');
     const contract = helper.ethNativeContract.collection(collectionAddress, 'rft', caller);
 
-    {
-      const nextTokenId = await contract.methods.nextTokenId().call();
-      await contract.methods.mint(caller, nextTokenId).send();
-    }
-    {
-      const nextTokenId = await contract.methods.nextTokenId().call();
-      await contract.methods.mint(caller, nextTokenId).send();
-    }
-    {
-      const nextTokenId = await contract.methods.nextTokenId().call();
-      await contract.methods.mint(caller, nextTokenId).send();
-    }
+    await contract.methods.mint(caller).send();
+    await contract.methods.mint(caller).send();
+    await contract.methods.mint(caller).send();
 
     const balance = await contract.methods.balanceOf(caller).call();
     expect(balance).to.equal('3');
@@ -63,11 +55,11 @@
 
   itEth('ownerOf', async ({helper}) => {
     const caller = await helper.eth.createAccountWithBalance(donor);
-    const {collectionAddress} = await helper.eth.createRefungibleCollection(caller, 'OwnerOf', '6', '6');
+    const {collectionAddress} = await helper.eth.createRFTCollection(caller, 'OwnerOf', '6', '6');
     const contract = helper.ethNativeContract.collection(collectionAddress, 'rft', caller);
 
-    const tokenId = await contract.methods.nextTokenId().call();
-    await contract.methods.mint(caller, tokenId).send();
+    const result = await contract.methods.mint(caller).send();
+    const tokenId = result.events.Transfer.returnValues.tokenId;
 
     const owner = await contract.methods.ownerOf(tokenId).call();
     expect(owner).to.equal(caller);
@@ -76,11 +68,11 @@
   itEth('ownerOf after burn', async ({helper}) => {
     const caller = await helper.eth.createAccountWithBalance(donor);
     const receiver = helper.eth.createAccount();
-    const {collectionId, collectionAddress} = await helper.eth.createRefungibleCollection(caller, 'OwnerOf-AfterBurn', '6', '6');
+    const {collectionId, collectionAddress} = await helper.eth.createRFTCollection(caller, 'OwnerOf-AfterBurn', '6', '6');
     const contract = helper.ethNativeContract.collection(collectionAddress, 'rft', caller);
 
-    const tokenId = await contract.methods.nextTokenId().call();
-    await contract.methods.mint(caller, tokenId).send();
+    const result = await contract.methods.mint(caller).send();
+    const tokenId = result.events.Transfer.returnValues.tokenId;
     const tokenContract = helper.ethNativeContract.rftTokenById(collectionId, tokenId, caller);
 
     await tokenContract.methods.repartition(2).send();
@@ -95,11 +87,11 @@
   itEth('ownerOf for partial ownership', async ({helper}) => {
     const caller = await helper.eth.createAccountWithBalance(donor);
     const receiver = helper.eth.createAccount();
-    const {collectionId, collectionAddress} = await helper.eth.createRefungibleCollection(caller, 'Partial-OwnerOf', '6', '6');
+    const {collectionId, collectionAddress} = await helper.eth.createRFTCollection(caller, 'Partial-OwnerOf', '6', '6');
     const contract = helper.ethNativeContract.collection(collectionAddress, 'rft', caller);
 
-    const tokenId = await contract.methods.nextTokenId().call();
-    await contract.methods.mint(caller, tokenId).send();
+    const result = await contract.methods.mint(caller).send();
+    const tokenId = result.events.Transfer.returnValues.tokenId;
     const tokenContract = helper.ethNativeContract.rftTokenById(collectionId, tokenId, caller);
 
     await tokenContract.methods.repartition(2).send();
@@ -124,30 +116,25 @@
   itEth('Can perform mint()', async ({helper}) => {
     const owner = await helper.eth.createAccountWithBalance(donor);
     const receiver = helper.eth.createAccount();
-    const {collectionAddress} = await helper.eth.createRefungibleCollection(owner, 'Minty', '6', '6');
+    const {collectionAddress} = await helper.eth.createERC721MetadataCompatibleRFTCollection(owner, 'Minty', '6', '6', '');
     const contract = helper.ethNativeContract.collection(collectionAddress, 'rft', owner);
-    
-    const nextTokenId = await contract.methods.nextTokenId().call();
-    expect(nextTokenId).to.be.equal('1');
-    const result = await contract.methods.mintWithTokenURI(
-      receiver,
-      nextTokenId,
-      'Test URI',
-    ).send();
 
+    const result = await contract.methods.mintWithTokenURI(receiver, 'Test URI').send();
+
     const event = result.events.Transfer;
     expect(event.address).to.equal(collectionAddress);
     expect(event.returnValues.from).to.equal('0x0000000000000000000000000000000000000000');
     expect(event.returnValues.to).to.equal(receiver);
-    expect(event.returnValues.tokenId).to.equal(nextTokenId);
+    const tokenId = event.returnValues.tokenId;
+    expect(tokenId).to.be.equal('1');
 
-    expect(await contract.methods.tokenURI(nextTokenId).call()).to.be.equal('Test URI');
+    expect(await contract.methods.tokenURI(tokenId).call()).to.be.equal('Test URI');
   });
 
   itEth('Can perform mintBulk()', async ({helper}) => {
     const owner = await helper.eth.createAccountWithBalance(donor);
     const receiver = helper.eth.createAccount();
-    const {collectionAddress} = await helper.eth.createRefungibleCollection(owner, 'MintBulky', '6', '6');
+    const {collectionAddress} = await helper.eth.createERC721MetadataCompatibleRFTCollection(owner, 'MintBulky', '6', '6', '');
     const contract = helper.ethNativeContract.collection(collectionAddress, 'rft', owner);
 
     {
@@ -179,11 +166,11 @@
 
   itEth('Can perform burn()', async ({helper}) => {
     const caller = await helper.eth.createAccountWithBalance(donor);
-    const {collectionAddress} = await helper.eth.createRefungibleCollection(caller, 'Burny', '6', '6');
+    const {collectionAddress} = await helper.eth.createRFTCollection(caller, 'Burny', '6', '6');
     const contract = helper.ethNativeContract.collection(collectionAddress, 'rft', caller);
 
-    const tokenId = await contract.methods.nextTokenId().call();
-    await contract.methods.mint(caller, tokenId).send();
+    const result = await contract.methods.mint(caller).send();
+    const tokenId = result.events.Transfer.returnValues.tokenId;
     {
       const result = await contract.methods.burn(tokenId).send();
       const event = result.events.Transfer;
@@ -197,12 +184,13 @@
   itEth('Can perform transferFrom()', async ({helper}) => {
     const caller = await helper.eth.createAccountWithBalance(donor);
     const receiver = helper.eth.createAccount();
-    const {collectionId, collectionAddress} = await helper.eth.createRefungibleCollection(caller, 'TransferFromy', '6', '6');
+    const {collectionId, collectionAddress} = await helper.eth.createRFTCollection(caller, 'TransferFromy', '6', '6');
     const contract = helper.ethNativeContract.collection(collectionAddress, 'rft', caller);
 
-    const tokenId = await contract.methods.nextTokenId().call();
+    const result = await contract.methods.mint(caller).send();
+    const tokenId = result.events.Transfer.returnValues.tokenId;
+
     const tokenAddress = helper.ethAddress.fromTokenId(collectionId, tokenId);
-    await contract.methods.mint(caller, tokenId).send();
 
     const tokenContract = helper.ethNativeContract.rftToken(tokenAddress, caller);
     await tokenContract.methods.repartition(15).send();
@@ -241,15 +229,15 @@
   itEth('Can perform transfer()', async ({helper}) => {
     const caller = await helper.eth.createAccountWithBalance(donor);
     const receiver = helper.eth.createAccount();
-    const {collectionAddress} = await helper.eth.createRefungibleCollection(caller, 'Transferry', '6', '6');
+    const {collectionAddress} = await helper.eth.createRFTCollection(caller, 'Transferry', '6', '6');
     const contract = helper.ethNativeContract.collection(collectionAddress, 'rft', caller);
 
-    const tokenId = await contract.methods.nextTokenId().call();
-    await contract.methods.mint(caller, tokenId).send();
+    const result = await contract.methods.mint(caller).send();
+    const tokenId = result.events.Transfer.returnValues.tokenId;
 
     {
       const result = await contract.methods.transfer(receiver, tokenId).send();
-      
+
       const event = result.events.Transfer;
       expect(event.address).to.equal(collectionAddress);
       expect(event.returnValues.from).to.equal(caller);
@@ -271,11 +259,11 @@
   itEth('transfer event on transfer from partial ownership to full ownership', async ({helper}) => {
     const caller = await helper.eth.createAccountWithBalance(donor);
     const receiver = helper.eth.createAccount();
-    const {collectionId, collectionAddress} = await helper.eth.createRefungibleCollection(caller, 'Transferry-Partial-to-Full', '6', '6');
+    const {collectionId, collectionAddress} = await helper.eth.createRFTCollection(caller, 'Transferry-Partial-to-Full', '6', '6');
     const contract = helper.ethNativeContract.collection(collectionAddress, 'rft', caller);
 
-    const tokenId = await contract.methods.nextTokenId().call();
-    await contract.methods.mint(caller, tokenId).send();
+    const result = await contract.methods.mint(caller).send();
+    const tokenId = result.events.Transfer.returnValues.tokenId;
 
     const tokenContract = helper.ethNativeContract.rftTokenById(collectionId, tokenId, caller);
 
@@ -300,11 +288,11 @@
   itEth('transfer event on transfer from full ownership to partial ownership', async ({helper}) => {
     const caller = await helper.eth.createAccountWithBalance(donor);
     const receiver = helper.eth.createAccount();
-    const {collectionId, collectionAddress} = await helper.eth.createRefungibleCollection(caller, 'Transferry-Full-to-Partial', '6', '6');
+    const {collectionId, collectionAddress} = await helper.eth.createRFTCollection(caller, 'Transferry-Full-to-Partial', '6', '6');
     const contract = helper.ethNativeContract.collection(collectionAddress, 'rft', caller);
 
-    const tokenId = await contract.methods.nextTokenId().call();
-    await contract.methods.mint(caller, tokenId).send();
+    const result = await contract.methods.mint(caller).send();
+    const tokenId = result.events.Transfer.returnValues.tokenId;
 
     const tokenContract = helper.ethNativeContract.rftTokenById(collectionId, tokenId, caller);
 
@@ -340,11 +328,11 @@
   itEth('transferFrom() call fee is less than 0.2UNQ', async ({helper}) => {
     const caller = await helper.eth.createAccountWithBalance(donor);
     const receiver = helper.eth.createAccount();
-    const {collectionAddress} = await helper.eth.createRefungibleCollection(caller, 'Feeful-Transfer-From', '6', '6');
+    const {collectionAddress} = await helper.eth.createRFTCollection(caller, 'Feeful-Transfer-From', '6', '6');
     const contract = helper.ethNativeContract.collection(collectionAddress, 'rft', caller);
 
-    const tokenId = await contract.methods.nextTokenId().call();
-    await contract.methods.mint(caller, tokenId).send();
+    const result = await contract.methods.mint(caller).send();
+    const tokenId = result.events.Transfer.returnValues.tokenId;
 
     const cost = await helper.eth.recordCallFee(caller, () => contract.methods.transferFrom(caller, receiver, tokenId).send());
     expect(cost < BigInt(0.2 * Number(helper.balance.getOneTokenNominal())));
@@ -354,11 +342,11 @@
   itEth('transfer() call fee is less than 0.2UNQ', async ({helper}) => {
     const caller = await helper.eth.createAccountWithBalance(donor);
     const receiver = helper.eth.createAccount();
-    const {collectionAddress} = await helper.eth.createRefungibleCollection(caller, 'Feeful-Transfer', '6', '6');
+    const {collectionAddress} = await helper.eth.createRFTCollection(caller, 'Feeful-Transfer', '6', '6');
     const contract = helper.ethNativeContract.collection(collectionAddress, 'rft', caller);
 
-    const tokenId = await contract.methods.nextTokenId().call();
-    await contract.methods.mint(caller, tokenId).send();
+    const result = await contract.methods.mint(caller).send();
+    const tokenId = result.events.Transfer.returnValues.tokenId;
 
     const cost = await helper.eth.recordCallFee(caller, () => contract.methods.transfer(receiver, tokenId).send());
     expect(cost < BigInt(0.2 * Number(helper.balance.getOneTokenNominal())));
@@ -381,8 +369,24 @@
 
   itEth('Returns collection name', async ({helper}) => {
     const caller = helper.eth.createAccount();
-    const collection = await helper.rft.mintCollection(alice, {name: 'Leviathan', tokenPrefix: '11'});
-    
+    const tokenPropertyPermissions = [{
+      key: 'URI',
+      permission: {
+        mutable: true,
+        collectionAdmin: true,
+        tokenOwner: false,
+      },
+    }];
+    const collection = await helper.rft.mintCollection(
+      alice,
+      {
+        name: 'Leviathan',
+        tokenPrefix: '11',
+        properties: [{key: 'ERC721Metadata', value: '1'}],
+        tokenPropertyPermissions,
+      },
+    );
+
     const contract = helper.ethNativeContract.collectionById(collection.collectionId, 'rft', caller);
     const name = await contract.methods.name().call();
     expect(name).to.equal('Leviathan');
@@ -390,8 +394,25 @@
 
   itEth('Returns symbol name', async ({helper}) => {
     const caller = await helper.eth.createAccountWithBalance(donor);
-    const {collectionAddress} = await helper.eth.createRefungibleCollection(caller, 'Leviathan', '', '12');
-    const contract = helper.ethNativeContract.collection(collectionAddress, 'rft', caller);
+    const tokenPropertyPermissions = [{
+      key: 'URI',
+      permission: {
+        mutable: true,
+        collectionAdmin: true,
+        tokenOwner: false,
+      },
+    }];
+    const {collectionId} = await helper.rft.mintCollection(
+      alice,
+      {
+        name: 'Leviathan',
+        tokenPrefix: '12',
+        properties: [{key: 'ERC721Metadata', value: '1'}],
+        tokenPropertyPermissions,
+      },
+    );
+
+    const contract = helper.ethNativeContract.collectionById(collectionId, 'rft', caller);
     const symbol = await contract.methods.symbol().call();
     expect(symbol).to.equal('12');
   });
modifiedtests/src/eth/reFungibleAbi.jsondiffbeforeafterboth
--- a/tests/src/eth/reFungibleAbi.json
+++ b/tests/src/eth/reFungibleAbi.json
@@ -146,6 +146,15 @@
     "type": "function"
   },
   {
+    "inputs": [
+      { "internalType": "address", "name": "newOwner", "type": "address" }
+    ],
+    "name": "changeCollectionOwner",
+    "outputs": [],
+    "stateMutability": "nonpayable",
+    "type": "function"
+  },
+  {
     "inputs": [],
     "name": "collectionOwner",
     "outputs": [
@@ -260,12 +269,9 @@
     "type": "function"
   },
   {
-    "inputs": [
-      { "internalType": "address", "name": "to", "type": "address" },
-      { "internalType": "uint256", "name": "tokenId", "type": "uint256" }
-    ],
+    "inputs": [{ "internalType": "address", "name": "to", "type": "address" }],
     "name": "mint",
-    "outputs": [{ "internalType": "bool", "name": "", "type": "bool" }],
+    "outputs": [{ "internalType": "uint256", "name": "", "type": "uint256" }],
     "stateMutability": "nonpayable",
     "type": "function"
   },
@@ -287,7 +293,7 @@
           { "internalType": "uint256", "name": "field_0", "type": "uint256" },
           { "internalType": "string", "name": "field_1", "type": "string" }
         ],
-        "internalType": "struct Tuple8[]",
+        "internalType": "struct Tuple6[]",
         "name": "tokens",
         "type": "tuple[]"
       }
@@ -300,11 +306,10 @@
   {
     "inputs": [
       { "internalType": "address", "name": "to", "type": "address" },
-      { "internalType": "uint256", "name": "tokenId", "type": "uint256" },
       { "internalType": "string", "name": "tokenUri", "type": "string" }
     ],
     "name": "mintWithTokenURI",
-    "outputs": [{ "internalType": "bool", "name": "", "type": "bool" }],
+    "outputs": [{ "internalType": "uint256", "name": "", "type": "uint256" }],
     "stateMutability": "nonpayable",
     "type": "function"
   },
@@ -476,15 +481,6 @@
       { "internalType": "address", "name": "sponsor", "type": "address" }
     ],
     "name": "setCollectionSponsor",
-    "outputs": [],
-    "stateMutability": "nonpayable",
-    "type": "function"
-  },
-  {
-    "inputs": [
-      { "internalType": "address", "name": "newOwner", "type": "address" }
-    ],
-    "name": "setOwner",
     "outputs": [],
     "stateMutability": "nonpayable",
     "type": "function"
modifiedtests/src/eth/reFungibleToken.test.tsdiffbeforeafterboth
--- a/tests/src/eth/reFungibleToken.test.ts
+++ b/tests/src/eth/reFungibleToken.test.ts
@@ -76,34 +76,28 @@
     });
   });
 
-  async function setup(helper: EthUniqueHelper, tokenPrefix: string, propertyKey?: string, propertyValue?: string): Promise<{contract: Contract, nextTokenId: string}> {
+  async function setup(helper: EthUniqueHelper, baseUri: string, propertyKey?: string, propertyValue?: string): Promise<{contract: Contract, nextTokenId: string}> {
     const owner = await helper.eth.createAccountWithBalance(donor);
     const receiver = helper.eth.createAccount();
 
-    const collectionHelper = helper.ethNativeContract.collectionHelpers(owner);
-    let result = await collectionHelper.methods.createERC721MetadataCompatibleCollection('Mint collection', 'a', 'b', tokenPrefix).send({value: Number(2n * helper.balance.getOneTokenNominal())});
-    const collectionAddress = helper.ethAddress.normalizeAddress(result.events.CollectionCreated.returnValues.collectionId);
+    const {collectionAddress} = await helper.eth.createERC721MetadataCompatibleRFTCollection(owner, 'Mint collection', 'a', 'b', baseUri);
     const contract = helper.ethNativeContract.collection(collectionAddress, 'rft', owner);
-    
-    const nextTokenId = await contract.methods.nextTokenId().call();
-    expect(nextTokenId).to.be.equal('1');
-    result = await contract.methods.mint(
-      receiver,
-      nextTokenId,
-    ).send();
 
-    if (propertyKey && propertyValue) {
-      // Set URL or suffix
-      await contract.methods.setProperty(nextTokenId, propertyKey, Buffer.from(propertyValue)).send();
-    }
+    const result = await contract.methods.mint(receiver).send();
 
     const event = result.events.Transfer;
+    const tokenId = event.returnValues.tokenId;
+    expect(tokenId).to.be.equal('1');
     expect(event.address).to.be.equal(collectionAddress);
     expect(event.returnValues.from).to.be.equal('0x0000000000000000000000000000000000000000');
     expect(event.returnValues.to).to.be.equal(receiver);
-    expect(event.returnValues.tokenId).to.be.equal(nextTokenId);
 
-    return {contract, nextTokenId};
+    if (propertyKey && propertyValue) {
+      // Set URL or suffix
+      await contract.methods.setProperty(tokenId, propertyKey, Buffer.from(propertyValue)).send();
+    }
+
+    return {contract, nextTokenId: tokenId};
   }
 
   itEth('Empty tokenURI', async ({helper}) => {
@@ -112,18 +106,18 @@
   });
 
   itEth('TokenURI from url', async ({helper}) => {
-    const {contract, nextTokenId} = await setup(helper, 'BaseURI_', 'url', 'Token URI');
+    const {contract, nextTokenId} = await setup(helper, 'BaseURI_', 'URI', 'Token URI');
     expect(await contract.methods.tokenURI(nextTokenId).call()).to.be.equal('Token URI');
   });
 
-  itEth('TokenURI from baseURI + tokenId', async ({helper}) => {
+  itEth('TokenURI from baseURI', async ({helper}) => {
     const {contract, nextTokenId} = await setup(helper, 'BaseURI_');
-    expect(await contract.methods.tokenURI(nextTokenId).call()).to.be.equal('BaseURI_' + nextTokenId);
+    expect(await contract.methods.tokenURI(nextTokenId).call()).to.be.equal('BaseURI_');
   });
 
   itEth('TokenURI from baseURI + suffix', async ({helper}) => {
     const suffix = '/some/suffix';
-    const {contract, nextTokenId} = await setup(helper, 'BaseURI_', 'suffix', suffix);
+    const {contract, nextTokenId} = await setup(helper, 'BaseURI_', 'URISuffix', suffix);
     expect(await contract.methods.tokenURI(nextTokenId).call()).to.be.equal('BaseURI_' + suffix);
   });
 });
@@ -294,11 +288,11 @@
   itEth('Receiving Transfer event on burning into full ownership', async ({helper}) => {
     const caller = await helper.eth.createAccountWithBalance(donor);
     const receiver = await helper.eth.createAccountWithBalance(donor);
-    const {collectionId, collectionAddress} = await helper.eth.createRefungibleCollection(caller, 'Devastation', '6', '6');
+    const {collectionId, collectionAddress} = await helper.eth.createRFTCollection(caller, 'Devastation', '6', '6');
     const contract = helper.ethNativeContract.collection(collectionAddress, 'rft', caller);
 
-    const tokenId = await contract.methods.nextTokenId().call();
-    await contract.methods.mint(caller, tokenId).send();
+    const result = await contract.methods.mint(caller).send();
+    const tokenId = result.events.Transfer.returnValues.tokenId;
     const tokenAddress = helper.ethAddress.fromTokenId(collectionId, tokenId);
     const tokenContract = helper.ethNativeContract.rftToken(tokenAddress, caller);
 
@@ -484,11 +478,12 @@
   itEth('Default parent token address and id', async ({helper}) => {
     const owner = await helper.eth.createAccountWithBalance(donor);
 
-    const {collectionId, collectionAddress} = await helper.eth.createRefungibleCollection(owner, 'Sands', '', 'GRAIN');
+    const {collectionId, collectionAddress} = await helper.eth.createRFTCollection(owner, 'Sands', '', 'GRAIN');
     const collectionContract = helper.ethNativeContract.collection(collectionAddress, 'rft', owner);
-    
-    const tokenId = await collectionContract.methods.nextTokenId().call();
-    await collectionContract.methods.mint(owner, tokenId).send();
+
+    const result = await collectionContract.methods.mint(owner).send();
+    const tokenId = result.events.Transfer.returnValues.tokenId;
+
     const tokenAddress = helper.ethAddress.fromTokenId(collectionId, tokenId);
     const tokenContract = helper.ethNativeContract.rftToken(tokenAddress, owner);
 
modifiedtests/src/eth/util/playgrounds/unique.dev.tsdiffbeforeafterboth
--- a/tests/src/eth/util/playgrounds/unique.dev.ts
+++ b/tests/src/eth/util/playgrounds/unique.dev.ts
@@ -43,12 +43,12 @@
     if(!imports) return function(path: string) {
       return {error: `File not found: ${path}`};
     };
-  
+
     const knownImports = {} as {[key: string]: string};
     for(const imp of imports) {
       knownImports[imp.solPath] = (await readFile(imp.fsPath)).toString();
     }
-  
+
     return function(path: string) {
       if(path in knownImports) return {contents: knownImports[path]};
       return {error: `File not found: ${path}`};
@@ -71,7 +71,7 @@
         },
       },
     }), {import: await this.findImports(imports)})).contracts[`${name}.sol`][name];
-  
+
     return {
       abi: out.abi,
       object: '0x' + out.evm.bytecode.object,
@@ -94,7 +94,7 @@
   }
 
 }
-  
+
 class NativeContractGroup extends EthGroupBase {
 
   contractHelpers(caller: string): Contract {
@@ -145,14 +145,14 @@
   async createAccountWithBalance(donor: IKeyringPair, amount=100n) {
     const account = this.createAccount();
     await this.transferBalanceFromSubstrate(donor, account, amount);
-  
+
     return account;
   }
 
   async transferBalanceFromSubstrate(donor: IKeyringPair, recepient: string, amount=100n, inTokens=true) {
     return await this.helper.balance.transferToSubstrate(donor, evmToAddress(recepient), amount * (inTokens ? this.helper.balance.getOneTokenNominal() : 1n));
   }
-  
+
   async getCollectionCreationFee(signer: string) {
     const collectionHelper = this.helper.ethNativeContract.collectionHelpers(signer);
     return await collectionHelper.methods.collectionCreationFee().call();
@@ -174,22 +174,32 @@
     return await this.helper.callRpc('api.rpc.eth.call', [{from: signer, to: contractAddress, data: abi}]);
   }
 
-  async createNonfungibleCollection(signer: string, name: string, description: string, tokenPrefix: string): Promise<{collectionId: number, collectionAddress: string}> {
+  async createNFTCollection(signer: string, name: string, description: string, tokenPrefix: string): Promise<{collectionId: number, collectionAddress: string}> {
     const collectionCreationPrice = this.helper.balance.getCollectionCreationPrice();
     const collectionHelper = this.helper.ethNativeContract.collectionHelpers(signer);
-        
-    const result = await collectionHelper.methods.createNonfungibleCollection(name, description, tokenPrefix).send({value: Number(collectionCreationPrice)});
 
+    const result = await collectionHelper.methods.createNFTCollection(name, description, tokenPrefix).send({value: Number(collectionCreationPrice)});
+
     const collectionAddress = this.helper.ethAddress.normalizeAddress(result.events.CollectionCreated.returnValues.collectionId);
     const collectionId = this.helper.ethAddress.extractCollectionId(collectionAddress);
 
     return {collectionId, collectionAddress};
   }
 
-  async createRefungibleCollection(signer: string, name: string, description: string, tokenPrefix: string): Promise<{collectionId: number, collectionAddress: string}> {
+  async createERC721MetadataCompatibleNFTCollection(signer: string, name: string, description: string, tokenPrefix: string, baseUri: string): Promise<{collectionId: number, collectionAddress: string}> {
+    const collectionHelper = this.helper.ethNativeContract.collectionHelpers(signer);
+
+    const {collectionId, collectionAddress} = await this.createNFTCollection(signer, name, description, tokenPrefix)
+
+    await collectionHelper.methods.makeCollectionERC721MetadataCompatible(collectionAddress, baseUri).send();
+
+    return {collectionId, collectionAddress};
+  }
+
+  async createRFTCollection(signer: string, name: string, description: string, tokenPrefix: string): Promise<{collectionId: number, collectionAddress: string}> {
     const collectionCreationPrice = this.helper.balance.getCollectionCreationPrice();
     const collectionHelper = this.helper.ethNativeContract.collectionHelpers(signer);
-        
+
     const result = await collectionHelper.methods.createRFTCollection(name, description, tokenPrefix).send({value: Number(collectionCreationPrice)});
 
     const collectionAddress = this.helper.ethAddress.normalizeAddress(result.events.CollectionCreated.returnValues.collectionId);
@@ -198,6 +208,16 @@
     return {collectionId, collectionAddress};
   }
 
+  async createERC721MetadataCompatibleRFTCollection(signer: string, name: string, description: string, tokenPrefix: string, baseUri: string): Promise<{collectionId: number, collectionAddress: string}> {
+    const collectionHelper = this.helper.ethNativeContract.collectionHelpers(signer);
+
+    const {collectionId, collectionAddress} = await this.createRFTCollection(signer, name, description, tokenPrefix)
+
+    await collectionHelper.methods.makeCollectionERC721MetadataCompatible(collectionAddress, baseUri).send();
+
+    return {collectionId, collectionAddress};
+  }
+
   async deployCollectorContract(signer: string): Promise<Contract> {
     return await this.helper.ethContract.deployByCode(signer, 'Collector', `
     // SPDX-License-Identifier: UNLICENSED
@@ -288,7 +308,7 @@
     };
     return await this.helper.arrange.calculcateFee(address, wrappedCode);
   }
-}  
+}
 
 class EthAddressGroup extends EthGroupBase {
   extractCollectionId(address: string): number {
@@ -319,8 +339,8 @@
   normalizeAddress(address: string): string {
     return '0x' + address.substring(address.length - 40);
   }
-}  
- 
+}
+
 export type EthUniqueHelperConstructor = new (...args: any[]) => EthUniqueHelper;
 
 export class EthUniqueHelper extends DevUniqueHelper {
@@ -373,4 +393,3 @@
     return newHelper;
   }
 }
-  
\ No newline at end of file
modifiedtests/src/util/playgrounds/unique.tsdiffbeforeafterboth
before · tests/src/util/playgrounds/unique.ts
1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// SPDX-License-Identifier: Apache-2.034/* eslint-disable @typescript-eslint/no-var-requires */5/* eslint-disable function-call-argument-newline */6/* eslint-disable no-prototype-builtins */78import {ApiPromise, WsProvider, Keyring} from '@polkadot/api';9import {ApiInterfaceEvents, SignerOptions} from '@polkadot/api/types';10import {encodeAddress, decodeAddress, keccakAsHex, evmToAddress, addressToEvm} from '@polkadot/util-crypto';11import {IKeyringPair} from '@polkadot/types/types';12import {IApiListeners, IBlock, IEvent, IChainProperties, ICollectionCreationOptions, ICollectionLimits, ICollectionPermissions, ICrossAccountId, ICrossAccountIdLower, ILogger, INestingPermissions, IProperty, IStakingInfo, ISchedulerOptions, ISubstrateBalance, IToken, ITokenPropertyPermission, ITransactionResult, IUniqueHelperLog, TApiAllowedListeners, TEthereumAccount, TSigner, TSubstrateAccount, IForeignAssetMetadata, TNetworks, MoonbeamAssetInfo, DemocracyStandardAccountVote, AcalaAssetMetadata} from './types';1314export class CrossAccountId implements ICrossAccountId {15  Substrate?: TSubstrateAccount;16  Ethereum?: TEthereumAccount;1718  constructor(account: ICrossAccountId) {19    if (account.Substrate) this.Substrate = account.Substrate;20    if (account.Ethereum) this.Ethereum = account.Ethereum;21  }2223  static fromKeyring(account: IKeyringPair, domain: 'Substrate' | 'Ethereum' = 'Substrate') {24    switch (domain) {25      case 'Substrate': return new CrossAccountId({Substrate: account.address});26      case 'Ethereum': return new CrossAccountId({Substrate: account.address}).toEthereum();27    }28  }2930  static fromLowerCaseKeys(address: ICrossAccountIdLower): CrossAccountId {31    return new CrossAccountId({Substrate: address.substrate, Ethereum: address.ethereum});32  }3334  static normalizeSubstrateAddress(address: TSubstrateAccount, ss58Format = 42): TSubstrateAccount {35    return encodeAddress(decodeAddress(address), ss58Format);36  }3738  static withNormalizedSubstrate(address: TSubstrateAccount, ss58Format = 42): CrossAccountId {39    return new CrossAccountId({Substrate: CrossAccountId.normalizeSubstrateAddress(address, ss58Format)});40  }41  42  withNormalizedSubstrate(ss58Format = 42): CrossAccountId {43    if (this.Substrate) return CrossAccountId.withNormalizedSubstrate(this.Substrate, ss58Format);44    return this;45  }4647  static translateSubToEth(address: TSubstrateAccount): TEthereumAccount {48    return nesting.toChecksumAddress('0x' + Array.from(addressToEvm(address), i => i.toString(16).padStart(2, '0')).join(''));49  }5051  toEthereum(): CrossAccountId {52    if (this.Substrate) return new CrossAccountId({Ethereum: CrossAccountId.translateSubToEth(this.Substrate)});53    return this;54  }5556  static translateEthToSub(address: TEthereumAccount, ss58Format?: number): TSubstrateAccount {57    return evmToAddress(address, ss58Format);58  }5960  toSubstrate(ss58Format?: number): CrossAccountId {61    if (this.Ethereum) return new CrossAccountId({Substrate: CrossAccountId.translateEthToSub(this.Ethereum, ss58Format)});62    return this;63  }64  65  toLowerCase(): CrossAccountId {66    if (this.Substrate) this.Substrate = this.Substrate.toLowerCase();67    if (this.Ethereum) this.Ethereum = this.Ethereum.toLowerCase();68    return this;69  }70}7172const nesting = {73  toChecksumAddress(address: string): string {74    if (typeof address === 'undefined') return '';7576    if(!/^(0x)?[0-9a-f]{40}$/i.test(address)) throw new Error(`Given address "${address}" is not a valid Ethereum address.`);7778    address = address.toLowerCase().replace(/^0x/i,'');79    const addressHash = keccakAsHex(address).replace(/^0x/i,'');80    const checksumAddress = ['0x'];8182    for (let i = 0; i < address.length; i++) {83      // If ith character is 8 to f then make it uppercase84      if (parseInt(addressHash[i], 16) > 7) {85        checksumAddress.push(address[i].toUpperCase());86      } else {87        checksumAddress.push(address[i]);88      }89    }90    return checksumAddress.join('');91  },92  tokenIdToAddress(collectionId: number, tokenId: number) {93    return this.toChecksumAddress(`0xf8238ccfff8ed887463fd5e0${collectionId.toString(16).padStart(8, '0')}${tokenId.toString(16).padStart(8, '0')}`);94  },95};9697class UniqueUtil {98  static transactionStatus = {99    NOT_READY: 'NotReady',100    FAIL: 'Fail',101    SUCCESS: 'Success',102  };103104  static chainLogType = {105    EXTRINSIC: 'extrinsic',106    RPC: 'rpc',107  };108109  static getTokenAccount(token: IToken): CrossAccountId {110    return new CrossAccountId({Ethereum: this.getTokenAddress(token)});111  }112113  static getTokenAddress(token: IToken): string {114    return nesting.tokenIdToAddress(token.collectionId, token.tokenId);115  }116117  static getDefaultLogger(): ILogger {118    return {119      log(msg: any, level = 'INFO') {120        console[level.toLocaleLowerCase() === 'error' ? 'error' : 'log'](...(Array.isArray(msg) ? msg : [msg]));121      },122      level: {123        ERROR: 'ERROR',124        WARNING: 'WARNING',125        INFO: 'INFO',126      },127    };128  }129130  static vec2str(arr: string[] | number[]) {131    return arr.map(x => String.fromCharCode(parseInt(x.toString()))).join('');132  }133134  static str2vec(string: string) {135    if (typeof string !== 'string') return string;136    return Array.from(string).map(x => x.charCodeAt(0));137  }138139  static fromSeed(seed: string, ss58Format = 42) {140    const keyring = new Keyring({type: 'sr25519', ss58Format});141    return keyring.addFromUri(seed);142  }143144  static extractCollectionIdFromCreationResult(creationResult: ITransactionResult): number {145    if (creationResult.status !== this.transactionStatus.SUCCESS) {146      throw Error('Unable to create collection!');147    }148149    let collectionId = null;150    creationResult.result.events.forEach(({event: {data, method, section}}) => {151      if ((section === 'common') && (method === 'CollectionCreated')) {152        collectionId = parseInt(data[0].toString(), 10);153      }154    });155156    if (collectionId === null) {157      throw Error('No CollectionCreated event was found!');158    }159160    return collectionId;161  }162163  static extractTokensFromCreationResult(creationResult: ITransactionResult): {164    success: boolean, 165    tokens: {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[],166  } {167    if (creationResult.status !== this.transactionStatus.SUCCESS) {168      throw Error('Unable to create tokens!');169    }170    let success = false;171    const tokens = [] as {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[];172    creationResult.result.events.forEach(({event: {data, method, section}}) => {173      if (method === 'ExtrinsicSuccess') {174        success = true;175      } else if ((section === 'common') && (method === 'ItemCreated')) {176        tokens.push({177          collectionId: parseInt(data[0].toString(), 10),178          tokenId: parseInt(data[1].toString(), 10),179          owner: data[2].toHuman(),180          amount: data[3].toBigInt(),181        });182      }183    });184    return {success, tokens};185  }186187  static extractTokensFromBurnResult(burnResult: ITransactionResult): {188    success: boolean, 189    tokens: {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[],190  } {191    if (burnResult.status !== this.transactionStatus.SUCCESS) {192      throw Error('Unable to burn tokens!');193    }194    let success = false;195    const tokens = [] as {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[];196    burnResult.result.events.forEach(({event: {data, method, section}}) => {197      if (method === 'ExtrinsicSuccess') {198        success = true;199      } else if ((section === 'common') && (method === 'ItemDestroyed')) {200        tokens.push({201          collectionId: parseInt(data[0].toString(), 10),202          tokenId: parseInt(data[1].toString(), 10),203          owner: data[2].toHuman(),204          amount: data[3].toBigInt(),205        });206      }207    });208    return {success, tokens};209  }210211  static findCollectionInEvents(events: {event: IEvent}[], collectionId: number, expectedSection: string, expectedMethod: string): boolean {212    let eventId = null;213    events.forEach(({event: {data, method, section}}) => {214      if ((section === expectedSection) && (method === expectedMethod)) {215        eventId = parseInt(data[0].toString(), 10);216      }217    });218219    if (eventId === null) {220      throw Error(`No ${expectedMethod} event was found!`);221    }222    return eventId === collectionId;223  }224225  static isTokenTransferSuccess(events: {event: IEvent}[], collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {226    const normalizeAddress = (address: string | ICrossAccountId) => {227      if(typeof address === 'string') return address;228      const obj = {} as any;229      Object.keys(address).forEach(k => {230        obj[k.toLocaleLowerCase()] = address[k as 'Substrate' | 'Ethereum'];231      });232      if(obj.substrate) return CrossAccountId.withNormalizedSubstrate(obj.substrate);233      if(obj.ethereum) return CrossAccountId.fromLowerCaseKeys(obj).toLowerCase();234      return address;235    };236    let transfer = {collectionId: null, tokenId: null, from: null, to: null, amount: 1} as any;237    events.forEach(({event: {data, method, section}}) => {238      if ((section === 'common') && (method === 'Transfer')) {239        const hData = (data as any).toJSON();240        transfer = {241          collectionId: hData[0],242          tokenId: hData[1],243          from: normalizeAddress(hData[2]),244          to: normalizeAddress(hData[3]),245          amount: BigInt(hData[4]),246        };247      }248    });249    let isSuccess = parseInt(collectionId.toString()) === transfer.collectionId && parseInt(tokenId.toString()) === transfer.tokenId;250    isSuccess = isSuccess && JSON.stringify(normalizeAddress(fromAddressObj)) === JSON.stringify(transfer.from);251    isSuccess = isSuccess && JSON.stringify(normalizeAddress(toAddressObj)) === JSON.stringify(transfer.to);252    isSuccess = isSuccess && amount === transfer.amount;253    return isSuccess;254  }255256  static bigIntToDecimals(number: bigint, decimals = 18) {257    const numberStr = number.toString();258    const dotPos = numberStr.length - decimals;259  260    if (dotPos <= 0) {261      return '0.' + '0'.repeat(Math.abs(dotPos)) + numberStr;262    } else {263      const intPart = numberStr.substring(0, dotPos);264      const fractPart = numberStr.substring(dotPos);265      return intPart + '.' + fractPart;266    }267  }268}269270class UniqueEventHelper {271  private static extractIndex(index: any): [number, number] | string {272    if(index.toRawType() === '[u8;2]') return [index[0], index[1]];273    return index.toJSON();274  }275276  private static extractSub(data: any, subTypes: any): {[key: string]: any} {277    let obj: any = {};278    let index = 0;279280    if (data.entries) {281      for(const [key, value] of data.entries()) {282        obj[key] = this.extractData(value, subTypes[index]);283        index++;284      }285    } else obj = data.toJSON();286287    return obj;288  }289  290  private static extractData(data: any, type: any): any {291    if(!type) return data.toHuman();292    if (['u16', 'u32'].indexOf(type.type) > -1) return data.toNumber();293    if (['u64', 'u128', 'u256'].indexOf(type.type) > -1) return data.toBigInt();294    if(type.hasOwnProperty('sub')) return this.extractSub(data, type.sub);295    return data.toHuman();296  }297298  public static extractEvents(events: {event: any, phase: any}[]): IEvent[] {299    const parsedEvents: IEvent[] = [];300301    events.forEach((record) => {302      const {event, phase} = record;303      const types = event.typeDef;304305      const eventData: IEvent = {306        section: event.section.toString(),307        method: event.method.toString(),308        index: this.extractIndex(event.index),309        data: [],310        phase: phase.toJSON(),311      };312313      event.data.forEach((val: any, index: number) => {314        eventData.data.push(this.extractData(val, types[index]));315      });316317      parsedEvents.push(eventData);318    });319320    return parsedEvents;321  }322}323324export class ChainHelperBase {325  helperBase: any;326327  transactionStatus = UniqueUtil.transactionStatus;328  chainLogType = UniqueUtil.chainLogType;329  util: typeof UniqueUtil;330  eventHelper: typeof UniqueEventHelper;331  logger: ILogger;332  api: ApiPromise | null;333  forcedNetwork: TNetworks | null;334  network: TNetworks | null;335  chainLog: IUniqueHelperLog[];336  children: ChainHelperBase[];337  address: AddressGroup;338  chain: ChainGroup;339340  constructor(logger?: ILogger, helperBase?: any) {341    this.helperBase = helperBase;342343    this.util = UniqueUtil;344    this.eventHelper = UniqueEventHelper;345    if (typeof logger == 'undefined') logger = this.util.getDefaultLogger();346    this.logger = logger;347    this.api = null;348    this.forcedNetwork = null;349    this.network = null;350    this.chainLog = [];351    this.children = [];352    this.address = new AddressGroup(this);353    this.chain = new ChainGroup(this);354  }355356  clone(helperCls: ChainHelperBaseConstructor, options: {[key: string]: any} = {}) {357    Object.setPrototypeOf(helperCls.prototype, this);358    const newHelper = new helperCls(this.logger, options);359360    newHelper.api = this.api;361    newHelper.network = this.network;362    newHelper.forceNetwork = this.forceNetwork;363364    this.children.push(newHelper);365366    return newHelper;367  }368369  getApi(): ApiPromise {370    if(this.api === null) throw Error('API not initialized');371    return this.api;372  }373374  clearChainLog(): void {375    this.chainLog = [];376  }377378  forceNetwork(value: TNetworks): void {379    this.forcedNetwork = value;380  }381382  async connect(wsEndpoint: string, listeners?: IApiListeners) {383    if (this.api !== null) throw Error('Already connected');384    const {api, network} = await ChainHelperBase.createConnection(wsEndpoint, listeners, this.forcedNetwork);385    this.api = api;386    this.network = network;387  }388389  async disconnect() {390    for (const child of this.children) {391      child.clearApi();392    }393394    if (this.api === null) return;395    await this.api.disconnect();396    this.clearApi();397  }398399  clearApi() {400    this.api = null;401    this.network = null;402  }403404  static async detectNetwork(api: ApiPromise): Promise<TNetworks> {405    const spec = (await api.query.system.lastRuntimeUpgrade()).toJSON() as any;406    const xcmChains = ['rococo', 'westend', 'westmint', 'acala', 'karura', 'moonbeam', 'moonriver'];407408    if(xcmChains.indexOf(spec.specName) > -1) return spec.specName;409410    if(['quartz', 'unique'].indexOf(spec.specName) > -1) return spec.specName;411    return 'opal';412  }413414  static async detectNetworkByWsEndpoint(wsEndpoint: string): Promise<TNetworks> {415    const api = new ApiPromise({provider: new WsProvider(wsEndpoint)});416    await api.isReady;417418    const network = await this.detectNetwork(api);419420    await api.disconnect();421422    return network;423  }424425  static async createConnection(wsEndpoint: string, listeners?: IApiListeners, network?: TNetworks | null): Promise<{426    api: ApiPromise;427    network: TNetworks;428  }> {429    if(typeof network === 'undefined' || network === null) network = 'opal';430    const supportedRPC = {431      opal: {432        unique: require('@unique-nft/opal-testnet-types/definitions').unique.rpc,433      },434      quartz: {435        unique: require('@unique-nft/quartz-mainnet-types/definitions').unique.rpc,436      },437      unique: {438        unique: require('@unique-nft/unique-mainnet-types/definitions').unique.rpc,439      },440      rococo: {},441      westend: {},442      moonbeam: {},443      moonriver: {},444      acala: {},445      karura: {},446      westmint: {},447    };448    if(!supportedRPC.hasOwnProperty(network)) network = await this.detectNetworkByWsEndpoint(wsEndpoint);449    const rpc = supportedRPC[network];450451    // TODO: investigate how to replace rpc in runtime452    // api._rpcCore.addUserInterfaces(rpc);453454    const api = new ApiPromise({provider: new WsProvider(wsEndpoint), rpc});455456    await api.isReadyOrError;457458    if (typeof listeners === 'undefined') listeners = {};459    for (const event of ['connected', 'disconnected', 'error', 'ready', 'decorated']) {460      if (!listeners.hasOwnProperty(event) || typeof listeners[event as TApiAllowedListeners] === 'undefined') continue;461      api.on(event as ApiInterfaceEvents, listeners[event as TApiAllowedListeners] as (...args: any[]) => any);462    }463464    return {api, network};465  }466467  getTransactionStatus(data: {events: {event: IEvent}[], status: any}) {468    const {events, status} = data;469    if (status.isReady) {470      return this.transactionStatus.NOT_READY;471    }472    if (status.isBroadcast) {473      return this.transactionStatus.NOT_READY;474    }475    if (status.isInBlock || status.isFinalized) {476      const errors = events.filter(e => e.event.method === 'ExtrinsicFailed');477      if (errors.length > 0) {478        return this.transactionStatus.FAIL;479      }480      if (events.filter(e => e.event.method === 'ExtrinsicSuccess').length > 0) {481        return this.transactionStatus.SUCCESS;482      }483    }484485    return this.transactionStatus.FAIL;486  }487488  signTransaction(sender: TSigner, transaction: any, options: Partial<SignerOptions> | null = null, label = 'transaction') {489    const sign = (callback: any) => {490      if(options !== null) return transaction.signAndSend(sender, options, callback);491      return transaction.signAndSend(sender, callback);492    };493    // eslint-disable-next-line no-async-promise-executor494    return new Promise(async (resolve, reject) => {495      try {496        const unsub = await sign((result: any) => {497          const status = this.getTransactionStatus(result);498499          if (status === this.transactionStatus.SUCCESS) {500            this.logger.log(`${label} successful`);501            unsub();502            resolve({result, status});503          } else if (status === this.transactionStatus.FAIL) {504            let moduleError = null;505506            if (result.hasOwnProperty('dispatchError')) {507              const dispatchError = result['dispatchError'];508509              if (dispatchError) {510                if (dispatchError.isModule) {511                  const modErr = dispatchError.asModule;512                  const errorMeta = dispatchError.registry.findMetaError(modErr);513514                  moduleError = `${errorMeta.section}.${errorMeta.name}`;515                } else {516                  moduleError = dispatchError.toHuman();517                }518              } else {519                this.logger.log(result, this.logger.level.ERROR);520              }521            }522523            this.logger.log(`Something went wrong with ${label}. Status: ${status}`, this.logger.level.ERROR);524            unsub();525            reject({status, moduleError, result});526          }527        });528      } catch (e) {529        this.logger.log(e, this.logger.level.ERROR);530        reject(e);531      }532    });533  }534535  constructApiCall(apiCall: string, params: any[]) {536    if(!apiCall.startsWith('api.')) throw Error(`Invalid api call: ${apiCall}`);537    let call = this.getApi() as any;538    for(const part of apiCall.slice(4).split('.')) {539      call = call[part];540    }541    return call(...params);542  }543544  async executeExtrinsic(sender: TSigner, extrinsic: string, params: any[], expectSuccess=true, options: Partial<SignerOptions>|null = null/*, failureMessage='expected success'*/) {545    if(this.api === null) throw Error('API not initialized');546    if(!extrinsic.startsWith('api.tx.')) throw Error(`${extrinsic} is not transaction`);547548    const startTime = (new Date()).getTime();549    let result: ITransactionResult;550    let events: IEvent[] = [];551    try {552      result = await this.signTransaction(sender, this.constructApiCall(extrinsic, params), options, extrinsic) as ITransactionResult;553      events = this.eventHelper.extractEvents(result.result.events);554    }555    catch(e) {556      if(!(e as object).hasOwnProperty('status')) throw e;557      result = e as ITransactionResult;558    }559560    const endTime = (new Date()).getTime();561562    const log = {563      executedAt: endTime,564      executionTime: endTime - startTime,565      type: this.chainLogType.EXTRINSIC,566      status: result.status,567      call: extrinsic,568      signer: this.getSignerAddress(sender),569      params,570    } as IUniqueHelperLog;571572    if(result.status !== this.transactionStatus.SUCCESS) {573      if (result.moduleError) log.moduleError = result.moduleError;574      else if (result.result.dispatchError) log.dispatchError = result.result.dispatchError;575    }576    if(events.length > 0) log.events = events;577578    this.chainLog.push(log);579580    if(expectSuccess && result.status !== this.transactionStatus.SUCCESS) {581      if (result.moduleError) throw Error(`${result.moduleError}`);582      else if (result.result.dispatchError) throw Error(JSON.stringify(result.result.dispatchError));583    }584    return result;585  }586587  async callRpc(rpc: string, params?: any[]) {588    if(typeof params === 'undefined') params = [];589    if(this.api === null) throw Error('API not initialized');590    if(!rpc.startsWith('api.rpc.') && !rpc.startsWith('api.query.')) throw Error(`${rpc} is not RPC call`);591592    const startTime = (new Date()).getTime();593    let result;594    let error = null;595    const log = {596      type: this.chainLogType.RPC,597      call: rpc,598      params,599    } as IUniqueHelperLog;600601    try {602      result = await this.constructApiCall(rpc, params);603    }604    catch(e) {605      error = e;606    }607608    const endTime = (new Date()).getTime();609610    log.executedAt = endTime;611    log.status = (error === null ? this.transactionStatus.SUCCESS : this.transactionStatus.FAIL) as 'Fail' | 'Success';612    log.executionTime = endTime - startTime;613614    this.chainLog.push(log);615616    if(error !== null) throw error;617618    return result;619  }620621  getSignerAddress(signer: IKeyringPair | string): string {622    if(typeof signer === 'string') return signer;623    return signer.address;624  }625626  fetchAllPalletNames(): string[] {627    if(this.api === null) throw Error('API not initialized');628    return this.api.runtimeMetadata.asLatest.pallets.map(m => m.name.toString().toLowerCase());629  }630631  fetchMissingPalletNames(requiredPallets: string[]): string[] {632    const palletNames = this.fetchAllPalletNames();633    return requiredPallets.filter(p => !palletNames.includes(p));634  }635}636637638class HelperGroup<T extends ChainHelperBase> {639  helper: T;640641  constructor(uniqueHelper: T) {642    this.helper = uniqueHelper;643  }644}645646647class CollectionGroup extends HelperGroup<UniqueHelper> {648  /**649 * Get number of blocks when sponsored transaction is available.650 *651 * @param collectionId ID of collection652 * @param tokenId ID of token653 * @param addressObj address for which the sponsorship is checked654 * @example await getTokenNextSponsored(1, 2, {Substrate: '5DfhbVfww7ThF8q6f3...'});655 * @returns number of blocks or null if sponsorship hasn't been set656 */657  async getTokenNextSponsored(collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<number | null> {658    return (await this.helper.callRpc('api.rpc.unique.nextSponsored', [collectionId, addressObj, tokenId])).toJSON();659  }660661  /**662   * Get the number of created collections.663   *664   * @returns number of created collections665   */666  async getTotalCount(): Promise<number> {667    return (await this.helper.callRpc('api.rpc.unique.collectionStats')).created.toNumber();668  }669670  /**671   * Get information about the collection with additional data,672   * including the number of tokens it contains, its administrators,673   * the normalized address of the collection's owner, and decoded name and description.674   *675   * @param collectionId ID of collection676   * @example await getData(2)677   * @returns collection information object678   */679  async getData(collectionId: number): Promise<{680    id: number;681    name: string;682    description: string;683    tokensCount: number;684    admins: CrossAccountId[];685    normalizedOwner: TSubstrateAccount;686    raw: any687  } | null> {688    const collection = await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId]);689    const humanCollection = collection.toHuman(), collectionData = {690      id: collectionId, name: null, description: null, tokensCount: 0, admins: [],691      raw: humanCollection,692    } as any, jsonCollection = collection.toJSON();693    if (humanCollection === null) return null;694    collectionData.raw.limits = jsonCollection.limits;695    collectionData.raw.permissions = jsonCollection.permissions;696    collectionData.normalizedOwner = this.helper.address.normalizeSubstrate(collectionData.raw.owner);697    for (const key of ['name', 'description']) {698      collectionData[key] = this.helper.util.vec2str(humanCollection[key]);699    }700701    collectionData.tokensCount = (['RFT', 'NFT'].includes(humanCollection.mode))702      ? await this.helper[humanCollection.mode.toLocaleLowerCase() as 'nft' | 'rft'].getLastTokenId(collectionId)703      : 0;704    collectionData.admins = await this.getAdmins(collectionId);705706    return collectionData;707  }708709  /**710   * Get the addresses of the collection's administrators, optionally normalized.711   *712   * @param collectionId ID of collection713   * @param normalize whether to normalize the addresses to the default ss58 format714   * @example await getAdmins(1)715   * @returns array of administrators716   */717  async getAdmins(collectionId: number, normalize = false): Promise<CrossAccountId[]> {718    const admins = (await this.helper.callRpc('api.rpc.unique.adminlist', [collectionId])).toHuman();719720    return normalize721      ? admins.map((address: CrossAccountId) => address.withNormalizedSubstrate())722      : admins;723  }724725  /**726   * Get the addresses added to the collection allow-list, optionally normalized.727   * @param collectionId ID of collection728   * @param normalize whether to normalize the addresses to the default ss58 format729   * @example await getAllowList(1)730   * @returns array of allow-listed addresses731   */732  async getAllowList(collectionId: number, normalize = false): Promise<CrossAccountId[]> {733    const allowListed = (await this.helper.callRpc('api.rpc.unique.allowlist', [collectionId])).toHuman();734    return normalize735      ? allowListed.map((address: CrossAccountId) => address.withNormalizedSubstrate())736      : allowListed;737  }738739  /**740   * Get the effective limits of the collection instead of null for default values741   *742   * @param collectionId ID of collection743   * @example await getEffectiveLimits(2)744   * @returns object of collection limits745   */746  async getEffectiveLimits(collectionId: number): Promise<ICollectionLimits> {747    return (await this.helper.callRpc('api.rpc.unique.effectiveCollectionLimits', [collectionId])).toJSON();748  }749750  /**751   * Burns the collection if the signer has sufficient permissions and collection is empty.752   *753   * @param signer keyring of signer754   * @param collectionId ID of collection755   * @example await helper.collection.burn(aliceKeyring, 3);756   * @returns ```true``` if extrinsic success, otherwise ```false```757   */758  async burn(signer: TSigner, collectionId: number): Promise<boolean> {759    const result = await this.helper.executeExtrinsic(760      signer,761      'api.tx.unique.destroyCollection', [collectionId],762      true,763    );764765    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionDestroyed');766  }767768  /**769   * Sets the sponsor for the collection (Requires the Substrate address). Needs confirmation by the sponsor.770   *771   * @param signer keyring of signer772   * @param collectionId ID of collection773   * @param sponsorAddress Sponsor substrate address774   * @example setSponsor(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...")775   * @returns ```true``` if extrinsic success, otherwise ```false```776   */777  async setSponsor(signer: TSigner, collectionId: number, sponsorAddress: TSubstrateAccount): Promise<boolean> {778    const result = await this.helper.executeExtrinsic(779      signer,780      'api.tx.unique.setCollectionSponsor', [collectionId, sponsorAddress],781      true,782    );783784    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionSponsorSet');785  }786787  /**788   * Confirms consent to sponsor the collection on behalf of the signer.789   *790   * @param signer keyring of signer791   * @param collectionId ID of collection792   * @example confirmSponsorship(aliceKeyring, 10)793   * @returns ```true``` if extrinsic success, otherwise ```false```794   */795  async confirmSponsorship(signer: TSigner, collectionId: number): Promise<boolean> {796    const result = await this.helper.executeExtrinsic(797      signer,798      'api.tx.unique.confirmSponsorship', [collectionId],799      true,800    );801802    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'SponsorshipConfirmed');803  }804805  /**806   * Removes the sponsor of a collection, regardless if it consented or not.807   *808   * @param signer keyring of signer809   * @param collectionId ID of collection810   * @example removeSponsor(aliceKeyring, 10)811   * @returns ```true``` if extrinsic success, otherwise ```false```812   */813  async removeSponsor(signer: TSigner, collectionId: number): Promise<boolean> {814    const result = await this.helper.executeExtrinsic(815      signer,816      'api.tx.unique.removeCollectionSponsor', [collectionId],817      true,818    );819820    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionSponsorRemoved');821  }822823  /**824   * Sets the limits of the collection. At least one limit must be specified for a correct call.825   *826   * @param signer keyring of signer827   * @param collectionId ID of collection828   * @param limits collection limits object829   * @example830   * await setLimits(831   *   aliceKeyring,832   *   10,833   *   {834   *     sponsorTransferTimeout: 0,835   *     ownerCanDestroy: false836   *   }837   * )838   * @returns ```true``` if extrinsic success, otherwise ```false```839   */840  async setLimits(signer: TSigner, collectionId: number, limits: ICollectionLimits): Promise<boolean> {841    const result = await this.helper.executeExtrinsic(842      signer,843      'api.tx.unique.setCollectionLimits', [collectionId, limits],844      true,845    );846847    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionLimitSet');848  }849850  /**851   * Changes the owner of the collection to the new Substrate address.852   *853   * @param signer keyring of signer854   * @param collectionId ID of collection855   * @param ownerAddress substrate address of new owner856   * @example changeOwner(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...")857   * @returns ```true``` if extrinsic success, otherwise ```false```858   */859  async changeOwner(signer: TSigner, collectionId: number, ownerAddress: TSubstrateAccount): Promise<boolean> {860    const result = await this.helper.executeExtrinsic(861      signer,862      'api.tx.unique.changeCollectionOwner', [collectionId, ownerAddress],863      true,864    );865866    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionOwnedChanged');867  }868869  /**870   * Adds a collection administrator.871   *872   * @param signer keyring of signer873   * @param collectionId ID of collection874   * @param adminAddressObj Administrator address (substrate or ethereum)875   * @example addAdmin(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."})876   * @returns ```true``` if extrinsic success, otherwise ```false```877   */878  async addAdmin(signer: TSigner, collectionId: number, adminAddressObj: ICrossAccountId): Promise<boolean> {879    const result = await this.helper.executeExtrinsic(880      signer,881      'api.tx.unique.addCollectionAdmin', [collectionId, adminAddressObj],882      true,883    );884885    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionAdminAdded');886  }887888  /**889   * Removes a collection administrator.890   *891   * @param signer keyring of signer892   * @param collectionId ID of collection893   * @param adminAddressObj Administrator address (substrate or ethereum)894   * @example removeAdmin(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."})895   * @returns ```true``` if extrinsic success, otherwise ```false```896   */897  async removeAdmin(signer: TSigner, collectionId: number, adminAddressObj: ICrossAccountId): Promise<boolean> {898    const result = await this.helper.executeExtrinsic(899      signer,900      'api.tx.unique.removeCollectionAdmin', [collectionId, adminAddressObj],901      true,902    );903904    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionAdminRemoved');905  }906907  /**908   * Check if user is in allow list.909   * 910   * @param collectionId ID of collection911   * @param user Account to check912   * @example await getAdmins(1)913   * @returns is user in allow list914   */915  async allowed(collectionId: number, user: ICrossAccountId): Promise<boolean> {916    return (await this.helper.callRpc('api.rpc.unique.allowed', [collectionId, user])).toJSON();917  }918919  /**920   * Adds an address to allow list921   * @param signer keyring of signer922   * @param collectionId ID of collection923   * @param addressObj address to add to the allow list924   * @returns ```true``` if extrinsic success, otherwise ```false```925   */926  async addToAllowList(signer: TSigner, collectionId: number, addressObj: ICrossAccountId): Promise<boolean> {927    const result = await this.helper.executeExtrinsic(928      signer,929      'api.tx.unique.addToAllowList', [collectionId, addressObj],930      true,931    );932933    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'AllowListAddressAdded');934  }935936  /**937   * Removes an address from allow list938   *939   * @param signer keyring of signer940   * @param collectionId ID of collection941   * @param addressObj address to remove from the allow list942   * @returns ```true``` if extrinsic success, otherwise ```false```943   */944  async removeFromAllowList(signer: TSigner, collectionId: number, addressObj: ICrossAccountId): Promise<boolean> {945    const result = await this.helper.executeExtrinsic(946      signer,947      'api.tx.unique.removeFromAllowList', [collectionId, addressObj],948      true,949    );950951    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'AllowListAddressRemoved');952  }953954  /**955   * Sets onchain permissions for selected collection.956   *957   * @param signer keyring of signer958   * @param collectionId ID of collection959   * @param permissions collection permissions object960   * @example setPermissions(aliceKeyring, 10, {access:'AllowList', mintMode: true, nesting: {collectionAdmin: true, tokenOwner: true}});961   * @returns ```true``` if extrinsic success, otherwise ```false```962   */963  async setPermissions(signer: TSigner, collectionId: number, permissions: ICollectionPermissions): Promise<boolean> {964    const result = await this.helper.executeExtrinsic(965      signer,966      'api.tx.unique.setCollectionPermissions', [collectionId, permissions],967      true,968    );969970    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionPermissionSet');971  }972973  /**974   * Enables nesting for selected collection. If `restricted` set, you can nest only tokens from specified collections.975   *976   * @param signer keyring of signer977   * @param collectionId ID of collection978   * @param permissions nesting permissions object979   * @example enableNesting(aliceKeyring, 10, {collectionAdmin: true, tokenOwner: true});980   * @returns ```true``` if extrinsic success, otherwise ```false```981   */982  async enableNesting(signer: TSigner, collectionId: number, permissions: INestingPermissions): Promise<boolean> {983    return await this.setPermissions(signer, collectionId, {nesting: permissions});984  }985986  /**987   * Disables nesting for selected collection.988   *989   * @param signer keyring of signer990   * @param collectionId ID of collection991   * @example disableNesting(aliceKeyring, 10);992   * @returns ```true``` if extrinsic success, otherwise ```false```993   */994  async disableNesting(signer: TSigner, collectionId: number): Promise<boolean> {995    return await this.setPermissions(signer, collectionId, {nesting: {tokenOwner: false, collectionAdmin: false}});996  }997998  /**999   * Sets onchain properties to the collection.1000   *1001   * @param signer keyring of signer1002   * @param collectionId ID of collection1003   * @param properties array of property objects1004   * @example setProperties(aliceKeyring, 10, [{key: "gender", value: "male"}]);1005   * @returns ```true``` if extrinsic success, otherwise ```false```1006   */1007  async setProperties(signer: TSigner, collectionId: number, properties: IProperty[]): Promise<boolean> {1008    const result = await this.helper.executeExtrinsic(1009      signer,1010      'api.tx.unique.setCollectionProperties', [collectionId, properties],1011      true,1012    );10131014    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPropertySet');1015  }10161017  /**1018   * Get collection properties.1019   * 1020   * @param collectionId ID of collection1021   * @param propertyKeys optionally filter the returned properties to only these keys1022   * @example getProperties(1219, ['location', 'date', 'time', 'isParadise']);1023   * @returns array of key-value pairs1024   */1025  async getProperties(collectionId: number, propertyKeys?: string[] | null): Promise<IProperty[]> {1026    return (await this.helper.callRpc('api.rpc.unique.collectionProperties', [collectionId, propertyKeys])).toHuman();1027  }10281029  /**1030   * Deletes onchain properties from the collection.1031   *1032   * @param signer keyring of signer1033   * @param collectionId ID of collection1034   * @param propertyKeys array of property keys to delete1035   * @example deleteProperties(aliceKeyring, 10, ["gender", "age"]);1036   * @returns ```true``` if extrinsic success, otherwise ```false```1037   */1038  async deleteProperties(signer: TSigner, collectionId: number, propertyKeys: string[]): Promise<boolean> {1039    const result = await this.helper.executeExtrinsic(1040      signer,1041      'api.tx.unique.deleteCollectionProperties', [collectionId, propertyKeys],1042      true,1043    );10441045    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPropertyDeleted');1046  }10471048  /**1049   * Changes the owner of the token.1050   *1051   * @param signer keyring of signer1052   * @param collectionId ID of collection1053   * @param tokenId ID of token1054   * @param addressObj address of a new owner1055   * @param amount amount of tokens to be transfered. For NFT must be set to 1n1056   * @example transferToken(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."})1057   * @returns true if the token success, otherwise false1058   */1059  async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId, amount=1n): Promise<boolean> {1060    const result = await this.helper.executeExtrinsic(1061      signer,1062      'api.tx.unique.transfer', [addressObj, collectionId, tokenId, amount],1063      true, // `Unable to transfer token #${tokenId} from collection #${collectionId}`,1064    );10651066    return this.helper.util.isTokenTransferSuccess(result.result.events, collectionId, tokenId, {Substrate: typeof signer === 'string' ? signer : signer.address}, addressObj, amount);1067  }10681069  /**1070   *1071   * Change ownership of a token(s) on behalf of the owner.1072   *1073   * @param signer keyring of signer1074   * @param collectionId ID of collection1075   * @param tokenId ID of token1076   * @param fromAddressObj address on behalf of which the token will be sent1077   * @param toAddressObj new token owner1078   * @param amount amount of tokens to be transfered. For NFT must be set to 1n1079   * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg"}, {Ethereum: "0x9F0583DbB85..."})1080   * @returns true if the token success, otherwise false1081   */1082  async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1083    const result = await this.helper.executeExtrinsic(1084      signer,1085      'api.tx.unique.transferFrom', [fromAddressObj, toAddressObj, collectionId, tokenId, amount],1086      true, // `Unable to transfer token #${tokenId} from collection #${collectionId}`,1087    );1088    return this.helper.util.isTokenTransferSuccess(result.result.events, collectionId, tokenId, fromAddressObj, toAddressObj, amount);1089  }10901091  /**1092   *1093   * Destroys a concrete instance of NFT/RFT or burns a specified amount of fungible tokens.1094   *1095   * @param signer keyring of signer1096   * @param collectionId ID of collection1097   * @param tokenId ID of token1098   * @param amount amount of tokens to be burned. For NFT must be set to 1n1099   * @example burnToken(aliceKeyring, 10, 5);1100   * @returns ```true``` if the extrinsic is successful, otherwise ```false```1101   */1102  async burnToken(signer: TSigner, collectionId: number, tokenId: number, amount=1n): Promise<boolean> {1103    const burnResult = await this.helper.executeExtrinsic(1104      signer,1105      'api.tx.unique.burnItem', [collectionId, tokenId, amount],1106      true, // `Unable to burn token for ${label}`,1107    );1108    const burnedTokens = this.helper.util.extractTokensFromBurnResult(burnResult);1109    if (burnedTokens.tokens.length > 1) throw Error('Burned multiple tokens');1110    return burnedTokens.success;1111  }11121113  /**1114   * Destroys a concrete instance of NFT on behalf of the owner1115   *1116   * @param signer keyring of signer1117   * @param collectionId ID of collection1118   * @param tokenId ID of token1119   * @param fromAddressObj address on behalf of which the token will be burnt1120   * @param amount amount of tokens to be burned. For NFT must be set to 1n1121   * @example burnTokenFrom(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."}, 5, {Ethereum: "0x9F0583DbB85..."})1122   * @returns ```true``` if extrinsic success, otherwise ```false```1123   */1124  async burnTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1125    const burnResult = await this.helper.executeExtrinsic(1126      signer,1127      'api.tx.unique.burnFrom', [collectionId, fromAddressObj, tokenId, amount],1128      true, // `Unable to burn token from for ${label}`,1129    );1130    const burnedTokens = this.helper.util.extractTokensFromBurnResult(burnResult);1131    return burnedTokens.success && burnedTokens.tokens.length > 0;1132  }11331134  /**1135   * Set, change, or remove approved address to transfer the ownership of the NFT.1136   *1137   * @param signer keyring of signer1138   * @param collectionId ID of collection1139   * @param tokenId ID of token1140   * @param toAddressObj Substrate or Ethereum address which gets approved use of the signer's tokens1141   * @param amount amount of token to be approved. For NFT must be set to 1n1142   * @returns ```true``` if extrinsic success, otherwise ```false```1143   */1144  async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {1145    const approveResult = await this.helper.executeExtrinsic(1146      signer,1147      'api.tx.unique.approve', [toAddressObj, collectionId, tokenId, amount],1148      true, // `Unable to approve token for ${label}`,1149    );11501151    return this.helper.util.findCollectionInEvents(approveResult.result.events, collectionId, 'common', 'Approved');1152  }11531154  /**1155   * Get the amount of token pieces approved to transfer or burn. Normally 0.1156   *1157   * @param collectionId ID of collection1158   * @param tokenId ID of token1159   * @param toAccountObj address which is approved to use token pieces1160   * @param fromAccountObj address which may have allowed the use of its owned tokens1161   * @example getTokenApprovedPieces(10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, {Substrate: "5ERZNF88Mm7UGfPP3mdG..."})1162   * @returns number of approved to transfer pieces1163   */1164  async getTokenApprovedPieces(collectionId: number, tokenId: number, toAccountObj: ICrossAccountId, fromAccountObj: ICrossAccountId): Promise<bigint> {1165    return (await this.helper.callRpc('api.rpc.unique.allowance', [collectionId, fromAccountObj, toAccountObj, tokenId])).toBigInt();1166  }11671168  /**1169   * Get the last created token ID in a collection1170   *1171   * @param collectionId ID of collection1172   * @example getLastTokenId(10);1173   * @returns id of the last created token1174   */1175  async getLastTokenId(collectionId: number): Promise<number> {1176    return (await this.helper.callRpc('api.rpc.unique.lastTokenId', [collectionId])).toNumber();1177  }11781179  /**1180   * Check if token exists1181   *1182   * @param collectionId ID of collection1183   * @param tokenId ID of token1184   * @example doesTokenExist(10, 20);1185   * @returns true if the token exists, otherwise false1186   */1187  async doesTokenExist(collectionId: number, tokenId: number): Promise<boolean> {1188    return (await this.helper.callRpc('api.rpc.unique.tokenExists', [collectionId, tokenId])).toJSON();1189  }1190}11911192class NFTnRFT extends CollectionGroup {1193  /**1194   * Get tokens owned by account1195   *1196   * @param collectionId ID of collection1197   * @param addressObj tokens owner1198   * @example getTokensByAddress(10, {Substrate: "5DyN4Y92vZCjv38fg..."})1199   * @returns array of token ids owned by account1200   */1201  async getTokensByAddress(collectionId: number, addressObj: ICrossAccountId): Promise<number[]> {1202    return (await this.helper.callRpc('api.rpc.unique.accountTokens', [collectionId, addressObj])).toJSON();1203  }12041205  /**1206   * Get token data1207   *1208   * @param collectionId ID of collection1209   * @param tokenId ID of token1210   * @param propertyKeys optionally filter the token properties to only these keys1211   * @param blockHashAt optionally query the data at some block with this hash1212   * @example getToken(10, 5);1213   * @returns human readable token data1214   */1215  async getToken(collectionId: number, tokenId: number, propertyKeys: string[] = [], blockHashAt?: string): Promise<{1216    properties: IProperty[];1217    owner: CrossAccountId;1218    normalizedOwner: CrossAccountId;1219  }| null> {1220    let tokenData;1221    if(typeof blockHashAt === 'undefined') {1222      tokenData = await this.helper.callRpc('api.rpc.unique.tokenData', [collectionId, tokenId]);1223    }1224    else {1225      if(propertyKeys.length == 0) {1226        const collection = (await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId])).toHuman();1227        if(!collection) return null;1228        propertyKeys = collection.tokenPropertyPermissions.map((x: ITokenPropertyPermission) => x.key);1229      }1230      tokenData = await this.helper.callRpc('api.rpc.unique.tokenData', [collectionId, tokenId, propertyKeys, blockHashAt]);1231    }1232    tokenData = tokenData.toHuman();1233    if (tokenData === null || tokenData.owner === null) return null;1234    const owner = {} as any;1235    for (const key of Object.keys(tokenData.owner)) {1236      owner[key.toLocaleLowerCase()] = key.toLocaleLowerCase() == 'substrate' 1237        ? CrossAccountId.normalizeSubstrateAddress(tokenData.owner[key]) 1238        : tokenData.owner[key];1239    }1240    tokenData.normalizedOwner = CrossAccountId.fromLowerCaseKeys(owner);1241    return tokenData;1242  }12431244  /**1245   * Set permissions to change token properties1246   *1247   * @param signer keyring of signer1248   * @param collectionId ID of collection1249   * @param permissions permissions to change a property by the collection admin or token owner1250   * @example setTokenPropertyPermissions(1251   *   aliceKeyring, 10, [{key: "gender", permission: {tokenOwner: true, mutable: true, collectionAdmin: true}}]1252   * )1253   * @returns true if extrinsic success otherwise false1254   */1255  async setTokenPropertyPermissions(signer: TSigner, collectionId: number, permissions: ITokenPropertyPermission[]): Promise<boolean> {1256    const result = await this.helper.executeExtrinsic(1257      signer,1258      'api.tx.unique.setTokenPropertyPermissions', [collectionId, permissions],1259      true,1260    );12611262    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'PropertyPermissionSet');1263  }12641265  /**1266   * Get token property permissions.1267   * 1268   * @param collectionId ID of collection1269   * @param propertyKeys optionally filter the returned property permissions to only these keys1270   * @example getPropertyPermissions(1219, ['location', 'date', 'time', 'isParadise']);1271   * @returns array of key-permission pairs1272   */1273  async getPropertyPermissions(collectionId: number, propertyKeys: string[] | null = null): Promise<ITokenPropertyPermission[]> {1274    return (await this.helper.callRpc('api.rpc.unique.propertyPermissions', [collectionId, ...(propertyKeys === null ? [] : [propertyKeys])])).toHuman();1275  }12761277  /**1278   * Set token properties1279   *1280   * @param signer keyring of signer1281   * @param collectionId ID of collection1282   * @param tokenId ID of token1283   * @param properties key-value pairs of metadata which to add to a token. Keys must be permitted in the collection1284   * @example setTokenProperties(aliceKeyring, 10, 5, [{key: "gender", value: "female"}, {key: "age", value: "23"}])1285   * @returns ```true``` if extrinsic success, otherwise ```false```1286   */1287  async setTokenProperties(signer: TSigner, collectionId: number, tokenId: number, properties: IProperty[]): Promise<boolean> {1288    const result = await this.helper.executeExtrinsic(1289      signer,1290      'api.tx.unique.setTokenProperties', [collectionId, tokenId, properties],1291      true,1292    );12931294    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'TokenPropertySet');1295  }12961297  /**1298   * Get properties, metadata assigned to a token.1299   * 1300   * @param collectionId ID of collection1301   * @param tokenId ID of token1302   * @param propertyKeys optionally filter the returned properties to only these keys1303   * @example getTokenProperties(1219, ['location', 'date', 'time', 'isParadise']);1304   * @returns array of key-value pairs1305   */1306  async getTokenProperties(collectionId: number, tokenId: number, propertyKeys?: string[] | null): Promise<IProperty[]> {1307    return (await this.helper.callRpc('api.rpc.unique.tokenProperties', [collectionId, tokenId, propertyKeys])).toHuman();1308  }13091310  /**1311   * Delete the provided properties of a token1312   * @param signer keyring of signer1313   * @param collectionId ID of collection1314   * @param tokenId ID of token1315   * @param propertyKeys property keys to be deleted1316   * @example deleteTokenProperties(aliceKeyring, 10, 5, ["gender", "age"])1317   * @returns ```true``` if extrinsic success, otherwise ```false```1318   */1319  async deleteTokenProperties(signer: TSigner, collectionId: number, tokenId: number, propertyKeys: string[]): Promise<boolean> {1320    const result = await this.helper.executeExtrinsic(1321      signer,1322      'api.tx.unique.deleteTokenProperties', [collectionId, tokenId, propertyKeys],1323      true,1324    );13251326    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'TokenPropertyDeleted');1327  }13281329  /**1330   * Mint new collection1331   *1332   * @param signer keyring of signer1333   * @param collectionOptions basic collection options and properties1334   * @param mode NFT or RFT type of a collection1335   * @example mintCollection(aliceKeyring, {name: 'New', description: "New collection", tokenPrefix: "NEW"}, "NFT")1336   * @returns object of the created collection1337   */1338  async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions, mode: 'NFT' | 'RFT'): Promise<UniqueBaseCollection> {1339    collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; // Clone object1340    collectionOptions.mode = (mode === 'NFT') ? {nft: null} : {refungible: null};1341    for (const key of ['name', 'description', 'tokenPrefix']) {1342      if (typeof collectionOptions[key as 'name' | 'description' | 'tokenPrefix'] === 'string') collectionOptions[key as 'name' | 'description' | 'tokenPrefix'] = this.helper.util.str2vec(collectionOptions[key as 'name' | 'description' | 'tokenPrefix'] as string);1343    }1344    const creationResult = await this.helper.executeExtrinsic(1345      signer,1346      'api.tx.unique.createCollectionEx', [collectionOptions],1347      true, // errorLabel,1348    );1349    return this.getCollectionObject(this.helper.util.extractCollectionIdFromCreationResult(creationResult));1350  }13511352  getCollectionObject(_collectionId: number): any {1353    return null;1354  }13551356  getTokenObject(_collectionId: number, _tokenId: number): any {1357    return null;1358  }1359}136013611362class NFTGroup extends NFTnRFT {1363  /**1364   * Get collection object1365   * @param collectionId ID of collection1366   * @example getCollectionObject(2);1367   * @returns instance of UniqueNFTCollection1368   */1369  getCollectionObject(collectionId: number): UniqueNFTCollection {1370    return new UniqueNFTCollection(collectionId, this.helper);1371  }13721373  /**1374   * Get token object1375   * @param collectionId ID of collection1376   * @param tokenId ID of token1377   * @example getTokenObject(10, 5);1378   * @returns instance of UniqueNFTToken1379   */1380  getTokenObject(collectionId: number, tokenId: number): UniqueNFToken {1381    return new UniqueNFToken(tokenId, this.getCollectionObject(collectionId));1382  }13831384  /**1385   * Get token's owner1386   * @param collectionId ID of collection1387   * @param tokenId ID of token1388   * @param blockHashAt optionally query the data at the block with this hash1389   * @example getTokenOwner(10, 5);1390   * @returns Address in CrossAccountId format, e.g. {Substrate: "5DnSF6RRjwteE3BrCj..."}1391   */1392  async getTokenOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<CrossAccountId> {1393    let owner;1394    if (typeof blockHashAt === 'undefined') {1395      owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId]);1396    } else {1397      owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId, blockHashAt]);1398    }1399    return CrossAccountId.fromLowerCaseKeys(owner.toJSON());1400  }14011402  /**1403   * Is token approved to transfer1404   * @param collectionId ID of collection1405   * @param tokenId ID of token1406   * @param toAccountObj address to be approved1407   * @returns ```true``` if extrinsic success, otherwise ```false```1408   */1409  async isTokenApproved(collectionId: number, tokenId: number, toAccountObj: ICrossAccountId): Promise<boolean> {1410    return (await this.getTokenApprovedPieces(collectionId, tokenId, toAccountObj, await this.getTokenOwner(collectionId, tokenId))) === 1n;1411  }14121413  /**1414   * Changes the owner of the token.1415   *1416   * @param signer keyring of signer1417   * @param collectionId ID of collection1418   * @param tokenId ID of token1419   * @param addressObj address of a new owner1420   * @example transferToken(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."})1421   * @returns ```true``` if extrinsic success, otherwise ```false```1422   */1423  async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<boolean> {1424    return await super.transferToken(signer, collectionId, tokenId, addressObj, 1n);1425  }14261427  /**1428   *1429   * Change ownership of a NFT on behalf of the owner.1430   *1431   * @param signer keyring of signer1432   * @param collectionId ID of collection1433   * @param tokenId ID of token1434   * @param fromAddressObj address on behalf of which the token will be sent1435   * @param toAddressObj new token owner1436   * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, {Ethereum: "0x9F0583DbB85..."})1437   * @returns ```true``` if extrinsic success, otherwise ```false```1438   */1439  async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId): Promise<boolean> {1440    return await super.transferTokenFrom(signer, collectionId, tokenId, fromAddressObj, toAddressObj, 1n);1441  }14421443  /**1444   * Recursively find the address that owns the token1445   * @param collectionId ID of collection1446   * @param tokenId ID of token1447   * @param blockHashAt1448   * @example getTokenTopmostOwner(10, 5);1449   * @returns address in CrossAccountId format, e.g. {Substrate: "5DyN4Y92vZCjv38fg..."}1450   */1451  async getTokenTopmostOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<CrossAccountId | null> {1452    let owner;1453    if (typeof blockHashAt === 'undefined') {1454      owner = await this.helper.callRpc('api.rpc.unique.topmostTokenOwner', [collectionId, tokenId]);1455    } else {1456      owner = await this.helper.callRpc('api.rpc.unique.topmostTokenOwner', [collectionId, tokenId, blockHashAt]);1457    }14581459    if (owner === null) return null;14601461    return owner.toHuman();1462  }14631464  /**1465   * Get tokens nested in the provided token1466   * @param collectionId ID of collection1467   * @param tokenId ID of token1468   * @param blockHashAt optionally query the data at the block with this hash1469   * @example getTokenChildren(10, 5);1470   * @returns tokens whose depth of nesting is <= 51471   */1472  async getTokenChildren(collectionId: number, tokenId: number, blockHashAt?: string): Promise<IToken[]> {1473    let children;1474    if(typeof blockHashAt === 'undefined') {1475      children = await this.helper.callRpc('api.rpc.unique.tokenChildren', [collectionId, tokenId]);1476    } else {1477      children = await this.helper.callRpc('api.rpc.unique.tokenChildren', [collectionId, tokenId, blockHashAt]);1478    }14791480    return children.toJSON().map((x: any) => {1481      return {collectionId: x.collection, tokenId: x.token};1482    });1483  }14841485  /**1486   * Nest one token into another1487   * @param signer keyring of signer1488   * @param tokenObj token to be nested1489   * @param rootTokenObj token to be parent1490   * @example nestToken(aliceKeyring, {collectionId: 10, tokenId: 5}, {collectionId: 10, tokenId: 4});1491   * @returns ```true``` if extrinsic success, otherwise ```false```1492   */1493  async nestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken): Promise<boolean> {1494    const rootTokenAddress = this.helper.util.getTokenAccount(rootTokenObj);1495    const result = await this.transferToken(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress);1496    if(!result) {1497      throw Error('Unable to nest token!');1498    }1499    return result;1500  }15011502  /**1503   * Remove token from nested state1504   * @param signer keyring of signer1505   * @param tokenObj token to unnest1506   * @param rootTokenObj parent of a token1507   * @param toAddressObj address of a new token owner1508   * @example unnestToken(aliceKeyring, {collectionId: 10, tokenId: 5}, {collectionId: 10, tokenId: 4}, {Substrate: "5DyN4Y92vZCjv38fg..."});1509   * @returns ```true``` if extrinsic success, otherwise ```false```1510   */1511  async unnestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken, toAddressObj: ICrossAccountId): Promise<boolean> {1512    const rootTokenAddress = this.helper.util.getTokenAccount(rootTokenObj);1513    const result = await this.transferTokenFrom(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress, toAddressObj);1514    if(!result) {1515      throw Error('Unable to unnest token!');1516    }1517    return result;1518  }15191520  /**1521   * Mint new collection1522   * @param signer keyring of signer1523   * @param collectionOptions Collection options1524   * @example1525   * mintCollection(aliceKeyring, {1526   *   name: 'New',1527   *   description: 'New collection',1528   *   tokenPrefix: 'NEW',1529   * })1530   * @returns object of the created collection1531   */1532  async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}): Promise<UniqueNFTCollection> {1533    return await super.mintCollection(signer, collectionOptions, 'NFT') as UniqueNFTCollection;1534  }15351536  /**1537   * Mint new token1538   * @param signer keyring of signer1539   * @param data token data1540   * @returns created token object1541   */1542  async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; properties?: IProperty[]; }): Promise<UniqueNFToken> {1543    const creationResult = await this.helper.executeExtrinsic(1544      signer,1545      'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {1546        nft: {1547          properties: data.properties,1548        },1549      }],1550      true,1551    );1552    const createdTokens = this.helper.util.extractTokensFromCreationResult(creationResult);1553    if (createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');1554    if (createdTokens.tokens.length < 1) throw Error('No tokens minted');1555    return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);1556  }15571558  /**1559   * Mint multiple NFT tokens1560   * @param signer keyring of signer1561   * @param collectionId ID of collection1562   * @param tokens array of tokens with owner and properties1563   * @example1564   * mintMultipleTokens(aliceKeyring, 10, [{1565   *     owner: {Substrate: "5DyN4Y92vZCjv38fg..."},1566   *     properties: [{key: "gender", value: "male"},{key: "age", value: "45"}],1567   *   },{1568   *     owner: {Ethereum: "0x9F0583DbB855d..."},1569   *     properties: [{key: "gender", value: "female"},{key: "age", value: "22"}],1570   * }]);1571   * @returns ```true``` if extrinsic success, otherwise ```false```1572   */1573  async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: {owner: ICrossAccountId, properties?: IProperty[]}[]): Promise<UniqueNFToken[]> {1574    const creationResult = await this.helper.executeExtrinsic(1575      signer,1576      'api.tx.unique.createMultipleItemsEx', [collectionId, {NFT: tokens}],1577      true,1578    );1579    const collection = this.getCollectionObject(collectionId);1580    return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1581  }15821583  /**1584   * Mint multiple NFT tokens with one owner1585   * @param signer keyring of signer1586   * @param collectionId ID of collection1587   * @param owner tokens owner1588   * @param tokens array of tokens with owner and properties1589   * @example1590   * mintMultipleTokensWithOneOwner(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...", [{1591   *   properties: [{1592   *   key: "gender",1593   *   value: "female",1594   *  },{1595   *   key: "age",1596   *   value: "33",1597   *  }],1598   * }]);1599   * @returns array of newly created tokens1600   */1601  async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {properties?: IProperty[]}[]): Promise<UniqueNFToken[]> {1602    const rawTokens = [];1603    for (const token of tokens) {1604      const raw = {NFT: {properties: token.properties}};1605      rawTokens.push(raw);1606    }1607    const creationResult = await this.helper.executeExtrinsic(1608      signer,1609      'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1610      true,1611    );1612    const collection = this.getCollectionObject(collectionId);1613    return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1614  }16151616  /**1617   * Set, change, or remove approved address to transfer the ownership of the NFT.1618   *1619   * @param signer keyring of signer1620   * @param collectionId ID of collection1621   * @param tokenId ID of token1622   * @param toAddressObj address to approve1623   * @example approveToken(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."})1624   * @returns ```true``` if extrinsic success, otherwise ```false```1625   */1626  async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId) {1627    return super.approveToken(signer, collectionId, tokenId, toAddressObj, 1n);1628  }1629}163016311632class RFTGroup extends NFTnRFT {1633  /**1634   * Get collection object1635   * @param collectionId ID of collection1636   * @example getCollectionObject(2);1637   * @returns instance of UniqueRFTCollection1638   */1639  getCollectionObject(collectionId: number): UniqueRFTCollection {1640    return new UniqueRFTCollection(collectionId, this.helper);1641  }16421643  /**1644   * Get token object1645   * @param collectionId ID of collection1646   * @param tokenId ID of token1647   * @example getTokenObject(10, 5);1648   * @returns instance of UniqueNFTToken1649   */1650  getTokenObject(collectionId: number, tokenId: number): UniqueRFToken {1651    return new UniqueRFToken(tokenId, this.getCollectionObject(collectionId));1652  }16531654  /**1655   * Get top 10 token owners with the largest number of pieces1656   * @param collectionId ID of collection1657   * @param tokenId ID of token1658   * @example getTokenTop10Owners(10, 5);1659   * @returns array of top 10 owners1660   */1661  async getTokenTop10Owners(collectionId: number, tokenId: number): Promise<CrossAccountId[]> {1662    return (await this.helper.callRpc('api.rpc.unique.tokenOwners', [collectionId, tokenId])).toJSON().map(CrossAccountId.fromLowerCaseKeys);1663  }16641665  /**1666   * Get number of pieces owned by address1667   * @param collectionId ID of collection1668   * @param tokenId ID of token1669   * @param addressObj address token owner1670   * @example getTokenBalance(10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."});1671   * @returns number of pieces ownerd by address1672   */1673  async getTokenBalance(collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<bigint> {1674    return (await this.helper.callRpc('api.rpc.unique.balance', [collectionId, addressObj, tokenId])).toBigInt();1675  }16761677  /**1678   * Transfer pieces of token to another address1679   * @param signer keyring of signer1680   * @param collectionId ID of collection1681   * @param tokenId ID of token1682   * @param addressObj address of a new owner1683   * @param amount number of pieces to be transfered1684   * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, 2000n)1685   * @returns ```true``` if extrinsic success, otherwise ```false```1686   */1687  async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId, amount=1n): Promise<boolean> {1688    return await super.transferToken(signer, collectionId, tokenId, addressObj, amount);1689  }16901691  /**1692   * Change ownership of some pieces of RFT on behalf of the owner.1693   * @param signer keyring of signer1694   * @param collectionId ID of collection1695   * @param tokenId ID of token1696   * @param fromAddressObj address on behalf of which the token will be sent1697   * @param toAddressObj new token owner1698   * @param amount number of pieces to be transfered1699   * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, {Substrate: "5DfhbVfww7ThF8q6f3i..."}, 2000n)1700   * @returns ```true``` if extrinsic success, otherwise ```false```1701   */1702  async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1703    return await super.transferTokenFrom(signer, collectionId, tokenId, fromAddressObj, toAddressObj, amount);1704  }17051706  /**1707   * Mint new collection1708   * @param signer keyring of signer1709   * @param collectionOptions Collection options1710   * @example1711   * mintCollection(aliceKeyring, {1712   *   name: 'New',1713   *   description: 'New collection',1714   *   tokenPrefix: 'NEW',1715   * })1716   * @returns object of the created collection1717   */1718  async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}): Promise<UniqueRFTCollection> {1719    return await super.mintCollection(signer, collectionOptions, 'RFT') as UniqueRFTCollection;1720  }17211722  /**1723   * Mint new token1724   * @param signer keyring of signer1725   * @param data token data1726   * @example mintToken(aliceKeyring, {collectionId: 10, owner: {Substrate: '5GHoZe9c73RYbVzq...'}, pieces: 10000n});1727   * @returns created token object1728   */1729  async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; pieces: bigint; properties?: IProperty[]; }): Promise<UniqueRFToken> {1730    const creationResult = await this.helper.executeExtrinsic(1731      signer,1732      'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {1733        refungible: {1734          pieces: data.pieces,1735          properties: data.properties,1736        },1737      }],1738      true,1739    );1740    const createdTokens = this.helper.util.extractTokensFromCreationResult(creationResult);1741    if (createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');1742    if (createdTokens.tokens.length < 1) throw Error('No tokens minted');1743    return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);1744  }17451746  async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: {owner: ICrossAccountId, pieces: bigint, properties?: IProperty[]}[]): Promise<UniqueRFToken[]> {1747    throw Error('Not implemented');1748    const creationResult = await this.helper.executeExtrinsic(1749      signer,1750      'api.tx.unique.createMultipleItemsEx', [collectionId, {RefungibleMultipleOwners: tokens}],1751      true, // `Unable to mint RFT tokens for ${label}`,1752    );1753    const collection = this.getCollectionObject(collectionId);1754    return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1755  }17561757  /**1758   * Mint multiple RFT tokens with one owner1759   * @param signer keyring of signer1760   * @param collectionId ID of collection1761   * @param owner tokens owner1762   * @param tokens array of tokens with properties and pieces1763   * @example mintMultipleTokensWithOneOwner(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, [{pieces: 100000n, properties: [{key: "gender", value: "male"}]}]);1764   * @returns array of newly created RFT tokens1765   */1766  async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {pieces: bigint, properties?: IProperty[]}[]): Promise<UniqueRFToken[]> {1767    const rawTokens = [];1768    for (const token of tokens) {1769      const raw = {ReFungible: {pieces: token.pieces, properties: token.properties}};1770      rawTokens.push(raw);1771    }1772    const creationResult = await this.helper.executeExtrinsic(1773      signer,1774      'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1775      true,1776    );1777    const collection = this.getCollectionObject(collectionId);1778    return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1779  }17801781  /**1782   * Destroys a concrete instance of RFT.1783   * @param signer keyring of signer1784   * @param collectionId ID of collection1785   * @param tokenId ID of token1786   * @param amount number of pieces to be burnt1787   * @example burnToken(aliceKeyring, 10, 5);1788   * @returns ```true``` if the extrinsic is successful, otherwise ```false```1789   */1790  async burnToken(signer: IKeyringPair, collectionId: number, tokenId: number, amount=1n): Promise<boolean> {1791    return await super.burnToken(signer, collectionId, tokenId, amount);1792  }17931794  /**1795   * Destroys a concrete instance of RFT on behalf of the owner.1796   * @param signer keyring of signer1797   * @param collectionId ID of collection1798   * @param tokenId ID of token1799   * @param fromAddressObj address on behalf of which the token will be burnt1800   * @param amount number of pieces to be burnt1801   * @example burnTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, 2n)1802   * @returns ```true``` if extrinsic success, otherwise ```false```1803   */1804  async burnTokenFrom(signer: IKeyringPair, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1805    return await super.burnTokenFrom(signer, collectionId, tokenId, fromAddressObj, amount);1806  }18071808  /**1809   * Set, change, or remove approved address to transfer the ownership of the RFT.1810   *1811   * @param signer keyring of signer1812   * @param collectionId ID of collection1813   * @param tokenId ID of token1814   * @param toAddressObj address to approve1815   * @param amount number of pieces to be approved1816   * @example approveToken(aliceKeyring, 10, 5, {Substrate: "5GHoZe9c73RYbVzq..."}, "", 10000n);1817   * @returns true if the token success, otherwise false1818   */1819  async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {1820    return super.approveToken(signer, collectionId, tokenId, toAddressObj, amount);1821  }18221823  /**1824   * Get total number of pieces1825   * @param collectionId ID of collection1826   * @param tokenId ID of token1827   * @example getTokenTotalPieces(10, 5);1828   * @returns number of pieces1829   */1830  async getTokenTotalPieces(collectionId: number, tokenId: number): Promise<bigint> {1831    return (await this.helper.callRpc('api.rpc.unique.totalPieces', [collectionId, tokenId])).unwrap().toBigInt();1832  }18331834  /**1835   * Change number of token pieces. Signer must be the owner of all token pieces.1836   * @param signer keyring of signer1837   * @param collectionId ID of collection1838   * @param tokenId ID of token1839   * @param amount new number of pieces1840   * @example repartitionToken(aliceKeyring, 10, 5, 12345n);1841   * @returns true if the repartion was success, otherwise false1842   */1843  async repartitionToken(signer: TSigner, collectionId: number, tokenId: number, amount: bigint): Promise<boolean> {1844    const currentAmount = await this.getTokenTotalPieces(collectionId, tokenId);1845    const repartitionResult = await this.helper.executeExtrinsic(1846      signer,1847      'api.tx.unique.repartition', [collectionId, tokenId, amount],1848      true,1849    );1850    if(currentAmount < amount) return this.helper.util.findCollectionInEvents(repartitionResult.result.events, collectionId, 'common', 'ItemCreated');1851    return this.helper.util.findCollectionInEvents(repartitionResult.result.events, collectionId, 'common', 'ItemDestroyed');1852  }1853}185418551856class FTGroup extends CollectionGroup {1857  /**1858   * Get collection object1859   * @param collectionId ID of collection1860   * @example getCollectionObject(2);1861   * @returns instance of UniqueFTCollection1862   */1863  getCollectionObject(collectionId: number): UniqueFTCollection {1864    return new UniqueFTCollection(collectionId, this.helper);1865  }18661867  /**1868   * Mint new fungible collection1869   * @param signer keyring of signer1870   * @param collectionOptions Collection options1871   * @param decimalPoints number of token decimals1872   * @example1873   * mintCollection(aliceKeyring, {1874   *   name: 'New',1875   *   description: 'New collection',1876   *   tokenPrefix: 'NEW',1877   * }, 18)1878   * @returns newly created fungible collection1879   */1880  async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}, decimalPoints = 0): Promise<UniqueFTCollection> {1881    collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; // Clone object1882    if(collectionOptions.tokenPropertyPermissions) throw Error('Fungible collections has no tokenPropertyPermissions');1883    collectionOptions.mode = {fungible: decimalPoints};1884    for (const key of ['name', 'description', 'tokenPrefix']) {1885      if (typeof collectionOptions[key as 'name' | 'description' | 'tokenPrefix'] === 'string') collectionOptions[key as 'name' | 'description' | 'tokenPrefix'] = this.helper.util.str2vec(collectionOptions[key as 'name' | 'description' | 'tokenPrefix'] as string);1886    }1887    const creationResult = await this.helper.executeExtrinsic(1888      signer,1889      'api.tx.unique.createCollectionEx', [collectionOptions],1890      true,1891    );1892    return this.getCollectionObject(this.helper.util.extractCollectionIdFromCreationResult(creationResult));1893  }18941895  /**1896   * Mint tokens1897   * @param signer keyring of signer1898   * @param collectionId ID of collection1899   * @param owner address owner of new tokens1900   * @param amount amount of tokens to be meanted1901   * @example mintTokens(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq"}, 1000n);1902   * @returns ```true``` if extrinsic success, otherwise ```false```1903   */1904  async mintTokens(signer: TSigner, collectionId: number, amount: bigint, owner: ICrossAccountId | string): Promise<boolean> {1905    const creationResult = await this.helper.executeExtrinsic(1906      signer,1907      'api.tx.unique.createItem', [collectionId, (typeof owner === 'string') ? {Substrate: owner} : owner, {1908        fungible: {1909          value: amount,1910        },1911      }],1912      true, // `Unable to mint fungible tokens for ${label}`,1913    );1914    return this.helper.util.findCollectionInEvents(creationResult.result.events, collectionId, 'common', 'ItemCreated');1915  }19161917  /**1918   * Mint multiple Fungible tokens with one owner1919   * @param signer keyring of signer1920   * @param collectionId ID of collection1921   * @param owner tokens owner1922   * @param tokens array of tokens with properties and pieces1923   * @returns ```true``` if extrinsic success, otherwise ```false```1924   */1925  async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, tokens: {value: bigint}[], owner: ICrossAccountId): Promise<boolean> {1926    const rawTokens = [];1927    for (const token of tokens) {1928      const raw = {Fungible: {Value: token.value}};1929      rawTokens.push(raw);1930    }1931    const creationResult = await this.helper.executeExtrinsic(1932      signer,1933      'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1934      true,1935    );1936    return this.helper.util.findCollectionInEvents(creationResult.result.events, collectionId, 'common', 'ItemCreated');1937  }19381939  /**1940   * Get the top 10 owners with the largest balance for the Fungible collection1941   * @param collectionId ID of collection1942   * @example getTop10Owners(10);1943   * @returns array of ```ICrossAccountId```1944   */1945  async getTop10Owners(collectionId: number): Promise<CrossAccountId[]> {1946    return (await this.helper.callRpc('api.rpc.unique.tokenOwners', [collectionId, 0])).toJSON().map(CrossAccountId.fromLowerCaseKeys);1947  }19481949  /**1950   * Get account balance1951   * @param collectionId ID of collection1952   * @param addressObj address of owner1953   * @example getBalance(10, {Substrate: "5GHoZe9c73RYbVzq..."})1954   * @returns amount of fungible tokens owned by address1955   */1956  async getBalance(collectionId: number, addressObj: ICrossAccountId): Promise<bigint> {1957    return (await this.helper.callRpc('api.rpc.unique.balance', [collectionId, addressObj, 0])).toBigInt();1958  }19591960  /**1961   * Transfer tokens to address1962   * @param signer keyring of signer1963   * @param collectionId ID of collection1964   * @param toAddressObj address recipient1965   * @param amount amount of tokens to be sent1966   * @example transfer(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, 1000n);1967   * @returns ```true``` if extrinsic success, otherwise ```false```1968   */1969  async transfer(signer: TSigner, collectionId: number, toAddressObj: ICrossAccountId, amount=1n) {1970    return await super.transferToken(signer, collectionId, 0, toAddressObj, amount);1971  }19721973  /**1974   * Transfer some tokens on behalf of the owner.1975   * @param signer keyring of signer1976   * @param collectionId ID of collection1977   * @param fromAddressObj address on behalf of which tokens will be sent1978   * @param toAddressObj address where token to be sent1979   * @param amount number of tokens to be sent1980   * @example transferFrom(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, {Substrate: "5DfhbVfww7ThF8q6f3ij..."}, 10000n);1981   * @returns ```true``` if extrinsic success, otherwise ```false```1982   */1983  async transferFrom(signer: TSigner, collectionId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {1984    return await super.transferTokenFrom(signer, collectionId, 0, fromAddressObj, toAddressObj, amount);1985  }19861987  /**1988   * Destroy some amount of tokens1989   * @param signer keyring of signer1990   * @param collectionId ID of collection1991   * @param amount amount of tokens to be destroyed1992   * @example burnTokens(aliceKeyring, 10, 1000n);1993   * @returns ```true``` if extrinsic success, otherwise ```false```1994   */1995  async burnTokens(signer: IKeyringPair, collectionId: number, amount=1n): Promise<boolean> {1996    return await super.burnToken(signer, collectionId, 0, amount);1997  }19981999  /**2000   * Burn some tokens on behalf of the owner.2001   * @param signer keyring of signer2002   * @param collectionId ID of collection2003   * @param fromAddressObj address on behalf of which tokens will be burnt2004   * @param amount amount of tokens to be burnt2005   * @example burnTokensFrom(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, 1000n);2006   * @returns ```true``` if extrinsic success, otherwise ```false```2007   */2008  async burnTokensFrom(signer: IKeyringPair, collectionId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {2009    return await super.burnTokenFrom(signer, collectionId, 0, fromAddressObj, amount);2010  }20112012  /**2013   * Get total collection supply2014   * @param collectionId2015   * @returns2016   */2017  async getTotalPieces(collectionId: number): Promise<bigint> {2018    return (await this.helper.callRpc('api.rpc.unique.totalPieces', [collectionId, 0])).unwrap().toBigInt();2019  }20202021  /**2022   * Set, change, or remove approved address to transfer tokens.2023   *2024   * @param signer keyring of signer2025   * @param collectionId ID of collection2026   * @param toAddressObj address to be approved2027   * @param amount amount of tokens to be approved2028   * @example approveTokens(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, 1000n)2029   * @returns ```true``` if extrinsic success, otherwise ```false```2030   */2031  async approveTokens(signer: IKeyringPair, collectionId: number, toAddressObj: ICrossAccountId, amount=1n) {2032    return super.approveToken(signer, collectionId, 0, toAddressObj, amount);2033  }20342035  /**2036   * Get amount of fungible tokens approved to transfer2037   * @param collectionId ID of collection2038   * @param fromAddressObj owner of tokens2039   * @param toAddressObj the address approved for the transfer of tokens on behalf of the owner2040   * @returns number of tokens approved for the transfer2041   */2042  async getApprovedTokens(collectionId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2043    return super.getTokenApprovedPieces(collectionId, 0, toAddressObj, fromAddressObj);2044  }2045}204620472048class ChainGroup extends HelperGroup<ChainHelperBase> {2049  /**2050   * Get system properties of a chain2051   * @example getChainProperties();2052   * @returns ss58Format, token decimals, and token symbol2053   */2054  getChainProperties(): IChainProperties {2055    const properties = (this.helper.getApi() as any).registry.getChainProperties().toJSON();2056    return {2057      ss58Format: properties.ss58Format.toJSON(),2058      tokenDecimals: properties.tokenDecimals.toJSON(),2059      tokenSymbol: properties.tokenSymbol.toJSON(),2060    };2061  }20622063  /**2064   * Get chain header2065   * @example getLatestBlockNumber();2066   * @returns the number of the last block2067   */2068  async getLatestBlockNumber(): Promise<number> {2069    return (await this.helper.callRpc('api.rpc.chain.getHeader')).number.toNumber();2070  }20712072  /**2073   * Get block hash by block number2074   * @param blockNumber number of block2075   * @example getBlockHashByNumber(12345);2076   * @returns hash of a block2077   */2078  async getBlockHashByNumber(blockNumber: number): Promise<string | null> {2079    const blockHash = (await this.helper.callRpc('api.rpc.chain.getBlockHash', [blockNumber])).toJSON();2080    if(blockHash === '0x0000000000000000000000000000000000000000000000000000000000000000') return null;2081    return blockHash;2082  }20832084  // TODO add docs2085  async getBlock(blockHashOrNumber: string | number): Promise<IBlock | null> {2086    const blockHash = typeof blockHashOrNumber === 'string' ? blockHashOrNumber : await this.getBlockHashByNumber(blockHashOrNumber);2087    if (!blockHash) return null;2088    return (await this.helper.callRpc('api.rpc.chain.getBlock', [blockHash])).toHuman().block;2089  }20902091  /**2092   * Get account nonce2093   * @param address substrate address2094   * @example getNonce("5GrwvaEF5zXb26Fz...");2095   * @returns number, account's nonce2096   */2097  async getNonce(address: TSubstrateAccount): Promise<number> {2098    return (await this.helper.callRpc('api.query.system.account', [address])).nonce.toNumber();2099  }2100}21012102class SubstrateBalanceGroup<T extends ChainHelperBase> extends HelperGroup<T> {2103  /**2104 * Get substrate address balance2105 * @param address substrate address2106 * @example getSubstrate("5GrwvaEF5zXb26Fz...")2107 * @returns amount of tokens on address2108 */2109  async getSubstrate(address: TSubstrateAccount): Promise<bigint> {2110    return (await this.helper.callRpc('api.query.system.account', [address])).data.free.toBigInt();2111  }21122113  /**2114   * Transfer tokens to substrate address2115   * @param signer keyring of signer2116   * @param address substrate address of a recipient2117   * @param amount amount of tokens to be transfered2118   * @example transferToSubstrate(aliceKeyring, "5GrwvaEF5zXb26Fz...", 100_000_000_000n);2119   * @returns ```true``` if extrinsic success, otherwise ```false```2120   */2121  async transferToSubstrate(signer: TSigner, address: TSubstrateAccount, amount: bigint | string): Promise<boolean> {2122    const result = await this.helper.executeExtrinsic(signer, 'api.tx.balances.transfer', [address, amount], true/*, `Unable to transfer balance from ${this.helper.getSignerAddress(signer)} to ${address}`*/);21232124    let transfer = {from: null, to: null, amount: 0n} as any;2125    result.result.events.forEach(({event: {data, method, section}}) => {2126      if ((section === 'balances') && (method === 'Transfer')) {2127        transfer = {2128          from: this.helper.address.normalizeSubstrate(data[0]),2129          to: this.helper.address.normalizeSubstrate(data[1]),2130          amount: BigInt(data[2]),2131        };2132      }2133    });2134    const isSuccess = this.helper.address.normalizeSubstrate(typeof signer === 'string' ? signer : signer.address) === transfer.from 2135      && this.helper.address.normalizeSubstrate(address) === transfer.to 2136      && BigInt(amount) === transfer.amount;2137    return isSuccess;2138  }21392140  /**2141   * Get full substrate balance including free, miscFrozen, feeFrozen, and reserved2142   * @param address substrate address2143   * @returns2144   */2145  async getSubstrateFull(address: TSubstrateAccount): Promise<ISubstrateBalance> {2146    const accountInfo = (await this.helper.callRpc('api.query.system.account', [address])).data;2147    return {free: accountInfo.free.toBigInt(), miscFrozen: accountInfo.miscFrozen.toBigInt(), feeFrozen: accountInfo.feeFrozen.toBigInt(), reserved: accountInfo.reserved.toBigInt()};2148  }2149}21502151class EthereumBalanceGroup<T extends ChainHelperBase> extends HelperGroup<T> {2152  /**2153   * Get ethereum address balance2154   * @param address ethereum address2155   * @example getEthereum("0x9F0583DbB855d...")2156   * @returns amount of tokens on address2157   */2158  async getEthereum(address: TEthereumAccount): Promise<bigint> {2159    return (await this.helper.callRpc('api.rpc.eth.getBalance', [address])).toBigInt();2160  }21612162  /**2163   * Transfer tokens to address2164   * @param signer keyring of signer2165   * @param address Ethereum address of a recipient2166   * @param amount amount of tokens to be transfered2167   * @example transferToEthereum(alithKeyring, "0x9F0583DbB855d...", 100_000_000_000n);2168   * @returns ```true``` if extrinsic success, otherwise ```false```2169   */2170  async transferToEthereum(signer: TSigner, address: TEthereumAccount, amount: bigint | string): Promise<boolean> {2171    const result = await this.helper.executeExtrinsic(signer, 'api.tx.balances.transfer', [address, amount], true);21722173    let transfer = {from: null, to: null, amount: 0n} as any;2174    result.result.events.forEach(({event: {data, method, section}}) => {2175      if ((section === 'balances') && (method === 'Transfer')) {2176        transfer = {2177          from: data[0].toString(),2178          to: data[1].toString(),2179          amount: BigInt(data[2]),2180        };2181      }2182    });2183    const isSuccess = (typeof signer === 'string' ? signer : signer.address) === transfer.from 2184      && address === transfer.to 2185      && BigInt(amount) === transfer.amount;2186    return isSuccess;2187  }2188}21892190class BalanceGroup<T extends ChainHelperBase> extends HelperGroup<T> {2191  subBalanceGroup: SubstrateBalanceGroup<T>;2192  ethBalanceGroup: EthereumBalanceGroup<T>;21932194  constructor(helper: T) {2195    super(helper);2196    this.subBalanceGroup = new SubstrateBalanceGroup(helper);2197    this.ethBalanceGroup = new EthereumBalanceGroup(helper);2198  }21992200  getCollectionCreationPrice(): bigint {2201    return 2n * this.getOneTokenNominal();2202  }2203  /**2204   * Representation of the native token in the smallest unit - one OPAL (OPL), QUARTZ (QTZ), or UNIQUE (UNQ).2205   * @example getOneTokenNominal()2206   * @returns ```BigInt``` representation of the native token in the smallest unit, e.g. ```1_000_000_000_000_000_000n``` for QTZ.2207   */2208  getOneTokenNominal(): bigint {2209    const chainProperties = this.helper.chain.getChainProperties();2210    return 10n ** BigInt((chainProperties.tokenDecimals || [18])[0]);2211  }22122213  /**2214   * Get substrate address balance2215   * @param address substrate address2216   * @example getSubstrate("5GrwvaEF5zXb26Fz...")2217   * @returns amount of tokens on address2218   */2219  async getSubstrate(address: TSubstrateAccount): Promise<bigint> {2220    return this.subBalanceGroup.getSubstrate(address);2221  }22222223  /**2224   * Get full substrate balance including free, miscFrozen, feeFrozen, and reserved2225   * @param address substrate address2226   * @returns2227   */2228  async getSubstrateFull(address: TSubstrateAccount): Promise<ISubstrateBalance> {2229    return this.subBalanceGroup.getSubstrateFull(address);2230  }22312232  /**2233   * Get ethereum address balance2234   * @param address ethereum address2235   * @example getEthereum("0x9F0583DbB855d...")2236   * @returns amount of tokens on address2237   */2238  async getEthereum(address: TEthereumAccount): Promise<bigint> {2239    return this.ethBalanceGroup.getEthereum(address);2240  }22412242  /**2243   * Transfer tokens to substrate address2244   * @param signer keyring of signer2245   * @param address substrate address of a recipient2246   * @param amount amount of tokens to be transfered2247   * @example transferToSubstrate(aliceKeyring, "5GrwvaEF5zXb26Fz...", 100_000_000_000n);2248   * @returns ```true``` if extrinsic success, otherwise ```false```2249   */2250  async transferToSubstrate(signer: TSigner, address: TSubstrateAccount, amount: bigint | string): Promise<boolean> {2251    return this.subBalanceGroup.transferToSubstrate(signer, address, amount);2252  }2253}22542255class AddressGroup extends HelperGroup<ChainHelperBase> {2256  /**2257   * Normalizes the address to the specified ss58 format, by default ```42```.2258   * @param address substrate address2259   * @param ss58Format format for address conversion, by default ```42```2260   * @example normalizeSubstrate("unjKJQJrRd238pkUZZvzDQrfKuM39zBSnQ5zjAGAGcdRhaJTx") // returns 5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY2261   * @returns substrate address converted to normalized (i.e., starting with 5) or specified explicitly representation2262   */2263  normalizeSubstrate(address: TSubstrateAccount, ss58Format = 42): TSubstrateAccount {2264    return CrossAccountId.normalizeSubstrateAddress(address, ss58Format);2265  }22662267  /**2268   * Get address in the connected chain format2269   * @param address substrate address2270   * @example normalizeSubstrateToChainFormat("5GrwvaEF5zXb26Fz...") // returns unjKJQJrRd238pkUZZ... for Unique Network2271   * @returns address in chain format2272   */2273  normalizeSubstrateToChainFormat(address: TSubstrateAccount): TSubstrateAccount {2274    return this.normalizeSubstrate(address, this.helper.chain.getChainProperties().ss58Format);2275  }22762277  /**2278   * Get substrate mirror of an ethereum address2279   * @param ethAddress ethereum address2280   * @param toChainFormat false for normalized account2281   * @example ethToSubstrate('0x9F0583DbB855d...')2282   * @returns substrate mirror of a provided ethereum address2283   */2284  ethToSubstrate(ethAddress: TEthereumAccount, toChainFormat=false): TSubstrateAccount {2285    return CrossAccountId.translateEthToSub(ethAddress, toChainFormat ? this.helper.chain.getChainProperties().ss58Format : undefined);2286  }22872288  /**2289   * Get ethereum mirror of a substrate address2290   * @param subAddress substrate account2291   * @example substrateToEth("5DnSF6RRjwteE3BrC...")2292   * @returns ethereum mirror of a provided substrate address2293   */2294  substrateToEth(subAddress: TSubstrateAccount): TEthereumAccount {2295    return CrossAccountId.translateSubToEth(subAddress);2296  }22972298  paraSiblingSovereignAccount(paraid: number) {2299    // We are getting a *sibling* parachain sovereign account,2300    // so we need a sibling prefix: encoded(b"sibl") == 0x7369626c2301    const siblingPrefix = '0x7369626c';23022303    const encodedParaId = this.helper.getApi().createType('u32', paraid).toHex(true).substring(2);2304    const suffix = '000000000000000000000000000000000000000000000000';23052306    return siblingPrefix + encodedParaId + suffix;2307  }2308}23092310class StakingGroup extends HelperGroup<UniqueHelper> {2311  /**2312   * Stake tokens for App Promotion2313   * @param signer keyring of signer2314   * @param amountToStake amount of tokens to stake2315   * @param label extra label for log2316   * @returns2317   */2318  async stake(signer: TSigner, amountToStake: bigint, label?: string): Promise<boolean> {2319    if(typeof label === 'undefined') label = `${signer.address} amount: ${amountToStake}`;2320    const _stakeResult = await this.helper.executeExtrinsic(2321      signer, 'api.tx.appPromotion.stake',2322      [amountToStake], true,2323    );2324    // TODO extract info from stakeResult2325    return true;2326  }23272328  /**2329   * Unstake tokens for App Promotion2330   * @param signer keyring of signer2331   * @param amountToUnstake amount of tokens to unstake2332   * @param label extra label for log2333   * @returns block number where balances will be unlocked2334   */2335  async unstake(signer: TSigner, label?: string): Promise<number> {2336    if(typeof label === 'undefined') label = `${signer.address}`;2337    const _unstakeResult = await this.helper.executeExtrinsic(2338      signer, 'api.tx.appPromotion.unstake',2339      [], true,2340    );2341    // TODO extract block number fron events2342    return 1;2343  }23442345  /**2346   * Get total staked amount for address2347   * @param address substrate or ethereum address2348   * @returns total staked amount2349   */2350  async getTotalStaked(address?: ICrossAccountId): Promise<bigint> {2351    if (address) return (await this.helper.callRpc('api.rpc.appPromotion.totalStaked', [address])).toBigInt();2352    return (await this.helper.callRpc('api.rpc.appPromotion.totalStaked')).toBigInt();2353  }23542355  /**2356   * Get total staked per block2357   * @param address substrate or ethereum address2358   * @returns array of stakes. `block` – the number of the block in which the stake was made. `amount` - the number of tokens staked in the block2359   */2360  async getTotalStakedPerBlock(address: ICrossAccountId): Promise<IStakingInfo[]> {2361    const rawTotalStakerdPerBlock = await this.helper.callRpc('api.rpc.appPromotion.totalStakedPerBlock', [address]);2362    return rawTotalStakerdPerBlock.map(([block, amount]: any[]) => {2363      return { 2364        block: block.toBigInt(),2365        amount: amount.toBigInt(),2366      };2367    });2368  }23692370  /**2371   * Get total pending unstake amount for address2372   * @param address substrate or ethereum address2373   * @returns total pending unstake amount2374   */2375  async getPendingUnstake(address: ICrossAccountId): Promise<bigint> {2376    return (await this.helper.callRpc('api.rpc.appPromotion.pendingUnstake', [address])).toBigInt();2377  }23782379  /**2380   * Get pending unstake amount per block for address2381   * @param address substrate or ethereum address2382   * @returns array of pending stakes. `block` – the number of the block in which the unstake was made. `amount` - the number of tokens unstaked in the block2383   */2384  async getPendingUnstakePerBlock(address: ICrossAccountId): Promise<IStakingInfo[]> {2385    const rawUnstakedPerBlock = await this.helper.callRpc('api.rpc.appPromotion.pendingUnstakePerBlock', [address]);2386    const result = rawUnstakedPerBlock.map(([block, amount]: any[]) => {2387      return {2388        block: block.toBigInt(),2389        amount: amount.toBigInt(),2390      };2391    });2392    return result;2393  }2394}23952396class SchedulerGroup extends HelperGroup<UniqueHelper> {2397  constructor(helper: UniqueHelper) {2398    super(helper);2399  }24002401  async cancelScheduled(signer: TSigner, scheduledId: string) {2402    return this.helper.executeExtrinsic(2403      signer,2404      'api.tx.scheduler.cancelNamed',2405      [scheduledId],2406      true,2407    );2408  }24092410  async changePriority(signer: TSigner, scheduledId: string, priority: number) {2411    return this.helper.executeExtrinsic(2412      signer,2413      'api.tx.scheduler.changeNamedPriority',2414      [scheduledId, priority],2415      true,2416    );2417  }24182419  scheduleAt<T extends UniqueHelper>(2420    scheduledId: string,2421    executionBlockNumber: number,2422    options: ISchedulerOptions = {},2423  ) {2424    return this.schedule<T>('scheduleNamed', scheduledId, executionBlockNumber, options);2425  }24262427  scheduleAfter<T extends UniqueHelper>(2428    scheduledId: string,2429    blocksBeforeExecution: number,2430    options: ISchedulerOptions = {},2431  ) {2432    return this.schedule<T>('scheduleNamedAfter', scheduledId, blocksBeforeExecution, options);2433  }24342435  schedule<T extends UniqueHelper>(2436    scheduleFn: 'scheduleNamed' | 'scheduleNamedAfter',2437    scheduledId: string,2438    blocksNum: number,2439    options: ISchedulerOptions = {},2440  ) {2441    // eslint-disable-next-line @typescript-eslint/naming-convention2442    const ScheduledHelperType = ScheduledUniqueHelper(this.helper.helperBase);2443    return this.helper.clone(ScheduledHelperType, {2444      scheduleFn,2445      scheduledId,2446      blocksNum,2447      options,2448    }) as T;2449  }2450}24512452class ForeignAssetsGroup extends HelperGroup<UniqueHelper> {2453  async register(signer: TSigner, ownerAddress: TSubstrateAccount, location: any, metadata: IForeignAssetMetadata) {2454    await this.helper.executeExtrinsic(2455      signer,2456      'api.tx.foreignAssets.registerForeignAsset',2457      [ownerAddress, location, metadata],2458      true,2459    );2460  }24612462  async update(signer: TSigner, foreignAssetId: number, location: any, metadata: IForeignAssetMetadata) {2463    await this.helper.executeExtrinsic(2464      signer,2465      'api.tx.foreignAssets.updateForeignAsset',2466      [foreignAssetId, location, metadata],2467      true,2468    );2469  }2470}24712472class XcmGroup<T extends ChainHelperBase> extends HelperGroup<T> {2473  palletName: string;24742475  constructor(helper: T, palletName: string) {2476    super(helper);24772478    this.palletName = palletName;2479  }24802481  async limitedReserveTransferAssets(signer: TSigner, destination: any, beneficiary: any, assets: any, feeAssetItem: number, weightLimit: number) {2482    await this.helper.executeExtrinsic(signer, `api.tx.${this.palletName}.limitedReserveTransferAssets`, [destination, beneficiary, assets, feeAssetItem, {Limited: weightLimit}], true);2483  }2484}24852486class XTokensGroup<T extends ChainHelperBase> extends HelperGroup<T> {2487  async transfer(signer: TSigner, currencyId: any, amount: bigint, destination: any, destWeight: number) {2488    await this.helper.executeExtrinsic(signer, 'api.tx.xTokens.transfer', [currencyId, amount, destination, destWeight], true);2489  }24902491  async transferMultiasset(signer: TSigner, asset: any, destination: any, destWeight: number) {2492    await this.helper.executeExtrinsic(signer, 'api.tx.xTokens.transferMultiasset', [asset, destination, destWeight], true);2493  }24942495  async transferMulticurrencies(signer: TSigner, currencies: any[], feeItem: number, destLocation: any, destWeight: number) {2496    await this.helper.executeExtrinsic(signer, 'api.tx.xTokens.transferMulticurrencies', [currencies, feeItem, destLocation, destWeight], true);2497  }2498}24992500class TokensGroup<T extends ChainHelperBase> extends HelperGroup<T> {2501  async accounts(address: string, currencyId: any) {2502    const {free} = (await this.helper.callRpc('api.query.tokens.accounts', [address, currencyId])).toJSON() as any;2503    return BigInt(free);2504  }2505}25062507class AssetsGroup<T extends ChainHelperBase> extends HelperGroup<T> {2508  async create(signer: TSigner, assetId: number, admin: string, minimalBalance: bigint) {2509    await this.helper.executeExtrinsic(signer, 'api.tx.assets.create', [assetId, admin, minimalBalance], true);2510  }25112512  async setMetadata(signer: TSigner, assetId: number, name: string, symbol: string, decimals: number) {2513    await this.helper.executeExtrinsic(signer, 'api.tx.assets.setMetadata', [assetId, name, symbol, decimals], true);2514  }25152516  async mint(signer: TSigner, assetId: number, beneficiary: string, amount: bigint) {2517    await this.helper.executeExtrinsic(signer, 'api.tx.assets.mint', [assetId, beneficiary, amount], true);2518  }25192520  async account(assetId: string | number, address: string) {2521    const accountAsset = (2522      await this.helper.callRpc('api.query.assets.account', [assetId, address])2523    ).toJSON()! as any;25242525    if (accountAsset !== null) {2526      return BigInt(accountAsset['balance']);2527    } else {2528      return null;2529    }2530  }2531}25322533class AcalaAssetRegistryGroup extends HelperGroup<AcalaHelper> {2534  async registerForeignAsset(signer: TSigner, destination: any, metadata: AcalaAssetMetadata) {2535    await this.helper.executeExtrinsic(signer, 'api.tx.assetRegistry.registerForeignAsset', [destination, metadata], true);2536  }2537}25382539class MoonbeamAssetManagerGroup extends HelperGroup<MoonbeamHelper> {2540  makeRegisterForeignAssetProposal(assetInfo: MoonbeamAssetInfo) {2541    const apiPrefix = 'api.tx.assetManager.';25422543    const registerTx = this.helper.constructApiCall(2544      apiPrefix + 'registerForeignAsset',2545      [assetInfo.location, assetInfo.metadata, assetInfo.existentialDeposit, assetInfo.isSufficient],2546    );25472548    const setUnitsTx = this.helper.constructApiCall(2549      apiPrefix + 'setAssetUnitsPerSecond',2550      [assetInfo.location, assetInfo.unitsPerSecond, assetInfo.numAssetsWeightHint],2551    );25522553    const batchCall = this.helper.getApi().tx.utility.batchAll([registerTx, setUnitsTx]);2554    const encodedProposal = batchCall?.method.toHex() || '';2555    return encodedProposal;2556  }25572558  async assetTypeId(location: any) {2559    return await this.helper.callRpc('api.query.assetManager.assetTypeId', [location]);2560  }2561}25622563class MoonbeamDemocracyGroup extends HelperGroup<MoonbeamHelper> {2564  async notePreimage(signer: TSigner, encodedProposal: string) {2565    await this.helper.executeExtrinsic(signer, 'api.tx.democracy.notePreimage', [encodedProposal], true);2566  }25672568  externalProposeMajority(proposalHash: string) {2569    return this.helper.constructApiCall('api.tx.democracy.externalProposeMajority', [proposalHash]);2570  }25712572  fastTrack(proposalHash: string, votingPeriod: number, delayPeriod: number) {2573    return this.helper.constructApiCall('api.tx.democracy.fastTrack', [proposalHash, votingPeriod, delayPeriod]);2574  }25752576  async referendumVote(signer: TSigner, referendumIndex: number, accountVote: DemocracyStandardAccountVote) {2577    await this.helper.executeExtrinsic(signer, 'api.tx.democracy.vote', [referendumIndex, {Standard: accountVote}], true);2578  }2579}25802581class MoonbeamCollectiveGroup extends HelperGroup<MoonbeamHelper> {2582  collective: string;25832584  constructor(helper: MoonbeamHelper, collective: string) {2585    super(helper);25862587    this.collective = collective;2588  }25892590  async propose(signer: TSigner, threshold: number, proposalHash: string, lengthBound: number) {2591    await this.helper.executeExtrinsic(signer, `api.tx.${this.collective}.propose`, [threshold, proposalHash, lengthBound], true);2592  }25932594  async vote(signer: TSigner, proposalHash: string, proposalIndex: number, approve: boolean) {2595    await this.helper.executeExtrinsic(signer, `api.tx.${this.collective}.vote`, [proposalHash, proposalIndex, approve], true);2596  }25972598  async close(signer: TSigner, proposalHash: string, proposalIndex: number, weightBound: number, lengthBound: number) {2599    await this.helper.executeExtrinsic(signer, `api.tx.${this.collective}.close`, [proposalHash, proposalIndex, weightBound, lengthBound], true);2600  }26012602  async proposalCount() {2603    return Number(await this.helper.callRpc(`api.query.${this.collective}.proposalCount`, []));2604  }2605}26062607export type ChainHelperBaseConstructor = new(...args: any[]) => ChainHelperBase;2608export type UniqueHelperConstructor = new(...args: any[]) => UniqueHelper;26092610export class UniqueHelper extends ChainHelperBase {2611  balance: BalanceGroup<UniqueHelper>;2612  collection: CollectionGroup;2613  nft: NFTGroup;2614  rft: RFTGroup;2615  ft: FTGroup;2616  staking: StakingGroup;2617  scheduler: SchedulerGroup;2618  foreignAssets: ForeignAssetsGroup;2619  xcm: XcmGroup<UniqueHelper>;2620  xTokens: XTokensGroup<UniqueHelper>;2621  tokens: TokensGroup<UniqueHelper>;26222623  constructor(logger?: ILogger, options: {[key: string]: any} = {}) {2624    super(logger, options.helperBase ?? UniqueHelper);26252626    this.balance = new BalanceGroup(this);2627    this.collection = new CollectionGroup(this);2628    this.nft = new NFTGroup(this);2629    this.rft = new RFTGroup(this);2630    this.ft = new FTGroup(this);2631    this.staking = new StakingGroup(this);2632    this.scheduler = new SchedulerGroup(this);2633    this.foreignAssets = new ForeignAssetsGroup(this);2634    this.xcm = new XcmGroup(this, 'polkadotXcm');2635    this.xTokens = new XTokensGroup(this);2636    this.tokens = new TokensGroup(this);2637  }26382639  getSudo<T extends UniqueHelper>() {2640    // eslint-disable-next-line @typescript-eslint/naming-convention2641    const SudoHelperType = SudoHelper(this.helperBase);2642    return this.clone(SudoHelperType) as T;2643  }2644}26452646export class XcmChainHelper extends ChainHelperBase {2647  async connect(wsEndpoint: string, _listeners?: any): Promise<void> {2648    const wsProvider = new WsProvider(wsEndpoint);2649    this.api = new ApiPromise({2650      provider: wsProvider,2651    });2652    await this.api.isReadyOrError;2653    this.network = await UniqueHelper.detectNetwork(this.api);2654  }2655}26562657export class RelayHelper extends XcmChainHelper {2658  xcm: XcmGroup<RelayHelper>;26592660  constructor(logger?: ILogger, options: {[key: string]: any} = {}) {2661    super(logger, options.helperBase ?? RelayHelper);26622663    this.xcm = new XcmGroup(this, 'xcmPallet');2664  }2665}26662667export class WestmintHelper extends XcmChainHelper {2668  balance: SubstrateBalanceGroup<WestmintHelper>;2669  xcm: XcmGroup<WestmintHelper>;2670  assets: AssetsGroup<WestmintHelper>;2671  xTokens: XTokensGroup<WestmintHelper>;26722673  constructor(logger?: ILogger, options: {[key: string]: any} = {}) {2674    super(logger, options.helperBase ?? WestmintHelper);26752676    this.balance = new SubstrateBalanceGroup(this);2677    this.xcm = new XcmGroup(this, 'polkadotXcm');2678    this.assets = new AssetsGroup(this);2679    this.xTokens = new XTokensGroup(this);2680  }2681}26822683export class MoonbeamHelper extends XcmChainHelper {2684  balance: EthereumBalanceGroup<MoonbeamHelper>;2685  assetManager: MoonbeamAssetManagerGroup;2686  assets: AssetsGroup<MoonbeamHelper>;2687  xTokens: XTokensGroup<MoonbeamHelper>;2688  democracy: MoonbeamDemocracyGroup;2689  collective: {2690    council: MoonbeamCollectiveGroup,2691    techCommittee: MoonbeamCollectiveGroup,2692  };26932694  constructor(logger?: ILogger, options: {[key: string]: any} = {}) {2695    super(logger, options.helperBase ?? MoonbeamHelper);26962697    this.balance = new EthereumBalanceGroup(this);2698    this.assetManager = new MoonbeamAssetManagerGroup(this);2699    this.assets = new AssetsGroup(this);2700    this.xTokens = new XTokensGroup(this);2701    this.democracy = new MoonbeamDemocracyGroup(this);2702    this.collective = {2703      council: new MoonbeamCollectiveGroup(this, 'councilCollective'),2704      techCommittee: new MoonbeamCollectiveGroup(this, 'techCommitteeCollective'),2705    };2706  }2707}27082709export class AcalaHelper extends XcmChainHelper {2710  balance: SubstrateBalanceGroup<AcalaHelper>;2711  assetRegistry: AcalaAssetRegistryGroup;2712  xTokens: XTokensGroup<AcalaHelper>;2713  tokens: TokensGroup<AcalaHelper>;27142715  constructor(logger?: ILogger, options: {[key: string]: any} = {}) {2716    super(logger, options.helperBase ?? AcalaHelper);27172718    this.balance = new SubstrateBalanceGroup(this);2719    this.assetRegistry = new AcalaAssetRegistryGroup(this);2720    this.xTokens = new XTokensGroup(this);2721    this.tokens = new TokensGroup(this);2722  }27232724  getSudo<T extends AcalaHelper>() {2725    // eslint-disable-next-line @typescript-eslint/naming-convention2726    const SudoHelperType = SudoHelper(this.helperBase);2727    return this.clone(SudoHelperType) as T;2728  }2729}27302731// eslint-disable-next-line @typescript-eslint/naming-convention2732function ScheduledUniqueHelper<T extends UniqueHelperConstructor>(Base: T) {2733  return class extends Base {2734    scheduleFn: 'scheduleNamed' | 'scheduleNamedAfter';2735    scheduledId: string;2736    blocksNum: number;2737    options: ISchedulerOptions;27382739    constructor(...args: any[]) {2740      const logger = args[0] as ILogger;2741      const options = args[1] as {2742        scheduleFn: 'scheduleNamed' | 'scheduleNamedAfter',2743        scheduledId: string,2744        blocksNum: number,2745        options: ISchedulerOptions2746      };27472748      super(logger);27492750      this.scheduleFn = options.scheduleFn;2751      this.scheduledId = options.scheduledId;2752      this.blocksNum = options.blocksNum;2753      this.options = options.options;2754    }27552756    executeExtrinsic(sender: IKeyringPair, scheduledExtrinsic: string, scheduledParams: any[], expectSuccess?: boolean): Promise<ITransactionResult> {2757      const scheduledTx = this.constructApiCall(scheduledExtrinsic, scheduledParams);2758      const extrinsic = 'api.tx.scheduler.' +  this.scheduleFn;27592760      return super.executeExtrinsic(2761        sender,2762        extrinsic,2763        [2764          this.scheduledId,2765          this.blocksNum,2766          this.options.periodic ? [this.options.periodic.period, this.options.periodic.repetitions] : null,2767          this.options.priority ?? null,2768          {Value: scheduledTx},2769        ],2770        expectSuccess,2771      );2772    }2773  };2774}27752776// eslint-disable-next-line @typescript-eslint/naming-convention2777function SudoHelper<T extends ChainHelperBaseConstructor>(Base: T) {2778  return class extends Base {2779    constructor(...args: any[]) {2780      super(...args);2781    }27822783    executeExtrinsic (2784      sender: IKeyringPair,2785      extrinsic: string,2786      params: any[],2787      expectSuccess?: boolean,2788    ): Promise<ITransactionResult> {2789      const call = this.constructApiCall(extrinsic, params);27902791      return super.executeExtrinsic(2792        sender,2793        'api.tx.sudo.sudo',2794        [call],2795        expectSuccess,2796      );2797    }2798  };2799}28002801export class UniqueBaseCollection {2802  helper: UniqueHelper;2803  collectionId: number;28042805  constructor(collectionId: number, uniqueHelper: UniqueHelper) {2806    this.collectionId = collectionId;2807    this.helper = uniqueHelper;2808  }28092810  async getData() {2811    return await this.helper.collection.getData(this.collectionId);2812  }28132814  async getLastTokenId() {2815    return await this.helper.collection.getLastTokenId(this.collectionId);2816  }28172818  async doesTokenExist(tokenId: number) {2819    return await this.helper.collection.doesTokenExist(this.collectionId, tokenId);2820  }28212822  async getAdmins() {2823    return await this.helper.collection.getAdmins(this.collectionId);2824  }28252826  async getAllowList() {2827    return await this.helper.collection.getAllowList(this.collectionId);2828  }28292830  async getEffectiveLimits() {2831    return await this.helper.collection.getEffectiveLimits(this.collectionId);2832  }28332834  async getProperties(propertyKeys?: string[] | null) {2835    return await this.helper.collection.getProperties(this.collectionId, propertyKeys);2836  }28372838  async getTokenNextSponsored(tokenId: number, addressObj: ICrossAccountId) {2839    return await this.helper.collection.getTokenNextSponsored(this.collectionId, tokenId, addressObj);2840  }28412842  async setSponsor(signer: TSigner, sponsorAddress: TSubstrateAccount) {2843    return await this.helper.collection.setSponsor(signer, this.collectionId, sponsorAddress);2844  }28452846  async confirmSponsorship(signer: TSigner) {2847    return await this.helper.collection.confirmSponsorship(signer, this.collectionId);2848  }28492850  async removeSponsor(signer: TSigner) {2851    return await this.helper.collection.removeSponsor(signer, this.collectionId);2852  }28532854  async setLimits(signer: TSigner, limits: ICollectionLimits) {2855    return await this.helper.collection.setLimits(signer, this.collectionId, limits);2856  }28572858  async changeOwner(signer: TSigner, ownerAddress: TSubstrateAccount) {2859    return await this.helper.collection.changeOwner(signer, this.collectionId, ownerAddress);2860  }28612862  async addAdmin(signer: TSigner, adminAddressObj: ICrossAccountId) {2863    return await this.helper.collection.addAdmin(signer, this.collectionId, adminAddressObj);2864  }28652866  async addToAllowList(signer: TSigner, addressObj: ICrossAccountId) {2867    return await this.helper.collection.addToAllowList(signer, this.collectionId, addressObj);2868  }28692870  async removeFromAllowList(signer: TSigner, addressObj: ICrossAccountId) {2871    return await this.helper.collection.removeFromAllowList(signer, this.collectionId, addressObj);2872  }28732874  async removeAdmin(signer: TSigner, adminAddressObj: ICrossAccountId) {2875    return await this.helper.collection.removeAdmin(signer, this.collectionId, adminAddressObj);2876  }28772878  async setProperties(signer: TSigner, properties: IProperty[]) {2879    return await this.helper.collection.setProperties(signer, this.collectionId, properties);2880  }28812882  async deleteProperties(signer: TSigner, propertyKeys: string[]) {2883    return await this.helper.collection.deleteProperties(signer, this.collectionId, propertyKeys);2884  }28852886  async setPermissions(signer: TSigner, permissions: ICollectionPermissions) {2887    return await this.helper.collection.setPermissions(signer, this.collectionId, permissions);2888  }28892890  async enableNesting(signer: TSigner, permissions: INestingPermissions) {2891    return await this.helper.collection.enableNesting(signer, this.collectionId, permissions);2892  }28932894  async disableNesting(signer: TSigner) {2895    return await this.helper.collection.disableNesting(signer, this.collectionId);2896  }28972898  async burn(signer: TSigner) {2899    return await this.helper.collection.burn(signer, this.collectionId);2900  }29012902  scheduleAt<T extends UniqueHelper>(2903    scheduledId: string,2904    executionBlockNumber: number,2905    options: ISchedulerOptions = {},2906  ) {2907    const scheduledHelper = this.helper.scheduler.scheduleAt<T>(scheduledId, executionBlockNumber, options);2908    return new UniqueBaseCollection(this.collectionId, scheduledHelper);2909  }29102911  scheduleAfter<T extends UniqueHelper>(2912    scheduledId: string,2913    blocksBeforeExecution: number,2914    options: ISchedulerOptions = {},2915  ) {2916    const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);2917    return new UniqueBaseCollection(this.collectionId, scheduledHelper);2918  }29192920  getSudo<T extends UniqueHelper>() {2921    return new UniqueBaseCollection(this.collectionId, this.helper.getSudo<T>());2922  }2923}292429252926export class UniqueNFTCollection extends UniqueBaseCollection {2927  getTokenObject(tokenId: number) {2928    return new UniqueNFToken(tokenId, this);2929  }29302931  async getTokensByAddress(addressObj: ICrossAccountId) {2932    return await this.helper.nft.getTokensByAddress(this.collectionId, addressObj);2933  }29342935  async getToken(tokenId: number, blockHashAt?: string) {2936    return await this.helper.nft.getToken(this.collectionId, tokenId, [], blockHashAt);2937  }29382939  async getTokenOwner(tokenId: number, blockHashAt?: string) {2940    return await this.helper.nft.getTokenOwner(this.collectionId, tokenId, blockHashAt);2941  }29422943  async getTokenTopmostOwner(tokenId: number, blockHashAt?: string) {2944    return await this.helper.nft.getTokenTopmostOwner(this.collectionId, tokenId, blockHashAt);2945  }29462947  async getTokenChildren(tokenId: number, blockHashAt?: string) {2948    return await this.helper.nft.getTokenChildren(this.collectionId, tokenId, blockHashAt);2949  }29502951  async getPropertyPermissions(propertyKeys: string[] | null = null) {2952    return await this.helper.nft.getPropertyPermissions(this.collectionId, propertyKeys);2953  }29542955  async getTokenProperties(tokenId: number, propertyKeys?: string[] | null) {2956    return await this.helper.nft.getTokenProperties(this.collectionId, tokenId, propertyKeys);2957  }29582959  async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId) {2960    return await this.helper.nft.transferToken(signer, this.collectionId, tokenId, addressObj);2961  }29622963  async transferTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2964    return await this.helper.nft.transferTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, toAddressObj);2965  }29662967  async approveToken(signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId) {2968    return await this.helper.nft.approveToken(signer, this.collectionId, tokenId, toAddressObj);2969  }29702971  async isTokenApproved(tokenId: number, toAddressObj: ICrossAccountId) {2972    return await this.helper.nft.isTokenApproved(this.collectionId, tokenId, toAddressObj);2973  }29742975  async mintToken(signer: TSigner, owner: ICrossAccountId = {Substrate: signer.address}, properties?: IProperty[]) {2976    return await this.helper.nft.mintToken(signer, {collectionId: this.collectionId, owner, properties});2977  }29782979  async mintMultipleTokens(signer: TSigner, tokens: {owner: ICrossAccountId, properties?: IProperty[]}[]) {2980    return await this.helper.nft.mintMultipleTokens(signer, this.collectionId, tokens);2981  }29822983  async burnToken(signer: TSigner, tokenId: number) {2984    return await this.helper.nft.burnToken(signer, this.collectionId, tokenId);2985  }29862987  async burnTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId) {2988    return await this.helper.nft.burnTokenFrom(signer, this.collectionId, tokenId, fromAddressObj);2989  }29902991  async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[]) {2992    return await this.helper.nft.setTokenProperties(signer, this.collectionId, tokenId, properties);2993  }29942995  async deleteTokenProperties(signer: TSigner, tokenId: number, propertyKeys: string[]) {2996    return await this.helper.nft.deleteTokenProperties(signer, this.collectionId, tokenId, propertyKeys);2997  }29982999  async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[]) {3000    return await this.helper.nft.setTokenPropertyPermissions(signer, this.collectionId, permissions);3001  }30023003  async nestToken(signer: TSigner, tokenId: number, toTokenObj: IToken) {3004    return await this.helper.nft.nestToken(signer, {collectionId: this.collectionId, tokenId}, toTokenObj);3005  }30063007  async unnestToken(signer: TSigner, tokenId: number, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {3008    return await this.helper.nft.unnestToken(signer, {collectionId: this.collectionId, tokenId}, fromTokenObj, toAddressObj);3009  }30103011  scheduleAt<T extends UniqueHelper>(3012    scheduledId: string,3013    executionBlockNumber: number,3014    options: ISchedulerOptions = {},3015  ) {3016    const scheduledHelper = this.helper.scheduler.scheduleAt<T>(scheduledId, executionBlockNumber, options);3017    return new UniqueNFTCollection(this.collectionId, scheduledHelper);3018  }30193020  scheduleAfter<T extends UniqueHelper>(3021    scheduledId: string,3022    blocksBeforeExecution: number,3023    options: ISchedulerOptions = {},3024  ) {3025    const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);3026    return new UniqueNFTCollection(this.collectionId, scheduledHelper);3027  }30283029  getSudo<T extends UniqueHelper>() {3030    return new UniqueNFTCollection(this.collectionId, this.helper.getSudo<T>());3031  }3032}303330343035export class UniqueRFTCollection extends UniqueBaseCollection {3036  getTokenObject(tokenId: number) {3037    return new UniqueRFToken(tokenId, this);3038  }30393040  async getToken(tokenId: number, blockHashAt?: string) {3041    return await this.helper.rft.getToken(this.collectionId, tokenId, [], blockHashAt);3042  }30433044  async getTokensByAddress(addressObj: ICrossAccountId) {3045    return await this.helper.rft.getTokensByAddress(this.collectionId, addressObj);3046  }30473048  async getTop10TokenOwners(tokenId: number) {3049    return await this.helper.rft.getTokenTop10Owners(this.collectionId, tokenId);3050  }30513052  async getTokenBalance(tokenId: number, addressObj: ICrossAccountId) {3053    return await this.helper.rft.getTokenBalance(this.collectionId, tokenId, addressObj);3054  }30553056  async getTokenTotalPieces(tokenId: number) {3057    return await this.helper.rft.getTokenTotalPieces(this.collectionId, tokenId);3058  }30593060  async getTokenApprovedPieces(tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {3061    return await this.helper.rft.getTokenApprovedPieces(this.collectionId, tokenId, toAddressObj, fromAddressObj);3062  }30633064  async getPropertyPermissions(propertyKeys: string[] | null = null) {3065    return await this.helper.rft.getPropertyPermissions(this.collectionId, propertyKeys);3066  }30673068  async getTokenProperties(tokenId: number, propertyKeys?: string[] | null) {3069    return await this.helper.rft.getTokenProperties(this.collectionId, tokenId, propertyKeys);3070  }30713072  async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId, amount=1n) {3073    return await this.helper.rft.transferToken(signer, this.collectionId, tokenId, addressObj, amount);3074  }30753076  async transferTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {3077    return await this.helper.rft.transferTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, toAddressObj, amount);3078  }30793080  async approveToken(signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {3081    return await this.helper.rft.approveToken(signer, this.collectionId, tokenId, toAddressObj, amount);3082  }30833084  async repartitionToken(signer: TSigner, tokenId: number, amount: bigint) {3085    return await this.helper.rft.repartitionToken(signer, this.collectionId, tokenId, amount);3086  }30873088  async mintToken(signer: TSigner, pieces=1n, owner: ICrossAccountId = {Substrate: signer.address}, properties?: IProperty[]) {3089    return await this.helper.rft.mintToken(signer, {collectionId: this.collectionId, owner, pieces, properties});3090  }30913092  async mintMultipleTokens(signer: TSigner, tokens: {pieces: bigint, owner: ICrossAccountId, properties?: IProperty[]}[]) {3093    return await this.helper.rft.mintMultipleTokens(signer, this.collectionId, tokens);3094  }30953096  async burnToken(signer: TSigner, tokenId: number, amount=1n) {3097    return await this.helper.rft.burnToken(signer, this.collectionId, tokenId, amount);3098  }30993100  async burnTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId,  amount=1n) {3101    return await this.helper.rft.burnTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, amount);3102  }31033104  async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[]) {3105    return await this.helper.rft.setTokenProperties(signer, this.collectionId, tokenId, properties);3106  }31073108  async deleteTokenProperties(signer: TSigner, tokenId: number, propertyKeys: string[]) {3109    return await this.helper.rft.deleteTokenProperties(signer, this.collectionId, tokenId, propertyKeys);3110  }31113112  async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[]) {3113    return await this.helper.rft.setTokenPropertyPermissions(signer, this.collectionId, permissions);3114  }31153116  scheduleAt<T extends UniqueHelper>(3117    scheduledId: string,3118    executionBlockNumber: number,3119    options: ISchedulerOptions = {},3120  ) {3121    const scheduledHelper = this.helper.scheduler.scheduleAt<T>(scheduledId, executionBlockNumber, options);3122    return new UniqueRFTCollection(this.collectionId, scheduledHelper);3123  }31243125  scheduleAfter<T extends UniqueHelper>(3126    scheduledId: string,3127    blocksBeforeExecution: number,3128    options: ISchedulerOptions = {},3129  ) {3130    const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);3131    return new UniqueRFTCollection(this.collectionId, scheduledHelper);3132  }31333134  getSudo<T extends UniqueHelper>() {3135    return new UniqueRFTCollection(this.collectionId, this.helper.getSudo<T>());3136  }3137}313831393140export class UniqueFTCollection extends UniqueBaseCollection {3141  async getBalance(addressObj: ICrossAccountId) {3142    return await this.helper.ft.getBalance(this.collectionId, addressObj);3143  }31443145  async getTotalPieces() {3146    return await this.helper.ft.getTotalPieces(this.collectionId);3147  }31483149  async getApprovedTokens(fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {3150    return await this.helper.ft.getApprovedTokens(this.collectionId, fromAddressObj, toAddressObj);3151  }31523153  async getTop10Owners() {3154    return await this.helper.ft.getTop10Owners(this.collectionId);3155  }31563157  async mint(signer: TSigner, amount=1n, owner: ICrossAccountId = {Substrate: signer.address}) {3158    return await this.helper.ft.mintTokens(signer, this.collectionId, amount, owner);3159  }31603161  async mintWithOneOwner(signer: TSigner, tokens: {value: bigint}[], owner: ICrossAccountId = {Substrate: signer.address}) {3162    return await this.helper.ft.mintMultipleTokensWithOneOwner(signer, this.collectionId, tokens, owner);3163  }31643165  async transfer(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {3166    return await this.helper.ft.transfer(signer, this.collectionId, toAddressObj, amount);3167  }31683169  async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {3170    return await this.helper.ft.transferFrom(signer, this.collectionId, fromAddressObj, toAddressObj, amount);3171  }31723173  async burnTokens(signer: TSigner, amount=1n) {3174    return await this.helper.ft.burnTokens(signer, this.collectionId, amount);3175  }31763177  async burnTokensFrom(signer: TSigner, fromAddressObj: ICrossAccountId, amount=1n) {3178    return await this.helper.ft.burnTokensFrom(signer, this.collectionId, fromAddressObj, amount);3179  }31803181  async approveTokens(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {3182    return await this.helper.ft.approveTokens(signer, this.collectionId, toAddressObj, amount);3183  }31843185  scheduleAt<T extends UniqueHelper>(3186    scheduledId: string,3187    executionBlockNumber: number,3188    options: ISchedulerOptions = {},3189  ) {3190    const scheduledHelper = this.helper.scheduler.scheduleAt<T>(scheduledId, executionBlockNumber, options);3191    return new UniqueFTCollection(this.collectionId, scheduledHelper);3192  }31933194  scheduleAfter<T extends UniqueHelper>(3195    scheduledId: string,3196    blocksBeforeExecution: number,3197    options: ISchedulerOptions = {},3198  ) {3199    const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);3200    return new UniqueFTCollection(this.collectionId, scheduledHelper);3201  }32023203  getSudo<T extends UniqueHelper>() {3204    return new UniqueFTCollection(this.collectionId, this.helper.getSudo<T>());3205  }3206}320732083209export class UniqueBaseToken {3210  collection: UniqueNFTCollection | UniqueRFTCollection;3211  collectionId: number;3212  tokenId: number;32133214  constructor(tokenId: number, collection: UniqueNFTCollection | UniqueRFTCollection) {3215    this.collection = collection;3216    this.collectionId = collection.collectionId;3217    this.tokenId = tokenId;3218  }32193220  async getNextSponsored(addressObj: ICrossAccountId) {3221    return await this.collection.getTokenNextSponsored(this.tokenId, addressObj);3222  }32233224  async getProperties(propertyKeys?: string[] | null) {3225    return await this.collection.getTokenProperties(this.tokenId, propertyKeys);3226  }32273228  async setProperties(signer: TSigner, properties: IProperty[]) {3229    return await this.collection.setTokenProperties(signer, this.tokenId, properties);3230  }32313232  async deleteProperties(signer: TSigner, propertyKeys: string[]) {3233    return await this.collection.deleteTokenProperties(signer, this.tokenId, propertyKeys);3234  }32353236  async doesExist() {3237    return await this.collection.doesTokenExist(this.tokenId);3238  }32393240  nestingAccount() {3241    return this.collection.helper.util.getTokenAccount(this);3242  }32433244  scheduleAt<T extends UniqueHelper>(3245    scheduledId: string,3246    executionBlockNumber: number,3247    options: ISchedulerOptions = {},3248  ) {3249    const scheduledCollection = this.collection.scheduleAt<T>(scheduledId, executionBlockNumber, options);3250    return new UniqueBaseToken(this.tokenId, scheduledCollection);3251  }32523253  scheduleAfter<T extends UniqueHelper>(3254    scheduledId: string,3255    blocksBeforeExecution: number,3256    options: ISchedulerOptions = {},3257  ) {3258    const scheduledCollection = this.collection.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);3259    return new UniqueBaseToken(this.tokenId, scheduledCollection);3260  }32613262  getSudo<T extends UniqueHelper>() {3263    return new UniqueBaseToken(this.tokenId, this.collection.getSudo<T>());3264  }3265}326632673268export class UniqueNFToken extends UniqueBaseToken {3269  collection: UniqueNFTCollection;32703271  constructor(tokenId: number, collection: UniqueNFTCollection) {3272    super(tokenId, collection);3273    this.collection = collection;3274  }32753276  async getData(blockHashAt?: string) {3277    return await this.collection.getToken(this.tokenId, blockHashAt);3278  }32793280  async getOwner(blockHashAt?: string) {3281    return await this.collection.getTokenOwner(this.tokenId, blockHashAt);3282  }32833284  async getTopmostOwner(blockHashAt?: string) {3285    return await this.collection.getTokenTopmostOwner(this.tokenId, blockHashAt);3286  }32873288  async getChildren(blockHashAt?: string) {3289    return await this.collection.getTokenChildren(this.tokenId, blockHashAt);3290  }32913292  async nest(signer: TSigner, toTokenObj: IToken) {3293    return await this.collection.nestToken(signer, this.tokenId, toTokenObj);3294  }32953296  async unnest(signer: TSigner, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {3297    return await this.collection.unnestToken(signer, this.tokenId, fromTokenObj, toAddressObj);3298  }32993300  async transfer(signer: TSigner, addressObj: ICrossAccountId) {3301    return await this.collection.transferToken(signer, this.tokenId, addressObj);3302  }33033304  async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {3305    return await this.collection.transferTokenFrom(signer, this.tokenId, fromAddressObj, toAddressObj);3306  }33073308  async approve(signer: TSigner, toAddressObj: ICrossAccountId) {3309    return await this.collection.approveToken(signer, this.tokenId, toAddressObj);3310  }33113312  async isApproved(toAddressObj: ICrossAccountId) {3313    return await this.collection.isTokenApproved(this.tokenId, toAddressObj);3314  }33153316  async burn(signer: TSigner) {3317    return await this.collection.burnToken(signer, this.tokenId);3318  }33193320  async burnFrom(signer: TSigner, fromAddressObj: ICrossAccountId) {3321    return await this.collection.burnTokenFrom(signer, this.tokenId, fromAddressObj);3322  }33233324  scheduleAt<T extends UniqueHelper>(3325    scheduledId: string,3326    executionBlockNumber: number,3327    options: ISchedulerOptions = {},3328  ) {3329    const scheduledCollection = this.collection.scheduleAt<T>(scheduledId, executionBlockNumber, options);3330    return new UniqueNFToken(this.tokenId, scheduledCollection);3331  }33323333  scheduleAfter<T extends UniqueHelper>(3334    scheduledId: string,3335    blocksBeforeExecution: number,3336    options: ISchedulerOptions = {},3337  ) {3338    const scheduledCollection = this.collection.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);3339    return new UniqueNFToken(this.tokenId, scheduledCollection);3340  }33413342  getSudo<T extends UniqueHelper>() {3343    return new UniqueNFToken(this.tokenId, this.collection.getSudo<T>());3344  }3345}33463347export class UniqueRFToken extends UniqueBaseToken {3348  collection: UniqueRFTCollection;33493350  constructor(tokenId: number, collection: UniqueRFTCollection) {3351    super(tokenId, collection);3352    this.collection = collection;3353  }33543355  async getData(blockHashAt?: string) {3356    return await this.collection.getToken(this.tokenId, blockHashAt);3357  }33583359  async getTop10Owners() {3360    return await this.collection.getTop10TokenOwners(this.tokenId);3361  }33623363  async getBalance(addressObj: ICrossAccountId) {3364    return await this.collection.getTokenBalance(this.tokenId, addressObj);3365  }33663367  async getTotalPieces() {3368    return await this.collection.getTokenTotalPieces(this.tokenId);3369  }33703371  async getApprovedPieces(fromAddressObj: ICrossAccountId, toAccountObj: ICrossAccountId) {3372    return await this.collection.getTokenApprovedPieces(this.tokenId, fromAddressObj, toAccountObj);3373  }33743375  async transfer(signer: TSigner, addressObj: ICrossAccountId, amount=1n) {3376    return await this.collection.transferToken(signer, this.tokenId, addressObj, amount);3377  }33783379  async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {3380    return await this.collection.transferTokenFrom(signer, this.tokenId, fromAddressObj, toAddressObj, amount);3381  }33823383  async approve(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {3384    return await this.collection.approveToken(signer, this.tokenId, toAddressObj, amount);3385  }33863387  async repartition(signer: TSigner, amount: bigint) {3388    return await this.collection.repartitionToken(signer, this.tokenId, amount);3389  }33903391  async burn(signer: TSigner, amount=1n) {3392    return await this.collection.burnToken(signer, this.tokenId, amount);3393  }33943395  async burnFrom(signer: TSigner, fromAddressObj: ICrossAccountId, amount=1n) {3396    return await this.collection.burnTokenFrom(signer, this.tokenId, fromAddressObj, amount);3397  }33983399  scheduleAt<T extends UniqueHelper>(3400    scheduledId: string,3401    executionBlockNumber: number,3402    options: ISchedulerOptions = {},3403  ) {3404    const scheduledCollection = this.collection.scheduleAt<T>(scheduledId, executionBlockNumber, options);3405    return new UniqueRFToken(this.tokenId, scheduledCollection);3406  }34073408  scheduleAfter<T extends UniqueHelper>(3409    scheduledId: string,3410    blocksBeforeExecution: number,3411    options: ISchedulerOptions = {},3412  ) {3413    const scheduledCollection = this.collection.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);3414    return new UniqueRFToken(this.tokenId, scheduledCollection);3415  }34163417  getSudo<T extends UniqueHelper>() {3418    return new UniqueRFToken(this.tokenId, this.collection.getSudo<T>());3419  }3420}
after · tests/src/util/playgrounds/unique.ts
1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// SPDX-License-Identifier: Apache-2.034/* eslint-disable @typescript-eslint/no-var-requires */5/* eslint-disable function-call-argument-newline */6/* eslint-disable no-prototype-builtins */78import {ApiPromise, WsProvider, Keyring} from '@polkadot/api';9import {ApiInterfaceEvents, SignerOptions} from '@polkadot/api/types';10import {encodeAddress, decodeAddress, keccakAsHex, evmToAddress, addressToEvm} from '@polkadot/util-crypto';11import {IKeyringPair} from '@polkadot/types/types';12import {IApiListeners, IBlock, IEvent, IChainProperties, ICollectionCreationOptions, ICollectionLimits, ICollectionPermissions, ICrossAccountId, ICrossAccountIdLower, ILogger, INestingPermissions, IProperty, IStakingInfo, ISchedulerOptions, ISubstrateBalance, IToken, ITokenPropertyPermission, ITransactionResult, IUniqueHelperLog, TApiAllowedListeners, TEthereumAccount, TSigner, TSubstrateAccount, IForeignAssetMetadata, TNetworks, MoonbeamAssetInfo, DemocracyStandardAccountVote, AcalaAssetMetadata} from './types';1314export class CrossAccountId implements ICrossAccountId {15  Substrate?: TSubstrateAccount;16  Ethereum?: TEthereumAccount;1718  constructor(account: ICrossAccountId) {19    if (account.Substrate) this.Substrate = account.Substrate;20    if (account.Ethereum) this.Ethereum = account.Ethereum;21  }2223  static fromKeyring(account: IKeyringPair, domain: 'Substrate' | 'Ethereum' = 'Substrate') {24    switch (domain) {25      case 'Substrate': return new CrossAccountId({Substrate: account.address});26      case 'Ethereum': return new CrossAccountId({Substrate: account.address}).toEthereum();27    }28  }2930  static fromLowerCaseKeys(address: ICrossAccountIdLower): CrossAccountId {31    return new CrossAccountId({Substrate: address.substrate, Ethereum: address.ethereum});32  }3334  static normalizeSubstrateAddress(address: TSubstrateAccount, ss58Format = 42): TSubstrateAccount {35    return encodeAddress(decodeAddress(address), ss58Format);36  }3738  static withNormalizedSubstrate(address: TSubstrateAccount, ss58Format = 42): CrossAccountId {39    return new CrossAccountId({Substrate: CrossAccountId.normalizeSubstrateAddress(address, ss58Format)});40  }41  42  withNormalizedSubstrate(ss58Format = 42): CrossAccountId {43    if (this.Substrate) return CrossAccountId.withNormalizedSubstrate(this.Substrate, ss58Format);44    return this;45  }4647  static translateSubToEth(address: TSubstrateAccount): TEthereumAccount {48    return nesting.toChecksumAddress('0x' + Array.from(addressToEvm(address), i => i.toString(16).padStart(2, '0')).join(''));49  }5051  toEthereum(): CrossAccountId {52    if (this.Substrate) return new CrossAccountId({Ethereum: CrossAccountId.translateSubToEth(this.Substrate)});53    return this;54  }5556  static translateEthToSub(address: TEthereumAccount, ss58Format?: number): TSubstrateAccount {57    return evmToAddress(address, ss58Format);58  }5960  toSubstrate(ss58Format?: number): CrossAccountId {61    if (this.Ethereum) return new CrossAccountId({Substrate: CrossAccountId.translateEthToSub(this.Ethereum, ss58Format)});62    return this;63  }64  65  toLowerCase(): CrossAccountId {66    if (this.Substrate) this.Substrate = this.Substrate.toLowerCase();67    if (this.Ethereum) this.Ethereum = this.Ethereum.toLowerCase();68    return this;69  }70}7172const nesting = {73  toChecksumAddress(address: string): string {74    if (typeof address === 'undefined') return '';7576    if(!/^(0x)?[0-9a-f]{40}$/i.test(address)) throw new Error(`Given address "${address}" is not a valid Ethereum address.`);7778    address = address.toLowerCase().replace(/^0x/i,'');79    const addressHash = keccakAsHex(address).replace(/^0x/i,'');80    const checksumAddress = ['0x'];8182    for (let i = 0; i < address.length; i++) {83      // If ith character is 8 to f then make it uppercase84      if (parseInt(addressHash[i], 16) > 7) {85        checksumAddress.push(address[i].toUpperCase());86      } else {87        checksumAddress.push(address[i]);88      }89    }90    return checksumAddress.join('');91  },92  tokenIdToAddress(collectionId: number, tokenId: number) {93    return this.toChecksumAddress(`0xf8238ccfff8ed887463fd5e0${collectionId.toString(16).padStart(8, '0')}${tokenId.toString(16).padStart(8, '0')}`);94  },95};9697class UniqueUtil {98  static transactionStatus = {99    NOT_READY: 'NotReady',100    FAIL: 'Fail',101    SUCCESS: 'Success',102  };103104  static chainLogType = {105    EXTRINSIC: 'extrinsic',106    RPC: 'rpc',107  };108109  static getTokenAccount(token: IToken): CrossAccountId {110    return new CrossAccountId({Ethereum: this.getTokenAddress(token)});111  }112113  static getTokenAddress(token: IToken): string {114    return nesting.tokenIdToAddress(token.collectionId, token.tokenId);115  }116117  static getDefaultLogger(): ILogger {118    return {119      log(msg: any, level = 'INFO') {120        console[level.toLocaleLowerCase() === 'error' ? 'error' : 'log'](...(Array.isArray(msg) ? msg : [msg]));121      },122      level: {123        ERROR: 'ERROR',124        WARNING: 'WARNING',125        INFO: 'INFO',126      },127    };128  }129130  static vec2str(arr: string[] | number[]) {131    return arr.map(x => String.fromCharCode(parseInt(x.toString()))).join('');132  }133134  static str2vec(string: string) {135    if (typeof string !== 'string') return string;136    return Array.from(string).map(x => x.charCodeAt(0));137  }138139  static fromSeed(seed: string, ss58Format = 42) {140    const keyring = new Keyring({type: 'sr25519', ss58Format});141    return keyring.addFromUri(seed);142  }143144  static extractCollectionIdFromCreationResult(creationResult: ITransactionResult): number {145    if (creationResult.status !== this.transactionStatus.SUCCESS) {146      throw Error('Unable to create collection!');147    }148149    let collectionId = null;150    creationResult.result.events.forEach(({event: {data, method, section}}) => {151      if ((section === 'common') && (method === 'CollectionCreated')) {152        collectionId = parseInt(data[0].toString(), 10);153      }154    });155156    if (collectionId === null) {157      throw Error('No CollectionCreated event was found!');158    }159160    return collectionId;161  }162163  static extractTokensFromCreationResult(creationResult: ITransactionResult): {164    success: boolean, 165    tokens: {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[],166  } {167    if (creationResult.status !== this.transactionStatus.SUCCESS) {168      throw Error('Unable to create tokens!');169    }170    let success = false;171    const tokens = [] as {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[];172    creationResult.result.events.forEach(({event: {data, method, section}}) => {173      if (method === 'ExtrinsicSuccess') {174        success = true;175      } else if ((section === 'common') && (method === 'ItemCreated')) {176        tokens.push({177          collectionId: parseInt(data[0].toString(), 10),178          tokenId: parseInt(data[1].toString(), 10),179          owner: data[2].toHuman(),180          amount: data[3].toBigInt(),181        });182      }183    });184    return {success, tokens};185  }186187  static extractTokensFromBurnResult(burnResult: ITransactionResult): {188    success: boolean, 189    tokens: {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[],190  } {191    if (burnResult.status !== this.transactionStatus.SUCCESS) {192      throw Error('Unable to burn tokens!');193    }194    let success = false;195    const tokens = [] as {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[];196    burnResult.result.events.forEach(({event: {data, method, section}}) => {197      if (method === 'ExtrinsicSuccess') {198        success = true;199      } else if ((section === 'common') && (method === 'ItemDestroyed')) {200        tokens.push({201          collectionId: parseInt(data[0].toString(), 10),202          tokenId: parseInt(data[1].toString(), 10),203          owner: data[2].toHuman(),204          amount: data[3].toBigInt(),205        });206      }207    });208    return {success, tokens};209  }210211  static findCollectionInEvents(events: {event: IEvent}[], collectionId: number, expectedSection: string, expectedMethod: string): boolean {212    let eventId = null;213    events.forEach(({event: {data, method, section}}) => {214      if ((section === expectedSection) && (method === expectedMethod)) {215        eventId = parseInt(data[0].toString(), 10);216      }217    });218219    if (eventId === null) {220      throw Error(`No ${expectedMethod} event was found!`);221    }222    return eventId === collectionId;223  }224225  static isTokenTransferSuccess(events: {event: IEvent}[], collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {226    const normalizeAddress = (address: string | ICrossAccountId) => {227      if(typeof address === 'string') return address;228      const obj = {} as any;229      Object.keys(address).forEach(k => {230        obj[k.toLocaleLowerCase()] = address[k as 'Substrate' | 'Ethereum'];231      });232      if(obj.substrate) return CrossAccountId.withNormalizedSubstrate(obj.substrate);233      if(obj.ethereum) return CrossAccountId.fromLowerCaseKeys(obj).toLowerCase();234      return address;235    };236    let transfer = {collectionId: null, tokenId: null, from: null, to: null, amount: 1} as any;237    events.forEach(({event: {data, method, section}}) => {238      if ((section === 'common') && (method === 'Transfer')) {239        const hData = (data as any).toJSON();240        transfer = {241          collectionId: hData[0],242          tokenId: hData[1],243          from: normalizeAddress(hData[2]),244          to: normalizeAddress(hData[3]),245          amount: BigInt(hData[4]),246        };247      }248    });249    let isSuccess = parseInt(collectionId.toString()) === transfer.collectionId && parseInt(tokenId.toString()) === transfer.tokenId;250    isSuccess = isSuccess && JSON.stringify(normalizeAddress(fromAddressObj)) === JSON.stringify(transfer.from);251    isSuccess = isSuccess && JSON.stringify(normalizeAddress(toAddressObj)) === JSON.stringify(transfer.to);252    isSuccess = isSuccess && amount === transfer.amount;253    return isSuccess;254  }255256  static bigIntToDecimals(number: bigint, decimals = 18) {257    const numberStr = number.toString();258    const dotPos = numberStr.length - decimals;259  260    if (dotPos <= 0) {261      return '0.' + '0'.repeat(Math.abs(dotPos)) + numberStr;262    } else {263      const intPart = numberStr.substring(0, dotPos);264      const fractPart = numberStr.substring(dotPos);265      return intPart + '.' + fractPart;266    }267  }268}269270class UniqueEventHelper {271  private static extractIndex(index: any): [number, number] | string {272    if(index.toRawType() === '[u8;2]') return [index[0], index[1]];273    return index.toJSON();274  }275276  private static extractSub(data: any, subTypes: any): {[key: string]: any} {277    let obj: any = {};278    let index = 0;279280    if (data.entries) {281      for(const [key, value] of data.entries()) {282        obj[key] = this.extractData(value, subTypes[index]);283        index++;284      }285    } else obj = data.toJSON();286287    return obj;288  }289  290  private static extractData(data: any, type: any): any {291    if(!type) return data.toHuman();292    if (['u16', 'u32'].indexOf(type.type) > -1) return data.toNumber();293    if (['u64', 'u128', 'u256'].indexOf(type.type) > -1) return data.toBigInt();294    if(type.hasOwnProperty('sub')) return this.extractSub(data, type.sub);295    return data.toHuman();296  }297298  public static extractEvents(events: {event: any, phase: any}[]): IEvent[] {299    const parsedEvents: IEvent[] = [];300301    events.forEach((record) => {302      const {event, phase} = record;303      const types = event.typeDef;304305      const eventData: IEvent = {306        section: event.section.toString(),307        method: event.method.toString(),308        index: this.extractIndex(event.index),309        data: [],310        phase: phase.toJSON(),311      };312313      event.data.forEach((val: any, index: number) => {314        eventData.data.push(this.extractData(val, types[index]));315      });316317      parsedEvents.push(eventData);318    });319320    return parsedEvents;321  }322}323324export class ChainHelperBase {325  helperBase: any;326327  transactionStatus = UniqueUtil.transactionStatus;328  chainLogType = UniqueUtil.chainLogType;329  util: typeof UniqueUtil;330  eventHelper: typeof UniqueEventHelper;331  logger: ILogger;332  api: ApiPromise | null;333  forcedNetwork: TNetworks | null;334  network: TNetworks | null;335  chainLog: IUniqueHelperLog[];336  children: ChainHelperBase[];337  address: AddressGroup;338  chain: ChainGroup;339340  constructor(logger?: ILogger, helperBase?: any) {341    this.helperBase = helperBase;342343    this.util = UniqueUtil;344    this.eventHelper = UniqueEventHelper;345    if (typeof logger == 'undefined') logger = this.util.getDefaultLogger();346    this.logger = logger;347    this.api = null;348    this.forcedNetwork = null;349    this.network = null;350    this.chainLog = [];351    this.children = [];352    this.address = new AddressGroup(this);353    this.chain = new ChainGroup(this);354  }355356  clone(helperCls: ChainHelperBaseConstructor, options: {[key: string]: any} = {}) {357    Object.setPrototypeOf(helperCls.prototype, this);358    const newHelper = new helperCls(this.logger, options);359360    newHelper.api = this.api;361    newHelper.network = this.network;362    newHelper.forceNetwork = this.forceNetwork;363364    this.children.push(newHelper);365366    return newHelper;367  }368369  getApi(): ApiPromise {370    if(this.api === null) throw Error('API not initialized');371    return this.api;372  }373374  clearChainLog(): void {375    this.chainLog = [];376  }377378  forceNetwork(value: TNetworks): void {379    this.forcedNetwork = value;380  }381382  async connect(wsEndpoint: string, listeners?: IApiListeners) {383    if (this.api !== null) throw Error('Already connected');384    const {api, network} = await ChainHelperBase.createConnection(wsEndpoint, listeners, this.forcedNetwork);385    this.api = api;386    this.network = network;387  }388389  async disconnect() {390    for (const child of this.children) {391      child.clearApi();392    }393394    if (this.api === null) return;395    await this.api.disconnect();396    this.clearApi();397  }398399  clearApi() {400    this.api = null;401    this.network = null;402  }403404  static async detectNetwork(api: ApiPromise): Promise<TNetworks> {405    const spec = (await api.query.system.lastRuntimeUpgrade()).toJSON() as any;406    const xcmChains = ['rococo', 'westend', 'westmint', 'acala', 'karura', 'moonbeam', 'moonriver'];407408    if(xcmChains.indexOf(spec.specName) > -1) return spec.specName;409410    if(['quartz', 'unique'].indexOf(spec.specName) > -1) return spec.specName;411    return 'opal';412  }413414  static async detectNetworkByWsEndpoint(wsEndpoint: string): Promise<TNetworks> {415    const api = new ApiPromise({provider: new WsProvider(wsEndpoint)});416    await api.isReady;417418    const network = await this.detectNetwork(api);419420    await api.disconnect();421422    return network;423  }424425  static async createConnection(wsEndpoint: string, listeners?: IApiListeners, network?: TNetworks | null): Promise<{426    api: ApiPromise;427    network: TNetworks;428  }> {429    if(typeof network === 'undefined' || network === null) network = 'opal';430    const supportedRPC = {431      opal: {432        unique: require('@unique-nft/opal-testnet-types/definitions').unique.rpc,433      },434      quartz: {435        unique: require('@unique-nft/quartz-mainnet-types/definitions').unique.rpc,436      },437      unique: {438        unique: require('@unique-nft/unique-mainnet-types/definitions').unique.rpc,439      },440      rococo: {},441      westend: {},442      moonbeam: {},443      moonriver: {},444      acala: {},445      karura: {},446      westmint: {},447    };448    if(!supportedRPC.hasOwnProperty(network)) network = await this.detectNetworkByWsEndpoint(wsEndpoint);449    const rpc = supportedRPC[network];450451    // TODO: investigate how to replace rpc in runtime452    // api._rpcCore.addUserInterfaces(rpc);453454    const api = new ApiPromise({provider: new WsProvider(wsEndpoint), rpc});455456    await api.isReadyOrError;457458    if (typeof listeners === 'undefined') listeners = {};459    for (const event of ['connected', 'disconnected', 'error', 'ready', 'decorated']) {460      if (!listeners.hasOwnProperty(event) || typeof listeners[event as TApiAllowedListeners] === 'undefined') continue;461      api.on(event as ApiInterfaceEvents, listeners[event as TApiAllowedListeners] as (...args: any[]) => any);462    }463464    return {api, network};465  }466467  getTransactionStatus(data: {events: {event: IEvent}[], status: any}) {468    const {events, status} = data;469    if (status.isReady) {470      return this.transactionStatus.NOT_READY;471    }472    if (status.isBroadcast) {473      return this.transactionStatus.NOT_READY;474    }475    if (status.isInBlock || status.isFinalized) {476      const errors = events.filter(e => e.event.method === 'ExtrinsicFailed');477      if (errors.length > 0) {478        return this.transactionStatus.FAIL;479      }480      if (events.filter(e => e.event.method === 'ExtrinsicSuccess').length > 0) {481        return this.transactionStatus.SUCCESS;482      }483    }484485    return this.transactionStatus.FAIL;486  }487488  signTransaction(sender: TSigner, transaction: any, options: Partial<SignerOptions> | null = null, label = 'transaction') {489    const sign = (callback: any) => {490      if(options !== null) return transaction.signAndSend(sender, options, callback);491      return transaction.signAndSend(sender, callback);492    };493    // eslint-disable-next-line no-async-promise-executor494    return new Promise(async (resolve, reject) => {495      try {496        const unsub = await sign((result: any) => {497          const status = this.getTransactionStatus(result);498499          if (status === this.transactionStatus.SUCCESS) {500            this.logger.log(`${label} successful`);501            unsub();502            resolve({result, status});503          } else if (status === this.transactionStatus.FAIL) {504            let moduleError = null;505506            if (result.hasOwnProperty('dispatchError')) {507              const dispatchError = result['dispatchError'];508509              if (dispatchError) {510                if (dispatchError.isModule) {511                  const modErr = dispatchError.asModule;512                  const errorMeta = dispatchError.registry.findMetaError(modErr);513514                  moduleError = `${errorMeta.section}.${errorMeta.name}`;515                } else {516                  moduleError = dispatchError.toHuman();517                }518              } else {519                this.logger.log(result, this.logger.level.ERROR);520              }521            }522523            this.logger.log(`Something went wrong with ${label}. Status: ${status}`, this.logger.level.ERROR);524            unsub();525            reject({status, moduleError, result});526          }527        });528      } catch (e) {529        this.logger.log(e, this.logger.level.ERROR);530        reject(e);531      }532    });533  }534535  constructApiCall(apiCall: string, params: any[]) {536    if(!apiCall.startsWith('api.')) throw Error(`Invalid api call: ${apiCall}`);537    let call = this.getApi() as any;538    for(const part of apiCall.slice(4).split('.')) {539      call = call[part];540    }541    return call(...params);542  }543544  async executeExtrinsic(sender: TSigner, extrinsic: string, params: any[], expectSuccess=true, options: Partial<SignerOptions>|null = null/*, failureMessage='expected success'*/) {545    if(this.api === null) throw Error('API not initialized');546    if(!extrinsic.startsWith('api.tx.')) throw Error(`${extrinsic} is not transaction`);547548    const startTime = (new Date()).getTime();549    let result: ITransactionResult;550    let events: IEvent[] = [];551    try {552      result = await this.signTransaction(sender, this.constructApiCall(extrinsic, params), options, extrinsic) as ITransactionResult;553      events = this.eventHelper.extractEvents(result.result.events);554    }555    catch(e) {556      if(!(e as object).hasOwnProperty('status')) throw e;557      result = e as ITransactionResult;558    }559560    const endTime = (new Date()).getTime();561562    const log = {563      executedAt: endTime,564      executionTime: endTime - startTime,565      type: this.chainLogType.EXTRINSIC,566      status: result.status,567      call: extrinsic,568      signer: this.getSignerAddress(sender),569      params,570    } as IUniqueHelperLog;571572    if(result.status !== this.transactionStatus.SUCCESS) {573      if (result.moduleError) log.moduleError = result.moduleError;574      else if (result.result.dispatchError) log.dispatchError = result.result.dispatchError;575    }576    if(events.length > 0) log.events = events;577578    this.chainLog.push(log);579580    if(expectSuccess && result.status !== this.transactionStatus.SUCCESS) {581      if (result.moduleError) throw Error(`${result.moduleError}`);582      else if (result.result.dispatchError) throw Error(JSON.stringify(result.result.dispatchError));583    }584    return result;585  }586587  async callRpc(rpc: string, params?: any[]) {588    if(typeof params === 'undefined') params = [];589    if(this.api === null) throw Error('API not initialized');590    if(!rpc.startsWith('api.rpc.') && !rpc.startsWith('api.query.')) throw Error(`${rpc} is not RPC call`);591592    const startTime = (new Date()).getTime();593    let result;594    let error = null;595    const log = {596      type: this.chainLogType.RPC,597      call: rpc,598      params,599    } as IUniqueHelperLog;600601    try {602      result = await this.constructApiCall(rpc, params);603    }604    catch(e) {605      error = e;606    }607608    const endTime = (new Date()).getTime();609610    log.executedAt = endTime;611    log.status = (error === null ? this.transactionStatus.SUCCESS : this.transactionStatus.FAIL) as 'Fail' | 'Success';612    log.executionTime = endTime - startTime;613614    this.chainLog.push(log);615616    if(error !== null) throw error;617618    return result;619  }620621  getSignerAddress(signer: IKeyringPair | string): string {622    if(typeof signer === 'string') return signer;623    return signer.address;624  }625626  fetchAllPalletNames(): string[] {627    if(this.api === null) throw Error('API not initialized');628    return this.api.runtimeMetadata.asLatest.pallets.map(m => m.name.toString().toLowerCase());629  }630631  fetchMissingPalletNames(requiredPallets: string[]): string[] {632    const palletNames = this.fetchAllPalletNames();633    return requiredPallets.filter(p => !palletNames.includes(p));634  }635}636637638class HelperGroup<T extends ChainHelperBase> {639  helper: T;640641  constructor(uniqueHelper: T) {642    this.helper = uniqueHelper;643  }644}645646647class CollectionGroup extends HelperGroup<UniqueHelper> {648  /**649 * Get number of blocks when sponsored transaction is available.650 *651 * @param collectionId ID of collection652 * @param tokenId ID of token653 * @param addressObj address for which the sponsorship is checked654 * @example await getTokenNextSponsored(1, 2, {Substrate: '5DfhbVfww7ThF8q6f3...'});655 * @returns number of blocks or null if sponsorship hasn't been set656 */657  async getTokenNextSponsored(collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<number | null> {658    return (await this.helper.callRpc('api.rpc.unique.nextSponsored', [collectionId, addressObj, tokenId])).toJSON();659  }660661  /**662   * Get the number of created collections.663   *664   * @returns number of created collections665   */666  async getTotalCount(): Promise<number> {667    return (await this.helper.callRpc('api.rpc.unique.collectionStats')).created.toNumber();668  }669670  /**671   * Get information about the collection with additional data,672   * including the number of tokens it contains, its administrators,673   * the normalized address of the collection's owner, and decoded name and description.674   *675   * @param collectionId ID of collection676   * @example await getData(2)677   * @returns collection information object678   */679  async getData(collectionId: number): Promise<{680    id: number;681    name: string;682    description: string;683    tokensCount: number;684    admins: CrossAccountId[];685    normalizedOwner: TSubstrateAccount;686    raw: any687  } | null> {688    const collection = await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId]);689    const humanCollection = collection.toHuman(), collectionData = {690      id: collectionId, name: null, description: null, tokensCount: 0, admins: [],691      raw: humanCollection,692    } as any, jsonCollection = collection.toJSON();693    if (humanCollection === null) return null;694    collectionData.raw.limits = jsonCollection.limits;695    collectionData.raw.permissions = jsonCollection.permissions;696    collectionData.normalizedOwner = this.helper.address.normalizeSubstrate(collectionData.raw.owner);697    for (const key of ['name', 'description']) {698      collectionData[key] = this.helper.util.vec2str(humanCollection[key]);699    }700701    collectionData.tokensCount = (['RFT', 'NFT'].includes(humanCollection.mode))702      ? await this.helper[humanCollection.mode.toLocaleLowerCase() as 'nft' | 'rft'].getLastTokenId(collectionId)703      : 0;704    collectionData.admins = await this.getAdmins(collectionId);705706    return collectionData;707  }708709  /**710   * Get the addresses of the collection's administrators, optionally normalized.711   *712   * @param collectionId ID of collection713   * @param normalize whether to normalize the addresses to the default ss58 format714   * @example await getAdmins(1)715   * @returns array of administrators716   */717  async getAdmins(collectionId: number, normalize = false): Promise<CrossAccountId[]> {718    const admins = (await this.helper.callRpc('api.rpc.unique.adminlist', [collectionId])).toHuman();719720    return normalize721      ? admins.map((address: CrossAccountId) => address.withNormalizedSubstrate())722      : admins;723  }724725  /**726   * Get the addresses added to the collection allow-list, optionally normalized.727   * @param collectionId ID of collection728   * @param normalize whether to normalize the addresses to the default ss58 format729   * @example await getAllowList(1)730   * @returns array of allow-listed addresses731   */732  async getAllowList(collectionId: number, normalize = false): Promise<CrossAccountId[]> {733    const allowListed = (await this.helper.callRpc('api.rpc.unique.allowlist', [collectionId])).toHuman();734    return normalize735      ? allowListed.map((address: CrossAccountId) => address.withNormalizedSubstrate())736      : allowListed;737  }738739  /**740   * Get the effective limits of the collection instead of null for default values741   *742   * @param collectionId ID of collection743   * @example await getEffectiveLimits(2)744   * @returns object of collection limits745   */746  async getEffectiveLimits(collectionId: number): Promise<ICollectionLimits> {747    return (await this.helper.callRpc('api.rpc.unique.effectiveCollectionLimits', [collectionId])).toJSON();748  }749750  /**751   * Burns the collection if the signer has sufficient permissions and collection is empty.752   *753   * @param signer keyring of signer754   * @param collectionId ID of collection755   * @example await helper.collection.burn(aliceKeyring, 3);756   * @returns ```true``` if extrinsic success, otherwise ```false```757   */758  async burn(signer: TSigner, collectionId: number): Promise<boolean> {759    const result = await this.helper.executeExtrinsic(760      signer,761      'api.tx.unique.destroyCollection', [collectionId],762      true,763    );764765    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionDestroyed');766  }767768  /**769   * Sets the sponsor for the collection (Requires the Substrate address). Needs confirmation by the sponsor.770   *771   * @param signer keyring of signer772   * @param collectionId ID of collection773   * @param sponsorAddress Sponsor substrate address774   * @example setSponsor(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...")775   * @returns ```true``` if extrinsic success, otherwise ```false```776   */777  async setSponsor(signer: TSigner, collectionId: number, sponsorAddress: TSubstrateAccount): Promise<boolean> {778    const result = await this.helper.executeExtrinsic(779      signer,780      'api.tx.unique.setCollectionSponsor', [collectionId, sponsorAddress],781      true,782    );783784    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionSponsorSet');785  }786787  /**788   * Confirms consent to sponsor the collection on behalf of the signer.789   *790   * @param signer keyring of signer791   * @param collectionId ID of collection792   * @example confirmSponsorship(aliceKeyring, 10)793   * @returns ```true``` if extrinsic success, otherwise ```false```794   */795  async confirmSponsorship(signer: TSigner, collectionId: number): Promise<boolean> {796    const result = await this.helper.executeExtrinsic(797      signer,798      'api.tx.unique.confirmSponsorship', [collectionId],799      true,800    );801802    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'SponsorshipConfirmed');803  }804805  /**806   * Removes the sponsor of a collection, regardless if it consented or not.807   *808   * @param signer keyring of signer809   * @param collectionId ID of collection810   * @example removeSponsor(aliceKeyring, 10)811   * @returns ```true``` if extrinsic success, otherwise ```false```812   */813  async removeSponsor(signer: TSigner, collectionId: number): Promise<boolean> {814    const result = await this.helper.executeExtrinsic(815      signer,816      'api.tx.unique.removeCollectionSponsor', [collectionId],817      true,818    );819820    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionSponsorRemoved');821  }822823  /**824   * Sets the limits of the collection. At least one limit must be specified for a correct call.825   *826   * @param signer keyring of signer827   * @param collectionId ID of collection828   * @param limits collection limits object829   * @example830   * await setLimits(831   *   aliceKeyring,832   *   10,833   *   {834   *     sponsorTransferTimeout: 0,835   *     ownerCanDestroy: false836   *   }837   * )838   * @returns ```true``` if extrinsic success, otherwise ```false```839   */840  async setLimits(signer: TSigner, collectionId: number, limits: ICollectionLimits): Promise<boolean> {841    const result = await this.helper.executeExtrinsic(842      signer,843      'api.tx.unique.setCollectionLimits', [collectionId, limits],844      true,845    );846847    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionLimitSet');848  }849850  /**851   * Changes the owner of the collection to the new Substrate address.852   *853   * @param signer keyring of signer854   * @param collectionId ID of collection855   * @param ownerAddress substrate address of new owner856   * @example changeOwner(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...")857   * @returns ```true``` if extrinsic success, otherwise ```false```858   */859  async changeOwner(signer: TSigner, collectionId: number, ownerAddress: TSubstrateAccount): Promise<boolean> {860    const result = await this.helper.executeExtrinsic(861      signer,862      'api.tx.unique.changeCollectionOwner', [collectionId, ownerAddress],863      true,864    );865866    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionOwnedChanged');867  }868869  /**870   * Adds a collection administrator.871   *872   * @param signer keyring of signer873   * @param collectionId ID of collection874   * @param adminAddressObj Administrator address (substrate or ethereum)875   * @example addAdmin(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."})876   * @returns ```true``` if extrinsic success, otherwise ```false```877   */878  async addAdmin(signer: TSigner, collectionId: number, adminAddressObj: ICrossAccountId): Promise<boolean> {879    const result = await this.helper.executeExtrinsic(880      signer,881      'api.tx.unique.addCollectionAdmin', [collectionId, adminAddressObj],882      true,883    );884885    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionAdminAdded');886  }887888  /**889   * Removes a collection administrator.890   *891   * @param signer keyring of signer892   * @param collectionId ID of collection893   * @param adminAddressObj Administrator address (substrate or ethereum)894   * @example removeAdmin(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."})895   * @returns ```true``` if extrinsic success, otherwise ```false```896   */897  async removeAdmin(signer: TSigner, collectionId: number, adminAddressObj: ICrossAccountId): Promise<boolean> {898    const result = await this.helper.executeExtrinsic(899      signer,900      'api.tx.unique.removeCollectionAdmin', [collectionId, adminAddressObj],901      true,902    );903904    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionAdminRemoved');905  }906907  /**908   * Check if user is in allow list.909   * 910   * @param collectionId ID of collection911   * @param user Account to check912   * @example await getAdmins(1)913   * @returns is user in allow list914   */915  async allowed(collectionId: number, user: ICrossAccountId): Promise<boolean> {916    return (await this.helper.callRpc('api.rpc.unique.allowed', [collectionId, user])).toJSON();917  }918919  /**920   * Adds an address to allow list921   * @param signer keyring of signer922   * @param collectionId ID of collection923   * @param addressObj address to add to the allow list924   * @returns ```true``` if extrinsic success, otherwise ```false```925   */926  async addToAllowList(signer: TSigner, collectionId: number, addressObj: ICrossAccountId): Promise<boolean> {927    const result = await this.helper.executeExtrinsic(928      signer,929      'api.tx.unique.addToAllowList', [collectionId, addressObj],930      true,931    );932933    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'AllowListAddressAdded');934  }935936  /**937   * Removes an address from allow list938   *939   * @param signer keyring of signer940   * @param collectionId ID of collection941   * @param addressObj address to remove from the allow list942   * @returns ```true``` if extrinsic success, otherwise ```false```943   */944  async removeFromAllowList(signer: TSigner, collectionId: number, addressObj: ICrossAccountId): Promise<boolean> {945    const result = await this.helper.executeExtrinsic(946      signer,947      'api.tx.unique.removeFromAllowList', [collectionId, addressObj],948      true,949    );950951    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'AllowListAddressRemoved');952  }953954  /**955   * Sets onchain permissions for selected collection.956   *957   * @param signer keyring of signer958   * @param collectionId ID of collection959   * @param permissions collection permissions object960   * @example setPermissions(aliceKeyring, 10, {access:'AllowList', mintMode: true, nesting: {collectionAdmin: true, tokenOwner: true}});961   * @returns ```true``` if extrinsic success, otherwise ```false```962   */963  async setPermissions(signer: TSigner, collectionId: number, permissions: ICollectionPermissions): Promise<boolean> {964    const result = await this.helper.executeExtrinsic(965      signer,966      'api.tx.unique.setCollectionPermissions', [collectionId, permissions],967      true,968    );969970    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionPermissionSet');971  }972973  /**974   * Enables nesting for selected collection. If `restricted` set, you can nest only tokens from specified collections.975   *976   * @param signer keyring of signer977   * @param collectionId ID of collection978   * @param permissions nesting permissions object979   * @example enableNesting(aliceKeyring, 10, {collectionAdmin: true, tokenOwner: true});980   * @returns ```true``` if extrinsic success, otherwise ```false```981   */982  async enableNesting(signer: TSigner, collectionId: number, permissions: INestingPermissions): Promise<boolean> {983    return await this.setPermissions(signer, collectionId, {nesting: permissions});984  }985986  /**987   * Disables nesting for selected collection.988   *989   * @param signer keyring of signer990   * @param collectionId ID of collection991   * @example disableNesting(aliceKeyring, 10);992   * @returns ```true``` if extrinsic success, otherwise ```false```993   */994  async disableNesting(signer: TSigner, collectionId: number): Promise<boolean> {995    return await this.setPermissions(signer, collectionId, {nesting: {tokenOwner: false, collectionAdmin: false}});996  }997998  /**999   * Sets onchain properties to the collection.1000   *1001   * @param signer keyring of signer1002   * @param collectionId ID of collection1003   * @param properties array of property objects1004   * @example setProperties(aliceKeyring, 10, [{key: "gender", value: "male"}]);1005   * @returns ```true``` if extrinsic success, otherwise ```false```1006   */1007  async setProperties(signer: TSigner, collectionId: number, properties: IProperty[]): Promise<boolean> {1008    const result = await this.helper.executeExtrinsic(1009      signer,1010      'api.tx.unique.setCollectionProperties', [collectionId, properties],1011      true,1012    );10131014    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPropertySet');1015  }10161017  /**1018   * Get collection properties.1019   * 1020   * @param collectionId ID of collection1021   * @param propertyKeys optionally filter the returned properties to only these keys1022   * @example getProperties(1219, ['location', 'date', 'time', 'isParadise']);1023   * @returns array of key-value pairs1024   */1025  async getProperties(collectionId: number, propertyKeys?: string[] | null): Promise<IProperty[]> {1026    return (await this.helper.callRpc('api.rpc.unique.collectionProperties', [collectionId, propertyKeys])).toHuman();1027  }10281029  async getCollectionOptions(collectionId: number) {1030    return (await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId])).toHuman();1031  }10321033  /**1034   * Deletes onchain properties from the collection.1035   *1036   * @param signer keyring of signer1037   * @param collectionId ID of collection1038   * @param propertyKeys array of property keys to delete1039   * @example deleteProperties(aliceKeyring, 10, ["gender", "age"]);1040   * @returns ```true``` if extrinsic success, otherwise ```false```1041   */1042  async deleteProperties(signer: TSigner, collectionId: number, propertyKeys: string[]): Promise<boolean> {1043    const result = await this.helper.executeExtrinsic(1044      signer,1045      'api.tx.unique.deleteCollectionProperties', [collectionId, propertyKeys],1046      true,1047    );10481049    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPropertyDeleted');1050  }10511052  /**1053   * Changes the owner of the token.1054   *1055   * @param signer keyring of signer1056   * @param collectionId ID of collection1057   * @param tokenId ID of token1058   * @param addressObj address of a new owner1059   * @param amount amount of tokens to be transfered. For NFT must be set to 1n1060   * @example transferToken(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."})1061   * @returns true if the token success, otherwise false1062   */1063  async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId, amount=1n): Promise<boolean> {1064    const result = await this.helper.executeExtrinsic(1065      signer,1066      'api.tx.unique.transfer', [addressObj, collectionId, tokenId, amount],1067      true, // `Unable to transfer token #${tokenId} from collection #${collectionId}`,1068    );10691070    return this.helper.util.isTokenTransferSuccess(result.result.events, collectionId, tokenId, {Substrate: typeof signer === 'string' ? signer : signer.address}, addressObj, amount);1071  }10721073  /**1074   *1075   * Change ownership of a token(s) on behalf of the owner.1076   *1077   * @param signer keyring of signer1078   * @param collectionId ID of collection1079   * @param tokenId ID of token1080   * @param fromAddressObj address on behalf of which the token will be sent1081   * @param toAddressObj new token owner1082   * @param amount amount of tokens to be transfered. For NFT must be set to 1n1083   * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg"}, {Ethereum: "0x9F0583DbB85..."})1084   * @returns true if the token success, otherwise false1085   */1086  async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1087    const result = await this.helper.executeExtrinsic(1088      signer,1089      'api.tx.unique.transferFrom', [fromAddressObj, toAddressObj, collectionId, tokenId, amount],1090      true, // `Unable to transfer token #${tokenId} from collection #${collectionId}`,1091    );1092    return this.helper.util.isTokenTransferSuccess(result.result.events, collectionId, tokenId, fromAddressObj, toAddressObj, amount);1093  }10941095  /**1096   *1097   * Destroys a concrete instance of NFT/RFT or burns a specified amount of fungible tokens.1098   *1099   * @param signer keyring of signer1100   * @param collectionId ID of collection1101   * @param tokenId ID of token1102   * @param amount amount of tokens to be burned. For NFT must be set to 1n1103   * @example burnToken(aliceKeyring, 10, 5);1104   * @returns ```true``` if the extrinsic is successful, otherwise ```false```1105   */1106  async burnToken(signer: TSigner, collectionId: number, tokenId: number, amount=1n): Promise<boolean> {1107    const burnResult = await this.helper.executeExtrinsic(1108      signer,1109      'api.tx.unique.burnItem', [collectionId, tokenId, amount],1110      true, // `Unable to burn token for ${label}`,1111    );1112    const burnedTokens = this.helper.util.extractTokensFromBurnResult(burnResult);1113    if (burnedTokens.tokens.length > 1) throw Error('Burned multiple tokens');1114    return burnedTokens.success;1115  }11161117  /**1118   * Destroys a concrete instance of NFT on behalf of the owner1119   *1120   * @param signer keyring of signer1121   * @param collectionId ID of collection1122   * @param tokenId ID of token1123   * @param fromAddressObj address on behalf of which the token will be burnt1124   * @param amount amount of tokens to be burned. For NFT must be set to 1n1125   * @example burnTokenFrom(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."}, 5, {Ethereum: "0x9F0583DbB85..."})1126   * @returns ```true``` if extrinsic success, otherwise ```false```1127   */1128  async burnTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1129    const burnResult = await this.helper.executeExtrinsic(1130      signer,1131      'api.tx.unique.burnFrom', [collectionId, fromAddressObj, tokenId, amount],1132      true, // `Unable to burn token from for ${label}`,1133    );1134    const burnedTokens = this.helper.util.extractTokensFromBurnResult(burnResult);1135    return burnedTokens.success && burnedTokens.tokens.length > 0;1136  }11371138  /**1139   * Set, change, or remove approved address to transfer the ownership of the NFT.1140   *1141   * @param signer keyring of signer1142   * @param collectionId ID of collection1143   * @param tokenId ID of token1144   * @param toAddressObj Substrate or Ethereum address which gets approved use of the signer's tokens1145   * @param amount amount of token to be approved. For NFT must be set to 1n1146   * @returns ```true``` if extrinsic success, otherwise ```false```1147   */1148  async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {1149    const approveResult = await this.helper.executeExtrinsic(1150      signer,1151      'api.tx.unique.approve', [toAddressObj, collectionId, tokenId, amount],1152      true, // `Unable to approve token for ${label}`,1153    );11541155    return this.helper.util.findCollectionInEvents(approveResult.result.events, collectionId, 'common', 'Approved');1156  }11571158  /**1159   * Get the amount of token pieces approved to transfer or burn. Normally 0.1160   *1161   * @param collectionId ID of collection1162   * @param tokenId ID of token1163   * @param toAccountObj address which is approved to use token pieces1164   * @param fromAccountObj address which may have allowed the use of its owned tokens1165   * @example getTokenApprovedPieces(10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, {Substrate: "5ERZNF88Mm7UGfPP3mdG..."})1166   * @returns number of approved to transfer pieces1167   */1168  async getTokenApprovedPieces(collectionId: number, tokenId: number, toAccountObj: ICrossAccountId, fromAccountObj: ICrossAccountId): Promise<bigint> {1169    return (await this.helper.callRpc('api.rpc.unique.allowance', [collectionId, fromAccountObj, toAccountObj, tokenId])).toBigInt();1170  }11711172  /**1173   * Get the last created token ID in a collection1174   *1175   * @param collectionId ID of collection1176   * @example getLastTokenId(10);1177   * @returns id of the last created token1178   */1179  async getLastTokenId(collectionId: number): Promise<number> {1180    return (await this.helper.callRpc('api.rpc.unique.lastTokenId', [collectionId])).toNumber();1181  }11821183  /**1184   * Check if token exists1185   *1186   * @param collectionId ID of collection1187   * @param tokenId ID of token1188   * @example doesTokenExist(10, 20);1189   * @returns true if the token exists, otherwise false1190   */1191  async doesTokenExist(collectionId: number, tokenId: number): Promise<boolean> {1192    return (await this.helper.callRpc('api.rpc.unique.tokenExists', [collectionId, tokenId])).toJSON();1193  }1194}11951196class NFTnRFT extends CollectionGroup {1197  /**1198   * Get tokens owned by account1199   *1200   * @param collectionId ID of collection1201   * @param addressObj tokens owner1202   * @example getTokensByAddress(10, {Substrate: "5DyN4Y92vZCjv38fg..."})1203   * @returns array of token ids owned by account1204   */1205  async getTokensByAddress(collectionId: number, addressObj: ICrossAccountId): Promise<number[]> {1206    return (await this.helper.callRpc('api.rpc.unique.accountTokens', [collectionId, addressObj])).toJSON();1207  }12081209  /**1210   * Get token data1211   *1212   * @param collectionId ID of collection1213   * @param tokenId ID of token1214   * @param propertyKeys optionally filter the token properties to only these keys1215   * @param blockHashAt optionally query the data at some block with this hash1216   * @example getToken(10, 5);1217   * @returns human readable token data1218   */1219  async getToken(collectionId: number, tokenId: number, propertyKeys: string[] = [], blockHashAt?: string): Promise<{1220    properties: IProperty[];1221    owner: CrossAccountId;1222    normalizedOwner: CrossAccountId;1223  }| null> {1224    let tokenData;1225    if(typeof blockHashAt === 'undefined') {1226      tokenData = await this.helper.callRpc('api.rpc.unique.tokenData', [collectionId, tokenId]);1227    }1228    else {1229      if(propertyKeys.length == 0) {1230        const collection = (await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId])).toHuman();1231        if(!collection) return null;1232        propertyKeys = collection.tokenPropertyPermissions.map((x: ITokenPropertyPermission) => x.key);1233      }1234      tokenData = await this.helper.callRpc('api.rpc.unique.tokenData', [collectionId, tokenId, propertyKeys, blockHashAt]);1235    }1236    tokenData = tokenData.toHuman();1237    if (tokenData === null || tokenData.owner === null) return null;1238    const owner = {} as any;1239    for (const key of Object.keys(tokenData.owner)) {1240      owner[key.toLocaleLowerCase()] = key.toLocaleLowerCase() == 'substrate' 1241        ? CrossAccountId.normalizeSubstrateAddress(tokenData.owner[key]) 1242        : tokenData.owner[key];1243    }1244    tokenData.normalizedOwner = CrossAccountId.fromLowerCaseKeys(owner);1245    return tokenData;1246  }12471248  /**1249   * Set permissions to change token properties1250   *1251   * @param signer keyring of signer1252   * @param collectionId ID of collection1253   * @param permissions permissions to change a property by the collection admin or token owner1254   * @example setTokenPropertyPermissions(1255   *   aliceKeyring, 10, [{key: "gender", permission: {tokenOwner: true, mutable: true, collectionAdmin: true}}]1256   * )1257   * @returns true if extrinsic success otherwise false1258   */1259  async setTokenPropertyPermissions(signer: TSigner, collectionId: number, permissions: ITokenPropertyPermission[]): Promise<boolean> {1260    const result = await this.helper.executeExtrinsic(1261      signer,1262      'api.tx.unique.setTokenPropertyPermissions', [collectionId, permissions],1263      true,1264    );12651266    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'PropertyPermissionSet');1267  }12681269  /**1270   * Get token property permissions.1271   * 1272   * @param collectionId ID of collection1273   * @param propertyKeys optionally filter the returned property permissions to only these keys1274   * @example getPropertyPermissions(1219, ['location', 'date', 'time', 'isParadise']);1275   * @returns array of key-permission pairs1276   */1277  async getPropertyPermissions(collectionId: number, propertyKeys: string[] | null = null): Promise<ITokenPropertyPermission[]> {1278    return (await this.helper.callRpc('api.rpc.unique.propertyPermissions', [collectionId, ...(propertyKeys === null ? [] : [propertyKeys])])).toHuman();1279  }12801281  /**1282   * Set token properties1283   *1284   * @param signer keyring of signer1285   * @param collectionId ID of collection1286   * @param tokenId ID of token1287   * @param properties key-value pairs of metadata which to add to a token. Keys must be permitted in the collection1288   * @example setTokenProperties(aliceKeyring, 10, 5, [{key: "gender", value: "female"}, {key: "age", value: "23"}])1289   * @returns ```true``` if extrinsic success, otherwise ```false```1290   */1291  async setTokenProperties(signer: TSigner, collectionId: number, tokenId: number, properties: IProperty[]): Promise<boolean> {1292    const result = await this.helper.executeExtrinsic(1293      signer,1294      'api.tx.unique.setTokenProperties', [collectionId, tokenId, properties],1295      true,1296    );12971298    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'TokenPropertySet');1299  }13001301  /**1302   * Get properties, metadata assigned to a token.1303   * 1304   * @param collectionId ID of collection1305   * @param tokenId ID of token1306   * @param propertyKeys optionally filter the returned properties to only these keys1307   * @example getTokenProperties(1219, ['location', 'date', 'time', 'isParadise']);1308   * @returns array of key-value pairs1309   */1310  async getTokenProperties(collectionId: number, tokenId: number, propertyKeys?: string[] | null): Promise<IProperty[]> {1311    return (await this.helper.callRpc('api.rpc.unique.tokenProperties', [collectionId, tokenId, propertyKeys])).toHuman();1312  }13131314  /**1315   * Delete the provided properties of a token1316   * @param signer keyring of signer1317   * @param collectionId ID of collection1318   * @param tokenId ID of token1319   * @param propertyKeys property keys to be deleted1320   * @example deleteTokenProperties(aliceKeyring, 10, 5, ["gender", "age"])1321   * @returns ```true``` if extrinsic success, otherwise ```false```1322   */1323  async deleteTokenProperties(signer: TSigner, collectionId: number, tokenId: number, propertyKeys: string[]): Promise<boolean> {1324    const result = await this.helper.executeExtrinsic(1325      signer,1326      'api.tx.unique.deleteTokenProperties', [collectionId, tokenId, propertyKeys],1327      true,1328    );13291330    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'TokenPropertyDeleted');1331  }13321333  /**1334   * Mint new collection1335   *1336   * @param signer keyring of signer1337   * @param collectionOptions basic collection options and properties1338   * @param mode NFT or RFT type of a collection1339   * @example mintCollection(aliceKeyring, {name: 'New', description: "New collection", tokenPrefix: "NEW"}, "NFT")1340   * @returns object of the created collection1341   */1342  async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions, mode: 'NFT' | 'RFT'): Promise<UniqueBaseCollection> {1343    collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; // Clone object1344    collectionOptions.mode = (mode === 'NFT') ? {nft: null} : {refungible: null};1345    for (const key of ['name', 'description', 'tokenPrefix']) {1346      if (typeof collectionOptions[key as 'name' | 'description' | 'tokenPrefix'] === 'string') collectionOptions[key as 'name' | 'description' | 'tokenPrefix'] = this.helper.util.str2vec(collectionOptions[key as 'name' | 'description' | 'tokenPrefix'] as string);1347    }1348    const creationResult = await this.helper.executeExtrinsic(1349      signer,1350      'api.tx.unique.createCollectionEx', [collectionOptions],1351      true, // errorLabel,1352    );1353    return this.getCollectionObject(this.helper.util.extractCollectionIdFromCreationResult(creationResult));1354  }13551356  getCollectionObject(_collectionId: number): any {1357    return null;1358  }13591360  getTokenObject(_collectionId: number, _tokenId: number): any {1361    return null;1362  }1363}136413651366class NFTGroup extends NFTnRFT {1367  /**1368   * Get collection object1369   * @param collectionId ID of collection1370   * @example getCollectionObject(2);1371   * @returns instance of UniqueNFTCollection1372   */1373  getCollectionObject(collectionId: number): UniqueNFTCollection {1374    return new UniqueNFTCollection(collectionId, this.helper);1375  }13761377  /**1378   * Get token object1379   * @param collectionId ID of collection1380   * @param tokenId ID of token1381   * @example getTokenObject(10, 5);1382   * @returns instance of UniqueNFTToken1383   */1384  getTokenObject(collectionId: number, tokenId: number): UniqueNFToken {1385    return new UniqueNFToken(tokenId, this.getCollectionObject(collectionId));1386  }13871388  /**1389   * Get token's owner1390   * @param collectionId ID of collection1391   * @param tokenId ID of token1392   * @param blockHashAt optionally query the data at the block with this hash1393   * @example getTokenOwner(10, 5);1394   * @returns Address in CrossAccountId format, e.g. {Substrate: "5DnSF6RRjwteE3BrCj..."}1395   */1396  async getTokenOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<CrossAccountId> {1397    let owner;1398    if (typeof blockHashAt === 'undefined') {1399      owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId]);1400    } else {1401      owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId, blockHashAt]);1402    }1403    return CrossAccountId.fromLowerCaseKeys(owner.toJSON());1404  }14051406  /**1407   * Is token approved to transfer1408   * @param collectionId ID of collection1409   * @param tokenId ID of token1410   * @param toAccountObj address to be approved1411   * @returns ```true``` if extrinsic success, otherwise ```false```1412   */1413  async isTokenApproved(collectionId: number, tokenId: number, toAccountObj: ICrossAccountId): Promise<boolean> {1414    return (await this.getTokenApprovedPieces(collectionId, tokenId, toAccountObj, await this.getTokenOwner(collectionId, tokenId))) === 1n;1415  }14161417  /**1418   * Changes the owner of the token.1419   *1420   * @param signer keyring of signer1421   * @param collectionId ID of collection1422   * @param tokenId ID of token1423   * @param addressObj address of a new owner1424   * @example transferToken(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."})1425   * @returns ```true``` if extrinsic success, otherwise ```false```1426   */1427  async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<boolean> {1428    return await super.transferToken(signer, collectionId, tokenId, addressObj, 1n);1429  }14301431  /**1432   *1433   * Change ownership of a NFT on behalf of the owner.1434   *1435   * @param signer keyring of signer1436   * @param collectionId ID of collection1437   * @param tokenId ID of token1438   * @param fromAddressObj address on behalf of which the token will be sent1439   * @param toAddressObj new token owner1440   * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, {Ethereum: "0x9F0583DbB85..."})1441   * @returns ```true``` if extrinsic success, otherwise ```false```1442   */1443  async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId): Promise<boolean> {1444    return await super.transferTokenFrom(signer, collectionId, tokenId, fromAddressObj, toAddressObj, 1n);1445  }14461447  /**1448   * Recursively find the address that owns the token1449   * @param collectionId ID of collection1450   * @param tokenId ID of token1451   * @param blockHashAt1452   * @example getTokenTopmostOwner(10, 5);1453   * @returns address in CrossAccountId format, e.g. {Substrate: "5DyN4Y92vZCjv38fg..."}1454   */1455  async getTokenTopmostOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<CrossAccountId | null> {1456    let owner;1457    if (typeof blockHashAt === 'undefined') {1458      owner = await this.helper.callRpc('api.rpc.unique.topmostTokenOwner', [collectionId, tokenId]);1459    } else {1460      owner = await this.helper.callRpc('api.rpc.unique.topmostTokenOwner', [collectionId, tokenId, blockHashAt]);1461    }14621463    if (owner === null) return null;14641465    return owner.toHuman();1466  }14671468  /**1469   * Get tokens nested in the provided token1470   * @param collectionId ID of collection1471   * @param tokenId ID of token1472   * @param blockHashAt optionally query the data at the block with this hash1473   * @example getTokenChildren(10, 5);1474   * @returns tokens whose depth of nesting is <= 51475   */1476  async getTokenChildren(collectionId: number, tokenId: number, blockHashAt?: string): Promise<IToken[]> {1477    let children;1478    if(typeof blockHashAt === 'undefined') {1479      children = await this.helper.callRpc('api.rpc.unique.tokenChildren', [collectionId, tokenId]);1480    } else {1481      children = await this.helper.callRpc('api.rpc.unique.tokenChildren', [collectionId, tokenId, blockHashAt]);1482    }14831484    return children.toJSON().map((x: any) => {1485      return {collectionId: x.collection, tokenId: x.token};1486    });1487  }14881489  /**1490   * Nest one token into another1491   * @param signer keyring of signer1492   * @param tokenObj token to be nested1493   * @param rootTokenObj token to be parent1494   * @example nestToken(aliceKeyring, {collectionId: 10, tokenId: 5}, {collectionId: 10, tokenId: 4});1495   * @returns ```true``` if extrinsic success, otherwise ```false```1496   */1497  async nestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken): Promise<boolean> {1498    const rootTokenAddress = this.helper.util.getTokenAccount(rootTokenObj);1499    const result = await this.transferToken(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress);1500    if(!result) {1501      throw Error('Unable to nest token!');1502    }1503    return result;1504  }15051506  /**1507   * Remove token from nested state1508   * @param signer keyring of signer1509   * @param tokenObj token to unnest1510   * @param rootTokenObj parent of a token1511   * @param toAddressObj address of a new token owner1512   * @example unnestToken(aliceKeyring, {collectionId: 10, tokenId: 5}, {collectionId: 10, tokenId: 4}, {Substrate: "5DyN4Y92vZCjv38fg..."});1513   * @returns ```true``` if extrinsic success, otherwise ```false```1514   */1515  async unnestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken, toAddressObj: ICrossAccountId): Promise<boolean> {1516    const rootTokenAddress = this.helper.util.getTokenAccount(rootTokenObj);1517    const result = await this.transferTokenFrom(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress, toAddressObj);1518    if(!result) {1519      throw Error('Unable to unnest token!');1520    }1521    return result;1522  }15231524  /**1525   * Mint new collection1526   * @param signer keyring of signer1527   * @param collectionOptions Collection options1528   * @example1529   * mintCollection(aliceKeyring, {1530   *   name: 'New',1531   *   description: 'New collection',1532   *   tokenPrefix: 'NEW',1533   * })1534   * @returns object of the created collection1535   */1536  async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}): Promise<UniqueNFTCollection> {1537    return await super.mintCollection(signer, collectionOptions, 'NFT') as UniqueNFTCollection;1538  }15391540  /**1541   * Mint new token1542   * @param signer keyring of signer1543   * @param data token data1544   * @returns created token object1545   */1546  async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; properties?: IProperty[]; }): Promise<UniqueNFToken> {1547    const creationResult = await this.helper.executeExtrinsic(1548      signer,1549      'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {1550        nft: {1551          properties: data.properties,1552        },1553      }],1554      true,1555    );1556    const createdTokens = this.helper.util.extractTokensFromCreationResult(creationResult);1557    if (createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');1558    if (createdTokens.tokens.length < 1) throw Error('No tokens minted');1559    return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);1560  }15611562  /**1563   * Mint multiple NFT tokens1564   * @param signer keyring of signer1565   * @param collectionId ID of collection1566   * @param tokens array of tokens with owner and properties1567   * @example1568   * mintMultipleTokens(aliceKeyring, 10, [{1569   *     owner: {Substrate: "5DyN4Y92vZCjv38fg..."},1570   *     properties: [{key: "gender", value: "male"},{key: "age", value: "45"}],1571   *   },{1572   *     owner: {Ethereum: "0x9F0583DbB855d..."},1573   *     properties: [{key: "gender", value: "female"},{key: "age", value: "22"}],1574   * }]);1575   * @returns ```true``` if extrinsic success, otherwise ```false```1576   */1577  async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: {owner: ICrossAccountId, properties?: IProperty[]}[]): Promise<UniqueNFToken[]> {1578    const creationResult = await this.helper.executeExtrinsic(1579      signer,1580      'api.tx.unique.createMultipleItemsEx', [collectionId, {NFT: tokens}],1581      true,1582    );1583    const collection = this.getCollectionObject(collectionId);1584    return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1585  }15861587  /**1588   * Mint multiple NFT tokens with one owner1589   * @param signer keyring of signer1590   * @param collectionId ID of collection1591   * @param owner tokens owner1592   * @param tokens array of tokens with owner and properties1593   * @example1594   * mintMultipleTokensWithOneOwner(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...", [{1595   *   properties: [{1596   *   key: "gender",1597   *   value: "female",1598   *  },{1599   *   key: "age",1600   *   value: "33",1601   *  }],1602   * }]);1603   * @returns array of newly created tokens1604   */1605  async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {properties?: IProperty[]}[]): Promise<UniqueNFToken[]> {1606    const rawTokens = [];1607    for (const token of tokens) {1608      const raw = {NFT: {properties: token.properties}};1609      rawTokens.push(raw);1610    }1611    const creationResult = await this.helper.executeExtrinsic(1612      signer,1613      'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1614      true,1615    );1616    const collection = this.getCollectionObject(collectionId);1617    return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1618  }16191620  /**1621   * Set, change, or remove approved address to transfer the ownership of the NFT.1622   *1623   * @param signer keyring of signer1624   * @param collectionId ID of collection1625   * @param tokenId ID of token1626   * @param toAddressObj address to approve1627   * @example approveToken(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."})1628   * @returns ```true``` if extrinsic success, otherwise ```false```1629   */1630  async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId) {1631    return super.approveToken(signer, collectionId, tokenId, toAddressObj, 1n);1632  }1633}163416351636class RFTGroup extends NFTnRFT {1637  /**1638   * Get collection object1639   * @param collectionId ID of collection1640   * @example getCollectionObject(2);1641   * @returns instance of UniqueRFTCollection1642   */1643  getCollectionObject(collectionId: number): UniqueRFTCollection {1644    return new UniqueRFTCollection(collectionId, this.helper);1645  }16461647  /**1648   * Get token object1649   * @param collectionId ID of collection1650   * @param tokenId ID of token1651   * @example getTokenObject(10, 5);1652   * @returns instance of UniqueNFTToken1653   */1654  getTokenObject(collectionId: number, tokenId: number): UniqueRFToken {1655    return new UniqueRFToken(tokenId, this.getCollectionObject(collectionId));1656  }16571658  /**1659   * Get top 10 token owners with the largest number of pieces1660   * @param collectionId ID of collection1661   * @param tokenId ID of token1662   * @example getTokenTop10Owners(10, 5);1663   * @returns array of top 10 owners1664   */1665  async getTokenTop10Owners(collectionId: number, tokenId: number): Promise<CrossAccountId[]> {1666    return (await this.helper.callRpc('api.rpc.unique.tokenOwners', [collectionId, tokenId])).toJSON().map(CrossAccountId.fromLowerCaseKeys);1667  }16681669  /**1670   * Get number of pieces owned by address1671   * @param collectionId ID of collection1672   * @param tokenId ID of token1673   * @param addressObj address token owner1674   * @example getTokenBalance(10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."});1675   * @returns number of pieces ownerd by address1676   */1677  async getTokenBalance(collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<bigint> {1678    return (await this.helper.callRpc('api.rpc.unique.balance', [collectionId, addressObj, tokenId])).toBigInt();1679  }16801681  /**1682   * Transfer pieces of token to another address1683   * @param signer keyring of signer1684   * @param collectionId ID of collection1685   * @param tokenId ID of token1686   * @param addressObj address of a new owner1687   * @param amount number of pieces to be transfered1688   * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, 2000n)1689   * @returns ```true``` if extrinsic success, otherwise ```false```1690   */1691  async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId, amount=1n): Promise<boolean> {1692    return await super.transferToken(signer, collectionId, tokenId, addressObj, amount);1693  }16941695  /**1696   * Change ownership of some pieces of RFT on behalf of the owner.1697   * @param signer keyring of signer1698   * @param collectionId ID of collection1699   * @param tokenId ID of token1700   * @param fromAddressObj address on behalf of which the token will be sent1701   * @param toAddressObj new token owner1702   * @param amount number of pieces to be transfered1703   * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, {Substrate: "5DfhbVfww7ThF8q6f3i..."}, 2000n)1704   * @returns ```true``` if extrinsic success, otherwise ```false```1705   */1706  async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1707    return await super.transferTokenFrom(signer, collectionId, tokenId, fromAddressObj, toAddressObj, amount);1708  }17091710  /**1711   * Mint new collection1712   * @param signer keyring of signer1713   * @param collectionOptions Collection options1714   * @example1715   * mintCollection(aliceKeyring, {1716   *   name: 'New',1717   *   description: 'New collection',1718   *   tokenPrefix: 'NEW',1719   * })1720   * @returns object of the created collection1721   */1722  async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}): Promise<UniqueRFTCollection> {1723    return await super.mintCollection(signer, collectionOptions, 'RFT') as UniqueRFTCollection;1724  }17251726  /**1727   * Mint new token1728   * @param signer keyring of signer1729   * @param data token data1730   * @example mintToken(aliceKeyring, {collectionId: 10, owner: {Substrate: '5GHoZe9c73RYbVzq...'}, pieces: 10000n});1731   * @returns created token object1732   */1733  async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; pieces: bigint; properties?: IProperty[]; }): Promise<UniqueRFToken> {1734    const creationResult = await this.helper.executeExtrinsic(1735      signer,1736      'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {1737        refungible: {1738          pieces: data.pieces,1739          properties: data.properties,1740        },1741      }],1742      true,1743    );1744    const createdTokens = this.helper.util.extractTokensFromCreationResult(creationResult);1745    if (createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');1746    if (createdTokens.tokens.length < 1) throw Error('No tokens minted');1747    return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);1748  }17491750  async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: {owner: ICrossAccountId, pieces: bigint, properties?: IProperty[]}[]): Promise<UniqueRFToken[]> {1751    throw Error('Not implemented');1752    const creationResult = await this.helper.executeExtrinsic(1753      signer,1754      'api.tx.unique.createMultipleItemsEx', [collectionId, {RefungibleMultipleOwners: tokens}],1755      true, // `Unable to mint RFT tokens for ${label}`,1756    );1757    const collection = this.getCollectionObject(collectionId);1758    return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1759  }17601761  /**1762   * Mint multiple RFT tokens with one owner1763   * @param signer keyring of signer1764   * @param collectionId ID of collection1765   * @param owner tokens owner1766   * @param tokens array of tokens with properties and pieces1767   * @example mintMultipleTokensWithOneOwner(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, [{pieces: 100000n, properties: [{key: "gender", value: "male"}]}]);1768   * @returns array of newly created RFT tokens1769   */1770  async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {pieces: bigint, properties?: IProperty[]}[]): Promise<UniqueRFToken[]> {1771    const rawTokens = [];1772    for (const token of tokens) {1773      const raw = {ReFungible: {pieces: token.pieces, properties: token.properties}};1774      rawTokens.push(raw);1775    }1776    const creationResult = await this.helper.executeExtrinsic(1777      signer,1778      'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1779      true,1780    );1781    const collection = this.getCollectionObject(collectionId);1782    return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1783  }17841785  /**1786   * Destroys a concrete instance of RFT.1787   * @param signer keyring of signer1788   * @param collectionId ID of collection1789   * @param tokenId ID of token1790   * @param amount number of pieces to be burnt1791   * @example burnToken(aliceKeyring, 10, 5);1792   * @returns ```true``` if the extrinsic is successful, otherwise ```false```1793   */1794  async burnToken(signer: IKeyringPair, collectionId: number, tokenId: number, amount=1n): Promise<boolean> {1795    return await super.burnToken(signer, collectionId, tokenId, amount);1796  }17971798  /**1799   * Destroys a concrete instance of RFT on behalf of the owner.1800   * @param signer keyring of signer1801   * @param collectionId ID of collection1802   * @param tokenId ID of token1803   * @param fromAddressObj address on behalf of which the token will be burnt1804   * @param amount number of pieces to be burnt1805   * @example burnTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, 2n)1806   * @returns ```true``` if extrinsic success, otherwise ```false```1807   */1808  async burnTokenFrom(signer: IKeyringPair, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1809    return await super.burnTokenFrom(signer, collectionId, tokenId, fromAddressObj, amount);1810  }18111812  /**1813   * Set, change, or remove approved address to transfer the ownership of the RFT.1814   *1815   * @param signer keyring of signer1816   * @param collectionId ID of collection1817   * @param tokenId ID of token1818   * @param toAddressObj address to approve1819   * @param amount number of pieces to be approved1820   * @example approveToken(aliceKeyring, 10, 5, {Substrate: "5GHoZe9c73RYbVzq..."}, "", 10000n);1821   * @returns true if the token success, otherwise false1822   */1823  async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {1824    return super.approveToken(signer, collectionId, tokenId, toAddressObj, amount);1825  }18261827  /**1828   * Get total number of pieces1829   * @param collectionId ID of collection1830   * @param tokenId ID of token1831   * @example getTokenTotalPieces(10, 5);1832   * @returns number of pieces1833   */1834  async getTokenTotalPieces(collectionId: number, tokenId: number): Promise<bigint> {1835    return (await this.helper.callRpc('api.rpc.unique.totalPieces', [collectionId, tokenId])).unwrap().toBigInt();1836  }18371838  /**1839   * Change number of token pieces. Signer must be the owner of all token pieces.1840   * @param signer keyring of signer1841   * @param collectionId ID of collection1842   * @param tokenId ID of token1843   * @param amount new number of pieces1844   * @example repartitionToken(aliceKeyring, 10, 5, 12345n);1845   * @returns true if the repartion was success, otherwise false1846   */1847  async repartitionToken(signer: TSigner, collectionId: number, tokenId: number, amount: bigint): Promise<boolean> {1848    const currentAmount = await this.getTokenTotalPieces(collectionId, tokenId);1849    const repartitionResult = await this.helper.executeExtrinsic(1850      signer,1851      'api.tx.unique.repartition', [collectionId, tokenId, amount],1852      true,1853    );1854    if(currentAmount < amount) return this.helper.util.findCollectionInEvents(repartitionResult.result.events, collectionId, 'common', 'ItemCreated');1855    return this.helper.util.findCollectionInEvents(repartitionResult.result.events, collectionId, 'common', 'ItemDestroyed');1856  }1857}185818591860class FTGroup extends CollectionGroup {1861  /**1862   * Get collection object1863   * @param collectionId ID of collection1864   * @example getCollectionObject(2);1865   * @returns instance of UniqueFTCollection1866   */1867  getCollectionObject(collectionId: number): UniqueFTCollection {1868    return new UniqueFTCollection(collectionId, this.helper);1869  }18701871  /**1872   * Mint new fungible collection1873   * @param signer keyring of signer1874   * @param collectionOptions Collection options1875   * @param decimalPoints number of token decimals1876   * @example1877   * mintCollection(aliceKeyring, {1878   *   name: 'New',1879   *   description: 'New collection',1880   *   tokenPrefix: 'NEW',1881   * }, 18)1882   * @returns newly created fungible collection1883   */1884  async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}, decimalPoints = 0): Promise<UniqueFTCollection> {1885    collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; // Clone object1886    if(collectionOptions.tokenPropertyPermissions) throw Error('Fungible collections has no tokenPropertyPermissions');1887    collectionOptions.mode = {fungible: decimalPoints};1888    for (const key of ['name', 'description', 'tokenPrefix']) {1889      if (typeof collectionOptions[key as 'name' | 'description' | 'tokenPrefix'] === 'string') collectionOptions[key as 'name' | 'description' | 'tokenPrefix'] = this.helper.util.str2vec(collectionOptions[key as 'name' | 'description' | 'tokenPrefix'] as string);1890    }1891    const creationResult = await this.helper.executeExtrinsic(1892      signer,1893      'api.tx.unique.createCollectionEx', [collectionOptions],1894      true,1895    );1896    return this.getCollectionObject(this.helper.util.extractCollectionIdFromCreationResult(creationResult));1897  }18981899  /**1900   * Mint tokens1901   * @param signer keyring of signer1902   * @param collectionId ID of collection1903   * @param owner address owner of new tokens1904   * @param amount amount of tokens to be meanted1905   * @example mintTokens(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq"}, 1000n);1906   * @returns ```true``` if extrinsic success, otherwise ```false```1907   */1908  async mintTokens(signer: TSigner, collectionId: number, amount: bigint, owner: ICrossAccountId | string): Promise<boolean> {1909    const creationResult = await this.helper.executeExtrinsic(1910      signer,1911      'api.tx.unique.createItem', [collectionId, (typeof owner === 'string') ? {Substrate: owner} : owner, {1912        fungible: {1913          value: amount,1914        },1915      }],1916      true, // `Unable to mint fungible tokens for ${label}`,1917    );1918    return this.helper.util.findCollectionInEvents(creationResult.result.events, collectionId, 'common', 'ItemCreated');1919  }19201921  /**1922   * Mint multiple Fungible tokens with one owner1923   * @param signer keyring of signer1924   * @param collectionId ID of collection1925   * @param owner tokens owner1926   * @param tokens array of tokens with properties and pieces1927   * @returns ```true``` if extrinsic success, otherwise ```false```1928   */1929  async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, tokens: {value: bigint}[], owner: ICrossAccountId): Promise<boolean> {1930    const rawTokens = [];1931    for (const token of tokens) {1932      const raw = {Fungible: {Value: token.value}};1933      rawTokens.push(raw);1934    }1935    const creationResult = await this.helper.executeExtrinsic(1936      signer,1937      'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1938      true,1939    );1940    return this.helper.util.findCollectionInEvents(creationResult.result.events, collectionId, 'common', 'ItemCreated');1941  }19421943  /**1944   * Get the top 10 owners with the largest balance for the Fungible collection1945   * @param collectionId ID of collection1946   * @example getTop10Owners(10);1947   * @returns array of ```ICrossAccountId```1948   */1949  async getTop10Owners(collectionId: number): Promise<CrossAccountId[]> {1950    return (await this.helper.callRpc('api.rpc.unique.tokenOwners', [collectionId, 0])).toJSON().map(CrossAccountId.fromLowerCaseKeys);1951  }19521953  /**1954   * Get account balance1955   * @param collectionId ID of collection1956   * @param addressObj address of owner1957   * @example getBalance(10, {Substrate: "5GHoZe9c73RYbVzq..."})1958   * @returns amount of fungible tokens owned by address1959   */1960  async getBalance(collectionId: number, addressObj: ICrossAccountId): Promise<bigint> {1961    return (await this.helper.callRpc('api.rpc.unique.balance', [collectionId, addressObj, 0])).toBigInt();1962  }19631964  /**1965   * Transfer tokens to address1966   * @param signer keyring of signer1967   * @param collectionId ID of collection1968   * @param toAddressObj address recipient1969   * @param amount amount of tokens to be sent1970   * @example transfer(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, 1000n);1971   * @returns ```true``` if extrinsic success, otherwise ```false```1972   */1973  async transfer(signer: TSigner, collectionId: number, toAddressObj: ICrossAccountId, amount=1n) {1974    return await super.transferToken(signer, collectionId, 0, toAddressObj, amount);1975  }19761977  /**1978   * Transfer some tokens on behalf of the owner.1979   * @param signer keyring of signer1980   * @param collectionId ID of collection1981   * @param fromAddressObj address on behalf of which tokens will be sent1982   * @param toAddressObj address where token to be sent1983   * @param amount number of tokens to be sent1984   * @example transferFrom(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, {Substrate: "5DfhbVfww7ThF8q6f3ij..."}, 10000n);1985   * @returns ```true``` if extrinsic success, otherwise ```false```1986   */1987  async transferFrom(signer: TSigner, collectionId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {1988    return await super.transferTokenFrom(signer, collectionId, 0, fromAddressObj, toAddressObj, amount);1989  }19901991  /**1992   * Destroy some amount of tokens1993   * @param signer keyring of signer1994   * @param collectionId ID of collection1995   * @param amount amount of tokens to be destroyed1996   * @example burnTokens(aliceKeyring, 10, 1000n);1997   * @returns ```true``` if extrinsic success, otherwise ```false```1998   */1999  async burnTokens(signer: IKeyringPair, collectionId: number, amount=1n): Promise<boolean> {2000    return await super.burnToken(signer, collectionId, 0, amount);2001  }20022003  /**2004   * Burn some tokens on behalf of the owner.2005   * @param signer keyring of signer2006   * @param collectionId ID of collection2007   * @param fromAddressObj address on behalf of which tokens will be burnt2008   * @param amount amount of tokens to be burnt2009   * @example burnTokensFrom(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, 1000n);2010   * @returns ```true``` if extrinsic success, otherwise ```false```2011   */2012  async burnTokensFrom(signer: IKeyringPair, collectionId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {2013    return await super.burnTokenFrom(signer, collectionId, 0, fromAddressObj, amount);2014  }20152016  /**2017   * Get total collection supply2018   * @param collectionId2019   * @returns2020   */2021  async getTotalPieces(collectionId: number): Promise<bigint> {2022    return (await this.helper.callRpc('api.rpc.unique.totalPieces', [collectionId, 0])).unwrap().toBigInt();2023  }20242025  /**2026   * Set, change, or remove approved address to transfer tokens.2027   *2028   * @param signer keyring of signer2029   * @param collectionId ID of collection2030   * @param toAddressObj address to be approved2031   * @param amount amount of tokens to be approved2032   * @example approveTokens(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, 1000n)2033   * @returns ```true``` if extrinsic success, otherwise ```false```2034   */2035  async approveTokens(signer: IKeyringPair, collectionId: number, toAddressObj: ICrossAccountId, amount=1n) {2036    return super.approveToken(signer, collectionId, 0, toAddressObj, amount);2037  }20382039  /**2040   * Get amount of fungible tokens approved to transfer2041   * @param collectionId ID of collection2042   * @param fromAddressObj owner of tokens2043   * @param toAddressObj the address approved for the transfer of tokens on behalf of the owner2044   * @returns number of tokens approved for the transfer2045   */2046  async getApprovedTokens(collectionId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2047    return super.getTokenApprovedPieces(collectionId, 0, toAddressObj, fromAddressObj);2048  }2049}205020512052class ChainGroup extends HelperGroup<ChainHelperBase> {2053  /**2054   * Get system properties of a chain2055   * @example getChainProperties();2056   * @returns ss58Format, token decimals, and token symbol2057   */2058  getChainProperties(): IChainProperties {2059    const properties = (this.helper.getApi() as any).registry.getChainProperties().toJSON();2060    return {2061      ss58Format: properties.ss58Format.toJSON(),2062      tokenDecimals: properties.tokenDecimals.toJSON(),2063      tokenSymbol: properties.tokenSymbol.toJSON(),2064    };2065  }20662067  /**2068   * Get chain header2069   * @example getLatestBlockNumber();2070   * @returns the number of the last block2071   */2072  async getLatestBlockNumber(): Promise<number> {2073    return (await this.helper.callRpc('api.rpc.chain.getHeader')).number.toNumber();2074  }20752076  /**2077   * Get block hash by block number2078   * @param blockNumber number of block2079   * @example getBlockHashByNumber(12345);2080   * @returns hash of a block2081   */2082  async getBlockHashByNumber(blockNumber: number): Promise<string | null> {2083    const blockHash = (await this.helper.callRpc('api.rpc.chain.getBlockHash', [blockNumber])).toJSON();2084    if(blockHash === '0x0000000000000000000000000000000000000000000000000000000000000000') return null;2085    return blockHash;2086  }20872088  // TODO add docs2089  async getBlock(blockHashOrNumber: string | number): Promise<IBlock | null> {2090    const blockHash = typeof blockHashOrNumber === 'string' ? blockHashOrNumber : await this.getBlockHashByNumber(blockHashOrNumber);2091    if (!blockHash) return null;2092    return (await this.helper.callRpc('api.rpc.chain.getBlock', [blockHash])).toHuman().block;2093  }20942095  /**2096   * Get account nonce2097   * @param address substrate address2098   * @example getNonce("5GrwvaEF5zXb26Fz...");2099   * @returns number, account's nonce2100   */2101  async getNonce(address: TSubstrateAccount): Promise<number> {2102    return (await this.helper.callRpc('api.query.system.account', [address])).nonce.toNumber();2103  }2104}21052106class SubstrateBalanceGroup<T extends ChainHelperBase> extends HelperGroup<T> {2107  /**2108 * Get substrate address balance2109 * @param address substrate address2110 * @example getSubstrate("5GrwvaEF5zXb26Fz...")2111 * @returns amount of tokens on address2112 */2113  async getSubstrate(address: TSubstrateAccount): Promise<bigint> {2114    return (await this.helper.callRpc('api.query.system.account', [address])).data.free.toBigInt();2115  }21162117  /**2118   * Transfer tokens to substrate address2119   * @param signer keyring of signer2120   * @param address substrate address of a recipient2121   * @param amount amount of tokens to be transfered2122   * @example transferToSubstrate(aliceKeyring, "5GrwvaEF5zXb26Fz...", 100_000_000_000n);2123   * @returns ```true``` if extrinsic success, otherwise ```false```2124   */2125  async transferToSubstrate(signer: TSigner, address: TSubstrateAccount, amount: bigint | string): Promise<boolean> {2126    const result = await this.helper.executeExtrinsic(signer, 'api.tx.balances.transfer', [address, amount], true/*, `Unable to transfer balance from ${this.helper.getSignerAddress(signer)} to ${address}`*/);21272128    let transfer = {from: null, to: null, amount: 0n} as any;2129    result.result.events.forEach(({event: {data, method, section}}) => {2130      if ((section === 'balances') && (method === 'Transfer')) {2131        transfer = {2132          from: this.helper.address.normalizeSubstrate(data[0]),2133          to: this.helper.address.normalizeSubstrate(data[1]),2134          amount: BigInt(data[2]),2135        };2136      }2137    });2138    const isSuccess = this.helper.address.normalizeSubstrate(typeof signer === 'string' ? signer : signer.address) === transfer.from 2139      && this.helper.address.normalizeSubstrate(address) === transfer.to 2140      && BigInt(amount) === transfer.amount;2141    return isSuccess;2142  }21432144  /**2145   * Get full substrate balance including free, miscFrozen, feeFrozen, and reserved2146   * @param address substrate address2147   * @returns2148   */2149  async getSubstrateFull(address: TSubstrateAccount): Promise<ISubstrateBalance> {2150    const accountInfo = (await this.helper.callRpc('api.query.system.account', [address])).data;2151    return {free: accountInfo.free.toBigInt(), miscFrozen: accountInfo.miscFrozen.toBigInt(), feeFrozen: accountInfo.feeFrozen.toBigInt(), reserved: accountInfo.reserved.toBigInt()};2152  }2153}21542155class EthereumBalanceGroup<T extends ChainHelperBase> extends HelperGroup<T> {2156  /**2157   * Get ethereum address balance2158   * @param address ethereum address2159   * @example getEthereum("0x9F0583DbB855d...")2160   * @returns amount of tokens on address2161   */2162  async getEthereum(address: TEthereumAccount): Promise<bigint> {2163    return (await this.helper.callRpc('api.rpc.eth.getBalance', [address])).toBigInt();2164  }21652166  /**2167   * Transfer tokens to address2168   * @param signer keyring of signer2169   * @param address Ethereum address of a recipient2170   * @param amount amount of tokens to be transfered2171   * @example transferToEthereum(alithKeyring, "0x9F0583DbB855d...", 100_000_000_000n);2172   * @returns ```true``` if extrinsic success, otherwise ```false```2173   */2174  async transferToEthereum(signer: TSigner, address: TEthereumAccount, amount: bigint | string): Promise<boolean> {2175    const result = await this.helper.executeExtrinsic(signer, 'api.tx.balances.transfer', [address, amount], true);21762177    let transfer = {from: null, to: null, amount: 0n} as any;2178    result.result.events.forEach(({event: {data, method, section}}) => {2179      if ((section === 'balances') && (method === 'Transfer')) {2180        transfer = {2181          from: data[0].toString(),2182          to: data[1].toString(),2183          amount: BigInt(data[2]),2184        };2185      }2186    });2187    const isSuccess = (typeof signer === 'string' ? signer : signer.address) === transfer.from 2188      && address === transfer.to 2189      && BigInt(amount) === transfer.amount;2190    return isSuccess;2191  }2192}21932194class BalanceGroup<T extends ChainHelperBase> extends HelperGroup<T> {2195  subBalanceGroup: SubstrateBalanceGroup<T>;2196  ethBalanceGroup: EthereumBalanceGroup<T>;21972198  constructor(helper: T) {2199    super(helper);2200    this.subBalanceGroup = new SubstrateBalanceGroup(helper);2201    this.ethBalanceGroup = new EthereumBalanceGroup(helper);2202  }22032204  getCollectionCreationPrice(): bigint {2205    return 2n * this.getOneTokenNominal();2206  }2207  /**2208   * Representation of the native token in the smallest unit - one OPAL (OPL), QUARTZ (QTZ), or UNIQUE (UNQ).2209   * @example getOneTokenNominal()2210   * @returns ```BigInt``` representation of the native token in the smallest unit, e.g. ```1_000_000_000_000_000_000n``` for QTZ.2211   */2212  getOneTokenNominal(): bigint {2213    const chainProperties = this.helper.chain.getChainProperties();2214    return 10n ** BigInt((chainProperties.tokenDecimals || [18])[0]);2215  }22162217  /**2218   * Get substrate address balance2219   * @param address substrate address2220   * @example getSubstrate("5GrwvaEF5zXb26Fz...")2221   * @returns amount of tokens on address2222   */2223  async getSubstrate(address: TSubstrateAccount): Promise<bigint> {2224    return this.subBalanceGroup.getSubstrate(address);2225  }22262227  /**2228   * Get full substrate balance including free, miscFrozen, feeFrozen, and reserved2229   * @param address substrate address2230   * @returns2231   */2232  async getSubstrateFull(address: TSubstrateAccount): Promise<ISubstrateBalance> {2233    return this.subBalanceGroup.getSubstrateFull(address);2234  }22352236  /**2237   * Get ethereum address balance2238   * @param address ethereum address2239   * @example getEthereum("0x9F0583DbB855d...")2240   * @returns amount of tokens on address2241   */2242  async getEthereum(address: TEthereumAccount): Promise<bigint> {2243    return this.ethBalanceGroup.getEthereum(address);2244  }22452246  /**2247   * Transfer tokens to substrate address2248   * @param signer keyring of signer2249   * @param address substrate address of a recipient2250   * @param amount amount of tokens to be transfered2251   * @example transferToSubstrate(aliceKeyring, "5GrwvaEF5zXb26Fz...", 100_000_000_000n);2252   * @returns ```true``` if extrinsic success, otherwise ```false```2253   */2254  async transferToSubstrate(signer: TSigner, address: TSubstrateAccount, amount: bigint | string): Promise<boolean> {2255    return this.subBalanceGroup.transferToSubstrate(signer, address, amount);2256  }2257}22582259class AddressGroup extends HelperGroup<ChainHelperBase> {2260  /**2261   * Normalizes the address to the specified ss58 format, by default ```42```.2262   * @param address substrate address2263   * @param ss58Format format for address conversion, by default ```42```2264   * @example normalizeSubstrate("unjKJQJrRd238pkUZZvzDQrfKuM39zBSnQ5zjAGAGcdRhaJTx") // returns 5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY2265   * @returns substrate address converted to normalized (i.e., starting with 5) or specified explicitly representation2266   */2267  normalizeSubstrate(address: TSubstrateAccount, ss58Format = 42): TSubstrateAccount {2268    return CrossAccountId.normalizeSubstrateAddress(address, ss58Format);2269  }22702271  /**2272   * Get address in the connected chain format2273   * @param address substrate address2274   * @example normalizeSubstrateToChainFormat("5GrwvaEF5zXb26Fz...") // returns unjKJQJrRd238pkUZZ... for Unique Network2275   * @returns address in chain format2276   */2277  normalizeSubstrateToChainFormat(address: TSubstrateAccount): TSubstrateAccount {2278    return this.normalizeSubstrate(address, this.helper.chain.getChainProperties().ss58Format);2279  }22802281  /**2282   * Get substrate mirror of an ethereum address2283   * @param ethAddress ethereum address2284   * @param toChainFormat false for normalized account2285   * @example ethToSubstrate('0x9F0583DbB855d...')2286   * @returns substrate mirror of a provided ethereum address2287   */2288  ethToSubstrate(ethAddress: TEthereumAccount, toChainFormat=false): TSubstrateAccount {2289    return CrossAccountId.translateEthToSub(ethAddress, toChainFormat ? this.helper.chain.getChainProperties().ss58Format : undefined);2290  }22912292  /**2293   * Get ethereum mirror of a substrate address2294   * @param subAddress substrate account2295   * @example substrateToEth("5DnSF6RRjwteE3BrC...")2296   * @returns ethereum mirror of a provided substrate address2297   */2298  substrateToEth(subAddress: TSubstrateAccount): TEthereumAccount {2299    return CrossAccountId.translateSubToEth(subAddress);2300  }23012302  paraSiblingSovereignAccount(paraid: number) {2303    // We are getting a *sibling* parachain sovereign account,2304    // so we need a sibling prefix: encoded(b"sibl") == 0x7369626c2305    const siblingPrefix = '0x7369626c';23062307    const encodedParaId = this.helper.getApi().createType('u32', paraid).toHex(true).substring(2);2308    const suffix = '000000000000000000000000000000000000000000000000';23092310    return siblingPrefix + encodedParaId + suffix;2311  }2312}23132314class StakingGroup extends HelperGroup<UniqueHelper> {2315  /**2316   * Stake tokens for App Promotion2317   * @param signer keyring of signer2318   * @param amountToStake amount of tokens to stake2319   * @param label extra label for log2320   * @returns2321   */2322  async stake(signer: TSigner, amountToStake: bigint, label?: string): Promise<boolean> {2323    if(typeof label === 'undefined') label = `${signer.address} amount: ${amountToStake}`;2324    const _stakeResult = await this.helper.executeExtrinsic(2325      signer, 'api.tx.appPromotion.stake',2326      [amountToStake], true,2327    );2328    // TODO extract info from stakeResult2329    return true;2330  }23312332  /**2333   * Unstake tokens for App Promotion2334   * @param signer keyring of signer2335   * @param amountToUnstake amount of tokens to unstake2336   * @param label extra label for log2337   * @returns block number where balances will be unlocked2338   */2339  async unstake(signer: TSigner, label?: string): Promise<number> {2340    if(typeof label === 'undefined') label = `${signer.address}`;2341    const _unstakeResult = await this.helper.executeExtrinsic(2342      signer, 'api.tx.appPromotion.unstake',2343      [], true,2344    );2345    // TODO extract block number fron events2346    return 1;2347  }23482349  /**2350   * Get total staked amount for address2351   * @param address substrate or ethereum address2352   * @returns total staked amount2353   */2354  async getTotalStaked(address?: ICrossAccountId): Promise<bigint> {2355    if (address) return (await this.helper.callRpc('api.rpc.appPromotion.totalStaked', [address])).toBigInt();2356    return (await this.helper.callRpc('api.rpc.appPromotion.totalStaked')).toBigInt();2357  }23582359  /**2360   * Get total staked per block2361   * @param address substrate or ethereum address2362   * @returns array of stakes. `block` – the number of the block in which the stake was made. `amount` - the number of tokens staked in the block2363   */2364  async getTotalStakedPerBlock(address: ICrossAccountId): Promise<IStakingInfo[]> {2365    const rawTotalStakerdPerBlock = await this.helper.callRpc('api.rpc.appPromotion.totalStakedPerBlock', [address]);2366    return rawTotalStakerdPerBlock.map(([block, amount]: any[]) => {2367      return { 2368        block: block.toBigInt(),2369        amount: amount.toBigInt(),2370      };2371    });2372  }23732374  /**2375   * Get total pending unstake amount for address2376   * @param address substrate or ethereum address2377   * @returns total pending unstake amount2378   */2379  async getPendingUnstake(address: ICrossAccountId): Promise<bigint> {2380    return (await this.helper.callRpc('api.rpc.appPromotion.pendingUnstake', [address])).toBigInt();2381  }23822383  /**2384   * Get pending unstake amount per block for address2385   * @param address substrate or ethereum address2386   * @returns array of pending stakes. `block` – the number of the block in which the unstake was made. `amount` - the number of tokens unstaked in the block2387   */2388  async getPendingUnstakePerBlock(address: ICrossAccountId): Promise<IStakingInfo[]> {2389    const rawUnstakedPerBlock = await this.helper.callRpc('api.rpc.appPromotion.pendingUnstakePerBlock', [address]);2390    const result = rawUnstakedPerBlock.map(([block, amount]: any[]) => {2391      return {2392        block: block.toBigInt(),2393        amount: amount.toBigInt(),2394      };2395    });2396    return result;2397  }2398}23992400class SchedulerGroup extends HelperGroup<UniqueHelper> {2401  constructor(helper: UniqueHelper) {2402    super(helper);2403  }24042405  async cancelScheduled(signer: TSigner, scheduledId: string) {2406    return this.helper.executeExtrinsic(2407      signer,2408      'api.tx.scheduler.cancelNamed',2409      [scheduledId],2410      true,2411    );2412  }24132414  async changePriority(signer: TSigner, scheduledId: string, priority: number) {2415    return this.helper.executeExtrinsic(2416      signer,2417      'api.tx.scheduler.changeNamedPriority',2418      [scheduledId, priority],2419      true,2420    );2421  }24222423  scheduleAt<T extends UniqueHelper>(2424    scheduledId: string,2425    executionBlockNumber: number,2426    options: ISchedulerOptions = {},2427  ) {2428    return this.schedule<T>('scheduleNamed', scheduledId, executionBlockNumber, options);2429  }24302431  scheduleAfter<T extends UniqueHelper>(2432    scheduledId: string,2433    blocksBeforeExecution: number,2434    options: ISchedulerOptions = {},2435  ) {2436    return this.schedule<T>('scheduleNamedAfter', scheduledId, blocksBeforeExecution, options);2437  }24382439  schedule<T extends UniqueHelper>(2440    scheduleFn: 'scheduleNamed' | 'scheduleNamedAfter',2441    scheduledId: string,2442    blocksNum: number,2443    options: ISchedulerOptions = {},2444  ) {2445    // eslint-disable-next-line @typescript-eslint/naming-convention2446    const ScheduledHelperType = ScheduledUniqueHelper(this.helper.helperBase);2447    return this.helper.clone(ScheduledHelperType, {2448      scheduleFn,2449      scheduledId,2450      blocksNum,2451      options,2452    }) as T;2453  }2454}24552456class ForeignAssetsGroup extends HelperGroup<UniqueHelper> {2457  async register(signer: TSigner, ownerAddress: TSubstrateAccount, location: any, metadata: IForeignAssetMetadata) {2458    await this.helper.executeExtrinsic(2459      signer,2460      'api.tx.foreignAssets.registerForeignAsset',2461      [ownerAddress, location, metadata],2462      true,2463    );2464  }24652466  async update(signer: TSigner, foreignAssetId: number, location: any, metadata: IForeignAssetMetadata) {2467    await this.helper.executeExtrinsic(2468      signer,2469      'api.tx.foreignAssets.updateForeignAsset',2470      [foreignAssetId, location, metadata],2471      true,2472    );2473  }2474}24752476class XcmGroup<T extends ChainHelperBase> extends HelperGroup<T> {2477  palletName: string;24782479  constructor(helper: T, palletName: string) {2480    super(helper);24812482    this.palletName = palletName;2483  }24842485  async limitedReserveTransferAssets(signer: TSigner, destination: any, beneficiary: any, assets: any, feeAssetItem: number, weightLimit: number) {2486    await this.helper.executeExtrinsic(signer, `api.tx.${this.palletName}.limitedReserveTransferAssets`, [destination, beneficiary, assets, feeAssetItem, {Limited: weightLimit}], true);2487  }2488}24892490class XTokensGroup<T extends ChainHelperBase> extends HelperGroup<T> {2491  async transfer(signer: TSigner, currencyId: any, amount: bigint, destination: any, destWeight: number) {2492    await this.helper.executeExtrinsic(signer, 'api.tx.xTokens.transfer', [currencyId, amount, destination, destWeight], true);2493  }24942495  async transferMultiasset(signer: TSigner, asset: any, destination: any, destWeight: number) {2496    await this.helper.executeExtrinsic(signer, 'api.tx.xTokens.transferMultiasset', [asset, destination, destWeight], true);2497  }24982499  async transferMulticurrencies(signer: TSigner, currencies: any[], feeItem: number, destLocation: any, destWeight: number) {2500    await this.helper.executeExtrinsic(signer, 'api.tx.xTokens.transferMulticurrencies', [currencies, feeItem, destLocation, destWeight], true);2501  }2502}25032504class TokensGroup<T extends ChainHelperBase> extends HelperGroup<T> {2505  async accounts(address: string, currencyId: any) {2506    const {free} = (await this.helper.callRpc('api.query.tokens.accounts', [address, currencyId])).toJSON() as any;2507    return BigInt(free);2508  }2509}25102511class AssetsGroup<T extends ChainHelperBase> extends HelperGroup<T> {2512  async create(signer: TSigner, assetId: number, admin: string, minimalBalance: bigint) {2513    await this.helper.executeExtrinsic(signer, 'api.tx.assets.create', [assetId, admin, minimalBalance], true);2514  }25152516  async setMetadata(signer: TSigner, assetId: number, name: string, symbol: string, decimals: number) {2517    await this.helper.executeExtrinsic(signer, 'api.tx.assets.setMetadata', [assetId, name, symbol, decimals], true);2518  }25192520  async mint(signer: TSigner, assetId: number, beneficiary: string, amount: bigint) {2521    await this.helper.executeExtrinsic(signer, 'api.tx.assets.mint', [assetId, beneficiary, amount], true);2522  }25232524  async account(assetId: string | number, address: string) {2525    const accountAsset = (2526      await this.helper.callRpc('api.query.assets.account', [assetId, address])2527    ).toJSON()! as any;25282529    if (accountAsset !== null) {2530      return BigInt(accountAsset['balance']);2531    } else {2532      return null;2533    }2534  }2535}25362537class AcalaAssetRegistryGroup extends HelperGroup<AcalaHelper> {2538  async registerForeignAsset(signer: TSigner, destination: any, metadata: AcalaAssetMetadata) {2539    await this.helper.executeExtrinsic(signer, 'api.tx.assetRegistry.registerForeignAsset', [destination, metadata], true);2540  }2541}25422543class MoonbeamAssetManagerGroup extends HelperGroup<MoonbeamHelper> {2544  makeRegisterForeignAssetProposal(assetInfo: MoonbeamAssetInfo) {2545    const apiPrefix = 'api.tx.assetManager.';25462547    const registerTx = this.helper.constructApiCall(2548      apiPrefix + 'registerForeignAsset',2549      [assetInfo.location, assetInfo.metadata, assetInfo.existentialDeposit, assetInfo.isSufficient],2550    );25512552    const setUnitsTx = this.helper.constructApiCall(2553      apiPrefix + 'setAssetUnitsPerSecond',2554      [assetInfo.location, assetInfo.unitsPerSecond, assetInfo.numAssetsWeightHint],2555    );25562557    const batchCall = this.helper.getApi().tx.utility.batchAll([registerTx, setUnitsTx]);2558    const encodedProposal = batchCall?.method.toHex() || '';2559    return encodedProposal;2560  }25612562  async assetTypeId(location: any) {2563    return await this.helper.callRpc('api.query.assetManager.assetTypeId', [location]);2564  }2565}25662567class MoonbeamDemocracyGroup extends HelperGroup<MoonbeamHelper> {2568  async notePreimage(signer: TSigner, encodedProposal: string) {2569    await this.helper.executeExtrinsic(signer, 'api.tx.democracy.notePreimage', [encodedProposal], true);2570  }25712572  externalProposeMajority(proposalHash: string) {2573    return this.helper.constructApiCall('api.tx.democracy.externalProposeMajority', [proposalHash]);2574  }25752576  fastTrack(proposalHash: string, votingPeriod: number, delayPeriod: number) {2577    return this.helper.constructApiCall('api.tx.democracy.fastTrack', [proposalHash, votingPeriod, delayPeriod]);2578  }25792580  async referendumVote(signer: TSigner, referendumIndex: number, accountVote: DemocracyStandardAccountVote) {2581    await this.helper.executeExtrinsic(signer, 'api.tx.democracy.vote', [referendumIndex, {Standard: accountVote}], true);2582  }2583}25842585class MoonbeamCollectiveGroup extends HelperGroup<MoonbeamHelper> {2586  collective: string;25872588  constructor(helper: MoonbeamHelper, collective: string) {2589    super(helper);25902591    this.collective = collective;2592  }25932594  async propose(signer: TSigner, threshold: number, proposalHash: string, lengthBound: number) {2595    await this.helper.executeExtrinsic(signer, `api.tx.${this.collective}.propose`, [threshold, proposalHash, lengthBound], true);2596  }25972598  async vote(signer: TSigner, proposalHash: string, proposalIndex: number, approve: boolean) {2599    await this.helper.executeExtrinsic(signer, `api.tx.${this.collective}.vote`, [proposalHash, proposalIndex, approve], true);2600  }26012602  async close(signer: TSigner, proposalHash: string, proposalIndex: number, weightBound: number, lengthBound: number) {2603    await this.helper.executeExtrinsic(signer, `api.tx.${this.collective}.close`, [proposalHash, proposalIndex, weightBound, lengthBound], true);2604  }26052606  async proposalCount() {2607    return Number(await this.helper.callRpc(`api.query.${this.collective}.proposalCount`, []));2608  }2609}26102611export type ChainHelperBaseConstructor = new(...args: any[]) => ChainHelperBase;2612export type UniqueHelperConstructor = new(...args: any[]) => UniqueHelper;26132614export class UniqueHelper extends ChainHelperBase {2615  balance: BalanceGroup<UniqueHelper>;2616  collection: CollectionGroup;2617  nft: NFTGroup;2618  rft: RFTGroup;2619  ft: FTGroup;2620  staking: StakingGroup;2621  scheduler: SchedulerGroup;2622  foreignAssets: ForeignAssetsGroup;2623  xcm: XcmGroup<UniqueHelper>;2624  xTokens: XTokensGroup<UniqueHelper>;2625  tokens: TokensGroup<UniqueHelper>;26262627  constructor(logger?: ILogger, options: {[key: string]: any} = {}) {2628    super(logger, options.helperBase ?? UniqueHelper);26292630    this.balance = new BalanceGroup(this);2631    this.collection = new CollectionGroup(this);2632    this.nft = new NFTGroup(this);2633    this.rft = new RFTGroup(this);2634    this.ft = new FTGroup(this);2635    this.staking = new StakingGroup(this);2636    this.scheduler = new SchedulerGroup(this);2637    this.foreignAssets = new ForeignAssetsGroup(this);2638    this.xcm = new XcmGroup(this, 'polkadotXcm');2639    this.xTokens = new XTokensGroup(this);2640    this.tokens = new TokensGroup(this);2641  }26422643  getSudo<T extends UniqueHelper>() {2644    // eslint-disable-next-line @typescript-eslint/naming-convention2645    const SudoHelperType = SudoHelper(this.helperBase);2646    return this.clone(SudoHelperType) as T;2647  }2648}26492650export class XcmChainHelper extends ChainHelperBase {2651  async connect(wsEndpoint: string, _listeners?: any): Promise<void> {2652    const wsProvider = new WsProvider(wsEndpoint);2653    this.api = new ApiPromise({2654      provider: wsProvider,2655    });2656    await this.api.isReadyOrError;2657    this.network = await UniqueHelper.detectNetwork(this.api);2658  }2659}26602661export class RelayHelper extends XcmChainHelper {2662  xcm: XcmGroup<RelayHelper>;26632664  constructor(logger?: ILogger, options: {[key: string]: any} = {}) {2665    super(logger, options.helperBase ?? RelayHelper);26662667    this.xcm = new XcmGroup(this, 'xcmPallet');2668  }2669}26702671export class WestmintHelper extends XcmChainHelper {2672  balance: SubstrateBalanceGroup<WestmintHelper>;2673  xcm: XcmGroup<WestmintHelper>;2674  assets: AssetsGroup<WestmintHelper>;2675  xTokens: XTokensGroup<WestmintHelper>;26762677  constructor(logger?: ILogger, options: {[key: string]: any} = {}) {2678    super(logger, options.helperBase ?? WestmintHelper);26792680    this.balance = new SubstrateBalanceGroup(this);2681    this.xcm = new XcmGroup(this, 'polkadotXcm');2682    this.assets = new AssetsGroup(this);2683    this.xTokens = new XTokensGroup(this);2684  }2685}26862687export class MoonbeamHelper extends XcmChainHelper {2688  balance: EthereumBalanceGroup<MoonbeamHelper>;2689  assetManager: MoonbeamAssetManagerGroup;2690  assets: AssetsGroup<MoonbeamHelper>;2691  xTokens: XTokensGroup<MoonbeamHelper>;2692  democracy: MoonbeamDemocracyGroup;2693  collective: {2694    council: MoonbeamCollectiveGroup,2695    techCommittee: MoonbeamCollectiveGroup,2696  };26972698  constructor(logger?: ILogger, options: {[key: string]: any} = {}) {2699    super(logger, options.helperBase ?? MoonbeamHelper);27002701    this.balance = new EthereumBalanceGroup(this);2702    this.assetManager = new MoonbeamAssetManagerGroup(this);2703    this.assets = new AssetsGroup(this);2704    this.xTokens = new XTokensGroup(this);2705    this.democracy = new MoonbeamDemocracyGroup(this);2706    this.collective = {2707      council: new MoonbeamCollectiveGroup(this, 'councilCollective'),2708      techCommittee: new MoonbeamCollectiveGroup(this, 'techCommitteeCollective'),2709    };2710  }2711}27122713export class AcalaHelper extends XcmChainHelper {2714  balance: SubstrateBalanceGroup<AcalaHelper>;2715  assetRegistry: AcalaAssetRegistryGroup;2716  xTokens: XTokensGroup<AcalaHelper>;2717  tokens: TokensGroup<AcalaHelper>;27182719  constructor(logger?: ILogger, options: {[key: string]: any} = {}) {2720    super(logger, options.helperBase ?? AcalaHelper);27212722    this.balance = new SubstrateBalanceGroup(this);2723    this.assetRegistry = new AcalaAssetRegistryGroup(this);2724    this.xTokens = new XTokensGroup(this);2725    this.tokens = new TokensGroup(this);2726  }27272728  getSudo<T extends AcalaHelper>() {2729    // eslint-disable-next-line @typescript-eslint/naming-convention2730    const SudoHelperType = SudoHelper(this.helperBase);2731    return this.clone(SudoHelperType) as T;2732  }2733}27342735// eslint-disable-next-line @typescript-eslint/naming-convention2736function ScheduledUniqueHelper<T extends UniqueHelperConstructor>(Base: T) {2737  return class extends Base {2738    scheduleFn: 'scheduleNamed' | 'scheduleNamedAfter';2739    scheduledId: string;2740    blocksNum: number;2741    options: ISchedulerOptions;27422743    constructor(...args: any[]) {2744      const logger = args[0] as ILogger;2745      const options = args[1] as {2746        scheduleFn: 'scheduleNamed' | 'scheduleNamedAfter',2747        scheduledId: string,2748        blocksNum: number,2749        options: ISchedulerOptions2750      };27512752      super(logger);27532754      this.scheduleFn = options.scheduleFn;2755      this.scheduledId = options.scheduledId;2756      this.blocksNum = options.blocksNum;2757      this.options = options.options;2758    }27592760    executeExtrinsic(sender: IKeyringPair, scheduledExtrinsic: string, scheduledParams: any[], expectSuccess?: boolean): Promise<ITransactionResult> {2761      const scheduledTx = this.constructApiCall(scheduledExtrinsic, scheduledParams);2762      const extrinsic = 'api.tx.scheduler.' +  this.scheduleFn;27632764      return super.executeExtrinsic(2765        sender,2766        extrinsic,2767        [2768          this.scheduledId,2769          this.blocksNum,2770          this.options.periodic ? [this.options.periodic.period, this.options.periodic.repetitions] : null,2771          this.options.priority ?? null,2772          {Value: scheduledTx},2773        ],2774        expectSuccess,2775      );2776    }2777  };2778}27792780// eslint-disable-next-line @typescript-eslint/naming-convention2781function SudoHelper<T extends ChainHelperBaseConstructor>(Base: T) {2782  return class extends Base {2783    constructor(...args: any[]) {2784      super(...args);2785    }27862787    executeExtrinsic (2788      sender: IKeyringPair,2789      extrinsic: string,2790      params: any[],2791      expectSuccess?: boolean,2792    ): Promise<ITransactionResult> {2793      const call = this.constructApiCall(extrinsic, params);27942795      return super.executeExtrinsic(2796        sender,2797        'api.tx.sudo.sudo',2798        [call],2799        expectSuccess,2800      );2801    }2802  };2803}28042805export class UniqueBaseCollection {2806  helper: UniqueHelper;2807  collectionId: number;28082809  constructor(collectionId: number, uniqueHelper: UniqueHelper) {2810    this.collectionId = collectionId;2811    this.helper = uniqueHelper;2812  }28132814  async getData() {2815    return await this.helper.collection.getData(this.collectionId);2816  }28172818  async getLastTokenId() {2819    return await this.helper.collection.getLastTokenId(this.collectionId);2820  }28212822  async doesTokenExist(tokenId: number) {2823    return await this.helper.collection.doesTokenExist(this.collectionId, tokenId);2824  }28252826  async getAdmins() {2827    return await this.helper.collection.getAdmins(this.collectionId);2828  }28292830  async getAllowList() {2831    return await this.helper.collection.getAllowList(this.collectionId);2832  }28332834  async getEffectiveLimits() {2835    return await this.helper.collection.getEffectiveLimits(this.collectionId);2836  }28372838  async getProperties(propertyKeys?: string[] | null) {2839    return await this.helper.collection.getProperties(this.collectionId, propertyKeys);2840  }28412842  async getTokenNextSponsored(tokenId: number, addressObj: ICrossAccountId) {2843    return await this.helper.collection.getTokenNextSponsored(this.collectionId, tokenId, addressObj);2844  }28452846  async getOptions() {2847    return await this.helper.collection.getCollectionOptions(this.collectionId);2848  }28492850  async setSponsor(signer: TSigner, sponsorAddress: TSubstrateAccount) {2851    return await this.helper.collection.setSponsor(signer, this.collectionId, sponsorAddress);2852  }28532854  async confirmSponsorship(signer: TSigner) {2855    return await this.helper.collection.confirmSponsorship(signer, this.collectionId);2856  }28572858  async removeSponsor(signer: TSigner) {2859    return await this.helper.collection.removeSponsor(signer, this.collectionId);2860  }28612862  async setLimits(signer: TSigner, limits: ICollectionLimits) {2863    return await this.helper.collection.setLimits(signer, this.collectionId, limits);2864  }28652866  async changeOwner(signer: TSigner, ownerAddress: TSubstrateAccount) {2867    return await this.helper.collection.changeOwner(signer, this.collectionId, ownerAddress);2868  }28692870  async addAdmin(signer: TSigner, adminAddressObj: ICrossAccountId) {2871    return await this.helper.collection.addAdmin(signer, this.collectionId, adminAddressObj);2872  }28732874  async addToAllowList(signer: TSigner, addressObj: ICrossAccountId) {2875    return await this.helper.collection.addToAllowList(signer, this.collectionId, addressObj);2876  }28772878  async removeFromAllowList(signer: TSigner, addressObj: ICrossAccountId) {2879    return await this.helper.collection.removeFromAllowList(signer, this.collectionId, addressObj);2880  }28812882  async removeAdmin(signer: TSigner, adminAddressObj: ICrossAccountId) {2883    return await this.helper.collection.removeAdmin(signer, this.collectionId, adminAddressObj);2884  }28852886  async setProperties(signer: TSigner, properties: IProperty[]) {2887    return await this.helper.collection.setProperties(signer, this.collectionId, properties);2888  }28892890  async deleteProperties(signer: TSigner, propertyKeys: string[]) {2891    return await this.helper.collection.deleteProperties(signer, this.collectionId, propertyKeys);2892  }28932894  async setPermissions(signer: TSigner, permissions: ICollectionPermissions) {2895    return await this.helper.collection.setPermissions(signer, this.collectionId, permissions);2896  }28972898  async enableNesting(signer: TSigner, permissions: INestingPermissions) {2899    return await this.helper.collection.enableNesting(signer, this.collectionId, permissions);2900  }29012902  async disableNesting(signer: TSigner) {2903    return await this.helper.collection.disableNesting(signer, this.collectionId);2904  }29052906  async burn(signer: TSigner) {2907    return await this.helper.collection.burn(signer, this.collectionId);2908  }29092910  scheduleAt<T extends UniqueHelper>(2911    scheduledId: string,2912    executionBlockNumber: number,2913    options: ISchedulerOptions = {},2914  ) {2915    const scheduledHelper = this.helper.scheduler.scheduleAt<T>(scheduledId, executionBlockNumber, options);2916    return new UniqueBaseCollection(this.collectionId, scheduledHelper);2917  }29182919  scheduleAfter<T extends UniqueHelper>(2920    scheduledId: string,2921    blocksBeforeExecution: number,2922    options: ISchedulerOptions = {},2923  ) {2924    const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);2925    return new UniqueBaseCollection(this.collectionId, scheduledHelper);2926  }29272928  getSudo<T extends UniqueHelper>() {2929    return new UniqueBaseCollection(this.collectionId, this.helper.getSudo<T>());2930  }2931}293229332934export class UniqueNFTCollection extends UniqueBaseCollection {2935  getTokenObject(tokenId: number) {2936    return new UniqueNFToken(tokenId, this);2937  }29382939  async getTokensByAddress(addressObj: ICrossAccountId) {2940    return await this.helper.nft.getTokensByAddress(this.collectionId, addressObj);2941  }29422943  async getToken(tokenId: number, blockHashAt?: string) {2944    return await this.helper.nft.getToken(this.collectionId, tokenId, [], blockHashAt);2945  }29462947  async getTokenOwner(tokenId: number, blockHashAt?: string) {2948    return await this.helper.nft.getTokenOwner(this.collectionId, tokenId, blockHashAt);2949  }29502951  async getTokenTopmostOwner(tokenId: number, blockHashAt?: string) {2952    return await this.helper.nft.getTokenTopmostOwner(this.collectionId, tokenId, blockHashAt);2953  }29542955  async getTokenChildren(tokenId: number, blockHashAt?: string) {2956    return await this.helper.nft.getTokenChildren(this.collectionId, tokenId, blockHashAt);2957  }29582959  async getPropertyPermissions(propertyKeys: string[] | null = null) {2960    return await this.helper.nft.getPropertyPermissions(this.collectionId, propertyKeys);2961  }29622963  async getTokenProperties(tokenId: number, propertyKeys?: string[] | null) {2964    return await this.helper.nft.getTokenProperties(this.collectionId, tokenId, propertyKeys);2965  }29662967  async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId) {2968    return await this.helper.nft.transferToken(signer, this.collectionId, tokenId, addressObj);2969  }29702971  async transferTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2972    return await this.helper.nft.transferTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, toAddressObj);2973  }29742975  async approveToken(signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId) {2976    return await this.helper.nft.approveToken(signer, this.collectionId, tokenId, toAddressObj);2977  }29782979  async isTokenApproved(tokenId: number, toAddressObj: ICrossAccountId) {2980    return await this.helper.nft.isTokenApproved(this.collectionId, tokenId, toAddressObj);2981  }29822983  async mintToken(signer: TSigner, owner: ICrossAccountId = {Substrate: signer.address}, properties?: IProperty[]) {2984    return await this.helper.nft.mintToken(signer, {collectionId: this.collectionId, owner, properties});2985  }29862987  async mintMultipleTokens(signer: TSigner, tokens: {owner: ICrossAccountId, properties?: IProperty[]}[]) {2988    return await this.helper.nft.mintMultipleTokens(signer, this.collectionId, tokens);2989  }29902991  async burnToken(signer: TSigner, tokenId: number) {2992    return await this.helper.nft.burnToken(signer, this.collectionId, tokenId);2993  }29942995  async burnTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId) {2996    return await this.helper.nft.burnTokenFrom(signer, this.collectionId, tokenId, fromAddressObj);2997  }29982999  async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[]) {3000    return await this.helper.nft.setTokenProperties(signer, this.collectionId, tokenId, properties);3001  }30023003  async deleteTokenProperties(signer: TSigner, tokenId: number, propertyKeys: string[]) {3004    return await this.helper.nft.deleteTokenProperties(signer, this.collectionId, tokenId, propertyKeys);3005  }30063007  async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[]) {3008    return await this.helper.nft.setTokenPropertyPermissions(signer, this.collectionId, permissions);3009  }30103011  async nestToken(signer: TSigner, tokenId: number, toTokenObj: IToken) {3012    return await this.helper.nft.nestToken(signer, {collectionId: this.collectionId, tokenId}, toTokenObj);3013  }30143015  async unnestToken(signer: TSigner, tokenId: number, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {3016    return await this.helper.nft.unnestToken(signer, {collectionId: this.collectionId, tokenId}, fromTokenObj, toAddressObj);3017  }30183019  scheduleAt<T extends UniqueHelper>(3020    scheduledId: string,3021    executionBlockNumber: number,3022    options: ISchedulerOptions = {},3023  ) {3024    const scheduledHelper = this.helper.scheduler.scheduleAt<T>(scheduledId, executionBlockNumber, options);3025    return new UniqueNFTCollection(this.collectionId, scheduledHelper);3026  }30273028  scheduleAfter<T extends UniqueHelper>(3029    scheduledId: string,3030    blocksBeforeExecution: number,3031    options: ISchedulerOptions = {},3032  ) {3033    const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);3034    return new UniqueNFTCollection(this.collectionId, scheduledHelper);3035  }30363037  getSudo<T extends UniqueHelper>() {3038    return new UniqueNFTCollection(this.collectionId, this.helper.getSudo<T>());3039  }3040}304130423043export class UniqueRFTCollection extends UniqueBaseCollection {3044  getTokenObject(tokenId: number) {3045    return new UniqueRFToken(tokenId, this);3046  }30473048  async getToken(tokenId: number, blockHashAt?: string) {3049    return await this.helper.rft.getToken(this.collectionId, tokenId, [], blockHashAt);3050  }30513052  async getTokensByAddress(addressObj: ICrossAccountId) {3053    return await this.helper.rft.getTokensByAddress(this.collectionId, addressObj);3054  }30553056  async getTop10TokenOwners(tokenId: number) {3057    return await this.helper.rft.getTokenTop10Owners(this.collectionId, tokenId);3058  }30593060  async getTokenBalance(tokenId: number, addressObj: ICrossAccountId) {3061    return await this.helper.rft.getTokenBalance(this.collectionId, tokenId, addressObj);3062  }30633064  async getTokenTotalPieces(tokenId: number) {3065    return await this.helper.rft.getTokenTotalPieces(this.collectionId, tokenId);3066  }30673068  async getTokenApprovedPieces(tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {3069    return await this.helper.rft.getTokenApprovedPieces(this.collectionId, tokenId, toAddressObj, fromAddressObj);3070  }30713072  async getPropertyPermissions(propertyKeys: string[] | null = null) {3073    return await this.helper.rft.getPropertyPermissions(this.collectionId, propertyKeys);3074  }30753076  async getTokenProperties(tokenId: number, propertyKeys?: string[] | null) {3077    return await this.helper.rft.getTokenProperties(this.collectionId, tokenId, propertyKeys);3078  }30793080  async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId, amount=1n) {3081    return await this.helper.rft.transferToken(signer, this.collectionId, tokenId, addressObj, amount);3082  }30833084  async transferTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {3085    return await this.helper.rft.transferTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, toAddressObj, amount);3086  }30873088  async approveToken(signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {3089    return await this.helper.rft.approveToken(signer, this.collectionId, tokenId, toAddressObj, amount);3090  }30913092  async repartitionToken(signer: TSigner, tokenId: number, amount: bigint) {3093    return await this.helper.rft.repartitionToken(signer, this.collectionId, tokenId, amount);3094  }30953096  async mintToken(signer: TSigner, pieces=1n, owner: ICrossAccountId = {Substrate: signer.address}, properties?: IProperty[]) {3097    return await this.helper.rft.mintToken(signer, {collectionId: this.collectionId, owner, pieces, properties});3098  }30993100  async mintMultipleTokens(signer: TSigner, tokens: {pieces: bigint, owner: ICrossAccountId, properties?: IProperty[]}[]) {3101    return await this.helper.rft.mintMultipleTokens(signer, this.collectionId, tokens);3102  }31033104  async burnToken(signer: TSigner, tokenId: number, amount=1n) {3105    return await this.helper.rft.burnToken(signer, this.collectionId, tokenId, amount);3106  }31073108  async burnTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId,  amount=1n) {3109    return await this.helper.rft.burnTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, amount);3110  }31113112  async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[]) {3113    return await this.helper.rft.setTokenProperties(signer, this.collectionId, tokenId, properties);3114  }31153116  async deleteTokenProperties(signer: TSigner, tokenId: number, propertyKeys: string[]) {3117    return await this.helper.rft.deleteTokenProperties(signer, this.collectionId, tokenId, propertyKeys);3118  }31193120  async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[]) {3121    return await this.helper.rft.setTokenPropertyPermissions(signer, this.collectionId, permissions);3122  }31233124  scheduleAt<T extends UniqueHelper>(3125    scheduledId: string,3126    executionBlockNumber: number,3127    options: ISchedulerOptions = {},3128  ) {3129    const scheduledHelper = this.helper.scheduler.scheduleAt<T>(scheduledId, executionBlockNumber, options);3130    return new UniqueRFTCollection(this.collectionId, scheduledHelper);3131  }31323133  scheduleAfter<T extends UniqueHelper>(3134    scheduledId: string,3135    blocksBeforeExecution: number,3136    options: ISchedulerOptions = {},3137  ) {3138    const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);3139    return new UniqueRFTCollection(this.collectionId, scheduledHelper);3140  }31413142  getSudo<T extends UniqueHelper>() {3143    return new UniqueRFTCollection(this.collectionId, this.helper.getSudo<T>());3144  }3145}314631473148export class UniqueFTCollection extends UniqueBaseCollection {3149  async getBalance(addressObj: ICrossAccountId) {3150    return await this.helper.ft.getBalance(this.collectionId, addressObj);3151  }31523153  async getTotalPieces() {3154    return await this.helper.ft.getTotalPieces(this.collectionId);3155  }31563157  async getApprovedTokens(fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {3158    return await this.helper.ft.getApprovedTokens(this.collectionId, fromAddressObj, toAddressObj);3159  }31603161  async getTop10Owners() {3162    return await this.helper.ft.getTop10Owners(this.collectionId);3163  }31643165  async mint(signer: TSigner, amount=1n, owner: ICrossAccountId = {Substrate: signer.address}) {3166    return await this.helper.ft.mintTokens(signer, this.collectionId, amount, owner);3167  }31683169  async mintWithOneOwner(signer: TSigner, tokens: {value: bigint}[], owner: ICrossAccountId = {Substrate: signer.address}) {3170    return await this.helper.ft.mintMultipleTokensWithOneOwner(signer, this.collectionId, tokens, owner);3171  }31723173  async transfer(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {3174    return await this.helper.ft.transfer(signer, this.collectionId, toAddressObj, amount);3175  }31763177  async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {3178    return await this.helper.ft.transferFrom(signer, this.collectionId, fromAddressObj, toAddressObj, amount);3179  }31803181  async burnTokens(signer: TSigner, amount=1n) {3182    return await this.helper.ft.burnTokens(signer, this.collectionId, amount);3183  }31843185  async burnTokensFrom(signer: TSigner, fromAddressObj: ICrossAccountId, amount=1n) {3186    return await this.helper.ft.burnTokensFrom(signer, this.collectionId, fromAddressObj, amount);3187  }31883189  async approveTokens(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {3190    return await this.helper.ft.approveTokens(signer, this.collectionId, toAddressObj, amount);3191  }31923193  scheduleAt<T extends UniqueHelper>(3194    scheduledId: string,3195    executionBlockNumber: number,3196    options: ISchedulerOptions = {},3197  ) {3198    const scheduledHelper = this.helper.scheduler.scheduleAt<T>(scheduledId, executionBlockNumber, options);3199    return new UniqueFTCollection(this.collectionId, scheduledHelper);3200  }32013202  scheduleAfter<T extends UniqueHelper>(3203    scheduledId: string,3204    blocksBeforeExecution: number,3205    options: ISchedulerOptions = {},3206  ) {3207    const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);3208    return new UniqueFTCollection(this.collectionId, scheduledHelper);3209  }32103211  getSudo<T extends UniqueHelper>() {3212    return new UniqueFTCollection(this.collectionId, this.helper.getSudo<T>());3213  }3214}321532163217export class UniqueBaseToken {3218  collection: UniqueNFTCollection | UniqueRFTCollection;3219  collectionId: number;3220  tokenId: number;32213222  constructor(tokenId: number, collection: UniqueNFTCollection | UniqueRFTCollection) {3223    this.collection = collection;3224    this.collectionId = collection.collectionId;3225    this.tokenId = tokenId;3226  }32273228  async getNextSponsored(addressObj: ICrossAccountId) {3229    return await this.collection.getTokenNextSponsored(this.tokenId, addressObj);3230  }32313232  async getProperties(propertyKeys?: string[] | null) {3233    return await this.collection.getTokenProperties(this.tokenId, propertyKeys);3234  }32353236  async setProperties(signer: TSigner, properties: IProperty[]) {3237    return await this.collection.setTokenProperties(signer, this.tokenId, properties);3238  }32393240  async deleteProperties(signer: TSigner, propertyKeys: string[]) {3241    return await this.collection.deleteTokenProperties(signer, this.tokenId, propertyKeys);3242  }32433244  async doesExist() {3245    return await this.collection.doesTokenExist(this.tokenId);3246  }32473248  nestingAccount() {3249    return this.collection.helper.util.getTokenAccount(this);3250  }32513252  scheduleAt<T extends UniqueHelper>(3253    scheduledId: string,3254    executionBlockNumber: number,3255    options: ISchedulerOptions = {},3256  ) {3257    const scheduledCollection = this.collection.scheduleAt<T>(scheduledId, executionBlockNumber, options);3258    return new UniqueBaseToken(this.tokenId, scheduledCollection);3259  }32603261  scheduleAfter<T extends UniqueHelper>(3262    scheduledId: string,3263    blocksBeforeExecution: number,3264    options: ISchedulerOptions = {},3265  ) {3266    const scheduledCollection = this.collection.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);3267    return new UniqueBaseToken(this.tokenId, scheduledCollection);3268  }32693270  getSudo<T extends UniqueHelper>() {3271    return new UniqueBaseToken(this.tokenId, this.collection.getSudo<T>());3272  }3273}327432753276export class UniqueNFToken extends UniqueBaseToken {3277  collection: UniqueNFTCollection;32783279  constructor(tokenId: number, collection: UniqueNFTCollection) {3280    super(tokenId, collection);3281    this.collection = collection;3282  }32833284  async getData(blockHashAt?: string) {3285    return await this.collection.getToken(this.tokenId, blockHashAt);3286  }32873288  async getOwner(blockHashAt?: string) {3289    return await this.collection.getTokenOwner(this.tokenId, blockHashAt);3290  }32913292  async getTopmostOwner(blockHashAt?: string) {3293    return await this.collection.getTokenTopmostOwner(this.tokenId, blockHashAt);3294  }32953296  async getChildren(blockHashAt?: string) {3297    return await this.collection.getTokenChildren(this.tokenId, blockHashAt);3298  }32993300  async nest(signer: TSigner, toTokenObj: IToken) {3301    return await this.collection.nestToken(signer, this.tokenId, toTokenObj);3302  }33033304  async unnest(signer: TSigner, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {3305    return await this.collection.unnestToken(signer, this.tokenId, fromTokenObj, toAddressObj);3306  }33073308  async transfer(signer: TSigner, addressObj: ICrossAccountId) {3309    return await this.collection.transferToken(signer, this.tokenId, addressObj);3310  }33113312  async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {3313    return await this.collection.transferTokenFrom(signer, this.tokenId, fromAddressObj, toAddressObj);3314  }33153316  async approve(signer: TSigner, toAddressObj: ICrossAccountId) {3317    return await this.collection.approveToken(signer, this.tokenId, toAddressObj);3318  }33193320  async isApproved(toAddressObj: ICrossAccountId) {3321    return await this.collection.isTokenApproved(this.tokenId, toAddressObj);3322  }33233324  async burn(signer: TSigner) {3325    return await this.collection.burnToken(signer, this.tokenId);3326  }33273328  async burnFrom(signer: TSigner, fromAddressObj: ICrossAccountId) {3329    return await this.collection.burnTokenFrom(signer, this.tokenId, fromAddressObj);3330  }33313332  scheduleAt<T extends UniqueHelper>(3333    scheduledId: string,3334    executionBlockNumber: number,3335    options: ISchedulerOptions = {},3336  ) {3337    const scheduledCollection = this.collection.scheduleAt<T>(scheduledId, executionBlockNumber, options);3338    return new UniqueNFToken(this.tokenId, scheduledCollection);3339  }33403341  scheduleAfter<T extends UniqueHelper>(3342    scheduledId: string,3343    blocksBeforeExecution: number,3344    options: ISchedulerOptions = {},3345  ) {3346    const scheduledCollection = this.collection.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);3347    return new UniqueNFToken(this.tokenId, scheduledCollection);3348  }33493350  getSudo<T extends UniqueHelper>() {3351    return new UniqueNFToken(this.tokenId, this.collection.getSudo<T>());3352  }3353}33543355export class UniqueRFToken extends UniqueBaseToken {3356  collection: UniqueRFTCollection;33573358  constructor(tokenId: number, collection: UniqueRFTCollection) {3359    super(tokenId, collection);3360    this.collection = collection;3361  }33623363  async getData(blockHashAt?: string) {3364    return await this.collection.getToken(this.tokenId, blockHashAt);3365  }33663367  async getTop10Owners() {3368    return await this.collection.getTop10TokenOwners(this.tokenId);3369  }33703371  async getBalance(addressObj: ICrossAccountId) {3372    return await this.collection.getTokenBalance(this.tokenId, addressObj);3373  }33743375  async getTotalPieces() {3376    return await this.collection.getTokenTotalPieces(this.tokenId);3377  }33783379  async getApprovedPieces(fromAddressObj: ICrossAccountId, toAccountObj: ICrossAccountId) {3380    return await this.collection.getTokenApprovedPieces(this.tokenId, fromAddressObj, toAccountObj);3381  }33823383  async transfer(signer: TSigner, addressObj: ICrossAccountId, amount=1n) {3384    return await this.collection.transferToken(signer, this.tokenId, addressObj, amount);3385  }33863387  async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {3388    return await this.collection.transferTokenFrom(signer, this.tokenId, fromAddressObj, toAddressObj, amount);3389  }33903391  async approve(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {3392    return await this.collection.approveToken(signer, this.tokenId, toAddressObj, amount);3393  }33943395  async repartition(signer: TSigner, amount: bigint) {3396    return await this.collection.repartitionToken(signer, this.tokenId, amount);3397  }33983399  async burn(signer: TSigner, amount=1n) {3400    return await this.collection.burnToken(signer, this.tokenId, amount);3401  }34023403  async burnFrom(signer: TSigner, fromAddressObj: ICrossAccountId, amount=1n) {3404    return await this.collection.burnTokenFrom(signer, this.tokenId, fromAddressObj, amount);3405  }34063407  scheduleAt<T extends UniqueHelper>(3408    scheduledId: string,3409    executionBlockNumber: number,3410    options: ISchedulerOptions = {},3411  ) {3412    const scheduledCollection = this.collection.scheduleAt<T>(scheduledId, executionBlockNumber, options);3413    return new UniqueRFToken(this.tokenId, scheduledCollection);3414  }34153416  scheduleAfter<T extends UniqueHelper>(3417    scheduledId: string,3418    blocksBeforeExecution: number,3419    options: ISchedulerOptions = {},3420  ) {3421    const scheduledCollection = this.collection.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);3422    return new UniqueRFToken(this.tokenId, scheduledCollection);3423  }34243425  getSudo<T extends UniqueHelper>() {3426    return new UniqueRFToken(this.tokenId, this.collection.getSudo<T>());3427  }3428}