git.delta.rocks / unique-network / refs/commits / 75d727efa2e1

difftreelog

Merge branch 'feature/app-staking' of https://github.com/UniqueNetwork/unique-chain into feature/app-staking

PraetorP2022-09-06parents: #3a6a58f #b9b1dbe.patch.diff
in: master

2 files changed

modifiedtests/src/eth/contractSponsoring.test.tsdiffbeforeafterboth
--- a/tests/src/eth/contractSponsoring.test.ts
+++ b/tests/src/eth/contractSponsoring.test.ts
@@ -15,6 +15,7 @@
 // along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
 
 import {expect} from 'chai';
+import { expectSubstrateEventsAtBlock } from '../util/helpers';
 import {
   contractHelpers,
   createEthAccountWithBalance,
@@ -43,8 +44,9 @@
     const helpers = contractHelpers(web3, owner);
     
     const result = await helpers.methods.selfSponsoredEnable(flipper.options.address).send();
-    const events = normalizeEvents(result.events);
-    expect(events).to.be.deep.equal([
+    // console.log(result);
+    const ethEvents = normalizeEvents(result.events);
+    expect(ethEvents).to.be.deep.equal([
       {
         address: flipper.options.address,
         event: 'ContractSponsorSet',
@@ -62,6 +64,13 @@
         },
       },
     ]);
+
+    await expectSubstrateEventsAtBlock(
+      api, 
+      result.blockNumber,
+      'evmContractHelpers',
+      ['ContractSponsorSet','ContractSponsorshipConfirmed'],
+    );
   });
 
   itWeb3('Self sponsored can not be set by the address that did not deployed the contract', async ({api, web3, privateKeyWrapper}) => {
@@ -121,6 +130,13 @@
         },
       },
     ]);
+
+    await expectSubstrateEventsAtBlock(
+      api, 
+      result.blockNumber,
+      'evmContractHelpers',
+      ['ContractSponsorSet'],
+    );
   });
   
   itWeb3('Sponsor can not be set by the address that did not deployed the contract', async ({api, web3, privateKeyWrapper}) => {
@@ -163,6 +179,13 @@
         },
       },
     ]);
+
+    await expectSubstrateEventsAtBlock(
+      api, 
+      result.blockNumber,
+      'evmContractHelpers',
+      ['ContractSponsorshipConfirmed'],
+    );
   });
 
   itWeb3('Sponsorship can not be confirmed by the address that not pending as sponsor', async ({api, web3, privateKeyWrapper}) => {
@@ -248,6 +271,13 @@
         },
       },
     ]);
+
+    await expectSubstrateEventsAtBlock(
+      api, 
+      result.blockNumber,
+      'evmContractHelpers',
+      ['ContractSponsorRemoved'],
+    );
   });
 
   itWeb3('Sponsor can not be removed by the address that did not deployed the contract', async ({api, web3, privateKeyWrapper}) => {
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';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  Scheduler = 'scheduler',51  AppPromotion = 'apppromotion',52}5354export async function isUnique(): Promise<boolean> {55  return usingApi(async api => {56    const chain = await api.rpc.system.chain();5758    return chain.eq('UNIQUE');59  });60}6162export async function isQuartz(): Promise<boolean> {63  return usingApi(async api => {64    const chain = await api.rpc.system.chain();65    66    return chain.eq('QUARTZ');67  });68}6970let modulesNames: any;71export function getModuleNames(api: ApiPromise): string[] {72  if (typeof modulesNames === 'undefined') 73    modulesNames = api.runtimeMetadata.asLatest.pallets.map(m => m.name.toString().toLowerCase());74  return modulesNames;75}7677export async function missingRequiredPallets(requiredPallets: string[]): Promise<string[]> {78  return await usingApi(async api => {79    const pallets = getModuleNames(api);8081    return requiredPallets.filter(p => !pallets.includes(p));82  });83}8485export async function checkPalletsPresence(requiredPallets: string[]): Promise<boolean> {86  return (await missingRequiredPallets(requiredPallets)).length == 0;87}8889export async function requirePallets(mocha: Context, requiredPallets: string[]) {90  const missingPallets = await missingRequiredPallets(requiredPallets);9192  if (missingPallets.length > 0) {93    const skippingTestMsg = `\tSkipping test "${mocha.test?.title}".`;94    const missingPalletsMsg = `\tThe following pallets are missing:\n\t- ${missingPallets.join('\n\t- ')}`;95    const skipMsg = `${skippingTestMsg}\n${missingPalletsMsg}`;9697    console.error('\x1b[38:5:208m%s\x1b[0m', skipMsg);9899    mocha.skip();100  }101}102103export function bigIntToSub(api: ApiPromise, number: bigint) {104  return api.registry.createType('AccountId', '0x' + number.toString(16).padStart(64, '0')).toJSON();105}106107export function normalizeAccountId(input: string | AccountId | CrossAccountId | IKeyringPair): CrossAccountId {108  if (typeof input === 'string') {109    if (input.length >= 47) {110      return {Substrate: input};111    } else if (input.length === 42 && input.startsWith('0x')) {112      return {Ethereum: input.toLowerCase()};113    } else if (input.length === 40 && !input.startsWith('0x')) {114      return {Ethereum: '0x' + input.toLowerCase()};115    } else {116      throw new Error(`Unknown address format: "${input}"`);117    }118  }119  if ('address' in input) {120    return {Substrate: input.address};121  }122  if ('Ethereum' in input) {123    return {124      Ethereum: input.Ethereum.toLowerCase(),125    };126  } else if ('ethereum' in input) {127    return {128      Ethereum: (input as any).ethereum.toLowerCase(),129    };130  } else if ('Substrate' in input) {131    return input;132  } else if ('substrate' in input) {133    return {134      Substrate: (input as any).substrate,135    };136  }137138  // AccountId139  return {Substrate: input.toString()};140}141export function toSubstrateAddress(input: string | CrossAccountId | IKeyringPair): string {142  input = normalizeAccountId(input);143  if ('Substrate' in input) {144    return input.Substrate;145  } else {146    return evmToAddress(input.Ethereum);147  }148}149150export const U128_MAX = (1n << 128n) - 1n;151152const MICROUNIQUE = 1_000_000_000_000n;153const MILLIUNIQUE = 1_000n * MICROUNIQUE;154const CENTIUNIQUE = 10n * MILLIUNIQUE;155export const UNIQUE = 100n * CENTIUNIQUE;156157interface GenericResult<T> {158  success: boolean;159  data: T | null;160}161162interface CreateCollectionResult {163  success: boolean;164  collectionId: number;165}166167interface CreateItemResult {168  success: boolean;169  collectionId: number;170  itemId: number;171  recipient?: CrossAccountId;172  amount?: number;173}174175interface DestroyItemResult {176  success: boolean;177  collectionId: number;178  itemId: number;179  owner: CrossAccountId;180  amount: number;181}182183interface TransferResult {184  collectionId: number;185  itemId: number;186  sender?: CrossAccountId;187  recipient?: CrossAccountId;188  value: bigint;189}190191interface IReFungibleOwner {192  fraction: BN;193  owner: number[];194}195196interface IGetMessage {197  checkMsgUnqMethod: string;198  checkMsgTrsMethod: string;199  checkMsgSysMethod: string;200}201202export interface IFungibleTokenDataType {203  value: number;204}205206export interface IChainLimits {207  collectionNumbersLimit: number;208  accountTokenOwnershipLimit: number;209  collectionsAdminsLimit: number;210  customDataLimit: number;211  nftSponsorTransferTimeout: number;212  fungibleSponsorTransferTimeout: number;213  refungibleSponsorTransferTimeout: number;214  //offchainSchemaLimit: number;215  //constOnChainSchemaLimit: number;216}217218export interface IReFungibleTokenDataType {219  owner: IReFungibleOwner[];220}221222export function uniqueEventMessage(events: EventRecord[]): IGetMessage {223  let checkMsgUnqMethod = '';224  let checkMsgTrsMethod = '';225  let checkMsgSysMethod = '';226  events.forEach(({event: {method, section}}) => {227    if (section === 'common') {228      checkMsgUnqMethod = method;229    } else if (section === 'treasury') {230      checkMsgTrsMethod = method;231    } else if (section === 'system') {232      checkMsgSysMethod = method;233    } else { return null; }234  });235  const result: IGetMessage = {236    checkMsgUnqMethod,237    checkMsgTrsMethod,238    checkMsgSysMethod,239  };240  return result;241}242243export function getEvent<T extends Event>(events: EventRecord[], check: (event: IEvent<AnyTuple>) => event is T): T | undefined {244  const event = events.find(r => check(r.event));245  if (!event) return;246  return event.event as T;247}248249export function getGenericResult<T>(events: EventRecord[]): GenericResult<T>;250export function getGenericResult<T>(251  events: EventRecord[],252  expectSection: string,253  expectMethod: string,254  extractAction: (data: GenericEventData) => T255): GenericResult<T>;256257export function getGenericResult<T>(258  events: EventRecord[],259  expectSection?: string,260  expectMethod?: string,261  extractAction?: (data: GenericEventData) => T,262): GenericResult<T> {263  let success = false;264  let successData = null;265266  events.forEach(({event: {data, method, section}}) => {267    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);268    if (method === 'ExtrinsicSuccess') {269      success = true;270    } else if ((expectSection == section) && (expectMethod == method)) {271      successData = extractAction!(data as any);272    }273  });274275  const result: GenericResult<T> = {276    success,277    data: successData,278  };279  return result;280}281282export function getCreateCollectionResult(events: EventRecord[]): CreateCollectionResult {283  const genericResult = getGenericResult(events, 'common', 'CollectionCreated', (data) => parseInt(data[0].toString(), 10));284  const result: CreateCollectionResult = {285    success: genericResult.success,286    collectionId: genericResult.data ?? 0,287  };288  return result;289}290291export function getCreateItemsResult(events: EventRecord[]): CreateItemResult[] {292  const results: CreateItemResult[] = [];293  294  const genericResult = getGenericResult<CreateItemResult[]>(events, 'common', 'ItemCreated', (data) => {295    const collectionId = parseInt(data[0].toString(), 10);296    const itemId = parseInt(data[1].toString(), 10);297    const recipient = normalizeAccountId(data[2].toJSON() as any);298    const amount = parseInt(data[3].toString(), 10);299300    const itemRes: CreateItemResult = {301      success: true,302      collectionId,303      itemId,304      recipient,305      amount,306    };307308    results.push(itemRes);309    return results;310  });311312  if (!genericResult.success) return [];313  return results;314}315316export function getCreateItemResult(events: EventRecord[]): CreateItemResult {317  const genericResult = getGenericResult(events, 'common', 'ItemCreated', (data) => data.map(function(value) { return value.toJSON(); }));318  319  if (genericResult.data == null) 320    return {321      success: genericResult.success,322      collectionId: 0,323      itemId: 0,324      amount: 0,325    };326  else 327    return {328      success: genericResult.success,329      collectionId: genericResult.data[0] as number,330      itemId: genericResult.data[1] as number,331      recipient: normalizeAccountId(genericResult.data![2] as any),332      amount: genericResult.data[3] as number,333    };334}335336export function getDestroyItemsResult(events: EventRecord[]): DestroyItemResult[] {337  const results: DestroyItemResult[] = [];338  339  const genericResult = getGenericResult<DestroyItemResult[]>(events, 'common', 'ItemDestroyed', (data) => {340    const collectionId = parseInt(data[0].toString(), 10);341    const itemId = parseInt(data[1].toString(), 10);342    const owner = normalizeAccountId(data[2].toJSON() as any);343    const amount = parseInt(data[3].toString(), 10);344345    const itemRes: DestroyItemResult = {346      success: true,347      collectionId,348      itemId,349      owner,350      amount,351    };352353    results.push(itemRes);354    return results;355  });356357  if (!genericResult.success) return [];358  return results;359}360361export function getTransferResult(api: ApiPromise, events: EventRecord[]): TransferResult {362  for (const {event} of events) {363    if (api.events.common.Transfer.is(event)) {364      const [collection, token, sender, recipient, value] = event.data;365      return {366        collectionId: collection.toNumber(),367        itemId: token.toNumber(),368        sender: normalizeAccountId(sender.toJSON() as any),369        recipient: normalizeAccountId(recipient.toJSON() as any),370        value: value.toBigInt(),371      };372    }373  }374  throw new Error('no transfer event');375}376377interface Nft {378  type: 'NFT';379}380381interface Fungible {382  type: 'Fungible';383  decimalPoints: number;384}385386interface ReFungible {387  type: 'ReFungible';388}389390export type CollectionMode = Nft | Fungible | ReFungible;391392export type Property = {393  key: any,394  value: any,395};396397type Permission = {398  mutable: boolean;399  collectionAdmin: boolean;400  tokenOwner: boolean;401}402403type PropertyPermission = {404  key: any;405  permission: Permission;406}407408export type CreateCollectionParams = {409  mode: CollectionMode,410  name: string,411  description: string,412  tokenPrefix: string,413  properties?: Array<Property>,414  propPerm?: Array<PropertyPermission>415};416417const defaultCreateCollectionParams: CreateCollectionParams = {418  description: 'description',419  mode: {type: 'NFT'},420  name: 'name',421  tokenPrefix: 'prefix',422};423424export async function425createCollection(426  api: ApiPromise,427  sender: IKeyringPair,428  params: Partial<CreateCollectionParams> = {},429): Promise<CreateCollectionResult> {430  const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};431432  let modeprm = {};433  if (mode.type === 'NFT') {434    modeprm = {nft: null};435  } else if (mode.type === 'Fungible') {436    modeprm = {fungible: mode.decimalPoints};437  } else if (mode.type === 'ReFungible') {438    modeprm = {refungible: null};439  }440441  const tx = api.tx.unique.createCollectionEx({442    name: strToUTF16(name),443    description: strToUTF16(description),444    tokenPrefix: strToUTF16(tokenPrefix),445    mode: modeprm as any,446  });447  const events = await executeTransaction(api, sender, tx);448  return getCreateCollectionResult(events);449}450451export async function createCollectionExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {452  const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};453454  let collectionId = 0;455  await usingApi(async (api, privateKeyWrapper) => {456    // Get number of collections before the transaction457    const collectionCountBefore = await getCreatedCollectionCount(api);458459    // Run the CreateCollection transaction460    const alicePrivateKey = privateKeyWrapper('//Alice');461462    const result = await createCollection(api, alicePrivateKey, params);463464    // Get number of collections after the transaction465    const collectionCountAfter = await getCreatedCollectionCount(api);466467    // Get the collection468    const collection = await queryCollectionExpectSuccess(api, result.collectionId);469470    // What to expect471    // tslint:disable-next-line:no-unused-expression472    expect(result.success).to.be.true;473    expect(result.collectionId).to.be.equal(collectionCountAfter);474    // tslint:disable-next-line:no-unused-expression475    expect(collection).to.be.not.null;476    expect(collectionCountAfter).to.be.equal(collectionCountBefore + 1, 'Error: NFT collection NOT created.');477    expect(collection.owner.toString()).to.be.equal(toSubstrateAddress(alicePrivateKey));478    expect(utf16ToStr(collection.name.toJSON() as any)).to.be.equal(name);479    expect(utf16ToStr(collection.description.toJSON() as any)).to.be.equal(description);480    expect(hexToStr(collection.tokenPrefix.toJSON())).to.be.equal(tokenPrefix);481482    collectionId = result.collectionId;483  });484485  return collectionId;486}487488export async function createCollectionWithPropsExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {489  const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};490491  let collectionId = 0;492  await usingApi(async (api, privateKeyWrapper) => {493    // Get number of collections before the transaction494    const collectionCountBefore = await getCreatedCollectionCount(api);495496    // Run the CreateCollection transaction497    const alicePrivateKey = privateKeyWrapper('//Alice');498499    let modeprm = {};500    if (mode.type === 'NFT') {501      modeprm = {nft: null};502    } else if (mode.type === 'Fungible') {503      modeprm = {fungible: mode.decimalPoints};504    } else if (mode.type === 'ReFungible') {505      modeprm = {refungible: null};506    }507508    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});509    const events = await submitTransactionAsync(alicePrivateKey, tx);510    const result = getCreateCollectionResult(events);511512    // Get number of collections after the transaction513    const collectionCountAfter = await getCreatedCollectionCount(api);514515    // Get the collection516    const collection = await queryCollectionExpectSuccess(api, result.collectionId);517518    // What to expect519    // tslint:disable-next-line:no-unused-expression520    expect(result.success).to.be.true;521    expect(result.collectionId).to.be.equal(collectionCountAfter);522    // tslint:disable-next-line:no-unused-expression523    expect(collection).to.be.not.null;524    expect(collectionCountAfter).to.be.equal(collectionCountBefore + 1, 'Error: NFT collection NOT created.');525    expect(collection.owner.toString()).to.be.equal(toSubstrateAddress(alicePrivateKey));526    expect(utf16ToStr(collection.name.toJSON() as any)).to.be.equal(name);527    expect(utf16ToStr(collection.description.toJSON() as any)).to.be.equal(description);528    expect(hexToStr(collection.tokenPrefix.toJSON())).to.be.equal(tokenPrefix);529530531    collectionId = result.collectionId;532  });533534  return collectionId;535}536537export async function createCollectionWithPropsExpectFailure(params: Partial<CreateCollectionParams> = {}) {538  const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};539540  await usingApi(async (api, privateKeyWrapper) => {541    // Get number of collections before the transaction542    const collectionCountBefore = await getCreatedCollectionCount(api);543544    // Run the CreateCollection transaction545    const alicePrivateKey = privateKeyWrapper('//Alice');546547    let modeprm = {};548    if (mode.type === 'NFT') {549      modeprm = {nft: null};550    } else if (mode.type === 'Fungible') {551      modeprm = {fungible: mode.decimalPoints};552    } else if (mode.type === 'ReFungible') {553      modeprm = {refungible: null};554    }555556    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});557    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;558559560    // Get number of collections after the transaction561    const collectionCountAfter = await getCreatedCollectionCount(api);562563    expect(collectionCountAfter).to.be.equal(collectionCountBefore, 'Error: Collection with incorrect data created.');564  });565}566567export async function createCollectionExpectFailure(params: Partial<CreateCollectionParams> = {}) {568  const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};569570  let modeprm = {};571  if (mode.type === 'NFT') {572    modeprm = {nft: null};573  } else if (mode.type === 'Fungible') {574    modeprm = {fungible: mode.decimalPoints};575  } else if (mode.type === 'ReFungible') {576    modeprm = {refungible: null};577  }578579  await usingApi(async (api, privateKeyWrapper) => {580    // Get number of collections before the transaction581    const collectionCountBefore = await getCreatedCollectionCount(api);582583    // Run the CreateCollection transaction584    const alicePrivateKey = privateKeyWrapper('//Alice');585    const tx = api.tx.unique.createCollectionEx({name: strToUTF16(name), description: strToUTF16(description), tokenPrefix: strToUTF16(tokenPrefix), mode: modeprm as any});586    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;587588    // Get number of collections after the transaction589    const collectionCountAfter = await getCreatedCollectionCount(api);590591    // What to expect592    expect(collectionCountAfter).to.be.equal(collectionCountBefore, 'Error: Collection with incorrect data created.');593  });594}595596export async function findUnusedAddress(api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair, seedAddition = ''): Promise<IKeyringPair> {597  let bal = 0n;598  let unused;599  do {600    const randomSeed = 'seed' + Math.floor(Math.random() * Math.floor(10000)) + seedAddition;601    unused = privateKeyWrapper(`//${randomSeed}`);602    bal = (await api.query.system.account(unused.address)).data.free.toBigInt();603  } while (bal !== 0n);604  return unused;605}606607export async function getAllowance(api: ApiPromise, collectionId: number, owner: CrossAccountId | string | IKeyringPair, approved: CrossAccountId | string | IKeyringPair, tokenId: number) {608  return (await api.rpc.unique.allowance(collectionId, normalizeAccountId(owner), normalizeAccountId(approved), tokenId)).toBigInt();609}610611export function findUnusedAddresses(api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair, amount: number): Promise<IKeyringPair[]> {612  return Promise.all(new Array(amount).fill(null).map(() => findUnusedAddress(api, privateKeyWrapper, '_' + Date.now())));613}614615export async function findNotExistingCollection(api: ApiPromise): Promise<number> {616  const totalNumber = await getCreatedCollectionCount(api);617  const newCollection: number = totalNumber + 1;618  return newCollection;619}620621function getDestroyResult(events: EventRecord[]): boolean {622  let success = false;623  events.forEach(({event: {method}}) => {624    if (method == 'ExtrinsicSuccess') {625      success = true;626    }627  });628  return success;629}630631export async function destroyCollectionExpectFailure(collectionId: number, senderSeed = '//Alice') {632  await usingApi(async (api, privateKeyWrapper) => {633    // Run the DestroyCollection transaction634    const alicePrivateKey = privateKeyWrapper(senderSeed);635    const tx = api.tx.unique.destroyCollection(collectionId);636    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;637  });638}639640export async function destroyCollectionExpectSuccess(collectionId: number, senderSeed = '//Alice') {641  await usingApi(async (api, privateKeyWrapper) => {642    // Run the DestroyCollection transaction643    const alicePrivateKey = privateKeyWrapper(senderSeed);644    const tx = api.tx.unique.destroyCollection(collectionId);645    const events = await submitTransactionAsync(alicePrivateKey, tx);646    const result = getDestroyResult(events);647    expect(result).to.be.true;648649    // What to expect650    expect(await getDetailedCollectionInfo(api, collectionId)).to.be.null;651  });652}653654export async function setCollectionLimitsExpectSuccess(sender: IKeyringPair, collectionId: number, limits: any) {655  await usingApi(async (api) => {656    const tx = api.tx.unique.setCollectionLimits(collectionId, limits);657    const events = await submitTransactionAsync(sender, tx);658    const result = getGenericResult(events);659660    expect(result.success).to.be.true;661  });662}663664export const setCollectionPermissionsExpectSuccess = async (sender: IKeyringPair, collectionId: number, permissions: any) => {665  await usingApi(async(api) => {666    const tx = api.tx.unique.setCollectionPermissions(collectionId, permissions);667    const events = await submitTransactionAsync(sender, tx);668    const result = getGenericResult(events);669670    expect(result.success).to.be.true;671  });672};673674export async function setCollectionLimitsExpectFailure(sender: IKeyringPair, collectionId: number, limits: any) {675  await usingApi(async (api) => {676    const tx = api.tx.unique.setCollectionLimits(collectionId, limits);677    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;678    const result = getGenericResult(events);679680    expect(result.success).to.be.false;681  });682}683684export async function setCollectionSponsorExpectSuccess(collectionId: number, sponsor: string, sender = '//Alice') {685  await usingApi(async (api, privateKeyWrapper) => {686687    // Run the transaction688    const senderPrivateKey = privateKeyWrapper(sender);689    const tx = api.tx.unique.setCollectionSponsor(collectionId, sponsor);690    const events = await submitTransactionAsync(senderPrivateKey, tx);691    const result = getGenericResult(events);692693    // Get the collection694    const collection = await queryCollectionExpectSuccess(api, collectionId);695696    // What to expect697    expect(result.success).to.be.true;698    expect(collection.sponsorship.toJSON()).to.deep.equal({699      unconfirmed: sponsor,700    });701  });702}703704export async function removeCollectionSponsorExpectSuccess(collectionId: number, sender = '//Alice') {705  await usingApi(async (api, privateKeyWrapper) => {706707    // Run the transaction708    const alicePrivateKey = privateKeyWrapper(sender);709    const tx = api.tx.unique.removeCollectionSponsor(collectionId);710    const events = await submitTransactionAsync(alicePrivateKey, tx);711    const result = getGenericResult(events);712713    // Get the collection714    const collection = await queryCollectionExpectSuccess(api, collectionId);715716    // What to expect717    expect(result.success).to.be.true;718    expect(collection.sponsorship.toJSON()).to.be.deep.equal({disabled: null});719  });720}721722export async function removeCollectionSponsorExpectFailure(collectionId: number, senderSeed = '//Alice') {723  await usingApi(async (api, privateKeyWrapper) => {724725    // Run the transaction726    const alicePrivateKey = privateKeyWrapper(senderSeed);727    const tx = api.tx.unique.removeCollectionSponsor(collectionId);728    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;729  });730}731732export async function setCollectionSponsorExpectFailure(collectionId: number, sponsor: string, senderSeed = '//Alice') {733  await usingApi(async (api, privateKeyWrapper) => {734735    // Run the transaction736    const alicePrivateKey = privateKeyWrapper(senderSeed);737    const tx = api.tx.unique.setCollectionSponsor(collectionId, sponsor);738    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;739  });740}741742export async function confirmSponsorshipExpectSuccess(collectionId: number, senderSeed = '//Alice') {743  await usingApi(async (api, privateKeyWrapper) => {744745    // Run the transaction746    const sender = privateKeyWrapper(senderSeed);747    await confirmSponsorshipByKeyExpectSuccess(collectionId, sender);748  });749}750751export async function confirmSponsorshipByKeyExpectSuccess(collectionId: number, sender: IKeyringPair) {752  await usingApi(async (api, privateKeyWrapper) => {753754    // Run the transaction755    const tx = api.tx.unique.confirmSponsorship(collectionId);756    const events = await submitTransactionAsync(sender, tx);757    const result = getGenericResult(events);758759    // Get the collection760    const collection = await queryCollectionExpectSuccess(api, collectionId);761762    // What to expect763    expect(result.success).to.be.true;764    expect(collection.sponsorship.toJSON()).to.be.deep.equal({765      confirmed: sender.address,766    });767  });768}769770771export async function confirmSponsorshipExpectFailure(collectionId: number, senderSeed = '//Alice') {772  await usingApi(async (api, privateKeyWrapper) => {773774    // Run the transaction775    const sender = privateKeyWrapper(senderSeed);776    const tx = api.tx.unique.confirmSponsorship(collectionId);777    await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;778  });779}780781export async function enableContractSponsoringExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {782  await usingApi(async (api) => {783    const tx = api.tx.unique.enableContractSponsoring(contractAddress, enable);784    const events = await submitTransactionAsync(sender, tx);785    const result = getGenericResult(events);786787    expect(result.success).to.be.true;788  });789}790791export async function enableContractSponsoringExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {792  await usingApi(async (api) => {793    const tx = api.tx.unique.enableContractSponsoring(contractAddress, enable);794    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;795    const result = getGenericResult(events);796797    expect(result.success).to.be.false;798  });799}800801export async function setTransferFlagExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {802803  await usingApi(async (api) => {804805    const tx = api.tx.unique.setTransfersEnabledFlag(collectionId, enabled);806    const events = await submitTransactionAsync(sender, tx);807    const result = getGenericResult(events);808809    expect(result.success).to.be.true;810  });811}812813export async function setTransferFlagExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {814815  await usingApi(async (api) => {816817    const tx = api.tx.unique.setTransfersEnabledFlag(collectionId, enabled);818    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;819    const result = getGenericResult(events);820821    expect(result.success).to.be.false;822  });823}824825export async function setContractSponsoringRateLimitExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {826  await usingApi(async (api) => {827    const tx = api.tx.unique.setContractSponsoringRateLimit(contractAddress, rateLimit);828    const events = await submitTransactionAsync(sender, tx);829    const result = getGenericResult(events);830831    expect(result.success).to.be.true;832  });833}834835export async function setContractSponsoringRateLimitExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {836  await usingApi(async (api) => {837    const tx = api.tx.unique.setContractSponsoringRateLimit(contractAddress, rateLimit);838    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;839    const result = getGenericResult(events);840841    expect(result.success).to.be.false;842  });843}844845export async function getNextSponsored(846  api: ApiPromise,847  collectionId: number,848  account: string | CrossAccountId,849  tokenId: number,850): Promise<number> {851  return Number((await api.rpc.unique.nextSponsored(collectionId, account, tokenId)).unwrapOr(-1));852}853854export async function toggleContractAllowlistExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, value = true) {855  await usingApi(async (api) => {856    const tx = api.tx.unique.toggleContractAllowList(contractAddress, value);857    const events = await submitTransactionAsync(sender, tx);858    const result = getGenericResult(events);859860    expect(result.success).to.be.true;861  });862}863864export async function isAllowlistedInContract(contractAddress: AccountId | string, user: string) {865  let allowlisted = false;866  await usingApi(async (api) => {867    allowlisted = (await api.query.unique.contractAllowList(contractAddress, user)).toJSON() as boolean;868  });869  return allowlisted;870}871872export async function addToContractAllowListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {873  await usingApi(async (api) => {874    const tx = api.tx.unique.addToContractAllowList(contractAddress.toString(), user.toString());875    const events = await submitTransactionAsync(sender, tx);876    const result = getGenericResult(events);877878    expect(result.success).to.be.true;879  });880}881882export async function removeFromContractAllowListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {883  await usingApi(async (api) => {884    const tx = api.tx.unique.removeFromContractAllowList(contractAddress.toString(), user.toString());885    const events = await submitTransactionAsync(sender, tx);886    const result = getGenericResult(events);887888    expect(result.success).to.be.true;889  });890}891892export async function removeFromContractAllowListExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {893  await usingApi(async (api) => {894    const tx = api.tx.unique.removeFromContractAllowList(contractAddress.toString(), user.toString());895    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;896    const result = getGenericResult(events);897898    expect(result.success).to.be.false;899  });900}901902export interface CreateFungibleData {903  readonly Value: bigint;904}905906export interface CreateReFungibleData { }907export interface CreateNftData { }908909export type CreateItemData = {910  NFT: CreateNftData;911} | {912  Fungible: CreateFungibleData;913} | {914  ReFungible: CreateReFungibleData;915};916917export async function burnItem(api: ApiPromise, sender: IKeyringPair, collectionId: number, tokenId: number, value: number | bigint) : Promise<boolean> {918  const tx = api.tx.unique.burnItem(collectionId, tokenId, value);919  const events = await submitTransactionAsync(sender, tx);920  return getGenericResult(events).success;921}922923export async function burnItemExpectSuccess(sender: IKeyringPair, collectionId: number, tokenId: number, value: number | bigint = 1) {924  await usingApi(async (api) => {925    const balanceBefore = await getBalance(api, collectionId, normalizeAccountId(sender), tokenId);926    // if burning token by admin - use adminButnItemExpectSuccess927    expect(balanceBefore >= BigInt(value)).to.be.true;928929    expect(await burnItem(api, sender, collectionId, tokenId, value)).to.be.true;930931    const balanceAfter = await getBalance(api, collectionId, normalizeAccountId(sender), tokenId);932    expect(balanceAfter + BigInt(value)).to.be.equal(balanceBefore);933  });934}935936export async function burnItemExpectFailure(sender: IKeyringPair, collectionId: number, tokenId: number, value: number | bigint = 1) {937  await usingApi(async (api) => {938    const tx = api.tx.unique.burnItem(collectionId, tokenId, value);939940    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;941    const result = getCreateCollectionResult(events);942    // tslint:disable-next-line:no-unused-expression943    expect(result.success).to.be.false;944  });945}946947export async function burnFromExpectSuccess(sender: IKeyringPair, from: IKeyringPair | CrossAccountId, collectionId: number, tokenId: number, value: number | bigint = 1) {948  await usingApi(async (api) => {949    const tx = api.tx.unique.burnFrom(collectionId, normalizeAccountId(from), tokenId, value);950    const events = await submitTransactionAsync(sender, tx);951    return getGenericResult(events).success;952  });953}954955export async function956approve(957  api: ApiPromise,958  collectionId: number,959  tokenId: number, owner: IKeyringPair, approved: CrossAccountId | string | IKeyringPair, amount: number | bigint,960) {961  const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);962  const events = await submitTransactionAsync(owner, approveUniqueTx);963  return getGenericResult(events).success;964}965966export async function967approveExpectSuccess(968  collectionId: number,969  tokenId: number, owner: IKeyringPair, approved: CrossAccountId | string, amount: number | bigint = 1,970) {971  await usingApi(async (api: ApiPromise) => {972    const result = await approve(api, collectionId, tokenId, owner, approved, amount);973    expect(result).to.be.true;974975    expect(await getAllowance(api, collectionId, owner, approved, tokenId)).to.be.equal(BigInt(amount));976  });977}978979export async function adminApproveFromExpectSuccess(980  collectionId: number,981  tokenId: number, admin: IKeyringPair, owner: CrossAccountId | string, approved: CrossAccountId | string, amount: number | bigint = 1,982) {983  await usingApi(async (api: ApiPromise) => {984    const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);985    const events = await submitTransactionAsync(admin, approveUniqueTx);986    const result = getGenericResult(events);987    expect(result.success).to.be.true;988989    expect(await getAllowance(api, collectionId, owner, approved, tokenId)).to.be.equal(BigInt(amount));990  });991}992993export async function994transferFrom(995  api: ApiPromise,996  collectionId: number,997  tokenId: number,998  accountApproved: IKeyringPair,999  accountFrom: IKeyringPair | CrossAccountId,1000  accountTo: IKeyringPair | CrossAccountId,1001  value: number | bigint,1002) {1003  const from = normalizeAccountId(accountFrom);1004  const to = normalizeAccountId(accountTo);1005  const transferFromTx = api.tx.unique.transferFrom(from, to, collectionId, tokenId, value);1006  const events = await submitTransactionAsync(accountApproved, transferFromTx);1007  return getGenericResult(events).success;1008}10091010export async function1011transferFromExpectSuccess(1012  collectionId: number,1013  tokenId: number,1014  accountApproved: IKeyringPair,1015  accountFrom: IKeyringPair | CrossAccountId,1016  accountTo: IKeyringPair | CrossAccountId,1017  value: number | bigint = 1,1018  type = 'NFT',1019) {1020  await usingApi(async (api: ApiPromise) => {1021    const from = normalizeAccountId(accountFrom);1022    const to = normalizeAccountId(accountTo);1023    let balanceBefore = 0n;1024    if (type === 'Fungible' || type === 'ReFungible') {1025      balanceBefore = await getBalance(api, collectionId, to, tokenId);1026    }1027    expect(await transferFrom(api, collectionId, tokenId, accountApproved, accountFrom, accountTo, value)).to.be.true;1028    if (type === 'NFT') {1029      expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(to);1030    }1031    if (type === 'Fungible') {1032      const balanceAfter = await getBalance(api, collectionId, to, tokenId);1033      if (JSON.stringify(to) !== JSON.stringify(from)) {1034        expect(balanceAfter - balanceBefore).to.be.equal(BigInt(value));1035      } else {1036        expect(balanceAfter).to.be.equal(balanceBefore);1037      }1038    }1039    if (type === 'ReFungible') {1040      expect(await getBalance(api, collectionId, to, tokenId)).to.be.equal(balanceBefore + BigInt(value));1041    }1042  });1043}10441045export async function1046transferFromExpectFail(1047  collectionId: number,1048  tokenId: number,1049  accountApproved: IKeyringPair,1050  accountFrom: IKeyringPair,1051  accountTo: IKeyringPair,1052  value: number | bigint = 1,1053) {1054  await usingApi(async (api: ApiPromise) => {1055    const transferFromTx = api.tx.unique.transferFrom(normalizeAccountId(accountFrom.address), normalizeAccountId(accountTo.address), collectionId, tokenId, value);1056    const events = await expect(submitTransactionExpectFailAsync(accountApproved, transferFromTx)).to.be.rejected;1057    const result = getCreateCollectionResult(events);1058    // tslint:disable-next-line:no-unused-expression1059    expect(result.success).to.be.false;1060  });1061}10621063/* eslint no-async-promise-executor: "off" */1064export async function getBlockNumber(api: ApiPromise): Promise<number> {1065  return new Promise<number>(async (resolve) => {1066    const unsubscribe = await api.rpc.chain.subscribeNewHeads((head) => {1067      unsubscribe();1068      resolve(head.number.toNumber());1069    });1070  });1071}10721073export async function addCollectionAdminExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | CrossAccountId) {1074  await usingApi(async (api) => {1075    const changeAdminTx = api.tx.unique.addCollectionAdmin(collectionId, normalizeAccountId(address));1076    const events = await submitTransactionAsync(sender, changeAdminTx);1077    const result = getCreateCollectionResult(events);1078    expect(result.success).to.be.true;1079  });1080}10811082export async function adminApproveFromExpectFail(1083  collectionId: number,1084  tokenId: number, admin: IKeyringPair, owner: CrossAccountId | string, approved: CrossAccountId | string, amount: number | bigint = 1,1085) {1086  await usingApi(async (api: ApiPromise) => {1087    const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);1088    const events = await expect(submitTransactionAsync(admin, approveUniqueTx)).to.be.rejected;1089    const result = getGenericResult(events);1090    expect(result.success).to.be.false;1091  });1092}10931094export async function1095getFreeBalance(account: IKeyringPair): Promise<bigint> {1096  let balance = 0n;1097  await usingApi(async (api) => {1098    balance = BigInt((await api.query.system.account(account.address)).data.free.toString());1099  });11001101  return balance;1102}11031104export async function transferBalanceTo(api: ApiPromise, source: IKeyringPair, target: string, amount = 1000n * UNIQUE) {1105  const tx = api.tx.balances.transfer(target, amount);1106  const events = await submitTransactionAsync(source, tx);1107  const result = getGenericResult(events);1108  expect(result.success).to.be.true;1109}11101111export async function1112scheduleExpectSuccess(1113  operationTx: any,1114  sender: IKeyringPair,1115  blockSchedule: number,1116  scheduledId: string,1117  period = 1,1118  repetitions = 1,1119) {1120  await usingApi(async (api: ApiPromise) => {1121    const blockNumber: number | undefined = await getBlockNumber(api);1122    const expectedBlockNumber = blockNumber + blockSchedule;11231124    expect(blockNumber).to.be.greaterThan(0);1125    const scheduleTx = api.tx.scheduler.scheduleNamed( // schedule1126      scheduledId,1127      expectedBlockNumber, 1128      repetitions > 1 ? [period, repetitions] : null, 1129      0, 1130      {Value: operationTx as any},1131    );11321133    const events = await submitTransactionAsync(sender, scheduleTx);1134    expect(getGenericResult(events).success).to.be.true;1135  });1136}11371138export async function1139scheduleExpectFailure(1140  operationTx: any,1141  sender: IKeyringPair,1142  blockSchedule: number,1143  scheduledId: string,1144  period = 1,1145  repetitions = 1,1146) {1147  await usingApi(async (api: ApiPromise) => {1148    const blockNumber: number | undefined = await getBlockNumber(api);1149    const expectedBlockNumber = blockNumber + blockSchedule;11501151    expect(blockNumber).to.be.greaterThan(0);1152    const scheduleTx = api.tx.scheduler.scheduleNamed( // schedule1153      scheduledId,1154      expectedBlockNumber, 1155      repetitions <= 1 ? null : [period, repetitions], 1156      0, 1157      {Value: operationTx as any},1158    );11591160    //const events = 1161    await expect(submitTransactionExpectFailAsync(sender, scheduleTx)).to.be.rejected;1162    //expect(getGenericResult(events).success).to.be.false;1163  });1164}11651166export async function1167scheduleTransferAndWaitExpectSuccess(1168  collectionId: number,1169  tokenId: number,1170  sender: IKeyringPair,1171  recipient: IKeyringPair,1172  value: number | bigint = 1,1173  blockSchedule: number,1174  scheduledId: string,1175) {1176  await usingApi(async (api: ApiPromise) => {1177    await scheduleTransferExpectSuccess(collectionId, tokenId, sender, recipient, value, blockSchedule, scheduledId);11781179    const recipientBalanceBefore = (await api.query.system.account(recipient.address)).data.free.toBigInt();11801181    // sleep for n + 1 blocks1182    await waitNewBlocks(blockSchedule + 1);11831184    const recipientBalanceAfter = (await api.query.system.account(recipient.address)).data.free.toBigInt();11851186    expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(recipient.address));1187    expect(recipientBalanceAfter).to.be.equal(recipientBalanceBefore);1188  });1189}11901191export async function1192scheduleTransferExpectSuccess(1193  collectionId: number,1194  tokenId: number,1195  sender: IKeyringPair,1196  recipient: IKeyringPair,1197  value: number | bigint = 1,1198  blockSchedule: number,1199  scheduledId: string,1200) {1201  await usingApi(async (api: ApiPromise) => {1202    const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient.address), collectionId, tokenId, value);12031204    await scheduleExpectSuccess(transferTx, sender, blockSchedule, scheduledId);12051206    expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(sender.address));1207  });1208}12091210export async function1211scheduleTransferFundsPeriodicExpectSuccess(1212  amount: bigint,1213  sender: IKeyringPair,1214  recipient: IKeyringPair,1215  blockSchedule: number,1216  scheduledId: string,1217  period: number,1218  repetitions: number,1219) {1220  await usingApi(async (api: ApiPromise) => {1221    const transferTx = api.tx.balances.transfer(recipient.address, amount);12221223    const balanceBefore = await getFreeBalance(recipient);1224    1225    await scheduleExpectSuccess(transferTx, sender, blockSchedule, scheduledId, period, repetitions);12261227    expect(await getFreeBalance(recipient)).to.be.equal(balanceBefore);1228  });1229}12301231export async function1232transfer(1233  api: ApiPromise,1234  collectionId: number,1235  tokenId: number,1236  sender: IKeyringPair,1237  recipient: IKeyringPair | CrossAccountId,1238  value: number | bigint,1239) : Promise<boolean> {1240  const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient), collectionId, tokenId, value);1241  const events = await executeTransaction(api, sender, transferTx);1242  return getGenericResult(events).success;1243}12441245export async function1246transferExpectSuccess(1247  collectionId: number,1248  tokenId: number,1249  sender: IKeyringPair,1250  recipient: IKeyringPair | CrossAccountId,1251  value: number | bigint = 1,1252  type = 'NFT',1253) {1254  await usingApi(async (api: ApiPromise) => {1255    const from = normalizeAccountId(sender);1256    const to = normalizeAccountId(recipient);12571258    let balanceBefore = 0n;1259    if (type === 'Fungible' || type === 'ReFungible') {1260      balanceBefore = await getBalance(api, collectionId, to, tokenId);1261    }12621263    const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient), collectionId, tokenId, value);1264    const events = await executeTransaction(api, sender, transferTx);1265    const result = getTransferResult(api, events);12661267    expect(result.collectionId).to.be.equal(collectionId);1268    expect(result.itemId).to.be.equal(tokenId);1269    expect(result.sender).to.be.deep.equal(normalizeAccountId(sender.address));1270    expect(result.recipient).to.be.deep.equal(to);1271    expect(result.value).to.be.equal(BigInt(value));12721273    if (type === 'NFT') {1274      expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(to);1275    }1276    if (type === 'Fungible' || type === 'ReFungible') {1277      const balanceAfter = await getBalance(api, collectionId, to, tokenId);1278      if (JSON.stringify(to) !== JSON.stringify(from)) {1279        expect(balanceAfter - balanceBefore).to.be.equal(BigInt(value));1280      } else {1281        expect(balanceAfter).to.be.equal(balanceBefore);1282      }1283    }1284  });1285}12861287export async function1288transferExpectFailure(1289  collectionId: number,1290  tokenId: number,1291  sender: IKeyringPair,1292  recipient: IKeyringPair | CrossAccountId,1293  value: number | bigint = 1,1294) {1295  await usingApi(async (api: ApiPromise) => {1296    const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient), collectionId, tokenId, value);1297    const events = await expect(submitTransactionExpectFailAsync(sender, transferTx)).to.be.rejected;1298    const result = getGenericResult(events);1299    // if (events && Array.isArray(events)) {1300    //   const result = getCreateCollectionResult(events);1301    // tslint:disable-next-line:no-unused-expression1302    expect(result.success).to.be.false;1303    //}1304  });1305}13061307export async function1308approveExpectFail(1309  collectionId: number,1310  tokenId: number, owner: IKeyringPair, approved: IKeyringPair, amount: number | bigint = 1,1311) {1312  await usingApi(async (api: ApiPromise) => {1313    const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved.address), collectionId, tokenId, amount);1314    const events = await expect(submitTransactionExpectFailAsync(owner, approveUniqueTx)).to.be.rejected;1315    const result = getCreateCollectionResult(events);1316    // tslint:disable-next-line:no-unused-expression1317    expect(result.success).to.be.false;1318  });1319}13201321export async function getBalance(1322  api: ApiPromise,1323  collectionId: number,1324  owner: string | CrossAccountId | IKeyringPair,1325  token: number,1326): Promise<bigint> {1327  return (await api.rpc.unique.balance(collectionId, normalizeAccountId(owner), token)).toBigInt();1328}1329export async function getTokenOwner(1330  api: ApiPromise,1331  collectionId: number,1332  token: number,1333): Promise<CrossAccountId> {1334  const owner = (await api.rpc.unique.tokenOwner(collectionId, token)).toJSON() as any;1335  if (owner == null) throw new Error('owner == null');1336  return normalizeAccountId(owner);1337}1338export async function getTopmostTokenOwner(1339  api: ApiPromise,1340  collectionId: number,1341  token: number,1342): Promise<CrossAccountId> {1343  const owner = (await api.rpc.unique.topmostTokenOwner(collectionId, token)).toJSON() as any;1344  if (owner == null) throw new Error('owner == null');1345  return normalizeAccountId(owner);1346}1347export async function getTokenChildren(1348  api: ApiPromise,1349  collectionId: number,1350  tokenId: number,1351): Promise<UpDataStructsTokenChild[]> {1352  return (await api.rpc.unique.tokenChildren(collectionId, tokenId)).toJSON() as any;1353}1354export async function isTokenExists(1355  api: ApiPromise,1356  collectionId: number,1357  token: number,1358): Promise<boolean> {1359  return (await api.rpc.unique.tokenExists(collectionId, token)).toJSON();1360}1361export async function getLastTokenId(1362  api: ApiPromise,1363  collectionId: number,1364): Promise<number> {1365  return (await api.rpc.unique.lastTokenId(collectionId)).toJSON();1366}1367export async function getAdminList(1368  api: ApiPromise,1369  collectionId: number,1370): Promise<string[]> {1371  return (await api.rpc.unique.adminlist(collectionId)).toHuman() as any;1372}1373export async function getTokenProperties(1374  api: ApiPromise,1375  collectionId: number,1376  tokenId: number,1377  propertyKeys: string[],1378): Promise<UpDataStructsProperty[]> {1379  return (await api.rpc.unique.tokenProperties(collectionId, tokenId, propertyKeys)).toHuman() as any;1380}13811382export async function createFungibleItemExpectSuccess(1383  sender: IKeyringPair,1384  collectionId: number,1385  data: CreateFungibleData,1386  owner: CrossAccountId | string = sender.address,1387) {1388  return await usingApi(async (api) => {1389    const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), {Fungible: data});13901391    const events = await submitTransactionAsync(sender, tx);1392    const result = getCreateItemResult(events);13931394    expect(result.success).to.be.true;1395    return result.itemId;1396  });1397}13981399export async function createMultipleItemsExpectSuccess(sender: IKeyringPair, collectionId: number, itemsData: any, owner: CrossAccountId | string = sender.address) {1400  await usingApi(async (api) => {1401    const to = normalizeAccountId(owner);1402    const tx = api.tx.unique.createMultipleItems(collectionId, to, itemsData);14031404    const events = await submitTransactionAsync(sender, tx);1405    expect(getGenericResult(events).success).to.be.true;1406  });1407}14081409export async function createMultipleItemsWithPropsExpectSuccess(sender: IKeyringPair, collectionId: number, itemsData: any, owner: CrossAccountId | string = sender.address) {1410  await usingApi(async (api) => {1411    const to = normalizeAccountId(owner);1412    const tx = api.tx.unique.createMultipleItems(collectionId, to, itemsData);14131414    const events = await submitTransactionAsync(sender, tx);1415    const result = getCreateItemsResult(events);14161417    for (const res of result) {1418      expect(await api.rpc.unique.tokenProperties(collectionId, res.itemId)).not.to.be.empty;1419    }1420  });1421}14221423export async function createMultipleItemsExWithPropsExpectSuccess(sender: IKeyringPair, collectionId: number, itemsData: any) {1424  await usingApi(async (api) => {1425    const tx = api.tx.unique.createMultipleItemsEx(collectionId, itemsData);14261427    const events = await submitTransactionAsync(sender, tx);1428    const result = getCreateItemsResult(events);14291430    for (const res of result) {1431      expect(await api.rpc.unique.tokenProperties(collectionId, res.itemId)).not.to.be.empty;1432    }1433  });1434}14351436export async function createItemWithPropsExpectSuccess(sender: IKeyringPair, collectionId: number, createMode: string, props:  Array<Property>, owner: CrossAccountId | string = sender.address) {1437  let newItemId = 0;1438  await usingApi(async (api) => {1439    const to = normalizeAccountId(owner);1440    const itemCountBefore = await getLastTokenId(api, collectionId);1441    const itemBalanceBefore = await getBalance(api, collectionId, to, newItemId);14421443    let tx;1444    if (createMode === 'Fungible') {1445      const createData = {fungible: {value: 10}};1446      tx = api.tx.unique.createItem(collectionId, to, createData as any);1447    } else if (createMode === 'ReFungible') {1448      const createData = {refungible: {pieces: 100}};1449      tx = api.tx.unique.createItem(collectionId, to, createData as any);1450    } else {1451      const data = api.createType('UpDataStructsCreateItemData', {NFT: {properties: props}});1452      tx = api.tx.unique.createItem(collectionId, to, data as UpDataStructsCreateItemData);1453    }14541455    const events = await submitTransactionAsync(sender, tx);1456    const result = getCreateItemResult(events);14571458    const itemCountAfter = await getLastTokenId(api, collectionId);1459    const itemBalanceAfter = await getBalance(api, collectionId, to, newItemId);14601461    if (createMode === 'NFT') {1462      expect(await api.rpc.unique.tokenProperties(collectionId, result.itemId)).not.to.be.empty;1463    }14641465    // What to expect1466    // tslint:disable-next-line:no-unused-expression1467    expect(result.success).to.be.true;1468    if (createMode === 'Fungible') {1469      expect(itemBalanceAfter - itemBalanceBefore).to.be.equal(10n);1470    } else {1471      expect(itemCountAfter).to.be.equal(itemCountBefore + 1);1472    }1473    expect(collectionId).to.be.equal(result.collectionId);1474    expect(itemCountAfter.toString()).to.be.equal(result.itemId.toString());1475    expect(to).to.be.deep.equal(result.recipient);1476    newItemId = result.itemId;1477  });1478  return newItemId;1479}14801481export async function createItemWithPropsExpectFailure(sender: IKeyringPair, collectionId: number, createMode: string, props: Array<Property>, owner: CrossAccountId | string = sender.address) {1482  await usingApi(async (api) => {14831484    let tx;1485    if (createMode === 'NFT') {1486      const data = api.createType('UpDataStructsCreateItemData', {NFT: {properties: props}}) as UpDataStructsCreateItemData;1487      tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), data);1488    } else {1489      tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), createMode);1490    }149114921493    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1494    if(events.message && events.message.toString().indexOf('1002: Verification Error') > -1) return;1495    const result = getCreateItemResult(events);14961497    expect(result.success).to.be.false;1498  });1499}15001501export async function createItemExpectSuccess(sender: IKeyringPair, collectionId: number, createMode: string, owner: CrossAccountId | string = sender.address) {1502  let newItemId = 0;1503  await usingApi(async (api) => {1504    const to = normalizeAccountId(owner);1505    const itemCountBefore = await getLastTokenId(api, collectionId);1506    const itemBalanceBefore = await getBalance(api, collectionId, to, newItemId);15071508    let tx;1509    if (createMode === 'Fungible') {1510      const createData = {fungible: {value: 10}};1511      tx = api.tx.unique.createItem(collectionId, to, createData as any);1512    } else if (createMode === 'ReFungible') {1513      const createData = {refungible: {pieces: 100}};1514      tx = api.tx.unique.createItem(collectionId, to, createData as any);1515    } else {1516      const createData = {nft: {}};1517      tx = api.tx.unique.createItem(collectionId, to, createData as any);1518    }15191520    const events = await executeTransaction(api, sender, tx);1521    const result = getCreateItemResult(events);15221523    const itemCountAfter = await getLastTokenId(api, collectionId);1524    const itemBalanceAfter = await getBalance(api, collectionId, to, newItemId);15251526    // What to expect1527    // tslint:disable-next-line:no-unused-expression1528    expect(result.success).to.be.true;1529    if (createMode === 'Fungible') {1530      expect(itemBalanceAfter - itemBalanceBefore).to.be.equal(10n);1531    } else {1532      expect(itemCountAfter).to.be.equal(itemCountBefore + 1);1533    }1534    expect(collectionId).to.be.equal(result.collectionId);1535    expect(itemCountAfter.toString()).to.be.equal(result.itemId.toString());1536    expect(to).to.be.deep.equal(result.recipient);1537    newItemId = result.itemId;1538  });1539  return newItemId;1540}15411542export async function createRefungibleToken(api: ApiPromise, sender: IKeyringPair, collectionId: number, amount: bigint, owner: CrossAccountId | IKeyringPair | string = sender.address) : Promise<CreateItemResult> {1543  const createData = {refungible: {pieces: amount}};1544  const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), createData as any);15451546  const events = await submitTransactionAsync(sender, tx);1547  return  getCreateItemResult(events);1548}15491550export async function createItemExpectFailure(sender: IKeyringPair, collectionId: number, createMode: string, owner: CrossAccountId | string = sender.address) {1551  await usingApi(async (api) => {1552    const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), createMode);15531554    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1555    const result = getCreateItemResult(events);15561557    expect(result.success).to.be.false;1558  });1559}15601561export async function setPublicAccessModeExpectSuccess(1562  sender: IKeyringPair, collectionId: number,1563  accessMode: 'Normal' | 'AllowList',1564) {1565  await usingApi(async (api) => {15661567    // Run the transaction1568    const tx = api.tx.unique.setCollectionPermissions(collectionId, {access: accessMode});1569    const events = await submitTransactionAsync(sender, tx);1570    const result = getGenericResult(events);15711572    // Get the collection1573    const collection = await queryCollectionExpectSuccess(api, collectionId);15741575    // What to expect1576    // tslint:disable-next-line:no-unused-expression1577    expect(result.success).to.be.true;1578    expect(collection.permissions.access.toHuman()).to.be.equal(accessMode);1579  });1580}15811582export async function setPublicAccessModeExpectFail(1583  sender: IKeyringPair, collectionId: number,1584  accessMode: 'Normal' | 'AllowList',1585) {1586  await usingApi(async (api) => {15871588    // Run the transaction1589    const tx = api.tx.unique.setCollectionPermissions(collectionId, {access: accessMode});1590    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1591    const result = getGenericResult(events);15921593    // What to expect1594    // tslint:disable-next-line:no-unused-expression1595    expect(result.success).to.be.false;1596  });1597}15981599export async function enableAllowListExpectSuccess(sender: IKeyringPair, collectionId: number) {1600  await setPublicAccessModeExpectSuccess(sender, collectionId, 'AllowList');1601}16021603export async function enableAllowListExpectFail(sender: IKeyringPair, collectionId: number) {1604  await setPublicAccessModeExpectFail(sender, collectionId, 'AllowList');1605}16061607export async function disableAllowListExpectSuccess(sender: IKeyringPair, collectionId: number) {1608  await setPublicAccessModeExpectSuccess(sender, collectionId, 'Normal');1609}16101611export async function setMintPermissionExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {1612  await usingApi(async (api) => {16131614    // Run the transaction1615    const tx = api.tx.unique.setCollectionPermissions(collectionId, {mintMode: enabled});1616    const events = await submitTransactionAsync(sender, tx);1617    const result = getGenericResult(events);1618    expect(result.success).to.be.true;16191620    // Get the collection1621    const collection = await queryCollectionExpectSuccess(api, collectionId);16221623    expect(collection.permissions.mintMode.toHuman()).to.be.equal(enabled);1624  });1625}16261627export async function enablePublicMintingExpectSuccess(sender: IKeyringPair, collectionId: number) {1628  await setMintPermissionExpectSuccess(sender, collectionId, true);1629}16301631export async function setMintPermissionExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {1632  await usingApi(async (api) => {1633    // Run the transaction1634    const tx = api.tx.unique.setCollectionPermissions(collectionId, {mintMode: enabled});1635    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1636    const result = getCreateCollectionResult(events);1637    // tslint:disable-next-line:no-unused-expression1638    expect(result.success).to.be.false;1639  });1640}16411642export async function setChainLimitsExpectFailure(sender: IKeyringPair, limits: IChainLimits) {1643  await usingApi(async (api) => {1644    // Run the transaction1645    const tx = api.tx.unique.setChainLimits(limits);1646    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1647    const result = getCreateCollectionResult(events);1648    // tslint:disable-next-line:no-unused-expression1649    expect(result.success).to.be.false;1650  });1651}16521653export async function isAllowlisted(api: ApiPromise, collectionId: number, address: string | CrossAccountId) {1654  return (await api.rpc.unique.allowed(collectionId, normalizeAccountId(address))).toJSON();1655}16561657export async function addToAllowListExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId | CrossAccountId) {1658  await usingApi(async (api) => {1659    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.false;16601661    // Run the transaction1662    const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1663    const events = await submitTransactionAsync(sender, tx);1664    const result = getGenericResult(events);1665    expect(result.success).to.be.true;16661667    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;1668  });1669}16701671export async function addToAllowListAgainExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId) {1672  await usingApi(async (api) => {16731674    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;16751676    // Run the transaction1677    const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1678    const events = await submitTransactionAsync(sender, tx);1679    const result = getGenericResult(events);1680    expect(result.success).to.be.true;16811682    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;1683  });1684}16851686export async function addToAllowListExpectFail(sender: IKeyringPair, collectionId: number, address: string | AccountId) {1687  await usingApi(async (api) => {16881689    // Run the transaction1690    const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1691    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1692    const result = getGenericResult(events);16931694    // What to expect1695    // tslint:disable-next-line:no-unused-expression1696    expect(result.success).to.be.false;1697  });1698}16991700export async function removeFromAllowListExpectSuccess(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1701  await usingApi(async (api) => {1702    // Run the transaction1703    const tx = api.tx.unique.removeFromAllowList(collectionId, normalizeAccountId(address));1704    const events = await submitTransactionAsync(sender, tx);1705    const result = getGenericResult(events);17061707    // What to expect1708    // tslint:disable-next-line:no-unused-expression1709    expect(result.success).to.be.true;1710  });1711}17121713export async function removeFromAllowListExpectFailure(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1714  await usingApi(async (api) => {1715    // Run the transaction1716    const tx = api.tx.unique.removeFromAllowList(collectionId, normalizeAccountId(address));1717    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1718    const result = getGenericResult(events);17191720    // What to expect1721    // tslint:disable-next-line:no-unused-expression1722    expect(result.success).to.be.false;1723  });1724}17251726export const getDetailedCollectionInfo = async (api: ApiPromise, collectionId: number)1727  : Promise<UpDataStructsRpcCollection | null> => {1728  return (await api.rpc.unique.collectionById(collectionId)).unwrapOr(null);1729};17301731export const getCreatedCollectionCount = async (api: ApiPromise): Promise<number> => {1732  // set global object - collectionsCount1733  return (await api.rpc.unique.collectionStats()).created.toNumber();1734};17351736export async function queryCollectionExpectSuccess(api: ApiPromise, collectionId: number): Promise<UpDataStructsRpcCollection> {1737  return (await api.rpc.unique.collectionById(collectionId)).unwrap();1738}17391740export async function waitNewBlocks(blocksCount = 1): Promise<void> {1741  await usingApi(async (api) => {1742    const promise = new Promise<void>(async (resolve) => {1743      const unsubscribe = await api.rpc.chain.subscribeNewHeads(() => {1744        if (blocksCount > 0) {1745          blocksCount--;1746        } else {1747          unsubscribe();1748          resolve();1749        }1750      });1751    });1752    return promise;1753  });1754}17551756export async function repartitionRFT(1757  api: ApiPromise,1758  collectionId: number,1759  sender: IKeyringPair,1760  tokenId: number,1761  amount: bigint,1762): Promise<boolean> {1763  const tx = api.tx.unique.repartition(collectionId, tokenId, amount);1764  const events = await submitTransactionAsync(sender, tx);1765  const result = getGenericResult(events);17661767  return result.success;1768}17691770export async function itApi(name: string, cb: (apis: { api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair }) => any, opts: { only?: boolean, skip?: boolean } = {}) {1771  let i: any = it;1772  if (opts.only) i = i.only;1773  else if (opts.skip) i = i.skip;1774  i(name, async () => {1775    await usingApi(async (api, privateKeyWrapper) => {1776      await cb({api, privateKeyWrapper});1777    });1778  });1779}17801781itApi.only = (name: string, cb: (apis: { api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair }) => any) => itApi(name, cb, {only: true});1782itApi.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, BlockNumber} 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 {AnyNumber} from '@polkadot/types-codec/types';25import BN from 'bn.js';26import chai from 'chai';27import chaiAsPromised from 'chai-as-promised';28import {default as usingApi, executeTransaction, submitTransactionAsync, submitTransactionExpectFailAsync} from '../substrate/substrate-api';29import {hexToStr, strToUTF16, utf16ToStr} from './util';30import {UpDataStructsRpcCollection, UpDataStructsCreateItemData, UpDataStructsProperty} from '@polkadot/types/lookup';31import {UpDataStructsTokenChild} from '../interfaces';32import {Context} from 'mocha';3334chai.use(chaiAsPromised);35const expect = chai.expect;3637export type CrossAccountId = {38  Substrate: string,39} | {40  Ethereum: string,41};424344export enum Pallets {45  Inflation = 'inflation',46  RmrkCore = 'rmrkcore',47  RmrkEquip = 'rmrkequip',48  ReFungible = 'refungible',49  Fungible = 'fungible',50  NFT = 'nonfungible',51  Scheduler = 'scheduler',52  AppPromotion = 'apppromotion',53}5455export async function isUnique(): Promise<boolean> {56  return usingApi(async api => {57    const chain = await api.rpc.system.chain();5859    return chain.eq('UNIQUE');60  });61}6263export async function isQuartz(): Promise<boolean> {64  return usingApi(async api => {65    const chain = await api.rpc.system.chain();66    67    return chain.eq('QUARTZ');68  });69}7071let modulesNames: any;72export function getModuleNames(api: ApiPromise): string[] {73  if (typeof modulesNames === 'undefined') 74    modulesNames = api.runtimeMetadata.asLatest.pallets.map(m => m.name.toString().toLowerCase());75  return modulesNames;76}7778export async function missingRequiredPallets(requiredPallets: string[]): Promise<string[]> {79  return await usingApi(async api => {80    const pallets = getModuleNames(api);8182    return requiredPallets.filter(p => !pallets.includes(p));83  });84}8586export async function checkPalletsPresence(requiredPallets: string[]): Promise<boolean> {87  return (await missingRequiredPallets(requiredPallets)).length == 0;88}8990export async function requirePallets(mocha: Context, requiredPallets: string[]) {91  const missingPallets = await missingRequiredPallets(requiredPallets);9293  if (missingPallets.length > 0) {94    const skippingTestMsg = `\tSkipping test "${mocha.test?.title}".`;95    const missingPalletsMsg = `\tThe following pallets are missing:\n\t- ${missingPallets.join('\n\t- ')}`;96    const skipMsg = `${skippingTestMsg}\n${missingPalletsMsg}`;9798    console.error('\x1b[38:5:208m%s\x1b[0m', skipMsg);99100    mocha.skip();101  }102}103104export function bigIntToSub(api: ApiPromise, number: bigint) {105  return api.registry.createType('AccountId', '0x' + number.toString(16).padStart(64, '0')).toJSON();106}107108export function normalizeAccountId(input: string | AccountId | CrossAccountId | IKeyringPair): CrossAccountId {109  if (typeof input === 'string') {110    if (input.length >= 47) {111      return {Substrate: input};112    } else if (input.length === 42 && input.startsWith('0x')) {113      return {Ethereum: input.toLowerCase()};114    } else if (input.length === 40 && !input.startsWith('0x')) {115      return {Ethereum: '0x' + input.toLowerCase()};116    } else {117      throw new Error(`Unknown address format: "${input}"`);118    }119  }120  if ('address' in input) {121    return {Substrate: input.address};122  }123  if ('Ethereum' in input) {124    return {125      Ethereum: input.Ethereum.toLowerCase(),126    };127  } else if ('ethereum' in input) {128    return {129      Ethereum: (input as any).ethereum.toLowerCase(),130    };131  } else if ('Substrate' in input) {132    return input;133  } else if ('substrate' in input) {134    return {135      Substrate: (input as any).substrate,136    };137  }138139  // AccountId140  return {Substrate: input.toString()};141}142export function toSubstrateAddress(input: string | CrossAccountId | IKeyringPair): string {143  input = normalizeAccountId(input);144  if ('Substrate' in input) {145    return input.Substrate;146  } else {147    return evmToAddress(input.Ethereum);148  }149}150151export const U128_MAX = (1n << 128n) - 1n;152153const MICROUNIQUE = 1_000_000_000_000n;154const MILLIUNIQUE = 1_000n * MICROUNIQUE;155const CENTIUNIQUE = 10n * MILLIUNIQUE;156export const UNIQUE = 100n * CENTIUNIQUE;157158interface GenericResult<T> {159  success: boolean;160  data: T | null;161}162163interface CreateCollectionResult {164  success: boolean;165  collectionId: number;166}167168interface CreateItemResult {169  success: boolean;170  collectionId: number;171  itemId: number;172  recipient?: CrossAccountId;173  amount?: number;174}175176interface DestroyItemResult {177  success: boolean;178  collectionId: number;179  itemId: number;180  owner: CrossAccountId;181  amount: number;182}183184interface TransferResult {185  collectionId: number;186  itemId: number;187  sender?: CrossAccountId;188  recipient?: CrossAccountId;189  value: bigint;190}191192interface IReFungibleOwner {193  fraction: BN;194  owner: number[];195}196197interface IGetMessage {198  checkMsgUnqMethod: string;199  checkMsgTrsMethod: string;200  checkMsgSysMethod: string;201}202203export interface IFungibleTokenDataType {204  value: number;205}206207export interface IChainLimits {208  collectionNumbersLimit: number;209  accountTokenOwnershipLimit: number;210  collectionsAdminsLimit: number;211  customDataLimit: number;212  nftSponsorTransferTimeout: number;213  fungibleSponsorTransferTimeout: number;214  refungibleSponsorTransferTimeout: number;215  //offchainSchemaLimit: number;216  //constOnChainSchemaLimit: number;217}218219export interface IReFungibleTokenDataType {220  owner: IReFungibleOwner[];221}222223export function uniqueEventMessage(events: EventRecord[]): IGetMessage {224  let checkMsgUnqMethod = '';225  let checkMsgTrsMethod = '';226  let checkMsgSysMethod = '';227  events.forEach(({event: {method, section}}) => {228    if (section === 'common') {229      checkMsgUnqMethod = method;230    } else if (section === 'treasury') {231      checkMsgTrsMethod = method;232    } else if (section === 'system') {233      checkMsgSysMethod = method;234    } else { return null; }235  });236  const result: IGetMessage = {237    checkMsgUnqMethod,238    checkMsgTrsMethod,239    checkMsgSysMethod,240  };241  return result;242}243244export function getEvent<T extends Event>(events: EventRecord[], check: (event: IEvent<AnyTuple>) => event is T): T | undefined {245  const event = events.find(r => check(r.event));246  if (!event) return;247  return event.event as T;248}249250export function getGenericResult<T>(events: EventRecord[]): GenericResult<T>;251export function getGenericResult<T>(252  events: EventRecord[],253  expectSection: string,254  expectMethod: string,255  extractAction: (data: GenericEventData) => T256): GenericResult<T>;257258export function getGenericResult<T>(259  events: EventRecord[],260  expectSection?: string,261  expectMethod?: string,262  extractAction?: (data: GenericEventData) => T,263): GenericResult<T> {264  let success = false;265  let successData = null;266267  events.forEach(({event: {data, method, section}}) => {268    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);269    if (method === 'ExtrinsicSuccess') {270      success = true;271    } else if ((expectSection == section) && (expectMethod == method)) {272      successData = extractAction!(data as any);273    }274  });275276  const result: GenericResult<T> = {277    success,278    data: successData,279  };280  return result;281}282283export function getCreateCollectionResult(events: EventRecord[]): CreateCollectionResult {284  const genericResult = getGenericResult(events, 'common', 'CollectionCreated', (data) => parseInt(data[0].toString(), 10));285  const result: CreateCollectionResult = {286    success: genericResult.success,287    collectionId: genericResult.data ?? 0,288  };289  return result;290}291292export function getCreateItemsResult(events: EventRecord[]): CreateItemResult[] {293  const results: CreateItemResult[] = [];294  295  const genericResult = getGenericResult<CreateItemResult[]>(events, 'common', 'ItemCreated', (data) => {296    const collectionId = parseInt(data[0].toString(), 10);297    const itemId = parseInt(data[1].toString(), 10);298    const recipient = normalizeAccountId(data[2].toJSON() as any);299    const amount = parseInt(data[3].toString(), 10);300301    const itemRes: CreateItemResult = {302      success: true,303      collectionId,304      itemId,305      recipient,306      amount,307    };308309    results.push(itemRes);310    return results;311  });312313  if (!genericResult.success) return [];314  return results;315}316317export function getCreateItemResult(events: EventRecord[]): CreateItemResult {318  const genericResult = getGenericResult(events, 'common', 'ItemCreated', (data) => data.map(function(value) { return value.toJSON(); }));319  320  if (genericResult.data == null) 321    return {322      success: genericResult.success,323      collectionId: 0,324      itemId: 0,325      amount: 0,326    };327  else 328    return {329      success: genericResult.success,330      collectionId: genericResult.data[0] as number,331      itemId: genericResult.data[1] as number,332      recipient: normalizeAccountId(genericResult.data![2] as any),333      amount: genericResult.data[3] as number,334    };335}336337export function getDestroyItemsResult(events: EventRecord[]): DestroyItemResult[] {338  const results: DestroyItemResult[] = [];339  340  const genericResult = getGenericResult<DestroyItemResult[]>(events, 'common', 'ItemDestroyed', (data) => {341    const collectionId = parseInt(data[0].toString(), 10);342    const itemId = parseInt(data[1].toString(), 10);343    const owner = normalizeAccountId(data[2].toJSON() as any);344    const amount = parseInt(data[3].toString(), 10);345346    const itemRes: DestroyItemResult = {347      success: true,348      collectionId,349      itemId,350      owner,351      amount,352    };353354    results.push(itemRes);355    return results;356  });357358  if (!genericResult.success) return [];359  return results;360}361362export function getTransferResult(api: ApiPromise, events: EventRecord[]): TransferResult {363  for (const {event} of events) {364    if (api.events.common.Transfer.is(event)) {365      const [collection, token, sender, recipient, value] = event.data;366      return {367        collectionId: collection.toNumber(),368        itemId: token.toNumber(),369        sender: normalizeAccountId(sender.toJSON() as any),370        recipient: normalizeAccountId(recipient.toJSON() as any),371        value: value.toBigInt(),372      };373    }374  }375  throw new Error('no transfer event');376}377378interface Nft {379  type: 'NFT';380}381382interface Fungible {383  type: 'Fungible';384  decimalPoints: number;385}386387interface ReFungible {388  type: 'ReFungible';389}390391export type CollectionMode = Nft | Fungible | ReFungible;392393export type Property = {394  key: any,395  value: any,396};397398type Permission = {399  mutable: boolean;400  collectionAdmin: boolean;401  tokenOwner: boolean;402}403404type PropertyPermission = {405  key: any;406  permission: Permission;407}408409export type CreateCollectionParams = {410  mode: CollectionMode,411  name: string,412  description: string,413  tokenPrefix: string,414  properties?: Array<Property>,415  propPerm?: Array<PropertyPermission>416};417418const defaultCreateCollectionParams: CreateCollectionParams = {419  description: 'description',420  mode: {type: 'NFT'},421  name: 'name',422  tokenPrefix: 'prefix',423};424425export async function426createCollection(427  api: ApiPromise,428  sender: IKeyringPair,429  params: Partial<CreateCollectionParams> = {},430): Promise<CreateCollectionResult> {431  const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};432433  let modeprm = {};434  if (mode.type === 'NFT') {435    modeprm = {nft: null};436  } else if (mode.type === 'Fungible') {437    modeprm = {fungible: mode.decimalPoints};438  } else if (mode.type === 'ReFungible') {439    modeprm = {refungible: null};440  }441442  const tx = api.tx.unique.createCollectionEx({443    name: strToUTF16(name),444    description: strToUTF16(description),445    tokenPrefix: strToUTF16(tokenPrefix),446    mode: modeprm as any,447  });448  const events = await executeTransaction(api, sender, tx);449  return getCreateCollectionResult(events);450}451452export async function createCollectionExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {453  const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};454455  let collectionId = 0;456  await usingApi(async (api, privateKeyWrapper) => {457    // Get number of collections before the transaction458    const collectionCountBefore = await getCreatedCollectionCount(api);459460    // Run the CreateCollection transaction461    const alicePrivateKey = privateKeyWrapper('//Alice');462463    const result = await createCollection(api, alicePrivateKey, params);464465    // Get number of collections after the transaction466    const collectionCountAfter = await getCreatedCollectionCount(api);467468    // Get the collection469    const collection = await queryCollectionExpectSuccess(api, result.collectionId);470471    // What to expect472    // tslint:disable-next-line:no-unused-expression473    expect(result.success).to.be.true;474    expect(result.collectionId).to.be.equal(collectionCountAfter);475    // tslint:disable-next-line:no-unused-expression476    expect(collection).to.be.not.null;477    expect(collectionCountAfter).to.be.equal(collectionCountBefore + 1, 'Error: NFT collection NOT created.');478    expect(collection.owner.toString()).to.be.equal(toSubstrateAddress(alicePrivateKey));479    expect(utf16ToStr(collection.name.toJSON() as any)).to.be.equal(name);480    expect(utf16ToStr(collection.description.toJSON() as any)).to.be.equal(description);481    expect(hexToStr(collection.tokenPrefix.toJSON())).to.be.equal(tokenPrefix);482483    collectionId = result.collectionId;484  });485486  return collectionId;487}488489export async function createCollectionWithPropsExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {490  const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};491492  let collectionId = 0;493  await usingApi(async (api, privateKeyWrapper) => {494    // Get number of collections before the transaction495    const collectionCountBefore = await getCreatedCollectionCount(api);496497    // Run the CreateCollection transaction498    const alicePrivateKey = privateKeyWrapper('//Alice');499500    let modeprm = {};501    if (mode.type === 'NFT') {502      modeprm = {nft: null};503    } else if (mode.type === 'Fungible') {504      modeprm = {fungible: mode.decimalPoints};505    } else if (mode.type === 'ReFungible') {506      modeprm = {refungible: null};507    }508509    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});510    const events = await submitTransactionAsync(alicePrivateKey, tx);511    const result = getCreateCollectionResult(events);512513    // Get number of collections after the transaction514    const collectionCountAfter = await getCreatedCollectionCount(api);515516    // Get the collection517    const collection = await queryCollectionExpectSuccess(api, result.collectionId);518519    // What to expect520    // tslint:disable-next-line:no-unused-expression521    expect(result.success).to.be.true;522    expect(result.collectionId).to.be.equal(collectionCountAfter);523    // tslint:disable-next-line:no-unused-expression524    expect(collection).to.be.not.null;525    expect(collectionCountAfter).to.be.equal(collectionCountBefore + 1, 'Error: NFT collection NOT created.');526    expect(collection.owner.toString()).to.be.equal(toSubstrateAddress(alicePrivateKey));527    expect(utf16ToStr(collection.name.toJSON() as any)).to.be.equal(name);528    expect(utf16ToStr(collection.description.toJSON() as any)).to.be.equal(description);529    expect(hexToStr(collection.tokenPrefix.toJSON())).to.be.equal(tokenPrefix);530531532    collectionId = result.collectionId;533  });534535  return collectionId;536}537538export async function createCollectionWithPropsExpectFailure(params: Partial<CreateCollectionParams> = {}) {539  const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};540541  await usingApi(async (api, privateKeyWrapper) => {542    // Get number of collections before the transaction543    const collectionCountBefore = await getCreatedCollectionCount(api);544545    // Run the CreateCollection transaction546    const alicePrivateKey = privateKeyWrapper('//Alice');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    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});558    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;559560561    // Get number of collections after the transaction562    const collectionCountAfter = await getCreatedCollectionCount(api);563564    expect(collectionCountAfter).to.be.equal(collectionCountBefore, 'Error: Collection with incorrect data created.');565  });566}567568export async function createCollectionExpectFailure(params: Partial<CreateCollectionParams> = {}) {569  const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};570571  let modeprm = {};572  if (mode.type === 'NFT') {573    modeprm = {nft: null};574  } else if (mode.type === 'Fungible') {575    modeprm = {fungible: mode.decimalPoints};576  } else if (mode.type === 'ReFungible') {577    modeprm = {refungible: null};578  }579580  await usingApi(async (api, privateKeyWrapper) => {581    // Get number of collections before the transaction582    const collectionCountBefore = await getCreatedCollectionCount(api);583584    // Run the CreateCollection transaction585    const alicePrivateKey = privateKeyWrapper('//Alice');586    const tx = api.tx.unique.createCollectionEx({name: strToUTF16(name), description: strToUTF16(description), tokenPrefix: strToUTF16(tokenPrefix), mode: modeprm as any});587    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;588589    // Get number of collections after the transaction590    const collectionCountAfter = await getCreatedCollectionCount(api);591592    // What to expect593    expect(collectionCountAfter).to.be.equal(collectionCountBefore, 'Error: Collection with incorrect data created.');594  });595}596597export async function findUnusedAddress(api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair, seedAddition = ''): Promise<IKeyringPair> {598  let bal = 0n;599  let unused;600  do {601    const randomSeed = 'seed' + Math.floor(Math.random() * Math.floor(10000)) + seedAddition;602    unused = privateKeyWrapper(`//${randomSeed}`);603    bal = (await api.query.system.account(unused.address)).data.free.toBigInt();604  } while (bal !== 0n);605  return unused;606}607608export async function getAllowance(api: ApiPromise, collectionId: number, owner: CrossAccountId | string | IKeyringPair, approved: CrossAccountId | string | IKeyringPair, tokenId: number) {609  return (await api.rpc.unique.allowance(collectionId, normalizeAccountId(owner), normalizeAccountId(approved), tokenId)).toBigInt();610}611612export function findUnusedAddresses(api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair, amount: number): Promise<IKeyringPair[]> {613  return Promise.all(new Array(amount).fill(null).map(() => findUnusedAddress(api, privateKeyWrapper, '_' + Date.now())));614}615616export async function findNotExistingCollection(api: ApiPromise): Promise<number> {617  const totalNumber = await getCreatedCollectionCount(api);618  const newCollection: number = totalNumber + 1;619  return newCollection;620}621622function getDestroyResult(events: EventRecord[]): boolean {623  let success = false;624  events.forEach(({event: {method}}) => {625    if (method == 'ExtrinsicSuccess') {626      success = true;627    }628  });629  return success;630}631632export async function destroyCollectionExpectFailure(collectionId: number, senderSeed = '//Alice') {633  await usingApi(async (api, privateKeyWrapper) => {634    // Run the DestroyCollection transaction635    const alicePrivateKey = privateKeyWrapper(senderSeed);636    const tx = api.tx.unique.destroyCollection(collectionId);637    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;638  });639}640641export async function destroyCollectionExpectSuccess(collectionId: number, senderSeed = '//Alice') {642  await usingApi(async (api, privateKeyWrapper) => {643    // Run the DestroyCollection transaction644    const alicePrivateKey = privateKeyWrapper(senderSeed);645    const tx = api.tx.unique.destroyCollection(collectionId);646    const events = await submitTransactionAsync(alicePrivateKey, tx);647    const result = getDestroyResult(events);648    expect(result).to.be.true;649650    // What to expect651    expect(await getDetailedCollectionInfo(api, collectionId)).to.be.null;652  });653}654655export async function setCollectionLimitsExpectSuccess(sender: IKeyringPair, collectionId: number, limits: any) {656  await usingApi(async (api) => {657    const tx = api.tx.unique.setCollectionLimits(collectionId, limits);658    const events = await submitTransactionAsync(sender, tx);659    const result = getGenericResult(events);660661    expect(result.success).to.be.true;662  });663}664665export const setCollectionPermissionsExpectSuccess = async (sender: IKeyringPair, collectionId: number, permissions: any) => {666  await usingApi(async(api) => {667    const tx = api.tx.unique.setCollectionPermissions(collectionId, permissions);668    const events = await submitTransactionAsync(sender, tx);669    const result = getGenericResult(events);670671    expect(result.success).to.be.true;672  });673};674675export async function setCollectionLimitsExpectFailure(sender: IKeyringPair, collectionId: number, limits: any) {676  await usingApi(async (api) => {677    const tx = api.tx.unique.setCollectionLimits(collectionId, limits);678    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;679    const result = getGenericResult(events);680681    expect(result.success).to.be.false;682  });683}684685export async function setCollectionSponsorExpectSuccess(collectionId: number, sponsor: string, sender = '//Alice') {686  await usingApi(async (api, privateKeyWrapper) => {687688    // Run the transaction689    const senderPrivateKey = privateKeyWrapper(sender);690    const tx = api.tx.unique.setCollectionSponsor(collectionId, sponsor);691    const events = await submitTransactionAsync(senderPrivateKey, tx);692    const result = getGenericResult(events);693694    // Get the collection695    const collection = await queryCollectionExpectSuccess(api, collectionId);696697    // What to expect698    expect(result.success).to.be.true;699    expect(collection.sponsorship.toJSON()).to.deep.equal({700      unconfirmed: sponsor,701    });702  });703}704705export async function removeCollectionSponsorExpectSuccess(collectionId: number, sender = '//Alice') {706  await usingApi(async (api, privateKeyWrapper) => {707708    // Run the transaction709    const alicePrivateKey = privateKeyWrapper(sender);710    const tx = api.tx.unique.removeCollectionSponsor(collectionId);711    const events = await submitTransactionAsync(alicePrivateKey, tx);712    const result = getGenericResult(events);713714    // Get the collection715    const collection = await queryCollectionExpectSuccess(api, collectionId);716717    // What to expect718    expect(result.success).to.be.true;719    expect(collection.sponsorship.toJSON()).to.be.deep.equal({disabled: null});720  });721}722723export async function removeCollectionSponsorExpectFailure(collectionId: number, senderSeed = '//Alice') {724  await usingApi(async (api, privateKeyWrapper) => {725726    // Run the transaction727    const alicePrivateKey = privateKeyWrapper(senderSeed);728    const tx = api.tx.unique.removeCollectionSponsor(collectionId);729    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;730  });731}732733export async function setCollectionSponsorExpectFailure(collectionId: number, sponsor: string, senderSeed = '//Alice') {734  await usingApi(async (api, privateKeyWrapper) => {735736    // Run the transaction737    const alicePrivateKey = privateKeyWrapper(senderSeed);738    const tx = api.tx.unique.setCollectionSponsor(collectionId, sponsor);739    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;740  });741}742743export async function confirmSponsorshipExpectSuccess(collectionId: number, senderSeed = '//Alice') {744  await usingApi(async (api, privateKeyWrapper) => {745746    // Run the transaction747    const sender = privateKeyWrapper(senderSeed);748    await confirmSponsorshipByKeyExpectSuccess(collectionId, sender);749  });750}751752export async function confirmSponsorshipByKeyExpectSuccess(collectionId: number, sender: IKeyringPair) {753  await usingApi(async (api, privateKeyWrapper) => {754755    // Run the transaction756    const tx = api.tx.unique.confirmSponsorship(collectionId);757    const events = await submitTransactionAsync(sender, tx);758    const result = getGenericResult(events);759760    // Get the collection761    const collection = await queryCollectionExpectSuccess(api, collectionId);762763    // What to expect764    expect(result.success).to.be.true;765    expect(collection.sponsorship.toJSON()).to.be.deep.equal({766      confirmed: sender.address,767    });768  });769}770771772export async function confirmSponsorshipExpectFailure(collectionId: number, senderSeed = '//Alice') {773  await usingApi(async (api, privateKeyWrapper) => {774775    // Run the transaction776    const sender = privateKeyWrapper(senderSeed);777    const tx = api.tx.unique.confirmSponsorship(collectionId);778    await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;779  });780}781782export async function enableContractSponsoringExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {783  await usingApi(async (api) => {784    const tx = api.tx.unique.enableContractSponsoring(contractAddress, enable);785    const events = await submitTransactionAsync(sender, tx);786    const result = getGenericResult(events);787788    expect(result.success).to.be.true;789  });790}791792export async function enableContractSponsoringExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {793  await usingApi(async (api) => {794    const tx = api.tx.unique.enableContractSponsoring(contractAddress, enable);795    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;796    const result = getGenericResult(events);797798    expect(result.success).to.be.false;799  });800}801802export async function setTransferFlagExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {803804  await usingApi(async (api) => {805806    const tx = api.tx.unique.setTransfersEnabledFlag(collectionId, enabled);807    const events = await submitTransactionAsync(sender, tx);808    const result = getGenericResult(events);809810    expect(result.success).to.be.true;811  });812}813814export async function setTransferFlagExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {815816  await usingApi(async (api) => {817818    const tx = api.tx.unique.setTransfersEnabledFlag(collectionId, enabled);819    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;820    const result = getGenericResult(events);821822    expect(result.success).to.be.false;823  });824}825826export async function setContractSponsoringRateLimitExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {827  await usingApi(async (api) => {828    const tx = api.tx.unique.setContractSponsoringRateLimit(contractAddress, rateLimit);829    const events = await submitTransactionAsync(sender, tx);830    const result = getGenericResult(events);831832    expect(result.success).to.be.true;833  });834}835836export async function setContractSponsoringRateLimitExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {837  await usingApi(async (api) => {838    const tx = api.tx.unique.setContractSponsoringRateLimit(contractAddress, rateLimit);839    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;840    const result = getGenericResult(events);841842    expect(result.success).to.be.false;843  });844}845846export async function getNextSponsored(847  api: ApiPromise,848  collectionId: number,849  account: string | CrossAccountId,850  tokenId: number,851): Promise<number> {852  return Number((await api.rpc.unique.nextSponsored(collectionId, account, tokenId)).unwrapOr(-1));853}854855export async function toggleContractAllowlistExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, value = true) {856  await usingApi(async (api) => {857    const tx = api.tx.unique.toggleContractAllowList(contractAddress, value);858    const events = await submitTransactionAsync(sender, tx);859    const result = getGenericResult(events);860861    expect(result.success).to.be.true;862  });863}864865export async function isAllowlistedInContract(contractAddress: AccountId | string, user: string) {866  let allowlisted = false;867  await usingApi(async (api) => {868    allowlisted = (await api.query.unique.contractAllowList(contractAddress, user)).toJSON() as boolean;869  });870  return allowlisted;871}872873export async function addToContractAllowListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {874  await usingApi(async (api) => {875    const tx = api.tx.unique.addToContractAllowList(contractAddress.toString(), user.toString());876    const events = await submitTransactionAsync(sender, tx);877    const result = getGenericResult(events);878879    expect(result.success).to.be.true;880  });881}882883export async function removeFromContractAllowListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {884  await usingApi(async (api) => {885    const tx = api.tx.unique.removeFromContractAllowList(contractAddress.toString(), user.toString());886    const events = await submitTransactionAsync(sender, tx);887    const result = getGenericResult(events);888889    expect(result.success).to.be.true;890  });891}892893export async function removeFromContractAllowListExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {894  await usingApi(async (api) => {895    const tx = api.tx.unique.removeFromContractAllowList(contractAddress.toString(), user.toString());896    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;897    const result = getGenericResult(events);898899    expect(result.success).to.be.false;900  });901}902903export interface CreateFungibleData {904  readonly Value: bigint;905}906907export interface CreateReFungibleData { }908export interface CreateNftData { }909910export type CreateItemData = {911  NFT: CreateNftData;912} | {913  Fungible: CreateFungibleData;914} | {915  ReFungible: CreateReFungibleData;916};917918export async function burnItem(api: ApiPromise, sender: IKeyringPair, collectionId: number, tokenId: number, value: number | bigint) : Promise<boolean> {919  const tx = api.tx.unique.burnItem(collectionId, tokenId, value);920  const events = await submitTransactionAsync(sender, tx);921  return getGenericResult(events).success;922}923924export async function burnItemExpectSuccess(sender: IKeyringPair, collectionId: number, tokenId: number, value: number | bigint = 1) {925  await usingApi(async (api) => {926    const balanceBefore = await getBalance(api, collectionId, normalizeAccountId(sender), tokenId);927    // if burning token by admin - use adminButnItemExpectSuccess928    expect(balanceBefore >= BigInt(value)).to.be.true;929930    expect(await burnItem(api, sender, collectionId, tokenId, value)).to.be.true;931932    const balanceAfter = await getBalance(api, collectionId, normalizeAccountId(sender), tokenId);933    expect(balanceAfter + BigInt(value)).to.be.equal(balanceBefore);934  });935}936937export async function burnItemExpectFailure(sender: IKeyringPair, collectionId: number, tokenId: number, value: number | bigint = 1) {938  await usingApi(async (api) => {939    const tx = api.tx.unique.burnItem(collectionId, tokenId, value);940941    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;942    const result = getCreateCollectionResult(events);943    // tslint:disable-next-line:no-unused-expression944    expect(result.success).to.be.false;945  });946}947948export async function burnFromExpectSuccess(sender: IKeyringPair, from: IKeyringPair | CrossAccountId, collectionId: number, tokenId: number, value: number | bigint = 1) {949  await usingApi(async (api) => {950    const tx = api.tx.unique.burnFrom(collectionId, normalizeAccountId(from), tokenId, value);951    const events = await submitTransactionAsync(sender, tx);952    return getGenericResult(events).success;953  });954}955956export async function957approve(958  api: ApiPromise,959  collectionId: number,960  tokenId: number, owner: IKeyringPair, approved: CrossAccountId | string | IKeyringPair, amount: number | bigint,961) {962  const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);963  const events = await submitTransactionAsync(owner, approveUniqueTx);964  return getGenericResult(events).success;965}966967export async function968approveExpectSuccess(969  collectionId: number,970  tokenId: number, owner: IKeyringPair, approved: CrossAccountId | string, amount: number | bigint = 1,971) {972  await usingApi(async (api: ApiPromise) => {973    const result = await approve(api, collectionId, tokenId, owner, approved, amount);974    expect(result).to.be.true;975976    expect(await getAllowance(api, collectionId, owner, approved, tokenId)).to.be.equal(BigInt(amount));977  });978}979980export async function adminApproveFromExpectSuccess(981  collectionId: number,982  tokenId: number, admin: IKeyringPair, owner: CrossAccountId | string, approved: CrossAccountId | string, amount: number | bigint = 1,983) {984  await usingApi(async (api: ApiPromise) => {985    const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);986    const events = await submitTransactionAsync(admin, approveUniqueTx);987    const result = getGenericResult(events);988    expect(result.success).to.be.true;989990    expect(await getAllowance(api, collectionId, owner, approved, tokenId)).to.be.equal(BigInt(amount));991  });992}993994export async function995transferFrom(996  api: ApiPromise,997  collectionId: number,998  tokenId: number,999  accountApproved: IKeyringPair,1000  accountFrom: IKeyringPair | CrossAccountId,1001  accountTo: IKeyringPair | CrossAccountId,1002  value: number | bigint,1003) {1004  const from = normalizeAccountId(accountFrom);1005  const to = normalizeAccountId(accountTo);1006  const transferFromTx = api.tx.unique.transferFrom(from, to, collectionId, tokenId, value);1007  const events = await submitTransactionAsync(accountApproved, transferFromTx);1008  return getGenericResult(events).success;1009}10101011export async function1012transferFromExpectSuccess(1013  collectionId: number,1014  tokenId: number,1015  accountApproved: IKeyringPair,1016  accountFrom: IKeyringPair | CrossAccountId,1017  accountTo: IKeyringPair | CrossAccountId,1018  value: number | bigint = 1,1019  type = 'NFT',1020) {1021  await usingApi(async (api: ApiPromise) => {1022    const from = normalizeAccountId(accountFrom);1023    const to = normalizeAccountId(accountTo);1024    let balanceBefore = 0n;1025    if (type === 'Fungible' || type === 'ReFungible') {1026      balanceBefore = await getBalance(api, collectionId, to, tokenId);1027    }1028    expect(await transferFrom(api, collectionId, tokenId, accountApproved, accountFrom, accountTo, value)).to.be.true;1029    if (type === 'NFT') {1030      expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(to);1031    }1032    if (type === 'Fungible') {1033      const balanceAfter = await getBalance(api, collectionId, to, tokenId);1034      if (JSON.stringify(to) !== JSON.stringify(from)) {1035        expect(balanceAfter - balanceBefore).to.be.equal(BigInt(value));1036      } else {1037        expect(balanceAfter).to.be.equal(balanceBefore);1038      }1039    }1040    if (type === 'ReFungible') {1041      expect(await getBalance(api, collectionId, to, tokenId)).to.be.equal(balanceBefore + BigInt(value));1042    }1043  });1044}10451046export async function1047transferFromExpectFail(1048  collectionId: number,1049  tokenId: number,1050  accountApproved: IKeyringPair,1051  accountFrom: IKeyringPair,1052  accountTo: IKeyringPair,1053  value: number | bigint = 1,1054) {1055  await usingApi(async (api: ApiPromise) => {1056    const transferFromTx = api.tx.unique.transferFrom(normalizeAccountId(accountFrom.address), normalizeAccountId(accountTo.address), collectionId, tokenId, value);1057    const events = await expect(submitTransactionExpectFailAsync(accountApproved, transferFromTx)).to.be.rejected;1058    const result = getCreateCollectionResult(events);1059    // tslint:disable-next-line:no-unused-expression1060    expect(result.success).to.be.false;1061  });1062}10631064/* eslint no-async-promise-executor: "off" */1065export async function getBlockNumber(api: ApiPromise): Promise<number> {1066  return new Promise<number>(async (resolve) => {1067    const unsubscribe = await api.rpc.chain.subscribeNewHeads((head) => {1068      unsubscribe();1069      resolve(head.number.toNumber());1070    });1071  });1072}10731074export async function addCollectionAdminExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | CrossAccountId) {1075  await usingApi(async (api) => {1076    const changeAdminTx = api.tx.unique.addCollectionAdmin(collectionId, normalizeAccountId(address));1077    const events = await submitTransactionAsync(sender, changeAdminTx);1078    const result = getCreateCollectionResult(events);1079    expect(result.success).to.be.true;1080  });1081}10821083export async function adminApproveFromExpectFail(1084  collectionId: number,1085  tokenId: number, admin: IKeyringPair, owner: CrossAccountId | string, approved: CrossAccountId | string, amount: number | bigint = 1,1086) {1087  await usingApi(async (api: ApiPromise) => {1088    const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);1089    const events = await expect(submitTransactionAsync(admin, approveUniqueTx)).to.be.rejected;1090    const result = getGenericResult(events);1091    expect(result.success).to.be.false;1092  });1093}10941095export async function1096getFreeBalance(account: IKeyringPair): Promise<bigint> {1097  let balance = 0n;1098  await usingApi(async (api) => {1099    balance = BigInt((await api.query.system.account(account.address)).data.free.toString());1100  });11011102  return balance;1103}11041105export async function transferBalanceTo(api: ApiPromise, source: IKeyringPair, target: string, amount = 1000n * UNIQUE) {1106  const tx = api.tx.balances.transfer(target, amount);1107  const events = await submitTransactionAsync(source, tx);1108  const result = getGenericResult(events);1109  expect(result.success).to.be.true;1110}11111112export async function1113scheduleExpectSuccess(1114  operationTx: any,1115  sender: IKeyringPair,1116  blockSchedule: number,1117  scheduledId: string,1118  period = 1,1119  repetitions = 1,1120) {1121  await usingApi(async (api: ApiPromise) => {1122    const blockNumber: number | undefined = await getBlockNumber(api);1123    const expectedBlockNumber = blockNumber + blockSchedule;11241125    expect(blockNumber).to.be.greaterThan(0);1126    const scheduleTx = api.tx.scheduler.scheduleNamed( // schedule1127      scheduledId,1128      expectedBlockNumber, 1129      repetitions > 1 ? [period, repetitions] : null, 1130      0, 1131      {Value: operationTx as any},1132    );11331134    const events = await submitTransactionAsync(sender, scheduleTx);1135    expect(getGenericResult(events).success).to.be.true;1136  });1137}11381139export async function1140scheduleExpectFailure(1141  operationTx: any,1142  sender: IKeyringPair,1143  blockSchedule: number,1144  scheduledId: string,1145  period = 1,1146  repetitions = 1,1147) {1148  await usingApi(async (api: ApiPromise) => {1149    const blockNumber: number | undefined = await getBlockNumber(api);1150    const expectedBlockNumber = blockNumber + blockSchedule;11511152    expect(blockNumber).to.be.greaterThan(0);1153    const scheduleTx = api.tx.scheduler.scheduleNamed( // schedule1154      scheduledId,1155      expectedBlockNumber, 1156      repetitions <= 1 ? null : [period, repetitions], 1157      0, 1158      {Value: operationTx as any},1159    );11601161    //const events = 1162    await expect(submitTransactionExpectFailAsync(sender, scheduleTx)).to.be.rejected;1163    //expect(getGenericResult(events).success).to.be.false;1164  });1165}11661167export async function1168scheduleTransferAndWaitExpectSuccess(1169  collectionId: number,1170  tokenId: number,1171  sender: IKeyringPair,1172  recipient: IKeyringPair,1173  value: number | bigint = 1,1174  blockSchedule: number,1175  scheduledId: string,1176) {1177  await usingApi(async (api: ApiPromise) => {1178    await scheduleTransferExpectSuccess(collectionId, tokenId, sender, recipient, value, blockSchedule, scheduledId);11791180    const recipientBalanceBefore = (await api.query.system.account(recipient.address)).data.free.toBigInt();11811182    // sleep for n + 1 blocks1183    await waitNewBlocks(blockSchedule + 1);11841185    const recipientBalanceAfter = (await api.query.system.account(recipient.address)).data.free.toBigInt();11861187    expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(recipient.address));1188    expect(recipientBalanceAfter).to.be.equal(recipientBalanceBefore);1189  });1190}11911192export async function1193scheduleTransferExpectSuccess(1194  collectionId: number,1195  tokenId: number,1196  sender: IKeyringPair,1197  recipient: IKeyringPair,1198  value: number | bigint = 1,1199  blockSchedule: number,1200  scheduledId: string,1201) {1202  await usingApi(async (api: ApiPromise) => {1203    const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient.address), collectionId, tokenId, value);12041205    await scheduleExpectSuccess(transferTx, sender, blockSchedule, scheduledId);12061207    expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(sender.address));1208  });1209}12101211export async function1212scheduleTransferFundsPeriodicExpectSuccess(1213  amount: bigint,1214  sender: IKeyringPair,1215  recipient: IKeyringPair,1216  blockSchedule: number,1217  scheduledId: string,1218  period: number,1219  repetitions: number,1220) {1221  await usingApi(async (api: ApiPromise) => {1222    const transferTx = api.tx.balances.transfer(recipient.address, amount);12231224    const balanceBefore = await getFreeBalance(recipient);1225    1226    await scheduleExpectSuccess(transferTx, sender, blockSchedule, scheduledId, period, repetitions);12271228    expect(await getFreeBalance(recipient)).to.be.equal(balanceBefore);1229  });1230}12311232export async function1233transfer(1234  api: ApiPromise,1235  collectionId: number,1236  tokenId: number,1237  sender: IKeyringPair,1238  recipient: IKeyringPair | CrossAccountId,1239  value: number | bigint,1240) : Promise<boolean> {1241  const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient), collectionId, tokenId, value);1242  const events = await executeTransaction(api, sender, transferTx);1243  return getGenericResult(events).success;1244}12451246export async function1247transferExpectSuccess(1248  collectionId: number,1249  tokenId: number,1250  sender: IKeyringPair,1251  recipient: IKeyringPair | CrossAccountId,1252  value: number | bigint = 1,1253  type = 'NFT',1254) {1255  await usingApi(async (api: ApiPromise) => {1256    const from = normalizeAccountId(sender);1257    const to = normalizeAccountId(recipient);12581259    let balanceBefore = 0n;1260    if (type === 'Fungible' || type === 'ReFungible') {1261      balanceBefore = await getBalance(api, collectionId, to, tokenId);1262    }12631264    const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient), collectionId, tokenId, value);1265    const events = await executeTransaction(api, sender, transferTx);1266    const result = getTransferResult(api, events);12671268    expect(result.collectionId).to.be.equal(collectionId);1269    expect(result.itemId).to.be.equal(tokenId);1270    expect(result.sender).to.be.deep.equal(normalizeAccountId(sender.address));1271    expect(result.recipient).to.be.deep.equal(to);1272    expect(result.value).to.be.equal(BigInt(value));12731274    if (type === 'NFT') {1275      expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(to);1276    }1277    if (type === 'Fungible' || type === 'ReFungible') {1278      const balanceAfter = await getBalance(api, collectionId, to, tokenId);1279      if (JSON.stringify(to) !== JSON.stringify(from)) {1280        expect(balanceAfter - balanceBefore).to.be.equal(BigInt(value));1281      } else {1282        expect(balanceAfter).to.be.equal(balanceBefore);1283      }1284    }1285  });1286}12871288export async function1289transferExpectFailure(1290  collectionId: number,1291  tokenId: number,1292  sender: IKeyringPair,1293  recipient: IKeyringPair | CrossAccountId,1294  value: number | bigint = 1,1295) {1296  await usingApi(async (api: ApiPromise) => {1297    const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient), collectionId, tokenId, value);1298    const events = await expect(submitTransactionExpectFailAsync(sender, transferTx)).to.be.rejected;1299    const result = getGenericResult(events);1300    // if (events && Array.isArray(events)) {1301    //   const result = getCreateCollectionResult(events);1302    // tslint:disable-next-line:no-unused-expression1303    expect(result.success).to.be.false;1304    //}1305  });1306}13071308export async function1309approveExpectFail(1310  collectionId: number,1311  tokenId: number, owner: IKeyringPair, approved: IKeyringPair, amount: number | bigint = 1,1312) {1313  await usingApi(async (api: ApiPromise) => {1314    const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved.address), collectionId, tokenId, amount);1315    const events = await expect(submitTransactionExpectFailAsync(owner, approveUniqueTx)).to.be.rejected;1316    const result = getCreateCollectionResult(events);1317    // tslint:disable-next-line:no-unused-expression1318    expect(result.success).to.be.false;1319  });1320}13211322export async function getBalance(1323  api: ApiPromise,1324  collectionId: number,1325  owner: string | CrossAccountId | IKeyringPair,1326  token: number,1327): Promise<bigint> {1328  return (await api.rpc.unique.balance(collectionId, normalizeAccountId(owner), token)).toBigInt();1329}1330export async function getTokenOwner(1331  api: ApiPromise,1332  collectionId: number,1333  token: number,1334): Promise<CrossAccountId> {1335  const owner = (await api.rpc.unique.tokenOwner(collectionId, token)).toJSON() as any;1336  if (owner == null) throw new Error('owner == null');1337  return normalizeAccountId(owner);1338}1339export async function getTopmostTokenOwner(1340  api: ApiPromise,1341  collectionId: number,1342  token: number,1343): Promise<CrossAccountId> {1344  const owner = (await api.rpc.unique.topmostTokenOwner(collectionId, token)).toJSON() as any;1345  if (owner == null) throw new Error('owner == null');1346  return normalizeAccountId(owner);1347}1348export async function getTokenChildren(1349  api: ApiPromise,1350  collectionId: number,1351  tokenId: number,1352): Promise<UpDataStructsTokenChild[]> {1353  return (await api.rpc.unique.tokenChildren(collectionId, tokenId)).toJSON() as any;1354}1355export async function isTokenExists(1356  api: ApiPromise,1357  collectionId: number,1358  token: number,1359): Promise<boolean> {1360  return (await api.rpc.unique.tokenExists(collectionId, token)).toJSON();1361}1362export async function getLastTokenId(1363  api: ApiPromise,1364  collectionId: number,1365): Promise<number> {1366  return (await api.rpc.unique.lastTokenId(collectionId)).toJSON();1367}1368export async function getAdminList(1369  api: ApiPromise,1370  collectionId: number,1371): Promise<string[]> {1372  return (await api.rpc.unique.adminlist(collectionId)).toHuman() as any;1373}1374export async function getTokenProperties(1375  api: ApiPromise,1376  collectionId: number,1377  tokenId: number,1378  propertyKeys: string[],1379): Promise<UpDataStructsProperty[]> {1380  return (await api.rpc.unique.tokenProperties(collectionId, tokenId, propertyKeys)).toHuman() as any;1381}13821383export async function createFungibleItemExpectSuccess(1384  sender: IKeyringPair,1385  collectionId: number,1386  data: CreateFungibleData,1387  owner: CrossAccountId | string = sender.address,1388) {1389  return await usingApi(async (api) => {1390    const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), {Fungible: data});13911392    const events = await submitTransactionAsync(sender, tx);1393    const result = getCreateItemResult(events);13941395    expect(result.success).to.be.true;1396    return result.itemId;1397  });1398}13991400export async function createMultipleItemsExpectSuccess(sender: IKeyringPair, collectionId: number, itemsData: any, owner: CrossAccountId | string = sender.address) {1401  await usingApi(async (api) => {1402    const to = normalizeAccountId(owner);1403    const tx = api.tx.unique.createMultipleItems(collectionId, to, itemsData);14041405    const events = await submitTransactionAsync(sender, tx);1406    expect(getGenericResult(events).success).to.be.true;1407  });1408}14091410export async function createMultipleItemsWithPropsExpectSuccess(sender: IKeyringPair, collectionId: number, itemsData: any, owner: CrossAccountId | string = sender.address) {1411  await usingApi(async (api) => {1412    const to = normalizeAccountId(owner);1413    const tx = api.tx.unique.createMultipleItems(collectionId, to, itemsData);14141415    const events = await submitTransactionAsync(sender, tx);1416    const result = getCreateItemsResult(events);14171418    for (const res of result) {1419      expect(await api.rpc.unique.tokenProperties(collectionId, res.itemId)).not.to.be.empty;1420    }1421  });1422}14231424export async function createMultipleItemsExWithPropsExpectSuccess(sender: IKeyringPair, collectionId: number, itemsData: any) {1425  await usingApi(async (api) => {1426    const tx = api.tx.unique.createMultipleItemsEx(collectionId, itemsData);14271428    const events = await submitTransactionAsync(sender, tx);1429    const result = getCreateItemsResult(events);14301431    for (const res of result) {1432      expect(await api.rpc.unique.tokenProperties(collectionId, res.itemId)).not.to.be.empty;1433    }1434  });1435}14361437export async function createItemWithPropsExpectSuccess(sender: IKeyringPair, collectionId: number, createMode: string, props:  Array<Property>, owner: CrossAccountId | string = sender.address) {1438  let newItemId = 0;1439  await usingApi(async (api) => {1440    const to = normalizeAccountId(owner);1441    const itemCountBefore = await getLastTokenId(api, collectionId);1442    const itemBalanceBefore = await getBalance(api, collectionId, to, newItemId);14431444    let tx;1445    if (createMode === 'Fungible') {1446      const createData = {fungible: {value: 10}};1447      tx = api.tx.unique.createItem(collectionId, to, createData as any);1448    } else if (createMode === 'ReFungible') {1449      const createData = {refungible: {pieces: 100}};1450      tx = api.tx.unique.createItem(collectionId, to, createData as any);1451    } else {1452      const data = api.createType('UpDataStructsCreateItemData', {NFT: {properties: props}});1453      tx = api.tx.unique.createItem(collectionId, to, data as UpDataStructsCreateItemData);1454    }14551456    const events = await submitTransactionAsync(sender, tx);1457    const result = getCreateItemResult(events);14581459    const itemCountAfter = await getLastTokenId(api, collectionId);1460    const itemBalanceAfter = await getBalance(api, collectionId, to, newItemId);14611462    if (createMode === 'NFT') {1463      expect(await api.rpc.unique.tokenProperties(collectionId, result.itemId)).not.to.be.empty;1464    }14651466    // What to expect1467    // tslint:disable-next-line:no-unused-expression1468    expect(result.success).to.be.true;1469    if (createMode === 'Fungible') {1470      expect(itemBalanceAfter - itemBalanceBefore).to.be.equal(10n);1471    } else {1472      expect(itemCountAfter).to.be.equal(itemCountBefore + 1);1473    }1474    expect(collectionId).to.be.equal(result.collectionId);1475    expect(itemCountAfter.toString()).to.be.equal(result.itemId.toString());1476    expect(to).to.be.deep.equal(result.recipient);1477    newItemId = result.itemId;1478  });1479  return newItemId;1480}14811482export async function createItemWithPropsExpectFailure(sender: IKeyringPair, collectionId: number, createMode: string, props: Array<Property>, owner: CrossAccountId | string = sender.address) {1483  await usingApi(async (api) => {14841485    let tx;1486    if (createMode === 'NFT') {1487      const data = api.createType('UpDataStructsCreateItemData', {NFT: {properties: props}}) as UpDataStructsCreateItemData;1488      tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), data);1489    } else {1490      tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), createMode);1491    }149214931494    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1495    if(events.message && events.message.toString().indexOf('1002: Verification Error') > -1) return;1496    const result = getCreateItemResult(events);14971498    expect(result.success).to.be.false;1499  });1500}15011502export async function createItemExpectSuccess(sender: IKeyringPair, collectionId: number, createMode: string, owner: CrossAccountId | string = sender.address) {1503  let newItemId = 0;1504  await usingApi(async (api) => {1505    const to = normalizeAccountId(owner);1506    const itemCountBefore = await getLastTokenId(api, collectionId);1507    const itemBalanceBefore = await getBalance(api, collectionId, to, newItemId);15081509    let tx;1510    if (createMode === 'Fungible') {1511      const createData = {fungible: {value: 10}};1512      tx = api.tx.unique.createItem(collectionId, to, createData as any);1513    } else if (createMode === 'ReFungible') {1514      const createData = {refungible: {pieces: 100}};1515      tx = api.tx.unique.createItem(collectionId, to, createData as any);1516    } else {1517      const createData = {nft: {}};1518      tx = api.tx.unique.createItem(collectionId, to, createData as any);1519    }15201521    const events = await executeTransaction(api, sender, tx);1522    const result = getCreateItemResult(events);15231524    const itemCountAfter = await getLastTokenId(api, collectionId);1525    const itemBalanceAfter = await getBalance(api, collectionId, to, newItemId);15261527    // What to expect1528    // tslint:disable-next-line:no-unused-expression1529    expect(result.success).to.be.true;1530    if (createMode === 'Fungible') {1531      expect(itemBalanceAfter - itemBalanceBefore).to.be.equal(10n);1532    } else {1533      expect(itemCountAfter).to.be.equal(itemCountBefore + 1);1534    }1535    expect(collectionId).to.be.equal(result.collectionId);1536    expect(itemCountAfter.toString()).to.be.equal(result.itemId.toString());1537    expect(to).to.be.deep.equal(result.recipient);1538    newItemId = result.itemId;1539  });1540  return newItemId;1541}15421543export async function createRefungibleToken(api: ApiPromise, sender: IKeyringPair, collectionId: number, amount: bigint, owner: CrossAccountId | IKeyringPair | string = sender.address) : Promise<CreateItemResult> {1544  const createData = {refungible: {pieces: amount}};1545  const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), createData as any);15461547  const events = await submitTransactionAsync(sender, tx);1548  return  getCreateItemResult(events);1549}15501551export async function createItemExpectFailure(sender: IKeyringPair, collectionId: number, createMode: string, owner: CrossAccountId | string = sender.address) {1552  await usingApi(async (api) => {1553    const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), createMode);15541555    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1556    const result = getCreateItemResult(events);15571558    expect(result.success).to.be.false;1559  });1560}15611562export async function setPublicAccessModeExpectSuccess(1563  sender: IKeyringPair, collectionId: number,1564  accessMode: 'Normal' | 'AllowList',1565) {1566  await usingApi(async (api) => {15671568    // Run the transaction1569    const tx = api.tx.unique.setCollectionPermissions(collectionId, {access: accessMode});1570    const events = await submitTransactionAsync(sender, tx);1571    const result = getGenericResult(events);15721573    // Get the collection1574    const collection = await queryCollectionExpectSuccess(api, collectionId);15751576    // What to expect1577    // tslint:disable-next-line:no-unused-expression1578    expect(result.success).to.be.true;1579    expect(collection.permissions.access.toHuman()).to.be.equal(accessMode);1580  });1581}15821583export async function setPublicAccessModeExpectFail(1584  sender: IKeyringPair, collectionId: number,1585  accessMode: 'Normal' | 'AllowList',1586) {1587  await usingApi(async (api) => {15881589    // Run the transaction1590    const tx = api.tx.unique.setCollectionPermissions(collectionId, {access: accessMode});1591    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1592    const result = getGenericResult(events);15931594    // What to expect1595    // tslint:disable-next-line:no-unused-expression1596    expect(result.success).to.be.false;1597  });1598}15991600export async function enableAllowListExpectSuccess(sender: IKeyringPair, collectionId: number) {1601  await setPublicAccessModeExpectSuccess(sender, collectionId, 'AllowList');1602}16031604export async function enableAllowListExpectFail(sender: IKeyringPair, collectionId: number) {1605  await setPublicAccessModeExpectFail(sender, collectionId, 'AllowList');1606}16071608export async function disableAllowListExpectSuccess(sender: IKeyringPair, collectionId: number) {1609  await setPublicAccessModeExpectSuccess(sender, collectionId, 'Normal');1610}16111612export async function setMintPermissionExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {1613  await usingApi(async (api) => {16141615    // Run the transaction1616    const tx = api.tx.unique.setCollectionPermissions(collectionId, {mintMode: enabled});1617    const events = await submitTransactionAsync(sender, tx);1618    const result = getGenericResult(events);1619    expect(result.success).to.be.true;16201621    // Get the collection1622    const collection = await queryCollectionExpectSuccess(api, collectionId);16231624    expect(collection.permissions.mintMode.toHuman()).to.be.equal(enabled);1625  });1626}16271628export async function enablePublicMintingExpectSuccess(sender: IKeyringPair, collectionId: number) {1629  await setMintPermissionExpectSuccess(sender, collectionId, true);1630}16311632export async function setMintPermissionExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {1633  await usingApi(async (api) => {1634    // Run the transaction1635    const tx = api.tx.unique.setCollectionPermissions(collectionId, {mintMode: enabled});1636    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1637    const result = getCreateCollectionResult(events);1638    // tslint:disable-next-line:no-unused-expression1639    expect(result.success).to.be.false;1640  });1641}16421643export async function setChainLimitsExpectFailure(sender: IKeyringPair, limits: IChainLimits) {1644  await usingApi(async (api) => {1645    // Run the transaction1646    const tx = api.tx.unique.setChainLimits(limits);1647    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1648    const result = getCreateCollectionResult(events);1649    // tslint:disable-next-line:no-unused-expression1650    expect(result.success).to.be.false;1651  });1652}16531654export async function isAllowlisted(api: ApiPromise, collectionId: number, address: string | CrossAccountId) {1655  return (await api.rpc.unique.allowed(collectionId, normalizeAccountId(address))).toJSON();1656}16571658export async function addToAllowListExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId | CrossAccountId) {1659  await usingApi(async (api) => {1660    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.false;16611662    // Run the transaction1663    const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1664    const events = await submitTransactionAsync(sender, tx);1665    const result = getGenericResult(events);1666    expect(result.success).to.be.true;16671668    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;1669  });1670}16711672export async function addToAllowListAgainExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId) {1673  await usingApi(async (api) => {16741675    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;16761677    // Run the transaction1678    const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1679    const events = await submitTransactionAsync(sender, tx);1680    const result = getGenericResult(events);1681    expect(result.success).to.be.true;16821683    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;1684  });1685}16861687export async function addToAllowListExpectFail(sender: IKeyringPair, collectionId: number, address: string | AccountId) {1688  await usingApi(async (api) => {16891690    // Run the transaction1691    const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1692    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1693    const result = getGenericResult(events);16941695    // What to expect1696    // tslint:disable-next-line:no-unused-expression1697    expect(result.success).to.be.false;1698  });1699}17001701export async function removeFromAllowListExpectSuccess(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1702  await usingApi(async (api) => {1703    // Run the transaction1704    const tx = api.tx.unique.removeFromAllowList(collectionId, normalizeAccountId(address));1705    const events = await submitTransactionAsync(sender, tx);1706    const result = getGenericResult(events);17071708    // What to expect1709    // tslint:disable-next-line:no-unused-expression1710    expect(result.success).to.be.true;1711  });1712}17131714export async function removeFromAllowListExpectFailure(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1715  await usingApi(async (api) => {1716    // Run the transaction1717    const tx = api.tx.unique.removeFromAllowList(collectionId, normalizeAccountId(address));1718    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1719    const result = getGenericResult(events);17201721    // What to expect1722    // tslint:disable-next-line:no-unused-expression1723    expect(result.success).to.be.false;1724  });1725}17261727export const getDetailedCollectionInfo = async (api: ApiPromise, collectionId: number)1728  : Promise<UpDataStructsRpcCollection | null> => {1729  return (await api.rpc.unique.collectionById(collectionId)).unwrapOr(null);1730};17311732export const getCreatedCollectionCount = async (api: ApiPromise): Promise<number> => {1733  // set global object - collectionsCount1734  return (await api.rpc.unique.collectionStats()).created.toNumber();1735};17361737export async function queryCollectionExpectSuccess(api: ApiPromise, collectionId: number): Promise<UpDataStructsRpcCollection> {1738  return (await api.rpc.unique.collectionById(collectionId)).unwrap();1739}17401741export async function waitNewBlocks(blocksCount = 1): Promise<void> {1742  await usingApi(async (api) => {1743    const promise = new Promise<void>(async (resolve) => {1744      const unsubscribe = await api.rpc.chain.subscribeNewHeads(() => {1745        if (blocksCount > 0) {1746          blocksCount--;1747        } else {1748          unsubscribe();1749          resolve();1750        }1751      });1752    });1753    return promise;1754  });1755}17561757export async function repartitionRFT(1758  api: ApiPromise,1759  collectionId: number,1760  sender: IKeyringPair,1761  tokenId: number,1762  amount: bigint,1763): Promise<boolean> {1764  const tx = api.tx.unique.repartition(collectionId, tokenId, amount);1765  const events = await submitTransactionAsync(sender, tx);1766  const result = getGenericResult(events);17671768  return result.success;1769}17701771export async function itApi(name: string, cb: (apis: { api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair }) => any, opts: { only?: boolean, skip?: boolean } = {}) {1772  let i: any = it;1773  if (opts.only) i = i.only;1774  else if (opts.skip) i = i.skip;1775  i(name, async () => {1776    await usingApi(async (api, privateKeyWrapper) => {1777      await cb({api, privateKeyWrapper});1778    });1779  });1780}17811782itApi.only = (name: string, cb: (apis: { api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair }) => any) => itApi(name, cb, {only: true});1783itApi.skip = (name: string, cb: (apis: { api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair }) => any) => itApi(name, cb, {skip: true});178417851786export async function expectSubstrateEventsAtBlock(api: ApiPromise, blockNumber: AnyNumber | BlockNumber, section: string, methods: string[], dryRun = false) {1787  const blockHash = await api.rpc.chain.getBlockHash(blockNumber);1788  const subEvents = (await api.query.system.events.at(blockHash))1789    .filter(x => x.event.section === section)1790    .map((x) => x.toHuman());1791  const events = methods.map((m) => {1792    return {1793      event: {1794        method: m,1795        section,1796      },1797    };1798  });1799  if (!dryRun) {1800    expect(subEvents).to.be.like(events);1801  }1802  return subEvents;1803}