git.delta.rocks / unique-network / refs/commits / b544464f4ffd

difftreelog

feat tests requirePallets

Daniel Shiposha2022-08-03parent: #fe18d26.patch.diff
in: master

21 files changed

modifiedtests/src/rmrk/acceptNft.test.tsdiffbeforeafterboth
--- a/tests/src/rmrk/acceptNft.test.ts
+++ b/tests/src/rmrk/acceptNft.test.ts
@@ -8,13 +8,13 @@
 } from './util/tx';
 import {NftIdTuple} from './util/fetch';
 import {isNftChildOfAnother, expectTxFailure} from './util/helpers';
-import { getModuleNames, Pallets } from '../util/helpers';
+import { requirePallets, Pallets } from '../util/helpers';
 
 describe('integration test: accept NFT', () => {
   let api: any;
   before(async function() {
     api = await getApiConnection();
-    if (!getModuleNames(api).includes(Pallets.RmrkCore)) this.skip();
+    requirePallets(this, api, [Pallets.RmrkCore]);
   });
   
   
modifiedtests/src/rmrk/addResource.test.tsdiffbeforeafterboth
--- a/tests/src/rmrk/addResource.test.ts
+++ b/tests/src/rmrk/addResource.test.ts
@@ -12,7 +12,7 @@
   addNftComposableResource,
 } from './util/tx';
 import {RmrkTraitsResourceResourceInfo as ResourceInfo} from '@polkadot/types/lookup';
-import { getModuleNames, Pallets } from '../util/helpers';
+import { requirePallets, Pallets } from '../util/helpers';
 
 describe('integration test: add NFT resource', () => {
   const Alice = '//Alice';
@@ -27,7 +27,7 @@
   let api: any;
   before(async function() {
     api = await getApiConnection();
-    if (!getModuleNames(api).includes(Pallets.RmrkCore)) this.skip();
+    requirePallets(this, api, [Pallets.RmrkCore]);
   });
 
   it('add resource', async () => {
modifiedtests/src/rmrk/addTheme.test.tsdiffbeforeafterboth
--- a/tests/src/rmrk/addTheme.test.ts
+++ b/tests/src/rmrk/addTheme.test.ts
@@ -3,13 +3,13 @@
 import {createBase, addTheme} from './util/tx';
 import {expectTxFailure} from './util/helpers';
 import {getThemeNames} from './util/fetch';
-import { getModuleNames, Pallets } from '../util/helpers';
+import { requirePallets, Pallets } from '../util/helpers';
 
 describe('integration test: add Theme to Base', () => {
   let api: any;
   before(async function() {
     api = await getApiConnection();
-    if (!getModuleNames(api).includes(Pallets.RmrkCore)) this.skip();
+    requirePallets(this, api, [Pallets.RmrkEquip]);
   });
 
   const alice = '//Alice';
modifiedtests/src/rmrk/burnNft.test.tsdiffbeforeafterboth
--- a/tests/src/rmrk/burnNft.test.ts
+++ b/tests/src/rmrk/burnNft.test.ts
@@ -5,7 +5,7 @@
 
 import chai from 'chai';
 import chaiAsPromised from 'chai-as-promised';
-import { getModuleNames, Pallets } from '../util/helpers';
+import { requirePallets, Pallets } from '../util/helpers';
 
 chai.use(chaiAsPromised);
 const expect = chai.expect;
@@ -17,7 +17,7 @@
   let api: any;
   before(async function() {
     api = await getApiConnection();
-    if (!getModuleNames(api).includes(Pallets.RmrkCore)) this.skip();
+    requirePallets(this, api, [Pallets.RmrkCore]);
   });
 
 
modifiedtests/src/rmrk/changeCollectionIssuer.test.tsdiffbeforeafterboth
--- a/tests/src/rmrk/changeCollectionIssuer.test.ts
+++ b/tests/src/rmrk/changeCollectionIssuer.test.ts
@@ -1,5 +1,5 @@
 import {getApiConnection} from '../substrate/substrate-api';
-import { getModuleNames, Pallets } from '../util/helpers';
+import { requirePallets, Pallets } from '../util/helpers';
 import {expectTxFailure} from './util/helpers';
 import {
   changeIssuer,
@@ -13,7 +13,7 @@
   let api: any;
   before(async function() {
     api = await getApiConnection();
-    if (!getModuleNames(api).includes(Pallets.RmrkCore)) this.skip();
+    requirePallets(this, api, [Pallets.RmrkCore]);
   });
 
 
modifiedtests/src/rmrk/createBase.test.tsdiffbeforeafterboth
--- a/tests/src/rmrk/createBase.test.ts
+++ b/tests/src/rmrk/createBase.test.ts
@@ -1,12 +1,12 @@
 import {getApiConnection} from '../substrate/substrate-api';
-import { getModuleNames, Pallets } from '../util/helpers';
+import { requirePallets, Pallets } from '../util/helpers';
 import {createCollection, createBase} from './util/tx';
 
 describe('integration test: create new Base', () => {
   let api: any;
   before(async function() {
     api = await getApiConnection();
-    if (!getModuleNames(api).includes(Pallets.RmrkCore)) this.skip();
+    requirePallets(this, api, [Pallets.RmrkCore, Pallets.RmrkEquip]);
   });
 
   const alice = '//Alice';
modifiedtests/src/rmrk/createCollection.test.tsdiffbeforeafterboth
--- a/tests/src/rmrk/createCollection.test.ts
+++ b/tests/src/rmrk/createCollection.test.ts
@@ -1,12 +1,12 @@
 import {getApiConnection} from '../substrate/substrate-api';
-import {getModuleNames, Pallets} from '../util/helpers';
+import {requirePallets, Pallets} from '../util/helpers';
 import {createCollection} from './util/tx';
 
 describe('Integration test: create new collection', () => {
   let api: any;
   before(async function () {
     api = await getApiConnection();
-    if (!getModuleNames(api).includes(Pallets.RmrkCore)) this.skip();
+    requirePallets(this, api, [Pallets.RmrkCore]);
   });
 
 
modifiedtests/src/rmrk/deleteCollection.test.tsdiffbeforeafterboth
--- a/tests/src/rmrk/deleteCollection.test.ts
+++ b/tests/src/rmrk/deleteCollection.test.ts
@@ -1,5 +1,5 @@
 import {getApiConnection} from '../substrate/substrate-api';
-import { getModuleNames, Pallets } from '../util/helpers';
+import { requirePallets, Pallets } from '../util/helpers';
 import {expectTxFailure} from './util/helpers';
 import {createCollection, deleteCollection} from './util/tx';
 
@@ -7,7 +7,7 @@
   let api: any;
   before(async function () {
     api = await getApiConnection();
-    if (!getModuleNames(api).includes(Pallets.RmrkCore)) this.skip();
+    requirePallets(this, api, [Pallets.RmrkCore]);
   });
 
   const Alice = '//Alice';
modifiedtests/src/rmrk/equipNft.test.tsdiffbeforeafterboth
--- a/tests/src/rmrk/equipNft.test.ts
+++ b/tests/src/rmrk/equipNft.test.ts
@@ -1,7 +1,7 @@
 import {ApiPromise} from '@polkadot/api';
 import {expect} from 'chai';
 import {getApiConnection} from '../substrate/substrate-api';
-import {getModuleNames, Pallets} from '../util/helpers';
+import {requirePallets, Pallets} from '../util/helpers';
 import {getNft, getParts, NftIdTuple} from './util/fetch';
 import {expectTxFailure} from './util/helpers';
 import {
@@ -126,7 +126,7 @@
   
   before(async function () {
     api = await getApiConnection();
-    if (!getModuleNames(api).includes(Pallets.RmrkCore)) this.skip();
+    requirePallets(this, api, [Pallets.RmrkCore, Pallets.RmrkEquip]);
   });
 
   it('equip nft', async () => {
modifiedtests/src/rmrk/getOwnedNfts.test.tsdiffbeforeafterboth
--- a/tests/src/rmrk/getOwnedNfts.test.ts
+++ b/tests/src/rmrk/getOwnedNfts.test.ts
@@ -1,6 +1,6 @@
 import {expect} from 'chai';
 import {getApiConnection} from '../substrate/substrate-api';
-import { getModuleNames, Pallets } from '../util/helpers';
+import { requirePallets, Pallets } from '../util/helpers';
 import {getOwnedNfts} from './util/fetch';
 import {mintNft, createCollection} from './util/tx';
 
@@ -9,7 +9,7 @@
   
   before(async function () {
     api = await getApiConnection();
-    if (!getModuleNames(api).includes(Pallets.RmrkCore)) this.skip();
+    requirePallets(this, api, [Pallets.RmrkCore]);
   });
 
 
modifiedtests/src/rmrk/lockCollection.test.tsdiffbeforeafterboth
--- a/tests/src/rmrk/lockCollection.test.ts
+++ b/tests/src/rmrk/lockCollection.test.ts
@@ -1,5 +1,5 @@
 import {getApiConnection} from '../substrate/substrate-api';
-import { getModuleNames, Pallets } from '../util/helpers';
+import { requirePallets, Pallets } from '../util/helpers';
 import {expectTxFailure} from './util/helpers';
 import {createCollection, lockCollection, mintNft} from './util/tx';
 
@@ -11,7 +11,7 @@
   let api: any;
   before(async function () {
     api = await getApiConnection();
-    if (!getModuleNames(api).includes(Pallets.RmrkCore)) this.skip();
+    requirePallets(this, api, [Pallets.RmrkCore]);
   });
 
   it('lock collection', async () => {
modifiedtests/src/rmrk/mintNft.test.tsdiffbeforeafterboth
--- a/tests/src/rmrk/mintNft.test.ts
+++ b/tests/src/rmrk/mintNft.test.ts
@@ -1,6 +1,6 @@
 import {expect} from 'chai';
 import {getApiConnection} from '../substrate/substrate-api';
-import { getModuleNames, Pallets } from '../util/helpers';
+import { requirePallets, Pallets } from '../util/helpers';
 import {getNft} from './util/fetch';
 import {expectTxFailure} from './util/helpers';
 import {createCollection, mintNft} from './util/tx';
@@ -10,7 +10,7 @@
  
   before(async function () {
     api = await getApiConnection();
-    if (!getModuleNames(api).includes(Pallets.RmrkCore)) this.skip();
+    requirePallets(this, api, [Pallets.RmrkCore]);
   });
 
 
modifiedtests/src/rmrk/rejectNft.test.tsdiffbeforeafterboth
--- a/tests/src/rmrk/rejectNft.test.ts
+++ b/tests/src/rmrk/rejectNft.test.ts
@@ -8,13 +8,13 @@
 } from './util/tx';
 import {getChildren, NftIdTuple} from './util/fetch';
 import {isNftChildOfAnother, expectTxFailure} from './util/helpers';
-import { getModuleNames, Pallets } from '../util/helpers';
+import { requirePallets, Pallets } from '../util/helpers';
 
 describe('integration test: reject NFT', () => {
   let api: any;
   before(async function () {
     api = await getApiConnection();
-    if (!getModuleNames(api).includes(Pallets.RmrkCore)) this.skip();
+    requirePallets(this, api, [Pallets.RmrkCore]);
   });
 
 
modifiedtests/src/rmrk/removeResource.test.tsdiffbeforeafterboth
--- a/tests/src/rmrk/removeResource.test.ts
+++ b/tests/src/rmrk/removeResource.test.ts
@@ -1,7 +1,7 @@
 import {expect} from 'chai';
 import privateKey from '../substrate/privateKey';
 import {executeTransaction, getApiConnection} from '../substrate/substrate-api';
-import { getModuleNames, Pallets } from '../util/helpers';
+import { requirePallets, Pallets } from '../util/helpers';
 import {getNft, NftIdTuple} from './util/fetch';
 import {expectTxFailure} from './util/helpers';
 import {
@@ -20,7 +20,7 @@
   before(async function() {
     api = await getApiConnection();
     ss58Format = api.registry.getChainProperties()!.toJSON().ss58Format;
-    if (!getModuleNames(api).includes(Pallets.RmrkCore)) this.skip();
+    requirePallets(this, api, [Pallets.RmrkCore]);
   });
 
   const Alice = '//Alice';
modifiedtests/src/rmrk/rmrkIsolation.test.tsdiffbeforeafterboth
--- a/tests/src/rmrk/rmrkIsolation.test.ts
+++ b/tests/src/rmrk/rmrkIsolation.test.ts
@@ -6,7 +6,7 @@
   getCreateCollectionResult,
   getDetailedCollectionInfo,
   getGenericResult,
-  getModuleNames,
+  requirePallets,
   normalizeAccountId,
   Pallets,
 } from '../util/helpers';
@@ -64,7 +64,7 @@
   before(async function() {
     await usingApi(async (api, privateKeyWrapper) => {
       alice = privateKeyWrapper('//Alice');
-      if (!getModuleNames(api).includes(Pallets.RmrkCore)) this.skip();
+      requirePallets(this, api, [Pallets.RmrkCore]);
     });
   });
 
modifiedtests/src/rmrk/sendNft.test.tsdiffbeforeafterboth
--- a/tests/src/rmrk/sendNft.test.ts
+++ b/tests/src/rmrk/sendNft.test.ts
@@ -3,13 +3,13 @@
 import {createCollection, mintNft, sendNft} from './util/tx';
 import {NftIdTuple} from './util/fetch';
 import {isNftChildOfAnother, expectTxFailure} from './util/helpers';
-import { getModuleNames, Pallets } from '../util/helpers';
+import { requirePallets, Pallets } from '../util/helpers';
 
 describe('integration test: send NFT', () => {
   let api: any;
   before(async function () {
     api = await getApiConnection();
-    if (!getModuleNames(api).includes(Pallets.RmrkCore)) this.skip();
+    requirePallets(this, api, [Pallets.RmrkCore]);
   });
 
   const maxNftId = 0xFFFFFFFF;
modifiedtests/src/rmrk/setCollectionProperty.test.tsdiffbeforeafterboth
--- a/tests/src/rmrk/setCollectionProperty.test.ts
+++ b/tests/src/rmrk/setCollectionProperty.test.ts
@@ -1,5 +1,5 @@
 import {getApiConnection} from '../substrate/substrate-api';
-import { getModuleNames, Pallets } from '../util/helpers';
+import { requirePallets, Pallets } from '../util/helpers';
 import {expectTxFailure} from './util/helpers';
 import {createCollection, setPropertyCollection} from './util/tx';
 
@@ -10,7 +10,7 @@
   let api: any;
   before(async function () {
     api = await getApiConnection();
-    if (!getModuleNames(api).includes(Pallets.RmrkCore)) this.skip();
+    requirePallets(this, api, [Pallets.RmrkCore]);
   });
 
   it('set collection property', async () => {
modifiedtests/src/rmrk/setEquippableList.test.tsdiffbeforeafterboth
--- a/tests/src/rmrk/setEquippableList.test.ts
+++ b/tests/src/rmrk/setEquippableList.test.ts
@@ -1,5 +1,5 @@
 import {getApiConnection} from '../substrate/substrate-api';
-import { getModuleNames, Pallets } from '../util/helpers';
+import { requirePallets, Pallets } from '../util/helpers';
 import {expectTxFailure} from './util/helpers';
 import {createCollection, createBase, setEquippableList} from './util/tx';
 
@@ -7,7 +7,7 @@
   let api: any;
   before(async function () {
     api = await getApiConnection();
-    if (!getModuleNames(api).includes(Pallets.RmrkCore)) this.skip();
+    requirePallets(this, api, [Pallets.RmrkCore]);
   });
 
   const alice = '//Alice';
modifiedtests/src/rmrk/setNftProperty.test.tsdiffbeforeafterboth
--- a/tests/src/rmrk/setNftProperty.test.ts
+++ b/tests/src/rmrk/setNftProperty.test.ts
@@ -1,5 +1,5 @@
 import {getApiConnection} from '../substrate/substrate-api';
-import { getModuleNames, Pallets } from '../util/helpers';
+import { requirePallets, Pallets } from '../util/helpers';
 import {NftIdTuple} from './util/fetch';
 import {expectTxFailure} from './util/helpers';
 import {createCollection, mintNft, sendNft, setNftProperty} from './util/tx';
@@ -8,7 +8,7 @@
   let api: any;
   before(async function () {
     api = await getApiConnection();
-    if (!getModuleNames(api).includes(Pallets.RmrkCore)) this.skip();
+    requirePallets(this, api, [Pallets.RmrkCore]);
   });
 
   const alice = '//Alice';
modifiedtests/src/rmrk/setResourcePriorities.test.tsdiffbeforeafterboth
--- a/tests/src/rmrk/setResourcePriorities.test.ts
+++ b/tests/src/rmrk/setResourcePriorities.test.ts
@@ -1,5 +1,5 @@
 import {getApiConnection} from '../substrate/substrate-api';
-import { getModuleNames, Pallets } from '../util/helpers';
+import { requirePallets, Pallets } from '../util/helpers';
 import {expectTxFailure} from './util/helpers';
 import {mintNft, createCollection, setResourcePriorities} from './util/tx';
 
@@ -7,7 +7,7 @@
   let api: any;
   before(async function () {
     api = await getApiConnection();
-    if (!getModuleNames(api).includes(Pallets.RmrkCore)) this.skip();
+    requirePallets(this, api, [Pallets.RmrkCore]);
   });
 
   const alice = '//Alice';
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} from '@polkadot/api';20import type {AccountId, EventRecord, Event} from '@polkadot/types/interfaces';21import type {GenericEventData} from '@polkadot/types';22import {AnyTuple, IEvent, IKeyringPair} from '@polkadot/types/types';23import {evmToAddress} from '@polkadot/util-crypto';24import BN from 'bn.js';25import chai from 'chai';26import chaiAsPromised from 'chai-as-promised';27import {default as usingApi, executeTransaction, submitTransactionAsync, submitTransactionExpectFailAsync} from '../substrate/substrate-api';28import {hexToStr, strToUTF16, utf16ToStr} from './util';29import {UpDataStructsRpcCollection, UpDataStructsCreateItemData, UpDataStructsProperty} from '@polkadot/types/lookup';30import {UpDataStructsTokenChild} from '../interfaces';3132chai.use(chaiAsPromised);33const expect = chai.expect;3435export type CrossAccountId = {36  Substrate: string,37} | {38  Ethereum: string,39};404142export enum Pallets {43  Inflation = 'inflation',44  RmrkCore = 'rmrkcore',45  ReFungible = 'refungible',46  Fungible = 'fungible',47  NFT = 'nonfungible',48}4950export async function isUnique(): Promise<boolean> {51  return usingApi(async api => {52    const chain = await api.rpc.system.chain();5354    return chain.eq('UNIQUE');55  });56}5758export async function isQuartz(): Promise<boolean> {59  return usingApi(async api => {60    const chain = await api.rpc.system.chain();61    62    return chain.eq('QUARTZ');63  });64}6566let modulesNames: any;67export function getModuleNames(api: ApiPromise): string[] {68  if (typeof modulesNames === 'undefined') 69    modulesNames = api.runtimeMetadata.asLatest.pallets.map(m => m.name.toString().toLowerCase());70  return modulesNames;71}7273export function normalizeAccountId(input: string | AccountId | CrossAccountId | IKeyringPair): CrossAccountId {74  if (typeof input === 'string') {75    if (input.length >= 47) {76      return {Substrate: input};77    } else if (input.length === 42 && input.startsWith('0x')) {78      return {Ethereum: input.toLowerCase()};79    } else if (input.length === 40 && !input.startsWith('0x')) {80      return {Ethereum: '0x' + input.toLowerCase()};81    } else {82      throw new Error(`Unknown address format: "${input}"`);83    }84  }85  if ('address' in input) {86    return {Substrate: input.address};87  }88  if ('Ethereum' in input) {89    return {90      Ethereum: input.Ethereum.toLowerCase(),91    };92  } else if ('ethereum' in input) {93    return {94      Ethereum: (input as any).ethereum.toLowerCase(),95    };96  } else if ('Substrate' in input) {97    return input;98  } else if ('substrate' in input) {99    return {100      Substrate: (input as any).substrate,101    };102  }103104  // AccountId105  return {Substrate: input.toString()};106}107export function toSubstrateAddress(input: string | CrossAccountId | IKeyringPair): string {108  input = normalizeAccountId(input);109  if ('Substrate' in input) {110    return input.Substrate;111  } else {112    return evmToAddress(input.Ethereum);113  }114}115116export const U128_MAX = (1n << 128n) - 1n;117118const MICROUNIQUE = 1_000_000_000_000n;119const MILLIUNIQUE = 1_000n * MICROUNIQUE;120const CENTIUNIQUE = 10n * MILLIUNIQUE;121export const UNIQUE = 100n * CENTIUNIQUE;122123interface GenericResult<T> {124  success: boolean;125  data: T | null;126}127128interface CreateCollectionResult {129  success: boolean;130  collectionId: number;131}132133interface CreateItemResult {134  success: boolean;135  collectionId: number;136  itemId: number;137  recipient?: CrossAccountId;138  amount?: number;139}140141interface DestroyItemResult {142  success: boolean;143  collectionId: number;144  itemId: number;145  owner: CrossAccountId;146  amount: number;147}148149interface TransferResult {150  collectionId: number;151  itemId: number;152  sender?: CrossAccountId;153  recipient?: CrossAccountId;154  value: bigint;155}156157interface IReFungibleOwner {158  fraction: BN;159  owner: number[];160}161162interface IGetMessage {163  checkMsgUnqMethod: string;164  checkMsgTrsMethod: string;165  checkMsgSysMethod: string;166}167168export interface IFungibleTokenDataType {169  value: number;170}171172export interface IChainLimits {173  collectionNumbersLimit: number;174  accountTokenOwnershipLimit: number;175  collectionsAdminsLimit: number;176  customDataLimit: number;177  nftSponsorTransferTimeout: number;178  fungibleSponsorTransferTimeout: number;179  refungibleSponsorTransferTimeout: number;180  //offchainSchemaLimit: number;181  //constOnChainSchemaLimit: number;182}183184export interface IReFungibleTokenDataType {185  owner: IReFungibleOwner[];186}187188export function uniqueEventMessage(events: EventRecord[]): IGetMessage {189  let checkMsgUnqMethod = '';190  let checkMsgTrsMethod = '';191  let checkMsgSysMethod = '';192  events.forEach(({event: {method, section}}) => {193    if (section === 'common') {194      checkMsgUnqMethod = method;195    } else if (section === 'treasury') {196      checkMsgTrsMethod = method;197    } else if (section === 'system') {198      checkMsgSysMethod = method;199    } else { return null; }200  });201  const result: IGetMessage = {202    checkMsgUnqMethod,203    checkMsgTrsMethod,204    checkMsgSysMethod,205  };206  return result;207}208209export function getEvent<T extends Event>(events: EventRecord[], check: (event: IEvent<AnyTuple>) => event is T): T | undefined {210  const event = events.find(r => check(r.event));211  if (!event) return;212  return event.event as T;213}214215export function getGenericResult<T>(events: EventRecord[]): GenericResult<T>;216export function getGenericResult<T>(217  events: EventRecord[],218  expectSection: string,219  expectMethod: string,220  extractAction: (data: GenericEventData) => T221): GenericResult<T>;222223export function getGenericResult<T>(224  events: EventRecord[],225  expectSection?: string,226  expectMethod?: string,227  extractAction?: (data: GenericEventData) => T,228): GenericResult<T> {229  let success = false;230  let successData = null;231232  events.forEach(({event: {data, method, section}}) => {233    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);234    if (method === 'ExtrinsicSuccess') {235      success = true;236    } else if ((expectSection == section) && (expectMethod == method)) {237      successData = extractAction!(data as any);238    }239  });240241  const result: GenericResult<T> = {242    success,243    data: successData,244  };245  return result;246}247248export function getCreateCollectionResult(events: EventRecord[]): CreateCollectionResult {249  const genericResult = getGenericResult(events, 'common', 'CollectionCreated', (data) => parseInt(data[0].toString(), 10));250  const result: CreateCollectionResult = {251    success: genericResult.success,252    collectionId: genericResult.data ?? 0,253  };254  return result;255}256257export function getCreateItemsResult(events: EventRecord[]): CreateItemResult[] {258  const results: CreateItemResult[] = [];259  260  const genericResult = getGenericResult<CreateItemResult[]>(events, 'common', 'ItemCreated', (data) => {261    const collectionId = parseInt(data[0].toString(), 10);262    const itemId = parseInt(data[1].toString(), 10);263    const recipient = normalizeAccountId(data[2].toJSON() as any);264    const amount = parseInt(data[3].toString(), 10);265266    const itemRes: CreateItemResult = {267      success: true,268      collectionId,269      itemId,270      recipient,271      amount,272    };273274    results.push(itemRes);275    return results;276  });277278  if (!genericResult.success) return [];279  return results;280}281282export function getCreateItemResult(events: EventRecord[]): CreateItemResult {283  const genericResult = getGenericResult(events, 'common', 'ItemCreated', (data) => data.map(function(value) { return value.toJSON(); }));284  285  if (genericResult.data == null) 286    return {287      success: genericResult.success,288      collectionId: 0,289      itemId: 0,290      amount: 0,291    };292  else 293    return {294      success: genericResult.success,295      collectionId: genericResult.data[0] as number,296      itemId: genericResult.data[1] as number,297      recipient: normalizeAccountId(genericResult.data![2] as any),298      amount: genericResult.data[3] as number,299    };300}301302export function getDestroyItemsResult(events: EventRecord[]): DestroyItemResult[] {303  const results: DestroyItemResult[] = [];304  305  const genericResult = getGenericResult<DestroyItemResult[]>(events, 'common', 'ItemDestroyed', (data) => {306    const collectionId = parseInt(data[0].toString(), 10);307    const itemId = parseInt(data[1].toString(), 10);308    const owner = normalizeAccountId(data[2].toJSON() as any);309    const amount = parseInt(data[3].toString(), 10);310311    const itemRes: DestroyItemResult = {312      success: true,313      collectionId,314      itemId,315      owner,316      amount,317    };318319    results.push(itemRes);320    return results;321  });322323  if (!genericResult.success) return [];324  return results;325}326327export function getTransferResult(api: ApiPromise, events: EventRecord[]): TransferResult {328  for (const {event} of events) {329    if (api.events.common.Transfer.is(event)) {330      const [collection, token, sender, recipient, value] = event.data;331      return {332        collectionId: collection.toNumber(),333        itemId: token.toNumber(),334        sender: normalizeAccountId(sender.toJSON() as any),335        recipient: normalizeAccountId(recipient.toJSON() as any),336        value: value.toBigInt(),337      };338    }339  }340  throw new Error('no transfer event');341}342343interface Nft {344  type: 'NFT';345}346347interface Fungible {348  type: 'Fungible';349  decimalPoints: number;350}351352interface ReFungible {353  type: 'ReFungible';354}355356export type CollectionMode = Nft | Fungible | ReFungible;357358export type Property = {359  key: any,360  value: any,361};362363type Permission = {364  mutable: boolean;365  collectionAdmin: boolean;366  tokenOwner: boolean;367}368369type PropertyPermission = {370  key: any;371  permission: Permission;372}373374export type CreateCollectionParams = {375  mode: CollectionMode,376  name: string,377  description: string,378  tokenPrefix: string,379  properties?: Array<Property>,380  propPerm?: Array<PropertyPermission>381};382383const defaultCreateCollectionParams: CreateCollectionParams = {384  description: 'description',385  mode: {type: 'NFT'},386  name: 'name',387  tokenPrefix: 'prefix',388};389390export async function391createCollection(392  api: ApiPromise,393  sender: IKeyringPair,394  params: Partial<CreateCollectionParams> = {},395): Promise<CreateCollectionResult> {396  const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};397398  let modeprm = {};399  if (mode.type === 'NFT') {400    modeprm = {nft: null};401  } else if (mode.type === 'Fungible') {402    modeprm = {fungible: mode.decimalPoints};403  } else if (mode.type === 'ReFungible') {404    modeprm = {refungible: null};405  }406407  const tx = api.tx.unique.createCollectionEx({408    name: strToUTF16(name),409    description: strToUTF16(description),410    tokenPrefix: strToUTF16(tokenPrefix),411    mode: modeprm as any,412  });413  const events = await submitTransactionAsync(sender, tx);414  return getCreateCollectionResult(events);415}416417export async function createCollectionExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {418  const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};419420  let collectionId = 0;421  await usingApi(async (api, privateKeyWrapper) => {422    // Get number of collections before the transaction423    const collectionCountBefore = await getCreatedCollectionCount(api);424425    // Run the CreateCollection transaction426    const alicePrivateKey = privateKeyWrapper('//Alice');427428    const result = await createCollection(api, alicePrivateKey, params);429430    // Get number of collections after the transaction431    const collectionCountAfter = await getCreatedCollectionCount(api);432433    // Get the collection434    const collection = await queryCollectionExpectSuccess(api, result.collectionId);435436    // What to expect437    // tslint:disable-next-line:no-unused-expression438    expect(result.success).to.be.true;439    expect(result.collectionId).to.be.equal(collectionCountAfter);440    // tslint:disable-next-line:no-unused-expression441    expect(collection).to.be.not.null;442    expect(collectionCountAfter).to.be.equal(collectionCountBefore + 1, 'Error: NFT collection NOT created.');443    expect(collection.owner.toString()).to.be.equal(toSubstrateAddress(alicePrivateKey));444    expect(utf16ToStr(collection.name.toJSON() as any)).to.be.equal(name);445    expect(utf16ToStr(collection.description.toJSON() as any)).to.be.equal(description);446    expect(hexToStr(collection.tokenPrefix.toJSON())).to.be.equal(tokenPrefix);447448    collectionId = result.collectionId;449  });450451  return collectionId;452}453454export async function createCollectionWithPropsExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {455  const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};456457  let collectionId = 0;458  await usingApi(async (api, privateKeyWrapper) => {459    // Get number of collections before the transaction460    const collectionCountBefore = await getCreatedCollectionCount(api);461462    // Run the CreateCollection transaction463    const alicePrivateKey = privateKeyWrapper('//Alice');464465    let modeprm = {};466    if (mode.type === 'NFT') {467      modeprm = {nft: null};468    } else if (mode.type === 'Fungible') {469      modeprm = {fungible: mode.decimalPoints};470    } else if (mode.type === 'ReFungible') {471      modeprm = {refungible: null};472    }473474    const tx = api.tx.unique.createCollectionEx({name: strToUTF16(name), description: strToUTF16(description), tokenPrefix: strToUTF16(tokenPrefix), mode: modeprm as any, properties: params.properties, tokenPropertyPermissions: params.propPerm});475    const events = await submitTransactionAsync(alicePrivateKey, tx);476    const result = getCreateCollectionResult(events);477478    // Get number of collections after the transaction479    const collectionCountAfter = await getCreatedCollectionCount(api);480481    // Get the collection482    const collection = await queryCollectionExpectSuccess(api, result.collectionId);483484    // What to expect485    // tslint:disable-next-line:no-unused-expression486    expect(result.success).to.be.true;487    expect(result.collectionId).to.be.equal(collectionCountAfter);488    // tslint:disable-next-line:no-unused-expression489    expect(collection).to.be.not.null;490    expect(collectionCountAfter).to.be.equal(collectionCountBefore + 1, 'Error: NFT collection NOT created.');491    expect(collection.owner.toString()).to.be.equal(toSubstrateAddress(alicePrivateKey));492    expect(utf16ToStr(collection.name.toJSON() as any)).to.be.equal(name);493    expect(utf16ToStr(collection.description.toJSON() as any)).to.be.equal(description);494    expect(hexToStr(collection.tokenPrefix.toJSON())).to.be.equal(tokenPrefix);495496497    collectionId = result.collectionId;498  });499500  return collectionId;501}502503export async function createCollectionWithPropsExpectFailure(params: Partial<CreateCollectionParams> = {}) {504  const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};505506  await usingApi(async (api, privateKeyWrapper) => {507    // Get number of collections before the transaction508    const collectionCountBefore = await getCreatedCollectionCount(api);509510    // Run the CreateCollection transaction511    const alicePrivateKey = privateKeyWrapper('//Alice');512513    let modeprm = {};514    if (mode.type === 'NFT') {515      modeprm = {nft: null};516    } else if (mode.type === 'Fungible') {517      modeprm = {fungible: mode.decimalPoints};518    } else if (mode.type === 'ReFungible') {519      modeprm = {refungible: null};520    }521522    const tx = api.tx.unique.createCollectionEx({name: strToUTF16(name), description: strToUTF16(description), tokenPrefix: strToUTF16(tokenPrefix), mode: modeprm as any, properties: params.properties, tokenPropertyPermissions: params.propPerm});523    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;524525526    // Get number of collections after the transaction527    const collectionCountAfter = await getCreatedCollectionCount(api);528529    expect(collectionCountAfter).to.be.equal(collectionCountBefore, 'Error: Collection with incorrect data created.');530  });531}532533export async function createCollectionExpectFailure(params: Partial<CreateCollectionParams> = {}) {534  const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};535536  let modeprm = {};537  if (mode.type === 'NFT') {538    modeprm = {nft: null};539  } else if (mode.type === 'Fungible') {540    modeprm = {fungible: mode.decimalPoints};541  } else if (mode.type === 'ReFungible') {542    modeprm = {refungible: null};543  }544545  await usingApi(async (api, privateKeyWrapper) => {546    // Get number of collections before the transaction547    const collectionCountBefore = await getCreatedCollectionCount(api);548549    // Run the CreateCollection transaction550    const alicePrivateKey = privateKeyWrapper('//Alice');551    const tx = api.tx.unique.createCollectionEx({name: strToUTF16(name), description: strToUTF16(description), tokenPrefix: strToUTF16(tokenPrefix), mode: modeprm as any});552    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;553554    // Get number of collections after the transaction555    const collectionCountAfter = await getCreatedCollectionCount(api);556557    // What to expect558    expect(collectionCountAfter).to.be.equal(collectionCountBefore, 'Error: Collection with incorrect data created.');559  });560}561562export async function findUnusedAddress(api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair, seedAddition = ''): Promise<IKeyringPair> {563  let bal = 0n;564  let unused;565  do {566    const randomSeed = 'seed' + Math.floor(Math.random() * Math.floor(10000)) + seedAddition;567    unused = privateKeyWrapper(`//${randomSeed}`);568    bal = (await api.query.system.account(unused.address)).data.free.toBigInt();569  } while (bal !== 0n);570  return unused;571}572573export async function getAllowance(api: ApiPromise, collectionId: number, owner: CrossAccountId | string | IKeyringPair, approved: CrossAccountId | string | IKeyringPair, tokenId: number) {574  return (await api.rpc.unique.allowance(collectionId, normalizeAccountId(owner), normalizeAccountId(approved), tokenId)).toBigInt();575}576577export function findUnusedAddresses(api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair, amount: number): Promise<IKeyringPair[]> {578  return Promise.all(new Array(amount).fill(null).map(() => findUnusedAddress(api, privateKeyWrapper, '_' + Date.now())));579}580581export async function findNotExistingCollection(api: ApiPromise): Promise<number> {582  const totalNumber = await getCreatedCollectionCount(api);583  const newCollection: number = totalNumber + 1;584  return newCollection;585}586587function getDestroyResult(events: EventRecord[]): boolean {588  let success = false;589  events.forEach(({event: {method}}) => {590    if (method == 'ExtrinsicSuccess') {591      success = true;592    }593  });594  return success;595}596597export async function destroyCollectionExpectFailure(collectionId: number, senderSeed = '//Alice') {598  await usingApi(async (api, privateKeyWrapper) => {599    // Run the DestroyCollection transaction600    const alicePrivateKey = privateKeyWrapper(senderSeed);601    const tx = api.tx.unique.destroyCollection(collectionId);602    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;603  });604}605606export async function destroyCollectionExpectSuccess(collectionId: number, senderSeed = '//Alice') {607  await usingApi(async (api, privateKeyWrapper) => {608    // Run the DestroyCollection transaction609    const alicePrivateKey = privateKeyWrapper(senderSeed);610    const tx = api.tx.unique.destroyCollection(collectionId);611    const events = await submitTransactionAsync(alicePrivateKey, tx);612    const result = getDestroyResult(events);613    expect(result).to.be.true;614615    // What to expect616    expect(await getDetailedCollectionInfo(api, collectionId)).to.be.null;617  });618}619620export async function setCollectionLimitsExpectSuccess(sender: IKeyringPair, collectionId: number, limits: any) {621  await usingApi(async (api) => {622    const tx = api.tx.unique.setCollectionLimits(collectionId, limits);623    const events = await submitTransactionAsync(sender, tx);624    const result = getGenericResult(events);625626    expect(result.success).to.be.true;627  });628}629630export const setCollectionPermissionsExpectSuccess = async (sender: IKeyringPair, collectionId: number, permissions: any) => {631  await usingApi(async(api) => {632    const tx = api.tx.unique.setCollectionPermissions(collectionId, permissions);633    const events = await submitTransactionAsync(sender, tx);634    const result = getGenericResult(events);635636    expect(result.success).to.be.true;637  });638};639640export async function setCollectionLimitsExpectFailure(sender: IKeyringPair, collectionId: number, limits: any) {641  await usingApi(async (api) => {642    const tx = api.tx.unique.setCollectionLimits(collectionId, limits);643    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;644    const result = getGenericResult(events);645646    expect(result.success).to.be.false;647  });648}649650export async function setCollectionSponsorExpectSuccess(collectionId: number, sponsor: string, sender = '//Alice') {651  await usingApi(async (api, privateKeyWrapper) => {652653    // Run the transaction654    const senderPrivateKey = privateKeyWrapper(sender);655    const tx = api.tx.unique.setCollectionSponsor(collectionId, sponsor);656    const events = await submitTransactionAsync(senderPrivateKey, tx);657    const result = getGenericResult(events);658659    // Get the collection660    const collection = await queryCollectionExpectSuccess(api, collectionId);661662    // What to expect663    expect(result.success).to.be.true;664    expect(collection.sponsorship.toJSON()).to.deep.equal({665      unconfirmed: sponsor,666    });667  });668}669670export async function removeCollectionSponsorExpectSuccess(collectionId: number, sender = '//Alice') {671  await usingApi(async (api, privateKeyWrapper) => {672673    // Run the transaction674    const alicePrivateKey = privateKeyWrapper(sender);675    const tx = api.tx.unique.removeCollectionSponsor(collectionId);676    const events = await submitTransactionAsync(alicePrivateKey, tx);677    const result = getGenericResult(events);678679    // Get the collection680    const collection = await queryCollectionExpectSuccess(api, collectionId);681682    // What to expect683    expect(result.success).to.be.true;684    expect(collection.sponsorship.toJSON()).to.be.deep.equal({disabled: null});685  });686}687688export async function removeCollectionSponsorExpectFailure(collectionId: number, senderSeed = '//Alice') {689  await usingApi(async (api, privateKeyWrapper) => {690691    // Run the transaction692    const alicePrivateKey = privateKeyWrapper(senderSeed);693    const tx = api.tx.unique.removeCollectionSponsor(collectionId);694    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;695  });696}697698export async function setCollectionSponsorExpectFailure(collectionId: number, sponsor: string, senderSeed = '//Alice') {699  await usingApi(async (api, privateKeyWrapper) => {700701    // Run the transaction702    const alicePrivateKey = privateKeyWrapper(senderSeed);703    const tx = api.tx.unique.setCollectionSponsor(collectionId, sponsor);704    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;705  });706}707708export async function confirmSponsorshipExpectSuccess(collectionId: number, senderSeed = '//Alice') {709  await usingApi(async (api, privateKeyWrapper) => {710711    // Run the transaction712    const sender = privateKeyWrapper(senderSeed);713    await confirmSponsorshipByKeyExpectSuccess(collectionId, sender);714  });715}716717export async function confirmSponsorshipByKeyExpectSuccess(collectionId: number, sender: IKeyringPair) {718  await usingApi(async (api, privateKeyWrapper) => {719720    // Run the transaction721    const tx = api.tx.unique.confirmSponsorship(collectionId);722    const events = await submitTransactionAsync(sender, tx);723    const result = getGenericResult(events);724725    // Get the collection726    const collection = await queryCollectionExpectSuccess(api, collectionId);727728    // What to expect729    expect(result.success).to.be.true;730    expect(collection.sponsorship.toJSON()).to.be.deep.equal({731      confirmed: sender.address,732    });733  });734}735736737export async function confirmSponsorshipExpectFailure(collectionId: number, senderSeed = '//Alice') {738  await usingApi(async (api, privateKeyWrapper) => {739740    // Run the transaction741    const sender = privateKeyWrapper(senderSeed);742    const tx = api.tx.unique.confirmSponsorship(collectionId);743    await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;744  });745}746747export async function enableContractSponsoringExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {748  await usingApi(async (api) => {749    const tx = api.tx.unique.enableContractSponsoring(contractAddress, enable);750    const events = await submitTransactionAsync(sender, tx);751    const result = getGenericResult(events);752753    expect(result.success).to.be.true;754  });755}756757export async function enableContractSponsoringExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {758  await usingApi(async (api) => {759    const tx = api.tx.unique.enableContractSponsoring(contractAddress, enable);760    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;761    const result = getGenericResult(events);762763    expect(result.success).to.be.false;764  });765}766767export async function setTransferFlagExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {768769  await usingApi(async (api) => {770771    const tx = api.tx.unique.setTransfersEnabledFlag(collectionId, enabled);772    const events = await submitTransactionAsync(sender, tx);773    const result = getGenericResult(events);774775    expect(result.success).to.be.true;776  });777}778779export async function setTransferFlagExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {780781  await usingApi(async (api) => {782783    const tx = api.tx.unique.setTransfersEnabledFlag(collectionId, enabled);784    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;785    const result = getGenericResult(events);786787    expect(result.success).to.be.false;788  });789}790791export async function setContractSponsoringRateLimitExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {792  await usingApi(async (api) => {793    const tx = api.tx.unique.setContractSponsoringRateLimit(contractAddress, rateLimit);794    const events = await submitTransactionAsync(sender, tx);795    const result = getGenericResult(events);796797    expect(result.success).to.be.true;798  });799}800801export async function setContractSponsoringRateLimitExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {802  await usingApi(async (api) => {803    const tx = api.tx.unique.setContractSponsoringRateLimit(contractAddress, rateLimit);804    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;805    const result = getGenericResult(events);806807    expect(result.success).to.be.false;808  });809}810811export async function getNextSponsored(812  api: ApiPromise,813  collectionId: number,814  account: string | CrossAccountId,815  tokenId: number,816): Promise<number> {817  return Number((await api.rpc.unique.nextSponsored(collectionId, account, tokenId)).unwrapOr(-1));818}819820export async function toggleContractAllowlistExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, value = true) {821  await usingApi(async (api) => {822    const tx = api.tx.unique.toggleContractAllowList(contractAddress, value);823    const events = await submitTransactionAsync(sender, tx);824    const result = getGenericResult(events);825826    expect(result.success).to.be.true;827  });828}829830export async function isAllowlistedInContract(contractAddress: AccountId | string, user: string) {831  let allowlisted = false;832  await usingApi(async (api) => {833    allowlisted = (await api.query.unique.contractAllowList(contractAddress, user)).toJSON() as boolean;834  });835  return allowlisted;836}837838export async function addToContractAllowListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {839  await usingApi(async (api) => {840    const tx = api.tx.unique.addToContractAllowList(contractAddress.toString(), user.toString());841    const events = await submitTransactionAsync(sender, tx);842    const result = getGenericResult(events);843844    expect(result.success).to.be.true;845  });846}847848export async function removeFromContractAllowListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {849  await usingApi(async (api) => {850    const tx = api.tx.unique.removeFromContractAllowList(contractAddress.toString(), user.toString());851    const events = await submitTransactionAsync(sender, tx);852    const result = getGenericResult(events);853854    expect(result.success).to.be.true;855  });856}857858export async function removeFromContractAllowListExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {859  await usingApi(async (api) => {860    const tx = api.tx.unique.removeFromContractAllowList(contractAddress.toString(), user.toString());861    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;862    const result = getGenericResult(events);863864    expect(result.success).to.be.false;865  });866}867868export interface CreateFungibleData {869  readonly Value: bigint;870}871872export interface CreateReFungibleData { }873export interface CreateNftData { }874875export type CreateItemData = {876  NFT: CreateNftData;877} | {878  Fungible: CreateFungibleData;879} | {880  ReFungible: CreateReFungibleData;881};882883export async function burnItem(api: ApiPromise, sender: IKeyringPair, collectionId: number, tokenId: number, value: number | bigint) : Promise<boolean> {884  const tx = api.tx.unique.burnItem(collectionId, tokenId, value);885  const events = await submitTransactionAsync(sender, tx);886  return getGenericResult(events).success;887}888889export async function burnItemExpectSuccess(sender: IKeyringPair, collectionId: number, tokenId: number, value: number | bigint = 1) {890  await usingApi(async (api) => {891    const balanceBefore = await getBalance(api, collectionId, normalizeAccountId(sender), tokenId);892    // if burning token by admin - use adminButnItemExpectSuccess893    expect(balanceBefore >= BigInt(value)).to.be.true;894895    expect(await burnItem(api, sender, collectionId, tokenId, value)).to.be.true;896897    const balanceAfter = await getBalance(api, collectionId, normalizeAccountId(sender), tokenId);898    expect(balanceAfter + BigInt(value)).to.be.equal(balanceBefore);899  });900}901902export async function burnItemExpectFailure(sender: IKeyringPair, collectionId: number, tokenId: number, value: number | bigint = 1) {903  await usingApi(async (api) => {904    const tx = api.tx.unique.burnItem(collectionId, tokenId, value);905906    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;907    const result = getCreateCollectionResult(events);908    // tslint:disable-next-line:no-unused-expression909    expect(result.success).to.be.false;910  });911}912913export async function burnFromExpectSuccess(sender: IKeyringPair, from: IKeyringPair | CrossAccountId, collectionId: number, tokenId: number, value: number | bigint = 1) {914  await usingApi(async (api) => {915    const tx = api.tx.unique.burnFrom(collectionId, normalizeAccountId(from), tokenId, value);916    const events = await submitTransactionAsync(sender, tx);917    return getGenericResult(events).success;918  });919}920921export async function922approve(923  api: ApiPromise,924  collectionId: number,925  tokenId: number, owner: IKeyringPair, approved: CrossAccountId | string | IKeyringPair, amount: number | bigint,926) {927  const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);928  const events = await submitTransactionAsync(owner, approveUniqueTx);929  return getGenericResult(events).success;930}931932export async function933approveExpectSuccess(934  collectionId: number,935  tokenId: number, owner: IKeyringPair, approved: CrossAccountId | string, amount: number | bigint = 1,936) {937  await usingApi(async (api: ApiPromise) => {938    const result = await approve(api, collectionId, tokenId, owner, approved, amount);939    expect(result).to.be.true;940941    expect(await getAllowance(api, collectionId, owner, approved, tokenId)).to.be.equal(BigInt(amount));942  });943}944945export async function adminApproveFromExpectSuccess(946  collectionId: number,947  tokenId: number, admin: IKeyringPair, owner: CrossAccountId | string, approved: CrossAccountId | string, amount: number | bigint = 1,948) {949  await usingApi(async (api: ApiPromise) => {950    const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);951    const events = await submitTransactionAsync(admin, approveUniqueTx);952    const result = getGenericResult(events);953    expect(result.success).to.be.true;954955    expect(await getAllowance(api, collectionId, owner, approved, tokenId)).to.be.equal(BigInt(amount));956  });957}958959export async function960transferFrom(961  api: ApiPromise,962  collectionId: number,963  tokenId: number,964  accountApproved: IKeyringPair,965  accountFrom: IKeyringPair | CrossAccountId,966  accountTo: IKeyringPair | CrossAccountId,967  value: number | bigint,968) {969  const from = normalizeAccountId(accountFrom);970  const to = normalizeAccountId(accountTo);971  const transferFromTx = api.tx.unique.transferFrom(from, to, collectionId, tokenId, value);972  const events = await submitTransactionAsync(accountApproved, transferFromTx);973  return getGenericResult(events).success;974}975976export async function977transferFromExpectSuccess(978  collectionId: number,979  tokenId: number,980  accountApproved: IKeyringPair,981  accountFrom: IKeyringPair | CrossAccountId,982  accountTo: IKeyringPair | CrossAccountId,983  value: number | bigint = 1,984  type = 'NFT',985) {986  await usingApi(async (api: ApiPromise) => {987    const from = normalizeAccountId(accountFrom);988    const to = normalizeAccountId(accountTo);989    let balanceBefore = 0n;990    if (type === 'Fungible' || type === 'ReFungible') {991      balanceBefore = await getBalance(api, collectionId, to, tokenId);992    }993    expect(await transferFrom(api, collectionId, tokenId, accountApproved, accountFrom, accountTo, value)).to.be.true;994    if (type === 'NFT') {995      expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(to);996    }997    if (type === 'Fungible') {998      const balanceAfter = await getBalance(api, collectionId, to, tokenId);999      if (JSON.stringify(to) !== JSON.stringify(from)) {1000        expect(balanceAfter - balanceBefore).to.be.equal(BigInt(value));1001      } else {1002        expect(balanceAfter).to.be.equal(balanceBefore);1003      }1004    }1005    if (type === 'ReFungible') {1006      expect(await getBalance(api, collectionId, to, tokenId)).to.be.equal(balanceBefore + BigInt(value));1007    }1008  });1009}10101011export async function1012transferFromExpectFail(1013  collectionId: number,1014  tokenId: number,1015  accountApproved: IKeyringPair,1016  accountFrom: IKeyringPair,1017  accountTo: IKeyringPair,1018  value: number | bigint = 1,1019) {1020  await usingApi(async (api: ApiPromise) => {1021    const transferFromTx = api.tx.unique.transferFrom(normalizeAccountId(accountFrom.address), normalizeAccountId(accountTo.address), collectionId, tokenId, value);1022    const events = await expect(submitTransactionExpectFailAsync(accountApproved, transferFromTx)).to.be.rejected;1023    const result = getCreateCollectionResult(events);1024    // tslint:disable-next-line:no-unused-expression1025    expect(result.success).to.be.false;1026  });1027}10281029/* eslint no-async-promise-executor: "off" */1030export async function getBlockNumber(api: ApiPromise): Promise<number> {1031  return new Promise<number>(async (resolve) => {1032    const unsubscribe = await api.rpc.chain.subscribeNewHeads((head) => {1033      unsubscribe();1034      resolve(head.number.toNumber());1035    });1036  });1037}10381039export async function addCollectionAdminExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | CrossAccountId) {1040  await usingApi(async (api) => {1041    const changeAdminTx = api.tx.unique.addCollectionAdmin(collectionId, normalizeAccountId(address));1042    const events = await submitTransactionAsync(sender, changeAdminTx);1043    const result = getCreateCollectionResult(events);1044    expect(result.success).to.be.true;1045  });1046}10471048export async function adminApproveFromExpectFail(1049  collectionId: number,1050  tokenId: number, admin: IKeyringPair, owner: CrossAccountId | string, approved: CrossAccountId | string, amount: number | bigint = 1,1051) {1052  await usingApi(async (api: ApiPromise) => {1053    const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);1054    const events = await expect(submitTransactionAsync(admin, approveUniqueTx)).to.be.rejected;1055    const result = getGenericResult(events);1056    expect(result.success).to.be.false;1057  });1058}10591060export async function1061getFreeBalance(account: IKeyringPair): Promise<bigint> {1062  let balance = 0n;1063  await usingApi(async (api) => {1064    balance = BigInt((await api.query.system.account(account.address)).data.free.toString());1065  });10661067  return balance;1068}10691070export async function transferBalanceTo(api: ApiPromise, source: IKeyringPair, target: string, amount = 1000n * UNIQUE) {1071  const tx = api.tx.balances.transfer(target, amount);1072  const events = await submitTransactionAsync(source, tx);1073  const result = getGenericResult(events);1074  expect(result.success).to.be.true;1075}10761077export async function1078scheduleExpectSuccess(1079  operationTx: any,1080  sender: IKeyringPair,1081  blockSchedule: number,1082  scheduledId: string,1083  period = 1,1084  repetitions = 1,1085) {1086  await usingApi(async (api: ApiPromise) => {1087    const blockNumber: number | undefined = await getBlockNumber(api);1088    const expectedBlockNumber = blockNumber + blockSchedule;10891090    expect(blockNumber).to.be.greaterThan(0);1091    const scheduleTx = api.tx.scheduler.scheduleNamed( // schedule1092      scheduledId,1093      expectedBlockNumber, 1094      repetitions > 1 ? [period, repetitions] : null, 1095      0, 1096      {Value: operationTx as any},1097    );10981099    const events = await submitTransactionAsync(sender, scheduleTx);1100    expect(getGenericResult(events).success).to.be.true;1101  });1102}11031104export async function1105scheduleExpectFailure(1106  operationTx: any,1107  sender: IKeyringPair,1108  blockSchedule: number,1109  scheduledId: string,1110  period = 1,1111  repetitions = 1,1112) {1113  await usingApi(async (api: ApiPromise) => {1114    const blockNumber: number | undefined = await getBlockNumber(api);1115    const expectedBlockNumber = blockNumber + blockSchedule;11161117    expect(blockNumber).to.be.greaterThan(0);1118    const scheduleTx = api.tx.scheduler.scheduleNamed( // schedule1119      scheduledId,1120      expectedBlockNumber, 1121      repetitions <= 1 ? null : [period, repetitions], 1122      0, 1123      {Value: operationTx as any},1124    );11251126    //const events = 1127    await expect(submitTransactionExpectFailAsync(sender, scheduleTx)).to.be.rejected;1128    //expect(getGenericResult(events).success).to.be.false;1129  });1130}11311132export async function1133scheduleTransferAndWaitExpectSuccess(1134  collectionId: number,1135  tokenId: number,1136  sender: IKeyringPair,1137  recipient: IKeyringPair,1138  value: number | bigint = 1,1139  blockSchedule: number,1140  scheduledId: string,1141) {1142  await usingApi(async (api: ApiPromise) => {1143    await scheduleTransferExpectSuccess(collectionId, tokenId, sender, recipient, value, blockSchedule, scheduledId);11441145    const recipientBalanceBefore = (await api.query.system.account(recipient.address)).data.free.toBigInt();11461147    // sleep for n + 1 blocks1148    await waitNewBlocks(blockSchedule + 1);11491150    const recipientBalanceAfter = (await api.query.system.account(recipient.address)).data.free.toBigInt();11511152    expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(recipient.address));1153    expect(recipientBalanceAfter).to.be.equal(recipientBalanceBefore);1154  });1155}11561157export async function1158scheduleTransferExpectSuccess(1159  collectionId: number,1160  tokenId: number,1161  sender: IKeyringPair,1162  recipient: IKeyringPair,1163  value: number | bigint = 1,1164  blockSchedule: number,1165  scheduledId: string,1166) {1167  await usingApi(async (api: ApiPromise) => {1168    const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient.address), collectionId, tokenId, value);11691170    await scheduleExpectSuccess(transferTx, sender, blockSchedule, scheduledId);11711172    expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(sender.address));1173  });1174}11751176export async function1177scheduleTransferFundsPeriodicExpectSuccess(1178  amount: bigint,1179  sender: IKeyringPair,1180  recipient: IKeyringPair,1181  blockSchedule: number,1182  scheduledId: string,1183  period: number,1184  repetitions: number,1185) {1186  await usingApi(async (api: ApiPromise) => {1187    const transferTx = api.tx.balances.transfer(recipient.address, amount);11881189    const balanceBefore = await getFreeBalance(recipient);1190    1191    await scheduleExpectSuccess(transferTx, sender, blockSchedule, scheduledId, period, repetitions);11921193    expect(await getFreeBalance(recipient)).to.be.equal(balanceBefore);1194  });1195}11961197export async function1198transfer(1199  api: ApiPromise,1200  collectionId: number,1201  tokenId: number,1202  sender: IKeyringPair,1203  recipient: IKeyringPair | CrossAccountId,1204  value: number | bigint,1205) : Promise<boolean> {1206  const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient), collectionId, tokenId, value);1207  const events = await executeTransaction(api, sender, transferTx);1208  return getGenericResult(events).success;1209}12101211export async function1212transferExpectSuccess(1213  collectionId: number,1214  tokenId: number,1215  sender: IKeyringPair,1216  recipient: IKeyringPair | CrossAccountId,1217  value: number | bigint = 1,1218  type = 'NFT',1219) {1220  await usingApi(async (api: ApiPromise) => {1221    const from = normalizeAccountId(sender);1222    const to = normalizeAccountId(recipient);12231224    let balanceBefore = 0n;1225    if (type === 'Fungible' || type === 'ReFungible') {1226      balanceBefore = await getBalance(api, collectionId, to, tokenId);1227    }12281229    const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient), collectionId, tokenId, value);1230    const events = await executeTransaction(api, sender, transferTx);1231    const result = getTransferResult(api, events);12321233    expect(result.collectionId).to.be.equal(collectionId);1234    expect(result.itemId).to.be.equal(tokenId);1235    expect(result.sender).to.be.deep.equal(normalizeAccountId(sender.address));1236    expect(result.recipient).to.be.deep.equal(to);1237    expect(result.value).to.be.equal(BigInt(value));12381239    if (type === 'NFT') {1240      expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(to);1241    }1242    if (type === 'Fungible' || type === 'ReFungible') {1243      const balanceAfter = await getBalance(api, collectionId, to, tokenId);1244      if (JSON.stringify(to) !== JSON.stringify(from)) {1245        expect(balanceAfter - balanceBefore).to.be.equal(BigInt(value));1246      } else {1247        expect(balanceAfter).to.be.equal(balanceBefore);1248      }1249    }1250  });1251}12521253export async function1254transferExpectFailure(1255  collectionId: number,1256  tokenId: number,1257  sender: IKeyringPair,1258  recipient: IKeyringPair | CrossAccountId,1259  value: number | bigint = 1,1260) {1261  await usingApi(async (api: ApiPromise) => {1262    const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient), collectionId, tokenId, value);1263    const events = await expect(submitTransactionExpectFailAsync(sender, transferTx)).to.be.rejected;1264    const result = getGenericResult(events);1265    // if (events && Array.isArray(events)) {1266    //   const result = getCreateCollectionResult(events);1267    // tslint:disable-next-line:no-unused-expression1268    expect(result.success).to.be.false;1269    //}1270  });1271}12721273export async function1274approveExpectFail(1275  collectionId: number,1276  tokenId: number, owner: IKeyringPair, approved: IKeyringPair, amount: number | bigint = 1,1277) {1278  await usingApi(async (api: ApiPromise) => {1279    const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved.address), collectionId, tokenId, amount);1280    const events = await expect(submitTransactionExpectFailAsync(owner, approveUniqueTx)).to.be.rejected;1281    const result = getCreateCollectionResult(events);1282    // tslint:disable-next-line:no-unused-expression1283    expect(result.success).to.be.false;1284  });1285}12861287export async function getBalance(1288  api: ApiPromise,1289  collectionId: number,1290  owner: string | CrossAccountId | IKeyringPair,1291  token: number,1292): Promise<bigint> {1293  return (await api.rpc.unique.balance(collectionId, normalizeAccountId(owner), token)).toBigInt();1294}1295export async function getTokenOwner(1296  api: ApiPromise,1297  collectionId: number,1298  token: number,1299): Promise<CrossAccountId> {1300  const owner = (await api.rpc.unique.tokenOwner(collectionId, token)).toJSON() as any;1301  if (owner == null) throw new Error('owner == null');1302  return normalizeAccountId(owner);1303}1304export async function getTopmostTokenOwner(1305  api: ApiPromise,1306  collectionId: number,1307  token: number,1308): Promise<CrossAccountId> {1309  const owner = (await api.rpc.unique.topmostTokenOwner(collectionId, token)).toJSON() as any;1310  if (owner == null) throw new Error('owner == null');1311  return normalizeAccountId(owner);1312}1313export async function getTokenChildren(1314  api: ApiPromise,1315  collectionId: number,1316  tokenId: number,1317): Promise<UpDataStructsTokenChild[]> {1318  return (await api.rpc.unique.tokenChildren(collectionId, tokenId)).toJSON() as any;1319}1320export async function isTokenExists(1321  api: ApiPromise,1322  collectionId: number,1323  token: number,1324): Promise<boolean> {1325  return (await api.rpc.unique.tokenExists(collectionId, token)).toJSON();1326}1327export async function getLastTokenId(1328  api: ApiPromise,1329  collectionId: number,1330): Promise<number> {1331  return (await api.rpc.unique.lastTokenId(collectionId)).toJSON();1332}1333export async function getAdminList(1334  api: ApiPromise,1335  collectionId: number,1336): Promise<string[]> {1337  return (await api.rpc.unique.adminlist(collectionId)).toHuman() as any;1338}1339export async function getTokenProperties(1340  api: ApiPromise,1341  collectionId: number,1342  tokenId: number,1343  propertyKeys: string[],1344): Promise<UpDataStructsProperty[]> {1345  return (await api.rpc.unique.tokenProperties(collectionId, tokenId, propertyKeys)).toHuman() as any;1346}13471348export async function createFungibleItemExpectSuccess(1349  sender: IKeyringPair,1350  collectionId: number,1351  data: CreateFungibleData,1352  owner: CrossAccountId | string = sender.address,1353) {1354  return await usingApi(async (api) => {1355    const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), {Fungible: data});13561357    const events = await submitTransactionAsync(sender, tx);1358    const result = getCreateItemResult(events);13591360    expect(result.success).to.be.true;1361    return result.itemId;1362  });1363}13641365export async function createMultipleItemsExpectSuccess(sender: IKeyringPair, collectionId: number, itemsData: any, owner: CrossAccountId | string = sender.address) {1366  await usingApi(async (api) => {1367    const to = normalizeAccountId(owner);1368    const tx = api.tx.unique.createMultipleItems(collectionId, to, itemsData);13691370    const events = await submitTransactionAsync(sender, tx);1371    expect(getGenericResult(events).success).to.be.true;1372  });1373}13741375export async function createMultipleItemsWithPropsExpectSuccess(sender: IKeyringPair, collectionId: number, itemsData: any, owner: CrossAccountId | string = sender.address) {1376  await usingApi(async (api) => {1377    const to = normalizeAccountId(owner);1378    const tx = api.tx.unique.createMultipleItems(collectionId, to, itemsData);13791380    const events = await submitTransactionAsync(sender, tx);1381    const result = getCreateItemsResult(events);13821383    for (const res of result) {1384      expect(await api.rpc.unique.tokenProperties(collectionId, res.itemId)).not.to.be.empty;1385    }1386  });1387}13881389export async function createMultipleItemsExWithPropsExpectSuccess(sender: IKeyringPair, collectionId: number, itemsData: any) {1390  await usingApi(async (api) => {1391    const tx = api.tx.unique.createMultipleItemsEx(collectionId, itemsData);13921393    const events = await submitTransactionAsync(sender, tx);1394    const result = getCreateItemsResult(events);13951396    for (const res of result) {1397      expect(await api.rpc.unique.tokenProperties(collectionId, res.itemId)).not.to.be.empty;1398    }1399  });1400}14011402export async function createItemWithPropsExpectSuccess(sender: IKeyringPair, collectionId: number, createMode: string, props:  Array<Property>, owner: CrossAccountId | string = sender.address) {1403  let newItemId = 0;1404  await usingApi(async (api) => {1405    const to = normalizeAccountId(owner);1406    const itemCountBefore = await getLastTokenId(api, collectionId);1407    const itemBalanceBefore = await getBalance(api, collectionId, to, newItemId);14081409    let tx;1410    if (createMode === 'Fungible') {1411      const createData = {fungible: {value: 10}};1412      tx = api.tx.unique.createItem(collectionId, to, createData as any);1413    } else if (createMode === 'ReFungible') {1414      const createData = {refungible: {pieces: 100}};1415      tx = api.tx.unique.createItem(collectionId, to, createData as any);1416    } else {1417      const data = api.createType('UpDataStructsCreateItemData', {NFT: {properties: props}});1418      tx = api.tx.unique.createItem(collectionId, to, data as UpDataStructsCreateItemData);1419    }14201421    const events = await submitTransactionAsync(sender, tx);1422    const result = getCreateItemResult(events);14231424    const itemCountAfter = await getLastTokenId(api, collectionId);1425    const itemBalanceAfter = await getBalance(api, collectionId, to, newItemId);14261427    if (createMode === 'NFT') {1428      expect(await api.rpc.unique.tokenProperties(collectionId, result.itemId)).not.to.be.empty;1429    }14301431    // What to expect1432    // tslint:disable-next-line:no-unused-expression1433    expect(result.success).to.be.true;1434    if (createMode === 'Fungible') {1435      expect(itemBalanceAfter - itemBalanceBefore).to.be.equal(10n);1436    } else {1437      expect(itemCountAfter).to.be.equal(itemCountBefore + 1);1438    }1439    expect(collectionId).to.be.equal(result.collectionId);1440    expect(itemCountAfter.toString()).to.be.equal(result.itemId.toString());1441    expect(to).to.be.deep.equal(result.recipient);1442    newItemId = result.itemId;1443  });1444  return newItemId;1445}14461447export async function createItemWithPropsExpectFailure(sender: IKeyringPair, collectionId: number, createMode: string, props: Array<Property>, owner: CrossAccountId | string = sender.address) {1448  await usingApi(async (api) => {14491450    let tx;1451    if (createMode === 'NFT') {1452      const data = api.createType('UpDataStructsCreateItemData', {NFT: {properties: props}}) as UpDataStructsCreateItemData;1453      tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), data);1454    } else {1455      tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), createMode);1456    }145714581459    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1460    if(events.message && events.message.toString().indexOf('1002: Verification Error') > -1) return;1461    const result = getCreateItemResult(events);14621463    expect(result.success).to.be.false;1464  });1465}14661467export async function createItemExpectSuccess(sender: IKeyringPair, collectionId: number, createMode: string, owner: CrossAccountId | string = sender.address) {1468  let newItemId = 0;1469  await usingApi(async (api) => {1470    const to = normalizeAccountId(owner);1471    const itemCountBefore = await getLastTokenId(api, collectionId);1472    const itemBalanceBefore = await getBalance(api, collectionId, to, newItemId);14731474    let tx;1475    if (createMode === 'Fungible') {1476      const createData = {fungible: {value: 10}};1477      tx = api.tx.unique.createItem(collectionId, to, createData as any);1478    } else if (createMode === 'ReFungible') {1479      const createData = {refungible: {pieces: 100}};1480      tx = api.tx.unique.createItem(collectionId, to, createData as any);1481    } else {1482      const createData = {nft: {}};1483      tx = api.tx.unique.createItem(collectionId, to, createData as any);1484    }14851486    const events = await executeTransaction(api, sender, tx);1487    const result = getCreateItemResult(events);14881489    const itemCountAfter = await getLastTokenId(api, collectionId);1490    const itemBalanceAfter = await getBalance(api, collectionId, to, newItemId);14911492    // What to expect1493    // tslint:disable-next-line:no-unused-expression1494    expect(result.success).to.be.true;1495    if (createMode === 'Fungible') {1496      expect(itemBalanceAfter - itemBalanceBefore).to.be.equal(10n);1497    } else {1498      expect(itemCountAfter).to.be.equal(itemCountBefore + 1);1499    }1500    expect(collectionId).to.be.equal(result.collectionId);1501    expect(itemCountAfter.toString()).to.be.equal(result.itemId.toString());1502    expect(to).to.be.deep.equal(result.recipient);1503    newItemId = result.itemId;1504  });1505  return newItemId;1506}15071508export async function createRefungibleToken(api: ApiPromise, sender: IKeyringPair, collectionId: number, amount: bigint, owner: CrossAccountId | IKeyringPair | string = sender.address) : Promise<CreateItemResult> {1509  const createData = {refungible: {pieces: amount}};1510  const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), createData as any);15111512  const events = await submitTransactionAsync(sender, tx);1513  return  getCreateItemResult(events);1514}15151516export async function createItemExpectFailure(sender: IKeyringPair, collectionId: number, createMode: string, owner: CrossAccountId | string = sender.address) {1517  await usingApi(async (api) => {1518    const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), createMode);15191520    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1521    const result = getCreateItemResult(events);15221523    expect(result.success).to.be.false;1524  });1525}15261527export async function setPublicAccessModeExpectSuccess(1528  sender: IKeyringPair, collectionId: number,1529  accessMode: 'Normal' | 'AllowList',1530) {1531  await usingApi(async (api) => {15321533    // Run the transaction1534    const tx = api.tx.unique.setCollectionPermissions(collectionId, {access: accessMode});1535    const events = await submitTransactionAsync(sender, tx);1536    const result = getGenericResult(events);15371538    // Get the collection1539    const collection = await queryCollectionExpectSuccess(api, collectionId);15401541    // What to expect1542    // tslint:disable-next-line:no-unused-expression1543    expect(result.success).to.be.true;1544    expect(collection.permissions.access.toHuman()).to.be.equal(accessMode);1545  });1546}15471548export async function setPublicAccessModeExpectFail(1549  sender: IKeyringPair, collectionId: number,1550  accessMode: 'Normal' | 'AllowList',1551) {1552  await usingApi(async (api) => {15531554    // Run the transaction1555    const tx = api.tx.unique.setCollectionPermissions(collectionId, {access: accessMode});1556    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1557    const result = getGenericResult(events);15581559    // What to expect1560    // tslint:disable-next-line:no-unused-expression1561    expect(result.success).to.be.false;1562  });1563}15641565export async function enableAllowListExpectSuccess(sender: IKeyringPair, collectionId: number) {1566  await setPublicAccessModeExpectSuccess(sender, collectionId, 'AllowList');1567}15681569export async function enableAllowListExpectFail(sender: IKeyringPair, collectionId: number) {1570  await setPublicAccessModeExpectFail(sender, collectionId, 'AllowList');1571}15721573export async function disableAllowListExpectSuccess(sender: IKeyringPair, collectionId: number) {1574  await setPublicAccessModeExpectSuccess(sender, collectionId, 'Normal');1575}15761577export async function setMintPermissionExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {1578  await usingApi(async (api) => {15791580    // Run the transaction1581    const tx = api.tx.unique.setCollectionPermissions(collectionId, {mintMode: enabled});1582    const events = await submitTransactionAsync(sender, tx);1583    const result = getGenericResult(events);1584    expect(result.success).to.be.true;15851586    // Get the collection1587    const collection = await queryCollectionExpectSuccess(api, collectionId);15881589    expect(collection.permissions.mintMode.toHuman()).to.be.equal(enabled);1590  });1591}15921593export async function enablePublicMintingExpectSuccess(sender: IKeyringPair, collectionId: number) {1594  await setMintPermissionExpectSuccess(sender, collectionId, true);1595}15961597export async function setMintPermissionExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {1598  await usingApi(async (api) => {1599    // Run the transaction1600    const tx = api.tx.unique.setCollectionPermissions(collectionId, {mintMode: enabled});1601    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1602    const result = getCreateCollectionResult(events);1603    // tslint:disable-next-line:no-unused-expression1604    expect(result.success).to.be.false;1605  });1606}16071608export async function setChainLimitsExpectFailure(sender: IKeyringPair, limits: IChainLimits) {1609  await usingApi(async (api) => {1610    // Run the transaction1611    const tx = api.tx.unique.setChainLimits(limits);1612    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1613    const result = getCreateCollectionResult(events);1614    // tslint:disable-next-line:no-unused-expression1615    expect(result.success).to.be.false;1616  });1617}16181619export async function isAllowlisted(api: ApiPromise, collectionId: number, address: string | CrossAccountId) {1620  return (await api.rpc.unique.allowed(collectionId, normalizeAccountId(address))).toJSON();1621}16221623export async function addToAllowListExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId | CrossAccountId) {1624  await usingApi(async (api) => {1625    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.false;16261627    // Run the transaction1628    const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1629    const events = await submitTransactionAsync(sender, tx);1630    const result = getGenericResult(events);1631    expect(result.success).to.be.true;16321633    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;1634  });1635}16361637export async function addToAllowListAgainExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId) {1638  await usingApi(async (api) => {16391640    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;16411642    // Run the transaction1643    const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1644    const events = await submitTransactionAsync(sender, tx);1645    const result = getGenericResult(events);1646    expect(result.success).to.be.true;16471648    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;1649  });1650}16511652export async function addToAllowListExpectFail(sender: IKeyringPair, collectionId: number, address: string | AccountId) {1653  await usingApi(async (api) => {16541655    // Run the transaction1656    const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1657    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1658    const result = getGenericResult(events);16591660    // What to expect1661    // tslint:disable-next-line:no-unused-expression1662    expect(result.success).to.be.false;1663  });1664}16651666export async function removeFromAllowListExpectSuccess(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1667  await usingApi(async (api) => {1668    // Run the transaction1669    const tx = api.tx.unique.removeFromAllowList(collectionId, normalizeAccountId(address));1670    const events = await submitTransactionAsync(sender, tx);1671    const result = getGenericResult(events);16721673    // What to expect1674    // tslint:disable-next-line:no-unused-expression1675    expect(result.success).to.be.true;1676  });1677}16781679export async function removeFromAllowListExpectFailure(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1680  await usingApi(async (api) => {1681    // Run the transaction1682    const tx = api.tx.unique.removeFromAllowList(collectionId, normalizeAccountId(address));1683    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1684    const result = getGenericResult(events);16851686    // What to expect1687    // tslint:disable-next-line:no-unused-expression1688    expect(result.success).to.be.false;1689  });1690}16911692export const getDetailedCollectionInfo = async (api: ApiPromise, collectionId: number)1693  : Promise<UpDataStructsRpcCollection | null> => {1694  return (await api.rpc.unique.collectionById(collectionId)).unwrapOr(null);1695};16961697export const getCreatedCollectionCount = async (api: ApiPromise): Promise<number> => {1698  // set global object - collectionsCount1699  return (await api.rpc.unique.collectionStats()).created.toNumber();1700};17011702export async function queryCollectionExpectSuccess(api: ApiPromise, collectionId: number): Promise<UpDataStructsRpcCollection> {1703  return (await api.rpc.unique.collectionById(collectionId)).unwrap();1704}17051706export async function waitNewBlocks(blocksCount = 1): Promise<void> {1707  await usingApi(async (api) => {1708    const promise = new Promise<void>(async (resolve) => {1709      const unsubscribe = await api.rpc.chain.subscribeNewHeads(() => {1710        if (blocksCount > 0) {1711          blocksCount--;1712        } else {1713          unsubscribe();1714          resolve();1715        }1716      });1717    });1718    return promise;1719  });1720}17211722export async function repartitionRFT(1723  api: ApiPromise,1724  collectionId: number,1725  sender: IKeyringPair,1726  tokenId: number,1727  amount: bigint,1728): Promise<boolean> {1729  const tx = api.tx.unique.repartition(collectionId, tokenId, amount);1730  const events = await submitTransactionAsync(sender, tx);1731  const result = getGenericResult(events);17321733  return result.success;1734}17351736export async function itApi(name: string, cb: (apis: { api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair }) => any, opts: { only?: boolean, skip?: boolean } = {}) {1737  let i: any = it;1738  if (opts.only) i = i.only;1739  else if (opts.skip) i = i.skip;1740  i(name, async () => {1741    await usingApi(async (api, privateKeyWrapper) => {1742      await cb({api, privateKeyWrapper});1743    });1744  });1745}17461747itApi.only = (name: string, cb: (apis: { api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair }) => any) => itApi(name, cb, {only: true});1748itApi.skip = (name: string, cb: (apis: { api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair }) => any) => itApi(name, cb, {skip: true});
after · tests/src/util/helpers.ts
1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617import '../interfaces/augment-api-rpc';18import '../interfaces/augment-api-query';19import {ApiPromise} from '@polkadot/api';20import type {AccountId, EventRecord, Event} from '@polkadot/types/interfaces';21import type {GenericEventData} from '@polkadot/types';22import {AnyTuple, IEvent, IKeyringPair} from '@polkadot/types/types';23import {evmToAddress} from '@polkadot/util-crypto';24import BN from 'bn.js';25import chai from 'chai';26import chaiAsPromised from 'chai-as-promised';27import {default as usingApi, executeTransaction, submitTransactionAsync, submitTransactionExpectFailAsync} from '../substrate/substrate-api';28import {hexToStr, strToUTF16, utf16ToStr} from './util';29import {UpDataStructsRpcCollection, UpDataStructsCreateItemData, UpDataStructsProperty} from '@polkadot/types/lookup';30import {UpDataStructsTokenChild} from '../interfaces';31import { Context } from 'mocha';3233chai.use(chaiAsPromised);34const expect = chai.expect;3536export type CrossAccountId = {37  Substrate: string,38} | {39  Ethereum: string,40};414243export enum Pallets {44  Inflation = 'inflation',45  RmrkCore = 'rmrkcore',46  RmrkEquip = 'rmrkequip',47  ReFungible = 'refungible',48  Fungible = 'fungible',49  NFT = 'nonfungible',50}5152export async function isUnique(): Promise<boolean> {53  return usingApi(async api => {54    const chain = await api.rpc.system.chain();5556    return chain.eq('UNIQUE');57  });58}5960export async function isQuartz(): Promise<boolean> {61  return usingApi(async api => {62    const chain = await api.rpc.system.chain();63    64    return chain.eq('QUARTZ');65  });66}6768let modulesNames: any;69export function getModuleNames(api: ApiPromise): string[] {70  if (typeof modulesNames === 'undefined') 71    modulesNames = api.runtimeMetadata.asLatest.pallets.map(m => m.name.toString().toLowerCase());72  return modulesNames;73}7475export function requirePallets(mocha: Context, api: ApiPromise, requiredPallets: string[]) {76  const pallets = getModuleNames(api);7778  const isAllPalletsPresent = requiredPallets.every(p => pallets.includes(p));7980  if (!isAllPalletsPresent) {81    mocha.skip();82  }83}8485export function normalizeAccountId(input: string | AccountId | CrossAccountId | IKeyringPair): CrossAccountId {86  if (typeof input === 'string') {87    if (input.length >= 47) {88      return {Substrate: input};89    } else if (input.length === 42 && input.startsWith('0x')) {90      return {Ethereum: input.toLowerCase()};91    } else if (input.length === 40 && !input.startsWith('0x')) {92      return {Ethereum: '0x' + input.toLowerCase()};93    } else {94      throw new Error(`Unknown address format: "${input}"`);95    }96  }97  if ('address' in input) {98    return {Substrate: input.address};99  }100  if ('Ethereum' in input) {101    return {102      Ethereum: input.Ethereum.toLowerCase(),103    };104  } else if ('ethereum' in input) {105    return {106      Ethereum: (input as any).ethereum.toLowerCase(),107    };108  } else if ('Substrate' in input) {109    return input;110  } else if ('substrate' in input) {111    return {112      Substrate: (input as any).substrate,113    };114  }115116  // AccountId117  return {Substrate: input.toString()};118}119export function toSubstrateAddress(input: string | CrossAccountId | IKeyringPair): string {120  input = normalizeAccountId(input);121  if ('Substrate' in input) {122    return input.Substrate;123  } else {124    return evmToAddress(input.Ethereum);125  }126}127128export const U128_MAX = (1n << 128n) - 1n;129130const MICROUNIQUE = 1_000_000_000_000n;131const MILLIUNIQUE = 1_000n * MICROUNIQUE;132const CENTIUNIQUE = 10n * MILLIUNIQUE;133export const UNIQUE = 100n * CENTIUNIQUE;134135interface GenericResult<T> {136  success: boolean;137  data: T | null;138}139140interface CreateCollectionResult {141  success: boolean;142  collectionId: number;143}144145interface CreateItemResult {146  success: boolean;147  collectionId: number;148  itemId: number;149  recipient?: CrossAccountId;150  amount?: number;151}152153interface DestroyItemResult {154  success: boolean;155  collectionId: number;156  itemId: number;157  owner: CrossAccountId;158  amount: number;159}160161interface TransferResult {162  collectionId: number;163  itemId: number;164  sender?: CrossAccountId;165  recipient?: CrossAccountId;166  value: bigint;167}168169interface IReFungibleOwner {170  fraction: BN;171  owner: number[];172}173174interface IGetMessage {175  checkMsgUnqMethod: string;176  checkMsgTrsMethod: string;177  checkMsgSysMethod: string;178}179180export interface IFungibleTokenDataType {181  value: number;182}183184export interface IChainLimits {185  collectionNumbersLimit: number;186  accountTokenOwnershipLimit: number;187  collectionsAdminsLimit: number;188  customDataLimit: number;189  nftSponsorTransferTimeout: number;190  fungibleSponsorTransferTimeout: number;191  refungibleSponsorTransferTimeout: number;192  //offchainSchemaLimit: number;193  //constOnChainSchemaLimit: number;194}195196export interface IReFungibleTokenDataType {197  owner: IReFungibleOwner[];198}199200export function uniqueEventMessage(events: EventRecord[]): IGetMessage {201  let checkMsgUnqMethod = '';202  let checkMsgTrsMethod = '';203  let checkMsgSysMethod = '';204  events.forEach(({event: {method, section}}) => {205    if (section === 'common') {206      checkMsgUnqMethod = method;207    } else if (section === 'treasury') {208      checkMsgTrsMethod = method;209    } else if (section === 'system') {210      checkMsgSysMethod = method;211    } else { return null; }212  });213  const result: IGetMessage = {214    checkMsgUnqMethod,215    checkMsgTrsMethod,216    checkMsgSysMethod,217  };218  return result;219}220221export function getEvent<T extends Event>(events: EventRecord[], check: (event: IEvent<AnyTuple>) => event is T): T | undefined {222  const event = events.find(r => check(r.event));223  if (!event) return;224  return event.event as T;225}226227export function getGenericResult<T>(events: EventRecord[]): GenericResult<T>;228export function getGenericResult<T>(229  events: EventRecord[],230  expectSection: string,231  expectMethod: string,232  extractAction: (data: GenericEventData) => T233): GenericResult<T>;234235export function getGenericResult<T>(236  events: EventRecord[],237  expectSection?: string,238  expectMethod?: string,239  extractAction?: (data: GenericEventData) => T,240): GenericResult<T> {241  let success = false;242  let successData = null;243244  events.forEach(({event: {data, method, section}}) => {245    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);246    if (method === 'ExtrinsicSuccess') {247      success = true;248    } else if ((expectSection == section) && (expectMethod == method)) {249      successData = extractAction!(data as any);250    }251  });252253  const result: GenericResult<T> = {254    success,255    data: successData,256  };257  return result;258}259260export function getCreateCollectionResult(events: EventRecord[]): CreateCollectionResult {261  const genericResult = getGenericResult(events, 'common', 'CollectionCreated', (data) => parseInt(data[0].toString(), 10));262  const result: CreateCollectionResult = {263    success: genericResult.success,264    collectionId: genericResult.data ?? 0,265  };266  return result;267}268269export function getCreateItemsResult(events: EventRecord[]): CreateItemResult[] {270  const results: CreateItemResult[] = [];271  272  const genericResult = getGenericResult<CreateItemResult[]>(events, 'common', 'ItemCreated', (data) => {273    const collectionId = parseInt(data[0].toString(), 10);274    const itemId = parseInt(data[1].toString(), 10);275    const recipient = normalizeAccountId(data[2].toJSON() as any);276    const amount = parseInt(data[3].toString(), 10);277278    const itemRes: CreateItemResult = {279      success: true,280      collectionId,281      itemId,282      recipient,283      amount,284    };285286    results.push(itemRes);287    return results;288  });289290  if (!genericResult.success) return [];291  return results;292}293294export function getCreateItemResult(events: EventRecord[]): CreateItemResult {295  const genericResult = getGenericResult(events, 'common', 'ItemCreated', (data) => data.map(function(value) { return value.toJSON(); }));296  297  if (genericResult.data == null) 298    return {299      success: genericResult.success,300      collectionId: 0,301      itemId: 0,302      amount: 0,303    };304  else 305    return {306      success: genericResult.success,307      collectionId: genericResult.data[0] as number,308      itemId: genericResult.data[1] as number,309      recipient: normalizeAccountId(genericResult.data![2] as any),310      amount: genericResult.data[3] as number,311    };312}313314export function getDestroyItemsResult(events: EventRecord[]): DestroyItemResult[] {315  const results: DestroyItemResult[] = [];316  317  const genericResult = getGenericResult<DestroyItemResult[]>(events, 'common', 'ItemDestroyed', (data) => {318    const collectionId = parseInt(data[0].toString(), 10);319    const itemId = parseInt(data[1].toString(), 10);320    const owner = normalizeAccountId(data[2].toJSON() as any);321    const amount = parseInt(data[3].toString(), 10);322323    const itemRes: DestroyItemResult = {324      success: true,325      collectionId,326      itemId,327      owner,328      amount,329    };330331    results.push(itemRes);332    return results;333  });334335  if (!genericResult.success) return [];336  return results;337}338339export function getTransferResult(api: ApiPromise, events: EventRecord[]): TransferResult {340  for (const {event} of events) {341    if (api.events.common.Transfer.is(event)) {342      const [collection, token, sender, recipient, value] = event.data;343      return {344        collectionId: collection.toNumber(),345        itemId: token.toNumber(),346        sender: normalizeAccountId(sender.toJSON() as any),347        recipient: normalizeAccountId(recipient.toJSON() as any),348        value: value.toBigInt(),349      };350    }351  }352  throw new Error('no transfer event');353}354355interface Nft {356  type: 'NFT';357}358359interface Fungible {360  type: 'Fungible';361  decimalPoints: number;362}363364interface ReFungible {365  type: 'ReFungible';366}367368export type CollectionMode = Nft | Fungible | ReFungible;369370export type Property = {371  key: any,372  value: any,373};374375type Permission = {376  mutable: boolean;377  collectionAdmin: boolean;378  tokenOwner: boolean;379}380381type PropertyPermission = {382  key: any;383  permission: Permission;384}385386export type CreateCollectionParams = {387  mode: CollectionMode,388  name: string,389  description: string,390  tokenPrefix: string,391  properties?: Array<Property>,392  propPerm?: Array<PropertyPermission>393};394395const defaultCreateCollectionParams: CreateCollectionParams = {396  description: 'description',397  mode: {type: 'NFT'},398  name: 'name',399  tokenPrefix: 'prefix',400};401402export async function403createCollection(404  api: ApiPromise,405  sender: IKeyringPair,406  params: Partial<CreateCollectionParams> = {},407): Promise<CreateCollectionResult> {408  const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};409410  let modeprm = {};411  if (mode.type === 'NFT') {412    modeprm = {nft: null};413  } else if (mode.type === 'Fungible') {414    modeprm = {fungible: mode.decimalPoints};415  } else if (mode.type === 'ReFungible') {416    modeprm = {refungible: null};417  }418419  const tx = api.tx.unique.createCollectionEx({420    name: strToUTF16(name),421    description: strToUTF16(description),422    tokenPrefix: strToUTF16(tokenPrefix),423    mode: modeprm as any,424  });425  const events = await submitTransactionAsync(sender, tx);426  return getCreateCollectionResult(events);427}428429export async function createCollectionExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {430  const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};431432  let collectionId = 0;433  await usingApi(async (api, privateKeyWrapper) => {434    // Get number of collections before the transaction435    const collectionCountBefore = await getCreatedCollectionCount(api);436437    // Run the CreateCollection transaction438    const alicePrivateKey = privateKeyWrapper('//Alice');439440    const result = await createCollection(api, alicePrivateKey, params);441442    // Get number of collections after the transaction443    const collectionCountAfter = await getCreatedCollectionCount(api);444445    // Get the collection446    const collection = await queryCollectionExpectSuccess(api, result.collectionId);447448    // What to expect449    // tslint:disable-next-line:no-unused-expression450    expect(result.success).to.be.true;451    expect(result.collectionId).to.be.equal(collectionCountAfter);452    // tslint:disable-next-line:no-unused-expression453    expect(collection).to.be.not.null;454    expect(collectionCountAfter).to.be.equal(collectionCountBefore + 1, 'Error: NFT collection NOT created.');455    expect(collection.owner.toString()).to.be.equal(toSubstrateAddress(alicePrivateKey));456    expect(utf16ToStr(collection.name.toJSON() as any)).to.be.equal(name);457    expect(utf16ToStr(collection.description.toJSON() as any)).to.be.equal(description);458    expect(hexToStr(collection.tokenPrefix.toJSON())).to.be.equal(tokenPrefix);459460    collectionId = result.collectionId;461  });462463  return collectionId;464}465466export async function createCollectionWithPropsExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {467  const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};468469  let collectionId = 0;470  await usingApi(async (api, privateKeyWrapper) => {471    // Get number of collections before the transaction472    const collectionCountBefore = await getCreatedCollectionCount(api);473474    // Run the CreateCollection transaction475    const alicePrivateKey = privateKeyWrapper('//Alice');476477    let modeprm = {};478    if (mode.type === 'NFT') {479      modeprm = {nft: null};480    } else if (mode.type === 'Fungible') {481      modeprm = {fungible: mode.decimalPoints};482    } else if (mode.type === 'ReFungible') {483      modeprm = {refungible: null};484    }485486    const tx = api.tx.unique.createCollectionEx({name: strToUTF16(name), description: strToUTF16(description), tokenPrefix: strToUTF16(tokenPrefix), mode: modeprm as any, properties: params.properties, tokenPropertyPermissions: params.propPerm});487    const events = await submitTransactionAsync(alicePrivateKey, tx);488    const result = getCreateCollectionResult(events);489490    // Get number of collections after the transaction491    const collectionCountAfter = await getCreatedCollectionCount(api);492493    // Get the collection494    const collection = await queryCollectionExpectSuccess(api, result.collectionId);495496    // What to expect497    // tslint:disable-next-line:no-unused-expression498    expect(result.success).to.be.true;499    expect(result.collectionId).to.be.equal(collectionCountAfter);500    // tslint:disable-next-line:no-unused-expression501    expect(collection).to.be.not.null;502    expect(collectionCountAfter).to.be.equal(collectionCountBefore + 1, 'Error: NFT collection NOT created.');503    expect(collection.owner.toString()).to.be.equal(toSubstrateAddress(alicePrivateKey));504    expect(utf16ToStr(collection.name.toJSON() as any)).to.be.equal(name);505    expect(utf16ToStr(collection.description.toJSON() as any)).to.be.equal(description);506    expect(hexToStr(collection.tokenPrefix.toJSON())).to.be.equal(tokenPrefix);507508509    collectionId = result.collectionId;510  });511512  return collectionId;513}514515export async function createCollectionWithPropsExpectFailure(params: Partial<CreateCollectionParams> = {}) {516  const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};517518  await usingApi(async (api, privateKeyWrapper) => {519    // Get number of collections before the transaction520    const collectionCountBefore = await getCreatedCollectionCount(api);521522    // Run the CreateCollection transaction523    const alicePrivateKey = privateKeyWrapper('//Alice');524525    let modeprm = {};526    if (mode.type === 'NFT') {527      modeprm = {nft: null};528    } else if (mode.type === 'Fungible') {529      modeprm = {fungible: mode.decimalPoints};530    } else if (mode.type === 'ReFungible') {531      modeprm = {refungible: null};532    }533534    const tx = api.tx.unique.createCollectionEx({name: strToUTF16(name), description: strToUTF16(description), tokenPrefix: strToUTF16(tokenPrefix), mode: modeprm as any, properties: params.properties, tokenPropertyPermissions: params.propPerm});535    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;536537538    // Get number of collections after the transaction539    const collectionCountAfter = await getCreatedCollectionCount(api);540541    expect(collectionCountAfter).to.be.equal(collectionCountBefore, 'Error: Collection with incorrect data created.');542  });543}544545export async function createCollectionExpectFailure(params: Partial<CreateCollectionParams> = {}) {546  const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};547548  let modeprm = {};549  if (mode.type === 'NFT') {550    modeprm = {nft: null};551  } else if (mode.type === 'Fungible') {552    modeprm = {fungible: mode.decimalPoints};553  } else if (mode.type === 'ReFungible') {554    modeprm = {refungible: null};555  }556557  await usingApi(async (api, privateKeyWrapper) => {558    // Get number of collections before the transaction559    const collectionCountBefore = await getCreatedCollectionCount(api);560561    // Run the CreateCollection transaction562    const alicePrivateKey = privateKeyWrapper('//Alice');563    const tx = api.tx.unique.createCollectionEx({name: strToUTF16(name), description: strToUTF16(description), tokenPrefix: strToUTF16(tokenPrefix), mode: modeprm as any});564    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;565566    // Get number of collections after the transaction567    const collectionCountAfter = await getCreatedCollectionCount(api);568569    // What to expect570    expect(collectionCountAfter).to.be.equal(collectionCountBefore, 'Error: Collection with incorrect data created.');571  });572}573574export async function findUnusedAddress(api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair, seedAddition = ''): Promise<IKeyringPair> {575  let bal = 0n;576  let unused;577  do {578    const randomSeed = 'seed' + Math.floor(Math.random() * Math.floor(10000)) + seedAddition;579    unused = privateKeyWrapper(`//${randomSeed}`);580    bal = (await api.query.system.account(unused.address)).data.free.toBigInt();581  } while (bal !== 0n);582  return unused;583}584585export async function getAllowance(api: ApiPromise, collectionId: number, owner: CrossAccountId | string | IKeyringPair, approved: CrossAccountId | string | IKeyringPair, tokenId: number) {586  return (await api.rpc.unique.allowance(collectionId, normalizeAccountId(owner), normalizeAccountId(approved), tokenId)).toBigInt();587}588589export function findUnusedAddresses(api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair, amount: number): Promise<IKeyringPair[]> {590  return Promise.all(new Array(amount).fill(null).map(() => findUnusedAddress(api, privateKeyWrapper, '_' + Date.now())));591}592593export async function findNotExistingCollection(api: ApiPromise): Promise<number> {594  const totalNumber = await getCreatedCollectionCount(api);595  const newCollection: number = totalNumber + 1;596  return newCollection;597}598599function getDestroyResult(events: EventRecord[]): boolean {600  let success = false;601  events.forEach(({event: {method}}) => {602    if (method == 'ExtrinsicSuccess') {603      success = true;604    }605  });606  return success;607}608609export async function destroyCollectionExpectFailure(collectionId: number, senderSeed = '//Alice') {610  await usingApi(async (api, privateKeyWrapper) => {611    // Run the DestroyCollection transaction612    const alicePrivateKey = privateKeyWrapper(senderSeed);613    const tx = api.tx.unique.destroyCollection(collectionId);614    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;615  });616}617618export async function destroyCollectionExpectSuccess(collectionId: number, senderSeed = '//Alice') {619  await usingApi(async (api, privateKeyWrapper) => {620    // Run the DestroyCollection transaction621    const alicePrivateKey = privateKeyWrapper(senderSeed);622    const tx = api.tx.unique.destroyCollection(collectionId);623    const events = await submitTransactionAsync(alicePrivateKey, tx);624    const result = getDestroyResult(events);625    expect(result).to.be.true;626627    // What to expect628    expect(await getDetailedCollectionInfo(api, collectionId)).to.be.null;629  });630}631632export async function setCollectionLimitsExpectSuccess(sender: IKeyringPair, collectionId: number, limits: any) {633  await usingApi(async (api) => {634    const tx = api.tx.unique.setCollectionLimits(collectionId, limits);635    const events = await submitTransactionAsync(sender, tx);636    const result = getGenericResult(events);637638    expect(result.success).to.be.true;639  });640}641642export const setCollectionPermissionsExpectSuccess = async (sender: IKeyringPair, collectionId: number, permissions: any) => {643  await usingApi(async(api) => {644    const tx = api.tx.unique.setCollectionPermissions(collectionId, permissions);645    const events = await submitTransactionAsync(sender, tx);646    const result = getGenericResult(events);647648    expect(result.success).to.be.true;649  });650};651652export async function setCollectionLimitsExpectFailure(sender: IKeyringPair, collectionId: number, limits: any) {653  await usingApi(async (api) => {654    const tx = api.tx.unique.setCollectionLimits(collectionId, limits);655    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;656    const result = getGenericResult(events);657658    expect(result.success).to.be.false;659  });660}661662export async function setCollectionSponsorExpectSuccess(collectionId: number, sponsor: string, sender = '//Alice') {663  await usingApi(async (api, privateKeyWrapper) => {664665    // Run the transaction666    const senderPrivateKey = privateKeyWrapper(sender);667    const tx = api.tx.unique.setCollectionSponsor(collectionId, sponsor);668    const events = await submitTransactionAsync(senderPrivateKey, tx);669    const result = getGenericResult(events);670671    // Get the collection672    const collection = await queryCollectionExpectSuccess(api, collectionId);673674    // What to expect675    expect(result.success).to.be.true;676    expect(collection.sponsorship.toJSON()).to.deep.equal({677      unconfirmed: sponsor,678    });679  });680}681682export async function removeCollectionSponsorExpectSuccess(collectionId: number, sender = '//Alice') {683  await usingApi(async (api, privateKeyWrapper) => {684685    // Run the transaction686    const alicePrivateKey = privateKeyWrapper(sender);687    const tx = api.tx.unique.removeCollectionSponsor(collectionId);688    const events = await submitTransactionAsync(alicePrivateKey, tx);689    const result = getGenericResult(events);690691    // Get the collection692    const collection = await queryCollectionExpectSuccess(api, collectionId);693694    // What to expect695    expect(result.success).to.be.true;696    expect(collection.sponsorship.toJSON()).to.be.deep.equal({disabled: null});697  });698}699700export async function removeCollectionSponsorExpectFailure(collectionId: number, senderSeed = '//Alice') {701  await usingApi(async (api, privateKeyWrapper) => {702703    // Run the transaction704    const alicePrivateKey = privateKeyWrapper(senderSeed);705    const tx = api.tx.unique.removeCollectionSponsor(collectionId);706    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;707  });708}709710export async function setCollectionSponsorExpectFailure(collectionId: number, sponsor: string, senderSeed = '//Alice') {711  await usingApi(async (api, privateKeyWrapper) => {712713    // Run the transaction714    const alicePrivateKey = privateKeyWrapper(senderSeed);715    const tx = api.tx.unique.setCollectionSponsor(collectionId, sponsor);716    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;717  });718}719720export async function confirmSponsorshipExpectSuccess(collectionId: number, senderSeed = '//Alice') {721  await usingApi(async (api, privateKeyWrapper) => {722723    // Run the transaction724    const sender = privateKeyWrapper(senderSeed);725    await confirmSponsorshipByKeyExpectSuccess(collectionId, sender);726  });727}728729export async function confirmSponsorshipByKeyExpectSuccess(collectionId: number, sender: IKeyringPair) {730  await usingApi(async (api, privateKeyWrapper) => {731732    // Run the transaction733    const tx = api.tx.unique.confirmSponsorship(collectionId);734    const events = await submitTransactionAsync(sender, tx);735    const result = getGenericResult(events);736737    // Get the collection738    const collection = await queryCollectionExpectSuccess(api, collectionId);739740    // What to expect741    expect(result.success).to.be.true;742    expect(collection.sponsorship.toJSON()).to.be.deep.equal({743      confirmed: sender.address,744    });745  });746}747748749export async function confirmSponsorshipExpectFailure(collectionId: number, senderSeed = '//Alice') {750  await usingApi(async (api, privateKeyWrapper) => {751752    // Run the transaction753    const sender = privateKeyWrapper(senderSeed);754    const tx = api.tx.unique.confirmSponsorship(collectionId);755    await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;756  });757}758759export async function enableContractSponsoringExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {760  await usingApi(async (api) => {761    const tx = api.tx.unique.enableContractSponsoring(contractAddress, enable);762    const events = await submitTransactionAsync(sender, tx);763    const result = getGenericResult(events);764765    expect(result.success).to.be.true;766  });767}768769export async function enableContractSponsoringExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {770  await usingApi(async (api) => {771    const tx = api.tx.unique.enableContractSponsoring(contractAddress, enable);772    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;773    const result = getGenericResult(events);774775    expect(result.success).to.be.false;776  });777}778779export async function setTransferFlagExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {780781  await usingApi(async (api) => {782783    const tx = api.tx.unique.setTransfersEnabledFlag(collectionId, enabled);784    const events = await submitTransactionAsync(sender, tx);785    const result = getGenericResult(events);786787    expect(result.success).to.be.true;788  });789}790791export async function setTransferFlagExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {792793  await usingApi(async (api) => {794795    const tx = api.tx.unique.setTransfersEnabledFlag(collectionId, enabled);796    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;797    const result = getGenericResult(events);798799    expect(result.success).to.be.false;800  });801}802803export async function setContractSponsoringRateLimitExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {804  await usingApi(async (api) => {805    const tx = api.tx.unique.setContractSponsoringRateLimit(contractAddress, rateLimit);806    const events = await submitTransactionAsync(sender, tx);807    const result = getGenericResult(events);808809    expect(result.success).to.be.true;810  });811}812813export async function setContractSponsoringRateLimitExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {814  await usingApi(async (api) => {815    const tx = api.tx.unique.setContractSponsoringRateLimit(contractAddress, rateLimit);816    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;817    const result = getGenericResult(events);818819    expect(result.success).to.be.false;820  });821}822823export async function getNextSponsored(824  api: ApiPromise,825  collectionId: number,826  account: string | CrossAccountId,827  tokenId: number,828): Promise<number> {829  return Number((await api.rpc.unique.nextSponsored(collectionId, account, tokenId)).unwrapOr(-1));830}831832export async function toggleContractAllowlistExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, value = true) {833  await usingApi(async (api) => {834    const tx = api.tx.unique.toggleContractAllowList(contractAddress, value);835    const events = await submitTransactionAsync(sender, tx);836    const result = getGenericResult(events);837838    expect(result.success).to.be.true;839  });840}841842export async function isAllowlistedInContract(contractAddress: AccountId | string, user: string) {843  let allowlisted = false;844  await usingApi(async (api) => {845    allowlisted = (await api.query.unique.contractAllowList(contractAddress, user)).toJSON() as boolean;846  });847  return allowlisted;848}849850export async function addToContractAllowListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {851  await usingApi(async (api) => {852    const tx = api.tx.unique.addToContractAllowList(contractAddress.toString(), user.toString());853    const events = await submitTransactionAsync(sender, tx);854    const result = getGenericResult(events);855856    expect(result.success).to.be.true;857  });858}859860export async function removeFromContractAllowListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {861  await usingApi(async (api) => {862    const tx = api.tx.unique.removeFromContractAllowList(contractAddress.toString(), user.toString());863    const events = await submitTransactionAsync(sender, tx);864    const result = getGenericResult(events);865866    expect(result.success).to.be.true;867  });868}869870export async function removeFromContractAllowListExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {871  await usingApi(async (api) => {872    const tx = api.tx.unique.removeFromContractAllowList(contractAddress.toString(), user.toString());873    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;874    const result = getGenericResult(events);875876    expect(result.success).to.be.false;877  });878}879880export interface CreateFungibleData {881  readonly Value: bigint;882}883884export interface CreateReFungibleData { }885export interface CreateNftData { }886887export type CreateItemData = {888  NFT: CreateNftData;889} | {890  Fungible: CreateFungibleData;891} | {892  ReFungible: CreateReFungibleData;893};894895export async function burnItem(api: ApiPromise, sender: IKeyringPair, collectionId: number, tokenId: number, value: number | bigint) : Promise<boolean> {896  const tx = api.tx.unique.burnItem(collectionId, tokenId, value);897  const events = await submitTransactionAsync(sender, tx);898  return getGenericResult(events).success;899}900901export async function burnItemExpectSuccess(sender: IKeyringPair, collectionId: number, tokenId: number, value: number | bigint = 1) {902  await usingApi(async (api) => {903    const balanceBefore = await getBalance(api, collectionId, normalizeAccountId(sender), tokenId);904    // if burning token by admin - use adminButnItemExpectSuccess905    expect(balanceBefore >= BigInt(value)).to.be.true;906907    expect(await burnItem(api, sender, collectionId, tokenId, value)).to.be.true;908909    const balanceAfter = await getBalance(api, collectionId, normalizeAccountId(sender), tokenId);910    expect(balanceAfter + BigInt(value)).to.be.equal(balanceBefore);911  });912}913914export async function burnItemExpectFailure(sender: IKeyringPair, collectionId: number, tokenId: number, value: number | bigint = 1) {915  await usingApi(async (api) => {916    const tx = api.tx.unique.burnItem(collectionId, tokenId, value);917918    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;919    const result = getCreateCollectionResult(events);920    // tslint:disable-next-line:no-unused-expression921    expect(result.success).to.be.false;922  });923}924925export async function burnFromExpectSuccess(sender: IKeyringPair, from: IKeyringPair | CrossAccountId, collectionId: number, tokenId: number, value: number | bigint = 1) {926  await usingApi(async (api) => {927    const tx = api.tx.unique.burnFrom(collectionId, normalizeAccountId(from), tokenId, value);928    const events = await submitTransactionAsync(sender, tx);929    return getGenericResult(events).success;930  });931}932933export async function934approve(935  api: ApiPromise,936  collectionId: number,937  tokenId: number, owner: IKeyringPair, approved: CrossAccountId | string | IKeyringPair, amount: number | bigint,938) {939  const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);940  const events = await submitTransactionAsync(owner, approveUniqueTx);941  return getGenericResult(events).success;942}943944export async function945approveExpectSuccess(946  collectionId: number,947  tokenId: number, owner: IKeyringPair, approved: CrossAccountId | string, amount: number | bigint = 1,948) {949  await usingApi(async (api: ApiPromise) => {950    const result = await approve(api, collectionId, tokenId, owner, approved, amount);951    expect(result).to.be.true;952953    expect(await getAllowance(api, collectionId, owner, approved, tokenId)).to.be.equal(BigInt(amount));954  });955}956957export async function adminApproveFromExpectSuccess(958  collectionId: number,959  tokenId: number, admin: IKeyringPair, owner: CrossAccountId | string, approved: CrossAccountId | string, amount: number | bigint = 1,960) {961  await usingApi(async (api: ApiPromise) => {962    const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);963    const events = await submitTransactionAsync(admin, approveUniqueTx);964    const result = getGenericResult(events);965    expect(result.success).to.be.true;966967    expect(await getAllowance(api, collectionId, owner, approved, tokenId)).to.be.equal(BigInt(amount));968  });969}970971export async function972transferFrom(973  api: ApiPromise,974  collectionId: number,975  tokenId: number,976  accountApproved: IKeyringPair,977  accountFrom: IKeyringPair | CrossAccountId,978  accountTo: IKeyringPair | CrossAccountId,979  value: number | bigint,980) {981  const from = normalizeAccountId(accountFrom);982  const to = normalizeAccountId(accountTo);983  const transferFromTx = api.tx.unique.transferFrom(from, to, collectionId, tokenId, value);984  const events = await submitTransactionAsync(accountApproved, transferFromTx);985  return getGenericResult(events).success;986}987988export async function989transferFromExpectSuccess(990  collectionId: number,991  tokenId: number,992  accountApproved: IKeyringPair,993  accountFrom: IKeyringPair | CrossAccountId,994  accountTo: IKeyringPair | CrossAccountId,995  value: number | bigint = 1,996  type = 'NFT',997) {998  await usingApi(async (api: ApiPromise) => {999    const from = normalizeAccountId(accountFrom);1000    const to = normalizeAccountId(accountTo);1001    let balanceBefore = 0n;1002    if (type === 'Fungible' || type === 'ReFungible') {1003      balanceBefore = await getBalance(api, collectionId, to, tokenId);1004    }1005    expect(await transferFrom(api, collectionId, tokenId, accountApproved, accountFrom, accountTo, value)).to.be.true;1006    if (type === 'NFT') {1007      expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(to);1008    }1009    if (type === 'Fungible') {1010      const balanceAfter = await getBalance(api, collectionId, to, tokenId);1011      if (JSON.stringify(to) !== JSON.stringify(from)) {1012        expect(balanceAfter - balanceBefore).to.be.equal(BigInt(value));1013      } else {1014        expect(balanceAfter).to.be.equal(balanceBefore);1015      }1016    }1017    if (type === 'ReFungible') {1018      expect(await getBalance(api, collectionId, to, tokenId)).to.be.equal(balanceBefore + BigInt(value));1019    }1020  });1021}10221023export async function1024transferFromExpectFail(1025  collectionId: number,1026  tokenId: number,1027  accountApproved: IKeyringPair,1028  accountFrom: IKeyringPair,1029  accountTo: IKeyringPair,1030  value: number | bigint = 1,1031) {1032  await usingApi(async (api: ApiPromise) => {1033    const transferFromTx = api.tx.unique.transferFrom(normalizeAccountId(accountFrom.address), normalizeAccountId(accountTo.address), collectionId, tokenId, value);1034    const events = await expect(submitTransactionExpectFailAsync(accountApproved, transferFromTx)).to.be.rejected;1035    const result = getCreateCollectionResult(events);1036    // tslint:disable-next-line:no-unused-expression1037    expect(result.success).to.be.false;1038  });1039}10401041/* eslint no-async-promise-executor: "off" */1042export async function getBlockNumber(api: ApiPromise): Promise<number> {1043  return new Promise<number>(async (resolve) => {1044    const unsubscribe = await api.rpc.chain.subscribeNewHeads((head) => {1045      unsubscribe();1046      resolve(head.number.toNumber());1047    });1048  });1049}10501051export async function addCollectionAdminExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | CrossAccountId) {1052  await usingApi(async (api) => {1053    const changeAdminTx = api.tx.unique.addCollectionAdmin(collectionId, normalizeAccountId(address));1054    const events = await submitTransactionAsync(sender, changeAdminTx);1055    const result = getCreateCollectionResult(events);1056    expect(result.success).to.be.true;1057  });1058}10591060export async function adminApproveFromExpectFail(1061  collectionId: number,1062  tokenId: number, admin: IKeyringPair, owner: CrossAccountId | string, approved: CrossAccountId | string, amount: number | bigint = 1,1063) {1064  await usingApi(async (api: ApiPromise) => {1065    const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);1066    const events = await expect(submitTransactionAsync(admin, approveUniqueTx)).to.be.rejected;1067    const result = getGenericResult(events);1068    expect(result.success).to.be.false;1069  });1070}10711072export async function1073getFreeBalance(account: IKeyringPair): Promise<bigint> {1074  let balance = 0n;1075  await usingApi(async (api) => {1076    balance = BigInt((await api.query.system.account(account.address)).data.free.toString());1077  });10781079  return balance;1080}10811082export async function transferBalanceTo(api: ApiPromise, source: IKeyringPair, target: string, amount = 1000n * UNIQUE) {1083  const tx = api.tx.balances.transfer(target, amount);1084  const events = await submitTransactionAsync(source, tx);1085  const result = getGenericResult(events);1086  expect(result.success).to.be.true;1087}10881089export async function1090scheduleExpectSuccess(1091  operationTx: any,1092  sender: IKeyringPair,1093  blockSchedule: number,1094  scheduledId: string,1095  period = 1,1096  repetitions = 1,1097) {1098  await usingApi(async (api: ApiPromise) => {1099    const blockNumber: number | undefined = await getBlockNumber(api);1100    const expectedBlockNumber = blockNumber + blockSchedule;11011102    expect(blockNumber).to.be.greaterThan(0);1103    const scheduleTx = api.tx.scheduler.scheduleNamed( // schedule1104      scheduledId,1105      expectedBlockNumber, 1106      repetitions > 1 ? [period, repetitions] : null, 1107      0, 1108      {Value: operationTx as any},1109    );11101111    const events = await submitTransactionAsync(sender, scheduleTx);1112    expect(getGenericResult(events).success).to.be.true;1113  });1114}11151116export async function1117scheduleExpectFailure(1118  operationTx: any,1119  sender: IKeyringPair,1120  blockSchedule: number,1121  scheduledId: string,1122  period = 1,1123  repetitions = 1,1124) {1125  await usingApi(async (api: ApiPromise) => {1126    const blockNumber: number | undefined = await getBlockNumber(api);1127    const expectedBlockNumber = blockNumber + blockSchedule;11281129    expect(blockNumber).to.be.greaterThan(0);1130    const scheduleTx = api.tx.scheduler.scheduleNamed( // schedule1131      scheduledId,1132      expectedBlockNumber, 1133      repetitions <= 1 ? null : [period, repetitions], 1134      0, 1135      {Value: operationTx as any},1136    );11371138    //const events = 1139    await expect(submitTransactionExpectFailAsync(sender, scheduleTx)).to.be.rejected;1140    //expect(getGenericResult(events).success).to.be.false;1141  });1142}11431144export async function1145scheduleTransferAndWaitExpectSuccess(1146  collectionId: number,1147  tokenId: number,1148  sender: IKeyringPair,1149  recipient: IKeyringPair,1150  value: number | bigint = 1,1151  blockSchedule: number,1152  scheduledId: string,1153) {1154  await usingApi(async (api: ApiPromise) => {1155    await scheduleTransferExpectSuccess(collectionId, tokenId, sender, recipient, value, blockSchedule, scheduledId);11561157    const recipientBalanceBefore = (await api.query.system.account(recipient.address)).data.free.toBigInt();11581159    // sleep for n + 1 blocks1160    await waitNewBlocks(blockSchedule + 1);11611162    const recipientBalanceAfter = (await api.query.system.account(recipient.address)).data.free.toBigInt();11631164    expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(recipient.address));1165    expect(recipientBalanceAfter).to.be.equal(recipientBalanceBefore);1166  });1167}11681169export async function1170scheduleTransferExpectSuccess(1171  collectionId: number,1172  tokenId: number,1173  sender: IKeyringPair,1174  recipient: IKeyringPair,1175  value: number | bigint = 1,1176  blockSchedule: number,1177  scheduledId: string,1178) {1179  await usingApi(async (api: ApiPromise) => {1180    const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient.address), collectionId, tokenId, value);11811182    await scheduleExpectSuccess(transferTx, sender, blockSchedule, scheduledId);11831184    expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(sender.address));1185  });1186}11871188export async function1189scheduleTransferFundsPeriodicExpectSuccess(1190  amount: bigint,1191  sender: IKeyringPair,1192  recipient: IKeyringPair,1193  blockSchedule: number,1194  scheduledId: string,1195  period: number,1196  repetitions: number,1197) {1198  await usingApi(async (api: ApiPromise) => {1199    const transferTx = api.tx.balances.transfer(recipient.address, amount);12001201    const balanceBefore = await getFreeBalance(recipient);1202    1203    await scheduleExpectSuccess(transferTx, sender, blockSchedule, scheduledId, period, repetitions);12041205    expect(await getFreeBalance(recipient)).to.be.equal(balanceBefore);1206  });1207}12081209export async function1210transfer(1211  api: ApiPromise,1212  collectionId: number,1213  tokenId: number,1214  sender: IKeyringPair,1215  recipient: IKeyringPair | CrossAccountId,1216  value: number | bigint,1217) : Promise<boolean> {1218  const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient), collectionId, tokenId, value);1219  const events = await executeTransaction(api, sender, transferTx);1220  return getGenericResult(events).success;1221}12221223export async function1224transferExpectSuccess(1225  collectionId: number,1226  tokenId: number,1227  sender: IKeyringPair,1228  recipient: IKeyringPair | CrossAccountId,1229  value: number | bigint = 1,1230  type = 'NFT',1231) {1232  await usingApi(async (api: ApiPromise) => {1233    const from = normalizeAccountId(sender);1234    const to = normalizeAccountId(recipient);12351236    let balanceBefore = 0n;1237    if (type === 'Fungible' || type === 'ReFungible') {1238      balanceBefore = await getBalance(api, collectionId, to, tokenId);1239    }12401241    const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient), collectionId, tokenId, value);1242    const events = await executeTransaction(api, sender, transferTx);1243    const result = getTransferResult(api, events);12441245    expect(result.collectionId).to.be.equal(collectionId);1246    expect(result.itemId).to.be.equal(tokenId);1247    expect(result.sender).to.be.deep.equal(normalizeAccountId(sender.address));1248    expect(result.recipient).to.be.deep.equal(to);1249    expect(result.value).to.be.equal(BigInt(value));12501251    if (type === 'NFT') {1252      expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(to);1253    }1254    if (type === 'Fungible' || type === 'ReFungible') {1255      const balanceAfter = await getBalance(api, collectionId, to, tokenId);1256      if (JSON.stringify(to) !== JSON.stringify(from)) {1257        expect(balanceAfter - balanceBefore).to.be.equal(BigInt(value));1258      } else {1259        expect(balanceAfter).to.be.equal(balanceBefore);1260      }1261    }1262  });1263}12641265export async function1266transferExpectFailure(1267  collectionId: number,1268  tokenId: number,1269  sender: IKeyringPair,1270  recipient: IKeyringPair | CrossAccountId,1271  value: number | bigint = 1,1272) {1273  await usingApi(async (api: ApiPromise) => {1274    const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient), collectionId, tokenId, value);1275    const events = await expect(submitTransactionExpectFailAsync(sender, transferTx)).to.be.rejected;1276    const result = getGenericResult(events);1277    // if (events && Array.isArray(events)) {1278    //   const result = getCreateCollectionResult(events);1279    // tslint:disable-next-line:no-unused-expression1280    expect(result.success).to.be.false;1281    //}1282  });1283}12841285export async function1286approveExpectFail(1287  collectionId: number,1288  tokenId: number, owner: IKeyringPair, approved: IKeyringPair, amount: number | bigint = 1,1289) {1290  await usingApi(async (api: ApiPromise) => {1291    const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved.address), collectionId, tokenId, amount);1292    const events = await expect(submitTransactionExpectFailAsync(owner, approveUniqueTx)).to.be.rejected;1293    const result = getCreateCollectionResult(events);1294    // tslint:disable-next-line:no-unused-expression1295    expect(result.success).to.be.false;1296  });1297}12981299export async function getBalance(1300  api: ApiPromise,1301  collectionId: number,1302  owner: string | CrossAccountId | IKeyringPair,1303  token: number,1304): Promise<bigint> {1305  return (await api.rpc.unique.balance(collectionId, normalizeAccountId(owner), token)).toBigInt();1306}1307export async function getTokenOwner(1308  api: ApiPromise,1309  collectionId: number,1310  token: number,1311): Promise<CrossAccountId> {1312  const owner = (await api.rpc.unique.tokenOwner(collectionId, token)).toJSON() as any;1313  if (owner == null) throw new Error('owner == null');1314  return normalizeAccountId(owner);1315}1316export async function getTopmostTokenOwner(1317  api: ApiPromise,1318  collectionId: number,1319  token: number,1320): Promise<CrossAccountId> {1321  const owner = (await api.rpc.unique.topmostTokenOwner(collectionId, token)).toJSON() as any;1322  if (owner == null) throw new Error('owner == null');1323  return normalizeAccountId(owner);1324}1325export async function getTokenChildren(1326  api: ApiPromise,1327  collectionId: number,1328  tokenId: number,1329): Promise<UpDataStructsTokenChild[]> {1330  return (await api.rpc.unique.tokenChildren(collectionId, tokenId)).toJSON() as any;1331}1332export async function isTokenExists(1333  api: ApiPromise,1334  collectionId: number,1335  token: number,1336): Promise<boolean> {1337  return (await api.rpc.unique.tokenExists(collectionId, token)).toJSON();1338}1339export async function getLastTokenId(1340  api: ApiPromise,1341  collectionId: number,1342): Promise<number> {1343  return (await api.rpc.unique.lastTokenId(collectionId)).toJSON();1344}1345export async function getAdminList(1346  api: ApiPromise,1347  collectionId: number,1348): Promise<string[]> {1349  return (await api.rpc.unique.adminlist(collectionId)).toHuman() as any;1350}1351export async function getTokenProperties(1352  api: ApiPromise,1353  collectionId: number,1354  tokenId: number,1355  propertyKeys: string[],1356): Promise<UpDataStructsProperty[]> {1357  return (await api.rpc.unique.tokenProperties(collectionId, tokenId, propertyKeys)).toHuman() as any;1358}13591360export async function createFungibleItemExpectSuccess(1361  sender: IKeyringPair,1362  collectionId: number,1363  data: CreateFungibleData,1364  owner: CrossAccountId | string = sender.address,1365) {1366  return await usingApi(async (api) => {1367    const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), {Fungible: data});13681369    const events = await submitTransactionAsync(sender, tx);1370    const result = getCreateItemResult(events);13711372    expect(result.success).to.be.true;1373    return result.itemId;1374  });1375}13761377export async function createMultipleItemsExpectSuccess(sender: IKeyringPair, collectionId: number, itemsData: any, owner: CrossAccountId | string = sender.address) {1378  await usingApi(async (api) => {1379    const to = normalizeAccountId(owner);1380    const tx = api.tx.unique.createMultipleItems(collectionId, to, itemsData);13811382    const events = await submitTransactionAsync(sender, tx);1383    expect(getGenericResult(events).success).to.be.true;1384  });1385}13861387export async function createMultipleItemsWithPropsExpectSuccess(sender: IKeyringPair, collectionId: number, itemsData: any, owner: CrossAccountId | string = sender.address) {1388  await usingApi(async (api) => {1389    const to = normalizeAccountId(owner);1390    const tx = api.tx.unique.createMultipleItems(collectionId, to, itemsData);13911392    const events = await submitTransactionAsync(sender, tx);1393    const result = getCreateItemsResult(events);13941395    for (const res of result) {1396      expect(await api.rpc.unique.tokenProperties(collectionId, res.itemId)).not.to.be.empty;1397    }1398  });1399}14001401export async function createMultipleItemsExWithPropsExpectSuccess(sender: IKeyringPair, collectionId: number, itemsData: any) {1402  await usingApi(async (api) => {1403    const tx = api.tx.unique.createMultipleItemsEx(collectionId, itemsData);14041405    const events = await submitTransactionAsync(sender, tx);1406    const result = getCreateItemsResult(events);14071408    for (const res of result) {1409      expect(await api.rpc.unique.tokenProperties(collectionId, res.itemId)).not.to.be.empty;1410    }1411  });1412}14131414export async function createItemWithPropsExpectSuccess(sender: IKeyringPair, collectionId: number, createMode: string, props:  Array<Property>, owner: CrossAccountId | string = sender.address) {1415  let newItemId = 0;1416  await usingApi(async (api) => {1417    const to = normalizeAccountId(owner);1418    const itemCountBefore = await getLastTokenId(api, collectionId);1419    const itemBalanceBefore = await getBalance(api, collectionId, to, newItemId);14201421    let tx;1422    if (createMode === 'Fungible') {1423      const createData = {fungible: {value: 10}};1424      tx = api.tx.unique.createItem(collectionId, to, createData as any);1425    } else if (createMode === 'ReFungible') {1426      const createData = {refungible: {pieces: 100}};1427      tx = api.tx.unique.createItem(collectionId, to, createData as any);1428    } else {1429      const data = api.createType('UpDataStructsCreateItemData', {NFT: {properties: props}});1430      tx = api.tx.unique.createItem(collectionId, to, data as UpDataStructsCreateItemData);1431    }14321433    const events = await submitTransactionAsync(sender, tx);1434    const result = getCreateItemResult(events);14351436    const itemCountAfter = await getLastTokenId(api, collectionId);1437    const itemBalanceAfter = await getBalance(api, collectionId, to, newItemId);14381439    if (createMode === 'NFT') {1440      expect(await api.rpc.unique.tokenProperties(collectionId, result.itemId)).not.to.be.empty;1441    }14421443    // What to expect1444    // tslint:disable-next-line:no-unused-expression1445    expect(result.success).to.be.true;1446    if (createMode === 'Fungible') {1447      expect(itemBalanceAfter - itemBalanceBefore).to.be.equal(10n);1448    } else {1449      expect(itemCountAfter).to.be.equal(itemCountBefore + 1);1450    }1451    expect(collectionId).to.be.equal(result.collectionId);1452    expect(itemCountAfter.toString()).to.be.equal(result.itemId.toString());1453    expect(to).to.be.deep.equal(result.recipient);1454    newItemId = result.itemId;1455  });1456  return newItemId;1457}14581459export async function createItemWithPropsExpectFailure(sender: IKeyringPair, collectionId: number, createMode: string, props: Array<Property>, owner: CrossAccountId | string = sender.address) {1460  await usingApi(async (api) => {14611462    let tx;1463    if (createMode === 'NFT') {1464      const data = api.createType('UpDataStructsCreateItemData', {NFT: {properties: props}}) as UpDataStructsCreateItemData;1465      tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), data);1466    } else {1467      tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), createMode);1468    }146914701471    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1472    if(events.message && events.message.toString().indexOf('1002: Verification Error') > -1) return;1473    const result = getCreateItemResult(events);14741475    expect(result.success).to.be.false;1476  });1477}14781479export async function createItemExpectSuccess(sender: IKeyringPair, collectionId: number, createMode: string, owner: CrossAccountId | string = sender.address) {1480  let newItemId = 0;1481  await usingApi(async (api) => {1482    const to = normalizeAccountId(owner);1483    const itemCountBefore = await getLastTokenId(api, collectionId);1484    const itemBalanceBefore = await getBalance(api, collectionId, to, newItemId);14851486    let tx;1487    if (createMode === 'Fungible') {1488      const createData = {fungible: {value: 10}};1489      tx = api.tx.unique.createItem(collectionId, to, createData as any);1490    } else if (createMode === 'ReFungible') {1491      const createData = {refungible: {pieces: 100}};1492      tx = api.tx.unique.createItem(collectionId, to, createData as any);1493    } else {1494      const createData = {nft: {}};1495      tx = api.tx.unique.createItem(collectionId, to, createData as any);1496    }14971498    const events = await executeTransaction(api, sender, tx);1499    const result = getCreateItemResult(events);15001501    const itemCountAfter = await getLastTokenId(api, collectionId);1502    const itemBalanceAfter = await getBalance(api, collectionId, to, newItemId);15031504    // What to expect1505    // tslint:disable-next-line:no-unused-expression1506    expect(result.success).to.be.true;1507    if (createMode === 'Fungible') {1508      expect(itemBalanceAfter - itemBalanceBefore).to.be.equal(10n);1509    } else {1510      expect(itemCountAfter).to.be.equal(itemCountBefore + 1);1511    }1512    expect(collectionId).to.be.equal(result.collectionId);1513    expect(itemCountAfter.toString()).to.be.equal(result.itemId.toString());1514    expect(to).to.be.deep.equal(result.recipient);1515    newItemId = result.itemId;1516  });1517  return newItemId;1518}15191520export async function createRefungibleToken(api: ApiPromise, sender: IKeyringPair, collectionId: number, amount: bigint, owner: CrossAccountId | IKeyringPair | string = sender.address) : Promise<CreateItemResult> {1521  const createData = {refungible: {pieces: amount}};1522  const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), createData as any);15231524  const events = await submitTransactionAsync(sender, tx);1525  return  getCreateItemResult(events);1526}15271528export async function createItemExpectFailure(sender: IKeyringPair, collectionId: number, createMode: string, owner: CrossAccountId | string = sender.address) {1529  await usingApi(async (api) => {1530    const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), createMode);15311532    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1533    const result = getCreateItemResult(events);15341535    expect(result.success).to.be.false;1536  });1537}15381539export async function setPublicAccessModeExpectSuccess(1540  sender: IKeyringPair, collectionId: number,1541  accessMode: 'Normal' | 'AllowList',1542) {1543  await usingApi(async (api) => {15441545    // Run the transaction1546    const tx = api.tx.unique.setCollectionPermissions(collectionId, {access: accessMode});1547    const events = await submitTransactionAsync(sender, tx);1548    const result = getGenericResult(events);15491550    // Get the collection1551    const collection = await queryCollectionExpectSuccess(api, collectionId);15521553    // What to expect1554    // tslint:disable-next-line:no-unused-expression1555    expect(result.success).to.be.true;1556    expect(collection.permissions.access.toHuman()).to.be.equal(accessMode);1557  });1558}15591560export async function setPublicAccessModeExpectFail(1561  sender: IKeyringPair, collectionId: number,1562  accessMode: 'Normal' | 'AllowList',1563) {1564  await usingApi(async (api) => {15651566    // Run the transaction1567    const tx = api.tx.unique.setCollectionPermissions(collectionId, {access: accessMode});1568    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1569    const result = getGenericResult(events);15701571    // What to expect1572    // tslint:disable-next-line:no-unused-expression1573    expect(result.success).to.be.false;1574  });1575}15761577export async function enableAllowListExpectSuccess(sender: IKeyringPair, collectionId: number) {1578  await setPublicAccessModeExpectSuccess(sender, collectionId, 'AllowList');1579}15801581export async function enableAllowListExpectFail(sender: IKeyringPair, collectionId: number) {1582  await setPublicAccessModeExpectFail(sender, collectionId, 'AllowList');1583}15841585export async function disableAllowListExpectSuccess(sender: IKeyringPair, collectionId: number) {1586  await setPublicAccessModeExpectSuccess(sender, collectionId, 'Normal');1587}15881589export async function setMintPermissionExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {1590  await usingApi(async (api) => {15911592    // Run the transaction1593    const tx = api.tx.unique.setCollectionPermissions(collectionId, {mintMode: enabled});1594    const events = await submitTransactionAsync(sender, tx);1595    const result = getGenericResult(events);1596    expect(result.success).to.be.true;15971598    // Get the collection1599    const collection = await queryCollectionExpectSuccess(api, collectionId);16001601    expect(collection.permissions.mintMode.toHuman()).to.be.equal(enabled);1602  });1603}16041605export async function enablePublicMintingExpectSuccess(sender: IKeyringPair, collectionId: number) {1606  await setMintPermissionExpectSuccess(sender, collectionId, true);1607}16081609export async function setMintPermissionExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {1610  await usingApi(async (api) => {1611    // Run the transaction1612    const tx = api.tx.unique.setCollectionPermissions(collectionId, {mintMode: enabled});1613    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1614    const result = getCreateCollectionResult(events);1615    // tslint:disable-next-line:no-unused-expression1616    expect(result.success).to.be.false;1617  });1618}16191620export async function setChainLimitsExpectFailure(sender: IKeyringPair, limits: IChainLimits) {1621  await usingApi(async (api) => {1622    // Run the transaction1623    const tx = api.tx.unique.setChainLimits(limits);1624    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1625    const result = getCreateCollectionResult(events);1626    // tslint:disable-next-line:no-unused-expression1627    expect(result.success).to.be.false;1628  });1629}16301631export async function isAllowlisted(api: ApiPromise, collectionId: number, address: string | CrossAccountId) {1632  return (await api.rpc.unique.allowed(collectionId, normalizeAccountId(address))).toJSON();1633}16341635export async function addToAllowListExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId | CrossAccountId) {1636  await usingApi(async (api) => {1637    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.false;16381639    // Run the transaction1640    const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1641    const events = await submitTransactionAsync(sender, tx);1642    const result = getGenericResult(events);1643    expect(result.success).to.be.true;16441645    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;1646  });1647}16481649export async function addToAllowListAgainExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId) {1650  await usingApi(async (api) => {16511652    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;16531654    // Run the transaction1655    const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1656    const events = await submitTransactionAsync(sender, tx);1657    const result = getGenericResult(events);1658    expect(result.success).to.be.true;16591660    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;1661  });1662}16631664export async function addToAllowListExpectFail(sender: IKeyringPair, collectionId: number, address: string | AccountId) {1665  await usingApi(async (api) => {16661667    // Run the transaction1668    const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1669    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1670    const result = getGenericResult(events);16711672    // What to expect1673    // tslint:disable-next-line:no-unused-expression1674    expect(result.success).to.be.false;1675  });1676}16771678export async function removeFromAllowListExpectSuccess(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1679  await usingApi(async (api) => {1680    // Run the transaction1681    const tx = api.tx.unique.removeFromAllowList(collectionId, normalizeAccountId(address));1682    const events = await submitTransactionAsync(sender, tx);1683    const result = getGenericResult(events);16841685    // What to expect1686    // tslint:disable-next-line:no-unused-expression1687    expect(result.success).to.be.true;1688  });1689}16901691export async function removeFromAllowListExpectFailure(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1692  await usingApi(async (api) => {1693    // Run the transaction1694    const tx = api.tx.unique.removeFromAllowList(collectionId, normalizeAccountId(address));1695    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1696    const result = getGenericResult(events);16971698    // What to expect1699    // tslint:disable-next-line:no-unused-expression1700    expect(result.success).to.be.false;1701  });1702}17031704export const getDetailedCollectionInfo = async (api: ApiPromise, collectionId: number)1705  : Promise<UpDataStructsRpcCollection | null> => {1706  return (await api.rpc.unique.collectionById(collectionId)).unwrapOr(null);1707};17081709export const getCreatedCollectionCount = async (api: ApiPromise): Promise<number> => {1710  // set global object - collectionsCount1711  return (await api.rpc.unique.collectionStats()).created.toNumber();1712};17131714export async function queryCollectionExpectSuccess(api: ApiPromise, collectionId: number): Promise<UpDataStructsRpcCollection> {1715  return (await api.rpc.unique.collectionById(collectionId)).unwrap();1716}17171718export async function waitNewBlocks(blocksCount = 1): Promise<void> {1719  await usingApi(async (api) => {1720    const promise = new Promise<void>(async (resolve) => {1721      const unsubscribe = await api.rpc.chain.subscribeNewHeads(() => {1722        if (blocksCount > 0) {1723          blocksCount--;1724        } else {1725          unsubscribe();1726          resolve();1727        }1728      });1729    });1730    return promise;1731  });1732}17331734export async function repartitionRFT(1735  api: ApiPromise,1736  collectionId: number,1737  sender: IKeyringPair,1738  tokenId: number,1739  amount: bigint,1740): Promise<boolean> {1741  const tx = api.tx.unique.repartition(collectionId, tokenId, amount);1742  const events = await submitTransactionAsync(sender, tx);1743  const result = getGenericResult(events);17441745  return result.success;1746}17471748export async function itApi(name: string, cb: (apis: { api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair }) => any, opts: { only?: boolean, skip?: boolean } = {}) {1749  let i: any = it;1750  if (opts.only) i = i.only;1751  else if (opts.skip) i = i.skip;1752  i(name, async () => {1753    await usingApi(async (api, privateKeyWrapper) => {1754      await cb({api, privateKeyWrapper});1755    });1756  });1757}17581759itApi.only = (name: string, cb: (apis: { api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair }) => any) => itApi(name, cb, {only: true});1760itApi.skip = (name: string, cb: (apis: { api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair }) => any) => itApi(name, cb, {skip: true});