git.delta.rocks / unique-network / refs/commits / 0f4242c739ad

difftreelog

feat add ApproveFrom eth mirror

Grigoriy Simonov2023-01-09parent: #fe83568.patch.diff
in: master

26 files changed

modifiedpallets/common/src/lib.rsdiffbeforeafterboth
--- a/pallets/common/src/lib.rs
+++ b/pallets/common/src/lib.rs
@@ -746,6 +746,8 @@
 		ApprovedValueTooLow,
 		/// Tried to approve more than owned
 		CantApproveMoreThanOwned,
+		/// Only spending from eth mirror could be approved
+		AddressIsNotEthMirror,
 
 		/// Can't transfer tokens to ethereum zero address
 		AddressIsZero,
@@ -1797,6 +1799,9 @@
 	/// The price of setting the permission of the operation from another user.
 	fn approve() -> Weight;
 
+	/// The price of setting the permission of the operation from another user for eth mirror.
+	fn approve_from() -> Weight;
+
 	/// Transfer price from another user.
 	fn transfer_from() -> Weight;
 
@@ -2008,6 +2013,22 @@
 		amount: u128,
 	) -> DispatchResultWithPostInfo;
 
+	/// Grant access to another account to transfer parts of the token owned by the calling user's eth mirror via [Self::transfer_from].
+	///
+	/// * `sender` - The user who grants access to the token.
+	/// * `from` - Spender's eth mirror.
+	/// * `to` - The user to whom the rights are granted.
+	/// * `token` - The token to which access is granted.
+	/// * `amount` - The amount of pieces that another user can dispose of.
+	fn approve_from(
+		&self,
+		sender: T::CrossAccountId,
+		from: T::CrossAccountId,
+		to: T::CrossAccountId,
+		token: TokenId,
+		amount: u128,
+	) -> DispatchResultWithPostInfo;
+
 	/// Send parts of a token owned by another user.
 	///
 	/// Before calling this method, you must grant rights to the calling user via [`Self::approve`].
modifiedpallets/evm-contract-helpers/src/stubs/ContractHelpers.rawdiffbeforeafterboth

binary blob — no preview

modifiedpallets/evm-contract-helpers/src/stubs/ContractHelpers.soldiffbeforeafterboth
--- a/pallets/evm-contract-helpers/src/stubs/ContractHelpers.sol
+++ b/pallets/evm-contract-helpers/src/stubs/ContractHelpers.sol
@@ -283,8 +283,8 @@
 
 /// Ethereum representation of Optional value with CrossAddress.
 struct OptionCrossAddress {
-	/// TODO: field description
+	/// Whether or not this CrossAdress is valid and has meaning.
 	bool status;
-	/// TODO: field description
+	/// The underlying CrossAddress value. If the status is false, can be set to whatever.
 	CrossAddress value;
 }
modifiedpallets/fungible/src/benchmarking.rsdiffbeforeafterboth
--- a/pallets/fungible/src/benchmarking.rs
+++ b/pallets/fungible/src/benchmarking.rs
@@ -82,6 +82,16 @@
 		<Pallet<T>>::create_item(&collection, &owner, (sender.clone(), 200), &Unlimited)?;
 	}: {<Pallet<T>>::set_allowance(&collection, &sender, &spender, 100)?}
 
+	approve_from {
+		bench_init!{
+			owner: sub; collection: collection(owner);
+			owner: cross_from_sub; sender: cross_sub; spender: cross_sub;
+
+		};
+		let owner_eth = T::CrossAccountId::from_eth(*sender.as_eth());
+		<Pallet<T>>::create_item(&collection, &owner, (owner_eth.clone(), 200), &Unlimited)?;
+	}: {<Pallet<T>>::set_allowance_for(&collection, &sender, &owner_eth, &spender, 100)?}
+
 	transfer_from {
 		bench_init!{
 			owner: sub; collection: collection(owner);
modifiedpallets/fungible/src/common.rsdiffbeforeafterboth
--- a/pallets/fungible/src/common.rs
+++ b/pallets/fungible/src/common.rs
@@ -87,6 +87,10 @@
 		<SelfWeightOf<T>>::approve()
 	}
 
+	fn approve_from() -> Weight {
+		<SelfWeightOf<T>>::approve_from()
+	}
+
 	fn transfer_from() -> Weight {
 		<SelfWeightOf<T>>::transfer_from()
 	}
@@ -254,6 +258,25 @@
 		)
 	}
 
+	fn approve_from(
+		&self,
+		sender: T::CrossAccountId,
+		from: T::CrossAccountId,
+		to: T::CrossAccountId,
+		token: TokenId,
+		amount: u128,
+	) -> DispatchResultWithPostInfo {
+		ensure!(
+			token == TokenId::default(),
+			<Error<T>>::FungibleItemsHaveNoId
+		);
+
+		with_weight(
+			<Pallet<T>>::set_allowance_for(self, &sender, &from, &to, amount),
+			<CommonWeights<T>>::approve_from(),
+		)
+	}
+
 	fn transfer_from(
 		&self,
 		sender: T::CrossAccountId,
modifiedpallets/fungible/src/lib.rsdiffbeforeafterboth
--- a/pallets/fungible/src/lib.rs
+++ b/pallets/fungible/src/lib.rs
@@ -613,6 +613,45 @@
 		Ok(())
 	}
 
+	/// Set allowance for the spender to `transfer` or `burn` owner's tokens from eth mirror.
+	///
+	/// - `collection`: Collection that contains the token
+	/// - `sender`: Owner of tokens that sets the allowance.
+	/// - `from`: Owner's eth mirror.
+	/// - `to`: Recipient of the allowance rights.
+	/// - `amount`: Amount of tokens the spender is allowed to `transfer` or `burn`.
+	pub fn set_allowance_for(
+		collection: &FungibleHandle<T>,
+		sender: &T::CrossAccountId,
+		from: &T::CrossAccountId,
+		to: &T::CrossAccountId,
+		amount: u128,
+	) -> DispatchResult {
+		if collection.permissions.access() == AccessMode::AllowList {
+			collection.check_allowlist(sender)?;
+			collection.check_allowlist(from)?;
+			collection.check_allowlist(to)?;
+		}
+
+		ensure!(
+			*sender.as_eth() == *from.as_eth(),
+			<CommonError<T>>::AddressIsNotEthMirror
+		);
+
+		if <Balance<T>>::get((collection.id, from)) < amount {
+			ensure!(
+				collection.limits.owner_can_transfer()
+					&& (collection.is_owner_or_admin(sender) || collection.is_owner_or_admin(from)),
+				<CommonError<T>>::CantApproveMoreThanOwned
+			);
+		}
+
+		// =========
+
+		Self::set_allowance_unchecked(collection, from, to, amount);
+		Ok(())
+	}
+
 	/// Checks if a non-owner has (enough) allowance from the owner to perform operations on the tokens.
 	/// Returns the expected remaining allowance - it should be set manually if the transaction proceeds.
 	///
modifiedpallets/fungible/src/weights.rsdiffbeforeafterboth
--- a/pallets/fungible/src/weights.rs
+++ b/pallets/fungible/src/weights.rs
@@ -39,6 +39,7 @@
 	fn burn_item() -> Weight;
 	fn transfer() -> Weight;
 	fn approve() -> Weight;
+	fn approve_from() -> Weight;
 	fn transfer_from() -> Weight;
 	fn burn_from() -> Weight;
 }
@@ -84,6 +85,13 @@
 			.saturating_add(T::DbWeight::get().reads(1 as u64))
 			.saturating_add(T::DbWeight::get().writes(1 as u64))
 	}
+	// Storage: Fungible Balance (r:1 w:0)
+	// Storage: Fungible Allowance (r:0 w:1)
+	fn approve_from() -> Weight {
+		Weight::from_ref_time(19_817_000 as u64)
+			.saturating_add(T::DbWeight::get().reads(1 as u64))
+			.saturating_add(T::DbWeight::get().writes(1 as u64))
+	}
 	// Storage: Fungible Allowance (r:1 w:1)
 	// Storage: Fungible Balance (r:2 w:2)
 	fn transfer_from() -> Weight {
@@ -141,6 +149,13 @@
 			.saturating_add(RocksDbWeight::get().reads(1 as u64))
 			.saturating_add(RocksDbWeight::get().writes(1 as u64))
 	}
+	// Storage: Fungible Balance (r:1 w:0)
+	// Storage: Fungible Allowance (r:0 w:1)
+	fn approve_from() -> Weight {
+		Weight::from_ref_time(19_817_000 as u64)
+			.saturating_add(RocksDbWeight::get().reads(1 as u64))
+			.saturating_add(RocksDbWeight::get().writes(1 as u64))
+	}
 	// Storage: Fungible Allowance (r:1 w:1)
 	// Storage: Fungible Balance (r:2 w:2)
 	fn transfer_from() -> Weight {
modifiedpallets/nonfungible/src/benchmarking.rsdiffbeforeafterboth
--- a/pallets/nonfungible/src/benchmarking.rs
+++ b/pallets/nonfungible/src/benchmarking.rs
@@ -134,6 +134,15 @@
 		let item = create_max_item(&collection, &owner, sender.clone())?;
 	}: {<Pallet<T>>::set_allowance(&collection, &sender, item, Some(&spender))?}
 
+	approve_from {
+		bench_init!{
+			owner: sub; collection: collection(owner);
+			owner: cross_from_sub; sender: cross_sub; spender: cross_sub;
+		};
+		let owner_eth = T::CrossAccountId::from_eth(*sender.as_eth());
+		let item = create_max_item(&collection, &owner, owner_eth.clone())?;
+	}: {<Pallet<T>>::set_allowance_for(&collection, &sender, &owner_eth, item, Some(&spender))?}
+
 	transfer_from {
 		bench_init!{
 			owner: sub; collection: collection(owner);
modifiedpallets/nonfungible/src/common.rsdiffbeforeafterboth
--- a/pallets/nonfungible/src/common.rs
+++ b/pallets/nonfungible/src/common.rs
@@ -102,6 +102,10 @@
 		<SelfWeightOf<T>>::approve()
 	}
 
+	fn approve_from() -> Weight {
+		<SelfWeightOf<T>>::approve_from()
+	}
+
 	fn transfer_from() -> Weight {
 		<SelfWeightOf<T>>::transfer_from()
 	}
@@ -353,6 +357,26 @@
 		)
 	}
 
+	fn approve_from(
+		&self,
+		sender: T::CrossAccountId,
+		from: T::CrossAccountId,
+		to: T::CrossAccountId,
+		token: TokenId,
+		amount: u128,
+	) -> DispatchResultWithPostInfo {
+		ensure!(amount <= 1, <Error<T>>::NonfungibleItemsHaveNoAmount);
+
+		with_weight(
+			if amount == 1 {
+				<Pallet<T>>::set_allowance_for(self, &sender, &from, token, Some(&to))
+			} else {
+				<Pallet<T>>::set_allowance_for(self, &sender, &from, token, None)
+			},
+			<CommonWeights<T>>::approve_from(),
+		)
+	}
+
 	fn transfer_from(
 		&self,
 		sender: T::CrossAccountId,
modifiedpallets/nonfungible/src/lib.rsdiffbeforeafterboth
--- a/pallets/nonfungible/src/lib.rs
+++ b/pallets/nonfungible/src/lib.rs
@@ -1171,6 +1171,51 @@
 		Ok(())
 	}
 
+	/// Set allowance for the spender to `transfer` or `burn` sender's token from eth mirror.
+	///
+	/// - `from`: Address of sender's eth mirror.
+	/// - `to`: Adress of spender.
+	/// - `token`: Token the spender is allowed to `transfer` or `burn`.
+	pub fn set_allowance_for(
+		collection: &NonfungibleHandle<T>,
+		sender: &T::CrossAccountId,
+		from: &T::CrossAccountId,
+		token: TokenId,
+		to: Option<&T::CrossAccountId>,
+	) -> DispatchResult {
+		if collection.permissions.access() == AccessMode::AllowList {
+			collection.check_allowlist(sender)?;
+			collection.check_allowlist(from)?;
+			if let Some(to) = to {
+				collection.check_allowlist(to)?;
+			}
+		}
+
+		if let Some(to) = to {
+			<PalletCommon<T>>::ensure_correct_receiver(to)?;
+		}
+
+		ensure!(
+			*sender.as_eth() == *from.as_eth(),
+			<CommonError<T>>::AddressIsNotEthMirror
+		);
+
+		let token_data =
+			<TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;
+		if token_data.owner != *from {
+			ensure!(
+				collection.limits.owner_can_transfer()
+					&& (collection.is_owner_or_admin(sender) || collection.is_owner_or_admin(from)),
+				<CommonError<T>>::CantApproveMoreThanOwned
+			);
+		}
+
+		// =========
+
+		Self::set_allowance_unchecked(collection, from, token, to, false);
+		Ok(())
+	}
+
 	/// Checks allowance for the spender to use the token.
 	fn check_allowed(
 		collection: &NonfungibleHandle<T>,
modifiedpallets/nonfungible/src/weights.rsdiffbeforeafterboth
--- a/pallets/nonfungible/src/weights.rs
+++ b/pallets/nonfungible/src/weights.rs
@@ -42,6 +42,7 @@
 	fn burn_recursively_breadth_plus_self_plus_self_per_each_raw(b: u32, ) -> Weight;
 	fn transfer() -> Weight;
 	fn approve() -> Weight;
+	fn approve_from() -> Weight;
 	fn transfer_from() -> Weight;
 	fn burn_from() -> Weight;
 	fn set_token_property_permissions(b: u32, ) -> Weight;
@@ -147,6 +148,13 @@
 			.saturating_add(T::DbWeight::get().reads(2 as u64))
 			.saturating_add(T::DbWeight::get().writes(1 as u64))
 	}
+	// Storage: Nonfungible TokenData (r:1 w:0)
+	// Storage: Nonfungible Allowance (r:1 w:1)
+	fn approve_from() -> Weight {
+		Weight::from_ref_time(18_965_000 as u64)
+			.saturating_add(T::DbWeight::get().reads(2 as u64))
+			.saturating_add(T::DbWeight::get().writes(1 as u64))
+	}
 	// Storage: Nonfungible Allowance (r:1 w:1)
 	// Storage: Nonfungible TokenData (r:1 w:1)
 	// Storage: Nonfungible AccountBalance (r:2 w:2)
@@ -310,6 +318,13 @@
 			.saturating_add(RocksDbWeight::get().reads(2 as u64))
 			.saturating_add(RocksDbWeight::get().writes(1 as u64))
 	}
+	// Storage: Nonfungible TokenData (r:1 w:0)
+	// Storage: Nonfungible Allowance (r:1 w:1)
+	fn approve_from() -> Weight {
+		Weight::from_ref_time(18_965_000 as u64)
+			.saturating_add(RocksDbWeight::get().reads(2 as u64))
+			.saturating_add(RocksDbWeight::get().writes(1 as u64))
+	}
 	// Storage: Nonfungible Allowance (r:1 w:1)
 	// Storage: Nonfungible TokenData (r:1 w:1)
 	// Storage: Nonfungible AccountBalance (r:2 w:2)
modifiedpallets/refungible/src/benchmarking.rsdiffbeforeafterboth
--- a/pallets/refungible/src/benchmarking.rs
+++ b/pallets/refungible/src/benchmarking.rs
@@ -163,6 +163,15 @@
 		let item = create_max_item(&collection, &owner, [(sender.clone(), 200)])?;
 	}: {<Pallet<T>>::set_allowance(&collection, &sender, &spender, item, 100)?}
 
+	approve_from {
+		bench_init!{
+			owner: sub; collection: collection(owner);
+			owner: cross_from_sub; sender: cross_sub; spender: cross_sub;
+		};
+		let owner_eth = T::CrossAccountId::from_eth(*sender.as_eth());
+		let item = create_max_item(&collection, &owner, [(owner_eth.clone(), 200)])?;
+	}: {<Pallet<T>>::set_allowance_for(&collection, &sender, &owner_eth, &spender, item, 100)?}
+
 	transfer_from_normal {
 		bench_init!{
 			owner: sub; collection: collection(owner);
modifiedpallets/refungible/src/common.rsdiffbeforeafterboth
--- a/pallets/refungible/src/common.rs
+++ b/pallets/refungible/src/common.rs
@@ -127,6 +127,10 @@
 		<SelfWeightOf<T>>::approve()
 	}
 
+	fn approve_from() -> Weight {
+		<SelfWeightOf<T>>::approve_from()
+	}
+
 	fn transfer_from() -> Weight {
 		max_weight_of!(
 			transfer_from_normal(),
@@ -314,6 +318,20 @@
 		)
 	}
 
+	fn approve_from(
+		&self,
+		sender: T::CrossAccountId,
+		from: T::CrossAccountId,
+		to: T::CrossAccountId,
+		token_id: TokenId,
+		amount: u128,
+	) -> DispatchResultWithPostInfo {
+		with_weight(
+			<Pallet<T>>::set_allowance_for(self, &sender, &from, &to, token_id, amount),
+			<CommonWeights<T>>::approve_from(),
+		)
+	}
+
 	fn transfer_from(
 		&self,
 		sender: T::CrossAccountId,
modifiedpallets/refungible/src/lib.rsdiffbeforeafterboth
--- a/pallets/refungible/src/lib.rs
+++ b/pallets/refungible/src/lib.rs
@@ -1102,6 +1102,47 @@
 		Ok(())
 	}
 
+	/// Set allowance to spend from sender's eth mirror
+	///
+	/// - `from`: Address of sender's eth mirror.
+	/// - `to`: Adress of spender.
+	/// - `amount`: Amount of token pieces the spender is allowed to `transfer` or `burn.
+	pub fn set_allowance_for(
+		collection: &RefungibleHandle<T>,
+		sender: &T::CrossAccountId,
+		from: &T::CrossAccountId,
+		to: &T::CrossAccountId,
+		token_id: TokenId,
+		amount: u128,
+	) -> DispatchResult {
+		if collection.permissions.access() == AccessMode::AllowList {
+			collection.check_allowlist(sender)?;
+			collection.check_allowlist(from)?;
+			collection.check_allowlist(to)?;
+		}
+
+		<PalletCommon<T>>::ensure_correct_receiver(to)?;
+
+		ensure!(
+			*sender.as_eth() == *from.as_eth(),
+			<CommonError<T>>::AddressIsNotEthMirror
+		);
+
+		if <Balance<T>>::get((collection.id, token_id, from)) < amount {
+			ensure!(
+				collection.limits.owner_can_transfer()
+					&& (collection.is_owner_or_admin(sender) || collection.is_owner_or_admin(from))
+					&& Self::token_exists(collection, token_id),
+				<CommonError<T>>::CantApproveMoreThanOwned
+			);
+		}
+
+		// =========
+
+		Self::set_allowance_unchecked(collection, from, to, token_id, amount);
+		Ok(())
+	}
+
 	/// Returns allowance, which should be set after transaction
 	fn check_allowed(
 		collection: &RefungibleHandle<T>,
modifiedpallets/refungible/src/weights.rsdiffbeforeafterboth
--- a/pallets/refungible/src/weights.rs
+++ b/pallets/refungible/src/weights.rs
@@ -45,6 +45,7 @@
 	fn transfer_removing() -> Weight;
 	fn transfer_creating_removing() -> Weight;
 	fn approve() -> Weight;
+	fn approve_from() -> Weight;
 	fn transfer_from_normal() -> Weight;
 	fn transfer_from_creating() -> Weight;
 	fn transfer_from_removing() -> Weight;
@@ -175,6 +176,13 @@
 			.saturating_add(T::DbWeight::get().reads(1 as u64))
 			.saturating_add(T::DbWeight::get().writes(1 as u64))
 	}
+	// Storage: Refungible Balance (r:1 w:0)
+	// Storage: Refungible Allowance (r:0 w:1)
+	fn approve_from() -> Weight {
+		Weight::from_ref_time(20_649_000 as u64)
+			.saturating_add(T::DbWeight::get().reads(1 as u64))
+			.saturating_add(T::DbWeight::get().writes(1 as u64))
+	}
 	// Storage: Refungible Allowance (r:1 w:1)
 	// Storage: Refungible CollectionAllowance (r:1 w:0)
 	// Storage: Refungible Balance (r:2 w:2)
@@ -400,6 +408,13 @@
 			.saturating_add(RocksDbWeight::get().reads(1 as u64))
 			.saturating_add(RocksDbWeight::get().writes(1 as u64))
 	}
+	// Storage: Refungible Balance (r:1 w:0)
+	// Storage: Refungible Allowance (r:0 w:1)
+	fn approve_from() -> Weight {
+		Weight::from_ref_time(20_649_000 as u64)
+			.saturating_add(RocksDbWeight::get().reads(1 as u64))
+			.saturating_add(RocksDbWeight::get().writes(1 as u64))
+	}
 	// Storage: Refungible Allowance (r:1 w:1)
 	// Storage: Refungible CollectionAllowance (r:1 w:0)
 	// Storage: Refungible Balance (r:2 w:2)
modifiedpallets/unique/src/lib.rsdiffbeforeafterboth
--- a/pallets/unique/src/lib.rs
+++ b/pallets/unique/src/lib.rs
@@ -851,6 +851,29 @@
 			dispatch_tx::<T, _>(collection_id, |d| d.approve(sender, spender, item_id, amount))
 		}
 
+		/// Allow a non-permissioned address to transfer or burn an item from owner's eth mirror.
+		///
+		/// # Permissions
+		///
+		/// * Collection owner
+		/// * Collection admin
+		/// * Current item owner
+		///
+		/// # Arguments
+		///
+		/// * `from`: Owner's account eth mirror
+		/// * `to`: Account to be approved to make specific transactions on non-owned tokens.
+		/// * `collection_id`: ID of the collection the item belongs to.
+		/// * `item_id`: ID of the item transactions on which are now approved.
+		/// * `amount`: Number of pieces of the item approved for a transaction (maximum of 1 for NFTs).
+		/// Set to 0 to revoke the approval.
+		#[weight = T::CommonWeightInfo::approve_from()]
+		pub fn approve_from(origin, from:T::CrossAccountId, to: T::CrossAccountId, collection_id: CollectionId, item_id: TokenId, amount: u128) -> DispatchResultWithPostInfo {
+			let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);
+
+			dispatch_tx::<T, _>(collection_id, |d| d.approve_from(sender, from, to, item_id, amount))
+		}
+
 		/// Change ownership of an item on behalf of the owner as a non-owner account.
 		///
 		/// See the [`approve`][`Pallet::approve`] method for additional information.
modifiedruntime/common/identity.rsdiffbeforeafterboth
--- a/runtime/common/identity.rs
+++ b/runtime/common/identity.rs
@@ -21,9 +21,7 @@
 
 use sp_runtime::{
 	traits::{DispatchInfoOf, SignedExtension},
-	transaction_validity::{
-		TransactionValidity, ValidTransaction, InvalidTransaction, TransactionValidityError,
-	},
+	transaction_validity::{TransactionValidity, ValidTransaction, TransactionValidityError},
 };
 
 #[derive(Debug, Encode, Decode, PartialEq, Eq, Clone, TypeInfo)]
modifiedruntime/common/weights.rsdiffbeforeafterboth
--- a/runtime/common/weights.rs
+++ b/runtime/common/weights.rs
@@ -101,6 +101,10 @@
 		dispatch_weight::<T>() + max_weight_of!(approve())
 	}
 
+	fn approve_from() -> Weight {
+		dispatch_weight::<T>() + max_weight_of!(approve_from())
+	}
+
 	fn transfer_from() -> Weight {
 		dispatch_weight::<T>() + max_weight_of!(transfer_from())
 	}
modifiedtests/src/approve.test.tsdiffbeforeafterboth
--- a/tests/src/approve.test.ts
+++ b/tests/src/approve.test.ts
@@ -16,336 +16,521 @@
 
 import {IKeyringPair} from '@polkadot/types/types';
 import {expect, itSub, Pallets, usingPlaygrounds} from './util';
+import {CrossAccountId} from './util/playgrounds/unique';
+
 
 
-describe('Integration Test approve(spender, collection_id, item_id, amount):', () => {
-  let alice: IKeyringPair;
-  let bob: IKeyringPair;
-  let charlie: IKeyringPair;
+[
+  {method: 'approveToken', account: (account: IKeyringPair) => CrossAccountId.fromKeyring(account)},
+  {method: 'approveTokenFromEth', account: (account: IKeyringPair) => CrossAccountId.fromKeyring(account).toEthereum()},
+].map(testCase => {
+  describe(`Integration Test ${testCase.method}(spender, collection_id, item_id, amount):`, () => {
+    let alice: IKeyringPair;
+    let bob: IKeyringPair;
+    let charlie: IKeyringPair;
 
-  before(async () => {
-    await usingPlaygrounds(async (helper, privateKey) => {
-      const donor = await privateKey({filename: __filename});
-      [alice, bob, charlie] = await helper.arrange.createAccounts([100n, 100n, 100n], donor);
+    before(async () => {
+      await usingPlaygrounds(async (helper, privateKey) => {
+        const donor = await privateKey({filename: __filename});
+        [alice, bob, charlie] = await helper.arrange.createAccounts([100n, 100n, 100n], donor);
+      });
     });
-  });
 
-  itSub('[nft] Execute the extrinsic and check approvedList', async ({helper}) => {
-    const {collectionId} = await helper.nft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});
-    const {tokenId} = await helper.nft.mintToken(alice, {collectionId: collectionId, owner: alice.address});
-    await helper.nft.approveToken(alice, collectionId, tokenId, {Substrate: bob.address});
-    expect(await helper.nft.isTokenApproved(collectionId, tokenId, {Substrate: bob.address})).to.be.true;
-  });
+    itSub('[nft] Execute the extrinsic and check approvedList', async ({helper}) => {
+      const {collectionId} = await helper.nft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});
+      const {tokenId} = await helper.nft.mintToken(alice, {collectionId: collectionId, owner: testCase.account(alice)});
+      await (helper.nft as any)[testCase.method](alice, collectionId, tokenId, {Substrate: bob.address});
+      expect(await helper.nft.isTokenApproved(collectionId, tokenId, {Substrate: bob.address})).to.be.true;
+    });
+
+    itSub('[fungible] Execute the extrinsic and check approvedList', async ({helper}) => {
+      const {collectionId} = await helper.ft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'}, 0);
+      await helper.ft.mintTokens(alice, collectionId, 10n, testCase.account(alice));
+      const tokenId = await helper.ft.getLastTokenId(collectionId);
+      await (helper.ft as any)[testCase.method](alice, collectionId, tokenId, {Substrate: bob.address});
+      const amount = await helper.ft.getTokenApprovedPieces(collectionId, tokenId, {Substrate: bob.address}, testCase.account(alice));
+      expect(amount).to.be.equal(BigInt(1));
+    });
+
+    itSub.ifWithPallets('[refungible] Execute the extrinsic and check approvedList', [Pallets.ReFungible], async ({helper}) => {
+      const {collectionId} = await helper.rft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});
+      const {tokenId} = await helper.rft.mintToken(alice, {collectionId: collectionId, owner: testCase.account(alice), pieces: 100n});
+      await (helper.rft as any)[testCase.method](alice, collectionId, tokenId, {Substrate: bob.address});
+      const amount = await helper.rft.getTokenApprovedPieces(collectionId, tokenId, {Substrate: bob.address}, testCase.account(alice));
+      expect(amount).to.be.equal(BigInt(1));
+    });
+
+    itSub('[nft] Remove approval by using 0 amount', async ({helper}) => {
+      const collection = await helper.nft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});
+      const collectionId = collection.collectionId;
+      const {tokenId} = await helper.nft.mintToken(alice, {collectionId: collectionId, owner: testCase.account(alice)});
+      await (helper.nft as any)[testCase.method](alice, collectionId, tokenId, {Substrate: bob.address});
+      expect(await helper.nft.isTokenApproved(collectionId, tokenId, {Substrate: bob.address})).to.be.true;
+      await (helper.nft as any)[testCase.method](alice, collectionId, tokenId, {Substrate: bob.address}, 0n);
+      expect(await helper.nft.isTokenApproved(collectionId, tokenId, {Substrate: bob.address})).to.be.false;
+    });
 
-  itSub('[fungible] Execute the extrinsic and check approvedList', async ({helper}) => {
-    const {collectionId} = await helper.ft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'}, 0);
-    await helper.ft.mintTokens(alice, collectionId, 10n, {Substrate: alice.address});
-    const tokenId = await helper.ft.getLastTokenId(collectionId);
-    await helper.ft.approveToken(alice, collectionId, tokenId, {Substrate: bob.address});
-    const amount = await helper.ft.getTokenApprovedPieces(collectionId, tokenId, {Substrate: bob.address}, {Substrate: alice.address});
-    expect(amount).to.be.equal(BigInt(1));
-  });
+    itSub('[fungible] Remove approval by using 0 amount', async ({helper}) => {
+      const {collectionId} = await helper.ft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'}, 0);
+      await helper.ft.mintTokens(alice, collectionId, 10n, testCase.account(alice));
+      const tokenId = await helper.ft.getLastTokenId(collectionId);
+      await (helper.ft as any)[testCase.method](alice, collectionId, tokenId, {Substrate: bob.address});
+      const amountBefore = await helper.ft.getTokenApprovedPieces(collectionId, tokenId, {Substrate: bob.address}, testCase.account(alice));
+      expect(amountBefore).to.be.equal(BigInt(1));
 
-  itSub.ifWithPallets('[refungible] Execute the extrinsic and check approvedList', [Pallets.ReFungible], async ({helper}) => {
-    const {collectionId} = await helper.rft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});
-    const {tokenId} = await helper.rft.mintToken(alice, {collectionId: collectionId, owner: alice.address, pieces: 100n});
-    await helper.rft.approveToken(alice, collectionId, tokenId, {Substrate: bob.address});
-    const amount = await helper.rft.getTokenApprovedPieces(collectionId, tokenId, {Substrate: bob.address}, {Substrate: alice.address});
-    expect(amount).to.be.equal(BigInt(1));
-  });
+      await (helper.ft as any)[testCase.method](alice, collectionId, tokenId, {Substrate: bob.address}, 0n);
+      const amountAfter = await helper.ft.getTokenApprovedPieces(collectionId, tokenId, {Substrate: bob.address}, testCase.account(alice));
+      expect(amountAfter).to.be.equal(BigInt(0));
+    });
 
-  itSub('[nft] Remove approval by using 0 amount', async ({helper}) => {
-    const collection = await helper.nft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});
-    const collectionId = collection.collectionId;
-    const {tokenId} = await helper.nft.mintToken(alice, {collectionId: collectionId, owner: alice.address});
-    await helper.nft.approveToken(alice, collectionId, tokenId, {Substrate: bob.address});
-    expect(await helper.nft.isTokenApproved(collectionId, tokenId, {Substrate: bob.address})).to.be.true;
-    await helper.signTransaction(alice, helper.constructApiCall('api.tx.unique.approve', [{Substrate: bob.address}, collectionId, tokenId, 0]));
-    expect(await helper.nft.isTokenApproved(collectionId, tokenId, {Substrate: bob.address})).to.be.false;
-  });
+    itSub.ifWithPallets('[refungible] Remove approval by using 0 amount', [Pallets.ReFungible], async ({helper}) => {
+      const {collectionId} = await helper.rft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});
+      const {tokenId} = await helper.rft.mintToken(alice, {collectionId: collectionId, owner: testCase.account(alice), pieces: 100n});
+      await (helper.rft as any)[testCase.method](alice, collectionId, tokenId, {Substrate: bob.address});
+      const amountBefore = await helper.rft.getTokenApprovedPieces(collectionId, tokenId, {Substrate: bob.address}, testCase.account(alice));
+      expect(amountBefore).to.be.equal(BigInt(1));
 
-  itSub('[fungible] Remove approval by using 0 amount', async ({helper}) => {
-    const {collectionId} = await helper.ft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'}, 0);
-    await helper.ft.mintTokens(alice, collectionId, 10n, {Substrate: alice.address});
-    const tokenId = await helper.ft.getLastTokenId(collectionId);
-    await helper.ft.approveToken(alice, collectionId, tokenId, {Substrate: bob.address});
-    const amountBefore = await helper.ft.getTokenApprovedPieces(collectionId, tokenId, {Substrate: bob.address}, {Substrate: alice.address});
-    expect(amountBefore).to.be.equal(BigInt(1));
+      await (helper.rft as any)[testCase.method](alice, collectionId, tokenId, {Substrate: bob.address}, 0n);
+      const amountAfter = await helper.rft.getTokenApprovedPieces(collectionId, tokenId, {Substrate: bob.address}, testCase.account(alice));
+      expect(amountAfter).to.be.equal(BigInt(0));
+    });
 
-    await helper.ft.approveToken(alice, collectionId, tokenId, {Substrate: bob.address}, 0n);
-    const amountAfter = await helper.ft.getTokenApprovedPieces(collectionId, tokenId, {Substrate: bob.address}, {Substrate: alice.address});
-    expect(amountAfter).to.be.equal(BigInt(0));
+    itSub('can`t be called by collection owner on non-owned item when OwnerCanTransfer == false', async ({helper}) => {
+      const {collectionId} = await helper.nft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});
+      const {tokenId} = await helper.nft.mintToken(alice, {collectionId: collectionId, owner: testCase.account(bob)});
+      const result = (helper.nft as any)[testCase.method](alice, collectionId, tokenId, {Substrate: charlie.address});
+      await expect(result).to.be.rejected;
+    });
   });
 
-  itSub.ifWithPallets('[refungible] Remove approval by using 0 amount', [Pallets.ReFungible], async ({helper}) => {
-    const {collectionId} = await helper.rft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});
-    const {tokenId} = await helper.rft.mintToken(alice, {collectionId: collectionId, owner: alice.address, pieces: 100n});
-    await helper.rft.approveToken(alice, collectionId, tokenId, {Substrate: bob.address});
-    const amountBefore = await helper.rft.getTokenApprovedPieces(collectionId, tokenId, {Substrate: bob.address}, {Substrate: alice.address});
-    expect(amountBefore).to.be.equal(BigInt(1));
+  describe(`[${testCase.method}] Normal user can approve other users to transfer:`, () => {
+    let alice: IKeyringPair;
+    let bob: IKeyringPair;
+    let charlie: IKeyringPair;
 
-    await helper.rft.approveToken(alice, collectionId, tokenId, {Substrate: bob.address}, 0n);
-    const amountAfter = await helper.rft.getTokenApprovedPieces(collectionId, tokenId, {Substrate: bob.address}, {Substrate: alice.address});
-    expect(amountAfter).to.be.equal(BigInt(0));
-  });
+    before(async () => {
+      await usingPlaygrounds(async (helper, privateKey) => {
+        const donor = await privateKey({filename: __filename});
+        [alice, bob, charlie] = await helper.arrange.createAccounts([100n, 100n, 100n], donor);
+      });
+    });
 
-  itSub('can`t be called by collection owner on non-owned item when OwnerCanTransfer == false', async ({helper}) => {
-    const {collectionId} = await helper.nft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});
-    const {tokenId} = await helper.nft.mintToken(alice, {collectionId: collectionId, owner: bob.address});
-    const approveTokenTx = () => helper.nft.approveToken(alice, collectionId, tokenId, {Substrate: charlie.address});
-    await expect(approveTokenTx()).to.be.rejected;
-  });
-});
+    itSub('NFT', async ({helper}) => {
+      const {collectionId} = await helper.nft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});
+      const {tokenId} = await helper.nft.mintToken(alice, {collectionId: collectionId, owner: testCase.account(bob)});
+      await (helper.nft as any)[testCase.method](bob, collectionId, tokenId, {Substrate: charlie.address});
+      expect(await helper.nft.isTokenApproved(collectionId, tokenId, {Substrate: charlie.address})).to.be.true;
+    });
 
-describe('Normal user can approve other users to transfer:', () => {
-  let alice: IKeyringPair;
-  let bob: IKeyringPair;
-  let charlie: IKeyringPair;
+    itSub('Fungible up to an approved amount', async ({helper}) => {
+      const {collectionId} = await helper.ft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'}, 0);
+      await helper.ft.mintTokens(alice, collectionId, 10n, testCase.account(bob));
+      const tokenId = await helper.ft.getLastTokenId(collectionId);
+      await (helper.ft as any)[testCase.method](bob, collectionId, tokenId, {Substrate: charlie.address});
+      const amount = await helper.ft.getTokenApprovedPieces(collectionId, tokenId, {Substrate: charlie.address}, testCase.account(bob));
+      expect(amount).to.be.equal(BigInt(1));
+    });
 
-  before(async () => {
-    await usingPlaygrounds(async (helper, privateKey) => {
-      const donor = await privateKey({filename: __filename});
-      [alice, bob, charlie] = await helper.arrange.createAccounts([100n, 100n, 100n], donor);
+    itSub.ifWithPallets('ReFungible up to an approved amount', [Pallets.ReFungible], async ({helper}) => {
+      const {collectionId} = await helper.rft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});
+      const {tokenId} = await helper.rft.mintToken(alice, {collectionId: collectionId, owner: testCase.account(bob), pieces: 100n});
+      await (helper.rft as any)[testCase.method](bob, collectionId, tokenId, {Substrate: charlie.address}, 100n);
+      const amount = await helper.rft.getTokenApprovedPieces(collectionId, tokenId, {Substrate: charlie.address}, testCase.account(bob));
+      expect(amount).to.be.equal(BigInt(100n));
     });
   });
 
-  itSub('NFT', async ({helper}) => {
-    const {collectionId} = await helper.nft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});
-    const {tokenId} = await helper.nft.mintToken(alice, {collectionId: collectionId, owner: bob.address});
-    await helper.nft.approveToken(bob, collectionId, tokenId, {Substrate: charlie.address});
-    expect(await helper.nft.isTokenApproved(collectionId, tokenId, {Substrate: charlie.address})).to.be.true;
-  });
+  describe(`[${testCase.method}] Approved users can transferFrom up to approved amount:`, () => {
+    let alice: IKeyringPair;
+    let bob: IKeyringPair;
+    let charlie: IKeyringPair;
 
-  itSub('Fungible up to an approved amount', async ({helper}) => {
-    const {collectionId} = await helper.ft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'}, 0);
-    await helper.ft.mintTokens(alice, collectionId, 10n, bob.address);
-    const tokenId = await helper.ft.getLastTokenId(collectionId);
-    await helper.ft.approveToken(bob, collectionId, tokenId, {Substrate: charlie.address});
-    const amount = await helper.ft.getTokenApprovedPieces(collectionId, tokenId, {Substrate: charlie.address}, {Substrate: bob.address});
-    expect(amount).to.be.equal(BigInt(1));
-  });
+    before(async () => {
+      await usingPlaygrounds(async (helper, privateKey) => {
+        const donor = await privateKey({filename: __filename});
+        [alice, bob, charlie] = await helper.arrange.createAccounts([100n, 100n, 100n], donor);
+      });
+    });
 
-  itSub.ifWithPallets('ReFungible up to an approved amount', [Pallets.ReFungible], async ({helper}) => {
-    const {collectionId} = await helper.rft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});
-    const {tokenId} = await helper.rft.mintToken(alice, {collectionId: collectionId, owner: bob.address, pieces: 100n});
-    await helper.rft.approveToken(bob, collectionId, tokenId, {Substrate: charlie.address}, 100n);
-    const amount = await helper.rft.getTokenApprovedPieces(collectionId, tokenId, {Substrate: charlie.address}, {Substrate: bob.address});
-    expect(amount).to.be.equal(BigInt(100n));
+    itSub('NFT', async ({helper}) => {
+      const {collectionId} = await helper.nft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});
+      const {tokenId} = await helper.nft.mintToken(alice, {collectionId: collectionId, owner: testCase.account(bob)});
+      await (helper.nft as any)[testCase.method](bob, collectionId, tokenId, {Substrate: charlie.address});
+      await helper.nft.transferTokenFrom(charlie, collectionId, tokenId, testCase.account(bob), {Substrate: alice.address});
+      const owner = await helper.nft.getTokenOwner(collectionId, tokenId);
+      expect(owner.Substrate).to.be.equal(alice.address);
+    });
+
+    itSub('Fungible up to an approved amount', async ({helper}) => {
+      const {collectionId} = await helper.ft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'}, 0);
+      await helper.ft.mintTokens(alice, collectionId, 10n, testCase.account(bob));
+      const tokenId = await helper.ft.getLastTokenId(collectionId);
+      await (helper.ft as any)[testCase.method](bob, collectionId, tokenId, {Substrate: charlie.address});
+      const before = await helper.ft.getBalance(collectionId, {Substrate: alice.address});
+      await helper.ft.transferTokenFrom(charlie, collectionId, tokenId, testCase.account(bob), {Substrate: alice.address}, 1n);
+      const after = await helper.ft.getBalance(collectionId, {Substrate: alice.address});
+      expect(after - before).to.be.equal(BigInt(1));
+    });
+
+    itSub.ifWithPallets('ReFungible up to an approved amount', [Pallets.ReFungible], async ({helper}) => {
+      const {collectionId} = await helper.rft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});
+      const {tokenId} = await helper.rft.mintToken(alice, {collectionId: collectionId, owner: testCase.account(bob), pieces: 100n});
+      await (helper.rft as any)[testCase.method](bob, collectionId, tokenId, {Substrate: charlie.address});
+      const before = await helper.rft.getTokenBalance(collectionId, tokenId, {Substrate: alice.address});
+      await helper.rft.transferTokenFrom(charlie, collectionId, tokenId, testCase.account(bob), {Substrate: alice.address}, 1n);
+      const after = await helper.rft.getTokenBalance(collectionId, tokenId, {Substrate: alice.address});
+      expect(after - before).to.be.equal(BigInt(1));
+    });
   });
-});
 
-describe('Approved users can transferFrom up to approved amount:', () => {
-  let alice: IKeyringPair;
-  let bob: IKeyringPair;
-  let charlie: IKeyringPair;
+  describe(`[${testCase.method}] Approved users cannot use transferFrom to repeat transfers if approved amount was already transferred:`, () => {
+    let alice: IKeyringPair;
+    let bob: IKeyringPair;
+    let charlie: IKeyringPair;
+
+    before(async () => {
+      await usingPlaygrounds(async (helper, privateKey) => {
+        const donor = await privateKey({filename: __filename});
+        [alice, bob, charlie] = await helper.arrange.createAccounts([100n, 100n, 100n], donor);
+      });
+    });
+
+    itSub('NFT', async ({helper}) => {
+      const {collectionId} = await helper.nft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});
+      const {tokenId} = await helper.nft.mintToken(alice, {collectionId: collectionId, owner: testCase.account(bob)});
+      await (helper.nft as any)[testCase.method](bob, collectionId, tokenId, {Substrate: charlie.address});
+      await helper.nft.transferTokenFrom(charlie, collectionId, tokenId, testCase.account(bob), {Substrate: alice.address});
+      const owner = await helper.nft.getTokenOwner(collectionId, tokenId);
+      expect(owner.Substrate).to.be.equal(alice.address);
+      const transferTokenFromTx = () => helper.nft.transferTokenFrom(charlie, collectionId, tokenId, testCase.account(bob), {Substrate: alice.address});
+      await expect(transferTokenFromTx()).to.be.rejected;
+    });
+
+    itSub('Fungible up to an approved amount', async ({helper}) => {
+      const {collectionId} = await helper.ft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'}, 0);
+      await helper.ft.mintTokens(alice, collectionId, 10n, testCase.account(bob));
+      const tokenId = await helper.ft.getLastTokenId(collectionId);
+      await (helper.ft as any)[testCase.method](bob, collectionId, tokenId, {Substrate: charlie.address});
+      const before = await helper.ft.getBalance(collectionId, {Substrate: alice.address});
+      await helper.ft.transferTokenFrom(charlie, collectionId, tokenId, testCase.account(bob), {Substrate: alice.address}, 1n);
+      const after = await helper.ft.getBalance(collectionId, {Substrate: alice.address});
+      expect(after - before).to.be.equal(BigInt(1));
+
+      const transferTokenFromTx = () => helper.ft.transferTokenFrom(charlie, collectionId, tokenId, testCase.account(bob), {Substrate: alice.address}, 1n);
+      await expect(transferTokenFromTx()).to.be.rejected;
+    });
 
-  before(async () => {
-    await usingPlaygrounds(async (helper, privateKey) => {
-      const donor = await privateKey({filename: __filename});
-      [alice, bob, charlie] = await helper.arrange.createAccounts([100n, 100n, 100n], donor);
+    itSub.ifWithPallets('ReFungible up to an approved amount', [Pallets.ReFungible], async ({helper}) => {
+      const {collectionId} = await helper.rft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});
+      const {tokenId} = await helper.rft.mintToken(alice, {collectionId: collectionId, owner: testCase.account(bob), pieces: 100n});
+      await (helper.ft as any)[testCase.method](bob, collectionId, tokenId, {Substrate: charlie.address}, 100n);
+      const before = await helper.rft.getTokenBalance(collectionId, tokenId, {Substrate: alice.address});
+      await helper.rft.transferTokenFrom(charlie, collectionId, tokenId, testCase.account(bob), {Substrate: alice.address}, 100n);
+      const after = await helper.rft.getTokenBalance(collectionId, tokenId, {Substrate: alice.address});
+      expect(after - before).to.be.equal(BigInt(100));
+      const transferTokenFromTx = () => helper.rft.transferTokenFrom(charlie, collectionId, tokenId, testCase.account(bob), {Substrate: alice.address}, 100n);
+      await expect(transferTokenFromTx()).to.be.rejected;
     });
   });
 
-  itSub('NFT', async ({helper}) => {
-    const {collectionId} = await helper.nft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});
-    const {tokenId} = await helper.nft.mintToken(alice, {collectionId: collectionId, owner: bob.address});
-    await helper.nft.approveToken(bob, collectionId, tokenId, {Substrate: charlie.address});
-    await helper.nft.transferTokenFrom(charlie, collectionId, tokenId, {Substrate: bob.address}, {Substrate: alice.address});
-    const owner = await helper.nft.getTokenOwner(collectionId, tokenId);
-    expect(owner.Substrate).to.be.equal(alice.address);
+  describe(`[${testCase.method}] Approved amount decreases by the transferred amount:`, () => {
+    let alice: IKeyringPair;
+    let bob: IKeyringPair;
+    let charlie: IKeyringPair;
+    let dave: IKeyringPair;
+
+    before(async () => {
+      await usingPlaygrounds(async (helper, privateKey) => {
+        const donor = await privateKey({filename: __filename});
+        [alice, bob, charlie, dave] = await helper.arrange.createAccounts([100n, 100n, 100n, 100n], donor);
+      });
+    });
+
+    itSub('If a user B is approved to transfer 10 Fungible tokens from user A, they can transfer 2 tokens to user C, which will result in decreasing approval from 10 to 8. Then user B can transfer 8 tokens to user D.', async ({helper}) => {
+      const {collectionId} = await helper.ft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'}, 0);
+      await helper.ft.mintTokens(alice, collectionId, 10n, testCase.account(alice));
+      const tokenId = await helper.ft.getLastTokenId(collectionId);
+      await (helper.ft as any)[testCase.method](alice, collectionId, tokenId, {Substrate: bob.address}, 10n);
+
+      const charlieBefore = await helper.ft.getBalance(collectionId, {Substrate: charlie.address});
+      await helper.ft.transferTokenFrom(bob, collectionId, tokenId, testCase.account(alice), {Substrate: charlie.address}, 2n);
+      const charlieAfter = await helper.ft.getBalance(collectionId, {Substrate: charlie.address});
+      expect(charlieAfter - charlieBefore).to.be.equal(BigInt(2));
+
+      const daveBefore = await helper.ft.getBalance(collectionId, {Substrate: dave.address});
+      await helper.ft.transferTokenFrom(bob, collectionId, tokenId, testCase.account(alice), {Substrate: dave.address}, 8n);
+      const daveAfter = await helper.ft.getBalance(collectionId, {Substrate: dave.address});
+      expect(daveAfter - daveBefore).to.be.equal(BigInt(8));
+    });
   });
 
-  itSub('Fungible up to an approved amount', async ({helper}) => {
-    const {collectionId} = await helper.ft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'}, 0);
-    await helper.ft.mintTokens(alice, collectionId, 10n, bob.address);
-    const tokenId = await helper.ft.getLastTokenId(collectionId);
-    await helper.ft.approveToken(bob, collectionId, tokenId, {Substrate: charlie.address});
-    const before = await helper.ft.getBalance(collectionId, {Substrate: alice.address});
-    await helper.ft.transferTokenFrom(charlie, collectionId, tokenId, {Substrate: bob.address}, {Substrate: alice.address}, 1n);
-    const after = await helper.ft.getBalance(collectionId, {Substrate: alice.address});
-    expect(after - before).to.be.equal(BigInt(1));
+  describe(`[${testCase.method}] User may clear the approvals to approving for 0 amount:`, () => {
+    let alice: IKeyringPair;
+    let bob: IKeyringPair;
+    let charlie: IKeyringPair;
+
+    before(async () => {
+      await usingPlaygrounds(async (helper, privateKey) => {
+        const donor = await privateKey({filename: __filename});
+        [alice, bob, charlie] = await helper.arrange.createAccounts([100n, 100n, 100n], donor);
+      });
+    });
+
+    itSub('NFT', async ({helper}) => {
+      const {collectionId} = await helper.nft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});
+      const {tokenId} = await helper.nft.mintToken(alice, {collectionId: collectionId, owner: testCase.account(alice)});
+      await (helper.nft as any)[testCase.method](alice, collectionId, tokenId, {Substrate: bob.address});
+      expect(await helper.nft.isTokenApproved(collectionId, tokenId, {Substrate: bob.address})).to.be.true;
+      await (helper.nft as any)[testCase.method](alice, collectionId, tokenId, {Substrate: bob.address}, 0n);
+      expect(await helper.nft.isTokenApproved(collectionId, tokenId, {Substrate: bob.address})).to.be.false;
+      const transferTokenFromTx = () => helper.nft.transferTokenFrom(bob, collectionId, tokenId, {Substrate: bob.address}, {Substrate: bob.address});
+      await expect(transferTokenFromTx()).to.be.rejected;
+    });
+
+    itSub('Fungible', async ({helper}) => {
+      const {collectionId} = await helper.ft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'}, 0);
+      await helper.ft.mintTokens(alice, collectionId, 10n, testCase.account(alice));
+      const tokenId = await helper.ft.getLastTokenId(collectionId);
+      await (helper.ft as any)[testCase.method](alice, collectionId, tokenId, {Substrate: bob.address});
+      const amountBefore = await helper.ft.getTokenApprovedPieces(collectionId, tokenId, {Substrate: bob.address}, testCase.account(alice));
+      expect(amountBefore).to.be.equal(BigInt(1));
+
+      await (helper.ft as any)[testCase.method](alice, collectionId, tokenId, {Substrate: bob.address}, 0n);
+      const amountAfter = await helper.ft.getTokenApprovedPieces(collectionId, tokenId, {Substrate: bob.address}, testCase.account(alice));
+      expect(amountAfter).to.be.equal(BigInt(0));
+
+      const transferTokenFromTx = () => helper.ft.transferTokenFrom(bob, collectionId, tokenId, {Substrate: bob.address}, {Substrate: charlie.address}, 1n);
+      await expect(transferTokenFromTx()).to.be.rejected;
+    });
+
+    itSub.ifWithPallets('ReFungible', [Pallets.ReFungible], async ({helper}) => {
+      const {collectionId} = await helper.rft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});
+      const {tokenId} = await helper.rft.mintToken(alice, {collectionId: collectionId, owner: testCase.account(alice), pieces: 100n});
+      await (helper.rft as any)[testCase.method](alice, collectionId, tokenId, {Substrate: bob.address});
+      const amountBefore = await helper.rft.getTokenApprovedPieces(collectionId, tokenId, {Substrate: bob.address}, testCase.account(alice));
+      expect(amountBefore).to.be.equal(BigInt(1));
+
+      await (helper.rft as any)[testCase.method](alice, collectionId, tokenId, {Substrate: bob.address}, 0n);
+      const amountAfter = await helper.rft.getTokenApprovedPieces(collectionId, tokenId, {Substrate: bob.address}, testCase.account(alice));
+      expect(amountAfter).to.be.equal(BigInt(0));
+
+      const transferTokenFromTx = () => helper.rft.transferTokenFrom(bob, collectionId, tokenId, {Substrate: bob.address}, {Substrate: charlie.address}, 100n);
+      await expect(transferTokenFromTx()).to.be.rejected;
+    });
   });
 
-  itSub.ifWithPallets('ReFungible up to an approved amount', [Pallets.ReFungible], async ({helper}) => {
-    const {collectionId} = await helper.rft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});
-    const {tokenId} = await helper.rft.mintToken(alice, {collectionId: collectionId, owner: bob.address, pieces: 100n});
-    await helper.rft.approveToken(bob, collectionId, tokenId, {Substrate: charlie.address});
-    const before = await helper.rft.getTokenBalance(collectionId, tokenId, {Substrate: alice.address});
-    await helper.rft.transferTokenFrom(charlie, collectionId, tokenId, {Substrate: bob.address}, {Substrate: alice.address}, 1n);
-    const after = await helper.rft.getTokenBalance(collectionId, tokenId, {Substrate: alice.address});
-    expect(after - before).to.be.equal(BigInt(1));
+  describe(`[${testCase.method}] User cannot approve for the amount greater than they own:`, () => {
+    let alice: IKeyringPair;
+    let bob: IKeyringPair;
+    let charlie: IKeyringPair;
+
+    before(async () => {
+      await usingPlaygrounds(async (helper, privateKey) => {
+        const donor = await privateKey({filename: __filename});
+        [alice, bob, charlie] = await helper.arrange.createAccounts([100n, 100n, 100n], donor);
+      });
+    });
+
+    itSub('1 for NFT', async ({helper}) => {
+      const {collectionId} = await helper.nft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});
+      const {tokenId} = await helper.nft.mintToken(alice, {collectionId: collectionId, owner: testCase.account(bob)});
+      const result = (helper.nft as any)[testCase.method](bob, collectionId, tokenId, {Substrate: charlie.address}, 2n);
+      await expect(result).to.be.rejected;
+      expect(await helper.nft.isTokenApproved(collectionId, tokenId, {Substrate: charlie.address})).to.be.false;
+    });
+
+    itSub('Fungible', async ({helper}) => {
+      const {collectionId} = await helper.ft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'}, 0);
+      await helper.ft.mintTokens(alice, collectionId, 10n, testCase.account(alice));
+      const tokenId = await helper.ft.getLastTokenId(collectionId);
+      const result = (helper.ft as any)[testCase.method](alice, collectionId, tokenId, {Substrate: bob.address}, 11n);
+      await expect(result).to.be.rejected;
+    });
+
+    itSub.ifWithPallets('ReFungible', [Pallets.ReFungible], async ({helper}) => {
+      const {collectionId} = await helper.rft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});
+      const {tokenId} = await helper.rft.mintToken(alice, {collectionId: collectionId, owner: testCase.account(alice), pieces: 100n});
+      const result = (helper.rft as any)[testCase.method](alice, collectionId, tokenId, {Substrate: bob.address}, 101n);
+      await expect(result).to.be.rejected;
+    });
   });
-});
 
-describe('Approved users cannot use transferFrom to repeat transfers if approved amount was already transferred:', () => {
-  let alice: IKeyringPair;
-  let bob: IKeyringPair;
-  let charlie: IKeyringPair;
+  describe(`[${testCase.method}] Integration Test approve(spender, collection_id, item_id, amount) with collection admin permissions:`, () => {
+    let alice: IKeyringPair;
+    let bob: IKeyringPair;
+    let charlie: IKeyringPair;
+
+    before(async () => {
+      await usingPlaygrounds(async (helper, privateKey) => {
+        const donor = await privateKey({filename: __filename});
+        [alice, bob, charlie] = await helper.arrange.createAccounts([100n, 100n, 100n], donor);
+      });
+    });
 
-  before(async () => {
-    await usingPlaygrounds(async (helper, privateKey) => {
-      const donor = await privateKey({filename: __filename});
-      [alice, bob, charlie] = await helper.arrange.createAccounts([100n, 100n, 100n], donor);
+    itSub('can be called by collection admin on non-owned item', async ({helper}) => {
+      const {collectionId} = await helper.nft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});
+      const {tokenId} = await helper.nft.mintToken(alice, {collectionId: collectionId, owner: testCase.account(alice)});
+      await helper.collection.addAdmin(alice, collectionId, {Substrate: bob.address});
+      const result = (helper.nft as any)[testCase.method](bob, collectionId, tokenId, {Substrate: charlie.address});
+      await expect(result).to.be.rejected;
     });
   });
 
-  itSub('NFT', async ({helper}) => {
-    const {collectionId} = await helper.nft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});
-    const {tokenId} = await helper.nft.mintToken(alice, {collectionId: collectionId, owner: bob.address});
-    await helper.nft.approveToken(bob, collectionId, tokenId, {Substrate: charlie.address});
-    await helper.nft.transferTokenFrom(charlie, collectionId, tokenId, {Substrate: bob.address}, {Substrate: alice.address});
-    const owner = await helper.nft.getTokenOwner(collectionId, tokenId);
-    expect(owner.Substrate).to.be.equal(alice.address);
-    const transferTokenFromTx = () => helper.nft.transferTokenFrom(charlie, collectionId, tokenId, {Substrate: bob.address}, {Substrate: alice.address});
-    await expect(transferTokenFromTx()).to.be.rejected;
-  });
+  describe(`[${testCase.method}] Negative Integration Test approve(spender, collection_id, item_id, amount):`, () => {
+    let alice: IKeyringPair;
+    let bob: IKeyringPair;
+    let charlie: IKeyringPair;
 
-  itSub('Fungible up to an approved amount', async ({helper}) => {
-    const {collectionId} = await helper.ft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'}, 0);
-    await helper.ft.mintTokens(alice, collectionId, 10n, bob.address);
-    const tokenId = await helper.ft.getLastTokenId(collectionId);
-    await helper.ft.approveToken(bob, collectionId, tokenId, {Substrate: charlie.address});
-    const before = await helper.ft.getBalance(collectionId, {Substrate: alice.address});
-    await helper.ft.transferTokenFrom(charlie, collectionId, tokenId, {Substrate: bob.address}, {Substrate: alice.address}, 1n);
-    const after = await helper.ft.getBalance(collectionId, {Substrate: alice.address});
-    expect(after - before).to.be.equal(BigInt(1));
+    before(async () => {
+      await usingPlaygrounds(async (helper, privateKey) => {
+        const donor = await privateKey({filename: __filename});
+        [alice, bob, charlie] = await helper.arrange.createAccounts([100n, 100n, 100n], donor);
+      });
+    });
 
-    const transferTokenFromTx = () => helper.ft.transferTokenFrom(charlie, collectionId, tokenId, {Substrate: bob.address}, {Substrate: alice.address}, 1n);
-    await expect(transferTokenFromTx()).to.be.rejected;
-  });
+    itSub('[nft] Approve for a collection that does not exist', async ({helper}) => {
+      const collectionId = 1 << 32 - 1;
+      await expect((helper.nft as any)[testCase.method](bob, collectionId, 1, {Substrate: charlie.address})).to.be.rejected;
+    });
+
+    itSub('[fungible] Approve for a collection that does not exist', async ({helper}) => {
+      const collectionId = 1 << 32 - 1;
+      const approveTx = () => (helper.ft as any)[testCase.method](bob, collectionId, 1, {Substrate: charlie.address});
+      await expect(approveTx()).to.be.rejected;
+    });
 
-  itSub.ifWithPallets('ReFungible up to an approved amount', [Pallets.ReFungible], async ({helper}) => {
-    const {collectionId} = await helper.rft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});
-    const {tokenId} = await helper.rft.mintToken(alice, {collectionId: collectionId, owner: bob.address, pieces: 100n});
-    await helper.rft.approveToken(bob, collectionId, tokenId, {Substrate: charlie.address}, 100n);
-    const before = await helper.rft.getTokenBalance(collectionId, tokenId, {Substrate: alice.address});
-    await helper.rft.transferTokenFrom(charlie, collectionId, tokenId, {Substrate: bob.address}, {Substrate: alice.address}, 100n);
-    const after = await helper.rft.getTokenBalance(collectionId, tokenId, {Substrate: alice.address});
-    expect(after - before).to.be.equal(BigInt(100));
-    const transferTokenFromTx = () => helper.rft.transferTokenFrom(charlie, collectionId, tokenId, {Substrate: bob.address}, {Substrate: alice.address}, 100n);
-    await expect(transferTokenFromTx()).to.be.rejected;
-  });
-});
+    itSub.ifWithPallets('[refungible] Approve for a collection that does not exist', [Pallets.ReFungible], async ({helper}) => {
+      const collectionId = 1 << 32 - 1;
+      const approveTx = () => (helper.rft as any)[testCase.method](bob, collectionId, 1, {Substrate: charlie.address});
+      await expect(approveTx()).to.be.rejected;
+    });
 
-describe('Approved amount decreases by the transferred amount:', () => {
-  let alice: IKeyringPair;
-  let bob: IKeyringPair;
-  let charlie: IKeyringPair;
-  let dave: IKeyringPair;
+    itSub('[nft] Approve for a collection that was destroyed', async ({helper}) => {
+      const {collectionId} = await helper.nft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});
+      await helper.nft.burn(alice, collectionId);
+      const approveTx = () => (helper.nft as any)[testCase.method](alice, collectionId, 1, {Substrate: bob.address});
+      await expect(approveTx()).to.be.rejected;
+    });
 
-  before(async () => {
-    await usingPlaygrounds(async (helper, privateKey) => {
-      const donor = await privateKey({filename: __filename});
-      [alice, bob, charlie, dave] = await helper.arrange.createAccounts([100n, 100n, 100n, 100n], donor);
+    itSub('[fungible] Approve for a collection that was destroyed', async ({helper}) => {
+      const {collectionId} = await helper.ft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});
+      await helper.ft.burn(alice, collectionId);
+      const approveTx = () => (helper.ft as any)[testCase.method](alice, collectionId, 1, {Substrate: bob.address});
+      await expect(approveTx()).to.be.rejected;
     });
-  });
 
-  itSub('If a user B is approved to transfer 10 Fungible tokens from user A, they can transfer 2 tokens to user C, which will result in decreasing approval from 10 to 8. Then user B can transfer 8 tokens to user D.', async ({helper}) => {
-    const {collectionId} = await helper.ft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'}, 0);
-    await helper.ft.mintTokens(alice, collectionId, 10n, alice.address);
-    const tokenId = await helper.ft.getLastTokenId(collectionId);
-    await helper.ft.approveToken(alice, collectionId, tokenId, {Substrate: bob.address}, 10n);
+    itSub.ifWithPallets('[refungible] Approve for a collection that was destroyed', [Pallets.ReFungible], async ({helper}) => {
+      const {collectionId} = await helper.rft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});
+      await helper.rft.burn(alice, collectionId);
+      const approveTx = () => (helper.rft as any)[testCase.method](alice, collectionId, 1, {Substrate: bob.address});
+      await expect(approveTx()).to.be.rejected;
+    });
 
-    const charlieBefore = await helper.ft.getBalance(collectionId, {Substrate: charlie.address});
-    await helper.ft.transferTokenFrom(bob, collectionId, tokenId, {Substrate: alice.address}, {Substrate: charlie.address}, 2n);
-    const charlieAfter = await helper.ft.getBalance(collectionId, {Substrate: charlie.address});
-    expect(charlieAfter - charlieBefore).to.be.equal(BigInt(2));
+    itSub('[nft] Approve transfer of a token that does not exist', async ({helper}) => {
+      const {collectionId} = await helper.nft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});
+      const approveTx = () => (helper.nft as any)[testCase.method](alice, collectionId, 2, {Substrate: bob.address});
+      await expect(approveTx()).to.be.rejected;
+    });
 
-    const daveBefore = await helper.ft.getBalance(collectionId, {Substrate: dave.address});
-    await helper.ft.transferTokenFrom(bob, collectionId, tokenId, {Substrate: alice.address}, {Substrate: dave.address}, 8n);
-    const daveAfter = await helper.ft.getBalance(collectionId, {Substrate: dave.address});
-    expect(daveAfter - daveBefore).to.be.equal(BigInt(8));
-  });
-});
+    itSub.ifWithPallets('[refungible] Approve transfer of a token that does not exist', [Pallets.ReFungible], async ({helper}) => {
+      const {collectionId} = await helper.rft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});
+      const approveTx = () => (helper.rft as any)[testCase.method](alice, collectionId, 2, {Substrate: bob.address});
+      await expect(approveTx()).to.be.rejected;
+    });
 
-describe('User may clear the approvals to approving for 0 amount:', () => {
-  let alice: IKeyringPair;
-  let bob: IKeyringPair;
-  let charlie: IKeyringPair;
+    itSub('[nft] Approve using the address that does not own the approved token', async ({helper}) => {
+      const {collectionId} = await helper.nft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});
+      const {tokenId} = await helper.nft.mintToken(alice, {collectionId: collectionId, owner: testCase.account(alice)});
+      const approveTx = () => (helper.nft as any)[testCase.method](bob, collectionId, tokenId, {Substrate: alice.address});
+      await expect(approveTx()).to.be.rejected;
+    });
 
-  before(async () => {
-    await usingPlaygrounds(async (helper, privateKey) => {
-      const donor = await privateKey({filename: __filename});
-      [alice, bob, charlie] = await helper.arrange.createAccounts([100n, 100n, 100n], donor);
+    itSub('[fungible] Approve using the address that does not own the approved token', async ({helper}) => {
+      const {collectionId} = await helper.ft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});
+      await helper.ft.mintTokens(alice, collectionId, 10n, testCase.account(alice));
+      const tokenId = await helper.ft.getLastTokenId(collectionId);
+      const approveTx = () => (helper.ft as any)[testCase.method](bob, collectionId, tokenId, {Substrate: alice.address});
+      await expect(approveTx()).to.be.rejected;
     });
-  });
 
-  itSub('NFT', async ({helper}) => {
-    const {collectionId} = await helper.nft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});
-    const {tokenId} = await helper.nft.mintToken(alice, {collectionId: collectionId, owner: alice.address});
-    await helper.nft.approveToken(alice, collectionId, tokenId, {Substrate: bob.address});
-    expect(await helper.nft.isTokenApproved(collectionId, tokenId, {Substrate: bob.address})).to.be.true;
-    await helper.signTransaction(alice, helper.constructApiCall('api.tx.unique.approve', [{Substrate: bob.address}, collectionId, tokenId, 0]));
-    expect(await helper.nft.isTokenApproved(collectionId, tokenId, {Substrate: bob.address})).to.be.false;
-    const transferTokenFromTx = () => helper.nft.transferTokenFrom(bob, collectionId, tokenId, {Substrate: bob.address}, {Substrate: bob.address});
-    await expect(transferTokenFromTx()).to.be.rejected;
-  });
+    itSub.ifWithPallets('[refungible] Approve using the address that does not own the approved token', [Pallets.ReFungible], async ({helper}) => {
+      const {collectionId} = await helper.rft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});
+      const {tokenId} = await helper.rft.mintToken(alice, {collectionId: collectionId, owner: testCase.account(alice), pieces: 100n});
+      const approveTx = () => (helper.rft as any)[testCase.method](bob, collectionId, tokenId, {Substrate: alice.address});
+      await expect(approveTx()).to.be.rejected;
+    });
 
-  itSub('Fungible', async ({helper}) => {
-    const {collectionId} = await helper.ft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'}, 0);
-    await helper.ft.mintTokens(alice, collectionId, 10n, alice.address);
-    const tokenId = await helper.ft.getLastTokenId(collectionId);
-    await helper.ft.approveToken(alice, collectionId, tokenId, {Substrate: bob.address});
-    const amountBefore = await helper.ft.getTokenApprovedPieces(collectionId, tokenId, {Substrate: bob.address}, {Substrate: alice.address});
-    expect(amountBefore).to.be.equal(BigInt(1));
+    itSub.ifWithPallets('should fail if approved more ReFungibles than owned', [Pallets.ReFungible], async ({helper}) => {
+      const {collectionId} = await helper.rft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});
+      const {tokenId} = await helper.rft.mintToken(alice, {collectionId: collectionId, owner: alice.address, pieces: 100n});
+      await helper.rft.transferToken(alice, collectionId, tokenId, testCase.account(bob), 100n);
+      await (helper.rft as any)[testCase.method](bob, collectionId, tokenId, {Substrate: alice.address}, 100n);
 
-    await helper.ft.approveToken(alice, collectionId, tokenId, {Substrate: bob.address}, 0n);
-    const amountAfter = await helper.ft.getTokenApprovedPieces(collectionId, tokenId, {Substrate: bob.address}, {Substrate: alice.address});
-    expect(amountAfter).to.be.equal(BigInt(0));
+      const approveTx = () => (helper.rft as any)[testCase.method](bob, collectionId, tokenId, {Substrate: alice.address}, 101n);
+      await expect(approveTx()).to.be.rejected;
+    });
 
-    const transferTokenFromTx = () => helper.ft.transferTokenFrom(bob, collectionId, tokenId, {Substrate: bob.address}, {Substrate: charlie.address}, 1n);
-    await expect(transferTokenFromTx()).to.be.rejected;
-  });
+    itSub('should fail if approved more Fungibles than owned', async ({helper}) => {
+      const {collectionId} = await helper.ft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});
+      await helper.ft.mintTokens(alice, collectionId, 10n, alice.address);
+      const tokenId = await helper.ft.getLastTokenId(collectionId);
 
-  itSub.ifWithPallets('ReFungible', [Pallets.ReFungible], async ({helper}) => {
-    const {collectionId} = await helper.rft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});
-    const {tokenId} = await helper.rft.mintToken(alice, {collectionId: collectionId, owner: alice.address, pieces: 100n});
-    await helper.rft.approveToken(alice, collectionId, tokenId, {Substrate: bob.address});
-    const amountBefore = await helper.rft.getTokenApprovedPieces(collectionId, tokenId, {Substrate: bob.address}, {Substrate: alice.address});
-    expect(amountBefore).to.be.equal(BigInt(1));
+      await helper.ft.transferToken(alice, collectionId, tokenId, testCase.account(bob), 10n);
+      await (helper.ft as any)[testCase.method](bob, collectionId, tokenId, {Substrate: alice.address}, 10n);
+      const approveTx = () => (helper.ft as any)[testCase.method](bob, collectionId, tokenId, {Substrate: alice.address}, 11n);
+      await expect(approveTx()).to.be.rejected;
+    });
 
-    await helper.rft.approveToken(alice, collectionId, tokenId, {Substrate: bob.address}, 0n);
-    const amountAfter = await helper.rft.getTokenApprovedPieces(collectionId, tokenId, {Substrate: bob.address}, {Substrate: alice.address});
-    expect(amountAfter).to.be.equal(BigInt(0));
+    itSub('fails when called by collection owner on non-owned item when OwnerCanTransfer == false', async ({helper}) => {
+      const {collectionId} = await helper.nft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});
+      const {tokenId} = await helper.nft.mintToken(alice, {collectionId: collectionId, owner: testCase.account(bob)});
+      await helper.collection.setLimits(alice, collectionId, {ownerCanTransfer: false});
 
-    const transferTokenFromTx = () => helper.rft.transferTokenFrom(bob, collectionId, tokenId, {Substrate: bob.address}, {Substrate: charlie.address}, 100n);
-    await expect(transferTokenFromTx()).to.be.rejected;
+      const approveTx = () => (helper.nft as any)[testCase.method](alice, collectionId, tokenId, {Substrate: charlie.address});
+      await expect(approveTx()).to.be.rejected;
+    });
   });
 });
 
-describe('User cannot approve for the amount greater than they own:', () => {
+describe('Normal user can approve other users to be wallet operator:', () => {
   let alice: IKeyringPair;
   let bob: IKeyringPair;
-  let charlie: IKeyringPair;
 
   before(async () => {
     await usingPlaygrounds(async (helper, privateKey) => {
       const donor = await privateKey({filename: __filename});
-      [alice, bob, charlie] = await helper.arrange.createAccounts([100n, 100n, 100n], donor);
+      [alice, bob] = await helper.arrange.createAccounts([100n, 100n], donor);
     });
   });
 
-  itSub('1 for NFT', async ({helper}) => {
+  itSub('[nft] Enable and disable approval', async ({helper}) => {
     const {collectionId} = await helper.nft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});
-    const {tokenId} = await helper.nft.mintToken(alice, {collectionId: collectionId, owner: bob.address});
-    const approveTx = () => helper.signTransaction(bob, helper.constructApiCall('api.tx.unique.approve', [{Substrate: charlie.address}, collectionId, tokenId, 2]));
-    await expect(approveTx()).to.be.rejected;
-    expect(await helper.nft.isTokenApproved(collectionId, tokenId, {Substrate: charlie.address})).to.be.false;
-  });
 
-  itSub('Fungible', async ({helper}) => {
-    const {collectionId} = await helper.ft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'}, 0);
-    await helper.ft.mintTokens(alice, collectionId, 10n, alice.address);
-    const tokenId = await helper.ft.getLastTokenId(collectionId);
-    const approveTx = () => helper.ft.approveToken(alice, collectionId, tokenId, {Substrate: bob.address}, 11n);
-    await expect(approveTx()).to.be.rejected;
+    const checkBeforeApproval = await helper.nft.allowanceForAll(collectionId, {Substrate: alice.address}, {Substrate: bob.address});
+    expect(checkBeforeApproval).to.be.false;
+
+    await helper.nft.setAllowanceForAll(alice, collectionId, {Substrate: bob.address}, true);
+    const checkAfterApproval = await helper.nft.allowanceForAll(collectionId, {Substrate: alice.address}, {Substrate: bob.address});
+    expect(checkAfterApproval).to.be.true;
+
+    await helper.nft.setAllowanceForAll(alice, collectionId, {Substrate: bob.address}, false);
+    const checkAfterDisapproval = await helper.nft.allowanceForAll(collectionId, {Substrate: alice.address}, {Substrate: bob.address});
+    expect(checkAfterDisapproval).to.be.false;
   });
 
-  itSub.ifWithPallets('ReFungible', [Pallets.ReFungible], async ({helper}) => {
+  itSub.ifWithPallets('[rft] Enable and disable approval', [Pallets.ReFungible], async ({helper}) => {
     const {collectionId} = await helper.rft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});
-    const {tokenId} = await helper.rft.mintToken(alice, {collectionId: collectionId, owner: alice.address, pieces: 100n});
-    const approveTx = () => helper.rft.approveToken(alice, collectionId, tokenId, {Substrate: bob.address}, 101n);
-    await expect(approveTx()).to.be.rejected;
+
+    const checkBeforeApproval = await helper.rft.allowanceForAll(collectionId, {Substrate: alice.address}, {Substrate: bob.address});
+    expect(checkBeforeApproval).to.be.false;
+
+    await helper.rft.setAllowanceForAll(alice, collectionId, {Substrate: bob.address}, true);
+    const checkAfterApproval = await helper.rft.allowanceForAll(collectionId, {Substrate: alice.address}, {Substrate: bob.address});
+    expect(checkAfterApproval).to.be.true;
+
+    await helper.rft.setAllowanceForAll(alice, collectionId, {Substrate: bob.address}, false);
+    const checkAfterDisapproval = await helper.rft.allowanceForAll(collectionId, {Substrate: alice.address}, {Substrate: bob.address});
+    expect(checkAfterDisapproval).to.be.false;
   });
 });
 
@@ -464,184 +649,5 @@
     await token.approve(dave, {Substrate: bob.address}, 50n);
     await expect(token.approve(dave, {Substrate: charlie.address}, 51n))
       .to.be.rejectedWith('this test would fail (since it is skipped), replace this expecting message with what would have been received');
-  });
-});
-
-describe('Integration Test approve(spender, collection_id, item_id, amount) with collection admin permissions:', () => {
-  let alice: IKeyringPair;
-  let bob: IKeyringPair;
-  let charlie: IKeyringPair;
-
-  before(async () => {
-    await usingPlaygrounds(async (helper, privateKey) => {
-      const donor = await privateKey({filename: __filename});
-      [alice, bob, charlie] = await helper.arrange.createAccounts([100n, 100n, 100n], donor);
-    });
-  });
-
-  itSub('can be called by collection admin on non-owned item', async ({helper}) => {
-    const {collectionId} = await helper.nft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});
-    const {tokenId} = await helper.nft.mintToken(alice, {collectionId: collectionId, owner: alice.address});
-    await helper.collection.addAdmin(alice, collectionId, {Substrate: bob.address});
-    const approveTx = () => helper.nft.approveToken(bob, collectionId, tokenId, {Substrate: charlie.address});
-    await expect(approveTx()).to.be.rejected;
-  });
-});
-
-describe('Negative Integration Test approve(spender, collection_id, item_id, amount):', () => {
-  let alice: IKeyringPair;
-  let bob: IKeyringPair;
-  let charlie: IKeyringPair;
-
-  before(async () => {
-    await usingPlaygrounds(async (helper, privateKey) => {
-      const donor = await privateKey({filename: __filename});
-      [alice, bob, charlie] = await helper.arrange.createAccounts([100n, 100n, 100n], donor);
-    });
-  });
-
-  itSub('[nft] Approve for a collection that does not exist', async ({helper}) => {
-    const collectionId = 1 << 32 - 1;
-    const approveTx = () => helper.nft.approveToken(bob, collectionId, 1, {Substrate: charlie.address});
-    await expect(approveTx()).to.be.rejected;
-  });
-
-  itSub('[fungible] Approve for a collection that does not exist', async ({helper}) => {
-    const collectionId = 1 << 32 - 1;
-    const approveTx = () => helper.ft.approveToken(bob, collectionId, 1, {Substrate: charlie.address});
-    await expect(approveTx()).to.be.rejected;
-  });
-
-  itSub.ifWithPallets('[refungible] Approve for a collection that does not exist', [Pallets.ReFungible], async ({helper}) => {
-    const collectionId = 1 << 32 - 1;
-    const approveTx = () => helper.rft.approveToken(bob, collectionId, 1, {Substrate: charlie.address});
-    await expect(approveTx()).to.be.rejected;
-  });
-
-  itSub('[nft] Approve for a collection that was destroyed', async ({helper}) => {
-    const {collectionId} = await helper.nft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});
-    await helper.nft.burn(alice, collectionId);
-    const approveTx = () => helper.nft.approveToken(alice, collectionId, 1, {Substrate: bob.address});
-    await expect(approveTx()).to.be.rejected;
-  });
-
-  itSub('[fungible] Approve for a collection that was destroyed', async ({helper}) => {
-    const {collectionId} = await helper.ft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});
-    await helper.ft.burn(alice, collectionId);
-    const approveTx = () => helper.ft.approveToken(alice, collectionId, 1, {Substrate: bob.address});
-    await expect(approveTx()).to.be.rejected;
-  });
-
-  itSub.ifWithPallets('[refungible] Approve for a collection that was destroyed', [Pallets.ReFungible], async ({helper}) => {
-    const {collectionId} = await helper.rft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});
-    await helper.rft.burn(alice, collectionId);
-    const approveTx = () => helper.rft.approveToken(alice, collectionId, 1, {Substrate: bob.address});
-    await expect(approveTx()).to.be.rejected;
-  });
-
-  itSub('[nft] Approve transfer of a token that does not exist', async ({helper}) => {
-    const {collectionId} = await helper.nft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});
-    const approveTx = () => helper.nft.approveToken(alice, collectionId, 2, {Substrate: bob.address});
-    await expect(approveTx()).to.be.rejected;
-  });
-
-  itSub.ifWithPallets('[refungible] Approve transfer of a token that does not exist', [Pallets.ReFungible], async ({helper}) => {
-    const {collectionId} = await helper.rft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});
-    const approveTx = () => helper.rft.approveToken(alice, collectionId, 2, {Substrate: bob.address});
-    await expect(approveTx()).to.be.rejected;
-  });
-
-  itSub('[nft] Approve using the address that does not own the approved token', async ({helper}) => {
-    const {collectionId} = await helper.nft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});
-    const {tokenId} = await helper.nft.mintToken(alice, {collectionId: collectionId, owner: alice.address});
-    const approveTx = () => helper.nft.approveToken(bob, collectionId, tokenId, {Substrate: alice.address});
-    await expect(approveTx()).to.be.rejected;
-  });
-
-  itSub('[fungible] Approve using the address that does not own the approved token', async ({helper}) => {
-    const {collectionId} = await helper.ft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});
-    await helper.ft.mintTokens(alice, collectionId, 10n, alice.address);
-    const tokenId = await helper.ft.getLastTokenId(collectionId);
-    const approveTx = () => helper.ft.approveToken(bob, collectionId, tokenId, {Substrate: alice.address});
-    await expect(approveTx()).to.be.rejected;
-  });
-
-  itSub.ifWithPallets('[refungible] Approve using the address that does not own the approved token', [Pallets.ReFungible], async ({helper}) => {
-    const {collectionId} = await helper.rft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});
-    const {tokenId} = await helper.rft.mintToken(alice, {collectionId: collectionId, owner: alice.address, pieces: 100n});
-    const approveTx = () => helper.rft.approveToken(bob, collectionId, tokenId, {Substrate: alice.address});
-    await expect(approveTx()).to.be.rejected;
-  });
-
-  itSub.ifWithPallets('should fail if approved more ReFungibles than owned', [Pallets.ReFungible], async ({helper}) => {
-    const {collectionId} = await helper.rft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});
-    const {tokenId} = await helper.rft.mintToken(alice, {collectionId: collectionId, owner: alice.address, pieces: 100n});
-    await helper.rft.transferToken(alice, collectionId, tokenId, {Substrate: bob.address}, 100n);
-    await helper.rft.approveToken(bob, collectionId, tokenId, {Substrate: alice.address}, 100n);
-
-    const approveTx = () => helper.rft.approveToken(bob, collectionId, tokenId, {Substrate: alice.address}, 101n);
-    await expect(approveTx()).to.be.rejected;
-  });
-
-  itSub('should fail if approved more Fungibles than owned', async ({helper}) => {
-    const {collectionId} = await helper.ft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});
-    await helper.ft.mintTokens(alice, collectionId, 10n, alice.address);
-    const tokenId = await helper.ft.getLastTokenId(collectionId);
-
-    await helper.ft.transferToken(alice, collectionId, tokenId, {Substrate: bob.address}, 10n);
-    await helper.ft.approveToken(bob, collectionId, tokenId, {Substrate: alice.address}, 10n);
-    const approveTx = () => helper.ft.approveToken(bob, collectionId, tokenId, {Substrate: alice.address}, 11n);
-    await expect(approveTx()).to.be.rejected;
-  });
-
-  itSub('fails when called by collection owner on non-owned item when OwnerCanTransfer == false', async ({helper}) => {
-    const {collectionId} = await helper.nft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});
-    const {tokenId} = await helper.nft.mintToken(alice, {collectionId: collectionId, owner: bob.address});
-    await helper.collection.setLimits(alice, collectionId, {ownerCanTransfer: false});
-
-    const approveTx = () => helper.nft.approveToken(alice, collectionId, tokenId, {Substrate: charlie.address});
-    await expect(approveTx()).to.be.rejected;
-  });
-});
-
-describe('Normal user can approve other users to be wallet operator:', () => {
-  let alice: IKeyringPair;
-  let bob: IKeyringPair;
-
-  before(async () => {
-    await usingPlaygrounds(async (helper, privateKey) => {
-      const donor = await privateKey({filename: __filename});
-      [alice, bob] = await helper.arrange.createAccounts([100n, 100n], donor);
-    });
-  });
-
-  itSub('[nft] Enable and disable approval', async ({helper}) => {
-    const {collectionId} = await helper.nft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});
-
-    const checkBeforeApproval = await helper.nft.allowanceForAll(collectionId, {Substrate: alice.address}, {Substrate: bob.address});
-    expect(checkBeforeApproval).to.be.false;
-
-    await helper.nft.setAllowanceForAll(alice, collectionId, {Substrate: bob.address}, true);
-    const checkAfterApproval = await helper.nft.allowanceForAll(collectionId, {Substrate: alice.address}, {Substrate: bob.address});
-    expect(checkAfterApproval).to.be.true;
-
-    await helper.nft.setAllowanceForAll(alice, collectionId, {Substrate: bob.address}, false);
-    const checkAfterDisapproval = await helper.nft.allowanceForAll(collectionId, {Substrate: alice.address}, {Substrate: bob.address});
-    expect(checkAfterDisapproval).to.be.false;
-  });
-
-  itSub.ifWithPallets('[rft] Enable and disable approval', [Pallets.ReFungible], async ({helper}) => {
-    const {collectionId} = await helper.rft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});
-
-    const checkBeforeApproval = await helper.rft.allowanceForAll(collectionId, {Substrate: alice.address}, {Substrate: bob.address});
-    expect(checkBeforeApproval).to.be.false;
-
-    await helper.rft.setAllowanceForAll(alice, collectionId, {Substrate: bob.address}, true);
-    const checkAfterApproval = await helper.rft.allowanceForAll(collectionId, {Substrate: alice.address}, {Substrate: bob.address});
-    expect(checkAfterApproval).to.be.true;
-
-    await helper.rft.setAllowanceForAll(alice, collectionId, {Substrate: bob.address}, false);
-    const checkAfterDisapproval = await helper.rft.allowanceForAll(collectionId, {Substrate: alice.address}, {Substrate: bob.address});
-    expect(checkAfterDisapproval).to.be.false;
   });
 });
modifiedtests/src/eth/api/ContractHelpers.soldiffbeforeafterboth
--- a/tests/src/eth/api/ContractHelpers.sol
+++ b/tests/src/eth/api/ContractHelpers.sol
@@ -183,9 +183,9 @@
 
 /// Ethereum representation of Optional value with CrossAddress.
 struct OptionCrossAddress {
-	/// TODO: field description
+	/// Whether or not this CrossAdress is valid and has meaning.
 	bool status;
-	/// TODO: field description
+	/// The underlying CrossAddress value. If the status is false, can be set to whatever.
 	CrossAddress value;
 }
 
modifiedtests/src/interfaces/augment-api-errors.tsdiffbeforeafterboth
--- a/tests/src/interfaces/augment-api-errors.ts
+++ b/tests/src/interfaces/augment-api-errors.ts
@@ -85,6 +85,10 @@
        **/
       AccountTokenLimitExceeded: AugmentedError<ApiType>;
       /**
+       * Only spending from eth mirror could be approved
+       **/
+      AddressIsNotEthMirror: AugmentedError<ApiType>;
+      /**
        * Can't transfer tokens to ethereum zero address
        **/
       AddressIsZero: AugmentedError<ApiType>;
modifiedtests/src/interfaces/augment-api-tx.tsdiffbeforeafterboth
--- a/tests/src/interfaces/augment-api-tx.ts
+++ b/tests/src/interfaces/augment-api-tx.ts
@@ -1214,6 +1214,25 @@
        **/
       approve: AugmentedSubmittable<(spender: PalletEvmAccountBasicCrossAccountIdRepr | { Substrate: any } | { Ethereum: any } | string | Uint8Array, collectionId: u32 | AnyNumber | Uint8Array, itemId: u32 | AnyNumber | Uint8Array, amount: u128 | AnyNumber | Uint8Array) => SubmittableExtrinsic<ApiType>, [PalletEvmAccountBasicCrossAccountIdRepr, u32, u32, u128]>;
       /**
+       * Allow a non-permissioned address to transfer or burn an item from owner's eth mirror.
+       * 
+       * # Permissions
+       * 
+       * * Collection owner
+       * * Collection admin
+       * * Current item owner
+       * 
+       * # Arguments
+       * 
+       * * `from`: Owner's account eth mirror
+       * * `to`: Account to be approved to make specific transactions on non-owned tokens.
+       * * `collection_id`: ID of the collection the item belongs to.
+       * * `item_id`: ID of the item transactions on which are now approved.
+       * * `amount`: Number of pieces of the item approved for a transaction (maximum of 1 for NFTs).
+       * Set to 0 to revoke the approval.
+       **/
+      approveFrom: AugmentedSubmittable<(from: PalletEvmAccountBasicCrossAccountIdRepr | { Substrate: any } | { Ethereum: any } | string | Uint8Array, to: PalletEvmAccountBasicCrossAccountIdRepr | { Substrate: any } | { Ethereum: any } | string | Uint8Array, collectionId: u32 | AnyNumber | Uint8Array, itemId: u32 | AnyNumber | Uint8Array, amount: u128 | AnyNumber | Uint8Array) => SubmittableExtrinsic<ApiType>, [PalletEvmAccountBasicCrossAccountIdRepr, PalletEvmAccountBasicCrossAccountIdRepr, u32, u32, u128]>;
+      /**
        * Destroy a token on behalf of the owner as a non-owner account.
        * 
        * See also: [`approve`][`Pallet::approve`].
modifiedtests/src/interfaces/default/types.tsdiffbeforeafterboth
--- a/tests/src/interfaces/default/types.ts
+++ b/tests/src/interfaces/default/types.ts
@@ -1216,6 +1216,7 @@
   readonly isTokenValueTooLow: boolean;
   readonly isApprovedValueTooLow: boolean;
   readonly isCantApproveMoreThanOwned: boolean;
+  readonly isAddressIsNotEthMirror: boolean;
   readonly isAddressIsZero: boolean;
   readonly isUnsupportedOperation: boolean;
   readonly isNotSufficientFounds: boolean;
@@ -1231,7 +1232,7 @@
   readonly isCollectionIsInternal: boolean;
   readonly isConfirmSponsorshipFail: boolean;
   readonly isUserIsNotCollectionAdmin: boolean;
-  readonly type: 'CollectionNotFound' | 'MustBeTokenOwner' | 'NoPermission' | 'CantDestroyNotEmptyCollection' | 'PublicMintingNotAllowed' | 'AddressNotInAllowlist' | 'CollectionNameLimitExceeded' | 'CollectionDescriptionLimitExceeded' | 'CollectionTokenPrefixLimitExceeded' | 'TotalCollectionsLimitExceeded' | 'CollectionAdminCountExceeded' | 'CollectionLimitBoundsExceeded' | 'OwnerPermissionsCantBeReverted' | 'TransferNotAllowed' | 'AccountTokenLimitExceeded' | 'CollectionTokenLimitExceeded' | 'MetadataFlagFrozen' | 'TokenNotFound' | 'TokenValueTooLow' | 'ApprovedValueTooLow' | 'CantApproveMoreThanOwned' | 'AddressIsZero' | 'UnsupportedOperation' | 'NotSufficientFounds' | 'UserIsNotAllowedToNest' | 'SourceCollectionIsNotAllowedToNest' | 'CollectionFieldSizeExceeded' | 'NoSpaceForProperty' | 'PropertyLimitReached' | 'PropertyKeyIsTooLong' | 'InvalidCharacterInPropertyKey' | 'EmptyPropertyKey' | 'CollectionIsExternal' | 'CollectionIsInternal' | 'ConfirmSponsorshipFail' | 'UserIsNotCollectionAdmin';
+  readonly type: 'CollectionNotFound' | 'MustBeTokenOwner' | 'NoPermission' | 'CantDestroyNotEmptyCollection' | 'PublicMintingNotAllowed' | 'AddressNotInAllowlist' | 'CollectionNameLimitExceeded' | 'CollectionDescriptionLimitExceeded' | 'CollectionTokenPrefixLimitExceeded' | 'TotalCollectionsLimitExceeded' | 'CollectionAdminCountExceeded' | 'CollectionLimitBoundsExceeded' | 'OwnerPermissionsCantBeReverted' | 'TransferNotAllowed' | 'AccountTokenLimitExceeded' | 'CollectionTokenLimitExceeded' | 'MetadataFlagFrozen' | 'TokenNotFound' | 'TokenValueTooLow' | 'ApprovedValueTooLow' | 'CantApproveMoreThanOwned' | 'AddressIsNotEthMirror' | 'AddressIsZero' | 'UnsupportedOperation' | 'NotSufficientFounds' | 'UserIsNotAllowedToNest' | 'SourceCollectionIsNotAllowedToNest' | 'CollectionFieldSizeExceeded' | 'NoSpaceForProperty' | 'PropertyLimitReached' | 'PropertyKeyIsTooLong' | 'InvalidCharacterInPropertyKey' | 'EmptyPropertyKey' | 'CollectionIsExternal' | 'CollectionIsInternal' | 'ConfirmSponsorshipFail' | 'UserIsNotCollectionAdmin';
 }
 
 /** @name PalletCommonEvent */
@@ -2306,6 +2307,14 @@
     readonly itemId: u32;
     readonly amount: u128;
   } & Struct;
+  readonly isApproveFrom: boolean;
+  readonly asApproveFrom: {
+    readonly from: PalletEvmAccountBasicCrossAccountIdRepr;
+    readonly to: PalletEvmAccountBasicCrossAccountIdRepr;
+    readonly collectionId: u32;
+    readonly itemId: u32;
+    readonly amount: u128;
+  } & Struct;
   readonly isTransferFrom: boolean;
   readonly asTransferFrom: {
     readonly from: PalletEvmAccountBasicCrossAccountIdRepr;
@@ -2345,7 +2354,7 @@
     readonly collectionId: u32;
     readonly itemId: u32;
   } & Struct;
-  readonly type: 'CreateCollection' | 'CreateCollectionEx' | 'DestroyCollection' | 'AddToAllowList' | 'RemoveFromAllowList' | 'ChangeCollectionOwner' | 'AddCollectionAdmin' | 'RemoveCollectionAdmin' | 'SetCollectionSponsor' | 'ConfirmSponsorship' | 'RemoveCollectionSponsor' | 'CreateItem' | 'CreateMultipleItems' | 'SetCollectionProperties' | 'DeleteCollectionProperties' | 'SetTokenProperties' | 'DeleteTokenProperties' | 'SetTokenPropertyPermissions' | 'CreateMultipleItemsEx' | 'SetTransfersEnabledFlag' | 'BurnItem' | 'BurnFrom' | 'Transfer' | 'Approve' | 'TransferFrom' | 'SetCollectionLimits' | 'SetCollectionPermissions' | 'Repartition' | 'SetAllowanceForAll' | 'ForceRepairCollection' | 'ForceRepairItem';
+  readonly type: 'CreateCollection' | 'CreateCollectionEx' | 'DestroyCollection' | 'AddToAllowList' | 'RemoveFromAllowList' | 'ChangeCollectionOwner' | 'AddCollectionAdmin' | 'RemoveCollectionAdmin' | 'SetCollectionSponsor' | 'ConfirmSponsorship' | 'RemoveCollectionSponsor' | 'CreateItem' | 'CreateMultipleItems' | 'SetCollectionProperties' | 'DeleteCollectionProperties' | 'SetTokenProperties' | 'DeleteTokenProperties' | 'SetTokenPropertyPermissions' | 'CreateMultipleItemsEx' | 'SetTransfersEnabledFlag' | 'BurnItem' | 'BurnFrom' | 'Transfer' | 'Approve' | 'ApproveFrom' | 'TransferFrom' | 'SetCollectionLimits' | 'SetCollectionPermissions' | 'Repartition' | 'SetAllowanceForAll' | 'ForceRepairCollection' | 'ForceRepairItem';
 }
 
 /** @name PalletUniqueError */
modifiedtests/src/interfaces/lookup.tsdiffbeforeafterboth
--- a/tests/src/interfaces/lookup.ts
+++ b/tests/src/interfaces/lookup.ts
@@ -2264,6 +2264,13 @@
         itemId: 'u32',
         amount: 'u128',
       },
+      approve_from: {
+        from: 'PalletEvmAccountBasicCrossAccountIdRepr',
+        to: 'PalletEvmAccountBasicCrossAccountIdRepr',
+        collectionId: 'u32',
+        itemId: 'u32',
+        amount: 'u128',
+      },
       transfer_from: {
         from: 'PalletEvmAccountBasicCrossAccountIdRepr',
         recipient: 'PalletEvmAccountBasicCrossAccountIdRepr',
@@ -3280,7 +3287,7 @@
    * Lookup423: pallet_common::pallet::Error<T>
    **/
   PalletCommonError: {
-    _enum: ['CollectionNotFound', 'MustBeTokenOwner', 'NoPermission', 'CantDestroyNotEmptyCollection', 'PublicMintingNotAllowed', 'AddressNotInAllowlist', 'CollectionNameLimitExceeded', 'CollectionDescriptionLimitExceeded', 'CollectionTokenPrefixLimitExceeded', 'TotalCollectionsLimitExceeded', 'CollectionAdminCountExceeded', 'CollectionLimitBoundsExceeded', 'OwnerPermissionsCantBeReverted', 'TransferNotAllowed', 'AccountTokenLimitExceeded', 'CollectionTokenLimitExceeded', 'MetadataFlagFrozen', 'TokenNotFound', 'TokenValueTooLow', 'ApprovedValueTooLow', 'CantApproveMoreThanOwned', 'AddressIsZero', 'UnsupportedOperation', 'NotSufficientFounds', 'UserIsNotAllowedToNest', 'SourceCollectionIsNotAllowedToNest', 'CollectionFieldSizeExceeded', 'NoSpaceForProperty', 'PropertyLimitReached', 'PropertyKeyIsTooLong', 'InvalidCharacterInPropertyKey', 'EmptyPropertyKey', 'CollectionIsExternal', 'CollectionIsInternal', 'ConfirmSponsorshipFail', 'UserIsNotCollectionAdmin']
+    _enum: ['CollectionNotFound', 'MustBeTokenOwner', 'NoPermission', 'CantDestroyNotEmptyCollection', 'PublicMintingNotAllowed', 'AddressNotInAllowlist', 'CollectionNameLimitExceeded', 'CollectionDescriptionLimitExceeded', 'CollectionTokenPrefixLimitExceeded', 'TotalCollectionsLimitExceeded', 'CollectionAdminCountExceeded', 'CollectionLimitBoundsExceeded', 'OwnerPermissionsCantBeReverted', 'TransferNotAllowed', 'AccountTokenLimitExceeded', 'CollectionTokenLimitExceeded', 'MetadataFlagFrozen', 'TokenNotFound', 'TokenValueTooLow', 'ApprovedValueTooLow', 'CantApproveMoreThanOwned', 'AddressIsNotEthMirror', 'AddressIsZero', 'UnsupportedOperation', 'NotSufficientFounds', 'UserIsNotAllowedToNest', 'SourceCollectionIsNotAllowedToNest', 'CollectionFieldSizeExceeded', 'NoSpaceForProperty', 'PropertyLimitReached', 'PropertyKeyIsTooLong', 'InvalidCharacterInPropertyKey', 'EmptyPropertyKey', 'CollectionIsExternal', 'CollectionIsInternal', 'ConfirmSponsorshipFail', 'UserIsNotCollectionAdmin']
   },
   /**
    * Lookup425: pallet_fungible::pallet::Error<T>
modifiedtests/src/interfaces/types-lookup.tsdiffbeforeafterboth
--- a/tests/src/interfaces/types-lookup.ts
+++ b/tests/src/interfaces/types-lookup.ts
@@ -2493,6 +2493,14 @@
       readonly itemId: u32;
       readonly amount: u128;
     } & Struct;
+    readonly isApproveFrom: boolean;
+    readonly asApproveFrom: {
+      readonly from: PalletEvmAccountBasicCrossAccountIdRepr;
+      readonly to: PalletEvmAccountBasicCrossAccountIdRepr;
+      readonly collectionId: u32;
+      readonly itemId: u32;
+      readonly amount: u128;
+    } & Struct;
     readonly isTransferFrom: boolean;
     readonly asTransferFrom: {
       readonly from: PalletEvmAccountBasicCrossAccountIdRepr;
@@ -2532,7 +2540,7 @@
       readonly collectionId: u32;
       readonly itemId: u32;
     } & Struct;
-    readonly type: 'CreateCollection' | 'CreateCollectionEx' | 'DestroyCollection' | 'AddToAllowList' | 'RemoveFromAllowList' | 'ChangeCollectionOwner' | 'AddCollectionAdmin' | 'RemoveCollectionAdmin' | 'SetCollectionSponsor' | 'ConfirmSponsorship' | 'RemoveCollectionSponsor' | 'CreateItem' | 'CreateMultipleItems' | 'SetCollectionProperties' | 'DeleteCollectionProperties' | 'SetTokenProperties' | 'DeleteTokenProperties' | 'SetTokenPropertyPermissions' | 'CreateMultipleItemsEx' | 'SetTransfersEnabledFlag' | 'BurnItem' | 'BurnFrom' | 'Transfer' | 'Approve' | 'TransferFrom' | 'SetCollectionLimits' | 'SetCollectionPermissions' | 'Repartition' | 'SetAllowanceForAll' | 'ForceRepairCollection' | 'ForceRepairItem';
+    readonly type: 'CreateCollection' | 'CreateCollectionEx' | 'DestroyCollection' | 'AddToAllowList' | 'RemoveFromAllowList' | 'ChangeCollectionOwner' | 'AddCollectionAdmin' | 'RemoveCollectionAdmin' | 'SetCollectionSponsor' | 'ConfirmSponsorship' | 'RemoveCollectionSponsor' | 'CreateItem' | 'CreateMultipleItems' | 'SetCollectionProperties' | 'DeleteCollectionProperties' | 'SetTokenProperties' | 'DeleteTokenProperties' | 'SetTokenPropertyPermissions' | 'CreateMultipleItemsEx' | 'SetTransfersEnabledFlag' | 'BurnItem' | 'BurnFrom' | 'Transfer' | 'Approve' | 'ApproveFrom' | 'TransferFrom' | 'SetCollectionLimits' | 'SetCollectionPermissions' | 'Repartition' | 'SetAllowanceForAll' | 'ForceRepairCollection' | 'ForceRepairItem';
   }
 
   /** @name UpDataStructsCollectionMode (236) */
@@ -3564,6 +3572,7 @@
     readonly isTokenValueTooLow: boolean;
     readonly isApprovedValueTooLow: boolean;
     readonly isCantApproveMoreThanOwned: boolean;
+    readonly isAddressIsNotEthMirror: boolean;
     readonly isAddressIsZero: boolean;
     readonly isUnsupportedOperation: boolean;
     readonly isNotSufficientFounds: boolean;
@@ -3579,7 +3588,7 @@
     readonly isCollectionIsInternal: boolean;
     readonly isConfirmSponsorshipFail: boolean;
     readonly isUserIsNotCollectionAdmin: boolean;
-    readonly type: 'CollectionNotFound' | 'MustBeTokenOwner' | 'NoPermission' | 'CantDestroyNotEmptyCollection' | 'PublicMintingNotAllowed' | 'AddressNotInAllowlist' | 'CollectionNameLimitExceeded' | 'CollectionDescriptionLimitExceeded' | 'CollectionTokenPrefixLimitExceeded' | 'TotalCollectionsLimitExceeded' | 'CollectionAdminCountExceeded' | 'CollectionLimitBoundsExceeded' | 'OwnerPermissionsCantBeReverted' | 'TransferNotAllowed' | 'AccountTokenLimitExceeded' | 'CollectionTokenLimitExceeded' | 'MetadataFlagFrozen' | 'TokenNotFound' | 'TokenValueTooLow' | 'ApprovedValueTooLow' | 'CantApproveMoreThanOwned' | 'AddressIsZero' | 'UnsupportedOperation' | 'NotSufficientFounds' | 'UserIsNotAllowedToNest' | 'SourceCollectionIsNotAllowedToNest' | 'CollectionFieldSizeExceeded' | 'NoSpaceForProperty' | 'PropertyLimitReached' | 'PropertyKeyIsTooLong' | 'InvalidCharacterInPropertyKey' | 'EmptyPropertyKey' | 'CollectionIsExternal' | 'CollectionIsInternal' | 'ConfirmSponsorshipFail' | 'UserIsNotCollectionAdmin';
+    readonly type: 'CollectionNotFound' | 'MustBeTokenOwner' | 'NoPermission' | 'CantDestroyNotEmptyCollection' | 'PublicMintingNotAllowed' | 'AddressNotInAllowlist' | 'CollectionNameLimitExceeded' | 'CollectionDescriptionLimitExceeded' | 'CollectionTokenPrefixLimitExceeded' | 'TotalCollectionsLimitExceeded' | 'CollectionAdminCountExceeded' | 'CollectionLimitBoundsExceeded' | 'OwnerPermissionsCantBeReverted' | 'TransferNotAllowed' | 'AccountTokenLimitExceeded' | 'CollectionTokenLimitExceeded' | 'MetadataFlagFrozen' | 'TokenNotFound' | 'TokenValueTooLow' | 'ApprovedValueTooLow' | 'CantApproveMoreThanOwned' | 'AddressIsNotEthMirror' | 'AddressIsZero' | 'UnsupportedOperation' | 'NotSufficientFounds' | 'UserIsNotAllowedToNest' | 'SourceCollectionIsNotAllowedToNest' | 'CollectionFieldSizeExceeded' | 'NoSpaceForProperty' | 'PropertyLimitReached' | 'PropertyKeyIsTooLong' | 'InvalidCharacterInPropertyKey' | 'EmptyPropertyKey' | 'CollectionIsExternal' | 'CollectionIsInternal' | 'ConfirmSponsorshipFail' | 'UserIsNotCollectionAdmin';
   }
 
   /** @name PalletFungibleError (425) */
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, base58Encode, blake2AsU8a} from '@polkadot/util-crypto';11import {IKeyringPair} from '@polkadot/types/types';12import {hexToU8a} from '@polkadot/util/hex';13import {u8aConcat} from '@polkadot/util/u8a';14import {15  IApiListeners,16  IBlock,17  IEvent,18  IChainProperties,19  ICollectionCreationOptions,20  ICollectionLimits,21  ICollectionPermissions,22  ICrossAccountId,23  ICrossAccountIdLower,24  ILogger,25  INestingPermissions,26  IProperty,27  IStakingInfo,28  ISchedulerOptions,29  ISubstrateBalance,30  IToken,31  ITokenPropertyPermission,32  ITransactionResult,33  IUniqueHelperLog,34  TApiAllowedListeners,35  TEthereumAccount,36  TSigner,37  TSubstrateAccount,38  TNetworks,39  IForeignAssetMetadata,40  AcalaAssetMetadata,41  MoonbeamAssetInfo,42  DemocracyStandardAccountVote,43  IEthCrossAccountId,44} from './types';45import {RuntimeDispatchInfo} from '@polkadot/types/interfaces';46import type {Vec} from '@polkadot/types-codec';47import {FrameSystemEventRecord} from '@polkadot/types/lookup';4849export class CrossAccountId implements ICrossAccountId {50  Substrate?: TSubstrateAccount;51  Ethereum?: TEthereumAccount;5253  constructor(account: ICrossAccountId) {54    if (account.Substrate) this.Substrate = account.Substrate;55    if (account.Ethereum) this.Ethereum = account.Ethereum;56  }5758  static fromKeyring(account: IKeyringPair, domain: 'Substrate' | 'Ethereum' = 'Substrate') {59    switch (domain) {60      case 'Substrate': return new CrossAccountId({Substrate: account.address});61      case 'Ethereum': return new CrossAccountId({Substrate: account.address}).toEthereum();62    }63  }6465  static fromLowerCaseKeys(address: ICrossAccountIdLower): CrossAccountId {66    return new CrossAccountId({Substrate: address.substrate, Ethereum: address.ethereum});67  }6869  static normalizeSubstrateAddress(address: TSubstrateAccount, ss58Format = 42): TSubstrateAccount {70    return encodeAddress(decodeAddress(address), ss58Format);71  }7273  static withNormalizedSubstrate(address: TSubstrateAccount, ss58Format = 42): CrossAccountId {74    return new CrossAccountId({Substrate: CrossAccountId.normalizeSubstrateAddress(address, ss58Format)});75  }7677  withNormalizedSubstrate(ss58Format = 42): CrossAccountId {78    if (this.Substrate) return CrossAccountId.withNormalizedSubstrate(this.Substrate, ss58Format);79    return this;80  }8182  static translateSubToEth(address: TSubstrateAccount): TEthereumAccount {83    return nesting.toChecksumAddress('0x' + Array.from(addressToEvm(address), i => i.toString(16).padStart(2, '0')).join(''));84  }8586  toEthereum(): CrossAccountId {87    if (this.Substrate) return new CrossAccountId({Ethereum: CrossAccountId.translateSubToEth(this.Substrate)});88    return this;89  }9091  static translateEthToSub(address: TEthereumAccount, ss58Format?: number): TSubstrateAccount {92    return evmToAddress(address, ss58Format);93  }9495  toSubstrate(ss58Format?: number): CrossAccountId {96    if (this.Ethereum) return new CrossAccountId({Substrate: CrossAccountId.translateEthToSub(this.Ethereum, ss58Format)});97    return this;98  }99100  toLowerCase(): CrossAccountId {101    if (this.Substrate) this.Substrate = this.Substrate.toLowerCase();102    if (this.Ethereum) this.Ethereum = this.Ethereum.toLowerCase();103    return this;104  }105}106107const nesting = {108  toChecksumAddress(address: string): string {109    if (typeof address === 'undefined') return '';110111    if(!/^(0x)?[0-9a-f]{40}$/i.test(address)) throw new Error(`Given address "${address}" is not a valid Ethereum address.`);112113    address = address.toLowerCase().replace(/^0x/i,'');114    const addressHash = keccakAsHex(address).replace(/^0x/i,'');115    const checksumAddress = ['0x'];116117    for (let i = 0; i < address.length; i++) {118      // If ith character is 8 to f then make it uppercase119      if (parseInt(addressHash[i], 16) > 7) {120        checksumAddress.push(address[i].toUpperCase());121      } else {122        checksumAddress.push(address[i]);123      }124    }125    return checksumAddress.join('');126  },127  tokenIdToAddress(collectionId: number, tokenId: number) {128    return this.toChecksumAddress(`0xf8238ccfff8ed887463fd5e0${collectionId.toString(16).padStart(8, '0')}${tokenId.toString(16).padStart(8, '0')}`);129  },130};131132class UniqueUtil {133  static transactionStatus = {134    NOT_READY: 'NotReady',135    FAIL: 'Fail',136    SUCCESS: 'Success',137  };138139  static chainLogType = {140    EXTRINSIC: 'extrinsic',141    RPC: 'rpc',142  };143144  static getTokenAccount(token: IToken): CrossAccountId {145    return new CrossAccountId({Ethereum: this.getTokenAddress(token)});146  }147148  static getTokenAddress(token: IToken): string {149    return nesting.tokenIdToAddress(token.collectionId, token.tokenId);150  }151152  static getDefaultLogger(): ILogger {153    return {154      log(msg: any, level = 'INFO') {155        console[level.toLocaleLowerCase() === 'error' ? 'error' : 'log'](...(Array.isArray(msg) ? msg : [msg]));156      },157      level: {158        ERROR: 'ERROR',159        WARNING: 'WARNING',160        INFO: 'INFO',161      },162    };163  }164165  static vec2str(arr: string[] | number[]) {166    return arr.map(x => String.fromCharCode(parseInt(x.toString()))).join('');167  }168169  static str2vec(string: string) {170    if (typeof string !== 'string') return string;171    return Array.from(string).map(x => x.charCodeAt(0));172  }173174  static fromSeed(seed: string, ss58Format = 42) {175    const keyring = new Keyring({type: 'sr25519', ss58Format});176    return keyring.addFromUri(seed);177  }178179  static extractCollectionIdFromCreationResult(creationResult: ITransactionResult): number {180    if (creationResult.status !== this.transactionStatus.SUCCESS) {181      throw Error('Unable to create collection!');182    }183184    let collectionId = null;185    creationResult.result.events.forEach(({event: {data, method, section}}) => {186      if ((section === 'common') && (method === 'CollectionCreated')) {187        collectionId = parseInt(data[0].toString(), 10);188      }189    });190191    if (collectionId === null) {192      throw Error('No CollectionCreated event was found!');193    }194195    return collectionId;196  }197198  static extractTokensFromCreationResult(creationResult: ITransactionResult): {199    success: boolean,200    tokens: {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[],201  } {202    if (creationResult.status !== this.transactionStatus.SUCCESS) {203      throw Error('Unable to create tokens!');204    }205    let success = false;206    const tokens = [] as {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[];207    creationResult.result.events.forEach(({event: {data, method, section}}) => {208      if (method === 'ExtrinsicSuccess') {209        success = true;210      } else if ((section === 'common') && (method === 'ItemCreated')) {211        tokens.push({212          collectionId: parseInt(data[0].toString(), 10),213          tokenId: parseInt(data[1].toString(), 10),214          owner: data[2].toHuman(),215          amount: data[3].toBigInt(),216        });217      }218    });219    return {success, tokens};220  }221222  static extractTokensFromBurnResult(burnResult: ITransactionResult): {223    success: boolean,224    tokens: {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[],225  } {226    if (burnResult.status !== this.transactionStatus.SUCCESS) {227      throw Error('Unable to burn tokens!');228    }229    let success = false;230    const tokens = [] as {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[];231    burnResult.result.events.forEach(({event: {data, method, section}}) => {232      if (method === 'ExtrinsicSuccess') {233        success = true;234      } else if ((section === 'common') && (method === 'ItemDestroyed')) {235        tokens.push({236          collectionId: parseInt(data[0].toString(), 10),237          tokenId: parseInt(data[1].toString(), 10),238          owner: data[2].toHuman(),239          amount: data[3].toBigInt(),240        });241      }242    });243    return {success, tokens};244  }245246  static findCollectionInEvents(events: {event: IEvent}[], collectionId: number, expectedSection: string, expectedMethod: string): boolean {247    let eventId = null;248    events.forEach(({event: {data, method, section}}) => {249      if ((section === expectedSection) && (method === expectedMethod)) {250        eventId = parseInt(data[0].toString(), 10);251      }252    });253254    if (eventId === null) {255      throw Error(`No ${expectedMethod} event was found!`);256    }257    return eventId === collectionId;258  }259260  static isTokenTransferSuccess(events: {event: IEvent}[], collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {261    const normalizeAddress = (address: string | ICrossAccountId) => {262      if(typeof address === 'string') return address;263      const obj = {} as any;264      Object.keys(address).forEach(k => {265        obj[k.toLocaleLowerCase()] = address[k as 'Substrate' | 'Ethereum'];266      });267      if(obj.substrate) return CrossAccountId.withNormalizedSubstrate(obj.substrate);268      if(obj.ethereum) return CrossAccountId.fromLowerCaseKeys(obj).toLowerCase();269      return address;270    };271    let transfer = {collectionId: null, tokenId: null, from: null, to: null, amount: 1} as any;272    events.forEach(({event: {data, method, section}}) => {273      if ((section === 'common') && (method === 'Transfer')) {274        const hData = (data as any).toJSON();275        transfer = {276          collectionId: hData[0],277          tokenId: hData[1],278          from: normalizeAddress(hData[2]),279          to: normalizeAddress(hData[3]),280          amount: BigInt(hData[4]),281        };282      }283    });284    let isSuccess = parseInt(collectionId.toString()) === transfer.collectionId && parseInt(tokenId.toString()) === transfer.tokenId;285    isSuccess = isSuccess && JSON.stringify(normalizeAddress(fromAddressObj)) === JSON.stringify(transfer.from);286    isSuccess = isSuccess && JSON.stringify(normalizeAddress(toAddressObj)) === JSON.stringify(transfer.to);287    isSuccess = isSuccess && amount === transfer.amount;288    return isSuccess;289  }290291  static bigIntToDecimals(number: bigint, decimals = 18) {292    const numberStr = number.toString();293    const dotPos = numberStr.length - decimals;294295    if (dotPos <= 0) {296      return '0.' + '0'.repeat(Math.abs(dotPos)) + numberStr;297    } else {298      const intPart = numberStr.substring(0, dotPos);299      const fractPart = numberStr.substring(dotPos);300      return intPart + '.' + fractPart;301    }302  }303}304305class UniqueEventHelper {306  private static extractIndex(index: any): [number, number] | string {307    if(index.toRawType() === '[u8;2]') return [index[0], index[1]];308    return index.toJSON();309  }310311  private static extractSub(data: any, subTypes: any): {[key: string]: any} {312    let obj: any = {};313    let index = 0;314315    if (data.entries) {316      for(const [key, value] of data.entries()) {317        obj[key] = this.extractData(value, subTypes[index]);318        index++;319      }320    } else obj = data.toJSON();321322    return obj;323  }324325  private static toHuman(data: any) {326    return data && data.toHuman ? data.toHuman() : `${data}`;327  }328329  private static extractData(data: any, type: any): any {330    if(!type) return this.toHuman(data);331    if (['u16', 'u32'].indexOf(type.type) > -1) return data.toNumber();332    if (['u64', 'u128', 'u256'].indexOf(type.type) > -1) return data.toBigInt();333    if(type.hasOwnProperty('sub')) return this.extractSub(data, type.sub);334    return this.toHuman(data);335  }336337  public static extractEvents(events: {event: any, phase: any}[]): IEvent[] {338    const parsedEvents: IEvent[] = [];339340    events.forEach((record) => {341      const {event, phase} = record;342      const types = event.typeDef;343344      const eventData: IEvent = {345        section: event.section.toString(),346        method: event.method.toString(),347        index: this.extractIndex(event.index),348        data: [],349        phase: phase.toJSON(),350      };351352      event.data.forEach((val: any, index: number) => {353        eventData.data.push(this.extractData(val, types[index]));354      });355356      parsedEvents.push(eventData);357    });358359    return parsedEvents;360  }361}362363export class ChainHelperBase {364  helperBase: any;365366  transactionStatus = UniqueUtil.transactionStatus;367  chainLogType = UniqueUtil.chainLogType;368  util: typeof UniqueUtil;369  eventHelper: typeof UniqueEventHelper;370  logger: ILogger;371  api: ApiPromise | null;372  forcedNetwork: TNetworks | null;373  network: TNetworks | null;374  wsEndpoint: string | null;375  chainLog: IUniqueHelperLog[];376  children: ChainHelperBase[];377  address: AddressGroup;378  chain: ChainGroup;379380  constructor(logger?: ILogger, helperBase?: any) {381    this.helperBase = helperBase;382383    this.util = UniqueUtil;384    this.eventHelper = UniqueEventHelper;385    if (typeof logger == 'undefined') logger = this.util.getDefaultLogger();386    this.logger = logger;387    this.api = null;388    this.forcedNetwork = null;389    this.network = null;390    this.wsEndpoint = null;391    this.chainLog = [];392    this.children = [];393    this.address = new AddressGroup(this);394    this.chain = new ChainGroup(this);395  }396397  clone(helperCls: ChainHelperBaseConstructor, options: {[key: string]: any} = {}) {398    Object.setPrototypeOf(helperCls.prototype, this);399    const newHelper = new helperCls(this.logger, options);400401    newHelper.api = this.api;402    newHelper.network = this.network;403    newHelper.forceNetwork = this.forceNetwork;404405    this.children.push(newHelper);406407    return newHelper;408  }409410  getEndpoint(): string {411    if (this.wsEndpoint === null) throw Error('No connection was established');412    return this.wsEndpoint;413  }414415  getApi(): ApiPromise {416    if(this.api === null) throw Error('API not initialized');417    return this.api;418  }419420  async subscribeEvents(expectedEvents: {section: string, names: string[]}[]) {421    const collectedEvents: IEvent[] = [];422    const unsubscribe = await this.getApi().query.system.events((events: Vec<FrameSystemEventRecord>) => {423      const ievents = this.eventHelper.extractEvents(events);424      ievents.forEach((event) => {425        expectedEvents.forEach((e => {426          if (event.section === e.section && e.names.includes(event.method)) {427            collectedEvents.push(event);428          }429        }));430      });431    });432    return {unsubscribe: unsubscribe as any, collectedEvents};433  }434435  clearChainLog(): void {436    this.chainLog = [];437  }438439  forceNetwork(value: TNetworks): void {440    this.forcedNetwork = value;441  }442443  async connect(wsEndpoint: string, listeners?: IApiListeners) {444    if (this.api !== null) throw Error('Already connected');445    const {api, network} = await ChainHelperBase.createConnection(wsEndpoint, listeners, this.forcedNetwork);446    this.wsEndpoint = wsEndpoint;447    this.api = api;448    this.network = network;449  }450451  async disconnect() {452    for (const child of this.children) {453      child.clearApi();454    }455456    if (this.api === null) return;457    await this.api.disconnect();458    this.clearApi();459  }460461  clearApi() {462    this.api = null;463    this.network = null;464  }465466  static async detectNetwork(api: ApiPromise): Promise<TNetworks> {467    const spec = (await api.query.system.lastRuntimeUpgrade()).toJSON() as any;468    const xcmChains = ['rococo', 'westend', 'westmint', 'acala', 'karura', 'moonbeam', 'moonriver'];469470    if(xcmChains.indexOf(spec.specName) > -1) return spec.specName;471472    if(['quartz', 'unique'].indexOf(spec.specName) > -1) return spec.specName;473    return 'opal';474  }475476  static async detectNetworkByWsEndpoint(wsEndpoint: string): Promise<TNetworks> {477    const api = new ApiPromise({provider: new WsProvider(wsEndpoint)});478    await api.isReady;479480    const network = await this.detectNetwork(api);481482    await api.disconnect();483484    return network;485  }486487  static async createConnection(wsEndpoint: string, listeners?: IApiListeners, network?: TNetworks | null): Promise<{488    api: ApiPromise;489    network: TNetworks;490  }> {491    if(typeof network === 'undefined' || network === null) network = 'opal';492    const supportedRPC = {493      opal: {494        unique: require('@unique-nft/opal-testnet-types/definitions').unique.rpc,495      },496      quartz: {497        unique: require('@unique-nft/quartz-mainnet-types/definitions').unique.rpc,498      },499      unique: {500        unique: require('@unique-nft/unique-mainnet-types/definitions').unique.rpc,501      },502      rococo: {},503      westend: {},504      moonbeam: {},505      moonriver: {},506      acala: {},507      karura: {},508      westmint: {},509    };510    if(!supportedRPC.hasOwnProperty(network)) network = await this.detectNetworkByWsEndpoint(wsEndpoint);511    const rpc = supportedRPC[network];512513    // TODO: investigate how to replace rpc in runtime514    // api._rpcCore.addUserInterfaces(rpc);515516    const api = new ApiPromise({provider: new WsProvider(wsEndpoint), rpc});517518    await api.isReadyOrError;519520    if (typeof listeners === 'undefined') listeners = {};521    for (const event of ['connected', 'disconnected', 'error', 'ready', 'decorated']) {522      if (!listeners.hasOwnProperty(event) || typeof listeners[event as TApiAllowedListeners] === 'undefined') continue;523      api.on(event as ApiInterfaceEvents, listeners[event as TApiAllowedListeners] as (...args: any[]) => any);524    }525526    return {api, network};527  }528529  getTransactionStatus(data: {events: {event: IEvent}[], status: any}) {530    const {events, status} = data;531    if (status.isReady) {532      return this.transactionStatus.NOT_READY;533    }534    if (status.isBroadcast) {535      return this.transactionStatus.NOT_READY;536    }537    if (status.isInBlock || status.isFinalized) {538      const errors = events.filter(e => e.event.method === 'ExtrinsicFailed');539      if (errors.length > 0) {540        return this.transactionStatus.FAIL;541      }542      if (events.filter(e => e.event.method === 'ExtrinsicSuccess').length > 0) {543        return this.transactionStatus.SUCCESS;544      }545    }546547    return this.transactionStatus.FAIL;548  }549550  signTransaction(sender: TSigner, transaction: any, options: Partial<SignerOptions> | null = null, label = 'transaction') {551    const sign = (callback: any) => {552      if(options !== null) return transaction.signAndSend(sender, options, callback);553      return transaction.signAndSend(sender, callback);554    };555    // eslint-disable-next-line no-async-promise-executor556    return new Promise(async (resolve, reject) => {557      try {558        const unsub = await sign((result: any) => {559          const status = this.getTransactionStatus(result);560561          if (status === this.transactionStatus.SUCCESS) {562            this.logger.log(`${label} successful`);563            unsub();564            resolve({result, status});565          } else if (status === this.transactionStatus.FAIL) {566            let moduleError = null;567568            if (result.hasOwnProperty('dispatchError')) {569              const dispatchError = result['dispatchError'];570571              if (dispatchError) {572                if (dispatchError.isModule) {573                  const modErr = dispatchError.asModule;574                  const errorMeta = dispatchError.registry.findMetaError(modErr);575576                  moduleError = `${errorMeta.section}.${errorMeta.name}`;577                } else {578                  moduleError = dispatchError.toHuman();579                }580              } else {581                this.logger.log(result, this.logger.level.ERROR);582              }583            }584585            this.logger.log(`Something went wrong with ${label}. Status: ${status}`, this.logger.level.ERROR);586            unsub();587            reject({status, moduleError, result});588          }589        });590      } catch (e) {591        this.logger.log(e, this.logger.level.ERROR);592        reject(e);593      }594    });595  }596597  async signTransactionWithoutSending(signer: TSigner, tx: any) {598    const api = this.getApi();599    const signingInfo = await api.derive.tx.signingInfo(signer.address);600601    tx.sign(signer, {602      blockHash: api.genesisHash,603      genesisHash: api.genesisHash,604      runtimeVersion: api.runtimeVersion,605      nonce: signingInfo.nonce,606    });607608    return tx.toHex();609  }610611  async getPaymentInfo(signer: TSigner, tx: any, len: number | null) {612    const api = this.getApi();613    const signingInfo = await api.derive.tx.signingInfo(signer.address);614615    // We need to sign the tx because616    // unsigned transactions does not have an inclusion fee617    tx.sign(signer, {618      blockHash: api.genesisHash,619      genesisHash: api.genesisHash,620      runtimeVersion: api.runtimeVersion,621      nonce: signingInfo.nonce,622    });623624    if (len === null) {625      return (await this.callRpc('api.rpc.payment.queryInfo', [tx.toHex()])) as RuntimeDispatchInfo;626    } else {627      return (await api.call.transactionPaymentApi.queryInfo(tx, len)) as RuntimeDispatchInfo;628    }629  }630631  constructApiCall(apiCall: string, params: any[]) {632    if(!apiCall.startsWith('api.')) throw Error(`Invalid api call: ${apiCall}`);633    let call = this.getApi() as any;634    for(const part of apiCall.slice(4).split('.')) {635      call = call[part];636    }637    return call(...params);638  }639640  async executeExtrinsic(sender: TSigner, extrinsic: string, params: any[], expectSuccess=true, options: Partial<SignerOptions>|null = null/*, failureMessage='expected success'*/) {641    if(this.api === null) throw Error('API not initialized');642    if(!extrinsic.startsWith('api.tx.')) throw Error(`${extrinsic} is not transaction`);643644    const startTime = (new Date()).getTime();645    let result: ITransactionResult;646    let events: IEvent[] = [];647    try {648      result = await this.signTransaction(sender, this.constructApiCall(extrinsic, params), options, extrinsic) as ITransactionResult;649      events = this.eventHelper.extractEvents(result.result.events);650    }651    catch(e) {652      if(!(e as object).hasOwnProperty('status')) throw e;653      result = e as ITransactionResult;654    }655656    const endTime = (new Date()).getTime();657658    const log = {659      executedAt: endTime,660      executionTime: endTime - startTime,661      type: this.chainLogType.EXTRINSIC,662      status: result.status,663      call: extrinsic,664      signer: this.getSignerAddress(sender),665      params,666    } as IUniqueHelperLog;667668    if(result.status !== this.transactionStatus.SUCCESS) {669      if (result.moduleError) log.moduleError = result.moduleError;670      else if (result.result.dispatchError) log.dispatchError = result.result.dispatchError;671    }672    if(events.length > 0) log.events = events;673674    this.chainLog.push(log);675676    if(expectSuccess && result.status !== this.transactionStatus.SUCCESS) {677      if (result.moduleError) throw Error(`${result.moduleError}`);678      else if (result.result.dispatchError) throw Error(JSON.stringify(result.result.dispatchError));679    }680    return result;681  }682683  async callRpc(rpc: string, params?: any[]) {684    if(typeof params === 'undefined') params = [];685    if(this.api === null) throw Error('API not initialized');686    if(!rpc.startsWith('api.rpc.') && !rpc.startsWith('api.query.')) throw Error(`${rpc} is not RPC call`);687688    const startTime = (new Date()).getTime();689    let result;690    let error = null;691    const log = {692      type: this.chainLogType.RPC,693      call: rpc,694      params,695    } as IUniqueHelperLog;696697    try {698      result = await this.constructApiCall(rpc, params);699    }700    catch(e) {701      error = e;702    }703704    const endTime = (new Date()).getTime();705706    log.executedAt = endTime;707    log.status = (error === null ? this.transactionStatus.SUCCESS : this.transactionStatus.FAIL) as 'Fail' | 'Success';708    log.executionTime = endTime - startTime;709710    this.chainLog.push(log);711712    if(error !== null) throw error;713714    return result;715  }716717  getSignerAddress(signer: IKeyringPair | string): string {718    if(typeof signer === 'string') return signer;719    return signer.address;720  }721722  fetchAllPalletNames(): string[] {723    if(this.api === null) throw Error('API not initialized');724    return this.api.runtimeMetadata.asLatest.pallets.map(m => m.name.toString().toLowerCase());725  }726727  fetchMissingPalletNames(requiredPallets: string[]): string[] {728    const palletNames = this.fetchAllPalletNames();729    return requiredPallets.filter(p => !palletNames.includes(p));730  }731}732733734class HelperGroup<T extends ChainHelperBase> {735  helper: T;736737  constructor(uniqueHelper: T) {738    this.helper = uniqueHelper;739  }740}741742743class CollectionGroup extends HelperGroup<UniqueHelper> {744  /**745 * Get number of blocks when sponsored transaction is available.746 *747 * @param collectionId ID of collection748 * @param tokenId ID of token749 * @param addressObj address for which the sponsorship is checked750 * @example await getTokenNextSponsored(1, 2, {Substrate: '5DfhbVfww7ThF8q6f3...'});751 * @returns number of blocks or null if sponsorship hasn't been set752 */753  async getTokenNextSponsored(collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<number | null> {754    return (await this.helper.callRpc('api.rpc.unique.nextSponsored', [collectionId, addressObj, tokenId])).toJSON();755  }756757  /**758   * Get the number of created collections.759   *760   * @returns number of created collections761   */762  async getTotalCount(): Promise<number> {763    return (await this.helper.callRpc('api.rpc.unique.collectionStats')).created.toNumber();764  }765766  /**767   * Get information about the collection with additional data,768   * including the number of tokens it contains, its administrators,769   * the normalized address of the collection's owner, and decoded name and description.770   *771   * @param collectionId ID of collection772   * @example await getData(2)773   * @returns collection information object774   */775  async getData(collectionId: number): Promise<{776    id: number;777    name: string;778    description: string;779    tokensCount: number;780    admins: CrossAccountId[];781    normalizedOwner: TSubstrateAccount;782    raw: any783  } | null> {784    const collection = await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId]);785    const humanCollection = collection.toHuman(), collectionData = {786      id: collectionId, name: null, description: null, tokensCount: 0, admins: [],787      raw: humanCollection,788    } as any, jsonCollection = collection.toJSON();789    if (humanCollection === null) return null;790    collectionData.raw.limits = jsonCollection.limits;791    collectionData.raw.permissions = jsonCollection.permissions;792    collectionData.normalizedOwner = this.helper.address.normalizeSubstrate(collectionData.raw.owner);793    for (const key of ['name', 'description']) {794      collectionData[key] = this.helper.util.vec2str(humanCollection[key]);795    }796797    collectionData.tokensCount = (['RFT', 'NFT'].includes(humanCollection.mode))798      ? await this.helper[humanCollection.mode.toLocaleLowerCase() as 'nft' | 'rft'].getLastTokenId(collectionId)799      : 0;800    collectionData.admins = await this.getAdmins(collectionId);801802    return collectionData;803  }804805  /**806   * Get the addresses of the collection's administrators, optionally normalized.807   *808   * @param collectionId ID of collection809   * @param normalize whether to normalize the addresses to the default ss58 format810   * @example await getAdmins(1)811   * @returns array of administrators812   */813  async getAdmins(collectionId: number, normalize = false): Promise<CrossAccountId[]> {814    const admins = (await this.helper.callRpc('api.rpc.unique.adminlist', [collectionId])).toHuman();815816    return normalize817      ? admins.map((address: CrossAccountId) => address.withNormalizedSubstrate())818      : admins;819  }820821  /**822   * Get the addresses added to the collection allow-list, optionally normalized.823   * @param collectionId ID of collection824   * @param normalize whether to normalize the addresses to the default ss58 format825   * @example await getAllowList(1)826   * @returns array of allow-listed addresses827   */828  async getAllowList(collectionId: number, normalize = false): Promise<CrossAccountId[]> {829    const allowListed = (await this.helper.callRpc('api.rpc.unique.allowlist', [collectionId])).toHuman();830    return normalize831      ? allowListed.map((address: CrossAccountId) => address.withNormalizedSubstrate())832      : allowListed;833  }834835  /**836   * Get the effective limits of the collection instead of null for default values837   *838   * @param collectionId ID of collection839   * @example await getEffectiveLimits(2)840   * @returns object of collection limits841   */842  async getEffectiveLimits(collectionId: number): Promise<ICollectionLimits> {843    return (await this.helper.callRpc('api.rpc.unique.effectiveCollectionLimits', [collectionId])).toJSON();844  }845846  /**847   * Burns the collection if the signer has sufficient permissions and collection is empty.848   *849   * @param signer keyring of signer850   * @param collectionId ID of collection851   * @example await helper.collection.burn(aliceKeyring, 3);852   * @returns ```true``` if extrinsic success, otherwise ```false```853   */854  async burn(signer: TSigner, collectionId: number): Promise<boolean> {855    const result = await this.helper.executeExtrinsic(856      signer,857      'api.tx.unique.destroyCollection', [collectionId],858      true,859    );860861    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionDestroyed');862  }863864  /**865   * Sets the sponsor for the collection (Requires the Substrate address). Needs confirmation by the sponsor.866   *867   * @param signer keyring of signer868   * @param collectionId ID of collection869   * @param sponsorAddress Sponsor substrate address870   * @example setSponsor(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...")871   * @returns ```true``` if extrinsic success, otherwise ```false```872   */873  async setSponsor(signer: TSigner, collectionId: number, sponsorAddress: TSubstrateAccount): Promise<boolean> {874    const result = await this.helper.executeExtrinsic(875      signer,876      'api.tx.unique.setCollectionSponsor', [collectionId, sponsorAddress],877      true,878    );879880    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionSponsorSet');881  }882883  /**884   * Confirms consent to sponsor the collection on behalf of the signer.885   *886   * @param signer keyring of signer887   * @param collectionId ID of collection888   * @example confirmSponsorship(aliceKeyring, 10)889   * @returns ```true``` if extrinsic success, otherwise ```false```890   */891  async confirmSponsorship(signer: TSigner, collectionId: number): Promise<boolean> {892    const result = await this.helper.executeExtrinsic(893      signer,894      'api.tx.unique.confirmSponsorship', [collectionId],895      true,896    );897898    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'SponsorshipConfirmed');899  }900901  /**902   * Removes the sponsor of a collection, regardless if it consented or not.903   *904   * @param signer keyring of signer905   * @param collectionId ID of collection906   * @example removeSponsor(aliceKeyring, 10)907   * @returns ```true``` if extrinsic success, otherwise ```false```908   */909  async removeSponsor(signer: TSigner, collectionId: number): Promise<boolean> {910    const result = await this.helper.executeExtrinsic(911      signer,912      'api.tx.unique.removeCollectionSponsor', [collectionId],913      true,914    );915916    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionSponsorRemoved');917  }918919  /**920   * Sets the limits of the collection. At least one limit must be specified for a correct call.921   *922   * @param signer keyring of signer923   * @param collectionId ID of collection924   * @param limits collection limits object925   * @example926   * await setLimits(927   *   aliceKeyring,928   *   10,929   *   {930   *     sponsorTransferTimeout: 0,931   *     ownerCanDestroy: false932   *   }933   * )934   * @returns ```true``` if extrinsic success, otherwise ```false```935   */936  async setLimits(signer: TSigner, collectionId: number, limits: ICollectionLimits): Promise<boolean> {937    const result = await this.helper.executeExtrinsic(938      signer,939      'api.tx.unique.setCollectionLimits', [collectionId, limits],940      true,941    );942943    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionLimitSet');944  }945946  /**947   * Changes the owner of the collection to the new Substrate address.948   *949   * @param signer keyring of signer950   * @param collectionId ID of collection951   * @param ownerAddress substrate address of new owner952   * @example changeOwner(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...")953   * @returns ```true``` if extrinsic success, otherwise ```false```954   */955  async changeOwner(signer: TSigner, collectionId: number, ownerAddress: TSubstrateAccount): Promise<boolean> {956    const result = await this.helper.executeExtrinsic(957      signer,958      'api.tx.unique.changeCollectionOwner', [collectionId, ownerAddress],959      true,960    );961962    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionOwnerChanged');963  }964965  /**966   * Adds a collection administrator.967   *968   * @param signer keyring of signer969   * @param collectionId ID of collection970   * @param adminAddressObj Administrator address (substrate or ethereum)971   * @example addAdmin(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."})972   * @returns ```true``` if extrinsic success, otherwise ```false```973   */974  async addAdmin(signer: TSigner, collectionId: number, adminAddressObj: ICrossAccountId): Promise<boolean> {975    const result = await this.helper.executeExtrinsic(976      signer,977      'api.tx.unique.addCollectionAdmin', [collectionId, adminAddressObj],978      true,979    );980981    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionAdminAdded');982  }983984  /**985   * Removes a collection administrator.986   *987   * @param signer keyring of signer988   * @param collectionId ID of collection989   * @param adminAddressObj Administrator address (substrate or ethereum)990   * @example removeAdmin(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."})991   * @returns ```true``` if extrinsic success, otherwise ```false```992   */993  async removeAdmin(signer: TSigner, collectionId: number, adminAddressObj: ICrossAccountId): Promise<boolean> {994    const result = await this.helper.executeExtrinsic(995      signer,996      'api.tx.unique.removeCollectionAdmin', [collectionId, adminAddressObj],997      true,998    );9991000    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionAdminRemoved');1001  }10021003  /**1004   * Check if user is in allow list.1005   *1006   * @param collectionId ID of collection1007   * @param user Account to check1008   * @example await getAdmins(1)1009   * @returns is user in allow list1010   */1011  async allowed(collectionId: number, user: ICrossAccountId): Promise<boolean> {1012    return (await this.helper.callRpc('api.rpc.unique.allowed', [collectionId, user])).toJSON();1013  }10141015  /**1016   * Adds an address to allow list1017   * @param signer keyring of signer1018   * @param collectionId ID of collection1019   * @param addressObj address to add to the allow list1020   * @returns ```true``` if extrinsic success, otherwise ```false```1021   */1022  async addToAllowList(signer: TSigner, collectionId: number, addressObj: ICrossAccountId): Promise<boolean> {1023    const result = await this.helper.executeExtrinsic(1024      signer,1025      'api.tx.unique.addToAllowList', [collectionId, addressObj],1026      true,1027    );10281029    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'AllowListAddressAdded');1030  }10311032  /**1033   * Removes an address from allow list1034   *1035   * @param signer keyring of signer1036   * @param collectionId ID of collection1037   * @param addressObj address to remove from the allow list1038   * @returns ```true``` if extrinsic success, otherwise ```false```1039   */1040  async removeFromAllowList(signer: TSigner, collectionId: number, addressObj: ICrossAccountId): Promise<boolean> {1041    const result = await this.helper.executeExtrinsic(1042      signer,1043      'api.tx.unique.removeFromAllowList', [collectionId, addressObj],1044      true,1045    );10461047    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'AllowListAddressRemoved');1048  }10491050  /**1051   * Sets onchain permissions for selected collection.1052   *1053   * @param signer keyring of signer1054   * @param collectionId ID of collection1055   * @param permissions collection permissions object1056   * @example setPermissions(aliceKeyring, 10, {access:'AllowList', mintMode: true, nesting: {collectionAdmin: true, tokenOwner: true}});1057   * @returns ```true``` if extrinsic success, otherwise ```false```1058   */1059  async setPermissions(signer: TSigner, collectionId: number, permissions: ICollectionPermissions): Promise<boolean> {1060    const result = await this.helper.executeExtrinsic(1061      signer,1062      'api.tx.unique.setCollectionPermissions', [collectionId, permissions],1063      true,1064    );10651066    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPermissionSet');1067  }10681069  /**1070   * Enables nesting for selected collection. If `restricted` set, you can nest only tokens from specified collections.1071   *1072   * @param signer keyring of signer1073   * @param collectionId ID of collection1074   * @param permissions nesting permissions object1075   * @example enableNesting(aliceKeyring, 10, {collectionAdmin: true, tokenOwner: true});1076   * @returns ```true``` if extrinsic success, otherwise ```false```1077   */1078  async enableNesting(signer: TSigner, collectionId: number, permissions: INestingPermissions): Promise<boolean> {1079    return await this.setPermissions(signer, collectionId, {nesting: permissions});1080  }10811082  /**1083   * Disables nesting for selected collection.1084   *1085   * @param signer keyring of signer1086   * @param collectionId ID of collection1087   * @example disableNesting(aliceKeyring, 10);1088   * @returns ```true``` if extrinsic success, otherwise ```false```1089   */1090  async disableNesting(signer: TSigner, collectionId: number): Promise<boolean> {1091    return await this.setPermissions(signer, collectionId, {nesting: {tokenOwner: false, collectionAdmin: false}});1092  }10931094  /**1095   * Sets onchain properties to the collection.1096   *1097   * @param signer keyring of signer1098   * @param collectionId ID of collection1099   * @param properties array of property objects1100   * @example setProperties(aliceKeyring, 10, [{key: "gender", value: "male"}]);1101   * @returns ```true``` if extrinsic success, otherwise ```false```1102   */1103  async setProperties(signer: TSigner, collectionId: number, properties: IProperty[]): Promise<boolean> {1104    const result = await this.helper.executeExtrinsic(1105      signer,1106      'api.tx.unique.setCollectionProperties', [collectionId, properties],1107      true,1108    );11091110    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPropertySet');1111  }11121113  /**1114   * Get collection properties.1115   *1116   * @param collectionId ID of collection1117   * @param propertyKeys optionally filter the returned properties to only these keys1118   * @example getProperties(1219, ['location', 'date', 'time', 'isParadise']);1119   * @returns array of key-value pairs1120   */1121  async getProperties(collectionId: number, propertyKeys?: string[] | null): Promise<IProperty[]> {1122    return (await this.helper.callRpc('api.rpc.unique.collectionProperties', [collectionId, propertyKeys])).toHuman();1123  }11241125  async getPropertiesConsumedSpace(collectionId: number): Promise<number> {1126    const api = this.helper.getApi();1127    const props = (await api.query.common.collectionProperties(collectionId)).toJSON();11281129    return (props! as any).consumedSpace;1130  }11311132  async getCollectionOptions(collectionId: number) {1133    return (await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId])).toHuman();1134  }11351136  /**1137   * Deletes onchain properties from the collection.1138   *1139   * @param signer keyring of signer1140   * @param collectionId ID of collection1141   * @param propertyKeys array of property keys to delete1142   * @example deleteProperties(aliceKeyring, 10, ["gender", "age"]);1143   * @returns ```true``` if extrinsic success, otherwise ```false```1144   */1145  async deleteProperties(signer: TSigner, collectionId: number, propertyKeys: string[]): Promise<boolean> {1146    const result = await this.helper.executeExtrinsic(1147      signer,1148      'api.tx.unique.deleteCollectionProperties', [collectionId, propertyKeys],1149      true,1150    );11511152    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPropertyDeleted');1153  }11541155  /**1156   * Changes the owner of the token.1157   *1158   * @param signer keyring of signer1159   * @param collectionId ID of collection1160   * @param tokenId ID of token1161   * @param addressObj address of a new owner1162   * @param amount amount of tokens to be transfered. For NFT must be set to 1n1163   * @example transferToken(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."})1164   * @returns true if the token success, otherwise false1165   */1166  async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId, amount=1n): Promise<boolean> {1167    const result = await this.helper.executeExtrinsic(1168      signer,1169      'api.tx.unique.transfer', [addressObj, collectionId, tokenId, amount],1170      true, // `Unable to transfer token #${tokenId} from collection #${collectionId}`,1171    );11721173    return this.helper.util.isTokenTransferSuccess(result.result.events, collectionId, tokenId, {Substrate: typeof signer === 'string' ? signer : signer.address}, addressObj, amount);1174  }11751176  /**1177   *1178   * Change ownership of a token(s) on behalf of the owner.1179   *1180   * @param signer keyring of signer1181   * @param collectionId ID of collection1182   * @param tokenId ID of token1183   * @param fromAddressObj address on behalf of which the token will be sent1184   * @param toAddressObj new token owner1185   * @param amount amount of tokens to be transfered. For NFT must be set to 1n1186   * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg"}, {Ethereum: "0x9F0583DbB85..."})1187   * @returns true if the token success, otherwise false1188   */1189  async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1190    const result = await this.helper.executeExtrinsic(1191      signer,1192      'api.tx.unique.transferFrom', [fromAddressObj, toAddressObj, collectionId, tokenId, amount],1193      true, // `Unable to transfer token #${tokenId} from collection #${collectionId}`,1194    );1195    return this.helper.util.isTokenTransferSuccess(result.result.events, collectionId, tokenId, fromAddressObj, toAddressObj, amount);1196  }11971198  /**1199   *1200   * Destroys a concrete instance of NFT/RFT or burns a specified amount of fungible tokens.1201   *1202   * @param signer keyring of signer1203   * @param collectionId ID of collection1204   * @param tokenId ID of token1205   * @param amount amount of tokens to be burned. For NFT must be set to 1n1206   * @example burnToken(aliceKeyring, 10, 5);1207   * @returns ```true``` if the extrinsic is successful, otherwise ```false```1208   */1209  async burnToken(signer: TSigner, collectionId: number, tokenId: number, amount=1n): Promise<boolean> {1210    const burnResult = await this.helper.executeExtrinsic(1211      signer,1212      'api.tx.unique.burnItem', [collectionId, tokenId, amount],1213      true, // `Unable to burn token for ${label}`,1214    );1215    const burnedTokens = this.helper.util.extractTokensFromBurnResult(burnResult);1216    if (burnedTokens.tokens.length > 1) throw Error('Burned multiple tokens');1217    return burnedTokens.success;1218  }12191220  /**1221   * Destroys a concrete instance of NFT on behalf of the owner1222   *1223   * @param signer keyring of signer1224   * @param collectionId ID of collection1225   * @param tokenId ID of token1226   * @param fromAddressObj address on behalf of which the token will be burnt1227   * @param amount amount of tokens to be burned. For NFT must be set to 1n1228   * @example burnTokenFrom(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."}, 5, {Ethereum: "0x9F0583DbB85..."})1229   * @returns ```true``` if extrinsic success, otherwise ```false```1230   */1231  async burnTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1232    const burnResult = await this.helper.executeExtrinsic(1233      signer,1234      'api.tx.unique.burnFrom', [collectionId, fromAddressObj, tokenId, amount],1235      true, // `Unable to burn token from for ${label}`,1236    );1237    const burnedTokens = this.helper.util.extractTokensFromBurnResult(burnResult);1238    return burnedTokens.success && burnedTokens.tokens.length > 0;1239  }12401241  /**1242   * Set, change, or remove approved address to transfer the ownership of the NFT.1243   *1244   * @param signer keyring of signer1245   * @param collectionId ID of collection1246   * @param tokenId ID of token1247   * @param toAddressObj Substrate or Ethereum address which gets approved use of the signer's tokens1248   * @param amount amount of token to be approved. For NFT must be set to 1n1249   * @returns ```true``` if extrinsic success, otherwise ```false```1250   */1251  async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {1252    const approveResult = await this.helper.executeExtrinsic(1253      signer,1254      'api.tx.unique.approve', [toAddressObj, collectionId, tokenId, amount],1255      true, // `Unable to approve token for ${label}`,1256    );12571258    return this.helper.util.findCollectionInEvents(approveResult.result.events, collectionId, 'common', 'Approved');1259  }12601261  /**1262   * Get the amount of token pieces approved to transfer or burn. Normally 0.1263   *1264   * @param collectionId ID of collection1265   * @param tokenId ID of token1266   * @param toAccountObj address which is approved to use token pieces1267   * @param fromAccountObj address which may have allowed the use of its owned tokens1268   * @example getTokenApprovedPieces(10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, {Substrate: "5ERZNF88Mm7UGfPP3mdG..."})1269   * @returns number of approved to transfer pieces1270   */1271  async getTokenApprovedPieces(collectionId: number, tokenId: number, toAccountObj: ICrossAccountId, fromAccountObj: ICrossAccountId): Promise<bigint> {1272    return (await this.helper.callRpc('api.rpc.unique.allowance', [collectionId, fromAccountObj, toAccountObj, tokenId])).toBigInt();1273  }12741275  /**1276   * Get the last created token ID in a collection1277   *1278   * @param collectionId ID of collection1279   * @example getLastTokenId(10);1280   * @returns id of the last created token1281   */1282  async getLastTokenId(collectionId: number): Promise<number> {1283    return (await this.helper.callRpc('api.rpc.unique.lastTokenId', [collectionId])).toNumber();1284  }12851286  /**1287   * Check if token exists1288   *1289   * @param collectionId ID of collection1290   * @param tokenId ID of token1291   * @example doesTokenExist(10, 20);1292   * @returns true if the token exists, otherwise false1293   */1294  async doesTokenExist(collectionId: number, tokenId: number): Promise<boolean> {1295    return (await this.helper.callRpc('api.rpc.unique.tokenExists', [collectionId, tokenId])).toJSON();1296  }1297}12981299class NFTnRFT extends CollectionGroup {1300  /**1301   * Get tokens owned by account1302   *1303   * @param collectionId ID of collection1304   * @param addressObj tokens owner1305   * @example getTokensByAddress(10, {Substrate: "5DyN4Y92vZCjv38fg..."})1306   * @returns array of token ids owned by account1307   */1308  async getTokensByAddress(collectionId: number, addressObj: ICrossAccountId): Promise<number[]> {1309    return (await this.helper.callRpc('api.rpc.unique.accountTokens', [collectionId, addressObj])).toJSON();1310  }13111312  /**1313   * Get token data1314   *1315   * @param collectionId ID of collection1316   * @param tokenId ID of token1317   * @param propertyKeys optionally filter the token properties to only these keys1318   * @param blockHashAt optionally query the data at some block with this hash1319   * @example getToken(10, 5);1320   * @returns human readable token data1321   */1322  async getToken(collectionId: number, tokenId: number, propertyKeys: string[] = [], blockHashAt?: string): Promise<{1323    properties: IProperty[];1324    owner: CrossAccountId;1325    normalizedOwner: CrossAccountId;1326  }| null> {1327    let tokenData;1328    if(typeof blockHashAt === 'undefined') {1329      tokenData = await this.helper.callRpc('api.rpc.unique.tokenData', [collectionId, tokenId]);1330    }1331    else {1332      if(propertyKeys.length == 0) {1333        const collection = (await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId])).toHuman();1334        if(!collection) return null;1335        propertyKeys = collection.tokenPropertyPermissions.map((x: ITokenPropertyPermission) => x.key);1336      }1337      tokenData = await this.helper.callRpc('api.rpc.unique.tokenData', [collectionId, tokenId, propertyKeys, blockHashAt]);1338    }1339    tokenData = tokenData.toHuman();1340    if (tokenData === null || tokenData.owner === null) return null;1341    const owner = {} as any;1342    for (const key of Object.keys(tokenData.owner)) {1343      owner[key.toLocaleLowerCase()] = key.toLocaleLowerCase() == 'substrate'1344        ? CrossAccountId.normalizeSubstrateAddress(tokenData.owner[key])1345        : tokenData.owner[key];1346    }1347    tokenData.normalizedOwner = CrossAccountId.fromLowerCaseKeys(owner);1348    return tokenData;1349  }13501351  /**1352   * Set permissions to change token properties1353   *1354   * @param signer keyring of signer1355   * @param collectionId ID of collection1356   * @param permissions permissions to change a property by the collection admin or token owner1357   * @example setTokenPropertyPermissions(1358   *   aliceKeyring, 10, [{key: "gender", permission: {tokenOwner: true, mutable: true, collectionAdmin: true}}]1359   * )1360   * @returns true if extrinsic success otherwise false1361   */1362  async setTokenPropertyPermissions(signer: TSigner, collectionId: number, permissions: ITokenPropertyPermission[]): Promise<boolean> {1363    const result = await this.helper.executeExtrinsic(1364      signer,1365      'api.tx.unique.setTokenPropertyPermissions', [collectionId, permissions],1366      true,1367    );13681369    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'PropertyPermissionSet');1370  }13711372  /**1373   * Get token property permissions.1374   *1375   * @param collectionId ID of collection1376   * @param propertyKeys optionally filter the returned property permissions to only these keys1377   * @example getPropertyPermissions(1219, ['location', 'date', 'time', 'isParadise']);1378   * @returns array of key-permission pairs1379   */1380  async getPropertyPermissions(collectionId: number, propertyKeys: string[] | null = null): Promise<ITokenPropertyPermission[]> {1381    return (await this.helper.callRpc('api.rpc.unique.propertyPermissions', [collectionId, ...(propertyKeys === null ? [] : [propertyKeys])])).toHuman();1382  }13831384  /**1385   * Set token properties1386   *1387   * @param signer keyring of signer1388   * @param collectionId ID of collection1389   * @param tokenId ID of token1390   * @param properties key-value pairs of metadata which to add to a token. Keys must be permitted in the collection1391   * @example setTokenProperties(aliceKeyring, 10, 5, [{key: "gender", value: "female"}, {key: "age", value: "23"}])1392   * @returns ```true``` if extrinsic success, otherwise ```false```1393   */1394  async setTokenProperties(signer: TSigner, collectionId: number, tokenId: number, properties: IProperty[]): Promise<boolean> {1395    const result = await this.helper.executeExtrinsic(1396      signer,1397      'api.tx.unique.setTokenProperties', [collectionId, tokenId, properties],1398      true,1399    );14001401    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'TokenPropertySet');1402  }14031404  /**1405   * Get properties, metadata assigned to a token.1406   *1407   * @param collectionId ID of collection1408   * @param tokenId ID of token1409   * @param propertyKeys optionally filter the returned properties to only these keys1410   * @example getTokenProperties(1219, ['location', 'date', 'time', 'isParadise']);1411   * @returns array of key-value pairs1412   */1413  async getTokenProperties(collectionId: number, tokenId: number, propertyKeys?: string[] | null): Promise<IProperty[]> {1414    return (await this.helper.callRpc('api.rpc.unique.tokenProperties', [collectionId, tokenId, propertyKeys])).toHuman();1415  }14161417  /**1418   * Delete the provided properties of a token1419   * @param signer keyring of signer1420   * @param collectionId ID of collection1421   * @param tokenId ID of token1422   * @param propertyKeys property keys to be deleted1423   * @example deleteTokenProperties(aliceKeyring, 10, 5, ["gender", "age"])1424   * @returns ```true``` if extrinsic success, otherwise ```false```1425   */1426  async deleteTokenProperties(signer: TSigner, collectionId: number, tokenId: number, propertyKeys: string[]): Promise<boolean> {1427    const result = await this.helper.executeExtrinsic(1428      signer,1429      'api.tx.unique.deleteTokenProperties', [collectionId, tokenId, propertyKeys],1430      true,1431    );14321433    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'TokenPropertyDeleted');1434  }14351436  /**1437   * Mint new collection1438   *1439   * @param signer keyring of signer1440   * @param collectionOptions basic collection options and properties1441   * @param mode NFT or RFT type of a collection1442   * @example mintCollection(aliceKeyring, {name: 'New', description: "New collection", tokenPrefix: "NEW"}, "NFT")1443   * @returns object of the created collection1444   */1445  async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions, mode: 'NFT' | 'RFT'): Promise<UniqueBaseCollection> {1446    collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; // Clone object1447    collectionOptions.mode = (mode === 'NFT') ? {nft: null} : {refungible: null};1448    for (const key of ['name', 'description', 'tokenPrefix']) {1449      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);1450    }1451    const creationResult = await this.helper.executeExtrinsic(1452      signer,1453      'api.tx.unique.createCollectionEx', [collectionOptions],1454      true, // errorLabel,1455    );1456    return this.getCollectionObject(this.helper.util.extractCollectionIdFromCreationResult(creationResult));1457  }14581459  getCollectionObject(_collectionId: number): any {1460    return null;1461  }14621463  getTokenObject(_collectionId: number, _tokenId: number): any {1464    return null;1465  }14661467  /**1468   * Tells whether the given `owner` approves the `operator`.1469   * @param collectionId ID of collection1470   * @param owner owner address1471   * @param operator operator addrees1472   * @returns true if operator is enabled1473   */1474  async allowanceForAll(collectionId: number, owner: ICrossAccountId, operator: ICrossAccountId): Promise<boolean> {1475    return (await this.helper.callRpc('api.rpc.unique.allowanceForAll', [collectionId, owner, operator])).toJSON();1476  }14771478  /** Sets or unsets the approval of a given operator.1479   *  The `operator` is allowed to transfer all tokens of the `caller` on their behalf.1480   *  @param operator Operator1481   *  @param approved Should operator status be granted or revoked?1482   *  @returns ```true``` if extrinsic success, otherwise ```false```1483   */1484  async setAllowanceForAll(signer: TSigner, collectionId: number, operator: ICrossAccountId, approved: boolean): Promise<boolean> {1485    const result = await this.helper.executeExtrinsic(1486      signer,1487      'api.tx.unique.setAllowanceForAll', [collectionId, operator, approved],1488      true,1489    );1490    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'ApprovedForAll');1491  }1492}149314941495class NFTGroup extends NFTnRFT {1496  /**1497   * Get collection object1498   * @param collectionId ID of collection1499   * @example getCollectionObject(2);1500   * @returns instance of UniqueNFTCollection1501   */1502  getCollectionObject(collectionId: number): UniqueNFTCollection {1503    return new UniqueNFTCollection(collectionId, this.helper);1504  }15051506  /**1507   * Get token object1508   * @param collectionId ID of collection1509   * @param tokenId ID of token1510   * @example getTokenObject(10, 5);1511   * @returns instance of UniqueNFTToken1512   */1513  getTokenObject(collectionId: number, tokenId: number): UniqueNFToken {1514    return new UniqueNFToken(tokenId, this.getCollectionObject(collectionId));1515  }15161517  /**1518   * Get token's owner1519   * @param collectionId ID of collection1520   * @param tokenId ID of token1521   * @param blockHashAt optionally query the data at the block with this hash1522   * @example getTokenOwner(10, 5);1523   * @returns Address in CrossAccountId format, e.g. {Substrate: "5DnSF6RRjwteE3BrCj..."}1524   */1525  async getTokenOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<CrossAccountId> {1526    let owner;1527    if (typeof blockHashAt === 'undefined') {1528      owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId]);1529    } else {1530      owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId, blockHashAt]);1531    }1532    return CrossAccountId.fromLowerCaseKeys(owner.toJSON());1533  }15341535  /**1536   * Is token approved to transfer1537   * @param collectionId ID of collection1538   * @param tokenId ID of token1539   * @param toAccountObj address to be approved1540   * @returns ```true``` if extrinsic success, otherwise ```false```1541   */1542  async isTokenApproved(collectionId: number, tokenId: number, toAccountObj: ICrossAccountId): Promise<boolean> {1543    return (await this.getTokenApprovedPieces(collectionId, tokenId, toAccountObj, await this.getTokenOwner(collectionId, tokenId))) === 1n;1544  }15451546  /**1547   * Changes the owner of the token.1548   *1549   * @param signer keyring of signer1550   * @param collectionId ID of collection1551   * @param tokenId ID of token1552   * @param addressObj address of a new owner1553   * @example transferToken(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."})1554   * @returns ```true``` if extrinsic success, otherwise ```false```1555   */1556  async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<boolean> {1557    return await super.transferToken(signer, collectionId, tokenId, addressObj, 1n);1558  }15591560  /**1561   *1562   * Change ownership of a NFT on behalf of the owner.1563   *1564   * @param signer keyring of signer1565   * @param collectionId ID of collection1566   * @param tokenId ID of token1567   * @param fromAddressObj address on behalf of which the token will be sent1568   * @param toAddressObj new token owner1569   * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, {Ethereum: "0x9F0583DbB85..."})1570   * @returns ```true``` if extrinsic success, otherwise ```false```1571   */1572  async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId): Promise<boolean> {1573    return await super.transferTokenFrom(signer, collectionId, tokenId, fromAddressObj, toAddressObj, 1n);1574  }15751576  /**1577   * Recursively find the address that owns the token1578   * @param collectionId ID of collection1579   * @param tokenId ID of token1580   * @param blockHashAt1581   * @example getTokenTopmostOwner(10, 5);1582   * @returns address in CrossAccountId format, e.g. {Substrate: "5DyN4Y92vZCjv38fg..."}1583   */1584  async getTokenTopmostOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<CrossAccountId | null> {1585    let owner;1586    if (typeof blockHashAt === 'undefined') {1587      owner = await this.helper.callRpc('api.rpc.unique.topmostTokenOwner', [collectionId, tokenId]);1588    } else {1589      owner = await this.helper.callRpc('api.rpc.unique.topmostTokenOwner', [collectionId, tokenId, blockHashAt]);1590    }15911592    if (owner === null) return null;15931594    return owner.toHuman();1595  }15961597  /**1598   * Get tokens nested in the provided token1599   * @param collectionId ID of collection1600   * @param tokenId ID of token1601   * @param blockHashAt optionally query the data at the block with this hash1602   * @example getTokenChildren(10, 5);1603   * @returns tokens whose depth of nesting is <= 51604   */1605  async getTokenChildren(collectionId: number, tokenId: number, blockHashAt?: string): Promise<IToken[]> {1606    let children;1607    if(typeof blockHashAt === 'undefined') {1608      children = await this.helper.callRpc('api.rpc.unique.tokenChildren', [collectionId, tokenId]);1609    } else {1610      children = await this.helper.callRpc('api.rpc.unique.tokenChildren', [collectionId, tokenId, blockHashAt]);1611    }16121613    return children.toJSON().map((x: any) => {1614      return {collectionId: x.collection, tokenId: x.token};1615    });1616  }16171618  /**1619   * Nest one token into another1620   * @param signer keyring of signer1621   * @param tokenObj token to be nested1622   * @param rootTokenObj token to be parent1623   * @example nestToken(aliceKeyring, {collectionId: 10, tokenId: 5}, {collectionId: 10, tokenId: 4});1624   * @returns ```true``` if extrinsic success, otherwise ```false```1625   */1626  async nestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken): Promise<boolean> {1627    const rootTokenAddress = this.helper.util.getTokenAccount(rootTokenObj);1628    const result = await this.transferToken(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress);1629    if(!result) {1630      throw Error('Unable to nest token!');1631    }1632    return result;1633  }16341635  /**1636   * Remove token from nested state1637   * @param signer keyring of signer1638   * @param tokenObj token to unnest1639   * @param rootTokenObj parent of a token1640   * @param toAddressObj address of a new token owner1641   * @example unnestToken(aliceKeyring, {collectionId: 10, tokenId: 5}, {collectionId: 10, tokenId: 4}, {Substrate: "5DyN4Y92vZCjv38fg..."});1642   * @returns ```true``` if extrinsic success, otherwise ```false```1643   */1644  async unnestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken, toAddressObj: ICrossAccountId): Promise<boolean> {1645    const rootTokenAddress = this.helper.util.getTokenAccount(rootTokenObj);1646    const result = await this.transferTokenFrom(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress, toAddressObj);1647    if(!result) {1648      throw Error('Unable to unnest token!');1649    }1650    return result;1651  }16521653  /**1654   * Mint new collection1655   * @param signer keyring of signer1656   * @param collectionOptions Collection options1657   * @example1658   * mintCollection(aliceKeyring, {1659   *   name: 'New',1660   *   description: 'New collection',1661   *   tokenPrefix: 'NEW',1662   * })1663   * @returns object of the created collection1664   */1665  async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}): Promise<UniqueNFTCollection> {1666    return await super.mintCollection(signer, collectionOptions, 'NFT') as UniqueNFTCollection;1667  }16681669  /**1670   * Mint new token1671   * @param signer keyring of signer1672   * @param data token data1673   * @returns created token object1674   */1675  async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; properties?: IProperty[]; }): Promise<UniqueNFToken> {1676    const creationResult = await this.helper.executeExtrinsic(1677      signer,1678      'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {1679        nft: {1680          properties: data.properties,1681        },1682      }],1683      true,1684    );1685    const createdTokens = this.helper.util.extractTokensFromCreationResult(creationResult);1686    if (createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');1687    if (createdTokens.tokens.length < 1) throw Error('No tokens minted');1688    return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);1689  }16901691  /**1692   * Mint multiple NFT tokens1693   * @param signer keyring of signer1694   * @param collectionId ID of collection1695   * @param tokens array of tokens with owner and properties1696   * @example1697   * mintMultipleTokens(aliceKeyring, 10, [{1698   *     owner: {Substrate: "5DyN4Y92vZCjv38fg..."},1699   *     properties: [{key: "gender", value: "male"},{key: "age", value: "45"}],1700   *   },{1701   *     owner: {Ethereum: "0x9F0583DbB855d..."},1702   *     properties: [{key: "gender", value: "female"},{key: "age", value: "22"}],1703   * }]);1704   * @returns ```true``` if extrinsic success, otherwise ```false```1705   */1706  async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: {owner: ICrossAccountId, properties?: IProperty[]}[]): Promise<UniqueNFToken[]> {1707    const creationResult = await this.helper.executeExtrinsic(1708      signer,1709      'api.tx.unique.createMultipleItemsEx', [collectionId, {NFT: tokens}],1710      true,1711    );1712    const collection = this.getCollectionObject(collectionId);1713    return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1714  }17151716  /**1717   * Mint multiple NFT tokens with one owner1718   * @param signer keyring of signer1719   * @param collectionId ID of collection1720   * @param owner tokens owner1721   * @param tokens array of tokens with owner and properties1722   * @example1723   * mintMultipleTokensWithOneOwner(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...", [{1724   *   properties: [{1725   *   key: "gender",1726   *   value: "female",1727   *  },{1728   *   key: "age",1729   *   value: "33",1730   *  }],1731   * }]);1732   * @returns array of newly created tokens1733   */1734  async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {properties?: IProperty[]}[]): Promise<UniqueNFToken[]> {1735    const rawTokens = [];1736    for (const token of tokens) {1737      const raw = {NFT: {properties: token.properties}};1738      rawTokens.push(raw);1739    }1740    const creationResult = await this.helper.executeExtrinsic(1741      signer,1742      'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1743      true,1744    );1745    const collection = this.getCollectionObject(collectionId);1746    return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1747  }17481749  /**1750   * Set, change, or remove approved address to transfer the ownership of the NFT.1751   *1752   * @param signer keyring of signer1753   * @param collectionId ID of collection1754   * @param tokenId ID of token1755   * @param toAddressObj address to approve1756   * @example approveToken(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."})1757   * @returns ```true``` if extrinsic success, otherwise ```false```1758   */1759  approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId) {1760    return super.approveToken(signer, collectionId, tokenId, toAddressObj, 1n);1761  }1762}176317641765class RFTGroup extends NFTnRFT {1766  /**1767   * Get collection object1768   * @param collectionId ID of collection1769   * @example getCollectionObject(2);1770   * @returns instance of UniqueRFTCollection1771   */1772  getCollectionObject(collectionId: number): UniqueRFTCollection {1773    return new UniqueRFTCollection(collectionId, this.helper);1774  }17751776  /**1777   * Get token object1778   * @param collectionId ID of collection1779   * @param tokenId ID of token1780   * @example getTokenObject(10, 5);1781   * @returns instance of UniqueNFTToken1782   */1783  getTokenObject(collectionId: number, tokenId: number): UniqueRFToken {1784    return new UniqueRFToken(tokenId, this.getCollectionObject(collectionId));1785  }17861787  /**1788   * Get top 10 token owners with the largest number of pieces1789   * @param collectionId ID of collection1790   * @param tokenId ID of token1791   * @example getTokenTop10Owners(10, 5);1792   * @returns array of top 10 owners1793   */1794  async getTokenTop10Owners(collectionId: number, tokenId: number): Promise<CrossAccountId[]> {1795    return (await this.helper.callRpc('api.rpc.unique.tokenOwners', [collectionId, tokenId])).toJSON().map(CrossAccountId.fromLowerCaseKeys);1796  }17971798  /**1799   * Get number of pieces owned by address1800   * @param collectionId ID of collection1801   * @param tokenId ID of token1802   * @param addressObj address token owner1803   * @example getTokenBalance(10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."});1804   * @returns number of pieces ownerd by address1805   */1806  async getTokenBalance(collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<bigint> {1807    return (await this.helper.callRpc('api.rpc.unique.balance', [collectionId, addressObj, tokenId])).toBigInt();1808  }18091810  /**1811   * Transfer pieces of token to another address1812   * @param signer keyring of signer1813   * @param collectionId ID of collection1814   * @param tokenId ID of token1815   * @param addressObj address of a new owner1816   * @param amount number of pieces to be transfered1817   * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, 2000n)1818   * @returns ```true``` if extrinsic success, otherwise ```false```1819   */1820  async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId, amount=1n): Promise<boolean> {1821    return await super.transferToken(signer, collectionId, tokenId, addressObj, amount);1822  }18231824  /**1825   * Change ownership of some pieces of RFT on behalf of the owner.1826   * @param signer keyring of signer1827   * @param collectionId ID of collection1828   * @param tokenId ID of token1829   * @param fromAddressObj address on behalf of which the token will be sent1830   * @param toAddressObj new token owner1831   * @param amount number of pieces to be transfered1832   * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, {Substrate: "5DfhbVfww7ThF8q6f3i..."}, 2000n)1833   * @returns ```true``` if extrinsic success, otherwise ```false```1834   */1835  async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1836    return await super.transferTokenFrom(signer, collectionId, tokenId, fromAddressObj, toAddressObj, amount);1837  }18381839  /**1840   * Mint new collection1841   * @param signer keyring of signer1842   * @param collectionOptions Collection options1843   * @example1844   * mintCollection(aliceKeyring, {1845   *   name: 'New',1846   *   description: 'New collection',1847   *   tokenPrefix: 'NEW',1848   * })1849   * @returns object of the created collection1850   */1851  async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}): Promise<UniqueRFTCollection> {1852    return await super.mintCollection(signer, collectionOptions, 'RFT') as UniqueRFTCollection;1853  }18541855  /**1856   * Mint new token1857   * @param signer keyring of signer1858   * @param data token data1859   * @example mintToken(aliceKeyring, {collectionId: 10, owner: {Substrate: '5GHoZe9c73RYbVzq...'}, pieces: 10000n});1860   * @returns created token object1861   */1862  async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; pieces: bigint; properties?: IProperty[]; }): Promise<UniqueRFToken> {1863    const creationResult = await this.helper.executeExtrinsic(1864      signer,1865      'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {1866        refungible: {1867          pieces: data.pieces,1868          properties: data.properties,1869        },1870      }],1871      true,1872    );1873    const createdTokens = this.helper.util.extractTokensFromCreationResult(creationResult);1874    if (createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');1875    if (createdTokens.tokens.length < 1) throw Error('No tokens minted');1876    return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);1877  }18781879  async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: {owner: ICrossAccountId, pieces: bigint, properties?: IProperty[]}[]): Promise<UniqueRFToken[]> {1880    throw Error('Not implemented');1881    const creationResult = await this.helper.executeExtrinsic(1882      signer,1883      'api.tx.unique.createMultipleItemsEx', [collectionId, {RefungibleMultipleOwners: tokens}],1884      true, // `Unable to mint RFT tokens for ${label}`,1885    );1886    const collection = this.getCollectionObject(collectionId);1887    return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1888  }18891890  /**1891   * Mint multiple RFT tokens with one owner1892   * @param signer keyring of signer1893   * @param collectionId ID of collection1894   * @param owner tokens owner1895   * @param tokens array of tokens with properties and pieces1896   * @example mintMultipleTokensWithOneOwner(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, [{pieces: 100000n, properties: [{key: "gender", value: "male"}]}]);1897   * @returns array of newly created RFT tokens1898   */1899  async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {pieces: bigint, properties?: IProperty[]}[]): Promise<UniqueRFToken[]> {1900    const rawTokens = [];1901    for (const token of tokens) {1902      const raw = {ReFungible: {pieces: token.pieces, properties: token.properties}};1903      rawTokens.push(raw);1904    }1905    const creationResult = await this.helper.executeExtrinsic(1906      signer,1907      'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1908      true,1909    );1910    const collection = this.getCollectionObject(collectionId);1911    return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1912  }19131914  /**1915   * Destroys a concrete instance of RFT.1916   * @param signer keyring of signer1917   * @param collectionId ID of collection1918   * @param tokenId ID of token1919   * @param amount number of pieces to be burnt1920   * @example burnToken(aliceKeyring, 10, 5);1921   * @returns ```true``` if the extrinsic is successful, otherwise ```false```1922   */1923  async burnToken(signer: IKeyringPair, collectionId: number, tokenId: number, amount=1n): Promise<boolean> {1924    return await super.burnToken(signer, collectionId, tokenId, amount);1925  }19261927  /**1928   * Destroys a concrete instance of RFT on behalf of the owner.1929   * @param signer keyring of signer1930   * @param collectionId ID of collection1931   * @param tokenId ID of token1932   * @param fromAddressObj address on behalf of which the token will be burnt1933   * @param amount number of pieces to be burnt1934   * @example burnTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, 2n)1935   * @returns ```true``` if extrinsic success, otherwise ```false```1936   */1937  async burnTokenFrom(signer: IKeyringPair, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1938    return await super.burnTokenFrom(signer, collectionId, tokenId, fromAddressObj, amount);1939  }19401941  /**1942   * Set, change, or remove approved address to transfer the ownership of the RFT.1943   *1944   * @param signer keyring of signer1945   * @param collectionId ID of collection1946   * @param tokenId ID of token1947   * @param toAddressObj address to approve1948   * @param amount number of pieces to be approved1949   * @example approveToken(aliceKeyring, 10, 5, {Substrate: "5GHoZe9c73RYbVzq..."}, "", 10000n);1950   * @returns true if the token success, otherwise false1951   */1952  approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {1953    return super.approveToken(signer, collectionId, tokenId, toAddressObj, amount);1954  }19551956  /**1957   * Get total number of pieces1958   * @param collectionId ID of collection1959   * @param tokenId ID of token1960   * @example getTokenTotalPieces(10, 5);1961   * @returns number of pieces1962   */1963  async getTokenTotalPieces(collectionId: number, tokenId: number): Promise<bigint> {1964    return (await this.helper.callRpc('api.rpc.unique.totalPieces', [collectionId, tokenId])).unwrap().toBigInt();1965  }19661967  /**1968   * Change number of token pieces. Signer must be the owner of all token pieces.1969   * @param signer keyring of signer1970   * @param collectionId ID of collection1971   * @param tokenId ID of token1972   * @param amount new number of pieces1973   * @example repartitionToken(aliceKeyring, 10, 5, 12345n);1974   * @returns true if the repartion was success, otherwise false1975   */1976  async repartitionToken(signer: TSigner, collectionId: number, tokenId: number, amount: bigint): Promise<boolean> {1977    const currentAmount = await this.getTokenTotalPieces(collectionId, tokenId);1978    const repartitionResult = await this.helper.executeExtrinsic(1979      signer,1980      'api.tx.unique.repartition', [collectionId, tokenId, amount],1981      true,1982    );1983    if(currentAmount < amount) return this.helper.util.findCollectionInEvents(repartitionResult.result.events, collectionId, 'common', 'ItemCreated');1984    return this.helper.util.findCollectionInEvents(repartitionResult.result.events, collectionId, 'common', 'ItemDestroyed');1985  }1986}198719881989class FTGroup extends CollectionGroup {1990  /**1991   * Get collection object1992   * @param collectionId ID of collection1993   * @example getCollectionObject(2);1994   * @returns instance of UniqueFTCollection1995   */1996  getCollectionObject(collectionId: number): UniqueFTCollection {1997    return new UniqueFTCollection(collectionId, this.helper);1998  }19992000  /**2001   * Mint new fungible collection2002   * @param signer keyring of signer2003   * @param collectionOptions Collection options2004   * @param decimalPoints number of token decimals2005   * @example2006   * mintCollection(aliceKeyring, {2007   *   name: 'New',2008   *   description: 'New collection',2009   *   tokenPrefix: 'NEW',2010   * }, 18)2011   * @returns newly created fungible collection2012   */2013  async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}, decimalPoints = 0): Promise<UniqueFTCollection> {2014    collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; // Clone object2015    if(collectionOptions.tokenPropertyPermissions) throw Error('Fungible collections has no tokenPropertyPermissions');2016    collectionOptions.mode = {fungible: decimalPoints};2017    for (const key of ['name', 'description', 'tokenPrefix']) {2018      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);2019    }2020    const creationResult = await this.helper.executeExtrinsic(2021      signer,2022      'api.tx.unique.createCollectionEx', [collectionOptions],2023      true,2024    );2025    return this.getCollectionObject(this.helper.util.extractCollectionIdFromCreationResult(creationResult));2026  }20272028  /**2029   * Mint tokens2030   * @param signer keyring of signer2031   * @param collectionId ID of collection2032   * @param owner address owner of new tokens2033   * @param amount amount of tokens to be meanted2034   * @example mintTokens(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq"}, 1000n);2035   * @returns ```true``` if extrinsic success, otherwise ```false```2036   */2037  async mintTokens(signer: TSigner, collectionId: number, amount: bigint, owner: ICrossAccountId | string): Promise<boolean> {2038    const creationResult = await this.helper.executeExtrinsic(2039      signer,2040      'api.tx.unique.createItem', [collectionId, (typeof owner === 'string') ? {Substrate: owner} : owner, {2041        fungible: {2042          value: amount,2043        },2044      }],2045      true, // `Unable to mint fungible tokens for ${label}`,2046    );2047    return this.helper.util.findCollectionInEvents(creationResult.result.events, collectionId, 'common', 'ItemCreated');2048  }20492050  /**2051   * Mint multiple Fungible tokens with one owner2052   * @param signer keyring of signer2053   * @param collectionId ID of collection2054   * @param owner tokens owner2055   * @param tokens array of tokens with properties and pieces2056   * @returns ```true``` if extrinsic success, otherwise ```false```2057   */2058  async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, tokens: {value: bigint}[], owner: ICrossAccountId): Promise<boolean> {2059    const rawTokens = [];2060    for (const token of tokens) {2061      const raw = {Fungible: {Value: token.value}};2062      rawTokens.push(raw);2063    }2064    const creationResult = await this.helper.executeExtrinsic(2065      signer,2066      'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],2067      true,2068    );2069    return this.helper.util.findCollectionInEvents(creationResult.result.events, collectionId, 'common', 'ItemCreated');2070  }20712072  /**2073   * Get the top 10 owners with the largest balance for the Fungible collection2074   * @param collectionId ID of collection2075   * @example getTop10Owners(10);2076   * @returns array of ```ICrossAccountId```2077   */2078  async getTop10Owners(collectionId: number): Promise<CrossAccountId[]> {2079    return (await this.helper.callRpc('api.rpc.unique.tokenOwners', [collectionId, 0])).toJSON().map(CrossAccountId.fromLowerCaseKeys);2080  }20812082  /**2083   * Get account balance2084   * @param collectionId ID of collection2085   * @param addressObj address of owner2086   * @example getBalance(10, {Substrate: "5GHoZe9c73RYbVzq..."})2087   * @returns amount of fungible tokens owned by address2088   */2089  async getBalance(collectionId: number, addressObj: ICrossAccountId): Promise<bigint> {2090    return (await this.helper.callRpc('api.rpc.unique.balance', [collectionId, addressObj, 0])).toBigInt();2091  }20922093  /**2094   * Transfer tokens to address2095   * @param signer keyring of signer2096   * @param collectionId ID of collection2097   * @param toAddressObj address recipient2098   * @param amount amount of tokens to be sent2099   * @example transfer(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, 1000n);2100   * @returns ```true``` if extrinsic success, otherwise ```false```2101   */2102  async transfer(signer: TSigner, collectionId: number, toAddressObj: ICrossAccountId, amount=1n) {2103    return await super.transferToken(signer, collectionId, 0, toAddressObj, amount);2104  }21052106  /**2107   * Transfer some tokens on behalf of the owner.2108   * @param signer keyring of signer2109   * @param collectionId ID of collection2110   * @param fromAddressObj address on behalf of which tokens will be sent2111   * @param toAddressObj address where token to be sent2112   * @param amount number of tokens to be sent2113   * @example transferFrom(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, {Substrate: "5DfhbVfww7ThF8q6f3ij..."}, 10000n);2114   * @returns ```true``` if extrinsic success, otherwise ```false```2115   */2116  async transferFrom(signer: TSigner, collectionId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {2117    return await super.transferTokenFrom(signer, collectionId, 0, fromAddressObj, toAddressObj, amount);2118  }21192120  /**2121   * Destroy some amount of tokens2122   * @param signer keyring of signer2123   * @param collectionId ID of collection2124   * @param amount amount of tokens to be destroyed2125   * @example burnTokens(aliceKeyring, 10, 1000n);2126   * @returns ```true``` if extrinsic success, otherwise ```false```2127   */2128  async burnTokens(signer: IKeyringPair, collectionId: number, amount=1n): Promise<boolean> {2129    return await super.burnToken(signer, collectionId, 0, amount);2130  }21312132  /**2133   * Burn some tokens on behalf of the owner.2134   * @param signer keyring of signer2135   * @param collectionId ID of collection2136   * @param fromAddressObj address on behalf of which tokens will be burnt2137   * @param amount amount of tokens to be burnt2138   * @example burnTokensFrom(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, 1000n);2139   * @returns ```true``` if extrinsic success, otherwise ```false```2140   */2141  async burnTokensFrom(signer: IKeyringPair, collectionId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {2142    return await super.burnTokenFrom(signer, collectionId, 0, fromAddressObj, amount);2143  }21442145  /**2146   * Get total collection supply2147   * @param collectionId2148   * @returns2149   */2150  async getTotalPieces(collectionId: number): Promise<bigint> {2151    return (await this.helper.callRpc('api.rpc.unique.totalPieces', [collectionId, 0])).unwrap().toBigInt();2152  }21532154  /**2155   * Set, change, or remove approved address to transfer tokens.2156   *2157   * @param signer keyring of signer2158   * @param collectionId ID of collection2159   * @param toAddressObj address to be approved2160   * @param amount amount of tokens to be approved2161   * @example approveTokens(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, 1000n)2162   * @returns ```true``` if extrinsic success, otherwise ```false```2163   */2164  approveTokens(signer: IKeyringPair, collectionId: number, toAddressObj: ICrossAccountId, amount=1n) {2165    return super.approveToken(signer, collectionId, 0, toAddressObj, amount);2166  }21672168  /**2169   * Get amount of fungible tokens approved to transfer2170   * @param collectionId ID of collection2171   * @param fromAddressObj owner of tokens2172   * @param toAddressObj the address approved for the transfer of tokens on behalf of the owner2173   * @returns number of tokens approved for the transfer2174   */2175  getApprovedTokens(collectionId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2176    return super.getTokenApprovedPieces(collectionId, 0, toAddressObj, fromAddressObj);2177  }2178}217921802181class ChainGroup extends HelperGroup<ChainHelperBase> {2182  /**2183   * Get system properties of a chain2184   * @example getChainProperties();2185   * @returns ss58Format, token decimals, and token symbol2186   */2187  getChainProperties(): IChainProperties {2188    const properties = (this.helper.getApi() as any).registry.getChainProperties().toJSON();2189    return {2190      ss58Format: properties.ss58Format.toJSON(),2191      tokenDecimals: properties.tokenDecimals.toJSON(),2192      tokenSymbol: properties.tokenSymbol.toJSON(),2193    };2194  }21952196  /**2197   * Get chain header2198   * @example getLatestBlockNumber();2199   * @returns the number of the last block2200   */2201  async getLatestBlockNumber(): Promise<number> {2202    return (await this.helper.callRpc('api.rpc.chain.getHeader')).number.toNumber();2203  }22042205  /**2206   * Get block hash by block number2207   * @param blockNumber number of block2208   * @example getBlockHashByNumber(12345);2209   * @returns hash of a block2210   */2211  async getBlockHashByNumber(blockNumber: number): Promise<string | null> {2212    const blockHash = (await this.helper.callRpc('api.rpc.chain.getBlockHash', [blockNumber])).toJSON();2213    if(blockHash === '0x0000000000000000000000000000000000000000000000000000000000000000') return null;2214    return blockHash;2215  }22162217  // TODO add docs2218  async getBlock(blockHashOrNumber: string | number): Promise<IBlock | null> {2219    const blockHash = typeof blockHashOrNumber === 'string' ? blockHashOrNumber : await this.getBlockHashByNumber(blockHashOrNumber);2220    if (!blockHash) return null;2221    return (await this.helper.callRpc('api.rpc.chain.getBlock', [blockHash])).toHuman().block;2222  }22232224  /**2225   * Get latest relay block2226   * @returns {number} relay block2227   */2228  async getRelayBlockNumber(): Promise<bigint> {2229    const blockNumber = (await this.helper.callRpc('api.query.parachainSystem.validationData')).toJSON().relayParentNumber;2230    return BigInt(blockNumber);2231  }22322233  /**2234   * Get account nonce2235   * @param address substrate address2236   * @example getNonce("5GrwvaEF5zXb26Fz...");2237   * @returns number, account's nonce2238   */2239  async getNonce(address: TSubstrateAccount): Promise<number> {2240    return (await this.helper.callRpc('api.query.system.account', [address])).nonce.toNumber();2241  }2242}22432244class SubstrateBalanceGroup<T extends ChainHelperBase> extends HelperGroup<T> {2245  /**2246 * Get substrate address balance2247 * @param address substrate address2248 * @example getSubstrate("5GrwvaEF5zXb26Fz...")2249 * @returns amount of tokens on address2250 */2251  async getSubstrate(address: TSubstrateAccount): Promise<bigint> {2252    return (await this.helper.callRpc('api.query.system.account', [address])).data.free.toBigInt();2253  }22542255  /**2256   * Transfer tokens to substrate address2257   * @param signer keyring of signer2258   * @param address substrate address of a recipient2259   * @param amount amount of tokens to be transfered2260   * @example transferToSubstrate(aliceKeyring, "5GrwvaEF5zXb26Fz...", 100_000_000_000n);2261   * @returns ```true``` if extrinsic success, otherwise ```false```2262   */2263  async transferToSubstrate(signer: TSigner, address: TSubstrateAccount, amount: bigint | string): Promise<boolean> {2264    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}`*/);22652266    let transfer = {from: null, to: null, amount: 0n} as any;2267    result.result.events.forEach(({event: {data, method, section}}) => {2268      if ((section === 'balances') && (method === 'Transfer')) {2269        transfer = {2270          from: this.helper.address.normalizeSubstrate(data[0]),2271          to: this.helper.address.normalizeSubstrate(data[1]),2272          amount: BigInt(data[2]),2273        };2274      }2275    });2276    const isSuccess = this.helper.address.normalizeSubstrate(typeof signer === 'string' ? signer : signer.address) === transfer.from2277      && this.helper.address.normalizeSubstrate(address) === transfer.to2278      && BigInt(amount) === transfer.amount;2279    return isSuccess;2280  }22812282  /**2283   * Get full substrate balance including free, miscFrozen, feeFrozen, and reserved2284   * @param address substrate address2285   * @returns2286   */2287  async getSubstrateFull(address: TSubstrateAccount): Promise<ISubstrateBalance> {2288    const accountInfo = (await this.helper.callRpc('api.query.system.account', [address])).data;2289    return {free: accountInfo.free.toBigInt(), miscFrozen: accountInfo.miscFrozen.toBigInt(), feeFrozen: accountInfo.feeFrozen.toBigInt(), reserved: accountInfo.reserved.toBigInt()};2290  }22912292  async getLocked(address: TSubstrateAccount): Promise<[{id: string, amount: bigint, reason: string}]> {2293    const locks = (await this.helper.callRpc('api.query.balances.locks', [address])).toHuman();2294    return locks.map((lock: any) => {return {id: lock.id, amount: BigInt(lock.amount.replace(/,/g, '')), reasons: lock.reasons};});2295  }2296}22972298class EthereumBalanceGroup<T extends ChainHelperBase> extends HelperGroup<T> {2299  /**2300   * Get ethereum address balance2301   * @param address ethereum address2302   * @example getEthereum("0x9F0583DbB855d...")2303   * @returns amount of tokens on address2304   */2305  async getEthereum(address: TEthereumAccount): Promise<bigint> {2306    return (await this.helper.callRpc('api.rpc.eth.getBalance', [address])).toBigInt();2307  }23082309  /**2310   * Transfer tokens to address2311   * @param signer keyring of signer2312   * @param address Ethereum address of a recipient2313   * @param amount amount of tokens to be transfered2314   * @example transferToEthereum(alithKeyring, "0x9F0583DbB855d...", 100_000_000_000n);2315   * @returns ```true``` if extrinsic success, otherwise ```false```2316   */2317  async transferToEthereum(signer: TSigner, address: TEthereumAccount, amount: bigint | string): Promise<boolean> {2318    const result = await this.helper.executeExtrinsic(signer, 'api.tx.balances.transfer', [address, amount], true);23192320    let transfer = {from: null, to: null, amount: 0n} as any;2321    result.result.events.forEach(({event: {data, method, section}}) => {2322      if ((section === 'balances') && (method === 'Transfer')) {2323        transfer = {2324          from: data[0].toString(),2325          to: data[1].toString(),2326          amount: BigInt(data[2]),2327        };2328      }2329    });2330    const isSuccess = (typeof signer === 'string' ? signer : signer.address) === transfer.from2331      && address === transfer.to2332      && BigInt(amount) === transfer.amount;2333    return isSuccess;2334  }2335}23362337class BalanceGroup<T extends ChainHelperBase> extends HelperGroup<T> {2338  subBalanceGroup: SubstrateBalanceGroup<T>;2339  ethBalanceGroup: EthereumBalanceGroup<T>;23402341  constructor(helper: T) {2342    super(helper);2343    this.subBalanceGroup = new SubstrateBalanceGroup(helper);2344    this.ethBalanceGroup = new EthereumBalanceGroup(helper);2345  }23462347  getCollectionCreationPrice(): bigint {2348    return 2n * this.getOneTokenNominal();2349  }2350  /**2351   * Representation of the native token in the smallest unit - one OPAL (OPL), QUARTZ (QTZ), or UNIQUE (UNQ).2352   * @example getOneTokenNominal()2353   * @returns ```BigInt``` representation of the native token in the smallest unit, e.g. ```1_000_000_000_000_000_000n``` for QTZ.2354   */2355  getOneTokenNominal(): bigint {2356    const chainProperties = this.helper.chain.getChainProperties();2357    return 10n ** BigInt((chainProperties.tokenDecimals || [18])[0]);2358  }23592360  /**2361   * Get substrate address balance2362   * @param address substrate address2363   * @example getSubstrate("5GrwvaEF5zXb26Fz...")2364   * @returns amount of tokens on address2365   */2366  getSubstrate(address: TSubstrateAccount): Promise<bigint> {2367    return this.subBalanceGroup.getSubstrate(address);2368  }23692370  /**2371   * Get full substrate balance including free, miscFrozen, feeFrozen, and reserved2372   * @param address substrate address2373   * @returns2374   */2375  getSubstrateFull(address: TSubstrateAccount): Promise<ISubstrateBalance> {2376    return this.subBalanceGroup.getSubstrateFull(address);2377  }23782379  /**2380   * Get locked balances2381   * @param address substrate address2382   * @returns locked balances with reason via api.query.balances.locks2383   */2384  getLocked(address: TSubstrateAccount) {2385    return this.subBalanceGroup.getLocked(address);2386  }23872388  /**2389   * Get ethereum address balance2390   * @param address ethereum address2391   * @example getEthereum("0x9F0583DbB855d...")2392   * @returns amount of tokens on address2393   */2394  getEthereum(address: TEthereumAccount): Promise<bigint> {2395    return this.ethBalanceGroup.getEthereum(address);2396  }23972398  /**2399   * Transfer tokens to substrate address2400   * @param signer keyring of signer2401   * @param address substrate address of a recipient2402   * @param amount amount of tokens to be transfered2403   * @example transferToSubstrate(aliceKeyring, "5GrwvaEF5zXb26Fz...", 100_000_000_000n);2404   * @returns ```true``` if extrinsic success, otherwise ```false```2405   */2406  transferToSubstrate(signer: TSigner, address: TSubstrateAccount, amount: bigint | string): Promise<boolean> {2407    return this.subBalanceGroup.transferToSubstrate(signer, address, amount);2408  }24092410  async forceTransferToSubstrate(signer: TSigner, from: TSubstrateAccount, to: TSubstrateAccount, amount: bigint | string): Promise<boolean> {2411    const result = await this.helper.executeExtrinsic(signer, 'api.tx.balances.forceTransfer', [from, to, amount], true);24122413    let transfer = {from: null, to: null, amount: 0n} as any;2414    result.result.events.forEach(({event: {data, method, section}}) => {2415      if ((section === 'balances') && (method === 'Transfer')) {2416        transfer = {2417          from: this.helper.address.normalizeSubstrate(data[0]),2418          to: this.helper.address.normalizeSubstrate(data[1]),2419          amount: BigInt(data[2]),2420        };2421      }2422    });2423    let isSuccess = this.helper.address.normalizeSubstrate(from) === transfer.from;2424    isSuccess = isSuccess && this.helper.address.normalizeSubstrate(to) === transfer.to;2425    isSuccess = isSuccess && BigInt(amount) === transfer.amount;2426    return isSuccess;2427  }24282429  /**2430   * Transfer tokens with the unlock period2431   * @param signer signers Keyring2432   * @param address Substrate address of recipient2433   * @param schedule Schedule params2434   * @example vestedTransfer(signer, recepient.address, 20000, 100, 10, 50 * nominal); // total amount of vested tokens will be 100 * 50 = 50002435   */2436  async vestedTransfer(signer: TSigner, address: TSubstrateAccount, schedule: {start: bigint, period: bigint, periodCount: bigint, perPeriod: bigint}): Promise<void> {2437    const result = await this.helper.executeExtrinsic(signer, 'api.tx.vesting.vestedTransfer', [address, schedule]);2438    const event = result.result.events2439      .find(e => e.event.section === 'vesting' &&2440            e.event.method === 'VestingScheduleAdded' &&2441            e.event.data[0].toHuman() === signer.address);2442    if (!event) throw Error('Cannot find transfer in events');2443  }24442445  /**2446   * Get schedule for recepient of vested transfer2447   * @param address Substrate address of recipient2448   * @returns2449   */2450  async getVestingSchedules(address: TSubstrateAccount): Promise<{start: bigint, period: bigint, periodCount: bigint, perPeriod: bigint}[]> {2451    const schedule = (await this.helper.callRpc('api.query.vesting.vestingSchedules', [address])).toJSON();2452    return schedule.map((schedule: any) => {2453      return {2454        start: BigInt(schedule.start),2455        period: BigInt(schedule.period),2456        periodCount: BigInt(schedule.periodCount),2457        perPeriod: BigInt(schedule.perPeriod),2458      };2459    });2460  }24612462  /**2463   * Claim vested tokens2464   * @param signer signers Keyring2465   */2466  async claim(signer: TSigner) {2467    const result = await this.helper.executeExtrinsic(signer, 'api.tx.vesting.claim', []);2468    const event = result.result.events2469      .find(e => e.event.section === 'vesting' &&2470            e.event.method === 'Claimed' &&2471            e.event.data[0].toHuman() === signer.address);2472    if (!event) throw Error('Cannot find claim in events');2473  }2474}24752476class AddressGroup extends HelperGroup<ChainHelperBase> {2477  /**2478   * Normalizes the address to the specified ss58 format, by default ```42```.2479   * @param address substrate address2480   * @param ss58Format format for address conversion, by default ```42```2481   * @example normalizeSubstrate("unjKJQJrRd238pkUZZvzDQrfKuM39zBSnQ5zjAGAGcdRhaJTx") // returns 5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY2482   * @returns substrate address converted to normalized (i.e., starting with 5) or specified explicitly representation2483   */2484  normalizeSubstrate(address: TSubstrateAccount, ss58Format = 42): TSubstrateAccount {2485    return CrossAccountId.normalizeSubstrateAddress(address, ss58Format);2486  }24872488  /**2489   * Get address in the connected chain format2490   * @param address substrate address2491   * @example normalizeSubstrateToChainFormat("5GrwvaEF5zXb26Fz...") // returns unjKJQJrRd238pkUZZ... for Unique Network2492   * @returns address in chain format2493   */2494  normalizeSubstrateToChainFormat(address: TSubstrateAccount): TSubstrateAccount {2495    return this.normalizeSubstrate(address, this.helper.chain.getChainProperties().ss58Format);2496  }24972498  /**2499   * Get substrate mirror of an ethereum address2500   * @param ethAddress ethereum address2501   * @param toChainFormat false for normalized account2502   * @example ethToSubstrate('0x9F0583DbB855d...')2503   * @returns substrate mirror of a provided ethereum address2504   */2505  ethToSubstrate(ethAddress: TEthereumAccount, toChainFormat=false): TSubstrateAccount {2506    return CrossAccountId.translateEthToSub(ethAddress, toChainFormat ? this.helper.chain.getChainProperties().ss58Format : undefined);2507  }25082509  /**2510   * Get ethereum mirror of a substrate address2511   * @param subAddress substrate account2512   * @example substrateToEth("5DnSF6RRjwteE3BrC...")2513   * @returns ethereum mirror of a provided substrate address2514   */2515  substrateToEth(subAddress: TSubstrateAccount): TEthereumAccount {2516    return CrossAccountId.translateSubToEth(subAddress);2517  }25182519  /**2520   * Encode key to substrate address2521   * @param key key for encoding address2522   * @param ss58Format prefix for encoding to the address of the corresponding network2523   * @returns encoded substrate address2524   */2525  encodeSubstrateAddress (key: Uint8Array | string | bigint, ss58Format = 42): string {2526    const u8a :Uint8Array = typeof key === 'string'2527      ? hexToU8a(key)2528      : typeof key === 'bigint'2529        ? hexToU8a(key.toString(16))2530        : key;25312532    if (ss58Format < 0 || ss58Format > 16383 || [46, 47].includes(ss58Format)) {2533      throw new Error(`ss58Format is not valid, received ${typeof ss58Format} "${ss58Format}"`);2534    }25352536    const allowedDecodedLengths = [1, 2, 4, 8, 32, 33];2537    if (!allowedDecodedLengths.includes(u8a.length)) {2538      throw new Error(`key length is not valid, received ${u8a.length}, valid values are ${allowedDecodedLengths.join(', ')}`);2539    }25402541    const u8aPrefix = ss58Format < 642542      ? new Uint8Array([ss58Format])2543      : new Uint8Array([2544        ((ss58Format & 0xfc) >> 2) | 0x40,2545        (ss58Format >> 8) | ((ss58Format & 0x03) << 6),2546      ]);25472548    const input = u8aConcat(u8aPrefix, u8a);25492550    return base58Encode(u8aConcat(2551      input,2552      blake2AsU8a(input).subarray(0, [32, 33].includes(u8a.length) ? 2 : 1),2553    ));2554  }25552556  /**2557   * Restore substrate address from bigint representation2558   * @param number decimal representation of substrate address2559   * @returns substrate address2560   */2561  restoreCrossAccountFromBigInt(number: bigint): TSubstrateAccount {2562    if (this.helper.api === null) {2563      throw 'Not connected';2564    }2565    const res = this.helper.api.registry.createType('AccountId', '0x' + number.toString(16).padStart(64, '0')).toJSON();2566    if (res === undefined || res === null) {2567      throw 'Restore address error';2568    }2569    return res.toString();2570  }25712572  /**2573   * Convert etherium cross account id to substrate cross account id2574   * @param ethCrossAccount etherium cross account2575   * @returns substrate cross account id2576   */2577  convertCrossAccountFromEthCrossAccount(ethCrossAccount: IEthCrossAccountId): ICrossAccountId {2578    if (ethCrossAccount.sub === '0') {2579      return {Ethereum: ethCrossAccount.eth.toLocaleLowerCase()};2580    }25812582    const ss58 = this.restoreCrossAccountFromBigInt(BigInt(ethCrossAccount.sub));2583    return {Substrate: ss58};2584  }25852586  paraSiblingSovereignAccount(paraid: number) {2587    // We are getting a *sibling* parachain sovereign account,2588    // so we need a sibling prefix: encoded(b"sibl") == 0x7369626c2589    const siblingPrefix = '0x7369626c';25902591    const encodedParaId = this.helper.getApi().createType('u32', paraid).toHex(true).substring(2);2592    const suffix = '000000000000000000000000000000000000000000000000';25932594    return siblingPrefix + encodedParaId + suffix;2595  }2596}25972598class StakingGroup extends HelperGroup<UniqueHelper> {2599  /**2600   * Stake tokens for App Promotion2601   * @param signer keyring of signer2602   * @param amountToStake amount of tokens to stake2603   * @param label extra label for log2604   * @returns2605   */2606  async stake(signer: TSigner, amountToStake: bigint, label?: string): Promise<boolean> {2607    if(typeof label === 'undefined') label = `${signer.address} amount: ${amountToStake}`;2608    const _stakeResult = await this.helper.executeExtrinsic(2609      signer, 'api.tx.appPromotion.stake',2610      [amountToStake], true,2611    );2612    // TODO extract info from stakeResult2613    return true;2614  }26152616  /**2617   * Unstake tokens for App Promotion2618   * @param signer keyring of signer2619   * @param amountToUnstake amount of tokens to unstake2620   * @param label extra label for log2621   * @returns block number where balances will be unlocked2622   */2623  async unstake(signer: TSigner, label?: string): Promise<number> {2624    if(typeof label === 'undefined') label = `${signer.address}`;2625    const _unstakeResult = await this.helper.executeExtrinsic(2626      signer, 'api.tx.appPromotion.unstake',2627      [], true,2628    );2629    // TODO extract block number fron events2630    return 1;2631  }26322633  /**2634   * Get total staked amount for address2635   * @param address substrate or ethereum address2636   * @returns total staked amount2637   */2638  async getTotalStaked(address?: ICrossAccountId): Promise<bigint> {2639    if (address) return (await this.helper.callRpc('api.rpc.appPromotion.totalStaked', [address])).toBigInt();2640    return (await this.helper.callRpc('api.rpc.appPromotion.totalStaked')).toBigInt();2641  }26422643  /**2644   * Get total staked per block2645   * @param address substrate or ethereum address2646   * @returns array of stakes. `block` – the number of the block in which the stake was made. `amount` - the number of tokens staked in the block2647   */2648  async getTotalStakedPerBlock(address: ICrossAccountId): Promise<IStakingInfo[]> {2649    const rawTotalStakerdPerBlock = await this.helper.callRpc('api.rpc.appPromotion.totalStakedPerBlock', [address]);2650    return rawTotalStakerdPerBlock.map(([block, amount]: any[]) => {2651      return {2652        block: block.toBigInt(),2653        amount: amount.toBigInt(),2654      };2655    });2656  }26572658  /**2659   * Get total pending unstake amount for address2660   * @param address substrate or ethereum address2661   * @returns total pending unstake amount2662   */2663  async getPendingUnstake(address: ICrossAccountId): Promise<bigint> {2664    return (await this.helper.callRpc('api.rpc.appPromotion.pendingUnstake', [address])).toBigInt();2665  }26662667  /**2668   * Get pending unstake amount per block for address2669   * @param address substrate or ethereum address2670   * @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 block2671   */2672  async getPendingUnstakePerBlock(address: ICrossAccountId): Promise<IStakingInfo[]> {2673    const rawUnstakedPerBlock = await this.helper.callRpc('api.rpc.appPromotion.pendingUnstakePerBlock', [address]);2674    const result = rawUnstakedPerBlock.map(([block, amount]: any[]) => {2675      return {2676        block: block.toBigInt(),2677        amount: amount.toBigInt(),2678      };2679    });2680    return result;2681  }2682}26832684class SchedulerGroup extends HelperGroup<UniqueHelper> {2685  constructor(helper: UniqueHelper) {2686    super(helper);2687  }26882689  cancelScheduled(signer: TSigner, scheduledId: string) {2690    return this.helper.executeExtrinsic(2691      signer,2692      'api.tx.scheduler.cancelNamed',2693      [scheduledId],2694      true,2695    );2696  }26972698  changePriority(signer: TSigner, scheduledId: string, priority: number) {2699    return this.helper.executeExtrinsic(2700      signer,2701      'api.tx.scheduler.changeNamedPriority',2702      [scheduledId, priority],2703      true,2704    );2705  }27062707  scheduleAt<T extends UniqueHelper>(2708    executionBlockNumber: number,2709    options: ISchedulerOptions = {},2710  ) {2711    return this.schedule<T>('schedule', executionBlockNumber, options);2712  }27132714  scheduleAfter<T extends UniqueHelper>(2715    blocksBeforeExecution: number,2716    options: ISchedulerOptions = {},2717  ) {2718    return this.schedule<T>('scheduleAfter', blocksBeforeExecution, options);2719  }27202721  schedule<T extends UniqueHelper>(2722    scheduleFn: 'schedule' | 'scheduleAfter',2723    blocksNum: number,2724    options: ISchedulerOptions = {},2725  ) {2726    // eslint-disable-next-line @typescript-eslint/naming-convention2727    const ScheduledHelperType = ScheduledUniqueHelper(this.helper.helperBase);2728    return this.helper.clone(ScheduledHelperType, {2729      scheduleFn,2730      blocksNum,2731      options,2732    }) as T;2733  }2734}27352736class CollatorSelectionGroup extends HelperGroup<UniqueHelper> {2737  //todo:collator documentation2738  addInvulnerable(signer: TSigner, address: string) {2739    return this.helper.executeExtrinsic(signer, 'api.tx.collatorSelection.addInvulnerable', [address]);2740  }27412742  removeInvulnerable(signer: TSigner, address: string) {2743    return this.helper.executeExtrinsic(signer, 'api.tx.collatorSelection.removeInvulnerable', [address]);2744  }27452746  async getInvulnerables(): Promise<string[]> {2747    return (await this.helper.callRpc('api.query.collatorSelection.invulnerables')).map((x: any) => x.toHuman());2748  }27492750  /** and also total max invulnerables */2751  maxCollators(): number {2752    return (this.helper.getApi().consts.configuration.defaultCollatorSelectionMaxCollators.toJSON() as number);2753  }27542755  async getDesiredCollators(): Promise<number> {2756    return (await this.helper.callRpc('api.query.configuration.collatorSelectionDesiredCollatorsOverride')).toNumber();2757  }27582759  setLicenseBond(signer: TSigner, amount: bigint) {2760    return this.helper.executeExtrinsic(signer, 'api.tx.configuration.setCollatorSelectionLicenseBond', [amount]);2761  }27622763  async getLicenseBond(): Promise<bigint> {2764    return (await this.helper.callRpc('api.query.configuration.collatorSelectionLicenseBondOverride')).toBigInt();2765  }27662767  obtainLicense(signer: TSigner) {2768    return this.helper.executeExtrinsic(signer, 'api.tx.collatorSelection.getLicense', []);2769  }27702771  releaseLicense(signer: TSigner) {2772    return this.helper.executeExtrinsic(signer, 'api.tx.collatorSelection.releaseLicense', []);2773  }27742775  forceReleaseLicense(signer: TSigner, released: string) {2776    return this.helper.executeExtrinsic(signer, 'api.tx.collatorSelection.forceReleaseLicense', [released]);2777  }27782779  async hasLicense(address: string): Promise<bigint> {2780    return (await this.helper.callRpc('api.query.collatorSelection.licenseDepositOf', [address])).toBigInt();2781  }27822783  onboard(signer: TSigner) {2784    return this.helper.executeExtrinsic(signer, 'api.tx.collatorSelection.onboard', []);2785  }27862787  offboard(signer: TSigner) {2788    return this.helper.executeExtrinsic(signer, 'api.tx.collatorSelection.offboard', []);2789  }27902791  async getCandidates(): Promise<string[]> {2792    return (await this.helper.callRpc('api.query.collatorSelection.candidates')).map((x: any) => x.toHuman());2793  }2794}27952796class ForeignAssetsGroup extends HelperGroup<UniqueHelper> {2797  async register(signer: TSigner, ownerAddress: TSubstrateAccount, location: any, metadata: IForeignAssetMetadata) {2798    await this.helper.executeExtrinsic(2799      signer,2800      'api.tx.foreignAssets.registerForeignAsset',2801      [ownerAddress, location, metadata],2802      true,2803    );2804  }28052806  async update(signer: TSigner, foreignAssetId: number, location: any, metadata: IForeignAssetMetadata) {2807    await this.helper.executeExtrinsic(2808      signer,2809      'api.tx.foreignAssets.updateForeignAsset',2810      [foreignAssetId, location, metadata],2811      true,2812    );2813  }2814}28152816class XcmGroup<T extends ChainHelperBase> extends HelperGroup<T> {2817  palletName: string;28182819  constructor(helper: T, palletName: string) {2820    super(helper);28212822    this.palletName = palletName;2823  }28242825  async limitedReserveTransferAssets(signer: TSigner, destination: any, beneficiary: any, assets: any, feeAssetItem: number, weightLimit: any) {2826    await this.helper.executeExtrinsic(signer, `api.tx.${this.palletName}.limitedReserveTransferAssets`, [destination, beneficiary, assets, feeAssetItem, weightLimit], true);2827  }28282829  async teleportAssets(signer: TSigner, destination: any, beneficiary: any, assets: any, feeAssetItem: number) {2830    await this.helper.executeExtrinsic(signer, `api.tx.${this.palletName}.teleportAssets`, [destination, beneficiary, assets, feeAssetItem], true);2831  }28322833  async teleportNativeAsset(signer: TSigner, destinationParaId: number, targetAccount: Uint8Array, amount: bigint) {2834    const destination = {2835      V1: {2836        parents: 0,2837        interior: {2838          X1: {2839            Parachain: destinationParaId,2840          },2841        },2842      },2843    };28442845    const beneficiary = {2846      V1: {2847        parents: 0,2848        interior: {2849          X1: {2850            AccountId32: {2851              network: 'Any',2852              id: targetAccount,2853            },2854          },2855        },2856      },2857    };28582859    const assets = {2860      V1: [2861        {2862          id: {2863            Concrete: {2864              parents: 0,2865              interior: 'Here',2866            },2867          },2868          fun: {2869            Fungible: amount,2870          },2871        },2872      ],2873    };28742875    const feeAssetItem = 0;28762877    await this.teleportAssets(signer, destination, beneficiary, assets, feeAssetItem);2878  }2879}28802881class XTokensGroup<T extends ChainHelperBase> extends HelperGroup<T> {2882  async transfer(signer: TSigner, currencyId: any, amount: bigint, destination: any, destWeight: any) {2883    await this.helper.executeExtrinsic(signer, 'api.tx.xTokens.transfer', [currencyId, amount, destination, destWeight], true);2884  }28852886  async transferMultiasset(signer: TSigner, asset: any, destination: any, destWeight: any) {2887    await this.helper.executeExtrinsic(signer, 'api.tx.xTokens.transferMultiasset', [asset, destination, destWeight], true);2888  }28892890  async transferMulticurrencies(signer: TSigner, currencies: any[], feeItem: number, destLocation: any, destWeight: any) {2891    await this.helper.executeExtrinsic(signer, 'api.tx.xTokens.transferMulticurrencies', [currencies, feeItem, destLocation, destWeight], true);2892  }2893}28942895class TokensGroup<T extends ChainHelperBase> extends HelperGroup<T> {2896  async accounts(address: string, currencyId: any) {2897    const {free} = (await this.helper.callRpc('api.query.tokens.accounts', [address, currencyId])).toJSON() as any;2898    return BigInt(free);2899  }2900}29012902class AssetsGroup<T extends ChainHelperBase> extends HelperGroup<T> {2903  async create(signer: TSigner, assetId: number, admin: string, minimalBalance: bigint) {2904    await this.helper.executeExtrinsic(signer, 'api.tx.assets.create', [assetId, admin, minimalBalance], true);2905  }29062907  async setMetadata(signer: TSigner, assetId: number, name: string, symbol: string, decimals: number) {2908    await this.helper.executeExtrinsic(signer, 'api.tx.assets.setMetadata', [assetId, name, symbol, decimals], true);2909  }29102911  async mint(signer: TSigner, assetId: number, beneficiary: string, amount: bigint) {2912    await this.helper.executeExtrinsic(signer, 'api.tx.assets.mint', [assetId, beneficiary, amount], true);2913  }29142915  async account(assetId: string | number, address: string) {2916    const accountAsset = (2917      await this.helper.callRpc('api.query.assets.account', [assetId, address])2918    ).toJSON()! as any;29192920    if (accountAsset !== null) {2921      return BigInt(accountAsset['balance']);2922    } else {2923      return null;2924    }2925  }2926}29272928class AcalaAssetRegistryGroup extends HelperGroup<AcalaHelper> {2929  async registerForeignAsset(signer: TSigner, destination: any, metadata: AcalaAssetMetadata) {2930    await this.helper.executeExtrinsic(signer, 'api.tx.assetRegistry.registerForeignAsset', [destination, metadata], true);2931  }2932}29332934class MoonbeamAssetManagerGroup extends HelperGroup<MoonbeamHelper> {2935  makeRegisterForeignAssetProposal(assetInfo: MoonbeamAssetInfo) {2936    const apiPrefix = 'api.tx.assetManager.';29372938    const registerTx = this.helper.constructApiCall(2939      apiPrefix + 'registerForeignAsset',2940      [assetInfo.location, assetInfo.metadata, assetInfo.existentialDeposit, assetInfo.isSufficient],2941    );29422943    const setUnitsTx = this.helper.constructApiCall(2944      apiPrefix + 'setAssetUnitsPerSecond',2945      [assetInfo.location, assetInfo.unitsPerSecond, assetInfo.numAssetsWeightHint],2946    );29472948    const batchCall = this.helper.getApi().tx.utility.batchAll([registerTx, setUnitsTx]);2949    const encodedProposal = batchCall?.method.toHex() || '';2950    return encodedProposal;2951  }29522953  async assetTypeId(location: any) {2954    return await this.helper.callRpc('api.query.assetManager.assetTypeId', [location]);2955  }2956}29572958class MoonbeamDemocracyGroup extends HelperGroup<MoonbeamHelper> {2959  notePreimagePallet: string;29602961  constructor(helper: MoonbeamHelper, options: {[key: string]: any} = {}) {2962    super(helper);2963    this.notePreimagePallet = options.notePreimagePallet;2964  }29652966  async notePreimage(signer: TSigner, encodedProposal: string) {2967    await this.helper.executeExtrinsic(signer, `api.tx.${this.notePreimagePallet}.notePreimage`, [encodedProposal], true);2968  }29692970  externalProposeMajority(proposal: any) {2971    return this.helper.constructApiCall('api.tx.democracy.externalProposeMajority', [proposal]);2972  }29732974  fastTrack(proposalHash: string, votingPeriod: number, delayPeriod: number) {2975    return this.helper.constructApiCall('api.tx.democracy.fastTrack', [proposalHash, votingPeriod, delayPeriod]);2976  }29772978  async referendumVote(signer: TSigner, referendumIndex: number, accountVote: DemocracyStandardAccountVote) {2979    await this.helper.executeExtrinsic(signer, 'api.tx.democracy.vote', [referendumIndex, {Standard: accountVote}], true);2980  }2981}29822983class MoonbeamCollectiveGroup extends HelperGroup<MoonbeamHelper> {2984  collective: string;29852986  constructor(helper: MoonbeamHelper, collective: string) {2987    super(helper);29882989    this.collective = collective;2990  }29912992  async propose(signer: TSigner, threshold: number, proposalHash: string, lengthBound: number) {2993    await this.helper.executeExtrinsic(signer, `api.tx.${this.collective}.propose`, [threshold, proposalHash, lengthBound], true);2994  }29952996  async vote(signer: TSigner, proposalHash: string, proposalIndex: number, approve: boolean) {2997    await this.helper.executeExtrinsic(signer, `api.tx.${this.collective}.vote`, [proposalHash, proposalIndex, approve], true);2998  }29993000  async close(signer: TSigner, proposalHash: string, proposalIndex: number, weightBound: any, lengthBound: number) {3001    await this.helper.executeExtrinsic(signer, `api.tx.${this.collective}.close`, [proposalHash, proposalIndex, weightBound, lengthBound], true);3002  }30033004  async proposalCount() {3005    return Number(await this.helper.callRpc(`api.query.${this.collective}.proposalCount`, []));3006  }3007}30083009export type ChainHelperBaseConstructor = new(...args: any[]) => ChainHelperBase;3010export type UniqueHelperConstructor = new(...args: any[]) => UniqueHelper;30113012export class UniqueHelper extends ChainHelperBase {3013  balance: BalanceGroup<UniqueHelper>;3014  collection: CollectionGroup;3015  nft: NFTGroup;3016  rft: RFTGroup;3017  ft: FTGroup;3018  staking: StakingGroup;3019  scheduler: SchedulerGroup;3020  collatorSelection: CollatorSelectionGroup;3021  foreignAssets: ForeignAssetsGroup;3022  xcm: XcmGroup<UniqueHelper>;3023  xTokens: XTokensGroup<UniqueHelper>;3024  tokens: TokensGroup<UniqueHelper>;30253026  constructor(logger?: ILogger, options: {[key: string]: any} = {}) {3027    super(logger, options.helperBase ?? UniqueHelper);30283029    this.balance = new BalanceGroup(this);3030    this.collection = new CollectionGroup(this);3031    this.nft = new NFTGroup(this);3032    this.rft = new RFTGroup(this);3033    this.ft = new FTGroup(this);3034    this.staking = new StakingGroup(this);3035    this.scheduler = new SchedulerGroup(this);3036    this.collatorSelection = new CollatorSelectionGroup(this);3037    this.foreignAssets = new ForeignAssetsGroup(this);3038    this.xcm = new XcmGroup(this, 'polkadotXcm');3039    this.xTokens = new XTokensGroup(this);3040    this.tokens = new TokensGroup(this);3041  }30423043  getSudo<T extends UniqueHelper>() {3044    // eslint-disable-next-line @typescript-eslint/naming-convention3045    const SudoHelperType = SudoHelper(this.helperBase);3046    return this.clone(SudoHelperType) as T;3047  }3048}30493050export class XcmChainHelper extends ChainHelperBase {3051  async connect(wsEndpoint: string, _listeners?: any): Promise<void> {3052    const wsProvider = new WsProvider(wsEndpoint);3053    this.api = new ApiPromise({3054      provider: wsProvider,3055    });3056    await this.api.isReadyOrError;3057    this.network = await UniqueHelper.detectNetwork(this.api);3058  }3059}30603061export class RelayHelper extends XcmChainHelper {3062  balance: SubstrateBalanceGroup<RelayHelper>;3063  xcm: XcmGroup<RelayHelper>;30643065  constructor(logger?: ILogger, options: {[key: string]: any} = {}) {3066    super(logger, options.helperBase ?? RelayHelper);30673068    this.balance = new SubstrateBalanceGroup(this);3069    this.xcm = new XcmGroup(this, 'xcmPallet');3070  }3071}30723073export class WestmintHelper extends XcmChainHelper {3074  balance: SubstrateBalanceGroup<WestmintHelper>;3075  xcm: XcmGroup<WestmintHelper>;3076  assets: AssetsGroup<WestmintHelper>;3077  xTokens: XTokensGroup<WestmintHelper>;30783079  constructor(logger?: ILogger, options: {[key: string]: any} = {}) {3080    super(logger, options.helperBase ?? WestmintHelper);30813082    this.balance = new SubstrateBalanceGroup(this);3083    this.xcm = new XcmGroup(this, 'polkadotXcm');3084    this.assets = new AssetsGroup(this);3085    this.xTokens = new XTokensGroup(this);3086  }3087}30883089export class MoonbeamHelper extends XcmChainHelper {3090  balance: EthereumBalanceGroup<MoonbeamHelper>;3091  assetManager: MoonbeamAssetManagerGroup;3092  assets: AssetsGroup<MoonbeamHelper>;3093  xTokens: XTokensGroup<MoonbeamHelper>;3094  democracy: MoonbeamDemocracyGroup;3095  collective: {3096    council: MoonbeamCollectiveGroup,3097    techCommittee: MoonbeamCollectiveGroup,3098  };30993100  constructor(logger?: ILogger, options: {[key: string]: any} = {}) {3101    super(logger, options.helperBase ?? MoonbeamHelper);31023103    this.balance = new EthereumBalanceGroup(this);3104    this.assetManager = new MoonbeamAssetManagerGroup(this);3105    this.assets = new AssetsGroup(this);3106    this.xTokens = new XTokensGroup(this);3107    this.democracy = new MoonbeamDemocracyGroup(this, options);3108    this.collective = {3109      council: new MoonbeamCollectiveGroup(this, 'councilCollective'),3110      techCommittee: new MoonbeamCollectiveGroup(this, 'techCommitteeCollective'),3111    };3112  }3113}31143115export class AcalaHelper extends XcmChainHelper {3116  balance: SubstrateBalanceGroup<AcalaHelper>;3117  assetRegistry: AcalaAssetRegistryGroup;3118  xTokens: XTokensGroup<AcalaHelper>;3119  tokens: TokensGroup<AcalaHelper>;31203121  constructor(logger?: ILogger, options: {[key: string]: any} = {}) {3122    super(logger, options.helperBase ?? AcalaHelper);31233124    this.balance = new SubstrateBalanceGroup(this);3125    this.assetRegistry = new AcalaAssetRegistryGroup(this);3126    this.xTokens = new XTokensGroup(this);3127    this.tokens = new TokensGroup(this);3128  }31293130  getSudo<T extends AcalaHelper>() {3131    // eslint-disable-next-line @typescript-eslint/naming-convention3132    const SudoHelperType = SudoHelper(this.helperBase);3133    return this.clone(SudoHelperType) as T;3134  }3135}31363137// eslint-disable-next-line @typescript-eslint/naming-convention3138function ScheduledUniqueHelper<T extends UniqueHelperConstructor>(Base: T) {3139  return class extends Base {3140    scheduleFn: 'schedule' | 'scheduleAfter';3141    blocksNum: number;3142    options: ISchedulerOptions;31433144    constructor(...args: any[]) {3145      const logger = args[0] as ILogger;3146      const options = args[1] as {3147        scheduleFn: 'schedule' | 'scheduleAfter',3148        blocksNum: number,3149        options: ISchedulerOptions3150      };31513152      super(logger);31533154      this.scheduleFn = options.scheduleFn;3155      this.blocksNum = options.blocksNum;3156      this.options = options.options;3157    }31583159    executeExtrinsic(sender: IKeyringPair, scheduledExtrinsic: string, scheduledParams: any[], expectSuccess?: boolean): Promise<ITransactionResult> {3160      const scheduledTx = this.constructApiCall(scheduledExtrinsic, scheduledParams);31613162      const mandatorySchedArgs = [3163        this.blocksNum,3164        this.options.periodic ? [this.options.periodic.period, this.options.periodic.repetitions] : null,3165        this.options.priority ?? null,3166        scheduledTx,3167      ];31683169      let schedArgs;3170      let scheduleFn;31713172      if (this.options.scheduledId) {3173        schedArgs = [this.options.scheduledId!, ...mandatorySchedArgs];31743175        if (this.scheduleFn == 'schedule') {3176          scheduleFn = 'scheduleNamed';3177        } else if (this.scheduleFn == 'scheduleAfter') {3178          scheduleFn = 'scheduleNamedAfter';3179        }3180      } else {3181        schedArgs = mandatorySchedArgs;3182        scheduleFn = this.scheduleFn;3183      }31843185      const extrinsic = 'api.tx.scheduler.' +  scheduleFn;31863187      return super.executeExtrinsic(3188        sender,3189        extrinsic,3190        schedArgs,3191        expectSuccess,3192      );3193    }3194  };3195}31963197// eslint-disable-next-line @typescript-eslint/naming-convention3198function SudoHelper<T extends ChainHelperBaseConstructor>(Base: T) {3199  return class extends Base {3200    constructor(...args: any[]) {3201      super(...args);3202    }32033204    async executeExtrinsic(3205      sender: IKeyringPair,3206      extrinsic: string,3207      params: any[],3208      expectSuccess?: boolean,3209      options: Partial<SignerOptions>|null = null,3210    ): Promise<ITransactionResult> {3211      const call = this.constructApiCall(extrinsic, params);3212      const result = await super.executeExtrinsic(3213        sender,3214        'api.tx.sudo.sudo',3215        [call],3216        expectSuccess,3217        options,3218      );32193220      if (result.status === 'Fail') return result;32213222      const data = (result.result.events.find(x => x.event.section == 'sudo' && x.event.method == 'Sudid')?.event.data as any).sudoResult;3223      if (data.isErr) {3224        if (data.asErr.isModule) {3225          const error = (result.result.events[1].event.data as any).sudoResult.asErr.asModule;3226          const metaError = super.getApi()?.registry.findMetaError(error);3227          throw new Error(`${metaError.section}.${metaError.name}`);3228        } else {3229          throw new Error(data.asErr.toHuman());3230        }3231      }3232      return result;3233    }3234  };3235}32363237export class UniqueBaseCollection {3238  helper: UniqueHelper;3239  collectionId: number;32403241  constructor(collectionId: number, uniqueHelper: UniqueHelper) {3242    this.collectionId = collectionId;3243    this.helper = uniqueHelper;3244  }32453246  async getData() {3247    return await this.helper.collection.getData(this.collectionId);3248  }32493250  async getLastTokenId() {3251    return await this.helper.collection.getLastTokenId(this.collectionId);3252  }32533254  async doesTokenExist(tokenId: number) {3255    return await this.helper.collection.doesTokenExist(this.collectionId, tokenId);3256  }32573258  async getAdmins() {3259    return await this.helper.collection.getAdmins(this.collectionId);3260  }32613262  async getAllowList() {3263    return await this.helper.collection.getAllowList(this.collectionId);3264  }32653266  async getEffectiveLimits() {3267    return await this.helper.collection.getEffectiveLimits(this.collectionId);3268  }32693270  async getProperties(propertyKeys?: string[] | null) {3271    return await this.helper.collection.getProperties(this.collectionId, propertyKeys);3272  }32733274  async getPropertiesConsumedSpace() {3275    return await this.helper.collection.getPropertiesConsumedSpace(this.collectionId);3276  }32773278  async getTokenNextSponsored(tokenId: number, addressObj: ICrossAccountId) {3279    return await this.helper.collection.getTokenNextSponsored(this.collectionId, tokenId, addressObj);3280  }32813282  async getOptions() {3283    return await this.helper.collection.getCollectionOptions(this.collectionId);3284  }32853286  async setSponsor(signer: TSigner, sponsorAddress: TSubstrateAccount) {3287    return await this.helper.collection.setSponsor(signer, this.collectionId, sponsorAddress);3288  }32893290  async confirmSponsorship(signer: TSigner) {3291    return await this.helper.collection.confirmSponsorship(signer, this.collectionId);3292  }32933294  async removeSponsor(signer: TSigner) {3295    return await this.helper.collection.removeSponsor(signer, this.collectionId);3296  }32973298  async setLimits(signer: TSigner, limits: ICollectionLimits) {3299    return await this.helper.collection.setLimits(signer, this.collectionId, limits);3300  }33013302  async changeOwner(signer: TSigner, ownerAddress: TSubstrateAccount) {3303    return await this.helper.collection.changeOwner(signer, this.collectionId, ownerAddress);3304  }33053306  async addAdmin(signer: TSigner, adminAddressObj: ICrossAccountId) {3307    return await this.helper.collection.addAdmin(signer, this.collectionId, adminAddressObj);3308  }33093310  async addToAllowList(signer: TSigner, addressObj: ICrossAccountId) {3311    return await this.helper.collection.addToAllowList(signer, this.collectionId, addressObj);3312  }33133314  async removeFromAllowList(signer: TSigner, addressObj: ICrossAccountId) {3315    return await this.helper.collection.removeFromAllowList(signer, this.collectionId, addressObj);3316  }33173318  async removeAdmin(signer: TSigner, adminAddressObj: ICrossAccountId) {3319    return await this.helper.collection.removeAdmin(signer, this.collectionId, adminAddressObj);3320  }33213322  async setProperties(signer: TSigner, properties: IProperty[]) {3323    return await this.helper.collection.setProperties(signer, this.collectionId, properties);3324  }33253326  async deleteProperties(signer: TSigner, propertyKeys: string[]) {3327    return await this.helper.collection.deleteProperties(signer, this.collectionId, propertyKeys);3328  }33293330  async setPermissions(signer: TSigner, permissions: ICollectionPermissions) {3331    return await this.helper.collection.setPermissions(signer, this.collectionId, permissions);3332  }33333334  async enableNesting(signer: TSigner, permissions: INestingPermissions) {3335    return await this.helper.collection.enableNesting(signer, this.collectionId, permissions);3336  }33373338  async disableNesting(signer: TSigner) {3339    return await this.helper.collection.disableNesting(signer, this.collectionId);3340  }33413342  async burn(signer: TSigner) {3343    return await this.helper.collection.burn(signer, this.collectionId);3344  }33453346  scheduleAt<T extends UniqueHelper>(3347    executionBlockNumber: number,3348    options: ISchedulerOptions = {},3349  ) {3350    const scheduledHelper = this.helper.scheduler.scheduleAt<T>(executionBlockNumber, options);3351    return new UniqueBaseCollection(this.collectionId, scheduledHelper);3352  }33533354  scheduleAfter<T extends UniqueHelper>(3355    blocksBeforeExecution: number,3356    options: ISchedulerOptions = {},3357  ) {3358    const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(blocksBeforeExecution, options);3359    return new UniqueBaseCollection(this.collectionId, scheduledHelper);3360  }33613362  getSudo<T extends UniqueHelper>() {3363    return new UniqueBaseCollection(this.collectionId, this.helper.getSudo<T>());3364  }3365}336633673368export class UniqueNFTCollection extends UniqueBaseCollection {3369  getTokenObject(tokenId: number) {3370    return new UniqueNFToken(tokenId, this);3371  }33723373  async getTokensByAddress(addressObj: ICrossAccountId) {3374    return await this.helper.nft.getTokensByAddress(this.collectionId, addressObj);3375  }33763377  async getToken(tokenId: number, blockHashAt?: string) {3378    return await this.helper.nft.getToken(this.collectionId, tokenId, [], blockHashAt);3379  }33803381  async getTokenOwner(tokenId: number, blockHashAt?: string) {3382    return await this.helper.nft.getTokenOwner(this.collectionId, tokenId, blockHashAt);3383  }33843385  async getTokenTopmostOwner(tokenId: number, blockHashAt?: string) {3386    return await this.helper.nft.getTokenTopmostOwner(this.collectionId, tokenId, blockHashAt);3387  }33883389  async getTokenChildren(tokenId: number, blockHashAt?: string) {3390    return await this.helper.nft.getTokenChildren(this.collectionId, tokenId, blockHashAt);3391  }33923393  async getPropertyPermissions(propertyKeys: string[] | null = null) {3394    return await this.helper.nft.getPropertyPermissions(this.collectionId, propertyKeys);3395  }33963397  async getTokenProperties(tokenId: number, propertyKeys?: string[] | null) {3398    return await this.helper.nft.getTokenProperties(this.collectionId, tokenId, propertyKeys);3399  }34003401  async getTokenPropertiesConsumedSpace(tokenId: number): Promise<number> {3402    const api = this.helper.getApi();3403    const props = (await api.query.nonfungible.tokenProperties(this.collectionId, tokenId)).toJSON();34043405    return (props! as any).consumedSpace;3406  }34073408  async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId) {3409    return await this.helper.nft.transferToken(signer, this.collectionId, tokenId, addressObj);3410  }34113412  async transferTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {3413    return await this.helper.nft.transferTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, toAddressObj);3414  }34153416  async approveToken(signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId) {3417    return await this.helper.nft.approveToken(signer, this.collectionId, tokenId, toAddressObj);3418  }34193420  async isTokenApproved(tokenId: number, toAddressObj: ICrossAccountId) {3421    return await this.helper.nft.isTokenApproved(this.collectionId, tokenId, toAddressObj);3422  }34233424  async mintToken(signer: TSigner, owner: ICrossAccountId = {Substrate: signer.address}, properties?: IProperty[]) {3425    return await this.helper.nft.mintToken(signer, {collectionId: this.collectionId, owner, properties});3426  }34273428  async mintMultipleTokens(signer: TSigner, tokens: {owner: ICrossAccountId, properties?: IProperty[]}[]) {3429    return await this.helper.nft.mintMultipleTokens(signer, this.collectionId, tokens);3430  }34313432  async burnToken(signer: TSigner, tokenId: number) {3433    return await this.helper.nft.burnToken(signer, this.collectionId, tokenId);3434  }34353436  async burnTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId) {3437    return await this.helper.nft.burnTokenFrom(signer, this.collectionId, tokenId, fromAddressObj);3438  }34393440  async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[]) {3441    return await this.helper.nft.setTokenProperties(signer, this.collectionId, tokenId, properties);3442  }34433444  async deleteTokenProperties(signer: TSigner, tokenId: number, propertyKeys: string[]) {3445    return await this.helper.nft.deleteTokenProperties(signer, this.collectionId, tokenId, propertyKeys);3446  }34473448  async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[]) {3449    return await this.helper.nft.setTokenPropertyPermissions(signer, this.collectionId, permissions);3450  }34513452  async nestToken(signer: TSigner, tokenId: number, toTokenObj: IToken) {3453    return await this.helper.nft.nestToken(signer, {collectionId: this.collectionId, tokenId}, toTokenObj);3454  }34553456  async unnestToken(signer: TSigner, tokenId: number, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {3457    return await this.helper.nft.unnestToken(signer, {collectionId: this.collectionId, tokenId}, fromTokenObj, toAddressObj);3458  }34593460  scheduleAt<T extends UniqueHelper>(3461    executionBlockNumber: number,3462    options: ISchedulerOptions = {},3463  ) {3464    const scheduledHelper = this.helper.scheduler.scheduleAt<T>(executionBlockNumber, options);3465    return new UniqueNFTCollection(this.collectionId, scheduledHelper);3466  }34673468  scheduleAfter<T extends UniqueHelper>(3469    blocksBeforeExecution: number,3470    options: ISchedulerOptions = {},3471  ) {3472    const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(blocksBeforeExecution, options);3473    return new UniqueNFTCollection(this.collectionId, scheduledHelper);3474  }34753476  getSudo<T extends UniqueHelper>() {3477    return new UniqueNFTCollection(this.collectionId, this.helper.getSudo<T>());3478  }3479}348034813482export class UniqueRFTCollection extends UniqueBaseCollection {3483  getTokenObject(tokenId: number) {3484    return new UniqueRFToken(tokenId, this);3485  }34863487  async getToken(tokenId: number, blockHashAt?: string) {3488    return await this.helper.rft.getToken(this.collectionId, tokenId, [], blockHashAt);3489  }34903491  async getTokensByAddress(addressObj: ICrossAccountId) {3492    return await this.helper.rft.getTokensByAddress(this.collectionId, addressObj);3493  }34943495  async getTop10TokenOwners(tokenId: number) {3496    return await this.helper.rft.getTokenTop10Owners(this.collectionId, tokenId);3497  }34983499  async getTokenBalance(tokenId: number, addressObj: ICrossAccountId) {3500    return await this.helper.rft.getTokenBalance(this.collectionId, tokenId, addressObj);3501  }35023503  async getTokenTotalPieces(tokenId: number) {3504    return await this.helper.rft.getTokenTotalPieces(this.collectionId, tokenId);3505  }35063507  async getTokenApprovedPieces(tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {3508    return await this.helper.rft.getTokenApprovedPieces(this.collectionId, tokenId, toAddressObj, fromAddressObj);3509  }35103511  async getPropertyPermissions(propertyKeys: string[] | null = null) {3512    return await this.helper.rft.getPropertyPermissions(this.collectionId, propertyKeys);3513  }35143515  async getTokenProperties(tokenId: number, propertyKeys?: string[] | null) {3516    return await this.helper.rft.getTokenProperties(this.collectionId, tokenId, propertyKeys);3517  }35183519  async getTokenPropertiesConsumedSpace(tokenId: number): Promise<number> {3520    const api = this.helper.getApi();3521    const props = (await api.query.refungible.tokenProperties(this.collectionId, tokenId)).toJSON();35223523    return (props! as any).consumedSpace;3524  }35253526  async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId, amount=1n) {3527    return await this.helper.rft.transferToken(signer, this.collectionId, tokenId, addressObj, amount);3528  }35293530  async transferTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {3531    return await this.helper.rft.transferTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, toAddressObj, amount);3532  }35333534  async approveToken(signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {3535    return await this.helper.rft.approveToken(signer, this.collectionId, tokenId, toAddressObj, amount);3536  }35373538  async repartitionToken(signer: TSigner, tokenId: number, amount: bigint) {3539    return await this.helper.rft.repartitionToken(signer, this.collectionId, tokenId, amount);3540  }35413542  async mintToken(signer: TSigner, pieces=1n, owner: ICrossAccountId = {Substrate: signer.address}, properties?: IProperty[]) {3543    return await this.helper.rft.mintToken(signer, {collectionId: this.collectionId, owner, pieces, properties});3544  }35453546  async mintMultipleTokens(signer: TSigner, tokens: {pieces: bigint, owner: ICrossAccountId, properties?: IProperty[]}[]) {3547    return await this.helper.rft.mintMultipleTokens(signer, this.collectionId, tokens);3548  }35493550  async burnToken(signer: TSigner, tokenId: number, amount=1n) {3551    return await this.helper.rft.burnToken(signer, this.collectionId, tokenId, amount);3552  }35533554  async burnTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId,  amount=1n) {3555    return await this.helper.rft.burnTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, amount);3556  }35573558  async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[]) {3559    return await this.helper.rft.setTokenProperties(signer, this.collectionId, tokenId, properties);3560  }35613562  async deleteTokenProperties(signer: TSigner, tokenId: number, propertyKeys: string[]) {3563    return await this.helper.rft.deleteTokenProperties(signer, this.collectionId, tokenId, propertyKeys);3564  }35653566  async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[]) {3567    return await this.helper.rft.setTokenPropertyPermissions(signer, this.collectionId, permissions);3568  }35693570  scheduleAt<T extends UniqueHelper>(3571    executionBlockNumber: number,3572    options: ISchedulerOptions = {},3573  ) {3574    const scheduledHelper = this.helper.scheduler.scheduleAt<T>(executionBlockNumber, options);3575    return new UniqueRFTCollection(this.collectionId, scheduledHelper);3576  }35773578  scheduleAfter<T extends UniqueHelper>(3579    blocksBeforeExecution: number,3580    options: ISchedulerOptions = {},3581  ) {3582    const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(blocksBeforeExecution, options);3583    return new UniqueRFTCollection(this.collectionId, scheduledHelper);3584  }35853586  getSudo<T extends UniqueHelper>() {3587    return new UniqueRFTCollection(this.collectionId, this.helper.getSudo<T>());3588  }3589}359035913592export class UniqueFTCollection extends UniqueBaseCollection {3593  async getBalance(addressObj: ICrossAccountId) {3594    return await this.helper.ft.getBalance(this.collectionId, addressObj);3595  }35963597  async getTotalPieces() {3598    return await this.helper.ft.getTotalPieces(this.collectionId);3599  }36003601  async getApprovedTokens(fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {3602    return await this.helper.ft.getApprovedTokens(this.collectionId, fromAddressObj, toAddressObj);3603  }36043605  async getTop10Owners() {3606    return await this.helper.ft.getTop10Owners(this.collectionId);3607  }36083609  async mint(signer: TSigner, amount=1n, owner: ICrossAccountId = {Substrate: signer.address}) {3610    return await this.helper.ft.mintTokens(signer, this.collectionId, amount, owner);3611  }36123613  async mintWithOneOwner(signer: TSigner, tokens: {value: bigint}[], owner: ICrossAccountId = {Substrate: signer.address}) {3614    return await this.helper.ft.mintMultipleTokensWithOneOwner(signer, this.collectionId, tokens, owner);3615  }36163617  async transfer(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {3618    return await this.helper.ft.transfer(signer, this.collectionId, toAddressObj, amount);3619  }36203621  async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {3622    return await this.helper.ft.transferFrom(signer, this.collectionId, fromAddressObj, toAddressObj, amount);3623  }36243625  async burnTokens(signer: TSigner, amount=1n) {3626    return await this.helper.ft.burnTokens(signer, this.collectionId, amount);3627  }36283629  async burnTokensFrom(signer: TSigner, fromAddressObj: ICrossAccountId, amount=1n) {3630    return await this.helper.ft.burnTokensFrom(signer, this.collectionId, fromAddressObj, amount);3631  }36323633  async approveTokens(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {3634    return await this.helper.ft.approveTokens(signer, this.collectionId, toAddressObj, amount);3635  }36363637  scheduleAt<T extends UniqueHelper>(3638    executionBlockNumber: number,3639    options: ISchedulerOptions = {},3640  ) {3641    const scheduledHelper = this.helper.scheduler.scheduleAt<T>(executionBlockNumber, options);3642    return new UniqueFTCollection(this.collectionId, scheduledHelper);3643  }36443645  scheduleAfter<T extends UniqueHelper>(3646    blocksBeforeExecution: number,3647    options: ISchedulerOptions = {},3648  ) {3649    const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(blocksBeforeExecution, options);3650    return new UniqueFTCollection(this.collectionId, scheduledHelper);3651  }36523653  getSudo<T extends UniqueHelper>() {3654    return new UniqueFTCollection(this.collectionId, this.helper.getSudo<T>());3655  }3656}365736583659export class UniqueBaseToken {3660  collection: UniqueNFTCollection | UniqueRFTCollection;3661  collectionId: number;3662  tokenId: number;36633664  constructor(tokenId: number, collection: UniqueNFTCollection | UniqueRFTCollection) {3665    this.collection = collection;3666    this.collectionId = collection.collectionId;3667    this.tokenId = tokenId;3668  }36693670  async getNextSponsored(addressObj: ICrossAccountId) {3671    return await this.collection.getTokenNextSponsored(this.tokenId, addressObj);3672  }36733674  async getProperties(propertyKeys?: string[] | null) {3675    return await this.collection.getTokenProperties(this.tokenId, propertyKeys);3676  }36773678  async getTokenPropertiesConsumedSpace() {3679    return await this.collection.getTokenPropertiesConsumedSpace(this.tokenId);3680  }36813682  async setProperties(signer: TSigner, properties: IProperty[]) {3683    return await this.collection.setTokenProperties(signer, this.tokenId, properties);3684  }36853686  async deleteProperties(signer: TSigner, propertyKeys: string[]) {3687    return await this.collection.deleteTokenProperties(signer, this.tokenId, propertyKeys);3688  }36893690  async doesExist() {3691    return await this.collection.doesTokenExist(this.tokenId);3692  }36933694  nestingAccount() {3695    return this.collection.helper.util.getTokenAccount(this);3696  }36973698  scheduleAt<T extends UniqueHelper>(3699    executionBlockNumber: number,3700    options: ISchedulerOptions = {},3701  ) {3702    const scheduledCollection = this.collection.scheduleAt<T>(executionBlockNumber, options);3703    return new UniqueBaseToken(this.tokenId, scheduledCollection);3704  }37053706  scheduleAfter<T extends UniqueHelper>(3707    blocksBeforeExecution: number,3708    options: ISchedulerOptions = {},3709  ) {3710    const scheduledCollection = this.collection.scheduleAfter<T>(blocksBeforeExecution, options);3711    return new UniqueBaseToken(this.tokenId, scheduledCollection);3712  }37133714  getSudo<T extends UniqueHelper>() {3715    return new UniqueBaseToken(this.tokenId, this.collection.getSudo<T>());3716  }3717}371837193720export class UniqueNFToken extends UniqueBaseToken {3721  collection: UniqueNFTCollection;37223723  constructor(tokenId: number, collection: UniqueNFTCollection) {3724    super(tokenId, collection);3725    this.collection = collection;3726  }37273728  async getData(blockHashAt?: string) {3729    return await this.collection.getToken(this.tokenId, blockHashAt);3730  }37313732  async getOwner(blockHashAt?: string) {3733    return await this.collection.getTokenOwner(this.tokenId, blockHashAt);3734  }37353736  async getTopmostOwner(blockHashAt?: string) {3737    return await this.collection.getTokenTopmostOwner(this.tokenId, blockHashAt);3738  }37393740  async getChildren(blockHashAt?: string) {3741    return await this.collection.getTokenChildren(this.tokenId, blockHashAt);3742  }37433744  async nest(signer: TSigner, toTokenObj: IToken) {3745    return await this.collection.nestToken(signer, this.tokenId, toTokenObj);3746  }37473748  async unnest(signer: TSigner, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {3749    return await this.collection.unnestToken(signer, this.tokenId, fromTokenObj, toAddressObj);3750  }37513752  async transfer(signer: TSigner, addressObj: ICrossAccountId) {3753    return await this.collection.transferToken(signer, this.tokenId, addressObj);3754  }37553756  async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {3757    return await this.collection.transferTokenFrom(signer, this.tokenId, fromAddressObj, toAddressObj);3758  }37593760  async approve(signer: TSigner, toAddressObj: ICrossAccountId) {3761    return await this.collection.approveToken(signer, this.tokenId, toAddressObj);3762  }37633764  async isApproved(toAddressObj: ICrossAccountId) {3765    return await this.collection.isTokenApproved(this.tokenId, toAddressObj);3766  }37673768  async burn(signer: TSigner) {3769    return await this.collection.burnToken(signer, this.tokenId);3770  }37713772  async burnFrom(signer: TSigner, fromAddressObj: ICrossAccountId) {3773    return await this.collection.burnTokenFrom(signer, this.tokenId, fromAddressObj);3774  }37753776  scheduleAt<T extends UniqueHelper>(3777    executionBlockNumber: number,3778    options: ISchedulerOptions = {},3779  ) {3780    const scheduledCollection = this.collection.scheduleAt<T>(executionBlockNumber, options);3781    return new UniqueNFToken(this.tokenId, scheduledCollection);3782  }37833784  scheduleAfter<T extends UniqueHelper>(3785    blocksBeforeExecution: number,3786    options: ISchedulerOptions = {},3787  ) {3788    const scheduledCollection = this.collection.scheduleAfter<T>(blocksBeforeExecution, options);3789    return new UniqueNFToken(this.tokenId, scheduledCollection);3790  }37913792  getSudo<T extends UniqueHelper>() {3793    return new UniqueNFToken(this.tokenId, this.collection.getSudo<T>());3794  }3795}37963797export class UniqueRFToken extends UniqueBaseToken {3798  collection: UniqueRFTCollection;37993800  constructor(tokenId: number, collection: UniqueRFTCollection) {3801    super(tokenId, collection);3802    this.collection = collection;3803  }38043805  async getData(blockHashAt?: string) {3806    return await this.collection.getToken(this.tokenId, blockHashAt);3807  }38083809  async getTop10Owners() {3810    return await this.collection.getTop10TokenOwners(this.tokenId);3811  }38123813  async getBalance(addressObj: ICrossAccountId) {3814    return await this.collection.getTokenBalance(this.tokenId, addressObj);3815  }38163817  async getTotalPieces() {3818    return await this.collection.getTokenTotalPieces(this.tokenId);3819  }38203821  async getApprovedPieces(fromAddressObj: ICrossAccountId, toAccountObj: ICrossAccountId) {3822    return await this.collection.getTokenApprovedPieces(this.tokenId, fromAddressObj, toAccountObj);3823  }38243825  async transfer(signer: TSigner, addressObj: ICrossAccountId, amount=1n) {3826    return await this.collection.transferToken(signer, this.tokenId, addressObj, amount);3827  }38283829  async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {3830    return await this.collection.transferTokenFrom(signer, this.tokenId, fromAddressObj, toAddressObj, amount);3831  }38323833  async approve(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {3834    return await this.collection.approveToken(signer, this.tokenId, toAddressObj, amount);3835  }38363837  async repartition(signer: TSigner, amount: bigint) {3838    return await this.collection.repartitionToken(signer, this.tokenId, amount);3839  }38403841  async burn(signer: TSigner, amount=1n) {3842    return await this.collection.burnToken(signer, this.tokenId, amount);3843  }38443845  async burnFrom(signer: TSigner, fromAddressObj: ICrossAccountId, amount=1n) {3846    return await this.collection.burnTokenFrom(signer, this.tokenId, fromAddressObj, amount);3847  }38483849  scheduleAt<T extends UniqueHelper>(3850    executionBlockNumber: number,3851    options: ISchedulerOptions = {},3852  ) {3853    const scheduledCollection = this.collection.scheduleAt<T>(executionBlockNumber, options);3854    return new UniqueRFToken(this.tokenId, scheduledCollection);3855  }38563857  scheduleAfter<T extends UniqueHelper>(3858    blocksBeforeExecution: number,3859    options: ISchedulerOptions = {},3860  ) {3861    const scheduledCollection = this.collection.scheduleAfter<T>(blocksBeforeExecution, options);3862    return new UniqueRFToken(this.tokenId, scheduledCollection);3863  }38643865  getSudo<T extends UniqueHelper>() {3866    return new UniqueRFToken(this.tokenId, this.collection.getSudo<T>());3867  }3868}
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, base58Encode, blake2AsU8a} from '@polkadot/util-crypto';11import {IKeyringPair} from '@polkadot/types/types';12import {hexToU8a} from '@polkadot/util/hex';13import {u8aConcat} from '@polkadot/util/u8a';14import {15  IApiListeners,16  IBlock,17  IEvent,18  IChainProperties,19  ICollectionCreationOptions,20  ICollectionLimits,21  ICollectionPermissions,22  ICrossAccountId,23  ICrossAccountIdLower,24  ILogger,25  INestingPermissions,26  IProperty,27  IStakingInfo,28  ISchedulerOptions,29  ISubstrateBalance,30  IToken,31  ITokenPropertyPermission,32  ITransactionResult,33  IUniqueHelperLog,34  TApiAllowedListeners,35  TEthereumAccount,36  TSigner,37  TSubstrateAccount,38  TNetworks,39  IForeignAssetMetadata,40  AcalaAssetMetadata,41  MoonbeamAssetInfo,42  DemocracyStandardAccountVote,43  IEthCrossAccountId,44} from './types';45import {RuntimeDispatchInfo} from '@polkadot/types/interfaces';46import type {Vec} from '@polkadot/types-codec';47import {FrameSystemEventRecord} from '@polkadot/types/lookup';4849export class CrossAccountId implements ICrossAccountId {50  Substrate?: TSubstrateAccount;51  Ethereum?: TEthereumAccount;5253  constructor(account: ICrossAccountId) {54    if (account.Substrate) this.Substrate = account.Substrate;55    if (account.Ethereum) this.Ethereum = account.Ethereum;56  }5758  static fromKeyring(account: IKeyringPair, domain: 'Substrate' | 'Ethereum' = 'Substrate') {59    switch (domain) {60      case 'Substrate': return new CrossAccountId({Substrate: account.address});61      case 'Ethereum': return new CrossAccountId({Substrate: account.address}).toEthereum();62    }63  }6465  static fromLowerCaseKeys(address: ICrossAccountIdLower): CrossAccountId {66    return new CrossAccountId({Substrate: address.substrate, Ethereum: address.ethereum});67  }6869  static normalizeSubstrateAddress(address: TSubstrateAccount, ss58Format = 42): TSubstrateAccount {70    return encodeAddress(decodeAddress(address), ss58Format);71  }7273  static withNormalizedSubstrate(address: TSubstrateAccount, ss58Format = 42): CrossAccountId {74    return new CrossAccountId({Substrate: CrossAccountId.normalizeSubstrateAddress(address, ss58Format)});75  }7677  withNormalizedSubstrate(ss58Format = 42): CrossAccountId {78    if (this.Substrate) return CrossAccountId.withNormalizedSubstrate(this.Substrate, ss58Format);79    return this;80  }8182  static translateSubToEth(address: TSubstrateAccount): TEthereumAccount {83    return nesting.toChecksumAddress('0x' + Array.from(addressToEvm(address), i => i.toString(16).padStart(2, '0')).join(''));84  }8586  toEthereum(): CrossAccountId {87    if (this.Substrate) return new CrossAccountId({Ethereum: CrossAccountId.translateSubToEth(this.Substrate)});88    return this;89  }9091  static translateEthToSub(address: TEthereumAccount, ss58Format?: number): TSubstrateAccount {92    return evmToAddress(address, ss58Format);93  }9495  toSubstrate(ss58Format?: number): CrossAccountId {96    if (this.Ethereum) return new CrossAccountId({Substrate: CrossAccountId.translateEthToSub(this.Ethereum, ss58Format)});97    return this;98  }99100  toLowerCase(): CrossAccountId {101    if (this.Substrate) this.Substrate = this.Substrate.toLowerCase();102    if (this.Ethereum) this.Ethereum = this.Ethereum.toLowerCase();103    return this;104  }105}106107const nesting = {108  toChecksumAddress(address: string): string {109    if (typeof address === 'undefined') return '';110111    if(!/^(0x)?[0-9a-f]{40}$/i.test(address)) throw new Error(`Given address "${address}" is not a valid Ethereum address.`);112113    address = address.toLowerCase().replace(/^0x/i,'');114    const addressHash = keccakAsHex(address).replace(/^0x/i,'');115    const checksumAddress = ['0x'];116117    for (let i = 0; i < address.length; i++) {118      // If ith character is 8 to f then make it uppercase119      if (parseInt(addressHash[i], 16) > 7) {120        checksumAddress.push(address[i].toUpperCase());121      } else {122        checksumAddress.push(address[i]);123      }124    }125    return checksumAddress.join('');126  },127  tokenIdToAddress(collectionId: number, tokenId: number) {128    return this.toChecksumAddress(`0xf8238ccfff8ed887463fd5e0${collectionId.toString(16).padStart(8, '0')}${tokenId.toString(16).padStart(8, '0')}`);129  },130};131132class UniqueUtil {133  static transactionStatus = {134    NOT_READY: 'NotReady',135    FAIL: 'Fail',136    SUCCESS: 'Success',137  };138139  static chainLogType = {140    EXTRINSIC: 'extrinsic',141    RPC: 'rpc',142  };143144  static getTokenAccount(token: IToken): CrossAccountId {145    return new CrossAccountId({Ethereum: this.getTokenAddress(token)});146  }147148  static getTokenAddress(token: IToken): string {149    return nesting.tokenIdToAddress(token.collectionId, token.tokenId);150  }151152  static getDefaultLogger(): ILogger {153    return {154      log(msg: any, level = 'INFO') {155        console[level.toLocaleLowerCase() === 'error' ? 'error' : 'log'](...(Array.isArray(msg) ? msg : [msg]));156      },157      level: {158        ERROR: 'ERROR',159        WARNING: 'WARNING',160        INFO: 'INFO',161      },162    };163  }164165  static vec2str(arr: string[] | number[]) {166    return arr.map(x => String.fromCharCode(parseInt(x.toString()))).join('');167  }168169  static str2vec(string: string) {170    if (typeof string !== 'string') return string;171    return Array.from(string).map(x => x.charCodeAt(0));172  }173174  static fromSeed(seed: string, ss58Format = 42) {175    const keyring = new Keyring({type: 'sr25519', ss58Format});176    return keyring.addFromUri(seed);177  }178179  static extractCollectionIdFromCreationResult(creationResult: ITransactionResult): number {180    if (creationResult.status !== this.transactionStatus.SUCCESS) {181      throw Error('Unable to create collection!');182    }183184    let collectionId = null;185    creationResult.result.events.forEach(({event: {data, method, section}}) => {186      if ((section === 'common') && (method === 'CollectionCreated')) {187        collectionId = parseInt(data[0].toString(), 10);188      }189    });190191    if (collectionId === null) {192      throw Error('No CollectionCreated event was found!');193    }194195    return collectionId;196  }197198  static extractTokensFromCreationResult(creationResult: ITransactionResult): {199    success: boolean,200    tokens: {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[],201  } {202    if (creationResult.status !== this.transactionStatus.SUCCESS) {203      throw Error('Unable to create tokens!');204    }205    let success = false;206    const tokens = [] as {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[];207    creationResult.result.events.forEach(({event: {data, method, section}}) => {208      if (method === 'ExtrinsicSuccess') {209        success = true;210      } else if ((section === 'common') && (method === 'ItemCreated')) {211        tokens.push({212          collectionId: parseInt(data[0].toString(), 10),213          tokenId: parseInt(data[1].toString(), 10),214          owner: data[2].toHuman(),215          amount: data[3].toBigInt(),216        });217      }218    });219    return {success, tokens};220  }221222  static extractTokensFromBurnResult(burnResult: ITransactionResult): {223    success: boolean,224    tokens: {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[],225  } {226    if (burnResult.status !== this.transactionStatus.SUCCESS) {227      throw Error('Unable to burn tokens!');228    }229    let success = false;230    const tokens = [] as {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[];231    burnResult.result.events.forEach(({event: {data, method, section}}) => {232      if (method === 'ExtrinsicSuccess') {233        success = true;234      } else if ((section === 'common') && (method === 'ItemDestroyed')) {235        tokens.push({236          collectionId: parseInt(data[0].toString(), 10),237          tokenId: parseInt(data[1].toString(), 10),238          owner: data[2].toHuman(),239          amount: data[3].toBigInt(),240        });241      }242    });243    return {success, tokens};244  }245246  static findCollectionInEvents(events: {event: IEvent}[], collectionId: number, expectedSection: string, expectedMethod: string): boolean {247    let eventId = null;248    events.forEach(({event: {data, method, section}}) => {249      if ((section === expectedSection) && (method === expectedMethod)) {250        eventId = parseInt(data[0].toString(), 10);251      }252    });253254    if (eventId === null) {255      throw Error(`No ${expectedMethod} event was found!`);256    }257    return eventId === collectionId;258  }259260  static isTokenTransferSuccess(events: {event: IEvent}[], collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {261    const normalizeAddress = (address: string | ICrossAccountId) => {262      if(typeof address === 'string') return address;263      const obj = {} as any;264      Object.keys(address).forEach(k => {265        obj[k.toLocaleLowerCase()] = address[k as 'Substrate' | 'Ethereum'];266      });267      if(obj.substrate) return CrossAccountId.withNormalizedSubstrate(obj.substrate);268      if(obj.ethereum) return CrossAccountId.fromLowerCaseKeys(obj).toLowerCase();269      return address;270    };271    let transfer = {collectionId: null, tokenId: null, from: null, to: null, amount: 1} as any;272    events.forEach(({event: {data, method, section}}) => {273      if ((section === 'common') && (method === 'Transfer')) {274        const hData = (data as any).toJSON();275        transfer = {276          collectionId: hData[0],277          tokenId: hData[1],278          from: normalizeAddress(hData[2]),279          to: normalizeAddress(hData[3]),280          amount: BigInt(hData[4]),281        };282      }283    });284    let isSuccess = parseInt(collectionId.toString()) === transfer.collectionId && parseInt(tokenId.toString()) === transfer.tokenId;285    isSuccess = isSuccess && JSON.stringify(normalizeAddress(fromAddressObj)) === JSON.stringify(transfer.from);286    isSuccess = isSuccess && JSON.stringify(normalizeAddress(toAddressObj)) === JSON.stringify(transfer.to);287    isSuccess = isSuccess && amount === transfer.amount;288    return isSuccess;289  }290291  static bigIntToDecimals(number: bigint, decimals = 18) {292    const numberStr = number.toString();293    const dotPos = numberStr.length - decimals;294295    if (dotPos <= 0) {296      return '0.' + '0'.repeat(Math.abs(dotPos)) + numberStr;297    } else {298      const intPart = numberStr.substring(0, dotPos);299      const fractPart = numberStr.substring(dotPos);300      return intPart + '.' + fractPart;301    }302  }303}304305class UniqueEventHelper {306  private static extractIndex(index: any): [number, number] | string {307    if(index.toRawType() === '[u8;2]') return [index[0], index[1]];308    return index.toJSON();309  }310311  private static extractSub(data: any, subTypes: any): {[key: string]: any} {312    let obj: any = {};313    let index = 0;314315    if (data.entries) {316      for(const [key, value] of data.entries()) {317        obj[key] = this.extractData(value, subTypes[index]);318        index++;319      }320    } else obj = data.toJSON();321322    return obj;323  }324325  private static toHuman(data: any) {326    return data && data.toHuman ? data.toHuman() : `${data}`;327  }328329  private static extractData(data: any, type: any): any {330    if(!type) return this.toHuman(data);331    if (['u16', 'u32'].indexOf(type.type) > -1) return data.toNumber();332    if (['u64', 'u128', 'u256'].indexOf(type.type) > -1) return data.toBigInt();333    if(type.hasOwnProperty('sub')) return this.extractSub(data, type.sub);334    return this.toHuman(data);335  }336337  public static extractEvents(events: {event: any, phase: any}[]): IEvent[] {338    const parsedEvents: IEvent[] = [];339340    events.forEach((record) => {341      const {event, phase} = record;342      const types = event.typeDef;343344      const eventData: IEvent = {345        section: event.section.toString(),346        method: event.method.toString(),347        index: this.extractIndex(event.index),348        data: [],349        phase: phase.toJSON(),350      };351352      event.data.forEach((val: any, index: number) => {353        eventData.data.push(this.extractData(val, types[index]));354      });355356      parsedEvents.push(eventData);357    });358359    return parsedEvents;360  }361}362363export class ChainHelperBase {364  helperBase: any;365366  transactionStatus = UniqueUtil.transactionStatus;367  chainLogType = UniqueUtil.chainLogType;368  util: typeof UniqueUtil;369  eventHelper: typeof UniqueEventHelper;370  logger: ILogger;371  api: ApiPromise | null;372  forcedNetwork: TNetworks | null;373  network: TNetworks | null;374  wsEndpoint: string | null;375  chainLog: IUniqueHelperLog[];376  children: ChainHelperBase[];377  address: AddressGroup;378  chain: ChainGroup;379380  constructor(logger?: ILogger, helperBase?: any) {381    this.helperBase = helperBase;382383    this.util = UniqueUtil;384    this.eventHelper = UniqueEventHelper;385    if (typeof logger == 'undefined') logger = this.util.getDefaultLogger();386    this.logger = logger;387    this.api = null;388    this.forcedNetwork = null;389    this.network = null;390    this.wsEndpoint = null;391    this.chainLog = [];392    this.children = [];393    this.address = new AddressGroup(this);394    this.chain = new ChainGroup(this);395  }396397  clone(helperCls: ChainHelperBaseConstructor, options: {[key: string]: any} = {}) {398    Object.setPrototypeOf(helperCls.prototype, this);399    const newHelper = new helperCls(this.logger, options);400401    newHelper.api = this.api;402    newHelper.network = this.network;403    newHelper.forceNetwork = this.forceNetwork;404405    this.children.push(newHelper);406407    return newHelper;408  }409410  getEndpoint(): string {411    if (this.wsEndpoint === null) throw Error('No connection was established');412    return this.wsEndpoint;413  }414415  getApi(): ApiPromise {416    if(this.api === null) throw Error('API not initialized');417    return this.api;418  }419420  async subscribeEvents(expectedEvents: {section: string, names: string[]}[]) {421    const collectedEvents: IEvent[] = [];422    const unsubscribe = await this.getApi().query.system.events((events: Vec<FrameSystemEventRecord>) => {423      const ievents = this.eventHelper.extractEvents(events);424      ievents.forEach((event) => {425        expectedEvents.forEach((e => {426          if (event.section === e.section && e.names.includes(event.method)) {427            collectedEvents.push(event);428          }429        }));430      });431    });432    return {unsubscribe: unsubscribe as any, collectedEvents};433  }434435  clearChainLog(): void {436    this.chainLog = [];437  }438439  forceNetwork(value: TNetworks): void {440    this.forcedNetwork = value;441  }442443  async connect(wsEndpoint: string, listeners?: IApiListeners) {444    if (this.api !== null) throw Error('Already connected');445    const {api, network} = await ChainHelperBase.createConnection(wsEndpoint, listeners, this.forcedNetwork);446    this.wsEndpoint = wsEndpoint;447    this.api = api;448    this.network = network;449  }450451  async disconnect() {452    for (const child of this.children) {453      child.clearApi();454    }455456    if (this.api === null) return;457    await this.api.disconnect();458    this.clearApi();459  }460461  clearApi() {462    this.api = null;463    this.network = null;464  }465466  static async detectNetwork(api: ApiPromise): Promise<TNetworks> {467    const spec = (await api.query.system.lastRuntimeUpgrade()).toJSON() as any;468    const xcmChains = ['rococo', 'westend', 'westmint', 'acala', 'karura', 'moonbeam', 'moonriver'];469470    if(xcmChains.indexOf(spec.specName) > -1) return spec.specName;471472    if(['quartz', 'unique'].indexOf(spec.specName) > -1) return spec.specName;473    return 'opal';474  }475476  static async detectNetworkByWsEndpoint(wsEndpoint: string): Promise<TNetworks> {477    const api = new ApiPromise({provider: new WsProvider(wsEndpoint)});478    await api.isReady;479480    const network = await this.detectNetwork(api);481482    await api.disconnect();483484    return network;485  }486487  static async createConnection(wsEndpoint: string, listeners?: IApiListeners, network?: TNetworks | null): Promise<{488    api: ApiPromise;489    network: TNetworks;490  }> {491    if(typeof network === 'undefined' || network === null) network = 'opal';492    const supportedRPC = {493      opal: {494        unique: require('@unique-nft/opal-testnet-types/definitions').unique.rpc,495      },496      quartz: {497        unique: require('@unique-nft/quartz-mainnet-types/definitions').unique.rpc,498      },499      unique: {500        unique: require('@unique-nft/unique-mainnet-types/definitions').unique.rpc,501      },502      rococo: {},503      westend: {},504      moonbeam: {},505      moonriver: {},506      acala: {},507      karura: {},508      westmint: {},509    };510    if(!supportedRPC.hasOwnProperty(network)) network = await this.detectNetworkByWsEndpoint(wsEndpoint);511    const rpc = supportedRPC[network];512513    // TODO: investigate how to replace rpc in runtime514    // api._rpcCore.addUserInterfaces(rpc);515516    const api = new ApiPromise({provider: new WsProvider(wsEndpoint), rpc});517518    await api.isReadyOrError;519520    if (typeof listeners === 'undefined') listeners = {};521    for (const event of ['connected', 'disconnected', 'error', 'ready', 'decorated']) {522      if (!listeners.hasOwnProperty(event) || typeof listeners[event as TApiAllowedListeners] === 'undefined') continue;523      api.on(event as ApiInterfaceEvents, listeners[event as TApiAllowedListeners] as (...args: any[]) => any);524    }525526    return {api, network};527  }528529  getTransactionStatus(data: {events: {event: IEvent}[], status: any}) {530    const {events, status} = data;531    if (status.isReady) {532      return this.transactionStatus.NOT_READY;533    }534    if (status.isBroadcast) {535      return this.transactionStatus.NOT_READY;536    }537    if (status.isInBlock || status.isFinalized) {538      const errors = events.filter(e => e.event.method === 'ExtrinsicFailed');539      if (errors.length > 0) {540        return this.transactionStatus.FAIL;541      }542      if (events.filter(e => e.event.method === 'ExtrinsicSuccess').length > 0) {543        return this.transactionStatus.SUCCESS;544      }545    }546547    return this.transactionStatus.FAIL;548  }549550  signTransaction(sender: TSigner, transaction: any, options: Partial<SignerOptions> | null = null, label = 'transaction') {551    const sign = (callback: any) => {552      if(options !== null) return transaction.signAndSend(sender, options, callback);553      return transaction.signAndSend(sender, callback);554    };555    // eslint-disable-next-line no-async-promise-executor556    return new Promise(async (resolve, reject) => {557      try {558        const unsub = await sign((result: any) => {559          const status = this.getTransactionStatus(result);560561          if (status === this.transactionStatus.SUCCESS) {562            this.logger.log(`${label} successful`);563            unsub();564            resolve({result, status});565          } else if (status === this.transactionStatus.FAIL) {566            let moduleError = null;567568            if (result.hasOwnProperty('dispatchError')) {569              const dispatchError = result['dispatchError'];570571              if (dispatchError) {572                if (dispatchError.isModule) {573                  const modErr = dispatchError.asModule;574                  const errorMeta = dispatchError.registry.findMetaError(modErr);575576                  moduleError = `${errorMeta.section}.${errorMeta.name}`;577                } else {578                  moduleError = dispatchError.toHuman();579                }580              } else {581                this.logger.log(result, this.logger.level.ERROR);582              }583            }584585            this.logger.log(`Something went wrong with ${label}. Status: ${status}`, this.logger.level.ERROR);586            unsub();587            reject({status, moduleError, result});588          }589        });590      } catch (e) {591        this.logger.log(e, this.logger.level.ERROR);592        reject(e);593      }594    });595  }596597  async signTransactionWithoutSending(signer: TSigner, tx: any) {598    const api = this.getApi();599    const signingInfo = await api.derive.tx.signingInfo(signer.address);600601    tx.sign(signer, {602      blockHash: api.genesisHash,603      genesisHash: api.genesisHash,604      runtimeVersion: api.runtimeVersion,605      nonce: signingInfo.nonce,606    });607608    return tx.toHex();609  }610611  async getPaymentInfo(signer: TSigner, tx: any, len: number | null) {612    const api = this.getApi();613    const signingInfo = await api.derive.tx.signingInfo(signer.address);614615    // We need to sign the tx because616    // unsigned transactions does not have an inclusion fee617    tx.sign(signer, {618      blockHash: api.genesisHash,619      genesisHash: api.genesisHash,620      runtimeVersion: api.runtimeVersion,621      nonce: signingInfo.nonce,622    });623624    if (len === null) {625      return (await this.callRpc('api.rpc.payment.queryInfo', [tx.toHex()])) as RuntimeDispatchInfo;626    } else {627      return (await api.call.transactionPaymentApi.queryInfo(tx, len)) as RuntimeDispatchInfo;628    }629  }630631  constructApiCall(apiCall: string, params: any[]) {632    if(!apiCall.startsWith('api.')) throw Error(`Invalid api call: ${apiCall}`);633    let call = this.getApi() as any;634    for(const part of apiCall.slice(4).split('.')) {635      call = call[part];636      if (!call) {637        const advice = part.includes('_') ? ' Looks like it needs to be converted to camel case.' : '';638        throw Error(`Function ${part} of api call ${apiCall} not found.${advice}`);639      }640    }641    return call(...params);642  }643644  async executeExtrinsic(sender: TSigner, extrinsic: string, params: any[], expectSuccess=true, options: Partial<SignerOptions>|null = null/*, failureMessage='expected success'*/) {645    if(this.api === null) throw Error('API not initialized');646    if(!extrinsic.startsWith('api.tx.')) throw Error(`${extrinsic} is not transaction`);647648    const startTime = (new Date()).getTime();649    let result: ITransactionResult;650    let events: IEvent[] = [];651    try {652      result = await this.signTransaction(sender, this.constructApiCall(extrinsic, params), options, extrinsic) as ITransactionResult;653      events = this.eventHelper.extractEvents(result.result.events);654    }655    catch(e) {656      if(!(e as object).hasOwnProperty('status')) throw e;657      result = e as ITransactionResult;658    }659660    const endTime = (new Date()).getTime();661662    const log = {663      executedAt: endTime,664      executionTime: endTime - startTime,665      type: this.chainLogType.EXTRINSIC,666      status: result.status,667      call: extrinsic,668      signer: this.getSignerAddress(sender),669      params,670    } as IUniqueHelperLog;671672    if(result.status !== this.transactionStatus.SUCCESS) {673      if (result.moduleError) log.moduleError = result.moduleError;674      else if (result.result.dispatchError) log.dispatchError = result.result.dispatchError;675    }676    if(events.length > 0) log.events = events;677678    this.chainLog.push(log);679680    if(expectSuccess && result.status !== this.transactionStatus.SUCCESS) {681      if (result.moduleError) throw Error(`${result.moduleError}`);682      else if (result.result.dispatchError) throw Error(JSON.stringify(result.result.dispatchError));683    }684    return result;685  }686687  async callRpc(rpc: string, params?: any[]) {688    if(typeof params === 'undefined') params = [];689    if(this.api === null) throw Error('API not initialized');690    if(!rpc.startsWith('api.rpc.') && !rpc.startsWith('api.query.')) throw Error(`${rpc} is not RPC call`);691692    const startTime = (new Date()).getTime();693    let result;694    let error = null;695    const log = {696      type: this.chainLogType.RPC,697      call: rpc,698      params,699    } as IUniqueHelperLog;700701    try {702      result = await this.constructApiCall(rpc, params);703    }704    catch(e) {705      error = e;706    }707708    const endTime = (new Date()).getTime();709710    log.executedAt = endTime;711    log.status = (error === null ? this.transactionStatus.SUCCESS : this.transactionStatus.FAIL) as 'Fail' | 'Success';712    log.executionTime = endTime - startTime;713714    this.chainLog.push(log);715716    if(error !== null) throw error;717718    return result;719  }720721  getSignerAddress(signer: IKeyringPair | string): string {722    if(typeof signer === 'string') return signer;723    return signer.address;724  }725726  fetchAllPalletNames(): string[] {727    if(this.api === null) throw Error('API not initialized');728    return this.api.runtimeMetadata.asLatest.pallets.map(m => m.name.toString().toLowerCase());729  }730731  fetchMissingPalletNames(requiredPallets: string[]): string[] {732    const palletNames = this.fetchAllPalletNames();733    return requiredPallets.filter(p => !palletNames.includes(p));734  }735}736737738class HelperGroup<T extends ChainHelperBase> {739  helper: T;740741  constructor(uniqueHelper: T) {742    this.helper = uniqueHelper;743  }744}745746747class CollectionGroup extends HelperGroup<UniqueHelper> {748  /**749 * Get number of blocks when sponsored transaction is available.750 *751 * @param collectionId ID of collection752 * @param tokenId ID of token753 * @param addressObj address for which the sponsorship is checked754 * @example await getTokenNextSponsored(1, 2, {Substrate: '5DfhbVfww7ThF8q6f3...'});755 * @returns number of blocks or null if sponsorship hasn't been set756 */757  async getTokenNextSponsored(collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<number | null> {758    return (await this.helper.callRpc('api.rpc.unique.nextSponsored', [collectionId, addressObj, tokenId])).toJSON();759  }760761  /**762   * Get the number of created collections.763   *764   * @returns number of created collections765   */766  async getTotalCount(): Promise<number> {767    return (await this.helper.callRpc('api.rpc.unique.collectionStats')).created.toNumber();768  }769770  /**771   * Get information about the collection with additional data,772   * including the number of tokens it contains, its administrators,773   * the normalized address of the collection's owner, and decoded name and description.774   *775   * @param collectionId ID of collection776   * @example await getData(2)777   * @returns collection information object778   */779  async getData(collectionId: number): Promise<{780    id: number;781    name: string;782    description: string;783    tokensCount: number;784    admins: CrossAccountId[];785    normalizedOwner: TSubstrateAccount;786    raw: any787  } | null> {788    const collection = await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId]);789    const humanCollection = collection.toHuman(), collectionData = {790      id: collectionId, name: null, description: null, tokensCount: 0, admins: [],791      raw: humanCollection,792    } as any, jsonCollection = collection.toJSON();793    if (humanCollection === null) return null;794    collectionData.raw.limits = jsonCollection.limits;795    collectionData.raw.permissions = jsonCollection.permissions;796    collectionData.normalizedOwner = this.helper.address.normalizeSubstrate(collectionData.raw.owner);797    for (const key of ['name', 'description']) {798      collectionData[key] = this.helper.util.vec2str(humanCollection[key]);799    }800801    collectionData.tokensCount = (['RFT', 'NFT'].includes(humanCollection.mode))802      ? await this.helper[humanCollection.mode.toLocaleLowerCase() as 'nft' | 'rft'].getLastTokenId(collectionId)803      : 0;804    collectionData.admins = await this.getAdmins(collectionId);805806    return collectionData;807  }808809  /**810   * Get the addresses of the collection's administrators, optionally normalized.811   *812   * @param collectionId ID of collection813   * @param normalize whether to normalize the addresses to the default ss58 format814   * @example await getAdmins(1)815   * @returns array of administrators816   */817  async getAdmins(collectionId: number, normalize = false): Promise<CrossAccountId[]> {818    const admins = (await this.helper.callRpc('api.rpc.unique.adminlist', [collectionId])).toHuman();819820    return normalize821      ? admins.map((address: CrossAccountId) => address.withNormalizedSubstrate())822      : admins;823  }824825  /**826   * Get the addresses added to the collection allow-list, optionally normalized.827   * @param collectionId ID of collection828   * @param normalize whether to normalize the addresses to the default ss58 format829   * @example await getAllowList(1)830   * @returns array of allow-listed addresses831   */832  async getAllowList(collectionId: number, normalize = false): Promise<CrossAccountId[]> {833    const allowListed = (await this.helper.callRpc('api.rpc.unique.allowlist', [collectionId])).toHuman();834    return normalize835      ? allowListed.map((address: CrossAccountId) => address.withNormalizedSubstrate())836      : allowListed;837  }838839  /**840   * Get the effective limits of the collection instead of null for default values841   *842   * @param collectionId ID of collection843   * @example await getEffectiveLimits(2)844   * @returns object of collection limits845   */846  async getEffectiveLimits(collectionId: number): Promise<ICollectionLimits> {847    return (await this.helper.callRpc('api.rpc.unique.effectiveCollectionLimits', [collectionId])).toJSON();848  }849850  /**851   * Burns the collection if the signer has sufficient permissions and collection is empty.852   *853   * @param signer keyring of signer854   * @param collectionId ID of collection855   * @example await helper.collection.burn(aliceKeyring, 3);856   * @returns ```true``` if extrinsic success, otherwise ```false```857   */858  async burn(signer: TSigner, collectionId: number): Promise<boolean> {859    const result = await this.helper.executeExtrinsic(860      signer,861      'api.tx.unique.destroyCollection', [collectionId],862      true,863    );864865    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionDestroyed');866  }867868  /**869   * Sets the sponsor for the collection (Requires the Substrate address). Needs confirmation by the sponsor.870   *871   * @param signer keyring of signer872   * @param collectionId ID of collection873   * @param sponsorAddress Sponsor substrate address874   * @example setSponsor(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...")875   * @returns ```true``` if extrinsic success, otherwise ```false```876   */877  async setSponsor(signer: TSigner, collectionId: number, sponsorAddress: TSubstrateAccount): Promise<boolean> {878    const result = await this.helper.executeExtrinsic(879      signer,880      'api.tx.unique.setCollectionSponsor', [collectionId, sponsorAddress],881      true,882    );883884    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionSponsorSet');885  }886887  /**888   * Confirms consent to sponsor the collection on behalf of the signer.889   *890   * @param signer keyring of signer891   * @param collectionId ID of collection892   * @example confirmSponsorship(aliceKeyring, 10)893   * @returns ```true``` if extrinsic success, otherwise ```false```894   */895  async confirmSponsorship(signer: TSigner, collectionId: number): Promise<boolean> {896    const result = await this.helper.executeExtrinsic(897      signer,898      'api.tx.unique.confirmSponsorship', [collectionId],899      true,900    );901902    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'SponsorshipConfirmed');903  }904905  /**906   * Removes the sponsor of a collection, regardless if it consented or not.907   *908   * @param signer keyring of signer909   * @param collectionId ID of collection910   * @example removeSponsor(aliceKeyring, 10)911   * @returns ```true``` if extrinsic success, otherwise ```false```912   */913  async removeSponsor(signer: TSigner, collectionId: number): Promise<boolean> {914    const result = await this.helper.executeExtrinsic(915      signer,916      'api.tx.unique.removeCollectionSponsor', [collectionId],917      true,918    );919920    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionSponsorRemoved');921  }922923  /**924   * Sets the limits of the collection. At least one limit must be specified for a correct call.925   *926   * @param signer keyring of signer927   * @param collectionId ID of collection928   * @param limits collection limits object929   * @example930   * await setLimits(931   *   aliceKeyring,932   *   10,933   *   {934   *     sponsorTransferTimeout: 0,935   *     ownerCanDestroy: false936   *   }937   * )938   * @returns ```true``` if extrinsic success, otherwise ```false```939   */940  async setLimits(signer: TSigner, collectionId: number, limits: ICollectionLimits): Promise<boolean> {941    const result = await this.helper.executeExtrinsic(942      signer,943      'api.tx.unique.setCollectionLimits', [collectionId, limits],944      true,945    );946947    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionLimitSet');948  }949950  /**951   * Changes the owner of the collection to the new Substrate address.952   *953   * @param signer keyring of signer954   * @param collectionId ID of collection955   * @param ownerAddress substrate address of new owner956   * @example changeOwner(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...")957   * @returns ```true``` if extrinsic success, otherwise ```false```958   */959  async changeOwner(signer: TSigner, collectionId: number, ownerAddress: TSubstrateAccount): Promise<boolean> {960    const result = await this.helper.executeExtrinsic(961      signer,962      'api.tx.unique.changeCollectionOwner', [collectionId, ownerAddress],963      true,964    );965966    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionOwnerChanged');967  }968969  /**970   * Adds a collection administrator.971   *972   * @param signer keyring of signer973   * @param collectionId ID of collection974   * @param adminAddressObj Administrator address (substrate or ethereum)975   * @example addAdmin(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."})976   * @returns ```true``` if extrinsic success, otherwise ```false```977   */978  async addAdmin(signer: TSigner, collectionId: number, adminAddressObj: ICrossAccountId): Promise<boolean> {979    const result = await this.helper.executeExtrinsic(980      signer,981      'api.tx.unique.addCollectionAdmin', [collectionId, adminAddressObj],982      true,983    );984985    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionAdminAdded');986  }987988  /**989   * Removes a collection administrator.990   *991   * @param signer keyring of signer992   * @param collectionId ID of collection993   * @param adminAddressObj Administrator address (substrate or ethereum)994   * @example removeAdmin(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."})995   * @returns ```true``` if extrinsic success, otherwise ```false```996   */997  async removeAdmin(signer: TSigner, collectionId: number, adminAddressObj: ICrossAccountId): Promise<boolean> {998    const result = await this.helper.executeExtrinsic(999      signer,1000      'api.tx.unique.removeCollectionAdmin', [collectionId, adminAddressObj],1001      true,1002    );10031004    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionAdminRemoved');1005  }10061007  /**1008   * Check if user is in allow list.1009   *1010   * @param collectionId ID of collection1011   * @param user Account to check1012   * @example await getAdmins(1)1013   * @returns is user in allow list1014   */1015  async allowed(collectionId: number, user: ICrossAccountId): Promise<boolean> {1016    return (await this.helper.callRpc('api.rpc.unique.allowed', [collectionId, user])).toJSON();1017  }10181019  /**1020   * Adds an address to allow list1021   * @param signer keyring of signer1022   * @param collectionId ID of collection1023   * @param addressObj address to add to the allow list1024   * @returns ```true``` if extrinsic success, otherwise ```false```1025   */1026  async addToAllowList(signer: TSigner, collectionId: number, addressObj: ICrossAccountId): Promise<boolean> {1027    const result = await this.helper.executeExtrinsic(1028      signer,1029      'api.tx.unique.addToAllowList', [collectionId, addressObj],1030      true,1031    );10321033    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'AllowListAddressAdded');1034  }10351036  /**1037   * Removes an address from allow list1038   *1039   * @param signer keyring of signer1040   * @param collectionId ID of collection1041   * @param addressObj address to remove from the allow list1042   * @returns ```true``` if extrinsic success, otherwise ```false```1043   */1044  async removeFromAllowList(signer: TSigner, collectionId: number, addressObj: ICrossAccountId): Promise<boolean> {1045    const result = await this.helper.executeExtrinsic(1046      signer,1047      'api.tx.unique.removeFromAllowList', [collectionId, addressObj],1048      true,1049    );10501051    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'AllowListAddressRemoved');1052  }10531054  /**1055   * Sets onchain permissions for selected collection.1056   *1057   * @param signer keyring of signer1058   * @param collectionId ID of collection1059   * @param permissions collection permissions object1060   * @example setPermissions(aliceKeyring, 10, {access:'AllowList', mintMode: true, nesting: {collectionAdmin: true, tokenOwner: true}});1061   * @returns ```true``` if extrinsic success, otherwise ```false```1062   */1063  async setPermissions(signer: TSigner, collectionId: number, permissions: ICollectionPermissions): Promise<boolean> {1064    const result = await this.helper.executeExtrinsic(1065      signer,1066      'api.tx.unique.setCollectionPermissions', [collectionId, permissions],1067      true,1068    );10691070    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPermissionSet');1071  }10721073  /**1074   * Enables nesting for selected collection. If `restricted` set, you can nest only tokens from specified collections.1075   *1076   * @param signer keyring of signer1077   * @param collectionId ID of collection1078   * @param permissions nesting permissions object1079   * @example enableNesting(aliceKeyring, 10, {collectionAdmin: true, tokenOwner: true});1080   * @returns ```true``` if extrinsic success, otherwise ```false```1081   */1082  async enableNesting(signer: TSigner, collectionId: number, permissions: INestingPermissions): Promise<boolean> {1083    return await this.setPermissions(signer, collectionId, {nesting: permissions});1084  }10851086  /**1087   * Disables nesting for selected collection.1088   *1089   * @param signer keyring of signer1090   * @param collectionId ID of collection1091   * @example disableNesting(aliceKeyring, 10);1092   * @returns ```true``` if extrinsic success, otherwise ```false```1093   */1094  async disableNesting(signer: TSigner, collectionId: number): Promise<boolean> {1095    return await this.setPermissions(signer, collectionId, {nesting: {tokenOwner: false, collectionAdmin: false}});1096  }10971098  /**1099   * Sets onchain properties to the collection.1100   *1101   * @param signer keyring of signer1102   * @param collectionId ID of collection1103   * @param properties array of property objects1104   * @example setProperties(aliceKeyring, 10, [{key: "gender", value: "male"}]);1105   * @returns ```true``` if extrinsic success, otherwise ```false```1106   */1107  async setProperties(signer: TSigner, collectionId: number, properties: IProperty[]): Promise<boolean> {1108    const result = await this.helper.executeExtrinsic(1109      signer,1110      'api.tx.unique.setCollectionProperties', [collectionId, properties],1111      true,1112    );11131114    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPropertySet');1115  }11161117  /**1118   * Get collection properties.1119   *1120   * @param collectionId ID of collection1121   * @param propertyKeys optionally filter the returned properties to only these keys1122   * @example getProperties(1219, ['location', 'date', 'time', 'isParadise']);1123   * @returns array of key-value pairs1124   */1125  async getProperties(collectionId: number, propertyKeys?: string[] | null): Promise<IProperty[]> {1126    return (await this.helper.callRpc('api.rpc.unique.collectionProperties', [collectionId, propertyKeys])).toHuman();1127  }11281129  async getPropertiesConsumedSpace(collectionId: number): Promise<number> {1130    const api = this.helper.getApi();1131    const props = (await api.query.common.collectionProperties(collectionId)).toJSON();11321133    return (props! as any).consumedSpace;1134  }11351136  async getCollectionOptions(collectionId: number) {1137    return (await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId])).toHuman();1138  }11391140  /**1141   * Deletes onchain properties from the collection.1142   *1143   * @param signer keyring of signer1144   * @param collectionId ID of collection1145   * @param propertyKeys array of property keys to delete1146   * @example deleteProperties(aliceKeyring, 10, ["gender", "age"]);1147   * @returns ```true``` if extrinsic success, otherwise ```false```1148   */1149  async deleteProperties(signer: TSigner, collectionId: number, propertyKeys: string[]): Promise<boolean> {1150    const result = await this.helper.executeExtrinsic(1151      signer,1152      'api.tx.unique.deleteCollectionProperties', [collectionId, propertyKeys],1153      true,1154    );11551156    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPropertyDeleted');1157  }11581159  /**1160   * Changes the owner of the token.1161   *1162   * @param signer keyring of signer1163   * @param collectionId ID of collection1164   * @param tokenId ID of token1165   * @param addressObj address of a new owner1166   * @param amount amount of tokens to be transfered. For NFT must be set to 1n1167   * @example transferToken(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."})1168   * @returns true if the token success, otherwise false1169   */1170  async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId, amount=1n): Promise<boolean> {1171    const result = await this.helper.executeExtrinsic(1172      signer,1173      'api.tx.unique.transfer', [addressObj, collectionId, tokenId, amount],1174      true, // `Unable to transfer token #${tokenId} from collection #${collectionId}`,1175    );11761177    return this.helper.util.isTokenTransferSuccess(result.result.events, collectionId, tokenId, {Substrate: typeof signer === 'string' ? signer : signer.address}, addressObj, amount);1178  }11791180  /**1181   *1182   * Change ownership of a token(s) on behalf of the owner.1183   *1184   * @param signer keyring of signer1185   * @param collectionId ID of collection1186   * @param tokenId ID of token1187   * @param fromAddressObj address on behalf of which the token will be sent1188   * @param toAddressObj new token owner1189   * @param amount amount of tokens to be transfered. For NFT must be set to 1n1190   * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg"}, {Ethereum: "0x9F0583DbB85..."})1191   * @returns true if the token success, otherwise false1192   */1193  async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1194    const result = await this.helper.executeExtrinsic(1195      signer,1196      'api.tx.unique.transferFrom', [fromAddressObj, toAddressObj, collectionId, tokenId, amount],1197      true, // `Unable to transfer token #${tokenId} from collection #${collectionId}`,1198    );1199    return this.helper.util.isTokenTransferSuccess(result.result.events, collectionId, tokenId, fromAddressObj, toAddressObj, amount);1200  }12011202  /**1203   *1204   * Destroys a concrete instance of NFT/RFT or burns a specified amount of fungible tokens.1205   *1206   * @param signer keyring of signer1207   * @param collectionId ID of collection1208   * @param tokenId ID of token1209   * @param amount amount of tokens to be burned. For NFT must be set to 1n1210   * @example burnToken(aliceKeyring, 10, 5);1211   * @returns ```true``` if the extrinsic is successful, otherwise ```false```1212   */1213  async burnToken(signer: TSigner, collectionId: number, tokenId: number, amount=1n): Promise<boolean> {1214    const burnResult = await this.helper.executeExtrinsic(1215      signer,1216      'api.tx.unique.burnItem', [collectionId, tokenId, amount],1217      true, // `Unable to burn token for ${label}`,1218    );1219    const burnedTokens = this.helper.util.extractTokensFromBurnResult(burnResult);1220    if (burnedTokens.tokens.length > 1) throw Error('Burned multiple tokens');1221    return burnedTokens.success;1222  }12231224  /**1225   * Destroys a concrete instance of NFT on behalf of the owner1226   *1227   * @param signer keyring of signer1228   * @param collectionId ID of collection1229   * @param tokenId ID of token1230   * @param fromAddressObj address on behalf of which the token will be burnt1231   * @param amount amount of tokens to be burned. For NFT must be set to 1n1232   * @example burnTokenFrom(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."}, 5, {Ethereum: "0x9F0583DbB85..."})1233   * @returns ```true``` if extrinsic success, otherwise ```false```1234   */1235  async burnTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1236    const burnResult = await this.helper.executeExtrinsic(1237      signer,1238      'api.tx.unique.burnFrom', [collectionId, fromAddressObj, tokenId, amount],1239      true, // `Unable to burn token from for ${label}`,1240    );1241    const burnedTokens = this.helper.util.extractTokensFromBurnResult(burnResult);1242    return burnedTokens.success && burnedTokens.tokens.length > 0;1243  }12441245  /**1246   * Set, change, or remove approved address to transfer the ownership of the NFT.1247   *1248   * @param signer keyring of signer1249   * @param collectionId ID of collection1250   * @param tokenId ID of token1251   * @param toAddressObj Substrate or Ethereum address which gets approved use of the signer's tokens1252   * @param amount amount of token to be approved. For NFT must be set to 1n1253   * @returns ```true``` if extrinsic success, otherwise ```false```1254   */1255  async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {1256    const approveResult = await this.helper.executeExtrinsic(1257      signer,1258      'api.tx.unique.approve', [toAddressObj, collectionId, tokenId, amount],1259      true, // `Unable to approve token for ${label}`,1260    );12611262    return this.helper.util.findCollectionInEvents(approveResult.result.events, collectionId, 'common', 'Approved');1263  }12641265  /**1266   * Set, change, or remove approved address to transfer the ownership of the NFT from eth mirror.1267   *1268   * @param signer keyring of signer1269   * @param collectionId ID of collection1270   * @param tokenId ID of token1271   * @param fromAddressObj Signer's Ethereum address containing her tokens1272   * @param toAddressObj Substrate or Ethereum address which gets approved use of the signer's tokens1273   * @param amount amount of token to be approved. For NFT must be set to 1n1274   * @returns ```true``` if extrinsic success, otherwise ```false```1275   */1276  async approveTokenFrom(signer: IKeyringPair, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {1277    const approveResult = await this.helper.executeExtrinsic(1278      signer,1279      'api.tx.unique.approveFrom', [fromAddressObj, toAddressObj, collectionId, tokenId, amount],1280      true, // `Unable to approve token for ${label}`,1281    );12821283    return this.helper.util.findCollectionInEvents(approveResult.result.events, collectionId, 'common', 'Approved');1284  }12851286  /**1287   * Set, change, or remove approved address to transfer the ownership of the NFT from eth mirror.1288   *1289   * @param signer keyring of signer1290   * @param collectionId ID of collection1291   * @param tokenId ID of token1292   * @param toAddressObj Substrate or Ethereum address which gets approved use of the signer's tokens1293   * @param amount amount of token to be approved. For NFT must be set to 1n1294   * @returns ```true``` if extrinsic success, otherwise ```false```1295   */1296  async approveTokenFromEth(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {1297    const ethMirror = CrossAccountId.fromKeyring(signer).toEthereum();1298    return await this.approveTokenFrom(signer, collectionId, tokenId, ethMirror, toAddressObj, amount);1299  }13001301  /**1302   * Get the amount of token pieces approved to transfer or burn. Normally 0.1303   *1304   * @param collectionId ID of collection1305   * @param tokenId ID of token1306   * @param toAccountObj address which is approved to use token pieces1307   * @param fromAccountObj address which may have allowed the use of its owned tokens1308   * @example getTokenApprovedPieces(10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, {Substrate: "5ERZNF88Mm7UGfPP3mdG..."})1309   * @returns number of approved to transfer pieces1310   */1311  async getTokenApprovedPieces(collectionId: number, tokenId: number, toAccountObj: ICrossAccountId, fromAccountObj: ICrossAccountId): Promise<bigint> {1312    return (await this.helper.callRpc('api.rpc.unique.allowance', [collectionId, fromAccountObj, toAccountObj, tokenId])).toBigInt();1313  }13141315  /**1316   * Get the last created token ID in a collection1317   *1318   * @param collectionId ID of collection1319   * @example getLastTokenId(10);1320   * @returns id of the last created token1321   */1322  async getLastTokenId(collectionId: number): Promise<number> {1323    return (await this.helper.callRpc('api.rpc.unique.lastTokenId', [collectionId])).toNumber();1324  }13251326  /**1327   * Check if token exists1328   *1329   * @param collectionId ID of collection1330   * @param tokenId ID of token1331   * @example doesTokenExist(10, 20);1332   * @returns true if the token exists, otherwise false1333   */1334  async doesTokenExist(collectionId: number, tokenId: number): Promise<boolean> {1335    return (await this.helper.callRpc('api.rpc.unique.tokenExists', [collectionId, tokenId])).toJSON();1336  }1337}13381339class NFTnRFT extends CollectionGroup {1340  /**1341   * Get tokens owned by account1342   *1343   * @param collectionId ID of collection1344   * @param addressObj tokens owner1345   * @example getTokensByAddress(10, {Substrate: "5DyN4Y92vZCjv38fg..."})1346   * @returns array of token ids owned by account1347   */1348  async getTokensByAddress(collectionId: number, addressObj: ICrossAccountId): Promise<number[]> {1349    return (await this.helper.callRpc('api.rpc.unique.accountTokens', [collectionId, addressObj])).toJSON();1350  }13511352  /**1353   * Get token data1354   *1355   * @param collectionId ID of collection1356   * @param tokenId ID of token1357   * @param propertyKeys optionally filter the token properties to only these keys1358   * @param blockHashAt optionally query the data at some block with this hash1359   * @example getToken(10, 5);1360   * @returns human readable token data1361   */1362  async getToken(collectionId: number, tokenId: number, propertyKeys: string[] = [], blockHashAt?: string): Promise<{1363    properties: IProperty[];1364    owner: CrossAccountId;1365    normalizedOwner: CrossAccountId;1366  }| null> {1367    let tokenData;1368    if(typeof blockHashAt === 'undefined') {1369      tokenData = await this.helper.callRpc('api.rpc.unique.tokenData', [collectionId, tokenId]);1370    }1371    else {1372      if(propertyKeys.length == 0) {1373        const collection = (await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId])).toHuman();1374        if(!collection) return null;1375        propertyKeys = collection.tokenPropertyPermissions.map((x: ITokenPropertyPermission) => x.key);1376      }1377      tokenData = await this.helper.callRpc('api.rpc.unique.tokenData', [collectionId, tokenId, propertyKeys, blockHashAt]);1378    }1379    tokenData = tokenData.toHuman();1380    if (tokenData === null || tokenData.owner === null) return null;1381    const owner = {} as any;1382    for (const key of Object.keys(tokenData.owner)) {1383      owner[key.toLocaleLowerCase()] = key.toLocaleLowerCase() == 'substrate'1384        ? CrossAccountId.normalizeSubstrateAddress(tokenData.owner[key])1385        : tokenData.owner[key];1386    }1387    tokenData.normalizedOwner = CrossAccountId.fromLowerCaseKeys(owner);1388    return tokenData;1389  }13901391  /**1392   * Set permissions to change token properties1393   *1394   * @param signer keyring of signer1395   * @param collectionId ID of collection1396   * @param permissions permissions to change a property by the collection admin or token owner1397   * @example setTokenPropertyPermissions(1398   *   aliceKeyring, 10, [{key: "gender", permission: {tokenOwner: true, mutable: true, collectionAdmin: true}}]1399   * )1400   * @returns true if extrinsic success otherwise false1401   */1402  async setTokenPropertyPermissions(signer: TSigner, collectionId: number, permissions: ITokenPropertyPermission[]): Promise<boolean> {1403    const result = await this.helper.executeExtrinsic(1404      signer,1405      'api.tx.unique.setTokenPropertyPermissions', [collectionId, permissions],1406      true,1407    );14081409    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'PropertyPermissionSet');1410  }14111412  /**1413   * Get token property permissions.1414   *1415   * @param collectionId ID of collection1416   * @param propertyKeys optionally filter the returned property permissions to only these keys1417   * @example getPropertyPermissions(1219, ['location', 'date', 'time', 'isParadise']);1418   * @returns array of key-permission pairs1419   */1420  async getPropertyPermissions(collectionId: number, propertyKeys: string[] | null = null): Promise<ITokenPropertyPermission[]> {1421    return (await this.helper.callRpc('api.rpc.unique.propertyPermissions', [collectionId, ...(propertyKeys === null ? [] : [propertyKeys])])).toHuman();1422  }14231424  /**1425   * Set token properties1426   *1427   * @param signer keyring of signer1428   * @param collectionId ID of collection1429   * @param tokenId ID of token1430   * @param properties key-value pairs of metadata which to add to a token. Keys must be permitted in the collection1431   * @example setTokenProperties(aliceKeyring, 10, 5, [{key: "gender", value: "female"}, {key: "age", value: "23"}])1432   * @returns ```true``` if extrinsic success, otherwise ```false```1433   */1434  async setTokenProperties(signer: TSigner, collectionId: number, tokenId: number, properties: IProperty[]): Promise<boolean> {1435    const result = await this.helper.executeExtrinsic(1436      signer,1437      'api.tx.unique.setTokenProperties', [collectionId, tokenId, properties],1438      true,1439    );14401441    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'TokenPropertySet');1442  }14431444  /**1445   * Get properties, metadata assigned to a token.1446   *1447   * @param collectionId ID of collection1448   * @param tokenId ID of token1449   * @param propertyKeys optionally filter the returned properties to only these keys1450   * @example getTokenProperties(1219, ['location', 'date', 'time', 'isParadise']);1451   * @returns array of key-value pairs1452   */1453  async getTokenProperties(collectionId: number, tokenId: number, propertyKeys?: string[] | null): Promise<IProperty[]> {1454    return (await this.helper.callRpc('api.rpc.unique.tokenProperties', [collectionId, tokenId, propertyKeys])).toHuman();1455  }14561457  /**1458   * Delete the provided properties of a token1459   * @param signer keyring of signer1460   * @param collectionId ID of collection1461   * @param tokenId ID of token1462   * @param propertyKeys property keys to be deleted1463   * @example deleteTokenProperties(aliceKeyring, 10, 5, ["gender", "age"])1464   * @returns ```true``` if extrinsic success, otherwise ```false```1465   */1466  async deleteTokenProperties(signer: TSigner, collectionId: number, tokenId: number, propertyKeys: string[]): Promise<boolean> {1467    const result = await this.helper.executeExtrinsic(1468      signer,1469      'api.tx.unique.deleteTokenProperties', [collectionId, tokenId, propertyKeys],1470      true,1471    );14721473    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'TokenPropertyDeleted');1474  }14751476  /**1477   * Mint new collection1478   *1479   * @param signer keyring of signer1480   * @param collectionOptions basic collection options and properties1481   * @param mode NFT or RFT type of a collection1482   * @example mintCollection(aliceKeyring, {name: 'New', description: "New collection", tokenPrefix: "NEW"}, "NFT")1483   * @returns object of the created collection1484   */1485  async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions, mode: 'NFT' | 'RFT'): Promise<UniqueBaseCollection> {1486    collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; // Clone object1487    collectionOptions.mode = (mode === 'NFT') ? {nft: null} : {refungible: null};1488    for (const key of ['name', 'description', 'tokenPrefix']) {1489      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);1490    }1491    const creationResult = await this.helper.executeExtrinsic(1492      signer,1493      'api.tx.unique.createCollectionEx', [collectionOptions],1494      true, // errorLabel,1495    );1496    return this.getCollectionObject(this.helper.util.extractCollectionIdFromCreationResult(creationResult));1497  }14981499  getCollectionObject(_collectionId: number): any {1500    return null;1501  }15021503  getTokenObject(_collectionId: number, _tokenId: number): any {1504    return null;1505  }15061507  /**1508   * Tells whether the given `owner` approves the `operator`.1509   * @param collectionId ID of collection1510   * @param owner owner address1511   * @param operator operator addrees1512   * @returns true if operator is enabled1513   */1514  async allowanceForAll(collectionId: number, owner: ICrossAccountId, operator: ICrossAccountId): Promise<boolean> {1515    return (await this.helper.callRpc('api.rpc.unique.allowanceForAll', [collectionId, owner, operator])).toJSON();1516  }15171518  /** Sets or unsets the approval of a given operator.1519   *  The `operator` is allowed to transfer all tokens of the `caller` on their behalf.1520   *  @param operator Operator1521   *  @param approved Should operator status be granted or revoked?1522   *  @returns ```true``` if extrinsic success, otherwise ```false```1523   */1524  async setAllowanceForAll(signer: TSigner, collectionId: number, operator: ICrossAccountId, approved: boolean): Promise<boolean> {1525    const result = await this.helper.executeExtrinsic(1526      signer,1527      'api.tx.unique.setAllowanceForAll', [collectionId, operator, approved],1528      true,1529    );1530    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'ApprovedForAll');1531  }1532}153315341535class NFTGroup extends NFTnRFT {1536  /**1537   * Get collection object1538   * @param collectionId ID of collection1539   * @example getCollectionObject(2);1540   * @returns instance of UniqueNFTCollection1541   */1542  getCollectionObject(collectionId: number): UniqueNFTCollection {1543    return new UniqueNFTCollection(collectionId, this.helper);1544  }15451546  /**1547   * Get token object1548   * @param collectionId ID of collection1549   * @param tokenId ID of token1550   * @example getTokenObject(10, 5);1551   * @returns instance of UniqueNFTToken1552   */1553  getTokenObject(collectionId: number, tokenId: number): UniqueNFToken {1554    return new UniqueNFToken(tokenId, this.getCollectionObject(collectionId));1555  }15561557  /**1558   * Get token's owner1559   * @param collectionId ID of collection1560   * @param tokenId ID of token1561   * @param blockHashAt optionally query the data at the block with this hash1562   * @example getTokenOwner(10, 5);1563   * @returns Address in CrossAccountId format, e.g. {Substrate: "5DnSF6RRjwteE3BrCj..."}1564   */1565  async getTokenOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<CrossAccountId> {1566    let owner;1567    if (typeof blockHashAt === 'undefined') {1568      owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId]);1569    } else {1570      owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId, blockHashAt]);1571    }1572    return CrossAccountId.fromLowerCaseKeys(owner.toJSON());1573  }15741575  /**1576   * Is token approved to transfer1577   * @param collectionId ID of collection1578   * @param tokenId ID of token1579   * @param toAccountObj address to be approved1580   * @returns ```true``` if extrinsic success, otherwise ```false```1581   */1582  async isTokenApproved(collectionId: number, tokenId: number, toAccountObj: ICrossAccountId): Promise<boolean> {1583    return (await this.getTokenApprovedPieces(collectionId, tokenId, toAccountObj, await this.getTokenOwner(collectionId, tokenId))) === 1n;1584  }15851586  /**1587   * Changes the owner of the token.1588   *1589   * @param signer keyring of signer1590   * @param collectionId ID of collection1591   * @param tokenId ID of token1592   * @param addressObj address of a new owner1593   * @example transferToken(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."})1594   * @returns ```true``` if extrinsic success, otherwise ```false```1595   */1596  async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<boolean> {1597    return await super.transferToken(signer, collectionId, tokenId, addressObj, 1n);1598  }15991600  /**1601   *1602   * Change ownership of a NFT on behalf of the owner.1603   *1604   * @param signer keyring of signer1605   * @param collectionId ID of collection1606   * @param tokenId ID of token1607   * @param fromAddressObj address on behalf of which the token will be sent1608   * @param toAddressObj new token owner1609   * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, {Ethereum: "0x9F0583DbB85..."})1610   * @returns ```true``` if extrinsic success, otherwise ```false```1611   */1612  async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId): Promise<boolean> {1613    return await super.transferTokenFrom(signer, collectionId, tokenId, fromAddressObj, toAddressObj, 1n);1614  }16151616  /**1617   * Recursively find the address that owns the token1618   * @param collectionId ID of collection1619   * @param tokenId ID of token1620   * @param blockHashAt1621   * @example getTokenTopmostOwner(10, 5);1622   * @returns address in CrossAccountId format, e.g. {Substrate: "5DyN4Y92vZCjv38fg..."}1623   */1624  async getTokenTopmostOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<CrossAccountId | null> {1625    let owner;1626    if (typeof blockHashAt === 'undefined') {1627      owner = await this.helper.callRpc('api.rpc.unique.topmostTokenOwner', [collectionId, tokenId]);1628    } else {1629      owner = await this.helper.callRpc('api.rpc.unique.topmostTokenOwner', [collectionId, tokenId, blockHashAt]);1630    }16311632    if (owner === null) return null;16331634    return owner.toHuman();1635  }16361637  /**1638   * Get tokens nested in the provided token1639   * @param collectionId ID of collection1640   * @param tokenId ID of token1641   * @param blockHashAt optionally query the data at the block with this hash1642   * @example getTokenChildren(10, 5);1643   * @returns tokens whose depth of nesting is <= 51644   */1645  async getTokenChildren(collectionId: number, tokenId: number, blockHashAt?: string): Promise<IToken[]> {1646    let children;1647    if(typeof blockHashAt === 'undefined') {1648      children = await this.helper.callRpc('api.rpc.unique.tokenChildren', [collectionId, tokenId]);1649    } else {1650      children = await this.helper.callRpc('api.rpc.unique.tokenChildren', [collectionId, tokenId, blockHashAt]);1651    }16521653    return children.toJSON().map((x: any) => {1654      return {collectionId: x.collection, tokenId: x.token};1655    });1656  }16571658  /**1659   * Nest one token into another1660   * @param signer keyring of signer1661   * @param tokenObj token to be nested1662   * @param rootTokenObj token to be parent1663   * @example nestToken(aliceKeyring, {collectionId: 10, tokenId: 5}, {collectionId: 10, tokenId: 4});1664   * @returns ```true``` if extrinsic success, otherwise ```false```1665   */1666  async nestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken): Promise<boolean> {1667    const rootTokenAddress = this.helper.util.getTokenAccount(rootTokenObj);1668    const result = await this.transferToken(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress);1669    if(!result) {1670      throw Error('Unable to nest token!');1671    }1672    return result;1673  }16741675  /**1676   * Remove token from nested state1677   * @param signer keyring of signer1678   * @param tokenObj token to unnest1679   * @param rootTokenObj parent of a token1680   * @param toAddressObj address of a new token owner1681   * @example unnestToken(aliceKeyring, {collectionId: 10, tokenId: 5}, {collectionId: 10, tokenId: 4}, {Substrate: "5DyN4Y92vZCjv38fg..."});1682   * @returns ```true``` if extrinsic success, otherwise ```false```1683   */1684  async unnestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken, toAddressObj: ICrossAccountId): Promise<boolean> {1685    const rootTokenAddress = this.helper.util.getTokenAccount(rootTokenObj);1686    const result = await this.transferTokenFrom(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress, toAddressObj);1687    if(!result) {1688      throw Error('Unable to unnest token!');1689    }1690    return result;1691  }16921693  /**1694   * Mint new collection1695   * @param signer keyring of signer1696   * @param collectionOptions Collection options1697   * @example1698   * mintCollection(aliceKeyring, {1699   *   name: 'New',1700   *   description: 'New collection',1701   *   tokenPrefix: 'NEW',1702   * })1703   * @returns object of the created collection1704   */1705  async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}): Promise<UniqueNFTCollection> {1706    return await super.mintCollection(signer, collectionOptions, 'NFT') as UniqueNFTCollection;1707  }17081709  /**1710   * Mint new token1711   * @param signer keyring of signer1712   * @param data token data1713   * @returns created token object1714   */1715  async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; properties?: IProperty[]; }): Promise<UniqueNFToken> {1716    const creationResult = await this.helper.executeExtrinsic(1717      signer,1718      'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {1719        nft: {1720          properties: data.properties,1721        },1722      }],1723      true,1724    );1725    const createdTokens = this.helper.util.extractTokensFromCreationResult(creationResult);1726    if (createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');1727    if (createdTokens.tokens.length < 1) throw Error('No tokens minted');1728    return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);1729  }17301731  /**1732   * Mint multiple NFT tokens1733   * @param signer keyring of signer1734   * @param collectionId ID of collection1735   * @param tokens array of tokens with owner and properties1736   * @example1737   * mintMultipleTokens(aliceKeyring, 10, [{1738   *     owner: {Substrate: "5DyN4Y92vZCjv38fg..."},1739   *     properties: [{key: "gender", value: "male"},{key: "age", value: "45"}],1740   *   },{1741   *     owner: {Ethereum: "0x9F0583DbB855d..."},1742   *     properties: [{key: "gender", value: "female"},{key: "age", value: "22"}],1743   * }]);1744   * @returns ```true``` if extrinsic success, otherwise ```false```1745   */1746  async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: {owner: ICrossAccountId, properties?: IProperty[]}[]): Promise<UniqueNFToken[]> {1747    const creationResult = await this.helper.executeExtrinsic(1748      signer,1749      'api.tx.unique.createMultipleItemsEx', [collectionId, {NFT: tokens}],1750      true,1751    );1752    const collection = this.getCollectionObject(collectionId);1753    return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1754  }17551756  /**1757   * Mint multiple NFT tokens with one owner1758   * @param signer keyring of signer1759   * @param collectionId ID of collection1760   * @param owner tokens owner1761   * @param tokens array of tokens with owner and properties1762   * @example1763   * mintMultipleTokensWithOneOwner(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...", [{1764   *   properties: [{1765   *   key: "gender",1766   *   value: "female",1767   *  },{1768   *   key: "age",1769   *   value: "33",1770   *  }],1771   * }]);1772   * @returns array of newly created tokens1773   */1774  async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {properties?: IProperty[]}[]): Promise<UniqueNFToken[]> {1775    const rawTokens = [];1776    for (const token of tokens) {1777      const raw = {NFT: {properties: token.properties}};1778      rawTokens.push(raw);1779    }1780    const creationResult = await this.helper.executeExtrinsic(1781      signer,1782      'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1783      true,1784    );1785    const collection = this.getCollectionObject(collectionId);1786    return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1787  }17881789  /**1790   * Set, change, or remove approved address to transfer the ownership of the NFT.1791   *1792   * @param signer keyring of signer1793   * @param collectionId ID of collection1794   * @param tokenId ID of token1795   * @param toAddressObj address to approve1796   * @example approveToken(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."})1797   * @returns ```true``` if extrinsic success, otherwise ```false```1798   */1799  approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {1800    return super.approveToken(signer, collectionId, tokenId, toAddressObj, amount);1801  }1802}180318041805class RFTGroup extends NFTnRFT {1806  /**1807   * Get collection object1808   * @param collectionId ID of collection1809   * @example getCollectionObject(2);1810   * @returns instance of UniqueRFTCollection1811   */1812  getCollectionObject(collectionId: number): UniqueRFTCollection {1813    return new UniqueRFTCollection(collectionId, this.helper);1814  }18151816  /**1817   * Get token object1818   * @param collectionId ID of collection1819   * @param tokenId ID of token1820   * @example getTokenObject(10, 5);1821   * @returns instance of UniqueNFTToken1822   */1823  getTokenObject(collectionId: number, tokenId: number): UniqueRFToken {1824    return new UniqueRFToken(tokenId, this.getCollectionObject(collectionId));1825  }18261827  /**1828   * Get top 10 token owners with the largest number of pieces1829   * @param collectionId ID of collection1830   * @param tokenId ID of token1831   * @example getTokenTop10Owners(10, 5);1832   * @returns array of top 10 owners1833   */1834  async getTokenTop10Owners(collectionId: number, tokenId: number): Promise<CrossAccountId[]> {1835    return (await this.helper.callRpc('api.rpc.unique.tokenOwners', [collectionId, tokenId])).toJSON().map(CrossAccountId.fromLowerCaseKeys);1836  }18371838  /**1839   * Get number of pieces owned by address1840   * @param collectionId ID of collection1841   * @param tokenId ID of token1842   * @param addressObj address token owner1843   * @example getTokenBalance(10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."});1844   * @returns number of pieces ownerd by address1845   */1846  async getTokenBalance(collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<bigint> {1847    return (await this.helper.callRpc('api.rpc.unique.balance', [collectionId, addressObj, tokenId])).toBigInt();1848  }18491850  /**1851   * Transfer pieces of token to another address1852   * @param signer keyring of signer1853   * @param collectionId ID of collection1854   * @param tokenId ID of token1855   * @param addressObj address of a new owner1856   * @param amount number of pieces to be transfered1857   * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, 2000n)1858   * @returns ```true``` if extrinsic success, otherwise ```false```1859   */1860  async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId, amount=1n): Promise<boolean> {1861    return await super.transferToken(signer, collectionId, tokenId, addressObj, amount);1862  }18631864  /**1865   * Change ownership of some pieces of RFT on behalf of the owner.1866   * @param signer keyring of signer1867   * @param collectionId ID of collection1868   * @param tokenId ID of token1869   * @param fromAddressObj address on behalf of which the token will be sent1870   * @param toAddressObj new token owner1871   * @param amount number of pieces to be transfered1872   * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, {Substrate: "5DfhbVfww7ThF8q6f3i..."}, 2000n)1873   * @returns ```true``` if extrinsic success, otherwise ```false```1874   */1875  async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1876    return await super.transferTokenFrom(signer, collectionId, tokenId, fromAddressObj, toAddressObj, amount);1877  }18781879  /**1880   * Mint new collection1881   * @param signer keyring of signer1882   * @param collectionOptions Collection options1883   * @example1884   * mintCollection(aliceKeyring, {1885   *   name: 'New',1886   *   description: 'New collection',1887   *   tokenPrefix: 'NEW',1888   * })1889   * @returns object of the created collection1890   */1891  async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}): Promise<UniqueRFTCollection> {1892    return await super.mintCollection(signer, collectionOptions, 'RFT') as UniqueRFTCollection;1893  }18941895  /**1896   * Mint new token1897   * @param signer keyring of signer1898   * @param data token data1899   * @example mintToken(aliceKeyring, {collectionId: 10, owner: {Substrate: '5GHoZe9c73RYbVzq...'}, pieces: 10000n});1900   * @returns created token object1901   */1902  async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; pieces: bigint; properties?: IProperty[]; }): Promise<UniqueRFToken> {1903    const creationResult = await this.helper.executeExtrinsic(1904      signer,1905      'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {1906        refungible: {1907          pieces: data.pieces,1908          properties: data.properties,1909        },1910      }],1911      true,1912    );1913    const createdTokens = this.helper.util.extractTokensFromCreationResult(creationResult);1914    if (createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');1915    if (createdTokens.tokens.length < 1) throw Error('No tokens minted');1916    return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);1917  }19181919  async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: {owner: ICrossAccountId, pieces: bigint, properties?: IProperty[]}[]): Promise<UniqueRFToken[]> {1920    throw Error('Not implemented');1921    const creationResult = await this.helper.executeExtrinsic(1922      signer,1923      'api.tx.unique.createMultipleItemsEx', [collectionId, {RefungibleMultipleOwners: tokens}],1924      true, // `Unable to mint RFT tokens for ${label}`,1925    );1926    const collection = this.getCollectionObject(collectionId);1927    return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1928  }19291930  /**1931   * Mint multiple RFT tokens with one owner1932   * @param signer keyring of signer1933   * @param collectionId ID of collection1934   * @param owner tokens owner1935   * @param tokens array of tokens with properties and pieces1936   * @example mintMultipleTokensWithOneOwner(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, [{pieces: 100000n, properties: [{key: "gender", value: "male"}]}]);1937   * @returns array of newly created RFT tokens1938   */1939  async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {pieces: bigint, properties?: IProperty[]}[]): Promise<UniqueRFToken[]> {1940    const rawTokens = [];1941    for (const token of tokens) {1942      const raw = {ReFungible: {pieces: token.pieces, properties: token.properties}};1943      rawTokens.push(raw);1944    }1945    const creationResult = await this.helper.executeExtrinsic(1946      signer,1947      'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1948      true,1949    );1950    const collection = this.getCollectionObject(collectionId);1951    return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1952  }19531954  /**1955   * Destroys a concrete instance of RFT.1956   * @param signer keyring of signer1957   * @param collectionId ID of collection1958   * @param tokenId ID of token1959   * @param amount number of pieces to be burnt1960   * @example burnToken(aliceKeyring, 10, 5);1961   * @returns ```true``` if the extrinsic is successful, otherwise ```false```1962   */1963  async burnToken(signer: IKeyringPair, collectionId: number, tokenId: number, amount=1n): Promise<boolean> {1964    return await super.burnToken(signer, collectionId, tokenId, amount);1965  }19661967  /**1968   * Destroys a concrete instance of RFT on behalf of the owner.1969   * @param signer keyring of signer1970   * @param collectionId ID of collection1971   * @param tokenId ID of token1972   * @param fromAddressObj address on behalf of which the token will be burnt1973   * @param amount number of pieces to be burnt1974   * @example burnTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, 2n)1975   * @returns ```true``` if extrinsic success, otherwise ```false```1976   */1977  async burnTokenFrom(signer: IKeyringPair, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1978    return await super.burnTokenFrom(signer, collectionId, tokenId, fromAddressObj, amount);1979  }19801981  /**1982   * Set, change, or remove approved address to transfer the ownership of the RFT.1983   *1984   * @param signer keyring of signer1985   * @param collectionId ID of collection1986   * @param tokenId ID of token1987   * @param toAddressObj address to approve1988   * @param amount number of pieces to be approved1989   * @example approveToken(aliceKeyring, 10, 5, {Substrate: "5GHoZe9c73RYbVzq..."}, "", 10000n);1990   * @returns true if the token success, otherwise false1991   */1992  approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {1993    return super.approveToken(signer, collectionId, tokenId, toAddressObj, amount);1994  }19951996  /**1997   * Get total number of pieces1998   * @param collectionId ID of collection1999   * @param tokenId ID of token2000   * @example getTokenTotalPieces(10, 5);2001   * @returns number of pieces2002   */2003  async getTokenTotalPieces(collectionId: number, tokenId: number): Promise<bigint> {2004    return (await this.helper.callRpc('api.rpc.unique.totalPieces', [collectionId, tokenId])).unwrap().toBigInt();2005  }20062007  /**2008   * Change number of token pieces. Signer must be the owner of all token pieces.2009   * @param signer keyring of signer2010   * @param collectionId ID of collection2011   * @param tokenId ID of token2012   * @param amount new number of pieces2013   * @example repartitionToken(aliceKeyring, 10, 5, 12345n);2014   * @returns true if the repartion was success, otherwise false2015   */2016  async repartitionToken(signer: TSigner, collectionId: number, tokenId: number, amount: bigint): Promise<boolean> {2017    const currentAmount = await this.getTokenTotalPieces(collectionId, tokenId);2018    const repartitionResult = await this.helper.executeExtrinsic(2019      signer,2020      'api.tx.unique.repartition', [collectionId, tokenId, amount],2021      true,2022    );2023    if(currentAmount < amount) return this.helper.util.findCollectionInEvents(repartitionResult.result.events, collectionId, 'common', 'ItemCreated');2024    return this.helper.util.findCollectionInEvents(repartitionResult.result.events, collectionId, 'common', 'ItemDestroyed');2025  }2026}202720282029class FTGroup extends CollectionGroup {2030  /**2031   * Get collection object2032   * @param collectionId ID of collection2033   * @example getCollectionObject(2);2034   * @returns instance of UniqueFTCollection2035   */2036  getCollectionObject(collectionId: number): UniqueFTCollection {2037    return new UniqueFTCollection(collectionId, this.helper);2038  }20392040  /**2041   * Mint new fungible collection2042   * @param signer keyring of signer2043   * @param collectionOptions Collection options2044   * @param decimalPoints number of token decimals2045   * @example2046   * mintCollection(aliceKeyring, {2047   *   name: 'New',2048   *   description: 'New collection',2049   *   tokenPrefix: 'NEW',2050   * }, 18)2051   * @returns newly created fungible collection2052   */2053  async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}, decimalPoints = 0): Promise<UniqueFTCollection> {2054    collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; // Clone object2055    if(collectionOptions.tokenPropertyPermissions) throw Error('Fungible collections has no tokenPropertyPermissions');2056    collectionOptions.mode = {fungible: decimalPoints};2057    for (const key of ['name', 'description', 'tokenPrefix']) {2058      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);2059    }2060    const creationResult = await this.helper.executeExtrinsic(2061      signer,2062      'api.tx.unique.createCollectionEx', [collectionOptions],2063      true,2064    );2065    return this.getCollectionObject(this.helper.util.extractCollectionIdFromCreationResult(creationResult));2066  }20672068  /**2069   * Mint tokens2070   * @param signer keyring of signer2071   * @param collectionId ID of collection2072   * @param owner address owner of new tokens2073   * @param amount amount of tokens to be meanted2074   * @example mintTokens(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq"}, 1000n);2075   * @returns ```true``` if extrinsic success, otherwise ```false```2076   */2077  async mintTokens(signer: TSigner, collectionId: number, amount: bigint, owner: ICrossAccountId | string): Promise<boolean> {2078    const creationResult = await this.helper.executeExtrinsic(2079      signer,2080      'api.tx.unique.createItem', [collectionId, (typeof owner === 'string') ? {Substrate: owner} : owner, {2081        fungible: {2082          value: amount,2083        },2084      }],2085      true, // `Unable to mint fungible tokens for ${label}`,2086    );2087    return this.helper.util.findCollectionInEvents(creationResult.result.events, collectionId, 'common', 'ItemCreated');2088  }20892090  /**2091   * Mint multiple Fungible tokens with one owner2092   * @param signer keyring of signer2093   * @param collectionId ID of collection2094   * @param owner tokens owner2095   * @param tokens array of tokens with properties and pieces2096   * @returns ```true``` if extrinsic success, otherwise ```false```2097   */2098  async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, tokens: {value: bigint}[], owner: ICrossAccountId): Promise<boolean> {2099    const rawTokens = [];2100    for (const token of tokens) {2101      const raw = {Fungible: {Value: token.value}};2102      rawTokens.push(raw);2103    }2104    const creationResult = await this.helper.executeExtrinsic(2105      signer,2106      'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],2107      true,2108    );2109    return this.helper.util.findCollectionInEvents(creationResult.result.events, collectionId, 'common', 'ItemCreated');2110  }21112112  /**2113   * Get the top 10 owners with the largest balance for the Fungible collection2114   * @param collectionId ID of collection2115   * @example getTop10Owners(10);2116   * @returns array of ```ICrossAccountId```2117   */2118  async getTop10Owners(collectionId: number): Promise<CrossAccountId[]> {2119    return (await this.helper.callRpc('api.rpc.unique.tokenOwners', [collectionId, 0])).toJSON().map(CrossAccountId.fromLowerCaseKeys);2120  }21212122  /**2123   * Get account balance2124   * @param collectionId ID of collection2125   * @param addressObj address of owner2126   * @example getBalance(10, {Substrate: "5GHoZe9c73RYbVzq..."})2127   * @returns amount of fungible tokens owned by address2128   */2129  async getBalance(collectionId: number, addressObj: ICrossAccountId): Promise<bigint> {2130    return (await this.helper.callRpc('api.rpc.unique.balance', [collectionId, addressObj, 0])).toBigInt();2131  }21322133  /**2134   * Transfer tokens to address2135   * @param signer keyring of signer2136   * @param collectionId ID of collection2137   * @param toAddressObj address recipient2138   * @param amount amount of tokens to be sent2139   * @example transfer(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, 1000n);2140   * @returns ```true``` if extrinsic success, otherwise ```false```2141   */2142  async transfer(signer: TSigner, collectionId: number, toAddressObj: ICrossAccountId, amount=1n) {2143    return await super.transferToken(signer, collectionId, 0, toAddressObj, amount);2144  }21452146  /**2147   * Transfer some tokens on behalf of the owner.2148   * @param signer keyring of signer2149   * @param collectionId ID of collection2150   * @param fromAddressObj address on behalf of which tokens will be sent2151   * @param toAddressObj address where token to be sent2152   * @param amount number of tokens to be sent2153   * @example transferFrom(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, {Substrate: "5DfhbVfww7ThF8q6f3ij..."}, 10000n);2154   * @returns ```true``` if extrinsic success, otherwise ```false```2155   */2156  async transferFrom(signer: TSigner, collectionId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {2157    return await super.transferTokenFrom(signer, collectionId, 0, fromAddressObj, toAddressObj, amount);2158  }21592160  /**2161   * Destroy some amount of tokens2162   * @param signer keyring of signer2163   * @param collectionId ID of collection2164   * @param amount amount of tokens to be destroyed2165   * @example burnTokens(aliceKeyring, 10, 1000n);2166   * @returns ```true``` if extrinsic success, otherwise ```false```2167   */2168  async burnTokens(signer: IKeyringPair, collectionId: number, amount=1n): Promise<boolean> {2169    return await super.burnToken(signer, collectionId, 0, amount);2170  }21712172  /**2173   * Burn some tokens on behalf of the owner.2174   * @param signer keyring of signer2175   * @param collectionId ID of collection2176   * @param fromAddressObj address on behalf of which tokens will be burnt2177   * @param amount amount of tokens to be burnt2178   * @example burnTokensFrom(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, 1000n);2179   * @returns ```true``` if extrinsic success, otherwise ```false```2180   */2181  async burnTokensFrom(signer: IKeyringPair, collectionId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {2182    return await super.burnTokenFrom(signer, collectionId, 0, fromAddressObj, amount);2183  }21842185  /**2186   * Get total collection supply2187   * @param collectionId2188   * @returns2189   */2190  async getTotalPieces(collectionId: number): Promise<bigint> {2191    return (await this.helper.callRpc('api.rpc.unique.totalPieces', [collectionId, 0])).unwrap().toBigInt();2192  }21932194  /**2195   * Set, change, or remove approved address to transfer tokens.2196   *2197   * @param signer keyring of signer2198   * @param collectionId ID of collection2199   * @param toAddressObj address to be approved2200   * @param amount amount of tokens to be approved2201   * @example approveTokens(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, 1000n)2202   * @returns ```true``` if extrinsic success, otherwise ```false```2203   */2204  approveTokens(signer: IKeyringPair, collectionId: number, toAddressObj: ICrossAccountId, amount=1n) {2205    return super.approveToken(signer, collectionId, 0, toAddressObj, amount);2206  }22072208  /**2209   * Get amount of fungible tokens approved to transfer2210   * @param collectionId ID of collection2211   * @param fromAddressObj owner of tokens2212   * @param toAddressObj the address approved for the transfer of tokens on behalf of the owner2213   * @returns number of tokens approved for the transfer2214   */2215  getApprovedTokens(collectionId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2216    return super.getTokenApprovedPieces(collectionId, 0, toAddressObj, fromAddressObj);2217  }2218}221922202221class ChainGroup extends HelperGroup<ChainHelperBase> {2222  /**2223   * Get system properties of a chain2224   * @example getChainProperties();2225   * @returns ss58Format, token decimals, and token symbol2226   */2227  getChainProperties(): IChainProperties {2228    const properties = (this.helper.getApi() as any).registry.getChainProperties().toJSON();2229    return {2230      ss58Format: properties.ss58Format.toJSON(),2231      tokenDecimals: properties.tokenDecimals.toJSON(),2232      tokenSymbol: properties.tokenSymbol.toJSON(),2233    };2234  }22352236  /**2237   * Get chain header2238   * @example getLatestBlockNumber();2239   * @returns the number of the last block2240   */2241  async getLatestBlockNumber(): Promise<number> {2242    return (await this.helper.callRpc('api.rpc.chain.getHeader')).number.toNumber();2243  }22442245  /**2246   * Get block hash by block number2247   * @param blockNumber number of block2248   * @example getBlockHashByNumber(12345);2249   * @returns hash of a block2250   */2251  async getBlockHashByNumber(blockNumber: number): Promise<string | null> {2252    const blockHash = (await this.helper.callRpc('api.rpc.chain.getBlockHash', [blockNumber])).toJSON();2253    if(blockHash === '0x0000000000000000000000000000000000000000000000000000000000000000') return null;2254    return blockHash;2255  }22562257  // TODO add docs2258  async getBlock(blockHashOrNumber: string | number): Promise<IBlock | null> {2259    const blockHash = typeof blockHashOrNumber === 'string' ? blockHashOrNumber : await this.getBlockHashByNumber(blockHashOrNumber);2260    if (!blockHash) return null;2261    return (await this.helper.callRpc('api.rpc.chain.getBlock', [blockHash])).toHuman().block;2262  }22632264  /**2265   * Get latest relay block2266   * @returns {number} relay block2267   */2268  async getRelayBlockNumber(): Promise<bigint> {2269    const blockNumber = (await this.helper.callRpc('api.query.parachainSystem.validationData')).toJSON().relayParentNumber;2270    return BigInt(blockNumber);2271  }22722273  /**2274   * Get account nonce2275   * @param address substrate address2276   * @example getNonce("5GrwvaEF5zXb26Fz...");2277   * @returns number, account's nonce2278   */2279  async getNonce(address: TSubstrateAccount): Promise<number> {2280    return (await this.helper.callRpc('api.query.system.account', [address])).nonce.toNumber();2281  }2282}22832284class SubstrateBalanceGroup<T extends ChainHelperBase> extends HelperGroup<T> {2285  /**2286 * Get substrate address balance2287 * @param address substrate address2288 * @example getSubstrate("5GrwvaEF5zXb26Fz...")2289 * @returns amount of tokens on address2290 */2291  async getSubstrate(address: TSubstrateAccount): Promise<bigint> {2292    return (await this.helper.callRpc('api.query.system.account', [address])).data.free.toBigInt();2293  }22942295  /**2296   * Transfer tokens to substrate address2297   * @param signer keyring of signer2298   * @param address substrate address of a recipient2299   * @param amount amount of tokens to be transfered2300   * @example transferToSubstrate(aliceKeyring, "5GrwvaEF5zXb26Fz...", 100_000_000_000n);2301   * @returns ```true``` if extrinsic success, otherwise ```false```2302   */2303  async transferToSubstrate(signer: TSigner, address: TSubstrateAccount, amount: bigint | string): Promise<boolean> {2304    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}`*/);23052306    let transfer = {from: null, to: null, amount: 0n} as any;2307    result.result.events.forEach(({event: {data, method, section}}) => {2308      if ((section === 'balances') && (method === 'Transfer')) {2309        transfer = {2310          from: this.helper.address.normalizeSubstrate(data[0]),2311          to: this.helper.address.normalizeSubstrate(data[1]),2312          amount: BigInt(data[2]),2313        };2314      }2315    });2316    const isSuccess = this.helper.address.normalizeSubstrate(typeof signer === 'string' ? signer : signer.address) === transfer.from2317      && this.helper.address.normalizeSubstrate(address) === transfer.to2318      && BigInt(amount) === transfer.amount;2319    return isSuccess;2320  }23212322  /**2323   * Get full substrate balance including free, miscFrozen, feeFrozen, and reserved2324   * @param address substrate address2325   * @returns2326   */2327  async getSubstrateFull(address: TSubstrateAccount): Promise<ISubstrateBalance> {2328    const accountInfo = (await this.helper.callRpc('api.query.system.account', [address])).data;2329    return {free: accountInfo.free.toBigInt(), miscFrozen: accountInfo.miscFrozen.toBigInt(), feeFrozen: accountInfo.feeFrozen.toBigInt(), reserved: accountInfo.reserved.toBigInt()};2330  }23312332  async getLocked(address: TSubstrateAccount): Promise<[{id: string, amount: bigint, reason: string}]> {2333    const locks = (await this.helper.callRpc('api.query.balances.locks', [address])).toHuman();2334    return locks.map((lock: any) => {return {id: lock.id, amount: BigInt(lock.amount.replace(/,/g, '')), reasons: lock.reasons};});2335  }2336}23372338class EthereumBalanceGroup<T extends ChainHelperBase> extends HelperGroup<T> {2339  /**2340   * Get ethereum address balance2341   * @param address ethereum address2342   * @example getEthereum("0x9F0583DbB855d...")2343   * @returns amount of tokens on address2344   */2345  async getEthereum(address: TEthereumAccount): Promise<bigint> {2346    return (await this.helper.callRpc('api.rpc.eth.getBalance', [address])).toBigInt();2347  }23482349  /**2350   * Transfer tokens to address2351   * @param signer keyring of signer2352   * @param address Ethereum address of a recipient2353   * @param amount amount of tokens to be transfered2354   * @example transferToEthereum(alithKeyring, "0x9F0583DbB855d...", 100_000_000_000n);2355   * @returns ```true``` if extrinsic success, otherwise ```false```2356   */2357  async transferToEthereum(signer: TSigner, address: TEthereumAccount, amount: bigint | string): Promise<boolean> {2358    const result = await this.helper.executeExtrinsic(signer, 'api.tx.balances.transfer', [address, amount], true);23592360    let transfer = {from: null, to: null, amount: 0n} as any;2361    result.result.events.forEach(({event: {data, method, section}}) => {2362      if ((section === 'balances') && (method === 'Transfer')) {2363        transfer = {2364          from: data[0].toString(),2365          to: data[1].toString(),2366          amount: BigInt(data[2]),2367        };2368      }2369    });2370    const isSuccess = (typeof signer === 'string' ? signer : signer.address) === transfer.from2371      && address === transfer.to2372      && BigInt(amount) === transfer.amount;2373    return isSuccess;2374  }2375}23762377class BalanceGroup<T extends ChainHelperBase> extends HelperGroup<T> {2378  subBalanceGroup: SubstrateBalanceGroup<T>;2379  ethBalanceGroup: EthereumBalanceGroup<T>;23802381  constructor(helper: T) {2382    super(helper);2383    this.subBalanceGroup = new SubstrateBalanceGroup(helper);2384    this.ethBalanceGroup = new EthereumBalanceGroup(helper);2385  }23862387  getCollectionCreationPrice(): bigint {2388    return 2n * this.getOneTokenNominal();2389  }2390  /**2391   * Representation of the native token in the smallest unit - one OPAL (OPL), QUARTZ (QTZ), or UNIQUE (UNQ).2392   * @example getOneTokenNominal()2393   * @returns ```BigInt``` representation of the native token in the smallest unit, e.g. ```1_000_000_000_000_000_000n``` for QTZ.2394   */2395  getOneTokenNominal(): bigint {2396    const chainProperties = this.helper.chain.getChainProperties();2397    return 10n ** BigInt((chainProperties.tokenDecimals || [18])[0]);2398  }23992400  /**2401   * Get substrate address balance2402   * @param address substrate address2403   * @example getSubstrate("5GrwvaEF5zXb26Fz...")2404   * @returns amount of tokens on address2405   */2406  getSubstrate(address: TSubstrateAccount): Promise<bigint> {2407    return this.subBalanceGroup.getSubstrate(address);2408  }24092410  /**2411   * Get full substrate balance including free, miscFrozen, feeFrozen, and reserved2412   * @param address substrate address2413   * @returns2414   */2415  getSubstrateFull(address: TSubstrateAccount): Promise<ISubstrateBalance> {2416    return this.subBalanceGroup.getSubstrateFull(address);2417  }24182419  /**2420   * Get locked balances2421   * @param address substrate address2422   * @returns locked balances with reason via api.query.balances.locks2423   */2424  getLocked(address: TSubstrateAccount) {2425    return this.subBalanceGroup.getLocked(address);2426  }24272428  /**2429   * Get ethereum address balance2430   * @param address ethereum address2431   * @example getEthereum("0x9F0583DbB855d...")2432   * @returns amount of tokens on address2433   */2434  getEthereum(address: TEthereumAccount): Promise<bigint> {2435    return this.ethBalanceGroup.getEthereum(address);2436  }24372438  /**2439   * Transfer tokens to substrate address2440   * @param signer keyring of signer2441   * @param address substrate address of a recipient2442   * @param amount amount of tokens to be transfered2443   * @example transferToSubstrate(aliceKeyring, "5GrwvaEF5zXb26Fz...", 100_000_000_000n);2444   * @returns ```true``` if extrinsic success, otherwise ```false```2445   */2446  transferToSubstrate(signer: TSigner, address: TSubstrateAccount, amount: bigint | string): Promise<boolean> {2447    return this.subBalanceGroup.transferToSubstrate(signer, address, amount);2448  }24492450  async forceTransferToSubstrate(signer: TSigner, from: TSubstrateAccount, to: TSubstrateAccount, amount: bigint | string): Promise<boolean> {2451    const result = await this.helper.executeExtrinsic(signer, 'api.tx.balances.forceTransfer', [from, to, amount], true);24522453    let transfer = {from: null, to: null, amount: 0n} as any;2454    result.result.events.forEach(({event: {data, method, section}}) => {2455      if ((section === 'balances') && (method === 'Transfer')) {2456        transfer = {2457          from: this.helper.address.normalizeSubstrate(data[0]),2458          to: this.helper.address.normalizeSubstrate(data[1]),2459          amount: BigInt(data[2]),2460        };2461      }2462    });2463    let isSuccess = this.helper.address.normalizeSubstrate(from) === transfer.from;2464    isSuccess = isSuccess && this.helper.address.normalizeSubstrate(to) === transfer.to;2465    isSuccess = isSuccess && BigInt(amount) === transfer.amount;2466    return isSuccess;2467  }24682469  /**2470   * Transfer tokens with the unlock period2471   * @param signer signers Keyring2472   * @param address Substrate address of recipient2473   * @param schedule Schedule params2474   * @example vestedTransfer(signer, recepient.address, 20000, 100, 10, 50 * nominal); // total amount of vested tokens will be 100 * 50 = 50002475   */2476  async vestedTransfer(signer: TSigner, address: TSubstrateAccount, schedule: {start: bigint, period: bigint, periodCount: bigint, perPeriod: bigint}): Promise<void> {2477    const result = await this.helper.executeExtrinsic(signer, 'api.tx.vesting.vestedTransfer', [address, schedule]);2478    const event = result.result.events2479      .find(e => e.event.section === 'vesting' &&2480            e.event.method === 'VestingScheduleAdded' &&2481            e.event.data[0].toHuman() === signer.address);2482    if (!event) throw Error('Cannot find transfer in events');2483  }24842485  /**2486   * Get schedule for recepient of vested transfer2487   * @param address Substrate address of recipient2488   * @returns2489   */2490  async getVestingSchedules(address: TSubstrateAccount): Promise<{start: bigint, period: bigint, periodCount: bigint, perPeriod: bigint}[]> {2491    const schedule = (await this.helper.callRpc('api.query.vesting.vestingSchedules', [address])).toJSON();2492    return schedule.map((schedule: any) => {2493      return {2494        start: BigInt(schedule.start),2495        period: BigInt(schedule.period),2496        periodCount: BigInt(schedule.periodCount),2497        perPeriod: BigInt(schedule.perPeriod),2498      };2499    });2500  }25012502  /**2503   * Claim vested tokens2504   * @param signer signers Keyring2505   */2506  async claim(signer: TSigner) {2507    const result = await this.helper.executeExtrinsic(signer, 'api.tx.vesting.claim', []);2508    const event = result.result.events2509      .find(e => e.event.section === 'vesting' &&2510            e.event.method === 'Claimed' &&2511            e.event.data[0].toHuman() === signer.address);2512    if (!event) throw Error('Cannot find claim in events');2513  }2514}25152516class AddressGroup extends HelperGroup<ChainHelperBase> {2517  /**2518   * Normalizes the address to the specified ss58 format, by default ```42```.2519   * @param address substrate address2520   * @param ss58Format format for address conversion, by default ```42```2521   * @example normalizeSubstrate("unjKJQJrRd238pkUZZvzDQrfKuM39zBSnQ5zjAGAGcdRhaJTx") // returns 5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY2522   * @returns substrate address converted to normalized (i.e., starting with 5) or specified explicitly representation2523   */2524  normalizeSubstrate(address: TSubstrateAccount, ss58Format = 42): TSubstrateAccount {2525    return CrossAccountId.normalizeSubstrateAddress(address, ss58Format);2526  }25272528  /**2529   * Get address in the connected chain format2530   * @param address substrate address2531   * @example normalizeSubstrateToChainFormat("5GrwvaEF5zXb26Fz...") // returns unjKJQJrRd238pkUZZ... for Unique Network2532   * @returns address in chain format2533   */2534  normalizeSubstrateToChainFormat(address: TSubstrateAccount): TSubstrateAccount {2535    return this.normalizeSubstrate(address, this.helper.chain.getChainProperties().ss58Format);2536  }25372538  /**2539   * Get substrate mirror of an ethereum address2540   * @param ethAddress ethereum address2541   * @param toChainFormat false for normalized account2542   * @example ethToSubstrate('0x9F0583DbB855d...')2543   * @returns substrate mirror of a provided ethereum address2544   */2545  ethToSubstrate(ethAddress: TEthereumAccount, toChainFormat=false): TSubstrateAccount {2546    return CrossAccountId.translateEthToSub(ethAddress, toChainFormat ? this.helper.chain.getChainProperties().ss58Format : undefined);2547  }25482549  /**2550   * Get ethereum mirror of a substrate address2551   * @param subAddress substrate account2552   * @example substrateToEth("5DnSF6RRjwteE3BrC...")2553   * @returns ethereum mirror of a provided substrate address2554   */2555  substrateToEth(subAddress: TSubstrateAccount): TEthereumAccount {2556    return CrossAccountId.translateSubToEth(subAddress);2557  }25582559  /**2560   * Encode key to substrate address2561   * @param key key for encoding address2562   * @param ss58Format prefix for encoding to the address of the corresponding network2563   * @returns encoded substrate address2564   */2565  encodeSubstrateAddress (key: Uint8Array | string | bigint, ss58Format = 42): string {2566    const u8a :Uint8Array = typeof key === 'string'2567      ? hexToU8a(key)2568      : typeof key === 'bigint'2569        ? hexToU8a(key.toString(16))2570        : key;25712572    if (ss58Format < 0 || ss58Format > 16383 || [46, 47].includes(ss58Format)) {2573      throw new Error(`ss58Format is not valid, received ${typeof ss58Format} "${ss58Format}"`);2574    }25752576    const allowedDecodedLengths = [1, 2, 4, 8, 32, 33];2577    if (!allowedDecodedLengths.includes(u8a.length)) {2578      throw new Error(`key length is not valid, received ${u8a.length}, valid values are ${allowedDecodedLengths.join(', ')}`);2579    }25802581    const u8aPrefix = ss58Format < 642582      ? new Uint8Array([ss58Format])2583      : new Uint8Array([2584        ((ss58Format & 0xfc) >> 2) | 0x40,2585        (ss58Format >> 8) | ((ss58Format & 0x03) << 6),2586      ]);25872588    const input = u8aConcat(u8aPrefix, u8a);25892590    return base58Encode(u8aConcat(2591      input,2592      blake2AsU8a(input).subarray(0, [32, 33].includes(u8a.length) ? 2 : 1),2593    ));2594  }25952596  /**2597   * Restore substrate address from bigint representation2598   * @param number decimal representation of substrate address2599   * @returns substrate address2600   */2601  restoreCrossAccountFromBigInt(number: bigint): TSubstrateAccount {2602    if (this.helper.api === null) {2603      throw 'Not connected';2604    }2605    const res = this.helper.api.registry.createType('AccountId', '0x' + number.toString(16).padStart(64, '0')).toJSON();2606    if (res === undefined || res === null) {2607      throw 'Restore address error';2608    }2609    return res.toString();2610  }26112612  /**2613   * Convert etherium cross account id to substrate cross account id2614   * @param ethCrossAccount etherium cross account2615   * @returns substrate cross account id2616   */2617  convertCrossAccountFromEthCrossAccount(ethCrossAccount: IEthCrossAccountId): ICrossAccountId {2618    if (ethCrossAccount.sub === '0') {2619      return {Ethereum: ethCrossAccount.eth.toLocaleLowerCase()};2620    }26212622    const ss58 = this.restoreCrossAccountFromBigInt(BigInt(ethCrossAccount.sub));2623    return {Substrate: ss58};2624  }26252626  paraSiblingSovereignAccount(paraid: number) {2627    // We are getting a *sibling* parachain sovereign account,2628    // so we need a sibling prefix: encoded(b"sibl") == 0x7369626c2629    const siblingPrefix = '0x7369626c';26302631    const encodedParaId = this.helper.getApi().createType('u32', paraid).toHex(true).substring(2);2632    const suffix = '000000000000000000000000000000000000000000000000';26332634    return siblingPrefix + encodedParaId + suffix;2635  }2636}26372638class StakingGroup extends HelperGroup<UniqueHelper> {2639  /**2640   * Stake tokens for App Promotion2641   * @param signer keyring of signer2642   * @param amountToStake amount of tokens to stake2643   * @param label extra label for log2644   * @returns2645   */2646  async stake(signer: TSigner, amountToStake: bigint, label?: string): Promise<boolean> {2647    if(typeof label === 'undefined') label = `${signer.address} amount: ${amountToStake}`;2648    const _stakeResult = await this.helper.executeExtrinsic(2649      signer, 'api.tx.appPromotion.stake',2650      [amountToStake], true,2651    );2652    // TODO extract info from stakeResult2653    return true;2654  }26552656  /**2657   * Unstake tokens for App Promotion2658   * @param signer keyring of signer2659   * @param amountToUnstake amount of tokens to unstake2660   * @param label extra label for log2661   * @returns block number where balances will be unlocked2662   */2663  async unstake(signer: TSigner, label?: string): Promise<number> {2664    if(typeof label === 'undefined') label = `${signer.address}`;2665    const _unstakeResult = await this.helper.executeExtrinsic(2666      signer, 'api.tx.appPromotion.unstake',2667      [], true,2668    );2669    // TODO extract block number fron events2670    return 1;2671  }26722673  /**2674   * Get total staked amount for address2675   * @param address substrate or ethereum address2676   * @returns total staked amount2677   */2678  async getTotalStaked(address?: ICrossAccountId): Promise<bigint> {2679    if (address) return (await this.helper.callRpc('api.rpc.appPromotion.totalStaked', [address])).toBigInt();2680    return (await this.helper.callRpc('api.rpc.appPromotion.totalStaked')).toBigInt();2681  }26822683  /**2684   * Get total staked per block2685   * @param address substrate or ethereum address2686   * @returns array of stakes. `block` – the number of the block in which the stake was made. `amount` - the number of tokens staked in the block2687   */2688  async getTotalStakedPerBlock(address: ICrossAccountId): Promise<IStakingInfo[]> {2689    const rawTotalStakerdPerBlock = await this.helper.callRpc('api.rpc.appPromotion.totalStakedPerBlock', [address]);2690    return rawTotalStakerdPerBlock.map(([block, amount]: any[]) => {2691      return {2692        block: block.toBigInt(),2693        amount: amount.toBigInt(),2694      };2695    });2696  }26972698  /**2699   * Get total pending unstake amount for address2700   * @param address substrate or ethereum address2701   * @returns total pending unstake amount2702   */2703  async getPendingUnstake(address: ICrossAccountId): Promise<bigint> {2704    return (await this.helper.callRpc('api.rpc.appPromotion.pendingUnstake', [address])).toBigInt();2705  }27062707  /**2708   * Get pending unstake amount per block for address2709   * @param address substrate or ethereum address2710   * @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 block2711   */2712  async getPendingUnstakePerBlock(address: ICrossAccountId): Promise<IStakingInfo[]> {2713    const rawUnstakedPerBlock = await this.helper.callRpc('api.rpc.appPromotion.pendingUnstakePerBlock', [address]);2714    const result = rawUnstakedPerBlock.map(([block, amount]: any[]) => {2715      return {2716        block: block.toBigInt(),2717        amount: amount.toBigInt(),2718      };2719    });2720    return result;2721  }2722}27232724class SchedulerGroup extends HelperGroup<UniqueHelper> {2725  constructor(helper: UniqueHelper) {2726    super(helper);2727  }27282729  cancelScheduled(signer: TSigner, scheduledId: string) {2730    return this.helper.executeExtrinsic(2731      signer,2732      'api.tx.scheduler.cancelNamed',2733      [scheduledId],2734      true,2735    );2736  }27372738  changePriority(signer: TSigner, scheduledId: string, priority: number) {2739    return this.helper.executeExtrinsic(2740      signer,2741      'api.tx.scheduler.changeNamedPriority',2742      [scheduledId, priority],2743      true,2744    );2745  }27462747  scheduleAt<T extends UniqueHelper>(2748    executionBlockNumber: number,2749    options: ISchedulerOptions = {},2750  ) {2751    return this.schedule<T>('schedule', executionBlockNumber, options);2752  }27532754  scheduleAfter<T extends UniqueHelper>(2755    blocksBeforeExecution: number,2756    options: ISchedulerOptions = {},2757  ) {2758    return this.schedule<T>('scheduleAfter', blocksBeforeExecution, options);2759  }27602761  schedule<T extends UniqueHelper>(2762    scheduleFn: 'schedule' | 'scheduleAfter',2763    blocksNum: number,2764    options: ISchedulerOptions = {},2765  ) {2766    // eslint-disable-next-line @typescript-eslint/naming-convention2767    const ScheduledHelperType = ScheduledUniqueHelper(this.helper.helperBase);2768    return this.helper.clone(ScheduledHelperType, {2769      scheduleFn,2770      blocksNum,2771      options,2772    }) as T;2773  }2774}27752776class CollatorSelectionGroup extends HelperGroup<UniqueHelper> {2777  //todo:collator documentation2778  addInvulnerable(signer: TSigner, address: string) {2779    return this.helper.executeExtrinsic(signer, 'api.tx.collatorSelection.addInvulnerable', [address]);2780  }27812782  removeInvulnerable(signer: TSigner, address: string) {2783    return this.helper.executeExtrinsic(signer, 'api.tx.collatorSelection.removeInvulnerable', [address]);2784  }27852786  async getInvulnerables(): Promise<string[]> {2787    return (await this.helper.callRpc('api.query.collatorSelection.invulnerables')).map((x: any) => x.toHuman());2788  }27892790  /** and also total max invulnerables */2791  maxCollators(): number {2792    return (this.helper.getApi().consts.configuration.defaultCollatorSelectionMaxCollators.toJSON() as number);2793  }27942795  async getDesiredCollators(): Promise<number> {2796    return (await this.helper.callRpc('api.query.configuration.collatorSelectionDesiredCollatorsOverride')).toNumber();2797  }27982799  setLicenseBond(signer: TSigner, amount: bigint) {2800    return this.helper.executeExtrinsic(signer, 'api.tx.configuration.setCollatorSelectionLicenseBond', [amount]);2801  }28022803  async getLicenseBond(): Promise<bigint> {2804    return (await this.helper.callRpc('api.query.configuration.collatorSelectionLicenseBondOverride')).toBigInt();2805  }28062807  obtainLicense(signer: TSigner) {2808    return this.helper.executeExtrinsic(signer, 'api.tx.collatorSelection.getLicense', []);2809  }28102811  releaseLicense(signer: TSigner) {2812    return this.helper.executeExtrinsic(signer, 'api.tx.collatorSelection.releaseLicense', []);2813  }28142815  forceReleaseLicense(signer: TSigner, released: string) {2816    return this.helper.executeExtrinsic(signer, 'api.tx.collatorSelection.forceReleaseLicense', [released]);2817  }28182819  async hasLicense(address: string): Promise<bigint> {2820    return (await this.helper.callRpc('api.query.collatorSelection.licenseDepositOf', [address])).toBigInt();2821  }28222823  onboard(signer: TSigner) {2824    return this.helper.executeExtrinsic(signer, 'api.tx.collatorSelection.onboard', []);2825  }28262827  offboard(signer: TSigner) {2828    return this.helper.executeExtrinsic(signer, 'api.tx.collatorSelection.offboard', []);2829  }28302831  async getCandidates(): Promise<string[]> {2832    return (await this.helper.callRpc('api.query.collatorSelection.candidates')).map((x: any) => x.toHuman());2833  }2834}28352836class ForeignAssetsGroup extends HelperGroup<UniqueHelper> {2837  async register(signer: TSigner, ownerAddress: TSubstrateAccount, location: any, metadata: IForeignAssetMetadata) {2838    await this.helper.executeExtrinsic(2839      signer,2840      'api.tx.foreignAssets.registerForeignAsset',2841      [ownerAddress, location, metadata],2842      true,2843    );2844  }28452846  async update(signer: TSigner, foreignAssetId: number, location: any, metadata: IForeignAssetMetadata) {2847    await this.helper.executeExtrinsic(2848      signer,2849      'api.tx.foreignAssets.updateForeignAsset',2850      [foreignAssetId, location, metadata],2851      true,2852    );2853  }2854}28552856class XcmGroup<T extends ChainHelperBase> extends HelperGroup<T> {2857  palletName: string;28582859  constructor(helper: T, palletName: string) {2860    super(helper);28612862    this.palletName = palletName;2863  }28642865  async limitedReserveTransferAssets(signer: TSigner, destination: any, beneficiary: any, assets: any, feeAssetItem: number, weightLimit: any) {2866    await this.helper.executeExtrinsic(signer, `api.tx.${this.palletName}.limitedReserveTransferAssets`, [destination, beneficiary, assets, feeAssetItem, weightLimit], true);2867  }28682869  async teleportAssets(signer: TSigner, destination: any, beneficiary: any, assets: any, feeAssetItem: number) {2870    await this.helper.executeExtrinsic(signer, `api.tx.${this.palletName}.teleportAssets`, [destination, beneficiary, assets, feeAssetItem], true);2871  }28722873  async teleportNativeAsset(signer: TSigner, destinationParaId: number, targetAccount: Uint8Array, amount: bigint) {2874    const destination = {2875      V1: {2876        parents: 0,2877        interior: {2878          X1: {2879            Parachain: destinationParaId,2880          },2881        },2882      },2883    };28842885    const beneficiary = {2886      V1: {2887        parents: 0,2888        interior: {2889          X1: {2890            AccountId32: {2891              network: 'Any',2892              id: targetAccount,2893            },2894          },2895        },2896      },2897    };28982899    const assets = {2900      V1: [2901        {2902          id: {2903            Concrete: {2904              parents: 0,2905              interior: 'Here',2906            },2907          },2908          fun: {2909            Fungible: amount,2910          },2911        },2912      ],2913    };29142915    const feeAssetItem = 0;29162917    await this.teleportAssets(signer, destination, beneficiary, assets, feeAssetItem);2918  }2919}29202921class XTokensGroup<T extends ChainHelperBase> extends HelperGroup<T> {2922  async transfer(signer: TSigner, currencyId: any, amount: bigint, destination: any, destWeight: any) {2923    await this.helper.executeExtrinsic(signer, 'api.tx.xTokens.transfer', [currencyId, amount, destination, destWeight], true);2924  }29252926  async transferMultiasset(signer: TSigner, asset: any, destination: any, destWeight: any) {2927    await this.helper.executeExtrinsic(signer, 'api.tx.xTokens.transferMultiasset', [asset, destination, destWeight], true);2928  }29292930  async transferMulticurrencies(signer: TSigner, currencies: any[], feeItem: number, destLocation: any, destWeight: any) {2931    await this.helper.executeExtrinsic(signer, 'api.tx.xTokens.transferMulticurrencies', [currencies, feeItem, destLocation, destWeight], true);2932  }2933}29342935class TokensGroup<T extends ChainHelperBase> extends HelperGroup<T> {2936  async accounts(address: string, currencyId: any) {2937    const {free} = (await this.helper.callRpc('api.query.tokens.accounts', [address, currencyId])).toJSON() as any;2938    return BigInt(free);2939  }2940}29412942class AssetsGroup<T extends ChainHelperBase> extends HelperGroup<T> {2943  async create(signer: TSigner, assetId: number, admin: string, minimalBalance: bigint) {2944    await this.helper.executeExtrinsic(signer, 'api.tx.assets.create', [assetId, admin, minimalBalance], true);2945  }29462947  async setMetadata(signer: TSigner, assetId: number, name: string, symbol: string, decimals: number) {2948    await this.helper.executeExtrinsic(signer, 'api.tx.assets.setMetadata', [assetId, name, symbol, decimals], true);2949  }29502951  async mint(signer: TSigner, assetId: number, beneficiary: string, amount: bigint) {2952    await this.helper.executeExtrinsic(signer, 'api.tx.assets.mint', [assetId, beneficiary, amount], true);2953  }29542955  async account(assetId: string | number, address: string) {2956    const accountAsset = (2957      await this.helper.callRpc('api.query.assets.account', [assetId, address])2958    ).toJSON()! as any;29592960    if (accountAsset !== null) {2961      return BigInt(accountAsset['balance']);2962    } else {2963      return null;2964    }2965  }2966}29672968class AcalaAssetRegistryGroup extends HelperGroup<AcalaHelper> {2969  async registerForeignAsset(signer: TSigner, destination: any, metadata: AcalaAssetMetadata) {2970    await this.helper.executeExtrinsic(signer, 'api.tx.assetRegistry.registerForeignAsset', [destination, metadata], true);2971  }2972}29732974class MoonbeamAssetManagerGroup extends HelperGroup<MoonbeamHelper> {2975  makeRegisterForeignAssetProposal(assetInfo: MoonbeamAssetInfo) {2976    const apiPrefix = 'api.tx.assetManager.';29772978    const registerTx = this.helper.constructApiCall(2979      apiPrefix + 'registerForeignAsset',2980      [assetInfo.location, assetInfo.metadata, assetInfo.existentialDeposit, assetInfo.isSufficient],2981    );29822983    const setUnitsTx = this.helper.constructApiCall(2984      apiPrefix + 'setAssetUnitsPerSecond',2985      [assetInfo.location, assetInfo.unitsPerSecond, assetInfo.numAssetsWeightHint],2986    );29872988    const batchCall = this.helper.getApi().tx.utility.batchAll([registerTx, setUnitsTx]);2989    const encodedProposal = batchCall?.method.toHex() || '';2990    return encodedProposal;2991  }29922993  async assetTypeId(location: any) {2994    return await this.helper.callRpc('api.query.assetManager.assetTypeId', [location]);2995  }2996}29972998class MoonbeamDemocracyGroup extends HelperGroup<MoonbeamHelper> {2999  notePreimagePallet: string;30003001  constructor(helper: MoonbeamHelper, options: {[key: string]: any} = {}) {3002    super(helper);3003    this.notePreimagePallet = options.notePreimagePallet;3004  }30053006  async notePreimage(signer: TSigner, encodedProposal: string) {3007    await this.helper.executeExtrinsic(signer, `api.tx.${this.notePreimagePallet}.notePreimage`, [encodedProposal], true);3008  }30093010  externalProposeMajority(proposal: any) {3011    return this.helper.constructApiCall('api.tx.democracy.externalProposeMajority', [proposal]);3012  }30133014  fastTrack(proposalHash: string, votingPeriod: number, delayPeriod: number) {3015    return this.helper.constructApiCall('api.tx.democracy.fastTrack', [proposalHash, votingPeriod, delayPeriod]);3016  }30173018  async referendumVote(signer: TSigner, referendumIndex: number, accountVote: DemocracyStandardAccountVote) {3019    await this.helper.executeExtrinsic(signer, 'api.tx.democracy.vote', [referendumIndex, {Standard: accountVote}], true);3020  }3021}30223023class MoonbeamCollectiveGroup extends HelperGroup<MoonbeamHelper> {3024  collective: string;30253026  constructor(helper: MoonbeamHelper, collective: string) {3027    super(helper);30283029    this.collective = collective;3030  }30313032  async propose(signer: TSigner, threshold: number, proposalHash: string, lengthBound: number) {3033    await this.helper.executeExtrinsic(signer, `api.tx.${this.collective}.propose`, [threshold, proposalHash, lengthBound], true);3034  }30353036  async vote(signer: TSigner, proposalHash: string, proposalIndex: number, approve: boolean) {3037    await this.helper.executeExtrinsic(signer, `api.tx.${this.collective}.vote`, [proposalHash, proposalIndex, approve], true);3038  }30393040  async close(signer: TSigner, proposalHash: string, proposalIndex: number, weightBound: any, lengthBound: number) {3041    await this.helper.executeExtrinsic(signer, `api.tx.${this.collective}.close`, [proposalHash, proposalIndex, weightBound, lengthBound], true);3042  }30433044  async proposalCount() {3045    return Number(await this.helper.callRpc(`api.query.${this.collective}.proposalCount`, []));3046  }3047}30483049export type ChainHelperBaseConstructor = new(...args: any[]) => ChainHelperBase;3050export type UniqueHelperConstructor = new(...args: any[]) => UniqueHelper;30513052export class UniqueHelper extends ChainHelperBase {3053  balance: BalanceGroup<UniqueHelper>;3054  collection: CollectionGroup;3055  nft: NFTGroup;3056  rft: RFTGroup;3057  ft: FTGroup;3058  staking: StakingGroup;3059  scheduler: SchedulerGroup;3060  collatorSelection: CollatorSelectionGroup;3061  foreignAssets: ForeignAssetsGroup;3062  xcm: XcmGroup<UniqueHelper>;3063  xTokens: XTokensGroup<UniqueHelper>;3064  tokens: TokensGroup<UniqueHelper>;30653066  constructor(logger?: ILogger, options: {[key: string]: any} = {}) {3067    super(logger, options.helperBase ?? UniqueHelper);30683069    this.balance = new BalanceGroup(this);3070    this.collection = new CollectionGroup(this);3071    this.nft = new NFTGroup(this);3072    this.rft = new RFTGroup(this);3073    this.ft = new FTGroup(this);3074    this.staking = new StakingGroup(this);3075    this.scheduler = new SchedulerGroup(this);3076    this.collatorSelection = new CollatorSelectionGroup(this);3077    this.foreignAssets = new ForeignAssetsGroup(this);3078    this.xcm = new XcmGroup(this, 'polkadotXcm');3079    this.xTokens = new XTokensGroup(this);3080    this.tokens = new TokensGroup(this);3081  }30823083  getSudo<T extends UniqueHelper>() {3084    // eslint-disable-next-line @typescript-eslint/naming-convention3085    const SudoHelperType = SudoHelper(this.helperBase);3086    return this.clone(SudoHelperType) as T;3087  }3088}30893090export class XcmChainHelper extends ChainHelperBase {3091  async connect(wsEndpoint: string, _listeners?: any): Promise<void> {3092    const wsProvider = new WsProvider(wsEndpoint);3093    this.api = new ApiPromise({3094      provider: wsProvider,3095    });3096    await this.api.isReadyOrError;3097    this.network = await UniqueHelper.detectNetwork(this.api);3098  }3099}31003101export class RelayHelper extends XcmChainHelper {3102  balance: SubstrateBalanceGroup<RelayHelper>;3103  xcm: XcmGroup<RelayHelper>;31043105  constructor(logger?: ILogger, options: {[key: string]: any} = {}) {3106    super(logger, options.helperBase ?? RelayHelper);31073108    this.balance = new SubstrateBalanceGroup(this);3109    this.xcm = new XcmGroup(this, 'xcmPallet');3110  }3111}31123113export class WestmintHelper extends XcmChainHelper {3114  balance: SubstrateBalanceGroup<WestmintHelper>;3115  xcm: XcmGroup<WestmintHelper>;3116  assets: AssetsGroup<WestmintHelper>;3117  xTokens: XTokensGroup<WestmintHelper>;31183119  constructor(logger?: ILogger, options: {[key: string]: any} = {}) {3120    super(logger, options.helperBase ?? WestmintHelper);31213122    this.balance = new SubstrateBalanceGroup(this);3123    this.xcm = new XcmGroup(this, 'polkadotXcm');3124    this.assets = new AssetsGroup(this);3125    this.xTokens = new XTokensGroup(this);3126  }3127}31283129export class MoonbeamHelper extends XcmChainHelper {3130  balance: EthereumBalanceGroup<MoonbeamHelper>;3131  assetManager: MoonbeamAssetManagerGroup;3132  assets: AssetsGroup<MoonbeamHelper>;3133  xTokens: XTokensGroup<MoonbeamHelper>;3134  democracy: MoonbeamDemocracyGroup;3135  collective: {3136    council: MoonbeamCollectiveGroup,3137    techCommittee: MoonbeamCollectiveGroup,3138  };31393140  constructor(logger?: ILogger, options: {[key: string]: any} = {}) {3141    super(logger, options.helperBase ?? MoonbeamHelper);31423143    this.balance = new EthereumBalanceGroup(this);3144    this.assetManager = new MoonbeamAssetManagerGroup(this);3145    this.assets = new AssetsGroup(this);3146    this.xTokens = new XTokensGroup(this);3147    this.democracy = new MoonbeamDemocracyGroup(this, options);3148    this.collective = {3149      council: new MoonbeamCollectiveGroup(this, 'councilCollective'),3150      techCommittee: new MoonbeamCollectiveGroup(this, 'techCommitteeCollective'),3151    };3152  }3153}31543155export class AcalaHelper extends XcmChainHelper {3156  balance: SubstrateBalanceGroup<AcalaHelper>;3157  assetRegistry: AcalaAssetRegistryGroup;3158  xTokens: XTokensGroup<AcalaHelper>;3159  tokens: TokensGroup<AcalaHelper>;31603161  constructor(logger?: ILogger, options: {[key: string]: any} = {}) {3162    super(logger, options.helperBase ?? AcalaHelper);31633164    this.balance = new SubstrateBalanceGroup(this);3165    this.assetRegistry = new AcalaAssetRegistryGroup(this);3166    this.xTokens = new XTokensGroup(this);3167    this.tokens = new TokensGroup(this);3168  }31693170  getSudo<T extends AcalaHelper>() {3171    // eslint-disable-next-line @typescript-eslint/naming-convention3172    const SudoHelperType = SudoHelper(this.helperBase);3173    return this.clone(SudoHelperType) as T;3174  }3175}31763177// eslint-disable-next-line @typescript-eslint/naming-convention3178function ScheduledUniqueHelper<T extends UniqueHelperConstructor>(Base: T) {3179  return class extends Base {3180    scheduleFn: 'schedule' | 'scheduleAfter';3181    blocksNum: number;3182    options: ISchedulerOptions;31833184    constructor(...args: any[]) {3185      const logger = args[0] as ILogger;3186      const options = args[1] as {3187        scheduleFn: 'schedule' | 'scheduleAfter',3188        blocksNum: number,3189        options: ISchedulerOptions3190      };31913192      super(logger);31933194      this.scheduleFn = options.scheduleFn;3195      this.blocksNum = options.blocksNum;3196      this.options = options.options;3197    }31983199    executeExtrinsic(sender: IKeyringPair, scheduledExtrinsic: string, scheduledParams: any[], expectSuccess?: boolean): Promise<ITransactionResult> {3200      const scheduledTx = this.constructApiCall(scheduledExtrinsic, scheduledParams);32013202      const mandatorySchedArgs = [3203        this.blocksNum,3204        this.options.periodic ? [this.options.periodic.period, this.options.periodic.repetitions] : null,3205        this.options.priority ?? null,3206        scheduledTx,3207      ];32083209      let schedArgs;3210      let scheduleFn;32113212      if (this.options.scheduledId) {3213        schedArgs = [this.options.scheduledId!, ...mandatorySchedArgs];32143215        if (this.scheduleFn == 'schedule') {3216          scheduleFn = 'scheduleNamed';3217        } else if (this.scheduleFn == 'scheduleAfter') {3218          scheduleFn = 'scheduleNamedAfter';3219        }3220      } else {3221        schedArgs = mandatorySchedArgs;3222        scheduleFn = this.scheduleFn;3223      }32243225      const extrinsic = 'api.tx.scheduler.' +  scheduleFn;32263227      return super.executeExtrinsic(3228        sender,3229        extrinsic,3230        schedArgs,3231        expectSuccess,3232      );3233    }3234  };3235}32363237// eslint-disable-next-line @typescript-eslint/naming-convention3238function SudoHelper<T extends ChainHelperBaseConstructor>(Base: T) {3239  return class extends Base {3240    constructor(...args: any[]) {3241      super(...args);3242    }32433244    async executeExtrinsic(3245      sender: IKeyringPair,3246      extrinsic: string,3247      params: any[],3248      expectSuccess?: boolean,3249      options: Partial<SignerOptions>|null = null,3250    ): Promise<ITransactionResult> {3251      const call = this.constructApiCall(extrinsic, params);3252      const result = await super.executeExtrinsic(3253        sender,3254        'api.tx.sudo.sudo',3255        [call],3256        expectSuccess,3257        options,3258      );32593260      if (result.status === 'Fail') return result;32613262      const data = (result.result.events.find(x => x.event.section == 'sudo' && x.event.method == 'Sudid')?.event.data as any).sudoResult;3263      if (data.isErr) {3264        if (data.asErr.isModule) {3265          const error = (result.result.events[1].event.data as any).sudoResult.asErr.asModule;3266          const metaError = super.getApi()?.registry.findMetaError(error);3267          throw new Error(`${metaError.section}.${metaError.name}`);3268        } else {3269          throw new Error(data.asErr.toHuman());3270        }3271      }3272      return result;3273    }3274  };3275}32763277export class UniqueBaseCollection {3278  helper: UniqueHelper;3279  collectionId: number;32803281  constructor(collectionId: number, uniqueHelper: UniqueHelper) {3282    this.collectionId = collectionId;3283    this.helper = uniqueHelper;3284  }32853286  async getData() {3287    return await this.helper.collection.getData(this.collectionId);3288  }32893290  async getLastTokenId() {3291    return await this.helper.collection.getLastTokenId(this.collectionId);3292  }32933294  async doesTokenExist(tokenId: number) {3295    return await this.helper.collection.doesTokenExist(this.collectionId, tokenId);3296  }32973298  async getAdmins() {3299    return await this.helper.collection.getAdmins(this.collectionId);3300  }33013302  async getAllowList() {3303    return await this.helper.collection.getAllowList(this.collectionId);3304  }33053306  async getEffectiveLimits() {3307    return await this.helper.collection.getEffectiveLimits(this.collectionId);3308  }33093310  async getProperties(propertyKeys?: string[] | null) {3311    return await this.helper.collection.getProperties(this.collectionId, propertyKeys);3312  }33133314  async getPropertiesConsumedSpace() {3315    return await this.helper.collection.getPropertiesConsumedSpace(this.collectionId);3316  }33173318  async getTokenNextSponsored(tokenId: number, addressObj: ICrossAccountId) {3319    return await this.helper.collection.getTokenNextSponsored(this.collectionId, tokenId, addressObj);3320  }33213322  async getOptions() {3323    return await this.helper.collection.getCollectionOptions(this.collectionId);3324  }33253326  async setSponsor(signer: TSigner, sponsorAddress: TSubstrateAccount) {3327    return await this.helper.collection.setSponsor(signer, this.collectionId, sponsorAddress);3328  }33293330  async confirmSponsorship(signer: TSigner) {3331    return await this.helper.collection.confirmSponsorship(signer, this.collectionId);3332  }33333334  async removeSponsor(signer: TSigner) {3335    return await this.helper.collection.removeSponsor(signer, this.collectionId);3336  }33373338  async setLimits(signer: TSigner, limits: ICollectionLimits) {3339    return await this.helper.collection.setLimits(signer, this.collectionId, limits);3340  }33413342  async changeOwner(signer: TSigner, ownerAddress: TSubstrateAccount) {3343    return await this.helper.collection.changeOwner(signer, this.collectionId, ownerAddress);3344  }33453346  async addAdmin(signer: TSigner, adminAddressObj: ICrossAccountId) {3347    return await this.helper.collection.addAdmin(signer, this.collectionId, adminAddressObj);3348  }33493350  async addToAllowList(signer: TSigner, addressObj: ICrossAccountId) {3351    return await this.helper.collection.addToAllowList(signer, this.collectionId, addressObj);3352  }33533354  async removeFromAllowList(signer: TSigner, addressObj: ICrossAccountId) {3355    return await this.helper.collection.removeFromAllowList(signer, this.collectionId, addressObj);3356  }33573358  async removeAdmin(signer: TSigner, adminAddressObj: ICrossAccountId) {3359    return await this.helper.collection.removeAdmin(signer, this.collectionId, adminAddressObj);3360  }33613362  async setProperties(signer: TSigner, properties: IProperty[]) {3363    return await this.helper.collection.setProperties(signer, this.collectionId, properties);3364  }33653366  async deleteProperties(signer: TSigner, propertyKeys: string[]) {3367    return await this.helper.collection.deleteProperties(signer, this.collectionId, propertyKeys);3368  }33693370  async setPermissions(signer: TSigner, permissions: ICollectionPermissions) {3371    return await this.helper.collection.setPermissions(signer, this.collectionId, permissions);3372  }33733374  async enableNesting(signer: TSigner, permissions: INestingPermissions) {3375    return await this.helper.collection.enableNesting(signer, this.collectionId, permissions);3376  }33773378  async disableNesting(signer: TSigner) {3379    return await this.helper.collection.disableNesting(signer, this.collectionId);3380  }33813382  async burn(signer: TSigner) {3383    return await this.helper.collection.burn(signer, this.collectionId);3384  }33853386  scheduleAt<T extends UniqueHelper>(3387    executionBlockNumber: number,3388    options: ISchedulerOptions = {},3389  ) {3390    const scheduledHelper = this.helper.scheduler.scheduleAt<T>(executionBlockNumber, options);3391    return new UniqueBaseCollection(this.collectionId, scheduledHelper);3392  }33933394  scheduleAfter<T extends UniqueHelper>(3395    blocksBeforeExecution: number,3396    options: ISchedulerOptions = {},3397  ) {3398    const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(blocksBeforeExecution, options);3399    return new UniqueBaseCollection(this.collectionId, scheduledHelper);3400  }34013402  getSudo<T extends UniqueHelper>() {3403    return new UniqueBaseCollection(this.collectionId, this.helper.getSudo<T>());3404  }3405}340634073408export class UniqueNFTCollection extends UniqueBaseCollection {3409  getTokenObject(tokenId: number) {3410    return new UniqueNFToken(tokenId, this);3411  }34123413  async getTokensByAddress(addressObj: ICrossAccountId) {3414    return await this.helper.nft.getTokensByAddress(this.collectionId, addressObj);3415  }34163417  async getToken(tokenId: number, blockHashAt?: string) {3418    return await this.helper.nft.getToken(this.collectionId, tokenId, [], blockHashAt);3419  }34203421  async getTokenOwner(tokenId: number, blockHashAt?: string) {3422    return await this.helper.nft.getTokenOwner(this.collectionId, tokenId, blockHashAt);3423  }34243425  async getTokenTopmostOwner(tokenId: number, blockHashAt?: string) {3426    return await this.helper.nft.getTokenTopmostOwner(this.collectionId, tokenId, blockHashAt);3427  }34283429  async getTokenChildren(tokenId: number, blockHashAt?: string) {3430    return await this.helper.nft.getTokenChildren(this.collectionId, tokenId, blockHashAt);3431  }34323433  async getPropertyPermissions(propertyKeys: string[] | null = null) {3434    return await this.helper.nft.getPropertyPermissions(this.collectionId, propertyKeys);3435  }34363437  async getTokenProperties(tokenId: number, propertyKeys?: string[] | null) {3438    return await this.helper.nft.getTokenProperties(this.collectionId, tokenId, propertyKeys);3439  }34403441  async getTokenPropertiesConsumedSpace(tokenId: number): Promise<number> {3442    const api = this.helper.getApi();3443    const props = (await api.query.nonfungible.tokenProperties(this.collectionId, tokenId)).toJSON();34443445    return (props! as any).consumedSpace;3446  }34473448  async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId) {3449    return await this.helper.nft.transferToken(signer, this.collectionId, tokenId, addressObj);3450  }34513452  async transferTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {3453    return await this.helper.nft.transferTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, toAddressObj);3454  }34553456  async approveToken(signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId) {3457    return await this.helper.nft.approveToken(signer, this.collectionId, tokenId, toAddressObj);3458  }34593460  async isTokenApproved(tokenId: number, toAddressObj: ICrossAccountId) {3461    return await this.helper.nft.isTokenApproved(this.collectionId, tokenId, toAddressObj);3462  }34633464  async mintToken(signer: TSigner, owner: ICrossAccountId = {Substrate: signer.address}, properties?: IProperty[]) {3465    return await this.helper.nft.mintToken(signer, {collectionId: this.collectionId, owner, properties});3466  }34673468  async mintMultipleTokens(signer: TSigner, tokens: {owner: ICrossAccountId, properties?: IProperty[]}[]) {3469    return await this.helper.nft.mintMultipleTokens(signer, this.collectionId, tokens);3470  }34713472  async burnToken(signer: TSigner, tokenId: number) {3473    return await this.helper.nft.burnToken(signer, this.collectionId, tokenId);3474  }34753476  async burnTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId) {3477    return await this.helper.nft.burnTokenFrom(signer, this.collectionId, tokenId, fromAddressObj);3478  }34793480  async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[]) {3481    return await this.helper.nft.setTokenProperties(signer, this.collectionId, tokenId, properties);3482  }34833484  async deleteTokenProperties(signer: TSigner, tokenId: number, propertyKeys: string[]) {3485    return await this.helper.nft.deleteTokenProperties(signer, this.collectionId, tokenId, propertyKeys);3486  }34873488  async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[]) {3489    return await this.helper.nft.setTokenPropertyPermissions(signer, this.collectionId, permissions);3490  }34913492  async nestToken(signer: TSigner, tokenId: number, toTokenObj: IToken) {3493    return await this.helper.nft.nestToken(signer, {collectionId: this.collectionId, tokenId}, toTokenObj);3494  }34953496  async unnestToken(signer: TSigner, tokenId: number, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {3497    return await this.helper.nft.unnestToken(signer, {collectionId: this.collectionId, tokenId}, fromTokenObj, toAddressObj);3498  }34993500  scheduleAt<T extends UniqueHelper>(3501    executionBlockNumber: number,3502    options: ISchedulerOptions = {},3503  ) {3504    const scheduledHelper = this.helper.scheduler.scheduleAt<T>(executionBlockNumber, options);3505    return new UniqueNFTCollection(this.collectionId, scheduledHelper);3506  }35073508  scheduleAfter<T extends UniqueHelper>(3509    blocksBeforeExecution: number,3510    options: ISchedulerOptions = {},3511  ) {3512    const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(blocksBeforeExecution, options);3513    return new UniqueNFTCollection(this.collectionId, scheduledHelper);3514  }35153516  getSudo<T extends UniqueHelper>() {3517    return new UniqueNFTCollection(this.collectionId, this.helper.getSudo<T>());3518  }3519}352035213522export class UniqueRFTCollection extends UniqueBaseCollection {3523  getTokenObject(tokenId: number) {3524    return new UniqueRFToken(tokenId, this);3525  }35263527  async getToken(tokenId: number, blockHashAt?: string) {3528    return await this.helper.rft.getToken(this.collectionId, tokenId, [], blockHashAt);3529  }35303531  async getTokensByAddress(addressObj: ICrossAccountId) {3532    return await this.helper.rft.getTokensByAddress(this.collectionId, addressObj);3533  }35343535  async getTop10TokenOwners(tokenId: number) {3536    return await this.helper.rft.getTokenTop10Owners(this.collectionId, tokenId);3537  }35383539  async getTokenBalance(tokenId: number, addressObj: ICrossAccountId) {3540    return await this.helper.rft.getTokenBalance(this.collectionId, tokenId, addressObj);3541  }35423543  async getTokenTotalPieces(tokenId: number) {3544    return await this.helper.rft.getTokenTotalPieces(this.collectionId, tokenId);3545  }35463547  async getTokenApprovedPieces(tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {3548    return await this.helper.rft.getTokenApprovedPieces(this.collectionId, tokenId, toAddressObj, fromAddressObj);3549  }35503551  async getPropertyPermissions(propertyKeys: string[] | null = null) {3552    return await this.helper.rft.getPropertyPermissions(this.collectionId, propertyKeys);3553  }35543555  async getTokenProperties(tokenId: number, propertyKeys?: string[] | null) {3556    return await this.helper.rft.getTokenProperties(this.collectionId, tokenId, propertyKeys);3557  }35583559  async getTokenPropertiesConsumedSpace(tokenId: number): Promise<number> {3560    const api = this.helper.getApi();3561    const props = (await api.query.refungible.tokenProperties(this.collectionId, tokenId)).toJSON();35623563    return (props! as any).consumedSpace;3564  }35653566  async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId, amount=1n) {3567    return await this.helper.rft.transferToken(signer, this.collectionId, tokenId, addressObj, amount);3568  }35693570  async transferTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {3571    return await this.helper.rft.transferTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, toAddressObj, amount);3572  }35733574  async approveToken(signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {3575    return await this.helper.rft.approveToken(signer, this.collectionId, tokenId, toAddressObj, amount);3576  }35773578  async repartitionToken(signer: TSigner, tokenId: number, amount: bigint) {3579    return await this.helper.rft.repartitionToken(signer, this.collectionId, tokenId, amount);3580  }35813582  async mintToken(signer: TSigner, pieces=1n, owner: ICrossAccountId = {Substrate: signer.address}, properties?: IProperty[]) {3583    return await this.helper.rft.mintToken(signer, {collectionId: this.collectionId, owner, pieces, properties});3584  }35853586  async mintMultipleTokens(signer: TSigner, tokens: {pieces: bigint, owner: ICrossAccountId, properties?: IProperty[]}[]) {3587    return await this.helper.rft.mintMultipleTokens(signer, this.collectionId, tokens);3588  }35893590  async burnToken(signer: TSigner, tokenId: number, amount=1n) {3591    return await this.helper.rft.burnToken(signer, this.collectionId, tokenId, amount);3592  }35933594  async burnTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId,  amount=1n) {3595    return await this.helper.rft.burnTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, amount);3596  }35973598  async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[]) {3599    return await this.helper.rft.setTokenProperties(signer, this.collectionId, tokenId, properties);3600  }36013602  async deleteTokenProperties(signer: TSigner, tokenId: number, propertyKeys: string[]) {3603    return await this.helper.rft.deleteTokenProperties(signer, this.collectionId, tokenId, propertyKeys);3604  }36053606  async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[]) {3607    return await this.helper.rft.setTokenPropertyPermissions(signer, this.collectionId, permissions);3608  }36093610  scheduleAt<T extends UniqueHelper>(3611    executionBlockNumber: number,3612    options: ISchedulerOptions = {},3613  ) {3614    const scheduledHelper = this.helper.scheduler.scheduleAt<T>(executionBlockNumber, options);3615    return new UniqueRFTCollection(this.collectionId, scheduledHelper);3616  }36173618  scheduleAfter<T extends UniqueHelper>(3619    blocksBeforeExecution: number,3620    options: ISchedulerOptions = {},3621  ) {3622    const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(blocksBeforeExecution, options);3623    return new UniqueRFTCollection(this.collectionId, scheduledHelper);3624  }36253626  getSudo<T extends UniqueHelper>() {3627    return new UniqueRFTCollection(this.collectionId, this.helper.getSudo<T>());3628  }3629}363036313632export class UniqueFTCollection extends UniqueBaseCollection {3633  async getBalance(addressObj: ICrossAccountId) {3634    return await this.helper.ft.getBalance(this.collectionId, addressObj);3635  }36363637  async getTotalPieces() {3638    return await this.helper.ft.getTotalPieces(this.collectionId);3639  }36403641  async getApprovedTokens(fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {3642    return await this.helper.ft.getApprovedTokens(this.collectionId, fromAddressObj, toAddressObj);3643  }36443645  async getTop10Owners() {3646    return await this.helper.ft.getTop10Owners(this.collectionId);3647  }36483649  async mint(signer: TSigner, amount=1n, owner: ICrossAccountId = {Substrate: signer.address}) {3650    return await this.helper.ft.mintTokens(signer, this.collectionId, amount, owner);3651  }36523653  async mintWithOneOwner(signer: TSigner, tokens: {value: bigint}[], owner: ICrossAccountId = {Substrate: signer.address}) {3654    return await this.helper.ft.mintMultipleTokensWithOneOwner(signer, this.collectionId, tokens, owner);3655  }36563657  async transfer(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {3658    return await this.helper.ft.transfer(signer, this.collectionId, toAddressObj, amount);3659  }36603661  async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {3662    return await this.helper.ft.transferFrom(signer, this.collectionId, fromAddressObj, toAddressObj, amount);3663  }36643665  async burnTokens(signer: TSigner, amount=1n) {3666    return await this.helper.ft.burnTokens(signer, this.collectionId, amount);3667  }36683669  async burnTokensFrom(signer: TSigner, fromAddressObj: ICrossAccountId, amount=1n) {3670    return await this.helper.ft.burnTokensFrom(signer, this.collectionId, fromAddressObj, amount);3671  }36723673  async approveTokens(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {3674    return await this.helper.ft.approveTokens(signer, this.collectionId, toAddressObj, amount);3675  }36763677  scheduleAt<T extends UniqueHelper>(3678    executionBlockNumber: number,3679    options: ISchedulerOptions = {},3680  ) {3681    const scheduledHelper = this.helper.scheduler.scheduleAt<T>(executionBlockNumber, options);3682    return new UniqueFTCollection(this.collectionId, scheduledHelper);3683  }36843685  scheduleAfter<T extends UniqueHelper>(3686    blocksBeforeExecution: number,3687    options: ISchedulerOptions = {},3688  ) {3689    const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(blocksBeforeExecution, options);3690    return new UniqueFTCollection(this.collectionId, scheduledHelper);3691  }36923693  getSudo<T extends UniqueHelper>() {3694    return new UniqueFTCollection(this.collectionId, this.helper.getSudo<T>());3695  }3696}369736983699export class UniqueBaseToken {3700  collection: UniqueNFTCollection | UniqueRFTCollection;3701  collectionId: number;3702  tokenId: number;37033704  constructor(tokenId: number, collection: UniqueNFTCollection | UniqueRFTCollection) {3705    this.collection = collection;3706    this.collectionId = collection.collectionId;3707    this.tokenId = tokenId;3708  }37093710  async getNextSponsored(addressObj: ICrossAccountId) {3711    return await this.collection.getTokenNextSponsored(this.tokenId, addressObj);3712  }37133714  async getProperties(propertyKeys?: string[] | null) {3715    return await this.collection.getTokenProperties(this.tokenId, propertyKeys);3716  }37173718  async getTokenPropertiesConsumedSpace() {3719    return await this.collection.getTokenPropertiesConsumedSpace(this.tokenId);3720  }37213722  async setProperties(signer: TSigner, properties: IProperty[]) {3723    return await this.collection.setTokenProperties(signer, this.tokenId, properties);3724  }37253726  async deleteProperties(signer: TSigner, propertyKeys: string[]) {3727    return await this.collection.deleteTokenProperties(signer, this.tokenId, propertyKeys);3728  }37293730  async doesExist() {3731    return await this.collection.doesTokenExist(this.tokenId);3732  }37333734  nestingAccount() {3735    return this.collection.helper.util.getTokenAccount(this);3736  }37373738  scheduleAt<T extends UniqueHelper>(3739    executionBlockNumber: number,3740    options: ISchedulerOptions = {},3741  ) {3742    const scheduledCollection = this.collection.scheduleAt<T>(executionBlockNumber, options);3743    return new UniqueBaseToken(this.tokenId, scheduledCollection);3744  }37453746  scheduleAfter<T extends UniqueHelper>(3747    blocksBeforeExecution: number,3748    options: ISchedulerOptions = {},3749  ) {3750    const scheduledCollection = this.collection.scheduleAfter<T>(blocksBeforeExecution, options);3751    return new UniqueBaseToken(this.tokenId, scheduledCollection);3752  }37533754  getSudo<T extends UniqueHelper>() {3755    return new UniqueBaseToken(this.tokenId, this.collection.getSudo<T>());3756  }3757}375837593760export class UniqueNFToken extends UniqueBaseToken {3761  collection: UniqueNFTCollection;37623763  constructor(tokenId: number, collection: UniqueNFTCollection) {3764    super(tokenId, collection);3765    this.collection = collection;3766  }37673768  async getData(blockHashAt?: string) {3769    return await this.collection.getToken(this.tokenId, blockHashAt);3770  }37713772  async getOwner(blockHashAt?: string) {3773    return await this.collection.getTokenOwner(this.tokenId, blockHashAt);3774  }37753776  async getTopmostOwner(blockHashAt?: string) {3777    return await this.collection.getTokenTopmostOwner(this.tokenId, blockHashAt);3778  }37793780  async getChildren(blockHashAt?: string) {3781    return await this.collection.getTokenChildren(this.tokenId, blockHashAt);3782  }37833784  async nest(signer: TSigner, toTokenObj: IToken) {3785    return await this.collection.nestToken(signer, this.tokenId, toTokenObj);3786  }37873788  async unnest(signer: TSigner, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {3789    return await this.collection.unnestToken(signer, this.tokenId, fromTokenObj, toAddressObj);3790  }37913792  async transfer(signer: TSigner, addressObj: ICrossAccountId) {3793    return await this.collection.transferToken(signer, this.tokenId, addressObj);3794  }37953796  async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {3797    return await this.collection.transferTokenFrom(signer, this.tokenId, fromAddressObj, toAddressObj);3798  }37993800  async approve(signer: TSigner, toAddressObj: ICrossAccountId) {3801    return await this.collection.approveToken(signer, this.tokenId, toAddressObj);3802  }38033804  async isApproved(toAddressObj: ICrossAccountId) {3805    return await this.collection.isTokenApproved(this.tokenId, toAddressObj);3806  }38073808  async burn(signer: TSigner) {3809    return await this.collection.burnToken(signer, this.tokenId);3810  }38113812  async burnFrom(signer: TSigner, fromAddressObj: ICrossAccountId) {3813    return await this.collection.burnTokenFrom(signer, this.tokenId, fromAddressObj);3814  }38153816  scheduleAt<T extends UniqueHelper>(3817    executionBlockNumber: number,3818    options: ISchedulerOptions = {},3819  ) {3820    const scheduledCollection = this.collection.scheduleAt<T>(executionBlockNumber, options);3821    return new UniqueNFToken(this.tokenId, scheduledCollection);3822  }38233824  scheduleAfter<T extends UniqueHelper>(3825    blocksBeforeExecution: number,3826    options: ISchedulerOptions = {},3827  ) {3828    const scheduledCollection = this.collection.scheduleAfter<T>(blocksBeforeExecution, options);3829    return new UniqueNFToken(this.tokenId, scheduledCollection);3830  }38313832  getSudo<T extends UniqueHelper>() {3833    return new UniqueNFToken(this.tokenId, this.collection.getSudo<T>());3834  }3835}38363837export class UniqueRFToken extends UniqueBaseToken {3838  collection: UniqueRFTCollection;38393840  constructor(tokenId: number, collection: UniqueRFTCollection) {3841    super(tokenId, collection);3842    this.collection = collection;3843  }38443845  async getData(blockHashAt?: string) {3846    return await this.collection.getToken(this.tokenId, blockHashAt);3847  }38483849  async getTop10Owners() {3850    return await this.collection.getTop10TokenOwners(this.tokenId);3851  }38523853  async getBalance(addressObj: ICrossAccountId) {3854    return await this.collection.getTokenBalance(this.tokenId, addressObj);3855  }38563857  async getTotalPieces() {3858    return await this.collection.getTokenTotalPieces(this.tokenId);3859  }38603861  async getApprovedPieces(fromAddressObj: ICrossAccountId, toAccountObj: ICrossAccountId) {3862    return await this.collection.getTokenApprovedPieces(this.tokenId, fromAddressObj, toAccountObj);3863  }38643865  async transfer(signer: TSigner, addressObj: ICrossAccountId, amount=1n) {3866    return await this.collection.transferToken(signer, this.tokenId, addressObj, amount);3867  }38683869  async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {3870    return await this.collection.transferTokenFrom(signer, this.tokenId, fromAddressObj, toAddressObj, amount);3871  }38723873  async approve(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {3874    return await this.collection.approveToken(signer, this.tokenId, toAddressObj, amount);3875  }38763877  async repartition(signer: TSigner, amount: bigint) {3878    return await this.collection.repartitionToken(signer, this.tokenId, amount);3879  }38803881  async burn(signer: TSigner, amount=1n) {3882    return await this.collection.burnToken(signer, this.tokenId, amount);3883  }38843885  async burnFrom(signer: TSigner, fromAddressObj: ICrossAccountId, amount=1n) {3886    return await this.collection.burnTokenFrom(signer, this.tokenId, fromAddressObj, amount);3887  }38883889  scheduleAt<T extends UniqueHelper>(3890    executionBlockNumber: number,3891    options: ISchedulerOptions = {},3892  ) {3893    const scheduledCollection = this.collection.scheduleAt<T>(executionBlockNumber, options);3894    return new UniqueRFToken(this.tokenId, scheduledCollection);3895  }38963897  scheduleAfter<T extends UniqueHelper>(3898    blocksBeforeExecution: number,3899    options: ISchedulerOptions = {},3900  ) {3901    const scheduledCollection = this.collection.scheduleAfter<T>(blocksBeforeExecution, options);3902    return new UniqueRFToken(this.tokenId, scheduledCollection);3903  }39043905  getSudo<T extends UniqueHelper>() {3906    return new UniqueRFToken(this.tokenId, this.collection.getSudo<T>());3907  }3908}