git.delta.rocks / unique-network / refs/commits / 9e257c429776

difftreelog

Merge branch 'develop' into feature/rmrk-proxy-rebased SS58 fixes

Daniel Shiposha2022-06-09parents: #c0e762d #66f33e3.patch.diff
in: master

21 files changed

deletedtests/src/accounts.tsdiffbeforeafterboth
--- a/tests/src/accounts.ts
+++ /dev/null
@@ -1,20 +0,0 @@
-// 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/>.
-
-export const bobsPublicKey = '5FHneW46xGXgs5mUiveU4sbTyGBzmstUspZC92UhjJM694ty';
-export const alicesPublicKey = '5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY';
-export const ferdiesPublicKey = '5CiPPseXPECbkjWCa6MnjNokrgYjMqmKndv2rSnekmSK2DjL';
-export const nullPublicKey = '5C4hrfjw9DjXZTzV3MwzrrAr9P1MJhSrvWGWqi1eSuyUpnhM';
\ No newline at end of file
modifiedtests/src/addToContractAllowList.test.tsdiffbeforeafterboth
--- a/tests/src/addToContractAllowList.test.ts
+++ b/tests/src/addToContractAllowList.test.ts
@@ -32,7 +32,7 @@
   it('Add an address to a contract allow list', async () => {
     await usingApi(async (api, privateKeyWrapper) => {
       const bob = privateKeyWrapper('//Bob');
-      const [contract, deployer] = await deployFlipper(api);
+      const [contract, deployer] = await deployFlipper(api, privateKeyWrapper);
 
       const allowListedBefore = (await api.query.unique.contractAllowList(contract.address, bob.address)).toJSON();
       const addTx = api.tx.unique.addToContractAllowList(contract.address, bob.address);
@@ -48,7 +48,7 @@
   it('Adding same address to allow list repeatedly should not produce errors', async () => {
     await usingApi(async (api, privateKeyWrapper) => {
       const bob = privateKeyWrapper('//Bob');
-      const [contract, deployer] = await deployFlipper(api);
+      const [contract, deployer] = await deployFlipper(api, privateKeyWrapper);
 
       const allowListedBefore = (await api.query.unique.contractAllowList(contract.address, bob.address)).toJSON();
       const addTx = api.tx.unique.addToContractAllowList(contract.address, bob.address);
@@ -87,7 +87,7 @@
   it('Add to a contract allow list using a non-owner address', async () => {
     await usingApi(async (api, privateKeyWrapper) => {
       const bob = privateKeyWrapper('//Bob');
-      const [contract] = await deployFlipper(api);
+      const [contract] = await deployFlipper(api, privateKeyWrapper);
 
       const allowListedBefore = (await api.query.unique.contractAllowList(contract.address, bob.address)).toJSON();
       const addTx = api.tx.unique.addToContractAllowList(contract.address, bob.address);
modifiedtests/src/burnItem.test.tsdiffbeforeafterboth
--- a/tests/src/burnItem.test.ts
+++ b/tests/src/burnItem.test.ts
@@ -15,7 +15,6 @@
 // along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
 
 import {default as usingApi, submitTransactionAsync, submitTransactionExpectFailAsync} from './substrate/substrate-api';
-import {Keyring} from '@polkadot/api';
 import {IKeyringPair} from '@polkadot/types/types';
 import {
   createCollectionExpectSuccess,
@@ -37,10 +36,9 @@
 
 describe('integration test: ext. burnItem():', () => {
   before(async () => {
-    await usingApi(async () => {
-      const keyring = new Keyring({type: 'sr25519'});
-      alice = keyring.addFromUri('//Alice');
-      bob = keyring.addFromUri('//Bob');
+    await usingApi(async (api, privateKeyWrapper) => {
+      alice = privateKeyWrapper('//Alice');
+      bob = privateKeyWrapper('//Bob');
     });
   });
 
@@ -142,10 +140,9 @@
 
 describe('integration test: ext. burnItem() with admin permissions:', () => {
   before(async () => {
-    await usingApi(async () => {
-      const keyring = new Keyring({type: 'sr25519'});
-      alice = keyring.addFromUri('//Alice');
-      bob = keyring.addFromUri('//Bob');
+    await usingApi(async (api, privateKeyWrapper) => {
+      alice = privateKeyWrapper('//Alice');
+      bob = privateKeyWrapper('//Bob');
     });
   });
 
@@ -209,10 +206,9 @@
 
 describe('Negative integration test: ext. burnItem():', () => {
   before(async () => {
-    await usingApi(async () => {
-      const keyring = new Keyring({type: 'sr25519'});
-      alice = keyring.addFromUri('//Alice');
-      bob = keyring.addFromUri('//Bob');
+    await usingApi(async (api, privateKeyWrapper) => {
+      alice = privateKeyWrapper('//Alice');
+      bob = privateKeyWrapper('//Bob');
     });
   });
 
modifiedtests/src/confirmSponsorship.test.tsdiffbeforeafterboth
--- a/tests/src/confirmSponsorship.test.ts
+++ b/tests/src/confirmSponsorship.test.ts
@@ -34,7 +34,6 @@
   getCreatedCollectionCount,
   UNIQUE,
 } from './util/helpers';
-import {Keyring} from '@polkadot/api';
 import {IKeyringPair} from '@polkadot/types/types';
 
 chai.use(chaiAsPromised);
@@ -47,11 +46,10 @@
 describe('integration test: ext. confirmSponsorship():', () => {
 
   before(async () => {
-    await usingApi(async () => {
-      const keyring = new Keyring({type: 'sr25519'});
-      alice = keyring.addFromUri('//Alice');
-      bob = keyring.addFromUri('//Bob');
-      charlie = keyring.addFromUri('//Charlie');
+    await usingApi(async (api, privateKeyWrapper) => {
+      alice = privateKeyWrapper('//Alice');
+      bob = privateKeyWrapper('//Bob');
+      charlie = privateKeyWrapper('//Charlie');
     });
   });
 
@@ -78,11 +76,11 @@
     await setCollectionSponsorExpectSuccess(collectionId, bob.address);
     await confirmSponsorshipExpectSuccess(collectionId, '//Bob');
 
-    await usingApi(async (api) => {
+    await usingApi(async (api, privateKeyWrapper) => {
       const sponsorBalanceBefore = (await api.query.system.account(bob.address)).data.free.toBigInt();
 
       // Find unused address
-      const zeroBalance = await findUnusedAddress(api);
+      const zeroBalance = await findUnusedAddress(api, privateKeyWrapper);
 
       // Mint token for unused address
       const itemId = await createItemExpectSuccess(alice, collectionId, 'NFT', zeroBalance.address);
@@ -105,11 +103,11 @@
     await setCollectionSponsorExpectSuccess(collectionId, bob.address);
     await confirmSponsorshipExpectSuccess(collectionId, '//Bob');
 
-    await usingApi(async (api) => {
+    await usingApi(async (api, privateKeyWrapper) => {
       const sponsorBalanceBefore = (await api.query.system.account(bob.address)).data.free.toBigInt();
 
       // Find unused address
-      const zeroBalance = await findUnusedAddress(api);
+      const zeroBalance = await findUnusedAddress(api, privateKeyWrapper);
 
       // Mint token for unused address
       const itemId = await createItemExpectSuccess(alice, collectionId, 'Fungible', zeroBalance.address);
@@ -131,11 +129,11 @@
     await setCollectionSponsorExpectSuccess(collectionId, bob.address);
     await confirmSponsorshipExpectSuccess(collectionId, '//Bob');
 
-    await usingApi(async (api) => {
+    await usingApi(async (api, privateKeyWrapper) => {
       const sponsorBalanceBefore = (await api.query.system.account(bob.address)).data.free.toBigInt();
 
       // Find unused address
-      const zeroBalance = await findUnusedAddress(api);
+      const zeroBalance = await findUnusedAddress(api, privateKeyWrapper);
 
       // Mint token for unused address
       const itemId = await createItemExpectSuccess(alice, collectionId, 'ReFungible', zeroBalance.address);
@@ -164,11 +162,11 @@
     await enablePublicMintingExpectSuccess(alice, collectionId);
 
     // Create Item
-    await usingApi(async (api) => {
+    await usingApi(async (api, privateKeyWrapper) => {
       const sponsorBalanceBefore = (await api.query.system.account(bob.address)).data.free.toBigInt();
 
       // Find unused address
-      const zeroBalance = await findUnusedAddress(api);
+      const zeroBalance = await findUnusedAddress(api, privateKeyWrapper);
 
       // Add zeroBalance address to allow list
       await addToAllowListExpectSuccess(alice, collectionId, zeroBalance.address);
@@ -187,9 +185,9 @@
     await setCollectionSponsorExpectSuccess(collectionId, bob.address);
     await confirmSponsorshipExpectSuccess(collectionId, '//Bob');
 
-    await usingApi(async (api) => {
+    await usingApi(async (api, privateKeyWrapper) => {
       // Find unused address
-      const zeroBalance = await findUnusedAddress(api);
+      const zeroBalance = await findUnusedAddress(api, privateKeyWrapper);
 
       // Mint token for alice
       const itemId = await createItemExpectSuccess(alice, collectionId, 'NFT', alice.address);
@@ -226,9 +224,9 @@
     await setCollectionSponsorExpectSuccess(collectionId, bob.address);
     await confirmSponsorshipExpectSuccess(collectionId, '//Bob');
 
-    await usingApi(async (api) => {
+    await usingApi(async (api, privateKeyWrapper) => {
       // Find unused address
-      const zeroBalance = await findUnusedAddress(api);
+      const zeroBalance = await findUnusedAddress(api, privateKeyWrapper);
 
       // Mint token for unused address
       const itemId = await createItemExpectSuccess(alice, collectionId, 'Fungible', zeroBalance.address);
@@ -259,9 +257,9 @@
     await setCollectionSponsorExpectSuccess(collectionId, bob.address);
     await confirmSponsorshipExpectSuccess(collectionId, '//Bob');
 
-    await usingApi(async (api) => {
+    await usingApi(async (api, privateKeyWrapper) => {
       // Find unused address
-      const zeroBalance = await findUnusedAddress(api);
+      const zeroBalance = await findUnusedAddress(api, privateKeyWrapper);
 
       // Mint token for alice
       const itemId = await createItemExpectSuccess(alice, collectionId, 'ReFungible', zeroBalance.address);
@@ -299,9 +297,9 @@
     // Enable public minting
     await enablePublicMintingExpectSuccess(alice, collectionId);
 
-    await usingApi(async (api) => {
+    await usingApi(async (api, privateKeyWrapper) => {
       // Find unused address
-      const zeroBalance = await findUnusedAddress(api);
+      const zeroBalance = await findUnusedAddress(api, privateKeyWrapper);
 
       // Add zeroBalance address to allow list
       await addToAllowListExpectSuccess(alice, collectionId, zeroBalance.address);
@@ -331,11 +329,10 @@
 
 describe('(!negative test!) integration test: ext. confirmSponsorship():', () => {
   before(async () => {
-    await usingApi(async () => {
-      const keyring = new Keyring({type: 'sr25519'});
-      alice = keyring.addFromUri('//Alice');
-      bob = keyring.addFromUri('//Bob');
-      charlie = keyring.addFromUri('//Charlie');
+    await usingApi(async (api, privateKeyWrapper) => {
+      alice = privateKeyWrapper('//Alice');
+      bob = privateKeyWrapper('//Bob');
+      charlie = privateKeyWrapper('//Charlie');
     });
   });
 
@@ -390,12 +387,12 @@
     await setCollectionSponsorExpectSuccess(collectionId, bob.address);
     await confirmSponsorshipExpectSuccess(collectionId, '//Bob');
 
-    await usingApi(async (api) => {
+    await usingApi(async (api, privateKeyWrapper) => {
       // Find unused address
-      const ownerZeroBalance = await findUnusedAddress(api);
+      const ownerZeroBalance = await findUnusedAddress(api, privateKeyWrapper);
 
       // Find another unused address
-      const senderZeroBalance = await findUnusedAddress(api);
+      const senderZeroBalance = await findUnusedAddress(api, privateKeyWrapper);
 
       // Mint token for an unused address
       const itemId = await createItemExpectSuccess(alice, collectionId, 'NFT', ownerZeroBalance.address);
modifiedtests/src/contracts.test.tsdiffbeforeafterboth
--- a/tests/src/contracts.test.ts
+++ b/tests/src/contracts.test.ts
@@ -50,7 +50,7 @@
 describe.skip('Contracts', () => {
   it('Can deploy smart contract Flipper, instantiate it and call it\'s get and flip messages.', async () => {
     await usingApi(async (api, privateKeyWrapper) => {
-      const [contract, deployer] = await deployFlipper(api);
+      const [contract, deployer] = await deployFlipper(api, privateKeyWrapper);
       const initialGetResponse = await getFlipValue(contract, deployer);
 
       const bob = privateKeyWrapper('//Bob');
@@ -82,7 +82,7 @@
       // Prep work
       const collectionId = await createCollectionExpectSuccess();
       const tokenId = await createItemExpectSuccess(alice, collectionId, 'NFT');
-      const [contract] = await deployTransferContract(api);
+      const [contract] = await deployTransferContract(api, privateKeyWrapper);
       const changeAdminTx = api.tx.unique.addCollectionAdmin(collectionId, contract.address);
       await submitTransactionAsync(alice, changeAdminTx);
 
@@ -104,7 +104,7 @@
       const bob = privateKeyWrapper('//Bob');
 
       const collectionId = await createCollectionExpectSuccess();
-      const [contract] = await deployTransferContract(api);
+      const [contract] = await deployTransferContract(api, privateKeyWrapper);
       await enablePublicMintingExpectSuccess(alice, collectionId);
       await enableAllowListExpectSuccess(alice, collectionId);
       await addToAllowListExpectSuccess(alice, collectionId, contract.address);
@@ -131,7 +131,7 @@
       const bob = privateKeyWrapper('//Bob');
 
       const collectionId = await createCollectionExpectSuccess();
-      const [contract] = await deployTransferContract(api);
+      const [contract] = await deployTransferContract(api, privateKeyWrapper);
       await enablePublicMintingExpectSuccess(alice, collectionId);
       await enableAllowListExpectSuccess(alice, collectionId);
       await addToAllowListExpectSuccess(alice, collectionId, contract.address);
@@ -173,7 +173,7 @@
       const charlie = privateKeyWrapper('//Charlie');
 
       const collectionId = await createCollectionExpectSuccess();
-      const [contract] = await deployTransferContract(api);
+      const [contract] = await deployTransferContract(api, privateKeyWrapper);
       const tokenId = await createItemExpectSuccess(alice, collectionId, 'NFT', contract.address.toString());
 
       const transferTx = contract.tx.approve(value, gasLimit, bob.address, collectionId, tokenId, 1);
@@ -192,7 +192,7 @@
       const charlie = privateKeyWrapper('//Charlie');
 
       const collectionId = await createCollectionExpectSuccess();
-      const [contract] = await deployTransferContract(api);
+      const [contract] = await deployTransferContract(api, privateKeyWrapper);
       const tokenId = await createItemExpectSuccess(alice, collectionId, 'NFT', bob.address);
       await approveExpectSuccess(collectionId, tokenId, bob, contract.address.toString(), 1);
 
@@ -212,7 +212,7 @@
       const bob = privateKeyWrapper('//Bob');
 
       const collectionId = await createCollectionExpectSuccess();
-      const [contract] = await deployTransferContract(api);
+      const [contract] = await deployTransferContract(api, privateKeyWrapper);
       const changeAdminTx = api.tx.unique.addCollectionAdmin(collectionId, contract.address);
       await submitTransactionAsync(alice, changeAdminTx);
 
modifiedtests/src/createItem.test.tsdiffbeforeafterboth
--- a/tests/src/createItem.test.ts
+++ b/tests/src/createItem.test.ts
@@ -16,7 +16,6 @@
 
 import {default as usingApi} from './substrate/substrate-api';
 import chai from 'chai';
-import {Keyring} from '@polkadot/api';
 import {IKeyringPair} from '@polkadot/types/types';
 import {
   createCollectionExpectSuccess,
@@ -33,10 +32,9 @@
 
 describe('integration test: ext. ():', () => {
   before(async () => {
-    await usingApi(async () => {
-      const keyring = new Keyring({type: 'sr25519'});
-      alice = keyring.addFromUri('//Alice');
-      bob = keyring.addFromUri('//Bob');
+    await usingApi(async (api, privateKeyWrapper) => {
+      alice = privateKeyWrapper('//Alice');
+      bob = privateKeyWrapper('//Bob');
     });
   });
 
@@ -101,10 +99,9 @@
 
 describe('Negative integration test: ext. createItem():', () => {
   before(async () => {
-    await usingApi(async () => {
-      const keyring = new Keyring({type: 'sr25519'});
-      alice = keyring.addFromUri('//Alice');
-      bob = keyring.addFromUri('//Bob');
+    await usingApi(async (api, privateKeyWrapper) => {
+      alice = privateKeyWrapper('//Alice');
+      bob = privateKeyWrapper('//Bob');
     });
   });
 
modifiedtests/src/creditFeesToTreasury.test.tsdiffbeforeafterboth
--- a/tests/src/creditFeesToTreasury.test.ts
+++ b/tests/src/creditFeesToTreasury.test.ts
@@ -18,7 +18,6 @@
 import chai from 'chai';
 import chaiAsPromised from 'chai-as-promised';
 import {default as usingApi, submitTransactionAsync, submitTransactionExpectFailAsync} from './substrate/substrate-api';
-import {alicesPublicKey, bobsPublicKey} from './accounts';
 import {IKeyringPair} from '@polkadot/types/types';
 import {
   createCollectionExpectSuccess,
@@ -71,17 +70,16 @@
   });
 
   it('Total issuance does not change', async () => {
-    await usingApi(async (api, privateKeyWrapper) => {
+    await usingApi(async (api) => {
       await skipInflationBlock(api);
       await waitNewBlocks(api, 1);
 
       const totalBefore = (await api.query.balances.totalIssuance()).toBigInt();
 
-      const alicePrivateKey = privateKeyWrapper('//Alice');
       const amount = 1n;
-      const transfer = api.tx.balances.transfer(bobsPublicKey, amount);
+      const transfer = api.tx.balances.transfer(bob.address, amount);
 
-      const result = getGenericResult(await submitTransactionAsync(alicePrivateKey, transfer));
+      const result = getGenericResult(await submitTransactionAsync(alice, transfer));
 
       const totalAfter = (await api.query.balances.totalIssuance()).toBigInt();
 
@@ -91,20 +89,19 @@
   });
 
   it('Sender balance decreased by fee+sent amount, Treasury balance increased by fee', async () => {
-    await usingApi(async (api, privateKeyWrapper) => {
+    await usingApi(async (api) => {
       await skipInflationBlock(api);
       await waitNewBlocks(api, 1);
 
-      const alicePrivateKey = privateKeyWrapper('//Alice');
       const treasuryBalanceBefore: bigint = (await api.query.system.account(TREASURY)).data.free.toBigInt();
-      const aliceBalanceBefore: bigint = (await api.query.system.account(alicesPublicKey)).data.free.toBigInt();
+      const aliceBalanceBefore: bigint = (await api.query.system.account(alice.address)).data.free.toBigInt();
 
       const amount = 1n;
-      const transfer = api.tx.balances.transfer(bobsPublicKey, amount);
-      const result = getGenericResult(await submitTransactionAsync(alicePrivateKey, transfer));
+      const transfer = api.tx.balances.transfer(bob.address, amount);
+      const result = getGenericResult(await submitTransactionAsync(alice, transfer));
 
       const treasuryBalanceAfter: bigint = (await api.query.system.account(TREASURY)).data.free.toBigInt();
-      const aliceBalanceAfter: bigint = (await api.query.system.account(alicesPublicKey)).data.free.toBigInt();
+      const aliceBalanceAfter: bigint = (await api.query.system.account(alice.address)).data.free.toBigInt();
       const fee = aliceBalanceBefore - aliceBalanceAfter - amount;
       const treasuryIncrease = treasuryBalanceAfter - treasuryBalanceBefore;
 
@@ -114,19 +111,18 @@
   });
 
   it('Treasury balance increased by failed tx fee', async () => {
-    await usingApi(async (api, privateKeyWrapper) => {
+    await usingApi(async (api) => {
       //await skipInflationBlock(api);
       await waitNewBlocks(api, 1);
 
-      const bobPrivateKey = privateKeyWrapper('//Bob');
       const treasuryBalanceBefore = (await api.query.system.account(TREASURY)).data.free.toBigInt();
-      const bobBalanceBefore = (await api.query.system.account(bobsPublicKey)).data.free.toBigInt();
+      const bobBalanceBefore = (await api.query.system.account(bob.address)).data.free.toBigInt();
 
-      const badTx = api.tx.balances.setBalance(alicesPublicKey, 0, 0);
-      await expect(submitTransactionExpectFailAsync(bobPrivateKey, badTx)).to.be.rejected;
+      const badTx = api.tx.balances.setBalance(alice.address, 0, 0);
+      await expect(submitTransactionExpectFailAsync(bob, badTx)).to.be.rejected;
 
       const treasuryBalanceAfter = (await api.query.system.account(TREASURY)).data.free.toBigInt();
-      const bobBalanceAfter = (await api.query.system.account(bobsPublicKey)).data.free.toBigInt();
+      const bobBalanceAfter = (await api.query.system.account(bob.address)).data.free.toBigInt();
       const fee = bobBalanceBefore - bobBalanceAfter;
       const treasuryIncrease = treasuryBalanceAfter - treasuryBalanceBefore;
 
@@ -140,12 +136,12 @@
       await waitNewBlocks(api, 1);
 
       const treasuryBalanceBefore = (await api.query.system.account(TREASURY)).data.free.toBigInt();
-      const aliceBalanceBefore = (await api.query.system.account(alicesPublicKey)).data.free.toBigInt();
+      const aliceBalanceBefore = (await api.query.system.account(alice.address)).data.free.toBigInt();
 
       await createCollectionExpectSuccess();
 
       const treasuryBalanceAfter = (await api.query.system.account(TREASURY)).data.free.toBigInt();
-      const aliceBalanceAfter = (await api.query.system.account(alicesPublicKey)).data.free.toBigInt();
+      const aliceBalanceAfter = (await api.query.system.account(alice.address)).data.free.toBigInt();
       const fee = aliceBalanceBefore - aliceBalanceAfter;
       const treasuryIncrease = treasuryBalanceAfter - treasuryBalanceBefore;
 
@@ -158,11 +154,11 @@
       await skipInflationBlock(api);
       await waitNewBlocks(api, 1);
 
-      const aliceBalanceBefore: bigint = (await api.query.system.account(alicesPublicKey)).data.free.toBigInt();
+      const aliceBalanceBefore: bigint = (await api.query.system.account(alice.address)).data.free.toBigInt();
 
       await createCollectionExpectSuccess();
 
-      const aliceBalanceAfter: bigint = (await api.query.system.account(alicesPublicKey)).data.free.toBigInt();
+      const aliceBalanceAfter: bigint = (await api.query.system.account(alice.address)).data.free.toBigInt();
       const fee = aliceBalanceBefore - aliceBalanceAfter;
 
       expect(fee / UNIQUE < BigInt(Math.ceil(saneMaximumFee + createCollectionDeposit))).to.be.true;
@@ -178,9 +174,9 @@
       const collectionId = await createCollectionExpectSuccess();
       const tokenId = await createItemExpectSuccess(alice, collectionId, 'NFT');
 
-      const aliceBalanceBefore: bigint = (await api.query.system.account(alicesPublicKey)).data.free.toBigInt();
+      const aliceBalanceBefore: bigint = (await api.query.system.account(alice.address)).data.free.toBigInt();
       await transferExpectSuccess(collectionId, tokenId, alice, bob, 1, 'NFT');
-      const aliceBalanceAfter: bigint = (await api.query.system.account(alicesPublicKey)).data.free.toBigInt();
+      const aliceBalanceAfter: bigint = (await api.query.system.account(alice.address)).data.free.toBigInt();
 
       const fee = Number(aliceBalanceBefore - aliceBalanceAfter) / Number(UNIQUE);
       const expectedTransferFee = 0.1;
modifiedtests/src/enableContractSponsoring.test.tsdiffbeforeafterboth
--- a/tests/src/enableContractSponsoring.test.ts
+++ b/tests/src/enableContractSponsoring.test.ts
@@ -31,10 +31,10 @@
 
 describe.skip('Integration Test enableContractSponsoring', () => {
   it('ensure tx fee is paid from endowment', async () => {
-    await usingApi(async (api) => {
-      const user = await findUnusedAddress(api);
+    await usingApi(async (api, privateKeyWrapper) => {
+      const user = await findUnusedAddress(api, privateKeyWrapper);
 
-      const [flipper, deployer] = await deployFlipper(api);
+      const [flipper, deployer] = await deployFlipper(api, privateKeyWrapper);
       await enableContractSponsoringExpectSuccess(deployer, flipper.address, true);
       await setContractSponsoringRateLimitExpectSuccess(deployer, flipper.address, 1);
       await toggleFlipValueExpectSuccess(user, flipper);
@@ -44,8 +44,8 @@
   });
 
   it('ensure it can be enabled twice', async () => {
-    await usingApi(async (api) => {
-      const [flipper, deployer] = await deployFlipper(api);
+    await usingApi(async (api, privateKeyWrapper) => {
+      const [flipper, deployer] = await deployFlipper(api, privateKeyWrapper);
 
       await enableContractSponsoringExpectSuccess(deployer, flipper.address, true);
       await enableContractSponsoringExpectSuccess(deployer, flipper.address, true);
@@ -53,8 +53,8 @@
   });
 
   it('ensure it can be disabled twice', async () => {
-    await usingApi(async (api) => {
-      const [flipper, deployer] = await deployFlipper(api);
+    await usingApi(async (api, privateKeyWrapper) => {
+      const [flipper, deployer] = await deployFlipper(api, privateKeyWrapper);
 
       await enableContractSponsoringExpectSuccess(deployer, flipper.address, true);
       await enableContractSponsoringExpectSuccess(deployer, flipper.address, false);
@@ -63,8 +63,8 @@
   });
 
   it('ensure it can be re-enabled', async () => {
-    await usingApi(async (api) => {
-      const [flipper, deployer] = await deployFlipper(api);
+    await usingApi(async (api, privateKeyWrapper) => {
+      const [flipper, deployer] = await deployFlipper(api, privateKeyWrapper);
 
       await enableContractSponsoringExpectSuccess(deployer, flipper.address, true);
       await enableContractSponsoringExpectSuccess(deployer, flipper.address, false);
@@ -84,16 +84,16 @@
   });
 
   it('fails when called for non-contract address', async () => {
-    await usingApi(async (api) => {
-      const user = await findUnusedAddress(api);
+    await usingApi(async (api, privateKeyWrapper) => {
+      const user = await findUnusedAddress(api, privateKeyWrapper);
 
       await enableContractSponsoringExpectFailure(alice, user.address, true);
     });
   });
 
   it('fails when called by non-owning user', async () => {
-    await usingApi(async (api) => {
-      const [flipper] = await deployFlipper(api);
+    await usingApi(async (api, privateKeyWrapper) => {
+      const [flipper] = await deployFlipper(api, privateKeyWrapper);
 
       await enableContractSponsoringExpectFailure(alice, flipper.address, true);
     });
modifiedtests/src/removeCollectionSponsor.test.tsdiffbeforeafterboth
--- a/tests/src/removeCollectionSponsor.test.ts
+++ b/tests/src/removeCollectionSponsor.test.ts
@@ -31,7 +31,6 @@
   addCollectionAdminExpectSuccess,
   getCreatedCollectionCount,
 } from './util/helpers';
-import {Keyring} from '@polkadot/api';
 import {IKeyringPair} from '@polkadot/types/types';
 
 chai.use(chaiAsPromised);
@@ -43,10 +42,9 @@
 describe('integration test: ext. removeCollectionSponsor():', () => {
 
   before(async () => {
-    await usingApi(async () => {
-      const keyring = new Keyring({type: 'sr25519'});
-      alice = keyring.addFromUri('//Alice');
-      bob = keyring.addFromUri('//Bob');
+    await usingApi(async (api, privateKeyWrapper) => {
+      alice = privateKeyWrapper('//Alice');
+      bob = privateKeyWrapper('//Bob');
     });
   });
 
@@ -56,9 +54,9 @@
     await confirmSponsorshipExpectSuccess(collectionId, '//Bob');
     await removeCollectionSponsorExpectSuccess(collectionId);
 
-    await usingApi(async (api) => {
+    await usingApi(async (api, privateKeyWrapper) => {
       // Find unused address
-      const zeroBalance = await findUnusedAddress(api);
+      const zeroBalance = await findUnusedAddress(api, privateKeyWrapper);
 
       // Mint token for unused address
       const itemId = await createItemExpectSuccess(alice, collectionId, 'NFT', zeroBalance.address);
@@ -99,10 +97,9 @@
 
 describe('(!negative test!) integration test: ext. removeCollectionSponsor():', () => {
   before(async () => {
-    await usingApi(async () => {
-      const keyring = new Keyring({type: 'sr25519'});
-      alice = keyring.addFromUri('//Alice');
-      bob = keyring.addFromUri('//Bob');
+    await usingApi(async (api, privateKeyWrapper) => {
+      alice = privateKeyWrapper('//Alice');
+      bob = privateKeyWrapper('//Bob');
     });
   });
 
modifiedtests/src/removeFromContractAllowList.test.tsdiffbeforeafterboth
--- a/tests/src/removeFromContractAllowList.test.ts
+++ b/tests/src/removeFromContractAllowList.test.ts
@@ -30,8 +30,8 @@
   });
 
   it('user is no longer allowlisted after removal', async () => {
-    await usingApi(async (api) => {
-      const [flipper, deployer] = await deployFlipper(api);
+    await usingApi(async (api, privateKeyWrapper) => {
+      const [flipper, deployer] = await deployFlipper(api, privateKeyWrapper);
 
       await addToContractAllowListExpectSuccess(deployer, flipper.address.toString(), bob.address);
       await removeFromContractAllowListExpectSuccess(deployer, flipper.address.toString(), bob.address);
@@ -41,8 +41,8 @@
   });
 
   it('user can\'t execute contract after removal', async () => {
-    await usingApi(async (api) => {
-      const [flipper, deployer] = await deployFlipper(api);
+    await usingApi(async (api, privateKeyWrapper) => {
+      const [flipper, deployer] = await deployFlipper(api, privateKeyWrapper);
       await toggleContractAllowlistExpectSuccess(deployer, flipper.address.toString(), true);
 
       await addToContractAllowListExpectSuccess(deployer, flipper.address.toString(), bob.address);
@@ -54,8 +54,8 @@
   });
 
   it('can be called twice', async () => {
-    await usingApi(async (api) => {
-      const [flipper, deployer] = await deployFlipper(api);
+    await usingApi(async (api, privateKeyWrapper) => {
+      const [flipper, deployer] = await deployFlipper(api, privateKeyWrapper);
 
       await addToContractAllowListExpectSuccess(deployer, flipper.address.toString(), bob.address);
       await removeFromContractAllowListExpectSuccess(deployer, flipper.address.toString(), bob.address);
@@ -82,8 +82,8 @@
   });
 
   it('fails when executed by non owner', async () => {
-    await usingApi(async (api) => {
-      const [flipper] = await deployFlipper(api);
+    await usingApi(async (api, privateKeyWrapper) => {
+      const [flipper] = await deployFlipper(api, privateKeyWrapper);
 
       await removeFromContractAllowListExpectFailure(alice, flipper.address.toString(), bob.address);
     });
modifiedtests/src/rpc.load.tsdiffbeforeafterboth
--- a/tests/src/rpc.load.ts
+++ b/tests/src/rpc.load.ts
@@ -54,9 +54,9 @@
   });
 }
 
-async function prepareDeployer(api: ApiPromise) {
+async function prepareDeployer(api: ApiPromise, privateKeyWrapper: ((account: string) => IKeyringPair)) {
   // Find unused address
-  const deployer = await findUnusedAddress(api);
+  const deployer = await findUnusedAddress(api, privateKeyWrapper);
 
   // Transfer balance to it
   const keyring = new Keyring({type: 'sr25519'});
@@ -68,11 +68,11 @@
   return deployer;
 }
 
-async function deployLoadTester(api: ApiPromise): Promise<[Contract, IKeyringPair]> {
+async function deployLoadTester(api: ApiPromise, privateKeyWrapper: ((account: string) => IKeyringPair)): Promise<[Contract, IKeyringPair]> {
   const metadata = JSON.parse(fs.readFileSync('./src/load_test_sc/metadata.json').toString('utf-8'));
   const abi = new Abi(metadata);
 
-  const deployer = await prepareDeployer(api);
+  const deployer = await prepareDeployer(api, privateKeyWrapper);
 
   const wasm = fs.readFileSync('./src/load_test_sc/loadtester.wasm');
 
@@ -123,7 +123,7 @@
     await usingApi(async (api, privateKeyWrapper) => {
 
       // Deploy smart contract
-      const [contract, deployer] = await deployLoadTester(api);
+      const [contract, deployer] = await deployLoadTester(api, privateKeyWrapper);
 
       // Fill smart contract up with data
       const bob = privateKeyWrapper('//Bob');
modifiedtests/src/scheduler.test.tsdiffbeforeafterboth
--- a/tests/src/scheduler.test.ts
+++ b/tests/src/scheduler.test.ts
@@ -116,9 +116,9 @@
   });
 
   it('Schedules and dispatches a transaction even if the caller has no funds at the time of the dispatch', async () => {
-    await usingApi(async (api) => {
+    await usingApi(async (api, privateKeyWrapper) => {
       // Find an empty, unused account
-      const zeroBalance = await findUnusedAddress(api);
+      const zeroBalance = await findUnusedAddress(api, privateKeyWrapper);
 
       const collectionId = await createCollectionExpectSuccess();
 
@@ -156,8 +156,8 @@
   it('Sponsor going bankrupt does not impact a scheduled transaction', async () => {
     const collectionId = await createCollectionExpectSuccess();
 
-    await usingApi(async (api) => {
-      const zeroBalance = await findUnusedAddress(api);
+    await usingApi(async (api, privateKeyWrapper) => {
+      const zeroBalance = await findUnusedAddress(api, privateKeyWrapper);
       const balanceTx = api.tx.balances.transfer(zeroBalance.address, 1n * UNIQUE);
       await submitTransactionAsync(alice, balanceTx);
 
@@ -186,8 +186,8 @@
     await setCollectionSponsorExpectSuccess(collectionId, bob.address);
     await confirmSponsorshipExpectSuccess(collectionId, '//Bob');
 
-    await usingApi(async (api) => {
-      const zeroBalance = await findUnusedAddress(api);
+    await usingApi(async (api, privateKeyWrapper) => {
+      const zeroBalance = await findUnusedAddress(api, privateKeyWrapper);
 
       await enablePublicMintingExpectSuccess(alice, collectionId);
       await addToAllowListExpectSuccess(alice, collectionId, zeroBalance.address);
modifiedtests/src/setCollectionLimits.test.tsdiffbeforeafterboth
--- a/tests/src/setCollectionLimits.test.ts
+++ b/tests/src/setCollectionLimits.test.ts
@@ -15,7 +15,7 @@
 // along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
 
 // https://unique-network.readthedocs.io/en/latest/jsapi.html#setchainlimits
-import {ApiPromise, Keyring} from '@polkadot/api';
+import {ApiPromise} from '@polkadot/api';
 import {IKeyringPair} from '@polkadot/types/types';
 import chai from 'chai';
 import chaiAsPromised from 'chai-as-promised';
@@ -44,9 +44,8 @@
 describe('setCollectionLimits positive', () => {
   let tx;
   before(async () => {
-    await usingApi(async () => {
-      const keyring = new Keyring({type: 'sr25519'});
-      alice = keyring.addFromUri('//Alice');
+    await usingApi(async (api, privateKeyWrapper) => {
+      alice = privateKeyWrapper('//Alice');
       collectionIdForTesting = await createCollectionExpectSuccess({name: 'A', description: 'B', tokenPrefix: 'C', mode: {type: 'NFT'}});
     });
   });
@@ -121,10 +120,9 @@
 describe('setCollectionLimits negative', () => {
   let tx;
   before(async () => {
-    await usingApi(async () => {
-      const keyring = new Keyring({type: 'sr25519'});
-      alice = keyring.addFromUri('//Alice');
-      bob = keyring.addFromUri('//Bob');
+    await usingApi(async (api, privateKeyWrapper) => {
+      alice = privateKeyWrapper('//Alice');
+      bob = privateKeyWrapper('//Bob');
       collectionIdForTesting = await createCollectionExpectSuccess({name: 'A', description: 'B', tokenPrefix: 'C', mode: {type: 'NFT'}});
     });
   });
modifiedtests/src/setCollectionSponsor.test.tsdiffbeforeafterboth
--- a/tests/src/setCollectionSponsor.test.ts
+++ b/tests/src/setCollectionSponsor.test.ts
@@ -24,7 +24,6 @@
   addCollectionAdminExpectSuccess,
   getCreatedCollectionCount,
 } from './util/helpers';
-import {Keyring} from '@polkadot/api';
 import {IKeyringPair} from '@polkadot/types/types';
 
 chai.use(chaiAsPromised);
@@ -36,10 +35,10 @@
 describe('integration test: ext. setCollectionSponsor():', () => {
 
   before(async () => {
-    await usingApi(async () => {
-      const keyring = new Keyring({type: 'sr25519'});
-      alice = keyring.addFromUri('//Alice');
-      bob = keyring.addFromUri('//Bob');
+    await usingApi(async (api, privateKeyWrapper) => {
+      alice = privateKeyWrapper('//Alice');
+      bob = privateKeyWrapper('//Bob');
+      charlie = privateKeyWrapper('//Charlie');
     });
   });
 
@@ -63,9 +62,6 @@
   });
   it('Replace collection sponsor', async () => {
     const collectionId = await createCollectionExpectSuccess();
-
-    const keyring = new Keyring({type: 'sr25519'});
-    const charlie = keyring.addFromUri('//Charlie');
     await setCollectionSponsorExpectSuccess(collectionId, bob.address);
     await setCollectionSponsorExpectSuccess(collectionId, charlie.address);
   });
@@ -73,11 +69,10 @@
 
 describe('(!negative test!) integration test: ext. setCollectionSponsor():', () => {
   before(async () => {
-    await usingApi(async () => {
-      const keyring = new Keyring({type: 'sr25519'});
-      alice = keyring.addFromUri('//Alice');
-      bob = keyring.addFromUri('//Bob');
-      charlie = keyring.addFromUri('//Charlie');
+    await usingApi(async (api, privateKeyWrapper) => {
+      alice = privateKeyWrapper('//Alice');
+      bob = privateKeyWrapper('//Bob');
+      charlie = privateKeyWrapper('//Charlie');
     });
   });
 
modifiedtests/src/setContractSponsoringRateLimit.test.tsdiffbeforeafterboth
--- a/tests/src/setContractSponsoringRateLimit.test.ts
+++ b/tests/src/setContractSponsoringRateLimit.test.ts
@@ -27,10 +27,10 @@
 
 describe.skip('Integration Test setContractSponsoringRateLimit', () => {
   it('ensure sponsored contract can\'t be called twice without pause for free', async () => {
-    await usingApi(async (api) => {
-      const user = await findUnusedAddress(api);
+    await usingApi(async (api, privateKeyWrapper) => {
+      const user = await findUnusedAddress(api, privateKeyWrapper);
 
-      const [flipper, deployer] = await deployFlipper(api);
+      const [flipper, deployer] = await deployFlipper(api, privateKeyWrapper);
       await enableContractSponsoringExpectSuccess(deployer, flipper.address, true);
       await setContractSponsoringRateLimitExpectSuccess(deployer, flipper.address, 10);
       await toggleFlipValueExpectSuccess(user, flipper);
@@ -39,10 +39,10 @@
   });
 
   it('ensure sponsored contract can be called twice with pause for free', async () => {
-    await usingApi(async (api) => {
-      const user = await findUnusedAddress(api);
+    await usingApi(async (api, privateKeyWrapper) => {
+      const user = await findUnusedAddress(api, privateKeyWrapper);
 
-      const [flipper, deployer] = await deployFlipper(api);
+      const [flipper, deployer] = await deployFlipper(api, privateKeyWrapper);
       await enableContractSponsoringExpectSuccess(deployer, flipper.address, true);
       await setContractSponsoringRateLimitExpectSuccess(deployer, flipper.address, 1);
       await toggleFlipValueExpectSuccess(user, flipper);
@@ -62,16 +62,16 @@
   });
 
   it('fails when called for non-contract address', async () => {
-    await usingApi(async (api) => {
-      const user = await findUnusedAddress(api);
+    await usingApi(async (api, privateKeyWrapper) => {
+      const user = await findUnusedAddress(api, privateKeyWrapper);
 
       await setContractSponsoringRateLimitExpectFailure(alice, user.address, 1);
     });
   });
 
   it('fails when called by non-owning user', async () => {
-    await usingApi(async (api) => {
-      const [flipper] = await deployFlipper(api);
+    await usingApi(async (api, privateKeyWrapper) => {
+      const [flipper] = await deployFlipper(api, privateKeyWrapper);
 
       await setContractSponsoringRateLimitExpectFailure(alice, flipper.address, 1);
     });
modifiedtests/src/substrate/substrate-api.tsdiffbeforeafterboth
--- a/tests/src/substrate/substrate-api.ts
+++ b/tests/src/substrate/substrate-api.ts
@@ -88,7 +88,7 @@
     await promisifySubstrate(api, async () => {
       if (api) {
         await api.isReadyOrError;
-        const ss58Format = (api.registry.getChainProperties())!.toHuman().ss58Format;
+        const ss58Format = (api.registry.getChainProperties())!.toJSON().ss58Format;
         const privateKeyWrapper = (account: string) => privateKey(account, Number(ss58Format));
         result = await action(api, privateKeyWrapper);
       }
modifiedtests/src/toggleContractAllowList.test.tsdiffbeforeafterboth
--- a/tests/src/toggleContractAllowList.test.ts
+++ b/tests/src/toggleContractAllowList.test.ts
@@ -34,8 +34,8 @@
 describe.skip('Integration Test toggleContractAllowList', () => {
 
   it('Enable allow list contract mode', async () => {
-    await usingApi(async api => {
-      const [contract, deployer] = await deployFlipper(api);
+    await usingApi(async (api, privateKeyWrapper) => {
+      const [contract, deployer] = await deployFlipper(api, privateKeyWrapper);
 
       const enabledBefore = (await api.query.unique.contractAllowListEnabled(contract.address)).toJSON();
       const enableAllowListTx = api.tx.unique.toggleContractAllowList(contract.address, true);
@@ -52,7 +52,7 @@
     await usingApi(async (api, privateKeyWrapper) => {
       const bob = privateKeyWrapper('//Bob');
 
-      const [contract, deployer] = await deployFlipper(api);
+      const [contract, deployer] = await deployFlipper(api, privateKeyWrapper);
 
       let flipValueBefore = await getFlipValue(contract, deployer);
       const flip = contract.tx.flip(value, gasLimit);
@@ -111,8 +111,8 @@
   });
 
   it('Enabling allow list repeatedly should not produce errors', async () => {
-    await usingApi(async api => {
-      const [contract, deployer] = await deployFlipper(api);
+    await usingApi(async (api, privateKeyWrapper) => {
+      const [contract, deployer] = await deployFlipper(api, privateKeyWrapper);
 
       const enabledBefore = (await api.query.unique.contractAllowListEnabled(contract.address)).toJSON();
       const enableAllowListTx = api.tx.unique.toggleContractAllowList(contract.address, true);
@@ -151,7 +151,7 @@
   it('Enable allow list using a non-owner address', async () => {
     await usingApi(async (api, privateKeyWrapper) => {
       const bob = privateKeyWrapper('//Bob');
-      const [contract] = await deployFlipper(api);
+      const [contract] = await deployFlipper(api, privateKeyWrapper);
 
       const enabledBefore = (await api.query.unique.contractAllowListEnabled(contract.address)).toJSON();
       const enableAllowListTx = api.tx.unique.toggleContractAllowList(contract.address, true);
modifiedtests/src/transfer.test.tsdiffbeforeafterboth
--- a/tests/src/transfer.test.ts
+++ b/tests/src/transfer.test.ts
@@ -17,7 +17,6 @@
 import {ApiPromise} from '@polkadot/api';
 import {IKeyringPair} from '@polkadot/types/types';
 import {expect} from 'chai';
-import {alicesPublicKey, bobsPublicKey} from './accounts';
 import getBalance from './substrate/get-balance';
 import {default as usingApi, submitTransactionAsync} from './substrate/substrate-api';
 import {
@@ -47,19 +46,24 @@
 let charlie: IKeyringPair;
 
 describe('Integration Test Transfer(recipient, collection_id, item_id, value)', () => {
+  before(async () => {
+    await usingApi(async (api, privateKeyWrapper) => {
+      alice = privateKeyWrapper('//Alice');
+      bob = privateKeyWrapper('//Bob');
+    });
+  });
+  
   it('Balance transfers and check balance', async () => {
     await usingApi(async (api, privateKeyWrapper) => {
-      const [alicesBalanceBefore, bobsBalanceBefore] = await getBalance(api, [alicesPublicKey, bobsPublicKey]);
+      const [alicesBalanceBefore, bobsBalanceBefore] = await getBalance(api, [alice.address, bob.address]);
 
-      const alicePrivateKey = privateKeyWrapper('//Alice');
-
-      const transfer = api.tx.balances.transfer(bobsPublicKey, 1n);
-      const events = await submitTransactionAsync(alicePrivateKey, transfer);
+      const transfer = api.tx.balances.transfer(bob.address, 1n);
+      const events = await submitTransactionAsync(alice, transfer);
       const result = getCreateItemResult(events);
       // tslint:disable-next-line:no-unused-expression
       expect(result.success).to.be.true;
 
-      const [alicesBalanceAfter, bobsBalanceAfter] = await getBalance(api, [alicesPublicKey, bobsPublicKey]);
+      const [alicesBalanceAfter, bobsBalanceAfter] = await getBalance(api, [alice.address, bob.address]);
 
       // tslint:disable-next-line:no-unused-expression
       expect(alicesBalanceAfter < alicesBalanceBefore).to.be.true;
@@ -69,11 +73,11 @@
   });
 
   it('Inability to pay fees error message is correct', async () => {
-    await usingApi(async (api) => {
+    await usingApi(async (api, privateKeyWrapper) => {
       // Find unused address
-      const pk = await findUnusedAddress(api);
+      const pk = await findUnusedAddress(api, privateKeyWrapper);
 
-      const badTransfer = api.tx.balances.transfer(bobsPublicKey, 1n);
+      const badTransfer = api.tx.balances.transfer(bob.address, 1n);
       // const events = await submitTransactionAsync(pk, badTransfer);
       const badTransaction = async () => {
         const events = await submitTransactionAsync(pk, badTransfer);
@@ -87,8 +91,6 @@
 
   it('User can transfer owned token', async () => {
     await usingApi(async (api, privateKeyWrapper) => {
-      const alice = privateKeyWrapper('//Alice');
-      const bob = privateKeyWrapper('//Bob');
       // nft
       const nftCollectionId = await createCollectionExpectSuccess();
       const newNftTokenId = await createItemExpectSuccess(alice, nftCollectionId, 'NFT');
@@ -114,8 +116,6 @@
 
   it('Collection admin can transfer owned token', async () => {
     await usingApi(async (api, privateKeyWrapper) => {
-      const alice = privateKeyWrapper('//Alice');
-      const bob = privateKeyWrapper('//Bob');
       // nft
       const nftCollectionId = await createCollectionExpectSuccess();
       await addCollectionAdminExpectSuccess(alice, nftCollectionId, bob.address);
@@ -316,7 +316,6 @@
 describe('Transfers to self (potentially over substrate-evm boundary)', () => {
   itWeb3('Transfers to self. In case of same frontend', async ({api, privateKeyWrapper}) => {
     const collectionId = await createCollectionExpectSuccess({mode: {type: 'Fungible', decimalPoints: 0}});
-    const alice = privateKeyWrapper('//Alice');
     const aliceProxy = subToEth(alice.address);
     const tokenId = await createItemExpectSuccess(alice, collectionId, 'Fungible', {Substrate: alice.address});
     await transferExpectSuccess(collectionId, tokenId, alice, {Ethereum: aliceProxy}, 10, 'Fungible');
@@ -328,7 +327,6 @@
 
   itWeb3('Transfers to self. In case of substrate-evm boundary', async ({api, privateKeyWrapper}) => {
     const collectionId = await createCollectionExpectSuccess({mode: {type: 'Fungible', decimalPoints: 0}});
-    const alice = privateKeyWrapper('//Alice');
     const aliceProxy = subToEth(alice.address);
     const tokenId = await createItemExpectSuccess(alice, collectionId, 'Fungible', {Substrate: alice.address});
     const balanceAliceBefore = await getTokenBalance(api, collectionId, normalizeAccountId(alice), tokenId);
@@ -340,7 +338,6 @@
 
   itWeb3('Transfers to self. In case of inside substrate-evm', async ({api, privateKeyWrapper}) => {
     const collectionId = await createCollectionExpectSuccess({mode: {type: 'Fungible', decimalPoints: 0}});
-    const alice = privateKeyWrapper('//Alice');
     const tokenId = await createItemExpectSuccess(alice, collectionId, 'Fungible', {Substrate: alice.address});
     const balanceAliceBefore = await getTokenBalance(api, collectionId, normalizeAccountId(alice), tokenId);
     await transferExpectSuccess(collectionId, tokenId, alice, alice , 10, 'Fungible');
@@ -351,7 +348,6 @@
 
   itWeb3('Transfers to self. In case of inside substrate-evm when not enought "Fungibles"', async ({api, privateKeyWrapper}) => {
     const collectionId = await createCollectionExpectSuccess({mode: {type: 'Fungible', decimalPoints: 0}});
-    const alice = privateKeyWrapper('//Alice');
     const tokenId = await createItemExpectSuccess(alice, collectionId, 'Fungible', {Substrate: alice.address});
     const balanceAliceBefore = await getTokenBalance(api, collectionId, normalizeAccountId(alice), tokenId);
     await transferExpectFailure(collectionId, tokenId, alice, alice , 11);
modifiedtests/src/util/contracthelpers.tsdiffbeforeafterboth
--- a/tests/src/util/contracthelpers.ts
+++ b/tests/src/util/contracthelpers.ts
@@ -20,7 +20,7 @@
 import fs from 'fs';
 import {Abi, CodePromise, ContractPromise as Contract} from '@polkadot/api-contract';
 import {IKeyringPair} from '@polkadot/types/types';
-import {ApiPromise, Keyring} from '@polkadot/api';
+import {ApiPromise} from '@polkadot/api';
 
 chai.use(chaiAsPromised);
 const expect = chai.expect;
@@ -45,13 +45,12 @@
   });
 }
 
-async function prepareDeployer(api: ApiPromise) {
+async function prepareDeployer(api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair) {
   // Find unused address
-  const deployer = await findUnusedAddress(api);
+  const deployer = await findUnusedAddress(api, privateKeyWrapper);
 
   // Transfer balance to it
-  const keyring = new Keyring({type: 'sr25519'});
-  const alice = keyring.addFromUri('//Alice');
+  const alice = privateKeyWrapper('//Alice');
   const amount = BigInt(endowment) + 10n**15n;
   const tx = api.tx.balances.transfer(deployer.address, amount);
   await submitTransactionAsync(alice, tx);
@@ -59,11 +58,11 @@
   return deployer;
 }
 
-export async function deployFlipper(api: ApiPromise): Promise<[Contract, IKeyringPair]> {
+export async function deployFlipper(api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair): Promise<[Contract, IKeyringPair]> {
   const metadata = JSON.parse(fs.readFileSync('./src/flipper/metadata.json').toString('utf-8'));
   const abi = new Abi(metadata);
 
-  const deployer = await prepareDeployer(api);
+  const deployer = await prepareDeployer(api, privateKeyWrapper);
 
   const wasm = fs.readFileSync('./src/flipper/flipper.wasm');
 
@@ -99,11 +98,11 @@
   await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;
 }
 
-export async function deployTransferContract(api: ApiPromise): Promise<[Contract, IKeyringPair]> {
+export async function deployTransferContract(api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair): Promise<[Contract, IKeyringPair]> {
   const metadata = JSON.parse(fs.readFileSync('./src/transfer_contract/metadata.json').toString('utf-8'));
   const abi = new Abi(metadata);
 
-  const deployer = await prepareDeployer(api);
+  const deployer = await prepareDeployer(api, privateKeyWrapper);
 
   const wasm = fs.readFileSync('./src/transfer_contract/nft_transfer.wasm');
 
modifiedtests/src/util/helpers.tsdiffbeforeafterboth
before · tests/src/util/helpers.ts
1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617import '../interfaces/augment-api-rpc';18import '../interfaces/augment-api-query';19import {ApiPromise, Keyring} from '@polkadot/api';20import type {AccountId, EventRecord, Event} from '@polkadot/types/interfaces';21import type {GenericEventData} from '@polkadot/types';22import {AnyTuple, IEvent, IKeyringPair} from '@polkadot/types/types';23import {evmToAddress} from '@polkadot/util-crypto';24import BN from 'bn.js';25import chai from 'chai';26import chaiAsPromised from 'chai-as-promised';27import {alicesPublicKey} from '../accounts';28import {default as usingApi, executeTransaction, submitTransactionAsync, submitTransactionExpectFailAsync} from '../substrate/substrate-api';29import {hexToStr, strToUTF16, utf16ToStr} from './util';30import {UpDataStructsRpcCollection, UpDataStructsCreateItemData, UpDataStructsProperty} from '@polkadot/types/lookup';31import {UpDataStructsTokenChild} from '../interfaces';3233chai.use(chaiAsPromised);34const expect = chai.expect;3536export type CrossAccountId = {37  Substrate: string,38} | {39  Ethereum: string,40};4142export function normalizeAccountId(input: string | AccountId | CrossAccountId | IKeyringPair): CrossAccountId {43  if (typeof input === 'string') {44    if (input.length === 48 || input.length === 47) {45      return {Substrate: input};46    } else if (input.length === 42 && input.startsWith('0x')) {47      return {Ethereum: input.toLowerCase()};48    } else if (input.length === 40 && !input.startsWith('0x')) {49      return {Ethereum: '0x' + input.toLowerCase()};50    } else {51      throw new Error(`Unknown address format: "${input}"`);52    }53  }54  if ('address' in input) {55    return {Substrate: input.address};56  }57  if ('Ethereum' in input) {58    return {59      Ethereum: input.Ethereum.toLowerCase(),60    };61  } else if ('ethereum' in input) {62    return {63      Ethereum: (input as any).ethereum.toLowerCase(),64    };65  } else if ('Substrate' in input) {66    return input;67  } else if ('substrate' in input) {68    return {69      Substrate: (input as any).substrate,70    };71  }7273  // AccountId74  return {Substrate: input.toString()};75}76export function toSubstrateAddress(input: string | CrossAccountId | IKeyringPair): string {77  input = normalizeAccountId(input);78  if ('Substrate' in input) {79    return input.Substrate;80  } else {81    return evmToAddress(input.Ethereum);82  }83}8485export const U128_MAX = (1n << 128n) - 1n;8687const MICROUNIQUE = 1_000_000_000_000n;88const MILLIUNIQUE = 1_000n * MICROUNIQUE;89const CENTIUNIQUE = 10n * MILLIUNIQUE;90export const UNIQUE = 100n * CENTIUNIQUE;9192interface GenericResult<T> {93  success: boolean;94  data: T | null;95}9697interface CreateCollectionResult {98  success: boolean;99  collectionId: number;100}101102interface CreateItemResult {103  success: boolean;104  collectionId: number;105  itemId: number;106  recipient?: CrossAccountId;107}108109interface TransferResult {110  collectionId: number;111  itemId: number;112  sender?: CrossAccountId;113  recipient?: CrossAccountId;114  value: bigint;115}116117interface IReFungibleOwner {118  fraction: BN;119  owner: number[];120}121122interface IGetMessage {123  checkMsgUnqMethod: string;124  checkMsgTrsMethod: string;125  checkMsgSysMethod: string;126}127128export interface IFungibleTokenDataType {129  value: number;130}131132export interface IChainLimits {133  collectionNumbersLimit: number;134  accountTokenOwnershipLimit: number;135  collectionsAdminsLimit: number;136  customDataLimit: number;137  nftSponsorTransferTimeout: number;138  fungibleSponsorTransferTimeout: number;139  refungibleSponsorTransferTimeout: number;140  //offchainSchemaLimit: number;141  //constOnChainSchemaLimit: number;142}143144export interface IReFungibleTokenDataType {145  owner: IReFungibleOwner[];146}147148export function uniqueEventMessage(events: EventRecord[]): IGetMessage {149  let checkMsgUnqMethod = '';150  let checkMsgTrsMethod = '';151  let checkMsgSysMethod = '';152  events.forEach(({event: {method, section}}) => {153    if (section === 'common') {154      checkMsgUnqMethod = method;155    } else if (section === 'treasury') {156      checkMsgTrsMethod = method;157    } else if (section === 'system') {158      checkMsgSysMethod = method;159    } else { return null; }160  });161  const result: IGetMessage = {162    checkMsgUnqMethod,163    checkMsgTrsMethod,164    checkMsgSysMethod,165  };166  return result;167}168169export function getEvent<T extends Event>(events: EventRecord[], check: (event: IEvent<AnyTuple>) => event is T): T | undefined {170  const event = events.find(r => check(r.event));171  if (!event) return;172  return event.event as T;173}174175export function getGenericResult<T>(events: EventRecord[]): GenericResult<T>;176export function getGenericResult<T>(177  events: EventRecord[],178  expectSection: string,179  expectMethod: string,180  extractAction: (data: GenericEventData) => T181): GenericResult<T>;182183export function getGenericResult<T>(184  events: EventRecord[],185  expectSection?: string,186  expectMethod?: string,187  extractAction?: (data: GenericEventData) => T,188): GenericResult<T> {189  let success = false;190  let successData = null;191192  events.forEach(({event: {data, method, section}}) => {193    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);194    if (method === 'ExtrinsicSuccess') {195      success = true;196    } else if ((expectSection == section) && (expectMethod == method)) {197      successData = extractAction!(data);198    }199  });200201  const result: GenericResult<T> = {202    success,203    data: successData,204  };205  return result;206}207208export function getCreateCollectionResult(events: EventRecord[]): CreateCollectionResult {209  const genericResult = getGenericResult(events, 'common', 'CollectionCreated', (data) => parseInt(data[0].toString(), 10));210  const result: CreateCollectionResult = {211    success: genericResult.success,212    collectionId: genericResult.data ?? 0,213  };214  return result;215}216217export function getCreateItemsResult(events: EventRecord[]): CreateItemResult[] {218  const results: CreateItemResult[] = [];219  220  const genericResult = getGenericResult<CreateItemResult[]>(events, 'common', 'ItemCreated', (data) => {221    const collectionId = parseInt(data[0].toString(), 10);222    const itemId = parseInt(data[1].toString(), 10);223    const recipient = normalizeAccountId(data[2].toJSON() as any);224225    const itemRes: CreateItemResult = {226      success: true,227      collectionId,228      itemId,229      recipient,230    };231232    results.push(itemRes);233    return results;234  });235236  if (!genericResult.success) return [];237  return results;238}239240export function getCreateItemResult(events: EventRecord[]): CreateItemResult {241  const genericResult = getGenericResult<[number, number, CrossAccountId?]>(events, 'common', 'ItemCreated', (data) => [242    parseInt(data[0].toString(), 10),243    parseInt(data[1].toString(), 10),244    normalizeAccountId(data[2].toJSON() as any),245  ]);246247  if (genericResult.data == null) genericResult.data = [0, 0];248249  const result: CreateItemResult = {250    success: genericResult.success,251    collectionId: genericResult.data[0],252    itemId: genericResult.data[1],253    recipient: genericResult.data![2],254  };255  256  return result;257}258259export function getTransferResult(api: ApiPromise, events: EventRecord[]): TransferResult {260  for (const {event} of events) {261    if (api.events.common.Transfer.is(event)) {262      const [collection, token, sender, recipient, value] = event.data;263      return {264        collectionId: collection.toNumber(),265        itemId: token.toNumber(),266        sender: normalizeAccountId(sender.toJSON() as any),267        recipient: normalizeAccountId(recipient.toJSON() as any),268        value: value.toBigInt(),269      };270    }271  }272  throw new Error('no transfer event');273}274275interface Nft {276  type: 'NFT';277}278279interface Fungible {280  type: 'Fungible';281  decimalPoints: number;282}283284interface ReFungible {285  type: 'ReFungible';286}287288type CollectionMode = Nft | Fungible | ReFungible;289290export type Property = {291  key: any,292  value: any,293};294295type Permission = {296  mutable: boolean;297  collectionAdmin: boolean;298  tokenOwner: boolean;299}300301type PropertyPermission = {302  key: any;303  permission: Permission;304}305306export type CreateCollectionParams = {307  mode: CollectionMode,308  name: string,309  description: string,310  tokenPrefix: string,311  properties?: Array<Property>,312  propPerm?: Array<PropertyPermission>313};314315const defaultCreateCollectionParams: CreateCollectionParams = {316  description: 'description',317  mode: {type: 'NFT'},318  name: 'name',319  tokenPrefix: 'prefix',320};321322export async function createCollectionExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {323  const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};324325  let collectionId = 0;326  await usingApi(async (api, privateKeyWrapper) => {327    // Get number of collections before the transaction328    const collectionCountBefore = await getCreatedCollectionCount(api);329330    // Run the CreateCollection transaction331    const alicePrivateKey = privateKeyWrapper('//Alice');332333    let modeprm = {};334    if (mode.type === 'NFT') {335      modeprm = {nft: null};336    } else if (mode.type === 'Fungible') {337      modeprm = {fungible: mode.decimalPoints};338    } else if (mode.type === 'ReFungible') {339      modeprm = {refungible: null};340    }341342    const tx = api.tx.unique.createCollectionEx({343      name: strToUTF16(name),344      description: strToUTF16(description),345      tokenPrefix: strToUTF16(tokenPrefix),346      mode: modeprm as any,347    });348    const events = await submitTransactionAsync(alicePrivateKey, tx);349    const result = getCreateCollectionResult(events);350351    // Get number of collections after the transaction352    const collectionCountAfter = await getCreatedCollectionCount(api);353354    // Get the collection355    const collection = await queryCollectionExpectSuccess(api, result.collectionId);356357    // What to expect358    // tslint:disable-next-line:no-unused-expression359    expect(result.success).to.be.true;360    expect(result.collectionId).to.be.equal(collectionCountAfter);361    // tslint:disable-next-line:no-unused-expression362    expect(collection).to.be.not.null;363    expect(collectionCountAfter).to.be.equal(collectionCountBefore + 1, 'Error: NFT collection NOT created.');364    expect(collection.owner.toString()).to.be.equal(toSubstrateAddress(alicesPublicKey));365    expect(utf16ToStr(collection.name.toJSON() as any)).to.be.equal(name);366    expect(utf16ToStr(collection.description.toJSON() as any)).to.be.equal(description);367    expect(hexToStr(collection.tokenPrefix.toJSON())).to.be.equal(tokenPrefix);368369    collectionId = result.collectionId;370  });371372  return collectionId;373}374375export async function createCollectionWithPropsExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {376  const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};377378  let collectionId = 0;379  await usingApi(async (api, privateKeyWrapper) => {380    // Get number of collections before the transaction381    const collectionCountBefore = await getCreatedCollectionCount(api);382383    // Run the CreateCollection transaction384    const alicePrivateKey = privateKeyWrapper('//Alice');385386    let modeprm = {};387    if (mode.type === 'NFT') {388      modeprm = {nft: null};389    } else if (mode.type === 'Fungible') {390      modeprm = {fungible: mode.decimalPoints};391    } else if (mode.type === 'ReFungible') {392      modeprm = {refungible: null};393    }394395    const tx = api.tx.unique.createCollectionEx({name: strToUTF16(name), description: strToUTF16(description), tokenPrefix: strToUTF16(tokenPrefix), mode: modeprm as any, properties: params.properties, tokenPropertyPermissions: params.propPerm});396    const events = await submitTransactionAsync(alicePrivateKey, tx);397    const result = getCreateCollectionResult(events);398399    // Get number of collections after the transaction400    const collectionCountAfter = await getCreatedCollectionCount(api);401402    // Get the collection403    const collection = await queryCollectionExpectSuccess(api, result.collectionId);404405    // What to expect406    // tslint:disable-next-line:no-unused-expression407    expect(result.success).to.be.true;408    expect(result.collectionId).to.be.equal(collectionCountAfter);409    // tslint:disable-next-line:no-unused-expression410    expect(collection).to.be.not.null;411    expect(collectionCountAfter).to.be.equal(collectionCountBefore + 1, 'Error: NFT collection NOT created.');412    expect(collection.owner.toString()).to.be.equal(toSubstrateAddress(alicesPublicKey));413    expect(utf16ToStr(collection.name.toJSON() as any)).to.be.equal(name);414    expect(utf16ToStr(collection.description.toJSON() as any)).to.be.equal(description);415    expect(hexToStr(collection.tokenPrefix.toJSON())).to.be.equal(tokenPrefix);416417418    collectionId = result.collectionId;419  });420421  return collectionId;422}423424export async function createCollectionWithPropsExpectFailure(params: Partial<CreateCollectionParams> = {}) {425  const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};426427  await usingApi(async (api, privateKeyWrapper) => {428    // Get number of collections before the transaction429    const collectionCountBefore = await getCreatedCollectionCount(api);430431    // Run the CreateCollection transaction432    const alicePrivateKey = privateKeyWrapper('//Alice');433434    let modeprm = {};435    if (mode.type === 'NFT') {436      modeprm = {nft: null};437    } else if (mode.type === 'Fungible') {438      modeprm = {fungible: mode.decimalPoints};439    } else if (mode.type === 'ReFungible') {440      modeprm = {refungible: null};441    }442443    const tx = api.tx.unique.createCollectionEx({name: strToUTF16(name), description: strToUTF16(description), tokenPrefix: strToUTF16(tokenPrefix), mode: modeprm as any, properties: params.properties, tokenPropertyPermissions: params.propPerm});444    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;445446447    // Get number of collections after the transaction448    const collectionCountAfter = await getCreatedCollectionCount(api);449450    expect(collectionCountAfter).to.be.equal(collectionCountBefore, 'Error: Collection with incorrect data created.');451  });452}453454export async function createCollectionExpectFailure(params: Partial<CreateCollectionParams> = {}) {455  const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};456457  let modeprm = {};458  if (mode.type === 'NFT') {459    modeprm = {nft: null};460  } else if (mode.type === 'Fungible') {461    modeprm = {fungible: mode.decimalPoints};462  } else if (mode.type === 'ReFungible') {463    modeprm = {refungible: null};464  }465466  await usingApi(async (api, privateKeyWrapper) => {467    // Get number of collections before the transaction468    const collectionCountBefore = await getCreatedCollectionCount(api);469470    // Run the CreateCollection transaction471    const alicePrivateKey = privateKeyWrapper('//Alice');472    const tx = api.tx.unique.createCollectionEx({name: strToUTF16(name), description: strToUTF16(description), tokenPrefix: strToUTF16(tokenPrefix), mode: modeprm as any});473    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;474475    // Get number of collections after the transaction476    const collectionCountAfter = await getCreatedCollectionCount(api);477478    // What to expect479    expect(collectionCountAfter).to.be.equal(collectionCountBefore, 'Error: Collection with incorrect data created.');480  });481}482483export async function findUnusedAddress(api: ApiPromise, seedAddition = ''): Promise<IKeyringPair> {484  let bal = 0n;485  let unused;486  do {487    const randomSeed = 'seed' + Math.floor(Math.random() * Math.floor(10000)) + seedAddition;488    const keyring = new Keyring({type: 'sr25519'});489    unused = keyring.addFromUri(`//${randomSeed}`);490    bal = (await api.query.system.account(unused.address)).data.free.toBigInt();491  } while (bal !== 0n);492  return unused;493}494495export async function getAllowance(api: ApiPromise, collectionId: number, owner: CrossAccountId | string, approved: CrossAccountId | string, tokenId: number) {496  return (await api.rpc.unique.allowance(collectionId, normalizeAccountId(owner), normalizeAccountId(approved), tokenId)).toBigInt();497}498499export function findUnusedAddresses(api: ApiPromise, amount: number): Promise<IKeyringPair[]> {500  return Promise.all(new Array(amount).fill(null).map(() => findUnusedAddress(api, '_' + Date.now())));501}502503export async function findNotExistingCollection(api: ApiPromise): Promise<number> {504  const totalNumber = await getCreatedCollectionCount(api);505  const newCollection: number = totalNumber + 1;506  return newCollection;507}508509function getDestroyResult(events: EventRecord[]): boolean {510  let success = false;511  events.forEach(({event: {method}}) => {512    if (method == 'ExtrinsicSuccess') {513      success = true;514    }515  });516  return success;517}518519export async function destroyCollectionExpectFailure(collectionId: number, senderSeed = '//Alice') {520  await usingApi(async (api, privateKeyWrapper) => {521    // Run the DestroyCollection transaction522    const alicePrivateKey = privateKeyWrapper(senderSeed);523    const tx = api.tx.unique.destroyCollection(collectionId);524    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;525  });526}527528export async function destroyCollectionExpectSuccess(collectionId: number, senderSeed = '//Alice') {529  await usingApi(async (api, privateKeyWrapper) => {530    // Run the DestroyCollection transaction531    const alicePrivateKey = privateKeyWrapper(senderSeed);532    const tx = api.tx.unique.destroyCollection(collectionId);533    const events = await submitTransactionAsync(alicePrivateKey, tx);534    const result = getDestroyResult(events);535    expect(result).to.be.true;536537    // What to expect538    expect(await getDetailedCollectionInfo(api, collectionId)).to.be.null;539  });540}541542export async function setCollectionLimitsExpectSuccess(sender: IKeyringPair, collectionId: number, limits: any) {543  await usingApi(async (api) => {544    const tx = api.tx.unique.setCollectionLimits(collectionId, limits);545    const events = await submitTransactionAsync(sender, tx);546    const result = getGenericResult(events);547548    expect(result.success).to.be.true;549  });550}551552export const setCollectionPermissionsExpectSuccess = async (sender: IKeyringPair, collectionId: number, permissions: {mintMode?: boolean, access?: 'Normal' | 'AllowList', nesting?: 'Disabled' | 'Owner' | {OwnerRestricted: number[]}}) => {553  await usingApi(async(api) => {554    const tx = api.tx.unique.setCollectionPermissions(collectionId, permissions);555    const events = await submitTransactionAsync(sender, tx);556    const result = getGenericResult(events);557558    expect(result.success).to.be.true;559  });560};561562export async function setCollectionLimitsExpectFailure(sender: IKeyringPair, collectionId: number, limits: any) {563  await usingApi(async (api) => {564    const tx = api.tx.unique.setCollectionLimits(collectionId, limits);565    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;566    const result = getGenericResult(events);567568    expect(result.success).to.be.false;569  });570}571572export async function setCollectionSponsorExpectSuccess(collectionId: number, sponsor: string, sender = '//Alice') {573  await usingApi(async (api, privateKeyWrapper) => {574575    // Run the transaction576    const senderPrivateKey = privateKeyWrapper(sender);577    const tx = api.tx.unique.setCollectionSponsor(collectionId, sponsor);578    const events = await submitTransactionAsync(senderPrivateKey, tx);579    const result = getGenericResult(events);580581    // Get the collection582    const collection = await queryCollectionExpectSuccess(api, collectionId);583584    // What to expect585    expect(result.success).to.be.true;586    expect(collection.sponsorship.toJSON()).to.deep.equal({587      unconfirmed: sponsor,588    });589  });590}591592export async function removeCollectionSponsorExpectSuccess(collectionId: number, sender = '//Alice') {593  await usingApi(async (api, privateKeyWrapper) => {594595    // Run the transaction596    const alicePrivateKey = privateKeyWrapper(sender);597    const tx = api.tx.unique.removeCollectionSponsor(collectionId);598    const events = await submitTransactionAsync(alicePrivateKey, tx);599    const result = getGenericResult(events);600601    // Get the collection602    const collection = await queryCollectionExpectSuccess(api, collectionId);603604    // What to expect605    expect(result.success).to.be.true;606    expect(collection.sponsorship.toJSON()).to.be.deep.equal({disabled: null});607  });608}609610export async function removeCollectionSponsorExpectFailure(collectionId: number, senderSeed = '//Alice') {611  await usingApi(async (api, privateKeyWrapper) => {612613    // Run the transaction614    const alicePrivateKey = privateKeyWrapper(senderSeed);615    const tx = api.tx.unique.removeCollectionSponsor(collectionId);616    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;617  });618}619620export async function setCollectionSponsorExpectFailure(collectionId: number, sponsor: string, senderSeed = '//Alice') {621  await usingApi(async (api, privateKeyWrapper) => {622623    // Run the transaction624    const alicePrivateKey = privateKeyWrapper(senderSeed);625    const tx = api.tx.unique.setCollectionSponsor(collectionId, sponsor);626    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;627  });628}629630export async function confirmSponsorshipExpectSuccess(collectionId: number, senderSeed = '//Alice') {631  await usingApi(async (api, privateKeyWrapper) => {632633    // Run the transaction634    const sender = privateKeyWrapper(senderSeed);635    await confirmSponsorshipByKeyExpectSuccess(collectionId, sender);636  });637}638639export async function confirmSponsorshipByKeyExpectSuccess(collectionId: number, sender: IKeyringPair) {640  await usingApi(async (api, privateKeyWrapper) => {641642    // Run the transaction643    const tx = api.tx.unique.confirmSponsorship(collectionId);644    const events = await submitTransactionAsync(sender, tx);645    const result = getGenericResult(events);646647    // Get the collection648    const collection = await queryCollectionExpectSuccess(api, collectionId);649650    // What to expect651    expect(result.success).to.be.true;652    expect(collection.sponsorship.toJSON()).to.be.deep.equal({653      confirmed: sender.address,654    });655  });656}657658659export async function confirmSponsorshipExpectFailure(collectionId: number, senderSeed = '//Alice') {660  await usingApi(async (api, privateKeyWrapper) => {661662    // Run the transaction663    const sender = privateKeyWrapper(senderSeed);664    const tx = api.tx.unique.confirmSponsorship(collectionId);665    await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;666  });667}668669export async function enableContractSponsoringExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {670  await usingApi(async (api) => {671    const tx = api.tx.unique.enableContractSponsoring(contractAddress, enable);672    const events = await submitTransactionAsync(sender, tx);673    const result = getGenericResult(events);674675    expect(result.success).to.be.true;676  });677}678679export async function enableContractSponsoringExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {680  await usingApi(async (api) => {681    const tx = api.tx.unique.enableContractSponsoring(contractAddress, enable);682    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;683    const result = getGenericResult(events);684685    expect(result.success).to.be.false;686  });687}688689export async function setTransferFlagExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {690691  await usingApi(async (api) => {692693    const tx = api.tx.unique.setTransfersEnabledFlag(collectionId, enabled);694    const events = await submitTransactionAsync(sender, tx);695    const result = getGenericResult(events);696697    expect(result.success).to.be.true;698  });699}700701export async function setTransferFlagExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {702703  await usingApi(async (api) => {704705    const tx = api.tx.unique.setTransfersEnabledFlag(collectionId, enabled);706    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;707    const result = getGenericResult(events);708709    expect(result.success).to.be.false;710  });711}712713export async function setContractSponsoringRateLimitExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {714  await usingApi(async (api) => {715    const tx = api.tx.unique.setContractSponsoringRateLimit(contractAddress, rateLimit);716    const events = await submitTransactionAsync(sender, tx);717    const result = getGenericResult(events);718719    expect(result.success).to.be.true;720  });721}722723export async function setContractSponsoringRateLimitExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {724  await usingApi(async (api) => {725    const tx = api.tx.unique.setContractSponsoringRateLimit(contractAddress, rateLimit);726    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;727    const result = getGenericResult(events);728729    expect(result.success).to.be.false;730  });731}732733export async function getNextSponsored(734  api: ApiPromise,735  collectionId: number,736  account: string | CrossAccountId,737  tokenId: number,738): Promise<number> {739  return Number((await api.rpc.unique.nextSponsored(collectionId, account, tokenId)).unwrapOr(-1));740}741742export async function toggleContractAllowlistExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, value = true) {743  await usingApi(async (api) => {744    const tx = api.tx.unique.toggleContractAllowList(contractAddress, value);745    const events = await submitTransactionAsync(sender, tx);746    const result = getGenericResult(events);747748    expect(result.success).to.be.true;749  });750}751752export async function isAllowlistedInContract(contractAddress: AccountId | string, user: string) {753  let allowlisted = false;754  await usingApi(async (api) => {755    allowlisted = (await api.query.unique.contractAllowList(contractAddress, user)).toJSON() as boolean;756  });757  return allowlisted;758}759760export async function addToContractAllowListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {761  await usingApi(async (api) => {762    const tx = api.tx.unique.addToContractAllowList(contractAddress.toString(), user.toString());763    const events = await submitTransactionAsync(sender, tx);764    const result = getGenericResult(events);765766    expect(result.success).to.be.true;767  });768}769770export async function removeFromContractAllowListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {771  await usingApi(async (api) => {772    const tx = api.tx.unique.removeFromContractAllowList(contractAddress.toString(), user.toString());773    const events = await submitTransactionAsync(sender, tx);774    const result = getGenericResult(events);775776    expect(result.success).to.be.true;777  });778}779780export async function removeFromContractAllowListExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {781  await usingApi(async (api) => {782    const tx = api.tx.unique.removeFromContractAllowList(contractAddress.toString(), user.toString());783    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;784    const result = getGenericResult(events);785786    expect(result.success).to.be.false;787  });788}789790export interface CreateFungibleData {791  readonly Value: bigint;792}793794export interface CreateReFungibleData { }795export interface CreateNftData { }796797export type CreateItemData = {798  NFT: CreateNftData;799} | {800  Fungible: CreateFungibleData;801} | {802  ReFungible: CreateReFungibleData;803};804805export async function burnItemExpectSuccess(sender: IKeyringPair, collectionId: number, tokenId: number, value = 1) {806  await usingApi(async (api) => {807    const balanceBefore = await getBalance(api, collectionId, normalizeAccountId(sender), tokenId);808    // if burning token by admin - use adminButnItemExpectSuccess809    expect(balanceBefore >= BigInt(value)).to.be.true;810811    const tx = api.tx.unique.burnItem(collectionId, tokenId, value);812    const events = await submitTransactionAsync(sender, tx);813    const result = getGenericResult(events);814    expect(result.success).to.be.true;815816    const balanceAfter = await getBalance(api, collectionId, normalizeAccountId(sender), tokenId);817    expect(balanceAfter + BigInt(value)).to.be.equal(balanceBefore);818  });819}820821export async function822approveExpectSuccess(823  collectionId: number,824  tokenId: number, owner: IKeyringPair, approved: CrossAccountId | string, amount: number | bigint = 1,825) {826  await usingApi(async (api: ApiPromise) => {827    const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);828    const events = await submitTransactionAsync(owner, approveUniqueTx);829    const result = getGenericResult(events);830    expect(result.success).to.be.true;831832    expect(await getAllowance(api, collectionId, owner.address, approved, tokenId)).to.be.equal(BigInt(amount));833  });834}835836export async function adminApproveFromExpectSuccess(837  collectionId: number,838  tokenId: number, admin: IKeyringPair, owner: CrossAccountId | string, approved: CrossAccountId | string, amount: number | bigint = 1,839) {840  await usingApi(async (api: ApiPromise) => {841    const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);842    const events = await submitTransactionAsync(admin, approveUniqueTx);843    const result = getGenericResult(events);844    expect(result.success).to.be.true;845846    expect(await getAllowance(api, collectionId, owner, approved, tokenId)).to.be.equal(BigInt(amount));847  });848}849850export async function851transferFromExpectSuccess(852  collectionId: number,853  tokenId: number,854  accountApproved: IKeyringPair,855  accountFrom: IKeyringPair | CrossAccountId,856  accountTo: IKeyringPair | CrossAccountId,857  value: number | bigint = 1,858  type = 'NFT',859) {860  await usingApi(async (api: ApiPromise) => {861    const from = normalizeAccountId(accountFrom);862    const to = normalizeAccountId(accountTo);863    let balanceBefore = 0n;864    if (type === 'Fungible' || type === 'ReFungible') {865      balanceBefore = await getBalance(api, collectionId, to, tokenId);866    }867    const transferFromTx = api.tx.unique.transferFrom(normalizeAccountId(accountFrom), to, collectionId, tokenId, value);868    const events = await submitTransactionAsync(accountApproved, transferFromTx);869    const result = getGenericResult(events);870    // tslint:disable-next-line:no-unused-expression871    expect(result.success).to.be.true;872    if (type === 'NFT') {873      expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(to);874    }875    if (type === 'Fungible') {876      const balanceAfter = await getBalance(api, collectionId, to, tokenId);877      if (JSON.stringify(to) !== JSON.stringify(from)) {878        expect(balanceAfter - balanceBefore).to.be.equal(BigInt(value));879      } else {880        expect(balanceAfter).to.be.equal(balanceBefore);881      }882    }883    if (type === 'ReFungible') {884      expect(await getBalance(api, collectionId, to, tokenId)).to.be.equal(balanceBefore + BigInt(value));885    }886  });887}888889export async function890transferFromExpectFail(891  collectionId: number,892  tokenId: number,893  accountApproved: IKeyringPair,894  accountFrom: IKeyringPair,895  accountTo: IKeyringPair,896  value: number | bigint = 1,897) {898  await usingApi(async (api: ApiPromise) => {899    const transferFromTx = api.tx.unique.transferFrom(normalizeAccountId(accountFrom.address), normalizeAccountId(accountTo.address), collectionId, tokenId, value);900    const events = await expect(submitTransactionExpectFailAsync(accountApproved, transferFromTx)).to.be.rejected;901    const result = getCreateCollectionResult(events);902    // tslint:disable-next-line:no-unused-expression903    expect(result.success).to.be.false;904  });905}906907/* eslint no-async-promise-executor: "off" */908export async function getBlockNumber(api: ApiPromise): Promise<number> {909  return new Promise<number>(async (resolve) => {910    const unsubscribe = await api.rpc.chain.subscribeNewHeads((head) => {911      unsubscribe();912      resolve(head.number.toNumber());913    });914  });915}916917export async function addCollectionAdminExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | CrossAccountId) {918  await usingApi(async (api) => {919    const changeAdminTx = api.tx.unique.addCollectionAdmin(collectionId, normalizeAccountId(address));920    const events = await submitTransactionAsync(sender, changeAdminTx);921    const result = getCreateCollectionResult(events);922    expect(result.success).to.be.true;923  });924}925926export async function927getFreeBalance(account: IKeyringPair): Promise<bigint> {928  let balance = 0n;929  await usingApi(async (api) => {930    balance = BigInt((await api.query.system.account(account.address)).data.free.toString());931  });932933  return balance;934}935936export async function transferBalanceTo(api: ApiPromise, source: IKeyringPair, target: string, amount = 1000n * UNIQUE) {937  const tx = api.tx.balances.transfer(target, amount);938  const events = await submitTransactionAsync(source, tx);939  const result = getGenericResult(events);940  expect(result.success).to.be.true;941}942943export async function944scheduleExpectSuccess(945  operationTx: any,946  sender: IKeyringPair,947  blockSchedule: number,948  scheduledId: string,949  period = 1,950  repetitions = 1,951) {952  await usingApi(async (api: ApiPromise) => {953    const blockNumber: number | undefined = await getBlockNumber(api);954    const expectedBlockNumber = blockNumber + blockSchedule;955956    expect(blockNumber).to.be.greaterThan(0);957    const scheduleTx = api.tx.scheduler.scheduleNamed( // schedule958      scheduledId,959      expectedBlockNumber, 960      repetitions > 1 ? [period, repetitions] : null, 961      0, 962      {value: operationTx as any},963    );964965    const events = await submitTransactionAsync(sender, scheduleTx);966    expect(getGenericResult(events).success).to.be.true;967  });968}969970export async function971scheduleExpectFailure(972  operationTx: any,973  sender: IKeyringPair,974  blockSchedule: number,975  scheduledId: string,976  period = 1,977  repetitions = 1,978) {979  await usingApi(async (api: ApiPromise) => {980    const blockNumber: number | undefined = await getBlockNumber(api);981    const expectedBlockNumber = blockNumber + blockSchedule;982983    expect(blockNumber).to.be.greaterThan(0);984    const scheduleTx = api.tx.scheduler.scheduleNamed( // schedule985      scheduledId,986      expectedBlockNumber, 987      repetitions <= 1 ? null : [period, repetitions], 988      0, 989      {value: operationTx as any},990    );991992    //const events = 993    await expect(submitTransactionExpectFailAsync(sender, scheduleTx)).to.be.rejected;994    //expect(getGenericResult(events).success).to.be.false;995  });996}997998export async function999scheduleTransferAndWaitExpectSuccess(1000  collectionId: number,1001  tokenId: number,1002  sender: IKeyringPair,1003  recipient: IKeyringPair,1004  value: number | bigint = 1,1005  blockSchedule: number,1006  scheduledId: string,1007) {1008  await usingApi(async (api: ApiPromise) => {1009    await scheduleTransferExpectSuccess(collectionId, tokenId, sender, recipient, value, blockSchedule, scheduledId);10101011    const recipientBalanceBefore = (await api.query.system.account(recipient.address)).data.free.toBigInt();10121013    // sleep for n + 1 blocks1014    await waitNewBlocks(blockSchedule + 1);10151016    const recipientBalanceAfter = (await api.query.system.account(recipient.address)).data.free.toBigInt();10171018    expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(recipient.address));1019    expect(recipientBalanceAfter).to.be.equal(recipientBalanceBefore);1020  });1021}10221023export async function1024scheduleTransferExpectSuccess(1025  collectionId: number,1026  tokenId: number,1027  sender: IKeyringPair,1028  recipient: IKeyringPair,1029  value: number | bigint = 1,1030  blockSchedule: number,1031  scheduledId: string,1032) {1033  await usingApi(async (api: ApiPromise) => {1034    const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient.address), collectionId, tokenId, value);10351036    await scheduleExpectSuccess(transferTx, sender, blockSchedule, scheduledId);10371038    expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(sender.address));1039  });1040}10411042export async function1043scheduleTransferFundsPeriodicExpectSuccess(1044  amount: bigint,1045  sender: IKeyringPair,1046  recipient: IKeyringPair,1047  blockSchedule: number,1048  scheduledId: string,1049  period: number,1050  repetitions: number,1051) {1052  await usingApi(async (api: ApiPromise) => {1053    const transferTx = api.tx.balances.transfer(recipient.address, amount);10541055    const balanceBefore = await getFreeBalance(recipient);1056    1057    await scheduleExpectSuccess(transferTx, sender, blockSchedule, scheduledId, period, repetitions);10581059    expect(await getFreeBalance(recipient)).to.be.equal(balanceBefore);1060  });1061}10621063export async function1064transferExpectSuccess(1065  collectionId: number,1066  tokenId: number,1067  sender: IKeyringPair,1068  recipient: IKeyringPair | CrossAccountId,1069  value: number | bigint = 1,1070  type = 'NFT',1071) {1072  await usingApi(async (api: ApiPromise) => {1073    const from = normalizeAccountId(sender);1074    const to = normalizeAccountId(recipient);10751076    let balanceBefore = 0n;1077    if (type === 'Fungible') {1078      balanceBefore = await getBalance(api, collectionId, to, tokenId);1079    }1080    const transferTx = api.tx.unique.transfer(to, collectionId, tokenId, value);1081    const events = await executeTransaction(api, sender, transferTx);10821083    const result = getTransferResult(api, events);1084    expect(result.collectionId).to.be.equal(collectionId);1085    expect(result.itemId).to.be.equal(tokenId);1086    expect(result.sender).to.be.deep.equal(normalizeAccountId(sender.address));1087    expect(result.recipient).to.be.deep.equal(to);1088    expect(result.value).to.be.equal(BigInt(value));10891090    if (type === 'NFT') {1091      expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(to);1092    }1093    if (type === 'Fungible') {1094      const balanceAfter = await getBalance(api, collectionId, to, tokenId);1095      if (JSON.stringify(to) !== JSON.stringify(from)) {1096        expect(balanceAfter - balanceBefore).to.be.equal(BigInt(value));1097      } else {1098        expect(balanceAfter).to.be.equal(balanceBefore);1099      }1100    }1101    if (type === 'ReFungible') {1102      expect(await getBalance(api, collectionId, to, tokenId) >= value).to.be.true;1103    }1104  });1105}11061107export async function1108transferExpectFailure(1109  collectionId: number,1110  tokenId: number,1111  sender: IKeyringPair,1112  recipient: IKeyringPair | CrossAccountId,1113  value: number | bigint = 1,1114) {1115  await usingApi(async (api: ApiPromise) => {1116    const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient), collectionId, tokenId, value);1117    const events = await expect(submitTransactionExpectFailAsync(sender, transferTx)).to.be.rejected;1118    const result = getGenericResult(events);1119    // if (events && Array.isArray(events)) {1120    //   const result = getCreateCollectionResult(events);1121    // tslint:disable-next-line:no-unused-expression1122    expect(result.success).to.be.false;1123    //}1124  });1125}11261127export async function1128approveExpectFail(1129  collectionId: number,1130  tokenId: number, owner: IKeyringPair, approved: IKeyringPair, amount: number | bigint = 1,1131) {1132  await usingApi(async (api: ApiPromise) => {1133    const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved.address), collectionId, tokenId, amount);1134    const events = await expect(submitTransactionExpectFailAsync(owner, approveUniqueTx)).to.be.rejected;1135    const result = getCreateCollectionResult(events);1136    // tslint:disable-next-line:no-unused-expression1137    expect(result.success).to.be.false;1138  });1139}11401141export async function getBalance(1142  api: ApiPromise,1143  collectionId: number,1144  owner: string | CrossAccountId,1145  token: number,1146): Promise<bigint> {1147  return (await api.rpc.unique.balance(collectionId, normalizeAccountId(owner), token)).toBigInt();1148}1149export async function getTokenOwner(1150  api: ApiPromise,1151  collectionId: number,1152  token: number,1153): Promise<CrossAccountId> {1154  const owner = (await api.rpc.unique.tokenOwner(collectionId, token)).toJSON() as any;1155  if (owner == null) throw new Error('owner == null');1156  return normalizeAccountId(owner);1157}1158export async function getTopmostTokenOwner(1159  api: ApiPromise,1160  collectionId: number,1161  token: number,1162): Promise<CrossAccountId> {1163  const owner = (await api.rpc.unique.topmostTokenOwner(collectionId, token)).toJSON() as any;1164  if (owner == null) throw new Error('owner == null');1165  return normalizeAccountId(owner);1166}1167export async function getTokenChildren(1168  api: ApiPromise,1169  collectionId: number,1170  tokenId: number,1171): Promise<UpDataStructsTokenChild[]> {1172  return (await api.rpc.unique.tokenChildren(collectionId, tokenId)).toJSON() as any;1173}1174export async function isTokenExists(1175  api: ApiPromise,1176  collectionId: number,1177  token: number,1178): Promise<boolean> {1179  return (await api.rpc.unique.tokenExists(collectionId, token)).toJSON();1180}1181export async function getLastTokenId(1182  api: ApiPromise,1183  collectionId: number,1184): Promise<number> {1185  return (await api.rpc.unique.lastTokenId(collectionId)).toJSON();1186}1187export async function getAdminList(1188  api: ApiPromise,1189  collectionId: number,1190): Promise<string[]> {1191  return (await api.rpc.unique.adminlist(collectionId)).toHuman() as any;1192}1193export async function getTokenProperties(1194  api: ApiPromise,1195  collectionId: number,1196  tokenId: number,1197  propertyKeys: string[],1198): Promise<UpDataStructsProperty[]> {1199  return (await api.rpc.unique.tokenProperties(collectionId, tokenId, propertyKeys)).toHuman() as any;1200}12011202export async function createFungibleItemExpectSuccess(1203  sender: IKeyringPair,1204  collectionId: number,1205  data: CreateFungibleData,1206  owner: CrossAccountId | string = sender.address,1207) {1208  return await usingApi(async (api) => {1209    const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), {Fungible: data});12101211    const events = await submitTransactionAsync(sender, tx);1212    const result = getCreateItemResult(events);12131214    expect(result.success).to.be.true;1215    return result.itemId;1216  });1217}12181219export async function createMultipleItemsWithPropsExpectSuccess(sender: IKeyringPair, collectionId: number, itemsData: any, owner: CrossAccountId | string = sender.address) {1220  await usingApi(async (api) => {1221    const to = normalizeAccountId(owner);1222    const tx = api.tx.unique.createMultipleItems(collectionId, to, itemsData);12231224    const events = await submitTransactionAsync(sender, tx);1225    const result = getCreateItemsResult(events);12261227    for (const res of result) {1228      expect(await api.rpc.unique.tokenProperties(collectionId, res.itemId)).not.to.be.empty;1229    }1230  });1231}12321233export async function createMultipleItemsExWithPropsExpectSuccess(sender: IKeyringPair, collectionId: number, itemsData: any) {1234  await usingApi(async (api) => {1235    const tx = api.tx.unique.createMultipleItemsEx(collectionId, itemsData);12361237    const events = await submitTransactionAsync(sender, tx);1238    const result = getCreateItemsResult(events);12391240    for (const res of result) {1241      expect(await api.rpc.unique.tokenProperties(collectionId, res.itemId)).not.to.be.empty;1242    }1243  });1244}12451246export async function createItemWithPropsExpectSuccess(sender: IKeyringPair, collectionId: number, createMode: string, props:  Array<Property>, owner: CrossAccountId | string = sender.address) {1247  let newItemId = 0;1248  await usingApi(async (api) => {1249    const to = normalizeAccountId(owner);1250    const itemCountBefore = await getLastTokenId(api, collectionId);1251    const itemBalanceBefore = await getBalance(api, collectionId, to, newItemId);12521253    let tx;1254    if (createMode === 'Fungible') {1255      const createData = {fungible: {value: 10}};1256      tx = api.tx.unique.createItem(collectionId, to, createData as any);1257    } else if (createMode === 'ReFungible') {1258      const createData = {refungible: {pieces: 100}};1259      tx = api.tx.unique.createItem(collectionId, to, createData as any);1260    } else {1261      const data = api.createType('UpDataStructsCreateItemData', {NFT: {properties: props}});1262      tx = api.tx.unique.createItem(collectionId, to, data as UpDataStructsCreateItemData);1263    }12641265    const events = await submitTransactionAsync(sender, tx);1266    const result = getCreateItemResult(events);12671268    const itemCountAfter = await getLastTokenId(api, collectionId);1269    const itemBalanceAfter = await getBalance(api, collectionId, to, newItemId);12701271    if (createMode === 'NFT') {1272      expect(await api.rpc.unique.tokenProperties(collectionId, result.itemId)).not.to.be.empty;1273    }12741275    // What to expect1276    // tslint:disable-next-line:no-unused-expression1277    expect(result.success).to.be.true;1278    if (createMode === 'Fungible') {1279      expect(itemBalanceAfter - itemBalanceBefore).to.be.equal(10n);1280    } else {1281      expect(itemCountAfter).to.be.equal(itemCountBefore + 1);1282    }1283    expect(collectionId).to.be.equal(result.collectionId);1284    expect(itemCountAfter.toString()).to.be.equal(result.itemId.toString());1285    expect(to).to.be.deep.equal(result.recipient);1286    newItemId = result.itemId;1287  });1288  return newItemId;1289}12901291export async function createItemWithPropsExpectFailure(sender: IKeyringPair, collectionId: number, createMode: string, props: Array<Property>, owner: CrossAccountId | string = sender.address) {1292  await usingApi(async (api) => {12931294    let tx;1295    if (createMode === 'NFT') {1296      const data = api.createType('UpDataStructsCreateItemData', {NFT: {properties: props}});1297      tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), data);1298    } else {1299      tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), createMode);1300    }130113021303    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1304    if(events.message && events.message.toString().indexOf('1002: Verification Error') > -1) return;1305    const result = getCreateItemResult(events);13061307    expect(result.success).to.be.false;1308  });1309}13101311export async function createItemExpectSuccess(sender: IKeyringPair, collectionId: number, createMode: string, owner: CrossAccountId | string = sender.address) {1312  let newItemId = 0;1313  await usingApi(async (api) => {1314    const to = normalizeAccountId(owner);1315    const itemCountBefore = await getLastTokenId(api, collectionId);1316    const itemBalanceBefore = await getBalance(api, collectionId, to, newItemId);13171318    let tx;1319    if (createMode === 'Fungible') {1320      const createData = {fungible: {value: 10}};1321      tx = api.tx.unique.createItem(collectionId, to, createData as any);1322    } else if (createMode === 'ReFungible') {1323      const createData = {refungible: {pieces: 100}};1324      tx = api.tx.unique.createItem(collectionId, to, createData as any);1325    } else {1326      const createData = {nft: {}};1327      tx = api.tx.unique.createItem(collectionId, to, createData as any);1328    }13291330    const events = await submitTransactionAsync(sender, tx);1331    const result = getCreateItemResult(events);13321333    const itemCountAfter = await getLastTokenId(api, collectionId);1334    const itemBalanceAfter = await getBalance(api, collectionId, to, newItemId);13351336    // What to expect1337    // tslint:disable-next-line:no-unused-expression1338    expect(result.success).to.be.true;1339    if (createMode === 'Fungible') {1340      expect(itemBalanceAfter - itemBalanceBefore).to.be.equal(10n);1341    } else {1342      expect(itemCountAfter).to.be.equal(itemCountBefore + 1);1343    }1344    expect(collectionId).to.be.equal(result.collectionId);1345    expect(itemCountAfter.toString()).to.be.equal(result.itemId.toString());1346    expect(to).to.be.deep.equal(result.recipient);1347    newItemId = result.itemId;1348  });1349  return newItemId;1350}13511352export async function createItemExpectFailure(sender: IKeyringPair, collectionId: number, createMode: string, owner: CrossAccountId | string = sender.address) {1353  await usingApi(async (api) => {1354    const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), createMode);13551356    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1357    const result = getCreateItemResult(events);13581359    expect(result.success).to.be.false;1360  });1361}13621363export async function setPublicAccessModeExpectSuccess(1364  sender: IKeyringPair, collectionId: number,1365  accessMode: 'Normal' | 'AllowList',1366) {1367  await usingApi(async (api) => {13681369    // Run the transaction1370    const tx = api.tx.unique.setCollectionPermissions(collectionId, {access: accessMode});1371    const events = await submitTransactionAsync(sender, tx);1372    const result = getGenericResult(events);13731374    // Get the collection1375    const collection = await queryCollectionExpectSuccess(api, collectionId);13761377    // What to expect1378    // tslint:disable-next-line:no-unused-expression1379    expect(result.success).to.be.true;1380    expect(collection.permissions.access.toHuman()).to.be.equal(accessMode);1381  });1382}13831384export async function setPublicAccessModeExpectFail(1385  sender: IKeyringPair, collectionId: number,1386  accessMode: 'Normal' | 'AllowList',1387) {1388  await usingApi(async (api) => {13891390    // Run the transaction1391    const tx = api.tx.unique.setCollectionPermissions(collectionId, {access: accessMode});1392    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1393    const result = getGenericResult(events);13941395    // What to expect1396    // tslint:disable-next-line:no-unused-expression1397    expect(result.success).to.be.false;1398  });1399}14001401export async function enableAllowListExpectSuccess(sender: IKeyringPair, collectionId: number) {1402  await setPublicAccessModeExpectSuccess(sender, collectionId, 'AllowList');1403}14041405export async function enableAllowListExpectFail(sender: IKeyringPair, collectionId: number) {1406  await setPublicAccessModeExpectFail(sender, collectionId, 'AllowList');1407}14081409export async function disableAllowListExpectSuccess(sender: IKeyringPair, collectionId: number) {1410  await setPublicAccessModeExpectSuccess(sender, collectionId, 'Normal');1411}14121413export async function setMintPermissionExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {1414  await usingApi(async (api) => {14151416    // Run the transaction1417    const tx = api.tx.unique.setCollectionPermissions(collectionId, {mintMode: enabled});1418    const events = await submitTransactionAsync(sender, tx);1419    const result = getGenericResult(events);1420    expect(result.success).to.be.true;14211422    // Get the collection1423    const collection = await queryCollectionExpectSuccess(api, collectionId);14241425    expect(collection.permissions.mintMode.toHuman()).to.be.equal(enabled);1426  });1427}14281429export async function enablePublicMintingExpectSuccess(sender: IKeyringPair, collectionId: number) {1430  await setMintPermissionExpectSuccess(sender, collectionId, true);1431}14321433export async function setMintPermissionExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {1434  await usingApi(async (api) => {1435    // Run the transaction1436    const tx = api.tx.unique.setCollectionPermissions(collectionId, {mintMode: enabled});1437    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1438    const result = getCreateCollectionResult(events);1439    // tslint:disable-next-line:no-unused-expression1440    expect(result.success).to.be.false;1441  });1442}14431444export async function setChainLimitsExpectFailure(sender: IKeyringPair, limits: IChainLimits) {1445  await usingApi(async (api) => {1446    // Run the transaction1447    const tx = api.tx.unique.setChainLimits(limits);1448    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1449    const result = getCreateCollectionResult(events);1450    // tslint:disable-next-line:no-unused-expression1451    expect(result.success).to.be.false;1452  });1453}14541455export async function isAllowlisted(api: ApiPromise, collectionId: number, address: string | CrossAccountId) {1456  return (await api.rpc.unique.allowed(collectionId, normalizeAccountId(address))).toJSON();1457}14581459export async function addToAllowListExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId | CrossAccountId) {1460  await usingApi(async (api) => {1461    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.false;14621463    // Run the transaction1464    const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1465    const events = await submitTransactionAsync(sender, tx);1466    const result = getGenericResult(events);1467    expect(result.success).to.be.true;14681469    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;1470  });1471}14721473export async function addToAllowListAgainExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId) {1474  await usingApi(async (api) => {14751476    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;14771478    // Run the transaction1479    const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1480    const events = await submitTransactionAsync(sender, tx);1481    const result = getGenericResult(events);1482    expect(result.success).to.be.true;14831484    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;1485  });1486}14871488export async function addToAllowListExpectFail(sender: IKeyringPair, collectionId: number, address: string | AccountId) {1489  await usingApi(async (api) => {14901491    // Run the transaction1492    const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1493    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1494    const result = getGenericResult(events);14951496    // What to expect1497    // tslint:disable-next-line:no-unused-expression1498    expect(result.success).to.be.false;1499  });1500}15011502export async function removeFromAllowListExpectSuccess(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1503  await usingApi(async (api) => {1504    // Run the transaction1505    const tx = api.tx.unique.removeFromAllowList(collectionId, normalizeAccountId(address));1506    const events = await submitTransactionAsync(sender, tx);1507    const result = getGenericResult(events);15081509    // What to expect1510    // tslint:disable-next-line:no-unused-expression1511    expect(result.success).to.be.true;1512  });1513}15141515export async function removeFromAllowListExpectFailure(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1516  await usingApi(async (api) => {1517    // Run the transaction1518    const tx = api.tx.unique.removeFromAllowList(collectionId, normalizeAccountId(address));1519    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1520    const result = getGenericResult(events);15211522    // What to expect1523    // tslint:disable-next-line:no-unused-expression1524    expect(result.success).to.be.false;1525  });1526}15271528export const getDetailedCollectionInfo = async (api: ApiPromise, collectionId: number)1529  : Promise<UpDataStructsRpcCollection | null> => {1530  return (await api.rpc.unique.collectionById(collectionId)).unwrapOr(null);1531};15321533export const getCreatedCollectionCount = async (api: ApiPromise): Promise<number> => {1534  // set global object - collectionsCount1535  return (await api.rpc.unique.collectionStats()).created.toNumber();1536};15371538export async function queryCollectionExpectSuccess(api: ApiPromise, collectionId: number): Promise<UpDataStructsRpcCollection> {1539  return (await api.rpc.unique.collectionById(collectionId)).unwrap();1540}15411542export async function waitNewBlocks(blocksCount = 1): Promise<void> {1543  await usingApi(async (api) => {1544    const promise = new Promise<void>(async (resolve) => {1545      const unsubscribe = await api.rpc.chain.subscribeNewHeads(() => {1546        if (blocksCount > 0) {1547          blocksCount--;1548        } else {1549          unsubscribe();1550          resolve();1551        }1552      });1553    });1554    return promise;1555  });1556}
after · tests/src/util/helpers.ts
1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617import '../interfaces/augment-api-rpc';18import '../interfaces/augment-api-query';19import {ApiPromise} from '@polkadot/api';20import type {AccountId, EventRecord, Event} from '@polkadot/types/interfaces';21import type {GenericEventData} from '@polkadot/types';22import {AnyTuple, IEvent, IKeyringPair} from '@polkadot/types/types';23import {evmToAddress} from '@polkadot/util-crypto';24import BN from 'bn.js';25import chai from 'chai';26import chaiAsPromised from 'chai-as-promised';27import {default as usingApi, executeTransaction, submitTransactionAsync, submitTransactionExpectFailAsync} from '../substrate/substrate-api';28import {hexToStr, strToUTF16, utf16ToStr} from './util';29import {UpDataStructsRpcCollection, UpDataStructsCreateItemData, UpDataStructsProperty} from '@polkadot/types/lookup';30import {UpDataStructsTokenChild} from '../interfaces';3132chai.use(chaiAsPromised);33const expect = chai.expect;3435export type CrossAccountId = {36  Substrate: string,37} | {38  Ethereum: string,39};4041export function normalizeAccountId(input: string | AccountId | CrossAccountId | IKeyringPair): CrossAccountId {42  if (typeof input === 'string') {43    if (input.length >= 47) {44      return {Substrate: input};45    } else if (input.length === 42 && input.startsWith('0x')) {46      return {Ethereum: input.toLowerCase()};47    } else if (input.length === 40 && !input.startsWith('0x')) {48      return {Ethereum: '0x' + input.toLowerCase()};49    } else {50      throw new Error(`Unknown address format: "${input}"`);51    }52  }53  if ('address' in input) {54    return {Substrate: input.address};55  }56  if ('Ethereum' in input) {57    return {58      Ethereum: input.Ethereum.toLowerCase(),59    };60  } else if ('ethereum' in input) {61    return {62      Ethereum: (input as any).ethereum.toLowerCase(),63    };64  } else if ('Substrate' in input) {65    return input;66  } else if ('substrate' in input) {67    return {68      Substrate: (input as any).substrate,69    };70  }7172  // AccountId73  return {Substrate: input.toString()};74}75export function toSubstrateAddress(input: string | CrossAccountId | IKeyringPair): string {76  input = normalizeAccountId(input);77  if ('Substrate' in input) {78    return input.Substrate;79  } else {80    return evmToAddress(input.Ethereum);81  }82}8384export const U128_MAX = (1n << 128n) - 1n;8586const MICROUNIQUE = 1_000_000_000_000n;87const MILLIUNIQUE = 1_000n * MICROUNIQUE;88const CENTIUNIQUE = 10n * MILLIUNIQUE;89export const UNIQUE = 100n * CENTIUNIQUE;9091interface GenericResult<T> {92  success: boolean;93  data: T | null;94}9596interface CreateCollectionResult {97  success: boolean;98  collectionId: number;99}100101interface CreateItemResult {102  success: boolean;103  collectionId: number;104  itemId: number;105  recipient?: CrossAccountId;106}107108interface TransferResult {109  collectionId: number;110  itemId: number;111  sender?: CrossAccountId;112  recipient?: CrossAccountId;113  value: bigint;114}115116interface IReFungibleOwner {117  fraction: BN;118  owner: number[];119}120121interface IGetMessage {122  checkMsgUnqMethod: string;123  checkMsgTrsMethod: string;124  checkMsgSysMethod: string;125}126127export interface IFungibleTokenDataType {128  value: number;129}130131export interface IChainLimits {132  collectionNumbersLimit: number;133  accountTokenOwnershipLimit: number;134  collectionsAdminsLimit: number;135  customDataLimit: number;136  nftSponsorTransferTimeout: number;137  fungibleSponsorTransferTimeout: number;138  refungibleSponsorTransferTimeout: number;139  //offchainSchemaLimit: number;140  //constOnChainSchemaLimit: number;141}142143export interface IReFungibleTokenDataType {144  owner: IReFungibleOwner[];145}146147export function uniqueEventMessage(events: EventRecord[]): IGetMessage {148  let checkMsgUnqMethod = '';149  let checkMsgTrsMethod = '';150  let checkMsgSysMethod = '';151  events.forEach(({event: {method, section}}) => {152    if (section === 'common') {153      checkMsgUnqMethod = method;154    } else if (section === 'treasury') {155      checkMsgTrsMethod = method;156    } else if (section === 'system') {157      checkMsgSysMethod = method;158    } else { return null; }159  });160  const result: IGetMessage = {161    checkMsgUnqMethod,162    checkMsgTrsMethod,163    checkMsgSysMethod,164  };165  return result;166}167168export function getEvent<T extends Event>(events: EventRecord[], check: (event: IEvent<AnyTuple>) => event is T): T | undefined {169  const event = events.find(r => check(r.event));170  if (!event) return;171  return event.event as T;172}173174export function getGenericResult<T>(events: EventRecord[]): GenericResult<T>;175export function getGenericResult<T>(176  events: EventRecord[],177  expectSection: string,178  expectMethod: string,179  extractAction: (data: GenericEventData) => T180): GenericResult<T>;181182export function getGenericResult<T>(183  events: EventRecord[],184  expectSection?: string,185  expectMethod?: string,186  extractAction?: (data: GenericEventData) => T,187): GenericResult<T> {188  let success = false;189  let successData = null;190191  events.forEach(({event: {data, method, section}}) => {192    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);193    if (method === 'ExtrinsicSuccess') {194      success = true;195    } else if ((expectSection == section) && (expectMethod == method)) {196      successData = extractAction!(data);197    }198  });199200  const result: GenericResult<T> = {201    success,202    data: successData,203  };204  return result;205}206207export function getCreateCollectionResult(events: EventRecord[]): CreateCollectionResult {208  const genericResult = getGenericResult(events, 'common', 'CollectionCreated', (data) => parseInt(data[0].toString(), 10));209  const result: CreateCollectionResult = {210    success: genericResult.success,211    collectionId: genericResult.data ?? 0,212  };213  return result;214}215216export function getCreateItemsResult(events: EventRecord[]): CreateItemResult[] {217  const results: CreateItemResult[] = [];218  219  const genericResult = getGenericResult<CreateItemResult[]>(events, 'common', 'ItemCreated', (data) => {220    const collectionId = parseInt(data[0].toString(), 10);221    const itemId = parseInt(data[1].toString(), 10);222    const recipient = normalizeAccountId(data[2].toJSON() as any);223224    const itemRes: CreateItemResult = {225      success: true,226      collectionId,227      itemId,228      recipient,229    };230231    results.push(itemRes);232    return results;233  });234235  if (!genericResult.success) return [];236  return results;237}238239export function getCreateItemResult(events: EventRecord[]): CreateItemResult {240  const genericResult = getGenericResult<[number, number, CrossAccountId?]>(events, 'common', 'ItemCreated', (data) => [241    parseInt(data[0].toString(), 10),242    parseInt(data[1].toString(), 10),243    normalizeAccountId(data[2].toJSON() as any),244  ]);245246  if (genericResult.data == null) genericResult.data = [0, 0];247248  const result: CreateItemResult = {249    success: genericResult.success,250    collectionId: genericResult.data[0],251    itemId: genericResult.data[1],252    recipient: genericResult.data![2],253  };254  255  return result;256}257258export function getTransferResult(api: ApiPromise, events: EventRecord[]): TransferResult {259  for (const {event} of events) {260    if (api.events.common.Transfer.is(event)) {261      const [collection, token, sender, recipient, value] = event.data;262      return {263        collectionId: collection.toNumber(),264        itemId: token.toNumber(),265        sender: normalizeAccountId(sender.toJSON() as any),266        recipient: normalizeAccountId(recipient.toJSON() as any),267        value: value.toBigInt(),268      };269    }270  }271  throw new Error('no transfer event');272}273274interface Nft {275  type: 'NFT';276}277278interface Fungible {279  type: 'Fungible';280  decimalPoints: number;281}282283interface ReFungible {284  type: 'ReFungible';285}286287type CollectionMode = Nft | Fungible | ReFungible;288289export type Property = {290  key: any,291  value: any,292};293294type Permission = {295  mutable: boolean;296  collectionAdmin: boolean;297  tokenOwner: boolean;298}299300type PropertyPermission = {301  key: any;302  permission: Permission;303}304305export type CreateCollectionParams = {306  mode: CollectionMode,307  name: string,308  description: string,309  tokenPrefix: string,310  properties?: Array<Property>,311  propPerm?: Array<PropertyPermission>312};313314const defaultCreateCollectionParams: CreateCollectionParams = {315  description: 'description',316  mode: {type: 'NFT'},317  name: 'name',318  tokenPrefix: 'prefix',319};320321export async function createCollectionExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {322  const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};323324  let collectionId = 0;325  await usingApi(async (api, privateKeyWrapper) => {326    // Get number of collections before the transaction327    const collectionCountBefore = await getCreatedCollectionCount(api);328329    // Run the CreateCollection transaction330    const alicePrivateKey = privateKeyWrapper('//Alice');331332    let modeprm = {};333    if (mode.type === 'NFT') {334      modeprm = {nft: null};335    } else if (mode.type === 'Fungible') {336      modeprm = {fungible: mode.decimalPoints};337    } else if (mode.type === 'ReFungible') {338      modeprm = {refungible: null};339    }340341    const tx = api.tx.unique.createCollectionEx({342      name: strToUTF16(name),343      description: strToUTF16(description),344      tokenPrefix: strToUTF16(tokenPrefix),345      mode: modeprm as any,346    });347    const events = await submitTransactionAsync(alicePrivateKey, tx);348    const result = getCreateCollectionResult(events);349350    // Get number of collections after the transaction351    const collectionCountAfter = await getCreatedCollectionCount(api);352353    // Get the collection354    const collection = await queryCollectionExpectSuccess(api, result.collectionId);355356    // What to expect357    // tslint:disable-next-line:no-unused-expression358    expect(result.success).to.be.true;359    expect(result.collectionId).to.be.equal(collectionCountAfter);360    // tslint:disable-next-line:no-unused-expression361    expect(collection).to.be.not.null;362    expect(collectionCountAfter).to.be.equal(collectionCountBefore + 1, 'Error: NFT collection NOT created.');363    expect(collection.owner.toString()).to.be.equal(toSubstrateAddress(alicePrivateKey));364    expect(utf16ToStr(collection.name.toJSON() as any)).to.be.equal(name);365    expect(utf16ToStr(collection.description.toJSON() as any)).to.be.equal(description);366    expect(hexToStr(collection.tokenPrefix.toJSON())).to.be.equal(tokenPrefix);367368    collectionId = result.collectionId;369  });370371  return collectionId;372}373374export async function createCollectionWithPropsExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {375  const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};376377  let collectionId = 0;378  await usingApi(async (api, privateKeyWrapper) => {379    // Get number of collections before the transaction380    const collectionCountBefore = await getCreatedCollectionCount(api);381382    // Run the CreateCollection transaction383    const alicePrivateKey = privateKeyWrapper('//Alice');384385    let modeprm = {};386    if (mode.type === 'NFT') {387      modeprm = {nft: null};388    } else if (mode.type === 'Fungible') {389      modeprm = {fungible: mode.decimalPoints};390    } else if (mode.type === 'ReFungible') {391      modeprm = {refungible: null};392    }393394    const tx = api.tx.unique.createCollectionEx({name: strToUTF16(name), description: strToUTF16(description), tokenPrefix: strToUTF16(tokenPrefix), mode: modeprm as any, properties: params.properties, tokenPropertyPermissions: params.propPerm});395    const events = await submitTransactionAsync(alicePrivateKey, tx);396    const result = getCreateCollectionResult(events);397398    // Get number of collections after the transaction399    const collectionCountAfter = await getCreatedCollectionCount(api);400401    // Get the collection402    const collection = await queryCollectionExpectSuccess(api, result.collectionId);403404    // What to expect405    // tslint:disable-next-line:no-unused-expression406    expect(result.success).to.be.true;407    expect(result.collectionId).to.be.equal(collectionCountAfter);408    // tslint:disable-next-line:no-unused-expression409    expect(collection).to.be.not.null;410    expect(collectionCountAfter).to.be.equal(collectionCountBefore + 1, 'Error: NFT collection NOT created.');411    expect(collection.owner.toString()).to.be.equal(toSubstrateAddress(alicePrivateKey));412    expect(utf16ToStr(collection.name.toJSON() as any)).to.be.equal(name);413    expect(utf16ToStr(collection.description.toJSON() as any)).to.be.equal(description);414    expect(hexToStr(collection.tokenPrefix.toJSON())).to.be.equal(tokenPrefix);415416417    collectionId = result.collectionId;418  });419420  return collectionId;421}422423export async function createCollectionWithPropsExpectFailure(params: Partial<CreateCollectionParams> = {}) {424  const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};425426  await usingApi(async (api, privateKeyWrapper) => {427    // Get number of collections before the transaction428    const collectionCountBefore = await getCreatedCollectionCount(api);429430    // Run the CreateCollection transaction431    const alicePrivateKey = privateKeyWrapper('//Alice');432433    let modeprm = {};434    if (mode.type === 'NFT') {435      modeprm = {nft: null};436    } else if (mode.type === 'Fungible') {437      modeprm = {fungible: mode.decimalPoints};438    } else if (mode.type === 'ReFungible') {439      modeprm = {refungible: null};440    }441442    const tx = api.tx.unique.createCollectionEx({name: strToUTF16(name), description: strToUTF16(description), tokenPrefix: strToUTF16(tokenPrefix), mode: modeprm as any, properties: params.properties, tokenPropertyPermissions: params.propPerm});443    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;444445446    // Get number of collections after the transaction447    const collectionCountAfter = await getCreatedCollectionCount(api);448449    expect(collectionCountAfter).to.be.equal(collectionCountBefore, 'Error: Collection with incorrect data created.');450  });451}452453export async function createCollectionExpectFailure(params: Partial<CreateCollectionParams> = {}) {454  const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};455456  let modeprm = {};457  if (mode.type === 'NFT') {458    modeprm = {nft: null};459  } else if (mode.type === 'Fungible') {460    modeprm = {fungible: mode.decimalPoints};461  } else if (mode.type === 'ReFungible') {462    modeprm = {refungible: null};463  }464465  await usingApi(async (api, privateKeyWrapper) => {466    // Get number of collections before the transaction467    const collectionCountBefore = await getCreatedCollectionCount(api);468469    // Run the CreateCollection transaction470    const alicePrivateKey = privateKeyWrapper('//Alice');471    const tx = api.tx.unique.createCollectionEx({name: strToUTF16(name), description: strToUTF16(description), tokenPrefix: strToUTF16(tokenPrefix), mode: modeprm as any});472    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;473474    // Get number of collections after the transaction475    const collectionCountAfter = await getCreatedCollectionCount(api);476477    // What to expect478    expect(collectionCountAfter).to.be.equal(collectionCountBefore, 'Error: Collection with incorrect data created.');479  });480}481482export async function findUnusedAddress(api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair, seedAddition = ''): Promise<IKeyringPair> {483  let bal = 0n;484  let unused;485  do {486    const randomSeed = 'seed' + Math.floor(Math.random() * Math.floor(10000)) + seedAddition;487    unused = privateKeyWrapper(`//${randomSeed}`);488    bal = (await api.query.system.account(unused.address)).data.free.toBigInt();489  } while (bal !== 0n);490  return unused;491}492493export async function getAllowance(api: ApiPromise, collectionId: number, owner: CrossAccountId | string, approved: CrossAccountId | string, tokenId: number) {494  return (await api.rpc.unique.allowance(collectionId, normalizeAccountId(owner), normalizeAccountId(approved), tokenId)).toBigInt();495}496497export function findUnusedAddresses(api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair, amount: number): Promise<IKeyringPair[]> {498  return Promise.all(new Array(amount).fill(null).map(() => findUnusedAddress(api, privateKeyWrapper, '_' + Date.now())));499}500501export async function findNotExistingCollection(api: ApiPromise): Promise<number> {502  const totalNumber = await getCreatedCollectionCount(api);503  const newCollection: number = totalNumber + 1;504  return newCollection;505}506507function getDestroyResult(events: EventRecord[]): boolean {508  let success = false;509  events.forEach(({event: {method}}) => {510    if (method == 'ExtrinsicSuccess') {511      success = true;512    }513  });514  return success;515}516517export async function destroyCollectionExpectFailure(collectionId: number, senderSeed = '//Alice') {518  await usingApi(async (api, privateKeyWrapper) => {519    // Run the DestroyCollection transaction520    const alicePrivateKey = privateKeyWrapper(senderSeed);521    const tx = api.tx.unique.destroyCollection(collectionId);522    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;523  });524}525526export async function destroyCollectionExpectSuccess(collectionId: number, senderSeed = '//Alice') {527  await usingApi(async (api, privateKeyWrapper) => {528    // Run the DestroyCollection transaction529    const alicePrivateKey = privateKeyWrapper(senderSeed);530    const tx = api.tx.unique.destroyCollection(collectionId);531    const events = await submitTransactionAsync(alicePrivateKey, tx);532    const result = getDestroyResult(events);533    expect(result).to.be.true;534535    // What to expect536    expect(await getDetailedCollectionInfo(api, collectionId)).to.be.null;537  });538}539540export async function setCollectionLimitsExpectSuccess(sender: IKeyringPair, collectionId: number, limits: any) {541  await usingApi(async (api) => {542    const tx = api.tx.unique.setCollectionLimits(collectionId, limits);543    const events = await submitTransactionAsync(sender, tx);544    const result = getGenericResult(events);545546    expect(result.success).to.be.true;547  });548}549550export const setCollectionPermissionsExpectSuccess = async (sender: IKeyringPair, collectionId: number, permissions: {mintMode?: boolean, access?: 'Normal' | 'AllowList', nesting?: 'Disabled' | 'Owner' | {OwnerRestricted: number[]}}) => {551  await usingApi(async(api) => {552    const tx = api.tx.unique.setCollectionPermissions(collectionId, permissions);553    const events = await submitTransactionAsync(sender, tx);554    const result = getGenericResult(events);555556    expect(result.success).to.be.true;557  });558};559560export async function setCollectionLimitsExpectFailure(sender: IKeyringPair, collectionId: number, limits: any) {561  await usingApi(async (api) => {562    const tx = api.tx.unique.setCollectionLimits(collectionId, limits);563    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;564    const result = getGenericResult(events);565566    expect(result.success).to.be.false;567  });568}569570export async function setCollectionSponsorExpectSuccess(collectionId: number, sponsor: string, sender = '//Alice') {571  await usingApi(async (api, privateKeyWrapper) => {572573    // Run the transaction574    const senderPrivateKey = privateKeyWrapper(sender);575    const tx = api.tx.unique.setCollectionSponsor(collectionId, sponsor);576    const events = await submitTransactionAsync(senderPrivateKey, tx);577    const result = getGenericResult(events);578579    // Get the collection580    const collection = await queryCollectionExpectSuccess(api, collectionId);581582    // What to expect583    expect(result.success).to.be.true;584    expect(collection.sponsorship.toJSON()).to.deep.equal({585      unconfirmed: sponsor,586    });587  });588}589590export async function removeCollectionSponsorExpectSuccess(collectionId: number, sender = '//Alice') {591  await usingApi(async (api, privateKeyWrapper) => {592593    // Run the transaction594    const alicePrivateKey = privateKeyWrapper(sender);595    const tx = api.tx.unique.removeCollectionSponsor(collectionId);596    const events = await submitTransactionAsync(alicePrivateKey, tx);597    const result = getGenericResult(events);598599    // Get the collection600    const collection = await queryCollectionExpectSuccess(api, collectionId);601602    // What to expect603    expect(result.success).to.be.true;604    expect(collection.sponsorship.toJSON()).to.be.deep.equal({disabled: null});605  });606}607608export async function removeCollectionSponsorExpectFailure(collectionId: number, senderSeed = '//Alice') {609  await usingApi(async (api, privateKeyWrapper) => {610611    // Run the transaction612    const alicePrivateKey = privateKeyWrapper(senderSeed);613    const tx = api.tx.unique.removeCollectionSponsor(collectionId);614    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;615  });616}617618export async function setCollectionSponsorExpectFailure(collectionId: number, sponsor: string, senderSeed = '//Alice') {619  await usingApi(async (api, privateKeyWrapper) => {620621    // Run the transaction622    const alicePrivateKey = privateKeyWrapper(senderSeed);623    const tx = api.tx.unique.setCollectionSponsor(collectionId, sponsor);624    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;625  });626}627628export async function confirmSponsorshipExpectSuccess(collectionId: number, senderSeed = '//Alice') {629  await usingApi(async (api, privateKeyWrapper) => {630631    // Run the transaction632    const sender = privateKeyWrapper(senderSeed);633    await confirmSponsorshipByKeyExpectSuccess(collectionId, sender);634  });635}636637export async function confirmSponsorshipByKeyExpectSuccess(collectionId: number, sender: IKeyringPair) {638  await usingApi(async (api, privateKeyWrapper) => {639640    // Run the transaction641    const tx = api.tx.unique.confirmSponsorship(collectionId);642    const events = await submitTransactionAsync(sender, tx);643    const result = getGenericResult(events);644645    // Get the collection646    const collection = await queryCollectionExpectSuccess(api, collectionId);647648    // What to expect649    expect(result.success).to.be.true;650    expect(collection.sponsorship.toJSON()).to.be.deep.equal({651      confirmed: sender.address,652    });653  });654}655656657export async function confirmSponsorshipExpectFailure(collectionId: number, senderSeed = '//Alice') {658  await usingApi(async (api, privateKeyWrapper) => {659660    // Run the transaction661    const sender = privateKeyWrapper(senderSeed);662    const tx = api.tx.unique.confirmSponsorship(collectionId);663    await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;664  });665}666667export async function enableContractSponsoringExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {668  await usingApi(async (api) => {669    const tx = api.tx.unique.enableContractSponsoring(contractAddress, enable);670    const events = await submitTransactionAsync(sender, tx);671    const result = getGenericResult(events);672673    expect(result.success).to.be.true;674  });675}676677export async function enableContractSponsoringExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {678  await usingApi(async (api) => {679    const tx = api.tx.unique.enableContractSponsoring(contractAddress, enable);680    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;681    const result = getGenericResult(events);682683    expect(result.success).to.be.false;684  });685}686687export async function setTransferFlagExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {688689  await usingApi(async (api) => {690691    const tx = api.tx.unique.setTransfersEnabledFlag(collectionId, enabled);692    const events = await submitTransactionAsync(sender, tx);693    const result = getGenericResult(events);694695    expect(result.success).to.be.true;696  });697}698699export async function setTransferFlagExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {700701  await usingApi(async (api) => {702703    const tx = api.tx.unique.setTransfersEnabledFlag(collectionId, enabled);704    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;705    const result = getGenericResult(events);706707    expect(result.success).to.be.false;708  });709}710711export async function setContractSponsoringRateLimitExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {712  await usingApi(async (api) => {713    const tx = api.tx.unique.setContractSponsoringRateLimit(contractAddress, rateLimit);714    const events = await submitTransactionAsync(sender, tx);715    const result = getGenericResult(events);716717    expect(result.success).to.be.true;718  });719}720721export async function setContractSponsoringRateLimitExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {722  await usingApi(async (api) => {723    const tx = api.tx.unique.setContractSponsoringRateLimit(contractAddress, rateLimit);724    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;725    const result = getGenericResult(events);726727    expect(result.success).to.be.false;728  });729}730731export async function getNextSponsored(732  api: ApiPromise,733  collectionId: number,734  account: string | CrossAccountId,735  tokenId: number,736): Promise<number> {737  return Number((await api.rpc.unique.nextSponsored(collectionId, account, tokenId)).unwrapOr(-1));738}739740export async function toggleContractAllowlistExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, value = true) {741  await usingApi(async (api) => {742    const tx = api.tx.unique.toggleContractAllowList(contractAddress, value);743    const events = await submitTransactionAsync(sender, tx);744    const result = getGenericResult(events);745746    expect(result.success).to.be.true;747  });748}749750export async function isAllowlistedInContract(contractAddress: AccountId | string, user: string) {751  let allowlisted = false;752  await usingApi(async (api) => {753    allowlisted = (await api.query.unique.contractAllowList(contractAddress, user)).toJSON() as boolean;754  });755  return allowlisted;756}757758export async function addToContractAllowListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {759  await usingApi(async (api) => {760    const tx = api.tx.unique.addToContractAllowList(contractAddress.toString(), user.toString());761    const events = await submitTransactionAsync(sender, tx);762    const result = getGenericResult(events);763764    expect(result.success).to.be.true;765  });766}767768export async function removeFromContractAllowListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {769  await usingApi(async (api) => {770    const tx = api.tx.unique.removeFromContractAllowList(contractAddress.toString(), user.toString());771    const events = await submitTransactionAsync(sender, tx);772    const result = getGenericResult(events);773774    expect(result.success).to.be.true;775  });776}777778export async function removeFromContractAllowListExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {779  await usingApi(async (api) => {780    const tx = api.tx.unique.removeFromContractAllowList(contractAddress.toString(), user.toString());781    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;782    const result = getGenericResult(events);783784    expect(result.success).to.be.false;785  });786}787788export interface CreateFungibleData {789  readonly Value: bigint;790}791792export interface CreateReFungibleData { }793export interface CreateNftData { }794795export type CreateItemData = {796  NFT: CreateNftData;797} | {798  Fungible: CreateFungibleData;799} | {800  ReFungible: CreateReFungibleData;801};802803export async function burnItemExpectSuccess(sender: IKeyringPair, collectionId: number, tokenId: number, value = 1) {804  await usingApi(async (api) => {805    const balanceBefore = await getBalance(api, collectionId, normalizeAccountId(sender), tokenId);806    // if burning token by admin - use adminButnItemExpectSuccess807    expect(balanceBefore >= BigInt(value)).to.be.true;808809    const tx = api.tx.unique.burnItem(collectionId, tokenId, value);810    const events = await submitTransactionAsync(sender, tx);811    const result = getGenericResult(events);812    expect(result.success).to.be.true;813814    const balanceAfter = await getBalance(api, collectionId, normalizeAccountId(sender), tokenId);815    expect(balanceAfter + BigInt(value)).to.be.equal(balanceBefore);816  });817}818819export async function820approveExpectSuccess(821  collectionId: number,822  tokenId: number, owner: IKeyringPair, approved: CrossAccountId | string, amount: number | bigint = 1,823) {824  await usingApi(async (api: ApiPromise) => {825    const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);826    const events = await submitTransactionAsync(owner, approveUniqueTx);827    const result = getGenericResult(events);828    expect(result.success).to.be.true;829830    expect(await getAllowance(api, collectionId, owner.address, approved, tokenId)).to.be.equal(BigInt(amount));831  });832}833834export async function adminApproveFromExpectSuccess(835  collectionId: number,836  tokenId: number, admin: IKeyringPair, owner: CrossAccountId | string, approved: CrossAccountId | string, amount: number | bigint = 1,837) {838  await usingApi(async (api: ApiPromise) => {839    const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);840    const events = await submitTransactionAsync(admin, approveUniqueTx);841    const result = getGenericResult(events);842    expect(result.success).to.be.true;843844    expect(await getAllowance(api, collectionId, owner, approved, tokenId)).to.be.equal(BigInt(amount));845  });846}847848export async function849transferFromExpectSuccess(850  collectionId: number,851  tokenId: number,852  accountApproved: IKeyringPair,853  accountFrom: IKeyringPair | CrossAccountId,854  accountTo: IKeyringPair | CrossAccountId,855  value: number | bigint = 1,856  type = 'NFT',857) {858  await usingApi(async (api: ApiPromise) => {859    const from = normalizeAccountId(accountFrom);860    const to = normalizeAccountId(accountTo);861    let balanceBefore = 0n;862    if (type === 'Fungible' || type === 'ReFungible') {863      balanceBefore = await getBalance(api, collectionId, to, tokenId);864    }865    const transferFromTx = api.tx.unique.transferFrom(normalizeAccountId(accountFrom), to, collectionId, tokenId, value);866    const events = await submitTransactionAsync(accountApproved, transferFromTx);867    const result = getGenericResult(events);868    // tslint:disable-next-line:no-unused-expression869    expect(result.success).to.be.true;870    if (type === 'NFT') {871      expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(to);872    }873    if (type === 'Fungible') {874      const balanceAfter = await getBalance(api, collectionId, to, tokenId);875      if (JSON.stringify(to) !== JSON.stringify(from)) {876        expect(balanceAfter - balanceBefore).to.be.equal(BigInt(value));877      } else {878        expect(balanceAfter).to.be.equal(balanceBefore);879      }880    }881    if (type === 'ReFungible') {882      expect(await getBalance(api, collectionId, to, tokenId)).to.be.equal(balanceBefore + BigInt(value));883    }884  });885}886887export async function888transferFromExpectFail(889  collectionId: number,890  tokenId: number,891  accountApproved: IKeyringPair,892  accountFrom: IKeyringPair,893  accountTo: IKeyringPair,894  value: number | bigint = 1,895) {896  await usingApi(async (api: ApiPromise) => {897    const transferFromTx = api.tx.unique.transferFrom(normalizeAccountId(accountFrom.address), normalizeAccountId(accountTo.address), collectionId, tokenId, value);898    const events = await expect(submitTransactionExpectFailAsync(accountApproved, transferFromTx)).to.be.rejected;899    const result = getCreateCollectionResult(events);900    // tslint:disable-next-line:no-unused-expression901    expect(result.success).to.be.false;902  });903}904905/* eslint no-async-promise-executor: "off" */906export async function getBlockNumber(api: ApiPromise): Promise<number> {907  return new Promise<number>(async (resolve) => {908    const unsubscribe = await api.rpc.chain.subscribeNewHeads((head) => {909      unsubscribe();910      resolve(head.number.toNumber());911    });912  });913}914915export async function addCollectionAdminExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | CrossAccountId) {916  await usingApi(async (api) => {917    const changeAdminTx = api.tx.unique.addCollectionAdmin(collectionId, normalizeAccountId(address));918    const events = await submitTransactionAsync(sender, changeAdminTx);919    const result = getCreateCollectionResult(events);920    expect(result.success).to.be.true;921  });922}923924export async function925getFreeBalance(account: IKeyringPair): Promise<bigint> {926  let balance = 0n;927  await usingApi(async (api) => {928    balance = BigInt((await api.query.system.account(account.address)).data.free.toString());929  });930931  return balance;932}933934export async function transferBalanceTo(api: ApiPromise, source: IKeyringPair, target: string, amount = 1000n * UNIQUE) {935  const tx = api.tx.balances.transfer(target, amount);936  const events = await submitTransactionAsync(source, tx);937  const result = getGenericResult(events);938  expect(result.success).to.be.true;939}940941export async function942scheduleExpectSuccess(943  operationTx: any,944  sender: IKeyringPair,945  blockSchedule: number,946  scheduledId: string,947  period = 1,948  repetitions = 1,949) {950  await usingApi(async (api: ApiPromise) => {951    const blockNumber: number | undefined = await getBlockNumber(api);952    const expectedBlockNumber = blockNumber + blockSchedule;953954    expect(blockNumber).to.be.greaterThan(0);955    const scheduleTx = api.tx.scheduler.scheduleNamed( // schedule956      scheduledId,957      expectedBlockNumber, 958      repetitions > 1 ? [period, repetitions] : null, 959      0, 960      {value: operationTx as any},961    );962963    const events = await submitTransactionAsync(sender, scheduleTx);964    expect(getGenericResult(events).success).to.be.true;965  });966}967968export async function969scheduleExpectFailure(970  operationTx: any,971  sender: IKeyringPair,972  blockSchedule: number,973  scheduledId: string,974  period = 1,975  repetitions = 1,976) {977  await usingApi(async (api: ApiPromise) => {978    const blockNumber: number | undefined = await getBlockNumber(api);979    const expectedBlockNumber = blockNumber + blockSchedule;980981    expect(blockNumber).to.be.greaterThan(0);982    const scheduleTx = api.tx.scheduler.scheduleNamed( // schedule983      scheduledId,984      expectedBlockNumber, 985      repetitions <= 1 ? null : [period, repetitions], 986      0, 987      {value: operationTx as any},988    );989990    //const events = 991    await expect(submitTransactionExpectFailAsync(sender, scheduleTx)).to.be.rejected;992    //expect(getGenericResult(events).success).to.be.false;993  });994}995996export async function997scheduleTransferAndWaitExpectSuccess(998  collectionId: number,999  tokenId: number,1000  sender: IKeyringPair,1001  recipient: IKeyringPair,1002  value: number | bigint = 1,1003  blockSchedule: number,1004  scheduledId: string,1005) {1006  await usingApi(async (api: ApiPromise) => {1007    await scheduleTransferExpectSuccess(collectionId, tokenId, sender, recipient, value, blockSchedule, scheduledId);10081009    const recipientBalanceBefore = (await api.query.system.account(recipient.address)).data.free.toBigInt();10101011    // sleep for n + 1 blocks1012    await waitNewBlocks(blockSchedule + 1);10131014    const recipientBalanceAfter = (await api.query.system.account(recipient.address)).data.free.toBigInt();10151016    expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(recipient.address));1017    expect(recipientBalanceAfter).to.be.equal(recipientBalanceBefore);1018  });1019}10201021export async function1022scheduleTransferExpectSuccess(1023  collectionId: number,1024  tokenId: number,1025  sender: IKeyringPair,1026  recipient: IKeyringPair,1027  value: number | bigint = 1,1028  blockSchedule: number,1029  scheduledId: string,1030) {1031  await usingApi(async (api: ApiPromise) => {1032    const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient.address), collectionId, tokenId, value);10331034    await scheduleExpectSuccess(transferTx, sender, blockSchedule, scheduledId);10351036    expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(sender.address));1037  });1038}10391040export async function1041scheduleTransferFundsPeriodicExpectSuccess(1042  amount: bigint,1043  sender: IKeyringPair,1044  recipient: IKeyringPair,1045  blockSchedule: number,1046  scheduledId: string,1047  period: number,1048  repetitions: number,1049) {1050  await usingApi(async (api: ApiPromise) => {1051    const transferTx = api.tx.balances.transfer(recipient.address, amount);10521053    const balanceBefore = await getFreeBalance(recipient);1054    1055    await scheduleExpectSuccess(transferTx, sender, blockSchedule, scheduledId, period, repetitions);10561057    expect(await getFreeBalance(recipient)).to.be.equal(balanceBefore);1058  });1059}10601061export async function1062transferExpectSuccess(1063  collectionId: number,1064  tokenId: number,1065  sender: IKeyringPair,1066  recipient: IKeyringPair | CrossAccountId,1067  value: number | bigint = 1,1068  type = 'NFT',1069) {1070  await usingApi(async (api: ApiPromise) => {1071    const from = normalizeAccountId(sender);1072    const to = normalizeAccountId(recipient);10731074    let balanceBefore = 0n;1075    if (type === 'Fungible') {1076      balanceBefore = await getBalance(api, collectionId, to, tokenId);1077    }1078    const transferTx = api.tx.unique.transfer(to, collectionId, tokenId, value);1079    const events = await executeTransaction(api, sender, transferTx);10801081    const result = getTransferResult(api, events);1082    expect(result.collectionId).to.be.equal(collectionId);1083    expect(result.itemId).to.be.equal(tokenId);1084    expect(result.sender).to.be.deep.equal(normalizeAccountId(sender.address));1085    expect(result.recipient).to.be.deep.equal(to);1086    expect(result.value).to.be.equal(BigInt(value));10871088    if (type === 'NFT') {1089      expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(to);1090    }1091    if (type === 'Fungible') {1092      const balanceAfter = await getBalance(api, collectionId, to, tokenId);1093      if (JSON.stringify(to) !== JSON.stringify(from)) {1094        expect(balanceAfter - balanceBefore).to.be.equal(BigInt(value));1095      } else {1096        expect(balanceAfter).to.be.equal(balanceBefore);1097      }1098    }1099    if (type === 'ReFungible') {1100      expect(await getBalance(api, collectionId, to, tokenId) >= value).to.be.true;1101    }1102  });1103}11041105export async function1106transferExpectFailure(1107  collectionId: number,1108  tokenId: number,1109  sender: IKeyringPair,1110  recipient: IKeyringPair | CrossAccountId,1111  value: number | bigint = 1,1112) {1113  await usingApi(async (api: ApiPromise) => {1114    const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient), collectionId, tokenId, value);1115    const events = await expect(submitTransactionExpectFailAsync(sender, transferTx)).to.be.rejected;1116    const result = getGenericResult(events);1117    // if (events && Array.isArray(events)) {1118    //   const result = getCreateCollectionResult(events);1119    // tslint:disable-next-line:no-unused-expression1120    expect(result.success).to.be.false;1121    //}1122  });1123}11241125export async function1126approveExpectFail(1127  collectionId: number,1128  tokenId: number, owner: IKeyringPair, approved: IKeyringPair, amount: number | bigint = 1,1129) {1130  await usingApi(async (api: ApiPromise) => {1131    const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved.address), collectionId, tokenId, amount);1132    const events = await expect(submitTransactionExpectFailAsync(owner, approveUniqueTx)).to.be.rejected;1133    const result = getCreateCollectionResult(events);1134    // tslint:disable-next-line:no-unused-expression1135    expect(result.success).to.be.false;1136  });1137}11381139export async function getBalance(1140  api: ApiPromise,1141  collectionId: number,1142  owner: string | CrossAccountId,1143  token: number,1144): Promise<bigint> {1145  return (await api.rpc.unique.balance(collectionId, normalizeAccountId(owner), token)).toBigInt();1146}1147export async function getTokenOwner(1148  api: ApiPromise,1149  collectionId: number,1150  token: number,1151): Promise<CrossAccountId> {1152  const owner = (await api.rpc.unique.tokenOwner(collectionId, token)).toJSON() as any;1153  if (owner == null) throw new Error('owner == null');1154  return normalizeAccountId(owner);1155}1156export async function getTopmostTokenOwner(1157  api: ApiPromise,1158  collectionId: number,1159  token: number,1160): Promise<CrossAccountId> {1161  const owner = (await api.rpc.unique.topmostTokenOwner(collectionId, token)).toJSON() as any;1162  if (owner == null) throw new Error('owner == null');1163  return normalizeAccountId(owner);1164}1165export async function getTokenChildren(1166  api: ApiPromise,1167  collectionId: number,1168  tokenId: number,1169): Promise<UpDataStructsTokenChild[]> {1170  return (await api.rpc.unique.tokenChildren(collectionId, tokenId)).toJSON() as any;1171}1172export async function isTokenExists(1173  api: ApiPromise,1174  collectionId: number,1175  token: number,1176): Promise<boolean> {1177  return (await api.rpc.unique.tokenExists(collectionId, token)).toJSON();1178}1179export async function getLastTokenId(1180  api: ApiPromise,1181  collectionId: number,1182): Promise<number> {1183  return (await api.rpc.unique.lastTokenId(collectionId)).toJSON();1184}1185export async function getAdminList(1186  api: ApiPromise,1187  collectionId: number,1188): Promise<string[]> {1189  return (await api.rpc.unique.adminlist(collectionId)).toHuman() as any;1190}1191export async function getTokenProperties(1192  api: ApiPromise,1193  collectionId: number,1194  tokenId: number,1195  propertyKeys: string[],1196): Promise<UpDataStructsProperty[]> {1197  return (await api.rpc.unique.tokenProperties(collectionId, tokenId, propertyKeys)).toHuman() as any;1198}11991200export async function createFungibleItemExpectSuccess(1201  sender: IKeyringPair,1202  collectionId: number,1203  data: CreateFungibleData,1204  owner: CrossAccountId | string = sender.address,1205) {1206  return await usingApi(async (api) => {1207    const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), {Fungible: data});12081209    const events = await submitTransactionAsync(sender, tx);1210    const result = getCreateItemResult(events);12111212    expect(result.success).to.be.true;1213    return result.itemId;1214  });1215}12161217export async function createMultipleItemsWithPropsExpectSuccess(sender: IKeyringPair, collectionId: number, itemsData: any, owner: CrossAccountId | string = sender.address) {1218  await usingApi(async (api) => {1219    const to = normalizeAccountId(owner);1220    const tx = api.tx.unique.createMultipleItems(collectionId, to, itemsData);12211222    const events = await submitTransactionAsync(sender, tx);1223    const result = getCreateItemsResult(events);12241225    for (const res of result) {1226      expect(await api.rpc.unique.tokenProperties(collectionId, res.itemId)).not.to.be.empty;1227    }1228  });1229}12301231export async function createMultipleItemsExWithPropsExpectSuccess(sender: IKeyringPair, collectionId: number, itemsData: any) {1232  await usingApi(async (api) => {1233    const tx = api.tx.unique.createMultipleItemsEx(collectionId, itemsData);12341235    const events = await submitTransactionAsync(sender, tx);1236    const result = getCreateItemsResult(events);12371238    for (const res of result) {1239      expect(await api.rpc.unique.tokenProperties(collectionId, res.itemId)).not.to.be.empty;1240    }1241  });1242}12431244export async function createItemWithPropsExpectSuccess(sender: IKeyringPair, collectionId: number, createMode: string, props:  Array<Property>, owner: CrossAccountId | string = sender.address) {1245  let newItemId = 0;1246  await usingApi(async (api) => {1247    const to = normalizeAccountId(owner);1248    const itemCountBefore = await getLastTokenId(api, collectionId);1249    const itemBalanceBefore = await getBalance(api, collectionId, to, newItemId);12501251    let tx;1252    if (createMode === 'Fungible') {1253      const createData = {fungible: {value: 10}};1254      tx = api.tx.unique.createItem(collectionId, to, createData as any);1255    } else if (createMode === 'ReFungible') {1256      const createData = {refungible: {pieces: 100}};1257      tx = api.tx.unique.createItem(collectionId, to, createData as any);1258    } else {1259      const data = api.createType('UpDataStructsCreateItemData', {NFT: {properties: props}});1260      tx = api.tx.unique.createItem(collectionId, to, data as UpDataStructsCreateItemData);1261    }12621263    const events = await submitTransactionAsync(sender, tx);1264    const result = getCreateItemResult(events);12651266    const itemCountAfter = await getLastTokenId(api, collectionId);1267    const itemBalanceAfter = await getBalance(api, collectionId, to, newItemId);12681269    if (createMode === 'NFT') {1270      expect(await api.rpc.unique.tokenProperties(collectionId, result.itemId)).not.to.be.empty;1271    }12721273    // What to expect1274    // tslint:disable-next-line:no-unused-expression1275    expect(result.success).to.be.true;1276    if (createMode === 'Fungible') {1277      expect(itemBalanceAfter - itemBalanceBefore).to.be.equal(10n);1278    } else {1279      expect(itemCountAfter).to.be.equal(itemCountBefore + 1);1280    }1281    expect(collectionId).to.be.equal(result.collectionId);1282    expect(itemCountAfter.toString()).to.be.equal(result.itemId.toString());1283    expect(to).to.be.deep.equal(result.recipient);1284    newItemId = result.itemId;1285  });1286  return newItemId;1287}12881289export async function createItemWithPropsExpectFailure(sender: IKeyringPair, collectionId: number, createMode: string, props: Array<Property>, owner: CrossAccountId | string = sender.address) {1290  await usingApi(async (api) => {12911292    let tx;1293    if (createMode === 'NFT') {1294      const data = api.createType('UpDataStructsCreateItemData', {NFT: {properties: props}});1295      tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), data);1296    } else {1297      tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), createMode);1298    }129913001301    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1302    if(events.message && events.message.toString().indexOf('1002: Verification Error') > -1) return;1303    const result = getCreateItemResult(events);13041305    expect(result.success).to.be.false;1306  });1307}13081309export async function createItemExpectSuccess(sender: IKeyringPair, collectionId: number, createMode: string, owner: CrossAccountId | string = sender.address) {1310  let newItemId = 0;1311  await usingApi(async (api) => {1312    const to = normalizeAccountId(owner);1313    const itemCountBefore = await getLastTokenId(api, collectionId);1314    const itemBalanceBefore = await getBalance(api, collectionId, to, newItemId);13151316    let tx;1317    if (createMode === 'Fungible') {1318      const createData = {fungible: {value: 10}};1319      tx = api.tx.unique.createItem(collectionId, to, createData as any);1320    } else if (createMode === 'ReFungible') {1321      const createData = {refungible: {pieces: 100}};1322      tx = api.tx.unique.createItem(collectionId, to, createData as any);1323    } else {1324      const createData = {nft: {}};1325      tx = api.tx.unique.createItem(collectionId, to, createData as any);1326    }13271328    const events = await submitTransactionAsync(sender, tx);1329    const result = getCreateItemResult(events);13301331    const itemCountAfter = await getLastTokenId(api, collectionId);1332    const itemBalanceAfter = await getBalance(api, collectionId, to, newItemId);13331334    // What to expect1335    // tslint:disable-next-line:no-unused-expression1336    expect(result.success).to.be.true;1337    if (createMode === 'Fungible') {1338      expect(itemBalanceAfter - itemBalanceBefore).to.be.equal(10n);1339    } else {1340      expect(itemCountAfter).to.be.equal(itemCountBefore + 1);1341    }1342    expect(collectionId).to.be.equal(result.collectionId);1343    expect(itemCountAfter.toString()).to.be.equal(result.itemId.toString());1344    expect(to).to.be.deep.equal(result.recipient);1345    newItemId = result.itemId;1346  });1347  return newItemId;1348}13491350export async function createItemExpectFailure(sender: IKeyringPair, collectionId: number, createMode: string, owner: CrossAccountId | string = sender.address) {1351  await usingApi(async (api) => {1352    const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), createMode);13531354    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1355    const result = getCreateItemResult(events);13561357    expect(result.success).to.be.false;1358  });1359}13601361export async function setPublicAccessModeExpectSuccess(1362  sender: IKeyringPair, collectionId: number,1363  accessMode: 'Normal' | 'AllowList',1364) {1365  await usingApi(async (api) => {13661367    // Run the transaction1368    const tx = api.tx.unique.setCollectionPermissions(collectionId, {access: accessMode});1369    const events = await submitTransactionAsync(sender, tx);1370    const result = getGenericResult(events);13711372    // Get the collection1373    const collection = await queryCollectionExpectSuccess(api, collectionId);13741375    // What to expect1376    // tslint:disable-next-line:no-unused-expression1377    expect(result.success).to.be.true;1378    expect(collection.permissions.access.toHuman()).to.be.equal(accessMode);1379  });1380}13811382export async function setPublicAccessModeExpectFail(1383  sender: IKeyringPair, collectionId: number,1384  accessMode: 'Normal' | 'AllowList',1385) {1386  await usingApi(async (api) => {13871388    // Run the transaction1389    const tx = api.tx.unique.setCollectionPermissions(collectionId, {access: accessMode});1390    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1391    const result = getGenericResult(events);13921393    // What to expect1394    // tslint:disable-next-line:no-unused-expression1395    expect(result.success).to.be.false;1396  });1397}13981399export async function enableAllowListExpectSuccess(sender: IKeyringPair, collectionId: number) {1400  await setPublicAccessModeExpectSuccess(sender, collectionId, 'AllowList');1401}14021403export async function enableAllowListExpectFail(sender: IKeyringPair, collectionId: number) {1404  await setPublicAccessModeExpectFail(sender, collectionId, 'AllowList');1405}14061407export async function disableAllowListExpectSuccess(sender: IKeyringPair, collectionId: number) {1408  await setPublicAccessModeExpectSuccess(sender, collectionId, 'Normal');1409}14101411export async function setMintPermissionExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {1412  await usingApi(async (api) => {14131414    // Run the transaction1415    const tx = api.tx.unique.setCollectionPermissions(collectionId, {mintMode: enabled});1416    const events = await submitTransactionAsync(sender, tx);1417    const result = getGenericResult(events);1418    expect(result.success).to.be.true;14191420    // Get the collection1421    const collection = await queryCollectionExpectSuccess(api, collectionId);14221423    expect(collection.permissions.mintMode.toHuman()).to.be.equal(enabled);1424  });1425}14261427export async function enablePublicMintingExpectSuccess(sender: IKeyringPair, collectionId: number) {1428  await setMintPermissionExpectSuccess(sender, collectionId, true);1429}14301431export async function setMintPermissionExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {1432  await usingApi(async (api) => {1433    // Run the transaction1434    const tx = api.tx.unique.setCollectionPermissions(collectionId, {mintMode: enabled});1435    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1436    const result = getCreateCollectionResult(events);1437    // tslint:disable-next-line:no-unused-expression1438    expect(result.success).to.be.false;1439  });1440}14411442export async function setChainLimitsExpectFailure(sender: IKeyringPair, limits: IChainLimits) {1443  await usingApi(async (api) => {1444    // Run the transaction1445    const tx = api.tx.unique.setChainLimits(limits);1446    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1447    const result = getCreateCollectionResult(events);1448    // tslint:disable-next-line:no-unused-expression1449    expect(result.success).to.be.false;1450  });1451}14521453export async function isAllowlisted(api: ApiPromise, collectionId: number, address: string | CrossAccountId) {1454  return (await api.rpc.unique.allowed(collectionId, normalizeAccountId(address))).toJSON();1455}14561457export async function addToAllowListExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId | CrossAccountId) {1458  await usingApi(async (api) => {1459    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.false;14601461    // Run the transaction1462    const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1463    const events = await submitTransactionAsync(sender, tx);1464    const result = getGenericResult(events);1465    expect(result.success).to.be.true;14661467    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;1468  });1469}14701471export async function addToAllowListAgainExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId) {1472  await usingApi(async (api) => {14731474    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;14751476    // Run the transaction1477    const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1478    const events = await submitTransactionAsync(sender, tx);1479    const result = getGenericResult(events);1480    expect(result.success).to.be.true;14811482    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;1483  });1484}14851486export async function addToAllowListExpectFail(sender: IKeyringPair, collectionId: number, address: string | AccountId) {1487  await usingApi(async (api) => {14881489    // Run the transaction1490    const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1491    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1492    const result = getGenericResult(events);14931494    // What to expect1495    // tslint:disable-next-line:no-unused-expression1496    expect(result.success).to.be.false;1497  });1498}14991500export async function removeFromAllowListExpectSuccess(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1501  await usingApi(async (api) => {1502    // Run the transaction1503    const tx = api.tx.unique.removeFromAllowList(collectionId, normalizeAccountId(address));1504    const events = await submitTransactionAsync(sender, tx);1505    const result = getGenericResult(events);15061507    // What to expect1508    // tslint:disable-next-line:no-unused-expression1509    expect(result.success).to.be.true;1510  });1511}15121513export async function removeFromAllowListExpectFailure(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1514  await usingApi(async (api) => {1515    // Run the transaction1516    const tx = api.tx.unique.removeFromAllowList(collectionId, normalizeAccountId(address));1517    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1518    const result = getGenericResult(events);15191520    // What to expect1521    // tslint:disable-next-line:no-unused-expression1522    expect(result.success).to.be.false;1523  });1524}15251526export const getDetailedCollectionInfo = async (api: ApiPromise, collectionId: number)1527  : Promise<UpDataStructsRpcCollection | null> => {1528  return (await api.rpc.unique.collectionById(collectionId)).unwrapOr(null);1529};15301531export const getCreatedCollectionCount = async (api: ApiPromise): Promise<number> => {1532  // set global object - collectionsCount1533  return (await api.rpc.unique.collectionStats()).created.toNumber();1534};15351536export async function queryCollectionExpectSuccess(api: ApiPromise, collectionId: number): Promise<UpDataStructsRpcCollection> {1537  return (await api.rpc.unique.collectionById(collectionId)).unwrap();1538}15391540export async function waitNewBlocks(blocksCount = 1): Promise<void> {1541  await usingApi(async (api) => {1542    const promise = new Promise<void>(async (resolve) => {1543      const unsubscribe = await api.rpc.chain.subscribeNewHeads(() => {1544        if (blocksCount > 0) {1545          blocksCount--;1546        } else {1547          unsubscribe();1548          resolve();1549        }1550      });1551    });1552    return promise;1553  });1554}
modifiedtests/src/xcmTransfer.test.tsdiffbeforeafterboth
--- a/tests/src/xcmTransfer.test.ts
+++ b/tests/src/xcmTransfer.test.ts
@@ -24,7 +24,6 @@
 import {getGenericResult} from './util/helpers';
 import waitNewBlocks from './substrate/wait-new-blocks';
 import getBalance from './substrate/get-balance';
-import {alicesPublicKey} from './accounts';
 
 chai.use(chaiAsPromised);
 const expect = chai.expect;
@@ -144,7 +143,7 @@
     let balanceBefore: bigint;
     
     await usingApi(async (api) => {
-      [balanceBefore] = await getBalance(api, [alicesPublicKey]);
+      [balanceBefore] = await getBalance(api, [alice.address]);
     });
 
     await usingApi(async (api) => {
@@ -181,7 +180,7 @@
     await usingApi(async (api) => {
       // todo do something about instant sealing, where there might not be any new blocks
       await waitNewBlocks(api, 3);
-      const [balanceAfter] = await getBalance(api, [alicesPublicKey]);
+      const [balanceAfter] = await getBalance(api, [alice.address]);
       expect(balanceAfter > balanceBefore).to.be.true;
     });
   });