git.delta.rocks / unique-network / refs/commits / 04cd15cc5d24

difftreelog

tests(nesting): refactored to use playgrounds

Fahrrader2022-09-22parent: #644729e.patch.diff
in: master

10 files changed

modifiedtests/src/eth/util/playgrounds/index.tsdiffbeforeafterboth
--- a/tests/src/eth/util/playgrounds/index.ts
+++ b/tests/src/eth/util/playgrounds/index.ts
@@ -12,7 +12,7 @@
 
 import chai from 'chai';
 import chaiAsPromised from 'chai-as-promised';
-import { requirePalletsOrSkip } from '../../../util/playgrounds';
+import {requirePalletsOrSkip} from '../../../util/playgrounds';
 chai.use(chaiAsPromised);
 export const expect = chai.expect;
 
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
@@ -240,7 +240,7 @@
   }
 
   fromTokenId(collectionId: number, tokenId: number): string  {
-    return this.helper.util.getNestingTokenAddress(collectionId, tokenId);
+    return this.helper.util.getNestingTokenAddressRaw({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, UniqueNFTToken} 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<UniqueNFTToken[]> {
+  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].nestingAddress(), tokens[7].nestingAddress()),
+      '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.nestingAddress());
+    expect(await nestedToken.getTopmostOwner()).to.be.deep.equal({Substrate: alice.address});
+    expect(await nestedToken.getOwner()).to.be.deep.equal(targetToken.nestingAddress());
+    
+    // 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.nestingAddress());
 
-      // 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.nestingAddress());
+    expect(await newToken.getTopmostOwner()).to.be.deep.equal({Substrate: bob.address});
+    expect(await newToken.getOwner()).to.be.deep.equal(targetToken.nestingAddress());
 
-      // 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.nestingAddress());
+    expect(await tokenC.getOwner()).to.be.deep.equal(tokenA.nestingAddress());
+    
+    // Transfer the nested token to another token
+    await expect(tokenC.transferFrom(alice, tokenA.nestingAddress(), tokenB.nestingAddress())).to.be.fulfilled;
+    expect(await tokenC.getTopmostOwner()).to.be.deep.equal({Substrate: alice.address});
+    expect(await tokenC.getOwner()).to.be.deep.equal(tokenB.nestingAddress());
   });
 
-  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.nestingAddress());
+    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.nestingAddress(), 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.nestingAddress(), tokenA.nestingAddress(), 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.nestingAddress(), tokenA.nestingAddress(), 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.nestingAddress());
+    expect(await nestedToken.getTopmostOwner()).to.be.deep.equal({Substrate: charlie.address});
+    expect(await nestedToken.getOwner()).to.be.deep.equal(targetToken.nestingAddress());
 
-      // 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.nestingAddress());
   });
 
-  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.nestingAddress());
+    expect(await nestedToken.getTopmostOwner()).to.be.deep.equal({Substrate: charlie.address});
+    expect(await nestedToken.getOwner()).to.be.deep.equal(targetToken.nestingAddress());
 
-      // 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.nestingAddress());
   });
 
-  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.nestingAddress());
+    expect(await nestedToken.getTopmostOwner()).to.be.deep.equal({Substrate: charlie.address});
+    expect(await nestedToken.getOwner()).to.be.deep.equal(targetToken.nestingAddress());
 
-      // 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.nestingAddress());
   });
 
   // ---------- 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.nestingAddress());
 
-      // 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.nestingAddress());
+    expect(await nestedToken.getTopmostOwner()).to.be.deep.equal({Substrate: charlie.address});
+    expect(await nestedToken.getOwner()).to.be.deep.equal(targetToken.nestingAddress());
 
-      // 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.nestingAddress());
   });
 
-  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.nestingAddress());
+
+    await collectionB.setPermissions(alice, {access: 'AllowList', mintMode: true});
+    await collectionB.addToAllowList(alice, {Substrate: charlie.address});
+    await collectionB.addToAllowList(alice, targetToken.nestingAddress());
 
-      // 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.nestingAddress());
+    expect(await nestedToken.getTopmostOwner()).to.be.deep.equal({Substrate: charlie.address});
+    expect(await nestedToken.getOwner()).to.be.deep.equal(targetToken.nestingAddress());
+
+    // 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.nestingAddress());
   });
 
   // ---------- 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.nestingAddress());
 
-      // 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.nestingAddress());
 
-      // 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.nestingAddress());
+    expect(await collectionFT.getBalance(targetToken.nestingAddress())).to.be.equal(5n);
+
+    // Create a token to be nested and nest
+    await collectionFT.mint(charlie, 5n);
+    await collectionFT.transfer(charlie, targetToken.nestingAddress(), 2n);
+    expect(await collectionFT.getBalance(targetToken.nestingAddress())).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.nestingAddress());
 
-      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.nestingAddress());
 
-      // 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.nestingAddress());
+    expect(await collectionFT.getBalance(targetToken.nestingAddress())).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.nestingAddress(), 2n);
+    expect(await collectionFT.getBalance(targetToken.nestingAddress())).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.nestingAddress());
 
-      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.nestingAddress());
 
-      // 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.nestingAddress());
+    expect(await nestedToken.getBalance(targetToken.nestingAddress())).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.nestingAddress(), 2n);
+    expect(await newToken.getBalance(targetToken.nestingAddress())).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.nestingAddress());
 
-      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.nestingAddress());
 
-      await setCollectionPermissionsExpectSuccess(alice, collectionNFT, {nesting: {tokenOwner: true, restricted:[collectionRFT]}});
+    // Create an immediately nested token
+    const nestedToken = await collectionRFT.mintToken(charlie, 5n, targetToken.nestingAddress());
+    expect(await nestedToken.getBalance(targetToken.nestingAddress())).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.nestingAddress(), 2n);
+    expect(await newToken.getBalance(targetToken.nestingAddress())).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.nestingAddress());
+    }
 
-      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.nestingAddress()))
+      .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.nestingAddress()))
+      .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.nestingAddress());
+
+    // Try to create a nested token as token owner when it's disallowed
+    await expect(collection.mintToken(bob, targetToken.nestingAddress()))
+      .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.nestingAddress());
 
-      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.nestingAddress());
+    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.nestingAddress());
   });
 
-  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.nestingAddress()))
+      .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.nestingAddress()))
+      .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.nestingAddress());
 
-      // 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.nestingAddress());
 
-      // 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.nestingAddress());
 
-      // 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.nestingAddress());
 
-      // 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.nestingAddress()))
+      .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.nestingAddress()))
+      .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.nestingAddress(), 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.nestingAddress());
 
-      // 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.nestingAddress(), {Substrate: bob.address}, 1n))
+      .to.be.rejectedWith(/common\.ApprovedValueTooLow/);
+    expect(await collectionFT.getBalance(targetToken.nestingAddress())).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.nestingAddress());
 
-      // 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.nestingAddress(), {Substrate: bob.address}, 1n))
+      .to.be.rejectedWith(/common\.ApprovedValueTooLow/);
+    expect(await collectionFT.getBalance(targetToken.nestingAddress())).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.nestingAddress()))
+      .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.nestingAddress(), 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.nestingAddress())).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.nestingAddress()))
+      .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.nestingAddress(), 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.nestingAddress());
 
-      // 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.nestingAddress())).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.nestingAddress());
 
-      // 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.nestingAddress(), {Substrate: alice.address}, 1n))
+      .to.be.rejectedWith(/common\.ApprovedValueTooLow/);
+    expect(await newToken.getBalance(targetToken.nestingAddress())).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.nestingAddress());
 
-      // 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.nestingAddress())).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.nestingAddress());
 
-      // 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.nestingAddress(), {Substrate: alice.address}, 1n))
+      .to.be.rejectedWith(/common\.ApprovedValueTooLow/);
+    expect(await newToken.getBalance(targetToken.nestingAddress())).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.nestingAddress()))
+      .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.nestingAddress(), 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,5 +1,20 @@
-import {expect} from 'chai';
-import usingApi, {executeTransaction} from '../substrate/substrate-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 usingApi, {executeTransaction} from '../substrate/substrate-api';
 import {
   addCollectionAdminExpectSuccess,
   CollectionMode,
@@ -8,997 +23,776 @@
   createItemExpectSuccess,
   getCreateCollectionResult,
   transferExpectSuccess,
-  requirePallets,
-  Pallets,
-} from '../util/helpers';
+} from '../util/helpers';*/
 import {IKeyringPair} from '@polkadot/types/types';
-import {tokenIdToAddress} from '../eth/util/helpers';
+import {itSub, Pallets, requirePalletsOrSkip, usingPlaygrounds, expect} from '../util/playgrounds';
+import {UniqueCollectionBase, UniqueHelper, UniqueNFTCollection, UniqueNFTToken, UniqueRFTCollection, UniqueRFTToken} from '../util/playgrounds/unique';
 
-let alice: IKeyringPair;
-let bob: IKeyringPair;
-let charlie: IKeyringPair;
+// ---------- COLLECTION PROPERTIES
+
+describe('Integration Test: Collection Properties', () => {
+  let alice: IKeyringPair;
+  let bob: IKeyringPair;
 
-describe('Composite Properties Test', () => {
   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 testMakeSureSuppliesRequired(mode: CollectionMode) {
-    await usingApi(async api => {
-      const collectionId = await createCollectionExpectSuccess({mode: mode});
+  itSub('Properties are initially empty', async ({helper}) => {
+    const collection = await helper.nft.mintCollection(alice);
+    expect(await collection.getProperties()).to.be.empty;
+  });
 
-      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;
+  async function testSetsPropertiesForCollection(collection: UniqueCollectionBase) {
+    // As owner
+    await expect(collection.setProperties(alice, [{key: 'electron', value: 'come bond'}])).to.be.fulfilled;
 
-      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;
+    await collection.addAdmin(alice, {Substrate: bob.address});
 
-      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;
+    // As administrator
+    await expect(collection.setProperties(bob, [{key: 'black_hole'}])).to.be.fulfilled;
 
-      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);
-    });
+    const properties = await collection.getProperties();
+    expect(properties).to.include.deep.members([
+      {key: 'electron', value: 'come bond'},
+      {key: 'black_hole', value: ''},
+    ]);
   }
 
-  it('Makes sure collectionById supplies required fields for NFT', async () => {
-    await testMakeSureSuppliesRequired({type: 'NFT'});
+  itSub('Sets properties for a NFT collection', async ({helper}) =>  {
+    await testSetsPropertiesForCollection(await helper.nft.mintCollection(alice));
   });
 
-  it('Makes sure collectionById supplies required fields for ReFungible', async function() {
-    await requirePallets(this, [Pallets.ReFungible]);
-
-    await testMakeSureSuppliesRequired({type: 'ReFungible'});
+  itSub.ifWithPallets('Sets properties for a ReFungible collection', [Pallets.ReFungible], async ({helper}) => {
+    await testSetsPropertiesForCollection(await helper.rft.mintCollection(alice));
   });
-});
 
-// ---------- COLLECTION PROPERTIES
+  async function testCheckValidNames(collection: UniqueCollectionBase) {
+    // alpha symbols
+    await expect(collection.setProperties(alice, [{key: 'answer'}])).to.be.fulfilled;
 
-describe('Integration Test: Collection Properties', () => {
-  before(async () => {
-    await usingApi(async (api, privateKeyWrapper) => {
-      alice = privateKeyWrapper('//Alice');
-      bob = privateKeyWrapper('//Bob');
-    });
-  });
+    // numeric symbols
+    await expect(collection.setProperties(alice, [{key: '451'}])).to.be.fulfilled;
 
-  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);
-    });
-  });
+    // underscore symbol
+    await expect(collection.setProperties(alice, [{key: 'black_hole'}])).to.be.fulfilled;
 
+    // dash symbol
+    await expect(collection.setProperties(alice, [{key: '-'}])).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);
+    // dot symbol
+    await expect(collection.setProperties(alice, [{key: 'once.in.a.long.long.while...', value: 'you get a little lost'}])).to.be.fulfilled;
 
-      // As owner
-      await expect(executeTransaction(
-        api, 
-        bob, 
-        api.tx.unique.setCollectionProperties(collectionId, [{key: 'electron', value: 'come bond'}]), 
-      )).to.not.be.rejected;
+    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'},
+    ]);
+  }
 
-      await addCollectionAdminExpectSuccess(bob, collectionId, alice.address);
-
-      // As administrator
-      await expect(executeTransaction(
-        api, 
-        alice, 
-        api.tx.unique.setCollectionProperties(collectionId, [{key: 'black_hole'}]), 
-      )).to.not.be.rejected;
-
-      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: ''},
-      ]);
-    });
-  }
-  it('Sets properties for a NFT collection', async () => {
-    await testSetsPropertiesForCollection('NFT');
+  itSub('Check valid names for NFT collection properties keys', async ({helper}) =>  {
+    await testCheckValidNames(await helper.nft.mintCollection(alice));
   });
-  it('Sets properties for a ReFungible collection', async function() {
-    await requirePallets(this, [Pallets.ReFungible]);
 
-    await testSetsPropertiesForCollection('ReFungible');
+  itSub.ifWithPallets('Check valid names for ReFungible collection properties keys', [Pallets.ReFungible], async ({helper}) => {
+    await testCheckValidNames(await helper.rft.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: ''},
-      ]);
-    });
+  async function testChangesProperties(collection: UniqueCollectionBase) {
+    await expect(collection.setProperties(alice, [{key: 'electron', value: 'come bond'}, {key: 'black_hole', value: ''}])).to.be.fulfilled;
+
+    // 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('Check valid names for NFT collection properties keys', async () => {
-    await testCheckValidNames('NFT');
+
+  itSub('Changes properties of a NFT collection', async ({helper}) =>  {
+    await testChangesProperties(await helper.nft.mintCollection(alice));
   });
-  it('Check valid names for ReFungible collection properties keys', async function() {
-    await requirePallets(this, [Pallets.ReFungible]);
 
-    await testCheckValidNames('ReFungible');
+  itSub.ifWithPallets('Changes properties of a ReFungible collection', [Pallets.ReFungible], async ({helper}) => {
+    await testChangesProperties(await helper.rft.mintCollection(alice));
   });
 
-  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'},
-      ]);
-    });
-  }
-  it('Changes properties of a NFT collection', async () => {
-    await testChangesProperties({type: 'NFT'});
-  });
-  it('Changes properties of a ReFungible collection', async function() {
-    await requirePallets(this, [Pallets.ReFungible]);
+  async function testDeleteProperties(collection: UniqueCollectionBase) {
+    await expect(collection.setProperties(alice, [{key: 'electron', value: 'come bond'}, {key: 'black_hole', value: 'LIGO'}])).to.be.fulfilled;
 
-    await testChangesProperties({type: 'ReFungible'});
-  });
+    await expect(collection.deleteProperties(alice, ['electron'])).to.be.fulfilled;
 
-  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'},
-      ]);
-    });  
+    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: UniqueCollectionBase) {  
+    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: UniqueCollectionBase) {
+    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: UniqueCollectionBase) {
+    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: UniqueCollectionBase) {
+    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
-
-      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]},
-      ];
+    await usingPlaygrounds(async (helper, privateKey) => {
+      const donor = privateKey('//Alice');
+      [alice, bob, charlie] = await helper.arrange.createAccounts([100n, 100n, 100n], donor);
     });
+
+    // 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: UniqueNFTToken | UniqueRFTToken) {
+    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: UniqueNFTToken | UniqueRFTToken, 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: UniqueNFTToken | UniqueRFTToken, 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: UniqueNFTToken | UniqueRFTToken, 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.nestingAddress());
 
-      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.nestingAddress());
 
-      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.nestingAddress());
 
-      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 +804,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: UniqueNFTToken | UniqueRFTToken, 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: UniqueNFTToken | UniqueRFTToken, 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;
-  
-        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/);
+  async function testForbidsChangingDeletingPropertiesIfPropertyImmutable(token: UniqueNFTToken | UniqueRFTToken, 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.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: UniqueNFTToken | UniqueRFTToken, pieces: bigint) {
+    const originalSpace = await prepare(token, pieces);
 
-    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);
-    });
+    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/);
+
+    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: UniqueNFTToken | UniqueRFTToken, 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<UniqueRFTToken> {
+    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;
+  }
 
-      await expect(executeTransaction(
-        api, 
-        alice, 
-        api.tx.unique.setTokenPropertyPermissions(collection, [{key: 'key', permission: {mutable:true, tokenOwner: true}}]), 
-      )).to.not.be.rejected;
-    });
+  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(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 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.setProperties(alice, [
+      {key: 'fractals', value: 'one headline - why believe it'}, 
+    ])).to.be.fulfilled;
+
+    await token.transfer(alice, {Substrate: charlie.address}, 33n);
+
+    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 token.transfer(alice, {Substrate: charlie.address}, 33n);
+
+    await expect(token.collection.setTokenPropertyPermissions(alice, [{key: 'fractals', permission: {mutable:true, collectionAdmin: true}}]))
+      .to.be.fulfilled;
 
-      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 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.nestingAddress());
 
-      // 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.nestingAddress(), {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.nestingAddress()), '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.nestingAddress());
+    await expect(collectionFT.transferFrom(alice, targetToken.nestingAddress(), {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.nestingAddress())).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.nestingAddress(), 5n);
+    await expect(collectionFT.burnTokensFrom(alice, targetToken.nestingAddress(), 6n), 'while burning').to.be.fulfilled;
+    expect(await collectionFT.getBalance({Substrate: alice.address})).to.be.equal(4n);
+    expect(await collectionFT.getBalance(targetToken.nestingAddress())).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.nestingAddress());
+    await expect(token.transferFrom(alice, targetToken.nestingAddress(), {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.nestingAddress())).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.nestingAddress(), 5n);
+    await expect(token.burnFrom(alice, targetToken.nestingAddress(), 6n), 'while burning').to.be.fulfilled;
+    expect(await token.getBalance({Substrate: alice.address})).to.be.equal(4n);
+    expect(await token.getBalance(targetToken.nestingAddress())).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.nestingAddress());
 
-      // 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.nestingAddress());
 
-      // 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.nestingAddress())).to.be.rejectedWith(/common\.ApprovedValueTooLow/);
+    expect(await nestedToken.getOwner()).to.be.deep.equal(targetToken.nestingAddress());
   });
 
   // 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.nestingAddress());
+    await expect(targetToken.nest(alice, nestedToken)).to.be.rejectedWith(/^structure\.OuroborosDetected$/);
   });
 });
modifiedtests/src/util/playgrounds/types.tsdiffbeforeafterboth
--- a/tests/src/util/playgrounds/types.ts
+++ b/tests/src/util/playgrounds/types.ts
@@ -94,21 +94,22 @@
 
 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;
   }
 }
 
 export interface IToken {
   collectionId: number;
   tokenId: number;
+  //nestingAddress: () => {Ethereum: string};
 }
 
 export interface IBlock {
modifiedtests/src/util/playgrounds/unique.tsdiffbeforeafterboth
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 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(token: IToken) {59    return {Ethereum: this.getNestingTokenAddressRaw(token).toLowerCase()};60  }6162  static getNestingTokenAddressRaw(token: IToken) {63    return nesting.tokenIdToAddress(token.collectionId, token.tokenId);64  }6566  static getDefaultLogger(): ILogger {67    return {68      log(msg: any, level = 'INFO') {69        console[level.toLocaleLowerCase() === 'error' ? 'error' : 'log'](...(Array.isArray(msg) ? msg : [msg]));70      },71      level: {72        ERROR: 'ERROR',73        WARNING: 'WARNING',74        INFO: 'INFO',75      },76    };77  }7879  static vec2str(arr: string[] | number[]) {80    return arr.map(x => String.fromCharCode(parseInt(x.toString()))).join('');81  }8283  static str2vec(string: string) {84    if (typeof string !== 'string') return string;85    return Array.from(string).map(x => x.charCodeAt(0));86  }8788  static fromSeed(seed: string, ss58Format = 42) {89    const keyring = new Keyring({type: 'sr25519', ss58Format});90    return keyring.addFromUri(seed);91  }9293  static normalizeSubstrateAddress(address: string, ss58Format = 42) {94    return encodeAddress(decodeAddress(address), ss58Format);95  }9697  static extractCollectionIdFromCreationResult(creationResult: ITransactionResult) {98    if (creationResult.status !== this.transactionStatus.SUCCESS) {99      throw Error('Unable to create collection!');100    }101102    let collectionId = null;103    creationResult.result.events.forEach(({event: {data, method, section}}) => {104      if ((section === 'common') && (method === 'CollectionCreated')) {105        collectionId = parseInt(data[0].toString(), 10);106      }107    });108109    if (collectionId === null) {110      throw Error('No CollectionCreated event was found!');111    }112113    return collectionId;114  }115116  static extractTokensFromCreationResult(creationResult: ITransactionResult) {117    if (creationResult.status !== this.transactionStatus.SUCCESS) {118      throw Error('Unable to create tokens!');119    }120    let success = false;121    const tokens = [] as any;122    creationResult.result.events.forEach(({event: {data, method, section}}) => {123      if (method === 'ExtrinsicSuccess') {124        success = true;125      } else if ((section === 'common') && (method === 'ItemCreated')) {126        tokens.push({127          collectionId: parseInt(data[0].toString(), 10),128          tokenId: parseInt(data[1].toString(), 10),129          owner: data[2].toJSON(),130        });131      }132    });133    return {success, tokens};134  }135136  static extractTokensFromBurnResult(burnResult: ITransactionResult) {137    if (burnResult.status !== this.transactionStatus.SUCCESS) {138      throw Error('Unable to burn tokens!');139    }140    let success = false;141    const tokens = [] as any;142    burnResult.result.events.forEach(({event: {data, method, section}}) => {143      if (method === 'ExtrinsicSuccess') {144        success = true;145      } else if ((section === 'common') && (method === 'ItemDestroyed')) {146        tokens.push({147          collectionId: parseInt(data[0].toString(), 10),148          tokenId: parseInt(data[1].toString(), 10),149          owner: data[2].toJSON(),150        });151      }152    });153    return {success, tokens};154  }155156  static findCollectionInEvents(events: {event: IEvent}[], collectionId: number, expectedSection: string, expectedMethod: string) {157    let eventId = null;158    events.forEach(({event: {data, method, section}}) => {159      if ((section === expectedSection) && (method === expectedMethod)) {160        eventId = parseInt(data[0].toString(), 10);161      }162    });163164    if (eventId === null) {165      throw Error(`No ${expectedMethod} event was found!`);166    }167    return eventId === collectionId;168  }169170  static isTokenTransferSuccess(events: {event: IEvent}[], collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {171    const normalizeAddress = (address: string | ICrossAccountId) => {172      if(typeof address === 'string') return address;173      const obj = {} as any;174      Object.keys(address).forEach(k => {175        obj[k.toLocaleLowerCase()] = address[k as 'Substrate' | 'Ethereum'];176      });177      if(obj.substrate) return {Substrate: this.normalizeSubstrateAddress(obj.substrate)};178      if(obj.ethereum) return {Ethereum: obj.ethereum.toLocaleLowerCase()};179      return address;180    };181    let transfer = {collectionId: null, tokenId: null, from: null, to: null, amount: 1} as any;182    events.forEach(({event: {data, method, section}}) => {183      if ((section === 'common') && (method === 'Transfer')) {184        const hData = (data as any).toJSON();185        transfer = {186          collectionId: hData[0],187          tokenId: hData[1],188          from: normalizeAddress(hData[2]),189          to: normalizeAddress(hData[3]),190          amount: BigInt(hData[4]),191        };192      }193    });194    let isSuccess = parseInt(collectionId.toString()) === transfer.collectionId && parseInt(tokenId.toString()) === transfer.tokenId;195    isSuccess = isSuccess && JSON.stringify(normalizeAddress(fromAddressObj)) === JSON.stringify(transfer.from);196    isSuccess = isSuccess && JSON.stringify(normalizeAddress(toAddressObj)) === JSON.stringify(transfer.to);197    isSuccess = isSuccess && amount === transfer.amount;198    return isSuccess;199  }200}201202class UniqueEventHelper {203  private static extractIndex(index: any): [number, number] | string {204    if(index.toRawType() === '[u8;2]') return [index[0], index[1]];205    return index.toJSON();206  }207208  private static extractSub(data: any, subTypes: any): {[key: string]: any} {209    let obj: any = {};210    let index = 0;211212    if (data.entries) {213      for(const [key, value] of data.entries()) {214        obj[key] = this.extractData(value, subTypes[index]);215        index++;216      }217    } else obj = data.toJSON();218219    return obj;220  }221  222  private static extractData(data: any, type: any): any {223    if (['u16', 'u32'].indexOf(type.type) > -1) return data.toNumber();224    if (['u64', 'u128', 'u256'].indexOf(type.type) > -1) return data.toBigInt();225    if(type.hasOwnProperty('sub')) return this.extractSub(data, type.sub);226    return data.toHuman();227  }228229  public static extractEvents(records: ITransactionResult): IEvent[] {230    const parsedEvents: IEvent[] = [];231232    records.result.events.forEach((record) => {233      const {event, phase} = record;234      const types = (event as any).typeDef;235236      const eventData: IEvent = {237        section: event.section.toString(),238        method: event.method.toString(),239        index: this.extractIndex(event.index),240        data: [],241        phase: phase.toJSON(),242      };243244      event.data.forEach((val: any, index: number) => {245        eventData.data.push(this.extractData(val, types[index]));246      });247248      parsedEvents.push(eventData);249    });250251    return parsedEvents;252  }253}254255class ChainHelperBase {256  transactionStatus = UniqueUtil.transactionStatus;257  chainLogType = UniqueUtil.chainLogType;258  util: typeof UniqueUtil;259  eventHelper: typeof UniqueEventHelper;260  logger: ILogger;261  api: ApiPromise | null;262  forcedNetwork: TUniqueNetworks | null;263  network: TUniqueNetworks | null;264  chainLog: IUniqueHelperLog[];265266  constructor(logger?: ILogger) {267    this.util = UniqueUtil;268    this.eventHelper = UniqueEventHelper;269    if (typeof logger == 'undefined') logger = this.util.getDefaultLogger();270    this.logger = logger;271    this.api = null;272    this.forcedNetwork = null;273    this.network = null;274    this.chainLog = [];275  }276277  clearChainLog(): void {278    this.chainLog = [];279  }280281  forceNetwork(value: TUniqueNetworks): void {282    this.forcedNetwork = value;283  }284285  async connect(wsEndpoint: string, listeners?: IApiListeners) {286    if (this.api !== null) throw Error('Already connected');287    const {api, network} = await ChainHelperBase.createConnection(wsEndpoint, listeners, this.forcedNetwork);288    this.api = api;289    this.network = network;290  }291292  async disconnect() {293    if (this.api === null) return;294    await this.api.disconnect();295    this.api = null;296    this.network = null;297  }298299  static async detectNetwork(api: ApiPromise): Promise<TUniqueNetworks> {300    const spec = (await api.query.system.lastRuntimeUpgrade()).toJSON() as any;301    if(['quartz', 'unique'].indexOf(spec.specName) > -1) return spec.specName;302    return 'opal';303  }304305  static async detectNetworkByWsEndpoint(wsEndpoint: string): Promise<TUniqueNetworks> {306    const api = new ApiPromise({provider: new WsProvider(wsEndpoint)});307    await api.isReady;308309    const network = await this.detectNetwork(api);310311    await api.disconnect();312313    return network;314  }315316  static async createConnection(wsEndpoint: string, listeners?: IApiListeners, network?: TUniqueNetworks | null): Promise<{317    api: ApiPromise;318    network: TUniqueNetworks;319  }> {320    if(typeof network === 'undefined' || network === null) network = 'opal';321    const supportedRPC = {322      opal: {323        unique: require('@unique-nft/opal-testnet-types/definitions').unique.rpc,324      },325      quartz: {326        unique: require('@unique-nft/quartz-mainnet-types/definitions').unique.rpc,327      },328      unique: {329        unique: require('@unique-nft/unique-mainnet-types/definitions').unique.rpc,330      },331    };332    if(!supportedRPC.hasOwnProperty(network)) network = await this.detectNetworkByWsEndpoint(wsEndpoint);333    const rpc = supportedRPC[network];334335    // TODO: investigate how to replace rpc in runtime336    // api._rpcCore.addUserInterfaces(rpc);337338    const api = new ApiPromise({provider: new WsProvider(wsEndpoint), rpc});339340    await api.isReadyOrError;341342    if (typeof listeners === 'undefined') listeners = {};343    for (const event of ['connected', 'disconnected', 'error', 'ready', 'decorated']) {344      if (!listeners.hasOwnProperty(event) || typeof listeners[event as TApiAllowedListeners] === 'undefined') continue;345      api.on(event as ApiInterfaceEvents, listeners[event as TApiAllowedListeners] as (...args: any[]) => any);346    }347348    return {api, network};349  }350351  getTransactionStatus(data: {events: {event: IEvent}[], status: any}) {352    const {events, status} = data;353    if (status.isReady) {354      return this.transactionStatus.NOT_READY;355    }356    if (status.isBroadcast) {357      return this.transactionStatus.NOT_READY;358    }359    if (status.isInBlock || status.isFinalized) {360      const errors = events.filter(e => e.event.method === 'ExtrinsicFailed');361      if (errors.length > 0) {362        return this.transactionStatus.FAIL;363      }364      if (events.filter(e => e.event.method === 'ExtrinsicSuccess').length > 0) {365        return this.transactionStatus.SUCCESS;366      }367    }368369    return this.transactionStatus.FAIL;370  }371372  signTransaction(sender: TSigner, transaction: any, options: Partial<SignerOptions> | null = null, label = 'transaction') {373    const sign = (callback: any) => {374      if(options !== null) return transaction.signAndSend(sender, options, callback);375      return transaction.signAndSend(sender, callback);376    };377    // eslint-disable-next-line no-async-promise-executor378    return new Promise(async (resolve, reject) => {379      try {380        const unsub = await sign((result: any) => {381          const status = this.getTransactionStatus(result);382383          if (status === this.transactionStatus.SUCCESS) {384            this.logger.log(`${label} successful`);385            unsub();386            resolve({result, status});387          } else if (status === this.transactionStatus.FAIL) {388            let moduleError = null;389390            if (result.hasOwnProperty('dispatchError')) {391              const dispatchError = result['dispatchError'];392393              if (dispatchError) {394                if (dispatchError.isModule) {395                  const modErr = dispatchError.asModule;396                  const errorMeta = dispatchError.registry.findMetaError(modErr);397398                  moduleError = `${errorMeta.section}.${errorMeta.name}`;399                } else {400                  moduleError = dispatchError.toHuman();401                }402              } else {403                this.logger.log(result, this.logger.level.ERROR);404              }405            }406407            this.logger.log(`Something went wrong with ${label}. Status: ${status}`, this.logger.level.ERROR);408            unsub();409            reject({status, moduleError, result});410          }411        });412      } catch (e) {413        this.logger.log(e, this.logger.level.ERROR);414        reject(e);415      }416    });417  }418419  constructApiCall(apiCall: string, params: any[]) {420    if(!apiCall.startsWith('api.')) throw Error(`Invalid api call: ${apiCall}`);421    let call = this.api as any;422    for(const part of apiCall.slice(4).split('.')) {423      call = call[part];424    }425    return call(...params);426  }427428  async executeExtrinsic(sender: TSigner, extrinsic: string, params: any[], expectSuccess=true, options: Partial<SignerOptions>|null = null/*, failureMessage='expected success'*/) {429    if(this.api === null) throw Error('API not initialized');430    if(!extrinsic.startsWith('api.tx.')) throw Error(`${extrinsic} is not transaction`);431432    const startTime = (new Date()).getTime();433    let result: ITransactionResult;434    let events: IEvent[] = [];435    try {436      result = await this.signTransaction(sender, this.constructApiCall(extrinsic, params), options, extrinsic) as ITransactionResult;437      events = this.eventHelper.extractEvents(result);438    }439    catch(e) {440      if(!(e as object).hasOwnProperty('status')) throw e;441      result = e as ITransactionResult;442    }443444    const endTime = (new Date()).getTime();445446    const log = {447      executedAt: endTime,448      executionTime: endTime - startTime,449      type: this.chainLogType.EXTRINSIC,450      status: result.status,451      call: extrinsic,452      signer: this.getSignerAddress(sender),453      params,454    } as IUniqueHelperLog;455456    if(result.status !== this.transactionStatus.SUCCESS && result.moduleError) log.moduleError = result.moduleError;457    if(events.length > 0) log.events = events;458459    this.chainLog.push(log);460461    if(expectSuccess && result.status !== this.transactionStatus.SUCCESS) throw Error(`${result.moduleError}`);462    return result;463  }464465  async callRpc(rpc: string, params?: any[]) {466    if(typeof params === 'undefined') params = [];467    if(this.api === null) throw Error('API not initialized');468    if(!rpc.startsWith('api.rpc.') && !rpc.startsWith('api.query.')) throw Error(`${rpc} is not RPC call`);469470    const startTime = (new Date()).getTime();471    let result;472    let error = null;473    const log = {474      type: this.chainLogType.RPC,475      call: rpc,476      params,477    } as IUniqueHelperLog;478479    try {480      result = await this.constructApiCall(rpc, params);481    }482    catch(e) {483      error = e;484    }485486    const endTime = (new Date()).getTime();487488    log.executedAt = endTime;489    log.status = (error === null ? this.transactionStatus.SUCCESS : this.transactionStatus.FAIL) as 'Fail' | 'Success';490    log.executionTime = endTime - startTime;491492    this.chainLog.push(log);493494    if(error !== null) throw error;495496    return result;497  }498499  getSignerAddress(signer: IKeyringPair | string): string {500    if(typeof signer === 'string') return signer;501    return signer.address;502  }503504  fetchAllPalletNames(): string[] {505    if(this.api === null) throw Error('API not initialized');506    return this.api.runtimeMetadata.asLatest.pallets.map(m => m.name.toString().toLowerCase());507  }508509  fetchMissingPalletNames(requiredPallets: string[]): string[] {510    const palletNames = this.fetchAllPalletNames();511    return requiredPallets.filter(p => !palletNames.includes(p));512  }513}514515516class HelperGroup {517  helper: UniqueHelper;518519  constructor(uniqueHelper: UniqueHelper) {520    this.helper = uniqueHelper;521  }522}523524525class CollectionGroup extends HelperGroup {526  /**527 * Get number of blocks when sponsored transaction is available.528 *529 * @param collectionId ID of collection530 * @param tokenId ID of token531 * @param addressObj address for which the sponsorship is checked532 * @example await getTokenNextSponsored(1, 2, {Substrate: '5DfhbVfww7ThF8q6f3...'});533 * @returns number of blocks or null if sponsorship hasn't been set534 */535  async getTokenNextSponsored(collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<number | null> {536    return (await this.helper.callRpc('api.rpc.unique.nextSponsored', [collectionId, addressObj, tokenId])).toJSON();537  }538539  /**540   * Get the number of created collections.541   *542   * @returns number of created collections543   */544  async getTotalCount(): Promise<number> {545    return (await this.helper.callRpc('api.rpc.unique.collectionStats')).created.toNumber();546  }547548  /**549   * Get information about the collection with additional data,550   * including the number of tokens it contains, its administrators,551   * the normalized address of the collection's owner, and decoded name and description.552   *553   * @param collectionId ID of collection554   * @example await getData(2)555   * @returns collection information object556   */557  async getData(collectionId: number): Promise<{558    id: number;559    name: string;560    description: string;561    tokensCount: number;562    admins: ICrossAccountId[];563    normalizedOwner: TSubstrateAccount;564    raw: any565  } | null> {566    const collection = await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId]);567    const humanCollection = collection.toHuman(), collectionData = {568      id: collectionId, name: null, description: null, tokensCount: 0, admins: [],569      raw: humanCollection,570    } as any, jsonCollection = collection.toJSON();571    if (humanCollection === null) return null;572    collectionData.raw.limits = jsonCollection.limits;573    collectionData.raw.permissions = jsonCollection.permissions;574    collectionData.normalizedOwner = this.helper.address.normalizeSubstrate(collectionData.raw.owner);575    for (const key of ['name', 'description']) {576      collectionData[key] = this.helper.util.vec2str(humanCollection[key]);577    }578579    collectionData.tokensCount = (['RFT', 'NFT'].includes(humanCollection.mode))580      ? await this.helper[humanCollection.mode.toLocaleLowerCase() as 'nft' | 'rft'].getLastTokenId(collectionId)581      : 0;582    collectionData.admins = await this.getAdmins(collectionId);583584    return collectionData;585  }586587  /**588   * Get the addresses of the collection's administrators, optionally normalized.589   *590   * @param collectionId ID of collection591   * @param normalize whether to normalize the addresses to the default ss58 format592   * @example await getAdmins(1)593   * @returns array of administrators594   */595  async getAdmins(collectionId: number, normalize = false): Promise<ICrossAccountId[]> {596    const admins = (await this.helper.callRpc('api.rpc.unique.adminlist', [collectionId])).toHuman();597598    return normalize599      ? admins.map((address: any) => {600        return address.Substrate601          ? {Substrate: this.helper.address.normalizeSubstrate(address.Substrate)}602          : address;603      })604      : admins;605  }606607  /**608   * Get the addresses added to the collection allow-list, optionally normalized.609   * @param collectionId ID of collection610   * @param normalize whether to normalize the addresses to the default ss58 format611   * @example await getAllowList(1)612   * @returns array of allow-listed addresses613   */614  async getAllowList(collectionId: number, normalize = false): Promise<ICrossAccountId[]> {615    const allowListed = (await this.helper.callRpc('api.rpc.unique.allowlist', [collectionId])).toHuman();616    return normalize617      ? allowListed.map((address: any) => {618        return address.Substrate619          ? {Substrate: this.helper.address.normalizeSubstrate(address.Substrate)}620          : address;621      })622      : allowListed;623  }624625  /**626   * Get the effective limits of the collection instead of null for default values627   *628   * @param collectionId ID of collection629   * @example await getEffectiveLimits(2)630   * @returns object of collection limits631   */632  async getEffectiveLimits(collectionId: number): Promise<ICollectionLimits> {633    return (await this.helper.callRpc('api.rpc.unique.effectiveCollectionLimits', [collectionId])).toJSON();634  }635636  /**637   * Burns the collection if the signer has sufficient permissions and collection is empty.638   *639   * @param signer keyring of signer640   * @param collectionId ID of collection641   * @example await helper.collection.burn(aliceKeyring, 3);642   * @returns ```true``` if extrinsic success, otherwise ```false```643   */644  async burn(signer: TSigner, collectionId: number): Promise<boolean> {645    const result = await this.helper.executeExtrinsic(646      signer,647      'api.tx.unique.destroyCollection', [collectionId],648      true,649    );650651    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionDestroyed');652  }653654  /**655   * Sets the sponsor for the collection (Requires the Substrate address). Needs confirmation by the sponsor.656   *657   * @param signer keyring of signer658   * @param collectionId ID of collection659   * @param sponsorAddress Sponsor substrate address660   * @example setSponsor(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...")661   * @returns ```true``` if extrinsic success, otherwise ```false```662   */663  async setSponsor(signer: TSigner, collectionId: number, sponsorAddress: TSubstrateAccount): Promise<boolean> {664    const result = await this.helper.executeExtrinsic(665      signer,666      'api.tx.unique.setCollectionSponsor', [collectionId, sponsorAddress],667      true,668    );669670    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionSponsorSet');671  }672673  /**674   * Confirms consent to sponsor the collection on behalf of the signer.675   *676   * @param signer keyring of signer677   * @param collectionId ID of collection678   * @example confirmSponsorship(aliceKeyring, 10)679   * @returns ```true``` if extrinsic success, otherwise ```false```680   */681  async confirmSponsorship(signer: TSigner, collectionId: number): Promise<boolean> {682    const result = await this.helper.executeExtrinsic(683      signer,684      'api.tx.unique.confirmSponsorship', [collectionId],685      true,686    );687688    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'SponsorshipConfirmed');689  }690691  /**692   * Removes the sponsor of a collection, regardless if it consented or not.693   *694   * @param signer keyring of signer695   * @param collectionId ID of collection696   * @example removeSponsor(aliceKeyring, 10)697   * @returns ```true``` if extrinsic success, otherwise ```false```698   */699  async removeSponsor(signer: TSigner, collectionId: number): Promise<boolean> {700    const result = await this.helper.executeExtrinsic(701      signer,702      'api.tx.unique.removeCollectionSponsor', [collectionId],703      true,704    );705706    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionSponsorRemoved');707  }708709  /**710   * Sets the limits of the collection. At least one limit must be specified for a correct call.711   *712   * @param signer keyring of signer713   * @param collectionId ID of collection714   * @param limits collection limits object715   * @example716   * await setLimits(717   *   aliceKeyring,718   *   10,719   *   {720   *     sponsorTransferTimeout: 0,721   *     ownerCanDestroy: false722   *   }723   * )724   * @returns ```true``` if extrinsic success, otherwise ```false```725   */726  async setLimits(signer: TSigner, collectionId: number, limits: ICollectionLimits): Promise<boolean> {727    const result = await this.helper.executeExtrinsic(728      signer,729      'api.tx.unique.setCollectionLimits', [collectionId, limits],730      true,731    );732733    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionLimitSet');734  }735736  /**737   * Changes the owner of the collection to the new Substrate address.738   *739   * @param signer keyring of signer740   * @param collectionId ID of collection741   * @param ownerAddress substrate address of new owner742   * @example changeOwner(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...")743   * @returns ```true``` if extrinsic success, otherwise ```false```744   */745  async changeOwner(signer: TSigner, collectionId: number, ownerAddress: TSubstrateAccount): Promise<boolean> {746    const result = await this.helper.executeExtrinsic(747      signer,748      'api.tx.unique.changeCollectionOwner', [collectionId, ownerAddress],749      true,750    );751752    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionOwnedChanged');753  }754755  /**756   * Adds a collection administrator.757   *758   * @param signer keyring of signer759   * @param collectionId ID of collection760   * @param adminAddressObj Administrator address (substrate or ethereum)761   * @example addAdmin(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."})762   * @returns ```true``` if extrinsic success, otherwise ```false```763   */764  async addAdmin(signer: TSigner, collectionId: number, adminAddressObj: ICrossAccountId): Promise<boolean> {765    const result = await this.helper.executeExtrinsic(766      signer,767      'api.tx.unique.addCollectionAdmin', [collectionId, adminAddressObj],768      true,769    );770771    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionAdminAdded');772  }773774  /**775   * Removes a collection administrator.776   *777   * @param signer keyring of signer778   * @param collectionId ID of collection779   * @param adminAddressObj Administrator address (substrate or ethereum)780   * @example removeAdmin(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."})781   * @returns ```true``` if extrinsic success, otherwise ```false```782   */783  async removeAdmin(signer: TSigner, collectionId: number, adminAddressObj: ICrossAccountId): Promise<boolean> {784    const result = await this.helper.executeExtrinsic(785      signer,786      'api.tx.unique.removeCollectionAdmin', [collectionId, adminAddressObj],787      true,788    );789790    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionAdminRemoved');791  }792793  /**794   * Check if user is in allow list.795   * 796   * @param collectionId ID of collection797   * @param user Account to check798   * @example await getAdmins(1)799   * @returns is user in allow list800   */801  async allowed(collectionId: number, user: ICrossAccountId): Promise<boolean> {802    return (await this.helper.callRpc('api.rpc.unique.allowed', [collectionId, user])).toJSON();803  }804805  /**806   * Adds an address to allow list807   * @param signer keyring of signer808   * @param collectionId ID of collection809   * @param addressObj address to add to the allow list810   * @returns ```true``` if extrinsic success, otherwise ```false```811   */812  async addToAllowList(signer: TSigner, collectionId: number, addressObj: ICrossAccountId): Promise<boolean> {813    const result = await this.helper.executeExtrinsic(814      signer,815      'api.tx.unique.addToAllowList', [collectionId, addressObj],816      true,817    );818819    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'AllowListAddressAdded');820  }821822  /**823   * Removes an address from allow list824   *825   * @param signer keyring of signer826   * @param collectionId ID of collection827   * @param addressObj address to remove from the allow list828   * @returns ```true``` if extrinsic success, otherwise ```false```829   */830  async removeFromAllowList(signer: TSigner, collectionId: number, addressObj: ICrossAccountId): Promise<boolean> {831    const result = await this.helper.executeExtrinsic(832      signer,833      'api.tx.unique.removeFromAllowList', [collectionId, addressObj],834      true,835    );836837    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'AllowListAddressRemoved');838  }839840  /**841   * Sets onchain permissions for selected collection.842   *843   * @param signer keyring of signer844   * @param collectionId ID of collection845   * @param permissions collection permissions object846   * @example setPermissions(aliceKeyring, 10, {access:'AllowList', mintMode: true, nesting: {collectionAdmin: true, tokenOwner: true}});847   * @returns ```true``` if extrinsic success, otherwise ```false```848   */849  async setPermissions(signer: TSigner, collectionId: number, permissions: ICollectionPermissions): Promise<boolean> {850    const result = await this.helper.executeExtrinsic(851      signer,852      'api.tx.unique.setCollectionPermissions', [collectionId, permissions],853      true,854    );855856    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionPermissionSet');857  }858859  /**860   * Enables nesting for selected collection. If `restricted` set, you can nest only tokens from specified collections.861   *862   * @param signer keyring of signer863   * @param collectionId ID of collection864   * @param permissions nesting permissions object865   * @example enableNesting(aliceKeyring, 10, {collectionAdmin: true, tokenOwner: true});866   * @returns ```true``` if extrinsic success, otherwise ```false```867   */868  async enableNesting(signer: TSigner, collectionId: number, permissions: INestingPermissions): Promise<boolean> {869    return await this.setPermissions(signer, collectionId, {nesting: permissions});870  }871872  /**873   * Disables nesting for selected collection.874   *875   * @param signer keyring of signer876   * @param collectionId ID of collection877   * @example disableNesting(aliceKeyring, 10);878   * @returns ```true``` if extrinsic success, otherwise ```false```879   */880  async disableNesting(signer: TSigner, collectionId: number): Promise<boolean> {881    return await this.setPermissions(signer, collectionId, {nesting: {tokenOwner: false, collectionAdmin: false}});882  }883884  /**885   * Sets onchain properties to the collection.886   *887   * @param signer keyring of signer888   * @param collectionId ID of collection889   * @param properties array of property objects890   * @example setProperties(aliceKeyring, 10, [{key: "gender", value: "male"}]);891   * @returns ```true``` if extrinsic success, otherwise ```false```892   */893  async setProperties(signer: TSigner, collectionId: number, properties: IProperty[]): Promise<boolean> {894    const result = await this.helper.executeExtrinsic(895      signer,896      'api.tx.unique.setCollectionProperties', [collectionId, properties],897      true,898    );899900    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPropertySet');901  }902903  /**904   * Get collection properties.905   * 906   * @param collectionId ID of collection907   * @param propertyKeys optionally filter the returned properties to only these keys908   * @example getProperties(1219, ['location', 'date', 'time', 'isParadise']);909   * @returns array of key-value pairs910   */911  async getProperties(collectionId: number, propertyKeys: string[] | null = null): Promise<IProperty[]> {912    return (await this.helper.callRpc('api.rpc.unique.collectionProperties', [collectionId, ...(propertyKeys === null ? [] : [propertyKeys])])).toHuman();913  }914915  /**916   * Deletes onchain properties from the collection.917   *918   * @param signer keyring of signer919   * @param collectionId ID of collection920   * @param propertyKeys array of property keys to delete921   * @example deleteProperties(aliceKeyring, 10, ["gender", "age"]);922   * @returns ```true``` if extrinsic success, otherwise ```false```923   */924  async deleteProperties(signer: TSigner, collectionId: number, propertyKeys: string[]): Promise<boolean> {925    const result = await this.helper.executeExtrinsic(926      signer,927      'api.tx.unique.deleteCollectionProperties', [collectionId, propertyKeys],928      true,929    );930931    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPropertyDeleted');932  }933934  /**935   * Changes the owner of the token.936   *937   * @param signer keyring of signer938   * @param collectionId ID of collection939   * @param tokenId ID of token940   * @param addressObj address of a new owner941   * @param amount amount of tokens to be transfered. For NFT must be set to 1n942   * @example transferToken(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."})943   * @returns true if the token success, otherwise false944   */945  async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId, amount=1n): Promise<boolean> {946    const result = await this.helper.executeExtrinsic(947      signer,948      'api.tx.unique.transfer', [addressObj, collectionId, tokenId, amount],949      true, // `Unable to transfer token #${tokenId} from collection #${collectionId}`,950    );951952    return this.helper.util.isTokenTransferSuccess(result.result.events, collectionId, tokenId, {Substrate: typeof signer === 'string' ? signer : signer.address}, addressObj, amount);953  }954955  /**956   *957   * Change ownership of a token(s) on behalf of the owner.958   *959   * @param signer keyring of signer960   * @param collectionId ID of collection961   * @param tokenId ID of token962   * @param fromAddressObj address on behalf of which the token will be sent963   * @param toAddressObj new token owner964   * @param amount amount of tokens to be transfered. For NFT must be set to 1n965   * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg"}, {Ethereum: "0x9F0583DbB85..."})966   * @returns true if the token success, otherwise false967   */968  async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {969    const result = await this.helper.executeExtrinsic(970      signer,971      'api.tx.unique.transferFrom', [fromAddressObj, toAddressObj, collectionId, tokenId, amount],972      true, // `Unable to transfer token #${tokenId} from collection #${collectionId}`,973    );974    return this.helper.util.isTokenTransferSuccess(result.result.events, collectionId, tokenId, fromAddressObj, toAddressObj, amount);975  }976977  /**978   *979   * Destroys a concrete instance of NFT/RFT or burns a specified amount of fungible tokens.980   *981   * @param signer keyring of signer982   * @param collectionId ID of collection983   * @param tokenId ID of token984   * @param amount amount of tokens to be burned. For NFT must be set to 1n985   * @example burnToken(aliceKeyring, 10, 5);986   * @returns ```true``` and burnt token number is extrinsic success. Otherwise ```false``` and ```null```987   */988  async burnToken(signer: TSigner, collectionId: number, tokenId: number, amount=1n): Promise<{989    success: boolean,990    token: number | null991  }> {992    const burnResult = await this.helper.executeExtrinsic(993      signer,994      'api.tx.unique.burnItem', [collectionId, tokenId, amount],995      true, // `Unable to burn token for ${label}`,996    );997    const burnedTokens = this.helper.util.extractTokensFromBurnResult(burnResult);998    if (burnedTokens.tokens.length > 1) throw Error('Burned multiple tokens');999    return {success: burnedTokens.success, token: burnedTokens.tokens.length > 0 ? burnedTokens.tokens[0] : null};1000  }10011002  /**1003   * Destroys a concrete instance of NFT on behalf of the owner1004   *1005   * @param signer keyring of signer1006   * @param collectionId ID of collection1007   * @param tokenId ID of token1008   * @param fromAddressObj address on behalf of which the token will be burnt1009   * @param amount amount of tokens to be burned. For NFT must be set to 1n1010   * @example burnTokenFrom(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."}, 5, {Ethereum: "0x9F0583DbB85..."})1011   * @returns ```true``` if extrinsic success, otherwise ```false```1012   */1013  async burnTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1014    const burnResult = await this.helper.executeExtrinsic(1015      signer,1016      'api.tx.unique.burnFrom', [collectionId, fromAddressObj, tokenId, amount],1017      true, // `Unable to burn token from for ${label}`,1018    );1019    const burnedTokens = this.helper.util.extractTokensFromBurnResult(burnResult);1020    return burnedTokens.success && burnedTokens.tokens.length > 0;1021  }10221023  /**1024   * Set, change, or remove approved address to transfer the ownership of the NFT.1025   *1026   * @param signer keyring of signer1027   * @param collectionId ID of collection1028   * @param tokenId ID of token1029   * @param toAddressObj Substrate or Ethereum address which gets approved use of the signer's tokens1030   * @param amount amount of token to be approved. For NFT must be set to 1n1031   * @returns ```true``` if extrinsic success, otherwise ```false```1032   */1033  async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {1034    const approveResult = await this.helper.executeExtrinsic(1035      signer,1036      'api.tx.unique.approve', [toAddressObj, collectionId, tokenId, amount],1037      true, // `Unable to approve token for ${label}`,1038    );10391040    return this.helper.util.findCollectionInEvents(approveResult.result.events, collectionId, 'common', 'Approved');1041  }10421043  /**1044   * Get the amount of token pieces approved to transfer or burn. Normally 0.1045   *1046   * @param collectionId ID of collection1047   * @param tokenId ID of token1048   * @param toAccountObj address which is approved to use token pieces1049   * @param fromAccountObj address which may have allowed the use of its owned tokens1050   * @example getTokenApprovedPieces(10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, {Substrate: "5ERZNF88Mm7UGfPP3mdG..."})1051   * @returns number of approved to transfer pieces1052   */1053  async getTokenApprovedPieces(collectionId: number, tokenId: number, toAccountObj: ICrossAccountId, fromAccountObj: ICrossAccountId): Promise<bigint> {1054    return (await this.helper.callRpc('api.rpc.unique.allowance', [collectionId, fromAccountObj, toAccountObj, tokenId])).toBigInt();1055  }10561057  /**1058   * Get the last created token ID in a collection1059   *1060   * @param collectionId ID of collection1061   * @example getLastTokenId(10);1062   * @returns id of the last created token1063   */1064  async getLastTokenId(collectionId: number): Promise<number> {1065    return (await this.helper.callRpc('api.rpc.unique.lastTokenId', [collectionId])).toNumber();1066  }10671068  /**1069   * Check if token exists1070   *1071   * @param collectionId ID of collection1072   * @param tokenId ID of token1073   * @example isTokenExists(10, 20);1074   * @returns true if the token exists, otherwise false1075   */1076  async isTokenExists(collectionId: number, tokenId: number): Promise<boolean> {1077    return (await this.helper.callRpc('api.rpc.unique.tokenExists', [collectionId, tokenId])).toJSON();1078  }1079}10801081class NFTnRFT extends CollectionGroup {1082  /**1083   * Get tokens owned by account1084   *1085   * @param collectionId ID of collection1086   * @param addressObj tokens owner1087   * @example getTokensByAddress(10, {Substrate: "5DyN4Y92vZCjv38fg..."})1088   * @returns array of token ids owned by account1089   */1090  async getTokensByAddress(collectionId: number, addressObj: ICrossAccountId): Promise<number[]> {1091    return (await this.helper.callRpc('api.rpc.unique.accountTokens', [collectionId, addressObj])).toJSON();1092  }10931094  /**1095   * Get token data1096   *1097   * @param collectionId ID of collection1098   * @param tokenId ID of token1099   * @param propertyKeys optionally filter the token properties to only these keys1100   * @param blockHashAt optionally query the data at some block with this hash1101   * @example getToken(10, 5);1102   * @returns human readable token data1103   */1104  async getToken(collectionId: number, tokenId: number, propertyKeys: string[] = [], blockHashAt?: string): Promise<{1105    properties: IProperty[];1106    owner: ICrossAccountId;1107    normalizedOwner: ICrossAccountId;1108  }| null> {1109    let tokenData;1110    if(typeof blockHashAt === 'undefined') {1111      tokenData = await this.helper.callRpc('api.rpc.unique.tokenData', [collectionId, tokenId]);1112    }1113    else {1114      if(propertyKeys.length == 0) {1115        const collection = (await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId])).toHuman();1116        if(!collection) return null;1117        propertyKeys = collection.tokenPropertyPermissions.map((x: ITokenPropertyPermission) => x.key);1118      }1119      tokenData = await this.helper.callRpc('api.rpc.unique.tokenData', [collectionId, tokenId, propertyKeys, blockHashAt]);1120    }1121    tokenData = tokenData.toHuman();1122    if (tokenData === null || tokenData.owner === null) return null;1123    const owner = {} as any;1124    for (const key of Object.keys(tokenData.owner)) {1125      owner[key.toLocaleLowerCase()] = key.toLocaleLowerCase() === 'substrate' ? this.helper.address.normalizeSubstrate(tokenData.owner[key]) : tokenData.owner[key];1126    }1127    tokenData.normalizedOwner = crossAccountIdFromLower(owner);1128    return tokenData;1129  }11301131  /**1132   * Set permissions to change token properties1133   *1134   * @param signer keyring of signer1135   * @param collectionId ID of collection1136   * @param permissions permissions to change a property by the collection admin or token owner1137   * @example setTokenPropertyPermissions(1138   *   aliceKeyring, 10, [{key: "gender", permission: {tokenOwner: true, mutable: true, collectionAdmin: true}}]1139   * )1140   * @returns true if extrinsic success otherwise false1141   */1142  async setTokenPropertyPermissions(signer: TSigner, collectionId: number, permissions: ITokenPropertyPermission[]): Promise<boolean> {1143    const result = await this.helper.executeExtrinsic(1144      signer,1145      'api.tx.unique.setTokenPropertyPermissions', [collectionId, permissions],1146      true,1147    );11481149    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'PropertyPermissionSet');1150  }11511152  /**1153   * Get token property permissions.1154   * 1155   * @param collectionId ID of collection1156   * @param propertyKeys optionally filter the returned property permissions to only these keys1157   * @example getPropertyPermissions(1219, ['location', 'date', 'time', 'isParadise']);1158   * @returns array of key-permission pairs1159   */1160  async getPropertyPermissions(collectionId: number, propertyKeys: string[] | null = null): Promise<ITokenPropertyPermission[]> {1161    return (await this.helper.callRpc('api.rpc.unique.propertyPermissions', [collectionId, ...(propertyKeys === null ? [] : [propertyKeys])])).toHuman();1162  }11631164  /**1165   * Set token properties1166   *1167   * @param signer keyring of signer1168   * @param collectionId ID of collection1169   * @param tokenId ID of token1170   * @param properties key-value pairs of metadata which to add to a token. Keys must be permitted in the collection1171   * @example setTokenProperties(aliceKeyring, 10, 5, [{key: "gender", value: "female"}, {key: "age", value: "23"}])1172   * @returns ```true``` if extrinsic success, otherwise ```false```1173   */1174  async setTokenProperties(signer: TSigner, collectionId: number, tokenId: number, properties: IProperty[]): Promise<boolean> {1175    const result = await this.helper.executeExtrinsic(1176      signer,1177      'api.tx.unique.setTokenProperties', [collectionId, tokenId, properties],1178      true,1179    );11801181    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'TokenPropertySet');1182  }11831184  /**1185   * Get properties, metadata assigned to a token.1186   * 1187   * @param collectionId ID of collection1188   * @param tokenId ID of token1189   * @param propertyKeys optionally filter the returned properties to only these keys1190   * @example getTokenProperties(1219, ['location', 'date', 'time', 'isParadise']);1191   * @returns array of key-value pairs1192   */1193  async getTokenProperties(collectionId: number, tokenId: number, propertyKeys: string[] | null = null): Promise<IProperty[]> {1194    return (await this.helper.callRpc('api.rpc.unique.tokenProperties', [collectionId, tokenId, ...(propertyKeys === null ? [] : [propertyKeys])])).toHuman();1195  }11961197  /**1198   * Delete the provided properties of a token1199   * @param signer keyring of signer1200   * @param collectionId ID of collection1201   * @param tokenId ID of token1202   * @param propertyKeys property keys to be deleted1203   * @example deleteTokenProperties(aliceKeyring, 10, 5, ["gender", "age"])1204   * @returns ```true``` if extrinsic success, otherwise ```false```1205   */1206  async deleteTokenProperties(signer: TSigner, collectionId: number, tokenId: number, propertyKeys: string[]): Promise<boolean> {1207    const result = await this.helper.executeExtrinsic(1208      signer,1209      'api.tx.unique.deleteTokenProperties', [collectionId, tokenId, propertyKeys],1210      true,1211    );12121213    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'TokenPropertyDeleted');1214  }12151216  /**1217   * Mint new collection1218   *1219   * @param signer keyring of signer1220   * @param collectionOptions basic collection options and properties1221   * @param mode NFT or RFT type of a collection1222   * @example mintCollection(aliceKeyring, {name: 'New', description: "New collection", tokenPrefix: "NEW"}, "NFT")1223   * @returns object of the created collection1224   */1225  async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions, mode: 'NFT' | 'RFT'): Promise<UniqueCollectionBase> {1226    collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; // Clone object1227    collectionOptions.mode = (mode === 'NFT') ? {nft: null} : {refungible: null};1228    for (const key of ['name', 'description', 'tokenPrefix']) {1229      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);1230    }1231    const creationResult = await this.helper.executeExtrinsic(1232      signer,1233      'api.tx.unique.createCollectionEx', [collectionOptions],1234      true, // errorLabel,1235    );1236    return this.getCollectionObject(this.helper.util.extractCollectionIdFromCreationResult(creationResult));1237  }12381239  getCollectionObject(_collectionId: number): any {1240    return null;1241  }12421243  getTokenObject(_collectionId: number, _tokenId: number): any {1244    return null;1245  }1246}124712481249class NFTGroup extends NFTnRFT {1250  /**1251   * Get collection object1252   * @param collectionId ID of collection1253   * @example getCollectionObject(2);1254   * @returns instance of UniqueNFTCollection1255   */1256  getCollectionObject(collectionId: number): UniqueNFTCollection {1257    return new UniqueNFTCollection(collectionId, this.helper);1258  }12591260  /**1261   * Get token object1262   * @param collectionId ID of collection1263   * @param tokenId ID of token1264   * @example getTokenObject(10, 5);1265   * @returns instance of UniqueNFTToken1266   */1267  getTokenObject(collectionId: number, tokenId: number): UniqueNFTToken {1268    return new UniqueNFTToken(tokenId, this.getCollectionObject(collectionId));1269  }12701271  /**1272   * Get token's owner1273   * @param collectionId ID of collection1274   * @param tokenId ID of token1275   * @param blockHashAt optionally query the data at the block with this hash1276   * @example getTokenOwner(10, 5);1277   * @returns Address in CrossAccountId format, e.g. {Substrate: "5DnSF6RRjwteE3BrCj..."}1278   */1279  async getTokenOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<ICrossAccountId> {1280    let owner;1281    if (typeof blockHashAt === 'undefined') {1282      owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId]);1283    } else {1284      owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId, blockHashAt]);1285    }1286    return crossAccountIdFromLower(owner.toJSON());1287  }12881289  /**1290   * Is token approved to transfer1291   * @param collectionId ID of collection1292   * @param tokenId ID of token1293   * @param toAccountObj address to be approved1294   * @returns ```true``` if extrinsic success, otherwise ```false```1295   */1296  async isTokenApproved(collectionId: number, tokenId: number, toAccountObj: ICrossAccountId): Promise<boolean> {1297    return (await this.getTokenApprovedPieces(collectionId, tokenId, toAccountObj, await this.getTokenOwner(collectionId, tokenId))) === 1n;1298  }12991300  /**1301   * Changes the owner of the token.1302   *1303   * @param signer keyring of signer1304   * @param collectionId ID of collection1305   * @param tokenId ID of token1306   * @param addressObj address of a new owner1307   * @example transferToken(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."})1308   * @returns ```true``` if extrinsic success, otherwise ```false```1309   */1310  async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<boolean> {1311    return await super.transferToken(signer, collectionId, tokenId, addressObj, 1n);1312  }13131314  /**1315   *1316   * Change ownership of a NFT on behalf of the owner.1317   *1318   * @param signer keyring of signer1319   * @param collectionId ID of collection1320   * @param tokenId ID of token1321   * @param fromAddressObj address on behalf of which the token will be sent1322   * @param toAddressObj new token owner1323   * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, {Ethereum: "0x9F0583DbB85..."})1324   * @returns ```true``` if extrinsic success, otherwise ```false```1325   */1326  async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId): Promise<boolean> {1327    return await super.transferTokenFrom(signer, collectionId, tokenId, fromAddressObj, toAddressObj, 1n);1328  }13291330  /**1331   * Recursively find the address that owns the token1332   * @param collectionId ID of collection1333   * @param tokenId ID of token1334   * @param blockHashAt1335   * @example getTokenTopmostOwner(10, 5);1336   * @returns address in CrossAccountId format, e.g. {Substrate: "5DyN4Y92vZCjv38fg..."}1337   */1338  async getTokenTopmostOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<ICrossAccountId | null> {1339    let owner;1340    if (typeof blockHashAt === 'undefined') {1341      owner = await this.helper.callRpc('api.rpc.unique.topmostTokenOwner', [collectionId, tokenId]);1342    } else {1343      owner = await this.helper.callRpc('api.rpc.unique.topmostTokenOwner', [collectionId, tokenId, blockHashAt]);1344    }13451346    if (owner === null) return null;13471348    owner = owner.toHuman();13491350    return owner.Substrate ? {Substrate: this.helper.address.normalizeSubstrate(owner.Substrate)} : owner;1351  }13521353  /**1354   * Get tokens nested in the provided token1355   * @param collectionId ID of collection1356   * @param tokenId ID of token1357   * @param blockHashAt optionally query the data at the block with this hash1358   * @example getTokenChildren(10, 5);1359   * @returns tokens whose depth of nesting is <= 51360   */1361  async getTokenChildren(collectionId: number, tokenId: number, blockHashAt?: string): Promise<IToken[]> {1362    let children;1363    if(typeof blockHashAt === 'undefined') {1364      children = await this.helper.callRpc('api.rpc.unique.tokenChildren', [collectionId, tokenId]);1365    } else {1366      children = await this.helper.callRpc('api.rpc.unique.tokenChildren', [collectionId, tokenId, blockHashAt]);1367    }13681369    return children.toJSON().map((x: any) => {1370      return {collectionId: x.collection, tokenId: x.token};1371    });1372  }13731374  /**1375   * Nest one token into another1376   * @param signer keyring of signer1377   * @param tokenObj token to be nested1378   * @param rootTokenObj token to be parent1379   * @example nestToken(aliceKeyring, {collectionId: 10, tokenId: 5}, {collectionId: 10, tokenId: 4});1380   * @returns ```true``` if extrinsic success, otherwise ```false```1381   */1382  async nestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken): Promise<boolean> {1383    const rootTokenAddress = this.helper.util.getNestingTokenAddress(rootTokenObj);1384    const result = await this.transferToken(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress);1385    if(!result) {1386      throw Error('Unable to nest token!');1387    }1388    return result;1389  }13901391  /**1392   * Remove token from nested state1393   * @param signer keyring of signer1394   * @param tokenObj token to unnest1395   * @param rootTokenObj parent of a token1396   * @param toAddressObj address of a new token owner1397   * @example unnestToken(aliceKeyring, {collectionId: 10, tokenId: 5}, {collectionId: 10, tokenId: 4}, {Substrate: "5DyN4Y92vZCjv38fg..."});1398   * @returns ```true``` if extrinsic success, otherwise ```false```1399   */1400  async unnestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken, toAddressObj: ICrossAccountId): Promise<boolean> {1401    const rootTokenAddress = this.helper.util.getNestingTokenAddress(rootTokenObj);1402    const result = await this.transferTokenFrom(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress, toAddressObj);1403    if(!result) {1404      throw Error('Unable to unnest token!');1405    }1406    return result;1407  }14081409  /**1410   * Mint new collection1411   * @param signer keyring of signer1412   * @param collectionOptions Collection options1413   * @example1414   * mintCollection(aliceKeyring, {1415   *   name: 'New',1416   *   description: 'New collection',1417   *   tokenPrefix: 'NEW',1418   * })1419   * @returns object of the created collection1420   */1421  async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}): Promise<UniqueNFTCollection> {1422    return await super.mintCollection(signer, collectionOptions, 'NFT') as UniqueNFTCollection;1423  }14241425  /**1426   * Mint new token1427   * @param signer keyring of signer1428   * @param data token data1429   * @returns created token object1430   */1431  async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; properties?: IProperty[]; }): Promise<UniqueNFTToken> {1432    const creationResult = await this.helper.executeExtrinsic(1433      signer,1434      'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {1435        nft: {1436          properties: data.properties,1437        },1438      }],1439      true,1440    );1441    const createdTokens = this.helper.util.extractTokensFromCreationResult(creationResult);1442    if (createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');1443    if (createdTokens.tokens.length < 1) throw Error('No tokens minted');1444    return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);1445  }14461447  /**1448   * Mint multiple NFT tokens1449   * @param signer keyring of signer1450   * @param collectionId ID of collection1451   * @param tokens array of tokens with owner and properties1452   * @example1453   * mintMultipleTokens(aliceKeyring, 10, [{1454   *     owner: {Substrate: "5DyN4Y92vZCjv38fg..."},1455   *     properties: [{key: "gender", value: "male"},{key: "age", value: "45"}],1456   *   },{1457   *     owner: {Ethereum: "0x9F0583DbB855d..."},1458   *     properties: [{key: "gender", value: "female"},{key: "age", value: "22"}],1459   * }]);1460   * @returns ```true``` if extrinsic success, otherwise ```false```1461   */1462  async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: {owner: ICrossAccountId, properties?: IProperty[]}[]): Promise<UniqueNFTToken[]> {1463    const creationResult = await this.helper.executeExtrinsic(1464      signer,1465      'api.tx.unique.createMultipleItemsEx', [collectionId, {NFT: tokens}],1466      true,1467    );1468    const collection = this.getCollectionObject(collectionId);1469    return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1470  }14711472  /**1473   * Mint multiple NFT tokens with one owner1474   * @param signer keyring of signer1475   * @param collectionId ID of collection1476   * @param owner tokens owner1477   * @param tokens array of tokens with owner and properties1478   * @example1479   * mintMultipleTokensWithOneOwner(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...", [{1480   *   properties: [{1481   *   key: "gender",1482   *   value: "female",1483   *  },{1484   *   key: "age",1485   *   value: "33",1486   *  }],1487   * }]);1488   * @returns array of newly created tokens1489   */1490  async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {properties?: IProperty[]}[]): Promise<UniqueNFTToken[]> {1491    const rawTokens = [];1492    for (const token of tokens) {1493      const raw = {NFT: {properties: token.properties}};1494      rawTokens.push(raw);1495    }1496    const creationResult = await this.helper.executeExtrinsic(1497      signer,1498      'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1499      true,1500    );1501    const collection = this.getCollectionObject(collectionId);1502    return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1503  }15041505  /**1506   * Set, change, or remove approved address to transfer the ownership of the NFT.1507   *1508   * @param signer keyring of signer1509   * @param collectionId ID of collection1510   * @param tokenId ID of token1511   * @param toAddressObj address to approve1512   * @example approveToken(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."})1513   * @returns ```true``` if extrinsic success, otherwise ```false```1514   */1515  async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId) {1516    return super.approveToken(signer, collectionId, tokenId, toAddressObj, 1n);1517  }1518}151915201521class RFTGroup extends NFTnRFT {1522  /**1523   * Get collection object1524   * @param collectionId ID of collection1525   * @example getCollectionObject(2);1526   * @returns instance of UniqueRFTCollection1527   */1528  getCollectionObject(collectionId: number): UniqueRFTCollection {1529    return new UniqueRFTCollection(collectionId, this.helper);1530  }15311532  /**1533   * Get token object1534   * @param collectionId ID of collection1535   * @param tokenId ID of token1536   * @example getTokenObject(10, 5);1537   * @returns instance of UniqueNFTToken1538   */1539  getTokenObject(collectionId: number, tokenId: number): UniqueRFTToken {1540    return new UniqueRFTToken(tokenId, this.getCollectionObject(collectionId));1541  }15421543  /**1544   * Get top 10 token owners with the largest number of pieces1545   * @param collectionId ID of collection1546   * @param tokenId ID of token1547   * @example getTokenTop10Owners(10, 5);1548   * @returns array of top 10 owners1549   */1550  async getTokenTop10Owners(collectionId: number, tokenId: number): Promise<ICrossAccountId[]> {1551    return (await this.helper.callRpc('api.rpc.unique.tokenOwners', [collectionId, tokenId])).toJSON().map(crossAccountIdFromLower);1552  }15531554  /**1555   * Get number of pieces owned by address1556   * @param collectionId ID of collection1557   * @param tokenId ID of token1558   * @param addressObj address token owner1559   * @example getTokenBalance(10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."});1560   * @returns number of pieces ownerd by address1561   */1562  async getTokenBalance(collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<bigint> {1563    return (await this.helper.callRpc('api.rpc.unique.balance', [collectionId, addressObj, tokenId])).toBigInt();1564  }15651566  /**1567   * Transfer pieces of token to another address1568   * @param signer keyring of signer1569   * @param collectionId ID of collection1570   * @param tokenId ID of token1571   * @param addressObj address of a new owner1572   * @param amount number of pieces to be transfered1573   * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, 2000n)1574   * @returns ```true``` if extrinsic success, otherwise ```false```1575   */1576  async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId, amount=1n): Promise<boolean> {1577    return await super.transferToken(signer, collectionId, tokenId, addressObj, amount);1578  }15791580  /**1581   * Change ownership of some pieces of RFT on behalf of the owner.1582   * @param signer keyring of signer1583   * @param collectionId ID of collection1584   * @param tokenId ID of token1585   * @param fromAddressObj address on behalf of which the token will be sent1586   * @param toAddressObj new token owner1587   * @param amount number of pieces to be transfered1588   * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, {Substrate: "5DfhbVfww7ThF8q6f3i..."}, 2000n)1589   * @returns ```true``` if extrinsic success, otherwise ```false```1590   */1591  async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1592    return await super.transferTokenFrom(signer, collectionId, tokenId, fromAddressObj, toAddressObj, amount);1593  }15941595  /**1596   * Mint new collection1597   * @param signer keyring of signer1598   * @param collectionOptions Collection options1599   * @example1600   * mintCollection(aliceKeyring, {1601   *   name: 'New',1602   *   description: 'New collection',1603   *   tokenPrefix: 'NEW',1604   * })1605   * @returns object of the created collection1606   */1607  async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}): Promise<UniqueRFTCollection> {1608    return await super.mintCollection(signer, collectionOptions, 'RFT') as UniqueRFTCollection;1609  }16101611  /**1612   * Mint new token1613   * @param signer keyring of signer1614   * @param data token data1615   * @example mintToken(aliceKeyring, {collectionId: 10, owner: {Substrate: '5GHoZe9c73RYbVzq...'}, pieces: 10000n});1616   * @returns created token object1617   */1618  async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; pieces: bigint; properties?: IProperty[]; }): Promise<UniqueRFTToken> {1619    const creationResult = await this.helper.executeExtrinsic(1620      signer,1621      'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {1622        refungible: {1623          pieces: data.pieces,1624          properties: data.properties,1625        },1626      }],1627      true,1628    );1629    const createdTokens = this.helper.util.extractTokensFromCreationResult(creationResult);1630    if (createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');1631    if (createdTokens.tokens.length < 1) throw Error('No tokens minted');1632    return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);1633  }16341635  async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: {owner: ICrossAccountId, pieces: bigint, properties?: IProperty[]}[]): Promise<UniqueRFTToken[]> {1636    throw Error('Not implemented');1637    const creationResult = await this.helper.executeExtrinsic(1638      signer,1639      'api.tx.unique.createMultipleItemsEx', [collectionId, {RefungibleMultipleOwners: tokens}],1640      true, // `Unable to mint RFT tokens for ${label}`,1641    );1642    const collection = this.getCollectionObject(collectionId);1643    return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1644  }16451646  /**1647   * Mint multiple RFT tokens with one owner1648   * @param signer keyring of signer1649   * @param collectionId ID of collection1650   * @param owner tokens owner1651   * @param tokens array of tokens with properties and pieces1652   * @example mintMultipleTokensWithOneOwner(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, [{pieces: 100000n, properties: [{key: "gender", value: "male"}]}]);1653   * @returns array of newly created RFT tokens1654   */1655  async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {pieces: bigint, properties?: IProperty[]}[]): Promise<UniqueRFTToken[]> {1656    const rawTokens = [];1657    for (const token of tokens) {1658      const raw = {ReFungible: {pieces: token.pieces, properties: token.properties}};1659      rawTokens.push(raw);1660    }1661    const creationResult = await this.helper.executeExtrinsic(1662      signer,1663      'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1664      true,1665    );1666    const collection = this.getCollectionObject(collectionId);1667    return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1668  }16691670  /**1671   * Destroys a concrete instance of RFT.1672   * @param signer keyring of signer1673   * @param collectionId ID of collection1674   * @param tokenId ID of token1675   * @param amount number of pieces to be burnt1676   * @example burnToken(aliceKeyring, 10, 5);1677   * @returns ```true``` and burnt token number, if extrinsic is successful. Otherwise ```false``` and ```null```1678   */1679  async burnToken(signer: IKeyringPair, collectionId: number, tokenId: number, amount=1n): Promise<{ success: boolean; token: number | null; }> {1680    return await super.burnToken(signer, collectionId, tokenId, amount);1681  }16821683  /**1684   * Destroys a concrete instance of RFT on behalf of the owner.1685   * @param signer keyring of signer1686   * @param collectionId ID of collection1687   * @param tokenId ID of token1688   * @param fromAddressObj address on behalf of which the token will be burnt1689   * @param amount number of pieces to be burnt1690   * @example burnTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, 2n)1691   * @returns ```true``` if extrinsic success, otherwise ```false```1692   */1693  async burnTokenFrom(signer: IKeyringPair, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1694    return await super.burnTokenFrom(signer, collectionId, tokenId, fromAddressObj, amount);1695  }16961697  /**1698   * Set, change, or remove approved address to transfer the ownership of the RFT.1699   *1700   * @param signer keyring of signer1701   * @param collectionId ID of collection1702   * @param tokenId ID of token1703   * @param toAddressObj address to approve1704   * @param amount number of pieces to be approved1705   * @example approveToken(aliceKeyring, 10, 5, {Substrate: "5GHoZe9c73RYbVzq..."}, "", 10000n);1706   * @returns true if the token success, otherwise false1707   */1708  async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {1709    return super.approveToken(signer, collectionId, tokenId, toAddressObj, amount);1710  }17111712  /**1713   * Get total number of pieces1714   * @param collectionId ID of collection1715   * @param tokenId ID of token1716   * @example getTokenTotalPieces(10, 5);1717   * @returns number of pieces1718   */1719  async getTokenTotalPieces(collectionId: number, tokenId: number): Promise<bigint> {1720    return (await this.helper.callRpc('api.rpc.unique.totalPieces', [collectionId, tokenId])).unwrap().toBigInt();1721  }17221723  /**1724   * Change number of token pieces. Signer must be the owner of all token pieces.1725   * @param signer keyring of signer1726   * @param collectionId ID of collection1727   * @param tokenId ID of token1728   * @param amount new number of pieces1729   * @example repartitionToken(aliceKeyring, 10, 5, 12345n);1730   * @returns true if the repartion was success, otherwise false1731   */1732  async repartitionToken(signer: TSigner, collectionId: number, tokenId: number, amount: bigint): Promise<boolean> {1733    const currentAmount = await this.getTokenTotalPieces(collectionId, tokenId);1734    const repartitionResult = await this.helper.executeExtrinsic(1735      signer,1736      'api.tx.unique.repartition', [collectionId, tokenId, amount],1737      true,1738    );1739    if(currentAmount < amount) return this.helper.util.findCollectionInEvents(repartitionResult.result.events, collectionId, 'common', 'ItemCreated');1740    return this.helper.util.findCollectionInEvents(repartitionResult.result.events, collectionId, 'common', 'ItemDestroyed');1741  }1742}174317441745class FTGroup extends CollectionGroup {1746  /**1747   * Get collection object1748   * @param collectionId ID of collection1749   * @example getCollectionObject(2);1750   * @returns instance of UniqueFTCollection1751   */1752  getCollectionObject(collectionId: number): UniqueFTCollection {1753    return new UniqueFTCollection(collectionId, this.helper);1754  }17551756  /**1757   * Mint new fungible collection1758   * @param signer keyring of signer1759   * @param collectionOptions Collection options1760   * @param decimalPoints number of token decimals1761   * @example1762   * mintCollection(aliceKeyring, {1763   *   name: 'New',1764   *   description: 'New collection',1765   *   tokenPrefix: 'NEW',1766   * }, 18)1767   * @returns newly created fungible collection1768   */1769  async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}, decimalPoints = 0): Promise<UniqueFTCollection> {1770    collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; // Clone object1771    if(collectionOptions.tokenPropertyPermissions) throw Error('Fungible collections has no tokenPropertyPermissions');1772    collectionOptions.mode = {fungible: decimalPoints};1773    for (const key of ['name', 'description', 'tokenPrefix']) {1774      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);1775    }1776    const creationResult = await this.helper.executeExtrinsic(1777      signer,1778      'api.tx.unique.createCollectionEx', [collectionOptions],1779      true,1780    );1781    return this.getCollectionObject(this.helper.util.extractCollectionIdFromCreationResult(creationResult));1782  }17831784  /**1785   * Mint tokens1786   * @param signer keyring of signer1787   * @param collectionId ID of collection1788   * @param owner address owner of new tokens1789   * @param amount amount of tokens to be meanted1790   * @example mintTokens(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq"}, 1000n);1791   * @returns ```true``` if extrinsic success, otherwise ```false```1792   */1793  async mintTokens(signer: TSigner, collectionId: number, amount: bigint, owner: ICrossAccountId | string): Promise<boolean> {1794    const creationResult = await this.helper.executeExtrinsic(1795      signer,1796      'api.tx.unique.createItem', [collectionId, (typeof owner === 'string') ? {Substrate: owner} : owner, {1797        fungible: {1798          value: amount,1799        },1800      }],1801      true, // `Unable to mint fungible tokens for ${label}`,1802    );1803    return this.helper.util.findCollectionInEvents(creationResult.result.events, collectionId, 'common', 'ItemCreated');1804  }18051806  /**1807   * Mint multiple Fungible tokens with one owner1808   * @param signer keyring of signer1809   * @param collectionId ID of collection1810   * @param owner tokens owner1811   * @param tokens array of tokens with properties and pieces1812   * @returns ```true``` if extrinsic success, otherwise ```false```1813   */1814  async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, tokens: {value: bigint}[], owner: ICrossAccountId): Promise<boolean> {1815    const rawTokens = [];1816    for (const token of tokens) {1817      const raw = {Fungible: {Value: token.value}};1818      rawTokens.push(raw);1819    }1820    const creationResult = await this.helper.executeExtrinsic(1821      signer,1822      'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1823      true,1824    );1825    return this.helper.util.findCollectionInEvents(creationResult.result.events, collectionId, 'common', 'ItemCreated');1826  }18271828  /**1829   * Get the top 10 owners with the largest balance for the Fungible collection1830   * @param collectionId ID of collection1831   * @example getTop10Owners(10);1832   * @returns array of ```ICrossAccountId```1833   */1834  async getTop10Owners(collectionId: number): Promise<ICrossAccountId[]> {1835    return (await this.helper.callRpc('api.rpc.unique.tokenOwners', [collectionId, 0])).toJSON().map(crossAccountIdFromLower);1836  }18371838  /**1839   * Get account balance1840   * @param collectionId ID of collection1841   * @param addressObj address of owner1842   * @example getBalance(10, {Substrate: "5GHoZe9c73RYbVzq..."})1843   * @returns amount of fungible tokens owned by address1844   */1845  async getBalance(collectionId: number, addressObj: ICrossAccountId): Promise<bigint> {1846    return (await this.helper.callRpc('api.rpc.unique.balance', [collectionId, addressObj, 0])).toBigInt();1847  }18481849  /**1850   * Transfer tokens to address1851   * @param signer keyring of signer1852   * @param collectionId ID of collection1853   * @param toAddressObj address recipient1854   * @param amount amount of tokens to be sent1855   * @example transfer(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, 1000n);1856   * @returns ```true``` if extrinsic success, otherwise ```false```1857   */1858  async transfer(signer: TSigner, collectionId: number, toAddressObj: ICrossAccountId, amount=1n) {1859    return await super.transferToken(signer, collectionId, 0, toAddressObj, amount);1860  }18611862  /**1863   * Transfer some tokens on behalf of the owner.1864   * @param signer keyring of signer1865   * @param collectionId ID of collection1866   * @param fromAddressObj address on behalf of which tokens will be sent1867   * @param toAddressObj address where token to be sent1868   * @param amount number of tokens to be sent1869   * @example transferFrom(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, {Substrate: "5DfhbVfww7ThF8q6f3ij..."}, 10000n);1870   * @returns ```true``` if extrinsic success, otherwise ```false```1871   */1872  async transferFrom(signer: TSigner, collectionId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {1873    return await super.transferTokenFrom(signer, collectionId, 0, fromAddressObj, toAddressObj, amount);1874  }18751876  /**1877   * Destroy some amount of tokens1878   * @param signer keyring of signer1879   * @param collectionId ID of collection1880   * @param amount amount of tokens to be destroyed1881   * @example burnTokens(aliceKeyring, 10, 1000n);1882   * @returns ```true``` if extrinsic success, otherwise ```false```1883   */1884  async burnTokens(signer: IKeyringPair, collectionId: number, amount=1n): Promise<boolean> {1885    return (await super.burnToken(signer, collectionId, 0, amount)).success;1886  }18871888  /**1889   * Burn some tokens on behalf of the owner.1890   * @param signer keyring of signer1891   * @param collectionId ID of collection1892   * @param fromAddressObj address on behalf of which tokens will be burnt1893   * @param amount amount of tokens to be burnt1894   * @example burnTokensFrom(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, 1000n);1895   * @returns ```true``` if extrinsic success, otherwise ```false```1896   */1897  async burnTokensFrom(signer: IKeyringPair, collectionId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1898    return await super.burnTokenFrom(signer, collectionId, 0, fromAddressObj, amount);1899  }19001901  /**1902   * Get total collection supply1903   * @param collectionId1904   * @returns1905   */1906  async getTotalPieces(collectionId: number): Promise<bigint> {1907    return (await this.helper.callRpc('api.rpc.unique.totalPieces', [collectionId, 0])).unwrap().toBigInt();1908  }19091910  /**1911   * Set, change, or remove approved address to transfer tokens.1912   *1913   * @param signer keyring of signer1914   * @param collectionId ID of collection1915   * @param toAddressObj address to be approved1916   * @param amount amount of tokens to be approved1917   * @example approveTokens(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, 1000n)1918   * @returns ```true``` if extrinsic success, otherwise ```false```1919   */1920  async approveTokens(signer: IKeyringPair, collectionId: number, toAddressObj: ICrossAccountId, amount=1n) {1921    return super.approveToken(signer, collectionId, 0, toAddressObj, amount);1922  }19231924  /**1925   * Get amount of fungible tokens approved to transfer1926   * @param collectionId ID of collection1927   * @param fromAddressObj owner of tokens1928   * @param toAddressObj the address approved for the transfer of tokens on behalf of the owner1929   * @returns number of tokens approved for the transfer1930   */1931  async getApprovedTokens(collectionId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {1932    return super.getTokenApprovedPieces(collectionId, 0, toAddressObj, fromAddressObj);1933  }1934}193519361937class ChainGroup extends HelperGroup {1938  /**1939   * Get system properties of a chain1940   * @example getChainProperties();1941   * @returns ss58Format, token decimals, and token symbol1942   */1943  getChainProperties(): IChainProperties {1944    const properties = (this.helper.api as any).registry.getChainProperties().toJSON();1945    return {1946      ss58Format: properties.ss58Format.toJSON(),1947      tokenDecimals: properties.tokenDecimals.toJSON(),1948      tokenSymbol: properties.tokenSymbol.toJSON(),1949    };1950  }19511952  /**1953   * Get chain header1954   * @example getLatestBlockNumber();1955   * @returns the number of the last block1956   */1957  async getLatestBlockNumber(): Promise<number> {1958    return (await this.helper.callRpc('api.rpc.chain.getHeader')).number.toNumber();1959  }19601961  /**1962   * Get block hash by block number1963   * @param blockNumber number of block1964   * @example getBlockHashByNumber(12345);1965   * @returns hash of a block1966   */1967  async getBlockHashByNumber(blockNumber: number): Promise<string | null> {1968    const blockHash = (await this.helper.callRpc('api.rpc.chain.getBlockHash', [blockNumber])).toJSON();1969    if(blockHash === '0x0000000000000000000000000000000000000000000000000000000000000000') return null;1970    return blockHash;1971  }19721973  // TODO add docs1974  async getBlock(blockHashOrNumber: string | number): Promise<IBlock | null> {1975    const blockHash = typeof blockHashOrNumber === 'string' ? blockHashOrNumber : await this.getBlockHashByNumber(blockHashOrNumber);1976    if (!blockHash) return null;1977    return (await this.helper.callRpc('api.rpc.chain.getBlock', [blockHash])).toHuman().block;1978  }19791980  /**1981   * Get account nonce1982   * @param address substrate address1983   * @example getNonce("5GrwvaEF5zXb26Fz...");1984   * @returns number, account's nonce1985   */1986  async getNonce(address: TSubstrateAccount): Promise<number> {1987    return (await (this.helper.api as any).query.system.account(address)).nonce.toNumber();1988  }1989}199019911992class BalanceGroup extends HelperGroup {1993  /**1994   * Representation of the native token in the smallest unit1995   * @example getOneTokenNominal()1996   * @returns ```BigInt``` representation of the native token in the smallest unit, e.g. ```1_000_000_000_000_000_000n``` for QTZ.1997   */1998  getOneTokenNominal(): bigint {1999    const chainProperties = this.helper.chain.getChainProperties();2000    return 10n ** BigInt((chainProperties.tokenDecimals || [18])[0]);2001  }20022003  /**2004   * Get substrate address balance2005   * @param address substrate address2006   * @example getSubstrate("5GrwvaEF5zXb26Fz...")2007   * @returns amount of tokens on address2008   */2009  async getSubstrate(address: TSubstrateAccount): Promise<bigint> {2010    return (await this.helper.callRpc('api.query.system.account', [address])).data.free.toBigInt();2011  }20122013  /**2014   * Get full substrate balance including free, miscFrozen, feeFrozen, and reserved2015   * @param address substrate address2016   * @returns2017   */2018  async getSubstrateFull(address: TSubstrateAccount): Promise<ISubstrateBalance> {2019    const accountInfo = (await this.helper.callRpc('api.query.system.account', [address])).data;2020    return {free: accountInfo.free.toBigInt(), miscFrozen: accountInfo.miscFrozen.toBigInt(), feeFrozen: accountInfo.feeFrozen.toBigInt(), reserved: accountInfo.reserved.toBigInt()};2021  }20222023  /**2024   * Get ethereum address balance2025   * @param address ethereum address2026   * @example getEthereum("0x9F0583DbB855d...")2027   * @returns amount of tokens on address2028   */2029  async getEthereum(address: TEthereumAccount): Promise<bigint> {2030    return (await this.helper.callRpc('api.rpc.eth.getBalance', [address])).toBigInt();2031  }20322033  /**2034   * Transfer tokens to substrate address2035   * @param signer keyring of signer2036   * @param address substrate address of a recipient2037   * @param amount amount of tokens to be transfered2038   * @example transferToSubstrate(aliceKeyring, "5GrwvaEF5zXb26Fz...", 100_000_000_000n);2039   * @returns ```true``` if extrinsic success, otherwise ```false```2040   */2041  async transferToSubstrate(signer: TSigner, address: TSubstrateAccount, amount: bigint | string): Promise<boolean> {2042    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}`*/);20432044    let transfer = {from: null, to: null, amount: 0n} as any;2045    result.result.events.forEach(({event: {data, method, section}}) => {2046      if ((section === 'balances') && (method === 'Transfer')) {2047        transfer = {2048          from: this.helper.address.normalizeSubstrate(data[0]),2049          to: this.helper.address.normalizeSubstrate(data[1]),2050          amount: BigInt(data[2]),2051        };2052      }2053    });2054    let isSuccess = this.helper.address.normalizeSubstrate(typeof signer === 'string' ? signer : signer.address) === transfer.from;2055    isSuccess = isSuccess && this.helper.address.normalizeSubstrate(address) === transfer.to;2056    isSuccess = isSuccess && BigInt(amount) === transfer.amount;2057    return isSuccess;2058  }2059}206020612062class AddressGroup extends HelperGroup {2063  /**2064   * Normalizes the address to the specified ss58 format, by default ```42```.2065   * @param address substrate address2066   * @param ss58Format format for address conversion, by default ```42```2067   * @example normalizeSubstrate("unjKJQJrRd238pkUZZvzDQrfKuM39zBSnQ5zjAGAGcdRhaJTx") // returns 5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY2068   * @returns substrate address converted to normalized (i.e., starting with 5) or specified explicitly representation2069   */2070  normalizeSubstrate(address: TSubstrateAccount, ss58Format = 42): TSubstrateAccount {2071    return this.helper.util.normalizeSubstrateAddress(address, ss58Format);2072  }20732074  /**2075   * Get address in the connected chain format2076   * @param address substrate address2077   * @example normalizeSubstrateToChainFormat("5GrwvaEF5zXb26Fz...") // returns unjKJQJrRd238pkUZZ... for Unique Network2078   * @returns address in chain format2079   */2080  async normalizeSubstrateToChainFormat(address: TSubstrateAccount): Promise<TSubstrateAccount> {2081    const info = this.helper.chain.getChainProperties();2082    return encodeAddress(decodeAddress(address), info.ss58Format);2083  }20842085  /**2086   * Get substrate mirror of an ethereum address2087   * @param ethAddress ethereum address2088   * @param toChainFormat false for normalized account2089   * @example ethToSubstrate('0x9F0583DbB855d...')2090   * @returns substrate mirror of a provided ethereum address2091   */2092  async ethToSubstrate(ethAddress: TEthereumAccount, toChainFormat=false): Promise<TSubstrateAccount> {2093    if(!toChainFormat) return evmToAddress(ethAddress);2094    const info = this.helper.chain.getChainProperties();2095    return evmToAddress(ethAddress, info.ss58Format);2096  }20972098  /**2099   * Get ethereum mirror of a substrate address2100   * @param subAddress substrate account2101   * @example substrateToEth("5DnSF6RRjwteE3BrC...")2102   * @returns ethereum mirror of a provided substrate address2103   */2104  substrateToEth(subAddress: TSubstrateAccount): TEthereumAccount {2105    return nesting.toChecksumAddress('0x' + Array.from(addressToEvm(subAddress), i => i.toString(16).padStart(2, '0')).join(''));2106  }2107}21082109class StakingGroup extends HelperGroup {2110  /**2111   * Stake tokens for App Promotion2112   * @param signer keyring of signer2113   * @param amountToStake amount of tokens to stake2114   * @param label extra label for log2115   * @returns2116   */2117  async stake(signer: TSigner, amountToStake: bigint, label?: string): Promise<boolean> {2118    if(typeof label === 'undefined') label = `${signer.address} amount: ${amountToStake}`;2119    const stakeResult = await this.helper.executeExtrinsic(2120      signer, 'api.tx.appPromotion.stake',2121      [amountToStake], true,2122    );2123    // TODO extract info from stakeResult2124    return true;2125  }21262127  /**2128   * Unstake tokens for App Promotion2129   * @param signer keyring of signer2130   * @param amountToUnstake amount of tokens to unstake2131   * @param label extra label for log2132   * @returns block number where balances will be unlocked2133   */2134  async unstake(signer: TSigner, label?: string): Promise<number> {2135    if(typeof label === 'undefined') label = `${signer.address}`;2136    const unstakeResult = await this.helper.executeExtrinsic(2137      signer, 'api.tx.appPromotion.unstake',2138      [], true,2139    );2140    // TODO extract block number fron events2141    return 1;2142  }21432144  /**2145   * Get total staked amount for address2146   * @param address substrate or ethereum address2147   * @returns total staked amount2148   */2149  async getTotalStaked(address?: ICrossAccountId): Promise<bigint> {2150    if (address) return (await this.helper.callRpc('api.rpc.appPromotion.totalStaked', [address])).toBigInt();2151    return (await this.helper.callRpc('api.rpc.appPromotion.totalStaked')).toBigInt();2152  }21532154  /**2155   * Get total staked per block2156   * @param address substrate or ethereum address2157   * @returns array of stakes. `block` – the number of the block in which the stake was made. `amount` - the number of tokens staked in the block2158   */2159  async getTotalStakedPerBlock(address: ICrossAccountId): Promise<IStakingInfo[]> {2160    const rawTotalStakerdPerBlock = await this.helper.callRpc('api.rpc.appPromotion.totalStakedPerBlock', [address]);2161    return rawTotalStakerdPerBlock.map(([block, amount]: any[]) => {2162      return { 2163        block: block.toBigInt(),2164        amount: amount.toBigInt(),2165      };2166    });2167  }21682169  /**2170   * Get total pending unstake amount for address2171   * @param address substrate or ethereum address2172   * @returns total pending unstake amount2173   */2174  async getPendingUnstake(address: ICrossAccountId): Promise<bigint> {2175    return (await this.helper.callRpc('api.rpc.appPromotion.pendingUnstake', [address])).toBigInt();2176  }21772178  /**2179   * Get pending unstake amount per block for address2180   * @param address substrate or ethereum address2181   * @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 block2182   */2183  async getPendingUnstakePerBlock(address: ICrossAccountId): Promise<IStakingInfo[]> {2184    const rawUnstakedPerBlock = await this.helper.callRpc('api.rpc.appPromotion.pendingUnstakePerBlock', [address]);2185    const result = rawUnstakedPerBlock.map(([block, amount]: any[]) => {2186      return {2187        block: block.toBigInt(),2188        amount: amount.toBigInt(),2189      };2190    });2191    return result;2192  }2193}21942195export class UniqueHelper extends ChainHelperBase {2196  chain: ChainGroup;2197  balance: BalanceGroup;2198  address: AddressGroup;2199  collection: CollectionGroup;2200  nft: NFTGroup;2201  rft: RFTGroup;2202  ft: FTGroup;2203  staking: StakingGroup;22042205  constructor(logger?: ILogger) {2206    super(logger);2207    this.chain = new ChainGroup(this);2208    this.balance = new BalanceGroup(this);2209    this.address = new AddressGroup(this);2210    this.collection = new CollectionGroup(this);2211    this.nft = new NFTGroup(this);2212    this.rft = new RFTGroup(this);2213    this.ft = new FTGroup(this);2214    this.staking = new StakingGroup(this);2215  }2216}221722182219export class UniqueCollectionBase {2220  helper: UniqueHelper;2221  collectionId: number;22222223  constructor(collectionId: number, uniqueHelper: UniqueHelper) {2224    this.collectionId = collectionId;2225    this.helper = uniqueHelper;2226  }22272228  async getData() {2229    return await this.helper.collection.getData(this.collectionId);2230  }22312232  async getLastTokenId() {2233    return await this.helper.collection.getLastTokenId(this.collectionId);2234  }22352236  async isTokenExists(tokenId: number) {2237    return await this.helper.collection.isTokenExists(this.collectionId, tokenId);2238  }22392240  async getAdmins() {2241    return await this.helper.collection.getAdmins(this.collectionId);2242  }22432244  async getAllowList() {2245    return await this.helper.collection.getAllowList(this.collectionId);2246  }22472248  async getEffectiveLimits() {2249    return await this.helper.collection.getEffectiveLimits(this.collectionId);2250  }22512252  async getProperties(propertyKeys: string[] | null = null) {2253    return await this.helper.collection.getProperties(this.collectionId, propertyKeys);2254  }22552256  async setSponsor(signer: TSigner, sponsorAddress: TSubstrateAccount) {2257    return await this.helper.collection.setSponsor(signer, this.collectionId, sponsorAddress);2258  }22592260  async confirmSponsorship(signer: TSigner) {2261    return await this.helper.collection.confirmSponsorship(signer, this.collectionId);2262  }22632264  async removeSponsor(signer: TSigner) {2265    return await this.helper.collection.removeSponsor(signer, this.collectionId);2266  }22672268  async setLimits(signer: TSigner, limits: ICollectionLimits) {2269    return await this.helper.collection.setLimits(signer, this.collectionId, limits);2270  }22712272  async changeOwner(signer: TSigner, ownerAddress: TSubstrateAccount) {2273    return await this.helper.collection.changeOwner(signer, this.collectionId, ownerAddress);2274  }22752276  async addAdmin(signer: TSigner, adminAddressObj: ICrossAccountId) {2277    return await this.helper.collection.addAdmin(signer, this.collectionId, adminAddressObj);2278  }22792280  async addToAllowList(signer: TSigner, addressObj: ICrossAccountId) {2281    return await this.helper.collection.addToAllowList(signer, this.collectionId, addressObj);2282  }22832284  async removeFromAllowList(signer: TSigner, addressObj: ICrossAccountId) {2285    return await this.helper.collection.removeFromAllowList(signer, this.collectionId, addressObj);2286  }22872288  async removeAdmin(signer: TSigner, adminAddressObj: ICrossAccountId) {2289    return await this.helper.collection.removeAdmin(signer, this.collectionId, adminAddressObj);2290  }22912292  async setProperties(signer: TSigner, properties: IProperty[]) {2293    return await this.helper.collection.setProperties(signer, this.collectionId, properties);2294  }22952296  async deleteProperties(signer: TSigner, propertyKeys: string[]) {2297    return await this.helper.collection.deleteProperties(signer, this.collectionId, propertyKeys);2298  }22992300  async getTokenNextSponsored(tokenId: number, addressObj: ICrossAccountId) {2301    return await this.helper.collection.getTokenNextSponsored(this.collectionId, tokenId, addressObj);2302  }23032304  async setPermissions(signer: TSigner, permissions: ICollectionPermissions) {2305    return await this.helper.collection.setPermissions(signer, this.collectionId, permissions);2306  }23072308  async enableNesting(signer: TSigner, permissions: INestingPermissions) {2309    return await this.helper.collection.enableNesting(signer, this.collectionId, permissions);2310  }23112312  async disableNesting(signer: TSigner) {2313    return await this.helper.collection.disableNesting(signer, this.collectionId);2314  }23152316  async burn(signer: TSigner) {2317    return await this.helper.collection.burn(signer, this.collectionId);2318  }2319}232023212322export class UniqueNFTCollection extends UniqueCollectionBase {2323  getTokenObject(tokenId: number) {2324    return new UniqueNFTToken(tokenId, this);2325  }23262327  async getTokensByAddress(addressObj: ICrossAccountId) {2328    return await this.helper.nft.getTokensByAddress(this.collectionId, addressObj);2329  }23302331  async getToken(tokenId: number, blockHashAt?: string) {2332    return await this.helper.nft.getToken(this.collectionId, tokenId, [], blockHashAt);2333  }23342335  async getTokenOwner(tokenId: number, blockHashAt?: string) {2336    return await this.helper.nft.getTokenOwner(this.collectionId, tokenId, blockHashAt);2337  }23382339  async getTokenTopmostOwner(tokenId: number, blockHashAt?: string) {2340    return await this.helper.nft.getTokenTopmostOwner(this.collectionId, tokenId, blockHashAt);2341  }23422343  async getTokenChildren(tokenId: number, blockHashAt?: string) {2344    return await this.helper.nft.getTokenChildren(this.collectionId, tokenId, blockHashAt);2345  }23462347  async getPropertyPermissions(propertyKeys: string[] | null = null) {2348    return await this.helper.nft.getPropertyPermissions(this.collectionId, propertyKeys);2349  }23502351  async getTokenProperties(tokenId: number, propertyKeys: string[] | null = null) {2352    return await this.helper.nft.getTokenProperties(this.collectionId, tokenId, propertyKeys);2353  }23542355  async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId) {2356    return await this.helper.nft.transferToken(signer, this.collectionId, tokenId, addressObj);2357  }23582359  async transferTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2360    return await this.helper.nft.transferTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, toAddressObj);2361  }23622363  async approveToken(signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId) {2364    return await this.helper.nft.approveToken(signer, this.collectionId, tokenId, toAddressObj);2365  }23662367  async isTokenApproved(tokenId: number, toAddressObj: ICrossAccountId) {2368    return await this.helper.nft.isTokenApproved(this.collectionId, tokenId, toAddressObj);2369  }23702371  async mintToken(signer: TSigner, owner: ICrossAccountId = {Substrate: signer.address}, properties?: IProperty[]) {2372    return await this.helper.nft.mintToken(signer, {collectionId: this.collectionId, owner, properties});2373  }23742375  async mintMultipleTokens(signer: TSigner, tokens: {owner: ICrossAccountId, properties?: IProperty[]}[]) {2376    return await this.helper.nft.mintMultipleTokens(signer, this.collectionId, tokens);2377  }23782379  async burnToken(signer: TSigner, tokenId: number) {2380    return await this.helper.nft.burnToken(signer, this.collectionId, tokenId);2381  }23822383  async burnTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId) {2384    return await this.helper.nft.burnTokenFrom(signer, this.collectionId, tokenId, fromAddressObj);2385  }23862387  async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[]) {2388    return await this.helper.nft.setTokenProperties(signer, this.collectionId, tokenId, properties);2389  }23902391  async deleteTokenProperties(signer: TSigner, tokenId: number, propertyKeys: string[]) {2392    return await this.helper.nft.deleteTokenProperties(signer, this.collectionId, tokenId, propertyKeys);2393  }23942395  async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[]) {2396    return await this.helper.nft.setTokenPropertyPermissions(signer, this.collectionId, permissions);2397  }23982399  async nestToken(signer: TSigner, tokenId: number, toTokenObj: IToken) {2400    return await this.helper.nft.nestToken(signer, {collectionId: this.collectionId, tokenId}, toTokenObj);2401  }24022403  async unnestToken(signer: TSigner, tokenId: number, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {2404    return await this.helper.nft.unnestToken(signer, {collectionId: this.collectionId, tokenId}, fromTokenObj, toAddressObj);2405  }2406}240724082409export class UniqueRFTCollection extends UniqueCollectionBase {2410  getTokenObject(tokenId: number) {2411    return new UniqueRFTToken(tokenId, this);2412  }24132414  async getToken(tokenId: number, blockHashAt?: string) {2415    return await this.helper.rft.getToken(this.collectionId, tokenId, [], blockHashAt);2416  }24172418  async getTokensByAddress(addressObj: ICrossAccountId) {2419    return await this.helper.rft.getTokensByAddress(this.collectionId, addressObj);2420  }24212422  async getTop10TokenOwners(tokenId: number) {2423    return await this.helper.rft.getTokenTop10Owners(this.collectionId, tokenId);2424  }24252426  async getTokenBalance(tokenId: number, addressObj: ICrossAccountId) {2427    return await this.helper.rft.getTokenBalance(this.collectionId, tokenId, addressObj);2428  }24292430  async getTokenTotalPieces(tokenId: number) {2431    return await this.helper.rft.getTokenTotalPieces(this.collectionId, tokenId);2432  }24332434  async getPropertyPermissions(propertyKeys: string[] | null = null) {2435    return await this.helper.rft.getPropertyPermissions(this.collectionId, propertyKeys);2436  }24372438  async getTokenProperties(tokenId: number, propertyKeys: string[] | null = null) {2439    return await this.helper.rft.getTokenProperties(this.collectionId, tokenId, propertyKeys);2440  }24412442  async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId, amount=1n) {2443    return await this.helper.rft.transferToken(signer, this.collectionId, tokenId, addressObj, amount);2444  }24452446  async transferTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {2447    return await this.helper.rft.transferTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, toAddressObj, amount);2448  }24492450  async approveToken(signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {2451    return await this.helper.rft.approveToken(signer, this.collectionId, tokenId, toAddressObj, amount);2452  }24532454  async getTokenApprovedPieces(tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2455    return await this.helper.rft.getTokenApprovedPieces(this.collectionId, tokenId, toAddressObj, fromAddressObj);2456  }24572458  async repartitionToken(signer: TSigner, tokenId: number, amount: bigint) {2459    return await this.helper.rft.repartitionToken(signer, this.collectionId, tokenId, amount);2460  }24612462  async mintToken(signer: TSigner, pieces=1n, owner: ICrossAccountId = {Substrate: signer.address}, properties?: IProperty[]) {2463    return await this.helper.rft.mintToken(signer, {collectionId: this.collectionId, owner, pieces, properties});2464  }24652466  async mintMultipleTokens(signer: TSigner, tokens: {pieces: bigint, owner: ICrossAccountId, properties?: IProperty[]}[]) {2467    return await this.helper.rft.mintMultipleTokens(signer, this.collectionId, tokens);2468  }24692470  async burnToken(signer: TSigner, tokenId: number, amount=1n) {2471    return await this.helper.rft.burnToken(signer, this.collectionId, tokenId, amount);2472  }24732474  async burnTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId,  amount=1n) {2475    return await this.helper.rft.burnTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, amount);2476  }24772478  async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[]) {2479    return await this.helper.rft.setTokenProperties(signer, this.collectionId, tokenId, properties);2480  }24812482  async deleteTokenProperties(signer: TSigner, tokenId: number, propertyKeys: string[]) {2483    return await this.helper.rft.deleteTokenProperties(signer, this.collectionId, tokenId, propertyKeys);2484  }24852486  async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[]) {2487    return await this.helper.rft.setTokenPropertyPermissions(signer, this.collectionId, permissions);2488  }2489}249024912492export class UniqueFTCollection extends UniqueCollectionBase {2493  async mint(signer: TSigner, amount=1n, owner: ICrossAccountId = {Substrate: signer.address}) {2494    return await this.helper.ft.mintTokens(signer, this.collectionId, amount, owner);2495  }24962497  async mintWithOneOwner(signer: TSigner, tokens: {value: bigint}[], owner: ICrossAccountId = {Substrate: signer.address}) {2498    return await this.helper.ft.mintMultipleTokensWithOneOwner(signer, this.collectionId, tokens, owner);2499  }25002501  async getBalance(addressObj: ICrossAccountId) {2502    return await this.helper.ft.getBalance(this.collectionId, addressObj);2503  }25042505  async getTop10Owners() {2506    return await this.helper.ft.getTop10Owners(this.collectionId);2507  }25082509  async transfer(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {2510    return await this.helper.ft.transfer(signer, this.collectionId, toAddressObj, amount);2511  }25122513  async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {2514    return await this.helper.ft.transferFrom(signer, this.collectionId, fromAddressObj, toAddressObj, amount);2515  }25162517  async burnTokens(signer: TSigner, amount=1n) {2518    return await this.helper.ft.burnTokens(signer, this.collectionId, amount);2519  }25202521  async burnTokensFrom(signer: TSigner, fromAddressObj: ICrossAccountId, amount=1n) {2522    return await this.helper.ft.burnTokensFrom(signer, this.collectionId, fromAddressObj, amount);2523  }25242525  async getTotalPieces() {2526    return await this.helper.ft.getTotalPieces(this.collectionId);2527  }25282529  async approveTokens(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {2530    return await this.helper.ft.approveTokens(signer, this.collectionId, toAddressObj, amount);2531  }25322533  async getApprovedTokens(fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2534    return await this.helper.ft.getApprovedTokens(this.collectionId, fromAddressObj, toAddressObj);2535  }2536}253725382539export class UniqueTokenBase implements IToken {2540  collection: UniqueNFTCollection | UniqueRFTCollection;2541  collectionId: number;2542  tokenId: number;25432544  constructor(tokenId: number, collection: UniqueNFTCollection | UniqueRFTCollection) {2545    this.collection = collection;2546    this.collectionId = collection.collectionId;2547    this.tokenId = tokenId;2548  }25492550  async getNextSponsored(addressObj: ICrossAccountId) {2551    return await this.collection.getTokenNextSponsored(this.tokenId, addressObj);2552  }25532554  async getProperties(propertyKeys: string[] | null = null) {2555    return await this.collection.getTokenProperties(this.tokenId, propertyKeys);2556  }25572558  async setProperties(signer: TSigner, properties: IProperty[]) {2559    return await this.collection.setTokenProperties(signer, this.tokenId, properties);2560  }25612562  async deleteProperties(signer: TSigner, propertyKeys: string[]) {2563    return await this.collection.deleteTokenProperties(signer, this.tokenId, propertyKeys);2564  }25652566  nestingAddress() {2567    return this.collection.helper.util.getNestingTokenAddress(this);2568  }2569}257025712572export class UniqueNFTToken extends UniqueTokenBase {2573  collection: UniqueNFTCollection;25742575  constructor(tokenId: number, collection: UniqueNFTCollection) {2576    super(tokenId, collection);2577    this.collection = collection;2578  }25792580  async getData(blockHashAt?: string) {2581    return await this.collection.getToken(this.tokenId, blockHashAt);2582  }25832584  async getOwner(blockHashAt?: string) {2585    return await this.collection.getTokenOwner(this.tokenId, blockHashAt);2586  }25872588  async getTopmostOwner(blockHashAt?: string) {2589    return await this.collection.getTokenTopmostOwner(this.tokenId, blockHashAt);2590  }25912592  async getChildren(blockHashAt?: string) {2593    return await this.collection.getTokenChildren(this.tokenId, blockHashAt);2594  }25952596  async nest(signer: TSigner, toTokenObj: IToken) {2597    return await this.collection.nestToken(signer, this.tokenId, toTokenObj);2598  }25992600  async unnest(signer: TSigner, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {2601    return await this.collection.unnestToken(signer, this.tokenId, fromTokenObj, toAddressObj);2602  }26032604  async transfer(signer: TSigner, addressObj: ICrossAccountId) {2605    return await this.collection.transferToken(signer, this.tokenId, addressObj);2606  }26072608  async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2609    return await this.collection.transferTokenFrom(signer, this.tokenId, fromAddressObj, toAddressObj);2610  }26112612  async approve(signer: TSigner, toAddressObj: ICrossAccountId) {2613    return await this.collection.approveToken(signer, this.tokenId, toAddressObj);2614  }26152616  async isApproved(toAddressObj: ICrossAccountId) {2617    return await this.collection.isTokenApproved(this.tokenId, toAddressObj);2618  }26192620  async burn(signer: TSigner) {2621    return await this.collection.burnToken(signer, this.tokenId);2622  }26232624  async burnFrom(signer: TSigner, fromAddressObj: ICrossAccountId) {2625    return await this.collection.burnTokenFrom(signer, this.tokenId, fromAddressObj);2626  }2627}26282629export class UniqueRFTToken extends UniqueTokenBase {2630  collection: UniqueRFTCollection;26312632  constructor(tokenId: number, collection: UniqueRFTCollection) {2633    super(tokenId, collection);2634    this.collection = collection;2635  }26362637  async getData(blockHashAt?: string) {2638    return await this.collection.getToken(this.tokenId, blockHashAt);2639  }26402641  async getTop10Owners() {2642    return await this.collection.getTop10TokenOwners(this.tokenId);2643  }26442645  async getBalance(addressObj: ICrossAccountId) {2646    return await this.collection.getTokenBalance(this.tokenId, addressObj);2647  }26482649  async getTotalPieces() {2650    return await this.collection.getTokenTotalPieces(this.tokenId);2651  }26522653  async transfer(signer: TSigner, addressObj: ICrossAccountId, amount=1n) {2654    return await this.collection.transferToken(signer, this.tokenId, addressObj, amount);2655  }26562657  async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {2658    return await this.collection.transferTokenFrom(signer, this.tokenId, fromAddressObj, toAddressObj, amount);2659  }26602661  async approve(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {2662    return await this.collection.approveToken(signer, this.tokenId, toAddressObj, amount);2663  }26642665  async getApprovedPieces(fromAddressObj: ICrossAccountId, toAccountObj: ICrossAccountId) {2666    return await this.collection.getTokenApprovedPieces(this.tokenId, fromAddressObj, toAccountObj);2667  }26682669  async repartition(signer: TSigner, amount: bigint) {2670    return await this.collection.repartitionToken(signer, this.tokenId, amount);2671  }26722673  async burn(signer: TSigner, amount=1n) {2674    return await this.collection.burnToken(signer, this.tokenId, amount);2675  }26762677  async burnFrom(signer: TSigner, fromAddressObj: ICrossAccountId, amount=1n) {2678    return await this.collection.burnTokenFrom(signer, this.tokenId, fromAddressObj, amount);2679  }2680}