git.delta.rocks / unique-network / refs/commits / 12b8d3cee6e7

difftreelog

test(Scheduler) EVM test + amendments

Fahrrader2022-03-31parent: #c2a4d96.patch.diff
in: master

5 files changed

modifiedpallets/scheduler/src/lib.rsdiffbeforeafterboth
--- a/pallets/scheduler/src/lib.rs
+++ b/pallets/scheduler/src/lib.rs
@@ -440,7 +440,7 @@
 						Err(err) => Err(err.error),
 					},
 					Err(_) => {
-						log::info!(
+						log::error!(
 							target: "runtime::scheduler",
 							"Warning: Scheduler has failed to execute a post-dispatch transaction. \
 							This block might have become invalid.");
modifiedtests/package.jsondiffbeforeafterboth
--- a/tests/package.json
+++ b/tests/package.json
@@ -64,6 +64,7 @@
     "testSetVariableMetadataSponsoringRateLimit": "mocha --timeout 9999999 -r ts-node/register ./**/setVariableMetadataSponsoringRateLimit.test.ts",
     "testInflation": "mocha --timeout 9999999 -r ts-node/register ./**/inflation.test.ts",
     "testScheduler": "mocha --timeout 9999999 -r ts-node/register ./**/scheduler.test.ts",
+    "testSchedulingEVM": "mocha --timeout 9999999 -r ts-node/register ./**/eth/scheduling.test.ts",
     "testXcmTransfer": "mocha --timeout 9999999 -r ts-node/register ./**/xcmTransfer.test.ts",
     "testPalletPresence": "mocha --timeout 9999999 -r ts-node/register ./**/pallet-presence.test.ts",
     "testBlockProduction": "mocha --timeout 9999999 -r ts-node/register ./**/block-production.test.ts",
addedtests/src/eth/scheduling.test.tsdiffbeforeafterboth
--- /dev/null
+++ b/tests/src/eth/scheduling.test.ts
@@ -0,0 +1,55 @@
+// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.
+// This file is part of Unique Network.
+
+// Unique Network is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+
+// Unique Network is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+// GNU General Public License for more details.
+
+// You should have received a copy of the GNU General Public License
+// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
+
+import {expect} from 'chai';
+import {createEthAccountWithBalance, deployFlipper, GAS_ARGS, itWeb3, subToEth, transferBalanceToEth} from './util/helpers';
+import {scheduleExpectSuccess, waitNewBlocks} from '../util/helpers';
+import privateKey from '../substrate/privateKey';
+
+describe('Scheduing EVM smart contracts', () => {
+  itWeb3('Successfully schedules and periodically executes an EVM contract', async ({api, web3}) => {
+    const deployer = await createEthAccountWithBalance(api, web3);
+    const flipper = await deployFlipper(web3, deployer);
+    const initialValue = await flipper.methods.getValue().call();
+    const alice = privateKey('//Alice');
+    await transferBalanceToEth(api, alice, subToEth(alice.address));
+
+    {
+      const tx = api.tx.evm.call(
+        subToEth(alice.address),
+        flipper.options.address,
+        flipper.methods.flip().encodeABI(),
+        '0',
+        GAS_ARGS.gas,
+        await web3.eth.getGasPrice(),
+        null,
+        null,
+        [],
+      );
+      const waitForBlocks = 4;
+      const periodBlocks = 2;
+
+      await scheduleExpectSuccess(tx, alice, waitForBlocks, '0x' + '0'.repeat(32), periodBlocks, 2);
+      expect(await flipper.methods.getValue().call()).to.be.equal(initialValue);
+      
+      await waitNewBlocks(waitForBlocks - 1);
+      expect(await flipper.methods.getValue().call()).to.be.not.equal(initialValue);
+  
+      await waitNewBlocks(periodBlocks);
+      expect(await flipper.methods.getValue().call()).to.be.equal(initialValue);
+    }
+  });
+});
\ No newline at end of file
modifiedtests/src/scheduler.test.tsdiffbeforeafterboth
--- a/tests/src/scheduler.test.ts
+++ b/tests/src/scheduler.test.ts
@@ -20,7 +20,6 @@
 import {
   default as usingApi, 
   submitTransactionAsync,
-  submitTransactionExpectFailAsync,
 } from './substrate/substrate-api';
 import {
   createItemExpectSuccess,
@@ -40,49 +39,58 @@
   scheduleTransferFundsPeriodicExpectSuccess,
   getFreeBalance,
   confirmSponsorshipByKeyExpectSuccess,
+  scheduleExpectFailure,
 } from './util/helpers';
 import {IKeyringPair} from '@polkadot/types/types';
-import {getBalanceSingle} from './substrate/get-balance';
 
 chai.use(chaiAsPromised);
 
 describe('Scheduling token and balance transfers', () => {
   let alice: IKeyringPair;
   let bob: IKeyringPair;
+  let scheduledIdBase: string;
+  let scheduledIdSlider: number;
 
   before(async() => {
     await usingApi(async () => {
       alice = privateKey('//Alice');
       bob = privateKey('//Bob');
     });
+
+    scheduledIdBase = '0x' + '0'.repeat(31);
+    scheduledIdSlider = 0;
   });
 
+  // Loop scheduledId around 10. Unless there are concurrent tasks with long periods/repetitions, tests' tasks' ids shouldn't ovelap.
+  function makeScheduledId(): string {
+    return scheduledIdBase + ((scheduledIdSlider++) % 10);
+  }
+
   it('Can schedule a transfer of an owned token with delay', async () => {
     await usingApi(async () => {
-      // nft
       const nftCollectionId = await createCollectionExpectSuccess();
       const newNftTokenId = await createItemExpectSuccess(alice, nftCollectionId, 'NFT');
       await setCollectionSponsorExpectSuccess(nftCollectionId, alice.address);
       await confirmSponsorshipExpectSuccess(nftCollectionId);
 
-      await scheduleTransferAndWaitExpectSuccess(nftCollectionId, newNftTokenId, alice, bob, 1, 4);
+      await scheduleTransferAndWaitExpectSuccess(nftCollectionId, newNftTokenId, alice, bob, 1, 4, makeScheduledId());
     });
   });
 
   it('Can transfer funds periodically', async () => {
-    await usingApi(async (api) => {
+    await usingApi(async () => {
       const waitForBlocks = 4;
       const period = 2;
-      await scheduleTransferFundsPeriodicExpectSuccess(1n * UNIQUE, alice, bob, waitForBlocks, period, 2);
-      const bobsBalanceBefore = await getBalanceSingle(api, bob.address);
+      await scheduleTransferFundsPeriodicExpectSuccess(1n * UNIQUE, alice, bob, waitForBlocks, makeScheduledId(), period, 2);
+      const bobsBalanceBefore = await getFreeBalance(bob);
 
       // discounting already waited-for operations
       await waitNewBlocks(waitForBlocks - 2);
-      const bobsBalanceAfterFirst = await getBalanceSingle(api, bob.address);
+      const bobsBalanceAfterFirst = await getFreeBalance(bob);
       expect(bobsBalanceAfterFirst > bobsBalanceBefore).to.be.true;
 
       await waitNewBlocks(period);
-      const bobsBalanceAfterSecond = await getBalanceSingle(api, bob.address);
+      const bobsBalanceAfterSecond = await getFreeBalance(bob);
       expect(bobsBalanceAfterSecond > bobsBalanceAfterFirst).to.be.true;
     });
   });
@@ -95,28 +103,18 @@
     await usingApi(async () => {
       const tokenId = await createItemExpectSuccess(alice, collectionId, 'NFT', alice.address);
 
-      const aliceBalanceBefore = await getFreeBalance(alice);
+      const bobBalanceBefore = await getFreeBalance(bob);
+      const waitForBlocks = 4;
       // no need to wait to check, fees must be deducted on scheduling, immediately
-      await scheduleTransferExpectSuccess(collectionId, tokenId, alice, bob, 0, 4);
-      const aliceBalanceAfter = await getFreeBalance(alice);
-      expect(aliceBalanceAfter == aliceBalanceBefore).to.be.true;
+      await scheduleTransferExpectSuccess(collectionId, tokenId, alice, bob, 0, waitForBlocks, makeScheduledId());
+      const bobBalanceAfter = await getFreeBalance(bob);
+      // expect(aliceBalanceAfter == aliceBalanceBefore).to.be.true;
+      expect(bobBalanceAfter < bobBalanceBefore).to.be.true;
+      // wait for sequentiality matters
+      await waitNewBlocks(waitForBlocks - 1);
     });
   });
 
-  /*it('Can\'t schedule a transaction with no funds', async () => {
-    await usingApi(async (api) => {
-      // Find an empty, unused account
-      const zeroBalance = await findUnusedAddress(api);
-
-      const collectionId = await createCollectionExpectSuccess();
-      const tokenId = await createItemExpectSuccess(alice, collectionId, 'NFT');
-
-      await transferExpectSuccess(collectionId, tokenId, alice, zeroBalance);
-
-      await scheduleTransferAndWaitExpectSuccess(collectionId, tokenId, zeroBalance, alice, 1, 4);
-    });
-  });*/
-
   it('Schedules and dispatches a transaction even if the caller has no funds at the time of the dispatch', async () => {
     await usingApi(async (api) => {
       // Find an empty, unused account
@@ -137,13 +135,16 @@
 
       // Schedule transfer of the NFT a few blocks ahead
       const waitForBlocks = 5;
-      await scheduleTransferExpectSuccess(collectionId, tokenId, zeroBalance, alice, 1, waitForBlocks);
+      await scheduleTransferExpectSuccess(collectionId, tokenId, zeroBalance, alice, 1, waitForBlocks, makeScheduledId());
 
       // Get rid of the account's funds before the scheduled transaction takes place
-      const emptyBalanceTx = api.tx.balances.setBalance(zeroBalance.address, 0, 0); // do not null reserved?
+      const balanceTx2 = api.tx.balances.transfer(alice.address, UNIQUE * 68n / 100n);
+      const events = await submitTransactionAsync(zeroBalance, balanceTx2);
+      expect(getGenericResult(events).success).to.be.true;
+      /*const emptyBalanceTx = api.tx.balances.setBalance(zeroBalance.address, 0, 0); // do not null reserved?
       const sudoTx = api.tx.sudo.sudo(emptyBalanceTx as any);
       const events = await submitTransactionAsync(alice, sudoTx);
-      expect(getGenericResult(events).success).to.be.true;
+      expect(getGenericResult(events).success).to.be.true;*/
 
       // Wait for a certain number of blocks, discarding the ones that already happened while accepting the late transactions
       await waitNewBlocks(waitForBlocks - 3);
@@ -157,11 +158,6 @@
 
     await usingApi(async (api) => {
       const zeroBalance = await findUnusedAddress(api);
-
-      /*await setCollectionLimitsExpectSuccess(alice, nftCollectionId, {
-        sponsoredDataRateLimit: 2,
-      });*/
-      //console.log(await getDetailedCollectionInfo(api, nftCollectionId));
       const balanceTx = api.tx.balances.transfer(zeroBalance.address, 1n * UNIQUE);
       await submitTransactionAsync(alice, balanceTx);
 
@@ -170,7 +166,8 @@
 
       const tokenId = await createItemExpectSuccess(alice, collectionId, 'NFT', alice.address);
 
-      await scheduleTransferExpectSuccess(collectionId, tokenId, alice, zeroBalance, 1, 5);
+      const waitForBlocks = 5;
+      await scheduleTransferExpectSuccess(collectionId, tokenId, alice, zeroBalance, 1, waitForBlocks, makeScheduledId());
 
       const emptyBalanceSponsorTx = api.tx.balances.setBalance(zeroBalance.address, 0, 0);
       const sudoTx = api.tx.sudo.sudo(emptyBalanceSponsorTx as any);
@@ -178,61 +175,36 @@
       expect(getGenericResult(events).success).to.be.true;
 
       // Wait for a certain number of blocks, save for the ones that already happened while accepting the late transactions
-      await waitNewBlocks(2);
+      await waitNewBlocks(waitForBlocks - 3);
 
       expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(zeroBalance.address));
     });
   });
-});
 
-describe.skip('Scheduling EVM smart contracts', () => {
-  let alice: IKeyringPair;
-  let bob: IKeyringPair;
-
-  before(async() => {
-    await usingApi(async () => {
-      alice = privateKey('//Alice');
-      bob = privateKey('//Bob');
-    });
-  });
-
-  // todo contract testing
-  it.skip('NFT: Sponsoring of transfers is rate limited', async () => {
+  it.skip('Exceeding sponsor rate limit without having enough funds prevents scheduling a periodic transaction', async () => {
     const collectionId = await createCollectionExpectSuccess();
     await setCollectionSponsorExpectSuccess(collectionId, bob.address);
     await confirmSponsorshipExpectSuccess(collectionId, '//Bob');
 
     await usingApi(async (api) => {
-      // Find unused address
       const zeroBalance = await findUnusedAddress(api);
 
-      // Mint token for alice
-      const itemId = await createItemExpectSuccess(alice, collectionId, 'NFT', alice.address);
+      await enablePublicMintingExpectSuccess(alice, collectionId);
+      await addToAllowListExpectSuccess(alice, collectionId, zeroBalance.address);
 
-      // Transfer this token from Alice to unused address and back
-      // Alice to Zero gets sponsored
-      const aliceToZero = api.tx.unique.transfer(normalizeAccountId(zeroBalance.address), collectionId, itemId, 0);
-      const events1 = await submitTransactionAsync(alice, aliceToZero);
-      const result1 = getGenericResult(events1);
+      const bobBalanceBefore = await getFreeBalance(bob);
+
+      const createData = {nft: {const_data: [], variable_data: []}};
+      const creationTx = api.tx.unique.createItem(collectionId, normalizeAccountId(zeroBalance), createData as any);
 
-      // Second transfer should fail
-      const sponsorBalanceBefore = (await api.query.system.account(bob.address)).data.free.toBigInt();
-      const zeroToAlice = api.tx.unique.transfer(normalizeAccountId(alice.address), collectionId, itemId, 0);
-      const badTransaction = async function () {
+      /*const badTransaction = async function () {
         await submitTransactionExpectFailAsync(zeroBalance, zeroToAlice);
       };
-      await expect(badTransaction()).to.be.rejectedWith('Inability to pay some fees');
-      const sponsorBalanceAfter = (await api.query.system.account(bob.address)).data.free.toBigInt();
+      await expect(badTransaction()).to.be.rejectedWith('Inability to pay some fees');*/
 
-      // Try again after Zero gets some balance - now it should succeed
-      const balancetx = api.tx.balances.transfer(zeroBalance.address, 1n * UNIQUE);
-      await submitTransactionAsync(alice, balancetx);
-      const events2 = await submitTransactionAsync(zeroBalance, zeroToAlice);
-      const result2 = getGenericResult(events2);
+      await scheduleExpectFailure(creationTx, zeroBalance, 3, makeScheduledId(), 1, 3);
 
-      expect(result1.success).to.be.true;
-      expect(result2.success).to.be.true;
-      expect(sponsorBalanceAfter).to.be.equal(sponsorBalanceBefore);
+      expect(await getFreeBalance(bob)).to.be.equal(bobBalanceBefore);
     });
   });
 });
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} from '@polkadot/types/interfaces';21import {IKeyringPair} from '@polkadot/types/types';22import {evmToAddress} from '@polkadot/util-crypto';23import BN from 'bn.js';24import chai from 'chai';25import chaiAsPromised from 'chai-as-promised';26import {alicesPublicKey} from '../accounts';27import privateKey from '../substrate/privateKey';28import {default as usingApi, submitTransactionAsync, submitTransactionExpectFailAsync} from '../substrate/substrate-api';29import {hexToStr, strToUTF16, utf16ToStr} from './util';30import {UpDataStructsCollection} from '@polkadot/types/lookup';3132chai.use(chaiAsPromised);33const expect = chai.expect;3435export type CrossAccountId = {36  Substrate: string,37} | {38  Ethereum: string,39};4041export function normalizeAccountId(input: string | AccountId | CrossAccountId | IKeyringPair): CrossAccountId {42  if (typeof input === 'string') {43    if (input.length === 48 || input.length === 47) {44      return {Substrate: input};45    } else if (input.length === 42 && input.startsWith('0x')) {46      return {Ethereum: input.toLowerCase()};47    } else if (input.length === 40 && !input.startsWith('0x')) {48      return {Ethereum: '0x' + input.toLowerCase()};49    } else {50      throw new Error(`Unknown address format: "${input}"`);51    }52  }53  if ('address' in input) {54    return {Substrate: input.address};55  }56  if ('Ethereum' in input) {57    return {58      Ethereum: input.Ethereum.toLowerCase(),59    };60  } else if ('ethereum' in input) {61    return {62      Ethereum: (input as any).ethereum.toLowerCase(),63    };64  } else if ('Substrate' in input) {65    return input;66  } else if ('substrate' in input) {67    return {68      Substrate: (input as any).substrate,69    };70  }7172  // AccountId73  return {Substrate: input.toString()};74}75export function toSubstrateAddress(input: string | CrossAccountId | IKeyringPair): string {76  input = normalizeAccountId(input);77  if ('Substrate' in input) {78    return input.Substrate;79  } else {80    return evmToAddress(input.Ethereum);81  }82}8384export const U128_MAX = (1n << 128n) - 1n;8586const MICROUNIQUE = 1_000_000_000_000n;87const MILLIUNIQUE = 1_000n * MICROUNIQUE;88const CENTIUNIQUE = 10n * MILLIUNIQUE;89export const UNIQUE = 100n * CENTIUNIQUE;9091type GenericResult = {92  success: boolean,93};9495interface CreateCollectionResult {96  success: boolean;97  collectionId: number;98}99100interface CreateItemResult {101  success: boolean;102  collectionId: number;103  itemId: number;104  recipient?: CrossAccountId;105}106107interface TransferResult {108  success: boolean;109  collectionId: number;110  itemId: number;111  sender?: CrossAccountId;112  recipient?: CrossAccountId;113  value: bigint;114}115116interface IReFungibleOwner {117  fraction: BN;118  owner: number[];119}120121interface IGetMessage {122  checkMsgUnqMethod: string;123  checkMsgTrsMethod: string;124  checkMsgSysMethod: string;125}126127export interface IFungibleTokenDataType {128  value: number;129}130131export interface IChainLimits {132  collectionNumbersLimit: number;133  accountTokenOwnershipLimit: number;134  collectionsAdminsLimit: number;135  customDataLimit: number;136  nftSponsorTransferTimeout: number;137  fungibleSponsorTransferTimeout: number;138  refungibleSponsorTransferTimeout: number;139  offchainSchemaLimit: number;140  variableOnChainSchemaLimit: number;141  constOnChainSchemaLimit: number;142}143144export interface IReFungibleTokenDataType {145  owner: IReFungibleOwner[];146  constData: number[];147  variableData: number[];148}149150export function uniqueEventMessage(events: EventRecord[]): IGetMessage {151  let checkMsgUnqMethod = '';152  let checkMsgTrsMethod = '';153  let checkMsgSysMethod = '';154  events.forEach(({event: {method, section}}) => {155    if (section === 'common') {156      checkMsgUnqMethod = method;157    } else if (section === 'treasury') {158      checkMsgTrsMethod = method;159    } else if (section === 'system') {160      checkMsgSysMethod = method;161    } else { return null; }162  });163  const result: IGetMessage = {164    checkMsgUnqMethod,165    checkMsgTrsMethod,166    checkMsgSysMethod,167  };168  return result;169}170171export function getGenericResult(events: EventRecord[]): GenericResult {172  const result: GenericResult = {173    success: false,174  };175  events.forEach(({event: {method}}) => {176    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);177    if (method === 'ExtrinsicSuccess') {178      result.success = true;179    }180  });181  return result;182}183184185186export function getCreateCollectionResult(events: EventRecord[]): CreateCollectionResult {187  let success = false;188  let collectionId = 0;189  events.forEach(({event: {data, method, section}}) => {190    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);191    if (method == 'ExtrinsicSuccess') {192      success = true;193    } else if ((section == 'common') && (method == 'CollectionCreated')) {194      collectionId = parseInt(data[0].toString(), 10);195    }196  });197  const result: CreateCollectionResult = {198    success,199    collectionId,200  };201  return result;202}203204export function getCreateItemResult(events: EventRecord[]): CreateItemResult {205  let success = false;206  let collectionId = 0;207  let itemId = 0;208  let recipient;209  events.forEach(({event: {data, method, section}}) => {210    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);211    if (method == 'ExtrinsicSuccess') {212      success = true;213    } else if ((section == 'common') && (method == 'ItemCreated')) {214      collectionId = parseInt(data[0].toString(), 10);215      itemId = parseInt(data[1].toString(), 10);216      recipient = normalizeAccountId(data[2].toJSON() as any);217    }218  });219  const result: CreateItemResult = {220    success,221    collectionId,222    itemId,223    recipient,224  };225  return result;226}227228export function getTransferResult(events: EventRecord[]): TransferResult {229  const result: TransferResult = {230    success: false,231    collectionId: 0,232    itemId: 0,233    value: 0n,234  };235236  events.forEach(({event: {data, method, section}}) => {237    if (method === 'ExtrinsicSuccess') {238      result.success = true;239    } else if (section === 'common' && method === 'Transfer') {240      result.collectionId = +data[0].toString();241      result.itemId = +data[1].toString();242      result.sender = normalizeAccountId(data[2].toJSON() as any);243      result.recipient = normalizeAccountId(data[3].toJSON() as any);244      result.value = BigInt(data[4].toString());245    }246  });247248  return result;249}250251interface Nft {252  type: 'NFT';253}254255interface Fungible {256  type: 'Fungible';257  decimalPoints: number;258}259260interface ReFungible {261  type: 'ReFungible';262}263264type CollectionMode = Nft | Fungible | ReFungible;265266export type CreateCollectionParams = {267  mode: CollectionMode,268  name: string,269  description: string,270  tokenPrefix: string,271};272273const defaultCreateCollectionParams: CreateCollectionParams = {274  description: 'description',275  mode: {type: 'NFT'},276  name: 'name',277  tokenPrefix: 'prefix',278};279280export async function createCollectionExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {281  const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};282283  let collectionId = 0;284  await usingApi(async (api) => {285    // Get number of collections before the transaction286    const collectionCountBefore = await getCreatedCollectionCount(api);287288    // Run the CreateCollection transaction289    const alicePrivateKey = privateKey('//Alice');290291    let modeprm = {};292    if (mode.type === 'NFT') {293      modeprm = {nft: null};294    } else if (mode.type === 'Fungible') {295      modeprm = {fungible: mode.decimalPoints};296    } else if (mode.type === 'ReFungible') {297      modeprm = {refungible: null};298    }299300    const tx = api.tx.unique.createCollectionEx({name: strToUTF16(name), description: strToUTF16(description), tokenPrefix: strToUTF16(tokenPrefix), mode: modeprm as any});301    const events = await submitTransactionAsync(alicePrivateKey, tx);302    const result = getCreateCollectionResult(events);303304    // Get number of collections after the transaction305    const collectionCountAfter = await getCreatedCollectionCount(api);306307    // Get the collection308    const collection = await queryCollectionExpectSuccess(api, result.collectionId);309310    // What to expect311    // tslint:disable-next-line:no-unused-expression312    expect(result.success).to.be.true;313    expect(result.collectionId).to.be.equal(collectionCountAfter);314    // tslint:disable-next-line:no-unused-expression315    expect(collection).to.be.not.null;316    expect(collectionCountAfter).to.be.equal(collectionCountBefore + 1, 'Error: NFT collection NOT created.');317    expect(collection.owner.toString()).to.be.equal(toSubstrateAddress(alicesPublicKey));318    expect(utf16ToStr(collection.name.toJSON() as any)).to.be.equal(name);319    expect(utf16ToStr(collection.description.toJSON() as any)).to.be.equal(description);320    expect(hexToStr(collection.tokenPrefix.toJSON())).to.be.equal(tokenPrefix);321322    collectionId = result.collectionId;323  });324325  return collectionId;326}327328export async function createCollectionExpectFailure(params: Partial<CreateCollectionParams> = {}) {329  const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};330331  let modeprm = {};332  if (mode.type === 'NFT') {333    modeprm = {nft: null};334  } else if (mode.type === 'Fungible') {335    modeprm = {fungible: mode.decimalPoints};336  } else if (mode.type === 'ReFungible') {337    modeprm = {refungible: null};338  }339340  await usingApi(async (api) => {341    // Get number of collections before the transaction342    const collectionCountBefore = await getCreatedCollectionCount(api);343344    // Run the CreateCollection transaction345    const alicePrivateKey = privateKey('//Alice');346    const tx = api.tx.unique.createCollectionEx({name: strToUTF16(name), description: strToUTF16(description), tokenPrefix: strToUTF16(tokenPrefix), mode: modeprm as any});347    const events = await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;348    const result = getCreateCollectionResult(events);349350    // Get number of collections after the transaction351    const collectionCountAfter = await getCreatedCollectionCount(api);352353    // What to expect354    // tslint:disable-next-line:no-unused-expression355    expect(result.success).to.be.false;356    expect(collectionCountAfter).to.be.equal(collectionCountBefore, 'Error: Collection with incorrect data created.');357  });358}359360export async function findUnusedAddress(api: ApiPromise, seedAddition = ''): Promise<IKeyringPair> {361  let bal = 0n;362  let unused;363  do {364    const randomSeed = 'seed' + Math.floor(Math.random() * Math.floor(10000)) + seedAddition;365    const keyring = new Keyring({type: 'sr25519'});366    unused = keyring.addFromUri(`//${randomSeed}`);367    bal = (await api.query.system.account(unused.address)).data.free.toBigInt();368  } while (bal !== 0n);369  return unused;370}371372export async function getAllowance(api: ApiPromise, collectionId: number, owner: CrossAccountId | string, approved: CrossAccountId | string, tokenId: number) {373  return (await api.rpc.unique.allowance(collectionId, normalizeAccountId(owner), normalizeAccountId(approved), tokenId)).toBigInt();374}375376export function findUnusedAddresses(api: ApiPromise, amount: number): Promise<IKeyringPair[]> {377  return Promise.all(new Array(amount).fill(null).map(() => findUnusedAddress(api, '_' + Date.now())));378}379380export async function findNotExistingCollection(api: ApiPromise): Promise<number> {381  const totalNumber = await getCreatedCollectionCount(api);382  const newCollection: number = totalNumber + 1;383  return newCollection;384}385386function getDestroyResult(events: EventRecord[]): boolean {387  let success = false;388  events.forEach(({event: {method}}) => {389    if (method == 'ExtrinsicSuccess') {390      success = true;391    }392  });393  return success;394}395396export async function destroyCollectionExpectFailure(collectionId: number, senderSeed = '//Alice') {397  await usingApi(async (api) => {398    // Run the DestroyCollection transaction399    const alicePrivateKey = privateKey(senderSeed);400    const tx = api.tx.unique.destroyCollection(collectionId);401    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;402  });403}404405export async function destroyCollectionExpectSuccess(collectionId: number, senderSeed = '//Alice') {406  await usingApi(async (api) => {407    // Run the DestroyCollection transaction408    const alicePrivateKey = privateKey(senderSeed);409    const tx = api.tx.unique.destroyCollection(collectionId);410    const events = await submitTransactionAsync(alicePrivateKey, tx);411    const result = getDestroyResult(events);412    expect(result).to.be.true;413414    // What to expect415    expect(await getDetailedCollectionInfo(api, collectionId)).to.be.null;416  });417}418419export async function setCollectionLimitsExpectSuccess(sender: IKeyringPair, collectionId: number, limits: any) {420  await usingApi(async (api) => {421    const tx = api.tx.unique.setCollectionLimits(collectionId, limits);422    const events = await submitTransactionAsync(sender, tx);423    const result = getGenericResult(events);424425    expect(result.success).to.be.true;426  });427}428429export async function setCollectionLimitsExpectFailure(sender: IKeyringPair, collectionId: number, limits: any) {430  await usingApi(async (api) => {431    const tx = api.tx.unique.setCollectionLimits(collectionId, limits);432    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;433    const result = getGenericResult(events);434435    expect(result.success).to.be.false;436  });437}438439export async function setCollectionSponsorExpectSuccess(collectionId: number, sponsor: string, sender = '//Alice') {440  await usingApi(async (api) => {441442    // Run the transaction443    const senderPrivateKey = privateKey(sender);444    const tx = api.tx.unique.setCollectionSponsor(collectionId, sponsor);445    const events = await submitTransactionAsync(senderPrivateKey, tx);446    const result = getGenericResult(events);447448    // Get the collection449    const collection = await queryCollectionExpectSuccess(api, collectionId);450451    // What to expect452    expect(result.success).to.be.true;453    expect(collection.sponsorship.toJSON()).to.deep.equal({454      unconfirmed: sponsor,455    });456  });457}458459export async function removeCollectionSponsorExpectSuccess(collectionId: number, sender = '//Alice') {460  await usingApi(async (api) => {461462    // Run the transaction463    const alicePrivateKey = privateKey(sender);464    const tx = api.tx.unique.removeCollectionSponsor(collectionId);465    const events = await submitTransactionAsync(alicePrivateKey, tx);466    const result = getGenericResult(events);467468    // Get the collection469    const collection = await queryCollectionExpectSuccess(api, collectionId);470471    // What to expect472    expect(result.success).to.be.true;473    expect(collection.sponsorship.toJSON()).to.be.deep.equal({disabled: null});474  });475}476477export async function removeCollectionSponsorExpectFailure(collectionId: number, senderSeed = '//Alice') {478  await usingApi(async (api) => {479480    // Run the transaction481    const alicePrivateKey = privateKey(senderSeed);482    const tx = api.tx.unique.removeCollectionSponsor(collectionId);483    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;484  });485}486487export async function setCollectionSponsorExpectFailure(collectionId: number, sponsor: string, senderSeed = '//Alice') {488  await usingApi(async (api) => {489490    // Run the transaction491    const alicePrivateKey = privateKey(senderSeed);492    const tx = api.tx.unique.setCollectionSponsor(collectionId, sponsor);493    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;494  });495}496497export async function confirmSponsorshipExpectSuccess(collectionId: number, senderSeed = '//Alice') {498  await usingApi(async () => {499    const sender = privateKey(senderSeed);500    await confirmSponsorshipByKeyExpectSuccess(collectionId, sender);501  });502}503504export async function confirmSponsorshipByKeyExpectSuccess(collectionId: number, sender: IKeyringPair) {505  await usingApi(async (api) => {506507    // Run the transaction508    const tx = api.tx.unique.confirmSponsorship(collectionId);509    const events = await submitTransactionAsync(sender, tx);510    const result = getGenericResult(events);511512    // Get the collection513    const collection = await queryCollectionExpectSuccess(api, collectionId);514515    // What to expect516    expect(result.success).to.be.true;517    expect(collection.sponsorship.toJSON()).to.be.deep.equal({518      confirmed: sender.address,519    });520  });521}522523524export async function confirmSponsorshipExpectFailure(collectionId: number, senderSeed = '//Alice') {525  await usingApi(async (api) => {526527    // Run the transaction528    const sender = privateKey(senderSeed);529    const tx = api.tx.unique.confirmSponsorship(collectionId);530    await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;531  });532}533534export async function setMetadataUpdatePermissionFlagExpectSuccess(sender: IKeyringPair, collectionId: number, flag: string) {535536  await usingApi(async (api) => {537    const tx = api.tx.unique.setMetaUpdatePermissionFlag(collectionId, flag as any);538    const events = await submitTransactionAsync(sender, tx);539    const result = getGenericResult(events);540541    expect(result.success).to.be.true;542  });543}544545export async function setMetadataUpdatePermissionFlagExpectFailure(sender: IKeyringPair, collectionId: number, flag: string) {546547  await usingApi(async (api) => {548    const tx = api.tx.unique.setMetaUpdatePermissionFlag(collectionId, flag as any);549    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;550    const result = getGenericResult(events);551552    expect(result.success).to.be.false;553  });554}555556export async function enableContractSponsoringExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {557  await usingApi(async (api) => {558    const tx = api.tx.unique.enableContractSponsoring(contractAddress, enable);559    const events = await submitTransactionAsync(sender, tx);560    const result = getGenericResult(events);561562    expect(result.success).to.be.true;563  });564}565566export async function enableContractSponsoringExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {567  await usingApi(async (api) => {568    const tx = api.tx.unique.enableContractSponsoring(contractAddress, enable);569    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;570    const result = getGenericResult(events);571572    expect(result.success).to.be.false;573  });574}575576export async function setTransferFlagExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {577578  await usingApi(async (api) => {579580    const tx = api.tx.unique.setTransfersEnabledFlag(collectionId, enabled);581    const events = await submitTransactionAsync(sender, tx);582    const result = getGenericResult(events);583584    expect(result.success).to.be.true;585  });586}587588export async function setTransferFlagExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {589590  await usingApi(async (api) => {591592    const tx = api.tx.unique.setTransfersEnabledFlag(collectionId, enabled);593    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;594    const result = getGenericResult(events);595596    expect(result.success).to.be.false;597  });598}599600export async function setContractSponsoringRateLimitExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {601  await usingApi(async (api) => {602    const tx = api.tx.unique.setContractSponsoringRateLimit(contractAddress, rateLimit);603    const events = await submitTransactionAsync(sender, tx);604    const result = getGenericResult(events);605606    expect(result.success).to.be.true;607  });608}609610export async function setContractSponsoringRateLimitExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {611  await usingApi(async (api) => {612    const tx = api.tx.unique.setContractSponsoringRateLimit(contractAddress, rateLimit);613    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;614    const result = getGenericResult(events);615616    expect(result.success).to.be.false;617  });618}619620export async function toggleContractAllowlistExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, value = true) {621  await usingApi(async (api) => {622    const tx = api.tx.unique.toggleContractAllowList(contractAddress, value);623    const events = await submitTransactionAsync(sender, tx);624    const result = getGenericResult(events);625626    expect(result.success).to.be.true;627  });628}629630export async function isAllowlistedInContract(contractAddress: AccountId | string, user: string) {631  let allowlisted = false;632  await usingApi(async (api) => {633    allowlisted = (await api.query.unique.contractAllowList(contractAddress, user)).toJSON() as boolean;634  });635  return allowlisted;636}637638export async function addToContractAllowListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {639  await usingApi(async (api) => {640    const tx = api.tx.unique.addToContractAllowList(contractAddress.toString(), user.toString());641    const events = await submitTransactionAsync(sender, tx);642    const result = getGenericResult(events);643644    expect(result.success).to.be.true;645  });646}647648export async function removeFromContractAllowListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {649  await usingApi(async (api) => {650    const tx = api.tx.unique.removeFromContractAllowList(contractAddress.toString(), user.toString());651    const events = await submitTransactionAsync(sender, tx);652    const result = getGenericResult(events);653654    expect(result.success).to.be.true;655  });656}657658export async function removeFromContractAllowListExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {659  await usingApi(async (api) => {660    const tx = api.tx.unique.removeFromContractAllowList(contractAddress.toString(), user.toString());661    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;662    const result = getGenericResult(events);663664    expect(result.success).to.be.false;665  });666}667668export async function setVariableMetaDataExpectSuccess(sender: IKeyringPair, collectionId: number, itemId: number, data: number[]) {669  await usingApi(async (api) => {670    const tx = api.tx.unique.setVariableMetaData(collectionId, itemId, '0x' + Buffer.from(data).toString('hex'));671    const events = await submitTransactionAsync(sender, tx);672    const result = getGenericResult(events);673674    expect(result.success).to.be.true;675  });676}677678export async function setVariableMetaDataExpectFailure(sender: IKeyringPair, collectionId: number, itemId: number, data: number[]) {679  await usingApi(async (api) => {680    const tx = api.tx.unique.setVariableMetaData(collectionId, itemId, '0x' + Buffer.from(data).toString('hex'));681    await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;682  });683}684685export async function setOffchainSchemaExpectSuccess(sender: IKeyringPair, collectionId: number, data: number[]) {686  await usingApi(async (api) => {687    const tx = api.tx.unique.setOffchainSchema(collectionId, '0x' + Buffer.from(data).toString('hex'));688    const events = await submitTransactionAsync(sender, tx);689    const result = getGenericResult(events);690691    expect(result.success).to.be.true;692  });693}694695export async function setOffchainSchemaExpectFailure(sender: IKeyringPair, collectionId: number, data: number[]) {696  await usingApi(async (api) => {697    const tx = api.tx.unique.setOffchainSchema(collectionId, '0x' + Buffer.from(data).toString('hex'));698    await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;699  });700}701702export interface CreateFungibleData {703  readonly Value: bigint;704}705706export interface CreateReFungibleData { }707export interface CreateNftData { }708709export type CreateItemData = {710  NFT: CreateNftData;711} | {712  Fungible: CreateFungibleData;713} | {714  ReFungible: CreateReFungibleData;715};716717export async function burnItemExpectSuccess(sender: IKeyringPair, collectionId: number, tokenId: number, value = 1) {718  await usingApi(async (api) => {719    const balanceBefore = await getBalance(api, collectionId, normalizeAccountId(sender), tokenId);720    // if burning token by admin - use adminButnItemExpectSuccess721    expect(balanceBefore >= BigInt(value)).to.be.true;722723    const tx = api.tx.unique.burnItem(collectionId, tokenId, value);724    const events = await submitTransactionAsync(sender, tx);725    const result = getGenericResult(events);726    expect(result.success).to.be.true;727728    const balanceAfter = await getBalance(api, collectionId, normalizeAccountId(sender), tokenId);729    expect(balanceAfter + BigInt(value)).to.be.equal(balanceBefore);730  });731}732733export async function734approveExpectSuccess(735  collectionId: number,736  tokenId: number, owner: IKeyringPair, approved: CrossAccountId | string, amount: number | bigint = 1,737) {738  await usingApi(async (api: ApiPromise) => {739    const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);740    const events = await submitTransactionAsync(owner, approveUniqueTx);741    const result = getGenericResult(events);742    expect(result.success).to.be.true;743744    expect(await getAllowance(api, collectionId, owner.address, approved, tokenId)).to.be.equal(BigInt(amount));745  });746}747748export async function adminApproveFromExpectSuccess(749  collectionId: number,750  tokenId: number, admin: IKeyringPair, owner: CrossAccountId | string, approved: CrossAccountId | string, amount: number | bigint = 1,751) {752  await usingApi(async (api: ApiPromise) => {753    const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);754    const events = await submitTransactionAsync(admin, approveUniqueTx);755    const result = getGenericResult(events);756    expect(result.success).to.be.true;757758    expect(await getAllowance(api, collectionId, owner, approved, tokenId)).to.be.equal(BigInt(amount));759  });760}761762export async function763transferFromExpectSuccess(764  collectionId: number,765  tokenId: number,766  accountApproved: IKeyringPair,767  accountFrom: IKeyringPair | CrossAccountId,768  accountTo: IKeyringPair | CrossAccountId,769  value: number | bigint = 1,770  type = 'NFT',771) {772  await usingApi(async (api: ApiPromise) => {773    const from = normalizeAccountId(accountFrom);774    const to = normalizeAccountId(accountTo);775    let balanceBefore = 0n;776    if (type === 'Fungible') {777      balanceBefore = await getBalance(api, collectionId, to, tokenId);778    }779    const transferFromTx = api.tx.unique.transferFrom(normalizeAccountId(accountFrom), to, collectionId, tokenId, value);780    const events = await submitTransactionAsync(accountApproved, transferFromTx);781    const result = getCreateItemResult(events);782    // tslint:disable-next-line:no-unused-expression783    expect(result.success).to.be.true;784    if (type === 'NFT') {785      expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(to);786    }787    if (type === 'Fungible') {788      const balanceAfter = await getBalance(api, collectionId, to, tokenId);789      if (JSON.stringify(to) !== JSON.stringify(from)) {790        expect(balanceAfter - balanceBefore).to.be.equal(BigInt(value));791      } else {792        expect(balanceAfter).to.be.equal(balanceBefore);793      }794    }795    if (type === 'ReFungible') {796      expect(await getBalance(api, collectionId, to, tokenId)).to.be.equal(BigInt(value));797    }798  });799}800801export async function802transferFromExpectFail(803  collectionId: number,804  tokenId: number,805  accountApproved: IKeyringPair,806  accountFrom: IKeyringPair,807  accountTo: IKeyringPair,808  value: number | bigint = 1,809) {810  await usingApi(async (api: ApiPromise) => {811    const transferFromTx = api.tx.unique.transferFrom(normalizeAccountId(accountFrom.address), normalizeAccountId(accountTo.address), collectionId, tokenId, value);812    const events = await expect(submitTransactionExpectFailAsync(accountApproved, transferFromTx)).to.be.rejected;813    const result = getCreateCollectionResult(events);814    // tslint:disable-next-line:no-unused-expression815    expect(result.success).to.be.false;816  });817}818819/* eslint no-async-promise-executor: "off" */820export async function getBlockNumber(api: ApiPromise): Promise<number> {821  return new Promise<number>(async (resolve) => {822    const unsubscribe = await api.rpc.chain.subscribeNewHeads((head) => {823      unsubscribe();824      resolve(head.number.toNumber());825    });826  });827}828829export async function addCollectionAdminExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | CrossAccountId) {830  await usingApi(async (api) => {831    const changeAdminTx = api.tx.unique.addCollectionAdmin(collectionId, normalizeAccountId(address));832    const events = await submitTransactionAsync(sender, changeAdminTx);833    const result = getCreateCollectionResult(events);834    expect(result.success).to.be.true;835  });836}837838export async function839getFreeBalance(account: IKeyringPair): Promise<bigint> {840  let balance = 0n;841  await usingApi(async (api) => {842    balance = BigInt((await api.query.system.account(account.address)).data.free.toString());843  });844845  return balance;846}847848export async function849scheduleTransferAndWaitExpectSuccess(850  collectionId: number,851  tokenId: number,852  sender: IKeyringPair,853  recipient: IKeyringPair,854  value: number | bigint = 1,855  blockSchedule: number,856) {857  await usingApi(async (api: ApiPromise) => {858    await scheduleTransferExpectSuccess(collectionId, tokenId, sender, recipient, value, blockSchedule);859860    const recipientBalanceBefore = (await api.query.system.account(recipient.address)).data.free.toBigInt();861    console.log(await getFreeBalance(sender));862863    // sleep for n + 1 blocks864    await waitNewBlocks(blockSchedule + 1);865866    const recipientBalanceAfter = (await api.query.system.account(recipient.address)).data.free.toBigInt();867868    expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(recipient.address));869    expect(recipientBalanceAfter).to.be.equal(recipientBalanceBefore);870  });871}872873export async function874scheduleTransferExpectSuccess(875  collectionId: number,876  tokenId: number,877  sender: IKeyringPair,878  recipient: IKeyringPair,879  value: number | bigint = 1,880  blockSchedule: number,881) {882  await usingApi(async (api: ApiPromise) => {883    const blockNumber: number | undefined = await getBlockNumber(api);884    const expectedBlockNumber = blockNumber + blockSchedule;885886    expect(blockNumber).to.be.greaterThan(0);887    const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient.address), collectionId, tokenId, value);888    const scheduleTx = api.tx.scheduler.schedule(expectedBlockNumber, null, 0, transferTx as any);889890    const events = await submitTransactionAsync(sender, scheduleTx);891    expect(getGenericResult(events).success).to.be.true;892893    expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(sender.address));894  });895}896897export async function898scheduleTransferFundsPeriodicExpectSuccess(899  amount: bigint,900  sender: IKeyringPair,901  recipient: IKeyringPair,902  blockSchedule: number,903  period: number,904  repetitions: number,905) {906  await usingApi(async (api: ApiPromise) => {907    const blockNumber: number | undefined = await getBlockNumber(api);908    const expectedBlockNumber = blockNumber + blockSchedule;909910    const balanceBefore = await getFreeBalance(recipient);911    912    expect(blockNumber).to.be.greaterThan(0);913    const transferTx = api.tx.balances.transfer(recipient.address, amount);914    const scheduleTx = api.tx.scheduler.schedule(expectedBlockNumber, [period, repetitions], 0, transferTx as any);915916    const events = await submitTransactionAsync(sender, scheduleTx);917    expect(getGenericResult(events).success).to.be.true;918919    expect(await getFreeBalance(recipient)).to.be.equal(balanceBefore);920  });921}922923924export async function925transferExpectSuccess(926  collectionId: number,927  tokenId: number,928  sender: IKeyringPair,929  recipient: IKeyringPair | CrossAccountId,930  value: number | bigint = 1,931  type = 'NFT',932) {933  await usingApi(async (api: ApiPromise) => {934    const from = normalizeAccountId(sender);935    const to = normalizeAccountId(recipient);936937    let balanceBefore = 0n;938    if (type === 'Fungible') {939      balanceBefore = await getBalance(api, collectionId, to, tokenId);940    }941    const transferTx = api.tx.unique.transfer(to, collectionId, tokenId, value);942    const events = await submitTransactionAsync(sender, transferTx);943    const result = getTransferResult(events);944    // tslint:disable-next-line:no-unused-expression945    expect(result.success).to.be.true;946    expect(result.collectionId).to.be.equal(collectionId);947    expect(result.itemId).to.be.equal(tokenId);948    expect(result.sender).to.be.deep.equal(normalizeAccountId(sender.address));949    expect(result.recipient).to.be.deep.equal(to);950    expect(result.value).to.be.equal(BigInt(value));951    if (type === 'NFT') {952      expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(to);953    }954    if (type === 'Fungible') {955      const balanceAfter = await getBalance(api, collectionId, to, tokenId);956      if (JSON.stringify(to) !== JSON.stringify(from)) {957        expect(balanceAfter - balanceBefore).to.be.equal(BigInt(value));958      } else {959        expect(balanceAfter).to.be.equal(balanceBefore);960      }961    }962    if (type === 'ReFungible') {963      expect(await getBalance(api, collectionId, to, tokenId) >= value).to.be.true;964    }965  });966}967968export async function969transferExpectFailure(970  collectionId: number,971  tokenId: number,972  sender: IKeyringPair,973  recipient: IKeyringPair,974  value: number | bigint = 1,975) {976  await usingApi(async (api: ApiPromise) => {977    const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient.address), collectionId, tokenId, value);978    const events = await expect(submitTransactionExpectFailAsync(sender, transferTx)).to.be.rejected;979    const result = getGenericResult(events);980    // if (events && Array.isArray(events)) {981    //   const result = getCreateCollectionResult(events);982    // tslint:disable-next-line:no-unused-expression983    expect(result.success).to.be.false;984    //}985  });986}987988export async function989approveExpectFail(990  collectionId: number,991  tokenId: number, owner: IKeyringPair, approved: IKeyringPair, amount: number | bigint = 1,992) {993  await usingApi(async (api: ApiPromise) => {994    const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved.address), collectionId, tokenId, amount);995    const events = await expect(submitTransactionExpectFailAsync(owner, approveUniqueTx)).to.be.rejected;996    const result = getCreateCollectionResult(events);997    // tslint:disable-next-line:no-unused-expression998    expect(result.success).to.be.false;999  });1000}10011002export async function getBalance(1003  api: ApiPromise,1004  collectionId: number,1005  owner: string | CrossAccountId,1006  token: number,1007): Promise<bigint> {1008  return (await api.rpc.unique.balance(collectionId, normalizeAccountId(owner), token)).toBigInt();1009}1010export async function getTokenOwner(1011  api: ApiPromise,1012  collectionId: number,1013  token: number,1014): Promise<CrossAccountId> {1015  return normalizeAccountId((await api.rpc.unique.tokenOwner(collectionId, token)).toJSON() as any);1016}1017export async function isTokenExists(1018  api: ApiPromise,1019  collectionId: number,1020  token: number,1021): Promise<boolean> {1022  return (await api.rpc.unique.tokenExists(collectionId, token)).toJSON();1023}1024export async function getLastTokenId(1025  api: ApiPromise,1026  collectionId: number,1027): Promise<number> {1028  return (await api.rpc.unique.lastTokenId(collectionId)).toJSON();1029}1030export async function getAdminList(1031  api: ApiPromise,1032  collectionId: number,1033): Promise<string[]> {1034  return (await api.rpc.unique.adminlist(collectionId)).toHuman() as any;1035}1036export async function getVariableMetadata(1037  api: ApiPromise,1038  collectionId: number,1039  tokenId: number,1040): Promise<number[]> {1041  return [...(await api.rpc.unique.variableMetadata(collectionId, tokenId))];1042}1043export async function getConstMetadata(1044  api: ApiPromise,1045  collectionId: number,1046  tokenId: number,1047): Promise<number[]> {1048  return [...(await api.rpc.unique.constMetadata(collectionId, tokenId))];1049}10501051export async function createFungibleItemExpectSuccess(1052  sender: IKeyringPair,1053  collectionId: number,1054  data: CreateFungibleData,1055  owner: CrossAccountId | string = sender.address,1056) {1057  return await usingApi(async (api) => {1058    const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), {Fungible: data});10591060    const events = await submitTransactionAsync(sender, tx);1061    const result = getCreateItemResult(events);10621063    expect(result.success).to.be.true;1064    return result.itemId;1065  });1066}10671068export async function createItemExpectSuccess(sender: IKeyringPair, collectionId: number, createMode: string, owner: CrossAccountId | string = sender.address) {1069  let newItemId = 0;1070  await usingApi(async (api) => {1071    const to = normalizeAccountId(owner);1072    const itemCountBefore = await getLastTokenId(api, collectionId);1073    const itemBalanceBefore = await getBalance(api, collectionId, to, newItemId);10741075    let tx;1076    if (createMode === 'Fungible') {1077      const createData = {fungible: {value: 10}};1078      tx = api.tx.unique.createItem(collectionId, to, createData as any);1079    } else if (createMode === 'ReFungible') {1080      const createData = {refungible: {const_data: [], variable_data: [], pieces: 100}};1081      tx = api.tx.unique.createItem(collectionId, to, createData as any);1082    } else {1083      const createData = {nft: {const_data: [], variable_data: []}};1084      tx = api.tx.unique.createItem(collectionId, to, createData as any);1085    }10861087    const events = await submitTransactionAsync(sender, tx);1088    const result = getCreateItemResult(events);10891090    const itemCountAfter = await getLastTokenId(api, collectionId);1091    const itemBalanceAfter = await getBalance(api, collectionId, to, newItemId);10921093    // What to expect1094    // tslint:disable-next-line:no-unused-expression1095    expect(result.success).to.be.true;1096    if (createMode === 'Fungible') {1097      expect(itemBalanceAfter - itemBalanceBefore).to.be.equal(10n);1098    } else {1099      expect(itemCountAfter).to.be.equal(itemCountBefore + 1);1100    }1101    expect(collectionId).to.be.equal(result.collectionId);1102    expect(itemCountAfter.toString()).to.be.equal(result.itemId.toString());1103    expect(to).to.be.deep.equal(result.recipient);1104    newItemId = result.itemId;1105  });1106  return newItemId;1107}11081109export async function createItemExpectFailure(sender: IKeyringPair, collectionId: number, createMode: string, owner: string = sender.address) {1110  await usingApi(async (api) => {1111    const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), createMode);11121113    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1114    const result = getCreateItemResult(events);11151116    expect(result.success).to.be.false;1117  });1118}11191120export async function setPublicAccessModeExpectSuccess(1121  sender: IKeyringPair, collectionId: number,1122  accessMode: 'Normal' | 'AllowList',1123) {1124  await usingApi(async (api) => {11251126    // Run the transaction1127    const tx = api.tx.unique.setPublicAccessMode(collectionId, accessMode);1128    const events = await submitTransactionAsync(sender, tx);1129    const result = getGenericResult(events);11301131    // Get the collection1132    const collection = await queryCollectionExpectSuccess(api, collectionId);11331134    // What to expect1135    // tslint:disable-next-line:no-unused-expression1136    expect(result.success).to.be.true;1137    expect(collection.access.toHuman()).to.be.equal(accessMode);1138  });1139}11401141export async function setPublicAccessModeExpectFail(1142  sender: IKeyringPair, collectionId: number,1143  accessMode: 'Normal' | 'AllowList',1144) {1145  await usingApi(async (api) => {11461147    // Run the transaction1148    const tx = api.tx.unique.setPublicAccessMode(collectionId, accessMode);1149    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1150    const result = getGenericResult(events);11511152    // What to expect1153    // tslint:disable-next-line:no-unused-expression1154    expect(result.success).to.be.false;1155  });1156}11571158export async function enableAllowListExpectSuccess(sender: IKeyringPair, collectionId: number) {1159  await setPublicAccessModeExpectSuccess(sender, collectionId, 'AllowList');1160}11611162export async function enableAllowListExpectFail(sender: IKeyringPair, collectionId: number) {1163  await setPublicAccessModeExpectFail(sender, collectionId, 'AllowList');1164}11651166export async function disableAllowListExpectSuccess(sender: IKeyringPair, collectionId: number) {1167  await setPublicAccessModeExpectSuccess(sender, collectionId, 'Normal');1168}11691170export async function setMintPermissionExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {1171  await usingApi(async (api) => {11721173    // Run the transaction1174    const tx = api.tx.unique.setMintPermission(collectionId, enabled);1175    const events = await submitTransactionAsync(sender, tx);1176    const result = getGenericResult(events);1177    expect(result.success).to.be.true;11781179    // Get the collection1180    const collection = await queryCollectionExpectSuccess(api, collectionId);11811182    expect(collection.mintMode.toHuman()).to.be.equal(enabled);1183  });1184}11851186export async function enablePublicMintingExpectSuccess(sender: IKeyringPair, collectionId: number) {1187  await setMintPermissionExpectSuccess(sender, collectionId, true);1188}11891190export async function setMintPermissionExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {1191  await usingApi(async (api) => {1192    // Run the transaction1193    const tx = api.tx.unique.setMintPermission(collectionId, enabled);1194    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1195    const result = getCreateCollectionResult(events);1196    // tslint:disable-next-line:no-unused-expression1197    expect(result.success).to.be.false;1198  });1199}12001201export async function setChainLimitsExpectFailure(sender: IKeyringPair, limits: IChainLimits) {1202  await usingApi(async (api) => {1203    // Run the transaction1204    const tx = api.tx.unique.setChainLimits(limits);1205    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1206    const result = getCreateCollectionResult(events);1207    // tslint:disable-next-line:no-unused-expression1208    expect(result.success).to.be.false;1209  });1210}12111212export async function isAllowlisted(api: ApiPromise, collectionId: number, address: string | CrossAccountId) {1213  return (await api.rpc.unique.allowed(collectionId, normalizeAccountId(address))).toJSON();1214}12151216export async function addToAllowListExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId | CrossAccountId) {1217  await usingApi(async (api) => {1218    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.false;12191220    // Run the transaction1221    const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1222    const events = await submitTransactionAsync(sender, tx);1223    const result = getGenericResult(events);1224    expect(result.success).to.be.true;12251226    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;1227  });1228}12291230export async function addToAllowListAgainExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId) {1231  await usingApi(async (api) => {12321233    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;12341235    // Run the transaction1236    const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1237    const events = await submitTransactionAsync(sender, tx);1238    const result = getGenericResult(events);1239    expect(result.success).to.be.true;12401241    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;1242  });1243}12441245export async function addToAllowListExpectFail(sender: IKeyringPair, collectionId: number, address: string | AccountId) {1246  await usingApi(async (api) => {12471248    // Run the transaction1249    const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1250    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1251    const result = getGenericResult(events);12521253    // What to expect1254    // tslint:disable-next-line:no-unused-expression1255    expect(result.success).to.be.false;1256  });1257}12581259export async function removeFromAllowListExpectSuccess(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1260  await usingApi(async (api) => {1261    // Run the transaction1262    const tx = api.tx.unique.removeFromAllowList(collectionId, normalizeAccountId(address));1263    const events = await submitTransactionAsync(sender, tx);1264    const result = getGenericResult(events);12651266    // What to expect1267    // tslint:disable-next-line:no-unused-expression1268    expect(result.success).to.be.true;1269  });1270}12711272export async function removeFromAllowListExpectFailure(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1273  await usingApi(async (api) => {1274    // Run the transaction1275    const tx = api.tx.unique.removeFromAllowList(collectionId, normalizeAccountId(address));1276    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1277    const result = getGenericResult(events);12781279    // What to expect1280    // tslint:disable-next-line:no-unused-expression1281    expect(result.success).to.be.false;1282  });1283}12841285export const getDetailedCollectionInfo = async (api: ApiPromise, collectionId: number)1286  : Promise<UpDataStructsCollection | null> => {1287  return (await api.rpc.unique.collectionById(collectionId)).unwrapOr(null);1288};12891290export const getCreatedCollectionCount = async (api: ApiPromise): Promise<number> => {1291  // set global object - collectionsCount1292  return (await api.rpc.unique.collectionStats()).created.toNumber();1293};12941295export async function queryCollectionExpectSuccess(api: ApiPromise, collectionId: number): Promise<UpDataStructsCollection> {1296  return (await api.rpc.unique.collectionById(collectionId)).unwrap();1297}12981299export async function waitNewBlocks(blocksCount = 1): Promise<void> {1300  await usingApi(async (api) => {1301    const promise = new Promise<void>(async (resolve) => {1302      const unsubscribe = await api.rpc.chain.subscribeNewHeads(() => {1303        if (blocksCount > 0) {1304          blocksCount--;1305        } else {1306          unsubscribe();1307          resolve();1308        }1309      });1310    });1311    return promise;1312  });1313}
after · tests/src/util/helpers.ts
1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617import '../interfaces/augment-api-rpc';18import '../interfaces/augment-api-query';19import {ApiPromise, Keyring} from '@polkadot/api';20import type {AccountId, EventRecord} from '@polkadot/types/interfaces';21import {IKeyringPair} from '@polkadot/types/types';22import {evmToAddress} from '@polkadot/util-crypto';23import BN from 'bn.js';24import chai from 'chai';25import chaiAsPromised from 'chai-as-promised';26import {alicesPublicKey} from '../accounts';27import privateKey from '../substrate/privateKey';28import {default as usingApi, submitTransactionAsync, submitTransactionExpectFailAsync} from '../substrate/substrate-api';29import {hexToStr, strToUTF16, utf16ToStr} from './util';30import {UpDataStructsCollection} from '@polkadot/types/lookup';3132chai.use(chaiAsPromised);33const expect = chai.expect;3435export type CrossAccountId = {36  Substrate: string,37} | {38  Ethereum: string,39};4041export function normalizeAccountId(input: string | AccountId | CrossAccountId | IKeyringPair): CrossAccountId {42  if (typeof input === 'string') {43    if (input.length === 48 || input.length === 47) {44      return {Substrate: input};45    } else if (input.length === 42 && input.startsWith('0x')) {46      return {Ethereum: input.toLowerCase()};47    } else if (input.length === 40 && !input.startsWith('0x')) {48      return {Ethereum: '0x' + input.toLowerCase()};49    } else {50      throw new Error(`Unknown address format: "${input}"`);51    }52  }53  if ('address' in input) {54    return {Substrate: input.address};55  }56  if ('Ethereum' in input) {57    return {58      Ethereum: input.Ethereum.toLowerCase(),59    };60  } else if ('ethereum' in input) {61    return {62      Ethereum: (input as any).ethereum.toLowerCase(),63    };64  } else if ('Substrate' in input) {65    return input;66  } else if ('substrate' in input) {67    return {68      Substrate: (input as any).substrate,69    };70  }7172  // AccountId73  return {Substrate: input.toString()};74}75export function toSubstrateAddress(input: string | CrossAccountId | IKeyringPair): string {76  input = normalizeAccountId(input);77  if ('Substrate' in input) {78    return input.Substrate;79  } else {80    return evmToAddress(input.Ethereum);81  }82}8384export const U128_MAX = (1n << 128n) - 1n;8586const MICROUNIQUE = 1_000_000_000_000n;87const MILLIUNIQUE = 1_000n * MICROUNIQUE;88const CENTIUNIQUE = 10n * MILLIUNIQUE;89export const UNIQUE = 100n * CENTIUNIQUE;9091type GenericResult = {92  success: boolean,93};9495interface CreateCollectionResult {96  success: boolean;97  collectionId: number;98}99100interface CreateItemResult {101  success: boolean;102  collectionId: number;103  itemId: number;104  recipient?: CrossAccountId;105}106107interface TransferResult {108  success: boolean;109  collectionId: number;110  itemId: number;111  sender?: CrossAccountId;112  recipient?: CrossAccountId;113  value: bigint;114}115116interface IReFungibleOwner {117  fraction: BN;118  owner: number[];119}120121interface IGetMessage {122  checkMsgUnqMethod: string;123  checkMsgTrsMethod: string;124  checkMsgSysMethod: string;125}126127export interface IFungibleTokenDataType {128  value: number;129}130131export interface IChainLimits {132  collectionNumbersLimit: number;133  accountTokenOwnershipLimit: number;134  collectionsAdminsLimit: number;135  customDataLimit: number;136  nftSponsorTransferTimeout: number;137  fungibleSponsorTransferTimeout: number;138  refungibleSponsorTransferTimeout: number;139  offchainSchemaLimit: number;140  variableOnChainSchemaLimit: number;141  constOnChainSchemaLimit: number;142}143144export interface IReFungibleTokenDataType {145  owner: IReFungibleOwner[];146  constData: number[];147  variableData: number[];148}149150export function uniqueEventMessage(events: EventRecord[]): IGetMessage {151  let checkMsgUnqMethod = '';152  let checkMsgTrsMethod = '';153  let checkMsgSysMethod = '';154  events.forEach(({event: {method, section}}) => {155    if (section === 'common') {156      checkMsgUnqMethod = method;157    } else if (section === 'treasury') {158      checkMsgTrsMethod = method;159    } else if (section === 'system') {160      checkMsgSysMethod = method;161    } else { return null; }162  });163  const result: IGetMessage = {164    checkMsgUnqMethod,165    checkMsgTrsMethod,166    checkMsgSysMethod,167  };168  return result;169}170171export function getGenericResult(events: EventRecord[]): GenericResult {172  const result: GenericResult = {173    success: false,174  };175  events.forEach(({event: {method}}) => {176    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);177    if (method === 'ExtrinsicSuccess') {178      result.success = true;179    }180  });181  return result;182}183184185186export function getCreateCollectionResult(events: EventRecord[]): CreateCollectionResult {187  let success = false;188  let collectionId = 0;189  events.forEach(({event: {data, method, section}}) => {190    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);191    if (method == 'ExtrinsicSuccess') {192      success = true;193    } else if ((section == 'common') && (method == 'CollectionCreated')) {194      collectionId = parseInt(data[0].toString(), 10);195    }196  });197  const result: CreateCollectionResult = {198    success,199    collectionId,200  };201  return result;202}203204export function getCreateItemResult(events: EventRecord[]): CreateItemResult {205  let success = false;206  let collectionId = 0;207  let itemId = 0;208  let recipient;209  events.forEach(({event: {data, method, section}}) => {210    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);211    if (method == 'ExtrinsicSuccess') {212      success = true;213    } else if ((section == 'common') && (method == 'ItemCreated')) {214      collectionId = parseInt(data[0].toString(), 10);215      itemId = parseInt(data[1].toString(), 10);216      recipient = normalizeAccountId(data[2].toJSON() as any);217    }218  });219  const result: CreateItemResult = {220    success,221    collectionId,222    itemId,223    recipient,224  };225  return result;226}227228export function getTransferResult(events: EventRecord[]): TransferResult {229  const result: TransferResult = {230    success: false,231    collectionId: 0,232    itemId: 0,233    value: 0n,234  };235236  events.forEach(({event: {data, method, section}}) => {237    if (method === 'ExtrinsicSuccess') {238      result.success = true;239    } else if (section === 'common' && method === 'Transfer') {240      result.collectionId = +data[0].toString();241      result.itemId = +data[1].toString();242      result.sender = normalizeAccountId(data[2].toJSON() as any);243      result.recipient = normalizeAccountId(data[3].toJSON() as any);244      result.value = BigInt(data[4].toString());245    }246  });247248  return result;249}250251interface Nft {252  type: 'NFT';253}254255interface Fungible {256  type: 'Fungible';257  decimalPoints: number;258}259260interface ReFungible {261  type: 'ReFungible';262}263264type CollectionMode = Nft | Fungible | ReFungible;265266export type CreateCollectionParams = {267  mode: CollectionMode,268  name: string,269  description: string,270  tokenPrefix: string,271};272273const defaultCreateCollectionParams: CreateCollectionParams = {274  description: 'description',275  mode: {type: 'NFT'},276  name: 'name',277  tokenPrefix: 'prefix',278};279280export async function createCollectionExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {281  const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};282283  let collectionId = 0;284  await usingApi(async (api) => {285    // Get number of collections before the transaction286    const collectionCountBefore = await getCreatedCollectionCount(api);287288    // Run the CreateCollection transaction289    const alicePrivateKey = privateKey('//Alice');290291    let modeprm = {};292    if (mode.type === 'NFT') {293      modeprm = {nft: null};294    } else if (mode.type === 'Fungible') {295      modeprm = {fungible: mode.decimalPoints};296    } else if (mode.type === 'ReFungible') {297      modeprm = {refungible: null};298    }299300    const tx = api.tx.unique.createCollectionEx({name: strToUTF16(name), description: strToUTF16(description), tokenPrefix: strToUTF16(tokenPrefix), mode: modeprm as any});301    const events = await submitTransactionAsync(alicePrivateKey, tx);302    const result = getCreateCollectionResult(events);303304    // Get number of collections after the transaction305    const collectionCountAfter = await getCreatedCollectionCount(api);306307    // Get the collection308    const collection = await queryCollectionExpectSuccess(api, result.collectionId);309310    // What to expect311    // tslint:disable-next-line:no-unused-expression312    expect(result.success).to.be.true;313    expect(result.collectionId).to.be.equal(collectionCountAfter);314    // tslint:disable-next-line:no-unused-expression315    expect(collection).to.be.not.null;316    expect(collectionCountAfter).to.be.equal(collectionCountBefore + 1, 'Error: NFT collection NOT created.');317    expect(collection.owner.toString()).to.be.equal(toSubstrateAddress(alicesPublicKey));318    expect(utf16ToStr(collection.name.toJSON() as any)).to.be.equal(name);319    expect(utf16ToStr(collection.description.toJSON() as any)).to.be.equal(description);320    expect(hexToStr(collection.tokenPrefix.toJSON())).to.be.equal(tokenPrefix);321322    collectionId = result.collectionId;323  });324325  return collectionId;326}327328export async function createCollectionExpectFailure(params: Partial<CreateCollectionParams> = {}) {329  const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};330331  let modeprm = {};332  if (mode.type === 'NFT') {333    modeprm = {nft: null};334  } else if (mode.type === 'Fungible') {335    modeprm = {fungible: mode.decimalPoints};336  } else if (mode.type === 'ReFungible') {337    modeprm = {refungible: null};338  }339340  await usingApi(async (api) => {341    // Get number of collections before the transaction342    const collectionCountBefore = await getCreatedCollectionCount(api);343344    // Run the CreateCollection transaction345    const alicePrivateKey = privateKey('//Alice');346    const tx = api.tx.unique.createCollectionEx({name: strToUTF16(name), description: strToUTF16(description), tokenPrefix: strToUTF16(tokenPrefix), mode: modeprm as any});347    const events = await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;348    const result = getCreateCollectionResult(events);349350    // Get number of collections after the transaction351    const collectionCountAfter = await getCreatedCollectionCount(api);352353    // What to expect354    // tslint:disable-next-line:no-unused-expression355    expect(result.success).to.be.false;356    expect(collectionCountAfter).to.be.equal(collectionCountBefore, 'Error: Collection with incorrect data created.');357  });358}359360export async function findUnusedAddress(api: ApiPromise, seedAddition = ''): Promise<IKeyringPair> {361  let bal = 0n;362  let unused;363  do {364    const randomSeed = 'seed' + Math.floor(Math.random() * Math.floor(10000)) + seedAddition;365    const keyring = new Keyring({type: 'sr25519'});366    unused = keyring.addFromUri(`//${randomSeed}`);367    bal = (await api.query.system.account(unused.address)).data.free.toBigInt();368  } while (bal !== 0n);369  return unused;370}371372export async function getAllowance(api: ApiPromise, collectionId: number, owner: CrossAccountId | string, approved: CrossAccountId | string, tokenId: number) {373  return (await api.rpc.unique.allowance(collectionId, normalizeAccountId(owner), normalizeAccountId(approved), tokenId)).toBigInt();374}375376export function findUnusedAddresses(api: ApiPromise, amount: number): Promise<IKeyringPair[]> {377  return Promise.all(new Array(amount).fill(null).map(() => findUnusedAddress(api, '_' + Date.now())));378}379380export async function findNotExistingCollection(api: ApiPromise): Promise<number> {381  const totalNumber = await getCreatedCollectionCount(api);382  const newCollection: number = totalNumber + 1;383  return newCollection;384}385386function getDestroyResult(events: EventRecord[]): boolean {387  let success = false;388  events.forEach(({event: {method}}) => {389    if (method == 'ExtrinsicSuccess') {390      success = true;391    }392  });393  return success;394}395396export async function destroyCollectionExpectFailure(collectionId: number, senderSeed = '//Alice') {397  await usingApi(async (api) => {398    // Run the DestroyCollection transaction399    const alicePrivateKey = privateKey(senderSeed);400    const tx = api.tx.unique.destroyCollection(collectionId);401    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;402  });403}404405export async function destroyCollectionExpectSuccess(collectionId: number, senderSeed = '//Alice') {406  await usingApi(async (api) => {407    // Run the DestroyCollection transaction408    const alicePrivateKey = privateKey(senderSeed);409    const tx = api.tx.unique.destroyCollection(collectionId);410    const events = await submitTransactionAsync(alicePrivateKey, tx);411    const result = getDestroyResult(events);412    expect(result).to.be.true;413414    // What to expect415    expect(await getDetailedCollectionInfo(api, collectionId)).to.be.null;416  });417}418419export async function setCollectionLimitsExpectSuccess(sender: IKeyringPair, collectionId: number, limits: any) {420  await usingApi(async (api) => {421    const tx = api.tx.unique.setCollectionLimits(collectionId, limits);422    const events = await submitTransactionAsync(sender, tx);423    const result = getGenericResult(events);424425    expect(result.success).to.be.true;426  });427}428429export async function setCollectionLimitsExpectFailure(sender: IKeyringPair, collectionId: number, limits: any) {430  await usingApi(async (api) => {431    const tx = api.tx.unique.setCollectionLimits(collectionId, limits);432    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;433    const result = getGenericResult(events);434435    expect(result.success).to.be.false;436  });437}438439export async function setCollectionSponsorExpectSuccess(collectionId: number, sponsor: string, sender = '//Alice') {440  await usingApi(async (api) => {441442    // Run the transaction443    const senderPrivateKey = privateKey(sender);444    const tx = api.tx.unique.setCollectionSponsor(collectionId, sponsor);445    const events = await submitTransactionAsync(senderPrivateKey, tx);446    const result = getGenericResult(events);447448    // Get the collection449    const collection = await queryCollectionExpectSuccess(api, collectionId);450451    // What to expect452    expect(result.success).to.be.true;453    expect(collection.sponsorship.toJSON()).to.deep.equal({454      unconfirmed: sponsor,455    });456  });457}458459export async function removeCollectionSponsorExpectSuccess(collectionId: number, sender = '//Alice') {460  await usingApi(async (api) => {461462    // Run the transaction463    const alicePrivateKey = privateKey(sender);464    const tx = api.tx.unique.removeCollectionSponsor(collectionId);465    const events = await submitTransactionAsync(alicePrivateKey, tx);466    const result = getGenericResult(events);467468    // Get the collection469    const collection = await queryCollectionExpectSuccess(api, collectionId);470471    // What to expect472    expect(result.success).to.be.true;473    expect(collection.sponsorship.toJSON()).to.be.deep.equal({disabled: null});474  });475}476477export async function removeCollectionSponsorExpectFailure(collectionId: number, senderSeed = '//Alice') {478  await usingApi(async (api) => {479480    // Run the transaction481    const alicePrivateKey = privateKey(senderSeed);482    const tx = api.tx.unique.removeCollectionSponsor(collectionId);483    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;484  });485}486487export async function setCollectionSponsorExpectFailure(collectionId: number, sponsor: string, senderSeed = '//Alice') {488  await usingApi(async (api) => {489490    // Run the transaction491    const alicePrivateKey = privateKey(senderSeed);492    const tx = api.tx.unique.setCollectionSponsor(collectionId, sponsor);493    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;494  });495}496497export async function confirmSponsorshipExpectSuccess(collectionId: number, senderSeed = '//Alice') {498  await usingApi(async () => {499    const sender = privateKey(senderSeed);500    await confirmSponsorshipByKeyExpectSuccess(collectionId, sender);501  });502}503504export async function confirmSponsorshipByKeyExpectSuccess(collectionId: number, sender: IKeyringPair) {505  await usingApi(async (api) => {506507    // Run the transaction508    const tx = api.tx.unique.confirmSponsorship(collectionId);509    const events = await submitTransactionAsync(sender, tx);510    const result = getGenericResult(events);511512    // Get the collection513    const collection = await queryCollectionExpectSuccess(api, collectionId);514515    // What to expect516    expect(result.success).to.be.true;517    expect(collection.sponsorship.toJSON()).to.be.deep.equal({518      confirmed: sender.address,519    });520  });521}522523524export async function confirmSponsorshipExpectFailure(collectionId: number, senderSeed = '//Alice') {525  await usingApi(async (api) => {526527    // Run the transaction528    const sender = privateKey(senderSeed);529    const tx = api.tx.unique.confirmSponsorship(collectionId);530    await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;531  });532}533534export async function setMetadataUpdatePermissionFlagExpectSuccess(sender: IKeyringPair, collectionId: number, flag: string) {535536  await usingApi(async (api) => {537    const tx = api.tx.unique.setMetaUpdatePermissionFlag(collectionId, flag as any);538    const events = await submitTransactionAsync(sender, tx);539    const result = getGenericResult(events);540541    expect(result.success).to.be.true;542  });543}544545export async function setMetadataUpdatePermissionFlagExpectFailure(sender: IKeyringPair, collectionId: number, flag: string) {546547  await usingApi(async (api) => {548    const tx = api.tx.unique.setMetaUpdatePermissionFlag(collectionId, flag as any);549    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;550    const result = getGenericResult(events);551552    expect(result.success).to.be.false;553  });554}555556export async function enableContractSponsoringExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {557  await usingApi(async (api) => {558    const tx = api.tx.unique.enableContractSponsoring(contractAddress, enable);559    const events = await submitTransactionAsync(sender, tx);560    const result = getGenericResult(events);561562    expect(result.success).to.be.true;563  });564}565566export async function enableContractSponsoringExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {567  await usingApi(async (api) => {568    const tx = api.tx.unique.enableContractSponsoring(contractAddress, enable);569    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;570    const result = getGenericResult(events);571572    expect(result.success).to.be.false;573  });574}575576export async function setTransferFlagExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {577578  await usingApi(async (api) => {579580    const tx = api.tx.unique.setTransfersEnabledFlag(collectionId, enabled);581    const events = await submitTransactionAsync(sender, tx);582    const result = getGenericResult(events);583584    expect(result.success).to.be.true;585  });586}587588export async function setTransferFlagExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {589590  await usingApi(async (api) => {591592    const tx = api.tx.unique.setTransfersEnabledFlag(collectionId, enabled);593    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;594    const result = getGenericResult(events);595596    expect(result.success).to.be.false;597  });598}599600export async function setContractSponsoringRateLimitExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {601  await usingApi(async (api) => {602    const tx = api.tx.unique.setContractSponsoringRateLimit(contractAddress, rateLimit);603    const events = await submitTransactionAsync(sender, tx);604    const result = getGenericResult(events);605606    expect(result.success).to.be.true;607  });608}609610export async function setContractSponsoringRateLimitExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {611  await usingApi(async (api) => {612    const tx = api.tx.unique.setContractSponsoringRateLimit(contractAddress, rateLimit);613    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;614    const result = getGenericResult(events);615616    expect(result.success).to.be.false;617  });618}619620export async function toggleContractAllowlistExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, value = true) {621  await usingApi(async (api) => {622    const tx = api.tx.unique.toggleContractAllowList(contractAddress, value);623    const events = await submitTransactionAsync(sender, tx);624    const result = getGenericResult(events);625626    expect(result.success).to.be.true;627  });628}629630export async function isAllowlistedInContract(contractAddress: AccountId | string, user: string) {631  let allowlisted = false;632  await usingApi(async (api) => {633    allowlisted = (await api.query.unique.contractAllowList(contractAddress, user)).toJSON() as boolean;634  });635  return allowlisted;636}637638export async function addToContractAllowListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {639  await usingApi(async (api) => {640    const tx = api.tx.unique.addToContractAllowList(contractAddress.toString(), user.toString());641    const events = await submitTransactionAsync(sender, tx);642    const result = getGenericResult(events);643644    expect(result.success).to.be.true;645  });646}647648export async function removeFromContractAllowListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {649  await usingApi(async (api) => {650    const tx = api.tx.unique.removeFromContractAllowList(contractAddress.toString(), user.toString());651    const events = await submitTransactionAsync(sender, tx);652    const result = getGenericResult(events);653654    expect(result.success).to.be.true;655  });656}657658export async function removeFromContractAllowListExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {659  await usingApi(async (api) => {660    const tx = api.tx.unique.removeFromContractAllowList(contractAddress.toString(), user.toString());661    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;662    const result = getGenericResult(events);663664    expect(result.success).to.be.false;665  });666}667668export async function setVariableMetaDataExpectSuccess(sender: IKeyringPair, collectionId: number, itemId: number, data: number[]) {669  await usingApi(async (api) => {670    const tx = api.tx.unique.setVariableMetaData(collectionId, itemId, '0x' + Buffer.from(data).toString('hex'));671    const events = await submitTransactionAsync(sender, tx);672    const result = getGenericResult(events);673674    expect(result.success).to.be.true;675  });676}677678export async function setVariableMetaDataExpectFailure(sender: IKeyringPair, collectionId: number, itemId: number, data: number[]) {679  await usingApi(async (api) => {680    const tx = api.tx.unique.setVariableMetaData(collectionId, itemId, '0x' + Buffer.from(data).toString('hex'));681    await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;682  });683}684685export async function setOffchainSchemaExpectSuccess(sender: IKeyringPair, collectionId: number, data: number[]) {686  await usingApi(async (api) => {687    const tx = api.tx.unique.setOffchainSchema(collectionId, '0x' + Buffer.from(data).toString('hex'));688    const events = await submitTransactionAsync(sender, tx);689    const result = getGenericResult(events);690691    expect(result.success).to.be.true;692  });693}694695export async function setOffchainSchemaExpectFailure(sender: IKeyringPair, collectionId: number, data: number[]) {696  await usingApi(async (api) => {697    const tx = api.tx.unique.setOffchainSchema(collectionId, '0x' + Buffer.from(data).toString('hex'));698    await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;699  });700}701702export interface CreateFungibleData {703  readonly Value: bigint;704}705706export interface CreateReFungibleData { }707export interface CreateNftData { }708709export type CreateItemData = {710  NFT: CreateNftData;711} | {712  Fungible: CreateFungibleData;713} | {714  ReFungible: CreateReFungibleData;715};716717export async function burnItemExpectSuccess(sender: IKeyringPair, collectionId: number, tokenId: number, value = 1) {718  await usingApi(async (api) => {719    const balanceBefore = await getBalance(api, collectionId, normalizeAccountId(sender), tokenId);720    // if burning token by admin - use adminButnItemExpectSuccess721    expect(balanceBefore >= BigInt(value)).to.be.true;722723    const tx = api.tx.unique.burnItem(collectionId, tokenId, value);724    const events = await submitTransactionAsync(sender, tx);725    const result = getGenericResult(events);726    expect(result.success).to.be.true;727728    const balanceAfter = await getBalance(api, collectionId, normalizeAccountId(sender), tokenId);729    expect(balanceAfter + BigInt(value)).to.be.equal(balanceBefore);730  });731}732733export async function734approveExpectSuccess(735  collectionId: number,736  tokenId: number, owner: IKeyringPair, approved: CrossAccountId | string, amount: number | bigint = 1,737) {738  await usingApi(async (api: ApiPromise) => {739    const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);740    const events = await submitTransactionAsync(owner, approveUniqueTx);741    const result = getGenericResult(events);742    expect(result.success).to.be.true;743744    expect(await getAllowance(api, collectionId, owner.address, approved, tokenId)).to.be.equal(BigInt(amount));745  });746}747748export async function adminApproveFromExpectSuccess(749  collectionId: number,750  tokenId: number, admin: IKeyringPair, owner: CrossAccountId | string, approved: CrossAccountId | string, amount: number | bigint = 1,751) {752  await usingApi(async (api: ApiPromise) => {753    const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);754    const events = await submitTransactionAsync(admin, approveUniqueTx);755    const result = getGenericResult(events);756    expect(result.success).to.be.true;757758    expect(await getAllowance(api, collectionId, owner, approved, tokenId)).to.be.equal(BigInt(amount));759  });760}761762export async function763transferFromExpectSuccess(764  collectionId: number,765  tokenId: number,766  accountApproved: IKeyringPair,767  accountFrom: IKeyringPair | CrossAccountId,768  accountTo: IKeyringPair | CrossAccountId,769  value: number | bigint = 1,770  type = 'NFT',771) {772  await usingApi(async (api: ApiPromise) => {773    const from = normalizeAccountId(accountFrom);774    const to = normalizeAccountId(accountTo);775    let balanceBefore = 0n;776    if (type === 'Fungible') {777      balanceBefore = await getBalance(api, collectionId, to, tokenId);778    }779    const transferFromTx = api.tx.unique.transferFrom(normalizeAccountId(accountFrom), to, collectionId, tokenId, value);780    const events = await submitTransactionAsync(accountApproved, transferFromTx);781    const result = getCreateItemResult(events);782    // tslint:disable-next-line:no-unused-expression783    expect(result.success).to.be.true;784    if (type === 'NFT') {785      expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(to);786    }787    if (type === 'Fungible') {788      const balanceAfter = await getBalance(api, collectionId, to, tokenId);789      if (JSON.stringify(to) !== JSON.stringify(from)) {790        expect(balanceAfter - balanceBefore).to.be.equal(BigInt(value));791      } else {792        expect(balanceAfter).to.be.equal(balanceBefore);793      }794    }795    if (type === 'ReFungible') {796      expect(await getBalance(api, collectionId, to, tokenId)).to.be.equal(BigInt(value));797    }798  });799}800801export async function802transferFromExpectFail(803  collectionId: number,804  tokenId: number,805  accountApproved: IKeyringPair,806  accountFrom: IKeyringPair,807  accountTo: IKeyringPair,808  value: number | bigint = 1,809) {810  await usingApi(async (api: ApiPromise) => {811    const transferFromTx = api.tx.unique.transferFrom(normalizeAccountId(accountFrom.address), normalizeAccountId(accountTo.address), collectionId, tokenId, value);812    const events = await expect(submitTransactionExpectFailAsync(accountApproved, transferFromTx)).to.be.rejected;813    const result = getCreateCollectionResult(events);814    // tslint:disable-next-line:no-unused-expression815    expect(result.success).to.be.false;816  });817}818819/* eslint no-async-promise-executor: "off" */820export async function getBlockNumber(api: ApiPromise): Promise<number> {821  return new Promise<number>(async (resolve) => {822    const unsubscribe = await api.rpc.chain.subscribeNewHeads((head) => {823      unsubscribe();824      resolve(head.number.toNumber());825    });826  });827}828829export async function addCollectionAdminExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | CrossAccountId) {830  await usingApi(async (api) => {831    const changeAdminTx = api.tx.unique.addCollectionAdmin(collectionId, normalizeAccountId(address));832    const events = await submitTransactionAsync(sender, changeAdminTx);833    const result = getCreateCollectionResult(events);834    expect(result.success).to.be.true;835  });836}837838export async function839getFreeBalance(account: IKeyringPair): Promise<bigint> {840  let balance = 0n;841  await usingApi(async (api) => {842    balance = BigInt((await api.query.system.account(account.address)).data.free.toString());843  });844845  return balance;846}847848export async function849scheduleExpectSuccess(850  operationTx: any,851  sender: IKeyringPair,852  blockSchedule: number,853  scheduledId: string,854  period = 1,855  repetitions = 1,856) {857  await usingApi(async (api: ApiPromise) => {858    const blockNumber: number | undefined = await getBlockNumber(api);859    const expectedBlockNumber = blockNumber + blockSchedule;860861    expect(blockNumber).to.be.greaterThan(0);862    const scheduleTx = api.tx.scheduler.scheduleNamed( // schedule863      scheduledId,864      expectedBlockNumber, 865      repetitions > 1 ? [period, repetitions] : null, 866      0, 867      {value: operationTx as any},868    );869870    const events = await submitTransactionAsync(sender, scheduleTx);871    expect(getGenericResult(events).success).to.be.true;872  });873}874875export async function876scheduleExpectFailure(877  operationTx: any,878  sender: IKeyringPair,879  blockSchedule: number,880  scheduledId: string,881  period = 1,882  repetitions = 1,883) {884  await usingApi(async (api: ApiPromise) => {885    const blockNumber: number | undefined = await getBlockNumber(api);886    const expectedBlockNumber = blockNumber + blockSchedule;887888    expect(blockNumber).to.be.greaterThan(0);889    const scheduleTx = api.tx.scheduler.scheduleNamed( // schedule890      scheduledId,891      expectedBlockNumber, 892      repetitions <= 1 ? null : [period, repetitions], 893      0, 894      {value: operationTx as any},895    );896897    //const events = 898    await expect(submitTransactionExpectFailAsync(sender, scheduleTx)).to.be.rejected;899    //expect(getGenericResult(events).success).to.be.false;900  });901}902903export async function904scheduleTransferAndWaitExpectSuccess(905  collectionId: number,906  tokenId: number,907  sender: IKeyringPair,908  recipient: IKeyringPair,909  value: number | bigint = 1,910  blockSchedule: number,911  scheduledId: string,912) {913  await usingApi(async (api: ApiPromise) => {914    await scheduleTransferExpectSuccess(collectionId, tokenId, sender, recipient, value, blockSchedule, scheduledId);915916    const recipientBalanceBefore = (await api.query.system.account(recipient.address)).data.free.toBigInt();917918    // sleep for n + 1 blocks919    await waitNewBlocks(blockSchedule + 1);920921    const recipientBalanceAfter = (await api.query.system.account(recipient.address)).data.free.toBigInt();922923    expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(recipient.address));924    expect(recipientBalanceAfter).to.be.equal(recipientBalanceBefore);925  });926}927928export async function929scheduleTransferExpectSuccess(930  collectionId: number,931  tokenId: number,932  sender: IKeyringPair,933  recipient: IKeyringPair,934  value: number | bigint = 1,935  blockSchedule: number,936  scheduledId: string,937) {938  await usingApi(async (api: ApiPromise) => {939    const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient.address), collectionId, tokenId, value);940941    await scheduleExpectSuccess(transferTx, sender, blockSchedule, scheduledId);942943    expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(sender.address));944  });945}946947export async function948scheduleTransferFundsPeriodicExpectSuccess(949  amount: bigint,950  sender: IKeyringPair,951  recipient: IKeyringPair,952  blockSchedule: number,953  scheduledId: string,954  period: number,955  repetitions: number,956) {957  await usingApi(async (api: ApiPromise) => {958    const transferTx = api.tx.balances.transfer(recipient.address, amount);959960    const balanceBefore = await getFreeBalance(recipient);961    962    await scheduleExpectSuccess(transferTx, sender, blockSchedule, scheduledId, period, repetitions);963964    expect(await getFreeBalance(recipient)).to.be.equal(balanceBefore);965  });966}967968export async function969transferExpectSuccess(970  collectionId: number,971  tokenId: number,972  sender: IKeyringPair,973  recipient: IKeyringPair | CrossAccountId,974  value: number | bigint = 1,975  type = 'NFT',976) {977  await usingApi(async (api: ApiPromise) => {978    const from = normalizeAccountId(sender);979    const to = normalizeAccountId(recipient);980981    let balanceBefore = 0n;982    if (type === 'Fungible') {983      balanceBefore = await getBalance(api, collectionId, to, tokenId);984    }985    const transferTx = api.tx.unique.transfer(to, collectionId, tokenId, value);986    const events = await submitTransactionAsync(sender, transferTx);987    const result = getTransferResult(events);988    // tslint:disable-next-line:no-unused-expression989    expect(result.success).to.be.true;990    expect(result.collectionId).to.be.equal(collectionId);991    expect(result.itemId).to.be.equal(tokenId);992    expect(result.sender).to.be.deep.equal(normalizeAccountId(sender.address));993    expect(result.recipient).to.be.deep.equal(to);994    expect(result.value).to.be.equal(BigInt(value));995    if (type === 'NFT') {996      expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(to);997    }998    if (type === 'Fungible') {999      const balanceAfter = await getBalance(api, collectionId, to, tokenId);1000      if (JSON.stringify(to) !== JSON.stringify(from)) {1001        expect(balanceAfter - balanceBefore).to.be.equal(BigInt(value));1002      } else {1003        expect(balanceAfter).to.be.equal(balanceBefore);1004      }1005    }1006    if (type === 'ReFungible') {1007      expect(await getBalance(api, collectionId, to, tokenId) >= value).to.be.true;1008    }1009  });1010}10111012export async function1013transferExpectFailure(1014  collectionId: number,1015  tokenId: number,1016  sender: IKeyringPair,1017  recipient: IKeyringPair,1018  value: number | bigint = 1,1019) {1020  await usingApi(async (api: ApiPromise) => {1021    const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient.address), collectionId, tokenId, value);1022    const events = await expect(submitTransactionExpectFailAsync(sender, transferTx)).to.be.rejected;1023    const result = getGenericResult(events);1024    // if (events && Array.isArray(events)) {1025    //   const result = getCreateCollectionResult(events);1026    // tslint:disable-next-line:no-unused-expression1027    expect(result.success).to.be.false;1028    //}1029  });1030}10311032export async function1033approveExpectFail(1034  collectionId: number,1035  tokenId: number, owner: IKeyringPair, approved: IKeyringPair, amount: number | bigint = 1,1036) {1037  await usingApi(async (api: ApiPromise) => {1038    const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved.address), collectionId, tokenId, amount);1039    const events = await expect(submitTransactionExpectFailAsync(owner, approveUniqueTx)).to.be.rejected;1040    const result = getCreateCollectionResult(events);1041    // tslint:disable-next-line:no-unused-expression1042    expect(result.success).to.be.false;1043  });1044}10451046export async function getBalance(1047  api: ApiPromise,1048  collectionId: number,1049  owner: string | CrossAccountId,1050  token: number,1051): Promise<bigint> {1052  return (await api.rpc.unique.balance(collectionId, normalizeAccountId(owner), token)).toBigInt();1053}1054export async function getTokenOwner(1055  api: ApiPromise,1056  collectionId: number,1057  token: number,1058): Promise<CrossAccountId> {1059  return normalizeAccountId((await api.rpc.unique.tokenOwner(collectionId, token)).toJSON() as any);1060}1061export async function isTokenExists(1062  api: ApiPromise,1063  collectionId: number,1064  token: number,1065): Promise<boolean> {1066  return (await api.rpc.unique.tokenExists(collectionId, token)).toJSON();1067}1068export async function getLastTokenId(1069  api: ApiPromise,1070  collectionId: number,1071): Promise<number> {1072  return (await api.rpc.unique.lastTokenId(collectionId)).toJSON();1073}1074export async function getAdminList(1075  api: ApiPromise,1076  collectionId: number,1077): Promise<string[]> {1078  return (await api.rpc.unique.adminlist(collectionId)).toHuman() as any;1079}1080export async function getVariableMetadata(1081  api: ApiPromise,1082  collectionId: number,1083  tokenId: number,1084): Promise<number[]> {1085  return [...(await api.rpc.unique.variableMetadata(collectionId, tokenId))];1086}1087export async function getConstMetadata(1088  api: ApiPromise,1089  collectionId: number,1090  tokenId: number,1091): Promise<number[]> {1092  return [...(await api.rpc.unique.constMetadata(collectionId, tokenId))];1093}10941095export async function createFungibleItemExpectSuccess(1096  sender: IKeyringPair,1097  collectionId: number,1098  data: CreateFungibleData,1099  owner: CrossAccountId | string = sender.address,1100) {1101  return await usingApi(async (api) => {1102    const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), {Fungible: data});11031104    const events = await submitTransactionAsync(sender, tx);1105    const result = getCreateItemResult(events);11061107    expect(result.success).to.be.true;1108    return result.itemId;1109  });1110}11111112export async function createItemExpectSuccess(sender: IKeyringPair, collectionId: number, createMode: string, owner: CrossAccountId | string = sender.address) {1113  let newItemId = 0;1114  await usingApi(async (api) => {1115    const to = normalizeAccountId(owner);1116    const itemCountBefore = await getLastTokenId(api, collectionId);1117    const itemBalanceBefore = await getBalance(api, collectionId, to, newItemId);11181119    let tx;1120    if (createMode === 'Fungible') {1121      const createData = {fungible: {value: 10}};1122      tx = api.tx.unique.createItem(collectionId, to, createData as any);1123    } else if (createMode === 'ReFungible') {1124      const createData = {refungible: {const_data: [], variable_data: [], pieces: 100}};1125      tx = api.tx.unique.createItem(collectionId, to, createData as any);1126    } else {1127      const createData = {nft: {const_data: [], variable_data: []}};1128      tx = api.tx.unique.createItem(collectionId, to, createData as any);1129    }11301131    const events = await submitTransactionAsync(sender, tx);1132    const result = getCreateItemResult(events);11331134    const itemCountAfter = await getLastTokenId(api, collectionId);1135    const itemBalanceAfter = await getBalance(api, collectionId, to, newItemId);11361137    // What to expect1138    // tslint:disable-next-line:no-unused-expression1139    expect(result.success).to.be.true;1140    if (createMode === 'Fungible') {1141      expect(itemBalanceAfter - itemBalanceBefore).to.be.equal(10n);1142    } else {1143      expect(itemCountAfter).to.be.equal(itemCountBefore + 1);1144    }1145    expect(collectionId).to.be.equal(result.collectionId);1146    expect(itemCountAfter.toString()).to.be.equal(result.itemId.toString());1147    expect(to).to.be.deep.equal(result.recipient);1148    newItemId = result.itemId;1149  });1150  return newItemId;1151}11521153export async function createItemExpectFailure(sender: IKeyringPair, collectionId: number, createMode: string, owner: string = sender.address) {1154  await usingApi(async (api) => {1155    const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), createMode);11561157    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1158    const result = getCreateItemResult(events);11591160    expect(result.success).to.be.false;1161  });1162}11631164export async function setPublicAccessModeExpectSuccess(1165  sender: IKeyringPair, collectionId: number,1166  accessMode: 'Normal' | 'AllowList',1167) {1168  await usingApi(async (api) => {11691170    // Run the transaction1171    const tx = api.tx.unique.setPublicAccessMode(collectionId, accessMode);1172    const events = await submitTransactionAsync(sender, tx);1173    const result = getGenericResult(events);11741175    // Get the collection1176    const collection = await queryCollectionExpectSuccess(api, collectionId);11771178    // What to expect1179    // tslint:disable-next-line:no-unused-expression1180    expect(result.success).to.be.true;1181    expect(collection.access.toHuman()).to.be.equal(accessMode);1182  });1183}11841185export async function setPublicAccessModeExpectFail(1186  sender: IKeyringPair, collectionId: number,1187  accessMode: 'Normal' | 'AllowList',1188) {1189  await usingApi(async (api) => {11901191    // Run the transaction1192    const tx = api.tx.unique.setPublicAccessMode(collectionId, accessMode);1193    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1194    const result = getGenericResult(events);11951196    // What to expect1197    // tslint:disable-next-line:no-unused-expression1198    expect(result.success).to.be.false;1199  });1200}12011202export async function enableAllowListExpectSuccess(sender: IKeyringPair, collectionId: number) {1203  await setPublicAccessModeExpectSuccess(sender, collectionId, 'AllowList');1204}12051206export async function enableAllowListExpectFail(sender: IKeyringPair, collectionId: number) {1207  await setPublicAccessModeExpectFail(sender, collectionId, 'AllowList');1208}12091210export async function disableAllowListExpectSuccess(sender: IKeyringPair, collectionId: number) {1211  await setPublicAccessModeExpectSuccess(sender, collectionId, 'Normal');1212}12131214export async function setMintPermissionExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {1215  await usingApi(async (api) => {12161217    // Run the transaction1218    const tx = api.tx.unique.setMintPermission(collectionId, enabled);1219    const events = await submitTransactionAsync(sender, tx);1220    const result = getGenericResult(events);1221    expect(result.success).to.be.true;12221223    // Get the collection1224    const collection = await queryCollectionExpectSuccess(api, collectionId);12251226    expect(collection.mintMode.toHuman()).to.be.equal(enabled);1227  });1228}12291230export async function enablePublicMintingExpectSuccess(sender: IKeyringPair, collectionId: number) {1231  await setMintPermissionExpectSuccess(sender, collectionId, true);1232}12331234export async function setMintPermissionExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {1235  await usingApi(async (api) => {1236    // Run the transaction1237    const tx = api.tx.unique.setMintPermission(collectionId, enabled);1238    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1239    const result = getCreateCollectionResult(events);1240    // tslint:disable-next-line:no-unused-expression1241    expect(result.success).to.be.false;1242  });1243}12441245export async function setChainLimitsExpectFailure(sender: IKeyringPair, limits: IChainLimits) {1246  await usingApi(async (api) => {1247    // Run the transaction1248    const tx = api.tx.unique.setChainLimits(limits);1249    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1250    const result = getCreateCollectionResult(events);1251    // tslint:disable-next-line:no-unused-expression1252    expect(result.success).to.be.false;1253  });1254}12551256export async function isAllowlisted(api: ApiPromise, collectionId: number, address: string | CrossAccountId) {1257  return (await api.rpc.unique.allowed(collectionId, normalizeAccountId(address))).toJSON();1258}12591260export async function addToAllowListExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId | CrossAccountId) {1261  await usingApi(async (api) => {1262    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.false;12631264    // Run the transaction1265    const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1266    const events = await submitTransactionAsync(sender, tx);1267    const result = getGenericResult(events);1268    expect(result.success).to.be.true;12691270    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;1271  });1272}12731274export async function addToAllowListAgainExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId) {1275  await usingApi(async (api) => {12761277    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;12781279    // Run the transaction1280    const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1281    const events = await submitTransactionAsync(sender, tx);1282    const result = getGenericResult(events);1283    expect(result.success).to.be.true;12841285    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;1286  });1287}12881289export async function addToAllowListExpectFail(sender: IKeyringPair, collectionId: number, address: string | AccountId) {1290  await usingApi(async (api) => {12911292    // Run the transaction1293    const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1294    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1295    const result = getGenericResult(events);12961297    // What to expect1298    // tslint:disable-next-line:no-unused-expression1299    expect(result.success).to.be.false;1300  });1301}13021303export async function removeFromAllowListExpectSuccess(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1304  await usingApi(async (api) => {1305    // Run the transaction1306    const tx = api.tx.unique.removeFromAllowList(collectionId, normalizeAccountId(address));1307    const events = await submitTransactionAsync(sender, tx);1308    const result = getGenericResult(events);13091310    // What to expect1311    // tslint:disable-next-line:no-unused-expression1312    expect(result.success).to.be.true;1313  });1314}13151316export async function removeFromAllowListExpectFailure(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1317  await usingApi(async (api) => {1318    // Run the transaction1319    const tx = api.tx.unique.removeFromAllowList(collectionId, normalizeAccountId(address));1320    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1321    const result = getGenericResult(events);13221323    // What to expect1324    // tslint:disable-next-line:no-unused-expression1325    expect(result.success).to.be.false;1326  });1327}13281329export const getDetailedCollectionInfo = async (api: ApiPromise, collectionId: number)1330  : Promise<UpDataStructsCollection | null> => {1331  return (await api.rpc.unique.collectionById(collectionId)).unwrapOr(null);1332};13331334export const getCreatedCollectionCount = async (api: ApiPromise): Promise<number> => {1335  // set global object - collectionsCount1336  return (await api.rpc.unique.collectionStats()).created.toNumber();1337};13381339export async function queryCollectionExpectSuccess(api: ApiPromise, collectionId: number): Promise<UpDataStructsCollection> {1340  return (await api.rpc.unique.collectionById(collectionId)).unwrap();1341}13421343export async function waitNewBlocks(blocksCount = 1): Promise<void> {1344  await usingApi(async (api) => {1345    const promise = new Promise<void>(async (resolve) => {1346      const unsubscribe = await api.rpc.chain.subscribeNewHeads(() => {1347        if (blocksCount > 0) {1348          blocksCount--;1349        } else {1350          unsubscribe();1351          resolve();1352        }1353      });1354    });1355    return promise;1356  });1357}