git.delta.rocks / unique-network / refs/commits / 66f33e369405

difftreelog

Merge pull request #373 from UniqueNetwork/feature/CORE-302-ss58Format

kozyrevdev2022-06-09parents: #c557492 #5a8eeab.patch.diff
in: master
test(ss58Format): fix format address, remove accounts constants

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 {AnyTuple, IEvent, IKeyringPair} from '@polkadot/types/types';22import {evmToAddress} from '@polkadot/util-crypto';23import BN from 'bn.js';24import chai from 'chai';25import chaiAsPromised from 'chai-as-promised';26import {alicesPublicKey} from '../accounts';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 === 48 || 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;9091type GenericResult = {92  success: boolean,93};9495interface CreateCollectionResult {96  success: boolean;97  collectionId: number;98}99100interface CreateItemResult {101  success: boolean;102  collectionId: number;103  itemId: number;104  recipient?: CrossAccountId;105}106107interface TransferResult {108  collectionId: number;109  itemId: number;110  sender?: CrossAccountId;111  recipient?: CrossAccountId;112  value: bigint;113}114115interface IReFungibleOwner {116  fraction: BN;117  owner: number[];118}119120interface IGetMessage {121  checkMsgUnqMethod: string;122  checkMsgTrsMethod: string;123  checkMsgSysMethod: string;124}125126export interface IFungibleTokenDataType {127  value: number;128}129130export interface IChainLimits {131  collectionNumbersLimit: number;132  accountTokenOwnershipLimit: number;133  collectionsAdminsLimit: number;134  customDataLimit: number;135  nftSponsorTransferTimeout: number;136  fungibleSponsorTransferTimeout: number;137  refungibleSponsorTransferTimeout: number;138  //offchainSchemaLimit: number;139  //constOnChainSchemaLimit: number;140}141142export interface IReFungibleTokenDataType {143  owner: IReFungibleOwner[];144}145146export function uniqueEventMessage(events: EventRecord[]): IGetMessage {147  let checkMsgUnqMethod = '';148  let checkMsgTrsMethod = '';149  let checkMsgSysMethod = '';150  events.forEach(({event: {method, section}}) => {151    if (section === 'common') {152      checkMsgUnqMethod = method;153    } else if (section === 'treasury') {154      checkMsgTrsMethod = method;155    } else if (section === 'system') {156      checkMsgSysMethod = method;157    } else { return null; }158  });159  const result: IGetMessage = {160    checkMsgUnqMethod,161    checkMsgTrsMethod,162    checkMsgSysMethod,163  };164  return result;165}166167export function getEvent<T extends Event>(events: EventRecord[], check: (event: IEvent<AnyTuple>) => event is T): T | undefined {168  const event = events.find(r => check(r.event));169  if (!event) return;170  return event.event as T;171}172173export function getGenericResult(events: EventRecord[]): GenericResult {174  const result: GenericResult = {175    success: false,176  };177  events.forEach(({event: {method}}) => {178    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);179    if (method === 'ExtrinsicSuccess') {180      result.success = true;181    }182  });183  return result;184}185186187188export function getCreateCollectionResult(events: EventRecord[]): CreateCollectionResult {189  let success = false;190  let collectionId = 0;191  events.forEach(({event: {data, method, section}}) => {192    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);193    if (method == 'ExtrinsicSuccess') {194      success = true;195    } else if ((section == 'common') && (method == 'CollectionCreated')) {196      collectionId = parseInt(data[0].toString(), 10);197    }198  });199  const result: CreateCollectionResult = {200    success,201    collectionId,202  };203  return result;204}205206export function getCreateItemsResult(events: EventRecord[]): CreateItemResult[] {207  let success = false;208  let collectionId = 0;209  let itemId = 0;210  let recipient;211212  const results : CreateItemResult[]  = [];213214  events.forEach(({event: {data, method, section}}) => {215    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);216    if (method == 'ExtrinsicSuccess') {217      success = true;218    } else if ((section == 'common') && (method == 'ItemCreated')) {219      collectionId = parseInt(data[0].toString(), 10);220      itemId = parseInt(data[1].toString(), 10);221      recipient = normalizeAccountId(data[2].toJSON() as any);222223      const itemRes: CreateItemResult = {224        success,225        collectionId,226        itemId,227        recipient,228      };229230      results.push(itemRes);231    }232  });233234  return results;235}236237export function getCreateItemResult(events: EventRecord[]): CreateItemResult {238  let success = false;239  let collectionId = 0;240  let itemId = 0;241  let recipient;242  events.forEach(({event: {data, method, section}}) => {243    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);244    if (method == 'ExtrinsicSuccess') {245      success = true;246    } else if ((section == 'common') && (method == 'ItemCreated')) {247      collectionId = parseInt(data[0].toString(), 10);248      itemId = parseInt(data[1].toString(), 10);249      recipient = normalizeAccountId(data[2].toJSON() as any);250    }251  });252  const result: CreateItemResult = {253    success,254    collectionId,255    itemId,256    recipient,257  };258  return result;259}260261export function getTransferResult(api: ApiPromise, events: EventRecord[]): TransferResult {262  for (const {event} of events) {263    if (api.events.common.Transfer.is(event)) {264      const [collection, token, sender, recipient, value] = event.data;265      return {266        collectionId: collection.toNumber(),267        itemId: token.toNumber(),268        sender: normalizeAccountId(sender.toJSON() as any),269        recipient: normalizeAccountId(recipient.toJSON() as any),270        value: value.toBigInt(),271      };272    }273  }274  throw new Error('no transfer event');275}276277interface Nft {278  type: 'NFT';279}280281interface Fungible {282  type: 'Fungible';283  decimalPoints: number;284}285286interface ReFungible {287  type: 'ReFungible';288}289290type CollectionMode = Nft | Fungible | ReFungible;291292export type Property = {293  key: any,294  value: any,295};296297type Permission = {298  mutable: boolean;299  collectionAdmin: boolean;300  tokenOwner: boolean;301}302303type PropertyPermission = {304  key: any;305  permission: Permission;306}307308export type CreateCollectionParams = {309  mode: CollectionMode,310  name: string,311  description: string,312  tokenPrefix: string,313  properties?: Array<Property>,314  propPerm?: Array<PropertyPermission>315};316317const defaultCreateCollectionParams: CreateCollectionParams = {318  description: 'description',319  mode: {type: 'NFT'},320  name: 'name',321  tokenPrefix: 'prefix',322};323324export async function createCollectionExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {325  const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};326327  let collectionId = 0;328  await usingApi(async (api, privateKeyWrapper) => {329    // Get number of collections before the transaction330    const collectionCountBefore = await getCreatedCollectionCount(api);331332    // Run the CreateCollection transaction333    const alicePrivateKey = privateKeyWrapper('//Alice');334335    let modeprm = {};336    if (mode.type === 'NFT') {337      modeprm = {nft: null};338    } else if (mode.type === 'Fungible') {339      modeprm = {fungible: mode.decimalPoints};340    } else if (mode.type === 'ReFungible') {341      modeprm = {refungible: null};342    }343344    const tx = api.tx.unique.createCollectionEx({345      name: strToUTF16(name),346      description: strToUTF16(description),347      tokenPrefix: strToUTF16(tokenPrefix),348      mode: modeprm as any,349    });350    const events = await submitTransactionAsync(alicePrivateKey, tx);351    const result = getCreateCollectionResult(events);352353    // Get number of collections after the transaction354    const collectionCountAfter = await getCreatedCollectionCount(api);355356    // Get the collection357    const collection = await queryCollectionExpectSuccess(api, result.collectionId);358359    // What to expect360    // tslint:disable-next-line:no-unused-expression361    expect(result.success).to.be.true;362    expect(result.collectionId).to.be.equal(collectionCountAfter);363    // tslint:disable-next-line:no-unused-expression364    expect(collection).to.be.not.null;365    expect(collectionCountAfter).to.be.equal(collectionCountBefore + 1, 'Error: NFT collection NOT created.');366    expect(collection.owner.toString()).to.be.equal(toSubstrateAddress(alicesPublicKey));367    expect(utf16ToStr(collection.name.toJSON() as any)).to.be.equal(name);368    expect(utf16ToStr(collection.description.toJSON() as any)).to.be.equal(description);369    expect(hexToStr(collection.tokenPrefix.toJSON())).to.be.equal(tokenPrefix);370371    collectionId = result.collectionId;372  });373374  return collectionId;375}376377export async function createCollectionWithPropsExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {378  const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};379380  let collectionId = 0;381  await usingApi(async (api, privateKeyWrapper) => {382    // Get number of collections before the transaction383    const collectionCountBefore = await getCreatedCollectionCount(api);384385    // Run the CreateCollection transaction386    const alicePrivateKey = privateKeyWrapper('//Alice');387388    let modeprm = {};389    if (mode.type === 'NFT') {390      modeprm = {nft: null};391    } else if (mode.type === 'Fungible') {392      modeprm = {fungible: mode.decimalPoints};393    } else if (mode.type === 'ReFungible') {394      modeprm = {refungible: null};395    }396397    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});398    const events = await submitTransactionAsync(alicePrivateKey, tx);399    const result = getCreateCollectionResult(events);400401    // Get number of collections after the transaction402    const collectionCountAfter = await getCreatedCollectionCount(api);403404    // Get the collection405    const collection = await queryCollectionExpectSuccess(api, result.collectionId);406407    // What to expect408    // tslint:disable-next-line:no-unused-expression409    expect(result.success).to.be.true;410    expect(result.collectionId).to.be.equal(collectionCountAfter);411    // tslint:disable-next-line:no-unused-expression412    expect(collection).to.be.not.null;413    expect(collectionCountAfter).to.be.equal(collectionCountBefore + 1, 'Error: NFT collection NOT created.');414    expect(collection.owner.toString()).to.be.equal(toSubstrateAddress(alicesPublicKey));415    expect(utf16ToStr(collection.name.toJSON() as any)).to.be.equal(name);416    expect(utf16ToStr(collection.description.toJSON() as any)).to.be.equal(description);417    expect(hexToStr(collection.tokenPrefix.toJSON())).to.be.equal(tokenPrefix);418419420    collectionId = result.collectionId;421  });422423  return collectionId;424}425426export async function createCollectionWithPropsExpectFailure(params: Partial<CreateCollectionParams> = {}) {427  const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};428429  await usingApi(async (api, privateKeyWrapper) => {430    // Get number of collections before the transaction431    const collectionCountBefore = await getCreatedCollectionCount(api);432433    // Run the CreateCollection transaction434    const alicePrivateKey = privateKeyWrapper('//Alice');435436    let modeprm = {};437    if (mode.type === 'NFT') {438      modeprm = {nft: null};439    } else if (mode.type === 'Fungible') {440      modeprm = {fungible: mode.decimalPoints};441    } else if (mode.type === 'ReFungible') {442      modeprm = {refungible: null};443    }444445    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});446    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;447448449    // Get number of collections after the transaction450    const collectionCountAfter = await getCreatedCollectionCount(api);451452    expect(collectionCountAfter).to.be.equal(collectionCountBefore, 'Error: Collection with incorrect data created.');453  });454}455456export async function createCollectionExpectFailure(params: Partial<CreateCollectionParams> = {}) {457  const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};458459  let modeprm = {};460  if (mode.type === 'NFT') {461    modeprm = {nft: null};462  } else if (mode.type === 'Fungible') {463    modeprm = {fungible: mode.decimalPoints};464  } else if (mode.type === 'ReFungible') {465    modeprm = {refungible: null};466  }467468  await usingApi(async (api, privateKeyWrapper) => {469    // Get number of collections before the transaction470    const collectionCountBefore = await getCreatedCollectionCount(api);471472    // Run the CreateCollection transaction473    const alicePrivateKey = privateKeyWrapper('//Alice');474    const tx = api.tx.unique.createCollectionEx({name: strToUTF16(name), description: strToUTF16(description), tokenPrefix: strToUTF16(tokenPrefix), mode: modeprm as any});475    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;476477    // Get number of collections after the transaction478    const collectionCountAfter = await getCreatedCollectionCount(api);479480    // What to expect481    expect(collectionCountAfter).to.be.equal(collectionCountBefore, 'Error: Collection with incorrect data created.');482  });483}484485export async function findUnusedAddress(api: ApiPromise, seedAddition = ''): Promise<IKeyringPair> {486  let bal = 0n;487  let unused;488  do {489    const randomSeed = 'seed' + Math.floor(Math.random() * Math.floor(10000)) + seedAddition;490    const keyring = new Keyring({type: 'sr25519'});491    unused = keyring.addFromUri(`//${randomSeed}`);492    bal = (await api.query.system.account(unused.address)).data.free.toBigInt();493  } while (bal !== 0n);494  return unused;495}496497export async function getAllowance(api: ApiPromise, collectionId: number, owner: CrossAccountId | string, approved: CrossAccountId | string, tokenId: number) {498  return (await api.rpc.unique.allowance(collectionId, normalizeAccountId(owner), normalizeAccountId(approved), tokenId)).toBigInt();499}500501export function findUnusedAddresses(api: ApiPromise, amount: number): Promise<IKeyringPair[]> {502  return Promise.all(new Array(amount).fill(null).map(() => findUnusedAddress(api, '_' + Date.now())));503}504505export async function findNotExistingCollection(api: ApiPromise): Promise<number> {506  const totalNumber = await getCreatedCollectionCount(api);507  const newCollection: number = totalNumber + 1;508  return newCollection;509}510511function getDestroyResult(events: EventRecord[]): boolean {512  let success = false;513  events.forEach(({event: {method}}) => {514    if (method == 'ExtrinsicSuccess') {515      success = true;516    }517  });518  return success;519}520521export async function destroyCollectionExpectFailure(collectionId: number, senderSeed = '//Alice') {522  await usingApi(async (api, privateKeyWrapper) => {523    // Run the DestroyCollection transaction524    const alicePrivateKey = privateKeyWrapper(senderSeed);525    const tx = api.tx.unique.destroyCollection(collectionId);526    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;527  });528}529530export async function destroyCollectionExpectSuccess(collectionId: number, senderSeed = '//Alice') {531  await usingApi(async (api, privateKeyWrapper) => {532    // Run the DestroyCollection transaction533    const alicePrivateKey = privateKeyWrapper(senderSeed);534    const tx = api.tx.unique.destroyCollection(collectionId);535    const events = await submitTransactionAsync(alicePrivateKey, tx);536    const result = getDestroyResult(events);537    expect(result).to.be.true;538539    // What to expect540    expect(await getDetailedCollectionInfo(api, collectionId)).to.be.null;541  });542}543544export async function setCollectionLimitsExpectSuccess(sender: IKeyringPair, collectionId: number, limits: any) {545  await usingApi(async (api) => {546    const tx = api.tx.unique.setCollectionLimits(collectionId, limits);547    const events = await submitTransactionAsync(sender, tx);548    const result = getGenericResult(events);549550    expect(result.success).to.be.true;551  });552}553554export const setCollectionPermissionsExpectSuccess = async (sender: IKeyringPair, collectionId: number, permissions: {mintMode?: boolean, access?: 'Normal' | 'AllowList', nesting?: 'Disabled' | 'Owner' | {OwnerRestricted: number[]}}) => {555  await usingApi(async(api) => {556    const tx = api.tx.unique.setCollectionPermissions(collectionId, permissions);557    const events = await submitTransactionAsync(sender, tx);558    const result = getGenericResult(events);559560    expect(result.success).to.be.true;561  });562};563564export async function setCollectionLimitsExpectFailure(sender: IKeyringPair, collectionId: number, limits: any) {565  await usingApi(async (api) => {566    const tx = api.tx.unique.setCollectionLimits(collectionId, limits);567    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;568    const result = getGenericResult(events);569570    expect(result.success).to.be.false;571  });572}573574export async function setCollectionSponsorExpectSuccess(collectionId: number, sponsor: string, sender = '//Alice') {575  await usingApi(async (api, privateKeyWrapper) => {576577    // Run the transaction578    const senderPrivateKey = privateKeyWrapper(sender);579    const tx = api.tx.unique.setCollectionSponsor(collectionId, sponsor);580    const events = await submitTransactionAsync(senderPrivateKey, tx);581    const result = getGenericResult(events);582583    // Get the collection584    const collection = await queryCollectionExpectSuccess(api, collectionId);585586    // What to expect587    expect(result.success).to.be.true;588    expect(collection.sponsorship.toJSON()).to.deep.equal({589      unconfirmed: sponsor,590    });591  });592}593594export async function removeCollectionSponsorExpectSuccess(collectionId: number, sender = '//Alice') {595  await usingApi(async (api, privateKeyWrapper) => {596597    // Run the transaction598    const alicePrivateKey = privateKeyWrapper(sender);599    const tx = api.tx.unique.removeCollectionSponsor(collectionId);600    const events = await submitTransactionAsync(alicePrivateKey, tx);601    const result = getGenericResult(events);602603    // Get the collection604    const collection = await queryCollectionExpectSuccess(api, collectionId);605606    // What to expect607    expect(result.success).to.be.true;608    expect(collection.sponsorship.toJSON()).to.be.deep.equal({disabled: null});609  });610}611612export async function removeCollectionSponsorExpectFailure(collectionId: number, senderSeed = '//Alice') {613  await usingApi(async (api, privateKeyWrapper) => {614615    // Run the transaction616    const alicePrivateKey = privateKeyWrapper(senderSeed);617    const tx = api.tx.unique.removeCollectionSponsor(collectionId);618    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;619  });620}621622export async function setCollectionSponsorExpectFailure(collectionId: number, sponsor: string, senderSeed = '//Alice') {623  await usingApi(async (api, privateKeyWrapper) => {624625    // Run the transaction626    const alicePrivateKey = privateKeyWrapper(senderSeed);627    const tx = api.tx.unique.setCollectionSponsor(collectionId, sponsor);628    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;629  });630}631632export async function confirmSponsorshipExpectSuccess(collectionId: number, senderSeed = '//Alice') {633  await usingApi(async (api, privateKeyWrapper) => {634635    // Run the transaction636    const sender = privateKeyWrapper(senderSeed);637    await confirmSponsorshipByKeyExpectSuccess(collectionId, sender);638  });639}640641export async function confirmSponsorshipByKeyExpectSuccess(collectionId: number, sender: IKeyringPair) {642  await usingApi(async (api, privateKeyWrapper) => {643644    // Run the transaction645    const tx = api.tx.unique.confirmSponsorship(collectionId);646    const events = await submitTransactionAsync(sender, tx);647    const result = getGenericResult(events);648649    // Get the collection650    const collection = await queryCollectionExpectSuccess(api, collectionId);651652    // What to expect653    expect(result.success).to.be.true;654    expect(collection.sponsorship.toJSON()).to.be.deep.equal({655      confirmed: sender.address,656    });657  });658}659660661export async function confirmSponsorshipExpectFailure(collectionId: number, senderSeed = '//Alice') {662  await usingApi(async (api, privateKeyWrapper) => {663664    // Run the transaction665    const sender = privateKeyWrapper(senderSeed);666    const tx = api.tx.unique.confirmSponsorship(collectionId);667    await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;668  });669}670671export async function enableContractSponsoringExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {672  await usingApi(async (api) => {673    const tx = api.tx.unique.enableContractSponsoring(contractAddress, enable);674    const events = await submitTransactionAsync(sender, tx);675    const result = getGenericResult(events);676677    expect(result.success).to.be.true;678  });679}680681export async function enableContractSponsoringExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {682  await usingApi(async (api) => {683    const tx = api.tx.unique.enableContractSponsoring(contractAddress, enable);684    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;685    const result = getGenericResult(events);686687    expect(result.success).to.be.false;688  });689}690691export async function setTransferFlagExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {692693  await usingApi(async (api) => {694695    const tx = api.tx.unique.setTransfersEnabledFlag(collectionId, enabled);696    const events = await submitTransactionAsync(sender, tx);697    const result = getGenericResult(events);698699    expect(result.success).to.be.true;700  });701}702703export async function setTransferFlagExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {704705  await usingApi(async (api) => {706707    const tx = api.tx.unique.setTransfersEnabledFlag(collectionId, enabled);708    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;709    const result = getGenericResult(events);710711    expect(result.success).to.be.false;712  });713}714715export async function setContractSponsoringRateLimitExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {716  await usingApi(async (api) => {717    const tx = api.tx.unique.setContractSponsoringRateLimit(contractAddress, rateLimit);718    const events = await submitTransactionAsync(sender, tx);719    const result = getGenericResult(events);720721    expect(result.success).to.be.true;722  });723}724725export async function setContractSponsoringRateLimitExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {726  await usingApi(async (api) => {727    const tx = api.tx.unique.setContractSponsoringRateLimit(contractAddress, rateLimit);728    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;729    const result = getGenericResult(events);730731    expect(result.success).to.be.false;732  });733}734735export async function getNextSponsored(736  api: ApiPromise,737  collectionId: number,738  account: string | CrossAccountId,739  tokenId: number,740): Promise<number> {741  return Number((await api.rpc.unique.nextSponsored(collectionId, account, tokenId)).unwrapOr(-1));742}743744export async function toggleContractAllowlistExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, value = true) {745  await usingApi(async (api) => {746    const tx = api.tx.unique.toggleContractAllowList(contractAddress, value);747    const events = await submitTransactionAsync(sender, tx);748    const result = getGenericResult(events);749750    expect(result.success).to.be.true;751  });752}753754export async function isAllowlistedInContract(contractAddress: AccountId | string, user: string) {755  let allowlisted = false;756  await usingApi(async (api) => {757    allowlisted = (await api.query.unique.contractAllowList(contractAddress, user)).toJSON() as boolean;758  });759  return allowlisted;760}761762export async function addToContractAllowListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {763  await usingApi(async (api) => {764    const tx = api.tx.unique.addToContractAllowList(contractAddress.toString(), user.toString());765    const events = await submitTransactionAsync(sender, tx);766    const result = getGenericResult(events);767768    expect(result.success).to.be.true;769  });770}771772export async function removeFromContractAllowListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {773  await usingApi(async (api) => {774    const tx = api.tx.unique.removeFromContractAllowList(contractAddress.toString(), user.toString());775    const events = await submitTransactionAsync(sender, tx);776    const result = getGenericResult(events);777778    expect(result.success).to.be.true;779  });780}781782export async function removeFromContractAllowListExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {783  await usingApi(async (api) => {784    const tx = api.tx.unique.removeFromContractAllowList(contractAddress.toString(), user.toString());785    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;786    const result = getGenericResult(events);787788    expect(result.success).to.be.false;789  });790}791792export interface CreateFungibleData {793  readonly Value: bigint;794}795796export interface CreateReFungibleData { }797export interface CreateNftData { }798799export type CreateItemData = {800  NFT: CreateNftData;801} | {802  Fungible: CreateFungibleData;803} | {804  ReFungible: CreateReFungibleData;805};806807export async function burnItemExpectSuccess(sender: IKeyringPair, collectionId: number, tokenId: number, value = 1) {808  await usingApi(async (api) => {809    const balanceBefore = await getBalance(api, collectionId, normalizeAccountId(sender), tokenId);810    // if burning token by admin - use adminButnItemExpectSuccess811    expect(balanceBefore >= BigInt(value)).to.be.true;812813    const tx = api.tx.unique.burnItem(collectionId, tokenId, value);814    const events = await submitTransactionAsync(sender, tx);815    const result = getGenericResult(events);816    expect(result.success).to.be.true;817818    const balanceAfter = await getBalance(api, collectionId, normalizeAccountId(sender), tokenId);819    expect(balanceAfter + BigInt(value)).to.be.equal(balanceBefore);820  });821}822823export async function824approveExpectSuccess(825  collectionId: number,826  tokenId: number, owner: IKeyringPair, approved: CrossAccountId | string, amount: number | bigint = 1,827) {828  await usingApi(async (api: ApiPromise) => {829    const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);830    const events = await submitTransactionAsync(owner, approveUniqueTx);831    const result = getGenericResult(events);832    expect(result.success).to.be.true;833834    expect(await getAllowance(api, collectionId, owner.address, approved, tokenId)).to.be.equal(BigInt(amount));835  });836}837838export async function adminApproveFromExpectSuccess(839  collectionId: number,840  tokenId: number, admin: IKeyringPair, owner: CrossAccountId | string, approved: CrossAccountId | string, amount: number | bigint = 1,841) {842  await usingApi(async (api: ApiPromise) => {843    const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);844    const events = await submitTransactionAsync(admin, approveUniqueTx);845    const result = getGenericResult(events);846    expect(result.success).to.be.true;847848    expect(await getAllowance(api, collectionId, owner, approved, tokenId)).to.be.equal(BigInt(amount));849  });850}851852export async function853transferFromExpectSuccess(854  collectionId: number,855  tokenId: number,856  accountApproved: IKeyringPair,857  accountFrom: IKeyringPair | CrossAccountId,858  accountTo: IKeyringPair | CrossAccountId,859  value: number | bigint = 1,860  type = 'NFT',861) {862  await usingApi(async (api: ApiPromise) => {863    const from = normalizeAccountId(accountFrom);864    const to = normalizeAccountId(accountTo);865    let balanceBefore = 0n;866    if (type === 'Fungible' || type === 'ReFungible') {867      balanceBefore = await getBalance(api, collectionId, to, tokenId);868    }869    const transferFromTx = api.tx.unique.transferFrom(normalizeAccountId(accountFrom), to, collectionId, tokenId, value);870    const events = await submitTransactionAsync(accountApproved, transferFromTx);871    const result = getCreateItemResult(events);872    // tslint:disable-next-line:no-unused-expression873    expect(result.success).to.be.true;874    if (type === 'NFT') {875      expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(to);876    }877    if (type === 'Fungible') {878      const balanceAfter = await getBalance(api, collectionId, to, tokenId);879      if (JSON.stringify(to) !== JSON.stringify(from)) {880        expect(balanceAfter - balanceBefore).to.be.equal(BigInt(value));881      } else {882        expect(balanceAfter).to.be.equal(balanceBefore);883      }884    }885    if (type === 'ReFungible') {886      expect(await getBalance(api, collectionId, to, tokenId)).to.be.equal(balanceBefore + BigInt(value));887    }888  });889}890891export async function892transferFromExpectFail(893  collectionId: number,894  tokenId: number,895  accountApproved: IKeyringPair,896  accountFrom: IKeyringPair,897  accountTo: IKeyringPair,898  value: number | bigint = 1,899) {900  await usingApi(async (api: ApiPromise) => {901    const transferFromTx = api.tx.unique.transferFrom(normalizeAccountId(accountFrom.address), normalizeAccountId(accountTo.address), collectionId, tokenId, value);902    const events = await expect(submitTransactionExpectFailAsync(accountApproved, transferFromTx)).to.be.rejected;903    const result = getCreateCollectionResult(events);904    // tslint:disable-next-line:no-unused-expression905    expect(result.success).to.be.false;906  });907}908909/* eslint no-async-promise-executor: "off" */910export async function getBlockNumber(api: ApiPromise): Promise<number> {911  return new Promise<number>(async (resolve) => {912    const unsubscribe = await api.rpc.chain.subscribeNewHeads((head) => {913      unsubscribe();914      resolve(head.number.toNumber());915    });916  });917}918919export async function addCollectionAdminExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | CrossAccountId) {920  await usingApi(async (api) => {921    const changeAdminTx = api.tx.unique.addCollectionAdmin(collectionId, normalizeAccountId(address));922    const events = await submitTransactionAsync(sender, changeAdminTx);923    const result = getCreateCollectionResult(events);924    expect(result.success).to.be.true;925  });926}927928export async function929getFreeBalance(account: IKeyringPair): Promise<bigint> {930  let balance = 0n;931  await usingApi(async (api) => {932    balance = BigInt((await api.query.system.account(account.address)).data.free.toString());933  });934935  return balance;936}937938export async function transferBalanceTo(api: ApiPromise, source: IKeyringPair, target: string, amount = 1000n * UNIQUE) {939  const tx = api.tx.balances.transfer(target, amount);940  const events = await submitTransactionAsync(source, tx);941  const result = getGenericResult(events);942  expect(result.success).to.be.true;943}944945export async function946scheduleExpectSuccess(947  operationTx: any,948  sender: IKeyringPair,949  blockSchedule: number,950  scheduledId: string,951  period = 1,952  repetitions = 1,953) {954  await usingApi(async (api: ApiPromise) => {955    const blockNumber: number | undefined = await getBlockNumber(api);956    const expectedBlockNumber = blockNumber + blockSchedule;957958    expect(blockNumber).to.be.greaterThan(0);959    const scheduleTx = api.tx.scheduler.scheduleNamed( // schedule960      scheduledId,961      expectedBlockNumber, 962      repetitions > 1 ? [period, repetitions] : null, 963      0, 964      {value: operationTx as any},965    );966967    const events = await submitTransactionAsync(sender, scheduleTx);968    expect(getGenericResult(events).success).to.be.true;969  });970}971972export async function973scheduleExpectFailure(974  operationTx: any,975  sender: IKeyringPair,976  blockSchedule: number,977  scheduledId: string,978  period = 1,979  repetitions = 1,980) {981  await usingApi(async (api: ApiPromise) => {982    const blockNumber: number | undefined = await getBlockNumber(api);983    const expectedBlockNumber = blockNumber + blockSchedule;984985    expect(blockNumber).to.be.greaterThan(0);986    const scheduleTx = api.tx.scheduler.scheduleNamed( // schedule987      scheduledId,988      expectedBlockNumber, 989      repetitions <= 1 ? null : [period, repetitions], 990      0, 991      {value: operationTx as any},992    );993994    //const events = 995    await expect(submitTransactionExpectFailAsync(sender, scheduleTx)).to.be.rejected;996    //expect(getGenericResult(events).success).to.be.false;997  });998}9991000export async function1001scheduleTransferAndWaitExpectSuccess(1002  collectionId: number,1003  tokenId: number,1004  sender: IKeyringPair,1005  recipient: IKeyringPair,1006  value: number | bigint = 1,1007  blockSchedule: number,1008  scheduledId: string,1009) {1010  await usingApi(async (api: ApiPromise) => {1011    await scheduleTransferExpectSuccess(collectionId, tokenId, sender, recipient, value, blockSchedule, scheduledId);10121013    const recipientBalanceBefore = (await api.query.system.account(recipient.address)).data.free.toBigInt();10141015    // sleep for n + 1 blocks1016    await waitNewBlocks(blockSchedule + 1);10171018    const recipientBalanceAfter = (await api.query.system.account(recipient.address)).data.free.toBigInt();10191020    expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(recipient.address));1021    expect(recipientBalanceAfter).to.be.equal(recipientBalanceBefore);1022  });1023}10241025export async function1026scheduleTransferExpectSuccess(1027  collectionId: number,1028  tokenId: number,1029  sender: IKeyringPair,1030  recipient: IKeyringPair,1031  value: number | bigint = 1,1032  blockSchedule: number,1033  scheduledId: string,1034) {1035  await usingApi(async (api: ApiPromise) => {1036    const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient.address), collectionId, tokenId, value);10371038    await scheduleExpectSuccess(transferTx, sender, blockSchedule, scheduledId);10391040    expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(sender.address));1041  });1042}10431044export async function1045scheduleTransferFundsPeriodicExpectSuccess(1046  amount: bigint,1047  sender: IKeyringPair,1048  recipient: IKeyringPair,1049  blockSchedule: number,1050  scheduledId: string,1051  period: number,1052  repetitions: number,1053) {1054  await usingApi(async (api: ApiPromise) => {1055    const transferTx = api.tx.balances.transfer(recipient.address, amount);10561057    const balanceBefore = await getFreeBalance(recipient);1058    1059    await scheduleExpectSuccess(transferTx, sender, blockSchedule, scheduledId, period, repetitions);10601061    expect(await getFreeBalance(recipient)).to.be.equal(balanceBefore);1062  });1063}10641065export async function1066transferExpectSuccess(1067  collectionId: number,1068  tokenId: number,1069  sender: IKeyringPair,1070  recipient: IKeyringPair | CrossAccountId,1071  value: number | bigint = 1,1072  type = 'NFT',1073) {1074  await usingApi(async (api: ApiPromise) => {1075    const from = normalizeAccountId(sender);1076    const to = normalizeAccountId(recipient);10771078    let balanceBefore = 0n;1079    if (type === 'Fungible') {1080      balanceBefore = await getBalance(api, collectionId, to, tokenId);1081    }1082    const transferTx = api.tx.unique.transfer(to, collectionId, tokenId, value);1083    const events = await executeTransaction(api, sender, transferTx);10841085    const result = getTransferResult(api, events);1086    expect(result.collectionId).to.be.equal(collectionId);1087    expect(result.itemId).to.be.equal(tokenId);1088    expect(result.sender).to.be.deep.equal(normalizeAccountId(sender.address));1089    expect(result.recipient).to.be.deep.equal(to);1090    expect(result.value).to.be.equal(BigInt(value));10911092    if (type === 'NFT') {1093      expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(to);1094    }1095    if (type === 'Fungible') {1096      const balanceAfter = await getBalance(api, collectionId, to, tokenId);1097      if (JSON.stringify(to) !== JSON.stringify(from)) {1098        expect(balanceAfter - balanceBefore).to.be.equal(BigInt(value));1099      } else {1100        expect(balanceAfter).to.be.equal(balanceBefore);1101      }1102    }1103    if (type === 'ReFungible') {1104      expect(await getBalance(api, collectionId, to, tokenId) >= value).to.be.true;1105    }1106  });1107}11081109export async function1110transferExpectFailure(1111  collectionId: number,1112  tokenId: number,1113  sender: IKeyringPair,1114  recipient: IKeyringPair | CrossAccountId,1115  value: number | bigint = 1,1116) {1117  await usingApi(async (api: ApiPromise) => {1118    const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient), collectionId, tokenId, value);1119    const events = await expect(submitTransactionExpectFailAsync(sender, transferTx)).to.be.rejected;1120    const result = getGenericResult(events);1121    // if (events && Array.isArray(events)) {1122    //   const result = getCreateCollectionResult(events);1123    // tslint:disable-next-line:no-unused-expression1124    expect(result.success).to.be.false;1125    //}1126  });1127}11281129export async function1130approveExpectFail(1131  collectionId: number,1132  tokenId: number, owner: IKeyringPair, approved: IKeyringPair, amount: number | bigint = 1,1133) {1134  await usingApi(async (api: ApiPromise) => {1135    const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved.address), collectionId, tokenId, amount);1136    const events = await expect(submitTransactionExpectFailAsync(owner, approveUniqueTx)).to.be.rejected;1137    const result = getCreateCollectionResult(events);1138    // tslint:disable-next-line:no-unused-expression1139    expect(result.success).to.be.false;1140  });1141}11421143export async function getBalance(1144  api: ApiPromise,1145  collectionId: number,1146  owner: string | CrossAccountId,1147  token: number,1148): Promise<bigint> {1149  return (await api.rpc.unique.balance(collectionId, normalizeAccountId(owner), token)).toBigInt();1150}1151export async function getTokenOwner(1152  api: ApiPromise,1153  collectionId: number,1154  token: number,1155): Promise<CrossAccountId> {1156  const owner = (await api.rpc.unique.tokenOwner(collectionId, token)).toJSON() as any;1157  if (owner == null) throw new Error('owner == null');1158  return normalizeAccountId(owner);1159}1160export async function getTopmostTokenOwner(1161  api: ApiPromise,1162  collectionId: number,1163  token: number,1164): Promise<CrossAccountId> {1165  const owner = (await api.rpc.unique.topmostTokenOwner(collectionId, token)).toJSON() as any;1166  if (owner == null) throw new Error('owner == null');1167  return normalizeAccountId(owner);1168}1169export async function getTokenChildren(1170  api: ApiPromise,1171  collectionId: number,1172  tokenId: number,1173): Promise<UpDataStructsTokenChild[]> {1174  return (await api.rpc.unique.tokenChildren(collectionId, tokenId)).toJSON() as any;1175}1176export async function isTokenExists(1177  api: ApiPromise,1178  collectionId: number,1179  token: number,1180): Promise<boolean> {1181  return (await api.rpc.unique.tokenExists(collectionId, token)).toJSON();1182}1183export async function getLastTokenId(1184  api: ApiPromise,1185  collectionId: number,1186): Promise<number> {1187  return (await api.rpc.unique.lastTokenId(collectionId)).toJSON();1188}1189export async function getAdminList(1190  api: ApiPromise,1191  collectionId: number,1192): Promise<string[]> {1193  return (await api.rpc.unique.adminlist(collectionId)).toHuman() as any;1194}1195export async function getTokenProperties(1196  api: ApiPromise,1197  collectionId: number,1198  tokenId: number,1199  propertyKeys: string[],1200): Promise<UpDataStructsProperty[]> {1201  return (await api.rpc.unique.tokenProperties(collectionId, tokenId, propertyKeys)).toHuman() as any;1202}12031204export async function createFungibleItemExpectSuccess(1205  sender: IKeyringPair,1206  collectionId: number,1207  data: CreateFungibleData,1208  owner: CrossAccountId | string = sender.address,1209) {1210  return await usingApi(async (api) => {1211    const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), {Fungible: data});12121213    const events = await submitTransactionAsync(sender, tx);1214    const result = getCreateItemResult(events);12151216    expect(result.success).to.be.true;1217    return result.itemId;1218  });1219}12201221export async function createMultipleItemsWithPropsExpectSuccess(sender: IKeyringPair, collectionId: number, itemsData: any, owner: CrossAccountId | string = sender.address) {1222  await usingApi(async (api) => {1223    const to = normalizeAccountId(owner);1224    const tx = api.tx.unique.createMultipleItems(collectionId, to, itemsData);12251226    const events = await submitTransactionAsync(sender, tx);1227    const result = getCreateItemsResult(events);12281229    for (const res of result) {1230      expect(await api.rpc.unique.tokenProperties(collectionId, res.itemId)).not.to.be.empty;1231    }1232  });1233}12341235export async function createMultipleItemsExWithPropsExpectSuccess(sender: IKeyringPair, collectionId: number, itemsData: any) {1236  await usingApi(async (api) => {1237    const tx = api.tx.unique.createMultipleItemsEx(collectionId, itemsData);12381239    const events = await submitTransactionAsync(sender, tx);1240    const result = getCreateItemsResult(events);12411242    for (const res of result) {1243      expect(await api.rpc.unique.tokenProperties(collectionId, res.itemId)).not.to.be.empty;1244    }1245  });1246}12471248export async function createItemWithPropsExpectSuccess(sender: IKeyringPair, collectionId: number, createMode: string, props:  Array<Property>, owner: CrossAccountId | string = sender.address) {1249  let newItemId = 0;1250  await usingApi(async (api) => {1251    const to = normalizeAccountId(owner);1252    const itemCountBefore = await getLastTokenId(api, collectionId);1253    const itemBalanceBefore = await getBalance(api, collectionId, to, newItemId);12541255    let tx;1256    if (createMode === 'Fungible') {1257      const createData = {fungible: {value: 10}};1258      tx = api.tx.unique.createItem(collectionId, to, createData as any);1259    } else if (createMode === 'ReFungible') {1260      const createData = {refungible: {pieces: 100}};1261      tx = api.tx.unique.createItem(collectionId, to, createData as any);1262    } else {1263      const data = api.createType('UpDataStructsCreateItemData', {NFT: {properties: props}});1264      tx = api.tx.unique.createItem(collectionId, to, data as UpDataStructsCreateItemData);1265    }12661267    const events = await submitTransactionAsync(sender, tx);1268    const result = getCreateItemResult(events);12691270    const itemCountAfter = await getLastTokenId(api, collectionId);1271    const itemBalanceAfter = await getBalance(api, collectionId, to, newItemId);12721273    if (createMode === 'NFT') {1274      expect(await api.rpc.unique.tokenProperties(collectionId, result.itemId)).not.to.be.empty;1275    }12761277    // What to expect1278    // tslint:disable-next-line:no-unused-expression1279    expect(result.success).to.be.true;1280    if (createMode === 'Fungible') {1281      expect(itemBalanceAfter - itemBalanceBefore).to.be.equal(10n);1282    } else {1283      expect(itemCountAfter).to.be.equal(itemCountBefore + 1);1284    }1285    expect(collectionId).to.be.equal(result.collectionId);1286    expect(itemCountAfter.toString()).to.be.equal(result.itemId.toString());1287    expect(to).to.be.deep.equal(result.recipient);1288    newItemId = result.itemId;1289  });1290  return newItemId;1291}12921293export async function createItemWithPropsExpectFailure(sender: IKeyringPair, collectionId: number, createMode: string, props: Array<Property>, owner: CrossAccountId | string = sender.address) {1294  await usingApi(async (api) => {12951296    let tx;1297    if (createMode === 'NFT') {1298      const data = api.createType('UpDataStructsCreateItemData', {NFT: {properties: props}});1299      tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), data);1300    } else {1301      tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), createMode);1302    }130313041305    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1306    if(events.message && events.message.toString().indexOf('1002: Verification Error') > -1) return;1307    const result = getCreateItemResult(events);13081309    expect(result.success).to.be.false;1310  });1311}13121313export async function createItemExpectSuccess(sender: IKeyringPair, collectionId: number, createMode: string, owner: CrossAccountId | string = sender.address) {1314  let newItemId = 0;1315  await usingApi(async (api) => {1316    const to = normalizeAccountId(owner);1317    const itemCountBefore = await getLastTokenId(api, collectionId);1318    const itemBalanceBefore = await getBalance(api, collectionId, to, newItemId);13191320    let tx;1321    if (createMode === 'Fungible') {1322      const createData = {fungible: {value: 10}};1323      tx = api.tx.unique.createItem(collectionId, to, createData as any);1324    } else if (createMode === 'ReFungible') {1325      const createData = {refungible: {pieces: 100}};1326      tx = api.tx.unique.createItem(collectionId, to, createData as any);1327    } else {1328      const createData = {nft: {}};1329      tx = api.tx.unique.createItem(collectionId, to, createData as any);1330    }13311332    const events = await submitTransactionAsync(sender, tx);1333    const result = getCreateItemResult(events);13341335    const itemCountAfter = await getLastTokenId(api, collectionId);1336    const itemBalanceAfter = await getBalance(api, collectionId, to, newItemId);13371338    // What to expect1339    // tslint:disable-next-line:no-unused-expression1340    expect(result.success).to.be.true;1341    if (createMode === 'Fungible') {1342      expect(itemBalanceAfter - itemBalanceBefore).to.be.equal(10n);1343    } else {1344      expect(itemCountAfter).to.be.equal(itemCountBefore + 1);1345    }1346    expect(collectionId).to.be.equal(result.collectionId);1347    expect(itemCountAfter.toString()).to.be.equal(result.itemId.toString());1348    expect(to).to.be.deep.equal(result.recipient);1349    newItemId = result.itemId;1350  });1351  return newItemId;1352}13531354export async function createItemExpectFailure(sender: IKeyringPair, collectionId: number, createMode: string, owner: CrossAccountId | string = sender.address) {1355  await usingApi(async (api) => {1356    const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), createMode);13571358    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1359    const result = getCreateItemResult(events);13601361    expect(result.success).to.be.false;1362  });1363}13641365export async function setPublicAccessModeExpectSuccess(1366  sender: IKeyringPair, collectionId: number,1367  accessMode: 'Normal' | 'AllowList',1368) {1369  await usingApi(async (api) => {13701371    // Run the transaction1372    const tx = api.tx.unique.setCollectionPermissions(collectionId, {access: accessMode});1373    const events = await submitTransactionAsync(sender, tx);1374    const result = getGenericResult(events);13751376    // Get the collection1377    const collection = await queryCollectionExpectSuccess(api, collectionId);13781379    // What to expect1380    // tslint:disable-next-line:no-unused-expression1381    expect(result.success).to.be.true;1382    expect(collection.permissions.access.toHuman()).to.be.equal(accessMode);1383  });1384}13851386export async function setPublicAccessModeExpectFail(1387  sender: IKeyringPair, collectionId: number,1388  accessMode: 'Normal' | 'AllowList',1389) {1390  await usingApi(async (api) => {13911392    // Run the transaction1393    const tx = api.tx.unique.setCollectionPermissions(collectionId, {access: accessMode});1394    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1395    const result = getGenericResult(events);13961397    // What to expect1398    // tslint:disable-next-line:no-unused-expression1399    expect(result.success).to.be.false;1400  });1401}14021403export async function enableAllowListExpectSuccess(sender: IKeyringPair, collectionId: number) {1404  await setPublicAccessModeExpectSuccess(sender, collectionId, 'AllowList');1405}14061407export async function enableAllowListExpectFail(sender: IKeyringPair, collectionId: number) {1408  await setPublicAccessModeExpectFail(sender, collectionId, 'AllowList');1409}14101411export async function disableAllowListExpectSuccess(sender: IKeyringPair, collectionId: number) {1412  await setPublicAccessModeExpectSuccess(sender, collectionId, 'Normal');1413}14141415export async function setMintPermissionExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {1416  await usingApi(async (api) => {14171418    // Run the transaction1419    const tx = api.tx.unique.setCollectionPermissions(collectionId, {mintMode: enabled});1420    const events = await submitTransactionAsync(sender, tx);1421    const result = getGenericResult(events);1422    expect(result.success).to.be.true;14231424    // Get the collection1425    const collection = await queryCollectionExpectSuccess(api, collectionId);14261427    expect(collection.permissions.mintMode.toHuman()).to.be.equal(enabled);1428  });1429}14301431export async function enablePublicMintingExpectSuccess(sender: IKeyringPair, collectionId: number) {1432  await setMintPermissionExpectSuccess(sender, collectionId, true);1433}14341435export async function setMintPermissionExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {1436  await usingApi(async (api) => {1437    // Run the transaction1438    const tx = api.tx.unique.setCollectionPermissions(collectionId, {mintMode: enabled});1439    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1440    const result = getCreateCollectionResult(events);1441    // tslint:disable-next-line:no-unused-expression1442    expect(result.success).to.be.false;1443  });1444}14451446export async function setChainLimitsExpectFailure(sender: IKeyringPair, limits: IChainLimits) {1447  await usingApi(async (api) => {1448    // Run the transaction1449    const tx = api.tx.unique.setChainLimits(limits);1450    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1451    const result = getCreateCollectionResult(events);1452    // tslint:disable-next-line:no-unused-expression1453    expect(result.success).to.be.false;1454  });1455}14561457export async function isAllowlisted(api: ApiPromise, collectionId: number, address: string | CrossAccountId) {1458  return (await api.rpc.unique.allowed(collectionId, normalizeAccountId(address))).toJSON();1459}14601461export async function addToAllowListExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId | CrossAccountId) {1462  await usingApi(async (api) => {1463    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.false;14641465    // Run the transaction1466    const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1467    const events = await submitTransactionAsync(sender, tx);1468    const result = getGenericResult(events);1469    expect(result.success).to.be.true;14701471    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;1472  });1473}14741475export async function addToAllowListAgainExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId) {1476  await usingApi(async (api) => {14771478    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;14791480    // Run the transaction1481    const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1482    const events = await submitTransactionAsync(sender, tx);1483    const result = getGenericResult(events);1484    expect(result.success).to.be.true;14851486    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;1487  });1488}14891490export async function addToAllowListExpectFail(sender: IKeyringPair, collectionId: number, address: string | AccountId) {1491  await usingApi(async (api) => {14921493    // Run the transaction1494    const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1495    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1496    const result = getGenericResult(events);14971498    // What to expect1499    // tslint:disable-next-line:no-unused-expression1500    expect(result.success).to.be.false;1501  });1502}15031504export async function removeFromAllowListExpectSuccess(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1505  await usingApi(async (api) => {1506    // Run the transaction1507    const tx = api.tx.unique.removeFromAllowList(collectionId, normalizeAccountId(address));1508    const events = await submitTransactionAsync(sender, tx);1509    const result = getGenericResult(events);15101511    // What to expect1512    // tslint:disable-next-line:no-unused-expression1513    expect(result.success).to.be.true;1514  });1515}15161517export async function removeFromAllowListExpectFailure(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1518  await usingApi(async (api) => {1519    // Run the transaction1520    const tx = api.tx.unique.removeFromAllowList(collectionId, normalizeAccountId(address));1521    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1522    const result = getGenericResult(events);15231524    // What to expect1525    // tslint:disable-next-line:no-unused-expression1526    expect(result.success).to.be.false;1527  });1528}15291530export const getDetailedCollectionInfo = async (api: ApiPromise, collectionId: number)1531  : Promise<UpDataStructsRpcCollection | null> => {1532  return (await api.rpc.unique.collectionById(collectionId)).unwrapOr(null);1533};15341535export const getCreatedCollectionCount = async (api: ApiPromise): Promise<number> => {1536  // set global object - collectionsCount1537  return (await api.rpc.unique.collectionStats()).created.toNumber();1538};15391540export async function queryCollectionExpectSuccess(api: ApiPromise, collectionId: number): Promise<UpDataStructsRpcCollection> {1541  return (await api.rpc.unique.collectionById(collectionId)).unwrap();1542}15431544export async function waitNewBlocks(blocksCount = 1): Promise<void> {1545  await usingApi(async (api) => {1546    const promise = new Promise<void>(async (resolve) => {1547      const unsubscribe = await api.rpc.chain.subscribeNewHeads(() => {1548        if (blocksCount > 0) {1549          blocksCount--;1550        } else {1551          unsubscribe();1552          resolve();1553        }1554      });1555    });1556    return promise;1557  });1558}
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 {AnyTuple, IEvent, IKeyringPair} from '@polkadot/types/types';22import {evmToAddress} from '@polkadot/util-crypto';23import BN from 'bn.js';24import chai from 'chai';25import chaiAsPromised from 'chai-as-promised';26import {default as usingApi, executeTransaction, submitTransactionAsync, submitTransactionExpectFailAsync} from '../substrate/substrate-api';27import {hexToStr, strToUTF16, utf16ToStr} from './util';28import {UpDataStructsRpcCollection, UpDataStructsCreateItemData, UpDataStructsProperty} from '@polkadot/types/lookup';29import {UpDataStructsTokenChild} from '../interfaces';3031chai.use(chaiAsPromised);32const expect = chai.expect;3334export type CrossAccountId = {35  Substrate: string,36} | {37  Ethereum: string,38};3940export function normalizeAccountId(input: string | AccountId | CrossAccountId | IKeyringPair): CrossAccountId {41  if (typeof input === 'string') {42    if (input.length >= 47) {43      return {Substrate: input};44    } else if (input.length === 42 && input.startsWith('0x')) {45      return {Ethereum: input.toLowerCase()};46    } else if (input.length === 40 && !input.startsWith('0x')) {47      return {Ethereum: '0x' + input.toLowerCase()};48    } else {49      throw new Error(`Unknown address format: "${input}"`);50    }51  }52  if ('address' in input) {53    return {Substrate: input.address};54  }55  if ('Ethereum' in input) {56    return {57      Ethereum: input.Ethereum.toLowerCase(),58    };59  } else if ('ethereum' in input) {60    return {61      Ethereum: (input as any).ethereum.toLowerCase(),62    };63  } else if ('Substrate' in input) {64    return input;65  } else if ('substrate' in input) {66    return {67      Substrate: (input as any).substrate,68    };69  }7071  // AccountId72  return {Substrate: input.toString()};73}74export function toSubstrateAddress(input: string | CrossAccountId | IKeyringPair): string {75  input = normalizeAccountId(input);76  if ('Substrate' in input) {77    return input.Substrate;78  } else {79    return evmToAddress(input.Ethereum);80  }81}8283export const U128_MAX = (1n << 128n) - 1n;8485const MICROUNIQUE = 1_000_000_000_000n;86const MILLIUNIQUE = 1_000n * MICROUNIQUE;87const CENTIUNIQUE = 10n * MILLIUNIQUE;88export const UNIQUE = 100n * CENTIUNIQUE;8990type GenericResult = {91  success: boolean,92};9394interface CreateCollectionResult {95  success: boolean;96  collectionId: number;97}9899interface CreateItemResult {100  success: boolean;101  collectionId: number;102  itemId: number;103  recipient?: CrossAccountId;104}105106interface TransferResult {107  collectionId: number;108  itemId: number;109  sender?: CrossAccountId;110  recipient?: CrossAccountId;111  value: bigint;112}113114interface IReFungibleOwner {115  fraction: BN;116  owner: number[];117}118119interface IGetMessage {120  checkMsgUnqMethod: string;121  checkMsgTrsMethod: string;122  checkMsgSysMethod: string;123}124125export interface IFungibleTokenDataType {126  value: number;127}128129export interface IChainLimits {130  collectionNumbersLimit: number;131  accountTokenOwnershipLimit: number;132  collectionsAdminsLimit: number;133  customDataLimit: number;134  nftSponsorTransferTimeout: number;135  fungibleSponsorTransferTimeout: number;136  refungibleSponsorTransferTimeout: number;137  //offchainSchemaLimit: number;138  //constOnChainSchemaLimit: number;139}140141export interface IReFungibleTokenDataType {142  owner: IReFungibleOwner[];143}144145export function uniqueEventMessage(events: EventRecord[]): IGetMessage {146  let checkMsgUnqMethod = '';147  let checkMsgTrsMethod = '';148  let checkMsgSysMethod = '';149  events.forEach(({event: {method, section}}) => {150    if (section === 'common') {151      checkMsgUnqMethod = method;152    } else if (section === 'treasury') {153      checkMsgTrsMethod = method;154    } else if (section === 'system') {155      checkMsgSysMethod = method;156    } else { return null; }157  });158  const result: IGetMessage = {159    checkMsgUnqMethod,160    checkMsgTrsMethod,161    checkMsgSysMethod,162  };163  return result;164}165166export function getEvent<T extends Event>(events: EventRecord[], check: (event: IEvent<AnyTuple>) => event is T): T | undefined {167  const event = events.find(r => check(r.event));168  if (!event) return;169  return event.event as T;170}171172export function getGenericResult(events: EventRecord[]): GenericResult {173  const result: GenericResult = {174    success: false,175  };176  events.forEach(({event: {method}}) => {177    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);178    if (method === 'ExtrinsicSuccess') {179      result.success = true;180    }181  });182  return result;183}184185186187export function getCreateCollectionResult(events: EventRecord[]): CreateCollectionResult {188  let success = false;189  let collectionId = 0;190  events.forEach(({event: {data, method, section}}) => {191    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);192    if (method == 'ExtrinsicSuccess') {193      success = true;194    } else if ((section == 'common') && (method == 'CollectionCreated')) {195      collectionId = parseInt(data[0].toString(), 10);196    }197  });198  const result: CreateCollectionResult = {199    success,200    collectionId,201  };202  return result;203}204205export function getCreateItemsResult(events: EventRecord[]): CreateItemResult[] {206  let success = false;207  let collectionId = 0;208  let itemId = 0;209  let recipient;210211  const results : CreateItemResult[]  = [];212213  events.forEach(({event: {data, method, section}}) => {214    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);215    if (method == 'ExtrinsicSuccess') {216      success = true;217    } else if ((section == 'common') && (method == 'ItemCreated')) {218      collectionId = parseInt(data[0].toString(), 10);219      itemId = parseInt(data[1].toString(), 10);220      recipient = normalizeAccountId(data[2].toJSON() as any);221222      const itemRes: CreateItemResult = {223        success,224        collectionId,225        itemId,226        recipient,227      };228229      results.push(itemRes);230    }231  });232233  return results;234}235236export function getCreateItemResult(events: EventRecord[]): CreateItemResult {237  let success = false;238  let collectionId = 0;239  let itemId = 0;240  let recipient;241  events.forEach(({event: {data, method, section}}) => {242    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);243    if (method == 'ExtrinsicSuccess') {244      success = true;245    } else if ((section == 'common') && (method == 'ItemCreated')) {246      collectionId = parseInt(data[0].toString(), 10);247      itemId = parseInt(data[1].toString(), 10);248      recipient = normalizeAccountId(data[2].toJSON() as any);249    }250  });251  const result: CreateItemResult = {252    success,253    collectionId,254    itemId,255    recipient,256  };257  return result;258}259260export function getTransferResult(api: ApiPromise, events: EventRecord[]): TransferResult {261  for (const {event} of events) {262    if (api.events.common.Transfer.is(event)) {263      const [collection, token, sender, recipient, value] = event.data;264      return {265        collectionId: collection.toNumber(),266        itemId: token.toNumber(),267        sender: normalizeAccountId(sender.toJSON() as any),268        recipient: normalizeAccountId(recipient.toJSON() as any),269        value: value.toBigInt(),270      };271    }272  }273  throw new Error('no transfer event');274}275276interface Nft {277  type: 'NFT';278}279280interface Fungible {281  type: 'Fungible';282  decimalPoints: number;283}284285interface ReFungible {286  type: 'ReFungible';287}288289type CollectionMode = Nft | Fungible | ReFungible;290291export type Property = {292  key: any,293  value: any,294};295296type Permission = {297  mutable: boolean;298  collectionAdmin: boolean;299  tokenOwner: boolean;300}301302type PropertyPermission = {303  key: any;304  permission: Permission;305}306307export type CreateCollectionParams = {308  mode: CollectionMode,309  name: string,310  description: string,311  tokenPrefix: string,312  properties?: Array<Property>,313  propPerm?: Array<PropertyPermission>314};315316const defaultCreateCollectionParams: CreateCollectionParams = {317  description: 'description',318  mode: {type: 'NFT'},319  name: 'name',320  tokenPrefix: 'prefix',321};322323export async function createCollectionExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {324  const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};325326  let collectionId = 0;327  await usingApi(async (api, privateKeyWrapper) => {328    // Get number of collections before the transaction329    const collectionCountBefore = await getCreatedCollectionCount(api);330331    // Run the CreateCollection transaction332    const alicePrivateKey = privateKeyWrapper('//Alice');333334    let modeprm = {};335    if (mode.type === 'NFT') {336      modeprm = {nft: null};337    } else if (mode.type === 'Fungible') {338      modeprm = {fungible: mode.decimalPoints};339    } else if (mode.type === 'ReFungible') {340      modeprm = {refungible: null};341    }342343    const tx = api.tx.unique.createCollectionEx({344      name: strToUTF16(name),345      description: strToUTF16(description),346      tokenPrefix: strToUTF16(tokenPrefix),347      mode: modeprm as any,348    });349    const events = await submitTransactionAsync(alicePrivateKey, tx);350    const result = getCreateCollectionResult(events);351352    // Get number of collections after the transaction353    const collectionCountAfter = await getCreatedCollectionCount(api);354355    // Get the collection356    const collection = await queryCollectionExpectSuccess(api, result.collectionId);357358    // What to expect359    // tslint:disable-next-line:no-unused-expression360    expect(result.success).to.be.true;361    expect(result.collectionId).to.be.equal(collectionCountAfter);362    // tslint:disable-next-line:no-unused-expression363    expect(collection).to.be.not.null;364    expect(collectionCountAfter).to.be.equal(collectionCountBefore + 1, 'Error: NFT collection NOT created.');365    expect(collection.owner.toString()).to.be.equal(toSubstrateAddress(alicePrivateKey));366    expect(utf16ToStr(collection.name.toJSON() as any)).to.be.equal(name);367    expect(utf16ToStr(collection.description.toJSON() as any)).to.be.equal(description);368    expect(hexToStr(collection.tokenPrefix.toJSON())).to.be.equal(tokenPrefix);369370    collectionId = result.collectionId;371  });372373  return collectionId;374}375376export async function createCollectionWithPropsExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {377  const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};378379  let collectionId = 0;380  await usingApi(async (api, privateKeyWrapper) => {381    // Get number of collections before the transaction382    const collectionCountBefore = await getCreatedCollectionCount(api);383384    // Run the CreateCollection transaction385    const alicePrivateKey = privateKeyWrapper('//Alice');386387    let modeprm = {};388    if (mode.type === 'NFT') {389      modeprm = {nft: null};390    } else if (mode.type === 'Fungible') {391      modeprm = {fungible: mode.decimalPoints};392    } else if (mode.type === 'ReFungible') {393      modeprm = {refungible: null};394    }395396    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});397    const events = await submitTransactionAsync(alicePrivateKey, tx);398    const result = getCreateCollectionResult(events);399400    // Get number of collections after the transaction401    const collectionCountAfter = await getCreatedCollectionCount(api);402403    // Get the collection404    const collection = await queryCollectionExpectSuccess(api, result.collectionId);405406    // What to expect407    // tslint:disable-next-line:no-unused-expression408    expect(result.success).to.be.true;409    expect(result.collectionId).to.be.equal(collectionCountAfter);410    // tslint:disable-next-line:no-unused-expression411    expect(collection).to.be.not.null;412    expect(collectionCountAfter).to.be.equal(collectionCountBefore + 1, 'Error: NFT collection NOT created.');413    expect(collection.owner.toString()).to.be.equal(toSubstrateAddress(alicePrivateKey));414    expect(utf16ToStr(collection.name.toJSON() as any)).to.be.equal(name);415    expect(utf16ToStr(collection.description.toJSON() as any)).to.be.equal(description);416    expect(hexToStr(collection.tokenPrefix.toJSON())).to.be.equal(tokenPrefix);417418419    collectionId = result.collectionId;420  });421422  return collectionId;423}424425export async function createCollectionWithPropsExpectFailure(params: Partial<CreateCollectionParams> = {}) {426  const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};427428  await usingApi(async (api, privateKeyWrapper) => {429    // Get number of collections before the transaction430    const collectionCountBefore = await getCreatedCollectionCount(api);431432    // Run the CreateCollection transaction433    const alicePrivateKey = privateKeyWrapper('//Alice');434435    let modeprm = {};436    if (mode.type === 'NFT') {437      modeprm = {nft: null};438    } else if (mode.type === 'Fungible') {439      modeprm = {fungible: mode.decimalPoints};440    } else if (mode.type === 'ReFungible') {441      modeprm = {refungible: null};442    }443444    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});445    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;446447448    // Get number of collections after the transaction449    const collectionCountAfter = await getCreatedCollectionCount(api);450451    expect(collectionCountAfter).to.be.equal(collectionCountBefore, 'Error: Collection with incorrect data created.');452  });453}454455export async function createCollectionExpectFailure(params: Partial<CreateCollectionParams> = {}) {456  const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};457458  let modeprm = {};459  if (mode.type === 'NFT') {460    modeprm = {nft: null};461  } else if (mode.type === 'Fungible') {462    modeprm = {fungible: mode.decimalPoints};463  } else if (mode.type === 'ReFungible') {464    modeprm = {refungible: null};465  }466467  await usingApi(async (api, privateKeyWrapper) => {468    // Get number of collections before the transaction469    const collectionCountBefore = await getCreatedCollectionCount(api);470471    // Run the CreateCollection transaction472    const alicePrivateKey = privateKeyWrapper('//Alice');473    const tx = api.tx.unique.createCollectionEx({name: strToUTF16(name), description: strToUTF16(description), tokenPrefix: strToUTF16(tokenPrefix), mode: modeprm as any});474    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;475476    // Get number of collections after the transaction477    const collectionCountAfter = await getCreatedCollectionCount(api);478479    // What to expect480    expect(collectionCountAfter).to.be.equal(collectionCountBefore, 'Error: Collection with incorrect data created.');481  });482}483484export async function findUnusedAddress(api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair, seedAddition = ''): Promise<IKeyringPair> {485  let bal = 0n;486  let unused;487  do {488    const randomSeed = 'seed' + Math.floor(Math.random() * Math.floor(10000)) + seedAddition;489    unused = privateKeyWrapper(`//${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, privateKeyWrapper: (account: string) => IKeyringPair, amount: number): Promise<IKeyringPair[]> {500  return Promise.all(new Array(amount).fill(null).map(() => findUnusedAddress(api, privateKeyWrapper, '_' + 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 = getCreateItemResult(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}
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;
     });
   });