git.delta.rocks / unique-network / refs/commits / 5a8eeab77dee

difftreelog

test(ss58Format) more test fixes

h3lpkey2022-06-09parent: #d76cc13.patch.diff
in: master

17 files changed

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/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/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
@@ -73,9 +73,9 @@
   });
 
   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(bob.address, 1n);
       // const events = await submitTransactionAsync(pk, badTransfer);
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 {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, 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    const keyring = new Keyring({type: 'sr25519'});490    unused = keyring.addFromUri(`//${randomSeed}`);491    bal = (await api.query.system.account(unused.address)).data.free.toBigInt();492  } while (bal !== 0n);493  return unused;494}495496export async function getAllowance(api: ApiPromise, collectionId: number, owner: CrossAccountId | string, approved: CrossAccountId | string, tokenId: number) {497  return (await api.rpc.unique.allowance(collectionId, normalizeAccountId(owner), normalizeAccountId(approved), tokenId)).toBigInt();498}499500export function findUnusedAddresses(api: ApiPromise, amount: number): Promise<IKeyringPair[]> {501  return Promise.all(new Array(amount).fill(null).map(() => findUnusedAddress(api, '_' + Date.now())));502}503504export async function findNotExistingCollection(api: ApiPromise): Promise<number> {505  const totalNumber = await getCreatedCollectionCount(api);506  const newCollection: number = totalNumber + 1;507  return newCollection;508}509510function getDestroyResult(events: EventRecord[]): boolean {511  let success = false;512  events.forEach(({event: {method}}) => {513    if (method == 'ExtrinsicSuccess') {514      success = true;515    }516  });517  return success;518}519520export async function destroyCollectionExpectFailure(collectionId: number, senderSeed = '//Alice') {521  await usingApi(async (api, privateKeyWrapper) => {522    // Run the DestroyCollection transaction523    const alicePrivateKey = privateKeyWrapper(senderSeed);524    const tx = api.tx.unique.destroyCollection(collectionId);525    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;526  });527}528529export async function destroyCollectionExpectSuccess(collectionId: number, senderSeed = '//Alice') {530  await usingApi(async (api, privateKeyWrapper) => {531    // Run the DestroyCollection transaction532    const alicePrivateKey = privateKeyWrapper(senderSeed);533    const tx = api.tx.unique.destroyCollection(collectionId);534    const events = await submitTransactionAsync(alicePrivateKey, tx);535    const result = getDestroyResult(events);536    expect(result).to.be.true;537538    // What to expect539    expect(await getDetailedCollectionInfo(api, collectionId)).to.be.null;540  });541}542543export async function setCollectionLimitsExpectSuccess(sender: IKeyringPair, collectionId: number, limits: any) {544  await usingApi(async (api) => {545    const tx = api.tx.unique.setCollectionLimits(collectionId, limits);546    const events = await submitTransactionAsync(sender, tx);547    const result = getGenericResult(events);548549    expect(result.success).to.be.true;550  });551}552553export const setCollectionPermissionsExpectSuccess = async (sender: IKeyringPair, collectionId: number, permissions: {mintMode?: boolean, access?: 'Normal' | 'AllowList', nesting?: 'Disabled' | 'Owner' | {OwnerRestricted: number[]}}) => {554  await usingApi(async(api) => {555    const tx = api.tx.unique.setCollectionPermissions(collectionId, permissions);556    const events = await submitTransactionAsync(sender, tx);557    const result = getGenericResult(events);558559    expect(result.success).to.be.true;560  });561};562563export async function setCollectionLimitsExpectFailure(sender: IKeyringPair, collectionId: number, limits: any) {564  await usingApi(async (api) => {565    const tx = api.tx.unique.setCollectionLimits(collectionId, limits);566    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;567    const result = getGenericResult(events);568569    expect(result.success).to.be.false;570  });571}572573export async function setCollectionSponsorExpectSuccess(collectionId: number, sponsor: string, sender = '//Alice') {574  await usingApi(async (api, privateKeyWrapper) => {575576    // Run the transaction577    const senderPrivateKey = privateKeyWrapper(sender);578    const tx = api.tx.unique.setCollectionSponsor(collectionId, sponsor);579    const events = await submitTransactionAsync(senderPrivateKey, tx);580    const result = getGenericResult(events);581582    // Get the collection583    const collection = await queryCollectionExpectSuccess(api, collectionId);584585    // What to expect586    expect(result.success).to.be.true;587    expect(collection.sponsorship.toJSON()).to.deep.equal({588      unconfirmed: sponsor,589    });590  });591}592593export async function removeCollectionSponsorExpectSuccess(collectionId: number, sender = '//Alice') {594  await usingApi(async (api, privateKeyWrapper) => {595596    // Run the transaction597    const alicePrivateKey = privateKeyWrapper(sender);598    const tx = api.tx.unique.removeCollectionSponsor(collectionId);599    const events = await submitTransactionAsync(alicePrivateKey, tx);600    const result = getGenericResult(events);601602    // Get the collection603    const collection = await queryCollectionExpectSuccess(api, collectionId);604605    // What to expect606    expect(result.success).to.be.true;607    expect(collection.sponsorship.toJSON()).to.be.deep.equal({disabled: null});608  });609}610611export async function removeCollectionSponsorExpectFailure(collectionId: number, senderSeed = '//Alice') {612  await usingApi(async (api, privateKeyWrapper) => {613614    // Run the transaction615    const alicePrivateKey = privateKeyWrapper(senderSeed);616    const tx = api.tx.unique.removeCollectionSponsor(collectionId);617    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;618  });619}620621export async function setCollectionSponsorExpectFailure(collectionId: number, sponsor: string, senderSeed = '//Alice') {622  await usingApi(async (api, privateKeyWrapper) => {623624    // Run the transaction625    const alicePrivateKey = privateKeyWrapper(senderSeed);626    const tx = api.tx.unique.setCollectionSponsor(collectionId, sponsor);627    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;628  });629}630631export async function confirmSponsorshipExpectSuccess(collectionId: number, senderSeed = '//Alice') {632  await usingApi(async (api, privateKeyWrapper) => {633634    // Run the transaction635    const sender = privateKeyWrapper(senderSeed);636    await confirmSponsorshipByKeyExpectSuccess(collectionId, sender);637  });638}639640export async function confirmSponsorshipByKeyExpectSuccess(collectionId: number, sender: IKeyringPair) {641  await usingApi(async (api, privateKeyWrapper) => {642643    // Run the transaction644    const tx = api.tx.unique.confirmSponsorship(collectionId);645    const events = await submitTransactionAsync(sender, tx);646    const result = getGenericResult(events);647648    // Get the collection649    const collection = await queryCollectionExpectSuccess(api, collectionId);650651    // What to expect652    expect(result.success).to.be.true;653    expect(collection.sponsorship.toJSON()).to.be.deep.equal({654      confirmed: sender.address,655    });656  });657}658659660export async function confirmSponsorshipExpectFailure(collectionId: number, senderSeed = '//Alice') {661  await usingApi(async (api, privateKeyWrapper) => {662663    // Run the transaction664    const sender = privateKeyWrapper(senderSeed);665    const tx = api.tx.unique.confirmSponsorship(collectionId);666    await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;667  });668}669670export async function enableContractSponsoringExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {671  await usingApi(async (api) => {672    const tx = api.tx.unique.enableContractSponsoring(contractAddress, enable);673    const events = await submitTransactionAsync(sender, tx);674    const result = getGenericResult(events);675676    expect(result.success).to.be.true;677  });678}679680export async function enableContractSponsoringExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {681  await usingApi(async (api) => {682    const tx = api.tx.unique.enableContractSponsoring(contractAddress, enable);683    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;684    const result = getGenericResult(events);685686    expect(result.success).to.be.false;687  });688}689690export async function setTransferFlagExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {691692  await usingApi(async (api) => {693694    const tx = api.tx.unique.setTransfersEnabledFlag(collectionId, enabled);695    const events = await submitTransactionAsync(sender, tx);696    const result = getGenericResult(events);697698    expect(result.success).to.be.true;699  });700}701702export async function setTransferFlagExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {703704  await usingApi(async (api) => {705706    const tx = api.tx.unique.setTransfersEnabledFlag(collectionId, enabled);707    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;708    const result = getGenericResult(events);709710    expect(result.success).to.be.false;711  });712}713714export async function setContractSponsoringRateLimitExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {715  await usingApi(async (api) => {716    const tx = api.tx.unique.setContractSponsoringRateLimit(contractAddress, rateLimit);717    const events = await submitTransactionAsync(sender, tx);718    const result = getGenericResult(events);719720    expect(result.success).to.be.true;721  });722}723724export async function setContractSponsoringRateLimitExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {725  await usingApi(async (api) => {726    const tx = api.tx.unique.setContractSponsoringRateLimit(contractAddress, rateLimit);727    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;728    const result = getGenericResult(events);729730    expect(result.success).to.be.false;731  });732}733734export async function getNextSponsored(735  api: ApiPromise,736  collectionId: number,737  account: string | CrossAccountId,738  tokenId: number,739): Promise<number> {740  return Number((await api.rpc.unique.nextSponsored(collectionId, account, tokenId)).unwrapOr(-1));741}742743export async function toggleContractAllowlistExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, value = true) {744  await usingApi(async (api) => {745    const tx = api.tx.unique.toggleContractAllowList(contractAddress, value);746    const events = await submitTransactionAsync(sender, tx);747    const result = getGenericResult(events);748749    expect(result.success).to.be.true;750  });751}752753export async function isAllowlistedInContract(contractAddress: AccountId | string, user: string) {754  let allowlisted = false;755  await usingApi(async (api) => {756    allowlisted = (await api.query.unique.contractAllowList(contractAddress, user)).toJSON() as boolean;757  });758  return allowlisted;759}760761export async function addToContractAllowListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {762  await usingApi(async (api) => {763    const tx = api.tx.unique.addToContractAllowList(contractAddress.toString(), user.toString());764    const events = await submitTransactionAsync(sender, tx);765    const result = getGenericResult(events);766767    expect(result.success).to.be.true;768  });769}770771export async function removeFromContractAllowListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {772  await usingApi(async (api) => {773    const tx = api.tx.unique.removeFromContractAllowList(contractAddress.toString(), user.toString());774    const events = await submitTransactionAsync(sender, tx);775    const result = getGenericResult(events);776777    expect(result.success).to.be.true;778  });779}780781export async function removeFromContractAllowListExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {782  await usingApi(async (api) => {783    const tx = api.tx.unique.removeFromContractAllowList(contractAddress.toString(), user.toString());784    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;785    const result = getGenericResult(events);786787    expect(result.success).to.be.false;788  });789}790791export interface CreateFungibleData {792  readonly Value: bigint;793}794795export interface CreateReFungibleData { }796export interface CreateNftData { }797798export type CreateItemData = {799  NFT: CreateNftData;800} | {801  Fungible: CreateFungibleData;802} | {803  ReFungible: CreateReFungibleData;804};805806export async function burnItemExpectSuccess(sender: IKeyringPair, collectionId: number, tokenId: number, value = 1) {807  await usingApi(async (api) => {808    const balanceBefore = await getBalance(api, collectionId, normalizeAccountId(sender), tokenId);809    // if burning token by admin - use adminButnItemExpectSuccess810    expect(balanceBefore >= BigInt(value)).to.be.true;811812    const tx = api.tx.unique.burnItem(collectionId, tokenId, value);813    const events = await submitTransactionAsync(sender, tx);814    const result = getGenericResult(events);815    expect(result.success).to.be.true;816817    const balanceAfter = await getBalance(api, collectionId, normalizeAccountId(sender), tokenId);818    expect(balanceAfter + BigInt(value)).to.be.equal(balanceBefore);819  });820}821822export async function823approveExpectSuccess(824  collectionId: number,825  tokenId: number, owner: IKeyringPair, approved: CrossAccountId | string, amount: number | bigint = 1,826) {827  await usingApi(async (api: ApiPromise) => {828    const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);829    const events = await submitTransactionAsync(owner, approveUniqueTx);830    const result = getGenericResult(events);831    expect(result.success).to.be.true;832833    expect(await getAllowance(api, collectionId, owner.address, approved, tokenId)).to.be.equal(BigInt(amount));834  });835}836837export async function adminApproveFromExpectSuccess(838  collectionId: number,839  tokenId: number, admin: IKeyringPair, owner: CrossAccountId | string, approved: CrossAccountId | string, amount: number | bigint = 1,840) {841  await usingApi(async (api: ApiPromise) => {842    const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);843    const events = await submitTransactionAsync(admin, approveUniqueTx);844    const result = getGenericResult(events);845    expect(result.success).to.be.true;846847    expect(await getAllowance(api, collectionId, owner, approved, tokenId)).to.be.equal(BigInt(amount));848  });849}850851export async function852transferFromExpectSuccess(853  collectionId: number,854  tokenId: number,855  accountApproved: IKeyringPair,856  accountFrom: IKeyringPair | CrossAccountId,857  accountTo: IKeyringPair | CrossAccountId,858  value: number | bigint = 1,859  type = 'NFT',860) {861  await usingApi(async (api: ApiPromise) => {862    const from = normalizeAccountId(accountFrom);863    const to = normalizeAccountId(accountTo);864    let balanceBefore = 0n;865    if (type === 'Fungible' || type === 'ReFungible') {866      balanceBefore = await getBalance(api, collectionId, to, tokenId);867    }868    const transferFromTx = api.tx.unique.transferFrom(normalizeAccountId(accountFrom), to, collectionId, tokenId, value);869    const events = await submitTransactionAsync(accountApproved, transferFromTx);870    const result = getCreateItemResult(events);871    // tslint:disable-next-line:no-unused-expression872    expect(result.success).to.be.true;873    if (type === 'NFT') {874      expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(to);875    }876    if (type === 'Fungible') {877      const balanceAfter = await getBalance(api, collectionId, to, tokenId);878      if (JSON.stringify(to) !== JSON.stringify(from)) {879        expect(balanceAfter - balanceBefore).to.be.equal(BigInt(value));880      } else {881        expect(balanceAfter).to.be.equal(balanceBefore);882      }883    }884    if (type === 'ReFungible') {885      expect(await getBalance(api, collectionId, to, tokenId)).to.be.equal(balanceBefore + BigInt(value));886    }887  });888}889890export async function891transferFromExpectFail(892  collectionId: number,893  tokenId: number,894  accountApproved: IKeyringPair,895  accountFrom: IKeyringPair,896  accountTo: IKeyringPair,897  value: number | bigint = 1,898) {899  await usingApi(async (api: ApiPromise) => {900    const transferFromTx = api.tx.unique.transferFrom(normalizeAccountId(accountFrom.address), normalizeAccountId(accountTo.address), collectionId, tokenId, value);901    const events = await expect(submitTransactionExpectFailAsync(accountApproved, transferFromTx)).to.be.rejected;902    const result = getCreateCollectionResult(events);903    // tslint:disable-next-line:no-unused-expression904    expect(result.success).to.be.false;905  });906}907908/* eslint no-async-promise-executor: "off" */909export async function getBlockNumber(api: ApiPromise): Promise<number> {910  return new Promise<number>(async (resolve) => {911    const unsubscribe = await api.rpc.chain.subscribeNewHeads((head) => {912      unsubscribe();913      resolve(head.number.toNumber());914    });915  });916}917918export async function addCollectionAdminExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | CrossAccountId) {919  await usingApi(async (api) => {920    const changeAdminTx = api.tx.unique.addCollectionAdmin(collectionId, normalizeAccountId(address));921    const events = await submitTransactionAsync(sender, changeAdminTx);922    const result = getCreateCollectionResult(events);923    expect(result.success).to.be.true;924  });925}926927export async function928getFreeBalance(account: IKeyringPair): Promise<bigint> {929  let balance = 0n;930  await usingApi(async (api) => {931    balance = BigInt((await api.query.system.account(account.address)).data.free.toString());932  });933934  return balance;935}936937export async function transferBalanceTo(api: ApiPromise, source: IKeyringPair, target: string, amount = 1000n * UNIQUE) {938  const tx = api.tx.balances.transfer(target, amount);939  const events = await submitTransactionAsync(source, tx);940  const result = getGenericResult(events);941  expect(result.success).to.be.true;942}943944export async function945scheduleExpectSuccess(946  operationTx: any,947  sender: IKeyringPair,948  blockSchedule: number,949  scheduledId: string,950  period = 1,951  repetitions = 1,952) {953  await usingApi(async (api: ApiPromise) => {954    const blockNumber: number | undefined = await getBlockNumber(api);955    const expectedBlockNumber = blockNumber + blockSchedule;956957    expect(blockNumber).to.be.greaterThan(0);958    const scheduleTx = api.tx.scheduler.scheduleNamed( // schedule959      scheduledId,960      expectedBlockNumber, 961      repetitions > 1 ? [period, repetitions] : null, 962      0, 963      {value: operationTx as any},964    );965966    const events = await submitTransactionAsync(sender, scheduleTx);967    expect(getGenericResult(events).success).to.be.true;968  });969}970971export async function972scheduleExpectFailure(973  operationTx: any,974  sender: IKeyringPair,975  blockSchedule: number,976  scheduledId: string,977  period = 1,978  repetitions = 1,979) {980  await usingApi(async (api: ApiPromise) => {981    const blockNumber: number | undefined = await getBlockNumber(api);982    const expectedBlockNumber = blockNumber + blockSchedule;983984    expect(blockNumber).to.be.greaterThan(0);985    const scheduleTx = api.tx.scheduler.scheduleNamed( // schedule986      scheduledId,987      expectedBlockNumber, 988      repetitions <= 1 ? null : [period, repetitions], 989      0, 990      {value: operationTx as any},991    );992993    //const events = 994    await expect(submitTransactionExpectFailAsync(sender, scheduleTx)).to.be.rejected;995    //expect(getGenericResult(events).success).to.be.false;996  });997}998999export async function1000scheduleTransferAndWaitExpectSuccess(1001  collectionId: number,1002  tokenId: number,1003  sender: IKeyringPair,1004  recipient: IKeyringPair,1005  value: number | bigint = 1,1006  blockSchedule: number,1007  scheduledId: string,1008) {1009  await usingApi(async (api: ApiPromise) => {1010    await scheduleTransferExpectSuccess(collectionId, tokenId, sender, recipient, value, blockSchedule, scheduledId);10111012    const recipientBalanceBefore = (await api.query.system.account(recipient.address)).data.free.toBigInt();10131014    // sleep for n + 1 blocks1015    await waitNewBlocks(blockSchedule + 1);10161017    const recipientBalanceAfter = (await api.query.system.account(recipient.address)).data.free.toBigInt();10181019    expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(recipient.address));1020    expect(recipientBalanceAfter).to.be.equal(recipientBalanceBefore);1021  });1022}10231024export async function1025scheduleTransferExpectSuccess(1026  collectionId: number,1027  tokenId: number,1028  sender: IKeyringPair,1029  recipient: IKeyringPair,1030  value: number | bigint = 1,1031  blockSchedule: number,1032  scheduledId: string,1033) {1034  await usingApi(async (api: ApiPromise) => {1035    const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient.address), collectionId, tokenId, value);10361037    await scheduleExpectSuccess(transferTx, sender, blockSchedule, scheduledId);10381039    expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(sender.address));1040  });1041}10421043export async function1044scheduleTransferFundsPeriodicExpectSuccess(1045  amount: bigint,1046  sender: IKeyringPair,1047  recipient: IKeyringPair,1048  blockSchedule: number,1049  scheduledId: string,1050  period: number,1051  repetitions: number,1052) {1053  await usingApi(async (api: ApiPromise) => {1054    const transferTx = api.tx.balances.transfer(recipient.address, amount);10551056    const balanceBefore = await getFreeBalance(recipient);1057    1058    await scheduleExpectSuccess(transferTx, sender, blockSchedule, scheduledId, period, repetitions);10591060    expect(await getFreeBalance(recipient)).to.be.equal(balanceBefore);1061  });1062}10631064export async function1065transferExpectSuccess(1066  collectionId: number,1067  tokenId: number,1068  sender: IKeyringPair,1069  recipient: IKeyringPair | CrossAccountId,1070  value: number | bigint = 1,1071  type = 'NFT',1072) {1073  await usingApi(async (api: ApiPromise) => {1074    const from = normalizeAccountId(sender);1075    const to = normalizeAccountId(recipient);10761077    let balanceBefore = 0n;1078    if (type === 'Fungible') {1079      balanceBefore = await getBalance(api, collectionId, to, tokenId);1080    }1081    const transferTx = api.tx.unique.transfer(to, collectionId, tokenId, value);1082    const events = await executeTransaction(api, sender, transferTx);10831084    const result = getTransferResult(api, events);1085    expect(result.collectionId).to.be.equal(collectionId);1086    expect(result.itemId).to.be.equal(tokenId);1087    expect(result.sender).to.be.deep.equal(normalizeAccountId(sender.address));1088    expect(result.recipient).to.be.deep.equal(to);1089    expect(result.value).to.be.equal(BigInt(value));10901091    if (type === 'NFT') {1092      expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(to);1093    }1094    if (type === 'Fungible') {1095      const balanceAfter = await getBalance(api, collectionId, to, tokenId);1096      if (JSON.stringify(to) !== JSON.stringify(from)) {1097        expect(balanceAfter - balanceBefore).to.be.equal(BigInt(value));1098      } else {1099        expect(balanceAfter).to.be.equal(balanceBefore);1100      }1101    }1102    if (type === 'ReFungible') {1103      expect(await getBalance(api, collectionId, to, tokenId) >= value).to.be.true;1104    }1105  });1106}11071108export async function1109transferExpectFailure(1110  collectionId: number,1111  tokenId: number,1112  sender: IKeyringPair,1113  recipient: IKeyringPair | CrossAccountId,1114  value: number | bigint = 1,1115) {1116  await usingApi(async (api: ApiPromise) => {1117    const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient), collectionId, tokenId, value);1118    const events = await expect(submitTransactionExpectFailAsync(sender, transferTx)).to.be.rejected;1119    const result = getGenericResult(events);1120    // if (events && Array.isArray(events)) {1121    //   const result = getCreateCollectionResult(events);1122    // tslint:disable-next-line:no-unused-expression1123    expect(result.success).to.be.false;1124    //}1125  });1126}11271128export async function1129approveExpectFail(1130  collectionId: number,1131  tokenId: number, owner: IKeyringPair, approved: IKeyringPair, amount: number | bigint = 1,1132) {1133  await usingApi(async (api: ApiPromise) => {1134    const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved.address), collectionId, tokenId, amount);1135    const events = await expect(submitTransactionExpectFailAsync(owner, approveUniqueTx)).to.be.rejected;1136    const result = getCreateCollectionResult(events);1137    // tslint:disable-next-line:no-unused-expression1138    expect(result.success).to.be.false;1139  });1140}11411142export async function getBalance(1143  api: ApiPromise,1144  collectionId: number,1145  owner: string | CrossAccountId,1146  token: number,1147): Promise<bigint> {1148  return (await api.rpc.unique.balance(collectionId, normalizeAccountId(owner), token)).toBigInt();1149}1150export async function getTokenOwner(1151  api: ApiPromise,1152  collectionId: number,1153  token: number,1154): Promise<CrossAccountId> {1155  const owner = (await api.rpc.unique.tokenOwner(collectionId, token)).toJSON() as any;1156  if (owner == null) throw new Error('owner == null');1157  return normalizeAccountId(owner);1158}1159export async function getTopmostTokenOwner(1160  api: ApiPromise,1161  collectionId: number,1162  token: number,1163): Promise<CrossAccountId> {1164  const owner = (await api.rpc.unique.topmostTokenOwner(collectionId, token)).toJSON() as any;1165  if (owner == null) throw new Error('owner == null');1166  return normalizeAccountId(owner);1167}1168export async function getTokenChildren(1169  api: ApiPromise,1170  collectionId: number,1171  tokenId: number,1172): Promise<UpDataStructsTokenChild[]> {1173  return (await api.rpc.unique.tokenChildren(collectionId, tokenId)).toJSON() as any;1174}1175export async function isTokenExists(1176  api: ApiPromise,1177  collectionId: number,1178  token: number,1179): Promise<boolean> {1180  return (await api.rpc.unique.tokenExists(collectionId, token)).toJSON();1181}1182export async function getLastTokenId(1183  api: ApiPromise,1184  collectionId: number,1185): Promise<number> {1186  return (await api.rpc.unique.lastTokenId(collectionId)).toJSON();1187}1188export async function getAdminList(1189  api: ApiPromise,1190  collectionId: number,1191): Promise<string[]> {1192  return (await api.rpc.unique.adminlist(collectionId)).toHuman() as any;1193}1194export async function getTokenProperties(1195  api: ApiPromise,1196  collectionId: number,1197  tokenId: number,1198  propertyKeys: string[],1199): Promise<UpDataStructsProperty[]> {1200  return (await api.rpc.unique.tokenProperties(collectionId, tokenId, propertyKeys)).toHuman() as any;1201}12021203export async function createFungibleItemExpectSuccess(1204  sender: IKeyringPair,1205  collectionId: number,1206  data: CreateFungibleData,1207  owner: CrossAccountId | string = sender.address,1208) {1209  return await usingApi(async (api) => {1210    const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), {Fungible: data});12111212    const events = await submitTransactionAsync(sender, tx);1213    const result = getCreateItemResult(events);12141215    expect(result.success).to.be.true;1216    return result.itemId;1217  });1218}12191220export async function createMultipleItemsWithPropsExpectSuccess(sender: IKeyringPair, collectionId: number, itemsData: any, owner: CrossAccountId | string = sender.address) {1221  await usingApi(async (api) => {1222    const to = normalizeAccountId(owner);1223    const tx = api.tx.unique.createMultipleItems(collectionId, to, itemsData);12241225    const events = await submitTransactionAsync(sender, tx);1226    const result = getCreateItemsResult(events);12271228    for (const res of result) {1229      expect(await api.rpc.unique.tokenProperties(collectionId, res.itemId)).not.to.be.empty;1230    }1231  });1232}12331234export async function createMultipleItemsExWithPropsExpectSuccess(sender: IKeyringPair, collectionId: number, itemsData: any) {1235  await usingApi(async (api) => {1236    const tx = api.tx.unique.createMultipleItemsEx(collectionId, itemsData);12371238    const events = await submitTransactionAsync(sender, tx);1239    const result = getCreateItemsResult(events);12401241    for (const res of result) {1242      expect(await api.rpc.unique.tokenProperties(collectionId, res.itemId)).not.to.be.empty;1243    }1244  });1245}12461247export async function createItemWithPropsExpectSuccess(sender: IKeyringPair, collectionId: number, createMode: string, props:  Array<Property>, owner: CrossAccountId | string = sender.address) {1248  let newItemId = 0;1249  await usingApi(async (api) => {1250    const to = normalizeAccountId(owner);1251    const itemCountBefore = await getLastTokenId(api, collectionId);1252    const itemBalanceBefore = await getBalance(api, collectionId, to, newItemId);12531254    let tx;1255    if (createMode === 'Fungible') {1256      const createData = {fungible: {value: 10}};1257      tx = api.tx.unique.createItem(collectionId, to, createData as any);1258    } else if (createMode === 'ReFungible') {1259      const createData = {refungible: {pieces: 100}};1260      tx = api.tx.unique.createItem(collectionId, to, createData as any);1261    } else {1262      const data = api.createType('UpDataStructsCreateItemData', {NFT: {properties: props}});1263      tx = api.tx.unique.createItem(collectionId, to, data as UpDataStructsCreateItemData);1264    }12651266    const events = await submitTransactionAsync(sender, tx);1267    const result = getCreateItemResult(events);12681269    const itemCountAfter = await getLastTokenId(api, collectionId);1270    const itemBalanceAfter = await getBalance(api, collectionId, to, newItemId);12711272    if (createMode === 'NFT') {1273      expect(await api.rpc.unique.tokenProperties(collectionId, result.itemId)).not.to.be.empty;1274    }12751276    // What to expect1277    // tslint:disable-next-line:no-unused-expression1278    expect(result.success).to.be.true;1279    if (createMode === 'Fungible') {1280      expect(itemBalanceAfter - itemBalanceBefore).to.be.equal(10n);1281    } else {1282      expect(itemCountAfter).to.be.equal(itemCountBefore + 1);1283    }1284    expect(collectionId).to.be.equal(result.collectionId);1285    expect(itemCountAfter.toString()).to.be.equal(result.itemId.toString());1286    expect(to).to.be.deep.equal(result.recipient);1287    newItemId = result.itemId;1288  });1289  return newItemId;1290}12911292export async function createItemWithPropsExpectFailure(sender: IKeyringPair, collectionId: number, createMode: string, props: Array<Property>, owner: CrossAccountId | string = sender.address) {1293  await usingApi(async (api) => {12941295    let tx;1296    if (createMode === 'NFT') {1297      const data = api.createType('UpDataStructsCreateItemData', {NFT: {properties: props}});1298      tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), data);1299    } else {1300      tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), createMode);1301    }130213031304    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1305    if(events.message && events.message.toString().indexOf('1002: Verification Error') > -1) return;1306    const result = getCreateItemResult(events);13071308    expect(result.success).to.be.false;1309  });1310}13111312export async function createItemExpectSuccess(sender: IKeyringPair, collectionId: number, createMode: string, owner: CrossAccountId | string = sender.address) {1313  let newItemId = 0;1314  await usingApi(async (api) => {1315    const to = normalizeAccountId(owner);1316    const itemCountBefore = await getLastTokenId(api, collectionId);1317    const itemBalanceBefore = await getBalance(api, collectionId, to, newItemId);13181319    let tx;1320    if (createMode === 'Fungible') {1321      const createData = {fungible: {value: 10}};1322      tx = api.tx.unique.createItem(collectionId, to, createData as any);1323    } else if (createMode === 'ReFungible') {1324      const createData = {refungible: {pieces: 100}};1325      tx = api.tx.unique.createItem(collectionId, to, createData as any);1326    } else {1327      const createData = {nft: {}};1328      tx = api.tx.unique.createItem(collectionId, to, createData as any);1329    }13301331    const events = await submitTransactionAsync(sender, tx);1332    const result = getCreateItemResult(events);13331334    const itemCountAfter = await getLastTokenId(api, collectionId);1335    const itemBalanceAfter = await getBalance(api, collectionId, to, newItemId);13361337    // What to expect1338    // tslint:disable-next-line:no-unused-expression1339    expect(result.success).to.be.true;1340    if (createMode === 'Fungible') {1341      expect(itemBalanceAfter - itemBalanceBefore).to.be.equal(10n);1342    } else {1343      expect(itemCountAfter).to.be.equal(itemCountBefore + 1);1344    }1345    expect(collectionId).to.be.equal(result.collectionId);1346    expect(itemCountAfter.toString()).to.be.equal(result.itemId.toString());1347    expect(to).to.be.deep.equal(result.recipient);1348    newItemId = result.itemId;1349  });1350  return newItemId;1351}13521353export async function createItemExpectFailure(sender: IKeyringPair, collectionId: number, createMode: string, owner: CrossAccountId | string = sender.address) {1354  await usingApi(async (api) => {1355    const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), createMode);13561357    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1358    const result = getCreateItemResult(events);13591360    expect(result.success).to.be.false;1361  });1362}13631364export async function setPublicAccessModeExpectSuccess(1365  sender: IKeyringPair, collectionId: number,1366  accessMode: 'Normal' | 'AllowList',1367) {1368  await usingApi(async (api) => {13691370    // Run the transaction1371    const tx = api.tx.unique.setCollectionPermissions(collectionId, {access: accessMode});1372    const events = await submitTransactionAsync(sender, tx);1373    const result = getGenericResult(events);13741375    // Get the collection1376    const collection = await queryCollectionExpectSuccess(api, collectionId);13771378    // What to expect1379    // tslint:disable-next-line:no-unused-expression1380    expect(result.success).to.be.true;1381    expect(collection.permissions.access.toHuman()).to.be.equal(accessMode);1382  });1383}13841385export async function setPublicAccessModeExpectFail(1386  sender: IKeyringPair, collectionId: number,1387  accessMode: 'Normal' | 'AllowList',1388) {1389  await usingApi(async (api) => {13901391    // Run the transaction1392    const tx = api.tx.unique.setCollectionPermissions(collectionId, {access: accessMode});1393    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1394    const result = getGenericResult(events);13951396    // What to expect1397    // tslint:disable-next-line:no-unused-expression1398    expect(result.success).to.be.false;1399  });1400}14011402export async function enableAllowListExpectSuccess(sender: IKeyringPair, collectionId: number) {1403  await setPublicAccessModeExpectSuccess(sender, collectionId, 'AllowList');1404}14051406export async function enableAllowListExpectFail(sender: IKeyringPair, collectionId: number) {1407  await setPublicAccessModeExpectFail(sender, collectionId, 'AllowList');1408}14091410export async function disableAllowListExpectSuccess(sender: IKeyringPair, collectionId: number) {1411  await setPublicAccessModeExpectSuccess(sender, collectionId, 'Normal');1412}14131414export async function setMintPermissionExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {1415  await usingApi(async (api) => {14161417    // Run the transaction1418    const tx = api.tx.unique.setCollectionPermissions(collectionId, {mintMode: enabled});1419    const events = await submitTransactionAsync(sender, tx);1420    const result = getGenericResult(events);1421    expect(result.success).to.be.true;14221423    // Get the collection1424    const collection = await queryCollectionExpectSuccess(api, collectionId);14251426    expect(collection.permissions.mintMode.toHuman()).to.be.equal(enabled);1427  });1428}14291430export async function enablePublicMintingExpectSuccess(sender: IKeyringPair, collectionId: number) {1431  await setMintPermissionExpectSuccess(sender, collectionId, true);1432}14331434export async function setMintPermissionExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {1435  await usingApi(async (api) => {1436    // Run the transaction1437    const tx = api.tx.unique.setCollectionPermissions(collectionId, {mintMode: enabled});1438    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1439    const result = getCreateCollectionResult(events);1440    // tslint:disable-next-line:no-unused-expression1441    expect(result.success).to.be.false;1442  });1443}14441445export async function setChainLimitsExpectFailure(sender: IKeyringPair, limits: IChainLimits) {1446  await usingApi(async (api) => {1447    // Run the transaction1448    const tx = api.tx.unique.setChainLimits(limits);1449    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1450    const result = getCreateCollectionResult(events);1451    // tslint:disable-next-line:no-unused-expression1452    expect(result.success).to.be.false;1453  });1454}14551456export async function isAllowlisted(api: ApiPromise, collectionId: number, address: string | CrossAccountId) {1457  return (await api.rpc.unique.allowed(collectionId, normalizeAccountId(address))).toJSON();1458}14591460export async function addToAllowListExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId | CrossAccountId) {1461  await usingApi(async (api) => {1462    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.false;14631464    // Run the transaction1465    const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1466    const events = await submitTransactionAsync(sender, tx);1467    const result = getGenericResult(events);1468    expect(result.success).to.be.true;14691470    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;1471  });1472}14731474export async function addToAllowListAgainExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId) {1475  await usingApi(async (api) => {14761477    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;14781479    // Run the transaction1480    const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1481    const events = await submitTransactionAsync(sender, tx);1482    const result = getGenericResult(events);1483    expect(result.success).to.be.true;14841485    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;1486  });1487}14881489export async function addToAllowListExpectFail(sender: IKeyringPair, collectionId: number, address: string | AccountId) {1490  await usingApi(async (api) => {14911492    // Run the transaction1493    const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1494    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1495    const result = getGenericResult(events);14961497    // What to expect1498    // tslint:disable-next-line:no-unused-expression1499    expect(result.success).to.be.false;1500  });1501}15021503export async function removeFromAllowListExpectSuccess(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1504  await usingApi(async (api) => {1505    // Run the transaction1506    const tx = api.tx.unique.removeFromAllowList(collectionId, normalizeAccountId(address));1507    const events = await submitTransactionAsync(sender, tx);1508    const result = getGenericResult(events);15091510    // What to expect1511    // tslint:disable-next-line:no-unused-expression1512    expect(result.success).to.be.true;1513  });1514}15151516export async function removeFromAllowListExpectFailure(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1517  await usingApi(async (api) => {1518    // Run the transaction1519    const tx = api.tx.unique.removeFromAllowList(collectionId, normalizeAccountId(address));1520    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1521    const result = getGenericResult(events);15221523    // What to expect1524    // tslint:disable-next-line:no-unused-expression1525    expect(result.success).to.be.false;1526  });1527}15281529export const getDetailedCollectionInfo = async (api: ApiPromise, collectionId: number)1530  : Promise<UpDataStructsRpcCollection | null> => {1531  return (await api.rpc.unique.collectionById(collectionId)).unwrapOr(null);1532};15331534export const getCreatedCollectionCount = async (api: ApiPromise): Promise<number> => {1535  // set global object - collectionsCount1536  return (await api.rpc.unique.collectionStats()).created.toNumber();1537};15381539export async function queryCollectionExpectSuccess(api: ApiPromise, collectionId: number): Promise<UpDataStructsRpcCollection> {1540  return (await api.rpc.unique.collectionById(collectionId)).unwrap();1541}15421543export async function waitNewBlocks(blocksCount = 1): Promise<void> {1544  await usingApi(async (api) => {1545    const promise = new Promise<void>(async (resolve) => {1546      const unsubscribe = await api.rpc.chain.subscribeNewHeads(() => {1547        if (blocksCount > 0) {1548          blocksCount--;1549        } else {1550          unsubscribe();1551          resolve();1552        }1553      });1554    });1555    return promise;1556  });1557}