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

difftreelog

Merge branch 'develop' into test/playground-migration

Fahrrader2022-09-30parents: #9e6bd66 #e15be01.patch.diff
in: master

40 files changed

modified.docker/Dockerfile-chain-dev-unitdiffbeforeafterboth
--- a/.docker/Dockerfile-chain-dev-unit
+++ b/.docker/Dockerfile-chain-dev-unit
@@ -23,4 +23,4 @@
 
 WORKDIR /dev_chain
 
-CMD cargo test --features=limit-testing
+CMD cargo test --features=limit-testing --workspace
added.docker/Dockerfile-testnet.j2diffbeforeafterboth
--- /dev/null
+++ b/.docker/Dockerfile-testnet.j2
@@ -0,0 +1,75 @@
+# ===== Rust builder =====
+FROM ubuntu:20.04 as rust-builder
+LABEL maintainer="Unique.Network"
+
+ENV CARGO_HOME="/cargo-home"
+ENV PATH="/cargo-home/bin:$PATH"
+ENV TZ=UTC
+RUN ln -snf /usr/share/zoneinfo/$TZ /etc/localtime && echo $TZ > /etc/timezone
+
+RUN apt-get update && \
+    apt-get install -y curl cmake pkg-config libssl-dev git clang llvm libudev-dev && \
+    apt-get clean && \
+    rm -r /var/lib/apt/lists/*
+
+RUN curl https://sh.rustup.rs -sSf | sh -s -- -y --default-toolchain none
+
+RUN rustup toolchain uninstall $(rustup toolchain list) && \
+    rustup toolchain install {{ RUST_TOOLCHAIN }} && \
+    rustup default {{ RUST_TOOLCHAIN }} && \
+    rustup target list --installed && \
+    rustup show
+RUN rustup target add wasm32-unknown-unknown --toolchain {{ RUST_TOOLCHAIN }}
+
+RUN mkdir /unique_parachain
+WORKDIR /unique_parachain
+
+# ===== BUILD ======
+FROM rust-builder as builder-unique
+
+ARG PROFILE=release
+
+WORKDIR /unique_parachain
+
+RUN git clone -b {{ BRANCH }} https://github.com/UniqueNetwork/unique-chain.git && \
+    cd unique-chain && \
+    cargo build --features={{ FEATURE }} --$PROFILE
+
+# ===== RUN ======
+
+FROM ubuntu:20.04
+
+RUN apt-get -y update && \
+      apt-get -y install curl git && \
+      curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.35.3/install.sh | bash && \
+      export NVM_DIR="$HOME/.nvm" && \
+      [ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh" && \
+      nvm install v16.16.0 && \
+      nvm use v16.16.0
+
+RUN git clone https://github.com/uniquenetwork/polkadot-launch -b {{ POLKADOT_LAUNCH_BRANCH }}
+
+RUN export NVM_DIR="$HOME/.nvm" && \
+    [ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh" && \
+    cd /polkadot-launch && \
+    npm install --global yarn && \
+    yarn install
+
+COPY --from=builder-unique /unique_parachain/unique-chain/.docker/testnet-config/launch-config.json /polkadot-launch/launch-config.json
+COPY --from=builder-unique /unique_parachain/unique-chain/target/release/unique-collator /unique-chain/target/release/
+
+COPY --from=uniquenetwork/builder-polkadot:{{ POLKADOT_BUILD_BRANCH }} /unique_parachain/polkadot/target/release/polkadot /polkadot/target/release/
+
+EXPOSE 9844
+EXPOSE 9944
+EXPOSE 9933
+EXPOSE 9833
+EXPOSE 40333
+EXPOSE 30333
+
+CMD export NVM_DIR="$HOME/.nvm" && \
+    [ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh" && \
+    cd /polkadot-launch && \
+    yarn start launch-config.json
+
+    
\ No newline at end of file
added.docker/testnet-config/launch-config.jsondiffbeforeafterboth
--- /dev/null
+++ b/.docker/testnet-config/launch-config.json
@@ -0,0 +1,121 @@
+{
+    "relaychain": {
+        "bin": "/polkadot/target/release/polkadot",
+        "chain": "rococo-local",
+        "nodes": [
+            {
+                "name": "alice",
+                "wsPort": 9844,
+                "rpcPort": 9843,
+                "port": 30444,
+                "flags": [
+                    "-lparachain::candidate_validation=debug",
+                    "-lxcm=trace",
+                    "--rpc-cors=all",
+                    "--unsafe-rpc-external",
+                    "--unsafe-ws-external"
+                ]
+            },
+            {
+                "name": "bob",
+                "wsPort": 9855,
+                "rpcPort": 9854,
+                "port": 30555,
+                "flags": [
+                    "-lparachain::candidate_validation=debug",
+                    "-lxcm=trace",
+                    "--rpc-cors=all",
+                    "--unsafe-rpc-external",
+                    "--unsafe-ws-external"
+                ]
+            },
+            {
+                "name": "charlie",
+                "wsPort": 9866,
+                "rpcPort": 9865,
+                "port": 30666,
+                "flags": [
+                    "-lparachain::candidate_validation=debug",
+                    "-lxcm=trace",
+                    "--rpc-cors=all",
+                    "--unsafe-rpc-external",
+                    "--unsafe-ws-external"
+                ]
+            },
+            {
+                "name": "dave",
+                "wsPort": 9877,
+                "rpcPort": 9876,
+                "port": 30777,
+                "flags": [
+                    "-lparachain::candidate_validation=debug",
+                    "-lxcm=trace",
+                    "--rpc-cors=all",
+                    "--unsafe-rpc-external",
+                    "--unsafe-ws-external"
+                ]
+            },
+            {
+                "name": "eve",
+                "wsPort": 9888,
+                "rpcPort": 9887,
+                "port": 30888,
+                "flags": [
+                    "-lparachain::candidate_validation=debug",
+                    "-lxcm=trace",
+                    "--rpc-cors=all",
+                    "--unsafe-rpc-external",
+                    "--unsafe-ws-external"
+                ]
+            }
+        ],
+        "genesis": {
+            "runtime": {
+                "runtime_genesis_config": {
+                    "parachainsConfiguration": {
+                        "config": {
+                            "validation_upgrade_frequency": 1,
+                            "validation_upgrade_delay": 1
+                        }
+                    }
+                }
+            }
+        }
+    },
+    "parachains": [
+        {
+            "bin": "/unique-chain/target/release/unique-collator",
+            "id": "1000",
+            "balance": "1000000000000000000000000",
+            "nodes": [
+                {
+                    "port": 31200,
+                    "wsPort": 9944,
+                    "rpcPort": 9933,
+                    "name": "alice",
+                    "flags": [
+                        "--rpc-cors=all",
+                        "--unsafe-rpc-external",
+                        "--unsafe-ws-external",
+                        "-lxcm=trace"
+                    ]
+                },
+                {
+                    "port": 31201,
+                    "wsPort": 9945,
+                    "rpcPort": 9934,
+                    "name": "bob",
+                    "flags": [
+                        "--rpc-cors=all",
+                        "--unsafe-rpc-external",
+                        "--unsafe-ws-external",
+                        "-lxcm=trace"
+                    ]
+                }
+            ]
+        }
+    ],
+    "simpleParachains": [],
+    "hrmpChannels": [],
+    "finalization": false
+}
modified.github/workflows/ci-develop.ymldiffbeforeafterboth
--- a/.github/workflows/ci-develop.yml
+++ b/.github/workflows/ci-develop.yml
@@ -3,7 +3,7 @@
 on:
   pull_request:
     branches: [ 'develop' ]
-    types: [ opened, reopened, synchronize, ready_for_review ]
+    types: [ opened, reopened, synchronize, ready_for_review, converted_to_draft ]
 
 concurrency:
   group: ${{ github.workflow }}-${{ github.head_ref }}
@@ -12,23 +12,28 @@
 jobs:
 
   yarn-test-dev:
+    if: github.event.pull_request.draft == false
     uses: ./.github/workflows/dev-build-tests_v2.yml
 
+
   unit-test:
+    if: github.event.pull_request.draft == false
     uses: ./.github/workflows/unit-test_v2.yml
 
   canary:
-    if: ${{ contains( github.event.pull_request.labels.*.name, 'canary') }}
+    if: ${{ (github.event.pull_request.draft == false && contains( github.event.pull_request.labels.*.name, 'canary')) }}
     uses: ./.github/workflows/canary.yml
     secrets: inherit # pass all secrets
 
   xcm:
-    if: ${{ contains( github.event.pull_request.labels.*.name, 'xcm') }}
+    if: ${{ (github.event.pull_request.draft == false && contains( github.event.pull_request.labels.*.name, 'xcm')) }}
     uses: ./.github/workflows/xcm.yml
     secrets: inherit # pass all secrets
 
   codestyle:
+    if: github.event.pull_request.draft == false
     uses: ./.github/workflows/codestyle_v2.yml
   
   yarn_eslint:
+    if: github.event.pull_request.draft == false
     uses: ./.github/workflows/test_codestyle_v2.yml
added.github/workflows/testnet-build.ymldiffbeforeafterboth
--- /dev/null
+++ b/.github/workflows/testnet-build.yml
@@ -0,0 +1,144 @@
+name: testnet-build
+
+# Controls when the action will run.
+on:
+ # Triggers the workflow on push or pull request events but only for the master branch
+  pull_request:
+    branches:
+      - master
+    types:
+      - opened
+      - reopened
+      - synchronize   #commit(s) pushed to the pull request
+      - ready_for_review
+
+  # Allows you to run this workflow manually from the Actions tab
+  workflow_dispatch:
+
+#Define Workflow variables
+env:
+  REPO_URL: ${{ github.server_url }}/${{ github.repository }}
+
+concurrency:
+  group: ${{ github.workflow }}-${{ github.ref }}
+  cancel-in-progress: true
+
+# A workflow run is made up of one or more jobs that can run sequentially or in parallel
+jobs:
+
+  prepare-execution-marix:
+
+    name: Prepare execution matrix
+
+    runs-on: [self-hosted-ci,medium]
+    outputs:
+      matrix: ${{ steps.create_matrix.outputs.matrix }}
+
+    steps:
+
+      - name: Clean Workspace
+        uses: AutoModality/action-clean@v1.1.0
+
+      # Checks-out your repository under $GITHUB_WORKSPACE, so your job can access it
+      - uses: actions/checkout@v3
+        with:
+          ref: ${{ github.head_ref }}  #Checking out head commit
+
+      - name: Read .env file
+        uses: xom9ikk/dotenv@v1.0.2
+
+      - name: Create Execution matrix
+        uses: fabiocaccamo/create-matrix-action@v2
+        id: create_matrix
+        with:
+          matrix: |
+            network {opal}, runtime {opal}, features {opal-runtime}
+            network {quartz}, runtime {quartz}, features {quartz-runtime}
+            network {unique}, runtime {unique}, features {unique-runtime}
+
+  testnet-build:
+    needs: prepare-execution-marix
+    # The type of runner that the job will run on
+    runs-on: [self-hosted-ci,medium]
+
+    timeout-minutes: 600
+
+    name: ${{ matrix.network }}
+
+    continue-on-error: true         #Do not stop testing of matrix runs failed.  As it decided during PR review - it required 50/50& Let's check it with false.
+
+    strategy:
+      matrix:
+        include: ${{fromJson(needs.prepare-execution-marix.outputs.matrix)}}
+
+    steps:
+      - name: Skip if pull request is in Draft
+        if: github.event.pull_request.draft == true
+        run: exit 1
+
+      - name: Clean Workspace
+        uses: AutoModality/action-clean@v1.1.0
+
+      # Checks-out your repository under $GITHUB_WORKSPACE, so your job can access it
+      - uses: actions/checkout@v3
+        with:
+          ref: ${{ github.head_ref }}  #Checking out head commit
+
+      - name: Read .env file
+        uses: xom9ikk/dotenv@v1.0.2
+
+      - name: Generate ENV related extend file for docker-compose
+        uses: cuchi/jinja2-action@v1.2.0
+        with:
+          template: .docker/Dockerfile-testnet.j2
+          output_file: .docker/Dockerfile-testnet.${{ matrix.network }}.yml
+          variables: |
+            RUST_TOOLCHAIN=${{ env.RUST_TOOLCHAIN }}
+            NETWORK=${{ matrix.network }}
+            POLKADOT_BUILD_BRANCH=${{ env.POLKADOT_BUILD_BRANCH }}
+            POLKADOT_LAUNCH_BRANCH=${{ env.POLKADOT_LAUNCH_BRANCH }}
+            FEATURE=${{ matrix.features }}
+            RUNTIME=${{ matrix.runtime }}
+            BRANCH=${{ github.head_ref }}
+
+      - name: Show build configuration
+        run: cat .docker/Dockerfile-testnet.${{ matrix.network }}.yml
+
+      - name: Show launch-config configuration
+        run: cat launch-config.json
+
+      - name: Run find-and-replace to remove slashes from branch name
+        uses: mad9000/actions-find-and-replace-string@2
+        id: branchname
+        with:
+          source: ${{ github.head_ref }}
+          find: '/'
+          replace: '-'
+
+      - name: Log in to Docker Hub
+        uses: docker/login-action@v2.0.0
+        with:
+          username: ${{ secrets.CORE_DOCKERHUB_USERNAME }}
+          password: ${{ secrets.CORE_DOCKERHUB_TOKEN }}
+
+      - name: Pull polkadot docker image
+        run: docker pull uniquenetwork/builder-polkadot:${{ env.POLKADOT_BUILD_BRANCH }}           
+
+      - name: Build the stack
+        run: cd .docker/ && docker build --file ./Dockerfile-testnet.${{ matrix.network }}.yml --tag uniquenetwork/${{ matrix.network }}-testnet-local:nightly-${{ steps.branchname.outputs.value }}-${{ github.sha }} --tag uniquenetwork/${{ matrix.network }}-testnet-local:latest . 
+
+      - name: Push docker version image
+        run: docker push uniquenetwork/${{ matrix.network }}-testnet-local:nightly-${{ steps.branchname.outputs.value }}-${{ github.sha }}
+
+      - name: Push docker latest image
+        run: docker push uniquenetwork/${{ matrix.network }}-testnet-local:latest
+
+      - name: Clean Workspace
+        if: always()
+        uses: AutoModality/action-clean@v1.1.0
+
+      - name: Remove builder cache
+        if: always()                   # run this step always
+        run: |
+          docker builder prune -f
+          docker system prune -f
modifiedpallets/common/src/erc.rsdiffbeforeafterboth
--- a/pallets/common/src/erc.rs
+++ b/pallets/common/src/erc.rs
@@ -139,25 +139,26 @@
 		save(self)
 	}
 
-	/// Set the substrate sponsor of the collection.
-	///
-	/// @dev In order for sponsorship to work, it must be confirmed on behalf of the sponsor.
-	///
-	/// @param sponsor Substrate address of the sponsor from whose account funds will be debited for operations with the contract.
-	fn set_collection_sponsor_substrate(
-		&mut self,
-		caller: caller,
-		sponsor: uint256,
-	) -> Result<void> {
-		self.consume_store_reads_and_writes(1, 1)?;
+	// TODO: Temprorary off. Need refactor
+	// /// Set the substrate sponsor of the collection.
+	// ///
+	// /// @dev In order for sponsorship to work, it must be confirmed on behalf of the sponsor.
+	// ///
+	// /// @param sponsor Substrate address of the sponsor from whose account funds will be debited for operations with the contract.
+	// fn set_collection_sponsor_substrate(
+	// 	&mut self,
+	// 	caller: caller,
+	// 	sponsor: uint256,
+	// ) -> Result<void> {
+	// 	self.consume_store_reads_and_writes(1, 1)?;
 
-		check_is_owner_or_admin(caller, self)?;
+	// 	check_is_owner_or_admin(caller, self)?;
 
-		let sponsor = convert_uint256_to_cross_account::<T>(sponsor);
-		self.set_sponsor(sponsor.as_sub().clone())
-			.map_err(dispatch_to_evm::<T>)?;
-		save(self)
-	}
+	// 	let sponsor = convert_uint256_to_cross_account::<T>(sponsor);
+	// 	self.set_sponsor(sponsor.as_sub().clone())
+	// 		.map_err(dispatch_to_evm::<T>)?;
+	// 	save(self)
+	// }
 
 	/// Whether there is a pending sponsor.
 	fn has_collection_pending_sponsor(&self) -> Result<bool> {
@@ -299,35 +300,37 @@
 		Ok(crate::eth::collection_id_to_address(self.id))
 	}
 
-	/// Add collection admin by substrate address.
-	/// @param newAdmin Substrate administrator address.
-	fn add_collection_admin_substrate(
-		&mut self,
-		caller: caller,
-		new_admin: uint256,
-	) -> Result<void> {
-		self.consume_store_writes(2)?;
+	// TODO: Temprorary off. Need refactor
+	// /// Add collection admin by substrate address.
+	// /// @param newAdmin Substrate administrator address.
+	// fn add_collection_admin_substrate(
+	// 	&mut self,
+	// 	caller: caller,
+	// 	new_admin: uint256,
+	// ) -> Result<void> {
+	// 	self.consume_store_writes(2)?;
 
-		let caller = T::CrossAccountId::from_eth(caller);
-		let new_admin = convert_uint256_to_cross_account::<T>(new_admin);
-		<Pallet<T>>::toggle_admin(self, &caller, &new_admin, true).map_err(dispatch_to_evm::<T>)?;
-		Ok(())
-	}
+	// 	let caller = T::CrossAccountId::from_eth(caller);
+	// 	let new_admin = convert_uint256_to_cross_account::<T>(new_admin);
+	// 	<Pallet<T>>::toggle_admin(self, &caller, &new_admin, true).map_err(dispatch_to_evm::<T>)?;
+	// 	Ok(())
+	// }
 
-	/// Remove collection admin by substrate address.
-	/// @param admin Substrate administrator address.
-	fn remove_collection_admin_substrate(
-		&mut self,
-		caller: caller,
-		admin: uint256,
-	) -> Result<void> {
-		self.consume_store_writes(2)?;
+	// TODO: Temprorary off. Need refactor
+	// /// Remove collection admin by substrate address.
+	// /// @param admin Substrate administrator address.
+	// fn remove_collection_admin_substrate(
+	// 	&mut self,
+	// 	caller: caller,
+	// 	admin: uint256,
+	// ) -> Result<void> {
+	// 	self.consume_store_writes(2)?;
 
-		let caller = T::CrossAccountId::from_eth(caller);
-		let admin = convert_uint256_to_cross_account::<T>(admin);
-		<Pallet<T>>::toggle_admin(self, &caller, &admin, false).map_err(dispatch_to_evm::<T>)?;
-		Ok(())
-	}
+	// 	let caller = T::CrossAccountId::from_eth(caller);
+	// 	let admin = convert_uint256_to_cross_account::<T>(admin);
+	// 	<Pallet<T>>::toggle_admin(self, &caller, &admin, false).map_err(dispatch_to_evm::<T>)?;
+	// 	Ok(())
+	// }
 
 	/// Add collection admin.
 	/// @param newAdmin Address of the added administrator.
@@ -476,21 +479,22 @@
 		Ok(())
 	}
 
-	/// Add substrate user to allowed list.
-	///
-	/// @param user User substrate address.
-	fn add_to_collection_allow_list_substrate(
-		&mut self,
-		caller: caller,
-		user: uint256,
-	) -> Result<void> {
-		self.consume_store_writes(1)?;
+	// TODO: Temprorary off. Need refactor
+	// /// Add substrate user to allowed list.
+	// ///
+	// /// @param user User substrate address.
+	// fn add_to_collection_allow_list_substrate(
+	// 	&mut self,
+	// 	caller: caller,
+	// 	user: uint256,
+	// ) -> Result<void> {
+	// 	self.consume_store_writes(1)?;
 
-		let caller = T::CrossAccountId::from_eth(caller);
-		let user = convert_uint256_to_cross_account::<T>(user);
-		Pallet::<T>::toggle_allowlist(self, &caller, &user, true).map_err(dispatch_to_evm::<T>)?;
-		Ok(())
-	}
+	// 	let caller = T::CrossAccountId::from_eth(caller);
+	// 	let user = convert_uint256_to_cross_account::<T>(user);
+	// 	Pallet::<T>::toggle_allowlist(self, &caller, &user, true).map_err(dispatch_to_evm::<T>)?;
+	// 	Ok(())
+	// }
 
 	/// Remove the user from the allowed list.
 	///
@@ -504,21 +508,22 @@
 		Ok(())
 	}
 
-	/// Remove substrate user from allowed list.
-	///
-	/// @param user User substrate address.
-	fn remove_from_collection_allow_list_substrate(
-		&mut self,
-		caller: caller,
-		user: uint256,
-	) -> Result<void> {
-		self.consume_store_writes(1)?;
+	// TODO: Temprorary off. Need refactor
+	// /// Remove substrate user from allowed list.
+	// ///
+	// /// @param user User substrate address.
+	// fn remove_from_collection_allow_list_substrate(
+	// 	&mut self,
+	// 	caller: caller,
+	// 	user: uint256,
+	// ) -> Result<void> {
+	// 	self.consume_store_writes(1)?;
 
-		let caller = T::CrossAccountId::from_eth(caller);
-		let user = convert_uint256_to_cross_account::<T>(user);
-		Pallet::<T>::toggle_allowlist(self, &caller, &user, false).map_err(dispatch_to_evm::<T>)?;
-		Ok(())
-	}
+	// 	let caller = T::CrossAccountId::from_eth(caller);
+	// 	let user = convert_uint256_to_cross_account::<T>(user);
+	// 	Pallet::<T>::toggle_allowlist(self, &caller, &user, false).map_err(dispatch_to_evm::<T>)?;
+	// 	Ok(())
+	// }
 
 	/// Switch permission for minting.
 	///
@@ -551,14 +556,15 @@
 		Ok(self.is_owner_or_admin(&user))
 	}
 
-	/// Check that substrate account is the owner or admin of the collection
-	///
-	/// @param user account to verify
-	/// @return "true" if account is the owner or admin
-	fn is_owner_or_admin_substrate(&self, user: uint256) -> Result<bool> {
-		let user = convert_uint256_to_cross_account::<T>(user);
-		Ok(self.is_owner_or_admin(&user))
-	}
+	// TODO: Temprorary off. Need refactor
+	// /// Check that substrate account is the owner or admin of the collection
+	// ///
+	// /// @param user account to verify
+	// /// @return "true" if account is the owner or admin
+	// fn is_owner_or_admin_substrate(&self, user: uint256) -> Result<bool> {
+	// 	let user = convert_uint256_to_cross_account::<T>(user);
+	// 	Ok(self.is_owner_or_admin(&user))
+	// }
 
 	/// Returns collection type
 	///
@@ -595,18 +601,19 @@
 			.map_err(dispatch_to_evm::<T>)
 	}
 
-	/// Changes collection owner to another substrate account
-	///
-	/// @dev Owner can be changed only by current owner
-	/// @param newOwner new owner substrate account
-	fn set_owner_substrate(&mut self, caller: caller, new_owner: uint256) -> Result<void> {
-		self.consume_store_writes(1)?;
+	// TODO: Temprorary off. Need refactor
+	// /// Changes collection owner to another substrate account
+	// ///
+	// /// @dev Owner can be changed only by current owner
+	// /// @param newOwner new owner substrate account
+	// fn set_owner_substrate(&mut self, caller: caller, new_owner: uint256) -> Result<void> {
+	// 	self.consume_store_writes(1)?;
 
-		let caller = T::CrossAccountId::from_eth(caller);
-		let new_owner = convert_uint256_to_cross_account::<T>(new_owner);
-		self.set_owner_internal(caller, new_owner)
-			.map_err(dispatch_to_evm::<T>)
-	}
+	// 	let caller = T::CrossAccountId::from_eth(caller);
+	// 	let new_owner = convert_uint256_to_cross_account::<T>(new_owner);
+	// 	self.set_owner_internal(caller, new_owner)
+	// 		.map_err(dispatch_to_evm::<T>)
+	// }
 
 	// TODO: need implement AbiWriter for &Vec<T>
 	// fn collection_admins(&self) -> Result<Vec<(address, uint256)>> {
modifiedpallets/fungible/src/stubs/UniqueFungible.rawdiffbeforeafterboth

binary blob — no preview

modifiedpallets/fungible/src/stubs/UniqueFungible.soldiffbeforeafterboth
--- a/pallets/fungible/src/stubs/UniqueFungible.sol
+++ b/pallets/fungible/src/stubs/UniqueFungible.sol
@@ -18,7 +18,7 @@
 }
 
 /// @title A contract that allows you to work with collections.
-/// @dev the ERC-165 identifier for this interface is 0x47dbc105
+/// @dev the ERC-165 identifier for this interface is 0x3e1e8083
 contract Collection is Dummy, ERC165 {
 	/// Set collection property.
 	///
@@ -72,19 +72,6 @@
 		dummy = 0;
 	}
 
-	/// Set the substrate sponsor of the collection.
-	///
-	/// @dev In order for sponsorship to work, it must be confirmed on behalf of the sponsor.
-	///
-	/// @param sponsor Substrate address of the sponsor from whose account funds will be debited for operations with the contract.
-	/// @dev EVM selector for this function is: 0xc74d6751,
-	///  or in textual repr: setCollectionSponsorSubstrate(uint256)
-	function setCollectionSponsorSubstrate(uint256 sponsor) public {
-		require(false, stub_error);
-		sponsor;
-		dummy = 0;
-	}
-
 	/// Whether there is a pending sponsor.
 	/// @dev EVM selector for this function is: 0x058ac185,
 	///  or in textual repr: hasCollectionPendingSponsor()
@@ -167,26 +154,6 @@
 		return 0x0000000000000000000000000000000000000000;
 	}
 
-	/// Add collection admin by substrate address.
-	/// @param newAdmin Substrate administrator address.
-	/// @dev EVM selector for this function is: 0x5730062b,
-	///  or in textual repr: addCollectionAdminSubstrate(uint256)
-	function addCollectionAdminSubstrate(uint256 newAdmin) public {
-		require(false, stub_error);
-		newAdmin;
-		dummy = 0;
-	}
-
-	/// Remove collection admin by substrate address.
-	/// @param admin Substrate administrator address.
-	/// @dev EVM selector for this function is: 0x4048fcf9,
-	///  or in textual repr: removeCollectionAdminSubstrate(uint256)
-	function removeCollectionAdminSubstrate(uint256 admin) public {
-		require(false, stub_error);
-		admin;
-		dummy = 0;
-	}
-
 	/// Add collection admin.
 	/// @param newAdmin Address of the added administrator.
 	/// @dev EVM selector for this function is: 0x92e462c7,
@@ -262,17 +229,6 @@
 	/// @dev EVM selector for this function is: 0x67844fe6,
 	///  or in textual repr: addToCollectionAllowList(address)
 	function addToCollectionAllowList(address user) public {
-		require(false, stub_error);
-		user;
-		dummy = 0;
-	}
-
-	/// Add substrate user to allowed list.
-	///
-	/// @param user User substrate address.
-	/// @dev EVM selector for this function is: 0xd06ad267,
-	///  or in textual repr: addToCollectionAllowListSubstrate(uint256)
-	function addToCollectionAllowListSubstrate(uint256 user) public {
 		require(false, stub_error);
 		user;
 		dummy = 0;
@@ -289,17 +245,6 @@
 		dummy = 0;
 	}
 
-	/// Remove substrate user from allowed list.
-	///
-	/// @param user User substrate address.
-	/// @dev EVM selector for this function is: 0xa31913ed,
-	///  or in textual repr: removeFromCollectionAllowListSubstrate(uint256)
-	function removeFromCollectionAllowListSubstrate(uint256 user) public {
-		require(false, stub_error);
-		user;
-		dummy = 0;
-	}
-
 	/// Switch permission for minting.
 	///
 	/// @param mode Enable if "true".
@@ -324,19 +269,6 @@
 		return false;
 	}
 
-	/// Check that substrate account is the owner or admin of the collection
-	///
-	/// @param user account to verify
-	/// @return "true" if account is the owner or admin
-	/// @dev EVM selector for this function is: 0x68910e00,
-	///  or in textual repr: isOwnerOrAdminSubstrate(uint256)
-	function isOwnerOrAdminSubstrate(uint256 user) public view returns (bool) {
-		require(false, stub_error);
-		user;
-		dummy;
-		return false;
-	}
-
 	/// Returns collection type
 	///
 	/// @return `Fungible` or `NFT` or `ReFungible`
@@ -367,18 +299,6 @@
 	/// @dev EVM selector for this function is: 0x13af4035,
 	///  or in textual repr: setOwner(address)
 	function setOwner(address newOwner) public {
-		require(false, stub_error);
-		newOwner;
-		dummy = 0;
-	}
-
-	/// Changes collection owner to another substrate account
-	///
-	/// @dev Owner can be changed only by current owner
-	/// @param newOwner new owner substrate account
-	/// @dev EVM selector for this function is: 0xb212138f,
-	///  or in textual repr: setOwnerSubstrate(uint256)
-	function setOwnerSubstrate(uint256 newOwner) public {
 		require(false, stub_error);
 		newOwner;
 		dummy = 0;
modifiedpallets/nonfungible/src/stubs/UniqueNFT.rawdiffbeforeafterboth

binary blob — no preview

modifiedpallets/nonfungible/src/stubs/UniqueNFT.soldiffbeforeafterboth
--- a/pallets/nonfungible/src/stubs/UniqueNFT.sol
+++ b/pallets/nonfungible/src/stubs/UniqueNFT.sol
@@ -91,7 +91,7 @@
 }
 
 /// @title A contract that allows you to work with collections.
-/// @dev the ERC-165 identifier for this interface is 0x47dbc105
+/// @dev the ERC-165 identifier for this interface is 0x3e1e8083
 contract Collection is Dummy, ERC165 {
 	/// Set collection property.
 	///
@@ -145,19 +145,6 @@
 		dummy = 0;
 	}
 
-	/// Set the substrate sponsor of the collection.
-	///
-	/// @dev In order for sponsorship to work, it must be confirmed on behalf of the sponsor.
-	///
-	/// @param sponsor Substrate address of the sponsor from whose account funds will be debited for operations with the contract.
-	/// @dev EVM selector for this function is: 0xc74d6751,
-	///  or in textual repr: setCollectionSponsorSubstrate(uint256)
-	function setCollectionSponsorSubstrate(uint256 sponsor) public {
-		require(false, stub_error);
-		sponsor;
-		dummy = 0;
-	}
-
 	/// Whether there is a pending sponsor.
 	/// @dev EVM selector for this function is: 0x058ac185,
 	///  or in textual repr: hasCollectionPendingSponsor()
@@ -240,26 +227,6 @@
 		return 0x0000000000000000000000000000000000000000;
 	}
 
-	/// Add collection admin by substrate address.
-	/// @param newAdmin Substrate administrator address.
-	/// @dev EVM selector for this function is: 0x5730062b,
-	///  or in textual repr: addCollectionAdminSubstrate(uint256)
-	function addCollectionAdminSubstrate(uint256 newAdmin) public {
-		require(false, stub_error);
-		newAdmin;
-		dummy = 0;
-	}
-
-	/// Remove collection admin by substrate address.
-	/// @param admin Substrate administrator address.
-	/// @dev EVM selector for this function is: 0x4048fcf9,
-	///  or in textual repr: removeCollectionAdminSubstrate(uint256)
-	function removeCollectionAdminSubstrate(uint256 admin) public {
-		require(false, stub_error);
-		admin;
-		dummy = 0;
-	}
-
 	/// Add collection admin.
 	/// @param newAdmin Address of the added administrator.
 	/// @dev EVM selector for this function is: 0x92e462c7,
@@ -335,17 +302,6 @@
 	/// @dev EVM selector for this function is: 0x67844fe6,
 	///  or in textual repr: addToCollectionAllowList(address)
 	function addToCollectionAllowList(address user) public {
-		require(false, stub_error);
-		user;
-		dummy = 0;
-	}
-
-	/// Add substrate user to allowed list.
-	///
-	/// @param user User substrate address.
-	/// @dev EVM selector for this function is: 0xd06ad267,
-	///  or in textual repr: addToCollectionAllowListSubstrate(uint256)
-	function addToCollectionAllowListSubstrate(uint256 user) public {
 		require(false, stub_error);
 		user;
 		dummy = 0;
@@ -362,17 +318,6 @@
 		dummy = 0;
 	}
 
-	/// Remove substrate user from allowed list.
-	///
-	/// @param user User substrate address.
-	/// @dev EVM selector for this function is: 0xa31913ed,
-	///  or in textual repr: removeFromCollectionAllowListSubstrate(uint256)
-	function removeFromCollectionAllowListSubstrate(uint256 user) public {
-		require(false, stub_error);
-		user;
-		dummy = 0;
-	}
-
 	/// Switch permission for minting.
 	///
 	/// @param mode Enable if "true".
@@ -397,19 +342,6 @@
 		return false;
 	}
 
-	/// Check that substrate account is the owner or admin of the collection
-	///
-	/// @param user account to verify
-	/// @return "true" if account is the owner or admin
-	/// @dev EVM selector for this function is: 0x68910e00,
-	///  or in textual repr: isOwnerOrAdminSubstrate(uint256)
-	function isOwnerOrAdminSubstrate(uint256 user) public view returns (bool) {
-		require(false, stub_error);
-		user;
-		dummy;
-		return false;
-	}
-
 	/// Returns collection type
 	///
 	/// @return `Fungible` or `NFT` or `ReFungible`
@@ -440,18 +372,6 @@
 	/// @dev EVM selector for this function is: 0x13af4035,
 	///  or in textual repr: setOwner(address)
 	function setOwner(address newOwner) public {
-		require(false, stub_error);
-		newOwner;
-		dummy = 0;
-	}
-
-	/// Changes collection owner to another substrate account
-	///
-	/// @dev Owner can be changed only by current owner
-	/// @param newOwner new owner substrate account
-	/// @dev EVM selector for this function is: 0xb212138f,
-	///  or in textual repr: setOwnerSubstrate(uint256)
-	function setOwnerSubstrate(uint256 newOwner) public {
 		require(false, stub_error);
 		newOwner;
 		dummy = 0;
modifiedpallets/refungible/src/stubs/UniqueRefungible.rawdiffbeforeafterboth

binary blob — no preview

modifiedpallets/refungible/src/stubs/UniqueRefungible.soldiffbeforeafterboth
--- a/pallets/refungible/src/stubs/UniqueRefungible.sol
+++ b/pallets/refungible/src/stubs/UniqueRefungible.sol
@@ -91,7 +91,7 @@
 }
 
 /// @title A contract that allows you to work with collections.
-/// @dev the ERC-165 identifier for this interface is 0x47dbc105
+/// @dev the ERC-165 identifier for this interface is 0x3e1e8083
 contract Collection is Dummy, ERC165 {
 	/// Set collection property.
 	///
@@ -145,19 +145,6 @@
 		dummy = 0;
 	}
 
-	/// Set the substrate sponsor of the collection.
-	///
-	/// @dev In order for sponsorship to work, it must be confirmed on behalf of the sponsor.
-	///
-	/// @param sponsor Substrate address of the sponsor from whose account funds will be debited for operations with the contract.
-	/// @dev EVM selector for this function is: 0xc74d6751,
-	///  or in textual repr: setCollectionSponsorSubstrate(uint256)
-	function setCollectionSponsorSubstrate(uint256 sponsor) public {
-		require(false, stub_error);
-		sponsor;
-		dummy = 0;
-	}
-
 	/// Whether there is a pending sponsor.
 	/// @dev EVM selector for this function is: 0x058ac185,
 	///  or in textual repr: hasCollectionPendingSponsor()
@@ -240,26 +227,6 @@
 		return 0x0000000000000000000000000000000000000000;
 	}
 
-	/// Add collection admin by substrate address.
-	/// @param newAdmin Substrate administrator address.
-	/// @dev EVM selector for this function is: 0x5730062b,
-	///  or in textual repr: addCollectionAdminSubstrate(uint256)
-	function addCollectionAdminSubstrate(uint256 newAdmin) public {
-		require(false, stub_error);
-		newAdmin;
-		dummy = 0;
-	}
-
-	/// Remove collection admin by substrate address.
-	/// @param admin Substrate administrator address.
-	/// @dev EVM selector for this function is: 0x4048fcf9,
-	///  or in textual repr: removeCollectionAdminSubstrate(uint256)
-	function removeCollectionAdminSubstrate(uint256 admin) public {
-		require(false, stub_error);
-		admin;
-		dummy = 0;
-	}
-
 	/// Add collection admin.
 	/// @param newAdmin Address of the added administrator.
 	/// @dev EVM selector for this function is: 0x92e462c7,
@@ -335,17 +302,6 @@
 	/// @dev EVM selector for this function is: 0x67844fe6,
 	///  or in textual repr: addToCollectionAllowList(address)
 	function addToCollectionAllowList(address user) public {
-		require(false, stub_error);
-		user;
-		dummy = 0;
-	}
-
-	/// Add substrate user to allowed list.
-	///
-	/// @param user User substrate address.
-	/// @dev EVM selector for this function is: 0xd06ad267,
-	///  or in textual repr: addToCollectionAllowListSubstrate(uint256)
-	function addToCollectionAllowListSubstrate(uint256 user) public {
 		require(false, stub_error);
 		user;
 		dummy = 0;
@@ -362,17 +318,6 @@
 		dummy = 0;
 	}
 
-	/// Remove substrate user from allowed list.
-	///
-	/// @param user User substrate address.
-	/// @dev EVM selector for this function is: 0xa31913ed,
-	///  or in textual repr: removeFromCollectionAllowListSubstrate(uint256)
-	function removeFromCollectionAllowListSubstrate(uint256 user) public {
-		require(false, stub_error);
-		user;
-		dummy = 0;
-	}
-
 	/// Switch permission for minting.
 	///
 	/// @param mode Enable if "true".
@@ -397,19 +342,6 @@
 		return false;
 	}
 
-	/// Check that substrate account is the owner or admin of the collection
-	///
-	/// @param user account to verify
-	/// @return "true" if account is the owner or admin
-	/// @dev EVM selector for this function is: 0x68910e00,
-	///  or in textual repr: isOwnerOrAdminSubstrate(uint256)
-	function isOwnerOrAdminSubstrate(uint256 user) public view returns (bool) {
-		require(false, stub_error);
-		user;
-		dummy;
-		return false;
-	}
-
 	/// Returns collection type
 	///
 	/// @return `Fungible` or `NFT` or `ReFungible`
@@ -440,18 +372,6 @@
 	/// @dev EVM selector for this function is: 0x13af4035,
 	///  or in textual repr: setOwner(address)
 	function setOwner(address newOwner) public {
-		require(false, stub_error);
-		newOwner;
-		dummy = 0;
-	}
-
-	/// Changes collection owner to another substrate account
-	///
-	/// @dev Owner can be changed only by current owner
-	/// @param newOwner new owner substrate account
-	/// @dev EVM selector for this function is: 0xb212138f,
-	///  or in textual repr: setOwnerSubstrate(uint256)
-	function setOwnerSubstrate(uint256 newOwner) public {
 		require(false, stub_error);
 		newOwner;
 		dummy = 0;
modifiedtests/package.jsondiffbeforeafterboth
--- a/tests/package.json
+++ b/tests/package.json
@@ -88,8 +88,11 @@
     "testLimits": "mocha --timeout 9999999 -r ts-node/register ./**/limits.test.ts",
     "testEthCreateNFTCollection": "mocha --timeout 9999999 -r ts-node/register ./**/eth/createNFTCollection.test.ts",
     "testEthCreateRFTCollection": "mocha --timeout 9999999 -r ts-node/register ./**/eth/createRFTCollection.test.ts",
+    "testEthNFT": "mocha --timeout 9999999 -r ts-node/register ./**/eth/nonFungible.test.ts",
     "testRFT": "mocha --timeout 9999999 -r ts-node/register ./**/refungible.test.ts",
+    "testEthRFT": "mocha --timeout 9999999 -r ts-node/register ./**/eth/reFungible.test.ts ./**/eth/reFungibleToken.test.ts",
     "testFT": "mocha --timeout 9999999 -r ts-node/register ./**/fungible.test.ts",
+    "testEthFT": "mocha --timeout 9999999 -r ts-node/register ./**/eth/fungible.test.ts",
     "testRPC": "mocha --timeout 9999999 -r ts-node/register ./**/rpc.test.ts",
     "testPromotion": "mocha --timeout 9999999 -r ts-node/register ./**/app-promotion.test.ts",
     "polkadot-types-fetch-metadata": "curl -H 'Content-Type: application/json' -d '{\"id\":\"1\", \"jsonrpc\":\"2.0\", \"method\": \"state_getMetadata\", \"params\":[]}' http://localhost:9933 > src/interfaces/metadata.json",
modifiedtests/src/eth/allowlist.test.tsdiffbeforeafterboth
--- a/tests/src/eth/allowlist.test.ts
+++ b/tests/src/eth/allowlist.test.ts
@@ -95,20 +95,21 @@
     expect(await collectionEvm.methods.allowed(user).call({from: owner})).to.be.false;
   });
 
-  itEth('Collection allowlist can be added and removed by [sub] address', async ({helper}) => {
-    const owner = await helper.eth.createAccountWithBalance(donor);
-    const user = donor;
+  // TODO: Temprorary off. Need refactor
+  // itEth('Collection allowlist can be added and removed by [sub] address', async ({helper}) => {
+  //   const owner = await helper.eth.createAccountWithBalance(donor);
+  //   const user = donor;
     
-    const {collectionAddress, collectionId} = await helper.eth.createNonfungibleCollection(owner, 'A', 'B', 'C');
-    const collectionEvm = helper.ethNativeContract.collection(collectionAddress, 'nft', owner);
+  //   const {collectionAddress, collectionId} = await helper.eth.createNonfungibleCollection(owner, 'A', 'B', 'C');
+  //   const collectionEvm = helper.ethNativeContract.collection(collectionAddress, 'nft', owner);
     
-    expect(await helper.collection.allowed(collectionId, {Substrate: user.address})).to.be.false;
-    await collectionEvm.methods.addToCollectionAllowListSubstrate(user.addressRaw).send({from: owner});
-    expect(await helper.collection.allowed(collectionId, {Substrate: user.address})).to.be.true;
+  //   expect(await helper.collection.allowed(collectionId, {Substrate: user.address})).to.be.false;
+  //   await collectionEvm.methods.addToCollectionAllowListSubstrate(user.addressRaw).send({from: owner});
+  //   expect(await helper.collection.allowed(collectionId, {Substrate: user.address})).to.be.true;
     
-    await collectionEvm.methods.removeFromCollectionAllowListSubstrate(user.addressRaw).send({from: owner});
-    expect(await helper.collection.allowed(collectionId, {Substrate: user.address})).to.be.false;
-  });
+  //   await collectionEvm.methods.removeFromCollectionAllowListSubstrate(user.addressRaw).send({from: owner});
+  //   expect(await helper.collection.allowed(collectionId, {Substrate: user.address})).to.be.false;
+  // });
 
   itEth('Collection allowlist can not be add and remove [eth] address by not owner', async ({helper}) => {
     const owner = await helper.eth.createAccountWithBalance(donor);
@@ -128,21 +129,22 @@
     expect(await collectionEvm.methods.allowed(user).call({from: owner})).to.be.true;
   });
 
-  itEth('Collection allowlist can not be add and remove [sub] address by not owner', async ({helper}) => {
-    const owner = await helper.eth.createAccountWithBalance(donor);
-    const notOwner = await helper.eth.createAccountWithBalance(donor);
-    const user = donor;
+  // TODO: Temprorary off. Need refactor
+  // itEth('Collection allowlist can not be add and remove [sub] address by not owner', async ({helper}) => {
+  //   const owner = await helper.eth.createAccountWithBalance(donor);
+  //   const notOwner = await helper.eth.createAccountWithBalance(donor);
+  //   const user = donor;
     
-    const {collectionAddress, collectionId} = await helper.eth.createNonfungibleCollection(owner, 'A', 'B', 'C');
-    const collectionEvm = helper.ethNativeContract.collection(collectionAddress, 'nft', owner);
+  //   const {collectionAddress, collectionId} = await helper.eth.createNonfungibleCollection(owner, 'A', 'B', 'C');
+  //   const collectionEvm = helper.ethNativeContract.collection(collectionAddress, 'nft', owner);
     
-    expect(await helper.collection.allowed(collectionId, {Substrate: user.address})).to.be.false;
-    await expect(collectionEvm.methods.addToCollectionAllowListSubstrate(user.addressRaw).call({from: notOwner})).to.be.rejectedWith('NoPermission');
-    expect(await helper.collection.allowed(collectionId, {Substrate: user.address})).to.be.false;
-    await collectionEvm.methods.addToCollectionAllowListSubstrate(user.addressRaw).send({from: owner});
+  //   expect(await helper.collection.allowed(collectionId, {Substrate: user.address})).to.be.false;
+  //   await expect(collectionEvm.methods.addToCollectionAllowListSubstrate(user.addressRaw).call({from: notOwner})).to.be.rejectedWith('NoPermission');
+  //   expect(await helper.collection.allowed(collectionId, {Substrate: user.address})).to.be.false;
+  //   await collectionEvm.methods.addToCollectionAllowListSubstrate(user.addressRaw).send({from: owner});
     
-    expect(await helper.collection.allowed(collectionId, {Substrate: user.address})).to.be.true;
-    await expect(collectionEvm.methods.removeFromCollectionAllowListSubstrate(user.addressRaw).call({from: notOwner})).to.be.rejectedWith('NoPermission');
-    expect(await helper.collection.allowed(collectionId, {Substrate: user.address})).to.be.true;
-  });
+  //   expect(await helper.collection.allowed(collectionId, {Substrate: user.address})).to.be.true;
+  //   await expect(collectionEvm.methods.removeFromCollectionAllowListSubstrate(user.addressRaw).call({from: notOwner})).to.be.rejectedWith('NoPermission');
+  //   expect(await helper.collection.allowed(collectionId, {Substrate: user.address})).to.be.true;
+  // });
 });
modifiedtests/src/eth/api/UniqueFungible.soldiffbeforeafterboth
--- a/tests/src/eth/api/UniqueFungible.sol
+++ b/tests/src/eth/api/UniqueFungible.sol
@@ -13,7 +13,7 @@
 }
 
 /// @title A contract that allows you to work with collections.
-/// @dev the ERC-165 identifier for this interface is 0x47dbc105
+/// @dev the ERC-165 identifier for this interface is 0x3e1e8083
 interface Collection is Dummy, ERC165 {
 	/// Set collection property.
 	///
@@ -48,15 +48,6 @@
 	/// @dev EVM selector for this function is: 0x7623402e,
 	///  or in textual repr: setCollectionSponsor(address)
 	function setCollectionSponsor(address sponsor) external;
-
-	/// Set the substrate sponsor of the collection.
-	///
-	/// @dev In order for sponsorship to work, it must be confirmed on behalf of the sponsor.
-	///
-	/// @param sponsor Substrate address of the sponsor from whose account funds will be debited for operations with the contract.
-	/// @dev EVM selector for this function is: 0xc74d6751,
-	///  or in textual repr: setCollectionSponsorSubstrate(uint256)
-	function setCollectionSponsorSubstrate(uint256 sponsor) external;
 
 	/// Whether there is a pending sponsor.
 	/// @dev EVM selector for this function is: 0x058ac185,
@@ -112,18 +103,6 @@
 	///  or in textual repr: contractAddress()
 	function contractAddress() external view returns (address);
 
-	/// Add collection admin by substrate address.
-	/// @param newAdmin Substrate administrator address.
-	/// @dev EVM selector for this function is: 0x5730062b,
-	///  or in textual repr: addCollectionAdminSubstrate(uint256)
-	function addCollectionAdminSubstrate(uint256 newAdmin) external;
-
-	/// Remove collection admin by substrate address.
-	/// @param admin Substrate administrator address.
-	/// @dev EVM selector for this function is: 0x4048fcf9,
-	///  or in textual repr: removeCollectionAdminSubstrate(uint256)
-	function removeCollectionAdminSubstrate(uint256 admin) external;
-
 	/// Add collection admin.
 	/// @param newAdmin Address of the added administrator.
 	/// @dev EVM selector for this function is: 0x92e462c7,
@@ -174,13 +153,6 @@
 	///  or in textual repr: addToCollectionAllowList(address)
 	function addToCollectionAllowList(address user) external;
 
-	/// Add substrate user to allowed list.
-	///
-	/// @param user User substrate address.
-	/// @dev EVM selector for this function is: 0xd06ad267,
-	///  or in textual repr: addToCollectionAllowListSubstrate(uint256)
-	function addToCollectionAllowListSubstrate(uint256 user) external;
-
 	/// Remove the user from the allowed list.
 	///
 	/// @param user Address of a removed user.
@@ -188,13 +160,6 @@
 	///  or in textual repr: removeFromCollectionAllowList(address)
 	function removeFromCollectionAllowList(address user) external;
 
-	/// Remove substrate user from allowed list.
-	///
-	/// @param user User substrate address.
-	/// @dev EVM selector for this function is: 0xa31913ed,
-	///  or in textual repr: removeFromCollectionAllowListSubstrate(uint256)
-	function removeFromCollectionAllowListSubstrate(uint256 user) external;
-
 	/// Switch permission for minting.
 	///
 	/// @param mode Enable if "true".
@@ -209,14 +174,6 @@
 	/// @dev EVM selector for this function is: 0x9811b0c7,
 	///  or in textual repr: isOwnerOrAdmin(address)
 	function isOwnerOrAdmin(address user) external view returns (bool);
-
-	/// Check that substrate account is the owner or admin of the collection
-	///
-	/// @param user account to verify
-	/// @return "true" if account is the owner or admin
-	/// @dev EVM selector for this function is: 0x68910e00,
-	///  or in textual repr: isOwnerOrAdminSubstrate(uint256)
-	function isOwnerOrAdminSubstrate(uint256 user) external view returns (bool);
 
 	/// Returns collection type
 	///
@@ -240,14 +197,6 @@
 	/// @dev EVM selector for this function is: 0x13af4035,
 	///  or in textual repr: setOwner(address)
 	function setOwner(address newOwner) external;
-
-	/// Changes collection owner to another substrate account
-	///
-	/// @dev Owner can be changed only by current owner
-	/// @param newOwner new owner substrate account
-	/// @dev EVM selector for this function is: 0xb212138f,
-	///  or in textual repr: setOwnerSubstrate(uint256)
-	function setOwnerSubstrate(uint256 newOwner) external;
 }
 
 /// @dev the ERC-165 identifier for this interface is 0x63034ac5
modifiedtests/src/eth/api/UniqueNFT.soldiffbeforeafterboth
--- a/tests/src/eth/api/UniqueNFT.sol
+++ b/tests/src/eth/api/UniqueNFT.sol
@@ -62,7 +62,7 @@
 }
 
 /// @title A contract that allows you to work with collections.
-/// @dev the ERC-165 identifier for this interface is 0x47dbc105
+/// @dev the ERC-165 identifier for this interface is 0x3e1e8083
 interface Collection is Dummy, ERC165 {
 	/// Set collection property.
 	///
@@ -97,15 +97,6 @@
 	/// @dev EVM selector for this function is: 0x7623402e,
 	///  or in textual repr: setCollectionSponsor(address)
 	function setCollectionSponsor(address sponsor) external;
-
-	/// Set the substrate sponsor of the collection.
-	///
-	/// @dev In order for sponsorship to work, it must be confirmed on behalf of the sponsor.
-	///
-	/// @param sponsor Substrate address of the sponsor from whose account funds will be debited for operations with the contract.
-	/// @dev EVM selector for this function is: 0xc74d6751,
-	///  or in textual repr: setCollectionSponsorSubstrate(uint256)
-	function setCollectionSponsorSubstrate(uint256 sponsor) external;
 
 	/// Whether there is a pending sponsor.
 	/// @dev EVM selector for this function is: 0x058ac185,
@@ -161,18 +152,6 @@
 	///  or in textual repr: contractAddress()
 	function contractAddress() external view returns (address);
 
-	/// Add collection admin by substrate address.
-	/// @param newAdmin Substrate administrator address.
-	/// @dev EVM selector for this function is: 0x5730062b,
-	///  or in textual repr: addCollectionAdminSubstrate(uint256)
-	function addCollectionAdminSubstrate(uint256 newAdmin) external;
-
-	/// Remove collection admin by substrate address.
-	/// @param admin Substrate administrator address.
-	/// @dev EVM selector for this function is: 0x4048fcf9,
-	///  or in textual repr: removeCollectionAdminSubstrate(uint256)
-	function removeCollectionAdminSubstrate(uint256 admin) external;
-
 	/// Add collection admin.
 	/// @param newAdmin Address of the added administrator.
 	/// @dev EVM selector for this function is: 0x92e462c7,
@@ -223,13 +202,6 @@
 	///  or in textual repr: addToCollectionAllowList(address)
 	function addToCollectionAllowList(address user) external;
 
-	/// Add substrate user to allowed list.
-	///
-	/// @param user User substrate address.
-	/// @dev EVM selector for this function is: 0xd06ad267,
-	///  or in textual repr: addToCollectionAllowListSubstrate(uint256)
-	function addToCollectionAllowListSubstrate(uint256 user) external;
-
 	/// Remove the user from the allowed list.
 	///
 	/// @param user Address of a removed user.
@@ -237,13 +209,6 @@
 	///  or in textual repr: removeFromCollectionAllowList(address)
 	function removeFromCollectionAllowList(address user) external;
 
-	/// Remove substrate user from allowed list.
-	///
-	/// @param user User substrate address.
-	/// @dev EVM selector for this function is: 0xa31913ed,
-	///  or in textual repr: removeFromCollectionAllowListSubstrate(uint256)
-	function removeFromCollectionAllowListSubstrate(uint256 user) external;
-
 	/// Switch permission for minting.
 	///
 	/// @param mode Enable if "true".
@@ -258,14 +223,6 @@
 	/// @dev EVM selector for this function is: 0x9811b0c7,
 	///  or in textual repr: isOwnerOrAdmin(address)
 	function isOwnerOrAdmin(address user) external view returns (bool);
-
-	/// Check that substrate account is the owner or admin of the collection
-	///
-	/// @param user account to verify
-	/// @return "true" if account is the owner or admin
-	/// @dev EVM selector for this function is: 0x68910e00,
-	///  or in textual repr: isOwnerOrAdminSubstrate(uint256)
-	function isOwnerOrAdminSubstrate(uint256 user) external view returns (bool);
 
 	/// Returns collection type
 	///
@@ -289,14 +246,6 @@
 	/// @dev EVM selector for this function is: 0x13af4035,
 	///  or in textual repr: setOwner(address)
 	function setOwner(address newOwner) external;
-
-	/// Changes collection owner to another substrate account
-	///
-	/// @dev Owner can be changed only by current owner
-	/// @param newOwner new owner substrate account
-	/// @dev EVM selector for this function is: 0xb212138f,
-	///  or in textual repr: setOwnerSubstrate(uint256)
-	function setOwnerSubstrate(uint256 newOwner) external;
 }
 
 /// @dev anonymous struct
modifiedtests/src/eth/api/UniqueRefungible.soldiffbeforeafterboth
--- a/tests/src/eth/api/UniqueRefungible.sol
+++ b/tests/src/eth/api/UniqueRefungible.sol
@@ -62,7 +62,7 @@
 }
 
 /// @title A contract that allows you to work with collections.
-/// @dev the ERC-165 identifier for this interface is 0x47dbc105
+/// @dev the ERC-165 identifier for this interface is 0x3e1e8083
 interface Collection is Dummy, ERC165 {
 	/// Set collection property.
 	///
@@ -97,15 +97,6 @@
 	/// @dev EVM selector for this function is: 0x7623402e,
 	///  or in textual repr: setCollectionSponsor(address)
 	function setCollectionSponsor(address sponsor) external;
-
-	/// Set the substrate sponsor of the collection.
-	///
-	/// @dev In order for sponsorship to work, it must be confirmed on behalf of the sponsor.
-	///
-	/// @param sponsor Substrate address of the sponsor from whose account funds will be debited for operations with the contract.
-	/// @dev EVM selector for this function is: 0xc74d6751,
-	///  or in textual repr: setCollectionSponsorSubstrate(uint256)
-	function setCollectionSponsorSubstrate(uint256 sponsor) external;
 
 	/// Whether there is a pending sponsor.
 	/// @dev EVM selector for this function is: 0x058ac185,
@@ -161,18 +152,6 @@
 	///  or in textual repr: contractAddress()
 	function contractAddress() external view returns (address);
 
-	/// Add collection admin by substrate address.
-	/// @param newAdmin Substrate administrator address.
-	/// @dev EVM selector for this function is: 0x5730062b,
-	///  or in textual repr: addCollectionAdminSubstrate(uint256)
-	function addCollectionAdminSubstrate(uint256 newAdmin) external;
-
-	/// Remove collection admin by substrate address.
-	/// @param admin Substrate administrator address.
-	/// @dev EVM selector for this function is: 0x4048fcf9,
-	///  or in textual repr: removeCollectionAdminSubstrate(uint256)
-	function removeCollectionAdminSubstrate(uint256 admin) external;
-
 	/// Add collection admin.
 	/// @param newAdmin Address of the added administrator.
 	/// @dev EVM selector for this function is: 0x92e462c7,
@@ -223,13 +202,6 @@
 	///  or in textual repr: addToCollectionAllowList(address)
 	function addToCollectionAllowList(address user) external;
 
-	/// Add substrate user to allowed list.
-	///
-	/// @param user User substrate address.
-	/// @dev EVM selector for this function is: 0xd06ad267,
-	///  or in textual repr: addToCollectionAllowListSubstrate(uint256)
-	function addToCollectionAllowListSubstrate(uint256 user) external;
-
 	/// Remove the user from the allowed list.
 	///
 	/// @param user Address of a removed user.
@@ -237,13 +209,6 @@
 	///  or in textual repr: removeFromCollectionAllowList(address)
 	function removeFromCollectionAllowList(address user) external;
 
-	/// Remove substrate user from allowed list.
-	///
-	/// @param user User substrate address.
-	/// @dev EVM selector for this function is: 0xa31913ed,
-	///  or in textual repr: removeFromCollectionAllowListSubstrate(uint256)
-	function removeFromCollectionAllowListSubstrate(uint256 user) external;
-
 	/// Switch permission for minting.
 	///
 	/// @param mode Enable if "true".
@@ -258,14 +223,6 @@
 	/// @dev EVM selector for this function is: 0x9811b0c7,
 	///  or in textual repr: isOwnerOrAdmin(address)
 	function isOwnerOrAdmin(address user) external view returns (bool);
-
-	/// Check that substrate account is the owner or admin of the collection
-	///
-	/// @param user account to verify
-	/// @return "true" if account is the owner or admin
-	/// @dev EVM selector for this function is: 0x68910e00,
-	///  or in textual repr: isOwnerOrAdminSubstrate(uint256)
-	function isOwnerOrAdminSubstrate(uint256 user) external view returns (bool);
 
 	/// Returns collection type
 	///
@@ -289,14 +246,6 @@
 	/// @dev EVM selector for this function is: 0x13af4035,
 	///  or in textual repr: setOwner(address)
 	function setOwner(address newOwner) external;
-
-	/// Changes collection owner to another substrate account
-	///
-	/// @dev Owner can be changed only by current owner
-	/// @param newOwner new owner substrate account
-	/// @dev EVM selector for this function is: 0xb212138f,
-	///  or in textual repr: setOwnerSubstrate(uint256)
-	function setOwnerSubstrate(uint256 newOwner) external;
 }
 
 /// @dev anonymous struct
modifiedtests/src/eth/collectionAdmin.test.tsdiffbeforeafterboth
--- a/tests/src/eth/collectionAdmin.test.ts
+++ b/tests/src/eth/collectionAdmin.test.ts
@@ -44,23 +44,24 @@
       .to.be.eq(newAdmin.toLocaleLowerCase());
   });
 
-  itWeb3('Add substrate admin by owner', async ({api, web3, privateKeyWrapper}) => {
-    const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
-    const collectionHelper = evmCollectionHelpers(web3, owner);
+  // TODO: Temprorary off. Need refactor
+  // itWeb3('Add substrate admin by owner', async ({api, web3, privateKeyWrapper}) => {
+  //   const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
+  //   const collectionHelper = evmCollectionHelpers(web3, owner);
         
-    const result = await collectionHelper.methods
-      .createNonfungibleCollection('A', 'B', 'C')
-      .send();
-    const {collectionIdAddress, collectionId} = await getCollectionAddressFromResult(api, result);
+  //   const result = await collectionHelper.methods
+  //     .createNonfungibleCollection('A', 'B', 'C')
+  //     .send();
+  //   const {collectionIdAddress, collectionId} = await getCollectionAddressFromResult(api, result);
 
-    const newAdmin = privateKeyWrapper('//Alice');
-    const collectionEvm = evmCollection(web3, owner, collectionIdAddress);
-    await collectionEvm.methods.addCollectionAdminSubstrate(newAdmin.addressRaw).send();
+  //   const newAdmin = privateKeyWrapper('//Alice');
+  //   const collectionEvm = evmCollection(web3, owner, collectionIdAddress);
+  //   await collectionEvm.methods.addCollectionAdminSubstrate(newAdmin.addressRaw).send();
 
-    const adminList = await api.rpc.unique.adminlist(collectionId);
-    expect(adminList[0].asSubstrate.toString().toLocaleLowerCase())
-      .to.be.eq(newAdmin.address.toLocaleLowerCase());
-  });
+  //   const adminList = await api.rpc.unique.adminlist(collectionId);
+  //   expect(adminList[0].asSubstrate.toString().toLocaleLowerCase())
+  //     .to.be.eq(newAdmin.address.toLocaleLowerCase());
+  // });
   
   itWeb3('Verify owner or admin', async ({api, web3, privateKeyWrapper}) => {
     const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
@@ -121,47 +122,49 @@
     expect(adminList.length).to.be.eq(0);
   });
 
-  itWeb3('(!negative tests!) Add substrate admin by ADMIN is not allowed', async ({api, web3, privateKeyWrapper}) => {
-    const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
-    const collectionHelper = evmCollectionHelpers(web3, owner);
+  // TODO: Temprorary off. Need refactor
+  // itWeb3('(!negative tests!) Add substrate admin by ADMIN is not allowed', async ({api, web3, privateKeyWrapper}) => {
+  //   const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
+  //   const collectionHelper = evmCollectionHelpers(web3, owner);
         
-    const result = await collectionHelper.methods
-      .createNonfungibleCollection('A', 'B', 'C')
-      .send();
-    const {collectionIdAddress, collectionId} = await getCollectionAddressFromResult(api, result);
+  //   const result = await collectionHelper.methods
+  //     .createNonfungibleCollection('A', 'B', 'C')
+  //     .send();
+  //   const {collectionIdAddress, collectionId} = await getCollectionAddressFromResult(api, result);
 
-    const admin = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
-    const collectionEvm = evmCollection(web3, owner, collectionIdAddress);
-    await collectionEvm.methods.addCollectionAdmin(admin).send();
+  //   const admin = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
+  //   const collectionEvm = evmCollection(web3, owner, collectionIdAddress);
+  //   await collectionEvm.methods.addCollectionAdmin(admin).send();
 
-    const notAdmin = privateKey('//Alice');
-    await expect(collectionEvm.methods.addCollectionAdminSubstrate(notAdmin.addressRaw).call({from: admin}))
-      .to.be.rejectedWith('NoPermission');
+  //   const notAdmin = privateKey('//Alice');
+  //   await expect(collectionEvm.methods.addCollectionAdminSubstrate(notAdmin.addressRaw).call({from: admin}))
+  //     .to.be.rejectedWith('NoPermission');
 
-    const adminList = await api.rpc.unique.adminlist(collectionId);
-    expect(adminList.length).to.be.eq(1);
-    expect(adminList[0].asEthereum.toString().toLocaleLowerCase())
-      .to.be.eq(admin.toLocaleLowerCase());
-  });
+  //   const adminList = await api.rpc.unique.adminlist(collectionId);
+  //   expect(adminList.length).to.be.eq(1);
+  //   expect(adminList[0].asEthereum.toString().toLocaleLowerCase())
+  //     .to.be.eq(admin.toLocaleLowerCase());
+  // });
   
-  itWeb3('(!negative tests!) Add substrate admin by USER is not allowed', async ({api, web3, privateKeyWrapper}) => {
-    const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
-    const collectionHelper = evmCollectionHelpers(web3, owner);
+  // TODO: Temprorary off. Need refactor
+  // itWeb3('(!negative tests!) Add substrate admin by USER is not allowed', async ({api, web3, privateKeyWrapper}) => {
+  //   const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
+  //   const collectionHelper = evmCollectionHelpers(web3, owner);
         
-    const result = await collectionHelper.methods
-      .createNonfungibleCollection('A', 'B', 'C')
-      .send();
-    const {collectionIdAddress, collectionId} = await getCollectionAddressFromResult(api, result);
+  //   const result = await collectionHelper.methods
+  //     .createNonfungibleCollection('A', 'B', 'C')
+  //     .send();
+  //   const {collectionIdAddress, collectionId} = await getCollectionAddressFromResult(api, result);
 
-    const notAdmin0 = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
-    const collectionEvm = evmCollection(web3, owner, collectionIdAddress);
-    const notAdmin1 = privateKey('//Alice');
-    await expect(collectionEvm.methods.addCollectionAdminSubstrate(notAdmin1.addressRaw).call({from: notAdmin0}))
-      .to.be.rejectedWith('NoPermission');
+  //   const notAdmin0 = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
+  //   const collectionEvm = evmCollection(web3, owner, collectionIdAddress);
+  //   const notAdmin1 = privateKey('//Alice');
+  //   await expect(collectionEvm.methods.addCollectionAdminSubstrate(notAdmin1.addressRaw).call({from: notAdmin0}))
+  //     .to.be.rejectedWith('NoPermission');
 
-    const adminList = await api.rpc.unique.adminlist(collectionId);
-    expect(adminList.length).to.be.eq(0);
-  });
+  //   const adminList = await api.rpc.unique.adminlist(collectionId);
+  //   expect(adminList.length).to.be.eq(0);
+  // });
 });
 
 describe('Remove collection admins', () => {
@@ -189,28 +192,29 @@
     expect(adminList.length).to.be.eq(0);
   });
 
-  itWeb3('Remove substrate admin by owner', async ({api, web3, privateKeyWrapper}) => {
-    const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
-    const collectionHelper = evmCollectionHelpers(web3, owner);
+  // TODO: Temprorary off. Need refactor
+  // itWeb3('Remove substrate admin by owner', async ({api, web3, privateKeyWrapper}) => {
+  //   const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
+  //   const collectionHelper = evmCollectionHelpers(web3, owner);
         
-    const result = await collectionHelper.methods
-      .createNonfungibleCollection('A', 'B', 'C')
-      .send();
-    const {collectionIdAddress, collectionId} = await getCollectionAddressFromResult(api, result);
+  //   const result = await collectionHelper.methods
+  //     .createNonfungibleCollection('A', 'B', 'C')
+  //     .send();
+  //   const {collectionIdAddress, collectionId} = await getCollectionAddressFromResult(api, result);
 
-    const newAdmin = privateKeyWrapper('//Alice');
-    const collectionEvm = evmCollection(web3, owner, collectionIdAddress);
-    await collectionEvm.methods.addCollectionAdminSubstrate(newAdmin.addressRaw).send();
-    {
-      const adminList = await api.rpc.unique.adminlist(collectionId);
-      expect(adminList[0].asSubstrate.toString().toLocaleLowerCase())
-        .to.be.eq(newAdmin.address.toLocaleLowerCase());
-    }
+  //   const newAdmin = privateKeyWrapper('//Alice');
+  //   const collectionEvm = evmCollection(web3, owner, collectionIdAddress);
+  //   await collectionEvm.methods.addCollectionAdminSubstrate(newAdmin.addressRaw).send();
+  //   {
+  //     const adminList = await api.rpc.unique.adminlist(collectionId);
+  //     expect(adminList[0].asSubstrate.toString().toLocaleLowerCase())
+  //       .to.be.eq(newAdmin.address.toLocaleLowerCase());
+  //   }
     
-    await collectionEvm.methods.removeCollectionAdminSubstrate(newAdmin.addressRaw).send();
-    const adminList = await api.rpc.unique.adminlist(collectionId);
-    expect(adminList.length).to.be.eq(0);
-  });
+  //   await collectionEvm.methods.removeCollectionAdminSubstrate(newAdmin.addressRaw).send();
+  //   const adminList = await api.rpc.unique.adminlist(collectionId);
+  //   expect(adminList.length).to.be.eq(0);
+  // });
 
   itWeb3('(!negative tests!) Remove admin by ADMIN is not allowed', async ({api, web3, privateKeyWrapper}) => {
     const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
@@ -264,53 +268,55 @@
     }
   });
 
-  itWeb3('(!negative tests!) Remove substrate admin by ADMIN is not allowed', async ({api, web3, privateKeyWrapper}) => {
-    const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
-    const collectionHelper = evmCollectionHelpers(web3, owner);
+  // TODO: Temprorary off. Need refactor
+  // itWeb3('(!negative tests!) Remove substrate admin by ADMIN is not allowed', async ({api, web3, privateKeyWrapper}) => {
+  //   const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
+  //   const collectionHelper = evmCollectionHelpers(web3, owner);
         
-    const result = await collectionHelper.methods
-      .createNonfungibleCollection('A', 'B', 'C')
-      .send();
-    const {collectionIdAddress, collectionId} = await getCollectionAddressFromResult(api, result);
+  //   const result = await collectionHelper.methods
+  //     .createNonfungibleCollection('A', 'B', 'C')
+  //     .send();
+  //   const {collectionIdAddress, collectionId} = await getCollectionAddressFromResult(api, result);
 
-    const adminSub = privateKeyWrapper('//Alice');
-    const collectionEvm = evmCollection(web3, owner, collectionIdAddress);
-    await collectionEvm.methods.addCollectionAdminSubstrate(adminSub.addressRaw).send();
-    const adminEth = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
-    await collectionEvm.methods.addCollectionAdmin(adminEth).send();
+  //   const adminSub = privateKeyWrapper('//Alice');
+  //   const collectionEvm = evmCollection(web3, owner, collectionIdAddress);
+  //   await collectionEvm.methods.addCollectionAdminSubstrate(adminSub.addressRaw).send();
+  //   const adminEth = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
+  //   await collectionEvm.methods.addCollectionAdmin(adminEth).send();
 
-    await expect(collectionEvm.methods.removeCollectionAdminSubstrate(adminSub.addressRaw).call({from: adminEth}))
-      .to.be.rejectedWith('NoPermission');
+  //   await expect(collectionEvm.methods.removeCollectionAdminSubstrate(adminSub.addressRaw).call({from: adminEth}))
+  //     .to.be.rejectedWith('NoPermission');
 
-    const adminList = await api.rpc.unique.adminlist(collectionId);
-    expect(adminList.length).to.be.eq(2);
-    expect(adminList.toString().toLocaleLowerCase())
-      .to.be.deep.contains(adminSub.address.toLocaleLowerCase())
-      .to.be.deep.contains(adminEth.toLocaleLowerCase());
-  });
+  //   const adminList = await api.rpc.unique.adminlist(collectionId);
+  //   expect(adminList.length).to.be.eq(2);
+  //   expect(adminList.toString().toLocaleLowerCase())
+  //     .to.be.deep.contains(adminSub.address.toLocaleLowerCase())
+  //     .to.be.deep.contains(adminEth.toLocaleLowerCase());
+  // });
 
-  itWeb3('(!negative tests!) Remove substrate admin by USER is not allowed', async ({api, web3, privateKeyWrapper}) => {
-    const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
-    const collectionHelper = evmCollectionHelpers(web3, owner);
+  // TODO: Temprorary off. Need refactor
+  // itWeb3('(!negative tests!) Remove substrate admin by USER is not allowed', async ({api, web3, privateKeyWrapper}) => {
+  //   const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
+  //   const collectionHelper = evmCollectionHelpers(web3, owner);
         
-    const result = await collectionHelper.methods
-      .createNonfungibleCollection('A', 'B', 'C')
-      .send();
-    const {collectionIdAddress, collectionId} = await getCollectionAddressFromResult(api, result);
+  //   const result = await collectionHelper.methods
+  //     .createNonfungibleCollection('A', 'B', 'C')
+  //     .send();
+  //   const {collectionIdAddress, collectionId} = await getCollectionAddressFromResult(api, result);
 
-    const adminSub = privateKeyWrapper('//Alice');
-    const collectionEvm = evmCollection(web3, owner, collectionIdAddress);
-    await collectionEvm.methods.addCollectionAdminSubstrate(adminSub.addressRaw).send();
-    const notAdminEth = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
+  //   const adminSub = privateKeyWrapper('//Alice');
+  //   const collectionEvm = evmCollection(web3, owner, collectionIdAddress);
+  //   await collectionEvm.methods.addCollectionAdminSubstrate(adminSub.addressRaw).send();
+  //   const notAdminEth = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
 
-    await expect(collectionEvm.methods.removeCollectionAdminSubstrate(adminSub.addressRaw).call({from: notAdminEth}))
-      .to.be.rejectedWith('NoPermission');
+  //   await expect(collectionEvm.methods.removeCollectionAdminSubstrate(adminSub.addressRaw).call({from: notAdminEth}))
+  //     .to.be.rejectedWith('NoPermission');
 
-    const adminList = await api.rpc.unique.adminlist(collectionId);
-    expect(adminList.length).to.be.eq(1);
-    expect(adminList[0].asSubstrate.toString().toLocaleLowerCase())
-      .to.be.eq(adminSub.address.toLocaleLowerCase());
-  });
+  //   const adminList = await api.rpc.unique.adminlist(collectionId);
+  //   expect(adminList.length).to.be.eq(1);
+  //   expect(adminList[0].asSubstrate.toString().toLocaleLowerCase())
+  //     .to.be.eq(adminSub.address.toLocaleLowerCase());
+  // });
 });
 
 describe('Change owner tests', () => {
@@ -361,52 +367,55 @@
 });
 
 describe('Change substrate owner tests', () => {
-  itWeb3('Change owner', async ({api, web3, privateKeyWrapper}) => {
-    const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
-    const newOwner = privateKeyWrapper('//Alice');
-    const collectionHelper = evmCollectionHelpers(web3, owner);
-    const result = await collectionHelper.methods
-      .createNonfungibleCollection('A', 'B', 'C')
-      .send();
-    const {collectionIdAddress} = await getCollectionAddressFromResult(api, result);
-    const collectionEvm = evmCollection(web3, owner, collectionIdAddress);
+  // TODO: Temprorary off. Need refactor
+  // itWeb3('Change owner', async ({api, web3, privateKeyWrapper}) => {
+  //   const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
+  //   const newOwner = privateKeyWrapper('//Alice');
+  //   const collectionHelper = evmCollectionHelpers(web3, owner);
+  //   const result = await collectionHelper.methods
+  //     .createNonfungibleCollection('A', 'B', 'C')
+  //     .send();
+  //   const {collectionIdAddress} = await getCollectionAddressFromResult(api, result);
+  //   const collectionEvm = evmCollection(web3, owner, collectionIdAddress);
   
-    expect(await collectionEvm.methods.isOwnerOrAdmin(owner).call()).to.be.true;
-    expect(await collectionEvm.methods.isOwnerOrAdminSubstrate(newOwner.addressRaw).call()).to.be.false;
+  //   expect(await collectionEvm.methods.isOwnerOrAdmin(owner).call()).to.be.true;
+  //   expect(await collectionEvm.methods.isOwnerOrAdminSubstrate(newOwner.addressRaw).call()).to.be.false;
     
-    await collectionEvm.methods.setOwnerSubstrate(newOwner.addressRaw).send();
+  //   await collectionEvm.methods.setOwnerSubstrate(newOwner.addressRaw).send();
   
-    expect(await collectionEvm.methods.isOwnerOrAdmin(owner).call()).to.be.false;
-    expect(await collectionEvm.methods.isOwnerOrAdminSubstrate(newOwner.addressRaw).call()).to.be.true;
-  });
+  //   expect(await collectionEvm.methods.isOwnerOrAdmin(owner).call()).to.be.false;
+  //   expect(await collectionEvm.methods.isOwnerOrAdminSubstrate(newOwner.addressRaw).call()).to.be.true;
+  // });
 
-  itWeb3('change owner call fee', async ({web3, api, privateKeyWrapper}) => {
-    const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
-    const newOwner = privateKeyWrapper('//Alice');
-    const collectionHelper = evmCollectionHelpers(web3, owner);
-    const result = await collectionHelper.methods
-      .createNonfungibleCollection('A', 'B', 'C')
-      .send();
-    const {collectionIdAddress} = await getCollectionAddressFromResult(api, result);
-    const collectionEvm = evmCollection(web3, owner, collectionIdAddress);
+  // TODO: Temprorary off. Need refactor
+  // itWeb3('change owner call fee', async ({web3, api, privateKeyWrapper}) => {
+  //   const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
+  //   const newOwner = privateKeyWrapper('//Alice');
+  //   const collectionHelper = evmCollectionHelpers(web3, owner);
+  //   const result = await collectionHelper.methods
+  //     .createNonfungibleCollection('A', 'B', 'C')
+  //     .send();
+  //   const {collectionIdAddress} = await getCollectionAddressFromResult(api, result);
+  //   const collectionEvm = evmCollection(web3, owner, collectionIdAddress);
 
-    const cost = await recordEthFee(api, owner, () => collectionEvm.methods.setOwnerSubstrate(newOwner.addressRaw).send());
-    expect(cost < BigInt(0.2 * Number(UNIQUE)));
-    expect(cost > 0);
-  });
+  //   const cost = await recordEthFee(api, owner, () => collectionEvm.methods.setOwnerSubstrate(newOwner.addressRaw).send());
+  //   expect(cost < BigInt(0.2 * Number(UNIQUE)));
+  //   expect(cost > 0);
+  // });
 
-  itWeb3('(!negative tests!) call setOwner by non owner', async ({api, web3, privateKeyWrapper}) => {
-    const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
-    const otherReceiver = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
-    const newOwner = privateKeyWrapper('//Alice');
-    const collectionHelper = evmCollectionHelpers(web3, owner);
-    const result = await collectionHelper.methods
-      .createNonfungibleCollection('A', 'B', 'C')
-      .send();
-    const {collectionIdAddress} = await getCollectionAddressFromResult(api, result);
-    const collectionEvm = evmCollection(web3, owner, collectionIdAddress);
+  // TODO: Temprorary off. Need refactor
+  // itWeb3('(!negative tests!) call setOwner by non owner', async ({api, web3, privateKeyWrapper}) => {
+  //   const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
+  //   const otherReceiver = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
+  //   const newOwner = privateKeyWrapper('//Alice');
+  //   const collectionHelper = evmCollectionHelpers(web3, owner);
+  //   const result = await collectionHelper.methods
+  //     .createNonfungibleCollection('A', 'B', 'C')
+  //     .send();
+  //   const {collectionIdAddress} = await getCollectionAddressFromResult(api, result);
+  //   const collectionEvm = evmCollection(web3, owner, collectionIdAddress);
   
-    await expect(collectionEvm.methods.setOwnerSubstrate(newOwner.addressRaw).send({from: otherReceiver})).to.be.rejected;
-    expect(await collectionEvm.methods.isOwnerOrAdminSubstrate(newOwner.addressRaw).call()).to.be.false;
-  });
+  //   await expect(collectionEvm.methods.setOwnerSubstrate(newOwner.addressRaw).send({from: otherReceiver})).to.be.rejected;
+  //   expect(await collectionEvm.methods.isOwnerOrAdminSubstrate(newOwner.addressRaw).call()).to.be.false;
+  // });
 });
\ No newline at end of file
modifiedtests/src/eth/collectionSponsoring.test.tsdiffbeforeafterboth
--- a/tests/src/eth/collectionSponsoring.test.ts
+++ b/tests/src/eth/collectionSponsoring.test.ts
@@ -40,25 +40,26 @@
     ]);
   });
 
-  itWeb3('Set substrate sponsor', async ({api, web3, privateKeyWrapper}) => {
-    const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
-    const collectionHelpers = evmCollectionHelpers(web3, owner);
-    let result = await collectionHelpers.methods.createNonfungibleCollection('Sponsor collection', '1', '1').send();
-    const {collectionIdAddress, collectionId} = await getCollectionAddressFromResult(api, result);
-    const sponsor = privateKeyWrapper('//Alice');
-    const collectionEvm = evmCollection(web3, owner, collectionIdAddress);
+  // TODO: Temprorary off. Need refactor
+  // itWeb3('Set substrate sponsor', async ({api, web3, privateKeyWrapper}) => {
+  //   const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
+  //   const collectionHelpers = evmCollectionHelpers(web3, owner);
+  //   let result = await collectionHelpers.methods.createNonfungibleCollection('Sponsor collection', '1', '1').send();
+  //   const {collectionIdAddress, collectionId} = await getCollectionAddressFromResult(api, result);
+  //   const sponsor = privateKeyWrapper('//Alice');
+  //   const collectionEvm = evmCollection(web3, owner, collectionIdAddress);
 
-    expect(await collectionEvm.methods.hasCollectionPendingSponsor().call({from: owner})).to.be.false;
-    result = await collectionEvm.methods.setCollectionSponsorSubstrate(sponsor.addressRaw).send({from: owner});
-    expect(await collectionEvm.methods.hasCollectionPendingSponsor().call({from: owner})).to.be.true;
+  //   expect(await collectionEvm.methods.hasCollectionPendingSponsor().call({from: owner})).to.be.false;
+  //   result = await collectionEvm.methods.setCollectionSponsorSubstrate(sponsor.addressRaw).send({from: owner});
+  //   expect(await collectionEvm.methods.hasCollectionPendingSponsor().call({from: owner})).to.be.true;
     
-    const confirmTx = await api.tx.unique.confirmSponsorship(collectionId);
-    await submitTransactionAsync(sponsor, confirmTx);
-    expect(await collectionEvm.methods.hasCollectionPendingSponsor().call({from: owner})).to.be.false;
+  //   const confirmTx = await api.tx.unique.confirmSponsorship(collectionId);
+  //   await submitTransactionAsync(sponsor, confirmTx);
+  //   expect(await collectionEvm.methods.hasCollectionPendingSponsor().call({from: owner})).to.be.false;
     
-    const sponsorTuple = await collectionEvm.methods.collectionSponsor().call({from: owner});
-    expect(bigIntToSub(api, BigInt(sponsorTuple[1]))).to.be.eq(sponsor.address);
-  });
+  //   const sponsorTuple = await collectionEvm.methods.collectionSponsor().call({from: owner});
+  //   expect(bigIntToSub(api, BigInt(sponsorTuple[1]))).to.be.eq(sponsor.address);
+  // });
 
   itWeb3('Remove sponsor', async ({api, web3, privateKeyWrapper}) => {
     const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
@@ -150,60 +151,61 @@
     }
   });
 
-  itWeb3('Sponsoring collection from substrate address via access list', async ({api, web3, privateKeyWrapper}) => {
-    const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
-    const collectionHelpers = evmCollectionHelpers(web3, owner);
-    const result = await collectionHelpers.methods.createNonfungibleCollection('Sponsor collection', '1', '1').send();
-    const {collectionIdAddress, collectionId} = await getCollectionAddressFromResult(api, result);
-    const sponsor = privateKeyWrapper('//Alice');
-    const collectionEvm = evmCollection(web3, owner, collectionIdAddress);
+  // TODO: Temprorary off. Need refactor
+  // itWeb3('Sponsoring collection from substrate address via access list', async ({api, web3, privateKeyWrapper}) => {
+  //   const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
+  //   const collectionHelpers = evmCollectionHelpers(web3, owner);
+  //   const result = await collectionHelpers.methods.createNonfungibleCollection('Sponsor collection', '1', '1').send();
+  //   const {collectionIdAddress, collectionId} = await getCollectionAddressFromResult(api, result);
+  //   const sponsor = privateKeyWrapper('//Alice');
+  //   const collectionEvm = evmCollection(web3, owner, collectionIdAddress);
 
-    await collectionEvm.methods.setCollectionSponsorSubstrate(sponsor.addressRaw).send({from: owner});
+  //   await collectionEvm.methods.setCollectionSponsorSubstrate(sponsor.addressRaw).send({from: owner});
     
-    const confirmTx = await api.tx.unique.confirmSponsorship(collectionId);
-    await submitTransactionAsync(sponsor, confirmTx);
+  //   const confirmTx = await api.tx.unique.confirmSponsorship(collectionId);
+  //   await submitTransactionAsync(sponsor, confirmTx);
     
-    const user = createEthAccount(web3);
-    const nextTokenId = await collectionEvm.methods.nextTokenId().call();
-    expect(nextTokenId).to.be.equal('1');
+  //   const user = createEthAccount(web3);
+  //   const nextTokenId = await collectionEvm.methods.nextTokenId().call();
+  //   expect(nextTokenId).to.be.equal('1');
 
-    await collectionEvm.methods.setCollectionAccess(1 /*'AllowList'*/).send({from: owner});
-    await collectionEvm.methods.addToCollectionAllowList(user).send({from: owner});
-    await collectionEvm.methods.setCollectionMintMode(true).send({from: owner});
+  //   await collectionEvm.methods.setCollectionAccess(1 /*'AllowList'*/).send({from: owner});
+  //   await collectionEvm.methods.addToCollectionAllowList(user).send({from: owner});
+  //   await collectionEvm.methods.setCollectionMintMode(true).send({from: owner});
 
-    const ownerBalanceBefore = await ethBalanceViaSub(api, owner);
-    const sponsorBalanceBefore = (await getBalance(api, [sponsor.address]))[0];
+  //   const ownerBalanceBefore = await ethBalanceViaSub(api, owner);
+  //   const sponsorBalanceBefore = (await getBalance(api, [sponsor.address]))[0];
 
-    {
-      const nextTokenId = await collectionEvm.methods.nextTokenId().call();
-      expect(nextTokenId).to.be.equal('1');
-      const result = await collectionEvm.methods.mintWithTokenURI(
-        user,
-        nextTokenId,
-        'Test URI',
-      ).send({from: user});
-      const events = normalizeEvents(result.events);
+  //   {
+  //     const nextTokenId = await collectionEvm.methods.nextTokenId().call();
+  //     expect(nextTokenId).to.be.equal('1');
+  //     const result = await collectionEvm.methods.mintWithTokenURI(
+  //       user,
+  //       nextTokenId,
+  //       'Test URI',
+  //     ).send({from: user});
+  //     const events = normalizeEvents(result.events);
 
-      expect(events).to.be.deep.equal([
-        {
-          address: collectionIdAddress,
-          event: 'Transfer',
-          args: {
-            from: '0x0000000000000000000000000000000000000000',
-            to: user,
-            tokenId: nextTokenId,
-          },
-        },
-      ]);
+  //     expect(events).to.be.deep.equal([
+  //       {
+  //         address: collectionIdAddress,
+  //         event: 'Transfer',
+  //         args: {
+  //           from: '0x0000000000000000000000000000000000000000',
+  //           to: user,
+  //           tokenId: nextTokenId,
+  //         },
+  //       },
+  //     ]);
 
-      const ownerBalanceAfter = await ethBalanceViaSub(api, owner);
-      const sponsorBalanceAfter = (await getBalance(api, [sponsor.address]))[0];
+  //     const ownerBalanceAfter = await ethBalanceViaSub(api, owner);
+  //     const sponsorBalanceAfter = (await getBalance(api, [sponsor.address]))[0];
 
-      expect(await collectionEvm.methods.tokenURI(nextTokenId).call()).to.be.equal('Test URI');
-      expect(ownerBalanceBefore).to.be.eq(ownerBalanceAfter);
-      expect(sponsorBalanceBefore > sponsorBalanceAfter).to.be.true;
-    }
-  });
+  //     expect(await collectionEvm.methods.tokenURI(nextTokenId).call()).to.be.equal('Test URI');
+  //     expect(ownerBalanceBefore).to.be.eq(ownerBalanceAfter);
+  //     expect(sponsorBalanceBefore > sponsorBalanceAfter).to.be.true;
+  //   }
+  // });
 
   itWeb3('Check that transaction via EVM spend money from sponsor address', async ({api, web3, privateKeyWrapper}) => {
     const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
modifiedtests/src/eth/fungible.test.tsdiffbeforeafterboth
--- a/tests/src/eth/fungible.test.ts
+++ b/tests/src/eth/fungible.test.ts
@@ -14,204 +14,132 @@
 // You should have received a copy of the GNU General Public License
 // along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
 
-import {approveExpectSuccess, createCollection, createCollectionExpectSuccess, createFungibleItemExpectSuccess, transferExpectSuccess, transferFromExpectSuccess, UNIQUE} from '../util/helpers';
-import {collectionIdToAddress, createEthAccount, createEthAccountWithBalance, evmCollection, GAS_ARGS, itWeb3, normalizeEvents, recordEthFee, recordEvents, subToEth, transferBalanceToEth} from './util/helpers';
-import fungibleAbi from './fungibleAbi.json';
-import {expect} from 'chai';
-import {submitTransactionAsync} from '../substrate/substrate-api';
+import {expect, itEth, usingEthPlaygrounds} from './util/playgrounds';
+import {IKeyringPair} from '@polkadot/types/types';
 
 describe('Fungible: Information getting', () => {
-  itWeb3('totalSupply', async ({api, web3, privateKeyWrapper}) => {
-    const collection = await createCollectionExpectSuccess({
-      name: 'token name',
-      mode: {type: 'Fungible', decimalPoints: 0},
+  let donor: IKeyringPair;
+  let alice: IKeyringPair;
+
+  before(async function() {
+    await usingEthPlaygrounds(async (helper, privateKey) => {
+      donor = privateKey('//Alice');
+      [alice] = await helper.arrange.createAccounts([20n], donor);
     });
-    const alice = privateKeyWrapper('//Alice');
+  });
 
-    const caller = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
+  itEth('totalSupply', async ({helper}) => {
+    const caller = await helper.eth.createAccountWithBalance(donor);
+    const collection = await helper.ft.mintCollection(alice);
+    await collection.mint(alice, 200n);
 
-    await createFungibleItemExpectSuccess(alice, collection, {Value: 200n}, {Substrate: alice.address});
-
-    const address = collectionIdToAddress(collection);
-    const contract = new web3.eth.Contract(fungibleAbi as any, address, {from: caller, ...GAS_ARGS});
+    const contract = helper.ethNativeContract.collectionById(collection.collectionId, 'ft', caller);
     const totalSupply = await contract.methods.totalSupply().call();
-
     expect(totalSupply).to.equal('200');
   });
 
-  itWeb3('balanceOf', async ({api, web3, privateKeyWrapper}) => {
-    const collection = await createCollectionExpectSuccess({
-      name: 'token name',
-      mode: {type: 'Fungible', decimalPoints: 0},
-    });
-    const alice = privateKeyWrapper('//Alice');
+  itEth('balanceOf', async ({helper}) => {
+    const caller = await helper.eth.createAccountWithBalance(donor);
+    const collection = await helper.ft.mintCollection(alice);
+    await collection.mint(alice, 200n, {Ethereum: caller});
 
-    const caller = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
-
-    await createFungibleItemExpectSuccess(alice, collection, {Value: 200n}, {Ethereum: caller});
-
-    const address = collectionIdToAddress(collection);
-    const contract = new web3.eth.Contract(fungibleAbi as any, address, {from: caller, ...GAS_ARGS});
+    const contract = helper.ethNativeContract.collectionById(collection.collectionId, 'ft', caller);
     const balance = await contract.methods.balanceOf(caller).call();
-
     expect(balance).to.equal('200');
   });
 });
 
 describe('Fungible: Plain calls', () => {
-  itWeb3('Can perform mint()', async ({web3, api, privateKeyWrapper}) => {
-    const alice = privateKeyWrapper('//Alice');
-    const collection = await createCollection(api, alice, {
-      name: 'token name',
-      mode: {type: 'Fungible', decimalPoints: 0},
+  let donor: IKeyringPair;
+  let alice: IKeyringPair;
+
+  before(async function() {
+    await usingEthPlaygrounds(async (helper, privateKey) => {
+      donor = privateKey('//Alice');
+      [alice] = await helper.arrange.createAccounts([20n], donor);
     });
+  });
 
-    const receiver = createEthAccount(web3);
+  itEth('Can perform mint()', async ({helper}) => {
+    const owner = await helper.eth.createAccountWithBalance(donor);
+    const receiver = helper.eth.createAccount();
+    const collection = await helper.ft.mintCollection(alice);
+    await collection.addAdmin(alice, {Ethereum: owner});
 
-    const collectionIdAddress = collectionIdToAddress(collection.collectionId);
-    const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
-    const changeAdminTx = api.tx.unique.addCollectionAdmin(collection.collectionId, {Ethereum: owner});
-    await submitTransactionAsync(alice, changeAdminTx);
+    const collectionAddress = helper.ethAddress.fromCollectionId(collection.collectionId);
+    const contract = helper.ethNativeContract.collection(collectionAddress, 'ft', owner);
 
-    const collectionContract = evmCollection(web3, owner, collectionIdAddress, {type: 'Fungible', decimalPoints: 0});
-    const result = await collectionContract.methods.mint(receiver, 100).send();
-    const events = normalizeEvents(result.events);
+    const result = await contract.methods.mint(receiver, 100).send();
     
-    expect(events).to.be.deep.equal([
-      {
-        address: collectionIdAddress,
-        event: 'Transfer',
-        args: {
-          from: '0x0000000000000000000000000000000000000000',
-          to: receiver,
-          value: '100',
-        },
-      },
-    ]);
+    const event = result.events.Transfer;
+    expect(event.address).to.equal(collectionAddress);
+    expect(event.returnValues.from).to.equal('0x0000000000000000000000000000000000000000');
+    expect(event.returnValues.to).to.equal(receiver);
+    expect(event.returnValues.value).to.equal('100');
   });
-
-  itWeb3('Can perform mintBulk()', async ({web3, api, privateKeyWrapper}) => {
-    const alice = privateKeyWrapper('//Alice');
-    const collection = await createCollection(api, alice, {
-      name: 'token name',
-      mode: {type: 'Fungible', decimalPoints: 0},
-    });
 
-    const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
-    const receiver1 = createEthAccount(web3);
-    const receiver2 = createEthAccount(web3);
-    const receiver3 = createEthAccount(web3);
-
-    const collectionIdAddress = collectionIdToAddress(collection.collectionId);
-    const changeAdminTx = api.tx.unique.addCollectionAdmin(collection.collectionId, {Ethereum: owner});
-    await submitTransactionAsync(alice, changeAdminTx);
+  itEth('Can perform mintBulk()', async ({helper}) => {
+    const owner = await helper.eth.createAccountWithBalance(donor);
+    const bulkSize = 3;
+    const receivers = [...new Array(bulkSize)].map(() => helper.eth.createAccount());
+    const collection = await helper.ft.mintCollection(alice);
+    await collection.addAdmin(alice, {Ethereum: owner});
 
-    const collectionContract = evmCollection(web3, owner, collectionIdAddress, {type: 'Fungible', decimalPoints: 0});
-    const result = await collectionContract.methods.mintBulk([
-      [receiver1, 10],
-      [receiver2, 20],
-      [receiver3, 30],
-    ]).send();
-    const events = normalizeEvents(result.events);
+    const collectionAddress = helper.ethAddress.fromCollectionId(collection.collectionId);
+    const contract = helper.ethNativeContract.collection(collectionAddress, 'ft', owner);
 
-    expect(events).to.be.deep.contain({
-      address:collectionIdAddress,
-      event: 'Transfer',
-      args: {
-        from: '0x0000000000000000000000000000000000000000',
-        to: receiver1,
-        value: '10',
-      },
-    });
-    
-    expect(events).to.be.deep.contain({
-      address:collectionIdAddress,
-      event: 'Transfer',
-      args: {
-        from: '0x0000000000000000000000000000000000000000',
-        to: receiver2,
-        value: '20',
-      },
-    });
-    
-    expect(events).to.be.deep.contain({
-      address:collectionIdAddress,
-      event: 'Transfer',
-      args: {
-        from: '0x0000000000000000000000000000000000000000',
-        to: receiver3,
-        value: '30',
-      },
-    });
+    const result = await contract.methods.mintBulk(Array.from({length: bulkSize}, (_, i) => (
+      [receivers[i], (i + 1) * 10]
+    ))).send();
+    const events = result.events.Transfer.sort((a: any, b: any) => +a.returnValues.value - b.returnValues.value);
+    for (let i = 0; i < bulkSize; i++) {
+      const event = events[i];
+      expect(event.address).to.equal(collectionAddress);
+      expect(event.returnValues.from).to.equal('0x0000000000000000000000000000000000000000');
+      expect(event.returnValues.to).to.equal(receivers[i]);
+      expect(event.returnValues.value).to.equal(String(10 * (i + 1)));
+    }
   });
 
-  itWeb3('Can perform burn()', async ({web3, api, privateKeyWrapper}) => {
-    const alice = privateKeyWrapper('//Alice');
-    const collection = await createCollection(api, alice, {
-      name: 'token name',
-      mode: {type: 'Fungible', decimalPoints: 0},
-    });
-
-    const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
-    const changeAdminTx = api.tx.unique.addCollectionAdmin(collection.collectionId, {Ethereum: owner});
-    await submitTransactionAsync(alice, changeAdminTx);
-    const receiver = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
+  itEth('Can perform burn()', async ({helper}) => {
+    const owner = await helper.eth.createAccountWithBalance(donor);
+    const receiver = await helper.eth.createAccountWithBalance(donor);
+    const collection = await helper.ft.mintCollection(alice);
+    await collection.addAdmin(alice, {Ethereum: owner});
 
-    const collectionIdAddress = collectionIdToAddress(collection.collectionId);
-    const collectionContract = evmCollection(web3, owner, collectionIdAddress, {type: 'Fungible', decimalPoints: 0});
-    await collectionContract.methods.mint(receiver, 100).send();
+    const collectionAddress = helper.ethAddress.fromCollectionId(collection.collectionId);
+    const contract = helper.ethNativeContract.collection(collectionAddress, 'ft', owner);
+    await contract.methods.mint(receiver, 100).send();
 
-    const result = await collectionContract.methods.burnFrom(receiver, 49).send({from: receiver});
+    const result = await contract.methods.burnFrom(receiver, 49).send({from: receiver});
     
-    const events = normalizeEvents(result.events);
-
-    expect(events).to.be.deep.equal([
-      {
-        address: collectionIdAddress,
-        event: 'Transfer',
-        args: {
-          from: receiver,
-          to: '0x0000000000000000000000000000000000000000',
-          value: '49',
-        },
-      },
-    ]);
+    const event = result.events.Transfer;
+    expect(event.address).to.equal(collectionAddress);
+    expect(event.returnValues.from).to.equal(receiver);
+    expect(event.returnValues.to).to.equal('0x0000000000000000000000000000000000000000');
+    expect(event.returnValues.value).to.equal('49');
 
-    const balance = await collectionContract.methods.balanceOf(receiver).call();
+    const balance = await contract.methods.balanceOf(receiver).call();
     expect(balance).to.equal('51');
   });
 
-  itWeb3('Can perform approve()', async ({web3, api, privateKeyWrapper}) => {
-    const collection = await createCollectionExpectSuccess({
-      name: 'token name',
-      mode: {type: 'Fungible', decimalPoints: 0},
-    });
-    const alice = privateKeyWrapper('//Alice');
+  itEth('Can perform approve()', async ({helper}) => {
+    const owner = await helper.eth.createAccountWithBalance(donor);
+    const spender = helper.eth.createAccount();
+    const collection = await helper.ft.mintCollection(alice);
+    await collection.mint(alice, 200n, {Ethereum: owner});
 
-    const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
-
-    await createFungibleItemExpectSuccess(alice, collection, {Value: 200n}, {Ethereum: owner});
-
-    const spender = createEthAccount(web3);
+    const collectionAddress = helper.ethAddress.fromCollectionId(collection.collectionId);
+    const contract = helper.ethNativeContract.collection(collectionAddress, 'ft', owner);
 
-    const address = collectionIdToAddress(collection);
-    const contract = new web3.eth.Contract(fungibleAbi as any, address, {from: owner, ...GAS_ARGS});
-
     {
       const result = await contract.methods.approve(spender, 100).send({from: owner});
-      const events = normalizeEvents(result.events);
 
-      expect(events).to.be.deep.equal([
-        {
-          address,
-          event: 'Approval',
-          args: {
-            owner,
-            spender,
-            value: '100',
-          },
-        },
-      ]);
+      const event = result.events.Approval;
+      expect(event.address).to.be.equal(collectionAddress);
+      expect(event.returnValues.owner).to.be.equal(owner);
+      expect(event.returnValues.spender).to.be.equal(spender);
+      expect(event.returnValues.value).to.be.equal('100');
     }
 
     {
@@ -220,51 +148,32 @@
     }
   });
 
-  itWeb3('Can perform transferFrom()', async ({web3, api, privateKeyWrapper}) => {
-    const collection = await createCollectionExpectSuccess({
-      name: 'token name',
-      mode: {type: 'Fungible', decimalPoints: 0},
-    });
-    const alice = privateKeyWrapper('//Alice');
-
-    const owner = createEthAccount(web3);
-    await transferBalanceToEth(api, alice, owner);
-
-    await createFungibleItemExpectSuccess(alice, collection, {Value: 200n}, {Ethereum: owner});
-
-    const spender = createEthAccount(web3);
-    await transferBalanceToEth(api, alice, spender);
-
-    const receiver = createEthAccount(web3);
+  itEth('Can perform transferFrom()', async ({helper}) => {
+    const owner = await helper.eth.createAccountWithBalance(donor);
+    const spender = await helper.eth.createAccountWithBalance(donor);
+    const receiver = helper.eth.createAccount();
+    const collection = await helper.ft.mintCollection(alice);
+    await collection.mint(alice, 200n, {Ethereum: owner});
 
-    const address = collectionIdToAddress(collection);
-    const contract = new web3.eth.Contract(fungibleAbi as any, address, {from: owner, ...GAS_ARGS});
+    const collectionAddress = helper.ethAddress.fromCollectionId(collection.collectionId);
+    const contract = helper.ethNativeContract.collection(collectionAddress, 'ft', owner);
 
     await contract.methods.approve(spender, 100).send();
 
     {
       const result = await contract.methods.transferFrom(owner, receiver, 49).send({from: spender});
-      const events = normalizeEvents(result.events);
-      expect(events).to.be.deep.equal([
-        {
-          address,
-          event: 'Transfer',
-          args: {
-            from: owner,
-            to: receiver,
-            value: '49',
-          },
-        },
-        {
-          address,
-          event: 'Approval',
-          args: {
-            owner,
-            spender,
-            value: '51',
-          },
-        },
-      ]);
+      
+      let event = result.events.Transfer;
+      expect(event.address).to.be.equal(collectionAddress);
+      expect(event.returnValues.from).to.be.equal(owner);
+      expect(event.returnValues.to).to.be.equal(receiver);
+      expect(event.returnValues.value).to.be.equal('49');
+
+      event = result.events.Approval;
+      expect(event.address).to.be.equal(collectionAddress);
+      expect(event.returnValues.owner).to.be.equal(owner);
+      expect(event.returnValues.spender).to.be.equal(spender);
+      expect(event.returnValues.value).to.be.equal('51');
     }
 
     {
@@ -278,38 +187,23 @@
     }
   });
 
-  itWeb3('Can perform transfer()', async ({web3, api, privateKeyWrapper}) => {
-    const collection = await createCollectionExpectSuccess({
-      name: 'token name',
-      mode: {type: 'Fungible', decimalPoints: 0},
-    });
-    const alice = privateKeyWrapper('//Alice');
-
-    const owner = createEthAccount(web3);
-    await transferBalanceToEth(api, alice, owner);
-
-    await createFungibleItemExpectSuccess(alice, collection, {Value: 200n}, {Ethereum: owner});
-
-    const receiver = createEthAccount(web3);
-    await transferBalanceToEth(api, alice, receiver);
+  itEth('Can perform transfer()', async ({helper}) => {
+    const owner = await helper.eth.createAccountWithBalance(donor);
+    const receiver = await helper.eth.createAccountWithBalance(donor);
+    const collection = await helper.ft.mintCollection(alice);
+    await collection.mint(alice, 200n, {Ethereum: owner});
 
-    const address = collectionIdToAddress(collection);
-    const contract = new web3.eth.Contract(fungibleAbi as any, address, {from: owner, ...GAS_ARGS});
+    const collectionAddress = helper.ethAddress.fromCollectionId(collection.collectionId);
+    const contract = helper.ethNativeContract.collection(collectionAddress, 'ft', owner);
 
     {
       const result = await contract.methods.transfer(receiver, 50).send({from: owner});
-      const events = normalizeEvents(result.events);
-      expect(events).to.be.deep.equal([
-        {
-          address,
-          event: 'Transfer',
-          args: {
-            from: owner,
-            to: receiver,
-            value: '50',
-          },
-        },
-      ]);
+      
+      const event = result.events.Transfer;
+      expect(event.address).to.be.equal(collectionAddress);
+      expect(event.returnValues.from).to.be.equal(owner);
+      expect(event.returnValues.to).to.be.equal(receiver);
+      expect(event.returnValues.value).to.be.equal('50');
     }
 
     {
@@ -325,162 +219,141 @@
 });
 
 describe('Fungible: Fees', () => {
-  itWeb3('approve() call fee is less than 0.2UNQ', async ({web3, api, privateKeyWrapper}) => {
-    const collection = await createCollectionExpectSuccess({
-      mode: {type: 'Fungible', decimalPoints: 0},
+  let donor: IKeyringPair;
+  let alice: IKeyringPair;
+
+  before(async function() {
+    await usingEthPlaygrounds(async (helper, privateKey) => {
+      donor = privateKey('//Alice');
+      [alice] = await helper.arrange.createAccounts([20n], donor);
     });
-    const alice = privateKeyWrapper('//Alice');
+  });
+  
+  itEth('approve() call fee is less than 0.2UNQ', async ({helper}) => {
+    const owner = await helper.eth.createAccountWithBalance(donor);
+    const spender = helper.eth.createAccount();
+    const collection = await helper.ft.mintCollection(alice);
+    await collection.mint(alice, 200n, {Ethereum: owner});
 
-    const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
-    const spender = createEthAccount(web3);
-
-    await createFungibleItemExpectSuccess(alice, collection, {Value: 200n}, {Ethereum: owner});
+    const collectionAddress = helper.ethAddress.fromCollectionId(collection.collectionId);
+    const contract = helper.ethNativeContract.collection(collectionAddress, 'ft', owner);
 
-    const address = collectionIdToAddress(collection);
-    const contract = new web3.eth.Contract(fungibleAbi as any, address, {from: owner, ...GAS_ARGS});
-
-    const cost = await recordEthFee(api, owner, () => contract.methods.approve(spender, 100).send({from: owner}));
-    expect(cost < BigInt(0.2 * Number(UNIQUE)));
+    const cost = await helper.eth.recordCallFee(owner, () => contract.methods.approve(spender, 100).send({from: owner}));
+    expect(cost < BigInt(0.2 * Number(helper.balance.getOneTokenNominal())));
   });
 
-  itWeb3('transferFrom() call fee is less than 0.2UNQ', async ({web3, api, privateKeyWrapper}) => {
-    const collection = await createCollectionExpectSuccess({
-      mode: {type: 'Fungible', decimalPoints: 0},
-    });
-    const alice = privateKeyWrapper('//Alice');
-
-    const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
-    const spender = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
-
-    await createFungibleItemExpectSuccess(alice, collection, {Value: 200n}, {Ethereum: owner});
+  itEth('transferFrom() call fee is less than 0.2UNQ', async ({helper}) => {
+    const owner = await helper.eth.createAccountWithBalance(donor);
+    const spender = await helper.eth.createAccountWithBalance(donor);
+    const collection = await helper.ft.mintCollection(alice);
+    await collection.mint(alice, 200n, {Ethereum: owner});
 
-    const address = collectionIdToAddress(collection);
-    const contract = new web3.eth.Contract(fungibleAbi as any, address, {from: owner, ...GAS_ARGS});
+    const collectionAddress = helper.ethAddress.fromCollectionId(collection.collectionId);
+    const contract = helper.ethNativeContract.collection(collectionAddress, 'ft', owner);
 
     await contract.methods.approve(spender, 100).send({from: owner});
 
-    const cost = await recordEthFee(api, spender, () => contract.methods.transferFrom(owner, spender, 100).send({from: spender}));
-    expect(cost < BigInt(0.2 * Number(UNIQUE)));
+    const cost = await helper.eth.recordCallFee(spender, () => contract.methods.transferFrom(owner, spender, 100).send({from: spender}));
+    expect(cost < BigInt(0.2 * Number(helper.balance.getOneTokenNominal())));
   });
-
-  itWeb3('transfer() call fee is less than 0.2UNQ', async ({web3, api, privateKeyWrapper}) => {
-    const collection = await createCollectionExpectSuccess({
-      mode: {type: 'Fungible', decimalPoints: 0},
-    });
-    const alice = privateKeyWrapper('//Alice');
 
-    const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
-    const receiver = createEthAccount(web3);
-
-    await createFungibleItemExpectSuccess(alice, collection, {Value: 200n}, {Ethereum: owner});
+  itEth('transfer() call fee is less than 0.2UNQ', async ({helper}) => {
+    const owner = await helper.eth.createAccountWithBalance(donor);
+    const receiver = helper.eth.createAccount();
+    const collection = await helper.ft.mintCollection(alice);
+    await collection.mint(alice, 200n, {Ethereum: owner});
 
-    const address = collectionIdToAddress(collection);
-    const contract = new web3.eth.Contract(fungibleAbi as any, address, {from: owner, ...GAS_ARGS});
+    const collectionAddress = helper.ethAddress.fromCollectionId(collection.collectionId);
+    const contract = helper.ethNativeContract.collection(collectionAddress, 'ft', owner);
 
-    const cost = await recordEthFee(api, owner, () => contract.methods.transfer(receiver, 100).send({from: owner}));
-    expect(cost < BigInt(0.2 * Number(UNIQUE)));
+    const cost = await helper.eth.recordCallFee(owner, () => contract.methods.transfer(receiver, 100).send({from: owner}));
+    expect(cost < BigInt(0.2 * Number(helper.balance.getOneTokenNominal())));
   });
 });
 
 describe('Fungible: Substrate calls', () => {
-  itWeb3('Events emitted for approve()', async ({web3, privateKeyWrapper}) => {
-    const collection = await createCollectionExpectSuccess({
-      mode: {type: 'Fungible', decimalPoints: 0},
+  let donor: IKeyringPair;
+  let alice: IKeyringPair;
+
+  before(async function() {
+    await usingEthPlaygrounds(async (helper, privateKey) => {
+      donor = privateKey('//Alice');
+      [alice] = await helper.arrange.createAccounts([20n], donor);
     });
-    const alice = privateKeyWrapper('//Alice');
+  });
 
-    const receiver = createEthAccount(web3);
+  itEth('Events emitted for approve()', async ({helper}) => {
+    const receiver = helper.eth.createAccount();
+    const collection = await helper.ft.mintCollection(alice);
+    await collection.mint(alice, 200n);
 
-    await createFungibleItemExpectSuccess(alice, collection, {Value: 200n});
+    const collectionAddress = helper.ethAddress.fromCollectionId(collection.collectionId);
+    const contract = helper.ethNativeContract.collection(collectionAddress, 'ft');
 
-    const address = collectionIdToAddress(collection);
-    const contract = new web3.eth.Contract(fungibleAbi as any, address);
-
-    const events = await recordEvents(contract, async () => {
-      await approveExpectSuccess(collection, 0, alice, {Ethereum: receiver}, 100);
+    const events: any = [];
+    contract.events.allEvents((_: any, event: any) => {
+      events.push(event);
     });
+    await collection.approveTokens(alice, {Ethereum: receiver}, 100n);
 
-    expect(events).to.be.deep.equal([
-      {
-        address,
-        event: 'Approval',
-        args: {
-          owner: subToEth(alice.address),
-          spender: receiver,
-          value: '100',
-        },
-      },
-    ]);
+    const event = events[0];
+    expect(event.event).to.be.equal('Approval');
+    expect(event.address).to.be.equal(collectionAddress);
+    expect(event.returnValues.owner).to.be.equal(helper.address.substrateToEth(alice.address));
+    expect(event.returnValues.spender).to.be.equal(receiver);
+    expect(event.returnValues.value).to.be.equal('100');
   });
 
-  itWeb3('Events emitted for transferFrom()', async ({web3, privateKeyWrapper}) => {
-    const collection = await createCollectionExpectSuccess({
-      mode: {type: 'Fungible', decimalPoints: 0},
-    });
-    const alice = privateKeyWrapper('//Alice');
-    const bob = privateKeyWrapper('//Bob');
+  itEth('Events emitted for transferFrom()', async ({helper}) => {
+    const [bob] = await helper.arrange.createAccounts([10n], donor);
+    const receiver = helper.eth.createAccount();
+    const collection = await helper.ft.mintCollection(alice);
+    await collection.mint(alice, 200n);
+    await collection.approveTokens(alice, {Substrate: bob.address}, 100n);
 
-    const receiver = createEthAccount(web3);
+    const collectionAddress = helper.ethAddress.fromCollectionId(collection.collectionId);
+    const contract = helper.ethNativeContract.collection(collectionAddress, 'ft');
 
-    await createFungibleItemExpectSuccess(alice, collection, {Value: 200n});
-    await approveExpectSuccess(collection, 0, alice, bob.address, 100);
+    const events: any = [];
+    contract.events.allEvents((_: any, event: any) => {
+      events.push(event);
+    });
+    await collection.transferFrom(bob, {Substrate: alice.address}, {Ethereum: receiver}, 51n);
 
-    const address = collectionIdToAddress(collection);
-    const contract = new web3.eth.Contract(fungibleAbi as any, address);
+    let event = events[0];
+    expect(event.event).to.be.equal('Transfer');
+    expect(event.address).to.be.equal(collectionAddress);
+    expect(event.returnValues.from).to.be.equal(helper.address.substrateToEth(alice.address));
+    expect(event.returnValues.to).to.be.equal(receiver);
+    expect(event.returnValues.value).to.be.equal('51');
 
-    const events = await recordEvents(contract, async () => {
-      await transferFromExpectSuccess(collection, 0, bob, alice, {Ethereum: receiver}, 51, 'Fungible');
-    });
-
-    expect(events).to.be.deep.equal([
-      {
-        address,
-        event: 'Transfer',
-        args: {
-          from: subToEth(alice.address),
-          to: receiver,
-          value: '51',
-        },
-      },
-      {
-        address,
-        event: 'Approval',
-        args: {
-          owner: subToEth(alice.address),
-          spender: subToEth(bob.address),
-          value: '49',
-        },
-      },
-    ]);
+    event = events[1];
+    expect(event.event).to.be.equal('Approval');
+    expect(event.address).to.be.equal(collectionAddress);
+    expect(event.returnValues.owner).to.be.equal(helper.address.substrateToEth(alice.address));
+    expect(event.returnValues.spender).to.be.equal(helper.address.substrateToEth(bob.address));
+    expect(event.returnValues.value).to.be.equal('49');
   });
 
-  itWeb3('Events emitted for transfer()', async ({web3, privateKeyWrapper}) => {
-    const collection = await createCollectionExpectSuccess({
-      mode: {type: 'Fungible', decimalPoints: 0},
-    });
-    const alice = privateKeyWrapper('//Alice');
+  itEth('Events emitted for transfer()', async ({helper}) => {
+    const receiver = helper.eth.createAccount();
+    const collection = await helper.ft.mintCollection(alice);
+    await collection.mint(alice, 200n);
 
-    const receiver = createEthAccount(web3);
+    const collectionAddress = helper.ethAddress.fromCollectionId(collection.collectionId);
+    const contract = helper.ethNativeContract.collection(collectionAddress, 'ft');
 
-    await createFungibleItemExpectSuccess(alice, collection, {Value: 200n});
-
-    const address = collectionIdToAddress(collection);
-    const contract = new web3.eth.Contract(fungibleAbi as any, address);
-
-    const events = await recordEvents(contract, async () => {
-      await transferExpectSuccess(collection, 0, alice, {Ethereum:receiver}, 51, 'Fungible');
+    const events: any = [];
+    contract.events.allEvents((_: any, event: any) => {
+      events.push(event);
     });
+    await collection.transfer(alice, {Ethereum:receiver}, 51n);
 
-    expect(events).to.be.deep.equal([
-      {
-        address,
-        event: 'Transfer',
-        args: {
-          from: subToEth(alice.address),
-          to: receiver,
-          value: '51',
-        },
-      },
-    ]);
+    const event = events[0];
+    expect(event.event).to.be.equal('Transfer');
+    expect(event.address).to.be.equal(collectionAddress);
+    expect(event.returnValues.from).to.be.equal(helper.address.substrateToEth(alice.address));
+    expect(event.returnValues.to).to.be.equal(receiver);
+    expect(event.returnValues.value).to.be.equal('51');
   });
 });
modifiedtests/src/eth/fungibleAbi.jsondiffbeforeafterboth
--- a/tests/src/eth/fungibleAbi.json
+++ b/tests/src/eth/fungibleAbi.json
@@ -60,27 +60,9 @@
   },
   {
     "inputs": [
-      { "internalType": "uint256", "name": "newAdmin", "type": "uint256" }
-    ],
-    "name": "addCollectionAdminSubstrate",
-    "outputs": [],
-    "stateMutability": "nonpayable",
-    "type": "function"
-  },
-  {
-    "inputs": [
       { "internalType": "address", "name": "user", "type": "address" }
     ],
     "name": "addToCollectionAllowList",
-    "outputs": [],
-    "stateMutability": "nonpayable",
-    "type": "function"
-  },
-  {
-    "inputs": [
-      { "internalType": "uint256", "name": "user", "type": "uint256" }
-    ],
-    "name": "addToCollectionAllowListSubstrate",
     "outputs": [],
     "stateMutability": "nonpayable",
     "type": "function"
@@ -214,15 +196,6 @@
       { "internalType": "address", "name": "user", "type": "address" }
     ],
     "name": "isOwnerOrAdmin",
-    "outputs": [{ "internalType": "bool", "name": "", "type": "bool" }],
-    "stateMutability": "view",
-    "type": "function"
-  },
-  {
-    "inputs": [
-      { "internalType": "uint256", "name": "user", "type": "uint256" }
-    ],
-    "name": "isOwnerOrAdminSubstrate",
     "outputs": [{ "internalType": "bool", "name": "", "type": "bool" }],
     "stateMutability": "view",
     "type": "function"
@@ -271,15 +244,6 @@
     "type": "function"
   },
   {
-    "inputs": [
-      { "internalType": "uint256", "name": "admin", "type": "uint256" }
-    ],
-    "name": "removeCollectionAdminSubstrate",
-    "outputs": [],
-    "stateMutability": "nonpayable",
-    "type": "function"
-  },
-  {
     "inputs": [],
     "name": "removeCollectionSponsor",
     "outputs": [],
@@ -291,15 +255,6 @@
       { "internalType": "address", "name": "user", "type": "address" }
     ],
     "name": "removeFromCollectionAllowList",
-    "outputs": [],
-    "stateMutability": "nonpayable",
-    "type": "function"
-  },
-  {
-    "inputs": [
-      { "internalType": "uint256", "name": "user", "type": "uint256" }
-    ],
-    "name": "removeFromCollectionAllowListSubstrate",
     "outputs": [],
     "stateMutability": "nonpayable",
     "type": "function"
@@ -380,27 +335,9 @@
   },
   {
     "inputs": [
-      { "internalType": "uint256", "name": "sponsor", "type": "uint256" }
-    ],
-    "name": "setCollectionSponsorSubstrate",
-    "outputs": [],
-    "stateMutability": "nonpayable",
-    "type": "function"
-  },
-  {
-    "inputs": [
       { "internalType": "address", "name": "newOwner", "type": "address" }
     ],
     "name": "setOwner",
-    "outputs": [],
-    "stateMutability": "nonpayable",
-    "type": "function"
-  },
-  {
-    "inputs": [
-      { "internalType": "uint256", "name": "newOwner", "type": "uint256" }
-    ],
-    "name": "setOwnerSubstrate",
     "outputs": [],
     "stateMutability": "nonpayable",
     "type": "function"
modifiedtests/src/eth/nonFungible.test.tsdiffbeforeafterboth
--- a/tests/src/eth/nonFungible.test.ts
+++ b/tests/src/eth/nonFungible.test.ts
@@ -14,72 +14,78 @@
 // You should have received a copy of the GNU General Public License
 // along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
 
-import {approveExpectSuccess, burnItemExpectSuccess, createCollectionExpectSuccess, createItemExpectSuccess, transferExpectSuccess, transferFromExpectSuccess, UNIQUE} from '../util/helpers';
-import {collectionIdToAddress, createEthAccount, createEthAccountWithBalance, evmCollection, evmCollectionHelpers, GAS_ARGS, getCollectionAddressFromResult, itWeb3, normalizeEvents, recordEthFee, recordEvents, subToEth, transferBalanceToEth} from './util/helpers';
-import nonFungibleAbi from './nonFungibleAbi.json';
-import {expect} from 'chai';
-import {submitTransactionAsync} from '../substrate/substrate-api';
+import {itEth, usingEthPlaygrounds, expect, EthUniqueHelper} from './util/playgrounds';
+import {IKeyringPair} from '@polkadot/types/types';
+import {Contract} from 'web3-eth-contract';
 
 describe('NFT: Information getting', () => {
-  itWeb3('totalSupply', async ({api, web3, privateKeyWrapper}) => {
-    const collection = await createCollectionExpectSuccess({
-      mode: {type: 'NFT'},
+  let donor: IKeyringPair;
+  let alice: IKeyringPair;
+
+  before(async function() {
+    await usingEthPlaygrounds(async (helper, privateKey) => {
+      donor = privateKey('//Alice');
+      [alice] = await helper.arrange.createAccounts([10n], donor);
     });
-    const alice = privateKeyWrapper('//Alice');
-    const caller = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
+  });
+  
+  itEth('totalSupply', async ({helper}) => {
+    const collection = await helper.nft.mintCollection(alice, {});
+    await collection.mintToken(alice);
 
-    await createItemExpectSuccess(alice, collection, 'NFT', {Substrate: alice.address});
+    const caller = await helper.eth.createAccountWithBalance(donor);
 
-    const address = collectionIdToAddress(collection);
-    const contract = new web3.eth.Contract(nonFungibleAbi as any, address, {from: caller, ...GAS_ARGS});
+    const contract = helper.ethNativeContract.collectionById(collection.collectionId, 'nft', caller);
     const totalSupply = await contract.methods.totalSupply().call();
 
     expect(totalSupply).to.equal('1');
   });
 
-  itWeb3('balanceOf', async ({api, web3, privateKeyWrapper}) => {
-    const collection = await createCollectionExpectSuccess({
-      mode: {type: 'NFT'},
-    });
-    const alice = privateKeyWrapper('//Alice');
+  itEth('balanceOf', async ({helper}) => {
+    const collection = await helper.nft.mintCollection(alice, {});
+    const caller = await helper.eth.createAccountWithBalance(donor);
 
-    const caller = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
-    await createItemExpectSuccess(alice, collection, 'NFT', {Ethereum:caller});
-    await createItemExpectSuccess(alice, collection, 'NFT', {Ethereum: caller});
-    await createItemExpectSuccess(alice, collection, 'NFT', {Ethereum: caller});
+    await collection.mintToken(alice, {Ethereum: caller});
+    await collection.mintToken(alice, {Ethereum: caller});
+    await collection.mintToken(alice, {Ethereum: caller});
 
-    const address = collectionIdToAddress(collection);
-    const contract = new web3.eth.Contract(nonFungibleAbi as any, address, {from: caller, ...GAS_ARGS});
+    const contract = helper.ethNativeContract.collectionById(collection.collectionId, 'nft', caller);
     const balance = await contract.methods.balanceOf(caller).call();
 
     expect(balance).to.equal('3');
   });
 
-  itWeb3('ownerOf', async ({api, web3, privateKeyWrapper}) => {
-    const collection = await createCollectionExpectSuccess({
-      mode: {type: 'NFT'},
-    });
-    const alice = privateKeyWrapper('//Alice');
+  itEth('ownerOf', async ({helper}) => {
+    const collection = await helper.nft.mintCollection(alice, {});
+    const caller = await helper.eth.createAccountWithBalance(donor);
 
-    const caller = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
-    const tokenId = await createItemExpectSuccess(alice, collection, 'NFT', {Ethereum: caller});
+    const token = await collection.mintToken(alice, {Ethereum: caller});
 
-    const address = collectionIdToAddress(collection);
-    const contract = new web3.eth.Contract(nonFungibleAbi as any, address, {from: caller, ...GAS_ARGS});
-    const owner = await contract.methods.ownerOf(tokenId).call();
+    const contract = helper.ethNativeContract.collectionById(collection.collectionId, 'nft', caller);
+
+    const owner = await contract.methods.ownerOf(token.tokenId).call();
 
     expect(owner).to.equal(caller);
   });
 });
 
 describe('Check ERC721 token URI for NFT', () => {
-  itWeb3('Empty tokenURI', async ({web3, api, privateKeyWrapper}) => {
-    const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
-    const helper = evmCollectionHelpers(web3, owner);
-    let result = await helper.methods.createERC721MetadataCompatibleCollection('Mint collection', '1', '1', '').send();
-    const {collectionIdAddress, collectionId} = await getCollectionAddressFromResult(api, result);
-    const receiver = createEthAccount(web3);
-    const contract = evmCollection(web3, owner, collectionIdAddress);
+  let donor: IKeyringPair;
+
+  before(async function() {
+    await usingEthPlaygrounds(async (_helper, privateKey) => {
+      donor = privateKey('//Alice');
+    });
+  });
+
+  async function setup(helper: EthUniqueHelper, tokenPrefix: string, propertyKey?: string, propertyValue?: string): Promise<{contract: Contract, nextTokenId: string}> {
+    const owner = await helper.eth.createAccountWithBalance(donor);
+    const receiver = helper.eth.createAccount();
+
+    const collectionHelper = helper.ethNativeContract.collectionHelpers(owner);
+    let result = await collectionHelper.methods.createERC721MetadataCompatibleCollection('Mint collection', 'a', 'b', tokenPrefix).send();
+    const collectionAddress = helper.ethAddress.normalizeAddress(result.events.CollectionCreated.returnValues.collectionId);
+    const contract = helper.ethNativeContract.collection(collectionAddress, 'nft', owner);
     
     const nextTokenId = await contract.methods.nextTokenId().call();
     expect(nextTokenId).to.be.equal('1');
@@ -88,162 +94,73 @@
       nextTokenId,
     ).send();
 
-    const events = normalizeEvents(result.events);
-    const address = collectionIdToAddress(collectionId);
+    if (propertyKey && propertyValue) {
+      // Set URL or suffix
+      await contract.methods.setProperty(nextTokenId, propertyKey, Buffer.from(propertyValue)).send();
+    }
 
-    expect(events).to.be.deep.equal([
-      {
-        address,
-        event: 'Transfer',
-        args: {
-          from: '0x0000000000000000000000000000000000000000',
-          to: receiver,
-          tokenId: nextTokenId,
-        },
-      },
-    ]);
+    const event = result.events.Transfer;
+    expect(event.address).to.be.equal(collectionAddress);
+    expect(event.returnValues.from).to.be.equal('0x0000000000000000000000000000000000000000');
+    expect(event.returnValues.to).to.be.equal(receiver);
+    expect(event.returnValues.tokenId).to.be.equal(nextTokenId);
 
+    return {contract, nextTokenId};
+  }
+
+  itEth('Empty tokenURI', async ({helper}) => {
+    const {contract, nextTokenId} = await setup(helper, '');
     expect(await contract.methods.tokenURI(nextTokenId).call()).to.be.equal('');
   });
 
-  itWeb3('TokenURI from url', async ({web3, api, privateKeyWrapper}) => {
-    const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
-    const helper = evmCollectionHelpers(web3, owner);
-    let result = await helper.methods.createERC721MetadataCompatibleCollection('Mint collection', '1', '1', 'BaseURI_').send();
-    const {collectionIdAddress, collectionId} = await getCollectionAddressFromResult(api, result);
-    const receiver = createEthAccount(web3);
-    const contract = evmCollection(web3, owner, collectionIdAddress);
-    
-    const nextTokenId = await contract.methods.nextTokenId().call();
-    expect(nextTokenId).to.be.equal('1');
-    result = await contract.methods.mint(
-      receiver,
-      nextTokenId,
-    ).send();
-    
-    // Set URL
-    await contract.methods.setProperty(nextTokenId, 'url', Buffer.from('Token URI')).send();
-      
-    const events = normalizeEvents(result.events);
-    const address = collectionIdToAddress(collectionId);
-
-    expect(events).to.be.deep.equal([
-      {
-        address,
-        event: 'Transfer',
-        args: {
-          from: '0x0000000000000000000000000000000000000000',
-          to: receiver,
-          tokenId: nextTokenId,
-        },
-      },
-    ]);
-
+  itEth('TokenURI from url', async ({helper}) => {
+    const {contract, nextTokenId} = await setup(helper, 'BaseURI_', 'url', 'Token URI');
     expect(await contract.methods.tokenURI(nextTokenId).call()).to.be.equal('Token URI');
   });
 
-  itWeb3('TokenURI from baseURI + tokenId', async ({web3, api, privateKeyWrapper}) => {
-    const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
-    const helper = evmCollectionHelpers(web3, owner);
-    let result = await helper.methods.createERC721MetadataCompatibleCollection('Mint collection', '1', '1', 'BaseURI_').send();
-    const {collectionIdAddress, collectionId} = await getCollectionAddressFromResult(api, result);
-    const receiver = createEthAccount(web3);
-    const contract = evmCollection(web3, owner, collectionIdAddress);
-    
-    const nextTokenId = await contract.methods.nextTokenId().call();
-    expect(nextTokenId).to.be.equal('1');
-    result = await contract.methods.mint(
-      receiver,
-      nextTokenId,
-    ).send();
-          
-    const events = normalizeEvents(result.events);
-    const address = collectionIdToAddress(collectionId);
-
-    expect(events).to.be.deep.equal([
-      {
-        address,
-        event: 'Transfer',
-        args: {
-          from: '0x0000000000000000000000000000000000000000',
-          to: receiver,
-          tokenId: nextTokenId,
-        },
-      },
-    ]);
-
+  itEth('TokenURI from baseURI + tokenId', async ({helper}) => {
+    const {contract, nextTokenId} = await setup(helper, 'BaseURI_');
     expect(await contract.methods.tokenURI(nextTokenId).call()).to.be.equal('BaseURI_' + nextTokenId);
   });
 
-  itWeb3('TokenURI from baseURI + suffix', async ({web3, api, privateKeyWrapper}) => {
-    const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
-    const helper = evmCollectionHelpers(web3, owner);
-    let result = await helper.methods.createERC721MetadataCompatibleCollection('Mint collection', '1', '1', 'BaseURI_').send();
-    const {collectionIdAddress, collectionId} = await getCollectionAddressFromResult(api, result);
-    const receiver = createEthAccount(web3);
-    const contract = evmCollection(web3, owner, collectionIdAddress);
-    
-    const nextTokenId = await contract.methods.nextTokenId().call();
-    expect(nextTokenId).to.be.equal('1');
-    result = await contract.methods.mint(
-      receiver,
-      nextTokenId,
-    ).send();
-          
-    // Set suffix
+  itEth('TokenURI from baseURI + suffix', async ({helper}) => {
     const suffix = '/some/suffix';
-    await contract.methods.setProperty(nextTokenId, 'suffix', Buffer.from(suffix)).send();
-
-    const events = normalizeEvents(result.events);
-    const address = collectionIdToAddress(collectionId);
-
-    expect(events).to.be.deep.equal([
-      {
-        address,
-        event: 'Transfer',
-        args: {
-          from: '0x0000000000000000000000000000000000000000',
-          to: receiver,
-          tokenId: nextTokenId,
-        },
-      },
-    ]);
-
+    const {contract, nextTokenId} = await setup(helper, 'BaseURI_', 'suffix', suffix);
     expect(await contract.methods.tokenURI(nextTokenId).call()).to.be.equal('BaseURI_' + suffix);
   });
 });
 
 describe('NFT: Plain calls', () => {
-  itWeb3('Can perform mint()', async ({web3, api, privateKeyWrapper}) => {
-    const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
-    const helper = evmCollectionHelpers(web3, owner);
-    let result = await helper.methods.createNonfungibleCollection('Mint collection', '6', '6').send();
-    const {collectionIdAddress, collectionId} = await getCollectionAddressFromResult(api, result);
-    const receiver = createEthAccount(web3);
-    const contract = evmCollection(web3, owner, collectionIdAddress);
+  let donor: IKeyringPair;
+  let alice: IKeyringPair;
+
+  before(async function() {
+    await usingEthPlaygrounds(async (helper, privateKey) => {
+      donor = privateKey('//Alice');
+      [alice] = await helper.arrange.createAccounts([10n], donor);
+    });
+  });
+
+  itEth('Can perform mint()', async ({helper}) => {
+    const owner = await helper.eth.createAccountWithBalance(donor);
+    const receiver = helper.eth.createAccount();
+
+    const {collectionAddress} = await helper.eth.createNonfungibleCollection(owner, 'Minty', '6', '6');
+    const contract = helper.ethNativeContract.collection(collectionAddress, 'nft', owner);
     const nextTokenId = await contract.methods.nextTokenId().call();
 
     expect(nextTokenId).to.be.equal('1');
-    result = await contract.methods.mintWithTokenURI(
+    const result = await contract.methods.mintWithTokenURI(
       receiver,
       nextTokenId,
       'Test URI',
     ).send();
 
-    const events = normalizeEvents(result.events);
-    const address = collectionIdToAddress(collectionId);
-
-    expect(events).to.be.deep.equal([
-      {
-        address,
-        event: 'Transfer',
-        args: {
-          from: '0x0000000000000000000000000000000000000000',
-          to: receiver,
-          tokenId: nextTokenId,
-        },
-      },
-    ]);
+    const event = result.events.Transfer;
+    expect(event.address).to.be.equal(collectionAddress);
+    expect(event.returnValues.from).to.be.equal('0x0000000000000000000000000000000000000000');
+    expect(event.returnValues.to).to.be.equal(receiver);
+    expect(event.returnValues.tokenId).to.be.equal(nextTokenId);
 
     expect(await contract.methods.tokenURI(nextTokenId).call()).to.be.equal('Test URI');
 
@@ -254,7 +171,8 @@
   });
 
   //TODO: CORE-302 add eth methods
-  itWeb3.skip('Can perform mintBulk()', async ({web3, api, privateKeyWrapper}) => {
+  /* todo:playgrounds skipped test!
+  itWeb3.skip('Can perform mintBulk()', async ({helper}) => {
     const collection = await createCollectionExpectSuccess({
       mode: {type: 'NFT'},
     });
@@ -316,107 +234,70 @@
       expect(await contract.methods.tokenURI(+nextTokenId + 2).call()).to.be.equal('Test URI 2');
     }
   });
-
-  itWeb3('Can perform burn()', async ({web3, api, privateKeyWrapper}) => {
-    const collection = await createCollectionExpectSuccess({
-      mode: {type: 'NFT'},
-    });
-    const alice = privateKeyWrapper('//Alice');
+  */
 
-    const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
+  itEth('Can perform burn()', async ({helper}) => {
+    const caller = await helper.eth.createAccountWithBalance(donor);
 
-    const tokenId = await createItemExpectSuccess(alice, collection, 'NFT', {Ethereum: owner});
+    const collection = await helper.nft.mintCollection(alice, {});
+    const {tokenId} = await collection.mintToken(alice, {Ethereum: caller});
 
-    const address = collectionIdToAddress(collection);
-    const contract = new web3.eth.Contract(nonFungibleAbi as any, address, {from: owner, ...GAS_ARGS});
+    const collectionAddress = helper.ethAddress.fromCollectionId(collection.collectionId);
+    const contract = helper.ethNativeContract.collection(collectionAddress, 'nft', caller);
 
     {
-      const result = await contract.methods.burn(tokenId).send({from: owner});
-      const events = normalizeEvents(result.events);
-
-      expect(events).to.be.deep.equal([
-        {
-          address,
-          event: 'Transfer',
-          args: {
-            from: owner,
-            to: '0x0000000000000000000000000000000000000000',
-            tokenId: tokenId.toString(),
-          },
-        },
-      ]);
+      const result = await contract.methods.burn(tokenId).send({from: caller});
+      
+      const event = result.events.Transfer;
+      expect(event.address).to.be.equal(collectionAddress);
+      expect(event.returnValues.from).to.be.equal(caller);
+      expect(event.returnValues.to).to.be.equal('0x0000000000000000000000000000000000000000');
+      expect(event.returnValues.tokenId).to.be.equal(`${tokenId}`);
     }
   });
 
-  itWeb3('Can perform approve()', async ({web3, api, privateKeyWrapper}) => {
-    const collection = await createCollectionExpectSuccess({
-      mode: {type: 'NFT'},
-    });
-    const alice = privateKeyWrapper('//Alice');
-
-    const owner = createEthAccount(web3);
-    await transferBalanceToEth(api, alice, owner);
-
-    const tokenId = await createItemExpectSuccess(alice, collection, 'NFT', {Ethereum: owner});
+  itEth('Can perform approve()', async ({helper}) => {
+    const owner = await helper.eth.createAccountWithBalance(donor);
+    const spender = helper.eth.createAccount();
 
-    const spender = createEthAccount(web3);
+    const collection = await helper.nft.mintCollection(alice, {});
+    const {tokenId} = await collection.mintToken(alice, {Ethereum: owner});
 
-    const address = collectionIdToAddress(collection);
-    const contract = new web3.eth.Contract(nonFungibleAbi as any, address);
+    const collectionAddress = helper.ethAddress.fromCollectionId(collection.collectionId);
+    const contract = helper.ethNativeContract.collection(collectionAddress, 'nft', owner);
 
     {
-      const result = await contract.methods.approve(spender, tokenId).send({from: owner, ...GAS_ARGS});
-      const events = normalizeEvents(result.events);
+      const result = await contract.methods.approve(spender, tokenId).send({from: owner});
 
-      expect(events).to.be.deep.equal([
-        {
-          address,
-          event: 'Approval',
-          args: {
-            owner,
-            approved: spender,
-            tokenId: tokenId.toString(),
-          },
-        },
-      ]);
+      const event = result.events.Approval;
+      expect(event.address).to.be.equal(collectionAddress);
+      expect(event.returnValues.owner).to.be.equal(owner);
+      expect(event.returnValues.approved).to.be.equal(spender);
+      expect(event.returnValues.tokenId).to.be.equal(`${tokenId}`);
     }
   });
 
-  itWeb3('Can perform transferFrom()', async ({web3, api, privateKeyWrapper}) => {
-    const collection = await createCollectionExpectSuccess({
-      mode: {type: 'NFT'},
-    });
-    const alice = privateKeyWrapper('//Alice');
-
-    const owner = createEthAccount(web3);
-    await transferBalanceToEth(api, alice, owner);
+  itEth('Can perform transferFrom()', async ({helper}) => {
+    const owner = await helper.eth.createAccountWithBalance(donor);
+    const spender = await helper.eth.createAccountWithBalance(donor);
+    const receiver = helper.eth.createAccount();
 
-    const tokenId = await createItemExpectSuccess(alice, collection, 'NFT', {Ethereum: owner});
-
-    const spender = createEthAccount(web3);
-    await transferBalanceToEth(api, alice, spender);
-
-    const receiver = createEthAccount(web3);
+    const collection = await helper.nft.mintCollection(alice, {});
+    const {tokenId} = await collection.mintToken(alice, {Ethereum: owner});
 
-    const address = collectionIdToAddress(collection);
-    const contract = new web3.eth.Contract(nonFungibleAbi as any, address, {from: owner, ...GAS_ARGS});
+    const collectionAddress = helper.ethAddress.fromCollectionId(collection.collectionId);
+    const contract = helper.ethNativeContract.collection(collectionAddress, 'nft', owner);
 
     await contract.methods.approve(spender, tokenId).send({from: owner});
 
     {
       const result = await contract.methods.transferFrom(owner, receiver, tokenId).send({from: spender});
-      const events = normalizeEvents(result.events);
-      expect(events).to.be.deep.equal([
-        {
-          address,
-          event: 'Transfer',
-          args: {
-            from: owner,
-            to: receiver,
-            tokenId: tokenId.toString(),
-          },
-        },
-      ]);
+
+      const event = result.events.Transfer;
+      expect(event.address).to.be.equal(collectionAddress);
+      expect(event.returnValues.from).to.be.equal(owner);
+      expect(event.returnValues.to).to.be.equal(receiver);
+      expect(event.returnValues.tokenId).to.be.equal(`${tokenId}`);
     }
 
     {
@@ -430,37 +311,24 @@
     }
   });
 
-  itWeb3('Can perform transfer()', async ({web3, api, privateKeyWrapper}) => {
-    const collection = await createCollectionExpectSuccess({
-      mode: {type: 'NFT'},
-    });
-    const alice = privateKeyWrapper('//Alice');
-
-    const owner = createEthAccount(web3);
-    await transferBalanceToEth(api, alice, owner);
-
-    const tokenId = await createItemExpectSuccess(alice, collection, 'NFT', {Ethereum: owner});
+  itEth('Can perform transfer()', async ({helper}) => {
+    const collection = await helper.nft.mintCollection(alice, {});
+    const owner = await helper.eth.createAccountWithBalance(donor);
+    const receiver = helper.eth.createAccount();
 
-    const receiver = createEthAccount(web3);
-    await transferBalanceToEth(api, alice, receiver);
+    const {tokenId} = await collection.mintToken(alice, {Ethereum: owner});
 
-    const address = collectionIdToAddress(collection);
-    const contract = new web3.eth.Contract(nonFungibleAbi as any, address, {from: owner, ...GAS_ARGS});
+    const collectionAddress = helper.ethAddress.fromCollectionId(collection.collectionId);
+    const contract = helper.ethNativeContract.collection(collectionAddress, 'nft', owner);
 
     {
       const result = await contract.methods.transfer(receiver, tokenId).send({from: owner});
-      const events = normalizeEvents(result.events);
-      expect(events).to.be.deep.equal([
-        {
-          address,
-          event: 'Transfer',
-          args: {
-            from: owner,
-            to: receiver,
-            tokenId: tokenId.toString(),
-          },
-        },
-      ]);
+
+      const event = result.events.Transfer;
+      expect(event.address).to.be.equal(collectionAddress);
+      expect(event.returnValues.from).to.be.equal(owner);
+      expect(event.returnValues.to).to.be.equal(receiver);
+      expect(event.returnValues.tokenId).to.be.equal(`${tokenId}`);
     }
 
     {
@@ -476,237 +344,209 @@
 });
 
 describe('NFT: Fees', () => {
-  itWeb3('approve() call fee is less than 0.2UNQ', async ({web3, api, privateKeyWrapper}) => {
-    const collection = await createCollectionExpectSuccess({
-      mode: {type: 'NFT'},
+  let donor: IKeyringPair;
+  let alice: IKeyringPair;
+
+  before(async function() {
+    await usingEthPlaygrounds(async (helper, privateKey) => {
+      donor = privateKey('//Alice');
+      [alice] = await helper.arrange.createAccounts([10n], donor);
     });
-    const alice = privateKeyWrapper('//Alice');
+  });
+  
+  itEth('approve() call fee is less than 0.2UNQ', async ({helper}) => {
+    const owner = await helper.eth.createAccountWithBalance(donor);
+    const spender = helper.eth.createAccount();
 
-    const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
-    const spender = createEthAccount(web3);
+    const collection = await helper.nft.mintCollection(alice, {});
+    const {tokenId} = await collection.mintToken(alice, {Ethereum: owner});
 
-    const tokenId = await createItemExpectSuccess(alice, collection, 'NFT', {Ethereum: owner});
+    const contract = helper.ethNativeContract.collectionById(collection.collectionId, 'nft', owner);
 
-    const address = collectionIdToAddress(collection);
-    const contract = new web3.eth.Contract(nonFungibleAbi as any, address, {from: owner, ...GAS_ARGS});
-
-    const cost = await recordEthFee(api, owner, () => contract.methods.approve(spender, tokenId).send({from: owner}));
-    expect(cost < BigInt(0.2 * Number(UNIQUE)));
+    const cost = await helper.eth.recordCallFee(owner, () => contract.methods.approve(spender, tokenId).send({from: owner}));
+    expect(cost < BigInt(0.2 * Number(helper.balance.getOneTokenNominal())));
   });
 
-  itWeb3('transferFrom() call fee is less than 0.2UNQ', async ({web3, api, privateKeyWrapper}) => {
-    const collection = await createCollectionExpectSuccess({
-      mode: {type: 'NFT'},
-    });
-    const alice = privateKeyWrapper('//Alice');
-
-    const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
-    const spender = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
+  itEth('transferFrom() call fee is less than 0.2UNQ', async ({helper}) => {
+    const owner = await helper.eth.createAccountWithBalance(donor);
+    const spender = await helper.eth.createAccountWithBalance(donor);
 
-    const tokenId = await createItemExpectSuccess(alice, collection, 'NFT', {Ethereum: owner});
+    const collection = await helper.nft.mintCollection(alice, {});
+    const {tokenId} = await collection.mintToken(alice, {Ethereum: owner});
 
-    const address = collectionIdToAddress(collection);
-    const contract = new web3.eth.Contract(nonFungibleAbi as any, address, {from: owner, ...GAS_ARGS});
+    const contract = helper.ethNativeContract.collectionById(collection.collectionId, 'nft', owner);
 
     await contract.methods.approve(spender, tokenId).send({from: owner});
 
-    const cost = await recordEthFee(api, spender, () => contract.methods.transferFrom(owner, spender, tokenId).send({from: spender}));
-    expect(cost < BigInt(0.2 * Number(UNIQUE)));
+    const cost = await helper.eth.recordCallFee(spender, () => contract.methods.transferFrom(owner, spender, tokenId).send({from: spender}));
+    expect(cost < BigInt(0.2 * Number(helper.balance.getOneTokenNominal())));
   });
 
-  itWeb3('transfer() call fee is less than 0.2UNQ', async ({web3, api, privateKeyWrapper}) => {
-    const collection = await createCollectionExpectSuccess({
-      mode: {type: 'NFT'},
-    });
-    const alice = privateKeyWrapper('//Alice');
+  itEth('transfer() call fee is less than 0.2UNQ', async ({helper}) => {
+    const owner = await helper.eth.createAccountWithBalance(donor);
+    const receiver = helper.eth.createAccount();
 
-    const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
-    const receiver = createEthAccount(web3);
+    const collection = await helper.nft.mintCollection(alice, {});
+    const {tokenId} = await collection.mintToken(alice, {Ethereum: owner});
 
-    const tokenId = await createItemExpectSuccess(alice, collection, 'NFT', {Ethereum: owner});
+    const contract = helper.ethNativeContract.collectionById(collection.collectionId, 'nft', owner);
 
-    const address = collectionIdToAddress(collection);
-    const contract = new web3.eth.Contract(nonFungibleAbi as any, address, {from: owner, ...GAS_ARGS});
-
-    const cost = await recordEthFee(api, owner, () => contract.methods.transfer(receiver, tokenId).send({from: owner}));
-    expect(cost < BigInt(0.2 * Number(UNIQUE)));
+    const cost = await helper.eth.recordCallFee(owner, () => contract.methods.transfer(receiver, tokenId).send({from: owner}));
+    expect(cost < BigInt(0.2 * Number(helper.balance.getOneTokenNominal())));
   });
 });
 
 describe('NFT: Substrate calls', () => {
-  itWeb3('Events emitted for mint()', async ({web3, privateKeyWrapper}) => {
-    const collection = await createCollectionExpectSuccess({
-      mode: {type: 'NFT'},
+  let donor: IKeyringPair;
+  let alice: IKeyringPair;
+
+  before(async function() {
+    await usingEthPlaygrounds(async (helper, privateKey) => {
+      donor = privateKey('//Alice');
+      [alice] = await helper.arrange.createAccounts([20n], donor);
     });
-    const alice = privateKeyWrapper('//Alice');
+  });
 
-    const address = collectionIdToAddress(collection);
-    const contract = new web3.eth.Contract(nonFungibleAbi as any, address);
+  itEth('Events emitted for mint()', async ({helper}) => {
+    const collection = await helper.nft.mintCollection(alice, {});
+    const collectionAddress = helper.ethAddress.fromCollectionId(collection.collectionId);
+    const contract = helper.ethNativeContract.collection(collectionAddress, 'nft');
 
-    let tokenId: number;
-    const events = await recordEvents(contract, async () => {
-      tokenId = await createItemExpectSuccess(alice, collection, 'NFT');
+    const events: any = [];
+    contract.events.allEvents((_: any, event: any) => {
+      events.push(event);
     });
+    const {tokenId} = await collection.mintToken(alice);
 
-    expect(events).to.be.deep.equal([
-      {
-        address,
-        event: 'Transfer',
-        args: {
-          from: '0x0000000000000000000000000000000000000000',
-          to: subToEth(alice.address),
-          tokenId: tokenId!.toString(),
-        },
-      },
-    ]);
+    const event = events[0];
+    expect(event.event).to.be.equal('Transfer');
+    expect(event.address).to.be.equal(collectionAddress);
+    expect(event.returnValues.from).to.be.equal('0x0000000000000000000000000000000000000000');
+    expect(event.returnValues.to).to.be.equal(helper.address.substrateToEth(alice.address));
+    expect(event.returnValues.tokenId).to.be.equal(tokenId.toString());
   });
 
-  itWeb3('Events emitted for burn()', async ({web3, privateKeyWrapper}) => {
-    const collection = await createCollectionExpectSuccess({
-      mode: {type: 'NFT'},
+  itEth('Events emitted for burn()', async ({helper}) => {
+    const collection = await helper.nft.mintCollection(alice, {});
+    const token = await collection.mintToken(alice);
+
+    const collectionAddress = helper.ethAddress.fromCollectionId(collection.collectionId);
+    const contract = helper.ethNativeContract.collection(collectionAddress, 'nft');
+    
+    const events: any = [];
+    contract.events.allEvents((_: any, event: any) => {
+      events.push(event);
     });
-    const alice = privateKeyWrapper('//Alice');
 
-    const address = collectionIdToAddress(collection);
-    const contract = new web3.eth.Contract(nonFungibleAbi as any, address);
+    await token.burn(alice);
 
-    const tokenId = await createItemExpectSuccess(alice, collection, 'NFT');
-    const events = await recordEvents(contract, async () => {
-      await burnItemExpectSuccess(alice, collection, tokenId);
-    });
-
-    expect(events).to.be.deep.equal([
-      {
-        address,
-        event: 'Transfer',
-        args: {
-          from: subToEth(alice.address),
-          to: '0x0000000000000000000000000000000000000000',
-          tokenId: tokenId.toString(),
-        },
-      },
-    ]);
+    const event = events[0];
+    expect(event.event).to.be.equal('Transfer');
+    expect(event.address).to.be.equal(collectionAddress);
+    expect(event.returnValues.from).to.be.equal(helper.address.substrateToEth(alice.address));
+    expect(event.returnValues.to).to.be.equal('0x0000000000000000000000000000000000000000');
+    expect(event.returnValues.tokenId).to.be.equal(token.tokenId.toString());
   });
 
-  itWeb3('Events emitted for approve()', async ({web3, privateKeyWrapper}) => {
-    const collection = await createCollectionExpectSuccess({
-      mode: {type: 'NFT'},
-    });
-    const alice = privateKeyWrapper('//Alice');
+  itEth('Events emitted for approve()', async ({helper}) => {
+    const receiver = helper.eth.createAccount();
 
-    const receiver = createEthAccount(web3);
-
-    const tokenId = await createItemExpectSuccess(alice, collection, 'NFT');
-
-    const address = collectionIdToAddress(collection);
-    const contract = new web3.eth.Contract(nonFungibleAbi as any, address);
+    const collection = await helper.nft.mintCollection(alice, {});
+    const token = await collection.mintToken(alice);
 
-    const events = await recordEvents(contract, async () => {
-      await approveExpectSuccess(collection, tokenId, alice, {Ethereum: receiver}, 1);
+    const collectionAddress = helper.ethAddress.fromCollectionId(collection.collectionId);
+    const contract = helper.ethNativeContract.collection(collectionAddress, 'nft');
+    
+    const events: any = [];
+    contract.events.allEvents((_: any, event: any) => {
+      events.push(event);
     });
 
-    expect(events).to.be.deep.equal([
-      {
-        address,
-        event: 'Approval',
-        args: {
-          owner: subToEth(alice.address),
-          approved: receiver,
-          tokenId: tokenId.toString(),
-        },
-      },
-    ]);
+    await token.approve(alice, {Ethereum: receiver});
+
+    const event = events[0];
+    expect(event.event).to.be.equal('Approval');
+    expect(event.address).to.be.equal(collectionAddress);
+    expect(event.returnValues.owner).to.be.equal(helper.address.substrateToEth(alice.address));
+    expect(event.returnValues.approved).to.be.equal(receiver);
+    expect(event.returnValues.tokenId).to.be.equal(token.tokenId.toString());
   });
 
-  itWeb3('Events emitted for transferFrom()', async ({web3, privateKeyWrapper}) => {
-    const collection = await createCollectionExpectSuccess({
-      mode: {type: 'NFT'},
-    });
-    const alice = privateKeyWrapper('//Alice');
-    const bob = privateKeyWrapper('//Bob');
+  itEth('Events emitted for transferFrom()', async ({helper}) => {
+    const [bob] = await helper.arrange.createAccounts([10n], donor);
+    const receiver = helper.eth.createAccount();
 
-    const receiver = createEthAccount(web3);
-
-    const tokenId = await createItemExpectSuccess(alice, collection, 'NFT');
-    await approveExpectSuccess(collection, tokenId, alice, bob.address, 1);
-
-    const address = collectionIdToAddress(collection);
-    const contract = new web3.eth.Contract(nonFungibleAbi as any, address);
+    const collection = await helper.nft.mintCollection(alice, {});
+    const token = await collection.mintToken(alice);
+    await token.approve(alice, {Substrate: bob.address});
 
-    const events = await recordEvents(contract, async () => {
-      await transferFromExpectSuccess(collection, tokenId, bob, alice, {Ethereum: receiver}, 1, 'NFT');
+    const collectionAddress = helper.ethAddress.fromCollectionId(collection.collectionId);
+    const contract = helper.ethNativeContract.collection(collectionAddress, 'nft');
+    
+    const events: any = [];
+    contract.events.allEvents((_: any, event: any) => {
+      events.push(event);
     });
 
-    expect(events).to.be.deep.equal([
-      {
-        address,
-        event: 'Transfer',
-        args: {
-          from: subToEth(alice.address),
-          to: receiver,
-          tokenId: tokenId.toString(),
-        },
-      },
-    ]);
+    await token.transferFrom(bob, {Substrate: alice.address}, {Ethereum: receiver});
+    
+    const event = events[0];
+    expect(event.address).to.be.equal(collectionAddress);
+    expect(event.returnValues.from).to.be.equal(helper.address.substrateToEth(alice.address));
+    expect(event.returnValues.to).to.be.equal(receiver);
+    expect(event.returnValues.tokenId).to.be.equal(`${token.tokenId}`);
   });
 
-  itWeb3('Events emitted for transfer()', async ({web3, privateKeyWrapper}) => {
-    const collection = await createCollectionExpectSuccess({
-      mode: {type: 'NFT'},
-    });
-    const alice = privateKeyWrapper('//Alice');
+  itEth('Events emitted for transfer()', async ({helper}) => {
+    const receiver = helper.eth.createAccount();
 
-    const receiver = createEthAccount(web3);
+    const collection = await helper.nft.mintCollection(alice, {});
+    const token = await collection.mintToken(alice);
 
-    const tokenId = await createItemExpectSuccess(alice, collection, 'NFT');
-
-    const address = collectionIdToAddress(collection);
-    const contract = new web3.eth.Contract(nonFungibleAbi as any, address);
-
-    const events = await recordEvents(contract, async () => {
-      await transferExpectSuccess(collection, tokenId, alice, {Ethereum: receiver}, 1, 'NFT');
+    const collectionAddress = helper.ethAddress.fromCollectionId(collection.collectionId);
+    const contract = helper.ethNativeContract.collection(collectionAddress, 'nft');
+    
+    const events: any = [];
+    contract.events.allEvents((_: any, event: any) => {
+      events.push(event);
     });
 
-    expect(events).to.be.deep.equal([
-      {
-        address,
-        event: 'Transfer',
-        args: {
-          from: subToEth(alice.address),
-          to: receiver,
-          tokenId: tokenId.toString(),
-        },
-      },
-    ]);
+    await token.transfer(alice, {Ethereum: receiver});
+    
+    const event = events[0];
+    expect(event.address).to.be.equal(collectionAddress);
+    expect(event.returnValues.from).to.be.equal(helper.address.substrateToEth(alice.address));
+    expect(event.returnValues.to).to.be.equal(receiver);
+    expect(event.returnValues.tokenId).to.be.equal(`${token.tokenId}`);
   });
 });
 
 describe('Common metadata', () => {
-  itWeb3('Returns collection name', async ({api, web3, privateKeyWrapper}) => {
-    const collection = await createCollectionExpectSuccess({
-      name: 'token name',
-      mode: {type: 'NFT'},
+  let donor: IKeyringPair;
+  let alice: IKeyringPair;
+
+  before(async function() {
+    await usingEthPlaygrounds(async (helper, privateKey) => {
+      donor = privateKey('//Alice');
+      [alice] = await helper.arrange.createAccounts([20n], donor);
     });
-    const caller = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
+  });
+
+  itEth('Returns collection name', async ({helper}) => {
+    const caller = await helper.eth.createAccountWithBalance(donor);
+    const collection = await helper.nft.mintCollection(alice, {name: 'oh River', tokenPrefix: 'CHANGE'});
 
-    const address = collectionIdToAddress(collection);
-    const contract = new web3.eth.Contract(nonFungibleAbi as any, address, {from: caller, ...GAS_ARGS});
+    const contract = helper.ethNativeContract.collectionById(collection.collectionId, 'nft', caller);
     const name = await contract.methods.name().call();
-
-    expect(name).to.equal('token name');
+    expect(name).to.equal('oh River');
   });
 
-  itWeb3('Returns symbol name', async ({api, web3, privateKeyWrapper}) => {
-    const collection = await createCollectionExpectSuccess({
-      tokenPrefix: 'TOK',
-      mode: {type: 'NFT'},
-    });
-    const caller = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
+  itEth('Returns symbol name', async ({helper}) => {
+    const caller = await helper.eth.createAccountWithBalance(donor);
+    const collection = await helper.nft.mintCollection(alice, {name: 'oh River', tokenPrefix: 'CHANGE'});
 
-    const address = collectionIdToAddress(collection);
-    const contract = new web3.eth.Contract(nonFungibleAbi as any, address, {from: caller, ...GAS_ARGS});
+    const contract = helper.ethNativeContract.collectionById(collection.collectionId, 'nft', caller);
     const symbol = await contract.methods.symbol().call();
-
-    expect(symbol).to.equal('TOK');
+    expect(symbol).to.equal('CHANGE');
   });
 });
\ No newline at end of file
modifiedtests/src/eth/nonFungibleAbi.jsondiffbeforeafterboth
--- a/tests/src/eth/nonFungibleAbi.json
+++ b/tests/src/eth/nonFungibleAbi.json
@@ -91,27 +91,9 @@
   },
   {
     "inputs": [
-      { "internalType": "uint256", "name": "newAdmin", "type": "uint256" }
-    ],
-    "name": "addCollectionAdminSubstrate",
-    "outputs": [],
-    "stateMutability": "nonpayable",
-    "type": "function"
-  },
-  {
-    "inputs": [
       { "internalType": "address", "name": "user", "type": "address" }
     ],
     "name": "addToCollectionAllowList",
-    "outputs": [],
-    "stateMutability": "nonpayable",
-    "type": "function"
-  },
-  {
-    "inputs": [
-      { "internalType": "uint256", "name": "user", "type": "uint256" }
-    ],
-    "name": "addToCollectionAllowListSubstrate",
     "outputs": [],
     "stateMutability": "nonpayable",
     "type": "function"
@@ -273,15 +255,6 @@
       { "internalType": "address", "name": "user", "type": "address" }
     ],
     "name": "isOwnerOrAdmin",
-    "outputs": [{ "internalType": "bool", "name": "", "type": "bool" }],
-    "stateMutability": "view",
-    "type": "function"
-  },
-  {
-    "inputs": [
-      { "internalType": "uint256", "name": "user", "type": "uint256" }
-    ],
-    "name": "isOwnerOrAdminSubstrate",
     "outputs": [{ "internalType": "bool", "name": "", "type": "bool" }],
     "stateMutability": "view",
     "type": "function"
@@ -385,15 +358,6 @@
     "type": "function"
   },
   {
-    "inputs": [
-      { "internalType": "uint256", "name": "admin", "type": "uint256" }
-    ],
-    "name": "removeCollectionAdminSubstrate",
-    "outputs": [],
-    "stateMutability": "nonpayable",
-    "type": "function"
-  },
-  {
     "inputs": [],
     "name": "removeCollectionSponsor",
     "outputs": [],
@@ -405,15 +369,6 @@
       { "internalType": "address", "name": "user", "type": "address" }
     ],
     "name": "removeFromCollectionAllowList",
-    "outputs": [],
-    "stateMutability": "nonpayable",
-    "type": "function"
-  },
-  {
-    "inputs": [
-      { "internalType": "uint256", "name": "user", "type": "uint256" }
-    ],
-    "name": "removeFromCollectionAllowListSubstrate",
     "outputs": [],
     "stateMutability": "nonpayable",
     "type": "function"
@@ -527,27 +482,9 @@
   },
   {
     "inputs": [
-      { "internalType": "uint256", "name": "sponsor", "type": "uint256" }
-    ],
-    "name": "setCollectionSponsorSubstrate",
-    "outputs": [],
-    "stateMutability": "nonpayable",
-    "type": "function"
-  },
-  {
-    "inputs": [
       { "internalType": "address", "name": "newOwner", "type": "address" }
     ],
     "name": "setOwner",
-    "outputs": [],
-    "stateMutability": "nonpayable",
-    "type": "function"
-  },
-  {
-    "inputs": [
-      { "internalType": "uint256", "name": "newOwner", "type": "uint256" }
-    ],
-    "name": "setOwnerSubstrate",
     "outputs": [],
     "stateMutability": "nonpayable",
     "type": "function"
modifiedtests/src/eth/payable.test.tsdiffbeforeafterboth
--- a/tests/src/eth/payable.test.ts
+++ b/tests/src/eth/payable.test.ts
@@ -50,7 +50,7 @@
     await helper.eth.transferBalanceFromSubstrate(alice, helper.address.substrateToEth(alice.address), 5n);
 
 
-    await helper.eth.callEVM(alice, contract.options.address, contract.methods.giveMoney().encodeABI(), weiCount);
+    await helper.eth.sendEVM(alice, contract.options.address, contract.methods.giveMoney().encodeABI(), weiCount);
 
     expect(await contract.methods.getCollected().call()).to.be.equal(weiCount);
   });
modifiedtests/src/eth/reFungible.test.tsdiffbeforeafterboth
--- a/tests/src/eth/reFungible.test.ts
+++ b/tests/src/eth/reFungible.test.ts
@@ -14,33 +14,35 @@
 // You should have received a copy of the GNU General Public License
 // along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
 
-import {createCollectionExpectSuccess, UNIQUE, requirePallets, Pallets} from '../util/helpers';
-import {collectionIdToAddress, createEthAccount, createEthAccountWithBalance, evmCollection, evmCollectionHelpers, getCollectionAddressFromResult, itWeb3, normalizeEvents, recordEthFee, recordEvents, tokenIdToAddress, uniqueRefungibleToken} from './util/helpers';
-import {expect} from 'chai';
+import {Pallets, requirePalletsOrSkip} from '../util/playgrounds';
+import {expect, itEth, usingEthPlaygrounds} from './util/playgrounds';
+import {IKeyringPair} from '@polkadot/types/types';
 
 describe('Refungible: Information getting', () => {
+  let donor: IKeyringPair;
+
   before(async function() {
-    await requirePallets(this, [Pallets.ReFungible]);
+    await usingEthPlaygrounds(async (helper, privateKey) => {
+      requirePalletsOrSkip(this, helper, [Pallets.ReFungible]);
+
+      donor = privateKey('//Alice');
+    });
   });
 
-  itWeb3('totalSupply', async ({api, web3, privateKeyWrapper}) => {
-    const caller = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
-    const helper = evmCollectionHelpers(web3, caller);
-    const result = await helper.methods.createRFTCollection('Mint collection', '6', '6').send();
-    const {collectionIdAddress} = await getCollectionAddressFromResult(api, result);
-    const contract = evmCollection(web3, caller, collectionIdAddress, {type: 'ReFungible'});
+  itEth('totalSupply', async ({helper}) => {
+    const caller = await helper.eth.createAccountWithBalance(donor);
+    const {collectionAddress} = await helper.eth.createRefungibleCollection(caller, 'TotalSupply', '6', '6');
+    const contract = helper.ethNativeContract.collection(collectionAddress, 'rft', caller);
     const nextTokenId = await contract.methods.nextTokenId().call();
     await contract.methods.mint(caller, nextTokenId).send();
     const totalSupply = await contract.methods.totalSupply().call();
     expect(totalSupply).to.equal('1');
   });
 
-  itWeb3('balanceOf', async ({api, web3, privateKeyWrapper}) => {
-    const caller = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
-    const helper = evmCollectionHelpers(web3, caller);
-    const result = await helper.methods.createRFTCollection('Mint collection', '6', '6').send();
-    const {collectionIdAddress} = await getCollectionAddressFromResult(api, result);
-    const contract = evmCollection(web3, caller, collectionIdAddress, {type: 'ReFungible'});
+  itEth('balanceOf', async ({helper}) => {
+    const caller = await helper.eth.createAccountWithBalance(donor);
+    const {collectionAddress} = await helper.eth.createRefungibleCollection(caller, 'BalanceOf', '6', '6');
+    const contract = helper.ethNativeContract.collection(collectionAddress, 'rft', caller);
 
     {
       const nextTokenId = await contract.methods.nextTokenId().call();
@@ -56,38 +58,30 @@
     }
 
     const balance = await contract.methods.balanceOf(caller).call();
-
     expect(balance).to.equal('3');
   });
 
-  itWeb3('ownerOf', async ({api, web3, privateKeyWrapper}) => {
-    const caller = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
-    const helper = evmCollectionHelpers(web3, caller);
-    const result = await helper.methods.createRFTCollection('Mint collection', '6', '6').send();
-    const {collectionIdAddress} = await getCollectionAddressFromResult(api, result);
-    const contract = evmCollection(web3, caller, collectionIdAddress, {type: 'ReFungible'});
+  itEth('ownerOf', async ({helper}) => {
+    const caller = await helper.eth.createAccountWithBalance(donor);
+    const {collectionAddress} = await helper.eth.createRefungibleCollection(caller, 'OwnerOf', '6', '6');
+    const contract = helper.ethNativeContract.collection(collectionAddress, 'rft', caller);
 
     const tokenId = await contract.methods.nextTokenId().call();
     await contract.methods.mint(caller, tokenId).send();
 
     const owner = await contract.methods.ownerOf(tokenId).call();
-
     expect(owner).to.equal(caller);
   });
 
-  itWeb3('ownerOf after burn', async ({api, web3, privateKeyWrapper}) => {
-    const caller = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
-    const receiver = createEthAccount(web3);
-    const helper = evmCollectionHelpers(web3, caller);
-    const result = await helper.methods.createRFTCollection('Mint collection', '6', '6').send();
-    const {collectionIdAddress, collectionId} = await getCollectionAddressFromResult(api, result);
-    const contract = evmCollection(web3, caller, collectionIdAddress, {type: 'ReFungible'});
+  itEth('ownerOf after burn', async ({helper}) => {
+    const caller = await helper.eth.createAccountWithBalance(donor);
+    const receiver = helper.eth.createAccount();
+    const {collectionId, collectionAddress} = await helper.eth.createRefungibleCollection(caller, 'OwnerOf-AfterBurn', '6', '6');
+    const contract = helper.ethNativeContract.collection(collectionAddress, 'rft', caller);
 
     const tokenId = await contract.methods.nextTokenId().call();
     await contract.methods.mint(caller, tokenId).send();
-
-    const tokenAddress = tokenIdToAddress(collectionId, tokenId);
-    const tokenContract = uniqueRefungibleToken(web3, tokenAddress, caller);
+    const tokenContract = helper.ethNativeContract.rftTokenById(collectionId, tokenId, caller);
 
     await tokenContract.methods.repartition(2).send();
     await tokenContract.methods.transfer(receiver, 1).send();
@@ -95,80 +89,67 @@
     await tokenContract.methods.burnFrom(caller, 1).send();
 
     const owner = await contract.methods.ownerOf(tokenId).call();
-
     expect(owner).to.equal(receiver);
   });
 
-  itWeb3('ownerOf for partial ownership', async ({api, web3, privateKeyWrapper}) => {
-    const caller = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
-    const receiver = createEthAccount(web3);
-    const helper = evmCollectionHelpers(web3, caller);
-    const result = await helper.methods.createRFTCollection('Mint collection', '6', '6').send();
-    const {collectionIdAddress, collectionId} = await getCollectionAddressFromResult(api, result);
-    const contract = evmCollection(web3, caller, collectionIdAddress, {type: 'ReFungible'});
+  itEth('ownerOf for partial ownership', async ({helper}) => {
+    const caller = await helper.eth.createAccountWithBalance(donor);
+    const receiver = helper.eth.createAccount();
+    const {collectionId, collectionAddress} = await helper.eth.createRefungibleCollection(caller, 'Partial-OwnerOf', '6', '6');
+    const contract = helper.ethNativeContract.collection(collectionAddress, 'rft', caller);
 
     const tokenId = await contract.methods.nextTokenId().call();
     await contract.methods.mint(caller, tokenId).send();
-
-    const tokenAddress = tokenIdToAddress(collectionId, tokenId);
-    const tokenContract = uniqueRefungibleToken(web3, tokenAddress, caller);
+    const tokenContract = helper.ethNativeContract.rftTokenById(collectionId, tokenId, caller);
 
     await tokenContract.methods.repartition(2).send();
     await tokenContract.methods.transfer(receiver, 1).send();
 
     const owner = await contract.methods.ownerOf(tokenId).call();
-
     expect(owner).to.equal('0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF');
   });
 });
 
 describe('Refungible: Plain calls', () => {
+  let donor: IKeyringPair;
+
   before(async function() {
-    await requirePallets(this, [Pallets.ReFungible]);
+    await usingEthPlaygrounds(async (helper, privateKey) => {
+      requirePalletsOrSkip(this, helper, [Pallets.ReFungible]);
+
+      donor = privateKey('//Alice');
+    });
   });
 
-  itWeb3('Can perform mint()', async ({web3, api, privateKeyWrapper}) => {
-    const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
-    const helper = evmCollectionHelpers(web3, owner);
-    let result = await helper.methods.createRFTCollection('Mint collection', '6', '6').send();
-    const {collectionIdAddress} = await getCollectionAddressFromResult(api, result);
-    const receiver = createEthAccount(web3);
-    const contract = evmCollection(web3, owner, collectionIdAddress, {type: 'ReFungible'});
+  itEth('Can perform mint()', async ({helper}) => {
+    const owner = await helper.eth.createAccountWithBalance(donor);
+    const receiver = helper.eth.createAccount();
+    const {collectionAddress} = await helper.eth.createRefungibleCollection(owner, 'Minty', '6', '6');
+    const contract = helper.ethNativeContract.collection(collectionAddress, 'rft', owner);
+    
     const nextTokenId = await contract.methods.nextTokenId().call();
-
     expect(nextTokenId).to.be.equal('1');
-    result = await contract.methods.mintWithTokenURI(
+    const result = await contract.methods.mintWithTokenURI(
       receiver,
       nextTokenId,
       'Test URI',
     ).send();
 
-    const events = normalizeEvents(result.events);
-
-    expect(events).to.include.deep.members([
-      {
-        address: collectionIdAddress,
-        event: 'Transfer',
-        args: {
-          from: '0x0000000000000000000000000000000000000000',
-          to: receiver,
-          tokenId: nextTokenId,
-        },
-      },
-    ]);
+    const event = result.events.Transfer;
+    expect(event.address).to.equal(collectionAddress);
+    expect(event.returnValues.from).to.equal('0x0000000000000000000000000000000000000000');
+    expect(event.returnValues.to).to.equal(receiver);
+    expect(event.returnValues.tokenId).to.equal(nextTokenId);
 
     expect(await contract.methods.tokenURI(nextTokenId).call()).to.be.equal('Test URI');
   });
 
-  itWeb3('Can perform mintBulk()', async ({web3, api, privateKeyWrapper}) => {
-    const caller = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
-    const helper = evmCollectionHelpers(web3, caller);
-    const result = await helper.methods.createRFTCollection('Mint collection', '6', '6').send();
-    const {collectionIdAddress} = await getCollectionAddressFromResult(api, result);
-    const contract = evmCollection(web3, caller, collectionIdAddress, {type: 'ReFungible'});
+  itEth('Can perform mintBulk()', async ({helper}) => {
+    const owner = await helper.eth.createAccountWithBalance(donor);
+    const receiver = helper.eth.createAccount();
+    const {collectionAddress} = await helper.eth.createRefungibleCollection(owner, 'MintBulky', '6', '6');
+    const contract = helper.ethNativeContract.collection(collectionAddress, 'rft', owner);
 
-    const receiver = createEthAccount(web3);
-
     {
       const nextTokenId = await contract.methods.nextTokenId().call();
       expect(nextTokenId).to.be.equal('1');
@@ -180,37 +161,15 @@
           [+nextTokenId + 2, 'Test URI 2'],
         ],
       ).send();
-      const events = normalizeEvents(result.events);
 
-      expect(events).to.include.deep.members([
-        {
-          address: collectionIdAddress,
-          event: 'Transfer',
-          args: {
-            from: '0x0000000000000000000000000000000000000000',
-            to: receiver,
-            tokenId: nextTokenId,
-          },
-        },
-        {
-          address: collectionIdAddress,
-          event: 'Transfer',
-          args: {
-            from: '0x0000000000000000000000000000000000000000',
-            to: receiver,
-            tokenId: String(+nextTokenId + 1),
-          },
-        },
-        {
-          address: collectionIdAddress,
-          event: 'Transfer',
-          args: {
-            from: '0x0000000000000000000000000000000000000000',
-            to: receiver,
-            tokenId: String(+nextTokenId + 2),
-          },
-        },
-      ]);
+      const events = result.events.Transfer;
+      for (let i = 0; i < 2; i++) {
+        const event = events[i];
+        expect(event.address).to.equal(collectionAddress);
+        expect(event.returnValues.from).to.equal('0x0000000000000000000000000000000000000000');
+        expect(event.returnValues.to).to.equal(receiver);
+        expect(event.returnValues.tokenId).to.equal(String(+nextTokenId + i));
+      }
 
       expect(await contract.methods.tokenURI(nextTokenId).call()).to.be.equal('Test URI 0');
       expect(await contract.methods.tokenURI(+nextTokenId + 1).call()).to.be.equal('Test URI 1');
@@ -218,76 +177,54 @@
     }
   });
 
-  itWeb3('Can perform burn()', async ({web3, api, privateKeyWrapper}) => {
-    const caller = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
-    const helper = evmCollectionHelpers(web3, caller);
-    const result = await helper.methods.createRFTCollection('Mint collection', '6', '6').send();
-    const {collectionIdAddress} = await getCollectionAddressFromResult(api, result);
-    const contract = evmCollection(web3, caller, collectionIdAddress, {type: 'ReFungible'});
+  itEth('Can perform burn()', async ({helper}) => {
+    const caller = await helper.eth.createAccountWithBalance(donor);
+    const {collectionAddress} = await helper.eth.createRefungibleCollection(caller, 'Burny', '6', '6');
+    const contract = helper.ethNativeContract.collection(collectionAddress, 'rft', caller);
 
     const tokenId = await contract.methods.nextTokenId().call();
     await contract.methods.mint(caller, tokenId).send();
     {
       const result = await contract.methods.burn(tokenId).send();
-      const events = normalizeEvents(result.events);
-      expect(events).to.include.deep.members([
-        {
-          address: collectionIdAddress,
-          event: 'Transfer',
-          args: {
-            from: caller,
-            to: '0x0000000000000000000000000000000000000000',
-            tokenId: tokenId.toString(),
-          },
-        },
-      ]);
+      const event = result.events.Transfer;
+      expect(event.address).to.equal(collectionAddress);
+      expect(event.returnValues.from).to.equal(caller);
+      expect(event.returnValues.to).to.equal('0x0000000000000000000000000000000000000000');
+      expect(event.returnValues.tokenId).to.equal(tokenId.toString());
     }
   });
 
-  itWeb3('Can perform transferFrom()', async ({web3, api, privateKeyWrapper}) => {
-    const caller = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
-    const helper = evmCollectionHelpers(web3, caller);
-    const result = await helper.methods.createRFTCollection('Mint collection', '6', '6').send();
-    const {collectionIdAddress, collectionId} = await getCollectionAddressFromResult(api, result);
-    const contract = evmCollection(web3, caller, collectionIdAddress, {type: 'ReFungible'});
-
-    const receiver = createEthAccount(web3);
+  itEth('Can perform transferFrom()', async ({helper}) => {
+    const caller = await helper.eth.createAccountWithBalance(donor);
+    const receiver = helper.eth.createAccount();
+    const {collectionId, collectionAddress} = await helper.eth.createRefungibleCollection(caller, 'TransferFromy', '6', '6');
+    const contract = helper.ethNativeContract.collection(collectionAddress, 'rft', caller);
 
     const tokenId = await contract.methods.nextTokenId().call();
+    const tokenAddress = helper.ethAddress.fromTokenId(collectionId, tokenId);
     await contract.methods.mint(caller, tokenId).send();
 
-    const address = tokenIdToAddress(collectionId, tokenId);
-    const tokenContract = uniqueRefungibleToken(web3, address, caller);
+    const tokenContract = helper.ethNativeContract.rftToken(tokenAddress, caller);
     await tokenContract.methods.repartition(15).send();
 
     {
-      const erc20Events = await recordEvents(tokenContract, async () => {
-        const result = await contract.methods.transferFrom(caller, receiver, tokenId).send();
-        const events = normalizeEvents(result.events);
-        expect(events).to.include.deep.members([
-          {
-            address: collectionIdAddress,
-            event: 'Transfer',
-            args: {
-              from: caller,
-              to: receiver,
-              tokenId: tokenId.toString(),
-            },
-          },
-        ]);
+      const tokenEvents: any = [];
+      tokenContract.events.allEvents((_: any, event: any) => {
+        tokenEvents.push(event);
       });
+      const result = await contract.methods.transferFrom(caller, receiver, tokenId).send();
+
+      let event = result.events.Transfer;
+      expect(event.address).to.equal(collectionAddress);
+      expect(event.returnValues.from).to.equal(caller);
+      expect(event.returnValues.to).to.equal(receiver);
+      expect(event.returnValues.tokenId).to.equal(tokenId.toString());
 
-      expect(erc20Events).to.include.deep.members([
-        {
-          address,
-          event: 'Transfer',
-          args: {
-            from: caller,
-            to: receiver,
-            value: '15',
-          },
-        },
-      ]);
+      event = tokenEvents[0];
+      expect(event.address).to.equal(tokenAddress);
+      expect(event.returnValues.from).to.equal(caller);
+      expect(event.returnValues.to).to.equal(receiver);
+      expect(event.returnValues.value).to.equal('15');
     }
 
     {
@@ -301,32 +238,23 @@
     }
   });
 
-  itWeb3('Can perform transfer()', async ({web3, api, privateKeyWrapper}) => {
-    const caller = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
-    const helper = evmCollectionHelpers(web3, caller);
-    const result = await helper.methods.createRFTCollection('Mint collection', '6', '6').send();
-    const {collectionIdAddress} = await getCollectionAddressFromResult(api, result);
-    const contract = evmCollection(web3, caller, collectionIdAddress, {type: 'ReFungible'});
-
-    const receiver = createEthAccount(web3);
+  itEth('Can perform transfer()', async ({helper}) => {
+    const caller = await helper.eth.createAccountWithBalance(donor);
+    const receiver = helper.eth.createAccount();
+    const {collectionAddress} = await helper.eth.createRefungibleCollection(caller, 'Transferry', '6', '6');
+    const contract = helper.ethNativeContract.collection(collectionAddress, 'rft', caller);
 
     const tokenId = await contract.methods.nextTokenId().call();
     await contract.methods.mint(caller, tokenId).send();
 
     {
       const result = await contract.methods.transfer(receiver, tokenId).send();
-      const events = normalizeEvents(result.events);
-      expect(events).to.include.deep.members([
-        {
-          address: collectionIdAddress,
-          event: 'Transfer',
-          args: {
-            from: caller,
-            to: receiver,
-            tokenId: tokenId.toString(),
-          },
-        },
-      ]);
+      
+      const event = result.events.Transfer;
+      expect(event.address).to.equal(collectionAddress);
+      expect(event.returnValues.from).to.equal(caller);
+      expect(event.returnValues.to).to.equal(receiver);
+      expect(event.returnValues.tokenId).to.equal(tokenId.toString());
     }
 
     {
@@ -340,141 +268,127 @@
     }
   });
 
-  itWeb3('transfer event on transfer from partial ownership to full ownership', async ({api, web3, privateKeyWrapper}) => {
-    const caller = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
-    const receiver = createEthAccount(web3);
-    const helper = evmCollectionHelpers(web3, caller);
-    const result = await helper.methods.createRFTCollection('Mint collection', '6', '6').send();
-    const {collectionIdAddress, collectionId} = await getCollectionAddressFromResult(api, result);
-    const contract = evmCollection(web3, caller, collectionIdAddress, {type: 'ReFungible'});
+  itEth('transfer event on transfer from partial ownership to full ownership', async ({helper}) => {
+    const caller = await helper.eth.createAccountWithBalance(donor);
+    const receiver = helper.eth.createAccount();
+    const {collectionId, collectionAddress} = await helper.eth.createRefungibleCollection(caller, 'Transferry-Partial-to-Full', '6', '6');
+    const contract = helper.ethNativeContract.collection(collectionAddress, 'rft', caller);
 
     const tokenId = await contract.methods.nextTokenId().call();
     await contract.methods.mint(caller, tokenId).send();
 
-    const tokenAddress = tokenIdToAddress(collectionId, tokenId);
-    const tokenContract = uniqueRefungibleToken(web3, tokenAddress, caller);
+    const tokenContract = helper.ethNativeContract.rftTokenById(collectionId, tokenId, caller);
 
     await tokenContract.methods.repartition(2).send();
     await tokenContract.methods.transfer(receiver, 1).send();
 
-    const events =  await recordEvents(contract, async () =>
-      await tokenContract.methods.transfer(receiver, 1).send());
-    expect(events).to.deep.equal([
-      {
-        address: collectionIdAddress,
-        event: 'Transfer',
-        args: {
-          from: '0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF',
-          to: receiver,
-          tokenId: tokenId.toString(),
-        },
-      },
-    ]);
+    const events: any = [];
+    contract.events.allEvents((_: any, event: any) => {
+      events.push(event);
+    });
+    await tokenContract.methods.transfer(receiver, 1).send();
+
+    const event = events[0];
+    expect(event.address).to.equal(collectionAddress);
+    expect(event.returnValues.from).to.equal('0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF');
+    expect(event.returnValues.to).to.equal(receiver);
+    expect(event.returnValues.tokenId).to.equal(tokenId.toString());
   });
 
-  itWeb3('transfer event on transfer from full ownership to partial ownership', async ({api, web3, privateKeyWrapper}) => {
-    const caller = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
-    const receiver = createEthAccount(web3);
-    const helper = evmCollectionHelpers(web3, caller);
-    const result = await helper.methods.createRFTCollection('Mint collection', '6', '6').send();
-    const {collectionIdAddress, collectionId} = await getCollectionAddressFromResult(api, result);
-    const contract = evmCollection(web3, caller, collectionIdAddress, {type: 'ReFungible'});
+  itEth('transfer event on transfer from full ownership to partial ownership', async ({helper}) => {
+    const caller = await helper.eth.createAccountWithBalance(donor);
+    const receiver = helper.eth.createAccount();
+    const {collectionId, collectionAddress} = await helper.eth.createRefungibleCollection(caller, 'Transferry-Full-to-Partial', '6', '6');
+    const contract = helper.ethNativeContract.collection(collectionAddress, 'rft', caller);
 
     const tokenId = await contract.methods.nextTokenId().call();
     await contract.methods.mint(caller, tokenId).send();
 
-    const tokenAddress = tokenIdToAddress(collectionId, tokenId);
-    const tokenContract = uniqueRefungibleToken(web3, tokenAddress, caller);
+    const tokenContract = helper.ethNativeContract.rftTokenById(collectionId, tokenId, caller);
 
     await tokenContract.methods.repartition(2).send();
 
-    const events =  await recordEvents(contract, async () =>
-      await tokenContract.methods.transfer(receiver, 1).send());
+    const events: any = [];
+    contract.events.allEvents((_: any, event: any) => {
+      events.push(event);
+    });
+    await tokenContract.methods.transfer(receiver, 1).send();
 
-    expect(events).to.deep.equal([
-      {
-        address: collectionIdAddress,
-        event: 'Transfer',
-        args: {
-          from: caller,
-          to: '0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF',
-          tokenId: tokenId.toString(),
-        },
-      },
-    ]);
+    const event = events[0];
+    expect(event.address).to.equal(collectionAddress);
+    expect(event.returnValues.from).to.equal(caller);
+    expect(event.returnValues.to).to.equal('0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF');
+    expect(event.returnValues.tokenId).to.equal(tokenId.toString());
   });
 });
 
 describe('RFT: Fees', () => {
+  let donor: IKeyringPair;
+
   before(async function() {
-    await requirePallets(this, [Pallets.ReFungible]);
+    await usingEthPlaygrounds(async (helper, privateKey) => {
+      requirePalletsOrSkip(this, helper, [Pallets.ReFungible]);
+
+      donor = privateKey('//Alice');
+    });
   });
 
-  itWeb3('transferFrom() call fee is less than 0.2UNQ', async ({web3, api, privateKeyWrapper}) => {
-    const caller = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
-    const helper = evmCollectionHelpers(web3, caller);
-    const result = await helper.methods.createRFTCollection('Mint collection', '6', '6').send();
-    const {collectionIdAddress} = await getCollectionAddressFromResult(api, result);
-    const contract = evmCollection(web3, caller, collectionIdAddress, {type: 'ReFungible'});
-
-    const receiver = createEthAccount(web3);
+  itEth('transferFrom() call fee is less than 0.2UNQ', async ({helper}) => {
+    const caller = await helper.eth.createAccountWithBalance(donor);
+    const receiver = helper.eth.createAccount();
+    const {collectionAddress} = await helper.eth.createRefungibleCollection(caller, 'Feeful-Transfer-From', '6', '6');
+    const contract = helper.ethNativeContract.collection(collectionAddress, 'rft', caller);
 
     const tokenId = await contract.methods.nextTokenId().call();
     await contract.methods.mint(caller, tokenId).send();
 
-    const cost = await recordEthFee(api, caller, () => contract.methods.transferFrom(caller, receiver, tokenId).send());
-    expect(cost < BigInt(0.2 * Number(UNIQUE)));
+    const cost = await helper.eth.recordCallFee(caller, () => contract.methods.transferFrom(caller, receiver, tokenId).send());
+    expect(cost < BigInt(0.2 * Number(helper.balance.getOneTokenNominal())));
     expect(cost > 0n);
   });
 
-  itWeb3('transfer() call fee is less than 0.2UNQ', async ({web3, api, privateKeyWrapper}) => {
-    const caller = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
-    const helper = evmCollectionHelpers(web3, caller);
-    const result = await helper.methods.createRFTCollection('Mint collection', '6', '6').send();
-    const {collectionIdAddress} = await getCollectionAddressFromResult(api, result);
-    const contract = evmCollection(web3, caller, collectionIdAddress, {type: 'ReFungible'});
-
-    const receiver = createEthAccount(web3);
+  itEth('transfer() call fee is less than 0.2UNQ', async ({helper}) => {
+    const caller = await helper.eth.createAccountWithBalance(donor);
+    const receiver = helper.eth.createAccount();
+    const {collectionAddress} = await helper.eth.createRefungibleCollection(caller, 'Feeful-Transfer', '6', '6');
+    const contract = helper.ethNativeContract.collection(collectionAddress, 'rft', caller);
 
     const tokenId = await contract.methods.nextTokenId().call();
     await contract.methods.mint(caller, tokenId).send();
 
-    const cost = await recordEthFee(api, caller, () => contract.methods.transfer(receiver, tokenId).send());
-    expect(cost < BigInt(0.2 * Number(UNIQUE)));
+    const cost = await helper.eth.recordCallFee(caller, () => contract.methods.transfer(receiver, tokenId).send());
+    expect(cost < BigInt(0.2 * Number(helper.balance.getOneTokenNominal())));
     expect(cost > 0n);
   });
 });
 
 describe('Common metadata', () => {
+  let donor: IKeyringPair;
+  let alice: IKeyringPair;
+
   before(async function() {
-    await requirePallets(this, [Pallets.ReFungible]);
-  });
+    await usingEthPlaygrounds(async (helper, privateKey) => {
+      requirePalletsOrSkip(this, helper, [Pallets.ReFungible]);
 
-  itWeb3('Returns collection name', async ({api, web3, privateKeyWrapper}) => {
-    const collection = await createCollectionExpectSuccess({
-      name: 'token name',
-      mode: {type: 'ReFungible'},
+      donor = privateKey('//Alice');
+      [alice] = await helper.arrange.createAccounts([20n], donor);
     });
-    const caller = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
+  });
 
-    const address = collectionIdToAddress(collection);
-    const contract = evmCollection(web3, caller, address, {type: 'ReFungible'});
+  itEth('Returns collection name', async ({helper}) => {
+    const caller = helper.eth.createAccount();
+    const collection = await helper.rft.mintCollection(alice, {name: 'Leviathan', tokenPrefix: '11'});
+    
+    const contract = helper.ethNativeContract.collectionById(collection.collectionId, 'rft', caller);
     const name = await contract.methods.name().call();
-
-    expect(name).to.equal('token name');
+    expect(name).to.equal('Leviathan');
   });
 
-  itWeb3('Returns symbol name', async ({api, web3, privateKeyWrapper}) => {
-    const collection = await createCollectionExpectSuccess({
-      tokenPrefix: 'TOK',
-      mode: {type: 'ReFungible'},
-    });
-    const caller = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
-
-    const address = collectionIdToAddress(collection);
-    const contract = evmCollection(web3, caller, address, {type: 'ReFungible'});
+  itEth('Returns symbol name', async ({helper}) => {
+    const caller = await helper.eth.createAccountWithBalance(donor);
+    const {collectionAddress} = await helper.eth.createRefungibleCollection(caller, 'Leviathan', '', '12');
+    const contract = helper.ethNativeContract.collection(collectionAddress, 'rft', caller);
     const symbol = await contract.methods.symbol().call();
-
-    expect(symbol).to.equal('TOK');
+    expect(symbol).to.equal('12');
   });
 });
modifiedtests/src/eth/reFungibleAbi.jsondiffbeforeafterboth
--- a/tests/src/eth/reFungibleAbi.json
+++ b/tests/src/eth/reFungibleAbi.json
@@ -91,27 +91,9 @@
   },
   {
     "inputs": [
-      { "internalType": "uint256", "name": "newAdmin", "type": "uint256" }
-    ],
-    "name": "addCollectionAdminSubstrate",
-    "outputs": [],
-    "stateMutability": "nonpayable",
-    "type": "function"
-  },
-  {
-    "inputs": [
       { "internalType": "address", "name": "user", "type": "address" }
     ],
     "name": "addToCollectionAllowList",
-    "outputs": [],
-    "stateMutability": "nonpayable",
-    "type": "function"
-  },
-  {
-    "inputs": [
-      { "internalType": "uint256", "name": "user", "type": "uint256" }
-    ],
-    "name": "addToCollectionAllowListSubstrate",
     "outputs": [],
     "stateMutability": "nonpayable",
     "type": "function"
@@ -273,15 +255,6 @@
       { "internalType": "address", "name": "user", "type": "address" }
     ],
     "name": "isOwnerOrAdmin",
-    "outputs": [{ "internalType": "bool", "name": "", "type": "bool" }],
-    "stateMutability": "view",
-    "type": "function"
-  },
-  {
-    "inputs": [
-      { "internalType": "uint256", "name": "user", "type": "uint256" }
-    ],
-    "name": "isOwnerOrAdminSubstrate",
     "outputs": [{ "internalType": "bool", "name": "", "type": "bool" }],
     "stateMutability": "view",
     "type": "function"
@@ -385,15 +358,6 @@
     "type": "function"
   },
   {
-    "inputs": [
-      { "internalType": "uint256", "name": "admin", "type": "uint256" }
-    ],
-    "name": "removeCollectionAdminSubstrate",
-    "outputs": [],
-    "stateMutability": "nonpayable",
-    "type": "function"
-  },
-  {
     "inputs": [],
     "name": "removeCollectionSponsor",
     "outputs": [],
@@ -405,15 +369,6 @@
       { "internalType": "address", "name": "user", "type": "address" }
     ],
     "name": "removeFromCollectionAllowList",
-    "outputs": [],
-    "stateMutability": "nonpayable",
-    "type": "function"
-  },
-  {
-    "inputs": [
-      { "internalType": "uint256", "name": "user", "type": "uint256" }
-    ],
-    "name": "removeFromCollectionAllowListSubstrate",
     "outputs": [],
     "stateMutability": "nonpayable",
     "type": "function"
@@ -527,27 +482,9 @@
   },
   {
     "inputs": [
-      { "internalType": "uint256", "name": "sponsor", "type": "uint256" }
-    ],
-    "name": "setCollectionSponsorSubstrate",
-    "outputs": [],
-    "stateMutability": "nonpayable",
-    "type": "function"
-  },
-  {
-    "inputs": [
       { "internalType": "address", "name": "newOwner", "type": "address" }
     ],
     "name": "setOwner",
-    "outputs": [],
-    "stateMutability": "nonpayable",
-    "type": "function"
-  },
-  {
-    "inputs": [
-      { "internalType": "uint256", "name": "newOwner", "type": "uint256" }
-    ],
-    "name": "setOwnerSubstrate",
     "outputs": [],
     "stateMutability": "nonpayable",
     "type": "function"
modifiedtests/src/eth/reFungibleToken.test.tsdiffbeforeafterboth
--- a/tests/src/eth/reFungibleToken.test.ts
+++ b/tests/src/eth/reFungibleToken.test.ts
@@ -14,82 +14,76 @@
 // You should have received a copy of the GNU General Public License
 // along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
 
-import {approve, createCollection, createRefungibleToken, transfer, transferFrom, UNIQUE, requirePallets, Pallets} from '../util/helpers';
-import {collectionIdToAddress, createEthAccount, createEthAccountWithBalance, createRFTCollection, evmCollection, evmCollectionHelpers, getCollectionAddressFromResult, itWeb3, normalizeEvents, recordEthFee, recordEvents, subToEth, tokenIdToAddress, transferBalanceToEth, uniqueRefungible, uniqueRefungibleToken} from './util/helpers';
+import {Pallets, requirePalletsOrSkip} from '../util/playgrounds';
+import {EthUniqueHelper, expect, itEth, usingEthPlaygrounds} from './util/playgrounds';
+import {IKeyringPair} from '@polkadot/types/types';
+import {Contract} from 'web3-eth-contract';
 
-import chai from 'chai';
-import chaiAsPromised from 'chai-as-promised';
-chai.use(chaiAsPromised);
-const expect = chai.expect;
+describe('Refungible token: Information getting', () => {
+  let donor: IKeyringPair;
+  let alice: IKeyringPair;
 
-describe('Refungible token: Information getting', () => {
   before(async function() {
-    await requirePallets(this, [Pallets.ReFungible]);
-  });
+    await usingEthPlaygrounds(async (helper, privateKey) => {
+      requirePalletsOrSkip(this, helper, [Pallets.ReFungible]);
 
-  itWeb3('totalSupply', async ({api, web3, privateKeyWrapper}) => {
-    const alice = privateKeyWrapper('//Alice');
-
-    const collectionId = (await createCollection(api, alice, {name: 'token name', mode: {type: 'ReFungible'}})).collectionId;
-
-    const caller = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
+      donor = privateKey('//Alice');
+      [alice] = await helper.arrange.createAccounts([20n], donor);
+    });
+  });
 
-    const tokenId = (await createRefungibleToken(api, alice, collectionId, 200n, {Ethereum: caller})).itemId;
+  itEth('totalSupply', async ({helper}) => {
+    const caller = await helper.eth.createAccountWithBalance(donor);
+    const collection = await helper.rft.mintCollection(alice, {tokenPrefix: 'MUON'});
+    const {tokenId} = await collection.mintToken(alice, 200n, {Ethereum: caller});
 
-    const address = tokenIdToAddress(collectionId, tokenId);
-    const contract = uniqueRefungibleToken(web3, address, caller);
+    const contract = helper.ethNativeContract.rftTokenById(collection.collectionId, tokenId, caller);
     const totalSupply = await contract.methods.totalSupply().call();
-
     expect(totalSupply).to.equal('200');
   });
 
-  itWeb3('balanceOf', async ({api, web3, privateKeyWrapper}) => {
-    const alice = privateKeyWrapper('//Alice');
-
-    const collectionId = (await createCollection(api, alice, {name: 'token name', mode: {type: 'ReFungible'}})).collectionId;
+  itEth('balanceOf', async ({helper}) => {
+    const caller = await helper.eth.createAccountWithBalance(donor);
+    const collection = await helper.rft.mintCollection(alice, {tokenPrefix: 'MUON'});
+    const {tokenId} = await collection.mintToken(alice, 200n, {Ethereum: caller});
 
-    const caller = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
-
-    const tokenId = (await createRefungibleToken(api, alice, collectionId, 200n, {Ethereum: caller})).itemId;
-
-    const address = tokenIdToAddress(collectionId, tokenId);
-    const contract = uniqueRefungibleToken(web3, address, caller);
+    const contract = helper.ethNativeContract.rftTokenById(collection.collectionId, tokenId, caller);
     const balance = await contract.methods.balanceOf(caller).call();
-
     expect(balance).to.equal('200');
   });
 
-  itWeb3('decimals', async ({api, web3, privateKeyWrapper}) => {
-    const alice = privateKeyWrapper('//Alice');
+  itEth('decimals', async ({helper}) => {
+    const caller = await helper.eth.createAccountWithBalance(donor);
+    const collection = await helper.rft.mintCollection(alice, {tokenPrefix: 'MUON'});
+    const {tokenId} = await collection.mintToken(alice, 200n, {Ethereum: caller});
 
-    const collectionId = (await createCollection(api, alice, {name: 'token name', mode: {type: 'ReFungible'}})).collectionId;
-
-    const caller = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
-
-    const tokenId = (await createRefungibleToken(api, alice, collectionId, 200n, {Ethereum: caller})).itemId;
-
-    const address = tokenIdToAddress(collectionId, tokenId);
-    const contract = uniqueRefungibleToken(web3, address, caller);
+    const contract = helper.ethNativeContract.rftTokenById(collection.collectionId, tokenId, caller);
     const decimals = await contract.methods.decimals().call();
-
     expect(decimals).to.equal('0');
   });
 });
 
 // FIXME: Need erc721 for ReFubgible.
 describe('Check ERC721 token URI for ReFungible', () => {
+  let donor: IKeyringPair;
+
   before(async function() {
-    await requirePallets(this, [Pallets.ReFungible]);
+    await usingEthPlaygrounds(async (helper, privateKey) => {
+      requirePalletsOrSkip(this, helper, [Pallets.ReFungible]);
+
+      donor = privateKey('//Alice');
+    });
   });
 
-  itWeb3('Empty tokenURI', async ({web3, api, privateKeyWrapper}) => {
-    const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
-    const helper = evmCollectionHelpers(web3, owner);
-    let result = await helper.methods.createERC721MetadataCompatibleCollection('Mint collection', '1', '1', '').send();
-    const {collectionIdAddress, collectionId} = await getCollectionAddressFromResult(api, result);
-    const receiver = createEthAccount(web3);
-    const contract = evmCollection(web3, owner, collectionIdAddress, {type: 'ReFungible'});
+  async function setup(helper: EthUniqueHelper, tokenPrefix: string, propertyKey?: string, propertyValue?: string): Promise<{contract: Contract, nextTokenId: string}> {
+    const owner = await helper.eth.createAccountWithBalance(donor);
+    const receiver = helper.eth.createAccount();
 
+    const collectionHelper = helper.ethNativeContract.collectionHelpers(owner);
+    let result = await collectionHelper.methods.createERC721MetadataCompatibleCollection('Mint collection', 'a', 'b', tokenPrefix).send();
+    const collectionAddress = helper.ethAddress.normalizeAddress(result.events.CollectionCreated.returnValues.collectionId);
+    const contract = helper.ethNativeContract.collection(collectionAddress, 'rft', owner);
+    
     const nextTokenId = await contract.methods.nextTokenId().call();
     expect(nextTokenId).to.be.equal('1');
     result = await contract.methods.mint(
@@ -97,166 +91,71 @@
       nextTokenId,
     ).send();
 
-    const events = normalizeEvents(result.events);
-    const address = collectionIdToAddress(collectionId);
+    if (propertyKey && propertyValue) {
+      // Set URL or suffix
+      await contract.methods.setProperty(nextTokenId, propertyKey, Buffer.from(propertyValue)).send();
+    }
+
+    const event = result.events.Transfer;
+    expect(event.address).to.be.equal(collectionAddress);
+    expect(event.returnValues.from).to.be.equal('0x0000000000000000000000000000000000000000');
+    expect(event.returnValues.to).to.be.equal(receiver);
+    expect(event.returnValues.tokenId).to.be.equal(nextTokenId);
 
-    expect(events).to.be.deep.equal([
-      {
-        address,
-        event: 'Transfer',
-        args: {
-          from: '0x0000000000000000000000000000000000000000',
-          to: receiver,
-          tokenId: nextTokenId,
-        },
-      },
-    ]);
+    return {contract, nextTokenId};
+  }
 
+  itEth('Empty tokenURI', async ({helper}) => {
+    const {contract, nextTokenId} = await setup(helper, '');
     expect(await contract.methods.tokenURI(nextTokenId).call()).to.be.equal('');
   });
-
-  itWeb3('TokenURI from url', async ({web3, api, privateKeyWrapper}) => {
-    const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
-    const helper = evmCollectionHelpers(web3, owner);
-    let result = await helper.methods.createERC721MetadataCompatibleCollection('Mint collection', '1', '1', 'BaseURI_').send();
-    const {collectionIdAddress, collectionId} = await getCollectionAddressFromResult(api, result);
-    const receiver = createEthAccount(web3);
-    const contract = evmCollection(web3, owner, collectionIdAddress, {type: 'ReFungible'});
 
-    const nextTokenId = await contract.methods.nextTokenId().call();
-    expect(nextTokenId).to.be.equal('1');
-    result = await contract.methods.mint(
-      receiver,
-      nextTokenId,
-    ).send();
-
-    // Set URL
-    await contract.methods.setProperty(nextTokenId, 'url', Buffer.from('Token URI')).send();
-
-    const events = normalizeEvents(result.events);
-    const address = collectionIdToAddress(collectionId);
-
-    expect(events).to.be.deep.equal([
-      {
-        address,
-        event: 'Transfer',
-        args: {
-          from: '0x0000000000000000000000000000000000000000',
-          to: receiver,
-          tokenId: nextTokenId,
-        },
-      },
-    ]);
-
+  itEth('TokenURI from url', async ({helper}) => {
+    const {contract, nextTokenId} = await setup(helper, 'BaseURI_', 'url', 'Token URI');
     expect(await contract.methods.tokenURI(nextTokenId).call()).to.be.equal('Token URI');
   });
-
-  itWeb3('TokenURI from baseURI + tokenId', async ({web3, api, privateKeyWrapper}) => {
-    const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
-    const helper = evmCollectionHelpers(web3, owner);
-    let result = await helper.methods.createERC721MetadataCompatibleCollection('Mint collection', '1', '1', 'BaseURI_').send();
-    const {collectionIdAddress, collectionId} = await getCollectionAddressFromResult(api, result);
-    const receiver = createEthAccount(web3);
-    const contract = evmCollection(web3, owner, collectionIdAddress, {type: 'ReFungible'});
 
-    const nextTokenId = await contract.methods.nextTokenId().call();
-    expect(nextTokenId).to.be.equal('1');
-    result = await contract.methods.mint(
-      receiver,
-      nextTokenId,
-    ).send();
-
-    const events = normalizeEvents(result.events);
-    const address = collectionIdToAddress(collectionId);
-
-    expect(events).to.be.deep.equal([
-      {
-        address,
-        event: 'Transfer',
-        args: {
-          from: '0x0000000000000000000000000000000000000000',
-          to: receiver,
-          tokenId: nextTokenId,
-        },
-      },
-    ]);
-
+  itEth('TokenURI from baseURI + tokenId', async ({helper}) => {
+    const {contract, nextTokenId} = await setup(helper, 'BaseURI_');
     expect(await contract.methods.tokenURI(nextTokenId).call()).to.be.equal('BaseURI_' + nextTokenId);
   });
 
-  itWeb3('TokenURI from baseURI + suffix', async ({web3, api, privateKeyWrapper}) => {
-    const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
-    const helper = evmCollectionHelpers(web3, owner);
-    let result = await helper.methods.createERC721MetadataCompatibleCollection('Mint collection', '1', '1', 'BaseURI_').send();
-    const {collectionIdAddress, collectionId} = await getCollectionAddressFromResult(api, result);
-    const receiver = createEthAccount(web3);
-    const contract = evmCollection(web3, owner, collectionIdAddress, {type: 'ReFungible'});
-
-    const nextTokenId = await contract.methods.nextTokenId().call();
-    expect(nextTokenId).to.be.equal('1');
-    result = await contract.methods.mint(
-      receiver,
-      nextTokenId,
-    ).send();
-
-    // Set suffix
+  itEth('TokenURI from baseURI + suffix', async ({helper}) => {
     const suffix = '/some/suffix';
-    await contract.methods.setProperty(nextTokenId, 'suffix', Buffer.from(suffix)).send();
-
-    const events = normalizeEvents(result.events);
-    const address = collectionIdToAddress(collectionId);
-
-    expect(events).to.be.deep.equal([
-      {
-        address,
-        event: 'Transfer',
-        args: {
-          from: '0x0000000000000000000000000000000000000000',
-          to: receiver,
-          tokenId: nextTokenId,
-        },
-      },
-    ]);
-
+    const {contract, nextTokenId} = await setup(helper, 'BaseURI_', 'suffix', suffix);
     expect(await contract.methods.tokenURI(nextTokenId).call()).to.be.equal('BaseURI_' + suffix);
   });
 });
 
 describe('Refungible: Plain calls', () => {
+  let donor: IKeyringPair;
+  let alice: IKeyringPair;
+
   before(async function() {
-    await requirePallets(this, [Pallets.ReFungible]);
+    await usingEthPlaygrounds(async (helper, privateKey) => {
+      requirePalletsOrSkip(this, helper, [Pallets.ReFungible]);
+
+      donor = privateKey('//Alice');
+      [alice] = await helper.arrange.createAccounts([50n], donor);
+    });
   });
 
-  itWeb3('Can perform approve()', async ({web3, api, privateKeyWrapper}) => {
-    const alice = privateKeyWrapper('//Alice');
+  itEth('Can perform approve()', async ({helper}) => {
+    const owner = await helper.eth.createAccountWithBalance(donor);
+    const spender = helper.eth.createAccount();
+    const collection = await helper.rft.mintCollection(alice);
+    const {tokenId} = await collection.mintToken(alice, 200n, {Ethereum: owner});
 
-    const collectionId = (await createCollection(api, alice, {name: 'token name', mode: {type: 'ReFungible'}})).collectionId;
-
-    const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
-
-    const tokenId = (await createRefungibleToken(api, alice, collectionId, 200n, {Ethereum: owner})).itemId;
-
-    const address = tokenIdToAddress(collectionId, tokenId);
+    const tokenAddress = helper.ethAddress.fromTokenId(collection.collectionId, tokenId);
+    const contract = helper.ethNativeContract.rftToken(tokenAddress, owner);
 
-    const spender = createEthAccount(web3);
-
-    const contract = uniqueRefungibleToken(web3, address, owner);
-
     {
       const result = await contract.methods.approve(spender, 100).send({from: owner});
-      const events = normalizeEvents(result.events);
-
-      expect(events).to.be.deep.equal([
-        {
-          address,
-          event: 'Approval',
-          args: {
-            owner,
-            spender,
-            value: '100',
-          },
-        },
-      ]);
+      const event = result.events.Approval;
+      expect(event.address).to.be.equal(tokenAddress);
+      expect(event.returnValues.owner).to.be.equal(owner);
+      expect(event.returnValues.spender).to.be.equal(spender);
+      expect(event.returnValues.value).to.be.equal('100');
     }
 
     {
@@ -265,49 +164,31 @@
     }
   });
 
-  itWeb3('Can perform transferFrom()', async ({web3, api, privateKeyWrapper}) => {
-    const alice = privateKeyWrapper('//Alice');
-
-    const collectionId = (await createCollection(api, alice, {name: 'token name', mode: {type: 'ReFungible'}})).collectionId;
+  itEth('Can perform transferFrom()', async ({helper}) => {
+    const owner = await helper.eth.createAccountWithBalance(donor);
+    const spender = await helper.eth.createAccountWithBalance(donor);
+    const receiver = helper.eth.createAccount();
+    const collection = await helper.rft.mintCollection(alice);
+    const {tokenId} = await collection.mintToken(alice, 200n, {Ethereum: owner});
 
-    const owner = createEthAccount(web3);
-    await transferBalanceToEth(api, alice, owner);
-
-    const tokenId = (await createRefungibleToken(api, alice, collectionId, 200n, {Ethereum: owner})).itemId;
-
-    const spender = createEthAccount(web3);
-    await transferBalanceToEth(api, alice, spender);
+    const tokenAddress = helper.ethAddress.fromTokenId(collection.collectionId, tokenId);
+    const contract = helper.ethNativeContract.rftToken(tokenAddress, owner);
 
-    const receiver = createEthAccount(web3);
-
-    const address = tokenIdToAddress(collectionId, tokenId);
-    const contract = uniqueRefungibleToken(web3, address, owner);
-
     await contract.methods.approve(spender, 100).send();
 
     {
       const result = await contract.methods.transferFrom(owner, receiver, 49).send({from: spender});
-      const events = normalizeEvents(result.events);
-      expect(events).to.include.deep.members([
-        {
-          address,
-          event: 'Transfer',
-          args: {
-            from: owner,
-            to: receiver,
-            value: '49',
-          },
-        },
-        {
-          address,
-          event: 'Approval',
-          args: {
-            owner,
-            spender,
-            value: '51',
-          },
-        },
-      ]);
+      let event = result.events.Transfer;
+      expect(event.address).to.be.equal(tokenAddress);
+      expect(event.returnValues.from).to.be.equal(owner);
+      expect(event.returnValues.to).to.be.equal(receiver);
+      expect(event.returnValues.value).to.be.equal('49');
+
+      event = result.events.Approval;
+      expect(event.address).to.be.equal(tokenAddress);
+      expect(event.returnValues.owner).to.be.equal(owner);
+      expect(event.returnValues.spender).to.be.equal(spender);
+      expect(event.returnValues.value).to.be.equal('51');
     }
 
     {
@@ -321,36 +202,22 @@
     }
   });
 
-  itWeb3('Can perform transfer()', async ({web3, api, privateKeyWrapper}) => {
-    const alice = privateKeyWrapper('//Alice');
+  itEth('Can perform transfer()', async ({helper}) => {
+    const owner = await helper.eth.createAccountWithBalance(donor);
+    const receiver = helper.eth.createAccount();
+    const collection = await helper.rft.mintCollection(alice);
+    const {tokenId} = await collection.mintToken(alice, 200n, {Ethereum: owner});
 
-    const collectionId = (await createCollection(api, alice, {name: 'token name', mode: {type: 'ReFungible'}})).collectionId;
-
-    const owner = createEthAccount(web3);
-    await transferBalanceToEth(api, alice, owner);
-
-    const tokenId = (await createRefungibleToken(api, alice, collectionId, 200n, {Ethereum: owner})).itemId;
-
-    const receiver = createEthAccount(web3);
-    await transferBalanceToEth(api, alice, receiver);
-
-    const address = tokenIdToAddress(collectionId, tokenId);
-    const contract = uniqueRefungibleToken(web3, address, owner);
+    const tokenAddress = helper.ethAddress.fromTokenId(collection.collectionId, tokenId);
+    const contract = helper.ethNativeContract.rftToken(tokenAddress, owner);
 
     {
       const result = await contract.methods.transfer(receiver, 50).send({from: owner});
-      const events = normalizeEvents(result.events);
-      expect(events).to.include.deep.members([
-        {
-          address,
-          event: 'Transfer',
-          args: {
-            from: owner,
-            to: receiver,
-            value: '50',
-          },
-        },
-      ]);
+      const event = result.events.Transfer;
+      expect(event.address).to.be.equal(tokenAddress);
+      expect(event.returnValues.from).to.be.equal(owner);
+      expect(event.returnValues.to).to.be.equal(receiver);
+      expect(event.returnValues.value).to.be.equal('50');
     }
 
     {
@@ -364,311 +231,262 @@
     }
   });
 
-  itWeb3('Can perform repartition()', async ({web3, api, privateKeyWrapper}) => {
-    const alice = privateKeyWrapper('//Alice');
-
-    const collectionId = (await createCollection(api, alice, {name: 'token name', mode: {type: 'ReFungible'}})).collectionId;
+  itEth('Can perform repartition()', async ({helper}) => {
+    const owner = await helper.eth.createAccountWithBalance(donor);
+    const receiver = await helper.eth.createAccountWithBalance(donor);
+    const collection = await helper.rft.mintCollection(alice);
+    const {tokenId} = await collection.mintToken(alice, 100n, {Ethereum: owner});
 
-    const owner = createEthAccount(web3);
-    await transferBalanceToEth(api, alice, owner);
+    const tokenAddress = helper.ethAddress.fromTokenId(collection.collectionId, tokenId);
+    const contract = helper.ethNativeContract.rftToken(tokenAddress, owner);
 
-    const receiver = createEthAccount(web3);
-    await transferBalanceToEth(api, alice, receiver);
-
-    const tokenId = (await createRefungibleToken(api, alice, collectionId, 100n, {Ethereum: owner})).itemId;
-
-    const address = tokenIdToAddress(collectionId, tokenId);
-    const contract = uniqueRefungibleToken(web3, address, owner);
-
     await contract.methods.repartition(200).send({from: owner});
     expect(+await contract.methods.balanceOf(owner).call()).to.be.equal(200);
     await contract.methods.transfer(receiver, 110).send({from: owner});
     expect(+await contract.methods.balanceOf(owner).call()).to.be.equal(90);
     expect(+await contract.methods.balanceOf(receiver).call()).to.be.equal(110);
 
-    await expect(contract.methods.repartition(80).send({from: owner})).to.eventually.be.rejected;
+    await expect(contract.methods.repartition(80).send({from: owner})).to.eventually.be.rejected; // Transaction is reverted
 
     await contract.methods.transfer(receiver, 90).send({from: owner});
     expect(+await contract.methods.balanceOf(owner).call()).to.be.equal(0);
     expect(+await contract.methods.balanceOf(receiver).call()).to.be.equal(200);
 
     await contract.methods.repartition(150).send({from: receiver});
-    await expect(contract.methods.transfer(owner, 160).send({from: receiver})).to.eventually.be.rejected;
+    await expect(contract.methods.transfer(owner, 160).send({from: receiver})).to.eventually.be.rejected; // Transaction is reverted
     expect(+await contract.methods.balanceOf(receiver).call()).to.be.equal(150);
   });
 
-  itWeb3('Can repartition with increased amount', async ({web3, api, privateKeyWrapper}) => {
-    const alice = privateKeyWrapper('//Alice');
-
-    const collectionId = (await createCollection(api, alice, {name: 'token name', mode: {type: 'ReFungible'}})).collectionId;
-
-    const owner = createEthAccount(web3);
-    await transferBalanceToEth(api, alice, owner);
-
-    const tokenId = (await createRefungibleToken(api, alice, collectionId, 100n, {Ethereum: owner})).itemId;
+  itEth('Can repartition with increased amount', async ({helper}) => {
+    const owner = await helper.eth.createAccountWithBalance(donor);
+    const collection = await helper.rft.mintCollection(alice);
+    const {tokenId} = await collection.mintToken(alice, 100n, {Ethereum: owner});
 
-    const address = tokenIdToAddress(collectionId, tokenId);
-    const contract = uniqueRefungibleToken(web3, address, owner);
+    const tokenAddress = helper.ethAddress.fromTokenId(collection.collectionId, tokenId);
+    const contract = helper.ethNativeContract.rftToken(tokenAddress, owner);
 
     const result = await contract.methods.repartition(200).send();
-    const events = normalizeEvents(result.events);
 
-    expect(events).to.deep.equal([
-      {
-        address,
-        event: 'Transfer',
-        args: {
-          from: '0x0000000000000000000000000000000000000000',
-          to: owner,
-          value: '100',
-        },
-      },
-    ]);
+    const event = result.events.Transfer;
+    expect(event.address).to.be.equal(tokenAddress);
+    expect(event.returnValues.from).to.be.equal('0x0000000000000000000000000000000000000000');
+    expect(event.returnValues.to).to.be.equal(owner);
+    expect(event.returnValues.value).to.be.equal('100');
   });
 
-  itWeb3('Can repartition with decreased amount', async ({web3, api, privateKeyWrapper}) => {
-    const alice = privateKeyWrapper('//Alice');
+  itEth('Can repartition with decreased amount', async ({helper}) => {
+    const owner = await helper.eth.createAccountWithBalance(donor);
+    const collection = await helper.rft.mintCollection(alice);
+    const {tokenId} = await collection.mintToken(alice, 100n, {Ethereum: owner});
 
-    const collectionId = (await createCollection(api, alice, {name: 'token name', mode: {type: 'ReFungible'}})).collectionId;
-
-    const owner = createEthAccount(web3);
-    await transferBalanceToEth(api, alice, owner);
-
-    const tokenId = (await createRefungibleToken(api, alice, collectionId, 100n, {Ethereum: owner})).itemId;
-
-    const address = tokenIdToAddress(collectionId, tokenId);
-    const contract = uniqueRefungibleToken(web3, address, owner);
+    const tokenAddress = helper.ethAddress.fromTokenId(collection.collectionId, tokenId);
+    const contract = helper.ethNativeContract.rftToken(tokenAddress, owner);
 
     const result = await contract.methods.repartition(50).send();
-    const events = normalizeEvents(result.events);
-    expect(events).to.deep.equal([
-      {
-        address,
-        event: 'Transfer',
-        args: {
-          from: owner,
-          to: '0x0000000000000000000000000000000000000000',
-          value: '50',
-        },
-      },
-    ]);
+    const event = result.events.Transfer;
+    expect(event.address).to.be.equal(tokenAddress);
+    expect(event.returnValues.from).to.be.equal(owner);
+    expect(event.returnValues.to).to.be.equal('0x0000000000000000000000000000000000000000');
+    expect(event.returnValues.value).to.be.equal('50');
   });
 
-  itWeb3('Receiving Transfer event on burning into full ownership', async ({web3, api, privateKeyWrapper}) => {
-    const caller = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
-    const receiver = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
-    const helper = evmCollectionHelpers(web3, caller);
-    const result = await helper.methods.createRFTCollection('Mint collection', '6', '6').send();
-    const {collectionIdAddress, collectionId} = await getCollectionAddressFromResult(api, result);
-    const contract = evmCollection(web3, caller, collectionIdAddress, {type: 'ReFungible'});
+  itEth('Receiving Transfer event on burning into full ownership', async ({helper}) => {
+    const caller = await helper.eth.createAccountWithBalance(donor);
+    const receiver = await helper.eth.createAccountWithBalance(donor);
+    const {collectionId, collectionAddress} = await helper.eth.createRefungibleCollection(caller, 'Devastation', '6', '6');
+    const contract = helper.ethNativeContract.collection(collectionAddress, 'rft', caller);
 
     const tokenId = await contract.methods.nextTokenId().call();
     await contract.methods.mint(caller, tokenId).send();
+    const tokenAddress = helper.ethAddress.fromTokenId(collectionId, tokenId);
+    const tokenContract = helper.ethNativeContract.rftToken(tokenAddress, caller);
 
-    const address = tokenIdToAddress(collectionId, tokenId);
-
-    const tokenContract =  uniqueRefungibleToken(web3, address, caller);
     await tokenContract.methods.repartition(2).send();
     await tokenContract.methods.transfer(receiver, 1).send();
 
-    const events =  await recordEvents(contract, async () =>
-      await tokenContract.methods.burnFrom(caller, 1).send());
-    expect(events).to.deep.equal([
-      {
-        address: collectionIdAddress,
-        event: 'Transfer',
-        args: {
-          from: '0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF',
-          to: receiver,
-          tokenId,
-        },
-      },
-    ]);
+    const events: any = [];
+    contract.events.allEvents((_: any, event: any) => {
+      events.push(event);
+    });
+    await tokenContract.methods.burnFrom(caller, 1).send();
+
+    const event = events[0];
+    expect(event.address).to.be.equal(collectionAddress);
+    expect(event.returnValues.from).to.be.equal('0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF');
+    expect(event.returnValues.to).to.be.equal(receiver);
+    expect(event.returnValues.tokenId).to.be.equal(tokenId);
   });
 });
 
 describe('Refungible: Fees', () => {
+  let donor: IKeyringPair;
+  let alice: IKeyringPair;
+
   before(async function() {
-    await requirePallets(this, [Pallets.ReFungible]);
+    await usingEthPlaygrounds(async (helper, privateKey) => {
+      requirePalletsOrSkip(this, helper, [Pallets.ReFungible]);
+
+      donor = privateKey('//Alice');
+      [alice] = await helper.arrange.createAccounts([50n], donor);
+    });
   });
 
-  itWeb3('approve() call fee is less than 0.2UNQ', async ({web3, api, privateKeyWrapper}) => {
-    const alice = privateKeyWrapper('//Alice');
+  itEth('approve() call fee is less than 0.2UNQ', async ({helper}) => {
+    const owner = await helper.eth.createAccountWithBalance(donor);
+    const spender = helper.eth.createAccount();
+    const collection = await helper.rft.mintCollection(alice);
+    const {tokenId} = await collection.mintToken(alice, 100n, {Ethereum: owner});
 
-    const collectionId = (await createCollection(api, alice, {mode: {type: 'ReFungible'}})).collectionId;
+    const tokenAddress = helper.ethAddress.fromTokenId(collection.collectionId, tokenId);
+    const contract = helper.ethNativeContract.rftToken(tokenAddress, owner);
 
-    const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
-    const spender = createEthAccount(web3);
-
-    const tokenId = (await createRefungibleToken(api, alice, collectionId, 200n, {Ethereum: owner})).itemId;
-
-    const address = tokenIdToAddress(collectionId, tokenId);
-    const contract = uniqueRefungibleToken(web3, address, owner);
-
-    const cost = await recordEthFee(api, owner, () => contract.methods.approve(spender, 100).send({from: owner}));
-    expect(cost < BigInt(0.2 * Number(UNIQUE)));
+    const cost = await helper.eth.recordCallFee(owner, () => contract.methods.approve(spender, 100).send({from: owner}));
+    expect(cost < BigInt(0.2 * Number(helper.balance.getOneTokenNominal())));
   });
 
-  itWeb3('transferFrom() call fee is less than 0.2UNQ', async ({web3, api, privateKeyWrapper}) => {
-    const alice = privateKeyWrapper('//Alice');
-
-    const collectionId = (await createCollection(api, alice, {mode: {type: 'ReFungible'}})).collectionId;
-
-    const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
-    const spender = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
-
-    const tokenId = (await createRefungibleToken(api, alice, collectionId, 200n, {Ethereum: owner})).itemId;
+  itEth('transferFrom() call fee is less than 0.2UNQ', async ({helper}) => {
+    const owner = await helper.eth.createAccountWithBalance(donor);
+    const spender = await helper.eth.createAccountWithBalance(donor);
+    const collection = await helper.rft.mintCollection(alice);
+    const {tokenId} = await collection.mintToken(alice, 200n, {Ethereum: owner});
 
-    const address = tokenIdToAddress(collectionId, tokenId);
-    const contract = uniqueRefungibleToken(web3, address, owner);
+    const tokenAddress = helper.ethAddress.fromTokenId(collection.collectionId, tokenId);
+    const contract = helper.ethNativeContract.rftToken(tokenAddress, owner);
 
     await contract.methods.approve(spender, 100).send({from: owner});
 
-    const cost = await recordEthFee(api, spender, () => contract.methods.transferFrom(owner, spender, 100).send({from: spender}));
-    expect(cost < BigInt(0.2 * Number(UNIQUE)));
+    const cost = await helper.eth.recordCallFee(spender, () => contract.methods.transferFrom(owner, spender, 100).send({from: spender}));
+    expect(cost < BigInt(0.2 * Number(helper.balance.getOneTokenNominal())));
   });
 
-  itWeb3('transfer() call fee is less than 0.2UNQ', async ({web3, api, privateKeyWrapper}) => {
-    const alice = privateKeyWrapper('//Alice');
+  itEth('transfer() call fee is less than 0.2UNQ', async ({helper}) => {
+    const owner = await helper.eth.createAccountWithBalance(donor);
+    const receiver = helper.eth.createAccount();
+    const collection = await helper.rft.mintCollection(alice);
+    const {tokenId} = await collection.mintToken(alice, 200n, {Ethereum: owner});
 
-    const collectionId = (await createCollection(api, alice, {mode: {type: 'ReFungible'}})).collectionId;
+    const tokenAddress = helper.ethAddress.fromTokenId(collection.collectionId, tokenId);
+    const contract = helper.ethNativeContract.rftToken(tokenAddress, owner);
 
-    const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
-    const receiver = createEthAccount(web3);
-
-    const tokenId = (await createRefungibleToken(api, alice, collectionId, 200n, {Ethereum: owner})).itemId;
-
-    const address = tokenIdToAddress(collectionId, tokenId);
-    const contract = uniqueRefungibleToken(web3, address, owner);
-
-    const cost = await recordEthFee(api, owner, () => contract.methods.transfer(receiver, 100).send({from: owner}));
-    expect(cost < BigInt(0.2 * Number(UNIQUE)));
+    const cost = await helper.eth.recordCallFee(owner, () => contract.methods.transfer(receiver, 100).send({from: owner}));
+    expect(cost < BigInt(0.2 * Number(helper.balance.getOneTokenNominal())));
   });
 });
 
 describe('Refungible: Substrate calls', () => {
+  let donor: IKeyringPair;
+  let alice: IKeyringPair;
+
   before(async function() {
-    await requirePallets(this, [Pallets.ReFungible]);
-  });
+    await usingEthPlaygrounds(async (helper, privateKey) => {
+      requirePalletsOrSkip(this, helper, [Pallets.ReFungible]);
 
-  itWeb3('Events emitted for approve()', async ({web3, api, privateKeyWrapper}) => {
-    const alice = privateKeyWrapper('//Alice');
-
-    const collectionId = (await createCollection(api, alice, {mode: {type: 'ReFungible'}})).collectionId;
-
-    const receiver = createEthAccount(web3);
+      donor = privateKey('//Alice');
+      [alice] = await helper.arrange.createAccounts([50n], donor);
+    });
+  });
 
-    const tokenId = (await createRefungibleToken(api, alice, collectionId, 200n)).itemId;
+  itEth('Events emitted for approve()', async ({helper}) => {
+    const receiver = helper.eth.createAccount();
+    const collection = await helper.rft.mintCollection(alice);
+    const token = await collection.mintToken(alice, 200n);
 
-    const address = tokenIdToAddress(collectionId, tokenId);
-    const contract = uniqueRefungibleToken(web3, address);
+    const tokenAddress = helper.ethAddress.fromTokenId(collection.collectionId, token.tokenId);
+    const contract = helper.ethNativeContract.rftToken(tokenAddress);
 
-    const events = await recordEvents(contract, async () => {
-      expect(await approve(api, collectionId, tokenId, alice, {Ethereum: receiver}, 100n)).to.be.true;
+    const events: any = [];
+    contract.events.allEvents((_: any, event: any) => {
+      events.push(event);
     });
+    expect(await token.approve(alice, {Ethereum: receiver}, 100n)).to.be.true;
 
-    expect(events).to.be.deep.equal([
-      {
-        address,
-        event: 'Approval',
-        args: {
-          owner: subToEth(alice.address),
-          spender: receiver,
-          value: '100',
-        },
-      },
-    ]);
+    const event = events[0];
+    expect(event.event).to.be.equal('Approval');
+    expect(event.address).to.be.equal(tokenAddress);
+    expect(event.returnValues.owner).to.be.equal(helper.address.substrateToEth(alice.address));
+    expect(event.returnValues.spender).to.be.equal(receiver);
+    expect(event.returnValues.value).to.be.equal('100');
   });
 
-  itWeb3('Events emitted for transferFrom()', async ({web3, api, privateKeyWrapper}) => {
-    const alice = privateKeyWrapper('//Alice');
+  itEth('Events emitted for transferFrom()', async ({helper}) => {
+    const [bob] = await helper.arrange.createAccounts([10n], donor);
+    const receiver = helper.eth.createAccount();
+    const collection = await helper.rft.mintCollection(alice);
+    const token = await collection.mintToken(alice, 200n);
+    await token.approve(alice, {Substrate: bob.address}, 100n);
 
-    const collectionId = (await createCollection(api, alice, {mode: {type: 'ReFungible'}})).collectionId;
-    const bob = privateKeyWrapper('//Bob');
+    const tokenAddress = helper.ethAddress.fromTokenId(collection.collectionId, token.tokenId);
+    const contract = helper.ethNativeContract.rftToken(tokenAddress);
 
-    const receiver = createEthAccount(web3);
+    const events: any = [];
+    contract.events.allEvents((_: any, event: any) => {
+      events.push(event);
+    });
 
-    const tokenId = (await createRefungibleToken(api, alice, collectionId, 200n)).itemId;
-    expect(await approve(api, collectionId, tokenId, alice, bob.address, 100n)).to.be.true;
+    expect(await token.transferFrom(bob, {Substrate: alice.address}, {Ethereum: receiver},  51n)).to.be.true;
 
-    const address = tokenIdToAddress(collectionId, tokenId);
-    const contract = uniqueRefungibleToken(web3, address);
+    let event = events[0];
+    expect(event.event).to.be.equal('Transfer');
+    expect(event.address).to.be.equal(tokenAddress);
+    expect(event.returnValues.from).to.be.equal(helper.address.substrateToEth(alice.address));
+    expect(event.returnValues.to).to.be.equal(receiver);
+    expect(event.returnValues.value).to.be.equal('51');
 
-    const events = await recordEvents(contract, async () => {
-      expect(await transferFrom(api, collectionId, tokenId, bob, alice, {Ethereum: receiver},  51n)).to.be.true;
-    });
-
-    expect(events).to.be.deep.equal([
-      {
-        address,
-        event: 'Transfer',
-        args: {
-          from: subToEth(alice.address),
-          to: receiver,
-          value: '51',
-        },
-      },
-      {
-        address,
-        event: 'Approval',
-        args: {
-          owner: subToEth(alice.address),
-          spender: subToEth(bob.address),
-          value: '49',
-        },
-      },
-    ]);
+    event = events[1];
+    expect(event.event).to.be.equal('Approval');
+    expect(event.address).to.be.equal(tokenAddress);
+    expect(event.returnValues.owner).to.be.equal(helper.address.substrateToEth(alice.address));
+    expect(event.returnValues.spender).to.be.equal(helper.address.substrateToEth(bob.address));
+    expect(event.returnValues.value).to.be.equal('49');
   });
 
-  itWeb3('Events emitted for transfer()', async ({web3, api, privateKeyWrapper}) => {
-    const alice = privateKeyWrapper('//Alice');
+  itEth('Events emitted for transfer()', async ({helper}) => {
+    const receiver = helper.eth.createAccount();
+    const collection = await helper.rft.mintCollection(alice);
+    const token = await collection.mintToken(alice, 200n);
 
-    const collectionId = (await createCollection(api, alice, {mode: {type: 'ReFungible'}})).collectionId;
+    const tokenAddress = helper.ethAddress.fromTokenId(collection.collectionId, token.tokenId);
+    const contract = helper.ethNativeContract.rftToken(tokenAddress);
 
-    const receiver = createEthAccount(web3);
-
-    const tokenId = (await createRefungibleToken(api, alice, collectionId, 200n)).itemId;
+    const events: any = [];
+    contract.events.allEvents((_: any, event: any) => {
+      events.push(event);
+    });
 
-    const address = tokenIdToAddress(collectionId, tokenId);
-    const contract = uniqueRefungibleToken(web3, address);
+    expect(await token.transfer(alice, {Ethereum: receiver},  51n)).to.be.true;
 
-    const events = await recordEvents(contract, async () => {
-      expect(await transfer(api, collectionId, tokenId, alice, {Ethereum: receiver},  51n)).to.be.true;
-    });
-
-    expect(events).to.be.deep.equal([
-      {
-        address,
-        event: 'Transfer',
-        args: {
-          from: subToEth(alice.address),
-          to: receiver,
-          value: '51',
-        },
-      },
-    ]);
+    const event = events[0];
+    expect(event.event).to.be.equal('Transfer');
+    expect(event.address).to.be.equal(tokenAddress);
+    expect(event.returnValues.from).to.be.equal(helper.address.substrateToEth(alice.address));
+    expect(event.returnValues.to).to.be.equal(receiver);
+    expect(event.returnValues.value).to.be.equal('51');
   });
 });
 
 describe('ERC 1633 implementation', () => {
+  let donor: IKeyringPair;
+
   before(async function() {
-    await requirePallets(this, [Pallets.ReFungible]);
-  });
+    await usingEthPlaygrounds(async (helper, privateKey) => {
+      requirePalletsOrSkip(this, helper, [Pallets.ReFungible]);
 
-  itWeb3('Default parent token address and id', async ({api, web3, privateKeyWrapper}) => {
-    const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
+      donor = privateKey('//Alice');
+    });
+  });
 
-    const {collectionIdAddress, collectionId} = await createRFTCollection(api, web3, owner);
-    const refungibleContract = uniqueRefungible(web3, collectionIdAddress, owner);
-    const refungibleTokenId = await refungibleContract.methods.nextTokenId().call();
-    await refungibleContract.methods.mint(owner, refungibleTokenId).send();
+  itEth('Default parent token address and id', async ({helper}) => {
+    const owner = await helper.eth.createAccountWithBalance(donor);
 
-    const rftTokenAddress = tokenIdToAddress(collectionId, refungibleTokenId);
-    const refungibleTokenContract = uniqueRefungibleToken(web3, rftTokenAddress, owner);
+    const {collectionId, collectionAddress} = await helper.eth.createRefungibleCollection(owner, 'Sands', '', 'GRAIN');
+    const collectionContract = helper.ethNativeContract.collection(collectionAddress, 'rft', owner);
+    
+    const tokenId = await collectionContract.methods.nextTokenId().call();
+    await collectionContract.methods.mint(owner, tokenId).send();
+    const tokenAddress = helper.ethAddress.fromTokenId(collectionId, tokenId);
+    const tokenContract = helper.ethNativeContract.rftToken(tokenAddress, owner);
 
-    const tokenAddress = await refungibleTokenContract.methods.parentToken().call();
-    const tokenId = await refungibleTokenContract.methods.parentTokenId().call();
-    expect(tokenAddress).to.be.equal(collectionIdAddress);
-    expect(tokenId).to.be.equal(refungibleTokenId);
+    expect(await tokenContract.methods.parentToken().call()).to.be.equal(collectionAddress);
+    expect(await tokenContract.methods.parentTokenId().call()).to.be.equal(tokenId);
   });
 });
modifiedtests/src/eth/util/playgrounds/index.tsdiffbeforeafterboth
--- a/tests/src/eth/util/playgrounds/index.ts
+++ b/tests/src/eth/util/playgrounds/index.ts
@@ -12,6 +12,7 @@
 
 import chai from 'chai';
 import chaiAsPromised from 'chai-as-promised';
+import {requirePalletsOrSkip} from '../../../util/playgrounds';
 chai.use(chaiAsPromised);
 export const expect = chai.expect;
 
@@ -35,15 +36,26 @@
   }
 };
   
-export async function itEth(name: string, cb: (apis: { helper: EthUniqueHelper, privateKey: (seed: string) => IKeyringPair }) => any, opts: { only?: boolean, skip?: boolean } = {}) {
-  let i: any = it;
-  if (opts.only) i = i.only;
-  else if (opts.skip) i = i.skip;
-  i(name, async () => {
+export async function itEth(name: string, cb: (apis: { helper: EthUniqueHelper, privateKey: (seed: string) => IKeyringPair }) => any, opts: { only?: boolean, skip?: boolean, requiredPallets?: string[] } = {}) {
+  (opts.only ? it.only : 
+    opts.skip ? it.skip : it)(name, async function() {
     await usingEthPlaygrounds(async (helper, privateKey) => {
+      if (opts.requiredPallets) {
+        requirePalletsOrSkip(this, helper, opts.requiredPallets);
+      }
+
       await cb({helper, privateKey});
     });
   });
 }
+
+export async function itEthIfWithPallet(name: string, required: string[], cb: (apis: { helper: EthUniqueHelper, privateKey: (seed: string) => IKeyringPair }) => any, opts: { only?: boolean, skip?: boolean, requiredPallets?: string[] } = {}) {
+  return itEth(name, cb, {requiredPallets: required, ...opts});
+}
+
 itEth.only = (name: string, cb: (apis: { helper: EthUniqueHelper, privateKey: (seed: string) => IKeyringPair }) => any) => itEth(name, cb, {only: true});
-itEth.skip = (name: string, cb: (apis: { helper: EthUniqueHelper, privateKey: (seed: string) => IKeyringPair }) => any) => itEth(name, cb, {skip: true});
\ No newline at end of file
+itEth.skip = (name: string, cb: (apis: { helper: EthUniqueHelper, privateKey: (seed: string) => IKeyringPair }) => any) => itEth(name, cb, {skip: true});
+
+itEthIfWithPallet.only = (name: string, required: string[], cb: (apis: { helper: EthUniqueHelper, privateKey: (seed: string) => IKeyringPair }) => any) => itEthIfWithPallet(name, required, cb, {only: true});
+itEthIfWithPallet.skip = (name: string, required: string[], cb: (apis: { helper: EthUniqueHelper, privateKey: (seed: string) => IKeyringPair }) => any) => itEthIfWithPallet(name, required, cb, {skip: true});
+itEth.ifWithPallets = itEthIfWithPallet;
modifiedtests/src/eth/util/playgrounds/unique.dev.tsdiffbeforeafterboth
--- a/tests/src/eth/util/playgrounds/unique.dev.ts
+++ b/tests/src/eth/util/playgrounds/unique.dev.ts
@@ -27,6 +27,7 @@
 import refungibleAbi from '../../reFungibleAbi.json';
 import refungibleTokenAbi from '../../reFungibleTokenAbi.json';
 import contractHelpersAbi from './../contractHelpersAbi.json';
+import {TEthereumAccount} from '../../../util/playgrounds/types';
 
 class EthGroupBase {
   helper: EthUniqueHelper;
@@ -43,13 +44,13 @@
       return {error: `File not found: ${path}`};
     };
   
-    const knownImports = {} as any;
+    const knownImports = {} as {[key: string]: string};
     for(const imp of imports) {
       knownImports[imp.solPath] = (await readFile(imp.fsPath)).toString();
     }
   
     return function(path: string) {
-      if(knownImports.hasOwnPropertyDescriptor(path)) return {contents: knownImports[path]};
+      if(path in knownImports) return {contents: knownImports[path]};
       return {error: `File not found: ${path}`};
     };
   }
@@ -116,13 +117,17 @@
     return new web3.eth.Contract(abi as any, address, {gas: this.helper.eth.DEFAULT_GAS, ...(caller ? {from: caller} : {})});
   }
 
-  rftTokenByAddress(address: string, caller?: string): Contract {
+  collectionById(collectionId: number, mode: 'nft' | 'rft' | 'ft', caller?: string): Contract {
+    return this.collection(this.helper.ethAddress.fromCollectionId(collectionId), mode, caller);
+  }
+
+  rftToken(address: string, caller?: string): Contract {
     const web3 = this.helper.getWeb3();
     return new web3.eth.Contract(refungibleTokenAbi as any, address, {gas: this.helper.eth.DEFAULT_GAS, ...(caller ? {from: caller} : {})});
   }
 
-  rftToken(collectionId: number, tokenId: number, caller?: string): Contract {
-    return this.rftTokenByAddress(this.helper.ethAddress.fromTokenId(collectionId, tokenId), caller);
+  rftTokenById(collectionId: number, tokenId: number, caller?: string): Contract {
+    return this.rftToken(this.helper.ethAddress.fromTokenId(collectionId, tokenId), caller);
   }
 }
 
@@ -148,7 +153,7 @@
     return await this.helper.balance.transferToSubstrate(donor, evmToAddress(recepient), amount * (inTokens ? this.helper.balance.getOneTokenNominal() : 1n));
   }
 
-  async callEVM(signer: IKeyringPair, contractAddress: string, abi: any, value: string, gasLimit?: number) {
+  async sendEVM(signer: IKeyringPair, contractAddress: string, abi: string, value: string, gasLimit?: number) {
     if(!gasLimit) gasLimit = this.DEFAULT_GAS;
     const web3 = this.helper.getWeb3();
     const gasPrice = await web3.eth.getGasPrice();
@@ -159,6 +164,10 @@
       true,
     );
   }
+  
+  async callEVM(signer: TEthereumAccount, contractAddress: string, abi: string) {
+    return await this.helper.callRpc('api.rpc.eth.call', [{from: signer, to: contractAddress, data: abi}]);
+  }
 
   async createNonfungibleCollection(signer: string, name: string, description: string, tokenPrefix: string): Promise<{collectionId: number, collectionAddress: string}> {
     const collectionHelper = this.helper.ethNativeContract.collectionHelpers(signer);
@@ -171,6 +180,17 @@
     return {collectionId, collectionAddress};
   }
 
+  async createRefungibleCollection(signer: string, name: string, description: string, tokenPrefix: string): Promise<{collectionId: number, collectionAddress: string}> {
+    const collectionHelper = this.helper.ethNativeContract.collectionHelpers(signer);
+        
+    const result = await collectionHelper.methods.createRFTCollection(name, description, tokenPrefix).send();
+
+    const collectionAddress = this.helper.ethAddress.normalizeAddress(result.events.CollectionCreated.returnValues.collectionId);
+    const collectionId = this.helper.ethAddress.extractCollectionId(collectionAddress);
+
+    return {collectionId, collectionAddress};
+  }
+
   async deployCollectorContract(signer: string): Promise<Contract> {
     return await this.helper.ethContract.deployByCode(signer, 'Collector', `
     // SPDX-License-Identifier: UNLICENSED
@@ -215,6 +235,16 @@
     }
   `);
   }
+
+  async recordCallFee(user: string, call: () => Promise<any>): Promise<bigint> {
+    const before = await this.helper.balance.getEthereum(user);
+    await call();
+    // In dev mode, the transaction might not finish processing in time
+    await this.helper.wait.newBlocks(1);
+    const after = await this.helper.balance.getEthereum(user);
+
+    return before - after;
+  }
 }  
   
 class EthAddressGroup extends EthGroupBase {
@@ -240,7 +270,7 @@
   }
 
   fromTokenId(collectionId: number, tokenId: number): string  {
-    return this.helper.util.getNestingTokenAddress(collectionId, tokenId);
+    return this.helper.util.getTokenAddress({collectionId, tokenId});
   }
 
   normalizeAddress(address: string): string {
modifiedtests/src/nesting/graphs.test.tsdiffbeforeafterboth
--- a/tests/src/nesting/graphs.test.ts
+++ b/tests/src/nesting/graphs.test.ts
@@ -1,9 +1,22 @@
-import {ApiPromise} from '@polkadot/api';
+// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.
+// This file is part of Unique Network.
+
+// Unique Network is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+
+// Unique Network is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+// GNU General Public License for more details.
+
+// You should have received a copy of the GNU General Public License
+// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
+
 import {IKeyringPair} from '@polkadot/types/types';
-import {expect} from 'chai';
-import {tokenIdToCross} from '../eth/util/helpers';
-import usingApi, {executeTransaction} from '../substrate/substrate-api';
-import {getCreateCollectionResult, transferExpectSuccess, setCollectionLimitsExpectSuccess} from '../util/helpers';
+import {expect, itSub, usingPlaygrounds} from '../util/playgrounds';
+import {UniqueHelper, UniqueNFToken} from '../util/playgrounds/unique';
 
 /**
  * ```dot
@@ -12,46 +25,47 @@
  * 8 -> 5
  * ```
  */
-async function buildComplexObjectGraph(api: ApiPromise, sender: IKeyringPair): Promise<number> {
-  const events = await executeTransaction(api, sender, api.tx.unique.createCollectionEx({mode: 'NFT', permissions: {nesting: {tokenOwner: true}}}));
-  const {collectionId} = getCreateCollectionResult(events);
+async function buildComplexObjectGraph(helper: UniqueHelper, sender: IKeyringPair): Promise<UniqueNFToken[]> {
+  const collection = await helper.nft.mintCollection(sender, {permissions: {nesting: {tokenOwner: true}}});
+  const tokens = await collection.mintMultipleTokens(sender, Array(8).fill({owner: {Substrate: sender.address}}));
 
-  await executeTransaction(api, sender, api.tx.unique.createMultipleItemsEx(collectionId, {NFT: Array(8).fill({owner: {Substrate: sender.address}})}));
-
-  await transferExpectSuccess(collectionId, 8, sender, tokenIdToCross(collectionId, 5));
-
-  await transferExpectSuccess(collectionId, 7, sender, tokenIdToCross(collectionId, 6));
-  await transferExpectSuccess(collectionId, 6, sender, tokenIdToCross(collectionId, 5));
-  await transferExpectSuccess(collectionId, 5, sender, tokenIdToCross(collectionId, 2));
+  await tokens[7].nest(sender, tokens[4]);
+  await tokens[6].nest(sender, tokens[5]);
+  await tokens[5].nest(sender, tokens[4]);
+  await tokens[4].nest(sender, tokens[1]);
+  await tokens[3].nest(sender, tokens[2]);
+  await tokens[2].nest(sender, tokens[1]);
+  await tokens[1].nest(sender, tokens[0]);
 
-  await transferExpectSuccess(collectionId, 4, sender, tokenIdToCross(collectionId, 3));
-  await transferExpectSuccess(collectionId, 3, sender, tokenIdToCross(collectionId, 2));
-  await transferExpectSuccess(collectionId, 2, sender, tokenIdToCross(collectionId, 1));
-
-  return collectionId;
+  return tokens;
 }
 
 describe('Graphs', () => {
-  it('Ouroboros can\'t be created in a complex graph', async () => {
-    await usingApi(async (api, privateKeyWrapper) => {
-      const alice = privateKeyWrapper('//Alice');
-      const collection = await buildComplexObjectGraph(api, alice);
-      const tokenTwoParent = tokenIdToCross(collection, 1);
+  let alice: IKeyringPair;
 
-      // to self
-      await expect(
-        executeTransaction(api, alice, api.tx.unique.transfer(tokenIdToCross(collection, 1), collection, 1, 1)),
-        'first transaction',  
-      ).to.be.rejectedWith(/structure\.OuroborosDetected/);
-      // to nested part of graph
-      await expect(
-        executeTransaction(api, alice, api.tx.unique.transfer(tokenIdToCross(collection, 5), collection, 1, 1)),
-        'second transaction',
-      ).to.be.rejectedWith(/structure\.OuroborosDetected/);
-      await expect(
-        executeTransaction(api, alice, api.tx.unique.transferFrom(tokenTwoParent, tokenIdToCross(collection, 8), collection, 2, 1)),
-        'third transaction',
-      ).to.be.rejectedWith(/structure\.OuroborosDetected/);
+  before(async () => {
+    await usingPlaygrounds(async (helper, privateKey) => {
+      const donor = privateKey('//Alice');
+      [alice] = await helper.arrange.createAccounts([10n], donor);
     });
   });
+
+  itSub('Ouroboros can\'t be created in a complex graph', async ({helper}) => {
+    const tokens = await buildComplexObjectGraph(helper, alice);
+
+    // to self
+    await expect(
+      tokens[0].nest(alice, tokens[0]),
+      'first transaction',  
+    ).to.be.rejectedWith(/structure\.OuroborosDetected/);
+    // to nested part of graph
+    await expect(
+      tokens[0].nest(alice, tokens[4]),
+      'second transaction',
+    ).to.be.rejectedWith(/structure\.OuroborosDetected/);
+    await expect(
+      tokens[1].transferFrom(alice, tokens[0].nestingAccount(), tokens[7].nestingAccount()),
+      'third transaction',
+    ).to.be.rejectedWith(/structure\.OuroborosDetected/);
+  });
 });
modifiedtests/src/nesting/migration-check.test.tsdiffbeforeafterboth
--- a/tests/src/nesting/migration-check.test.ts
+++ b/tests/src/nesting/migration-check.test.ts
@@ -8,7 +8,8 @@
 import find from 'find-process';
 
 // todo un-skip for migrations
-describe.skip('Migration testing', () => {
+// todo:playgrounds skipped, this one is outdated. Probably to be deleted/replaced.
+describe.skip('Migration testing: Properties', () => {
   let alice: IKeyringPair;
 
   before(async() => {
modifiedtests/src/nesting/nest.test.tsdiffbeforeafterboth
--- a/tests/src/nesting/nest.test.ts
+++ b/tests/src/nesting/nest.test.ts
@@ -1,840 +1,667 @@
-import {expect} from 'chai';
-import {tokenIdToAddress} from '../eth/util/helpers';
-import usingApi, {executeTransaction} from '../substrate/substrate-api';
-import {
-  addCollectionAdminExpectSuccess,
-  addToAllowListExpectSuccess,
-  createCollectionExpectSuccess,
-  createItemExpectSuccess,
-  enableAllowListExpectSuccess,
-  enablePublicMintingExpectSuccess,
-  getTokenChildren,
-  getTokenOwner,
-  getTopmostTokenOwner,
-  normalizeAccountId,
-  setCollectionPermissionsExpectSuccess,
-  transferExpectFailure,
-  transferExpectSuccess,
-  transferFromExpectSuccess,
-  setCollectionLimitsExpectSuccess,
-  requirePallets,
-  Pallets,
-} from '../util/helpers';
-import {IKeyringPair} from '@polkadot/types/types';
+// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.
+// This file is part of Unique Network.
+
+// Unique Network is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
 
-let alice: IKeyringPair;
-let bob: IKeyringPair;
-let charlie: IKeyringPair;
+// Unique Network is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+// GNU General Public License for more details.
 
+// You should have received a copy of the GNU General Public License
+// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
+
+import {IKeyringPair} from '@polkadot/types/types';
+import {expect, itSub, Pallets, usingPlaygrounds} from '../util/playgrounds';
+
 describe('Integration Test: Composite nesting tests', () => {
+  let alice: IKeyringPair;
+  let bob: IKeyringPair;
+
   before(async () => {
-    await usingApi(async (_, privateKeyWrapper) => {
-      alice = privateKeyWrapper('//Alice');
-      bob = privateKeyWrapper('//Bob');
+    await usingPlaygrounds(async (helper, privateKey) => {
+      const donor = privateKey('//Alice');
+      [alice, bob] = await helper.arrange.createAccounts([50n, 10n], donor);
     });
   });
 
-  it('Performs the full suite: bundles a token, transfers, and unnests', async () => {
-    await usingApi(async api => {
-      const collection = await createCollectionExpectSuccess({mode: {type: 'NFT'}});
-      await setCollectionPermissionsExpectSuccess(alice, collection, {nesting: {tokenOwner: true}});
-      const targetToken = await createItemExpectSuccess(alice, collection, 'NFT');
+  itSub('Performs the full suite: bundles a token, transfers, and unnests', async ({helper}) => {
+    const collection = await helper.nft.mintCollection(alice, {permissions: {nesting: {tokenOwner: true}}});
+    const targetToken = await collection.mintToken(alice);
 
-      // Create a nested token
-      const nestedToken = await createItemExpectSuccess(alice, collection, 'NFT', {Ethereum: tokenIdToAddress(collection, targetToken)});
-      expect(await getTopmostTokenOwner(api, collection, nestedToken)).to.be.deep.equal({Substrate: alice.address});
-      expect(await getTokenOwner(api, collection, nestedToken)).to.be.deep.equal({Ethereum: tokenIdToAddress(collection, targetToken).toLowerCase()});
+    // Create an immediately nested token
+    const nestedToken = await collection.mintToken(alice, targetToken.nestingAccount());
+    expect(await nestedToken.getTopmostOwner()).to.be.deep.equal({Substrate: alice.address});
+    expect(await nestedToken.getOwner()).to.be.deep.equal(targetToken.nestingAccount().toLowerCase());
+    
+    // Create a token to be nested
+    const newToken = await collection.mintToken(alice);
 
-      // Create a token to be nested
-      const newToken = await createItemExpectSuccess(alice, collection, 'NFT');
-
-      // Nest
-      await transferExpectSuccess(collection, newToken, alice, {Ethereum: tokenIdToAddress(collection, targetToken)});
-      expect(await getTopmostTokenOwner(api, collection, newToken)).to.be.deep.equal({Substrate: alice.address});
-      expect(await getTokenOwner(api, collection, newToken)).to.be.deep.equal({Ethereum: tokenIdToAddress(collection, targetToken).toLowerCase()});
+    // Nest
+    await newToken.nest(alice, targetToken);
+    expect(await newToken.getTopmostOwner()).to.be.deep.equal({Substrate: alice.address});
+    expect(await newToken.getOwner()).to.be.deep.equal(targetToken.nestingAccount().toLowerCase());
 
-      // Move bundle to different user
-      await transferExpectSuccess(collection, targetToken, alice, {Substrate: bob.address});
-      expect(await getTopmostTokenOwner(api, collection, nestedToken)).to.be.deep.equal({Substrate: bob.address});
-      expect(await getTokenOwner(api, collection, nestedToken)).to.be.deep.equal({Ethereum: tokenIdToAddress(collection, targetToken).toLowerCase()});
+    // Move bundle to different user
+    await targetToken.transfer(alice, {Substrate: bob.address});
+    expect(await nestedToken.getTopmostOwner()).to.be.deep.equal({Substrate: bob.address});
+    expect(await nestedToken.getOwner()).to.be.deep.equal(targetToken.nestingAccount().toLowerCase());
+    expect(await newToken.getTopmostOwner()).to.be.deep.equal({Substrate: bob.address});
+    expect(await newToken.getOwner()).to.be.deep.equal(targetToken.nestingAccount().toLowerCase());
 
-      // Unnest
-      await transferFromExpectSuccess(collection, newToken, bob, {Ethereum: tokenIdToAddress(collection, targetToken)}, {Substrate: bob.address});
-      expect(await getTokenOwner(api, collection, newToken)).to.be.deep.equal({Substrate: bob.address});
-    });
+    // Unnest
+    await newToken.unnest(bob, targetToken, {Substrate: bob.address});
+    expect(await newToken.getTopmostOwner()).to.be.deep.equal({Substrate: bob.address});
+    expect(await newToken.getOwner()).to.be.deep.equal({Substrate: bob.address});
   });
-
-  it('Transfers an already bundled token', async () => {
-    await usingApi(async api => {
-      const collection = await createCollectionExpectSuccess({mode: {type: 'NFT'}});
-      await setCollectionPermissionsExpectSuccess(alice, collection, {nesting: {tokenOwner: true}});
 
-      const tokenA = await createItemExpectSuccess(alice, collection, 'NFT');
-      const tokenB = await createItemExpectSuccess(alice, collection, 'NFT');
-
-      // Create a nested token
-      const tokenC = await createItemExpectSuccess(alice, collection, 'NFT', {Ethereum: tokenIdToAddress(collection, tokenA)});
-      expect(await getTopmostTokenOwner(api, collection, tokenC)).to.be.deep.equal({Substrate: alice.address});
-      expect(await getTokenOwner(api, collection, tokenC)).to.be.deep.equal({Ethereum: tokenIdToAddress(collection, tokenA).toLowerCase()});
+  itSub('Transfers an already bundled token', async ({helper}) => {
+    const collection = await helper.nft.mintCollection(alice, {permissions: {nesting: {tokenOwner: true}}});
+    const tokenA = await collection.mintToken(alice);
+    const tokenB = await collection.mintToken(alice);
 
-      // Transfer the nested token to another token
-      await expect(executeTransaction(
-        api,
-        alice,
-        api.tx.unique.transferFrom(
-          normalizeAccountId({Ethereum: tokenIdToAddress(collection, tokenA)}),
-          normalizeAccountId({Ethereum: tokenIdToAddress(collection, tokenB)}),
-          collection,
-          tokenC,
-          1,
-        ),
-      )).to.not.be.rejected;
-      expect(await getTopmostTokenOwner(api, collection, tokenC)).to.be.deep.equal({Substrate: alice.address});
-      expect(await getTokenOwner(api, collection, tokenC)).to.be.deep.equal({Ethereum: tokenIdToAddress(collection, tokenB).toLowerCase()});
-    });
+    // Create a nested token
+    const tokenC = await collection.mintToken(alice, tokenA.nestingAccount());
+    expect(await tokenC.getOwner()).to.be.deep.equal(tokenA.nestingAccount().toLowerCase());
+    
+    // Transfer the nested token to another token
+    await expect(tokenC.transferFrom(alice, tokenA.nestingAccount(), tokenB.nestingAccount())).to.be.fulfilled;
+    expect(await tokenC.getTopmostOwner()).to.be.deep.equal({Substrate: alice.address});
+    expect(await tokenC.getOwner()).to.be.deep.equal(tokenB.nestingAccount().toLowerCase());
   });
 
-  it('Checks token children', async () => {
-    await usingApi(async api => {
-      const collectionA = await createCollectionExpectSuccess({mode: {type: 'NFT'}});
-      await setCollectionLimitsExpectSuccess(alice, collectionA, {ownerCanTransfer: true});
-      await setCollectionPermissionsExpectSuccess(alice, collectionA, {nesting: {tokenOwner: true}});
-      const collectionB = await createCollectionExpectSuccess({mode: {type: 'Fungible', decimalPoints: 0}});
+  itSub('Checks token children', async ({helper}) => {
+    const collectionA = await helper.nft.mintCollection(alice, {permissions: {nesting: {tokenOwner: true}}});
+    const collectionB = await helper.ft.mintCollection(alice);
+    
+    const targetToken = await collectionA.mintToken(alice);
+    expect((await targetToken.getChildren()).length).to.be.equal(0, 'Children length check at creation');
 
-      const targetToken = await createItemExpectSuccess(alice, collectionA, 'NFT');
-      const targetAddress = {Ethereum: tokenIdToAddress(collectionA, targetToken)};
-      let children = await getTokenChildren(api, collectionA, targetToken);
-      expect(children.length).to.be.equal(0, 'Children length check at creation');
+    // Create a nested NFT token
+    const tokenA = await collectionA.mintToken(alice, targetToken.nestingAccount());
+    expect(await targetToken.getChildren()).to.have.deep.members([
+      {tokenId: tokenA.tokenId, collectionId: collectionA.collectionId},
+    ], 'Children contents check at nesting #1').and.be.length(1, 'Children length check at nesting #1');
 
-      // Create a nested NFT token
-      const tokenA = await createItemExpectSuccess(alice, collectionA, 'NFT', targetAddress);
-      children = await getTokenChildren(api, collectionA, targetToken);
-      expect(children.length).to.be.equal(1, 'Children length check at nesting #1');
-      expect(children).to.have.deep.members([
-        {token: tokenA, collection: collectionA},
-      ], 'Children contents check at nesting #1');
+    // Create then nest
+    const tokenB = await collectionA.mintToken(alice);
+    await tokenB.nest(alice, targetToken);
+    expect(await targetToken.getChildren()).to.have.deep.members([
+      {tokenId: tokenA.tokenId, collectionId: collectionA.collectionId},
+      {tokenId: tokenB.tokenId, collectionId: collectionA.collectionId},
+    ], 'Children contents check at nesting #2').and.be.length(2, 'Children length check at nesting #2');
 
-      // Create then nest
-      const tokenB = await createItemExpectSuccess(alice, collectionA, 'NFT');
-      await transferExpectSuccess(collectionA, tokenB, alice, targetAddress);
-      children = await getTokenChildren(api, collectionA, targetToken);
-      expect(children.length).to.be.equal(2, 'Children length check at nesting #2');
-      expect(children).to.have.deep.members([
-        {token: tokenA, collection: collectionA},
-        {token: tokenB, collection: collectionA},
-      ], 'Children contents check at nesting #2');
+    // Move token B to a different user outside the nesting tree
+    await tokenB.unnest(alice, targetToken, {Substrate: bob.address});
+    expect(await targetToken.getChildren()).to.be.have.deep.members([
+      {tokenId: tokenA.tokenId, collectionId: collectionA.collectionId},
+    ], 'Children contents check at nesting #3 (unnesting)').and.be.length(1, 'Children length check at nesting #3 (unnesting)');
 
-      // Move token B to a different user outside the nesting tree
-      await transferFromExpectSuccess(collectionA, tokenB, alice, targetAddress, bob);
-      children = await getTokenChildren(api, collectionA, targetToken);
-      expect(children.length).to.be.equal(1, 'Children length check at unnesting');
-      expect(children).to.be.have.deep.members([
-        {token: tokenA, collection: collectionA},
-      ], 'Children contents check at unnesting');
+    // Create a fungible token in another collection and then nest
+    await collectionB.mint(alice, 10n);
+    await collectionB.transfer(alice, targetToken.nestingAccount(), 2n);
+    expect(await targetToken.getChildren()).to.be.have.deep.members([
+      {tokenId: tokenA.tokenId, collectionId: collectionA.collectionId},
+      {tokenId: 0, collectionId: collectionB.collectionId},
+    ], 'Children contents check at nesting #4 (from another collection)')
+      .and.be.length(2, 'Children length check at nesting #4 (from another collection)');
+    
+    // Move part of the fungible token inside token A deeper in the nesting tree
+    await collectionB.transferFrom(alice, targetToken.nestingAccount(), tokenA.nestingAccount(), 1n);
+    expect(await targetToken.getChildren()).to.be.have.deep.members([
+      {tokenId: tokenA.tokenId, collectionId: collectionA.collectionId},
+      {tokenId: 0, collectionId: collectionB.collectionId},
+    ], 'Children contents check at nesting #5 (deeper)').and.be.length(2, 'Children length check at nesting #5 (deeper)');
+    expect(await tokenA.getChildren()).to.be.have.deep.members([
+      {tokenId: 0, collectionId: collectionB.collectionId},
+    ], 'Children contents check at nesting #5.5 (deeper)').and.be.length(1, 'Children length check at nesting #5.5 (deeper)');
 
-      // Create a fungible token in another collection and then nest
-      const tokenC = await createItemExpectSuccess(alice, collectionB, 'Fungible');
-      await transferExpectSuccess(collectionB, tokenC, alice, targetAddress, 1, 'Fungible');
-      children = await getTokenChildren(api, collectionA, targetToken);
-      expect(children.length).to.be.equal(2, 'Children length check at nesting #3 (from another collection)');
-      expect(children).to.be.have.deep.members([
-        {token: tokenA, collection: collectionA},
-        {token: tokenC, collection: collectionB},
-      ], 'Children contents check at nesting #3 (from another collection)');
-
-      // Move the fungible token inside token A deeper in the nesting tree
-      await transferFromExpectSuccess(collectionB, tokenC, alice, targetAddress, {Ethereum: tokenIdToAddress(collectionA, tokenA)}, 1, 'Fungible');
-      children = await getTokenChildren(api, collectionA, targetToken);
-      expect(children.length).to.be.equal(1, 'Children length check at deeper nesting');
-      expect(children).to.be.have.deep.members([
-        {token: tokenA, collection: collectionA},
-      ], 'Children contents check at deeper nesting');
-    });
+    // Move the remaining part of the fungible token inside token A deeper in the nesting tree
+    await collectionB.transferFrom(alice, targetToken.nestingAccount(), tokenA.nestingAccount(), 1n);
+    expect(await targetToken.getChildren()).to.be.have.deep.members([
+      {tokenId: tokenA.tokenId, collectionId: collectionA.collectionId},
+    ], 'Children contents check at nesting #6 (deeper)').and.be.length(1, 'Children length check at nesting #6 (deeper)');
+    expect(await tokenA.getChildren()).to.be.have.deep.members([
+      {tokenId: 0, collectionId: collectionB.collectionId},
+    ], 'Children contents check at nesting #6.5 (deeper)').and.be.length(1, 'Children length check at nesting #6.5 (deeper)');
   });
 });
 
-describe('Integration Test: Various token type nesting', async () => {
+describe('Integration Test: Various token type nesting', () => {
+  let alice: IKeyringPair;
+  let bob: IKeyringPair;
+  let charlie: IKeyringPair;
+
   before(async () => {
-    await usingApi(async (_, privateKeyWrapper) => {
-      alice = privateKeyWrapper('//Alice');
-      bob = privateKeyWrapper('//Bob');
-      charlie = privateKeyWrapper('//Charlie');
+    await usingPlaygrounds(async (helper, privateKey) => {
+      const donor = privateKey('//Alice');
+      [alice, bob, charlie] = await helper.arrange.createAccounts([50n, 10n, 10n], donor);
     });
   });
 
-  it('Admin (NFT): allows an Admin to nest a token', async () => {
-    await usingApi(async api => {
-      const collection = await createCollectionExpectSuccess({mode: {type: 'NFT'}});
-      await setCollectionPermissionsExpectSuccess(alice, collection, {nesting: {collectionAdmin: true}});
-      await addCollectionAdminExpectSuccess(alice, collection, bob.address);
-      const targetToken = await createItemExpectSuccess(alice, collection, 'NFT', charlie.address);
+  itSub('Admin (NFT): allows an Admin to nest a token', async ({helper}) => {
+    const collection = await helper.nft.mintCollection(alice, {permissions: {nesting: {collectionAdmin: true}}});
+    await collection.addAdmin(alice, {Substrate: bob.address});
+    const targetToken = await collection.mintToken(alice, {Substrate: charlie.address});
 
-      // Create a nested token
-      const nestedToken = await createItemExpectSuccess(bob, collection, 'NFT', {Ethereum: tokenIdToAddress(collection, targetToken)});
-      expect(await getTopmostTokenOwner(api, collection, nestedToken)).to.be.deep.equal({Substrate: charlie.address});
-      expect(await getTokenOwner(api, collection, nestedToken)).to.be.deep.equal({Ethereum: tokenIdToAddress(collection, targetToken).toLowerCase()});
+    // Create an immediately nested token
+    const nestedToken = await collection.mintToken(bob, targetToken.nestingAccount());
+    expect(await nestedToken.getTopmostOwner()).to.be.deep.equal({Substrate: charlie.address});
+    expect(await nestedToken.getOwner()).to.be.deep.equal(targetToken.nestingAccount().toLowerCase());
 
-      // Create a token to be nested and nest
-      const newToken = await createItemExpectSuccess(bob, collection, 'NFT');
-      await transferExpectSuccess(collection, newToken, bob, {Ethereum: tokenIdToAddress(collection, targetToken)});
-      expect(await getTopmostTokenOwner(api, collection, newToken)).to.be.deep.equal({Substrate: charlie.address});
-      expect(await getTokenOwner(api, collection, newToken)).to.be.deep.equal({Ethereum: tokenIdToAddress(collection, targetToken).toLowerCase()});
-    });
+    // Create a token to be nested and nest
+    const newToken = await collection.mintToken(bob);
+    await newToken.nest(bob, targetToken);
+    expect(await newToken.getTopmostOwner()).to.be.deep.equal({Substrate: charlie.address});
+    expect(await newToken.getOwner()).to.be.deep.equal(targetToken.nestingAccount().toLowerCase());
   });
 
-  it('Admin (NFT): Admin and Token Owner can operate together', async () => {
-    await usingApi(async api => {
-      const collection = await createCollectionExpectSuccess({mode: {type: 'NFT'}});
-      await setCollectionPermissionsExpectSuccess(alice, collection, {nesting: {tokenOwner: true, collectionAdmin: true}});
-      await addCollectionAdminExpectSuccess(alice, collection, bob.address);
-      const targetToken = await createItemExpectSuccess(alice, collection, 'NFT', charlie.address);
+  itSub('Admin (NFT): Admin and Token Owner can operate together', async ({helper}) => {
+    const collection = await helper.nft.mintCollection(alice, {permissions: {nesting: {collectionAdmin: true, tokenOwner: true}}});
+    await collection.addAdmin(alice, {Substrate: bob.address});
+    const targetToken = await collection.mintToken(alice, {Substrate: charlie.address});
 
-      // Create a nested token by an administrator
-      const nestedToken = await createItemExpectSuccess(bob, collection, 'NFT', {Ethereum: tokenIdToAddress(collection, targetToken)});
-      expect(await getTopmostTokenOwner(api, collection, nestedToken)).to.be.deep.equal({Substrate: charlie.address});
-      expect(await getTokenOwner(api, collection, nestedToken)).to.be.deep.equal({Ethereum: tokenIdToAddress(collection, targetToken).toLowerCase()});
+    // Create an immediately nested token by an administrator
+    const nestedToken = await collection.mintToken(bob, targetToken.nestingAccount());
+    expect(await nestedToken.getTopmostOwner()).to.be.deep.equal({Substrate: charlie.address});
+    expect(await nestedToken.getOwner()).to.be.deep.equal(targetToken.nestingAccount().toLowerCase());
 
-      // Create a token and allow the owner to nest too
-      const newToken = await createItemExpectSuccess(alice, collection, 'NFT', charlie.address);
-      await transferExpectSuccess(collection, newToken, charlie, {Ethereum: tokenIdToAddress(collection, nestedToken)});
-      expect(await getTopmostTokenOwner(api, collection, newToken)).to.be.deep.equal({Substrate: charlie.address});
-      expect(await getTokenOwner(api, collection, newToken)).to.be.deep.equal({Ethereum: tokenIdToAddress(collection, nestedToken).toLowerCase()});
-    });
+    // Create a token to be nested and nest
+    const newToken = await collection.mintToken(alice, {Substrate: charlie.address});
+    await newToken.nest(charlie, targetToken);
+    expect(await newToken.getTopmostOwner()).to.be.deep.equal({Substrate: charlie.address});
+    expect(await newToken.getOwner()).to.be.deep.equal(targetToken.nestingAccount().toLowerCase());
   });
 
-  it('Admin (NFT): allows an Admin to nest a token (Restricted nesting)', async () => {
-    await usingApi(async api => {
-      const collectionA = await createCollectionExpectSuccess({mode: {type: 'NFT'}});
-      await addCollectionAdminExpectSuccess(alice, collectionA, bob.address);
-      const collectionB = await createCollectionExpectSuccess({mode: {type: 'NFT'}});
-      await addCollectionAdminExpectSuccess(alice, collectionB, bob.address);
-      await setCollectionPermissionsExpectSuccess(alice, collectionA, {nesting: {collectionAdmin: true, restricted:[collectionA, collectionB]}});
-      const targetToken = await createItemExpectSuccess(alice, collectionA, 'NFT', charlie.address);
+  itSub('Admin (NFT): allows an Admin to nest a token (Restricted nesting)', async ({helper}) => {
+    const collectionA = await helper.nft.mintCollection(alice);
+    await collectionA.addAdmin(alice, {Substrate: bob.address});
+    const collectionB = await helper.nft.mintCollection(alice);
+    await collectionB.addAdmin(alice, {Substrate: bob.address});
+    await collectionA.setPermissions(alice, {nesting: {collectionAdmin: true, restricted:[collectionB.collectionId]}});
+    const targetToken = await collectionA.mintToken(alice, {Substrate: charlie.address});
 
-      // Create a nested token
-      const nestedToken = await createItemExpectSuccess(bob, collectionB, 'NFT', {Ethereum: tokenIdToAddress(collectionA, targetToken)});
-      expect(await getTopmostTokenOwner(api, collectionB, nestedToken)).to.be.deep.equal({Substrate: charlie.address});
-      expect(await getTokenOwner(api, collectionB, nestedToken)).to.be.deep.equal({Ethereum: tokenIdToAddress(collectionA, targetToken).toLowerCase()});
+    // Create an immediately nested token
+    const nestedToken = await collectionB.mintToken(bob, targetToken.nestingAccount());
+    expect(await nestedToken.getTopmostOwner()).to.be.deep.equal({Substrate: charlie.address});
+    expect(await nestedToken.getOwner()).to.be.deep.equal(targetToken.nestingAccount().toLowerCase());
 
-      // Create a token to be nested and nest
-      const newToken = await createItemExpectSuccess(bob, collectionB, 'NFT');
-      await transferExpectSuccess(collectionB, newToken, bob, {Ethereum: tokenIdToAddress(collectionA, targetToken)});
-      expect(await getTopmostTokenOwner(api, collectionB, newToken)).to.be.deep.equal({Substrate: charlie.address});
-      expect(await getTokenOwner(api, collectionB, newToken)).to.be.deep.equal({Ethereum: tokenIdToAddress(collectionA, targetToken).toLowerCase()});
-    });
+    // Create a token to be nested and nest
+    const newToken = await collectionB.mintToken(bob);
+    await newToken.nest(bob, targetToken);
+    expect(await newToken.getTopmostOwner()).to.be.deep.equal({Substrate: charlie.address});
+    expect(await newToken.getOwner()).to.be.deep.equal(targetToken.nestingAccount().toLowerCase());
   });
 
   // ---------- Non-Fungible ----------
 
-  it('NFT: allows an Owner to nest/unnest their token', async () => {
-    await usingApi(async api => {
-      const collection = await createCollectionExpectSuccess({mode: {type: 'NFT'}});
-      await setCollectionPermissionsExpectSuccess(alice, collection, {nesting: {tokenOwner: true}});
-      const targetToken = await createItemExpectSuccess(alice, collection, 'NFT');
+  itSub('NFT: allows an Owner to nest/unnest their token', async ({helper}) => {
+    const collection = await helper.nft.mintCollection(alice, {permissions: {access: 'AllowList', mintMode: true, nesting: {tokenOwner: true}}});
+    await collection.addToAllowList(alice, {Substrate: charlie.address});
+    const targetToken = await collection.mintToken(charlie);
+    await collection.addToAllowList(alice, targetToken.nestingAccount());
 
-      // Create a nested token
-      const nestedToken = await createItemExpectSuccess(alice, collection, 'NFT', {Ethereum: tokenIdToAddress(collection, targetToken)});
-      expect(await getTopmostTokenOwner(api, collection, nestedToken)).to.be.deep.equal({Substrate: alice.address});
-      expect(await getTokenOwner(api, collection, nestedToken)).to.be.deep.equal({Ethereum: tokenIdToAddress(collection, targetToken).toLowerCase()});
+    // Create an immediately nested token
+    const nestedToken = await collection.mintToken(charlie, targetToken.nestingAccount());
+    expect(await nestedToken.getTopmostOwner()).to.be.deep.equal({Substrate: charlie.address});
+    expect(await nestedToken.getOwner()).to.be.deep.equal(targetToken.nestingAccount().toLowerCase());
 
-      // Create a token to be nested and nest
-      const newToken = await createItemExpectSuccess(alice, collection, 'NFT');
-      await transferExpectSuccess(collection, newToken, alice, {Ethereum: tokenIdToAddress(collection, targetToken)});
-      expect(await getTopmostTokenOwner(api, collection, newToken)).to.be.deep.equal({Substrate: alice.address});
-      expect(await getTokenOwner(api, collection, newToken)).to.be.deep.equal({Ethereum: tokenIdToAddress(collection, targetToken).toLowerCase()});
-    });
+    // Create a token to be nested and nest
+    const newToken = await collection.mintToken(charlie);
+    await newToken.nest(charlie, targetToken);
+    expect(await newToken.getTopmostOwner()).to.be.deep.equal({Substrate: charlie.address});
+    expect(await newToken.getOwner()).to.be.deep.equal(targetToken.nestingAccount().toLowerCase());
   });
 
-  it('NFT: allows an Owner to nest/unnest their token (Restricted nesting)', async () => {
-    await usingApi(async api => {
-      const collection = await createCollectionExpectSuccess({mode: {type: 'NFT'}});
-      await setCollectionPermissionsExpectSuccess(alice, collection, {nesting: {tokenOwner: true, restricted:[collection]}});
-      const targetToken = await createItemExpectSuccess(alice, collection, 'NFT');
+  itSub('NFT: allows an Owner to nest/unnest their token (Restricted nesting)', async ({helper}) => {
+    const collectionA = await helper.nft.mintCollection(alice);
+    const collectionB = await helper.nft.mintCollection(alice);
+    //await collectionB.addAdmin(alice, {Substrate: bob.address});
+    const targetToken = await collectionA.mintToken(alice, {Substrate: charlie.address});
 
-      // Create a nested token
-      const nestedToken = await createItemExpectSuccess(alice, collection, 'NFT', {Ethereum: tokenIdToAddress(collection, targetToken)});
-      expect(await getTopmostTokenOwner(api, collection, nestedToken)).to.be.deep.equal({Substrate: alice.address});
-      expect(await getTokenOwner(api, collection, nestedToken)).to.be.deep.equal({Ethereum: tokenIdToAddress(collection, targetToken).toLowerCase()});
+    await collectionA.setPermissions(alice, {access: 'AllowList', mintMode: true, nesting: {tokenOwner: true, restricted:[collectionB.collectionId]}});
+    await collectionA.addToAllowList(alice, {Substrate: charlie.address});
+    await collectionA.addToAllowList(alice, targetToken.nestingAccount());
+
+    await collectionB.setPermissions(alice, {access: 'AllowList', mintMode: true});
+    await collectionB.addToAllowList(alice, {Substrate: charlie.address});
+    await collectionB.addToAllowList(alice, targetToken.nestingAccount());
 
-      // Create a token to be nested and nest
-      const newToken = await createItemExpectSuccess(alice, collection, 'NFT');
-      await transferExpectSuccess(collection, newToken, alice, {Ethereum: tokenIdToAddress(collection, targetToken)});
-      expect(await getTopmostTokenOwner(api, collection, newToken)).to.be.deep.equal({Substrate: alice.address});
-      expect(await getTokenOwner(api, collection, newToken)).to.be.deep.equal({Ethereum: tokenIdToAddress(collection, targetToken).toLowerCase()});
-    });
+    // Create an immediately nested token
+    const nestedToken = await collectionB.mintToken(charlie, targetToken.nestingAccount());
+    expect(await nestedToken.getTopmostOwner()).to.be.deep.equal({Substrate: charlie.address});
+    expect(await nestedToken.getOwner()).to.be.deep.equal(targetToken.nestingAccount().toLowerCase());
+
+    // Create a token to be nested and nest
+    const newToken = await collectionB.mintToken(charlie);
+    await newToken.nest(charlie, targetToken);
+    expect(await newToken.getTopmostOwner()).to.be.deep.equal({Substrate: charlie.address});
+    expect(await newToken.getOwner()).to.be.deep.equal(targetToken.nestingAccount().toLowerCase());
   });
 
   // ---------- Fungible ----------
 
-  it('Fungible: allows an Owner to nest/unnest their token', async () => {
-    await usingApi(async api => {
-      const collectionNFT = await createCollectionExpectSuccess({mode: {type: 'NFT'}});
-      await setCollectionPermissionsExpectSuccess(alice, collectionNFT, {nesting: {tokenOwner: true}});
-      const targetToken = await createItemExpectSuccess(alice, collectionNFT, 'NFT', {Substrate: alice.address});
-      const targetAddress = {Ethereum: tokenIdToAddress(collectionNFT, targetToken)};
+  itSub('Fungible: allows an Owner to nest/unnest their token', async ({helper}) => {
+    const collectionNFT = await helper.nft.mintCollection(alice, {permissions: {access: 'AllowList', mintMode: true, nesting: {tokenOwner: true}}});
+    const collectionFT = await helper.ft.mintCollection(alice);
+    const targetToken = await collectionNFT.mintToken(alice, {Substrate: charlie.address});
 
-      const collectionFT = await createCollectionExpectSuccess({mode: {type: 'Fungible', decimalPoints: 0}});
+    await collectionNFT.addToAllowList(alice, {Substrate: charlie.address});
+    await collectionNFT.addToAllowList(alice, targetToken.nestingAccount());
 
-      // Create a nested token
-      await expect(executeTransaction(api, alice, api.tx.unique.createItem(
-        collectionFT,
-        targetAddress,
-        {Fungible: {Value: 10}},
-      ))).to.not.be.rejected;
+    await collectionFT.setPermissions(alice, {access: 'AllowList', mintMode: true});
+    await collectionFT.addToAllowList(alice, {Substrate: charlie.address});
+    await collectionFT.addToAllowList(alice, targetToken.nestingAccount());
 
-      // Nest a new token
-      const newToken = await createItemExpectSuccess(alice, collectionFT, 'Fungible');
-      await transferExpectSuccess(collectionFT, newToken, alice, targetAddress, 1, 'Fungible');
-    });
+    // Create an immediately nested token
+    await collectionFT.mint(charlie, 5n, targetToken.nestingAccount());
+    expect(await collectionFT.getBalance(targetToken.nestingAccount())).to.be.equal(5n);
+
+    // Create a token to be nested and nest
+    await collectionFT.mint(charlie, 5n);
+    await collectionFT.transfer(charlie, targetToken.nestingAccount(), 2n);
+    expect(await collectionFT.getBalance(targetToken.nestingAccount())).to.be.equal(7n);
   });
 
-  it('Fungible: allows an Owner to nest/unnest their token (Restricted nesting)', async () => {
-    await usingApi(async api => {
-      const collectionNFT = await createCollectionExpectSuccess({mode: {type: 'NFT'}});
-      const targetToken = await createItemExpectSuccess(alice, collectionNFT, 'NFT', {Substrate: alice.address});
-      const targetAddress = {Ethereum: tokenIdToAddress(collectionNFT, targetToken)};
+  itSub('Fungible: allows an Owner to nest/unnest their token (Restricted nesting)', async ({helper}) => {
+    const collectionNFT = await helper.nft.mintCollection(alice);
+    const collectionFT = await helper.ft.mintCollection(alice);
+    const targetToken = await collectionNFT.mintToken(alice, {Substrate: charlie.address});
 
-      const collectionFT = await createCollectionExpectSuccess({mode: {type: 'Fungible', decimalPoints: 0}});
+    await collectionNFT.setPermissions(alice, {access: 'AllowList', mintMode: true, nesting: {tokenOwner: true, restricted:[collectionFT.collectionId]}});
+    await collectionNFT.addToAllowList(alice, {Substrate: charlie.address});
+    await collectionNFT.addToAllowList(alice, targetToken.nestingAccount());
 
-      await setCollectionPermissionsExpectSuccess(alice, collectionNFT, {nesting: {tokenOwner: true, restricted: [collectionFT]}});
+    await collectionFT.setPermissions(alice, {access: 'AllowList', mintMode: true});
+    await collectionFT.addToAllowList(alice, {Substrate: charlie.address});
+    await collectionFT.addToAllowList(alice, targetToken.nestingAccount());
 
-      // Create a nested token
-      await expect(executeTransaction(api, alice, api.tx.unique.createItem(
-        collectionFT,
-        targetAddress,
-        {Fungible: {Value: 10}},
-      ))).to.not.be.rejected;
+    // Create an immediately nested token
+    await collectionFT.mint(charlie, 5n, targetToken.nestingAccount());
+    expect(await collectionFT.getBalance(targetToken.nestingAccount())).to.be.equal(5n);
 
-      // Nest a new token
-      const newToken = await createItemExpectSuccess(alice, collectionFT, 'Fungible');
-      await transferExpectSuccess(collectionFT, newToken, alice, targetAddress, 1, 'Fungible');
-    });
+    // Create a token to be nested and nest
+    await collectionFT.mint(charlie, 5n);
+    await collectionFT.transfer(charlie, targetToken.nestingAccount(), 2n);
+    expect(await collectionFT.getBalance(targetToken.nestingAccount())).to.be.equal(7n);
   });
 
   // ---------- Re-Fungible ----------
 
-  it('ReFungible: allows an Owner to nest/unnest their token', async function() {
-    await requirePallets(this, [Pallets.ReFungible]);
+  itSub.ifWithPallets('ReFungible: allows an Owner to nest/unnest their token', [Pallets.ReFungible], async ({helper}) => {
+    const collectionNFT = await helper.nft.mintCollection(alice, {permissions: {access: 'AllowList', mintMode: true, nesting: {tokenOwner: true}}});
+    const collectionRFT = await helper.rft.mintCollection(alice);
+    const targetToken = await collectionNFT.mintToken(alice, {Substrate: charlie.address});
 
-    await usingApi(async api => {
-      const collectionNFT = await createCollectionExpectSuccess({mode: {type: 'NFT'}});
-      await setCollectionPermissionsExpectSuccess(alice, collectionNFT, {nesting: {tokenOwner: true}});
-      const targetToken = await createItemExpectSuccess(alice, collectionNFT, 'NFT', {Substrate: alice.address});
-      const targetAddress = {Ethereum: tokenIdToAddress(collectionNFT, targetToken)};
+    await collectionNFT.addToAllowList(alice, {Substrate: charlie.address});
+    await collectionNFT.addToAllowList(alice, targetToken.nestingAccount());
 
-      const collectionRFT = await createCollectionExpectSuccess({mode: {type: 'ReFungible'}});
+    await collectionRFT.setPermissions(alice, {access: 'AllowList', mintMode: true});
+    await collectionRFT.addToAllowList(alice, {Substrate: charlie.address});
+    await collectionRFT.addToAllowList(alice, targetToken.nestingAccount());
 
-      // Create a nested token
-      await expect(executeTransaction(api, alice, api.tx.unique.createItem(
-        collectionRFT,
-        targetAddress,
-        {ReFungible: {pieces: 100}},
-      ))).to.not.be.rejected;
+    // Create an immediately nested token
+    const nestedToken = await collectionRFT.mintToken(charlie, 5n, targetToken.nestingAccount());
+    expect(await nestedToken.getBalance(targetToken.nestingAccount())).to.be.equal(5n);
 
-      // Nest a new token
-      const newToken = await createItemExpectSuccess(alice, collectionRFT, 'ReFungible');
-      await transferExpectSuccess(collectionRFT, newToken, alice, targetAddress, 100, 'ReFungible');
-    });
+    // Create a token to be nested and nest
+    const newToken = await collectionRFT.mintToken(charlie, 5n);
+    await newToken.transfer(charlie, targetToken.nestingAccount(), 2n);
+    expect(await newToken.getBalance(targetToken.nestingAccount())).to.be.equal(2n);
   });
 
-  it('ReFungible: allows an Owner to nest/unnest their token (Restricted nesting)', async function() {
-    await requirePallets(this, [Pallets.ReFungible]);
+  itSub.ifWithPallets('ReFungible: allows an Owner to nest/unnest their token (Restricted nesting)', [Pallets.ReFungible], async ({helper}) => {
+    const collectionNFT = await helper.nft.mintCollection(alice);
+    const collectionRFT = await helper.rft.mintCollection(alice);
+    const targetToken = await collectionNFT.mintToken(alice, {Substrate: charlie.address});
 
-    await usingApi(async api => {
-      const collectionNFT = await createCollectionExpectSuccess({mode: {type: 'NFT'}});
-      const targetToken = await createItemExpectSuccess(alice, collectionNFT, 'NFT', {Substrate: alice.address});
-      const targetAddress = {Ethereum: tokenIdToAddress(collectionNFT, targetToken)};
+    await collectionNFT.setPermissions(alice, {access: 'AllowList', mintMode: true, nesting: {tokenOwner: true, restricted:[collectionRFT.collectionId]}});
+    await collectionNFT.addToAllowList(alice, {Substrate: charlie.address});
+    await collectionNFT.addToAllowList(alice, targetToken.nestingAccount());
 
-      const collectionRFT = await createCollectionExpectSuccess({mode: {type: 'ReFungible'}});
+    await collectionRFT.setPermissions(alice, {access: 'AllowList', mintMode: true});
+    await collectionRFT.addToAllowList(alice, {Substrate: charlie.address});
+    await collectionRFT.addToAllowList(alice, targetToken.nestingAccount());
 
-      await setCollectionPermissionsExpectSuccess(alice, collectionNFT, {nesting: {tokenOwner: true, restricted:[collectionRFT]}});
+    // Create an immediately nested token
+    const nestedToken = await collectionRFT.mintToken(charlie, 5n, targetToken.nestingAccount());
+    expect(await nestedToken.getBalance(targetToken.nestingAccount())).to.be.equal(5n);
 
-      // Create a nested token
-      await expect(executeTransaction(api, alice, api.tx.unique.createItem(
-        collectionRFT,
-        targetAddress,
-        {ReFungible: {pieces: 100}},
-      ))).to.not.be.rejected;
-
-      // Nest a new token
-      const newToken = await createItemExpectSuccess(alice, collectionRFT, 'ReFungible');
-      await transferExpectSuccess(collectionRFT, newToken, alice, targetAddress, 100, 'ReFungible');
-    });
+    // Create a token to be nested and nest
+    const newToken = await collectionRFT.mintToken(charlie, 5n);
+    await newToken.transfer(charlie, targetToken.nestingAccount(), 2n);
+    expect(await newToken.getBalance(targetToken.nestingAccount())).to.be.equal(2n);
   });
 });
 
-describe('Negative Test: Nesting', async() => {
+describe('Negative Test: Nesting', () => {
+  let alice: IKeyringPair;
+  let bob: IKeyringPair;
+
   before(async () => {
-    await usingApi(async (_, privateKeyWrapper) => {
-      alice = privateKeyWrapper('//Alice');
-      bob = privateKeyWrapper('//Bob');
+    await usingPlaygrounds(async (helper, privateKey) => {
+      const donor = privateKey('//Alice');
+      [alice, bob] = await helper.arrange.createAccounts([100n, 50n], donor);
     });
   });
 
-  it('Disallows excessive token nesting', async () => {
-    await usingApi(async api => {
-      const collection = await createCollectionExpectSuccess({mode: {type: 'NFT'}});
-      await setCollectionPermissionsExpectSuccess(alice, collection, {nesting: {tokenOwner: true}});
-      const targetToken = await createItemExpectSuccess(alice, collection, 'NFT');
-
-      const maxNestingLevel = 5;
-      let prevToken = targetToken;
+  itSub('Disallows excessive token nesting', async ({helper}) => {
+    const collection = await helper.nft.mintCollection(alice, {permissions: {nesting: {tokenOwner: true}}});
+    let token = await collection.mintToken(alice);
 
-      // Create a nested-token matryoshka
-      for (let i = 0; i < maxNestingLevel; i++) {
-        const nestedToken = await createItemExpectSuccess(
-          alice,
-          collection,
-          'NFT',
-          {Ethereum: tokenIdToAddress(collection, prevToken)},
-        );
+    const maxNestingLevel = 5;
 
-        prevToken = nestedToken;
-      }
-
-      // The nesting depth is limited by `maxNestingLevel`
-      await expect(executeTransaction(api, alice, api.tx.unique.createItem(
-        collection,
-        {Ethereum: tokenIdToAddress(collection, prevToken)},
-          {nft: {}} as any,
-      )), 'while creating nested token').to.be.rejectedWith(/^structure\.DepthLimit$/);
+    // Create a nested-token matryoshka
+    for (let i = 0; i < maxNestingLevel; i++) {
+      token = await collection.mintToken(alice, token.nestingAccount());
+    }
 
-      expect(await getTopmostTokenOwner(api, collection, prevToken)).to.be.deep.equal({Substrate: alice.address});
-    });
+    // The nesting depth is limited by `maxNestingLevel`
+    await expect(collection.mintToken(alice, token.nestingAccount()))
+      .to.be.rejectedWith(/structure\.DepthLimit/);
+    expect(await token.getTopmostOwner()).to.be.deep.equal({Substrate: alice.address});
+    expect(await token.getChildren()).to.be.length(0);
   });
 
   // ---------- Admin ------------
 
-  it('Admin (NFT): disallows an Admin to operate nesting when only TokenOwner is allowed', async () => {
-    await usingApi(async api => {
-      const collection = await createCollectionExpectSuccess({mode: {type: 'NFT'}});
-      await setCollectionPermissionsExpectSuccess(alice, collection, {nesting: {tokenOwner: true}});
-      await addCollectionAdminExpectSuccess(alice, collection, bob.address);
-      const targetToken = await createItemExpectSuccess(alice, collection, 'NFT');
+  itSub('Admin (NFT): disallows an Admin to operate nesting when only TokenOwner is allowed', async ({helper}) => {
+    const collection = await helper.nft.mintCollection(alice, {permissions: {nesting: {tokenOwner: true}}});
+    await collection.addAdmin(alice, {Substrate: bob.address});
+    const targetToken = await collection.mintToken(alice);
 
-      // Try to create a nested token as collection admin when it's disallowed
-      await expect(executeTransaction(api, bob, api.tx.unique.createItem(
-        collection,
-        {Ethereum: tokenIdToAddress(collection, targetToken)},
-          {nft: {}} as any,
-      )), 'while creating nested token').to.be.rejectedWith(/common\.UserIsNotAllowedToNest/);
+    // Try to create an immediately nested token as collection admin when it's disallowed
+    await expect(collection.mintToken(bob, targetToken.nestingAccount()))
+      .to.be.rejectedWith(/common\.UserIsNotAllowedToNest/);
 
-      // Try to create and nest a token in the wrong collection
-      const newToken = await createItemExpectSuccess(bob, collection, 'NFT');
-      await expect(executeTransaction(
-        api, 
-        bob, 
-        api.tx.unique.transfer({Ethereum: tokenIdToAddress(collection, targetToken)}, collection, newToken, 1),
-      ), 'while nesting new token').to.be.rejectedWith(/common\.UserIsNotAllowedToNest/);
-      expect(await getTokenOwner(api, collection, newToken)).to.be.deep.equal({Substrate: bob.address});
-    });
+    // Try to create a token to be nested and nest
+    const newToken = await collection.mintToken(bob);
+    await expect(newToken.nest(bob, targetToken))
+      .to.be.rejectedWith(/common\.UserIsNotAllowedToNest/);
+
+    expect(await targetToken.getChildren()).to.be.length(0);
+    expect(await newToken.getOwner()).to.be.deep.equal({Substrate: bob.address});
   });
 
-  it('Admin (NFT): disallows a Token Owner to operate nesting when only Admin is allowed', async () => {
-    await usingApi(async api => {
-      const collection = await createCollectionExpectSuccess({mode: {type: 'NFT'}});
-      await setCollectionPermissionsExpectSuccess(alice, collection, {nesting: {collectionAdmin: true}});
-      await addToAllowListExpectSuccess(alice, collection, bob.address);
-      await enableAllowListExpectSuccess(alice, collection);
-      await enablePublicMintingExpectSuccess(alice, collection);
-      const targetToken = await createItemExpectSuccess(alice, collection, 'NFT');
+  itSub('Admin (NFT): disallows a Token Owner to operate nesting when only Admin is allowed', async ({helper}) => {
+    const collection = await helper.nft.mintCollection(alice, {permissions: {access: 'AllowList', mintMode: true, nesting: {collectionAdmin: true}}});
+    const targetToken = await collection.mintToken(alice, {Substrate: bob.address});
+    await collection.addToAllowList(alice, {Substrate: bob.address});
+    await collection.addToAllowList(alice, targetToken.nestingAccount());
+
+    // Try to create a nested token as token owner when it's disallowed
+    await expect(collection.mintToken(bob, targetToken.nestingAccount()))
+      .to.be.rejectedWith(/common\.UserIsNotAllowedToNest/);
 
-      // Try to create a nested token as collection admin when it's disallowed
-      await expect(executeTransaction(api, bob, api.tx.unique.createItem(
-        collection,
-        {Ethereum: tokenIdToAddress(collection, targetToken)},
-          {nft: {}} as any,
-      )), 'while creating nested token').to.be.rejectedWith(/common\.AddressNotInAllowlist/); 
+    // Try to create a token to be nested and nest
+    const newToken = await collection.mintToken(bob);
+    await expect(newToken.nest(bob, targetToken))
+      .to.be.rejectedWith(/common\.UserIsNotAllowedToNest/);
 
-      // Try to create and nest a token in the wrong collection
-      const newToken = await createItemExpectSuccess(bob, collection, 'NFT');
-      await expect(executeTransaction(
-        api, 
-        bob, 
-        api.tx.unique.transfer({Ethereum: tokenIdToAddress(collection, targetToken)}, collection, newToken, 1),
-      ), 'while nesting new token').to.be.rejectedWith(/common\.AddressNotInAllowlist/);
-      expect(await getTokenOwner(api, collection, newToken)).to.be.deep.equal({Substrate: bob.address});
-    });
+    expect(await targetToken.getChildren()).to.be.length(0);
+    expect(await newToken.getOwner()).to.be.deep.equal({Substrate: bob.address});
   });
 
-  it('Admin (NFT): disallows an Admin to nest and unnest someone else\'s token', async () => {
-    await usingApi(async api => {
-      const collection = await createCollectionExpectSuccess({mode: {type: 'NFT'}});
-      await setCollectionLimitsExpectSuccess(alice, collection, {ownerCanTransfer: true});
-      await setCollectionPermissionsExpectSuccess(alice, collection, {nesting: {collectionAdmin: true}});
+  itSub('Admin (NFT): disallows an Admin to unnest someone else\'s token', async ({helper}) => {
+    const collection = await helper.nft.mintCollection(alice, {limits: {ownerCanTransfer: true}, permissions: {access: 'AllowList', mintMode: true, nesting: {collectionAdmin: true}}});
+    //await collection.addAdmin(alice, {Substrate: bob.address});
+    const targetToken = await collection.mintToken(alice, {Substrate: bob.address});
+    await collection.addToAllowList(alice, {Substrate: bob.address});
+    await collection.addToAllowList(alice, targetToken.nestingAccount());
 
-      await addToAllowListExpectSuccess(alice, collection, bob.address);
-      await enableAllowListExpectSuccess(alice, collection);
-      await enablePublicMintingExpectSuccess(alice, collection);
-
-      // Create a token to attempt to be nested into
-      const targetToken = await createItemExpectSuccess(bob, collection, 'NFT');
-      const targetAddress = {Ethereum: tokenIdToAddress(collection, targetToken).toLowerCase()};
+    // Try to nest somebody else's token
+    const newToken = await collection.mintToken(bob);
+    await expect(newToken.nest(alice, targetToken))
+      .to.be.rejectedWith(/common\.NoPermission/);
 
-      // Try to nest somebody else's token
-      const newToken = await createItemExpectSuccess(bob, collection, 'NFT');
-      await expect(executeTransaction(
-        api, 
-        alice, 
-        api.tx.unique.transferFrom(targetAddress, {Substrate: bob.address}, collection, newToken, 1),
-      ), 'while nesting another\'s token token').to.be.rejectedWith(/common\.AddressNotInAllowlist/);
-      expect(await getTokenOwner(api, collection, newToken)).to.be.deep.equal({Substrate: bob.address});
+    // Try to unnest a token belonging to someone else as collection admin
+    const nestedToken = await collection.mintToken(alice, targetToken.nestingAccount());
+    await expect(nestedToken.unnest(alice, targetToken, {Substrate: bob.address}))
+      .to.be.rejectedWith(/common\.AddressNotInAllowlist/);
 
-      // Nest a token as admin and try to unnest it, now belonging to someone else
-      const nestedToken = await createItemExpectSuccess(alice, collection, 'NFT', targetAddress);
-      await expect(executeTransaction(
-        api, 
-        alice, 
-        api.tx.unique.transferFrom(targetAddress, normalizeAccountId(alice), collection, nestedToken, 1),
-      ), 'while unnesting another\'s token').to.be.rejectedWith(/common\.AddressNotInAllowlist/);
-      expect(await getTokenOwner(api, collection, nestedToken)).to.be.deep.equal(targetAddress);
-      expect(await getTopmostTokenOwner(api, collection, nestedToken)).to.be.deep.equal({Substrate: bob.address});
-    });
+    expect(await targetToken.getChildren()).to.be.length(1);
+    expect(await nestedToken.getTopmostOwner()).to.be.deep.equal({Substrate: bob.address});
+    expect(await nestedToken.getOwner()).to.be.deep.equal(targetToken.nestingAccount().toLowerCase());
   });
 
-  it('Admin (NFT): disallows an Admin to nest a token from an unlisted collection (Restricted nesting)', async () => {
-    await usingApi(async api => {
-      const collectionA = await createCollectionExpectSuccess({mode: {type: 'NFT'}});
-      const collectionB = await createCollectionExpectSuccess({mode: {type: 'NFT'}});
-      await setCollectionPermissionsExpectSuccess(alice, collectionA, {nesting: {collectionAdmin: true, restricted:[collectionA]}});
+  itSub('Admin (NFT): disallows an Admin to nest a token from an unlisted collection (Restricted nesting)', async ({helper}) => {
+    const collectionA = await helper.nft.mintCollection(alice);
+    const collectionB = await helper.nft.mintCollection(alice);
+    await collectionA.setPermissions(alice, {nesting: {collectionAdmin: true, restricted: [collectionA.collectionId]}});
+    const targetToken = await collectionA.mintToken(alice);
 
-      // Create a token to attempt to be nested into
-      const targetToken = await createItemExpectSuccess(alice, collectionA, 'NFT');
+    // Try to create a nested token from another collection
+    await expect(collectionB.mintToken(alice, targetToken.nestingAccount()))
+      .to.be.rejectedWith(/common\.SourceCollectionIsNotAllowedToNest/);
 
-      // Try to create and nest a token in the wrong collection
-      const newToken = await createItemExpectSuccess(alice, collectionB, 'NFT');
-      await expect(executeTransaction(
-        api, 
-        alice, 
-        api.tx.unique.transfer({Ethereum: tokenIdToAddress(collectionA, targetToken)}, collectionB, newToken, 1),
-      ), 'while nesting a foreign token').to.be.rejectedWith(/common\.SourceCollectionIsNotAllowedToNest/);
-      expect(await getTokenOwner(api, collectionB, newToken)).to.be.deep.equal({Substrate: alice.address});
-    });
+    // Create a token in another collection yet to be nested and try to nest
+    const newToken = await collectionB.mintToken(alice);
+    await expect(newToken.nest(alice, targetToken))
+      .to.be.rejectedWith(/common\.SourceCollectionIsNotAllowedToNest/);
+
+    expect(await targetToken.getChildren()).to.be.length(0);
+    expect(await newToken.getOwner()).to.be.deep.equal({Substrate: alice.address});
   });
 
   // ---------- Non-Fungible ----------
 
-  it('NFT: disallows to nest token if nesting is disabled', async () => {
-    await usingApi(async api => {
-      const collection = await createCollectionExpectSuccess({mode: {type: 'NFT'}});
-      await setCollectionPermissionsExpectSuccess(alice, collection, {nesting: {}});
-      const targetToken = await createItemExpectSuccess(alice, collection, 'NFT');
+  itSub('NFT: disallows to nest token if nesting is disabled', async ({helper}) => {
+    // Collection is implicitly not allowed nesting at creation
+    const collection = await helper.nft.mintCollection(alice);
+    const targetToken = await collection.mintToken(alice);
 
-      // Try to create a nested token
-      await expect(executeTransaction(api, alice, api.tx.unique.createItem(
-        collection,
-        {Ethereum: tokenIdToAddress(collection, targetToken)},
-          {nft: {}} as any,
-      )), 'while creating nested token').to.be.rejectedWith(/^common\.UserIsNotAllowedToNest$/);
+    // Try to create a nested token as token owner when it's disallowed
+    await expect(collection.mintToken(alice, targetToken.nestingAccount()))
+      .to.be.rejectedWith(/common\.UserIsNotAllowedToNest/);
 
-      // Create a token to be nested
-      const newToken = await createItemExpectSuccess(alice, collection, 'NFT');
-      // Try to nest
-      await expect(executeTransaction(api, alice, api.tx.unique.transfer({Ethereum: tokenIdToAddress(collection, targetToken)}, collection, newToken, 1)), 'while nesting new token').to.be.rejectedWith(/common\.UserIsNotAllowedToNest/);
-      expect(await getTopmostTokenOwner(api, collection, newToken)).to.be.deep.equal({Substrate: alice.address});
-      expect(await getTokenOwner(api, collection, newToken)).to.be.deep.equal({Substrate: alice.address});
-    });
+    // Try to create a token to be nested and nest
+    const newToken = await collection.mintToken(alice);
+    await expect(newToken.nest(alice, targetToken))
+      .to.be.rejectedWith(/common\.UserIsNotAllowedToNest/);
+
+    expect(await targetToken.getChildren()).to.be.length(0);
+    expect(await newToken.getOwner()).to.be.deep.equal({Substrate: alice.address});
   });
 
-  it('NFT: disallows a non-Owner to nest someone else\'s token', async () => {
-    await usingApi(async api => {
-      const collection = await createCollectionExpectSuccess({mode: {type: 'NFT'}});
-      await setCollectionPermissionsExpectSuccess(alice, collection, {nesting: {tokenOwner: true}});
+  itSub('NFT: disallows a non-Owner to nest someone else\'s token', async ({helper}) => {
+    const collection = await helper.nft.mintCollection(alice);
+    const targetToken = await collection.mintToken(alice);
 
-      await addToAllowListExpectSuccess(alice, collection, bob.address);
-      await enableAllowListExpectSuccess(alice, collection);
-      await enablePublicMintingExpectSuccess(alice, collection);
-
-      // Create a token to attempt to be nested into
-      const targetToken = await createItemExpectSuccess(bob, collection, 'NFT');
+    await collection.setPermissions(alice, {access: 'AllowList', mintMode: true, nesting: {tokenOwner: true}});
+    await collection.addToAllowList(alice, {Substrate: bob.address});
+    await collection.addToAllowList(alice, targetToken.nestingAccount());
 
-      // Try to create a nested token in the wrong collection
-      await expect(executeTransaction(api, alice, api.tx.unique.createItem(
-        collection,
-        {Ethereum: tokenIdToAddress(collection, targetToken)},
-          {nft: {}} as any,
-      )), 'while creating nested token').to.be.rejectedWith(/common\.UserIsNotAllowedToNest/);
+    // Try to create a token to be nested and nest
+    const newToken = await collection.mintToken(alice);
+    await expect(newToken.nest(bob, targetToken)).to.be.rejectedWith(/common\.NoPermission/);
 
-      // Try to create and nest a token in the wrong collection
-      const newToken = await createItemExpectSuccess(alice, collection, 'NFT');
-      await expect(executeTransaction(api, alice, api.tx.unique.transfer({Ethereum: tokenIdToAddress(collection, targetToken)}, collection, newToken, 1)), 'while nesting new token').to.be.rejectedWith(/common\.AddressNotInAllowlist/);
-      expect(await getTokenOwner(api, collection, newToken)).to.be.deep.equal({Substrate: alice.address});
-    });
+    expect(await targetToken.getChildren()).to.be.length(0);
+    expect(await newToken.getOwner()).to.be.deep.equal({Substrate: alice.address});
   });
 
-  it('NFT: disallows a non-Owner to nest someone else\'s token (Restricted nesting)', async () => {
-    await usingApi(async api => {
-      const collection = await createCollectionExpectSuccess({mode: {type: 'NFT'}});
-      await setCollectionPermissionsExpectSuccess(alice, collection, {nesting: {tokenOwner: true, restricted:[collection]}});
+  itSub('NFT: disallows a non-Owner to nest someone else\'s token (Restricted nesting)', async ({helper}) => {
+    const collection = await helper.nft.mintCollection(alice);
+    const targetToken = await collection.mintToken(alice);
 
-      await addToAllowListExpectSuccess(alice, collection, bob.address);
-      await enableAllowListExpectSuccess(alice, collection);
-      await enablePublicMintingExpectSuccess(alice, collection);
+    await collection.setPermissions(alice, {access: 'AllowList', mintMode: true, nesting: {tokenOwner: true}});
+    await collection.addToAllowList(alice, {Substrate: bob.address});
+    await collection.addToAllowList(alice, targetToken.nestingAccount());
 
-      // Create a token to attempt to be nested into
-      const targetToken = await createItemExpectSuccess(bob, collection, 'NFT');
+    const collectionB = await helper.nft.mintCollection(alice, {permissions: {access: 'AllowList', mintMode: true}});
+    await collectionB.addToAllowList(alice, {Substrate: bob.address});
+    await collectionB.addToAllowList(alice, targetToken.nestingAccount());
 
-      // Try to create a nested token in the wrong collection
-      await expect(executeTransaction(api, alice, api.tx.unique.createItem(
-        collection,
-        {Ethereum: tokenIdToAddress(collection, targetToken)},
-          {nft: {}} as any,
-      )), 'while creating nested token').to.be.rejectedWith(/common\.UserIsNotAllowedToNest/);
+    // Try to create a token to be nested and nest
+    const newToken = await collectionB.mintToken(alice);
+    await expect(newToken.nest(bob, targetToken)).to.be.rejectedWith(/common\.NoPermission/);
 
-      // Try to create and nest a token in the wrong collection
-      const newToken = await createItemExpectSuccess(alice, collection, 'NFT');
-      await expect(executeTransaction(api, alice, api.tx.unique.transfer({Ethereum: tokenIdToAddress(collection, targetToken)}, collection, newToken, 1)), 'while nesting new token').to.be.rejectedWith(/common\.AddressNotInAllowlist/);
-      expect(await getTokenOwner(api, collection, newToken)).to.be.deep.equal({Substrate: alice.address});
-    });
+    expect(await targetToken.getChildren()).to.be.length(0);
+    expect(await newToken.getOwner()).to.be.deep.equal({Substrate: alice.address});
   });
 
-  it('NFT: disallows to nest token in an unlisted collection', async () => {
-    await usingApi(async api => {
-      const collection = await createCollectionExpectSuccess({mode: {type: 'NFT'}});
-      await setCollectionPermissionsExpectSuccess(alice, collection, {nesting: {tokenOwner: true, restricted:[]}});
+  itSub('NFT: disallows to nest token in an unlisted collection', async ({helper}) => {
+    // Create collection with restricted nesting -- even self is not allowed
+    const collection = await helper.nft.mintCollection(alice, {permissions: {access: 'AllowList', mintMode: true, nesting: {tokenOwner: true, restricted: []}}});
+    const targetToken = await collection.mintToken(alice, {Substrate: bob.address});
 
-      // Create a token to attempt to be nested into
-      const targetToken = await createItemExpectSuccess(alice, collection, 'NFT');
+    await collection.addToAllowList(alice, {Substrate: bob.address});
+    await collection.addToAllowList(alice, targetToken.nestingAccount());
 
-      // Try to create a nested token in the wrong collection
-      await expect(executeTransaction(api, alice, api.tx.unique.createItem(
-        collection,
-        {Ethereum: tokenIdToAddress(collection, targetToken)},
-          {nft: {}} as any,
-      )), 'while creating nested token').to.be.rejectedWith(/common\.SourceCollectionIsNotAllowedToNest/);
-
-      // Try to create and nest a token in the wrong collection
-      const newToken = await createItemExpectSuccess(alice, collection, 'NFT');
-      await expect(executeTransaction(api, alice, api.tx.unique.transfer({Ethereum: tokenIdToAddress(collection, targetToken)}, collection, newToken, 1)), 'while nesting new token').to.be.rejectedWith(/common\.SourceCollectionIsNotAllowedToNest/);
-      expect(await getTokenOwner(api, collection, newToken)).to.be.deep.equal({Substrate: alice.address});
-    });
+    // Try to mint in own collection after allowlisting the accounts
+    await expect(collection.mintToken(bob, targetToken.nestingAccount()))
+      .to.be.rejectedWith(/common\.SourceCollectionIsNotAllowedToNest/);
   });
 
   // ---------- Fungible ----------
-
-  it('Fungible: disallows to nest token if nesting is disabled', async () => {
-    await usingApi(async api => {
-      const collectionNFT = await createCollectionExpectSuccess({mode: {type: 'NFT'}});
-      await setCollectionPermissionsExpectSuccess(alice, collectionNFT, {nesting: {}});
-      const targetToken = await createItemExpectSuccess(alice, collectionNFT, 'NFT');
-      const targetAddress = {Ethereum: tokenIdToAddress(collectionNFT, targetToken)};
-
-      const collectionFT = await createCollectionExpectSuccess({mode: {type: 'Fungible', decimalPoints: 0}});
 
-      // Try to create a nested token
-      await expect(executeTransaction(api, alice, api.tx.unique.createItem(
-        collectionFT,
-        targetAddress,
-        {Fungible: {Value: 10}},
-      )), 'while creating nested token').to.be.rejectedWith(/^common\.UserIsNotAllowedToNest$/);
+  itSub('Fungible: disallows to nest token if nesting is disabled', async ({helper}) => {
+    const collectionNFT = await helper.nft.mintCollection(alice);
+    const collectionFT = await helper.ft.mintCollection(alice);
+    const targetToken = await collectionNFT.mintToken(alice);
 
-      // Create a token to be nested
-      const newToken = await createItemExpectSuccess(alice, collectionFT, 'Fungible');
-      // Try to nest
-      await expect(executeTransaction(api, alice, api.tx.unique.transfer(targetAddress, collectionFT, newToken, 1)), 'while nesting new token').to.be.rejectedWith(/common\.UserIsNotAllowedToNest/);
+    // Try to create an immediately nested token
+    await expect(collectionFT.mint(alice, 5n, targetToken.nestingAccount()))
+      .to.be.rejectedWith(/common\.UserIsNotAllowedToNest/);
 
-      // Create another token to be nested
-      const newToken2 = await createItemExpectSuccess(alice, collectionFT, 'Fungible');
-      // Try to nest inside a fungible token
-      await expect(executeTransaction(api, alice, api.tx.unique.transfer({Ethereum: tokenIdToAddress(collectionFT, newToken)}, collectionFT, newToken2, 1)), 'while nesting new token inside fungible').to.be.rejectedWith(/fungible\.FungibleDisallowsNesting/);
-    });
+    // Try to create a token to be nested and nest
+    await collectionFT.mint(alice, 5n);
+    await expect(collectionFT.transfer(alice, targetToken.nestingAccount(), 2n))
+      .to.be.rejectedWith(/common\.UserIsNotAllowedToNest/);
+    expect(await collectionFT.getBalance({Substrate: alice.address})).to.be.equal(5n);
   });
 
-  it('Fungible: disallows a non-Owner to nest someone else\'s token', async () => {
-    await usingApi(async api => {
-      const collectionNFT = await createCollectionExpectSuccess({mode: {type: 'NFT'}});
-      await setCollectionPermissionsExpectSuccess(alice, collectionNFT, {nesting: {tokenOwner: true}});
+  itSub('Fungible: disallows a non-Owner to unnest someone else\'s token', async ({helper}) => {
+    const collectionNFT = await helper.nft.mintCollection(alice, {permissions: {nesting: {collectionAdmin: true, tokenOwner: true}}});
+    const collectionFT = await helper.ft.mintCollection(alice);
+    const targetToken = await collectionNFT.mintToken(alice, {Substrate: bob.address});
 
-      await addToAllowListExpectSuccess(alice, collectionNFT, bob.address);
-      await enableAllowListExpectSuccess(alice, collectionNFT);
-      await enablePublicMintingExpectSuccess(alice, collectionNFT);
+    // Nest some tokens as Alice into Bob's token
+    await collectionFT.mint(alice, 5n, targetToken.nestingAccount());
 
-      // Create a token to attempt to be nested into
-      const targetToken = await createItemExpectSuccess(bob, collectionNFT, 'NFT');
-      const targetAddress = {Ethereum: tokenIdToAddress(collectionNFT, targetToken)};
-
-      const collectionFT = await createCollectionExpectSuccess({mode: {type: 'Fungible', decimalPoints: 0}});
-
-      // Try to create a nested token in the wrong collection
-      await expect(executeTransaction(api, alice, api.tx.unique.createItem(
-        collectionFT,
-        targetAddress,
-        {Fungible: {Value: 10}},
-      )), 'while creating nested token').to.be.rejectedWith(/common\.UserIsNotAllowedToNest/);
-
-      // Try to create and nest a token in the wrong collection
-      const newToken = await createItemExpectSuccess(alice, collectionFT, 'Fungible');
-      await expect(executeTransaction(api, alice, api.tx.unique.transfer(targetAddress, collectionFT, newToken, 1)), 'while nesting new token').to.be.rejectedWith(/common\.UserIsNotAllowedToNest/);
-    });
+    // Try to pull it out
+    await expect(collectionFT.transferFrom(alice, targetToken.nestingAccount(), {Substrate: bob.address}, 1n))
+      .to.be.rejectedWith(/common\.ApprovedValueTooLow/);
+    expect(await collectionFT.getBalance(targetToken.nestingAccount())).to.be.equal(5n);
   });
 
-  it('Fungible: disallows a non-Owner to nest someone else\'s token (Restricted nesting)', async () => {
-    await usingApi(async api => {
-      const collectionNFT = await createCollectionExpectSuccess({mode: {type: 'NFT'}});
-      await addToAllowListExpectSuccess(alice, collectionNFT, bob.address);
-      await enableAllowListExpectSuccess(alice, collectionNFT);
-      await enablePublicMintingExpectSuccess(alice, collectionNFT);
-
-      // Create a token to attempt to be nested into
-      const targetToken = await createItemExpectSuccess(bob, collectionNFT, 'NFT');
-      const targetAddress = {Ethereum: tokenIdToAddress(collectionNFT, targetToken)};
+  itSub('Fungible: disallows a non-Owner to unnest someone else\'s token (Restricted nesting)', async ({helper}) => {
+    const collectionNFT = await helper.nft.mintCollection(alice);
+    const collectionFT = await helper.ft.mintCollection(alice);
+    const targetToken = await collectionNFT.mintToken(alice, {Substrate: bob.address});
 
-      const collectionFT = await createCollectionExpectSuccess({mode: {type: 'Fungible', decimalPoints: 0}});
-      await setCollectionPermissionsExpectSuccess(alice, collectionNFT, {nesting: {tokenOwner: true, restricted:[collectionFT]}});
+    await collectionNFT.setPermissions(alice, {nesting: {collectionAdmin: true, tokenOwner: true, restricted: [collectionFT.collectionId]}});
 
-      // Try to create a nested token in the wrong collection
-      await expect(executeTransaction(api, alice, api.tx.unique.createItem(
-        collectionFT,
-        targetAddress,
-        {Fungible: {Value: 10}},
-      )), 'while creating nested token').to.be.rejectedWith(/common\.UserIsNotAllowedToNest/);
+    // Nest some tokens as Alice into Bob's token
+    await collectionFT.mint(alice, 5n, targetToken.nestingAccount());
 
-      // Try to create and nest a token in the wrong collection
-      const newToken = await createItemExpectSuccess(alice, collectionFT, 'Fungible');
-      await expect(executeTransaction(api, alice, api.tx.unique.transfer(targetAddress, collectionFT, newToken, 1)), 'while nesting new token').to.be.rejectedWith(/common\.UserIsNotAllowedToNest/);
-    });
+    // Try to pull it out as Alice still
+    await expect(collectionFT.transferFrom(alice, targetToken.nestingAccount(), {Substrate: bob.address}, 1n))
+      .to.be.rejectedWith(/common\.ApprovedValueTooLow/);
+    expect(await collectionFT.getBalance(targetToken.nestingAccount())).to.be.equal(5n);
   });
 
-  it('Fungible: disallows to nest token in an unlisted collection', async () => {
-    await usingApi(async api => {
-      const collectionNFT = await createCollectionExpectSuccess({mode: {type: 'NFT'}});
-      await setCollectionPermissionsExpectSuccess(alice, collectionNFT, {nesting: {tokenOwner: true, restricted:[]}});
-
-      // Create a token to attempt to be nested into
-      const targetToken = await createItemExpectSuccess(alice, collectionNFT, 'NFT');
-      const targetAddress = {Ethereum: tokenIdToAddress(collectionNFT, targetToken)};
+  itSub('Fungible: disallows to nest token in an unlisted collection', async ({helper}) => {
+    const collectionNFT = await helper.nft.mintCollection(alice, {permissions: {nesting: {collectionAdmin: true, tokenOwner: true, restricted: []}}});
+    const collectionFT = await helper.ft.mintCollection(alice);
+    const targetToken = await collectionNFT.mintToken(alice);
 
-      const collectionFT = await createCollectionExpectSuccess({mode: {type: 'Fungible', decimalPoints: 0}});
+    // Try to mint an immediately nested token
+    await expect(collectionFT.mint(alice, 5n, targetToken.nestingAccount()))
+      .to.be.rejectedWith(/common\.SourceCollectionIsNotAllowedToNest/);
 
-      // Try to create a nested token in the wrong collection
-      await expect(executeTransaction(api, alice, api.tx.unique.createItem(
-        collectionFT,
-        targetAddress,
-        {Fungible: {Value: 10}},
-      )), 'while creating a nested token').to.be.rejectedWith(/common\.SourceCollectionIsNotAllowedToNest/);
+    // Mint a token and try to nest it
+    await collectionFT.mint(alice, 5n);
+    await expect(collectionFT.transfer(alice, targetToken.nestingAccount(), 1n))
+      .to.be.rejectedWith(/common\.SourceCollectionIsNotAllowedToNest/);
 
-      // Try to create and nest a token in the wrong collection
-      const newToken = await createItemExpectSuccess(alice, collectionFT, 'Fungible');
-      await expect(executeTransaction(api, alice, api.tx.unique.transfer(targetAddress, collectionFT, newToken, 1)), 'while nesting new token').to.be.rejectedWith(/common\.SourceCollectionIsNotAllowedToNest/);
-    });
+    expect(await collectionFT.getBalance(targetToken.nestingAccount())).to.be.equal(0n);
+    expect(await collectionFT.getBalance({Substrate: alice.address})).to.be.equal(5n);
   });
 
   // ---------- Re-Fungible ----------
-
-  it('ReFungible: disallows to nest token if nesting is disabled', async function() {
-    await requirePallets(this, [Pallets.ReFungible]);
 
-    await usingApi(async api => {
-      const collectionNFT = await createCollectionExpectSuccess({mode: {type: 'NFT'}});
-      await setCollectionPermissionsExpectSuccess(alice, collectionNFT, {nesting: {}});
-      const targetToken = await createItemExpectSuccess(alice, collectionNFT, 'NFT');
-      const targetAddress = {Ethereum: tokenIdToAddress(collectionNFT, targetToken)};
-
-      const collectionRFT = await createCollectionExpectSuccess({mode: {type: 'ReFungible'}});
-
-      // Create a nested token
-      await expect(executeTransaction(api, alice, api.tx.unique.createItem(
-        collectionRFT,
-        targetAddress,
-        {ReFungible: {pieces: 100}},
-      )), 'while creating a nested token').to.be.rejectedWith(/^common\.UserIsNotAllowedToNest$/);
+  itSub.ifWithPallets('ReFungible: disallows to nest token if nesting is disabled', [Pallets.ReFungible], async ({helper}) => {
+    const collectionNFT = await helper.nft.mintCollection(alice);
+    const collectionRFT = await helper.rft.mintCollection(alice);
+    const targetToken = await collectionNFT.mintToken(alice);
 
-      // Create a token to be nested
-      const newToken = await createItemExpectSuccess(alice, collectionRFT, 'ReFungible');
-      // Try to nest
-      await transferExpectFailure(collectionRFT, newToken, alice, targetAddress, 100);
-      // Try to nest
-      await expect(executeTransaction(api, alice, api.tx.unique.transfer(targetAddress, collectionRFT, newToken, 1)), 'while nesting new token').to.be.rejectedWith(/common\.UserIsNotAllowedToNest/);
+    // Try to create an immediately nested token
+    await expect(collectionRFT.mintToken(alice, 5n, targetToken.nestingAccount()))
+      .to.be.rejectedWith(/common\.UserIsNotAllowedToNest/);
 
-      // Create another token to be nested
-      const newToken2 = await createItemExpectSuccess(alice, collectionRFT, 'ReFungible');
-      // Try to nest inside a fungible token
-      await expect(executeTransaction(api, alice, api.tx.unique.transfer({Ethereum: tokenIdToAddress(collectionRFT, newToken)}, collectionRFT, newToken2, 1)), 'while nesting new token inside refungible').to.be.rejectedWith(/refungible\.RefungibleDisallowsNesting/);
-    });
+    // Try to create a token to be nested and nest
+    const token = await collectionRFT.mintToken(alice, 5n);
+    await expect(token.transfer(alice, targetToken.nestingAccount(), 2n))
+      .to.be.rejectedWith(/common\.UserIsNotAllowedToNest/);
+    expect(await token.getBalance({Substrate: alice.address})).to.be.equal(5n);
   });
-
-  it('ReFungible: disallows a non-Owner to nest someone else\'s token', async function() {
-    await requirePallets(this, [Pallets.ReFungible]);
 
-    await usingApi(async api => {
-      const collectionNFT = await createCollectionExpectSuccess({mode: {type: 'NFT'}});
-      await setCollectionPermissionsExpectSuccess(alice, collectionNFT, {nesting: {tokenOwner: true}});
+  itSub.ifWithPallets('ReFungible: disallows a non-Owner to nest someone else\'s token', [Pallets.ReFungible], async ({helper}) => {
+    const collectionNFT = await helper.nft.mintCollection(alice);
+    const collectionRFT = await helper.rft.mintCollection(alice);
+    const targetToken = await collectionNFT.mintToken(alice);
 
-      await addToAllowListExpectSuccess(alice, collectionNFT, bob.address);
-      await enableAllowListExpectSuccess(alice, collectionNFT);
-      await enablePublicMintingExpectSuccess(alice, collectionNFT);
+    await collectionNFT.setPermissions(alice, {access: 'AllowList', mintMode: true, nesting: {tokenOwner: true}});
+    await collectionNFT.addToAllowList(alice, {Substrate: bob.address});
+    await collectionNFT.addToAllowList(alice, targetToken.nestingAccount());
 
-      // Create a token to attempt to be nested into
-      const targetToken = await createItemExpectSuccess(bob, collectionNFT, 'NFT');
-      const targetAddress = {Ethereum: tokenIdToAddress(collectionNFT, targetToken)};
+    // Try to create a token to be nested and nest
+    const newToken = await collectionRFT.mintToken(alice);
+    await expect(newToken.transfer(bob, targetToken.nestingAccount())).to.be.rejectedWith(/common\.TokenValueTooLow/);
 
-      const collectionRFT = await createCollectionExpectSuccess({mode: {type: 'ReFungible'}});
+    expect(await targetToken.getChildren()).to.be.length(0);
+    expect(await newToken.getBalance({Substrate: alice.address})).to.be.equal(1n);
 
-      // Try to create a nested token in the wrong collection
-      await expect(executeTransaction(api, alice, api.tx.unique.createItem(
-        collectionRFT,
-        targetAddress,
-        {ReFungible: {pieces: 100}},
-      )), 'while creating a nested token').to.be.rejectedWith(/common\.UserIsNotAllowedToNest/);
+    // Nest some tokens as Alice into Bob's token
+    await newToken.transfer(alice, targetToken.nestingAccount());
 
-      // Try to create and nest a token in the wrong collection
-      const newToken = await createItemExpectSuccess(alice, collectionRFT, 'ReFungible');
-      await expect(executeTransaction(api, alice, api.tx.unique.transfer(targetAddress, collectionRFT, newToken, 1)), 'while nesting new token').to.be.rejectedWith(/common\.UserIsNotAllowedToNest/);
-    });
+    // Try to pull it out
+    await expect(newToken.transferFrom(bob, targetToken.nestingAccount(), {Substrate: alice.address}, 1n))
+      .to.be.rejectedWith(/common\.ApprovedValueTooLow/);
+    expect(await newToken.getBalance(targetToken.nestingAccount())).to.be.equal(1n);
   });
 
-  it('ReFungible: disallows a non-Owner to nest someone else\'s token (Restricted nesting)', async function() {
-    await requirePallets(this, [Pallets.ReFungible]);
+  itSub.ifWithPallets('ReFungible: disallows a non-Owner to nest someone else\'s token (Restricted nesting)', [Pallets.ReFungible], async ({helper}) => {
+    const collectionNFT = await helper.nft.mintCollection(alice);
+    const collectionRFT = await helper.rft.mintCollection(alice);
+    const targetToken = await collectionNFT.mintToken(alice);
 
-    await usingApi(async api => {
-      const collectionNFT = await createCollectionExpectSuccess({mode: {type: 'NFT'}});
-      await addToAllowListExpectSuccess(alice, collectionNFT, bob.address);
-      await enableAllowListExpectSuccess(alice, collectionNFT);
-      await enablePublicMintingExpectSuccess(alice, collectionNFT);
+    await collectionNFT.setPermissions(alice, {access: 'AllowList', mintMode: true, nesting: {tokenOwner: true, restricted: [collectionRFT.collectionId]}});
+    await collectionNFT.addToAllowList(alice, {Substrate: bob.address});
+    await collectionNFT.addToAllowList(alice, targetToken.nestingAccount());
 
-      // Create a token to attempt to be nested into
-      const targetToken = await createItemExpectSuccess(bob, collectionNFT, 'NFT');
-      const targetAddress = {Ethereum: tokenIdToAddress(collectionNFT, targetToken)};
+    // Try to create a token to be nested and nest
+    const newToken = await collectionRFT.mintToken(alice);
+    await expect(newToken.transfer(bob, targetToken.nestingAccount())).to.be.rejectedWith(/common\.TokenValueTooLow/);
 
-      const collectionRFT = await createCollectionExpectSuccess({mode: {type: 'ReFungible'}});
-      await setCollectionPermissionsExpectSuccess(alice, collectionNFT, {nesting: {tokenOwner: true, restricted:[collectionRFT]}});
+    expect(await targetToken.getChildren()).to.be.length(0);
+    expect(await newToken.getBalance({Substrate: alice.address})).to.be.equal(1n);
 
-      // Try to create a nested token in the wrong collection
-      await expect(executeTransaction(api, alice, api.tx.unique.createItem(
-        collectionRFT,
-        targetAddress,
-        {ReFungible: {pieces: 100}},
-      )), 'while creating a nested token').to.be.rejectedWith(/common\.UserIsNotAllowedToNest/);
+    // Nest some tokens as Alice into Bob's token
+    await newToken.transfer(alice, targetToken.nestingAccount());
 
-      // Try to create and nest a token in the wrong collection
-      const newToken = await createItemExpectSuccess(alice, collectionRFT, 'ReFungible');
-      await expect(executeTransaction(api, alice, api.tx.unique.transfer(targetAddress, collectionRFT, newToken, 1)), 'while nesting new token').to.be.rejectedWith(/common\.UserIsNotAllowedToNest/);
-    });
+    // Try to pull it out
+    await expect(newToken.transferFrom(bob, targetToken.nestingAccount(), {Substrate: alice.address}, 1n))
+      .to.be.rejectedWith(/common\.ApprovedValueTooLow/);
+    expect(await newToken.getBalance(targetToken.nestingAccount())).to.be.equal(1n);
   });
 
-  it('ReFungible: disallows to nest token to an unlisted collection', async function() {
-    await requirePallets(this, [Pallets.ReFungible]);
+  itSub.ifWithPallets('ReFungible: disallows to nest token to an unlisted collection', [Pallets.ReFungible], async ({helper}) => {
+    const collectionNFT = await helper.nft.mintCollection(alice, {permissions: {nesting: {tokenOwner: true, restricted: []}}});
+    const collectionRFT = await helper.rft.mintCollection(alice);
+    const targetToken = await collectionNFT.mintToken(alice);
 
-    await usingApi(async api => {
-      const collectionNFT = await createCollectionExpectSuccess({mode: {type: 'NFT'}});
-      await setCollectionPermissionsExpectSuccess(alice, collectionNFT, {nesting: {tokenOwner: true, restricted:[]}});
+    // Try to create an immediately nested token
+    await expect(collectionRFT.mintToken(alice, 5n, targetToken.nestingAccount()))
+      .to.be.rejectedWith(/common\.SourceCollectionIsNotAllowedToNest/);
 
-      // Create a token to attempt to be nested into
-      const targetToken = await createItemExpectSuccess(alice, collectionNFT, 'NFT');
-      const targetAddress = {Ethereum: tokenIdToAddress(collectionNFT, targetToken)};
-
-      const collectionRFT = await createCollectionExpectSuccess({mode: {type: 'ReFungible'}});
-
-      // Try to create a nested token in the wrong collection
-      await expect(executeTransaction(api, alice, api.tx.unique.createItem(
-        collectionRFT,
-        targetAddress,
-        {ReFungible: {pieces: 100}},
-      )), 'while creating a nested token').to.be.rejectedWith(/common\.SourceCollectionIsNotAllowedToNest/);
-
-      // Try to create and nest a token in the wrong collection
-      const newToken = await createItemExpectSuccess(alice, collectionRFT, 'ReFungible');
-      await expect(executeTransaction(api, alice, api.tx.unique.transfer(targetAddress, collectionRFT, newToken, 1)), 'while nesting new token').to.be.rejectedWith(/common\.SourceCollectionIsNotAllowedToNest/);
-    });
+    // Try to create a token to be nested and nest
+    const token = await collectionRFT.mintToken(alice, 5n);
+    await expect(token.transfer(alice, targetToken.nestingAccount(), 2n))
+      .to.be.rejectedWith(/common\.SourceCollectionIsNotAllowedToNest/);
+    expect(await token.getBalance({Substrate: alice.address})).to.be.equal(5n);
   });
 });
modifiedtests/src/nesting/properties.test.tsdiffbeforeafterboth
--- a/tests/src/nesting/properties.test.ts
+++ b/tests/src/nesting/properties.test.ts
@@ -1,1004 +1,788 @@
-import {expect} from 'chai';
-import usingApi, {executeTransaction} from '../substrate/substrate-api';
-import {
-  addCollectionAdminExpectSuccess,
-  CollectionMode,
-  createCollectionExpectSuccess,
-  setCollectionPermissionsExpectSuccess,
-  createItemExpectSuccess,
-  getCreateCollectionResult,
-  transferExpectSuccess,
-  requirePallets,
-  Pallets,
-} from '../util/helpers';
-import {IKeyringPair} from '@polkadot/types/types';
-import {tokenIdToAddress} from '../eth/util/helpers';
+// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.
+// This file is part of Unique Network.
 
-let alice: IKeyringPair;
-let bob: IKeyringPair;
-let charlie: IKeyringPair;
+// Unique Network is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
 
-describe('Composite Properties Test', () => {
-  before(async () => {
-    await usingApi(async (api, privateKeyWrapper) => {
-      alice = privateKeyWrapper('//Alice');
-      bob = privateKeyWrapper('//Bob');
-    });
-  });
+// Unique Network is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+// GNU General Public License for more details.
 
-  async function testMakeSureSuppliesRequired(mode: CollectionMode) {
-    await usingApi(async api => {
-      const collectionId = await createCollectionExpectSuccess({mode: mode});
+// You should have received a copy of the GNU General Public License
+// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
 
-      const collectionOption = await api.rpc.unique.collectionById(collectionId);
-      expect(collectionOption.isSome).to.be.true;
-      let collection = collectionOption.unwrap();
-      expect(collection.tokenPropertyPermissions.toHuman()).to.be.empty;
-      expect(collection.properties.toHuman()).to.be.empty;
+import {IKeyringPair} from '@polkadot/types/types';
+import {itSub, Pallets, requirePalletsOrSkip, usingPlaygrounds, expect} from '../util/playgrounds';
+import {UniqueHelper, UniqueBaseCollection, UniqueNFTCollection, UniqueNFToken, UniqueRFTCollection, UniqueRFToken} from '../util/playgrounds/unique';
 
-      const propertyPermissions = [
-        {key: 'mindgame', permission: {collectionAdmin: true, mutable: false, tokenOwner: true}},
-        {key: 'skullduggery', permission: {collectionAdmin: false, mutable: true, tokenOwner: false}},
-      ];
-      await expect(executeTransaction(
-        api, 
-        alice, 
-        api.tx.unique.setTokenPropertyPermissions(collectionId, propertyPermissions), 
-      )).to.not.be.rejected;
+// ---------- COLLECTION PROPERTIES
 
-      const collectionProperties = [
-        {key: 'black_hole', value: 'LIGO'},
-        {key: 'electron', value: 'come bond'}, 
-      ];
-      await expect(executeTransaction(
-        api, 
-        alice, 
-        api.tx.unique.setCollectionProperties(collectionId, collectionProperties), 
-      )).to.not.be.rejected;
+describe('Integration Test: Collection Properties', () => {
+  let alice: IKeyringPair;
+  let bob: IKeyringPair;
 
-      collection = (await api.rpc.unique.collectionById(collectionId)).unwrap();
-      expect(collection.tokenPropertyPermissions.toHuman()).to.be.deep.equal(propertyPermissions);
-      expect(collection.properties.toHuman()).to.be.deep.equal(collectionProperties);
+  before(async () => {
+    await usingPlaygrounds(async (helper, privateKey) => {
+      const donor = privateKey('//Alice');
+      [alice, bob] = await helper.arrange.createAccounts([50n, 10n], donor);
     });
-  }
+  });
 
-  it('Makes sure collectionById supplies required fields for NFT', async () => {
-    await testMakeSureSuppliesRequired({type: 'NFT'});
+  itSub('Properties are initially empty', async ({helper}) => {
+    const collection = await helper.nft.mintCollection(alice);
+    expect(await collection.getProperties()).to.be.empty;
   });
 
-  it('Makes sure collectionById supplies required fields for ReFungible', async function() {
-    await requirePallets(this, [Pallets.ReFungible]);
+  async function testSetsPropertiesForCollection(collection: UniqueBaseCollection) {
+    // As owner
+    await expect(collection.setProperties(alice, [{key: 'electron', value: 'come bond'}])).to.be.fulfilled;
+
+    await collection.addAdmin(alice, {Substrate: bob.address});
 
-    await testMakeSureSuppliesRequired({type: 'ReFungible'});
-  });
-});
+    // As administrator
+    await expect(collection.setProperties(bob, [{key: 'black_hole'}])).to.be.fulfilled;
 
-// ---------- COLLECTION PROPERTIES
+    const properties = await collection.getProperties();
+    expect(properties).to.include.deep.members([
+      {key: 'electron', value: 'come bond'},
+      {key: 'black_hole', value: ''},
+    ]);
+  }
 
-describe('Integration Test: Collection Properties', () => {
-  before(async () => {
-    await usingApi(async (api, privateKeyWrapper) => {
-      alice = privateKeyWrapper('//Alice');
-      bob = privateKeyWrapper('//Bob');
-    });
+  itSub('Sets properties for a NFT collection', async ({helper}) =>  {
+    await testSetsPropertiesForCollection(await helper.nft.mintCollection(alice));
   });
 
-  it('Reads properties from a collection', async () => {
-    await usingApi(async api => {
-      const collection = await createCollectionExpectSuccess();
-      const properties = (await api.query.common.collectionProperties(collection)).toJSON();
-      expect(properties.map).to.be.empty;
-      expect(properties.consumedSpace).to.equal(0);
-    });
+  itSub.ifWithPallets('Sets properties for a ReFungible collection', [Pallets.ReFungible], async ({helper}) => {
+    await testSetsPropertiesForCollection(await helper.rft.mintCollection(alice));
   });
 
+  async function testCheckValidNames(collection: UniqueBaseCollection) {
+    // alpha symbols
+    await expect(collection.setProperties(alice, [{key: 'answer'}])).to.be.fulfilled;
 
-  async function testSetsPropertiesForCollection(mode: string) {
-    await usingApi(async api => {
-      const events = await executeTransaction(api, bob, api.tx.unique.createCollectionEx({mode: mode}));
-      const {collectionId} = getCreateCollectionResult(events);
+    // numeric symbols
+    await expect(collection.setProperties(alice, [{key: '451'}])).to.be.fulfilled;
 
-      // As owner
-      await expect(executeTransaction(
-        api, 
-        bob, 
-        api.tx.unique.setCollectionProperties(collectionId, [{key: 'electron', value: 'come bond'}]), 
-      )).to.not.be.rejected;
+    // underscore symbol
+    await expect(collection.setProperties(alice, [{key: 'black_hole'}])).to.be.fulfilled;
 
-      await addCollectionAdminExpectSuccess(bob, collectionId, alice.address);
+    // dash symbol
+    await expect(collection.setProperties(alice, [{key: '-'}])).to.be.fulfilled;
 
-      // As administrator
-      await expect(executeTransaction(
-        api, 
-        alice, 
-        api.tx.unique.setCollectionProperties(collectionId, [{key: 'black_hole'}]), 
-      )).to.not.be.rejected;
+    // dot symbol
+    await expect(collection.setProperties(alice, [{key: 'once.in.a.long.long.while...', value: 'you get a little lost'}])).to.be.fulfilled;
 
-      const properties = (await api.rpc.unique.collectionProperties(collectionId, ['electron', 'black_hole'])).toHuman();
-      expect(properties).to.be.deep.equal([
-        {key: 'electron', value: 'come bond'},
-        {key: 'black_hole', value: ''},
-      ]);
-    });
+    const properties = await collection.getProperties();
+    expect(properties).to.include.deep.members([
+      {key: 'answer', value: ''},
+      {key: '451', value: ''},
+      {key: 'black_hole', value: ''},
+      {key: '-', value: ''},
+      {key: 'once.in.a.long.long.while...', value: 'you get a little lost'},
+    ]);
   }
-  it('Sets properties for a NFT collection', async () => {
-    await testSetsPropertiesForCollection('NFT');
-  });
-  it('Sets properties for a ReFungible collection', async function() {
-    await requirePallets(this, [Pallets.ReFungible]);
 
-    await testSetsPropertiesForCollection('ReFungible');
+  itSub('Check valid names for NFT collection properties keys', async ({helper}) =>  {
+    await testCheckValidNames(await helper.nft.mintCollection(alice));
   });
 
-  async function testCheckValidNames(mode: string) {
-    await usingApi(async api => {
-      const events = await executeTransaction(api, bob, api.tx.unique.createCollectionEx({mode: mode}));
-      const {collectionId} = getCreateCollectionResult(events);
-  
-      // alpha symbols
-      await expect(executeTransaction(
-        api, 
-        bob, 
-        api.tx.unique.setCollectionProperties(collectionId, [{key: 'alpha'}]), 
-      )).to.not.be.rejected;
-  
-      // numeric symbols
-      await expect(executeTransaction(
-        api, 
-        bob, 
-        api.tx.unique.setCollectionProperties(collectionId, [{key: '123'}]), 
-      )).to.not.be.rejected;
-  
-      // underscore symbol
-      await expect(executeTransaction(
-        api, 
-        bob, 
-        api.tx.unique.setCollectionProperties(collectionId, [{key: 'black_hole'}]), 
-      )).to.not.be.rejected;
-  
-      // dash symbol
-      await expect(executeTransaction(
-        api, 
-        bob, 
-        api.tx.unique.setCollectionProperties(collectionId, [{key: 'semi-automatic'}]), 
-      )).to.not.be.rejected;
-  
-      // underscore symbol
-      await expect(executeTransaction(
-        api, 
-        bob, 
-        api.tx.unique.setCollectionProperties(collectionId, [{key: 'build.rs'}]), 
-      )).to.not.be.rejected;
-  
-      const propertyKeys = ['alpha', '123', 'black_hole', 'semi-automatic', 'build.rs'];
-      const properties = (await api.rpc.unique.collectionProperties(collectionId, propertyKeys)).toHuman();
-      expect(properties).to.be.deep.equal([
-        {key: 'alpha', value: ''},
-        {key: '123', value: ''},
-        {key: 'black_hole', value: ''},
-        {key: 'semi-automatic', value: ''},
-        {key: 'build.rs', value: ''},
-      ]);
-    });
-  }
-  it('Check valid names for NFT collection properties keys', async () => {
-    await testCheckValidNames('NFT');
+  itSub.ifWithPallets('Check valid names for ReFungible collection properties keys', [Pallets.ReFungible], async ({helper}) => {
+    await testCheckValidNames(await helper.rft.mintCollection(alice));
   });
-  it('Check valid names for ReFungible collection properties keys', async function() {
-    await requirePallets(this, [Pallets.ReFungible]);
 
-    await testCheckValidNames('ReFungible');
-  });
+  async function testChangesProperties(collection: UniqueBaseCollection) {
+    await expect(collection.setProperties(alice, [{key: 'electron', value: 'come bond'}, {key: 'black_hole', value: ''}])).to.be.fulfilled;
 
-  async function testChangesProperties(mode: CollectionMode) {
-    await usingApi(async api => {
-      const collection = await createCollectionExpectSuccess({mode: mode});
-  
-      await expect(executeTransaction(
-        api, 
-        alice, 
-        api.tx.unique.setCollectionProperties(collection, [{key: 'electron', value: 'come bond'}, {key: 'black_hole'}]), 
-      )).to.not.be.rejected;
-  
-      // Mutate the properties
-      await expect(executeTransaction(
-        api, 
-        alice, 
-        api.tx.unique.setCollectionProperties(collection, [{key: 'electron', value: 'bonded'}, {key: 'black_hole', value: 'LIGO'}]), 
-      )).to.not.be.rejected;
-  
-      const properties = (await api.rpc.unique.collectionProperties(collection, ['electron', 'black_hole'])).toHuman();
-      expect(properties).to.be.deep.equal([
-        {key: 'electron', value: 'bonded'},
-        {key: 'black_hole', value: 'LIGO'},
-      ]);
-    });
+    // Mutate the properties
+    await expect(collection.setProperties(alice, [{key: 'black_hole', value: 'LIGO'}])).to.be.fulfilled;
+
+    const properties = await collection.getProperties();
+    expect(properties).to.include.deep.members([
+      {key: 'electron', value: 'come bond'},
+      {key: 'black_hole', value: 'LIGO'},
+    ]);
   }
-  it('Changes properties of a NFT collection', async () => {
-    await testChangesProperties({type: 'NFT'});
+
+  itSub('Changes properties of a NFT collection', async ({helper}) =>  {
+    await testChangesProperties(await helper.nft.mintCollection(alice));
   });
-  it('Changes properties of a ReFungible collection', async function() {
-    await requirePallets(this, [Pallets.ReFungible]);
 
-    await testChangesProperties({type: 'ReFungible'});
+  itSub.ifWithPallets('Changes properties of a ReFungible collection', [Pallets.ReFungible], async ({helper}) => {
+    await testChangesProperties(await helper.rft.mintCollection(alice));
   });
 
-  async function testDeleteProperties(mode: CollectionMode) {
-    await usingApi(async api => {
-      const collection = await createCollectionExpectSuccess({mode: mode});
-  
-      await expect(executeTransaction(
-        api, 
-        alice, 
-        api.tx.unique.setCollectionProperties(collection, [{key: 'electron', value: 'come bond'}, {key: 'black_hole', value: 'LIGO'}]), 
-      )).to.not.be.rejected;
-  
-      await expect(executeTransaction(
-        api, 
-        alice, 
-        api.tx.unique.deleteCollectionProperties(collection, ['electron']), 
-      )).to.not.be.rejected;
-  
-      const properties = (await api.rpc.unique.collectionProperties(collection, ['electron', 'black_hole'])).toHuman();
-      expect(properties).to.be.deep.equal([
-        {key: 'black_hole', value: 'LIGO'},
-      ]);
-    });  
+  async function testDeleteProperties(collection: UniqueBaseCollection) {
+    await expect(collection.setProperties(alice, [{key: 'electron', value: 'come bond'}, {key: 'black_hole', value: 'LIGO'}])).to.be.fulfilled;
+
+    await expect(collection.deleteProperties(alice, ['electron'])).to.be.fulfilled;
+
+    const properties = await collection.getProperties(['black_hole', 'electron']);
+    expect(properties).to.be.deep.equal([
+      {key: 'black_hole', value: 'LIGO'},
+    ]);
   }
-  it('Deletes properties of a NFT collection', async () => {
-    await testDeleteProperties({type: 'NFT'});
+
+  itSub('Deletes properties of a NFT collection', async ({helper}) =>  {
+    await testDeleteProperties(await helper.nft.mintCollection(alice));
   });
-  it('Deletes properties of a ReFungible collection', async function() {
-    await requirePallets(this, [Pallets.ReFungible]);
 
-    await testDeleteProperties({type: 'ReFungible'});
+  itSub.ifWithPallets('Deletes properties of a ReFungible collection', [Pallets.ReFungible], async ({helper}) => {
+    await testDeleteProperties(await helper.rft.mintCollection(alice));
   });
 });
 
 describe('Negative Integration Test: Collection Properties', () => {
+  let alice: IKeyringPair;
+  let bob: IKeyringPair;
+
   before(async () => {
-    await usingApi(async (api, privateKeyWrapper) => {
-      alice = privateKeyWrapper('//Alice');
-      bob = privateKeyWrapper('//Bob');
+    await usingPlaygrounds(async (helper, privateKey) => {
+      const donor = privateKey('//Alice');
+      [alice, bob] = await helper.arrange.createAccounts([100n, 10n], donor);
     });
   });
-  
-  async function testFailsSetPropertiesIfNotOwnerOrAdmin(mode: CollectionMode) {
-    await usingApi(async api => {
-      const collection = await createCollectionExpectSuccess({mode: mode});
   
-      await expect(executeTransaction(
-        api, 
-        bob, 
-        api.tx.unique.setCollectionProperties(collection, [{key: 'electron', value: 'come bond'}, {key: 'black_hole', value: 'LIGO'}]), 
-      )).to.be.rejectedWith(/common\.NoPermission/);
-  
-      const properties = (await api.query.common.collectionProperties(collection)).toJSON();
-      expect(properties.map).to.be.empty;
-      expect(properties.consumedSpace).to.equal(0);
-    });  
+  async function testFailsSetPropertiesIfNotOwnerOrAdmin(collection: UniqueBaseCollection) {  
+    await expect(collection.setProperties(bob, [{key: 'electron', value: 'come bond'}, {key: 'black_hole', value: 'LIGO'}]))
+      .to.be.rejectedWith(/common\.NoPermission/);
+
+    expect(await collection.getProperties()).to.be.empty;
   }
-  it('Fails to set properties in a NFT collection if not its onwer/administrator', async () => {
-    await testFailsSetPropertiesIfNotOwnerOrAdmin({type: 'NFT'});
+
+  itSub('Fails to set properties in a NFT collection if not its onwer/administrator', async ({helper}) =>  {
+    await testFailsSetPropertiesIfNotOwnerOrAdmin(await helper.nft.mintCollection(alice));
   });
-  it('Fails to set properties in a ReFungible collection if not its onwer/administrator', async function() {
-    await requirePallets(this, [Pallets.ReFungible]);
 
-    await testFailsSetPropertiesIfNotOwnerOrAdmin({type: 'ReFungible'});
+  itSub.ifWithPallets('Fails to set properties in a ReFungible collection if not its onwer/administrator', [Pallets.ReFungible], async ({helper}) => {
+    await testFailsSetPropertiesIfNotOwnerOrAdmin(await helper.rft.mintCollection(alice));
   });
   
-  async function testFailsSetPropertiesThatExeedLimits(mode: CollectionMode) {
-    await usingApi(async api => {
-      const collection = await createCollectionExpectSuccess({mode: mode});
-      const spaceLimit = (await api.query.common.collectionProperties(collection)).toJSON().spaceLimit as number; 
+  async function testFailsSetPropertiesThatExeedLimits(collection: UniqueBaseCollection) {
+    const spaceLimit = (await (collection.helper!.api! as any).query.common.collectionProperties(collection.collectionId)).spaceLimit.toNumber();
   
-      // Mute the general tx parsing error, too many bytes to process
-      {
-        console.error = () => {};
-        await expect(executeTransaction(
-          api, 
-          alice, 
-          api.tx.unique.setCollectionProperties(collection, [{key: 'electron', value: 'low high '.repeat(Math.ceil(spaceLimit! / 9))}]), 
-        )).to.be.rejected;
-      }
-  
-      let properties = (await api.rpc.unique.collectionProperties(collection, ['electron'])).toJSON();
-      expect(properties).to.be.empty;
-  
-      await expect(executeTransaction(
-        api, 
-        alice, 
-        api.tx.unique.setCollectionProperties(collection, [
-          {key: 'electron', value: 'low high '.repeat(Math.ceil(spaceLimit! / 18))}, 
-          {key: 'black_hole', value: '0'.repeat(Math.ceil(spaceLimit! / 2))}, 
-        ]), 
-      )).to.be.rejectedWith(/common\.NoSpaceForProperty/);
-  
-      properties = (await api.rpc.unique.collectionProperties(collection, ['electron', 'black hole'])).toJSON();
-      expect(properties).to.be.empty;
-    });  
+    // Mute the general tx parsing error, too many bytes to process
+    {
+      console.error = () => {};
+      await expect(collection.setProperties(alice, [
+        {key: 'electron', value: 'low high '.repeat(Math.ceil(spaceLimit! / 9))},
+      ])).to.be.rejected;
+    }
+
+    expect(await collection.getProperties(['electron'])).to.be.empty;
+
+    await expect(collection.setProperties(alice, [
+      {key: 'electron', value: 'low high '.repeat(Math.ceil(spaceLimit! / 18))}, 
+      {key: 'black_hole', value: '0'.repeat(Math.ceil(spaceLimit! / 2))}, 
+    ])).to.be.rejectedWith(/common\.NoSpaceForProperty/);
+
+    expect(await collection.getProperties(['electron', 'black_hole'])).to.be.empty;
   }
-  it('Fails to set properties that exceed the limits (NFT)', async () => {
-    await testFailsSetPropertiesThatExeedLimits({type: 'NFT'});
+
+  itSub('Fails to set properties that exceed the limits (NFT)', async ({helper}) =>  {
+    await testFailsSetPropertiesThatExeedLimits(await helper.nft.mintCollection(alice));
   });
-  it('Fails to set properties that exceed the limits (ReFungible)', async function() {
-    await requirePallets(this, [Pallets.ReFungible]);
 
-    await testFailsSetPropertiesThatExeedLimits({type: 'ReFungible'});
+  itSub.ifWithPallets('Fails to set properties that exceed the limits (ReFungible)', [Pallets.ReFungible], async ({helper}) => {
+    await testFailsSetPropertiesThatExeedLimits(await helper.rft.mintCollection(alice));
   });
   
-  async function testFailsSetMorePropertiesThanAllowed(mode: CollectionMode) {
-    await usingApi(async api => {
-      const collection = await createCollectionExpectSuccess({mode: mode});
-  
-      const propertiesToBeSet = [];
-      for (let i = 0; i < 65; i++) {
-        propertiesToBeSet.push({
-          key: 'electron_' + i,
-          value: Math.random() > 0.5 ? 'high' : 'low',
-        });
-      }
-  
-      await expect(executeTransaction(
-        api, 
-        alice, 
-        api.tx.unique.setCollectionProperties(collection, propertiesToBeSet), 
-      )).to.be.rejectedWith(/common\.PropertyLimitReached/);
-  
-      const properties = (await api.query.common.collectionProperties(collection)).toJSON();
-      expect(properties.map).to.be.empty;
-      expect(properties.consumedSpace).to.equal(0);
-    });  
+  async function testFailsSetMorePropertiesThanAllowed(collection: UniqueBaseCollection) {
+    const propertiesToBeSet = [];
+    for (let i = 0; i < 65; i++) {
+      propertiesToBeSet.push({
+        key: 'electron_' + i,
+        value: Math.random() > 0.5 ? 'high' : 'low',
+      });
+    }
+
+    await expect(collection.setProperties(alice, propertiesToBeSet)).
+      to.be.rejectedWith(/common\.PropertyLimitReached/);
+
+    expect(await collection.getProperties()).to.be.empty;
   }
-  it('Fails to set more properties than it is allowed (NFT)', async () => {
-    await testFailsSetMorePropertiesThanAllowed({type: 'NFT'});
+
+  itSub('Fails to set more properties than it is allowed (NFT)', async ({helper}) =>  {
+    await testFailsSetMorePropertiesThanAllowed(await helper.nft.mintCollection(alice));
   });
-  it('Fails to set more properties than it is allowed (ReFungible)', async function() {
-    await requirePallets(this, [Pallets.ReFungible]);
 
-    await testFailsSetMorePropertiesThanAllowed({type: 'ReFungible'});
+  itSub.ifWithPallets('Fails to set more properties than it is allowed (ReFungible)', [Pallets.ReFungible], async ({helper}) => {
+    await testFailsSetMorePropertiesThanAllowed(await helper.rft.mintCollection(alice));
   });
-  
-  async function testFailsSetPropertiesWithInvalidNames(mode: CollectionMode) {
-    await usingApi(async api => {
-      const collection = await createCollectionExpectSuccess({mode: mode});
-  
-      const invalidProperties = [
-        [{key: 'electron', value: 'negative'}, {key: 'string theory', value: 'understandable'}],
-        [{key: 'Mr/Sandman', value: 'Bring me a gene'}],
-        [{key: 'déjà vu', value: 'hmm...'}],
-      ];
   
-      for (let i = 0; i < invalidProperties.length; i++) {
-        await expect(executeTransaction(
-          api, 
-          alice, 
-          api.tx.unique.setCollectionProperties(collection, invalidProperties[i]), 
-        ), `on rejecting the new badly-named property #${i}`).to.be.rejectedWith(/common\.InvalidCharacterInPropertyKey/);
-      }
-  
-      await expect(executeTransaction(
-        api, 
-        alice, 
-        api.tx.unique.setCollectionProperties(collection, [{key: '', value: 'nothing must not exist'}]), 
-      ), 'on rejecting an unnamed property').to.be.rejectedWith(/common\.EmptyPropertyKey/);
-  
-      await expect(executeTransaction(
-        api, 
-        alice, 
-        api.tx.unique.setCollectionProperties(collection, [
-          {key: 'CRISPR-Cas9', value: 'rewriting nature!'},
-        ]), 
-      ), 'on setting the correctly-but-still-badly-named property').to.not.be.rejected;
-  
-      const keys = invalidProperties.flatMap(propertySet => propertySet.map(property => property.key)).concat('CRISPR-Cas9').concat('');
-  
-      const properties = (await api.rpc.unique.collectionProperties(collection, keys)).toHuman();
-      expect(properties).to.be.deep.equal([
-        {key: 'CRISPR-Cas9', value: 'rewriting nature!'},
-      ]);
-  
-      for (let i = 0; i < invalidProperties.length; i++) {
-        await expect(executeTransaction(
-          api, 
-          alice, 
-          api.tx.unique.deleteCollectionProperties(collection, invalidProperties[i].map(propertySet => propertySet.key)), 
-        ), `on trying to delete the non-existent badly-named property #${i}`).to.be.rejectedWith(/common\.InvalidCharacterInPropertyKey/);
-      }
-    });
+  async function testFailsSetPropertiesWithInvalidNames(collection: UniqueBaseCollection) {
+    const invalidProperties = [
+      [{key: 'electron', value: 'negative'}, {key: 'string theory', value: 'understandable'}],
+      [{key: 'Mr/Sandman', value: 'Bring me a gene'}],
+      [{key: 'déjà vu', value: 'hmm...'}],
+    ];
+
+    for (let i = 0; i < invalidProperties.length; i++) {
+      await expect(
+        collection.setProperties(alice, invalidProperties[i]), 
+        `on rejecting the new badly-named property #${i}`,
+      ).to.be.rejectedWith(/common\.InvalidCharacterInPropertyKey/);
+    }
+
+    await expect(
+      collection.setProperties(alice, [{key: '', value: 'nothing must not exist'}]), 
+      'on rejecting an unnamed property',
+    ).to.be.rejectedWith(/common\.EmptyPropertyKey/);
+
+    await expect(
+      collection.setProperties(alice, [{key: 'CRISPR-Cas9', value: 'rewriting nature!'}]), 
+      'on setting the correctly-but-still-badly-named property',
+    ).to.be.fulfilled;
+
+    const keys = invalidProperties.flatMap(propertySet => propertySet.map(property => property.key)).concat('CRISPR-Cas9').concat('');
+
+    const properties = await collection.getProperties(keys);
+    expect(properties).to.be.deep.equal([
+      {key: 'CRISPR-Cas9', value: 'rewriting nature!'},
+    ]);
+
+    for (let i = 0; i < invalidProperties.length; i++) {
+      await expect(
+        collection.deleteProperties(alice, invalidProperties[i].map(propertySet => propertySet.key)), 
+        `on trying to delete the non-existent badly-named property #${i}`,
+      ).to.be.rejectedWith(/common\.InvalidCharacterInPropertyKey/);
+    }
   }
-  it('Fails to set properties with invalid names (NFT)', async () => {
-    await testFailsSetPropertiesWithInvalidNames({type: 'NFT'});
+
+  itSub('Fails to set properties with invalid names (NFT)', async ({helper}) =>  {
+    await testFailsSetPropertiesWithInvalidNames(await helper.nft.mintCollection(alice));
   });
-  it('Fails to set properties with invalid names (ReFungible)', async function() {
-    await requirePallets(this, [Pallets.ReFungible]);
 
-    await testFailsSetPropertiesWithInvalidNames({type: 'ReFungible'});
+  itSub.ifWithPallets('Fails to set properties with invalid names (ReFungible)', [Pallets.ReFungible], async ({helper}) => {
+    await testFailsSetPropertiesWithInvalidNames(await helper.rft.mintCollection(alice));
   });
 });
 
 // ---------- ACCESS RIGHTS
 
 describe('Integration Test: Access Rights to Token Properties', () => {
+  let alice: IKeyringPair;
+  let bob: IKeyringPair;
+
   before(async () => {
-    await usingApi(async (api, privateKeyWrapper) => {
-      alice = privateKeyWrapper('//Alice');
-      bob = privateKeyWrapper('//Bob');
+    await usingPlaygrounds(async (helper, privateKey) => {
+      const donor = privateKey('//Alice');
+      [alice, bob] = await helper.arrange.createAccounts([100n, 10n], donor);
     });
   });
   
-  it('Reads access rights to properties of a collection', async () => {
-    await usingApi(async api => {
-      const collection = await createCollectionExpectSuccess();
-      const propertyRights = (await api.query.common.collectionPropertyPermissions(collection)).toJSON();
-      expect(propertyRights).to.be.empty;
-    });
+  itSub('Reads access rights to properties of a collection', async ({helper}) =>  {
+    const collection = await helper.nft.mintCollection(alice);
+    const propertyRights = (await helper.api!.query.common.collectionPropertyPermissions(collection.collectionId)).toJSON();
+    expect(propertyRights).to.be.empty;
   });
   
-  async function testSetsAccessRightsToProperties(mode: CollectionMode) {
-    await usingApi(async api => {
-      const collection = await createCollectionExpectSuccess({mode: mode});
-  
-      await expect(executeTransaction(
-        api, 
-        alice, 
-        api.tx.unique.setTokenPropertyPermissions(collection, [{key: 'skullduggery', permission: {mutable: true}}]), 
-      )).to.not.be.rejected;
-  
-      await addCollectionAdminExpectSuccess(alice, collection, bob.address);
-  
-      await expect(executeTransaction(
-        api, 
-        alice, 
-        api.tx.unique.setTokenPropertyPermissions(collection, [{key: 'mindgame', permission: {collectionAdmin: true, tokenOwner: false}}]), 
-      )).to.not.be.rejected;
-  
-      const propertyRights = (await api.rpc.unique.propertyPermissions(collection, ['skullduggery', 'mindgame'])).toHuman();
-      expect(propertyRights).to.be.deep.equal([
-        {key: 'skullduggery', permission: {'mutable': true, 'collectionAdmin': false, 'tokenOwner': false}},
-        {key: 'mindgame', permission: {'mutable': false, 'collectionAdmin': true, 'tokenOwner': false}},
-      ]);
-    });  
+  async function testSetsAccessRightsToProperties(collection: UniqueNFTCollection | UniqueRFTCollection) {  
+    await expect(collection.setTokenPropertyPermissions(alice, [{key: 'skullduggery', permission: {mutable: true}}]))
+      .to.be.fulfilled;
+
+    await collection.addAdmin(alice, {Substrate: bob.address});
+
+    await expect(collection.setTokenPropertyPermissions(bob, [{key: 'mindgame', permission: {collectionAdmin: true, tokenOwner: false}}]))
+      .to.be.fulfilled;
+
+    const propertyRights = await collection.getPropertyPermissions(['skullduggery', 'mindgame']);
+    expect(propertyRights).to.include.deep.members([
+      {key: 'skullduggery', permission: {mutable: true, collectionAdmin: false, tokenOwner: false}},
+      {key: 'mindgame', permission: {mutable: false, collectionAdmin: true, tokenOwner: false}},
+    ]);
   }
-  it('Sets access rights to properties of a collection (NFT)', async () => {
-    await testSetsAccessRightsToProperties({type: 'NFT'});
+
+  itSub('Sets access rights to properties of a collection (NFT)', async ({helper}) =>  {
+    await testSetsAccessRightsToProperties(await helper.nft.mintCollection(alice));
   });
-  it('Sets access rights to properties of a collection (ReFungible)', async function() {
-    await requirePallets(this, [Pallets.ReFungible]);
 
-    await testSetsAccessRightsToProperties({type: 'ReFungible'});
+  itSub.ifWithPallets('Sets access rights to properties of a collection (ReFungible)', [Pallets.ReFungible], async ({helper}) => {
+    await testSetsAccessRightsToProperties(await helper.rft.mintCollection(alice));
   });
-  
-  async function testChangesAccessRightsToProperty(mode: CollectionMode) {
-    await usingApi(async api => {
-      const collection = await createCollectionExpectSuccess({mode: mode});
   
-      await expect(executeTransaction(
-        api, 
-        alice, 
-        api.tx.unique.setTokenPropertyPermissions(collection, [{key: 'skullduggery', permission: {mutable: true, collectionAdmin: true}}]), 
-      )).to.not.be.rejected;
-  
-      await expect(executeTransaction(
-        api, 
-        alice, 
-        api.tx.unique.setTokenPropertyPermissions(collection, [{key: 'skullduggery', permission: {mutable: false, tokenOwner: true}}]), 
-      )).to.not.be.rejected;
-  
-      const propertyRights = (await api.rpc.unique.propertyPermissions(collection, ['skullduggery'])).toHuman();
-      expect(propertyRights).to.be.deep.equal([
-        {key: 'skullduggery', permission: {'mutable': false, 'collectionAdmin': false, 'tokenOwner': true}},
-      ]);
-    });
+  async function testChangesAccessRightsToProperty(collection: UniqueNFTCollection | UniqueRFTCollection) {
+    await expect(collection.setTokenPropertyPermissions(alice, [{key: 'skullduggery', permission: {mutable: true, collectionAdmin: true}}]))
+      .to.be.fulfilled;
+
+    await expect(collection.setTokenPropertyPermissions(alice, [{key: 'skullduggery', permission: {mutable: false, tokenOwner: true}}]))
+      .to.be.fulfilled;
+
+    const propertyRights = await collection.getPropertyPermissions();
+    expect(propertyRights).to.be.deep.equal([
+      {key: 'skullduggery', permission: {'mutable': false, 'collectionAdmin': false, 'tokenOwner': true}},
+    ]);
   }
-  it('Changes access rights to properties of a NFT collection', async () => {
-    await testChangesAccessRightsToProperty({type: 'NFT'});
+
+  itSub('Changes access rights to properties of a NFT collection', async ({helper}) =>  {
+    await testChangesAccessRightsToProperty(await helper.nft.mintCollection(alice));
   });
-  it('Changes access rights to properties of a ReFungible collection', async function() {
-    await requirePallets(this, [Pallets.ReFungible]);
 
-    await testChangesAccessRightsToProperty({type: 'ReFungible'});
+  itSub.ifWithPallets('Changes access rights to properties of a ReFungible collection', [Pallets.ReFungible], async ({helper}) => {
+    await testChangesAccessRightsToProperty(await helper.rft.mintCollection(alice));
   });
 });
 
 describe('Negative Integration Test: Access Rights to Token Properties', () => {
+  let alice: IKeyringPair;
+  let bob: IKeyringPair;
+
   before(async () => {
-    await usingApi(async (api, privateKeyWrapper) => {
-      alice = privateKeyWrapper('//Alice');
-      bob = privateKeyWrapper('//Bob');
+    await usingPlaygrounds(async (helper, privateKey) => {
+      const donor = privateKey('//Alice');
+      [alice, bob] = await helper.arrange.createAccounts([50n, 10n], donor);
     });
   });
 
-  async function testPreventsFromSettingAccessRightsNotAdminOrOwner(mode: CollectionMode) {
-    await usingApi(async api => {
-      const collection = await createCollectionExpectSuccess({mode: mode});
-  
-      await expect(executeTransaction(
-        api, 
-        bob, 
-        api.tx.unique.setTokenPropertyPermissions(collection, [{key: 'skullduggery', permission: {mutable: true, tokenOwner: true}}]), 
-      )).to.be.rejectedWith(/common\.NoPermission/);
-  
-      const propertyRights = (await api.rpc.unique.propertyPermissions(collection, ['skullduggery'])).toJSON();
-      expect(propertyRights).to.be.empty;
-    });
+  async function testPreventsFromSettingAccessRightsNotAdminOrOwner(collection: UniqueNFTCollection | UniqueRFTCollection) {
+    await expect(collection.setTokenPropertyPermissions(bob, [{key: 'skullduggery', permission: {mutable: true, tokenOwner: true}}]))
+      .to.be.rejectedWith(/common\.NoPermission/);
+
+    const propertyRights = await collection.getPropertyPermissions(['skullduggery']);
+    expect(propertyRights).to.be.empty;
   }
-  it('Prevents from setting access rights to properties of a NFT collection if not an onwer/admin', async () => {
-    await testPreventsFromSettingAccessRightsNotAdminOrOwner({type: 'NFT'});
+
+  itSub('Prevents from setting access rights to properties of a NFT collection if not an onwer/admin', async ({helper}) =>  {
+    await testPreventsFromSettingAccessRightsNotAdminOrOwner(await helper.nft.mintCollection(alice));
   });
-  it('Prevents from setting access rights to properties of a ReFungible collection if not an onwer/admin', async function() {
-    await requirePallets(this, [Pallets.ReFungible]);
 
-    await testPreventsFromSettingAccessRightsNotAdminOrOwner({type: 'ReFungible'});
+  itSub.ifWithPallets('Prevents from setting access rights to properties of a ReFungible collection if not an onwer/admin', [Pallets.ReFungible], async ({helper}) => {
+    await testPreventsFromSettingAccessRightsNotAdminOrOwner(await helper.rft.mintCollection(alice));
   });
 
-  async function testPreventFromAddingTooManyPossibleProperties(mode: CollectionMode) {
-    await usingApi(async api => {
-      const collection = await createCollectionExpectSuccess({mode: mode});
-  
-      const constitution = [];
-      for (let i = 0; i < 65; i++) {
-        constitution.push({
-          key: 'property_' + i,
-          permission: Math.random() > 0.5 ? {mutable: true, collectionAdmin: true, tokenOwner: true} : {},
-        });
-      }
-  
-      await expect(executeTransaction(
-        api, 
-        alice, 
-        api.tx.unique.setTokenPropertyPermissions(collection, constitution), 
-      )).to.be.rejectedWith(/common\.PropertyLimitReached/);
-  
-      const propertyRights = (await api.query.common.collectionPropertyPermissions(collection)).toJSON();
-      expect(propertyRights).to.be.empty;
-    });  
+  async function testPreventFromAddingTooManyPossibleProperties(collection: UniqueNFTCollection | UniqueRFTCollection) {  
+    const constitution = [];
+    for (let i = 0; i < 65; i++) {
+      constitution.push({
+        key: 'property_' + i,
+        permission: Math.random() > 0.5 ? {mutable: true, collectionAdmin: true, tokenOwner: true} : {},
+      });
+    }
+
+    await expect(collection.setTokenPropertyPermissions(alice, constitution))
+      .to.be.rejectedWith(/common\.PropertyLimitReached/);
+
+    const propertyRights = await collection.getPropertyPermissions();
+    expect(propertyRights).to.be.empty;
   }
-  it('Prevents from adding too many possible properties (NFT)', async () => {
-    await testPreventFromAddingTooManyPossibleProperties({type: 'NFT'});
+
+  itSub('Prevents from adding too many possible properties (NFT)', async ({helper}) =>  {
+    await testPreventFromAddingTooManyPossibleProperties(await helper.nft.mintCollection(alice));
   });
-  it('Prevents from adding too many possible properties (ReFungible)', async function() {
-    await requirePallets(this, [Pallets.ReFungible]);
 
-    await testPreventFromAddingTooManyPossibleProperties({type: 'ReFungible'});
+  itSub.ifWithPallets('Prevents from adding too many possible properties (ReFungible)', [Pallets.ReFungible], async ({helper}) => {
+    await testPreventFromAddingTooManyPossibleProperties(await helper.rft.mintCollection(alice));
   });
 
-  async function testPreventAccessRightsModifiedIfConstant(mode: CollectionMode) {
-    await usingApi(async api => {
-      const collection = await createCollectionExpectSuccess({mode: mode});
-  
-      await expect(executeTransaction(
-        api, 
-        alice, 
-        api.tx.unique.setTokenPropertyPermissions(collection, [{key: 'skullduggery', permission: {mutable: false, tokenOwner: true}}]), 
-      )).to.not.be.rejected;
-  
-      await expect(executeTransaction(
-        api, 
-        alice, 
-        api.tx.unique.setTokenPropertyPermissions(collection, [{key: 'skullduggery', permission: {}}]), 
-      )).to.be.rejectedWith(/common\.NoPermission/);
-  
-      const propertyRights = (await api.rpc.unique.propertyPermissions(collection, ['skullduggery'])).toHuman();
-      expect(propertyRights).to.deep.equal([
-        {key: 'skullduggery', permission: {'mutable': false, 'collectionAdmin': false, 'tokenOwner': true}},
-      ]);
-    });  
+  async function testPreventAccessRightsModifiedIfConstant(collection: UniqueNFTCollection | UniqueRFTCollection) {
+    await expect(collection.setTokenPropertyPermissions(alice, [{key: 'skullduggery', permission: {mutable: false, tokenOwner: true}}]))
+      .to.be.fulfilled;
+
+    await expect(collection.setTokenPropertyPermissions(alice, [{key: 'skullduggery', permission: {collectionAdmin: true}}]))
+      .to.be.rejectedWith(/common\.NoPermission/);
+
+    const propertyRights = await collection.getPropertyPermissions(['skullduggery']);
+    expect(propertyRights).to.deep.equal([
+      {key: 'skullduggery', permission: {'mutable': false, 'collectionAdmin': false, 'tokenOwner': true}},
+    ]);
   }
-  it('Prevents access rights to be modified if constant (NFT)', async () => {
-    await testPreventAccessRightsModifiedIfConstant({type: 'NFT'});
+
+  itSub('Prevents access rights to be modified if constant (NFT)', async ({helper}) =>  {
+    await testPreventAccessRightsModifiedIfConstant(await helper.nft.mintCollection(alice));
   });
-  it('Prevents access rights to be modified if constant (ReFungible)', async function() {
-    await requirePallets(this, [Pallets.ReFungible]);
 
-    await testPreventAccessRightsModifiedIfConstant({type: 'ReFungible'});
+  itSub.ifWithPallets('Prevents access rights to be modified if constant (ReFungible)', [Pallets.ReFungible], async ({helper}) => {
+    await testPreventAccessRightsModifiedIfConstant(await helper.rft.mintCollection(alice));
   });
 
-  async function testPreventsAddingPropertiesWithInvalidNames(mode: CollectionMode) {
-    await usingApi(async api => {
-      const collection = await createCollectionExpectSuccess({mode: mode});
-  
-      const invalidProperties = [
-        [{key: 'skullduggery', permission: {tokenOwner: true}}, {key: 'im possible', permission: {collectionAdmin: true}}],
-        [{key: 'G#4', permission: {tokenOwner: true}}],
-        [{key: 'HÆMILTON', permission: {mutable: false, collectionAdmin: true, tokenOwner: true}}],
-      ];
-  
-      for (let i = 0; i < invalidProperties.length; i++) {
-        await expect(executeTransaction(
-          api, 
-          alice, 
-          api.tx.unique.setTokenPropertyPermissions(collection, invalidProperties[i]), 
-        ), `on setting the new badly-named property #${i}`).to.be.rejectedWith(/common\.InvalidCharacterInPropertyKey/);
-      }
-  
-      await expect(executeTransaction(
-        api, 
-        alice, 
-        api.tx.unique.setTokenPropertyPermissions(collection, [{key: '', permission: {}}]), 
-      ), 'on rejecting an unnamed property').to.be.rejectedWith(/common\.EmptyPropertyKey/);
-  
-      const correctKey = '--0x03116e387820CA05'; // PolkadotJS would parse this as an already encoded hex-string
-      await expect(executeTransaction(
-        api, 
-        alice, 
-        api.tx.unique.setTokenPropertyPermissions(collection, [
-          {key: correctKey, permission: {collectionAdmin: true}},
-        ]), 
-      ), 'on setting the correctly-but-still-badly-named property').to.not.be.rejected;
-  
-      const keys = invalidProperties.flatMap(propertySet => propertySet.map(property => property.key)).concat(correctKey).concat('');
-  
-      const propertyRights = (await api.rpc.unique.propertyPermissions(collection, keys)).toHuman();
-      expect(propertyRights).to.be.deep.equal([
-        {key: correctKey, permission: {mutable: false, collectionAdmin: true, tokenOwner: false}},
-      ]);
-    });
+  async function testPreventsAddingPropertiesWithInvalidNames(collection: UniqueNFTCollection | UniqueRFTCollection) {
+    const invalidProperties = [
+      [{key: 'skullduggery', permission: {tokenOwner: true}}, {key: 'im possible', permission: {collectionAdmin: true}}],
+      [{key: 'G#4', permission: {tokenOwner: true}}],
+      [{key: 'HÆMILTON', permission: {mutable: false, collectionAdmin: true, tokenOwner: true}}],
+    ];
+
+    for (let i = 0; i < invalidProperties.length; i++) {
+      await expect(
+        collection.setTokenPropertyPermissions(alice, invalidProperties[i]), 
+        `on setting the new badly-named property #${i}`,
+      ).to.be.rejectedWith(/common\.InvalidCharacterInPropertyKey/);
+    }
+
+    await expect(
+      collection.setTokenPropertyPermissions(alice, [{key: '', permission: {}}]), 
+      'on rejecting an unnamed property',
+    ).to.be.rejectedWith(/common\.EmptyPropertyKey/);
+
+    const correctKey = '--0x03116e387820CA05'; // PolkadotJS would parse this as an already encoded hex-string
+    await expect(
+      collection.setTokenPropertyPermissions(alice, [
+        {key: correctKey, permission: {collectionAdmin: true}},
+      ]), 
+      'on setting the correctly-but-still-badly-named property',
+    ).to.be.fulfilled;
+
+    const keys = invalidProperties.flatMap(propertySet => propertySet.map(property => property.key)).concat(correctKey).concat('');
+
+    const propertyRights = await collection.getPropertyPermissions(keys);
+    expect(propertyRights).to.be.deep.equal([
+      {key: correctKey, permission: {mutable: false, collectionAdmin: true, tokenOwner: false}},
+    ]);
   }
-  it('Prevents adding properties with invalid names (NFT)', async () => {
-    await testPreventsAddingPropertiesWithInvalidNames({type: 'NFT'});
+
+  itSub('Prevents adding properties with invalid names (NFT)', async ({helper}) =>  {
+    await testPreventsAddingPropertiesWithInvalidNames(await helper.nft.mintCollection(alice));
   });
-  it('Prevents adding properties with invalid names (ReFungible)', async function() {
-    await requirePallets(this, [Pallets.ReFungible]);
 
-    await testPreventsAddingPropertiesWithInvalidNames({type: 'ReFungible'});
+  itSub.ifWithPallets('Prevents adding properties with invalid names (ReFungible)', [Pallets.ReFungible], async ({helper}) => {
+    await testPreventsAddingPropertiesWithInvalidNames(await helper.rft.mintCollection(alice));
   });
 });
 
 // ---------- TOKEN PROPERTIES
 
 describe('Integration Test: Token Properties', () => {
+  let alice: IKeyringPair; // collection owner
+  let bob: IKeyringPair; // collection admin
+  let charlie: IKeyringPair; // token owner
+
   let permissions: {permission: any, signers: IKeyringPair[]}[];
 
   before(async () => {
-    await usingApi(async (api, privateKeyWrapper) => {
-      alice = privateKeyWrapper('//Alice'); // collection owner
-      bob = privateKeyWrapper('//Bob'); // collection admin
-      charlie = privateKeyWrapper('//Charlie'); // token owner
+    await usingPlaygrounds(async (helper, privateKey) => {
+      const donor = privateKey('//Alice');
+      [alice, bob, charlie] = await helper.arrange.createAccounts([100n, 100n, 100n], donor);
+    });
 
-      permissions = [
-        {permission: {mutable: true, collectionAdmin: true}, signers: [alice, bob]},
-        {permission: {mutable: false, collectionAdmin: true}, signers: [alice, bob]},
-        {permission: {mutable: true, tokenOwner: true}, signers: [charlie]},
-        {permission: {mutable: false, tokenOwner: true}, signers: [charlie]},
-        {permission: {mutable: true, collectionAdmin: true, tokenOwner: true}, signers: [alice, bob, charlie]},
-        {permission: {mutable: false, collectionAdmin: true, tokenOwner: true}, signers: [alice, bob, charlie]},
-      ];
-    });
+    // todo:playgrounds probably separate these tests later
+    permissions = [
+      {permission: {mutable: true, collectionAdmin: true}, signers: [alice, bob]},
+      {permission: {mutable: false, collectionAdmin: true}, signers: [alice, bob]},
+      {permission: {mutable: true, tokenOwner: true}, signers: [charlie]},
+      {permission: {mutable: false, tokenOwner: true}, signers: [charlie]},
+      {permission: {mutable: true, collectionAdmin: true, tokenOwner: true}, signers: [alice, bob, charlie]},
+      {permission: {mutable: false, collectionAdmin: true, tokenOwner: true}, signers: [alice, bob, charlie]},
+    ];
   });
   
-  async function testReadsYetEmptyProperties(mode: CollectionMode) {
-    await usingApi(async api => {
-      const collection = await createCollectionExpectSuccess({mode: mode});
-      const token = await createItemExpectSuccess(alice, collection, mode.type);
-  
-      const properties = (await api.query.nonfungible.tokenProperties(collection, token)).toJSON();
-      expect(properties.map).to.be.empty;
-      expect(properties.consumedSpace).to.be.equal(0);
-  
-      const tokenData = (await api.rpc.unique.tokenData(collection, token, ['anything'])).toJSON().properties;
-      expect(tokenData).to.be.empty;
-    });
+  async function testReadsYetEmptyProperties(token: UniqueNFToken | UniqueRFToken) {
+    const properties = await token.getProperties();
+    expect(properties).to.be.empty;
+
+    const tokenData = await token.getData();
+    expect(tokenData!.properties).to.be.empty;
   }
-  it('Reads yet empty properties of a token (NFT)', async () => {
-    await testReadsYetEmptyProperties({type: 'NFT'});
-  });
-  it('Reads yet empty properties of a token (ReFungible)', async function() {
-    await requirePallets(this, [Pallets.ReFungible]);
 
-    await testReadsYetEmptyProperties({type: 'ReFungible'});
+  itSub('Reads yet empty properties of a token (NFT)', async ({helper}) => {
+    const collection = await helper.nft.mintCollection(alice);
+    const token = await collection.mintToken(alice);
+    await testReadsYetEmptyProperties(token);
   });
 
-  async function testAssignPropertiesAccordingToPermissions(mode: CollectionMode, pieces: number) {
-    await usingApi(async api => {
-      const collection = await createCollectionExpectSuccess({mode: mode});
-      const token = await createItemExpectSuccess(alice, collection, mode.type);
-      await addCollectionAdminExpectSuccess(alice, collection, bob.address);
-      await transferExpectSuccess(collection, token, alice, charlie, pieces, mode.type);
+  itSub.ifWithPallets('Reads yet empty properties of a token (ReFungible)', [Pallets.ReFungible], async ({helper}) => {
+    const collection = await helper.rft.mintCollection(alice);
+    const token = await collection.mintToken(alice);
+    await testReadsYetEmptyProperties(token);
+  });
 
-      const propertyKeys: string[] = [];
-      let i = 0;
-      for (const permission of permissions) {
-        for (const signer of permission.signers) {
-          const key = i + '_' + signer.address;
-          propertyKeys.push(key);
+  async function testAssignPropertiesAccordingToPermissions(token: UniqueNFToken | UniqueRFToken, pieces: bigint) {
+    await token.collection.addAdmin(alice, {Substrate: bob.address});
+    await token.transfer(alice, {Substrate: charlie.address}, pieces);
 
-          await expect(executeTransaction(
-            api, 
-            alice, 
-            api.tx.unique.setTokenPropertyPermissions(collection, [{key: key, permission: permission.permission}]), 
-          ), `on setting permission ${i} by ${signer.address}`).to.not.be.rejected;
+    const propertyKeys: string[] = [];
+    let i = 0;
+    for (const permission of permissions) {
+      i++;
+      let j = 0;
+      for (const signer of permission.signers) {
+        j++;
+        const key = i + '_' + signer.address;
+        propertyKeys.push(key);
 
-          await expect(executeTransaction(
-            api, 
-            signer, 
-            api.tx.unique.setTokenProperties(collection, token, [{key: key, value: 'Serotonin increase'}]), 
-          ), `on adding property ${i} by ${signer.address}`).to.not.be.rejected;
-        }
+        await expect(
+          token.collection.setTokenPropertyPermissions(alice, [{key: key, permission: permission.permission}]), 
+          `on setting permission #${i} by alice`,
+        ).to.be.fulfilled;
 
-        i++;
+        await expect(
+          token.setProperties(signer, [{key: key, value: 'Serotonin increase'}]), 
+          `on adding property #${i} by signer #${j}`,
+        ).to.be.fulfilled;
       }
+    }
 
-      const properties = (await api.rpc.unique.tokenProperties(collection, token, propertyKeys)).toHuman() as any[];
-      const tokensData = (await api.rpc.unique.tokenData(collection, token, propertyKeys)).toHuman().properties as any[];
-      for (let i = 0; i < properties.length; i++) {
-        expect(properties[i].value).to.be.equal('Serotonin increase');
-        expect(tokensData[i].value).to.be.equal('Serotonin increase');
-      }
-    });
+    const properties = await token.getProperties(propertyKeys);
+    const tokenData = await token.getData();
+    for (let i = 0; i < properties.length; i++) {
+      expect(properties[i].value).to.be.equal('Serotonin increase');
+      expect(tokenData!.properties[i].value).to.be.equal('Serotonin increase');
+    }
   }
-  it('Assigns properties to a token according to permissions (NFT)', async () => {
-    await testAssignPropertiesAccordingToPermissions({type: 'NFT'}, 1);
+
+  itSub('Assigns properties to a token according to permissions (NFT)', async ({helper}) =>  {
+    const collection = await helper.nft.mintCollection(alice);
+    const token = await collection.mintToken(alice);
+    await testAssignPropertiesAccordingToPermissions(token, 1n);
   });
-  it('Assigns properties to a token according to permissions (ReFungible)', async function() {
-    await requirePallets(this, [Pallets.ReFungible]);
 
-    await testAssignPropertiesAccordingToPermissions({type: 'ReFungible'}, 100);
+  itSub.ifWithPallets('Assigns properties to a token according to permissions (ReFungible)', [Pallets.ReFungible], async ({helper}) => {
+    const collection = await helper.rft.mintCollection(alice);
+    const token = await collection.mintToken(alice, 100n);
+    await testAssignPropertiesAccordingToPermissions(token, 100n);
   });
 
-  async function testChangesPropertiesAccordingPermission(mode: CollectionMode, pieces: number) {
-    await usingApi(async api => {
-      const collection = await createCollectionExpectSuccess({mode: mode});
-      const token = await createItemExpectSuccess(alice, collection, mode.type);
-      await addCollectionAdminExpectSuccess(alice, collection, bob.address);
-      await transferExpectSuccess(collection, token, alice, charlie, pieces, mode.type);
+  async function testChangesPropertiesAccordingPermission(token: UniqueNFToken | UniqueRFToken, pieces: bigint) {
+    await token.collection.addAdmin(alice, {Substrate: bob.address});
+    await token.transfer(alice, {Substrate: charlie.address}, pieces);
+
+    const propertyKeys: string[] = [];
+    let i = 0;
+    for (const permission of permissions) {
+      i++;
+      if (!permission.permission.mutable) continue;
+      
+      let j = 0;
+      for (const signer of permission.signers) {
+        j++;
+        const key = i + '_' + signer.address;
+        propertyKeys.push(key);
+
+        await expect(
+          token.collection.setTokenPropertyPermissions(alice, [{key: key, permission: permission.permission}]), 
+          `on setting permission #${i} by alice`,
+        ).to.be.fulfilled;
+
+        await expect(
+          token.setProperties(signer, [{key, value: 'Serotonin increase'}]), 
+          `on adding property #${i} by signer #${j}`,
+        ).to.be.fulfilled;
 
-      const propertyKeys: string[] = [];
-      let i = 0;
-      for (const permission of permissions) {
-        if (!permission.permission.mutable) continue;
-        
-        for (const signer of permission.signers) {
-          const key = i + '_' + signer.address;
-          propertyKeys.push(key);
-  
-          await expect(executeTransaction(
-            api, 
-            alice, 
-            api.tx.unique.setTokenPropertyPermissions(collection, [{key: key, permission: permission.permission}]), 
-          ), `on setting permission ${i} by ${signer.address}`).to.not.be.rejected;
-  
-          await expect(executeTransaction(
-            api, 
-            signer, 
-            api.tx.unique.setTokenProperties(collection, token, [{key: key, value: 'Serotonin increase'}]), 
-          ), `on adding property ${i} by ${signer.address}`).to.not.be.rejected;
-  
-          await expect(executeTransaction(
-            api, 
-            signer, 
-            api.tx.unique.setTokenProperties(collection, token, [{key: key, value: 'Serotonin stable'}]), 
-          ), `on changing property ${i} by ${signer.address}`).to.not.be.rejected;
-        }
-  
-        i++;
+        await expect(
+          token.setProperties(signer, [{key, value: 'Serotonin stable'}]), 
+          `on changing property #${i} by signer #${j}`,
+        ).to.be.fulfilled;
       }
-  
-      const properties = (await api.rpc.unique.tokenProperties(collection, token, propertyKeys)).toHuman() as any[];
-      const tokensData = (await api.rpc.unique.tokenData(collection, token, propertyKeys)).toHuman().properties as any[];
-      for (let i = 0; i < properties.length; i++) {
-        expect(properties[i].value).to.be.equal('Serotonin stable');
-        expect(tokensData[i].value).to.be.equal('Serotonin stable');
-      }
-    });
+    }
+
+    const properties = await token.getProperties(propertyKeys);
+    const tokenData = await token.getData();
+    for (let i = 0; i < properties.length; i++) {
+      expect(properties[i].value).to.be.equal('Serotonin stable');
+      expect(tokenData!.properties[i].value).to.be.equal('Serotonin stable');
+    }
   }
-  it('Changes properties of a token according to permissions (NFT)', async () => {
-    await testChangesPropertiesAccordingPermission({type: 'NFT'}, 1);
+
+  itSub('Changes properties of a token according to permissions (NFT)', async ({helper}) =>  {
+    const collection = await helper.nft.mintCollection(alice);
+    const token = await collection.mintToken(alice);
+    await testChangesPropertiesAccordingPermission(token, 1n);
   });
-  it('Changes properties of a token according to permissions (ReFungible)', async function() {
-    await requirePallets(this, [Pallets.ReFungible]);
 
-    await testChangesPropertiesAccordingPermission({type: 'ReFungible'}, 100);
+  itSub.ifWithPallets('Changes properties of a token according to permissions (ReFungible)', [Pallets.ReFungible], async ({helper}) => {
+    const collection = await helper.rft.mintCollection(alice);
+    const token = await collection.mintToken(alice, 100n);
+    await testChangesPropertiesAccordingPermission(token, 100n);
   });
 
-  async function testDeletePropertiesAccordingPermission(mode: CollectionMode, pieces: number) {
-    await usingApi(async api => {
-      const collection = await createCollectionExpectSuccess({mode: mode});
-      const token = await createItemExpectSuccess(alice, collection, mode.type);
-      await addCollectionAdminExpectSuccess(alice, collection, bob.address);
-      await transferExpectSuccess(collection, token, alice, charlie, pieces, mode.type);
+  async function testDeletePropertiesAccordingPermission(token: UniqueNFToken | UniqueRFToken, pieces: bigint) {
+    await token.collection.addAdmin(alice, {Substrate: bob.address});
+    await token.transfer(alice, {Substrate: charlie.address}, pieces);
+
+    const propertyKeys: string[] = [];
+    let i = 0;
+
+    for (const permission of permissions) {
+      i++;
+      if (!permission.permission.mutable) continue;
+      
+      let j = 0;
+      for (const signer of permission.signers) {
+        j++;
+        const key = i + '_' + signer.address;
+        propertyKeys.push(key);
+
+        await expect(
+          token.collection.setTokenPropertyPermissions(alice, [{key: key, permission: permission.permission}]), 
+          `on setting permission #${i} by alice`,
+        ).to.be.fulfilled;
 
-      const propertyKeys: string[] = [];
-      let i = 0;
-  
-      for (const permission of permissions) {
-        if (!permission.permission.mutable) continue;
-        
-        for (const signer of permission.signers) {
-          const key = i + '_' + signer.address;
-          propertyKeys.push(key);
-  
-          await expect(executeTransaction(
-            api, 
-            alice, 
-            api.tx.unique.setTokenPropertyPermissions(collection, [{key: key, permission: permission.permission}]), 
-          ), `on setting permission ${i} by ${signer.address}`).to.not.be.rejected;
-  
-          await expect(executeTransaction(
-            api, 
-            signer, 
-            api.tx.unique.setTokenProperties(collection, token, [{key: key, value: 'Serotonin increase'}]), 
-          ), `on adding property ${i} by ${signer.address}`).to.not.be.rejected;
-  
-          await expect(executeTransaction(
-            api, 
-            signer, 
-            api.tx.unique.deleteTokenProperties(collection, token, [key]), 
-          ), `on deleting property ${i} by ${signer.address}`).to.not.be.rejected;
-        }
-        
-        i++;
+        await expect(
+          token.setProperties(signer, [{key, value: 'Serotonin increase'}]), 
+          `on adding property #${i} by signer #${j}`,
+        ).to.be.fulfilled;
+
+        await expect(
+          token.deleteProperties(signer, [key]), 
+          `on deleting property #${i} by signer #${j}`,
+        ).to.be.fulfilled;
       }
-  
-      const properties = (await api.rpc.unique.tokenProperties(collection, token, propertyKeys)).toJSON() as any[];
-      expect(properties).to.be.empty;
-      const tokensData = (await api.rpc.unique.tokenData(collection, token, propertyKeys)).toJSON().properties as any[];
-      expect(tokensData).to.be.empty;
-      expect((await api.query.nonfungible.tokenProperties(collection, token)).toJSON().consumedSpace).to.be.equal(0);
-    });
+    }
+
+    expect(await token.getProperties(propertyKeys)).to.be.empty;
+    expect((await token.getData())!.properties).to.be.empty;
   }
-  it('Deletes properties of a token according to permissions (NFT)', async () => {
-    await testDeletePropertiesAccordingPermission({type: 'NFT'}, 1);
+  
+  itSub('Deletes properties of a token according to permissions (NFT)', async ({helper}) =>  {
+    const collection = await helper.nft.mintCollection(alice);
+    const token = await collection.mintToken(alice);
+    await testDeletePropertiesAccordingPermission(token, 1n);
   });
-  it('Deletes properties of a token according to permissions (ReFungible)', async function() {
-    await requirePallets(this, [Pallets.ReFungible]);
 
-    await testDeletePropertiesAccordingPermission({type: 'ReFungible'}, 100);
+  itSub.ifWithPallets('Deletes properties of a token according to permissions (ReFungible)', [Pallets.ReFungible], async ({helper}) => {
+    const collection = await helper.rft.mintCollection(alice);
+    const token = await collection.mintToken(alice, 100n);
+    await testDeletePropertiesAccordingPermission(token, 100n);
   });
 
-  it('Assigns properties to a nested token according to permissions', async () => {
-    await usingApi(async api => {
-      const collection = await createCollectionExpectSuccess({mode: {type: 'NFT'}});
-      await setCollectionPermissionsExpectSuccess(alice, collection, {nesting: {tokenOwner: true}});
-      const token = await createItemExpectSuccess(alice, collection, 'NFT');
-      const nestedToken = await createItemExpectSuccess(alice, collection, 'NFT', {Ethereum: tokenIdToAddress(collection, token)});
-      await addCollectionAdminExpectSuccess(alice, collection, bob.address);
-      await transferExpectSuccess(collection, token, alice, charlie);
+  itSub('Assigns properties to a nested token according to permissions', async ({helper}) =>  {
+    const collectionA = await helper.nft.mintCollection(alice, {permissions: {nesting: {tokenOwner: true}}});
+    const collectionB = await helper.nft.mintCollection(alice);
+    const targetToken = await collectionA.mintToken(alice);
+    const nestedToken = await collectionB.mintToken(alice, targetToken.nestingAccount());
 
-      const propertyKeys: string[] = [];
-      let i = 0;
-      for (const permission of permissions) {
-        for (const signer of permission.signers) {
-          const key = i + '_' + signer.address;
-          propertyKeys.push(key);
+    await collectionB.addAdmin(alice, {Substrate: bob.address});
+    await targetToken.transfer(alice, {Substrate: charlie.address});
 
-          await expect(executeTransaction(
-            api, 
-            alice, 
-            api.tx.unique.setTokenPropertyPermissions(collection, [{key: key, permission: permission.permission}]), 
-          ), `on setting permission ${i} by ${signer.address}`).to.not.be.rejected;
+    const propertyKeys: string[] = [];
+    let i = 0;
+    for (const permission of permissions) {
+      i++;
+      let j = 0;
+      for (const signer of permission.signers) {
+        j++;
+        const key = i + '_' + signer.address;
+        propertyKeys.push(key);
+        
+        await expect(
+          nestedToken.collection.setTokenPropertyPermissions(alice, [{key: key, permission: permission.permission}]), 
+          `on setting permission #${i} by alice`,
+        ).to.be.fulfilled;
 
-          await expect(executeTransaction(
-            api, 
-            signer, 
-            api.tx.unique.setTokenProperties(collection, nestedToken, [{key: key, value: 'Serotonin increase'}]), 
-          ), `on adding property ${i} by ${signer.address}`).to.not.be.rejected;
-        }
-
-        i++;
+        await expect(
+          nestedToken.setProperties(signer, [{key, value: 'Serotonin increase'}]), 
+          `on adding property #${i} by signer #${j}`,
+        ).to.be.fulfilled;
       }
 
-      const properties = (await api.rpc.unique.tokenProperties(collection, nestedToken, propertyKeys)).toHuman() as any[];
-      const tokensData = (await api.rpc.unique.tokenData(collection, nestedToken, propertyKeys)).toHuman().properties as any[];
-      for (let i = 0; i < properties.length; i++) {
-        expect(properties[i].value).to.be.equal('Serotonin increase');
-        expect(tokensData[i].value).to.be.equal('Serotonin increase');
-      }
-    });
+    }
+
+    const properties = await nestedToken.getProperties(propertyKeys);
+    const tokenData = await nestedToken.getData();
+    for (let i = 0; i < properties.length; i++) {
+      expect(properties[i].value).to.be.equal('Serotonin increase');
+      expect(tokenData!.properties[i].value).to.be.equal('Serotonin increase');
+    }
+    expect(await targetToken.getProperties()).to.be.empty;
   });
 
-  it('Changes properties of a nested token according to permissions', async () => {
-    await usingApi(async api => {
-      const collection = await createCollectionExpectSuccess({mode: {type: 'NFT'}});
-      await setCollectionPermissionsExpectSuccess(alice, collection, {nesting: {tokenOwner: true}});
-      const token = await createItemExpectSuccess(alice, collection, 'NFT');
-      const nestedToken = await createItemExpectSuccess(alice, collection, 'NFT', {Ethereum: tokenIdToAddress(collection, token)});
-      await addCollectionAdminExpectSuccess(alice, collection, bob.address);
-      await transferExpectSuccess(collection, token, alice, charlie);
+  itSub('Changes properties of a nested token according to permissions', async ({helper}) =>  {
+    const collectionA = await helper.nft.mintCollection(alice, {permissions: {nesting: {tokenOwner: true}}});
+    const collectionB = await helper.nft.mintCollection(alice);
+    const targetToken = await collectionA.mintToken(alice);
+    const nestedToken = await collectionB.mintToken(alice, targetToken.nestingAccount());
 
-      const propertyKeys: string[] = [];
-      let i = 0;
-      for (const permission of permissions) {
-        if (!permission.permission.mutable) continue;
-        
-        for (const signer of permission.signers) {
-          const key = i + '_' + signer.address;
-          propertyKeys.push(key);
+    await collectionB.addAdmin(alice, {Substrate: bob.address});
+    await targetToken.transfer(alice, {Substrate: charlie.address});
 
-          await expect(executeTransaction(
-            api, 
-            alice, 
-            api.tx.unique.setTokenPropertyPermissions(collection, [{key: key, permission: permission.permission}]), 
-          ), `on setting permission ${i} by ${signer.address}`).to.not.be.rejected;
+    const propertyKeys: string[] = [];
+    let i = 0;
+    for (const permission of permissions) {
+      i++;
+      if (!permission.permission.mutable) continue;
+      
+      let j = 0;
+      for (const signer of permission.signers) {
+        j++;
+        const key = i + '_' + signer.address;
+        propertyKeys.push(key);
 
-          await expect(executeTransaction(
-            api, 
-            signer, 
-            api.tx.unique.setTokenProperties(collection, nestedToken, [{key: key, value: 'Serotonin increase'}]), 
-          ), `on adding property ${i} by ${signer.address}`).to.not.be.rejected;
+        await expect(
+          nestedToken.collection.setTokenPropertyPermissions(alice, [{key: key, permission: permission.permission}]), 
+          `on setting permission #${i} by alice`,
+        ).to.be.fulfilled;
 
-          await expect(executeTransaction(
-            api, 
-            signer, 
-            api.tx.unique.setTokenProperties(collection, nestedToken, [{key: key, value: 'Serotonin stable'}]), 
-          ), `on changing property ${i} by ${signer.address}`).to.not.be.rejected;
-        }
+        await expect(
+          nestedToken.setProperties(signer, [{key, value: 'Serotonin increase'}]), 
+          `on adding property #${i} by signer #${j}`,
+        ).to.be.fulfilled;
 
-        i++;
+        await expect(
+          nestedToken.setProperties(signer, [{key, value: 'Serotonin stable'}]), 
+          `on changing property #${i} by signer #${j}`,
+        ).to.be.fulfilled;
       }
+    }
 
-      const properties = (await api.rpc.unique.tokenProperties(collection, nestedToken, propertyKeys)).toHuman() as any[];
-      const tokensData = (await api.rpc.unique.tokenData(collection, nestedToken, propertyKeys)).toHuman().properties as any[];
-      for (let i = 0; i < properties.length; i++) {
-        expect(properties[i].value).to.be.equal('Serotonin stable');
-        expect(tokensData[i].value).to.be.equal('Serotonin stable');
-      }
-    });
+    const properties = await nestedToken.getProperties(propertyKeys);
+    const tokenData = await nestedToken.getData();
+    for (let i = 0; i < properties.length; i++) {
+      expect(properties[i].value).to.be.equal('Serotonin stable');
+      expect(tokenData!.properties[i].value).to.be.equal('Serotonin stable');
+    }
+    expect(await targetToken.getProperties()).to.be.empty;
   });
 
-  it('Deletes properties of a nested token according to permissions', async () => {
-    await usingApi(async api => {
-      const collection = await createCollectionExpectSuccess({mode: {type: 'NFT'}});
-      await setCollectionPermissionsExpectSuccess(alice, collection, {nesting: {tokenOwner: true}});
-      const token = await createItemExpectSuccess(alice, collection, 'NFT');
-      const nestedToken = await createItemExpectSuccess(alice, collection, 'NFT', {Ethereum: tokenIdToAddress(collection, token)});
-      await addCollectionAdminExpectSuccess(alice, collection, bob.address);
-      await transferExpectSuccess(collection, token, alice, charlie);
+  itSub('Deletes properties of a nested token according to permissions', async ({helper}) =>  {
+    const collectionA = await helper.nft.mintCollection(alice, {permissions: {nesting: {tokenOwner: true}}});
+    const collectionB = await helper.nft.mintCollection(alice);
+    const targetToken = await collectionA.mintToken(alice);
+    const nestedToken = await collectionB.mintToken(alice, targetToken.nestingAccount());
 
-      const propertyKeys: string[] = [];
-      let i = 0;
+    await collectionB.addAdmin(alice, {Substrate: bob.address});
+    await targetToken.transfer(alice, {Substrate: charlie.address});
 
-      for (const permission of permissions) {
-        if (!permission.permission.mutable) continue;
-        
-        for (const signer of permission.signers) {
-          const key = i + '_' + signer.address;
-          propertyKeys.push(key);
+    const propertyKeys: string[] = [];
+    let i = 0;
+    for (const permission of permissions) {
+      i++;
+      if (!permission.permission.mutable) continue;
+      
+      let j = 0;
+      for (const signer of permission.signers) {
+        j++;
+        const key = i + '_' + signer.address;
+        propertyKeys.push(key);
 
-          await expect(executeTransaction(
-            api, 
-            alice, 
-            api.tx.unique.setTokenPropertyPermissions(collection, [{key: key, permission: permission.permission}]), 
-          ), `on setting permission ${i} by ${signer.address}`).to.not.be.rejected;
+        await expect(
+          nestedToken.collection.setTokenPropertyPermissions(alice, [{key: key, permission: permission.permission}]), 
+          `on setting permission #${i} by alice`,
+        ).to.be.fulfilled;
 
-          await expect(executeTransaction(
-            api, 
-            signer, 
-            api.tx.unique.setTokenProperties(collection, nestedToken, [{key: key, value: 'Serotonin increase'}]), 
-          ), `on adding property ${i} by ${signer.address}`).to.not.be.rejected;
+        await expect(
+          nestedToken.setProperties(signer, [{key, value: 'Serotonin increase'}]), 
+          `on adding property #${i} by signer #${j}`,
+        ).to.be.fulfilled;
 
-          await expect(executeTransaction(
-            api, 
-            signer, 
-            api.tx.unique.deleteTokenProperties(collection, nestedToken, [key]), 
-          ), `on deleting property ${i} by ${signer.address}`).to.not.be.rejected;
-        }
-        
-        i++;
+        await expect(
+          nestedToken.deleteProperties(signer, [key]), 
+          `on deleting property #${i} by signer #${j}`,
+        ).to.be.fulfilled;
       }
+    }
 
-      const properties = (await api.rpc.unique.tokenProperties(collection, nestedToken, propertyKeys)).toJSON() as any[];
-      expect(properties).to.be.empty;
-      const tokensData = (await api.rpc.unique.tokenData(collection, nestedToken, propertyKeys)).toJSON().properties as any[];
-      expect(tokensData).to.be.empty;
-      expect((await api.query.nonfungible.tokenProperties(collection, nestedToken)).toJSON().consumedSpace).to.be.equal(0);
-    });
+    expect(await nestedToken.getProperties(propertyKeys)).to.be.empty;
+    expect((await nestedToken.getData())!.properties).to.be.empty;
+    expect(await targetToken.getProperties()).to.be.empty;
   });
 });
 
 describe('Negative Integration Test: Token Properties', () => {
-  let collection: number;
-  let token: number;
-  let originalSpace: number;
+  let alice: IKeyringPair; // collection owner
+  let bob: IKeyringPair; // collection admin
+  let charlie: IKeyringPair; // token owner
+
   let constitution: {permission: any, signers: IKeyringPair[], sinner: IKeyringPair}[];
 
   before(async () => {
-    await usingApi(async (api, privateKeyWrapper) => {
-      alice = privateKeyWrapper('//Alice');
-      bob = privateKeyWrapper('//Bob');
-      charlie = privateKeyWrapper('//Charlie');
-      const dave = privateKeyWrapper('//Dave');
+    await usingPlaygrounds(async (helper, privateKey) => {
+      const donor = privateKey('//Alice');
+      let dave: IKeyringPair;
+      [alice, bob, charlie, dave] = await helper.arrange.createAccounts([100n, 100n, 100n, 100n], donor);
 
+      // todo:playgrounds probably separate these tests later
       constitution = [
         {permission: {mutable: true, collectionAdmin: true}, signers: [alice, bob], sinner: charlie},
         {permission: {mutable: false, collectionAdmin: true}, signers: [alice, bob], sinner: charlie},
@@ -1010,278 +794,255 @@
     });
   });
 
-  async function prepare(mode: CollectionMode, pieces: number) {
-    collection = await createCollectionExpectSuccess({mode: mode});
-    token = await createItemExpectSuccess(alice, collection, mode.type);
-    await addCollectionAdminExpectSuccess(alice, collection, bob.address);
-    await transferExpectSuccess(collection, token, alice, charlie, pieces, mode.type);
-        
-    await usingApi(async api => {
-      let i = 0;
-      for (const passage of constitution) {
-        const signer = passage.signers[0];
-        
-        await expect(executeTransaction(
-          api, 
-          alice, 
-          api.tx.unique.setTokenPropertyPermissions(collection, [{key: `${i}`, permission: passage.permission}]), 
-        ), `on setting permission ${i} by ${signer.address}`).to.not.be.rejected;
-  
-        await expect(executeTransaction(
-          api, 
-          signer, 
-          api.tx.unique.setTokenProperties(collection, token, [{key: `${i}`, value: 'Serotonin increase'}]), 
-        ), `on adding property ${i} by ${signer.address}`).to.not.be.rejected;
-  
-        i++;
-      }
-  
-      originalSpace = (await api.query.nonfungible.tokenProperties(collection, token)).toJSON().consumedSpace as number;
-    }); 
+  async function getConsumedSpace(api: any, collectionId: number, tokenId: number, mode: 'NFT' | 'RFT'): Promise<number> {
+    return (await (mode == 'NFT' ? api.query.nonfungible : api.query.refungible).tokenProperties(collectionId, tokenId)).toJSON().consumedSpace;
+  }
+
+  async function prepare(token: UniqueNFToken | UniqueRFToken, pieces: bigint): Promise<number> {
+    await token.collection.addAdmin(alice, {Substrate: bob.address});
+    await token.transfer(alice, {Substrate: charlie.address}, pieces);
+
+    let i = 0;
+    for (const passage of constitution) {
+      i++;
+      const signer = passage.signers[0];
+      
+      await expect(
+        token.collection.setTokenPropertyPermissions(alice, [{key: `${i}`, permission: passage.permission}]), 
+        `on setting permission ${i} by alice`,
+      ).to.be.fulfilled;
+
+      await expect(
+        token.setProperties(signer, [{key: `${i}`, value: 'Serotonin increase'}]), 
+        `on adding property ${i} by ${signer.address}`,
+      ).to.be.fulfilled;
+    }
+
+    const originalSpace = await getConsumedSpace(token.collection.helper.api, token.collectionId, token.tokenId, pieces == 1n ? 'NFT' : 'RFT'); 
+    return originalSpace;
   }
 
-  async function testForbidsChangingDeletingPropertiesUserOutsideOfPermissions(mode: CollectionMode, pieces: number) {
-    await prepare(mode, pieces);
-  
-    await usingApi(async api => {
-      let i = -1;
-      for (const forbiddance of constitution) {
-        i++;
-        if (!forbiddance.permission.mutable) continue;
-  
-        await expect(executeTransaction(
-          api, 
-          forbiddance.sinner, 
-          api.tx.unique.setTokenProperties(collection, token, [{key: `${i}`, value: 'Serotonin down'}]), 
-        ), `on failing to change property ${i} by ${forbiddance.sinner.address}`).to.be.rejectedWith(/common\.NoPermission/);
-  
-        await expect(executeTransaction(
-          api, 
-          forbiddance.sinner, 
-          api.tx.unique.deleteTokenProperties(collection, token, [`${i}`]), 
-        ), `on failing to delete property ${i} by ${forbiddance.sinner.address}`).to.be.rejectedWith(/common\.NoPermission/);
-      }
-  
-      const properties = (await api.query.nonfungible.tokenProperties(collection, token)).toJSON();
-      expect(properties.consumedSpace).to.be.equal(originalSpace);
-    });
+  async function testForbidsChangingDeletingPropertiesUserOutsideOfPermissions(token: UniqueNFToken | UniqueRFToken, pieces: bigint) {
+    const originalSpace = await prepare(token, pieces);
+
+    let i = 0;
+    for (const forbiddance of constitution) {
+      i++;
+      if (!forbiddance.permission.mutable) continue;
+
+      await expect(
+        token.setProperties(forbiddance.sinner, [{key: `${i}`, value: 'Serotonin down'}]), 
+        `on failing to change property ${i} by the malefactor`,
+      ).to.be.rejectedWith(/common\.NoPermission/);
+
+      await expect(
+        token.deleteProperties(forbiddance.sinner, [`${i}`]), 
+        `on failing to delete property ${i} by the malefactor`,
+      ).to.be.rejectedWith(/common\.NoPermission/);
+    }
+
+    const consumedSpace = await getConsumedSpace(token.collection.helper.api, token.collectionId, token.tokenId, pieces == 1n ? 'NFT' : 'RFT'); 
+    expect(consumedSpace).to.be.equal(originalSpace);
   }
-  it('Forbids changing/deleting properties of a token if the user is outside of permissions (NFT)', async () => {
-    await testForbidsChangingDeletingPropertiesUserOutsideOfPermissions({type: 'NFT'}, 1);
+
+  itSub('Forbids changing/deleting properties of a token if the user is outside of permissions (NFT)', async ({helper}) =>  {
+    const collection = await helper.nft.mintCollection(alice);
+    const token = await collection.mintToken(alice);
+    await testForbidsChangingDeletingPropertiesUserOutsideOfPermissions(token, 1n);
   });
-  it('Forbids changing/deleting properties of a token if the user is outside of permissions (ReFungible)', async function() {
-    await requirePallets(this, [Pallets.ReFungible]);
 
-    await testForbidsChangingDeletingPropertiesUserOutsideOfPermissions({type: 'ReFungible'}, 100);
+  itSub.ifWithPallets('Forbids changing/deleting properties of a token if the user is outside of permissions (ReFungible)', [Pallets.ReFungible], async ({helper}) => {
+    const collection = await helper.rft.mintCollection(alice);
+    const token = await collection.mintToken(alice, 100n);
+    await testForbidsChangingDeletingPropertiesUserOutsideOfPermissions(token, 100n);
   });
 
-  async function testForbidsChangingDeletingPropertiesIfPropertyImmutable(mode: CollectionMode, pieces: number) {
-    await prepare(mode, pieces);
-    
-    await usingApi(async api => {
-      let i = -1;
-      for (const permission of constitution) {
-        i++;
-        if (permission.permission.mutable) continue;
+  async function testForbidsChangingDeletingPropertiesIfPropertyImmutable(token: UniqueNFToken | UniqueRFToken, pieces: bigint) {
+    const originalSpace = await prepare(token, pieces);
+
+    let i = 0;
+    for (const permission of constitution) {
+      i++;
+      if (permission.permission.mutable) continue;
+
+      await expect(
+        token.setProperties(permission.signers[0], [{key: `${i}`, value: 'Serotonin down'}]), 
+        `on failing to change property ${i} by signer #0`,
+      ).to.be.rejectedWith(/common\.NoPermission/);
+
+      await expect(
+        token.deleteProperties(permission.signers[0], [i.toString()]), 
+        `on failing to delete property ${i} by signer #0`,
+      ).to.be.rejectedWith(/common\.NoPermission/);
+    }
   
-        await expect(executeTransaction(
-          api, 
-          permission.signers[0], 
-          api.tx.unique.setTokenProperties(collection, token, [{key: `${i}`, value: 'Serotonin down'}]), 
-        ), `on failing to change property ${i} by ${permission.signers[0].address}`).to.be.rejectedWith(/common\.NoPermission/);
-  
-        await expect(executeTransaction(
-          api, 
-          permission.signers[0], 
-          api.tx.unique.deleteTokenProperties(collection, token, [i.toString()]), 
-        ), `on failing to delete property ${i} by ${permission.signers[0].address}`).to.be.rejectedWith(/common\.NoPermission/);
-      }
-  
-      const properties = (await api.query.nonfungible.tokenProperties(collection, token)).toJSON();
-      expect(properties.consumedSpace).to.be.equal(originalSpace);
-    });  
+    const consumedSpace = await getConsumedSpace(token.collection.helper.api, token.collectionId, token.tokenId, pieces == 1n ? 'NFT' : 'RFT'); 
+    expect(consumedSpace).to.be.equal(originalSpace);
   }
-  it('Forbids changing/deleting properties of a token if the property is permanent (immutable) (NFT)', async () => {
-    await testForbidsChangingDeletingPropertiesIfPropertyImmutable({type: 'NFT'}, 1);
+
+  itSub('Forbids changing/deleting properties of a token if the property is permanent (immutable) (NFT)', async ({helper}) =>  {
+    const collection = await helper.nft.mintCollection(alice);
+    const token = await collection.mintToken(alice);
+    await testForbidsChangingDeletingPropertiesIfPropertyImmutable(token, 1n);
   });
-  it('Forbids changing/deleting properties of a token if the property is permanent (immutable) (ReFungible)', async function() {
-    await requirePallets(this, [Pallets.ReFungible]);
 
-    await testForbidsChangingDeletingPropertiesIfPropertyImmutable({type: 'ReFungible'}, 100);
+  itSub.ifWithPallets('Forbids changing/deleting properties of a token if the property is permanent (immutable) (ReFungible)', [Pallets.ReFungible], async ({helper}) => {
+    const collection = await helper.rft.mintCollection(alice);
+    const token = await collection.mintToken(alice, 100n);
+    await testForbidsChangingDeletingPropertiesIfPropertyImmutable(token, 100n);
   });
 
-  async function testForbidsAddingPropertiesIfPropertyNotDeclared(mode: CollectionMode, pieces: number) {
-    await prepare(mode, pieces);
+  async function testForbidsAddingPropertiesIfPropertyNotDeclared(token: UniqueNFToken | UniqueRFToken, pieces: bigint) {
+    const originalSpace = await prepare(token, pieces);
+
+    await expect(
+      token.setProperties(alice, [{key: 'non-existent', value: 'I exist!'}]), 
+      'on failing to add a previously non-existent property',
+    ).to.be.rejectedWith(/common\.NoPermission/);
+      
+    await expect(
+      token.collection.setTokenPropertyPermissions(alice, [{key: 'now-existent', permission: {}}]), 
+      'on setting a new non-permitted property',
+    ).to.be.fulfilled;
+
+    await expect(
+      token.setProperties(alice, [{key: 'now-existent', value: 'I exist!'}]), 
+      'on failing to add a property forbidden by the \'None\' permission',
+    ).to.be.rejectedWith(/common\.NoPermission/);
 
-    await usingApi(async api => {
-      await expect(executeTransaction(
-        api, 
-        alice, 
-        api.tx.unique.setTokenProperties(collection, token, [{key: 'non-existent', value: 'I exist!'}]), 
-      ), 'on failing to add a previously non-existent property').to.be.rejectedWith(/common\.NoPermission/);
-        
-      await expect(executeTransaction(
-        api, 
-        alice, 
-        api.tx.unique.setTokenPropertyPermissions(collection, [{key: 'now-existent', permission: {}}]), 
-      ), 'on setting a new non-permitted property').to.not.be.rejected;
-  
-      await expect(executeTransaction(
-        api, 
-        alice, 
-        api.tx.unique.setTokenProperties(collection, token, [{key: 'now-existent', value: 'I exist!'}]), 
-      ), 'on failing to add a property forbidden by the \'None\' permission').to.be.rejectedWith(/common\.NoPermission/);
-  
-      expect((await api.rpc.unique.tokenProperties(collection, token, ['non-existent', 'now-existent'])).toJSON()).to.be.empty;
-      const properties = (await api.query.nonfungible.tokenProperties(collection, token)).toJSON();
-      expect(properties.consumedSpace).to.be.equal(originalSpace);
-    });
+    expect(await token.getProperties(['non-existent', 'now-existent'])).to.be.empty;
+      
+    const consumedSpace = await getConsumedSpace(token.collection.helper.api, token.collectionId, token.tokenId, pieces == 1n ? 'NFT' : 'RFT'); 
+    expect(consumedSpace).to.be.equal(originalSpace);
   }
-  it('Forbids adding properties to a token if the property is not declared / forbidden with the \'None\' permission (NFT)', async () => {
-    await testForbidsAddingPropertiesIfPropertyNotDeclared({type: 'NFT'}, 1);
+
+  itSub('Forbids adding properties to a token if the property is not declared / forbidden with the \'None\' permission (NFT)', async ({helper}) =>  {
+    const collection = await helper.nft.mintCollection(alice);
+    const token = await collection.mintToken(alice);
+    await testForbidsAddingPropertiesIfPropertyNotDeclared(token, 1n);
   });
-  it('Forbids adding properties to a token if the property is not declared / forbidden with the \'None\' permission (ReFungible)', async function() {
-    await requirePallets(this, [Pallets.ReFungible]);
 
-    await testForbidsAddingPropertiesIfPropertyNotDeclared({type: 'ReFungible'}, 100);
+  itSub.ifWithPallets('Forbids adding properties to a token if the property is not declared / forbidden with the \'None\' permission (ReFungible)', [Pallets.ReFungible], async ({helper}) => {
+    const collection = await helper.rft.mintCollection(alice);
+    const token = await collection.mintToken(alice, 100n);
+    await testForbidsAddingPropertiesIfPropertyNotDeclared(token, 100n);
   });
 
-  async function testForbidsAddingTooManyProperties(mode: CollectionMode, pieces: number) {
-    await prepare(mode, pieces);
+  async function testForbidsAddingTooManyProperties(token: UniqueNFToken | UniqueRFToken, pieces: bigint) {
+    const originalSpace = await prepare(token, pieces);
+
+    await expect(
+      token.collection.setTokenPropertyPermissions(alice, [
+        {key: 'a_holy_book', permission: {collectionAdmin: true, tokenOwner: true}}, 
+        {key: 'young_years', permission: {collectionAdmin: true, tokenOwner: true}},
+      ]), 
+      'on setting new permissions for properties',
+    ).to.be.fulfilled;
+
+    // Mute the general tx parsing error
+    {
+      console.error = () => {};
+      await expect(token.setProperties(alice, [{key: 'a_holy_book', value: 'word '.repeat(6554)}]))
+        .to.be.rejected;
+    }
 
-    await usingApi(async api => {
-      await expect(executeTransaction(
-        api, 
-        alice, 
-        api.tx.unique.setTokenPropertyPermissions(collection, [
-          {key: 'a_holy_book', permission: {collectionAdmin: true, tokenOwner: true}}, 
-          {key: 'young_years', permission: {collectionAdmin: true, tokenOwner: true}},
-        ]), 
-      ), 'on setting a new non-permitted property').to.not.be.rejected;
+    await expect(token.setProperties(alice, [
+      {key: 'a_holy_book', value: 'word '.repeat(3277)}, 
+      {key: 'young_years', value: 'neverending'.repeat(1490)},
+    ])).to.be.rejectedWith(/common\.NoSpaceForProperty/);
   
-      // Mute the general tx parsing error
-      {
-        console.error = () => {};
-        await expect(executeTransaction(
-          api, 
-          alice, 
-          api.tx.unique.setCollectionProperties(collection, [{key: 'a_holy_book', value: 'word '.repeat(6554)}]), 
-        )).to.be.rejected;
-      }
-  
-      await expect(executeTransaction(
-        api, 
-        alice, 
-        api.tx.unique.setTokenProperties(collection, token, [
-          {key: 'a_holy_book', value: 'word '.repeat(3277)}, 
-          {key: 'young_years', value: 'neverending'.repeat(1490)},
-        ]), 
-      )).to.be.rejectedWith(/common\.NoSpaceForProperty/);
-  
-      expect((await api.rpc.unique.tokenProperties(collection, token, ['a_holy_book', 'young_years'])).toJSON()).to.be.empty;
-      const propertiesMap = (await api.query.nonfungible.tokenProperties(collection, token)).toJSON();
-      expect(propertiesMap.consumedSpace).to.be.equal(originalSpace);
-    });
+    expect(await token.getProperties(['a_holy_book', 'young_years'])).to.be.empty;
+    const consumedSpace = await getConsumedSpace(token.collection.helper.api, token.collectionId, token.tokenId, pieces == 1n ? 'NFT' : 'RFT'); 
+    expect(consumedSpace).to.be.equal(originalSpace);
   }
-  it('Forbids adding too many properties to a token (NFT)', async () => {
-    await testForbidsAddingTooManyProperties({type: 'NFT'}, 1);
+
+  itSub('Forbids adding too many properties to a token (NFT)', async ({helper}) =>  {
+    const collection = await helper.nft.mintCollection(alice);
+    const token = await collection.mintToken(alice);
+    await testForbidsAddingTooManyProperties(token, 1n);
   });
-  it('Forbids adding too many properties to a token (ReFungible)', async function() {
-    await requirePallets(this, [Pallets.ReFungible]);
 
-    await testForbidsAddingTooManyProperties({type: 'ReFungible'}, 100);
+  itSub.ifWithPallets('Forbids adding too many properties to a token (ReFungible)', [Pallets.ReFungible], async ({helper}) => {
+    const collection = await helper.rft.mintCollection(alice);
+    const token = await collection.mintToken(alice, 100n);
+    await testForbidsAddingTooManyProperties(token, 100n);
   });
 });
 
 describe('ReFungible token properties permissions tests', () => {
-  let collection: number;
-  let token: number;
+  let alice: IKeyringPair;
+  let bob: IKeyringPair;
+  let charlie: IKeyringPair;
 
   before(async function() {
-    await requirePallets(this, [Pallets.ReFungible]);
+    await usingPlaygrounds(async (helper, privateKey) => {
+      requirePalletsOrSkip(this, helper, [Pallets.ReFungible]);
 
-    await usingApi(async (api, privateKeyWrapper) => {
-      alice = privateKeyWrapper('//Alice');
-      bob = privateKeyWrapper('//Bob');
-      charlie = privateKeyWrapper('//Charlie');
+      const donor = privateKey('//Alice');
+      [alice, bob, charlie] = await helper.arrange.createAccounts([100n, 100n, 100n], donor);
     });
   });
 
-  beforeEach(async () => {
-    await usingApi(async api => {
-      collection = await createCollectionExpectSuccess({mode: {type: 'ReFungible'}});
-      token = await createItemExpectSuccess(alice, collection, 'ReFungible');
-      await addCollectionAdminExpectSuccess(alice, collection, bob.address);
+  async function prepare(helper: UniqueHelper): Promise<UniqueRFToken> {
+    const collection = await helper.rft.mintCollection(alice);
+    const token = await collection.mintToken(alice, 100n);
+    
+    await collection.addAdmin(alice, {Substrate: bob.address});
+    await collection.setTokenPropertyPermissions(alice, [{key: 'fractals', permission: {mutable: true, tokenOwner: true}}]);
+    
+    return token;
+  }
+
+  itSub('Forbids adding token property with tokenOwner==true when signer doesn\'t have all pieces', async ({helper}) =>  {
+    const token = await prepare(helper);
+
+    await token.transfer(alice, {Substrate: charlie.address}, 33n);
 
-      await expect(executeTransaction(
-        api, 
-        alice, 
-        api.tx.unique.setTokenPropertyPermissions(collection, [{key: 'key', permission: {mutable:true, tokenOwner: true}}]), 
-      )).to.not.be.rejected;
-    });
+    await expect(token.setProperties(alice, [
+      {key: 'fractals', value: 'multiverse'}, 
+    ])).to.be.rejectedWith(/common\.NoPermission/);
   });
 
-  it('Forbids add token property with tokenOwher==true but signer have\'t all pieces', async () => {
-    await usingApi(async api => {
-      await transferExpectSuccess(collection, token, alice, charlie, 33, 'ReFungible');
-  
-      await expect(executeTransaction(
-        api, 
-        alice, 
-        api.tx.unique.setTokenProperties(collection, token, [
-          {key: 'key', value: 'word'}, 
-        ]), 
-      )).to.be.rejectedWith(/common\.NoPermission/);
-    });
+  itSub('Forbids mutating token property with tokenOwher==true when signer doesn\'t have all pieces', async ({helper}) =>  {
+    const token = await prepare(helper);
+
+    await expect(token.collection.setTokenPropertyPermissions(alice, [{key: 'fractals', permission: {mutable:true, tokenOwner: true}}]))
+      .to.be.fulfilled;
+
+    await expect(token.setProperties(alice, [
+      {key: 'fractals', value: 'multiverse'}, 
+    ])).to.be.fulfilled;
+
+    await token.transfer(alice, {Substrate: charlie.address}, 33n);
+
+    await expect(token.setProperties(alice, [
+      {key: 'fractals', value: 'want to rule the world'}, 
+    ])).to.be.rejectedWith(/common\.NoPermission/);
   });
 
-  it('Forbids mutate token property with tokenOwher==true but signer have\'t all pieces', async () => {
-    await usingApi(async api => {
-      await expect(executeTransaction(
-        api, 
-        alice, 
-        api.tx.unique.setTokenPropertyPermissions(collection, [{key: 'key', permission: {mutable:true, tokenOwner: true}}]), 
-      )).to.not.be.rejected;
-  
-      await expect(executeTransaction(
-        api, 
-        alice, 
-        api.tx.unique.setTokenProperties(collection, token, [
-          {key: 'key', value: 'word'}, 
-        ]), 
-      )).to.be.not.rejected;
+  itSub('Forbids deleting token property with tokenOwner==true when signer doesn\'t have all pieces', async ({helper}) =>  {
+    const token = await prepare(helper);
+
+    await expect(token.setProperties(alice, [
+      {key: 'fractals', value: 'one headline - why believe it'}, 
+    ])).to.be.fulfilled;
+
+    await token.transfer(alice, {Substrate: charlie.address}, 33n);
 
-      await transferExpectSuccess(collection, token, alice, charlie, 33, 'ReFungible');
-  
-      await expect(executeTransaction(
-        api, 
-        alice, 
-        api.tx.unique.setTokenProperties(collection, token, [
-          {key: 'key', value: 'bad word'}, 
-        ]), 
-      )).to.be.rejectedWith(/common\.NoPermission/);
-    });
+    await expect(token.deleteProperties(alice, ['fractals'])).
+      to.be.rejectedWith(/common\.NoPermission/);
   });
 
-  it('Forbids delete token property with tokenOwher==true but signer have\'t all pieces', async () => {
-    await usingApi(async api => {
-      await expect(executeTransaction(
-        api, 
-        alice, 
-        api.tx.unique.setTokenProperties(collection, token, [
-          {key: 'key', value: 'word'}, 
-        ]), 
-      )).to.be.not.rejected;
+  itSub('Allows token property mutation with collectionOwner==true when admin doesn\'t have all pieces', async ({helper}) =>  {
+    const token = await prepare(helper);
 
-      await transferExpectSuccess(collection, token, alice, charlie, 33, 'ReFungible');
-  
-      await expect(executeTransaction(
-        api, 
-        alice, 
-        api.tx.unique.deleteTokenProperties(collection, token, [
-          'key',
-        ]), 
-      )).to.be.rejectedWith(/common\.NoPermission/);
-    });
+    await token.transfer(alice, {Substrate: charlie.address}, 33n);
+
+    await expect(token.collection.setTokenPropertyPermissions(alice, [{key: 'fractals', permission: {mutable:true, collectionAdmin: true}}]))
+      .to.be.fulfilled;
+
+    await expect(token.setProperties(alice, [
+      {key: 'fractals', value: 'multiverse'}, 
+    ])).to.be.fulfilled;
   });
 });
deletedtests/src/nesting/rules-smoke.test.tsdiffbeforeafterboth
--- a/tests/src/nesting/rules-smoke.test.ts
+++ /dev/null
@@ -1,63 +0,0 @@
-import {expect} from 'chai';
-import {tokenIdToAddress} from '../eth/util/helpers';
-import usingApi, {executeTransaction} from '../substrate/substrate-api';
-import {createCollectionExpectSuccess, createFungibleItemExpectSuccess, createItemExpectSuccess, CrossAccountId, getCreateCollectionResult, requirePallets, Pallets} from '../util/helpers';
-import {IKeyringPair} from '@polkadot/types/types';
-
-describe('nesting check', () => {
-  let alice!: IKeyringPair;
-  let nestTarget!: CrossAccountId;
-  before(async() => {
-    await usingApi(async (api, privateKeyWrapper) => {
-      alice = privateKeyWrapper('//Alice');
-      const bob = privateKeyWrapper('//Bob');
-      const events = await executeTransaction(api, alice, api.tx.unique.createCollectionEx({
-        mode: 'NFT',
-        permissions: {
-          nesting: {tokenOwner: true, restricted: []},
-        },
-      }));
-      const collection = getCreateCollectionResult(events).collectionId;
-      const token = await createItemExpectSuccess(alice, collection, 'NFT', {Substrate: bob.address});
-      nestTarget = {Ethereum: tokenIdToAddress(collection, token)};
-    });
-  });
-
-  it('called for fungible', async () => {
-    await usingApi(async api => {
-      const collection = await createCollectionExpectSuccess({mode: {type: 'Fungible',decimalPoints:0}});
-      await expect(executeTransaction(api, alice, api.tx.unique.createItem(collection, nestTarget, {Fungible: {Value: 1}})))
-        .to.be.rejectedWith(/^common\.UserIsNotAllowedToNest$/);
-
-      await createFungibleItemExpectSuccess(alice, collection, {Value:1n}, {Substrate: alice.address});
-      await expect(executeTransaction(api, alice, api.tx.unique.transfer(nestTarget, collection, 0, 1n)))
-        .to.be.rejectedWith(/^common\.UserIsNotAllowedToNest$/);
-    });
-  });
-
-  it('called for nonfungible', async () => {
-    await usingApi(async api => {
-      const collection = await createCollectionExpectSuccess({mode: {type: 'NFT'}});
-      await expect(executeTransaction(api, alice, api.tx.unique.createItem(collection, nestTarget, {NFT: {properties: []}})))
-        .to.be.rejectedWith(/^common\.UserIsNotAllowedToNest$/);
-
-      const token = await createItemExpectSuccess(alice, collection, 'NFT', {Substrate: alice.address});
-      await expect(executeTransaction(api, alice, api.tx.unique.transfer(nestTarget, collection, token, 1n)))
-        .to.be.rejectedWith(/^common\.UserIsNotAllowedToNest$/);
-    });
-  });
-
-  it('called for refungible', async function() {
-    await requirePallets(this, [Pallets.ReFungible]);
-
-    await usingApi(async api => {
-      const collection = await createCollectionExpectSuccess({mode: {type: 'ReFungible'}});
-      await expect(executeTransaction(api, alice, api.tx.unique.createItem(collection, nestTarget, {ReFungible: {}})))
-        .to.be.rejectedWith(/^common\.UserIsNotAllowedToNest$/);
-
-      const token = await createItemExpectSuccess(alice, collection, 'ReFungible', {Substrate: alice.address});
-      await expect(executeTransaction(api, alice, api.tx.unique.transfer(nestTarget, collection, token, 1n)))
-        .to.be.rejectedWith(/^common\.UserIsNotAllowedToNest$/);
-    });
-  });
-});
modifiedtests/src/nesting/unnest.test.tsdiffbeforeafterboth
--- a/tests/src/nesting/unnest.test.ts
+++ b/tests/src/nesting/unnest.test.ts
@@ -1,162 +1,126 @@
-import {expect} from 'chai';
-import {tokenIdToAddress} from '../eth/util/helpers';
-import usingApi, {executeTransaction} from '../substrate/substrate-api';
-import {
-  createCollectionExpectSuccess,
-  createItemExpectSuccess,
-  getBalance,
-  getTokenOwner,
-  normalizeAccountId,
-  setCollectionPermissionsExpectSuccess,
-  transferExpectSuccess,
-  transferFromExpectSuccess,
-  requirePallets,
-  Pallets,
-} from '../util/helpers';
+// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.
+// This file is part of Unique Network.
+
+// Unique Network is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+
+// Unique Network is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+// GNU General Public License for more details.
+
+// You should have received a copy of the GNU General Public License
+// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
+
 import {IKeyringPair} from '@polkadot/types/types';
+import {expect, itSub, Pallets, usingPlaygrounds} from '../util/playgrounds';
 
-let alice: IKeyringPair;
-let bob: IKeyringPair;
+describe('Integration Test: Unnesting', () => {
+  let alice: IKeyringPair;
 
-describe('Integration Test: Unnesting', () => {
   before(async () => {
-    await usingApi(async (api, privateKeyWrapper) => {
-      alice = privateKeyWrapper('//Alice');
-      bob = privateKeyWrapper('//Bob');
+    await usingPlaygrounds(async (helper, privateKey) => {
+      const donor = privateKey('//Alice');
+      [alice] = await helper.arrange.createAccounts([50n], donor);
     });
   });
 
-  it('NFT: allows the owner to successfully unnest a token', async () => {
-    await usingApi(async api => {
-      const collection = await createCollectionExpectSuccess({mode: {type: 'NFT'}});
-      await setCollectionPermissionsExpectSuccess(alice, collection, {nesting: {tokenOwner: true}});
-      const targetToken = await createItemExpectSuccess(alice, collection, 'NFT');
-      const targetAddress = {Ethereum: tokenIdToAddress(collection, targetToken)};
-
-      // Create a nested token
-      const nestedToken = await createItemExpectSuccess(alice, collection, 'NFT', targetAddress);
+  itSub('NFT: allows the owner to successfully unnest a token', async ({helper}) => {
+    const collection = await helper.nft.mintCollection(alice, {permissions: {nesting: {tokenOwner: true}}});
+    const targetToken = await collection.mintToken(alice);
+    
+    // Create a nested token
+    const nestedToken = await collection.mintToken(alice, targetToken.nestingAccount());
 
-      // Unnest
-      await expect(executeTransaction(
-        api,
-        alice,
-        api.tx.unique.transferFrom(normalizeAccountId(targetAddress), normalizeAccountId(alice), collection, nestedToken, 1),
-      ), 'while unnesting').to.not.be.rejected;
-      expect(await getTokenOwner(api, collection, nestedToken)).to.be.deep.equal({Substrate: alice.address});
+    // Unnest
+    await expect(nestedToken.transferFrom(alice, targetToken.nestingAccount(), {Substrate: alice.address}), 'while unnesting').to.be.fulfilled;
+    expect(await nestedToken.getOwner()).to.be.deep.equal({Substrate: alice.address});
 
-      // Nest and burn
-      await transferExpectSuccess(collection, nestedToken, alice, targetAddress);
-      await expect(executeTransaction(
-        api,
-        alice,
-        api.tx.unique.burnFrom(collection, normalizeAccountId(targetAddress), nestedToken, 1),
-      ), 'while burning').to.not.be.rejected;
-      await expect(getTokenOwner(api, collection, nestedToken)).to.be.rejected;
-    });
+    // Nest and burn
+    await nestedToken.nest(alice, targetToken);
+    await expect(nestedToken.burnFrom(alice, targetToken.nestingAccount()), 'while burning').to.be.fulfilled;
+    await expect(nestedToken.getOwner()).to.be.rejected;
   });
 
-  it('Fungible: allows the owner to successfully unnest a token', async () => {
-    await usingApi(async api => {
-      const collection = await createCollectionExpectSuccess({mode: {type: 'NFT'}});
-      await setCollectionPermissionsExpectSuccess(alice, collection, {nesting: {tokenOwner: true}});
-      const targetToken = await createItemExpectSuccess(alice, collection, 'NFT');
-      const targetAddress = {Ethereum: tokenIdToAddress(collection, targetToken)};
+  itSub('Fungible: allows the owner to successfully unnest a token', async ({helper}) => {
+    const collection = await helper.nft.mintCollection(alice, {permissions: {nesting: {tokenOwner: true}}});
+    const targetToken = await collection.mintToken(alice);
 
-      const collectionFT = await createCollectionExpectSuccess({mode: {type: 'Fungible', decimalPoints: 0}});
-      const nestedToken = await createItemExpectSuccess(alice, collectionFT, 'Fungible');
+    const collectionFT = await helper.ft.mintCollection(alice);
+    
+    // Nest and unnest
+    await collectionFT.mint(alice, 10n, targetToken.nestingAccount());
+    await expect(collectionFT.transferFrom(alice, targetToken.nestingAccount(), {Substrate: alice.address}, 9n), 'while unnesting').to.be.fulfilled;
+    expect(await collectionFT.getBalance({Substrate: alice.address})).to.be.equal(9n);
+    expect(await collectionFT.getBalance(targetToken.nestingAccount())).to.be.equal(1n);
 
-      // Nest and unnest
-      await transferExpectSuccess(collectionFT, nestedToken, alice, targetAddress, 1, 'Fungible');
-      await transferFromExpectSuccess(collectionFT, nestedToken, alice, targetAddress, alice, 1, 'Fungible');
-
-      // Nest and burn
-      await transferExpectSuccess(collectionFT, nestedToken, alice, targetAddress, 1, 'Fungible');
-      const balanceBefore = await getBalance(api, collectionFT, normalizeAccountId(targetAddress), nestedToken);
-      await expect(executeTransaction(
-        api,
-        alice,
-        api.tx.unique.burnFrom(collectionFT, normalizeAccountId(targetAddress), nestedToken, 1),
-      ), 'while burning').to.not.be.rejected;
-      const balanceAfter = await getBalance(api, collectionFT, normalizeAccountId(targetAddress), nestedToken);
-      expect(balanceAfter + BigInt(1)).to.be.equal(balanceBefore);
-    });
+    // Nest and burn
+    await collectionFT.transfer(alice, targetToken.nestingAccount(), 5n);
+    await expect(collectionFT.burnTokensFrom(alice, targetToken.nestingAccount(), 6n), 'while burning').to.be.fulfilled;
+    expect(await collectionFT.getBalance({Substrate: alice.address})).to.be.equal(4n);
+    expect(await collectionFT.getBalance(targetToken.nestingAccount())).to.be.equal(0n);
+    expect(await targetToken.getChildren()).to.be.length(0);
   });
 
-  it('ReFungible: allows the owner to successfully unnest a token', async function() {
-    await requirePallets(this, [Pallets.ReFungible]);
+  itSub.ifWithPallets('ReFungible: allows the owner to successfully unnest a token', [Pallets.ReFungible], async ({helper}) => {
+    const collection = await helper.nft.mintCollection(alice, {permissions: {nesting: {tokenOwner: true}}});
+    const targetToken = await collection.mintToken(alice);
 
-    await usingApi(async api => {
-      const collection = await createCollectionExpectSuccess({mode: {type: 'NFT'}});
-      await setCollectionPermissionsExpectSuccess(alice, collection, {nesting: {tokenOwner: true}});
-      const targetToken = await createItemExpectSuccess(alice, collection, 'NFT');
-      const targetAddress = {Ethereum: tokenIdToAddress(collection, targetToken)};
-
-      const collectionRFT = await createCollectionExpectSuccess({mode: {type: 'ReFungible'}});
-      const nestedToken = await createItemExpectSuccess(alice, collectionRFT, 'ReFungible');
-
-      // Nest and unnest
-      await transferExpectSuccess(collectionRFT, nestedToken, alice, targetAddress, 1, 'ReFungible');
-      await transferFromExpectSuccess(collectionRFT, nestedToken, alice, targetAddress, alice, 1, 'ReFungible');
+    const collectionRFT = await helper.rft.mintCollection(alice);
+    
+    // Nest and unnest
+    const token = await collectionRFT.mintToken(alice, 10n, targetToken.nestingAccount());
+    await expect(token.transferFrom(alice, targetToken.nestingAccount(), {Substrate: alice.address}, 9n), 'while unnesting').to.be.fulfilled;
+    expect(await token.getBalance({Substrate: alice.address})).to.be.equal(9n);
+    expect(await token.getBalance(targetToken.nestingAccount())).to.be.equal(1n);
 
-      // Nest and burn
-      await transferExpectSuccess(collectionRFT, nestedToken, alice, targetAddress, 1, 'ReFungible');
-      await expect(executeTransaction(
-        api,
-        alice,
-        api.tx.unique.burnFrom(collectionRFT, normalizeAccountId(targetAddress), nestedToken, 1),
-      ), 'while burning').to.not.be.rejected;
-      const balance = await getBalance(api, collectionRFT, normalizeAccountId(targetAddress), nestedToken);
-      expect(balance).to.be.equal(0n);
-    });
+    // Nest and burn
+    await token.transfer(alice, targetToken.nestingAccount(), 5n);
+    await expect(token.burnFrom(alice, targetToken.nestingAccount(), 6n), 'while burning').to.be.fulfilled;
+    expect(await token.getBalance({Substrate: alice.address})).to.be.equal(4n);
+    expect(await token.getBalance(targetToken.nestingAccount())).to.be.equal(0n);
+    expect(await targetToken.getChildren()).to.be.length(0);
   });
 });
 
 describe('Negative Test: Unnesting', () => {
+  let alice: IKeyringPair;
+  let bob: IKeyringPair;
+
   before(async () => {
-    await usingApi(async (api, privateKeyWrapper) => {
-      alice = privateKeyWrapper('//Alice');
-      bob = privateKeyWrapper('//Bob');
+    await usingPlaygrounds(async (helper, privateKey) => {
+      const donor = privateKey('//Alice');
+      [alice, bob] = await helper.arrange.createAccounts([50n, 10n], donor);
     });
   });
 
-  it('Disallows a non-owner to unnest/burn a token', async () => {
-    await usingApi(async api => {
-      const collection = await createCollectionExpectSuccess({mode: {type: 'NFT'}});
-      await setCollectionPermissionsExpectSuccess(alice, collection, {nesting: {tokenOwner: true}});
-      const targetToken = await createItemExpectSuccess(alice, collection, 'NFT');
-      const targetAddress = {Ethereum: tokenIdToAddress(collection, targetToken)};
+  itSub('Disallows a non-owner to unnest/burn a token', async ({helper}) => {
+    const collection = await helper.nft.mintCollection(alice, {permissions: {nesting: {tokenOwner: true}}});
+    const targetToken = await collection.mintToken(alice);
 
-      // Create a nested token
-      const nestedToken = await createItemExpectSuccess(alice, collection, 'NFT', targetAddress);
+    // Create a nested token
+    const nestedToken = await collection.mintToken(alice, targetToken.nestingAccount());
 
-      // Try to unnest
-      await expect(executeTransaction(
-        api,
-        bob,
-        api.tx.unique.transferFrom(normalizeAccountId(targetAddress), normalizeAccountId(bob), collection, nestedToken, 1),
-      ), 'while unnesting').to.be.rejectedWith(/^common\.ApprovedValueTooLow$/);
-      expect(await getTokenOwner(api, collection, nestedToken)).to.be.deep.equal({Ethereum: tokenIdToAddress(collection, targetToken).toLowerCase()});
+    // Try to unnest
+    await expect(nestedToken.unnest(bob, targetToken, {Substrate: alice.address})).to.be.rejectedWith(/common\.ApprovedValueTooLow/);
+    expect(await nestedToken.getOwner()).to.be.deep.equal(targetToken.nestingAccount().toLowerCase());
 
-      // Try to burn
-      await expect(executeTransaction(
-        api,
-        bob,
-        api.tx.unique.burnFrom(collection, normalizeAccountId(bob.address), nestedToken, 1),
-      ), 'while burning').to.not.be.rejectedWith(/^common\.ApprovedValueTooLow$/);
-      expect(await getTokenOwner(api, collection, nestedToken)).to.be.deep.equal({Ethereum: tokenIdToAddress(collection, targetToken).toLowerCase()});
-    });
+    // Try to burn
+    await expect(nestedToken.burnFrom(bob, targetToken.nestingAccount())).to.be.rejectedWith(/common\.ApprovedValueTooLow/);
+    expect(await nestedToken.getOwner()).to.be.deep.equal(targetToken.nestingAccount().toLowerCase());
   });
 
   // todo another test for creating excessive depth matryoshka with Ethereum?
 
   // Recursive nesting
-  it('Prevents Ouroboros creation', async () => {
-    const collection = await createCollectionExpectSuccess({mode: {type: 'NFT'}});
-    await setCollectionPermissionsExpectSuccess(alice, collection, {nesting: {tokenOwner: true}});
-    const targetToken = await createItemExpectSuccess(alice, collection, 'NFT');
+  itSub('Prevents Ouroboros creation', async ({helper}) => {
+    const collection = await helper.nft.mintCollection(alice, {permissions: {nesting: {tokenOwner: true}}});
+    const targetToken = await collection.mintToken(alice);
 
-    // Create a nested token ouroboros
-    const nestedToken = await createItemExpectSuccess(alice, collection, 'NFT', {Ethereum: tokenIdToAddress(collection, targetToken)});
-    await expect(transferExpectSuccess(collection, targetToken, alice, {Ethereum: tokenIdToAddress(collection, nestedToken)})).to.be.rejectedWith(/^structure\.OuroborosDetected$/);
+    // Fail to create a nested token ouroboros
+    const nestedToken = await collection.mintToken(alice, targetToken.nestingAccount());
+    await expect(targetToken.nest(alice, nestedToken)).to.be.rejectedWith(/^structure\.OuroborosDetected$/);
   });
 });
modifiedtests/src/rpc.test.tsdiffbeforeafterboth
--- a/tests/src/rpc.test.ts
+++ b/tests/src/rpc.test.ts
@@ -16,7 +16,7 @@
 
 import {IKeyringPair} from '@polkadot/types/types';
 import {usingPlaygrounds, itSub, expect} from './util/playgrounds';
-import {crossAccountIdFromLower} from './util/playgrounds/unique';
+import {CrossAccountId} from './util/playgrounds/unique';
 
 describe('integration test: RPC methods', () => {
   let donor: IKeyringPair;
@@ -55,7 +55,7 @@
     // Set-up over
 
     const owners = await helper.callRpc('api.rpc.unique.tokenOwners', [collection.collectionId, 0]);
-    const ids = (owners.toJSON() as any[]).map(crossAccountIdFromLower);
+    const ids = (owners.toJSON() as any[]).map(CrossAccountId.fromLowerCaseKeys);
 
     expect(ids).to.deep.include.members([{Substrate: alice.address}, ethAcc, {Substrate: bob.address}, ...facelessCrowd]);
     expect(owners.length == 10).to.be.true;
modifiedtests/src/util/playgrounds/index.tsdiffbeforeafterboth
--- a/tests/src/util/playgrounds/index.ts
+++ b/tests/src/util/playgrounds/index.ts
@@ -9,7 +9,6 @@
 import '../../interfaces/augment-api-events';
 import {DevUniqueHelper, SilentLogger, SilentConsole} from './unique.dev';
 
-
 chai.use(chaiAsPromised);
 export const expect = chai.expect;
 
@@ -63,6 +62,12 @@
     });
   });
 }
+export async function itSubIfWithPallet(name: string, required: string[], cb: (apis: { helper: DevUniqueHelper, privateKey: (seed: string) => IKeyringPair }) => any, opts: { only?: boolean, skip?: boolean, requiredPallets?: string[] } = {}) {
+  return itSub(name, cb, {requiredPallets: required, ...opts});
+}
 itSub.only = (name: string, cb: (apis: { helper: DevUniqueHelper, privateKey: (seed: string) => IKeyringPair }) => any) => itSub(name, cb, {only: true});
 itSub.skip = (name: string, cb: (apis: { helper: DevUniqueHelper, privateKey: (seed: string) => IKeyringPair }) => any) => itSub(name, cb, {skip: true});
-itSub.ifWithPallets = (name: string, required: string[], cb: (apis: { helper: DevUniqueHelper, privateKey: (seed: string) => IKeyringPair }) => any) => itSub(name, cb, {requiredPallets: required});
+
+itSubIfWithPallet.only = (name: string, required: string[], cb: (apis: { helper: DevUniqueHelper, privateKey: (seed: string) => IKeyringPair }) => any) => itSubIfWithPallet(name, required, cb, {only: true});
+itSubIfWithPallet.skip = (name: string, required: string[], cb: (apis: { helper: DevUniqueHelper, privateKey: (seed: string) => IKeyringPair }) => any) => itSubIfWithPallet(name, required, cb, {skip: true});
+itSub.ifWithPallets = itSubIfWithPallet;
modifiedtests/src/util/playgrounds/types.tsdiffbeforeafterboth
--- a/tests/src/util/playgrounds/types.ts
+++ b/tests/src/util/playgrounds/types.ts
@@ -94,15 +94,15 @@
 
 export interface IProperty {
   key: string;
-  value: string;
+  value?: string;
 }
 
 export interface ITokenPropertyPermission {
   key: string;
   permission: {
-    mutable: boolean;
-    tokenOwner: boolean;
-    collectionAdmin: boolean;
+    mutable?: boolean;
+    tokenOwner?: boolean;
+    collectionAdmin?: boolean;
   }
 }
 
modifiedtests/src/util/playgrounds/unique.dev.tsdiffbeforeafterboth
--- a/tests/src/util/playgrounds/unique.dev.ts
+++ b/tests/src/util/playgrounds/unique.dev.ts
@@ -6,6 +6,7 @@
 import {ApiPromise, WsProvider} from '@polkadot/api';
 import * as defs from '../../interfaces/definitions';
 import {IKeyringPair} from '@polkadot/types/types';
+import {ICrossAccountId} from './types';
 
 
 export class SilentLogger {
@@ -230,6 +231,17 @@
     const block2date = await findCreationDate(block2);
     if(block2date! - block1date! < 9000) return true;
   };
+  
+  async calculcateFee(payer: ICrossAccountId, promise: () => Promise<any>): Promise<bigint> {
+    const address = payer.Substrate ? payer.Substrate : await this.helper.address.ethToSubstrate(payer.Ethereum!);
+    let balance = await this.helper.balance.getSubstrate(address); 
+    
+    await promise();
+    
+    balance -= await this.helper.balance.getSubstrate(address);
+    
+    return balance;
+  }
 }
 
 class WaitGroup {
modifiedtests/src/util/playgrounds/unique.tsdiffbeforeafterboth
before · tests/src/util/playgrounds/unique.ts
1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// SPDX-License-Identifier: Apache-2.034/* eslint-disable @typescript-eslint/no-var-requires */5/* eslint-disable function-call-argument-newline */6/* eslint-disable no-prototype-builtins */78import {ApiPromise, WsProvider, Keyring} from '@polkadot/api';9import {ApiInterfaceEvents, SignerOptions} from '@polkadot/api/types';10import {encodeAddress, decodeAddress, keccakAsHex, evmToAddress, addressToEvm} from '@polkadot/util-crypto';11import {IKeyringPair} from '@polkadot/types/types';12import {IApiListeners, IBlock, IEvent, IChainProperties, ICollectionCreationOptions, ICollectionLimits, ICollectionPermissions, ICrossAccountId, ICrossAccountIdLower, ILogger, INestingPermissions, IProperty, IStakingInfo, ISubstrateBalance, IToken, ITokenPropertyPermission, ITransactionResult, IUniqueHelperLog, TApiAllowedListeners, TEthereumAccount, TSigner, TSubstrateAccount, TUniqueNetworks} from './types';1314export const crossAccountIdFromLower = (lowerAddress: ICrossAccountIdLower): ICrossAccountId => {15  const address = {} as ICrossAccountId;16  if(lowerAddress.substrate) address.Substrate = lowerAddress.substrate;17  if(lowerAddress.ethereum) address.Ethereum = lowerAddress.ethereum;18  return address;19};2021const nesting = {22  toChecksumAddress(address: string): string {23    if (typeof address === 'undefined') return '';2425    if(!/^(0x)?[0-9a-f]{40}$/i.test(address)) throw new Error(`Given address "${address}" is not a valid Ethereum address.`);2627    address = address.toLowerCase().replace(/^0x/i,'');28    const addressHash = keccakAsHex(address).replace(/^0x/i,'');29    const checksumAddress = ['0x'];3031    for (let i = 0; i < address.length; i++) {32      // If ith character is 8 to f then make it uppercase33      if (parseInt(addressHash[i], 16) > 7) {34        checksumAddress.push(address[i].toUpperCase());35      } else {36        checksumAddress.push(address[i]);37      }38    }39    return checksumAddress.join('');40  },41  tokenIdToAddress(collectionId: number, tokenId: number) {42    return this.toChecksumAddress(`0xf8238ccfff8ed887463fd5e0${collectionId.toString(16).padStart(8, '0')}${tokenId.toString(16).padStart(8, '0')}`);43  },44};4546class UniqueUtil {47  static transactionStatus = {48    NOT_READY: 'NotReady',49    FAIL: 'Fail',50    SUCCESS: 'Success',51  };5253  static chainLogType = {54    EXTRINSIC: 'extrinsic',55    RPC: 'rpc',56  };5758  static getNestingTokenAddress(collectionId: number, tokenId: number) {59    return nesting.tokenIdToAddress(collectionId, tokenId);60  }6162  static getDefaultLogger(): ILogger {63    return {64      log(msg: any, level = 'INFO') {65        console[level.toLocaleLowerCase() === 'error' ? 'error' : 'log'](...(Array.isArray(msg) ? msg : [msg]));66      },67      level: {68        ERROR: 'ERROR',69        WARNING: 'WARNING',70        INFO: 'INFO',71      },72    };73  }7475  static vec2str(arr: string[] | number[]) {76    return arr.map(x => String.fromCharCode(parseInt(x.toString()))).join('');77  }7879  static str2vec(string: string) {80    if (typeof string !== 'string') return string;81    return Array.from(string).map(x => x.charCodeAt(0));82  }8384  static fromSeed(seed: string, ss58Format = 42) {85    const keyring = new Keyring({type: 'sr25519', ss58Format});86    return keyring.addFromUri(seed);87  }8889  static normalizeSubstrateAddress(address: string, ss58Format = 42) {90    return encodeAddress(decodeAddress(address), ss58Format);91  }9293  static extractCollectionIdFromCreationResult(creationResult: ITransactionResult) {94    if (creationResult.status !== this.transactionStatus.SUCCESS) {95      throw Error('Unable to create collection!');96    }9798    let collectionId = null;99    creationResult.result.events.forEach(({event: {data, method, section}}) => {100      if ((section === 'common') && (method === 'CollectionCreated')) {101        collectionId = parseInt(data[0].toString(), 10);102      }103    });104105    if (collectionId === null) {106      throw Error('No CollectionCreated event was found!');107    }108109    return collectionId;110  }111112  static extractTokensFromCreationResult(creationResult: ITransactionResult) {113    if (creationResult.status !== this.transactionStatus.SUCCESS) {114      throw Error('Unable to create tokens!');115    }116    let success = false;117    const tokens = [] as any;118    creationResult.result.events.forEach(({event: {data, method, section}}) => {119      if (method === 'ExtrinsicSuccess') {120        success = true;121      } else if ((section === 'common') && (method === 'ItemCreated')) {122        tokens.push({123          collectionId: parseInt(data[0].toString(), 10),124          tokenId: parseInt(data[1].toString(), 10),125          owner: data[2].toJSON(),126        });127      }128    });129    return {success, tokens};130  }131132  static extractTokensFromBurnResult(burnResult: ITransactionResult) {133    if (burnResult.status !== this.transactionStatus.SUCCESS) {134      throw Error('Unable to burn tokens!');135    }136    let success = false;137    const tokens = [] as any;138    burnResult.result.events.forEach(({event: {data, method, section}}) => {139      if (method === 'ExtrinsicSuccess') {140        success = true;141      } else if ((section === 'common') && (method === 'ItemDestroyed')) {142        tokens.push({143          collectionId: parseInt(data[0].toString(), 10),144          tokenId: parseInt(data[1].toString(), 10),145          owner: data[2].toJSON(),146        });147      }148    });149    return {success, tokens};150  }151152  static findCollectionInEvents(events: {event: IEvent}[], collectionId: number, expectedSection: string, expectedMethod: string) {153    let eventId = null;154    events.forEach(({event: {data, method, section}}) => {155      if ((section === expectedSection) && (method === expectedMethod)) {156        eventId = parseInt(data[0].toString(), 10);157      }158    });159160    if (eventId === null) {161      throw Error(`No ${expectedMethod} event was found!`);162    }163    return eventId === collectionId;164  }165166  static isTokenTransferSuccess(events: {event: IEvent}[], collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {167    const normalizeAddress = (address: string | ICrossAccountId) => {168      if(typeof address === 'string') return address;169      const obj = {} as any;170      Object.keys(address).forEach(k => {171        obj[k.toLocaleLowerCase()] = address[k as 'Substrate' | 'Ethereum'];172      });173      if(obj.substrate) return {Substrate: this.normalizeSubstrateAddress(obj.substrate)};174      if(obj.ethereum) return {Ethereum: obj.ethereum.toLocaleLowerCase()};175      return address;176    };177    let transfer = {collectionId: null, tokenId: null, from: null, to: null, amount: 1} as any;178    events.forEach(({event: {data, method, section}}) => {179      if ((section === 'common') && (method === 'Transfer')) {180        const hData = (data as any).toJSON();181        transfer = {182          collectionId: hData[0],183          tokenId: hData[1],184          from: normalizeAddress(hData[2]),185          to: normalizeAddress(hData[3]),186          amount: BigInt(hData[4]),187        };188      }189    });190    let isSuccess = parseInt(collectionId.toString()) === transfer.collectionId && parseInt(tokenId.toString()) === transfer.tokenId;191    isSuccess = isSuccess && JSON.stringify(normalizeAddress(fromAddressObj)) === JSON.stringify(transfer.from);192    isSuccess = isSuccess && JSON.stringify(normalizeAddress(toAddressObj)) === JSON.stringify(transfer.to);193    isSuccess = isSuccess && amount === transfer.amount;194    return isSuccess;195  }196}197198class UniqueEventHelper {199  private static extractIndex(index: any): [number, number] | string {200    if(index.toRawType() === '[u8;2]') return [index[0], index[1]];201    return index.toJSON();202  }203204  private static extractSub(data: any, subTypes: any): {[key: string]: any} {205    let obj: any = {};206    let index = 0;207208    if (data.entries) {209      for(const [key, value] of data.entries()) {210        obj[key] = this.extractData(value, subTypes[index]);211        index++;212      }213    } else obj = data.toJSON();214215    return obj;216  }217  218  private static extractData(data: any, type: any): any {219    if (['u16', 'u32'].indexOf(type.type) > -1) return data.toNumber();220    if (['u64', 'u128', 'u256'].indexOf(type.type) > -1) return data.toBigInt();221    if(type.hasOwnProperty('sub')) return this.extractSub(data, type.sub);222    return data.toHuman();223  }224225  public static extractEvents(records: ITransactionResult): IEvent[] {226    const parsedEvents: IEvent[] = [];227228    records.result.events.forEach((record) => {229      const {event, phase} = record;230      const types = (event as any).typeDef;231232      const eventData: IEvent = {233        section: event.section.toString(),234        method: event.method.toString(),235        index: this.extractIndex(event.index),236        data: [],237        phase: phase.toJSON(),238      };239240      event.data.forEach((val: any, index: number) => {241        eventData.data.push(this.extractData(val, types[index]));242      });243244      parsedEvents.push(eventData);245    });246247    return parsedEvents;248  }249}250251class ChainHelperBase {252  transactionStatus = UniqueUtil.transactionStatus;253  chainLogType = UniqueUtil.chainLogType;254  util: typeof UniqueUtil;255  eventHelper: typeof UniqueEventHelper;256  logger: ILogger;257  api: ApiPromise | null;258  forcedNetwork: TUniqueNetworks | null;259  network: TUniqueNetworks | null;260  chainLog: IUniqueHelperLog[];261262  constructor(logger?: ILogger) {263    this.util = UniqueUtil;264    this.eventHelper = UniqueEventHelper;265    if (typeof logger == 'undefined') logger = this.util.getDefaultLogger();266    this.logger = logger;267    this.api = null;268    this.forcedNetwork = null;269    this.network = null;270    this.chainLog = [];271  }272273  clearChainLog(): void {274    this.chainLog = [];275  }276277  forceNetwork(value: TUniqueNetworks): void {278    this.forcedNetwork = value;279  }280281  async connect(wsEndpoint: string, listeners?: IApiListeners) {282    if (this.api !== null) throw Error('Already connected');283    const {api, network} = await ChainHelperBase.createConnection(wsEndpoint, listeners, this.forcedNetwork);284    this.api = api;285    this.network = network;286  }287288  async disconnect() {289    if (this.api === null) return;290    await this.api.disconnect();291    this.api = null;292    this.network = null;293  }294295  static async detectNetwork(api: ApiPromise): Promise<TUniqueNetworks> {296    const spec = (await api.query.system.lastRuntimeUpgrade()).toJSON() as any;297    if(['quartz', 'unique'].indexOf(spec.specName) > -1) return spec.specName;298    return 'opal';299  }300301  static async detectNetworkByWsEndpoint(wsEndpoint: string): Promise<TUniqueNetworks> {302    const api = new ApiPromise({provider: new WsProvider(wsEndpoint)});303    await api.isReady;304305    const network = await this.detectNetwork(api);306307    await api.disconnect();308309    return network;310  }311312  static async createConnection(wsEndpoint: string, listeners?: IApiListeners, network?: TUniqueNetworks | null): Promise<{313    api: ApiPromise;314    network: TUniqueNetworks;315  }> {316    if(typeof network === 'undefined' || network === null) network = 'opal';317    const supportedRPC = {318      opal: {319        unique: require('@unique-nft/opal-testnet-types/definitions').unique.rpc,320      },321      quartz: {322        unique: require('@unique-nft/quartz-mainnet-types/definitions').unique.rpc,323      },324      unique: {325        unique: require('@unique-nft/unique-mainnet-types/definitions').unique.rpc,326      },327    };328    if(!supportedRPC.hasOwnProperty(network)) network = await this.detectNetworkByWsEndpoint(wsEndpoint);329    const rpc = supportedRPC[network];330331    // TODO: investigate how to replace rpc in runtime332    // api._rpcCore.addUserInterfaces(rpc);333334    const api = new ApiPromise({provider: new WsProvider(wsEndpoint), rpc});335336    await api.isReadyOrError;337338    if (typeof listeners === 'undefined') listeners = {};339    for (const event of ['connected', 'disconnected', 'error', 'ready', 'decorated']) {340      if (!listeners.hasOwnProperty(event) || typeof listeners[event as TApiAllowedListeners] === 'undefined') continue;341      api.on(event as ApiInterfaceEvents, listeners[event as TApiAllowedListeners] as (...args: any[]) => any);342    }343344    return {api, network};345  }346347  getTransactionStatus(data: {events: {event: IEvent}[], status: any}) {348    const {events, status} = data;349    if (status.isReady) {350      return this.transactionStatus.NOT_READY;351    }352    if (status.isBroadcast) {353      return this.transactionStatus.NOT_READY;354    }355    if (status.isInBlock || status.isFinalized) {356      const errors = events.filter(e => e.event.method === 'ExtrinsicFailed');357      if (errors.length > 0) {358        return this.transactionStatus.FAIL;359      }360      if (events.filter(e => e.event.method === 'ExtrinsicSuccess').length > 0) {361        return this.transactionStatus.SUCCESS;362      }363    }364365    return this.transactionStatus.FAIL;366  }367368  signTransaction(sender: TSigner, transaction: any, options: Partial<SignerOptions> | null = null, label = 'transaction') {369    const sign = (callback: any) => {370      if(options !== null) return transaction.signAndSend(sender, options, callback);371      return transaction.signAndSend(sender, callback);372    };373    // eslint-disable-next-line no-async-promise-executor374    return new Promise(async (resolve, reject) => {375      try {376        const unsub = await sign((result: any) => {377          const status = this.getTransactionStatus(result);378379          if (status === this.transactionStatus.SUCCESS) {380            this.logger.log(`${label} successful`);381            unsub();382            resolve({result, status});383          } else if (status === this.transactionStatus.FAIL) {384            let moduleError = null;385386            if (result.hasOwnProperty('dispatchError')) {387              const dispatchError = result['dispatchError'];388389              if (dispatchError) {390                if (dispatchError.isModule) {391                  const modErr = dispatchError.asModule;392                  const errorMeta = dispatchError.registry.findMetaError(modErr);393394                  moduleError = `${errorMeta.section}.${errorMeta.name}`;395                } else {396                  moduleError = dispatchError.toHuman();397                }398              } else {399                this.logger.log(result, this.logger.level.ERROR);400              }401            }402403            this.logger.log(`Something went wrong with ${label}. Status: ${status}`, this.logger.level.ERROR);404            unsub();405            reject({status, moduleError, result});406          }407        });408      } catch (e) {409        this.logger.log(e, this.logger.level.ERROR);410        reject(e);411      }412    });413  }414415  constructApiCall(apiCall: string, params: any[]) {416    if(!apiCall.startsWith('api.')) throw Error(`Invalid api call: ${apiCall}`);417    let call = this.api as any;418    for(const part of apiCall.slice(4).split('.')) {419      call = call[part];420    }421    return call(...params);422  }423424  async executeExtrinsic(sender: TSigner, extrinsic: string, params: any[], expectSuccess=true, options: Partial<SignerOptions>|null = null/*, failureMessage='expected success'*/) {425    if(this.api === null) throw Error('API not initialized');426    if(!extrinsic.startsWith('api.tx.')) throw Error(`${extrinsic} is not transaction`);427428    const startTime = (new Date()).getTime();429    let result: ITransactionResult;430    let events: IEvent[] = [];431    try {432      result = await this.signTransaction(sender, this.constructApiCall(extrinsic, params), options, extrinsic) as ITransactionResult;433      events = this.eventHelper.extractEvents(result);434    }435    catch(e) {436      if(!(e as object).hasOwnProperty('status')) throw e;437      result = e as ITransactionResult;438    }439440    const endTime = (new Date()).getTime();441442    const log = {443      executedAt: endTime,444      executionTime: endTime - startTime,445      type: this.chainLogType.EXTRINSIC,446      status: result.status,447      call: extrinsic,448      signer: this.getSignerAddress(sender),449      params,450    } as IUniqueHelperLog;451452    if(result.status !== this.transactionStatus.SUCCESS && result.moduleError) log.moduleError = result.moduleError;453    if(events.length > 0) log.events = events;454455    this.chainLog.push(log);456457    if(expectSuccess && result.status !== this.transactionStatus.SUCCESS) throw Error(`${result.moduleError}`);458    return result;459  }460461  async callRpc(rpc: string, params?: any[]) {462    if(typeof params === 'undefined') params = [];463    if(this.api === null) throw Error('API not initialized');464    if(!rpc.startsWith('api.rpc.') && !rpc.startsWith('api.query.')) throw Error(`${rpc} is not RPC call`);465466    const startTime = (new Date()).getTime();467    let result;468    let error = null;469    const log = {470      type: this.chainLogType.RPC,471      call: rpc,472      params,473    } as IUniqueHelperLog;474475    try {476      result = await this.constructApiCall(rpc, params);477    }478    catch(e) {479      error = e;480    }481482    const endTime = (new Date()).getTime();483484    log.executedAt = endTime;485    log.status = (error === null ? this.transactionStatus.SUCCESS : this.transactionStatus.FAIL) as 'Fail' | 'Success';486    log.executionTime = endTime - startTime;487488    this.chainLog.push(log);489490    if(error !== null) throw error;491492    return result;493  }494495  getSignerAddress(signer: IKeyringPair | string): string {496    if(typeof signer === 'string') return signer;497    return signer.address;498  }499500  fetchAllPalletNames(): string[] {501    if(this.api === null) throw Error('API not initialized');502    return this.api.runtimeMetadata.asLatest.pallets.map(m => m.name.toString().toLowerCase());503  }504505  fetchMissingPalletNames(requiredPallets: string[]): string[] {506    const palletNames = this.fetchAllPalletNames();507    return requiredPallets.filter(p => !palletNames.includes(p));508  }509}510511512class HelperGroup {513  helper: UniqueHelper;514515  constructor(uniqueHelper: UniqueHelper) {516    this.helper = uniqueHelper;517  }518}519520521class CollectionGroup extends HelperGroup {522  /**523 * Get number of blocks when sponsored transaction is available.524 *525 * @param collectionId ID of collection526 * @param tokenId ID of token527 * @param addressObj address for which the sponsorship is checked528 * @example await getTokenNextSponsored(1, 2, {Substrate: '5DfhbVfww7ThF8q6f3...'});529 * @returns number of blocks or null if sponsorship hasn't been set530 */531  async getTokenNextSponsored(collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<number | null> {532    return (await this.helper.callRpc('api.rpc.unique.nextSponsored', [collectionId, addressObj, tokenId])).toJSON();533  }534535  /**536   * Get the number of created collections.537   *538   * @returns number of created collections539   */540  async getTotalCount(): Promise<number> {541    return (await this.helper.callRpc('api.rpc.unique.collectionStats')).created.toNumber();542  }543544  /**545   * Get information about the collection with additional data,546   * including the number of tokens it contains, its administrators,547   * the normalized address of the collection's owner, and decoded name and description.548   *549   * @param collectionId ID of collection550   * @example await getData(2)551   * @returns collection information object552   */553  async getData(collectionId: number): Promise<{554    id: number;555    name: string;556    description: string;557    tokensCount: number;558    admins: ICrossAccountId[];559    normalizedOwner: TSubstrateAccount;560    raw: any561  } | null> {562    const collection = await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId]);563    const humanCollection = collection.toHuman(), collectionData = {564      id: collectionId, name: null, description: null, tokensCount: 0, admins: [],565      raw: humanCollection,566    } as any, jsonCollection = collection.toJSON();567    if (humanCollection === null) return null;568    collectionData.raw.limits = jsonCollection.limits;569    collectionData.raw.permissions = jsonCollection.permissions;570    collectionData.normalizedOwner = this.helper.address.normalizeSubstrate(collectionData.raw.owner);571    for (const key of ['name', 'description']) {572      collectionData[key] = this.helper.util.vec2str(humanCollection[key]);573    }574575    collectionData.tokensCount = (['RFT', 'NFT'].includes(humanCollection.mode))576      ? await this.helper[humanCollection.mode.toLocaleLowerCase() as 'nft' | 'rft'].getLastTokenId(collectionId)577      : 0;578    collectionData.admins = await this.getAdmins(collectionId);579580    return collectionData;581  }582583  /**584   * Get the addresses of the collection's administrators, optionally normalized.585   *586   * @param collectionId ID of collection587   * @param normalize whether to normalize the addresses to the default ss58 format588   * @example await getAdmins(1)589   * @returns array of administrators590   */591  async getAdmins(collectionId: number, normalize = false): Promise<ICrossAccountId[]> {592    const admins = (await this.helper.callRpc('api.rpc.unique.adminlist', [collectionId])).toHuman();593594    return normalize595      ? admins.map((address: any) => {596        return address.Substrate597          ? {Substrate: this.helper.address.normalizeSubstrate(address.Substrate)}598          : address;599      })600      : admins;601  }602603  /**604   * Get the addresses added to the collection allow-list, optionally normalized.605   * @param collectionId ID of collection606   * @param normalize whether to normalize the addresses to the default ss58 format607   * @example await getAllowList(1)608   * @returns array of allow-listed addresses609   */610  async getAllowList(collectionId: number, normalize = false): Promise<ICrossAccountId[]> {611    const allowListed = (await this.helper.callRpc('api.rpc.unique.allowlist', [collectionId])).toHuman();612    return normalize613      ? allowListed.map((address: any) => {614        return address.Substrate615          ? {Substrate: this.helper.address.normalizeSubstrate(address.Substrate)}616          : address;617      })618      : allowListed;619  }620621  /**622   * Get the effective limits of the collection instead of null for default values623   *624   * @param collectionId ID of collection625   * @example await getEffectiveLimits(2)626   * @returns object of collection limits627   */628  async getEffectiveLimits(collectionId: number): Promise<ICollectionLimits> {629    return (await this.helper.callRpc('api.rpc.unique.effectiveCollectionLimits', [collectionId])).toJSON();630  }631632  /**633   * Burns the collection if the signer has sufficient permissions and collection is empty.634   *635   * @param signer keyring of signer636   * @param collectionId ID of collection637   * @example await helper.collection.burn(aliceKeyring, 3);638   * @returns ```true``` if extrinsic success, otherwise ```false```639   */640  async burn(signer: TSigner, collectionId: number): Promise<boolean> {641    const result = await this.helper.executeExtrinsic(642      signer,643      'api.tx.unique.destroyCollection', [collectionId],644      true,645    );646647    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionDestroyed');648  }649650  /**651   * Sets the sponsor for the collection (Requires the Substrate address). Needs confirmation by the sponsor.652   *653   * @param signer keyring of signer654   * @param collectionId ID of collection655   * @param sponsorAddress Sponsor substrate address656   * @example setSponsor(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...")657   * @returns ```true``` if extrinsic success, otherwise ```false```658   */659  async setSponsor(signer: TSigner, collectionId: number, sponsorAddress: TSubstrateAccount): Promise<boolean> {660    const result = await this.helper.executeExtrinsic(661      signer,662      'api.tx.unique.setCollectionSponsor', [collectionId, sponsorAddress],663      true,664    );665666    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionSponsorSet');667  }668669  /**670   * Confirms consent to sponsor the collection on behalf of the signer.671   *672   * @param signer keyring of signer673   * @param collectionId ID of collection674   * @example confirmSponsorship(aliceKeyring, 10)675   * @returns ```true``` if extrinsic success, otherwise ```false```676   */677  async confirmSponsorship(signer: TSigner, collectionId: number): Promise<boolean> {678    const result = await this.helper.executeExtrinsic(679      signer,680      'api.tx.unique.confirmSponsorship', [collectionId],681      true,682    );683684    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'SponsorshipConfirmed');685  }686687  /**688   * Removes the sponsor of a collection, regardless if it consented or not.689   *690   * @param signer keyring of signer691   * @param collectionId ID of collection692   * @example removeSponsor(aliceKeyring, 10)693   * @returns ```true``` if extrinsic success, otherwise ```false```694   */695  async removeSponsor(signer: TSigner, collectionId: number): Promise<boolean> {696    const result = await this.helper.executeExtrinsic(697      signer,698      'api.tx.unique.removeCollectionSponsor', [collectionId],699      true,700    );701702    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionSponsorRemoved');703  }704705  /**706   * Sets the limits of the collection. At least one limit must be specified for a correct call.707   *708   * @param signer keyring of signer709   * @param collectionId ID of collection710   * @param limits collection limits object711   * @example712   * await setLimits(713   *   aliceKeyring,714   *   10,715   *   {716   *     sponsorTransferTimeout: 0,717   *     ownerCanDestroy: false718   *   }719   * )720   * @returns ```true``` if extrinsic success, otherwise ```false```721   */722  async setLimits(signer: TSigner, collectionId: number, limits: ICollectionLimits): Promise<boolean> {723    const result = await this.helper.executeExtrinsic(724      signer,725      'api.tx.unique.setCollectionLimits', [collectionId, limits],726      true,727    );728729    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionLimitSet');730  }731732  /**733   * Changes the owner of the collection to the new Substrate address.734   *735   * @param signer keyring of signer736   * @param collectionId ID of collection737   * @param ownerAddress substrate address of new owner738   * @example changeOwner(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...")739   * @returns ```true``` if extrinsic success, otherwise ```false```740   */741  async changeOwner(signer: TSigner, collectionId: number, ownerAddress: TSubstrateAccount): Promise<boolean> {742    const result = await this.helper.executeExtrinsic(743      signer,744      'api.tx.unique.changeCollectionOwner', [collectionId, ownerAddress],745      true,746    );747748    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionOwnedChanged');749  }750751  /**752   * Adds a collection administrator.753   *754   * @param signer keyring of signer755   * @param collectionId ID of collection756   * @param adminAddressObj Administrator address (substrate or ethereum)757   * @example addAdmin(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."})758   * @returns ```true``` if extrinsic success, otherwise ```false```759   */760  async addAdmin(signer: TSigner, collectionId: number, adminAddressObj: ICrossAccountId): Promise<boolean> {761    const result = await this.helper.executeExtrinsic(762      signer,763      'api.tx.unique.addCollectionAdmin', [collectionId, adminAddressObj],764      true,765    );766767    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionAdminAdded');768  }769770  /**771   * Removes a collection administrator.772   *773   * @param signer keyring of signer774   * @param collectionId ID of collection775   * @param adminAddressObj Administrator address (substrate or ethereum)776   * @example removeAdmin(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."})777   * @returns ```true``` if extrinsic success, otherwise ```false```778   */779  async removeAdmin(signer: TSigner, collectionId: number, adminAddressObj: ICrossAccountId): Promise<boolean> {780    const result = await this.helper.executeExtrinsic(781      signer,782      'api.tx.unique.removeCollectionAdmin', [collectionId, adminAddressObj],783      true,784    );785786    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionAdminRemoved');787  }788789  /**790   * Check if user is in allow list.791   * 792   * @param collectionId ID of collection793   * @param user Account to check794   * @example await getAdmins(1)795   * @returns is user in allow list796   */797  async allowed(collectionId: number, user: ICrossAccountId): Promise<boolean> {798    return (await this.helper.callRpc('api.rpc.unique.allowed', [collectionId, user])).toJSON();799  }800801  /**802   * Adds an address to allow list803   * @param signer keyring of signer804   * @param collectionId ID of collection805   * @param addressObj address to add to the allow list806   * @returns ```true``` if extrinsic success, otherwise ```false```807   */808  async addToAllowList(signer: TSigner, collectionId: number, addressObj: ICrossAccountId): Promise<boolean> {809    const result = await this.helper.executeExtrinsic(810      signer,811      'api.tx.unique.addToAllowList', [collectionId, addressObj],812      true,813    );814815    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'AllowListAddressAdded');816  }817818  /**819   * Removes an address from allow list820   *821   * @param signer keyring of signer822   * @param collectionId ID of collection823   * @param addressObj address to remove from the allow list824   * @returns ```true``` if extrinsic success, otherwise ```false```825   */826  async removeFromAllowList(signer: TSigner, collectionId: number, addressObj: ICrossAccountId): Promise<boolean> {827    const result = await this.helper.executeExtrinsic(828      signer,829      'api.tx.unique.removeFromAllowList', [collectionId, addressObj],830      true,831    );832833    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'AllowListAddressRemoved');834  }835836  /**837   * Sets onchain permissions for selected collection.838   *839   * @param signer keyring of signer840   * @param collectionId ID of collection841   * @param permissions collection permissions object842   * @example setPermissions(aliceKeyring, 10, {access:'AllowList', mintMode: true, nesting: {collectionAdmin: true, tokenOwner: true}});843   * @returns ```true``` if extrinsic success, otherwise ```false```844   */845  async setPermissions(signer: TSigner, collectionId: number, permissions: ICollectionPermissions): Promise<boolean> {846    const result = await this.helper.executeExtrinsic(847      signer,848      'api.tx.unique.setCollectionPermissions', [collectionId, permissions],849      true,850    );851852    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionPermissionSet');853  }854855  /**856   * Enables nesting for selected collection. If `restricted` set, you can nest only tokens from specified collections.857   *858   * @param signer keyring of signer859   * @param collectionId ID of collection860   * @param permissions nesting permissions object861   * @example enableNesting(aliceKeyring, 10, {collectionAdmin: true, tokenOwner: true});862   * @returns ```true``` if extrinsic success, otherwise ```false```863   */864  async enableNesting(signer: TSigner, collectionId: number, permissions: INestingPermissions): Promise<boolean> {865    return await this.setPermissions(signer, collectionId, {nesting: permissions});866  }867868  /**869   * Disables nesting for selected collection.870   *871   * @param signer keyring of signer872   * @param collectionId ID of collection873   * @example disableNesting(aliceKeyring, 10);874   * @returns ```true``` if extrinsic success, otherwise ```false```875   */876  async disableNesting(signer: TSigner, collectionId: number): Promise<boolean> {877    return await this.setPermissions(signer, collectionId, {nesting: {tokenOwner: false, collectionAdmin: false}});878  }879880  /**881   * Sets onchain properties to the collection.882   *883   * @param signer keyring of signer884   * @param collectionId ID of collection885   * @param properties array of property objects886   * @example setProperties(aliceKeyring, 10, [{key: "gender", value: "male"}]);887   * @returns ```true``` if extrinsic success, otherwise ```false```888   */889  async setProperties(signer: TSigner, collectionId: number, properties: IProperty[]): Promise<boolean> {890    const result = await this.helper.executeExtrinsic(891      signer,892      'api.tx.unique.setCollectionProperties', [collectionId, properties],893      true,894    );895896    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPropertySet');897  }898899  /**900   * Deletes onchain properties from the collection.901   *902   * @param signer keyring of signer903   * @param collectionId ID of collection904   * @param propertyKeys array of property keys to delete905   * @example deleteProperties(aliceKeyring, 10, ["gender", "age"]);906   * @returns ```true``` if extrinsic success, otherwise ```false```907   */908  async deleteProperties(signer: TSigner, collectionId: number, propertyKeys: string[]): Promise<boolean> {909    const result = await this.helper.executeExtrinsic(910      signer,911      'api.tx.unique.deleteCollectionProperties', [collectionId, propertyKeys],912      true,913    );914915    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPropertyDeleted');916  }917918  /**919   * Changes the owner of the token.920   *921   * @param signer keyring of signer922   * @param collectionId ID of collection923   * @param tokenId ID of token924   * @param addressObj address of a new owner925   * @param amount amount of tokens to be transfered. For NFT must be set to 1n926   * @example transferToken(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."})927   * @returns true if the token success, otherwise false928   */929  async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId, amount=1n): Promise<boolean> {930    const result = await this.helper.executeExtrinsic(931      signer,932      'api.tx.unique.transfer', [addressObj, collectionId, tokenId, amount],933      true, // `Unable to transfer token #${tokenId} from collection #${collectionId}`,934    );935936    return this.helper.util.isTokenTransferSuccess(result.result.events, collectionId, tokenId, {Substrate: typeof signer === 'string' ? signer : signer.address}, addressObj, amount);937  }938939  /**940   *941   * Change ownership of a token(s) on behalf of the owner.942   *943   * @param signer keyring of signer944   * @param collectionId ID of collection945   * @param tokenId ID of token946   * @param fromAddressObj address on behalf of which the token will be sent947   * @param toAddressObj new token owner948   * @param amount amount of tokens to be transfered. For NFT must be set to 1n949   * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg"}, {Ethereum: "0x9F0583DbB85..."})950   * @returns true if the token success, otherwise false951   */952  async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {953    const result = await this.helper.executeExtrinsic(954      signer,955      'api.tx.unique.transferFrom', [fromAddressObj, toAddressObj, collectionId, tokenId, amount],956      true, // `Unable to transfer token #${tokenId} from collection #${collectionId}`,957    );958    return this.helper.util.isTokenTransferSuccess(result.result.events, collectionId, tokenId, fromAddressObj, toAddressObj, amount);959  }960961  /**962   *963   * Destroys a concrete instance of NFT/RFT or burns a specified amount of fungible tokens.964   *965   * @param signer keyring of signer966   * @param collectionId ID of collection967   * @param tokenId ID of token968   * @param amount amount of tokens to be burned. For NFT must be set to 1n969   * @example burnToken(aliceKeyring, 10, 5);970   * @returns ```true``` and burnt token number is extrinsic success. Otherwise ```false``` and ```null```971   */972  async burnToken(signer: TSigner, collectionId: number, tokenId: number, amount=1n): Promise<{973    success: boolean,974    token: number | null975  }> {976    const burnResult = await this.helper.executeExtrinsic(977      signer,978      'api.tx.unique.burnItem', [collectionId, tokenId, amount],979      true, // `Unable to burn token for ${label}`,980    );981    const burnedTokens = this.helper.util.extractTokensFromBurnResult(burnResult);982    if (burnedTokens.tokens.length > 1) throw Error('Burned multiple tokens');983    return {success: burnedTokens.success, token: burnedTokens.tokens.length > 0 ? burnedTokens.tokens[0] : null};984  }985986  /**987   * Destroys a concrete instance of NFT on behalf of the owner988   *989   * @param signer keyring of signer990   * @param collectionId ID of collection991   * @param fromAddressObj address on behalf of which the token will be burnt992   * @param tokenId ID of token993   * @param amount amount of tokens to be burned. For NFT must be set to 1n994   * @example burnTokenFrom(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."}, 5, {Ethereum: "0x9F0583DbB85..."})995   * @returns ```true``` if extrinsic success, otherwise ```false```996   */997  async burnTokenFrom(signer: TSigner, collectionId: number, fromAddressObj: ICrossAccountId, tokenId: number, amount=1n): Promise<boolean> {998    const burnResult = await this.helper.executeExtrinsic(999      signer,1000      'api.tx.unique.burnFrom', [collectionId, fromAddressObj, tokenId, amount],1001      true, // `Unable to burn token from for ${label}`,1002    );1003    const burnedTokens = this.helper.util.extractTokensFromBurnResult(burnResult);1004    return burnedTokens.success && burnedTokens.tokens.length > 0;1005  }10061007  /**1008   * Set, change, or remove approved address to transfer the ownership of the NFT.1009   *1010   * @param signer keyring of signer1011   * @param collectionId ID of collection1012   * @param tokenId ID of token1013   * @param toAddressObj Substrate or Ethereum address which gets approved use of the signer's tokens1014   * @param amount amount of token to be approved. For NFT must be set to 1n1015   * @returns ```true``` if extrinsic success, otherwise ```false```1016   */1017  async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {1018    const approveResult = await this.helper.executeExtrinsic(1019      signer,1020      'api.tx.unique.approve', [toAddressObj, collectionId, tokenId, amount],1021      true, // `Unable to approve token for ${label}`,1022    );10231024    return this.helper.util.findCollectionInEvents(approveResult.result.events, collectionId, 'common', 'Approved');1025  }10261027  /**1028   * Get the amount of token pieces approved to transfer or burn. Normally 0.1029   *1030   * @param collectionId ID of collection1031   * @param tokenId ID of token1032   * @param toAccountObj address which is approved to use token pieces1033   * @param fromAccountObj address which may have allowed the use of its owned tokens1034   * @example getTokenApprovedPieces(10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, {Substrate: "5ERZNF88Mm7UGfPP3mdG..."})1035   * @returns number of approved to transfer pieces1036   */1037  async getTokenApprovedPieces(collectionId: number, tokenId: number, toAccountObj: ICrossAccountId, fromAccountObj: ICrossAccountId): Promise<bigint> {1038    return (await this.helper.callRpc('api.rpc.unique.allowance', [collectionId, fromAccountObj, toAccountObj, tokenId])).toBigInt();1039  }10401041  /**1042   * Get the last created token ID in a collection1043   *1044   * @param collectionId ID of collection1045   * @example getLastTokenId(10);1046   * @returns id of the last created token1047   */1048  async getLastTokenId(collectionId: number): Promise<number> {1049    return (await this.helper.callRpc('api.rpc.unique.lastTokenId', [collectionId])).toNumber();1050  }10511052  /**1053   * Check if token exists1054   *1055   * @param collectionId ID of collection1056   * @param tokenId ID of token1057   * @example isTokenExists(10, 20);1058   * @returns true if the token exists, otherwise false1059   */1060  async isTokenExists(collectionId: number, tokenId: number): Promise<boolean> {1061    return (await this.helper.callRpc('api.rpc.unique.tokenExists', [collectionId, tokenId])).toJSON();1062  }1063}10641065class NFTnRFT extends CollectionGroup {1066  /**1067   * Get tokens owned by account1068   *1069   * @param collectionId ID of collection1070   * @param addressObj tokens owner1071   * @example getTokensByAddress(10, {Substrate: "5DyN4Y92vZCjv38fg..."})1072   * @returns array of token ids owned by account1073   */1074  async getTokensByAddress(collectionId: number, addressObj: ICrossAccountId): Promise<number[]> {1075    return (await this.helper.callRpc('api.rpc.unique.accountTokens', [collectionId, addressObj])).toJSON();1076  }10771078  /**1079   * Get token data1080   *1081   * @param collectionId ID of collection1082   * @param tokenId ID of token1083   * @param propertyKeys optionally filter the token properties to only these keys1084   * @param blockHashAt optionally query the data at some block with this hash1085   * @example getToken(10, 5);1086   * @returns human readable token data1087   */1088  async getToken(collectionId: number, tokenId: number, propertyKeys: string[] = [], blockHashAt?: string): Promise<{1089    properties: IProperty[];1090    owner: ICrossAccountId;1091    normalizedOwner: ICrossAccountId;1092  }| null> {1093    let tokenData;1094    if(typeof blockHashAt === 'undefined') {1095      tokenData = await this.helper.callRpc('api.rpc.unique.tokenData', [collectionId, tokenId]);1096    }1097    else {1098      if(propertyKeys.length == 0) {1099        const collection = (await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId])).toHuman();1100        if(!collection) return null;1101        propertyKeys = collection.tokenPropertyPermissions.map((x: ITokenPropertyPermission) => x.key);1102      }1103      tokenData = await this.helper.callRpc('api.rpc.unique.tokenData', [collectionId, tokenId, propertyKeys, blockHashAt]);1104    }1105    tokenData = tokenData.toHuman();1106    if (tokenData === null || tokenData.owner === null) return null;1107    const owner = {} as any;1108    for (const key of Object.keys(tokenData.owner)) {1109      owner[key.toLocaleLowerCase()] = key.toLocaleLowerCase() === 'substrate' ? this.helper.address.normalizeSubstrate(tokenData.owner[key]) : tokenData.owner[key];1110    }1111    tokenData.normalizedOwner = crossAccountIdFromLower(owner);1112    return tokenData;1113  }11141115  /**1116   * Set permissions to change token properties1117   *1118   * @param signer keyring of signer1119   * @param collectionId ID of collection1120   * @param permissions permissions to change a property by the collection owner or admin1121   * @example setTokenPropertyPermissions(1122   *   aliceKeyring, 10, [{key: "gender", permission: {tokenOwner: true, mutable: true, collectionAdmin: true}}]1123   * )1124   * @returns true if extrinsic success otherwise false1125   */1126  async setTokenPropertyPermissions(signer: TSigner, collectionId: number, permissions: ITokenPropertyPermission[]): Promise<boolean> {1127    const result = await this.helper.executeExtrinsic(1128      signer,1129      'api.tx.unique.setTokenPropertyPermissions', [collectionId, permissions],1130      true,1131    );11321133    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'PropertyPermissionSet');1134  }11351136  /**1137   * Set token properties1138   *1139   * @param signer keyring of signer1140   * @param collectionId ID of collection1141   * @param tokenId ID of token1142   * @param properties key-value pairs of metadata which to add to a token. Keys must be permitted in the collection1143   * @example setTokenProperties(aliceKeyring, 10, 5, [{key: "gender", value: "female"}, {key: "age", value: "23"}])1144   * @returns ```true``` if extrinsic success, otherwise ```false```1145   */1146  async setTokenProperties(signer: TSigner, collectionId: number, tokenId: number, properties: IProperty[]): Promise<boolean> {1147    const result = await this.helper.executeExtrinsic(1148      signer,1149      'api.tx.unique.setTokenProperties', [collectionId, tokenId, properties],1150      true,1151    );11521153    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'TokenPropertySet');1154  }11551156  /**1157   * Delete the provided properties of a token1158   * @param signer keyring of signer1159   * @param collectionId ID of collection1160   * @param tokenId ID of token1161   * @param propertyKeys property keys to be deleted1162   * @example deleteTokenProperties(aliceKeyring, 10, 5, ["gender", "age"])1163   * @returns ```true``` if extrinsic success, otherwise ```false```1164   */1165  async deleteTokenProperties(signer: TSigner, collectionId: number, tokenId: number, propertyKeys: string[]): Promise<boolean> {1166    const result = await this.helper.executeExtrinsic(1167      signer,1168      'api.tx.unique.deleteTokenProperties', [collectionId, tokenId, propertyKeys],1169      true,1170    );11711172    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'TokenPropertyDeleted');1173  }11741175  /**1176   * Mint new collection1177   *1178   * @param signer keyring of signer1179   * @param collectionOptions basic collection options and properties1180   * @param mode NFT or RFT type of a collection1181   * @example mintCollection(aliceKeyring, {name: 'New', description: "New collection", tokenPrefix: "NEW"}, "NFT")1182   * @returns object of the created collection1183   */1184  async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions, mode: 'NFT' | 'RFT'): Promise<UniqueCollectionBase> {1185    collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; // Clone object1186    collectionOptions.mode = (mode === 'NFT') ? {nft: null} : {refungible: null};1187    for (const key of ['name', 'description', 'tokenPrefix']) {1188      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);1189    }1190    const creationResult = await this.helper.executeExtrinsic(1191      signer,1192      'api.tx.unique.createCollectionEx', [collectionOptions],1193      true, // errorLabel,1194    );1195    return this.getCollectionObject(this.helper.util.extractCollectionIdFromCreationResult(creationResult));1196  }11971198  getCollectionObject(_collectionId: number): any {1199    return null;1200  }12011202  getTokenObject(_collectionId: number, _tokenId: number): any {1203    return null;1204  }1205}120612071208class NFTGroup extends NFTnRFT {1209  /**1210   * Get collection object1211   * @param collectionId ID of collection1212   * @example getCollectionObject(2);1213   * @returns instance of UniqueNFTCollection1214   */1215  getCollectionObject(collectionId: number): UniqueNFTCollection {1216    return new UniqueNFTCollection(collectionId, this.helper);1217  }12181219  /**1220   * Get token object1221   * @param collectionId ID of collection1222   * @param tokenId ID of token1223   * @example getTokenObject(10, 5);1224   * @returns instance of UniqueNFTToken1225   */1226  getTokenObject(collectionId: number, tokenId: number): UniqueNFTToken {1227    return new UniqueNFTToken(tokenId, this.getCollectionObject(collectionId));1228  }12291230  /**1231   * Get token's owner1232   * @param collectionId ID of collection1233   * @param tokenId ID of token1234   * @param blockHashAt optionally query the data at the block with this hash1235   * @example getTokenOwner(10, 5);1236   * @returns Address in CrossAccountId format, e.g. {Substrate: "5DnSF6RRjwteE3BrCj..."}1237   */1238  async getTokenOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<ICrossAccountId> {1239    let owner;1240    if (typeof blockHashAt === 'undefined') {1241      owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId]);1242    } else {1243      owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId, blockHashAt]);1244    }1245    return crossAccountIdFromLower(owner.toJSON());1246  }12471248  /**1249   * Is token approved to transfer1250   * @param collectionId ID of collection1251   * @param tokenId ID of token1252   * @param toAccountObj address to be approved1253   * @returns ```true``` if extrinsic success, otherwise ```false```1254   */1255  async isTokenApproved(collectionId: number, tokenId: number, toAccountObj: ICrossAccountId): Promise<boolean> {1256    return (await this.getTokenApprovedPieces(collectionId, tokenId, toAccountObj, await this.getTokenOwner(collectionId, tokenId))) === 1n;1257  }12581259  /**1260   * Changes the owner of the token.1261   *1262   * @param signer keyring of signer1263   * @param collectionId ID of collection1264   * @param tokenId ID of token1265   * @param addressObj address of a new owner1266   * @example transferToken(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."})1267   * @returns ```true``` if extrinsic success, otherwise ```false```1268   */1269  async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<boolean> {1270    return await super.transferToken(signer, collectionId, tokenId, addressObj, 1n);1271  }12721273  /**1274   *1275   * Change ownership of a NFT on behalf of the owner.1276   *1277   * @param signer keyring of signer1278   * @param collectionId ID of collection1279   * @param tokenId ID of token1280   * @param fromAddressObj address on behalf of which the token will be sent1281   * @param toAddressObj new token owner1282   * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, {Ethereum: "0x9F0583DbB85..."})1283   * @returns ```true``` if extrinsic success, otherwise ```false```1284   */1285  async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId): Promise<boolean> {1286    return await super.transferTokenFrom(signer, collectionId, tokenId, fromAddressObj, toAddressObj, 1n);1287  }12881289  /**1290   * Recursively find the address that owns the token1291   * @param collectionId ID of collection1292   * @param tokenId ID of token1293   * @param blockHashAt1294   * @example getTokenTopmostOwner(10, 5);1295   * @returns address in CrossAccountId format, e.g. {Substrate: "5DyN4Y92vZCjv38fg..."}1296   */1297  async getTokenTopmostOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<ICrossAccountId | null> {1298    let owner;1299    if (typeof blockHashAt === 'undefined') {1300      owner = await this.helper.callRpc('api.rpc.unique.topmostTokenOwner', [collectionId, tokenId]);1301    } else {1302      owner = await this.helper.callRpc('api.rpc.unique.topmostTokenOwner', [collectionId, tokenId, blockHashAt]);1303    }13041305    if (owner === null) return null;13061307    owner = owner.toHuman();13081309    return owner.Substrate ? {Substrate: this.helper.address.normalizeSubstrate(owner.Substrate)} : owner;1310  }13111312  /**1313   * Get tokens nested in the provided token1314   * @param collectionId ID of collection1315   * @param tokenId ID of token1316   * @param blockHashAt optionally query the data at the block with this hash1317   * @example getTokenChildren(10, 5);1318   * @returns tokens whose depth of nesting is <= 51319   */1320  async getTokenChildren(collectionId: number, tokenId: number, blockHashAt?: string): Promise<IToken[]> {1321    let children;1322    if(typeof blockHashAt === 'undefined') {1323      children = await this.helper.callRpc('api.rpc.unique.tokenChildren', [collectionId, tokenId]);1324    } else {1325      children = await this.helper.callRpc('api.rpc.unique.tokenChildren', [collectionId, tokenId, blockHashAt]);1326    }13271328    return children.toJSON().map((x: any) => {1329      return {collectionId: x.collection, tokenId: x.token};1330    });1331  }13321333  /**1334   * Nest one token into another1335   * @param signer keyring of signer1336   * @param tokenObj token to be nested1337   * @param rootTokenObj token to be parent1338   * @example nestToken(aliceKeyring, {collectionId: 10, tokenId: 5}, {collectionId: 10, tokenId: 4});1339   * @returns ```true``` if extrinsic success, otherwise ```false```1340   */1341  async nestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken): Promise<boolean> {1342    const rootTokenAddress = {Ethereum: this.helper.util.getNestingTokenAddress(rootTokenObj.collectionId, rootTokenObj.tokenId)};1343    const result = await this.transferToken(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress);1344    if(!result) {1345      throw Error('Unable to nest token!');1346    }1347    return result;1348  }13491350  /**1351   * Remove token from nested state1352   * @param signer keyring of signer1353   * @param tokenObj token to unnest1354   * @param rootTokenObj parent of a token1355   * @param toAddressObj address of a new token owner1356   * @example unnestToken(aliceKeyring, {collectionId: 10, tokenId: 5}, {collectionId: 10, tokenId: 4}, {Substrate: "5DyN4Y92vZCjv38fg..."});1357   * @returns ```true``` if extrinsic success, otherwise ```false```1358   */1359  async unnestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken, toAddressObj: ICrossAccountId): Promise<boolean> {1360    const rootTokenAddress = {Ethereum: this.helper.util.getNestingTokenAddress(rootTokenObj.collectionId, rootTokenObj.tokenId)};1361    const result = await this.transferTokenFrom(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress, toAddressObj);1362    if(!result) {1363      throw Error('Unable to unnest token!');1364    }1365    return result;1366  }13671368  /**1369   * Mint new collection1370   * @param signer keyring of signer1371   * @param collectionOptions Collection options1372   * @example1373   * mintCollection(aliceKeyring, {1374   *   name: 'New',1375   *   description: 'New collection',1376   *   tokenPrefix: 'NEW',1377   * })1378   * @returns object of the created collection1379   */1380  async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions): Promise<UniqueNFTCollection> {1381    return await super.mintCollection(signer, collectionOptions, 'NFT') as UniqueNFTCollection;1382  }13831384  /**1385   * Mint new token1386   * @param signer keyring of signer1387   * @param data token data1388   * @returns created token object1389   */1390  async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; properties?: IProperty[]; }): Promise<UniqueNFTToken> {1391    const creationResult = await this.helper.executeExtrinsic(1392      signer,1393      'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {1394        nft: {1395          properties: data.properties,1396        },1397      }],1398      true,1399    );1400    const createdTokens = this.helper.util.extractTokensFromCreationResult(creationResult);1401    if (createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');1402    if (createdTokens.tokens.length < 1) throw Error('No tokens minted');1403    return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);1404  }14051406  /**1407   * Mint multiple NFT tokens1408   * @param signer keyring of signer1409   * @param collectionId ID of collection1410   * @param tokens array of tokens with owner and properties1411   * @example1412   * mintMultipleTokens(aliceKeyring, 10, [{1413   *     owner: {Substrate: "5DyN4Y92vZCjv38fg..."},1414   *     properties: [{key: "gender", value: "male"},{key: "age", value: "45"}],1415   *   },{1416   *     owner: {Ethereum: "0x9F0583DbB855d..."},1417   *     properties: [{key: "gender", value: "female"},{key: "age", value: "22"}],1418   * }]);1419   * @returns ```true``` if extrinsic success, otherwise ```false```1420   */1421  async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: {owner: ICrossAccountId, properties?: IProperty[]}[]): Promise<UniqueNFTToken[]> {1422    const creationResult = await this.helper.executeExtrinsic(1423      signer,1424      'api.tx.unique.createMultipleItemsEx', [collectionId, {NFT: tokens}],1425      true,1426    );1427    const collection = this.getCollectionObject(collectionId);1428    return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1429  }14301431  /**1432   * Mint multiple NFT tokens with one owner1433   * @param signer keyring of signer1434   * @param collectionId ID of collection1435   * @param owner tokens owner1436   * @param tokens array of tokens with owner and properties1437   * @example1438   * mintMultipleTokensWithOneOwner(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...", [{1439   *   properties: [{1440   *   key: "gender",1441   *   value: "female",1442   *  },{1443   *   key: "age",1444   *   value: "33",1445   *  }],1446   * }]);1447   * @returns array of newly created tokens1448   */1449  async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {properties?: IProperty[]}[]): Promise<UniqueNFTToken[]> {1450    const rawTokens = [];1451    for (const token of tokens) {1452      const raw = {NFT: {properties: token.properties}};1453      rawTokens.push(raw);1454    }1455    const creationResult = await this.helper.executeExtrinsic(1456      signer,1457      'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1458      true,1459    );1460    const collection = this.getCollectionObject(collectionId);1461    return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1462  }14631464  /**1465   * Set, change, or remove approved address to transfer the ownership of the NFT.1466   *1467   * @param signer keyring of signer1468   * @param collectionId ID of collection1469   * @param tokenId ID of token1470   * @param toAddressObj address to approve1471   * @example approveToken(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."})1472   * @returns ```true``` if extrinsic success, otherwise ```false```1473   */1474  async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId) {1475    return super.approveToken(signer, collectionId, tokenId, toAddressObj, 1n);1476  }1477}147814791480class RFTGroup extends NFTnRFT {1481  /**1482   * Get collection object1483   * @param collectionId ID of collection1484   * @example getCollectionObject(2);1485   * @returns instance of UniqueRFTCollection1486   */1487  getCollectionObject(collectionId: number): UniqueRFTCollection {1488    return new UniqueRFTCollection(collectionId, this.helper);1489  }14901491  /**1492   * Get token object1493   * @param collectionId ID of collection1494   * @param tokenId ID of token1495   * @example getTokenObject(10, 5);1496   * @returns instance of UniqueNFTToken1497   */1498  getTokenObject(collectionId: number, tokenId: number): UniqueRFTToken {1499    return new UniqueRFTToken(tokenId, this.getCollectionObject(collectionId));1500  }15011502  /**1503   * Get top 10 token owners with the largest number of pieces1504   * @param collectionId ID of collection1505   * @param tokenId ID of token1506   * @example getTokenTop10Owners(10, 5);1507   * @returns array of top 10 owners1508   */1509  async getTokenTop10Owners(collectionId: number, tokenId: number): Promise<ICrossAccountId[]> {1510    return (await this.helper.callRpc('api.rpc.unique.tokenOwners', [collectionId, tokenId])).toJSON().map(crossAccountIdFromLower);1511  }15121513  /**1514   * Get number of pieces owned by address1515   * @param collectionId ID of collection1516   * @param tokenId ID of token1517   * @param addressObj address token owner1518   * @example getTokenBalance(10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."});1519   * @returns number of pieces ownerd by address1520   */1521  async getTokenBalance(collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<bigint> {1522    return (await this.helper.callRpc('api.rpc.unique.balance', [collectionId, addressObj, tokenId])).toBigInt();1523  }15241525  /**1526   * Transfer pieces of token to another address1527   * @param signer keyring of signer1528   * @param collectionId ID of collection1529   * @param tokenId ID of token1530   * @param addressObj address of a new owner1531   * @param amount number of pieces to be transfered1532   * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, 2000n)1533   * @returns ```true``` if extrinsic success, otherwise ```false```1534   */1535  async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId, amount=1n): Promise<boolean> {1536    return await super.transferToken(signer, collectionId, tokenId, addressObj, amount);1537  }15381539  /**1540   * Change ownership of some pieces of RFT on behalf of the owner.1541   * @param signer keyring of signer1542   * @param collectionId ID of collection1543   * @param tokenId ID of token1544   * @param fromAddressObj address on behalf of which the token will be sent1545   * @param toAddressObj new token owner1546   * @param amount number of pieces to be transfered1547   * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, {Substrate: "5DfhbVfww7ThF8q6f3i..."}, 2000n)1548   * @returns ```true``` if extrinsic success, otherwise ```false```1549   */1550  async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1551    return await super.transferTokenFrom(signer, collectionId, tokenId, fromAddressObj, toAddressObj, amount);1552  }15531554  /**1555   * Mint new collection1556   * @param signer keyring of signer1557   * @param collectionOptions Collection options1558   * @example1559   * mintCollection(aliceKeyring, {1560   *   name: 'New',1561   *   description: 'New collection',1562   *   tokenPrefix: 'NEW',1563   * })1564   * @returns object of the created collection1565   */1566  async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions): Promise<UniqueRFTCollection> {1567    return await super.mintCollection(signer, collectionOptions, 'RFT') as UniqueRFTCollection;1568  }15691570  /**1571   * Mint new token1572   * @param signer keyring of signer1573   * @param data token data1574   * @example mintToken(aliceKeyring, {collectionId: 10, owner: {Substrate: '5GHoZe9c73RYbVzq...'}, pieces: 10000n});1575   * @returns created token object1576   */1577  async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; pieces: bigint; properties?: IProperty[]; }): Promise<UniqueRFTToken> {1578    const creationResult = await this.helper.executeExtrinsic(1579      signer,1580      'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {1581        refungible: {1582          pieces: data.pieces,1583          properties: data.properties,1584        },1585      }],1586      true,1587    );1588    const createdTokens = this.helper.util.extractTokensFromCreationResult(creationResult);1589    if (createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');1590    if (createdTokens.tokens.length < 1) throw Error('No tokens minted');1591    return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);1592  }15931594  async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: {owner: ICrossAccountId, pieces: bigint, properties?: IProperty[]}[]): Promise<UniqueRFTToken[]> {1595    throw Error('Not implemented');1596    const creationResult = await this.helper.executeExtrinsic(1597      signer,1598      'api.tx.unique.createMultipleItemsEx', [collectionId, {RefungibleMultipleOwners: tokens}],1599      true, // `Unable to mint RFT tokens for ${label}`,1600    );1601    const collection = this.getCollectionObject(collectionId);1602    return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1603  }16041605  /**1606   * Mint multiple RFT tokens with one owner1607   * @param signer keyring of signer1608   * @param collectionId ID of collection1609   * @param owner tokens owner1610   * @param tokens array of tokens with properties and pieces1611   * @example mintMultipleTokensWithOneOwner(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, [{pieces: 100000n, properties: [{key: "gender", value: "male"}]}]);1612   * @returns array of newly created RFT tokens1613   */1614  async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {pieces: bigint, properties?: IProperty[]}[]): Promise<UniqueRFTToken[]> {1615    const rawTokens = [];1616    for (const token of tokens) {1617      const raw = {ReFungible: {pieces: token.pieces, properties: token.properties}};1618      rawTokens.push(raw);1619    }1620    const creationResult = await this.helper.executeExtrinsic(1621      signer,1622      'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1623      true,1624    );1625    const collection = this.getCollectionObject(collectionId);1626    return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1627  }16281629  /**1630   * Destroys a concrete instance of RFT.1631   * @param signer keyring of signer1632   * @param collectionId ID of collection1633   * @param tokenId ID of token1634   * @param amount number of pieces to be burnt1635   * @example burnToken(aliceKeyring, 10, 5);1636   * @returns ```true``` and burnt token number is extrinsic success. Otherwise ```false``` and ```null```1637   */1638  async burnToken(signer: IKeyringPair, collectionId: number, tokenId: number, amount=1n): Promise<{ success: boolean; token: number | null; }> {1639    return await super.burnToken(signer, collectionId, tokenId, amount);1640  }16411642  /**1643   * Set, change, or remove approved address to transfer the ownership of the RFT.1644   *1645   * @param signer keyring of signer1646   * @param collectionId ID of collection1647   * @param tokenId ID of token1648   * @param toAddressObj address to approve1649   * @param amount number of pieces to be approved1650   * @example approveToken(aliceKeyring, 10, 5, {Substrate: "5GHoZe9c73RYbVzq..."}, "", 10000n);1651   * @returns true if the token success, otherwise false1652   */1653  async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {1654    return super.approveToken(signer, collectionId, tokenId, toAddressObj, amount);1655  }16561657  /**1658   * Get total number of pieces1659   * @param collectionId ID of collection1660   * @param tokenId ID of token1661   * @example getTokenTotalPieces(10, 5);1662   * @returns number of pieces1663   */1664  async getTokenTotalPieces(collectionId: number, tokenId: number): Promise<bigint> {1665    return (await this.helper.callRpc('api.rpc.unique.totalPieces', [collectionId, tokenId])).unwrap().toBigInt();1666  }16671668  /**1669   * Change number of token pieces. Signer must be the owner of all token pieces.1670   * @param signer keyring of signer1671   * @param collectionId ID of collection1672   * @param tokenId ID of token1673   * @param amount new number of pieces1674   * @example repartitionToken(aliceKeyring, 10, 5, 12345n);1675   * @returns true if the repartion was success, otherwise false1676   */1677  async repartitionToken(signer: TSigner, collectionId: number, tokenId: number, amount: bigint): Promise<boolean> {1678    const currentAmount = await this.getTokenTotalPieces(collectionId, tokenId);1679    const repartitionResult = await this.helper.executeExtrinsic(1680      signer,1681      'api.tx.unique.repartition', [collectionId, tokenId, amount],1682      true,1683    );1684    if(currentAmount < amount) return this.helper.util.findCollectionInEvents(repartitionResult.result.events, collectionId, 'common', 'ItemCreated');1685    return this.helper.util.findCollectionInEvents(repartitionResult.result.events, collectionId, 'common', 'ItemDestroyed');1686  }1687}168816891690class FTGroup extends CollectionGroup {1691  /**1692   * Get collection object1693   * @param collectionId ID of collection1694   * @example getCollectionObject(2);1695   * @returns instance of UniqueFTCollection1696   */1697  getCollectionObject(collectionId: number): UniqueFTCollection {1698    return new UniqueFTCollection(collectionId, this.helper);1699  }17001701  /**1702   * Mint new fungible collection1703   * @param signer keyring of signer1704   * @param collectionOptions Collection options1705   * @param decimalPoints number of token decimals1706   * @example1707   * mintCollection(aliceKeyring, {1708   *   name: 'New',1709   *   description: 'New collection',1710   *   tokenPrefix: 'NEW',1711   * }, 18)1712   * @returns newly created fungible collection1713   */1714  async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions, decimalPoints = 0): Promise<UniqueFTCollection> {1715    collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; // Clone object1716    if(collectionOptions.tokenPropertyPermissions) throw Error('Fungible collections has no tokenPropertyPermissions');1717    collectionOptions.mode = {fungible: decimalPoints};1718    for (const key of ['name', 'description', 'tokenPrefix']) {1719      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);1720    }1721    const creationResult = await this.helper.executeExtrinsic(1722      signer,1723      'api.tx.unique.createCollectionEx', [collectionOptions],1724      true,1725    );1726    return this.getCollectionObject(this.helper.util.extractCollectionIdFromCreationResult(creationResult));1727  }17281729  /**1730   * Mint tokens1731   * @param signer keyring of signer1732   * @param collectionId ID of collection1733   * @param owner address owner of new tokens1734   * @param amount amount of tokens to be meanted1735   * @example mintTokens(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq"}, 1000n);1736   * @returns ```true``` if extrinsic success, otherwise ```false```1737   */1738  async mintTokens(signer: TSigner, collectionId: number, amount: bigint, owner: ICrossAccountId | string): Promise<boolean> {1739    const creationResult = await this.helper.executeExtrinsic(1740      signer,1741      'api.tx.unique.createItem', [collectionId, (typeof owner === 'string') ? {Substrate: owner} : owner, {1742        fungible: {1743          value: amount,1744        },1745      }],1746      true, // `Unable to mint fungible tokens for ${label}`,1747    );1748    return this.helper.util.findCollectionInEvents(creationResult.result.events, collectionId, 'common', 'ItemCreated');1749  }17501751  /**1752   * Mint multiple Fungible tokens with one owner1753   * @param signer keyring of signer1754   * @param collectionId ID of collection1755   * @param owner tokens owner1756   * @param tokens array of tokens with properties and pieces1757   * @returns ```true``` if extrinsic success, otherwise ```false```1758   */1759  async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, tokens: {value: bigint}[], owner: ICrossAccountId): Promise<boolean> {1760    const rawTokens = [];1761    for (const token of tokens) {1762      const raw = {Fungible: {Value: token.value}};1763      rawTokens.push(raw);1764    }1765    const creationResult = await this.helper.executeExtrinsic(1766      signer,1767      'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1768      true,1769    );1770    return this.helper.util.findCollectionInEvents(creationResult.result.events, collectionId, 'common', 'ItemCreated');1771  }17721773  /**1774   * Get the top 10 owners with the largest balance for the Fungible collection1775   * @param collectionId ID of collection1776   * @example getTop10Owners(10);1777   * @returns array of ```ICrossAccountId```1778   */1779  async getTop10Owners(collectionId: number): Promise<ICrossAccountId[]> {1780    return (await this.helper.callRpc('api.rpc.unique.tokenOwners', [collectionId, 0])).toJSON().map(crossAccountIdFromLower);1781  }17821783  /**1784   * Get account balance1785   * @param collectionId ID of collection1786   * @param addressObj address of owner1787   * @example getBalance(10, {Substrate: "5GHoZe9c73RYbVzq..."})1788   * @returns amount of fungible tokens owned by address1789   */1790  async getBalance(collectionId: number, addressObj: ICrossAccountId): Promise<bigint> {1791    return (await this.helper.callRpc('api.rpc.unique.balance', [collectionId, addressObj, 0])).toBigInt();1792  }17931794  /**1795   * Transfer tokens to address1796   * @param signer keyring of signer1797   * @param collectionId ID of collection1798   * @param toAddressObj address recipient1799   * @param amount amount of tokens to be sent1800   * @example transfer(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, 1000n);1801   * @returns ```true``` if extrinsic success, otherwise ```false```1802   */1803  async transfer(signer: TSigner, collectionId: number, toAddressObj: ICrossAccountId, amount=1n) {1804    return await super.transferToken(signer, collectionId, 0, toAddressObj, amount);1805  }18061807  /**1808   * Transfer some tokens on behalf of the owner.1809   * @param signer keyring of signer1810   * @param collectionId ID of collection1811   * @param fromAddressObj address on behalf of which tokens will be sent1812   * @param toAddressObj address where token to be sent1813   * @param amount number of tokens to be sent1814   * @example transferFrom(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, {Substrate: "5DfhbVfww7ThF8q6f3ij..."}, 10000n);1815   * @returns ```true``` if extrinsic success, otherwise ```false```1816   */1817  async transferFrom(signer: TSigner, collectionId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {1818    return await super.transferTokenFrom(signer, collectionId, 0, fromAddressObj, toAddressObj, amount);1819  }18201821  /**1822   * Destroy some amount of tokens1823   * @param signer keyring of signer1824   * @param collectionId ID of collection1825   * @param amount amount of tokens to be destroyed1826   * @example burnTokens(aliceKeyring, 10, 1000n);1827   * @returns ```true``` if extrinsic success, otherwise ```false```1828   */1829  async burnTokens(signer: IKeyringPair, collectionId: number, amount=1n): Promise<boolean> {1830    return (await super.burnToken(signer, collectionId, 0, amount)).success;1831  }18321833  /**1834   * Burn some tokens on behalf of the owner.1835   * @param signer keyring of signer1836   * @param collectionId ID of collection1837   * @param fromAddressObj address on behalf of which tokens will be burnt1838   * @param amount amount of tokens to be burnt1839   * @example burnTokensFrom(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, 1000n);1840   * @returns ```true``` if extrinsic success, otherwise ```false```1841   */1842  async burnTokensFrom(signer: IKeyringPair, collectionId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1843    return await super.burnTokenFrom(signer, collectionId, fromAddressObj, 0, amount);1844  }18451846  /**1847   * Get total collection supply1848   * @param collectionId1849   * @returns1850   */1851  async getTotalPieces(collectionId: number): Promise<bigint> {1852    return (await this.helper.callRpc('api.rpc.unique.totalPieces', [collectionId, 0])).unwrap().toBigInt();1853  }18541855  /**1856   * Set, change, or remove approved address to transfer tokens.1857   *1858   * @param signer keyring of signer1859   * @param collectionId ID of collection1860   * @param toAddressObj address to be approved1861   * @param amount amount of tokens to be approved1862   * @example approveTokens(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, 1000n)1863   * @returns ```true``` if extrinsic success, otherwise ```false```1864   */1865  async approveTokens(signer: IKeyringPair, collectionId: number, toAddressObj: ICrossAccountId, amount=1n) {1866    return super.approveToken(signer, collectionId, 0, toAddressObj, amount);1867  }18681869  /**1870   * Get amount of fungible tokens approved to transfer1871   * @param collectionId ID of collection1872   * @param fromAddressObj owner of tokens1873   * @param toAddressObj the address approved for the transfer of tokens on behalf of the owner1874   * @returns number of tokens approved for the transfer1875   */1876  async getApprovedTokens(collectionId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {1877    return super.getTokenApprovedPieces(collectionId, 0, toAddressObj, fromAddressObj);1878  }1879}188018811882class ChainGroup extends HelperGroup {1883  /**1884   * Get system properties of a chain1885   * @example getChainProperties();1886   * @returns ss58Format, token decimals, and token symbol1887   */1888  getChainProperties(): IChainProperties {1889    const properties = (this.helper.api as any).registry.getChainProperties().toJSON();1890    return {1891      ss58Format: properties.ss58Format.toJSON(),1892      tokenDecimals: properties.tokenDecimals.toJSON(),1893      tokenSymbol: properties.tokenSymbol.toJSON(),1894    };1895  }18961897  /**1898   * Get chain header1899   * @example getLatestBlockNumber();1900   * @returns the number of the last block1901   */1902  async getLatestBlockNumber(): Promise<number> {1903    return (await this.helper.callRpc('api.rpc.chain.getHeader')).number.toNumber();1904  }19051906  /**1907   * Get block hash by block number1908   * @param blockNumber number of block1909   * @example getBlockHashByNumber(12345);1910   * @returns hash of a block1911   */1912  async getBlockHashByNumber(blockNumber: number): Promise<string | null> {1913    const blockHash = (await this.helper.callRpc('api.rpc.chain.getBlockHash', [blockNumber])).toJSON();1914    if(blockHash === '0x0000000000000000000000000000000000000000000000000000000000000000') return null;1915    return blockHash;1916  }19171918  // TODO add docs1919  async getBlock(blockHashOrNumber: string | number): Promise<IBlock | null> {1920    const blockHash = typeof blockHashOrNumber === 'string' ? blockHashOrNumber : await this.getBlockHashByNumber(blockHashOrNumber);1921    if (!blockHash) return null;1922    return (await this.helper.callRpc('api.rpc.chain.getBlock', [blockHash])).toHuman().block;1923  }19241925  /**1926   * Get account nonce1927   * @param address substrate address1928   * @example getNonce("5GrwvaEF5zXb26Fz...");1929   * @returns number, account's nonce1930   */1931  async getNonce(address: TSubstrateAccount): Promise<number> {1932    return (await (this.helper.api as any).query.system.account(address)).nonce.toNumber();1933  }1934}193519361937class BalanceGroup extends HelperGroup {1938  /**1939   * Representation of the native token in the smallest unit1940   * @example getOneTokenNominal()1941   * @returns ```BigInt``` representation of the native token in the smallest unit, e.g. ```1_000_000_000_000_000_000n``` for QTZ.1942   */1943  getOneTokenNominal(): bigint {1944    const chainProperties = this.helper.chain.getChainProperties();1945    return 10n ** BigInt((chainProperties.tokenDecimals || [18])[0]);1946  }19471948  /**1949   * Get substrate address balance1950   * @param address substrate address1951   * @example getSubstrate("5GrwvaEF5zXb26Fz...")1952   * @returns amount of tokens on address1953   */1954  async getSubstrate(address: TSubstrateAccount): Promise<bigint> {1955    return (await this.helper.callRpc('api.query.system.account', [address])).data.free.toBigInt();1956  }19571958  /**1959   * Get full substrate balance including free, miscFrozen, feeFrozen, and reserved1960   * @param address substrate address1961   * @returns1962   */1963  async getSubstrateFull(address: TSubstrateAccount): Promise<ISubstrateBalance> {1964    const accountInfo = (await this.helper.callRpc('api.query.system.account', [address])).data;1965    return {free: accountInfo.free.toBigInt(), miscFrozen: accountInfo.miscFrozen.toBigInt(), feeFrozen: accountInfo.feeFrozen.toBigInt(), reserved: accountInfo.reserved.toBigInt()};1966  }19671968  /**1969   * Get ethereum address balance1970   * @param address ethereum address1971   * @example getEthereum("0x9F0583DbB855d...")1972   * @returns amount of tokens on address1973   */1974  async getEthereum(address: TEthereumAccount): Promise<bigint> {1975    return (await this.helper.callRpc('api.rpc.eth.getBalance', [address])).toBigInt();1976  }19771978  /**1979   * Transfer tokens to substrate address1980   * @param signer keyring of signer1981   * @param address substrate address of a recipient1982   * @param amount amount of tokens to be transfered1983   * @example transferToSubstrate(aliceKeyring, "5GrwvaEF5zXb26Fz...", 100_000_000_000n);1984   * @returns ```true``` if extrinsic success, otherwise ```false```1985   */1986  async transferToSubstrate(signer: TSigner, address: TSubstrateAccount, amount: bigint | string): Promise<boolean> {1987    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}`*/);19881989    let transfer = {from: null, to: null, amount: 0n} as any;1990    result.result.events.forEach(({event: {data, method, section}}) => {1991      if ((section === 'balances') && (method === 'Transfer')) {1992        transfer = {1993          from: this.helper.address.normalizeSubstrate(data[0]),1994          to: this.helper.address.normalizeSubstrate(data[1]),1995          amount: BigInt(data[2]),1996        };1997      }1998    });1999    let isSuccess = this.helper.address.normalizeSubstrate(typeof signer === 'string' ? signer : signer.address) === transfer.from;2000    isSuccess = isSuccess && this.helper.address.normalizeSubstrate(address) === transfer.to;2001    isSuccess = isSuccess && BigInt(amount) === transfer.amount;2002    return isSuccess;2003  }2004}200520062007class AddressGroup extends HelperGroup {2008  /**2009   * Normalizes the address to the specified ss58 format, by default ```42```.2010   * @param address substrate address2011   * @param ss58Format format for address conversion, by default ```42```2012   * @example normalizeSubstrate("unjKJQJrRd238pkUZZvzDQrfKuM39zBSnQ5zjAGAGcdRhaJTx") // returns 5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY2013   * @returns substrate address converted to normalized (i.e., starting with 5) or specified explicitly representation2014   */2015  normalizeSubstrate(address: TSubstrateAccount, ss58Format = 42): TSubstrateAccount {2016    return this.helper.util.normalizeSubstrateAddress(address, ss58Format);2017  }20182019  /**2020   * Get address in the connected chain format2021   * @param address substrate address2022   * @example normalizeSubstrateToChainFormat("5GrwvaEF5zXb26Fz...") // returns unjKJQJrRd238pkUZZ... for Unique Network2023   * @returns address in chain format2024   */2025  async normalizeSubstrateToChainFormat(address: TSubstrateAccount): Promise<TSubstrateAccount> {2026    const info = this.helper.chain.getChainProperties();2027    return encodeAddress(decodeAddress(address), info.ss58Format);2028  }20292030  /**2031   * Get substrate mirror of an ethereum address2032   * @param ethAddress ethereum address2033   * @param toChainFormat false for normalized account2034   * @example ethToSubstrate('0x9F0583DbB855d...')2035   * @returns substrate mirror of a provided ethereum address2036   */2037  async ethToSubstrate(ethAddress: TEthereumAccount, toChainFormat=false): Promise<TSubstrateAccount> {2038    if(!toChainFormat) return evmToAddress(ethAddress);2039    const info = this.helper.chain.getChainProperties();2040    return evmToAddress(ethAddress, info.ss58Format);2041  }20422043  /**2044   * Get ethereum mirror of a substrate address2045   * @param subAddress substrate account2046   * @example substrateToEth("5DnSF6RRjwteE3BrC...")2047   * @returns ethereum mirror of a provided substrate address2048   */2049  substrateToEth(subAddress: TSubstrateAccount): TEthereumAccount {2050    return nesting.toChecksumAddress('0x' + Array.from(addressToEvm(subAddress), i => i.toString(16).padStart(2, '0')).join(''));2051  }2052}20532054class StakingGroup extends HelperGroup {2055  /**2056   * Stake tokens for App Promotion2057   * @param signer keyring of signer2058   * @param amountToStake amount of tokens to stake2059   * @param label extra label for log2060   * @returns2061   */2062  async stake(signer: TSigner, amountToStake: bigint, label?: string): Promise<boolean> {2063    if(typeof label === 'undefined') label = `${signer.address} amount: ${amountToStake}`;2064    const stakeResult = await this.helper.executeExtrinsic(2065      signer, 'api.tx.appPromotion.stake',2066      [amountToStake], true,2067    );2068    // TODO extract info from stakeResult2069    return true;2070  }20712072  /**2073   * Unstake tokens for App Promotion2074   * @param signer keyring of signer2075   * @param amountToUnstake amount of tokens to unstake2076   * @param label extra label for log2077   * @returns block number where balances will be unlocked2078   */2079  async unstake(signer: TSigner, label?: string): Promise<number> {2080    if(typeof label === 'undefined') label = `${signer.address}`;2081    const unstakeResult = await this.helper.executeExtrinsic(2082      signer, 'api.tx.appPromotion.unstake',2083      [], true,2084    );2085    // TODO extract block number fron events2086    return 1;2087  }20882089  /**2090   * Get total staked amount for address2091   * @param address substrate or ethereum address2092   * @returns total staked amount2093   */2094  async getTotalStaked(address?: ICrossAccountId): Promise<bigint> {2095    if (address) return (await this.helper.callRpc('api.rpc.appPromotion.totalStaked', [address])).toBigInt();2096    return (await this.helper.callRpc('api.rpc.appPromotion.totalStaked')).toBigInt();2097  }20982099  /**2100   * Get total staked per block2101   * @param address substrate or ethereum address2102   * @returns array of stakes. `block` – the number of the block in which the stake was made. `amount` - the number of tokens staked in the block2103   */2104  async getTotalStakedPerBlock(address: ICrossAccountId): Promise<IStakingInfo[]> {2105    const rawTotalStakerdPerBlock = await this.helper.callRpc('api.rpc.appPromotion.totalStakedPerBlock', [address]);2106    return rawTotalStakerdPerBlock.map(([block, amount]: any[]) => {2107      return { 2108        block: block.toBigInt(),2109        amount: amount.toBigInt(),2110      };2111    });2112  }21132114  /**2115   * Get total pending unstake amount for address2116   * @param address substrate or ethereum address2117   * @returns total pending unstake amount2118   */2119  async getPendingUnstake(address: ICrossAccountId): Promise<bigint> {2120    return (await this.helper.callRpc('api.rpc.appPromotion.pendingUnstake', [address])).toBigInt();2121  }21222123  /**2124   * Get pending unstake amount per block for address2125   * @param address substrate or ethereum address2126   * @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 block2127   */2128  async getPendingUnstakePerBlock(address: ICrossAccountId): Promise<IStakingInfo[]> {2129    const rawUnstakedPerBlock = await this.helper.callRpc('api.rpc.appPromotion.pendingUnstakePerBlock', [address]);2130    const result = rawUnstakedPerBlock.map(([block, amount]: any[]) => {2131      return {2132        block: block.toBigInt(),2133        amount: amount.toBigInt(),2134      };2135    });2136    return result;2137  }2138}21392140export class UniqueHelper extends ChainHelperBase {2141  chain: ChainGroup;2142  balance: BalanceGroup;2143  address: AddressGroup;2144  collection: CollectionGroup;2145  nft: NFTGroup;2146  rft: RFTGroup;2147  ft: FTGroup;2148  staking: StakingGroup;21492150  constructor(logger?: ILogger) {2151    super(logger);2152    this.chain = new ChainGroup(this);2153    this.balance = new BalanceGroup(this);2154    this.address = new AddressGroup(this);2155    this.collection = new CollectionGroup(this);2156    this.nft = new NFTGroup(this);2157    this.rft = new RFTGroup(this);2158    this.ft = new FTGroup(this);2159    this.staking = new StakingGroup(this);2160  }2161}216221632164class UniqueCollectionBase {2165  helper: UniqueHelper;2166  collectionId: number;21672168  constructor(collectionId: number, uniqueHelper: UniqueHelper) {2169    this.collectionId = collectionId;2170    this.helper = uniqueHelper;2171  }21722173  async getData() {2174    return await this.helper.collection.getData(this.collectionId);2175  }21762177  async getLastTokenId() {2178    return await this.helper.collection.getLastTokenId(this.collectionId);2179  }21802181  async isTokenExists(tokenId: number) {2182    return await this.helper.collection.isTokenExists(this.collectionId, tokenId);2183  }21842185  async getAdmins() {2186    return await this.helper.collection.getAdmins(this.collectionId);2187  }21882189  async getAllowList() {2190    return await this.helper.collection.getAllowList(this.collectionId);2191  }21922193  async getEffectiveLimits() {2194    return await this.helper.collection.getEffectiveLimits(this.collectionId);2195  }21962197  async setSponsor(signer: TSigner, sponsorAddress: TSubstrateAccount) {2198    return await this.helper.collection.setSponsor(signer, this.collectionId, sponsorAddress);2199  }22002201  async confirmSponsorship(signer: TSigner) {2202    return await this.helper.collection.confirmSponsorship(signer, this.collectionId);2203  }22042205  async removeSponsor(signer: TSigner) {2206    return await this.helper.collection.removeSponsor(signer, this.collectionId);2207  }22082209  async setLimits(signer: TSigner, limits: ICollectionLimits) {2210    return await this.helper.collection.setLimits(signer, this.collectionId, limits);2211  }22122213  async changeOwner(signer: TSigner, ownerAddress: TSubstrateAccount) {2214    return await this.helper.collection.changeOwner(signer, this.collectionId, ownerAddress);2215  }22162217  async addAdmin(signer: TSigner, adminAddressObj: ICrossAccountId) {2218    return await this.helper.collection.addAdmin(signer, this.collectionId, adminAddressObj);2219  }22202221  async addToAllowList(signer: TSigner, addressObj: ICrossAccountId) {2222    return await this.helper.collection.addToAllowList(signer, this.collectionId, addressObj);2223  }22242225  async removeFromAllowList(signer: TSigner, addressObj: ICrossAccountId) {2226    return await this.helper.collection.removeFromAllowList(signer, this.collectionId, addressObj);2227  }22282229  async removeAdmin(signer: TSigner, adminAddressObj: ICrossAccountId) {2230    return await this.helper.collection.removeAdmin(signer, this.collectionId, adminAddressObj);2231  }22322233  async setProperties(signer: TSigner, properties: IProperty[]) {2234    return await this.helper.collection.setProperties(signer, this.collectionId, properties);2235  }22362237  async deleteProperties(signer: TSigner, propertyKeys: string[]) {2238    return await this.helper.collection.deleteProperties(signer, this.collectionId, propertyKeys);2239  }22402241  async getTokenNextSponsored(tokenId: number, addressObj: ICrossAccountId) {2242    return await this.helper.collection.getTokenNextSponsored(this.collectionId, tokenId, addressObj);2243  }22442245  async setPermissions(signer: TSigner, permissions: ICollectionPermissions) {2246    return await this.helper.collection.setPermissions(signer, this.collectionId, permissions);2247  }22482249  async enableNesting(signer: TSigner, permissions: INestingPermissions) {2250    return await this.helper.collection.enableNesting(signer, this.collectionId, permissions);2251  }22522253  async disableNesting(signer: TSigner) {2254    return await this.helper.collection.disableNesting(signer, this.collectionId);2255  }22562257  async burn(signer: TSigner) {2258    return await this.helper.collection.burn(signer, this.collectionId);2259  }2260}226122622263class UniqueNFTCollection extends UniqueCollectionBase {2264  getTokenObject(tokenId: number) {2265    return new UniqueNFTToken(tokenId, this);2266  }22672268  async getTokensByAddress(addressObj: ICrossAccountId) {2269    return await this.helper.nft.getTokensByAddress(this.collectionId, addressObj);2270  }22712272  async getToken(tokenId: number, blockHashAt?: string) {2273    return await this.helper.nft.getToken(this.collectionId, tokenId, [], blockHashAt);2274  }22752276  async getTokenOwner(tokenId: number, blockHashAt?: string) {2277    return await this.helper.nft.getTokenOwner(this.collectionId, tokenId, blockHashAt);2278  }22792280  async getTokenTopmostOwner(tokenId: number, blockHashAt?: string) {2281    return await this.helper.nft.getTokenTopmostOwner(this.collectionId, tokenId, blockHashAt);2282  }22832284  async getTokenChildren(tokenId: number, blockHashAt?: string) {2285    return await this.helper.nft.getTokenChildren(this.collectionId, tokenId, blockHashAt);2286  }22872288  async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId) {2289    return await this.helper.nft.transferToken(signer, this.collectionId, tokenId, addressObj);2290  }22912292  async transferTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2293    return await this.helper.nft.transferTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, toAddressObj);2294  }22952296  async approveToken(signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId) {2297    return await this.helper.nft.approveToken(signer, this.collectionId, tokenId, toAddressObj);2298  }22992300  async isTokenApproved(tokenId: number, toAddressObj: ICrossAccountId) {2301    return await this.helper.nft.isTokenApproved(this.collectionId, tokenId, toAddressObj);2302  }23032304  async mintToken(signer: TSigner, owner: ICrossAccountId = {Substrate: signer.address}, properties?: IProperty[]) {2305    return await this.helper.nft.mintToken(signer, {collectionId: this.collectionId, owner, properties});2306  }23072308  async mintMultipleTokens(signer: TSigner, tokens: {owner: ICrossAccountId, properties?: IProperty[]}[]) {2309    return await this.helper.nft.mintMultipleTokens(signer, this.collectionId, tokens);2310  }23112312  async burnToken(signer: TSigner, tokenId: number) {2313    return await this.helper.nft.burnToken(signer, this.collectionId, tokenId);2314  }23152316  async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[]) {2317    return await this.helper.nft.setTokenProperties(signer, this.collectionId, tokenId, properties);2318  }23192320  async deleteTokenProperties(signer: TSigner, tokenId: number, propertyKeys: string[]) {2321    return await this.helper.nft.deleteTokenProperties(signer, this.collectionId, tokenId, propertyKeys);2322  }23232324  async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[]) {2325    return await this.helper.nft.setTokenPropertyPermissions(signer, this.collectionId, permissions);2326  }23272328  async nestToken(signer: TSigner, tokenId: number, toTokenObj: IToken) {2329    return await this.helper.nft.nestToken(signer, {collectionId: this.collectionId, tokenId}, toTokenObj);2330  }23312332  async unnestToken(signer: TSigner, tokenId: number, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {2333    return await this.helper.nft.unnestToken(signer, {collectionId: this.collectionId, tokenId}, fromTokenObj, toAddressObj);2334  }2335}233623372338class UniqueRFTCollection extends UniqueCollectionBase {2339  getTokenObject(tokenId: number) {2340    return new UniqueRFTToken(tokenId, this);2341  }23422343  async getTokensByAddress(addressObj: ICrossAccountId) {2344    return await this.helper.rft.getTokensByAddress(this.collectionId, addressObj);2345  }23462347  async getTop10TokenOwners(tokenId: number) {2348    return await this.helper.rft.getTokenTop10Owners(this.collectionId, tokenId);2349  }23502351  async getTokenBalance(tokenId: number, addressObj: ICrossAccountId) {2352    return await this.helper.rft.getTokenBalance(this.collectionId, tokenId, addressObj);2353  }23542355  async getTokenTotalPieces(tokenId: number) {2356    return await this.helper.rft.getTokenTotalPieces(this.collectionId, tokenId);2357  }23582359  async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId, amount=1n) {2360    return await this.helper.rft.transferToken(signer, this.collectionId, tokenId, addressObj, amount);2361  }23622363  async transferTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {2364    return await this.helper.rft.transferTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, toAddressObj, amount);2365  }23662367  async approveToken(signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {2368    return await this.helper.rft.approveToken(signer, this.collectionId, tokenId, toAddressObj, amount);2369  }23702371  async getTokenApprovedPieces(tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2372    return await this.helper.rft.getTokenApprovedPieces(this.collectionId, tokenId, toAddressObj, fromAddressObj);2373  }23742375  async repartitionToken(signer: TSigner, tokenId: number, amount: bigint) {2376    return await this.helper.rft.repartitionToken(signer, this.collectionId, tokenId, amount);2377  }23782379  async mintToken(signer: TSigner, pieces=1n, owner: ICrossAccountId = {Substrate: signer.address}, properties?: IProperty[]) {2380    return await this.helper.rft.mintToken(signer, {collectionId: this.collectionId, owner, pieces, properties});2381  }23822383  async mintMultipleTokens(signer: TSigner, tokens: {pieces: bigint, owner: ICrossAccountId, properties?: IProperty[]}[]) {2384    return await this.helper.rft.mintMultipleTokens(signer, this.collectionId, tokens);2385  }23862387  async burnToken(signer: TSigner, tokenId: number, amount=1n) {2388    return await this.helper.rft.burnToken(signer, this.collectionId, tokenId, amount);2389  }23902391  async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[]) {2392    return await this.helper.rft.setTokenProperties(signer, this.collectionId, tokenId, properties);2393  }23942395  async deleteTokenProperties(signer: TSigner, tokenId: number, propertyKeys: string[]) {2396    return await this.helper.rft.deleteTokenProperties(signer, this.collectionId, tokenId, propertyKeys);2397  }23982399  async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[]) {2400    return await this.helper.rft.setTokenPropertyPermissions(signer, this.collectionId, permissions);2401  }2402}240324042405class UniqueFTCollection extends UniqueCollectionBase {2406  async mint(signer: TSigner, amount=1n, owner: ICrossAccountId = {Substrate: signer.address}) {2407    return await this.helper.ft.mintTokens(signer, this.collectionId, amount, owner);2408  }24092410  async mintWithOneOwner(signer: TSigner, tokens: {value: bigint}[], owner: ICrossAccountId = {Substrate: signer.address}) {2411    return await this.helper.ft.mintMultipleTokensWithOneOwner(signer, this.collectionId, tokens, owner);2412  }24132414  async getBalance(addressObj: ICrossAccountId) {2415    return await this.helper.ft.getBalance(this.collectionId, addressObj);2416  }24172418  async getTop10Owners() {2419    return await this.helper.ft.getTop10Owners(this.collectionId);2420  }24212422  async transfer(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {2423    return await this.helper.ft.transfer(signer, this.collectionId, toAddressObj, amount);2424  }24252426  async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {2427    return await this.helper.ft.transferFrom(signer, this.collectionId, fromAddressObj, toAddressObj, amount);2428  }24292430  async burnTokens(signer: TSigner, amount=1n) {2431    return await this.helper.ft.burnTokens(signer, this.collectionId, amount);2432  }24332434  async burnTokensFrom(signer: TSigner, fromAddressObj: ICrossAccountId, amount=1n) {2435    return await this.helper.ft.burnTokensFrom(signer, this.collectionId, fromAddressObj, amount);2436  }24372438  async getTotalPieces() {2439    return await this.helper.ft.getTotalPieces(this.collectionId);2440  }24412442  async approveTokens(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {2443    return await this.helper.ft.approveTokens(signer, this.collectionId, toAddressObj, amount);2444  }24452446  async getApprovedTokens(fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2447    return await this.helper.ft.getApprovedTokens(this.collectionId, fromAddressObj, toAddressObj);2448  }2449}245024512452class UniqueTokenBase implements IToken {2453  collection: UniqueNFTCollection | UniqueRFTCollection;2454  collectionId: number;2455  tokenId: number;24562457  constructor(tokenId: number, collection: UniqueNFTCollection | UniqueRFTCollection) {2458    this.collection = collection;2459    this.collectionId = collection.collectionId;2460    this.tokenId = tokenId;2461  }24622463  async getNextSponsored(addressObj: ICrossAccountId) {2464    return await this.collection.getTokenNextSponsored(this.tokenId, addressObj);2465  }24662467  async setProperties(signer: TSigner, properties: IProperty[]) {2468    return await this.collection.setTokenProperties(signer, this.tokenId, properties);2469  }24702471  async deleteProperties(signer: TSigner, propertyKeys: string[]) {2472    return await this.collection.deleteTokenProperties(signer, this.tokenId, propertyKeys);2473  }2474}247524762477class UniqueNFTToken extends UniqueTokenBase {2478  collection: UniqueNFTCollection;24792480  constructor(tokenId: number, collection: UniqueNFTCollection) {2481    super(tokenId, collection);2482    this.collection = collection;2483  }24842485  async getData(blockHashAt?: string) {2486    return await this.collection.getToken(this.tokenId, blockHashAt);2487  }24882489  async getOwner(blockHashAt?: string) {2490    return await this.collection.getTokenOwner(this.tokenId, blockHashAt);2491  }24922493  async getTopmostOwner(blockHashAt?: string) {2494    return await this.collection.getTokenTopmostOwner(this.tokenId, blockHashAt);2495  }24962497  async getChildren(blockHashAt?: string) {2498    return await this.collection.getTokenChildren(this.tokenId, blockHashAt);2499  }25002501  async nest(signer: TSigner, toTokenObj: IToken) {2502    return await this.collection.nestToken(signer, this.tokenId, toTokenObj);2503  }25042505  async unnest(signer: TSigner, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {2506    return await this.collection.unnestToken(signer, this.tokenId, fromTokenObj, toAddressObj);2507  }25082509  async transfer(signer: TSigner, addressObj: ICrossAccountId) {2510    return await this.collection.transferToken(signer, this.tokenId, addressObj);2511  }25122513  async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2514    return await this.collection.transferTokenFrom(signer, this.tokenId, fromAddressObj, toAddressObj);2515  }25162517  async approve(signer: TSigner, toAddressObj: ICrossAccountId) {2518    return await this.collection.approveToken(signer, this.tokenId, toAddressObj);2519  }25202521  async isApproved(toAddressObj: ICrossAccountId) {2522    return await this.collection.isTokenApproved(this.tokenId, toAddressObj);2523  }25242525  async burn(signer: TSigner) {2526    return await this.collection.burnToken(signer, this.tokenId);2527  }2528}25292530class UniqueRFTToken extends UniqueTokenBase {2531  collection: UniqueRFTCollection;25322533  constructor(tokenId: number, collection: UniqueRFTCollection) {2534    super(tokenId, collection);2535    this.collection = collection;2536  }25372538  async getTop10Owners() {2539    return await this.collection.getTop10TokenOwners(this.tokenId);2540  }25412542  async getBalance(addressObj: ICrossAccountId) {2543    return await this.collection.getTokenBalance(this.tokenId, addressObj);2544  }25452546  async getTotalPieces() {2547    return await this.collection.getTokenTotalPieces(this.tokenId);2548  }25492550  async transfer(signer: TSigner, addressObj: ICrossAccountId, amount=1n) {2551    return await this.collection.transferToken(signer, this.tokenId, addressObj, amount);2552  }25532554  async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {2555    return await this.collection.transferTokenFrom(signer, this.tokenId, fromAddressObj, toAddressObj, amount);2556  }25572558  async approve(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {2559    return await this.collection.approveToken(signer, this.tokenId, toAddressObj, amount);2560  }25612562  async getApprovedPieces(fromAddressObj: ICrossAccountId, toAccountObj: ICrossAccountId) {2563    return await this.collection.getTokenApprovedPieces(this.tokenId, fromAddressObj, toAccountObj);2564  }25652566  async repartition(signer: TSigner, amount: bigint) {2567    return await this.collection.repartitionToken(signer, this.tokenId, amount);2568  }25692570  async burn(signer: TSigner, amount=1n) {2571    return await this.collection.burnToken(signer, this.tokenId, amount);2572  }2573}
after · tests/src/util/playgrounds/unique.ts
1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// SPDX-License-Identifier: Apache-2.034/* eslint-disable @typescript-eslint/no-var-requires */5/* eslint-disable function-call-argument-newline */6/* eslint-disable no-prototype-builtins */78import {ApiPromise, WsProvider, Keyring} from '@polkadot/api';9import {ApiInterfaceEvents, SignerOptions} from '@polkadot/api/types';10import {encodeAddress, decodeAddress, keccakAsHex, evmToAddress, addressToEvm} from '@polkadot/util-crypto';11import {IKeyringPair} from '@polkadot/types/types';12import {IApiListeners, IBlock, IEvent, IChainProperties, ICollectionCreationOptions, ICollectionLimits, ICollectionPermissions, ICrossAccountId, ICrossAccountIdLower, ILogger, INestingPermissions, IProperty, IStakingInfo, ISubstrateBalance, IToken, ITokenPropertyPermission, ITransactionResult, IUniqueHelperLog, TApiAllowedListeners, TEthereumAccount, TSigner, TSubstrateAccount, TUniqueNetworks} from './types';1314export class CrossAccountId implements ICrossAccountId {15  Substrate?: TSubstrateAccount;16  Ethereum?: TEthereumAccount;1718  constructor(account: ICrossAccountId) {19    if (account.Substrate) this.Substrate = account.Substrate;20    if (account.Ethereum) this.Ethereum = account.Ethereum;21  }2223  static fromKeyring(account: IKeyringPair) {24    return new CrossAccountId({Substrate: account.address});25  }2627  static fromLowerCaseKeys(address: ICrossAccountIdLower): CrossAccountId {28    return new CrossAccountId({Substrate: address.substrate, Ethereum: address.ethereum});29  }3031  static normalizeSubstrateAddress(address: TSubstrateAccount, ss58Format = 42): TSubstrateAccount {32    return encodeAddress(decodeAddress(address), ss58Format);33  }3435  static withNormalizedSubstrate(address: TSubstrateAccount, ss58Format = 42): CrossAccountId {36    return new CrossAccountId({Substrate: CrossAccountId.normalizeSubstrateAddress(address, ss58Format)});37  }38  39  withNormalizedSubstrate(ss58Format = 42): CrossAccountId {40    if (this.Substrate) return CrossAccountId.withNormalizedSubstrate(this.Substrate, ss58Format);41    return this;42  }43  44  toLowerCase(): CrossAccountId {45    if (this.Substrate) this.Substrate = this.Substrate.toLowerCase();46    if (this.Ethereum) this.Ethereum = this.Ethereum.toLowerCase();47    return this;48  }49}5051const nesting = {52  toChecksumAddress(address: string): string {53    if (typeof address === 'undefined') return '';5455    if(!/^(0x)?[0-9a-f]{40}$/i.test(address)) throw new Error(`Given address "${address}" is not a valid Ethereum address.`);5657    address = address.toLowerCase().replace(/^0x/i,'');58    const addressHash = keccakAsHex(address).replace(/^0x/i,'');59    const checksumAddress = ['0x'];6061    for (let i = 0; i < address.length; i++) {62      // If ith character is 8 to f then make it uppercase63      if (parseInt(addressHash[i], 16) > 7) {64        checksumAddress.push(address[i].toUpperCase());65      } else {66        checksumAddress.push(address[i]);67      }68    }69    return checksumAddress.join('');70  },71  tokenIdToAddress(collectionId: number, tokenId: number) {72    return this.toChecksumAddress(`0xf8238ccfff8ed887463fd5e0${collectionId.toString(16).padStart(8, '0')}${tokenId.toString(16).padStart(8, '0')}`);73  },74};7576class UniqueUtil {77  static transactionStatus = {78    NOT_READY: 'NotReady',79    FAIL: 'Fail',80    SUCCESS: 'Success',81  };8283  static chainLogType = {84    EXTRINSIC: 'extrinsic',85    RPC: 'rpc',86  };8788  static getTokenAccount(token: IToken): CrossAccountId {89    return new CrossAccountId({Ethereum: this.getTokenAddress(token)});90  }9192  static getTokenAddress(token: IToken): string {93    return nesting.tokenIdToAddress(token.collectionId, token.tokenId);94  }9596  static getDefaultLogger(): ILogger {97    return {98      log(msg: any, level = 'INFO') {99        console[level.toLocaleLowerCase() === 'error' ? 'error' : 'log'](...(Array.isArray(msg) ? msg : [msg]));100      },101      level: {102        ERROR: 'ERROR',103        WARNING: 'WARNING',104        INFO: 'INFO',105      },106    };107  }108109  static vec2str(arr: string[] | number[]) {110    return arr.map(x => String.fromCharCode(parseInt(x.toString()))).join('');111  }112113  static str2vec(string: string) {114    if (typeof string !== 'string') return string;115    return Array.from(string).map(x => x.charCodeAt(0));116  }117118  static fromSeed(seed: string, ss58Format = 42) {119    const keyring = new Keyring({type: 'sr25519', ss58Format});120    return keyring.addFromUri(seed);121  }122123  static extractCollectionIdFromCreationResult(creationResult: ITransactionResult) {124    if (creationResult.status !== this.transactionStatus.SUCCESS) {125      throw Error('Unable to create collection!');126    }127128    let collectionId = null;129    creationResult.result.events.forEach(({event: {data, method, section}}) => {130      if ((section === 'common') && (method === 'CollectionCreated')) {131        collectionId = parseInt(data[0].toString(), 10);132      }133    });134135    if (collectionId === null) {136      throw Error('No CollectionCreated event was found!');137    }138139    return collectionId;140  }141142  static extractTokensFromCreationResult(creationResult: ITransactionResult) {143    if (creationResult.status !== this.transactionStatus.SUCCESS) {144      throw Error('Unable to create tokens!');145    }146    let success = false;147    const tokens = [] as any;148    creationResult.result.events.forEach(({event: {data, method, section}}) => {149      if (method === 'ExtrinsicSuccess') {150        success = true;151      } else if ((section === 'common') && (method === 'ItemCreated')) {152        tokens.push({153          collectionId: parseInt(data[0].toString(), 10),154          tokenId: parseInt(data[1].toString(), 10),155          owner: data[2].toJSON(),156        });157      }158    });159    return {success, tokens};160  }161162  static extractTokensFromBurnResult(burnResult: ITransactionResult) {163    if (burnResult.status !== this.transactionStatus.SUCCESS) {164      throw Error('Unable to burn tokens!');165    }166    let success = false;167    const tokens = [] as any;168    burnResult.result.events.forEach(({event: {data, method, section}}) => {169      if (method === 'ExtrinsicSuccess') {170        success = true;171      } else if ((section === 'common') && (method === 'ItemDestroyed')) {172        tokens.push({173          collectionId: parseInt(data[0].toString(), 10),174          tokenId: parseInt(data[1].toString(), 10),175          owner: data[2].toJSON(),176        });177      }178    });179    return {success, tokens};180  }181182  static findCollectionInEvents(events: {event: IEvent}[], collectionId: number, expectedSection: string, expectedMethod: string) {183    let eventId = null;184    events.forEach(({event: {data, method, section}}) => {185      if ((section === expectedSection) && (method === expectedMethod)) {186        eventId = parseInt(data[0].toString(), 10);187      }188    });189190    if (eventId === null) {191      throw Error(`No ${expectedMethod} event was found!`);192    }193    return eventId === collectionId;194  }195196  static isTokenTransferSuccess(events: {event: IEvent}[], collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {197    const normalizeAddress = (address: string | ICrossAccountId) => {198      if(typeof address === 'string') return address;199      const obj = {} as any;200      Object.keys(address).forEach(k => {201        obj[k.toLocaleLowerCase()] = address[k as 'Substrate' | 'Ethereum'];202      });203      if(obj.substrate) return CrossAccountId.withNormalizedSubstrate(obj.substrate);204      if(obj.ethereum) return CrossAccountId.fromLowerCaseKeys(obj).toLowerCase();205      return address;206    };207    let transfer = {collectionId: null, tokenId: null, from: null, to: null, amount: 1} as any;208    events.forEach(({event: {data, method, section}}) => {209      if ((section === 'common') && (method === 'Transfer')) {210        const hData = (data as any).toJSON();211        transfer = {212          collectionId: hData[0],213          tokenId: hData[1],214          from: normalizeAddress(hData[2]),215          to: normalizeAddress(hData[3]),216          amount: BigInt(hData[4]),217        };218      }219    });220    let isSuccess = parseInt(collectionId.toString()) === transfer.collectionId && parseInt(tokenId.toString()) === transfer.tokenId;221    isSuccess = isSuccess && JSON.stringify(normalizeAddress(fromAddressObj)) === JSON.stringify(transfer.from);222    isSuccess = isSuccess && JSON.stringify(normalizeAddress(toAddressObj)) === JSON.stringify(transfer.to);223    isSuccess = isSuccess && amount === transfer.amount;224    return isSuccess;225  }226}227228class UniqueEventHelper {229  private static extractIndex(index: any): [number, number] | string {230    if(index.toRawType() === '[u8;2]') return [index[0], index[1]];231    return index.toJSON();232  }233234  private static extractSub(data: any, subTypes: any): {[key: string]: any} {235    let obj: any = {};236    let index = 0;237238    if (data.entries) {239      for(const [key, value] of data.entries()) {240        obj[key] = this.extractData(value, subTypes[index]);241        index++;242      }243    } else obj = data.toJSON();244245    return obj;246  }247  248  private static extractData(data: any, type: any): any {249    if (['u16', 'u32'].indexOf(type.type) > -1) return data.toNumber();250    if (['u64', 'u128', 'u256'].indexOf(type.type) > -1) return data.toBigInt();251    if(type.hasOwnProperty('sub')) return this.extractSub(data, type.sub);252    return data.toHuman();253  }254255  public static extractEvents(records: ITransactionResult): IEvent[] {256    const parsedEvents: IEvent[] = [];257258    records.result.events.forEach((record) => {259      const {event, phase} = record;260      const types = (event as any).typeDef;261262      const eventData: IEvent = {263        section: event.section.toString(),264        method: event.method.toString(),265        index: this.extractIndex(event.index),266        data: [],267        phase: phase.toJSON(),268      };269270      event.data.forEach((val: any, index: number) => {271        eventData.data.push(this.extractData(val, types[index]));272      });273274      parsedEvents.push(eventData);275    });276277    return parsedEvents;278  }279}280281class ChainHelperBase {282  transactionStatus = UniqueUtil.transactionStatus;283  chainLogType = UniqueUtil.chainLogType;284  util: typeof UniqueUtil;285  eventHelper: typeof UniqueEventHelper;286  logger: ILogger;287  api: ApiPromise | null;288  forcedNetwork: TUniqueNetworks | null;289  network: TUniqueNetworks | null;290  chainLog: IUniqueHelperLog[];291292  constructor(logger?: ILogger) {293    this.util = UniqueUtil;294    this.eventHelper = UniqueEventHelper;295    if (typeof logger == 'undefined') logger = this.util.getDefaultLogger();296    this.logger = logger;297    this.api = null;298    this.forcedNetwork = null;299    this.network = null;300    this.chainLog = [];301  }302303  clearChainLog(): void {304    this.chainLog = [];305  }306307  forceNetwork(value: TUniqueNetworks): void {308    this.forcedNetwork = value;309  }310311  async connect(wsEndpoint: string, listeners?: IApiListeners) {312    if (this.api !== null) throw Error('Already connected');313    const {api, network} = await ChainHelperBase.createConnection(wsEndpoint, listeners, this.forcedNetwork);314    this.api = api;315    this.network = network;316  }317318  async disconnect() {319    if (this.api === null) return;320    await this.api.disconnect();321    this.api = null;322    this.network = null;323  }324325  static async detectNetwork(api: ApiPromise): Promise<TUniqueNetworks> {326    const spec = (await api.query.system.lastRuntimeUpgrade()).toJSON() as any;327    if(['quartz', 'unique'].indexOf(spec.specName) > -1) return spec.specName;328    return 'opal';329  }330331  static async detectNetworkByWsEndpoint(wsEndpoint: string): Promise<TUniqueNetworks> {332    const api = new ApiPromise({provider: new WsProvider(wsEndpoint)});333    await api.isReady;334335    const network = await this.detectNetwork(api);336337    await api.disconnect();338339    return network;340  }341342  static async createConnection(wsEndpoint: string, listeners?: IApiListeners, network?: TUniqueNetworks | null): Promise<{343    api: ApiPromise;344    network: TUniqueNetworks;345  }> {346    if(typeof network === 'undefined' || network === null) network = 'opal';347    const supportedRPC = {348      opal: {349        unique: require('@unique-nft/opal-testnet-types/definitions').unique.rpc,350      },351      quartz: {352        unique: require('@unique-nft/quartz-mainnet-types/definitions').unique.rpc,353      },354      unique: {355        unique: require('@unique-nft/unique-mainnet-types/definitions').unique.rpc,356      },357    };358    if(!supportedRPC.hasOwnProperty(network)) network = await this.detectNetworkByWsEndpoint(wsEndpoint);359    const rpc = supportedRPC[network];360361    // TODO: investigate how to replace rpc in runtime362    // api._rpcCore.addUserInterfaces(rpc);363364    const api = new ApiPromise({provider: new WsProvider(wsEndpoint), rpc});365366    await api.isReadyOrError;367368    if (typeof listeners === 'undefined') listeners = {};369    for (const event of ['connected', 'disconnected', 'error', 'ready', 'decorated']) {370      if (!listeners.hasOwnProperty(event) || typeof listeners[event as TApiAllowedListeners] === 'undefined') continue;371      api.on(event as ApiInterfaceEvents, listeners[event as TApiAllowedListeners] as (...args: any[]) => any);372    }373374    return {api, network};375  }376377  getTransactionStatus(data: {events: {event: IEvent}[], status: any}) {378    const {events, status} = data;379    if (status.isReady) {380      return this.transactionStatus.NOT_READY;381    }382    if (status.isBroadcast) {383      return this.transactionStatus.NOT_READY;384    }385    if (status.isInBlock || status.isFinalized) {386      const errors = events.filter(e => e.event.method === 'ExtrinsicFailed');387      if (errors.length > 0) {388        return this.transactionStatus.FAIL;389      }390      if (events.filter(e => e.event.method === 'ExtrinsicSuccess').length > 0) {391        return this.transactionStatus.SUCCESS;392      }393    }394395    return this.transactionStatus.FAIL;396  }397398  signTransaction(sender: TSigner, transaction: any, options: Partial<SignerOptions> | null = null, label = 'transaction') {399    const sign = (callback: any) => {400      if(options !== null) return transaction.signAndSend(sender, options, callback);401      return transaction.signAndSend(sender, callback);402    };403    // eslint-disable-next-line no-async-promise-executor404    return new Promise(async (resolve, reject) => {405      try {406        const unsub = await sign((result: any) => {407          const status = this.getTransactionStatus(result);408409          if (status === this.transactionStatus.SUCCESS) {410            this.logger.log(`${label} successful`);411            unsub();412            resolve({result, status});413          } else if (status === this.transactionStatus.FAIL) {414            let moduleError = null;415416            if (result.hasOwnProperty('dispatchError')) {417              const dispatchError = result['dispatchError'];418419              if (dispatchError) {420                if (dispatchError.isModule) {421                  const modErr = dispatchError.asModule;422                  const errorMeta = dispatchError.registry.findMetaError(modErr);423424                  moduleError = `${errorMeta.section}.${errorMeta.name}`;425                } else {426                  moduleError = dispatchError.toHuman();427                }428              } else {429                this.logger.log(result, this.logger.level.ERROR);430              }431            }432433            this.logger.log(`Something went wrong with ${label}. Status: ${status}`, this.logger.level.ERROR);434            unsub();435            reject({status, moduleError, result});436          }437        });438      } catch (e) {439        this.logger.log(e, this.logger.level.ERROR);440        reject(e);441      }442    });443  }444445  constructApiCall(apiCall: string, params: any[]) {446    if(!apiCall.startsWith('api.')) throw Error(`Invalid api call: ${apiCall}`);447    let call = this.api as any;448    for(const part of apiCall.slice(4).split('.')) {449      call = call[part];450    }451    return call(...params);452  }453454  async executeExtrinsic(sender: TSigner, extrinsic: string, params: any[], expectSuccess=true, options: Partial<SignerOptions>|null = null/*, failureMessage='expected success'*/) {455    if(this.api === null) throw Error('API not initialized');456    if(!extrinsic.startsWith('api.tx.')) throw Error(`${extrinsic} is not transaction`);457458    const startTime = (new Date()).getTime();459    let result: ITransactionResult;460    let events: IEvent[] = [];461    try {462      result = await this.signTransaction(sender, this.constructApiCall(extrinsic, params), options, extrinsic) as ITransactionResult;463      events = this.eventHelper.extractEvents(result);464    }465    catch(e) {466      if(!(e as object).hasOwnProperty('status')) throw e;467      result = e as ITransactionResult;468    }469470    const endTime = (new Date()).getTime();471472    const log = {473      executedAt: endTime,474      executionTime: endTime - startTime,475      type: this.chainLogType.EXTRINSIC,476      status: result.status,477      call: extrinsic,478      signer: this.getSignerAddress(sender),479      params,480    } as IUniqueHelperLog;481482    if(result.status !== this.transactionStatus.SUCCESS && result.moduleError) log.moduleError = result.moduleError;483    if(events.length > 0) log.events = events;484485    this.chainLog.push(log);486487    if(expectSuccess && result.status !== this.transactionStatus.SUCCESS) throw Error(`${result.moduleError}`);488    return result;489  }490491  async callRpc(rpc: string, params?: any[]) {492    if(typeof params === 'undefined') params = [];493    if(this.api === null) throw Error('API not initialized');494    if(!rpc.startsWith('api.rpc.') && !rpc.startsWith('api.query.')) throw Error(`${rpc} is not RPC call`);495496    const startTime = (new Date()).getTime();497    let result;498    let error = null;499    const log = {500      type: this.chainLogType.RPC,501      call: rpc,502      params,503    } as IUniqueHelperLog;504505    try {506      result = await this.constructApiCall(rpc, params);507    }508    catch(e) {509      error = e;510    }511512    const endTime = (new Date()).getTime();513514    log.executedAt = endTime;515    log.status = (error === null ? this.transactionStatus.SUCCESS : this.transactionStatus.FAIL) as 'Fail' | 'Success';516    log.executionTime = endTime - startTime;517518    this.chainLog.push(log);519520    if(error !== null) throw error;521522    return result;523  }524525  getSignerAddress(signer: IKeyringPair | string): string {526    if(typeof signer === 'string') return signer;527    return signer.address;528  }529530  fetchAllPalletNames(): string[] {531    if(this.api === null) throw Error('API not initialized');532    return this.api.runtimeMetadata.asLatest.pallets.map(m => m.name.toString().toLowerCase());533  }534535  fetchMissingPalletNames(requiredPallets: string[]): string[] {536    const palletNames = this.fetchAllPalletNames();537    return requiredPallets.filter(p => !palletNames.includes(p));538  }539}540541542class HelperGroup {543  helper: UniqueHelper;544545  constructor(uniqueHelper: UniqueHelper) {546    this.helper = uniqueHelper;547  }548}549550551class CollectionGroup extends HelperGroup {552  /**553 * Get number of blocks when sponsored transaction is available.554 *555 * @param collectionId ID of collection556 * @param tokenId ID of token557 * @param addressObj address for which the sponsorship is checked558 * @example await getTokenNextSponsored(1, 2, {Substrate: '5DfhbVfww7ThF8q6f3...'});559 * @returns number of blocks or null if sponsorship hasn't been set560 */561  async getTokenNextSponsored(collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<number | null> {562    return (await this.helper.callRpc('api.rpc.unique.nextSponsored', [collectionId, addressObj, tokenId])).toJSON();563  }564565  /**566   * Get the number of created collections.567   *568   * @returns number of created collections569   */570  async getTotalCount(): Promise<number> {571    return (await this.helper.callRpc('api.rpc.unique.collectionStats')).created.toNumber();572  }573574  /**575   * Get information about the collection with additional data,576   * including the number of tokens it contains, its administrators,577   * the normalized address of the collection's owner, and decoded name and description.578   *579   * @param collectionId ID of collection580   * @example await getData(2)581   * @returns collection information object582   */583  async getData(collectionId: number): Promise<{584    id: number;585    name: string;586    description: string;587    tokensCount: number;588    admins: CrossAccountId[];589    normalizedOwner: TSubstrateAccount;590    raw: any591  } | null> {592    const collection = await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId]);593    const humanCollection = collection.toHuman(), collectionData = {594      id: collectionId, name: null, description: null, tokensCount: 0, admins: [],595      raw: humanCollection,596    } as any, jsonCollection = collection.toJSON();597    if (humanCollection === null) return null;598    collectionData.raw.limits = jsonCollection.limits;599    collectionData.raw.permissions = jsonCollection.permissions;600    collectionData.normalizedOwner = this.helper.address.normalizeSubstrate(collectionData.raw.owner);601    for (const key of ['name', 'description']) {602      collectionData[key] = this.helper.util.vec2str(humanCollection[key]);603    }604605    collectionData.tokensCount = (['RFT', 'NFT'].includes(humanCollection.mode))606      ? await this.helper[humanCollection.mode.toLocaleLowerCase() as 'nft' | 'rft'].getLastTokenId(collectionId)607      : 0;608    collectionData.admins = await this.getAdmins(collectionId);609610    return collectionData;611  }612613  /**614   * Get the addresses of the collection's administrators, optionally normalized.615   *616   * @param collectionId ID of collection617   * @param normalize whether to normalize the addresses to the default ss58 format618   * @example await getAdmins(1)619   * @returns array of administrators620   */621  async getAdmins(collectionId: number, normalize = false): Promise<CrossAccountId[]> {622    const admins = (await this.helper.callRpc('api.rpc.unique.adminlist', [collectionId])).toHuman();623624    return normalize625      ? admins.map((address: CrossAccountId) => address.withNormalizedSubstrate())626      : admins;627  }628629  /**630   * Get the addresses added to the collection allow-list, optionally normalized.631   * @param collectionId ID of collection632   * @param normalize whether to normalize the addresses to the default ss58 format633   * @example await getAllowList(1)634   * @returns array of allow-listed addresses635   */636  async getAllowList(collectionId: number, normalize = false): Promise<CrossAccountId[]> {637    const allowListed = (await this.helper.callRpc('api.rpc.unique.allowlist', [collectionId])).toHuman();638    return normalize639      ? allowListed.map((address: CrossAccountId) => address.withNormalizedSubstrate())640      : allowListed;641  }642643  /**644   * Get the effective limits of the collection instead of null for default values645   *646   * @param collectionId ID of collection647   * @example await getEffectiveLimits(2)648   * @returns object of collection limits649   */650  async getEffectiveLimits(collectionId: number): Promise<ICollectionLimits> {651    return (await this.helper.callRpc('api.rpc.unique.effectiveCollectionLimits', [collectionId])).toJSON();652  }653654  /**655   * Burns the collection if the signer has sufficient permissions and collection is empty.656   *657   * @param signer keyring of signer658   * @param collectionId ID of collection659   * @example await helper.collection.burn(aliceKeyring, 3);660   * @returns ```true``` if extrinsic success, otherwise ```false```661   */662  async burn(signer: TSigner, collectionId: number): Promise<boolean> {663    const result = await this.helper.executeExtrinsic(664      signer,665      'api.tx.unique.destroyCollection', [collectionId],666      true,667    );668669    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionDestroyed');670  }671672  /**673   * Sets the sponsor for the collection (Requires the Substrate address). Needs confirmation by the sponsor.674   *675   * @param signer keyring of signer676   * @param collectionId ID of collection677   * @param sponsorAddress Sponsor substrate address678   * @example setSponsor(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...")679   * @returns ```true``` if extrinsic success, otherwise ```false```680   */681  async setSponsor(signer: TSigner, collectionId: number, sponsorAddress: TSubstrateAccount): Promise<boolean> {682    const result = await this.helper.executeExtrinsic(683      signer,684      'api.tx.unique.setCollectionSponsor', [collectionId, sponsorAddress],685      true,686    );687688    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionSponsorSet');689  }690691  /**692   * Confirms consent to sponsor the collection on behalf of the signer.693   *694   * @param signer keyring of signer695   * @param collectionId ID of collection696   * @example confirmSponsorship(aliceKeyring, 10)697   * @returns ```true``` if extrinsic success, otherwise ```false```698   */699  async confirmSponsorship(signer: TSigner, collectionId: number): Promise<boolean> {700    const result = await this.helper.executeExtrinsic(701      signer,702      'api.tx.unique.confirmSponsorship', [collectionId],703      true,704    );705706    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'SponsorshipConfirmed');707  }708709  /**710   * Removes the sponsor of a collection, regardless if it consented or not.711   *712   * @param signer keyring of signer713   * @param collectionId ID of collection714   * @example removeSponsor(aliceKeyring, 10)715   * @returns ```true``` if extrinsic success, otherwise ```false```716   */717  async removeSponsor(signer: TSigner, collectionId: number): Promise<boolean> {718    const result = await this.helper.executeExtrinsic(719      signer,720      'api.tx.unique.removeCollectionSponsor', [collectionId],721      true,722    );723724    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionSponsorRemoved');725  }726727  /**728   * Sets the limits of the collection. At least one limit must be specified for a correct call.729   *730   * @param signer keyring of signer731   * @param collectionId ID of collection732   * @param limits collection limits object733   * @example734   * await setLimits(735   *   aliceKeyring,736   *   10,737   *   {738   *     sponsorTransferTimeout: 0,739   *     ownerCanDestroy: false740   *   }741   * )742   * @returns ```true``` if extrinsic success, otherwise ```false```743   */744  async setLimits(signer: TSigner, collectionId: number, limits: ICollectionLimits): Promise<boolean> {745    const result = await this.helper.executeExtrinsic(746      signer,747      'api.tx.unique.setCollectionLimits', [collectionId, limits],748      true,749    );750751    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionLimitSet');752  }753754  /**755   * Changes the owner of the collection to the new Substrate address.756   *757   * @param signer keyring of signer758   * @param collectionId ID of collection759   * @param ownerAddress substrate address of new owner760   * @example changeOwner(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...")761   * @returns ```true``` if extrinsic success, otherwise ```false```762   */763  async changeOwner(signer: TSigner, collectionId: number, ownerAddress: TSubstrateAccount): Promise<boolean> {764    const result = await this.helper.executeExtrinsic(765      signer,766      'api.tx.unique.changeCollectionOwner', [collectionId, ownerAddress],767      true,768    );769770    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionOwnedChanged');771  }772773  /**774   * Adds a collection administrator.775   *776   * @param signer keyring of signer777   * @param collectionId ID of collection778   * @param adminAddressObj Administrator address (substrate or ethereum)779   * @example addAdmin(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."})780   * @returns ```true``` if extrinsic success, otherwise ```false```781   */782  async addAdmin(signer: TSigner, collectionId: number, adminAddressObj: ICrossAccountId): Promise<boolean> {783    const result = await this.helper.executeExtrinsic(784      signer,785      'api.tx.unique.addCollectionAdmin', [collectionId, adminAddressObj],786      true,787    );788789    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionAdminAdded');790  }791792  /**793   * Removes a collection administrator.794   *795   * @param signer keyring of signer796   * @param collectionId ID of collection797   * @param adminAddressObj Administrator address (substrate or ethereum)798   * @example removeAdmin(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."})799   * @returns ```true``` if extrinsic success, otherwise ```false```800   */801  async removeAdmin(signer: TSigner, collectionId: number, adminAddressObj: ICrossAccountId): Promise<boolean> {802    const result = await this.helper.executeExtrinsic(803      signer,804      'api.tx.unique.removeCollectionAdmin', [collectionId, adminAddressObj],805      true,806    );807808    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionAdminRemoved');809  }810811  /**812   * Check if user is in allow list.813   * 814   * @param collectionId ID of collection815   * @param user Account to check816   * @example await getAdmins(1)817   * @returns is user in allow list818   */819  async allowed(collectionId: number, user: ICrossAccountId): Promise<boolean> {820    return (await this.helper.callRpc('api.rpc.unique.allowed', [collectionId, user])).toJSON();821  }822823  /**824   * Adds an address to allow list825   * @param signer keyring of signer826   * @param collectionId ID of collection827   * @param addressObj address to add to the allow list828   * @returns ```true``` if extrinsic success, otherwise ```false```829   */830  async addToAllowList(signer: TSigner, collectionId: number, addressObj: ICrossAccountId): Promise<boolean> {831    const result = await this.helper.executeExtrinsic(832      signer,833      'api.tx.unique.addToAllowList', [collectionId, addressObj],834      true,835    );836837    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'AllowListAddressAdded');838  }839840  /**841   * Removes an address from allow list842   *843   * @param signer keyring of signer844   * @param collectionId ID of collection845   * @param addressObj address to remove from the allow list846   * @returns ```true``` if extrinsic success, otherwise ```false```847   */848  async removeFromAllowList(signer: TSigner, collectionId: number, addressObj: ICrossAccountId): Promise<boolean> {849    const result = await this.helper.executeExtrinsic(850      signer,851      'api.tx.unique.removeFromAllowList', [collectionId, addressObj],852      true,853    );854855    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'AllowListAddressRemoved');856  }857858  /**859   * Sets onchain permissions for selected collection.860   *861   * @param signer keyring of signer862   * @param collectionId ID of collection863   * @param permissions collection permissions object864   * @example setPermissions(aliceKeyring, 10, {access:'AllowList', mintMode: true, nesting: {collectionAdmin: true, tokenOwner: true}});865   * @returns ```true``` if extrinsic success, otherwise ```false```866   */867  async setPermissions(signer: TSigner, collectionId: number, permissions: ICollectionPermissions): Promise<boolean> {868    const result = await this.helper.executeExtrinsic(869      signer,870      'api.tx.unique.setCollectionPermissions', [collectionId, permissions],871      true,872    );873874    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionPermissionSet');875  }876877  /**878   * Enables nesting for selected collection. If `restricted` set, you can nest only tokens from specified collections.879   *880   * @param signer keyring of signer881   * @param collectionId ID of collection882   * @param permissions nesting permissions object883   * @example enableNesting(aliceKeyring, 10, {collectionAdmin: true, tokenOwner: true});884   * @returns ```true``` if extrinsic success, otherwise ```false```885   */886  async enableNesting(signer: TSigner, collectionId: number, permissions: INestingPermissions): Promise<boolean> {887    return await this.setPermissions(signer, collectionId, {nesting: permissions});888  }889890  /**891   * Disables nesting for selected collection.892   *893   * @param signer keyring of signer894   * @param collectionId ID of collection895   * @example disableNesting(aliceKeyring, 10);896   * @returns ```true``` if extrinsic success, otherwise ```false```897   */898  async disableNesting(signer: TSigner, collectionId: number): Promise<boolean> {899    return await this.setPermissions(signer, collectionId, {nesting: {tokenOwner: false, collectionAdmin: false}});900  }901902  /**903   * Sets onchain properties to the collection.904   *905   * @param signer keyring of signer906   * @param collectionId ID of collection907   * @param properties array of property objects908   * @example setProperties(aliceKeyring, 10, [{key: "gender", value: "male"}]);909   * @returns ```true``` if extrinsic success, otherwise ```false```910   */911  async setProperties(signer: TSigner, collectionId: number, properties: IProperty[]): Promise<boolean> {912    const result = await this.helper.executeExtrinsic(913      signer,914      'api.tx.unique.setCollectionProperties', [collectionId, properties],915      true,916    );917918    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPropertySet');919  }920921  /**922   * Get collection properties.923   * 924   * @param collectionId ID of collection925   * @param propertyKeys optionally filter the returned properties to only these keys926   * @example getProperties(1219, ['location', 'date', 'time', 'isParadise']);927   * @returns array of key-value pairs928   */929  async getProperties(collectionId: number, propertyKeys: string[] | null = null): Promise<IProperty[]> {930    return (await this.helper.callRpc('api.rpc.unique.collectionProperties', [collectionId, ...(propertyKeys === null ? [] : [propertyKeys])])).toHuman();931  }932933  /**934   * Deletes onchain properties from the collection.935   *936   * @param signer keyring of signer937   * @param collectionId ID of collection938   * @param propertyKeys array of property keys to delete939   * @example deleteProperties(aliceKeyring, 10, ["gender", "age"]);940   * @returns ```true``` if extrinsic success, otherwise ```false```941   */942  async deleteProperties(signer: TSigner, collectionId: number, propertyKeys: string[]): Promise<boolean> {943    const result = await this.helper.executeExtrinsic(944      signer,945      'api.tx.unique.deleteCollectionProperties', [collectionId, propertyKeys],946      true,947    );948949    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPropertyDeleted');950  }951952  /**953   * Changes the owner of the token.954   *955   * @param signer keyring of signer956   * @param collectionId ID of collection957   * @param tokenId ID of token958   * @param addressObj address of a new owner959   * @param amount amount of tokens to be transfered. For NFT must be set to 1n960   * @example transferToken(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."})961   * @returns true if the token success, otherwise false962   */963  async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId, amount=1n): Promise<boolean> {964    const result = await this.helper.executeExtrinsic(965      signer,966      'api.tx.unique.transfer', [addressObj, collectionId, tokenId, amount],967      true, // `Unable to transfer token #${tokenId} from collection #${collectionId}`,968    );969970    return this.helper.util.isTokenTransferSuccess(result.result.events, collectionId, tokenId, {Substrate: typeof signer === 'string' ? signer : signer.address}, addressObj, amount);971  }972973  /**974   *975   * Change ownership of a token(s) on behalf of the owner.976   *977   * @param signer keyring of signer978   * @param collectionId ID of collection979   * @param tokenId ID of token980   * @param fromAddressObj address on behalf of which the token will be sent981   * @param toAddressObj new token owner982   * @param amount amount of tokens to be transfered. For NFT must be set to 1n983   * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg"}, {Ethereum: "0x9F0583DbB85..."})984   * @returns true if the token success, otherwise false985   */986  async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {987    const result = await this.helper.executeExtrinsic(988      signer,989      'api.tx.unique.transferFrom', [fromAddressObj, toAddressObj, collectionId, tokenId, amount],990      true, // `Unable to transfer token #${tokenId} from collection #${collectionId}`,991    );992    return this.helper.util.isTokenTransferSuccess(result.result.events, collectionId, tokenId, fromAddressObj, toAddressObj, amount);993  }994995  /**996   *997   * Destroys a concrete instance of NFT/RFT or burns a specified amount of fungible tokens.998   *999   * @param signer keyring of signer1000   * @param collectionId ID of collection1001   * @param tokenId ID of token1002   * @param amount amount of tokens to be burned. For NFT must be set to 1n1003   * @example burnToken(aliceKeyring, 10, 5);1004   * @returns ```true``` and burnt token number is extrinsic success. Otherwise ```false``` and ```null```1005   */1006  async burnToken(signer: TSigner, collectionId: number, tokenId: number, amount=1n): Promise<{1007    success: boolean,1008    token: number | null1009  }> {1010    const burnResult = await this.helper.executeExtrinsic(1011      signer,1012      'api.tx.unique.burnItem', [collectionId, tokenId, amount],1013      true, // `Unable to burn token for ${label}`,1014    );1015    const burnedTokens = this.helper.util.extractTokensFromBurnResult(burnResult);1016    if (burnedTokens.tokens.length > 1) throw Error('Burned multiple tokens');1017    return {success: burnedTokens.success, token: burnedTokens.tokens.length > 0 ? burnedTokens.tokens[0] : null};1018  }10191020  /**1021   * Destroys a concrete instance of NFT on behalf of the owner1022   *1023   * @param signer keyring of signer1024   * @param collectionId ID of collection1025   * @param tokenId ID of token1026   * @param fromAddressObj address on behalf of which the token will be burnt1027   * @param amount amount of tokens to be burned. For NFT must be set to 1n1028   * @example burnTokenFrom(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."}, 5, {Ethereum: "0x9F0583DbB85..."})1029   * @returns ```true``` if extrinsic success, otherwise ```false```1030   */1031  async burnTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1032    const burnResult = await this.helper.executeExtrinsic(1033      signer,1034      'api.tx.unique.burnFrom', [collectionId, fromAddressObj, tokenId, amount],1035      true, // `Unable to burn token from for ${label}`,1036    );1037    const burnedTokens = this.helper.util.extractTokensFromBurnResult(burnResult);1038    return burnedTokens.success && burnedTokens.tokens.length > 0;1039  }10401041  /**1042   * Set, change, or remove approved address to transfer the ownership of the NFT.1043   *1044   * @param signer keyring of signer1045   * @param collectionId ID of collection1046   * @param tokenId ID of token1047   * @param toAddressObj Substrate or Ethereum address which gets approved use of the signer's tokens1048   * @param amount amount of token to be approved. For NFT must be set to 1n1049   * @returns ```true``` if extrinsic success, otherwise ```false```1050   */1051  async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {1052    const approveResult = await this.helper.executeExtrinsic(1053      signer,1054      'api.tx.unique.approve', [toAddressObj, collectionId, tokenId, amount],1055      true, // `Unable to approve token for ${label}`,1056    );10571058    return this.helper.util.findCollectionInEvents(approveResult.result.events, collectionId, 'common', 'Approved');1059  }10601061  /**1062   * Get the amount of token pieces approved to transfer or burn. Normally 0.1063   *1064   * @param collectionId ID of collection1065   * @param tokenId ID of token1066   * @param toAccountObj address which is approved to use token pieces1067   * @param fromAccountObj address which may have allowed the use of its owned tokens1068   * @example getTokenApprovedPieces(10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, {Substrate: "5ERZNF88Mm7UGfPP3mdG..."})1069   * @returns number of approved to transfer pieces1070   */1071  async getTokenApprovedPieces(collectionId: number, tokenId: number, toAccountObj: ICrossAccountId, fromAccountObj: ICrossAccountId): Promise<bigint> {1072    return (await this.helper.callRpc('api.rpc.unique.allowance', [collectionId, fromAccountObj, toAccountObj, tokenId])).toBigInt();1073  }10741075  /**1076   * Get the last created token ID in a collection1077   *1078   * @param collectionId ID of collection1079   * @example getLastTokenId(10);1080   * @returns id of the last created token1081   */1082  async getLastTokenId(collectionId: number): Promise<number> {1083    return (await this.helper.callRpc('api.rpc.unique.lastTokenId', [collectionId])).toNumber();1084  }10851086  /**1087   * Check if token exists1088   *1089   * @param collectionId ID of collection1090   * @param tokenId ID of token1091   * @example isTokenExists(10, 20);1092   * @returns true if the token exists, otherwise false1093   */1094  async isTokenExists(collectionId: number, tokenId: number): Promise<boolean> {1095    return (await this.helper.callRpc('api.rpc.unique.tokenExists', [collectionId, tokenId])).toJSON();1096  }1097}10981099class NFTnRFT extends CollectionGroup {1100  /**1101   * Get tokens owned by account1102   *1103   * @param collectionId ID of collection1104   * @param addressObj tokens owner1105   * @example getTokensByAddress(10, {Substrate: "5DyN4Y92vZCjv38fg..."})1106   * @returns array of token ids owned by account1107   */1108  async getTokensByAddress(collectionId: number, addressObj: ICrossAccountId): Promise<number[]> {1109    return (await this.helper.callRpc('api.rpc.unique.accountTokens', [collectionId, addressObj])).toJSON();1110  }11111112  /**1113   * Get token data1114   *1115   * @param collectionId ID of collection1116   * @param tokenId ID of token1117   * @param propertyKeys optionally filter the token properties to only these keys1118   * @param blockHashAt optionally query the data at some block with this hash1119   * @example getToken(10, 5);1120   * @returns human readable token data1121   */1122  async getToken(collectionId: number, tokenId: number, propertyKeys: string[] = [], blockHashAt?: string): Promise<{1123    properties: IProperty[];1124    owner: CrossAccountId;1125    normalizedOwner: CrossAccountId;1126  }| null> {1127    let tokenData;1128    if(typeof blockHashAt === 'undefined') {1129      tokenData = await this.helper.callRpc('api.rpc.unique.tokenData', [collectionId, tokenId]);1130    }1131    else {1132      if(propertyKeys.length == 0) {1133        const collection = (await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId])).toHuman();1134        if(!collection) return null;1135        propertyKeys = collection.tokenPropertyPermissions.map((x: ITokenPropertyPermission) => x.key);1136      }1137      tokenData = await this.helper.callRpc('api.rpc.unique.tokenData', [collectionId, tokenId, propertyKeys, blockHashAt]);1138    }1139    tokenData = tokenData.toHuman();1140    if (tokenData === null || tokenData.owner === null) return null;1141    const owner = {} as any;1142    for (const key of Object.keys(tokenData.owner)) {1143      owner[key.toLocaleLowerCase()] = new CrossAccountId(tokenData.owner[key]).withNormalizedSubstrate();1144    }1145    tokenData.normalizedOwner = CrossAccountId.fromLowerCaseKeys(owner);1146    return tokenData;1147  }11481149  /**1150   * Set permissions to change token properties1151   *1152   * @param signer keyring of signer1153   * @param collectionId ID of collection1154   * @param permissions permissions to change a property by the collection admin or token owner1155   * @example setTokenPropertyPermissions(1156   *   aliceKeyring, 10, [{key: "gender", permission: {tokenOwner: true, mutable: true, collectionAdmin: true}}]1157   * )1158   * @returns true if extrinsic success otherwise false1159   */1160  async setTokenPropertyPermissions(signer: TSigner, collectionId: number, permissions: ITokenPropertyPermission[]): Promise<boolean> {1161    const result = await this.helper.executeExtrinsic(1162      signer,1163      'api.tx.unique.setTokenPropertyPermissions', [collectionId, permissions],1164      true,1165    );11661167    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'PropertyPermissionSet');1168  }11691170  /**1171   * Get token property permissions.1172   * 1173   * @param collectionId ID of collection1174   * @param propertyKeys optionally filter the returned property permissions to only these keys1175   * @example getPropertyPermissions(1219, ['location', 'date', 'time', 'isParadise']);1176   * @returns array of key-permission pairs1177   */1178  async getPropertyPermissions(collectionId: number, propertyKeys: string[] | null = null): Promise<ITokenPropertyPermission[]> {1179    return (await this.helper.callRpc('api.rpc.unique.propertyPermissions', [collectionId, ...(propertyKeys === null ? [] : [propertyKeys])])).toHuman();1180  }11811182  /**1183   * Set token properties1184   *1185   * @param signer keyring of signer1186   * @param collectionId ID of collection1187   * @param tokenId ID of token1188   * @param properties key-value pairs of metadata which to add to a token. Keys must be permitted in the collection1189   * @example setTokenProperties(aliceKeyring, 10, 5, [{key: "gender", value: "female"}, {key: "age", value: "23"}])1190   * @returns ```true``` if extrinsic success, otherwise ```false```1191   */1192  async setTokenProperties(signer: TSigner, collectionId: number, tokenId: number, properties: IProperty[]): Promise<boolean> {1193    const result = await this.helper.executeExtrinsic(1194      signer,1195      'api.tx.unique.setTokenProperties', [collectionId, tokenId, properties],1196      true,1197    );11981199    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'TokenPropertySet');1200  }12011202  /**1203   * Get properties, metadata assigned to a token.1204   * 1205   * @param collectionId ID of collection1206   * @param tokenId ID of token1207   * @param propertyKeys optionally filter the returned properties to only these keys1208   * @example getTokenProperties(1219, ['location', 'date', 'time', 'isParadise']);1209   * @returns array of key-value pairs1210   */1211  async getTokenProperties(collectionId: number, tokenId: number, propertyKeys: string[] | null = null): Promise<IProperty[]> {1212    return (await this.helper.callRpc('api.rpc.unique.tokenProperties', [collectionId, tokenId, ...(propertyKeys === null ? [] : [propertyKeys])])).toHuman();1213  }12141215  /**1216   * Delete the provided properties of a token1217   * @param signer keyring of signer1218   * @param collectionId ID of collection1219   * @param tokenId ID of token1220   * @param propertyKeys property keys to be deleted1221   * @example deleteTokenProperties(aliceKeyring, 10, 5, ["gender", "age"])1222   * @returns ```true``` if extrinsic success, otherwise ```false```1223   */1224  async deleteTokenProperties(signer: TSigner, collectionId: number, tokenId: number, propertyKeys: string[]): Promise<boolean> {1225    const result = await this.helper.executeExtrinsic(1226      signer,1227      'api.tx.unique.deleteTokenProperties', [collectionId, tokenId, propertyKeys],1228      true,1229    );12301231    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'TokenPropertyDeleted');1232  }12331234  /**1235   * Mint new collection1236   *1237   * @param signer keyring of signer1238   * @param collectionOptions basic collection options and properties1239   * @param mode NFT or RFT type of a collection1240   * @example mintCollection(aliceKeyring, {name: 'New', description: "New collection", tokenPrefix: "NEW"}, "NFT")1241   * @returns object of the created collection1242   */1243  async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions, mode: 'NFT' | 'RFT'): Promise<UniqueBaseCollection> {1244    collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; // Clone object1245    collectionOptions.mode = (mode === 'NFT') ? {nft: null} : {refungible: null};1246    for (const key of ['name', 'description', 'tokenPrefix']) {1247      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);1248    }1249    const creationResult = await this.helper.executeExtrinsic(1250      signer,1251      'api.tx.unique.createCollectionEx', [collectionOptions],1252      true, // errorLabel,1253    );1254    return this.getCollectionObject(this.helper.util.extractCollectionIdFromCreationResult(creationResult));1255  }12561257  getCollectionObject(_collectionId: number): any {1258    return null;1259  }12601261  getTokenObject(_collectionId: number, _tokenId: number): any {1262    return null;1263  }1264}126512661267class NFTGroup extends NFTnRFT {1268  /**1269   * Get collection object1270   * @param collectionId ID of collection1271   * @example getCollectionObject(2);1272   * @returns instance of UniqueNFTCollection1273   */1274  getCollectionObject(collectionId: number): UniqueNFTCollection {1275    return new UniqueNFTCollection(collectionId, this.helper);1276  }12771278  /**1279   * Get token object1280   * @param collectionId ID of collection1281   * @param tokenId ID of token1282   * @example getTokenObject(10, 5);1283   * @returns instance of UniqueNFTToken1284   */1285  getTokenObject(collectionId: number, tokenId: number): UniqueNFToken {1286    return new UniqueNFToken(tokenId, this.getCollectionObject(collectionId));1287  }12881289  /**1290   * Get token's owner1291   * @param collectionId ID of collection1292   * @param tokenId ID of token1293   * @param blockHashAt optionally query the data at the block with this hash1294   * @example getTokenOwner(10, 5);1295   * @returns Address in CrossAccountId format, e.g. {Substrate: "5DnSF6RRjwteE3BrCj..."}1296   */1297  async getTokenOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<CrossAccountId> {1298    let owner;1299    if (typeof blockHashAt === 'undefined') {1300      owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId]);1301    } else {1302      owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId, blockHashAt]);1303    }1304    return CrossAccountId.fromLowerCaseKeys(owner.toJSON());1305  }13061307  /**1308   * Is token approved to transfer1309   * @param collectionId ID of collection1310   * @param tokenId ID of token1311   * @param toAccountObj address to be approved1312   * @returns ```true``` if extrinsic success, otherwise ```false```1313   */1314  async isTokenApproved(collectionId: number, tokenId: number, toAccountObj: ICrossAccountId): Promise<boolean> {1315    return (await this.getTokenApprovedPieces(collectionId, tokenId, toAccountObj, await this.getTokenOwner(collectionId, tokenId))) === 1n;1316  }13171318  /**1319   * Changes the owner of the token.1320   *1321   * @param signer keyring of signer1322   * @param collectionId ID of collection1323   * @param tokenId ID of token1324   * @param addressObj address of a new owner1325   * @example transferToken(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."})1326   * @returns ```true``` if extrinsic success, otherwise ```false```1327   */1328  async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<boolean> {1329    return await super.transferToken(signer, collectionId, tokenId, addressObj, 1n);1330  }13311332  /**1333   *1334   * Change ownership of a NFT on behalf of the owner.1335   *1336   * @param signer keyring of signer1337   * @param collectionId ID of collection1338   * @param tokenId ID of token1339   * @param fromAddressObj address on behalf of which the token will be sent1340   * @param toAddressObj new token owner1341   * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, {Ethereum: "0x9F0583DbB85..."})1342   * @returns ```true``` if extrinsic success, otherwise ```false```1343   */1344  async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId): Promise<boolean> {1345    return await super.transferTokenFrom(signer, collectionId, tokenId, fromAddressObj, toAddressObj, 1n);1346  }13471348  /**1349   * Recursively find the address that owns the token1350   * @param collectionId ID of collection1351   * @param tokenId ID of token1352   * @param blockHashAt1353   * @example getTokenTopmostOwner(10, 5);1354   * @returns address in CrossAccountId format, e.g. {Substrate: "5DyN4Y92vZCjv38fg..."}1355   */1356  async getTokenTopmostOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<CrossAccountId | null> {1357    let owner;1358    if (typeof blockHashAt === 'undefined') {1359      owner = await this.helper.callRpc('api.rpc.unique.topmostTokenOwner', [collectionId, tokenId]);1360    } else {1361      owner = await this.helper.callRpc('api.rpc.unique.topmostTokenOwner', [collectionId, tokenId, blockHashAt]);1362    }13631364    if (owner === null) return null;13651366    return owner.toHuman();1367  }13681369  /**1370   * Get tokens nested in the provided token1371   * @param collectionId ID of collection1372   * @param tokenId ID of token1373   * @param blockHashAt optionally query the data at the block with this hash1374   * @example getTokenChildren(10, 5);1375   * @returns tokens whose depth of nesting is <= 51376   */1377  async getTokenChildren(collectionId: number, tokenId: number, blockHashAt?: string): Promise<IToken[]> {1378    let children;1379    if(typeof blockHashAt === 'undefined') {1380      children = await this.helper.callRpc('api.rpc.unique.tokenChildren', [collectionId, tokenId]);1381    } else {1382      children = await this.helper.callRpc('api.rpc.unique.tokenChildren', [collectionId, tokenId, blockHashAt]);1383    }13841385    return children.toJSON().map((x: any) => {1386      return {collectionId: x.collection, tokenId: x.token};1387    });1388  }13891390  /**1391   * Nest one token into another1392   * @param signer keyring of signer1393   * @param tokenObj token to be nested1394   * @param rootTokenObj token to be parent1395   * @example nestToken(aliceKeyring, {collectionId: 10, tokenId: 5}, {collectionId: 10, tokenId: 4});1396   * @returns ```true``` if extrinsic success, otherwise ```false```1397   */1398  async nestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken): Promise<boolean> {1399    const rootTokenAddress = this.helper.util.getTokenAccount(rootTokenObj);1400    const result = await this.transferToken(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress);1401    if(!result) {1402      throw Error('Unable to nest token!');1403    }1404    return result;1405  }14061407  /**1408   * Remove token from nested state1409   * @param signer keyring of signer1410   * @param tokenObj token to unnest1411   * @param rootTokenObj parent of a token1412   * @param toAddressObj address of a new token owner1413   * @example unnestToken(aliceKeyring, {collectionId: 10, tokenId: 5}, {collectionId: 10, tokenId: 4}, {Substrate: "5DyN4Y92vZCjv38fg..."});1414   * @returns ```true``` if extrinsic success, otherwise ```false```1415   */1416  async unnestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken, toAddressObj: ICrossAccountId): Promise<boolean> {1417    const rootTokenAddress = this.helper.util.getTokenAccount(rootTokenObj);1418    const result = await this.transferTokenFrom(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress, toAddressObj);1419    if(!result) {1420      throw Error('Unable to unnest token!');1421    }1422    return result;1423  }14241425  /**1426   * Mint new collection1427   * @param signer keyring of signer1428   * @param collectionOptions Collection options1429   * @example1430   * mintCollection(aliceKeyring, {1431   *   name: 'New',1432   *   description: 'New collection',1433   *   tokenPrefix: 'NEW',1434   * })1435   * @returns object of the created collection1436   */1437  async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}): Promise<UniqueNFTCollection> {1438    return await super.mintCollection(signer, collectionOptions, 'NFT') as UniqueNFTCollection;1439  }14401441  /**1442   * Mint new token1443   * @param signer keyring of signer1444   * @param data token data1445   * @returns created token object1446   */1447  async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; properties?: IProperty[]; }): Promise<UniqueNFToken> {1448    const creationResult = await this.helper.executeExtrinsic(1449      signer,1450      'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {1451        nft: {1452          properties: data.properties,1453        },1454      }],1455      true,1456    );1457    const createdTokens = this.helper.util.extractTokensFromCreationResult(creationResult);1458    if (createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');1459    if (createdTokens.tokens.length < 1) throw Error('No tokens minted');1460    return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);1461  }14621463  /**1464   * Mint multiple NFT tokens1465   * @param signer keyring of signer1466   * @param collectionId ID of collection1467   * @param tokens array of tokens with owner and properties1468   * @example1469   * mintMultipleTokens(aliceKeyring, 10, [{1470   *     owner: {Substrate: "5DyN4Y92vZCjv38fg..."},1471   *     properties: [{key: "gender", value: "male"},{key: "age", value: "45"}],1472   *   },{1473   *     owner: {Ethereum: "0x9F0583DbB855d..."},1474   *     properties: [{key: "gender", value: "female"},{key: "age", value: "22"}],1475   * }]);1476   * @returns ```true``` if extrinsic success, otherwise ```false```1477   */1478  async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: {owner: ICrossAccountId, properties?: IProperty[]}[]): Promise<UniqueNFToken[]> {1479    const creationResult = await this.helper.executeExtrinsic(1480      signer,1481      'api.tx.unique.createMultipleItemsEx', [collectionId, {NFT: tokens}],1482      true,1483    );1484    const collection = this.getCollectionObject(collectionId);1485    return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1486  }14871488  /**1489   * Mint multiple NFT tokens with one owner1490   * @param signer keyring of signer1491   * @param collectionId ID of collection1492   * @param owner tokens owner1493   * @param tokens array of tokens with owner and properties1494   * @example1495   * mintMultipleTokensWithOneOwner(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...", [{1496   *   properties: [{1497   *   key: "gender",1498   *   value: "female",1499   *  },{1500   *   key: "age",1501   *   value: "33",1502   *  }],1503   * }]);1504   * @returns array of newly created tokens1505   */1506  async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {properties?: IProperty[]}[]): Promise<UniqueNFToken[]> {1507    const rawTokens = [];1508    for (const token of tokens) {1509      const raw = {NFT: {properties: token.properties}};1510      rawTokens.push(raw);1511    }1512    const creationResult = await this.helper.executeExtrinsic(1513      signer,1514      'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1515      true,1516    );1517    const collection = this.getCollectionObject(collectionId);1518    return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1519  }15201521  /**1522   * Set, change, or remove approved address to transfer the ownership of the NFT.1523   *1524   * @param signer keyring of signer1525   * @param collectionId ID of collection1526   * @param tokenId ID of token1527   * @param toAddressObj address to approve1528   * @example approveToken(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."})1529   * @returns ```true``` if extrinsic success, otherwise ```false```1530   */1531  async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId) {1532    return super.approveToken(signer, collectionId, tokenId, toAddressObj, 1n);1533  }1534}153515361537class RFTGroup extends NFTnRFT {1538  /**1539   * Get collection object1540   * @param collectionId ID of collection1541   * @example getCollectionObject(2);1542   * @returns instance of UniqueRFTCollection1543   */1544  getCollectionObject(collectionId: number): UniqueRFTCollection {1545    return new UniqueRFTCollection(collectionId, this.helper);1546  }15471548  /**1549   * Get token object1550   * @param collectionId ID of collection1551   * @param tokenId ID of token1552   * @example getTokenObject(10, 5);1553   * @returns instance of UniqueNFTToken1554   */1555  getTokenObject(collectionId: number, tokenId: number): UniqueRFToken {1556    return new UniqueRFToken(tokenId, this.getCollectionObject(collectionId));1557  }15581559  /**1560   * Get top 10 token owners with the largest number of pieces1561   * @param collectionId ID of collection1562   * @param tokenId ID of token1563   * @example getTokenTop10Owners(10, 5);1564   * @returns array of top 10 owners1565   */1566  async getTokenTop10Owners(collectionId: number, tokenId: number): Promise<CrossAccountId[]> {1567    return (await this.helper.callRpc('api.rpc.unique.tokenOwners', [collectionId, tokenId])).toJSON().map(CrossAccountId.fromLowerCaseKeys);1568  }15691570  /**1571   * Get number of pieces owned by address1572   * @param collectionId ID of collection1573   * @param tokenId ID of token1574   * @param addressObj address token owner1575   * @example getTokenBalance(10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."});1576   * @returns number of pieces ownerd by address1577   */1578  async getTokenBalance(collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<bigint> {1579    return (await this.helper.callRpc('api.rpc.unique.balance', [collectionId, addressObj, tokenId])).toBigInt();1580  }15811582  /**1583   * Transfer pieces of token to another address1584   * @param signer keyring of signer1585   * @param collectionId ID of collection1586   * @param tokenId ID of token1587   * @param addressObj address of a new owner1588   * @param amount number of pieces to be transfered1589   * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, 2000n)1590   * @returns ```true``` if extrinsic success, otherwise ```false```1591   */1592  async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId, amount=1n): Promise<boolean> {1593    return await super.transferToken(signer, collectionId, tokenId, addressObj, amount);1594  }15951596  /**1597   * Change ownership of some pieces of RFT on behalf of the owner.1598   * @param signer keyring of signer1599   * @param collectionId ID of collection1600   * @param tokenId ID of token1601   * @param fromAddressObj address on behalf of which the token will be sent1602   * @param toAddressObj new token owner1603   * @param amount number of pieces to be transfered1604   * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, {Substrate: "5DfhbVfww7ThF8q6f3i..."}, 2000n)1605   * @returns ```true``` if extrinsic success, otherwise ```false```1606   */1607  async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1608    return await super.transferTokenFrom(signer, collectionId, tokenId, fromAddressObj, toAddressObj, amount);1609  }16101611  /**1612   * Mint new collection1613   * @param signer keyring of signer1614   * @param collectionOptions Collection options1615   * @example1616   * mintCollection(aliceKeyring, {1617   *   name: 'New',1618   *   description: 'New collection',1619   *   tokenPrefix: 'NEW',1620   * })1621   * @returns object of the created collection1622   */1623  async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}): Promise<UniqueRFTCollection> {1624    return await super.mintCollection(signer, collectionOptions, 'RFT') as UniqueRFTCollection;1625  }16261627  /**1628   * Mint new token1629   * @param signer keyring of signer1630   * @param data token data1631   * @example mintToken(aliceKeyring, {collectionId: 10, owner: {Substrate: '5GHoZe9c73RYbVzq...'}, pieces: 10000n});1632   * @returns created token object1633   */1634  async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; pieces: bigint; properties?: IProperty[]; }): Promise<UniqueRFToken> {1635    const creationResult = await this.helper.executeExtrinsic(1636      signer,1637      'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {1638        refungible: {1639          pieces: data.pieces,1640          properties: data.properties,1641        },1642      }],1643      true,1644    );1645    const createdTokens = this.helper.util.extractTokensFromCreationResult(creationResult);1646    if (createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');1647    if (createdTokens.tokens.length < 1) throw Error('No tokens minted');1648    return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);1649  }16501651  async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: {owner: ICrossAccountId, pieces: bigint, properties?: IProperty[]}[]): Promise<UniqueRFToken[]> {1652    throw Error('Not implemented');1653    const creationResult = await this.helper.executeExtrinsic(1654      signer,1655      'api.tx.unique.createMultipleItemsEx', [collectionId, {RefungibleMultipleOwners: tokens}],1656      true, // `Unable to mint RFT tokens for ${label}`,1657    );1658    const collection = this.getCollectionObject(collectionId);1659    return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1660  }16611662  /**1663   * Mint multiple RFT tokens with one owner1664   * @param signer keyring of signer1665   * @param collectionId ID of collection1666   * @param owner tokens owner1667   * @param tokens array of tokens with properties and pieces1668   * @example mintMultipleTokensWithOneOwner(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, [{pieces: 100000n, properties: [{key: "gender", value: "male"}]}]);1669   * @returns array of newly created RFT tokens1670   */1671  async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {pieces: bigint, properties?: IProperty[]}[]): Promise<UniqueRFToken[]> {1672    const rawTokens = [];1673    for (const token of tokens) {1674      const raw = {ReFungible: {pieces: token.pieces, properties: token.properties}};1675      rawTokens.push(raw);1676    }1677    const creationResult = await this.helper.executeExtrinsic(1678      signer,1679      'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1680      true,1681    );1682    const collection = this.getCollectionObject(collectionId);1683    return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1684  }16851686  /**1687   * Destroys a concrete instance of RFT.1688   * @param signer keyring of signer1689   * @param collectionId ID of collection1690   * @param tokenId ID of token1691   * @param amount number of pieces to be burnt1692   * @example burnToken(aliceKeyring, 10, 5);1693   * @returns ```true``` and burnt token number, if extrinsic is successful. Otherwise ```false``` and ```null```1694   */1695  async burnToken(signer: IKeyringPair, collectionId: number, tokenId: number, amount=1n): Promise<{ success: boolean; token: number | null; }> {1696    return await super.burnToken(signer, collectionId, tokenId, amount);1697  }16981699  /**1700   * Destroys a concrete instance of RFT on behalf of the owner.1701   * @param signer keyring of signer1702   * @param collectionId ID of collection1703   * @param tokenId ID of token1704   * @param fromAddressObj address on behalf of which the token will be burnt1705   * @param amount number of pieces to be burnt1706   * @example burnTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, 2n)1707   * @returns ```true``` if extrinsic success, otherwise ```false```1708   */1709  async burnTokenFrom(signer: IKeyringPair, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1710    return await super.burnTokenFrom(signer, collectionId, tokenId, fromAddressObj, amount);1711  }17121713  /**1714   * Set, change, or remove approved address to transfer the ownership of the RFT.1715   *1716   * @param signer keyring of signer1717   * @param collectionId ID of collection1718   * @param tokenId ID of token1719   * @param toAddressObj address to approve1720   * @param amount number of pieces to be approved1721   * @example approveToken(aliceKeyring, 10, 5, {Substrate: "5GHoZe9c73RYbVzq..."}, "", 10000n);1722   * @returns true if the token success, otherwise false1723   */1724  async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {1725    return super.approveToken(signer, collectionId, tokenId, toAddressObj, amount);1726  }17271728  /**1729   * Get total number of pieces1730   * @param collectionId ID of collection1731   * @param tokenId ID of token1732   * @example getTokenTotalPieces(10, 5);1733   * @returns number of pieces1734   */1735  async getTokenTotalPieces(collectionId: number, tokenId: number): Promise<bigint> {1736    return (await this.helper.callRpc('api.rpc.unique.totalPieces', [collectionId, tokenId])).unwrap().toBigInt();1737  }17381739  /**1740   * Change number of token pieces. Signer must be the owner of all token pieces.1741   * @param signer keyring of signer1742   * @param collectionId ID of collection1743   * @param tokenId ID of token1744   * @param amount new number of pieces1745   * @example repartitionToken(aliceKeyring, 10, 5, 12345n);1746   * @returns true if the repartion was success, otherwise false1747   */1748  async repartitionToken(signer: TSigner, collectionId: number, tokenId: number, amount: bigint): Promise<boolean> {1749    const currentAmount = await this.getTokenTotalPieces(collectionId, tokenId);1750    const repartitionResult = await this.helper.executeExtrinsic(1751      signer,1752      'api.tx.unique.repartition', [collectionId, tokenId, amount],1753      true,1754    );1755    if(currentAmount < amount) return this.helper.util.findCollectionInEvents(repartitionResult.result.events, collectionId, 'common', 'ItemCreated');1756    return this.helper.util.findCollectionInEvents(repartitionResult.result.events, collectionId, 'common', 'ItemDestroyed');1757  }1758}175917601761class FTGroup extends CollectionGroup {1762  /**1763   * Get collection object1764   * @param collectionId ID of collection1765   * @example getCollectionObject(2);1766   * @returns instance of UniqueFTCollection1767   */1768  getCollectionObject(collectionId: number): UniqueFTCollection {1769    return new UniqueFTCollection(collectionId, this.helper);1770  }17711772  /**1773   * Mint new fungible collection1774   * @param signer keyring of signer1775   * @param collectionOptions Collection options1776   * @param decimalPoints number of token decimals1777   * @example1778   * mintCollection(aliceKeyring, {1779   *   name: 'New',1780   *   description: 'New collection',1781   *   tokenPrefix: 'NEW',1782   * }, 18)1783   * @returns newly created fungible collection1784   */1785  async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}, decimalPoints = 0): Promise<UniqueFTCollection> {1786    collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; // Clone object1787    if(collectionOptions.tokenPropertyPermissions) throw Error('Fungible collections has no tokenPropertyPermissions');1788    collectionOptions.mode = {fungible: decimalPoints};1789    for (const key of ['name', 'description', 'tokenPrefix']) {1790      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);1791    }1792    const creationResult = await this.helper.executeExtrinsic(1793      signer,1794      'api.tx.unique.createCollectionEx', [collectionOptions],1795      true,1796    );1797    return this.getCollectionObject(this.helper.util.extractCollectionIdFromCreationResult(creationResult));1798  }17991800  /**1801   * Mint tokens1802   * @param signer keyring of signer1803   * @param collectionId ID of collection1804   * @param owner address owner of new tokens1805   * @param amount amount of tokens to be meanted1806   * @example mintTokens(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq"}, 1000n);1807   * @returns ```true``` if extrinsic success, otherwise ```false```1808   */1809  async mintTokens(signer: TSigner, collectionId: number, amount: bigint, owner: ICrossAccountId | string): Promise<boolean> {1810    const creationResult = await this.helper.executeExtrinsic(1811      signer,1812      'api.tx.unique.createItem', [collectionId, (typeof owner === 'string') ? {Substrate: owner} : owner, {1813        fungible: {1814          value: amount,1815        },1816      }],1817      true, // `Unable to mint fungible tokens for ${label}`,1818    );1819    return this.helper.util.findCollectionInEvents(creationResult.result.events, collectionId, 'common', 'ItemCreated');1820  }18211822  /**1823   * Mint multiple Fungible tokens with one owner1824   * @param signer keyring of signer1825   * @param collectionId ID of collection1826   * @param owner tokens owner1827   * @param tokens array of tokens with properties and pieces1828   * @returns ```true``` if extrinsic success, otherwise ```false```1829   */1830  async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, tokens: {value: bigint}[], owner: ICrossAccountId): Promise<boolean> {1831    const rawTokens = [];1832    for (const token of tokens) {1833      const raw = {Fungible: {Value: token.value}};1834      rawTokens.push(raw);1835    }1836    const creationResult = await this.helper.executeExtrinsic(1837      signer,1838      'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1839      true,1840    );1841    return this.helper.util.findCollectionInEvents(creationResult.result.events, collectionId, 'common', 'ItemCreated');1842  }18431844  /**1845   * Get the top 10 owners with the largest balance for the Fungible collection1846   * @param collectionId ID of collection1847   * @example getTop10Owners(10);1848   * @returns array of ```ICrossAccountId```1849   */1850  async getTop10Owners(collectionId: number): Promise<CrossAccountId[]> {1851    return (await this.helper.callRpc('api.rpc.unique.tokenOwners', [collectionId, 0])).toJSON().map(CrossAccountId.fromLowerCaseKeys);1852  }18531854  /**1855   * Get account balance1856   * @param collectionId ID of collection1857   * @param addressObj address of owner1858   * @example getBalance(10, {Substrate: "5GHoZe9c73RYbVzq..."})1859   * @returns amount of fungible tokens owned by address1860   */1861  async getBalance(collectionId: number, addressObj: ICrossAccountId): Promise<bigint> {1862    return (await this.helper.callRpc('api.rpc.unique.balance', [collectionId, addressObj, 0])).toBigInt();1863  }18641865  /**1866   * Transfer tokens to address1867   * @param signer keyring of signer1868   * @param collectionId ID of collection1869   * @param toAddressObj address recipient1870   * @param amount amount of tokens to be sent1871   * @example transfer(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, 1000n);1872   * @returns ```true``` if extrinsic success, otherwise ```false```1873   */1874  async transfer(signer: TSigner, collectionId: number, toAddressObj: ICrossAccountId, amount=1n) {1875    return await super.transferToken(signer, collectionId, 0, toAddressObj, amount);1876  }18771878  /**1879   * Transfer some tokens on behalf of the owner.1880   * @param signer keyring of signer1881   * @param collectionId ID of collection1882   * @param fromAddressObj address on behalf of which tokens will be sent1883   * @param toAddressObj address where token to be sent1884   * @param amount number of tokens to be sent1885   * @example transferFrom(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, {Substrate: "5DfhbVfww7ThF8q6f3ij..."}, 10000n);1886   * @returns ```true``` if extrinsic success, otherwise ```false```1887   */1888  async transferFrom(signer: TSigner, collectionId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {1889    return await super.transferTokenFrom(signer, collectionId, 0, fromAddressObj, toAddressObj, amount);1890  }18911892  /**1893   * Destroy some amount of tokens1894   * @param signer keyring of signer1895   * @param collectionId ID of collection1896   * @param amount amount of tokens to be destroyed1897   * @example burnTokens(aliceKeyring, 10, 1000n);1898   * @returns ```true``` if extrinsic success, otherwise ```false```1899   */1900  async burnTokens(signer: IKeyringPair, collectionId: number, amount=1n): Promise<boolean> {1901    return (await super.burnToken(signer, collectionId, 0, amount)).success;1902  }19031904  /**1905   * Burn some tokens on behalf of the owner.1906   * @param signer keyring of signer1907   * @param collectionId ID of collection1908   * @param fromAddressObj address on behalf of which tokens will be burnt1909   * @param amount amount of tokens to be burnt1910   * @example burnTokensFrom(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, 1000n);1911   * @returns ```true``` if extrinsic success, otherwise ```false```1912   */1913  async burnTokensFrom(signer: IKeyringPair, collectionId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1914    return await super.burnTokenFrom(signer, collectionId, 0, fromAddressObj, amount);1915  }19161917  /**1918   * Get total collection supply1919   * @param collectionId1920   * @returns1921   */1922  async getTotalPieces(collectionId: number): Promise<bigint> {1923    return (await this.helper.callRpc('api.rpc.unique.totalPieces', [collectionId, 0])).unwrap().toBigInt();1924  }19251926  /**1927   * Set, change, or remove approved address to transfer tokens.1928   *1929   * @param signer keyring of signer1930   * @param collectionId ID of collection1931   * @param toAddressObj address to be approved1932   * @param amount amount of tokens to be approved1933   * @example approveTokens(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, 1000n)1934   * @returns ```true``` if extrinsic success, otherwise ```false```1935   */1936  async approveTokens(signer: IKeyringPair, collectionId: number, toAddressObj: ICrossAccountId, amount=1n) {1937    return super.approveToken(signer, collectionId, 0, toAddressObj, amount);1938  }19391940  /**1941   * Get amount of fungible tokens approved to transfer1942   * @param collectionId ID of collection1943   * @param fromAddressObj owner of tokens1944   * @param toAddressObj the address approved for the transfer of tokens on behalf of the owner1945   * @returns number of tokens approved for the transfer1946   */1947  async getApprovedTokens(collectionId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {1948    return super.getTokenApprovedPieces(collectionId, 0, toAddressObj, fromAddressObj);1949  }1950}195119521953class ChainGroup extends HelperGroup {1954  /**1955   * Get system properties of a chain1956   * @example getChainProperties();1957   * @returns ss58Format, token decimals, and token symbol1958   */1959  getChainProperties(): IChainProperties {1960    const properties = (this.helper.api as any).registry.getChainProperties().toJSON();1961    return {1962      ss58Format: properties.ss58Format.toJSON(),1963      tokenDecimals: properties.tokenDecimals.toJSON(),1964      tokenSymbol: properties.tokenSymbol.toJSON(),1965    };1966  }19671968  /**1969   * Get chain header1970   * @example getLatestBlockNumber();1971   * @returns the number of the last block1972   */1973  async getLatestBlockNumber(): Promise<number> {1974    return (await this.helper.callRpc('api.rpc.chain.getHeader')).number.toNumber();1975  }19761977  /**1978   * Get block hash by block number1979   * @param blockNumber number of block1980   * @example getBlockHashByNumber(12345);1981   * @returns hash of a block1982   */1983  async getBlockHashByNumber(blockNumber: number): Promise<string | null> {1984    const blockHash = (await this.helper.callRpc('api.rpc.chain.getBlockHash', [blockNumber])).toJSON();1985    if(blockHash === '0x0000000000000000000000000000000000000000000000000000000000000000') return null;1986    return blockHash;1987  }19881989  // TODO add docs1990  async getBlock(blockHashOrNumber: string | number): Promise<IBlock | null> {1991    const blockHash = typeof blockHashOrNumber === 'string' ? blockHashOrNumber : await this.getBlockHashByNumber(blockHashOrNumber);1992    if (!blockHash) return null;1993    return (await this.helper.callRpc('api.rpc.chain.getBlock', [blockHash])).toHuman().block;1994  }19951996  /**1997   * Get account nonce1998   * @param address substrate address1999   * @example getNonce("5GrwvaEF5zXb26Fz...");2000   * @returns number, account's nonce2001   */2002  async getNonce(address: TSubstrateAccount): Promise<number> {2003    return (await (this.helper.api as any).query.system.account(address)).nonce.toNumber();2004  }2005}200620072008class BalanceGroup extends HelperGroup {2009  /**2010   * Representation of the native token in the smallest unit - one OPAL (OPL), QUARTZ (QTZ), or UNIQUE (UNQ).2011   * @example getOneTokenNominal()2012   * @returns ```BigInt``` representation of the native token in the smallest unit, e.g. ```1_000_000_000_000_000_000n``` for QTZ.2013   */2014  getOneTokenNominal(): bigint {2015    const chainProperties = this.helper.chain.getChainProperties();2016    return 10n ** BigInt((chainProperties.tokenDecimals || [18])[0]);2017  }20182019  /**2020   * Get substrate address balance2021   * @param address substrate address2022   * @example getSubstrate("5GrwvaEF5zXb26Fz...")2023   * @returns amount of tokens on address2024   */2025  async getSubstrate(address: TSubstrateAccount): Promise<bigint> {2026    return (await this.helper.callRpc('api.query.system.account', [address])).data.free.toBigInt();2027  }20282029  /**2030   * Get full substrate balance including free, miscFrozen, feeFrozen, and reserved2031   * @param address substrate address2032   * @returns2033   */2034  async getSubstrateFull(address: TSubstrateAccount): Promise<ISubstrateBalance> {2035    const accountInfo = (await this.helper.callRpc('api.query.system.account', [address])).data;2036    return {free: accountInfo.free.toBigInt(), miscFrozen: accountInfo.miscFrozen.toBigInt(), feeFrozen: accountInfo.feeFrozen.toBigInt(), reserved: accountInfo.reserved.toBigInt()};2037  }20382039  /**2040   * Get ethereum address balance2041   * @param address ethereum address2042   * @example getEthereum("0x9F0583DbB855d...")2043   * @returns amount of tokens on address2044   */2045  async getEthereum(address: TEthereumAccount): Promise<bigint> {2046    return (await this.helper.callRpc('api.rpc.eth.getBalance', [address])).toBigInt();2047  }20482049  /**2050   * Transfer tokens to substrate address2051   * @param signer keyring of signer2052   * @param address substrate address of a recipient2053   * @param amount amount of tokens to be transfered2054   * @example transferToSubstrate(aliceKeyring, "5GrwvaEF5zXb26Fz...", 100_000_000_000n);2055   * @returns ```true``` if extrinsic success, otherwise ```false```2056   */2057  async transferToSubstrate(signer: TSigner, address: TSubstrateAccount, amount: bigint | string): Promise<boolean> {2058    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}`*/);20592060    let transfer = {from: null, to: null, amount: 0n} as any;2061    result.result.events.forEach(({event: {data, method, section}}) => {2062      if ((section === 'balances') && (method === 'Transfer')) {2063        transfer = {2064          from: this.helper.address.normalizeSubstrate(data[0]),2065          to: this.helper.address.normalizeSubstrate(data[1]),2066          amount: BigInt(data[2]),2067        };2068      }2069    });2070    const isSuccess = this.helper.address.normalizeSubstrate(typeof signer === 'string' ? signer : signer.address) === transfer.from 2071      && this.helper.address.normalizeSubstrate(address) === transfer.to 2072      && BigInt(amount) === transfer.amount;2073    return isSuccess;2074  }2075}207620772078class AddressGroup extends HelperGroup {2079  /**2080   * Normalizes the address to the specified ss58 format, by default ```42```.2081   * @param address substrate address2082   * @param ss58Format format for address conversion, by default ```42```2083   * @example normalizeSubstrate("unjKJQJrRd238pkUZZvzDQrfKuM39zBSnQ5zjAGAGcdRhaJTx") // returns 5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY2084   * @returns substrate address converted to normalized (i.e., starting with 5) or specified explicitly representation2085   */2086  normalizeSubstrate(address: TSubstrateAccount, ss58Format = 42): TSubstrateAccount {2087    return CrossAccountId.normalizeSubstrateAddress(address, ss58Format);2088  }20892090  /**2091   * Get address in the connected chain format2092   * @param address substrate address2093   * @example normalizeSubstrateToChainFormat("5GrwvaEF5zXb26Fz...") // returns unjKJQJrRd238pkUZZ... for Unique Network2094   * @returns address in chain format2095   */2096  async normalizeSubstrateToChainFormat(address: TSubstrateAccount): Promise<TSubstrateAccount> {2097    const info = this.helper.chain.getChainProperties();2098    return encodeAddress(decodeAddress(address), info.ss58Format);2099  }21002101  /**2102   * Get substrate mirror of an ethereum address2103   * @param ethAddress ethereum address2104   * @param toChainFormat false for normalized account2105   * @example ethToSubstrate('0x9F0583DbB855d...')2106   * @returns substrate mirror of a provided ethereum address2107   */2108  async ethToSubstrate(ethAddress: TEthereumAccount, toChainFormat=false): Promise<TSubstrateAccount> {2109    if(!toChainFormat) return evmToAddress(ethAddress);2110    const info = this.helper.chain.getChainProperties();2111    return evmToAddress(ethAddress, info.ss58Format);2112  }21132114  /**2115   * Get ethereum mirror of a substrate address2116   * @param subAddress substrate account2117   * @example substrateToEth("5DnSF6RRjwteE3BrC...")2118   * @returns ethereum mirror of a provided substrate address2119   */2120  substrateToEth(subAddress: TSubstrateAccount): TEthereumAccount {2121    return nesting.toChecksumAddress('0x' + Array.from(addressToEvm(subAddress), i => i.toString(16).padStart(2, '0')).join(''));2122  }2123}21242125class StakingGroup extends HelperGroup {2126  /**2127   * Stake tokens for App Promotion2128   * @param signer keyring of signer2129   * @param amountToStake amount of tokens to stake2130   * @param label extra label for log2131   * @returns2132   */2133  async stake(signer: TSigner, amountToStake: bigint, label?: string): Promise<boolean> {2134    if(typeof label === 'undefined') label = `${signer.address} amount: ${amountToStake}`;2135    const stakeResult = await this.helper.executeExtrinsic(2136      signer, 'api.tx.appPromotion.stake',2137      [amountToStake], true,2138    );2139    // TODO extract info from stakeResult2140    return true;2141  }21422143  /**2144   * Unstake tokens for App Promotion2145   * @param signer keyring of signer2146   * @param amountToUnstake amount of tokens to unstake2147   * @param label extra label for log2148   * @returns block number where balances will be unlocked2149   */2150  async unstake(signer: TSigner, label?: string): Promise<number> {2151    if(typeof label === 'undefined') label = `${signer.address}`;2152    const unstakeResult = await this.helper.executeExtrinsic(2153      signer, 'api.tx.appPromotion.unstake',2154      [], true,2155    );2156    // TODO extract block number fron events2157    return 1;2158  }21592160  /**2161   * Get total staked amount for address2162   * @param address substrate or ethereum address2163   * @returns total staked amount2164   */2165  async getTotalStaked(address?: ICrossAccountId): Promise<bigint> {2166    if (address) return (await this.helper.callRpc('api.rpc.appPromotion.totalStaked', [address])).toBigInt();2167    return (await this.helper.callRpc('api.rpc.appPromotion.totalStaked')).toBigInt();2168  }21692170  /**2171   * Get total staked per block2172   * @param address substrate or ethereum address2173   * @returns array of stakes. `block` – the number of the block in which the stake was made. `amount` - the number of tokens staked in the block2174   */2175  async getTotalStakedPerBlock(address: ICrossAccountId): Promise<IStakingInfo[]> {2176    const rawTotalStakerdPerBlock = await this.helper.callRpc('api.rpc.appPromotion.totalStakedPerBlock', [address]);2177    return rawTotalStakerdPerBlock.map(([block, amount]: any[]) => {2178      return { 2179        block: block.toBigInt(),2180        amount: amount.toBigInt(),2181      };2182    });2183  }21842185  /**2186   * Get total pending unstake amount for address2187   * @param address substrate or ethereum address2188   * @returns total pending unstake amount2189   */2190  async getPendingUnstake(address: ICrossAccountId): Promise<bigint> {2191    return (await this.helper.callRpc('api.rpc.appPromotion.pendingUnstake', [address])).toBigInt();2192  }21932194  /**2195   * Get pending unstake amount per block for address2196   * @param address substrate or ethereum address2197   * @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 block2198   */2199  async getPendingUnstakePerBlock(address: ICrossAccountId): Promise<IStakingInfo[]> {2200    const rawUnstakedPerBlock = await this.helper.callRpc('api.rpc.appPromotion.pendingUnstakePerBlock', [address]);2201    const result = rawUnstakedPerBlock.map(([block, amount]: any[]) => {2202      return {2203        block: block.toBigInt(),2204        amount: amount.toBigInt(),2205      };2206    });2207    return result;2208  }2209}22102211export class UniqueHelper extends ChainHelperBase {2212  chain: ChainGroup;2213  balance: BalanceGroup;2214  address: AddressGroup;2215  collection: CollectionGroup;2216  nft: NFTGroup;2217  rft: RFTGroup;2218  ft: FTGroup;2219  staking: StakingGroup;22202221  constructor(logger?: ILogger) {2222    super(logger);2223    this.chain = new ChainGroup(this);2224    this.balance = new BalanceGroup(this);2225    this.address = new AddressGroup(this);2226    this.collection = new CollectionGroup(this);2227    this.nft = new NFTGroup(this);2228    this.rft = new RFTGroup(this);2229    this.ft = new FTGroup(this);2230    this.staking = new StakingGroup(this);2231  }2232}223322342235export class UniqueBaseCollection {2236  helper: UniqueHelper;2237  collectionId: number;22382239  constructor(collectionId: number, uniqueHelper: UniqueHelper) {2240    this.collectionId = collectionId;2241    this.helper = uniqueHelper;2242  }22432244  async getData() {2245    return await this.helper.collection.getData(this.collectionId);2246  }22472248  async getLastTokenId() {2249    return await this.helper.collection.getLastTokenId(this.collectionId);2250  }22512252  async isTokenExists(tokenId: number) {2253    return await this.helper.collection.isTokenExists(this.collectionId, tokenId);2254  }22552256  async getAdmins() {2257    return await this.helper.collection.getAdmins(this.collectionId);2258  }22592260  async getAllowList() {2261    return await this.helper.collection.getAllowList(this.collectionId);2262  }22632264  async getEffectiveLimits() {2265    return await this.helper.collection.getEffectiveLimits(this.collectionId);2266  }22672268  async getProperties(propertyKeys: string[] | null = null) {2269    return await this.helper.collection.getProperties(this.collectionId, propertyKeys);2270  }22712272  async getTokenNextSponsored(tokenId: number, addressObj: ICrossAccountId) {2273    return await this.helper.collection.getTokenNextSponsored(this.collectionId, tokenId, addressObj);2274  }22752276  async setSponsor(signer: TSigner, sponsorAddress: TSubstrateAccount) {2277    return await this.helper.collection.setSponsor(signer, this.collectionId, sponsorAddress);2278  }22792280  async confirmSponsorship(signer: TSigner) {2281    return await this.helper.collection.confirmSponsorship(signer, this.collectionId);2282  }22832284  async removeSponsor(signer: TSigner) {2285    return await this.helper.collection.removeSponsor(signer, this.collectionId);2286  }22872288  async setLimits(signer: TSigner, limits: ICollectionLimits) {2289    return await this.helper.collection.setLimits(signer, this.collectionId, limits);2290  }22912292  async changeOwner(signer: TSigner, ownerAddress: TSubstrateAccount) {2293    return await this.helper.collection.changeOwner(signer, this.collectionId, ownerAddress);2294  }22952296  async addAdmin(signer: TSigner, adminAddressObj: ICrossAccountId) {2297    return await this.helper.collection.addAdmin(signer, this.collectionId, adminAddressObj);2298  }22992300  async addToAllowList(signer: TSigner, addressObj: ICrossAccountId) {2301    return await this.helper.collection.addToAllowList(signer, this.collectionId, addressObj);2302  }23032304  async removeFromAllowList(signer: TSigner, addressObj: ICrossAccountId) {2305    return await this.helper.collection.removeFromAllowList(signer, this.collectionId, addressObj);2306  }23072308  async removeAdmin(signer: TSigner, adminAddressObj: ICrossAccountId) {2309    return await this.helper.collection.removeAdmin(signer, this.collectionId, adminAddressObj);2310  }23112312  async setProperties(signer: TSigner, properties: IProperty[]) {2313    return await this.helper.collection.setProperties(signer, this.collectionId, properties);2314  }23152316  async deleteProperties(signer: TSigner, propertyKeys: string[]) {2317    return await this.helper.collection.deleteProperties(signer, this.collectionId, propertyKeys);2318  }23192320  async setPermissions(signer: TSigner, permissions: ICollectionPermissions) {2321    return await this.helper.collection.setPermissions(signer, this.collectionId, permissions);2322  }23232324  async enableNesting(signer: TSigner, permissions: INestingPermissions) {2325    return await this.helper.collection.enableNesting(signer, this.collectionId, permissions);2326  }23272328  async disableNesting(signer: TSigner) {2329    return await this.helper.collection.disableNesting(signer, this.collectionId);2330  }23312332  async burn(signer: TSigner) {2333    return await this.helper.collection.burn(signer, this.collectionId);2334  }2335}233623372338export class UniqueNFTCollection extends UniqueBaseCollection {2339  getTokenObject(tokenId: number) {2340    return new UniqueNFToken(tokenId, this);2341  }23422343  async getTokensByAddress(addressObj: ICrossAccountId) {2344    return await this.helper.nft.getTokensByAddress(this.collectionId, addressObj);2345  }23462347  async getToken(tokenId: number, blockHashAt?: string) {2348    return await this.helper.nft.getToken(this.collectionId, tokenId, [], blockHashAt);2349  }23502351  async getTokenOwner(tokenId: number, blockHashAt?: string) {2352    return await this.helper.nft.getTokenOwner(this.collectionId, tokenId, blockHashAt);2353  }23542355  async getTokenTopmostOwner(tokenId: number, blockHashAt?: string) {2356    return await this.helper.nft.getTokenTopmostOwner(this.collectionId, tokenId, blockHashAt);2357  }23582359  async getTokenChildren(tokenId: number, blockHashAt?: string) {2360    return await this.helper.nft.getTokenChildren(this.collectionId, tokenId, blockHashAt);2361  }23622363  async getPropertyPermissions(propertyKeys: string[] | null = null) {2364    return await this.helper.nft.getPropertyPermissions(this.collectionId, propertyKeys);2365  }23662367  async getTokenProperties(tokenId: number, propertyKeys: string[] | null = null) {2368    return await this.helper.nft.getTokenProperties(this.collectionId, tokenId, propertyKeys);2369  }23702371  async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId) {2372    return await this.helper.nft.transferToken(signer, this.collectionId, tokenId, addressObj);2373  }23742375  async transferTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2376    return await this.helper.nft.transferTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, toAddressObj);2377  }23782379  async approveToken(signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId) {2380    return await this.helper.nft.approveToken(signer, this.collectionId, tokenId, toAddressObj);2381  }23822383  async isTokenApproved(tokenId: number, toAddressObj: ICrossAccountId) {2384    return await this.helper.nft.isTokenApproved(this.collectionId, tokenId, toAddressObj);2385  }23862387  async mintToken(signer: TSigner, owner: ICrossAccountId = {Substrate: signer.address}, properties?: IProperty[]) {2388    return await this.helper.nft.mintToken(signer, {collectionId: this.collectionId, owner, properties});2389  }23902391  async mintMultipleTokens(signer: TSigner, tokens: {owner: ICrossAccountId, properties?: IProperty[]}[]) {2392    return await this.helper.nft.mintMultipleTokens(signer, this.collectionId, tokens);2393  }23942395  async burnToken(signer: TSigner, tokenId: number) {2396    return await this.helper.nft.burnToken(signer, this.collectionId, tokenId);2397  }23982399  async burnTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId) {2400    return await this.helper.nft.burnTokenFrom(signer, this.collectionId, tokenId, fromAddressObj);2401  }24022403  async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[]) {2404    return await this.helper.nft.setTokenProperties(signer, this.collectionId, tokenId, properties);2405  }24062407  async deleteTokenProperties(signer: TSigner, tokenId: number, propertyKeys: string[]) {2408    return await this.helper.nft.deleteTokenProperties(signer, this.collectionId, tokenId, propertyKeys);2409  }24102411  async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[]) {2412    return await this.helper.nft.setTokenPropertyPermissions(signer, this.collectionId, permissions);2413  }24142415  async nestToken(signer: TSigner, tokenId: number, toTokenObj: IToken) {2416    return await this.helper.nft.nestToken(signer, {collectionId: this.collectionId, tokenId}, toTokenObj);2417  }24182419  async unnestToken(signer: TSigner, tokenId: number, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {2420    return await this.helper.nft.unnestToken(signer, {collectionId: this.collectionId, tokenId}, fromTokenObj, toAddressObj);2421  }2422}242324242425export class UniqueRFTCollection extends UniqueBaseCollection {2426  getTokenObject(tokenId: number) {2427    return new UniqueRFToken(tokenId, this);2428  }24292430  async getToken(tokenId: number, blockHashAt?: string) {2431    return await this.helper.rft.getToken(this.collectionId, tokenId, [], blockHashAt);2432  }24332434  async getTokensByAddress(addressObj: ICrossAccountId) {2435    return await this.helper.rft.getTokensByAddress(this.collectionId, addressObj);2436  }24372438  async getTop10TokenOwners(tokenId: number) {2439    return await this.helper.rft.getTokenTop10Owners(this.collectionId, tokenId);2440  }24412442  async getTokenBalance(tokenId: number, addressObj: ICrossAccountId) {2443    return await this.helper.rft.getTokenBalance(this.collectionId, tokenId, addressObj);2444  }24452446  async getTokenTotalPieces(tokenId: number) {2447    return await this.helper.rft.getTokenTotalPieces(this.collectionId, tokenId);2448  }24492450  async getTokenApprovedPieces(tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2451    return await this.helper.rft.getTokenApprovedPieces(this.collectionId, tokenId, toAddressObj, fromAddressObj);2452  }24532454  async getPropertyPermissions(propertyKeys: string[] | null = null) {2455    return await this.helper.rft.getPropertyPermissions(this.collectionId, propertyKeys);2456  }24572458  async getTokenProperties(tokenId: number, propertyKeys: string[] | null = null) {2459    return await this.helper.rft.getTokenProperties(this.collectionId, tokenId, propertyKeys);2460  }24612462  async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId, amount=1n) {2463    return await this.helper.rft.transferToken(signer, this.collectionId, tokenId, addressObj, amount);2464  }24652466  async transferTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {2467    return await this.helper.rft.transferTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, toAddressObj, amount);2468  }24692470  async approveToken(signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {2471    return await this.helper.rft.approveToken(signer, this.collectionId, tokenId, toAddressObj, amount);2472  }24732474  async repartitionToken(signer: TSigner, tokenId: number, amount: bigint) {2475    return await this.helper.rft.repartitionToken(signer, this.collectionId, tokenId, amount);2476  }24772478  async mintToken(signer: TSigner, pieces=1n, owner: ICrossAccountId = {Substrate: signer.address}, properties?: IProperty[]) {2479    return await this.helper.rft.mintToken(signer, {collectionId: this.collectionId, owner, pieces, properties});2480  }24812482  async mintMultipleTokens(signer: TSigner, tokens: {pieces: bigint, owner: ICrossAccountId, properties?: IProperty[]}[]) {2483    return await this.helper.rft.mintMultipleTokens(signer, this.collectionId, tokens);2484  }24852486  async burnToken(signer: TSigner, tokenId: number, amount=1n) {2487    return await this.helper.rft.burnToken(signer, this.collectionId, tokenId, amount);2488  }24892490  async burnTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId,  amount=1n) {2491    return await this.helper.rft.burnTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, amount);2492  }24932494  async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[]) {2495    return await this.helper.rft.setTokenProperties(signer, this.collectionId, tokenId, properties);2496  }24972498  async deleteTokenProperties(signer: TSigner, tokenId: number, propertyKeys: string[]) {2499    return await this.helper.rft.deleteTokenProperties(signer, this.collectionId, tokenId, propertyKeys);2500  }25012502  async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[]) {2503    return await this.helper.rft.setTokenPropertyPermissions(signer, this.collectionId, permissions);2504  }2505}250625072508export class UniqueFTCollection extends UniqueBaseCollection {2509  async getBalance(addressObj: ICrossAccountId) {2510    return await this.helper.ft.getBalance(this.collectionId, addressObj);2511  }25122513  async getTotalPieces() {2514    return await this.helper.ft.getTotalPieces(this.collectionId);2515  }25162517  async getApprovedTokens(fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2518    return await this.helper.ft.getApprovedTokens(this.collectionId, fromAddressObj, toAddressObj);2519  }25202521  async getTop10Owners() {2522    return await this.helper.ft.getTop10Owners(this.collectionId);2523  }25242525  async mint(signer: TSigner, amount=1n, owner: ICrossAccountId = {Substrate: signer.address}) {2526    return await this.helper.ft.mintTokens(signer, this.collectionId, amount, owner);2527  }25282529  async mintWithOneOwner(signer: TSigner, tokens: {value: bigint}[], owner: ICrossAccountId = {Substrate: signer.address}) {2530    return await this.helper.ft.mintMultipleTokensWithOneOwner(signer, this.collectionId, tokens, owner);2531  }25322533  async transfer(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {2534    return await this.helper.ft.transfer(signer, this.collectionId, toAddressObj, amount);2535  }25362537  async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {2538    return await this.helper.ft.transferFrom(signer, this.collectionId, fromAddressObj, toAddressObj, amount);2539  }25402541  async burnTokens(signer: TSigner, amount=1n) {2542    return await this.helper.ft.burnTokens(signer, this.collectionId, amount);2543  }25442545  async burnTokensFrom(signer: TSigner, fromAddressObj: ICrossAccountId, amount=1n) {2546    return await this.helper.ft.burnTokensFrom(signer, this.collectionId, fromAddressObj, amount);2547  }25482549  async approveTokens(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {2550    return await this.helper.ft.approveTokens(signer, this.collectionId, toAddressObj, amount);2551  }2552}255325542555export class UniqueBaseToken {2556  collection: UniqueNFTCollection | UniqueRFTCollection;2557  collectionId: number;2558  tokenId: number;25592560  constructor(tokenId: number, collection: UniqueNFTCollection | UniqueRFTCollection) {2561    this.collection = collection;2562    this.collectionId = collection.collectionId;2563    this.tokenId = tokenId;2564  }25652566  async getNextSponsored(addressObj: ICrossAccountId) {2567    return await this.collection.getTokenNextSponsored(this.tokenId, addressObj);2568  }25692570  async getProperties(propertyKeys: string[] | null = null) {2571    return await this.collection.getTokenProperties(this.tokenId, propertyKeys);2572  }25732574  async setProperties(signer: TSigner, properties: IProperty[]) {2575    return await this.collection.setTokenProperties(signer, this.tokenId, properties);2576  }25772578  async deleteProperties(signer: TSigner, propertyKeys: string[]) {2579    return await this.collection.deleteTokenProperties(signer, this.tokenId, propertyKeys);2580  }25812582  nestingAccount() {2583    return this.collection.helper.util.getTokenAccount(this);2584  }2585}258625872588export class UniqueNFToken extends UniqueBaseToken {2589  collection: UniqueNFTCollection;25902591  constructor(tokenId: number, collection: UniqueNFTCollection) {2592    super(tokenId, collection);2593    this.collection = collection;2594  }25952596  async getData(blockHashAt?: string) {2597    return await this.collection.getToken(this.tokenId, blockHashAt);2598  }25992600  async getOwner(blockHashAt?: string) {2601    return await this.collection.getTokenOwner(this.tokenId, blockHashAt);2602  }26032604  async getTopmostOwner(blockHashAt?: string) {2605    return await this.collection.getTokenTopmostOwner(this.tokenId, blockHashAt);2606  }26072608  async getChildren(blockHashAt?: string) {2609    return await this.collection.getTokenChildren(this.tokenId, blockHashAt);2610  }26112612  async nest(signer: TSigner, toTokenObj: IToken) {2613    return await this.collection.nestToken(signer, this.tokenId, toTokenObj);2614  }26152616  async unnest(signer: TSigner, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {2617    return await this.collection.unnestToken(signer, this.tokenId, fromTokenObj, toAddressObj);2618  }26192620  async transfer(signer: TSigner, addressObj: ICrossAccountId) {2621    return await this.collection.transferToken(signer, this.tokenId, addressObj);2622  }26232624  async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2625    return await this.collection.transferTokenFrom(signer, this.tokenId, fromAddressObj, toAddressObj);2626  }26272628  async approve(signer: TSigner, toAddressObj: ICrossAccountId) {2629    return await this.collection.approveToken(signer, this.tokenId, toAddressObj);2630  }26312632  async isApproved(toAddressObj: ICrossAccountId) {2633    return await this.collection.isTokenApproved(this.tokenId, toAddressObj);2634  }26352636  async burn(signer: TSigner) {2637    return await this.collection.burnToken(signer, this.tokenId);2638  }26392640  async burnFrom(signer: TSigner, fromAddressObj: ICrossAccountId) {2641    return await this.collection.burnTokenFrom(signer, this.tokenId, fromAddressObj);2642  }2643}26442645export class UniqueRFToken extends UniqueBaseToken {2646  collection: UniqueRFTCollection;26472648  constructor(tokenId: number, collection: UniqueRFTCollection) {2649    super(tokenId, collection);2650    this.collection = collection;2651  }26522653  async getData(blockHashAt?: string) {2654    return await this.collection.getToken(this.tokenId, blockHashAt);2655  }26562657  async getTop10Owners() {2658    return await this.collection.getTop10TokenOwners(this.tokenId);2659  }26602661  async getBalance(addressObj: ICrossAccountId) {2662    return await this.collection.getTokenBalance(this.tokenId, addressObj);2663  }26642665  async getTotalPieces() {2666    return await this.collection.getTokenTotalPieces(this.tokenId);2667  }26682669  async getApprovedPieces(fromAddressObj: ICrossAccountId, toAccountObj: ICrossAccountId) {2670    return await this.collection.getTokenApprovedPieces(this.tokenId, fromAddressObj, toAccountObj);2671  }26722673  async transfer(signer: TSigner, addressObj: ICrossAccountId, amount=1n) {2674    return await this.collection.transferToken(signer, this.tokenId, addressObj, amount);2675  }26762677  async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {2678    return await this.collection.transferTokenFrom(signer, this.tokenId, fromAddressObj, toAddressObj, amount);2679  }26802681  async approve(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {2682    return await this.collection.approveToken(signer, this.tokenId, toAddressObj, amount);2683  }26842685  async repartition(signer: TSigner, amount: bigint) {2686    return await this.collection.repartitionToken(signer, this.tokenId, amount);2687  }26882689  async burn(signer: TSigner, amount=1n) {2690    return await this.collection.burnToken(signer, this.tokenId, amount);2691  }26922693  async burnFrom(signer: TSigner, fromAddressObj: ICrossAccountId, amount=1n) {2694    return await this.collection.burnTokenFrom(signer, this.tokenId, fromAddressObj, amount);2695  }2696}