git.delta.rocks / unique-network / refs/commits / 93112f6aa452

difftreelog

test(refungible-pallet) add tests for repartition events

Grigoriy Simonov2022-07-22parent: #d228734.patch.diff
in: master

3 files changed

modifiedtests/src/eth/reFungibleToken.test.tsdiffbeforeafterboth
--- a/tests/src/eth/reFungibleToken.test.ts
+++ b/tests/src/eth/reFungibleToken.test.ts
@@ -239,10 +239,69 @@
     expect(+await contract.methods.balanceOf(owner).call()).to.be.equal(0);
     expect(+await contract.methods.balanceOf(receiver).call()).to.be.equal(200);
 
-    await contract.methods.repartition(150).send({from: receiver});
+    const result = await contract.methods.repartition(150).send({from: receiver});
+    console.log(result.events);
     await expect(contract.methods.transfer(owner, 160).send({from: receiver})).to.eventually.be.rejected;
     expect(+await contract.methods.balanceOf(receiver).call()).to.be.equal(150);
   });
+
+  itWeb3('Can repartition with increased amount', async ({web3, api, privateKeyWrapper}) => {
+    const alice = privateKeyWrapper('//Alice');
+
+    const collectionId = (await createCollection(api, alice, {name: 'token name', mode: {type: 'ReFungible'}})).collectionId;
+
+    const owner = createEthAccount(web3);
+    await transferBalanceToEth(api, alice, owner);
+
+    const tokenId = (await createRefungibleToken(api, alice, collectionId, 100n, {Ethereum: owner})).itemId;
+
+    const address = tokenIdToAddress(collectionId, tokenId);
+    const contract = new web3.eth.Contract(reFungibleTokenAbi as any, address, {from: owner, ...GAS_ARGS});
+
+    const result = await contract.methods.repartition(200).send();
+    const events = normalizeEvents(result.events);
+
+    expect(events).to.include.deep.members([
+      {
+        address,
+        event: 'Transfer',
+        args: {
+          from: '0x0000000000000000000000000000000000000000',
+          to: owner,
+          value: '100',
+        },
+      },
+    ]);
+  });
+
+  itWeb3('Can repartition with decreased amount', async ({web3, api, privateKeyWrapper}) => {
+    const alice = privateKeyWrapper('//Alice');
+
+    const collectionId = (await createCollection(api, alice, {name: 'token name', mode: {type: 'ReFungible'}})).collectionId;
+
+    const owner = createEthAccount(web3);
+    await transferBalanceToEth(api, alice, owner);
+
+    const tokenId = (await createRefungibleToken(api, alice, collectionId, 100n, {Ethereum: owner})).itemId;
+
+    const address = tokenIdToAddress(collectionId, tokenId);
+    const contract = new web3.eth.Contract(reFungibleTokenAbi as any, address, {from: owner, ...GAS_ARGS});
+
+    const result = await contract.methods.repartition(50).send();
+    const events = normalizeEvents(result.events);
+
+    expect(events).to.include.deep.members([
+      {
+        address,
+        event: 'Transfer',
+        args: {
+          from: owner,
+          to: '0x0000000000000000000000000000000000000000',
+          value: '50',
+        },
+      },
+    ]);
+  });
 });
 
 describe('Refungible: Fees', () => {
modifiedtests/src/refungible.test.tsdiffbeforeafterboth
--- a/tests/src/refungible.test.ts
+++ b/tests/src/refungible.test.ts
@@ -14,7 +14,7 @@
 // You should have received a copy of the GNU General Public License
 // along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
 
-import {default as usingApi, executeTransaction} from './substrate/substrate-api';
+import {default as usingApi, submitTransactionAsync} from './substrate/substrate-api';
 import {IKeyringPair} from '@polkadot/types/types';
 import {
   createCollectionExpectSuccess,
@@ -32,6 +32,8 @@
   repartitionRFT,
   createCollectionWithPropsExpectSuccess,
   getDetailedCollectionInfo,
+  getCreateItemsResult,
+  getDestroyItemsResult,
 } from './util/helpers';
 
 import chai from 'chai';
@@ -188,6 +190,46 @@
       await expect(transfer(api, collectionId, tokenId, bob, alice, 160n)).to.eventually.be.rejected;
     });
   });
+
+  it('Repartition with increased amount', async () => {
+    await usingApi(async api => {
+      const collectionId = (await createCollection(api, alice, {mode: {type: 'ReFungible'}})).collectionId;
+      const tokenId = (await createRefungibleToken(api, alice, collectionId, 100n)).itemId;
+
+      const tx = api.tx.unique.repartition(collectionId, tokenId, 200n);
+      const events = await submitTransactionAsync(alice, tx);
+      const substrateEvents = getCreateItemsResult(events);
+      expect(substrateEvents).to.include.deep.members([
+        {
+          success: true,
+          collectionId,
+          itemId: tokenId,
+          recipient: {Substrate: alice.address},
+          amount: 100,
+        },
+      ]);
+    });
+  });
+
+  it('Repartition with decreased amount', async () => {
+    await usingApi(async api => {
+      const collectionId = (await createCollection(api, alice, {mode: {type: 'ReFungible'}})).collectionId;
+      const tokenId = (await createRefungibleToken(api, alice, collectionId, 100n)).itemId;
+
+      const tx = api.tx.unique.repartition(collectionId, tokenId, 50n);
+      const events = await submitTransactionAsync(alice, tx);
+      const substrateEvents = getDestroyItemsResult(events);
+      expect(substrateEvents).to.include.deep.members([
+        {
+          success: true,
+          collectionId,
+          itemId: tokenId,
+          owner: {Substrate: alice.address},
+          amount: 50,
+        },
+      ]);
+    });
+  });
 });
 
 describe('Test Refungible properties:', () => {
modifiedtests/src/util/helpers.tsdiffbeforeafterboth
before · tests/src/util/helpers.ts
1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617import '../interfaces/augment-api-rpc';18import '../interfaces/augment-api-query';19import {ApiPromise} from '@polkadot/api';20import type {AccountId, EventRecord, Event} from '@polkadot/types/interfaces';21import type {GenericEventData} from '@polkadot/types';22import {AnyTuple, IEvent, IKeyringPair} from '@polkadot/types/types';23import {evmToAddress} from '@polkadot/util-crypto';24import BN from 'bn.js';25import chai from 'chai';26import chaiAsPromised from 'chai-as-promised';27import {default as usingApi, executeTransaction, submitTransactionAsync, submitTransactionExpectFailAsync} from '../substrate/substrate-api';28import {hexToStr, strToUTF16, utf16ToStr} from './util';29import {UpDataStructsRpcCollection, UpDataStructsCreateItemData, UpDataStructsProperty} from '@polkadot/types/lookup';30import {UpDataStructsTokenChild} from '../interfaces';3132chai.use(chaiAsPromised);33const expect = chai.expect;3435export type CrossAccountId = {36  Substrate: string,37} | {38  Ethereum: string,39};4041export function normalizeAccountId(input: string | AccountId | CrossAccountId | IKeyringPair): CrossAccountId {42  if (typeof input === 'string') {43    if (input.length >= 47) {44      return {Substrate: input};45    } else if (input.length === 42 && input.startsWith('0x')) {46      return {Ethereum: input.toLowerCase()};47    } else if (input.length === 40 && !input.startsWith('0x')) {48      return {Ethereum: '0x' + input.toLowerCase()};49    } else {50      throw new Error(`Unknown address format: "${input}"`);51    }52  }53  if ('address' in input) {54    return {Substrate: input.address};55  }56  if ('Ethereum' in input) {57    return {58      Ethereum: input.Ethereum.toLowerCase(),59    };60  } else if ('ethereum' in input) {61    return {62      Ethereum: (input as any).ethereum.toLowerCase(),63    };64  } else if ('Substrate' in input) {65    return input;66  } else if ('substrate' in input) {67    return {68      Substrate: (input as any).substrate,69    };70  }7172  // AccountId73  return {Substrate: input.toString()};74}75export function toSubstrateAddress(input: string | CrossAccountId | IKeyringPair): string {76  input = normalizeAccountId(input);77  if ('Substrate' in input) {78    return input.Substrate;79  } else {80    return evmToAddress(input.Ethereum);81  }82}8384export const U128_MAX = (1n << 128n) - 1n;8586const MICROUNIQUE = 1_000_000_000_000n;87const MILLIUNIQUE = 1_000n * MICROUNIQUE;88const CENTIUNIQUE = 10n * MILLIUNIQUE;89export const UNIQUE = 100n * CENTIUNIQUE;9091interface GenericResult<T> {92  success: boolean;93  data: T | null;94}9596interface CreateCollectionResult {97  success: boolean;98  collectionId: number;99}100101interface CreateItemResult {102  success: boolean;103  collectionId: number;104  itemId: number;105  recipient?: CrossAccountId;106}107108interface TransferResult {109  collectionId: number;110  itemId: number;111  sender?: CrossAccountId;112  recipient?: CrossAccountId;113  value: bigint;114}115116interface IReFungibleOwner {117  fraction: BN;118  owner: number[];119}120121interface IGetMessage {122  checkMsgUnqMethod: string;123  checkMsgTrsMethod: string;124  checkMsgSysMethod: string;125}126127export interface IFungibleTokenDataType {128  value: number;129}130131export interface IChainLimits {132  collectionNumbersLimit: number;133  accountTokenOwnershipLimit: number;134  collectionsAdminsLimit: number;135  customDataLimit: number;136  nftSponsorTransferTimeout: number;137  fungibleSponsorTransferTimeout: number;138  refungibleSponsorTransferTimeout: number;139  //offchainSchemaLimit: number;140  //constOnChainSchemaLimit: number;141}142143export interface IReFungibleTokenDataType {144  owner: IReFungibleOwner[];145}146147export function uniqueEventMessage(events: EventRecord[]): IGetMessage {148  let checkMsgUnqMethod = '';149  let checkMsgTrsMethod = '';150  let checkMsgSysMethod = '';151  events.forEach(({event: {method, section}}) => {152    if (section === 'common') {153      checkMsgUnqMethod = method;154    } else if (section === 'treasury') {155      checkMsgTrsMethod = method;156    } else if (section === 'system') {157      checkMsgSysMethod = method;158    } else { return null; }159  });160  const result: IGetMessage = {161    checkMsgUnqMethod,162    checkMsgTrsMethod,163    checkMsgSysMethod,164  };165  return result;166}167168export function getEvent<T extends Event>(events: EventRecord[], check: (event: IEvent<AnyTuple>) => event is T): T | undefined {169  const event = events.find(r => check(r.event));170  if (!event) return;171  return event.event as T;172}173174export function getGenericResult<T>(events: EventRecord[]): GenericResult<T>;175export function getGenericResult<T>(176  events: EventRecord[],177  expectSection: string,178  expectMethod: string,179  extractAction: (data: GenericEventData) => T180): GenericResult<T>;181182export function getGenericResult<T>(183  events: EventRecord[],184  expectSection?: string,185  expectMethod?: string,186  extractAction?: (data: GenericEventData) => T,187): GenericResult<T> {188  let success = false;189  let successData = null;190191  events.forEach(({event: {data, method, section}}) => {192    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);193    if (method === 'ExtrinsicSuccess') {194      success = true;195    } else if ((expectSection == section) && (expectMethod == method)) {196      successData = extractAction!(data as any);197    }198  });199200  const result: GenericResult<T> = {201    success,202    data: successData,203  };204  return result;205}206207export function getCreateCollectionResult(events: EventRecord[]): CreateCollectionResult {208  const genericResult = getGenericResult(events, 'common', 'CollectionCreated', (data) => parseInt(data[0].toString(), 10));209  const result: CreateCollectionResult = {210    success: genericResult.success,211    collectionId: genericResult.data ?? 0,212  };213  return result;214}215216export function getCreateItemsResult(events: EventRecord[]): CreateItemResult[] {217  const results: CreateItemResult[] = [];218  219  const genericResult = getGenericResult<CreateItemResult[]>(events, 'common', 'ItemCreated', (data) => {220    const collectionId = parseInt(data[0].toString(), 10);221    const itemId = parseInt(data[1].toString(), 10);222    const recipient = normalizeAccountId(data[2].toJSON() as any);223224    const itemRes: CreateItemResult = {225      success: true,226      collectionId,227      itemId,228      recipient,229    };230231    results.push(itemRes);232    return results;233  });234235  if (!genericResult.success) return [];236  return results;237}238239export function getCreateItemResult(events: EventRecord[]): CreateItemResult {240  const genericResult = getGenericResult<[number, number, CrossAccountId?]>(events, 'common', 'ItemCreated', (data) => [241    parseInt(data[0].toString(), 10),242    parseInt(data[1].toString(), 10),243    normalizeAccountId(data[2].toJSON() as any),244  ]);245246  if (genericResult.data == null) genericResult.data = [0, 0];247248  const result: CreateItemResult = {249    success: genericResult.success,250    collectionId: genericResult.data[0],251    itemId: genericResult.data[1],252    recipient: genericResult.data![2],253  };254  255  return result;256}257258export function getTransferResult(api: ApiPromise, events: EventRecord[]): TransferResult {259  for (const {event} of events) {260    if (api.events.common.Transfer.is(event)) {261      const [collection, token, sender, recipient, value] = event.data;262      return {263        collectionId: collection.toNumber(),264        itemId: token.toNumber(),265        sender: normalizeAccountId(sender.toJSON() as any),266        recipient: normalizeAccountId(recipient.toJSON() as any),267        value: value.toBigInt(),268      };269    }270  }271  throw new Error('no transfer event');272}273274interface Nft {275  type: 'NFT';276}277278interface Fungible {279  type: 'Fungible';280  decimalPoints: number;281}282283interface ReFungible {284  type: 'ReFungible';285}286287export type CollectionMode = Nft | Fungible | ReFungible;288289export type Property = {290  key: any,291  value: any,292};293294type Permission = {295  mutable: boolean;296  collectionAdmin: boolean;297  tokenOwner: boolean;298}299300type PropertyPermission = {301  key: any;302  permission: Permission;303}304305export type CreateCollectionParams = {306  mode: CollectionMode,307  name: string,308  description: string,309  tokenPrefix: string,310  properties?: Array<Property>,311  propPerm?: Array<PropertyPermission>312};313314const defaultCreateCollectionParams: CreateCollectionParams = {315  description: 'description',316  mode: {type: 'NFT'},317  name: 'name',318  tokenPrefix: 'prefix',319};320321export async function322createCollection(323  api: ApiPromise,324  sender: IKeyringPair,325  params: Partial<CreateCollectionParams> = {},326): Promise<CreateCollectionResult> {327  const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};328329  let modeprm = {};330  if (mode.type === 'NFT') {331    modeprm = {nft: null};332  } else if (mode.type === 'Fungible') {333    modeprm = {fungible: mode.decimalPoints};334  } else if (mode.type === 'ReFungible') {335    modeprm = {refungible: null};336  }337338  const tx = api.tx.unique.createCollectionEx({339    name: strToUTF16(name),340    description: strToUTF16(description),341    tokenPrefix: strToUTF16(tokenPrefix),342    mode: modeprm as any,343  });344  const events = await submitTransactionAsync(sender, tx);345  return getCreateCollectionResult(events);346}347348export async function createCollectionExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {349  const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};350351  let collectionId = 0;352  await usingApi(async (api, privateKeyWrapper) => {353    // Get number of collections before the transaction354    const collectionCountBefore = await getCreatedCollectionCount(api);355356    // Run the CreateCollection transaction357    const alicePrivateKey = privateKeyWrapper('//Alice');358359    const result = await createCollection(api, alicePrivateKey, params);360361    // Get number of collections after the transaction362    const collectionCountAfter = await getCreatedCollectionCount(api);363364    // Get the collection365    const collection = await queryCollectionExpectSuccess(api, result.collectionId);366367    // What to expect368    // tslint:disable-next-line:no-unused-expression369    expect(result.success).to.be.true;370    expect(result.collectionId).to.be.equal(collectionCountAfter);371    // tslint:disable-next-line:no-unused-expression372    expect(collection).to.be.not.null;373    expect(collectionCountAfter).to.be.equal(collectionCountBefore + 1, 'Error: NFT collection NOT created.');374    expect(collection.owner.toString()).to.be.equal(toSubstrateAddress(alicePrivateKey));375    expect(utf16ToStr(collection.name.toJSON() as any)).to.be.equal(name);376    expect(utf16ToStr(collection.description.toJSON() as any)).to.be.equal(description);377    expect(hexToStr(collection.tokenPrefix.toJSON())).to.be.equal(tokenPrefix);378379    collectionId = result.collectionId;380  });381382  return collectionId;383}384385export async function createCollectionWithPropsExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {386  const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};387388  let collectionId = 0;389  await usingApi(async (api, privateKeyWrapper) => {390    // Get number of collections before the transaction391    const collectionCountBefore = await getCreatedCollectionCount(api);392393    // Run the CreateCollection transaction394    const alicePrivateKey = privateKeyWrapper('//Alice');395396    let modeprm = {};397    if (mode.type === 'NFT') {398      modeprm = {nft: null};399    } else if (mode.type === 'Fungible') {400      modeprm = {fungible: mode.decimalPoints};401    } else if (mode.type === 'ReFungible') {402      modeprm = {refungible: null};403    }404405    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});406    const events = await submitTransactionAsync(alicePrivateKey, tx);407    const result = getCreateCollectionResult(events);408409    // Get number of collections after the transaction410    const collectionCountAfter = await getCreatedCollectionCount(api);411412    // Get the collection413    const collection = await queryCollectionExpectSuccess(api, result.collectionId);414415    // What to expect416    // tslint:disable-next-line:no-unused-expression417    expect(result.success).to.be.true;418    expect(result.collectionId).to.be.equal(collectionCountAfter);419    // tslint:disable-next-line:no-unused-expression420    expect(collection).to.be.not.null;421    expect(collectionCountAfter).to.be.equal(collectionCountBefore + 1, 'Error: NFT collection NOT created.');422    expect(collection.owner.toString()).to.be.equal(toSubstrateAddress(alicePrivateKey));423    expect(utf16ToStr(collection.name.toJSON() as any)).to.be.equal(name);424    expect(utf16ToStr(collection.description.toJSON() as any)).to.be.equal(description);425    expect(hexToStr(collection.tokenPrefix.toJSON())).to.be.equal(tokenPrefix);426427428    collectionId = result.collectionId;429  });430431  return collectionId;432}433434export async function createCollectionWithPropsExpectFailure(params: Partial<CreateCollectionParams> = {}) {435  const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};436437  await usingApi(async (api, privateKeyWrapper) => {438    // Get number of collections before the transaction439    const collectionCountBefore = await getCreatedCollectionCount(api);440441    // Run the CreateCollection transaction442    const alicePrivateKey = privateKeyWrapper('//Alice');443444    let modeprm = {};445    if (mode.type === 'NFT') {446      modeprm = {nft: null};447    } else if (mode.type === 'Fungible') {448      modeprm = {fungible: mode.decimalPoints};449    } else if (mode.type === 'ReFungible') {450      modeprm = {refungible: null};451    }452453    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});454    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;455456457    // Get number of collections after the transaction458    const collectionCountAfter = await getCreatedCollectionCount(api);459460    expect(collectionCountAfter).to.be.equal(collectionCountBefore, 'Error: Collection with incorrect data created.');461  });462}463464export async function createCollectionExpectFailure(params: Partial<CreateCollectionParams> = {}) {465  const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};466467  let modeprm = {};468  if (mode.type === 'NFT') {469    modeprm = {nft: null};470  } else if (mode.type === 'Fungible') {471    modeprm = {fungible: mode.decimalPoints};472  } else if (mode.type === 'ReFungible') {473    modeprm = {refungible: null};474  }475476  await usingApi(async (api, privateKeyWrapper) => {477    // Get number of collections before the transaction478    const collectionCountBefore = await getCreatedCollectionCount(api);479480    // Run the CreateCollection transaction481    const alicePrivateKey = privateKeyWrapper('//Alice');482    const tx = api.tx.unique.createCollectionEx({name: strToUTF16(name), description: strToUTF16(description), tokenPrefix: strToUTF16(tokenPrefix), mode: modeprm as any});483    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;484485    // Get number of collections after the transaction486    const collectionCountAfter = await getCreatedCollectionCount(api);487488    // What to expect489    expect(collectionCountAfter).to.be.equal(collectionCountBefore, 'Error: Collection with incorrect data created.');490  });491}492493export async function findUnusedAddress(api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair, seedAddition = ''): Promise<IKeyringPair> {494  let bal = 0n;495  let unused;496  do {497    const randomSeed = 'seed' + Math.floor(Math.random() * Math.floor(10000)) + seedAddition;498    unused = privateKeyWrapper(`//${randomSeed}`);499    bal = (await api.query.system.account(unused.address)).data.free.toBigInt();500  } while (bal !== 0n);501  return unused;502}503504export async function getAllowance(api: ApiPromise, collectionId: number, owner: CrossAccountId | string | IKeyringPair, approved: CrossAccountId | string | IKeyringPair, tokenId: number) {505  return (await api.rpc.unique.allowance(collectionId, normalizeAccountId(owner), normalizeAccountId(approved), tokenId)).toBigInt();506}507508export function findUnusedAddresses(api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair, amount: number): Promise<IKeyringPair[]> {509  return Promise.all(new Array(amount).fill(null).map(() => findUnusedAddress(api, privateKeyWrapper, '_' + Date.now())));510}511512export async function findNotExistingCollection(api: ApiPromise): Promise<number> {513  const totalNumber = await getCreatedCollectionCount(api);514  const newCollection: number = totalNumber + 1;515  return newCollection;516}517518function getDestroyResult(events: EventRecord[]): boolean {519  let success = false;520  events.forEach(({event: {method}}) => {521    if (method == 'ExtrinsicSuccess') {522      success = true;523    }524  });525  return success;526}527528export async function destroyCollectionExpectFailure(collectionId: number, senderSeed = '//Alice') {529  await usingApi(async (api, privateKeyWrapper) => {530    // Run the DestroyCollection transaction531    const alicePrivateKey = privateKeyWrapper(senderSeed);532    const tx = api.tx.unique.destroyCollection(collectionId);533    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;534  });535}536537export async function destroyCollectionExpectSuccess(collectionId: number, senderSeed = '//Alice') {538  await usingApi(async (api, privateKeyWrapper) => {539    // Run the DestroyCollection transaction540    const alicePrivateKey = privateKeyWrapper(senderSeed);541    const tx = api.tx.unique.destroyCollection(collectionId);542    const events = await submitTransactionAsync(alicePrivateKey, tx);543    const result = getDestroyResult(events);544    expect(result).to.be.true;545546    // What to expect547    expect(await getDetailedCollectionInfo(api, collectionId)).to.be.null;548  });549}550551export async function setCollectionLimitsExpectSuccess(sender: IKeyringPair, collectionId: number, limits: any) {552  await usingApi(async (api) => {553    const tx = api.tx.unique.setCollectionLimits(collectionId, limits);554    const events = await submitTransactionAsync(sender, tx);555    const result = getGenericResult(events);556557    expect(result.success).to.be.true;558  });559}560561export const setCollectionPermissionsExpectSuccess = async (sender: IKeyringPair, collectionId: number, permissions: any) => {562  await usingApi(async(api) => {563    const tx = api.tx.unique.setCollectionPermissions(collectionId, permissions);564    const events = await submitTransactionAsync(sender, tx);565    const result = getGenericResult(events);566567    expect(result.success).to.be.true;568  });569};570571export async function setCollectionLimitsExpectFailure(sender: IKeyringPair, collectionId: number, limits: any) {572  await usingApi(async (api) => {573    const tx = api.tx.unique.setCollectionLimits(collectionId, limits);574    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;575    const result = getGenericResult(events);576577    expect(result.success).to.be.false;578  });579}580581export async function setCollectionSponsorExpectSuccess(collectionId: number, sponsor: string, sender = '//Alice') {582  await usingApi(async (api, privateKeyWrapper) => {583584    // Run the transaction585    const senderPrivateKey = privateKeyWrapper(sender);586    const tx = api.tx.unique.setCollectionSponsor(collectionId, sponsor);587    const events = await submitTransactionAsync(senderPrivateKey, tx);588    const result = getGenericResult(events);589590    // Get the collection591    const collection = await queryCollectionExpectSuccess(api, collectionId);592593    // What to expect594    expect(result.success).to.be.true;595    expect(collection.sponsorship.toJSON()).to.deep.equal({596      unconfirmed: sponsor,597    });598  });599}600601export async function removeCollectionSponsorExpectSuccess(collectionId: number, sender = '//Alice') {602  await usingApi(async (api, privateKeyWrapper) => {603604    // Run the transaction605    const alicePrivateKey = privateKeyWrapper(sender);606    const tx = api.tx.unique.removeCollectionSponsor(collectionId);607    const events = await submitTransactionAsync(alicePrivateKey, tx);608    const result = getGenericResult(events);609610    // Get the collection611    const collection = await queryCollectionExpectSuccess(api, collectionId);612613    // What to expect614    expect(result.success).to.be.true;615    expect(collection.sponsorship.toJSON()).to.be.deep.equal({disabled: null});616  });617}618619export async function removeCollectionSponsorExpectFailure(collectionId: number, senderSeed = '//Alice') {620  await usingApi(async (api, privateKeyWrapper) => {621622    // Run the transaction623    const alicePrivateKey = privateKeyWrapper(senderSeed);624    const tx = api.tx.unique.removeCollectionSponsor(collectionId);625    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;626  });627}628629export async function setCollectionSponsorExpectFailure(collectionId: number, sponsor: string, senderSeed = '//Alice') {630  await usingApi(async (api, privateKeyWrapper) => {631632    // Run the transaction633    const alicePrivateKey = privateKeyWrapper(senderSeed);634    const tx = api.tx.unique.setCollectionSponsor(collectionId, sponsor);635    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;636  });637}638639export async function confirmSponsorshipExpectSuccess(collectionId: number, senderSeed = '//Alice') {640  await usingApi(async (api, privateKeyWrapper) => {641642    // Run the transaction643    const sender = privateKeyWrapper(senderSeed);644    await confirmSponsorshipByKeyExpectSuccess(collectionId, sender);645  });646}647648export async function confirmSponsorshipByKeyExpectSuccess(collectionId: number, sender: IKeyringPair) {649  await usingApi(async (api, privateKeyWrapper) => {650651    // Run the transaction652    const tx = api.tx.unique.confirmSponsorship(collectionId);653    const events = await submitTransactionAsync(sender, tx);654    const result = getGenericResult(events);655656    // Get the collection657    const collection = await queryCollectionExpectSuccess(api, collectionId);658659    // What to expect660    expect(result.success).to.be.true;661    expect(collection.sponsorship.toJSON()).to.be.deep.equal({662      confirmed: sender.address,663    });664  });665}666667668export async function confirmSponsorshipExpectFailure(collectionId: number, senderSeed = '//Alice') {669  await usingApi(async (api, privateKeyWrapper) => {670671    // Run the transaction672    const sender = privateKeyWrapper(senderSeed);673    const tx = api.tx.unique.confirmSponsorship(collectionId);674    await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;675  });676}677678export async function enableContractSponsoringExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {679  await usingApi(async (api) => {680    const tx = api.tx.unique.enableContractSponsoring(contractAddress, enable);681    const events = await submitTransactionAsync(sender, tx);682    const result = getGenericResult(events);683684    expect(result.success).to.be.true;685  });686}687688export async function enableContractSponsoringExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {689  await usingApi(async (api) => {690    const tx = api.tx.unique.enableContractSponsoring(contractAddress, enable);691    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;692    const result = getGenericResult(events);693694    expect(result.success).to.be.false;695  });696}697698export async function setTransferFlagExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {699700  await usingApi(async (api) => {701702    const tx = api.tx.unique.setTransfersEnabledFlag(collectionId, enabled);703    const events = await submitTransactionAsync(sender, tx);704    const result = getGenericResult(events);705706    expect(result.success).to.be.true;707  });708}709710export async function setTransferFlagExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {711712  await usingApi(async (api) => {713714    const tx = api.tx.unique.setTransfersEnabledFlag(collectionId, enabled);715    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;716    const result = getGenericResult(events);717718    expect(result.success).to.be.false;719  });720}721722export async function setContractSponsoringRateLimitExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {723  await usingApi(async (api) => {724    const tx = api.tx.unique.setContractSponsoringRateLimit(contractAddress, rateLimit);725    const events = await submitTransactionAsync(sender, tx);726    const result = getGenericResult(events);727728    expect(result.success).to.be.true;729  });730}731732export async function setContractSponsoringRateLimitExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {733  await usingApi(async (api) => {734    const tx = api.tx.unique.setContractSponsoringRateLimit(contractAddress, rateLimit);735    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;736    const result = getGenericResult(events);737738    expect(result.success).to.be.false;739  });740}741742export async function getNextSponsored(743  api: ApiPromise,744  collectionId: number,745  account: string | CrossAccountId,746  tokenId: number,747): Promise<number> {748  return Number((await api.rpc.unique.nextSponsored(collectionId, account, tokenId)).unwrapOr(-1));749}750751export async function toggleContractAllowlistExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, value = true) {752  await usingApi(async (api) => {753    const tx = api.tx.unique.toggleContractAllowList(contractAddress, value);754    const events = await submitTransactionAsync(sender, tx);755    const result = getGenericResult(events);756757    expect(result.success).to.be.true;758  });759}760761export async function isAllowlistedInContract(contractAddress: AccountId | string, user: string) {762  let allowlisted = false;763  await usingApi(async (api) => {764    allowlisted = (await api.query.unique.contractAllowList(contractAddress, user)).toJSON() as boolean;765  });766  return allowlisted;767}768769export async function addToContractAllowListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {770  await usingApi(async (api) => {771    const tx = api.tx.unique.addToContractAllowList(contractAddress.toString(), user.toString());772    const events = await submitTransactionAsync(sender, tx);773    const result = getGenericResult(events);774775    expect(result.success).to.be.true;776  });777}778779export async function removeFromContractAllowListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {780  await usingApi(async (api) => {781    const tx = api.tx.unique.removeFromContractAllowList(contractAddress.toString(), user.toString());782    const events = await submitTransactionAsync(sender, tx);783    const result = getGenericResult(events);784785    expect(result.success).to.be.true;786  });787}788789export async function removeFromContractAllowListExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {790  await usingApi(async (api) => {791    const tx = api.tx.unique.removeFromContractAllowList(contractAddress.toString(), user.toString());792    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;793    const result = getGenericResult(events);794795    expect(result.success).to.be.false;796  });797}798799export interface CreateFungibleData {800  readonly Value: bigint;801}802803export interface CreateReFungibleData { }804export interface CreateNftData { }805806export type CreateItemData = {807  NFT: CreateNftData;808} | {809  Fungible: CreateFungibleData;810} | {811  ReFungible: CreateReFungibleData;812};813814export async function burnItem(api: ApiPromise, sender: IKeyringPair, collectionId: number, tokenId: number, value: number | bigint) : Promise<boolean> {815  const tx = api.tx.unique.burnItem(collectionId, tokenId, value);816  const events = await submitTransactionAsync(sender, tx);817  return getGenericResult(events).success;818}819820export async function burnItemExpectSuccess(sender: IKeyringPair, collectionId: number, tokenId: number, value: number | bigint = 1) {821  await usingApi(async (api) => {822    const balanceBefore = await getBalance(api, collectionId, normalizeAccountId(sender), tokenId);823    // if burning token by admin - use adminButnItemExpectSuccess824    expect(balanceBefore >= BigInt(value)).to.be.true;825826    expect(await burnItem(api, sender, collectionId, tokenId, value)).to.be.true;827828    const balanceAfter = await getBalance(api, collectionId, normalizeAccountId(sender), tokenId);829    expect(balanceAfter + BigInt(value)).to.be.equal(balanceBefore);830  });831}832833export async function burnItemExpectFailure(sender: IKeyringPair, collectionId: number, tokenId: number, value: number | bigint = 1) {834  await usingApi(async (api) => {835    const tx = api.tx.unique.burnItem(collectionId, tokenId, value);836837    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;838    const result = getCreateCollectionResult(events);839    // tslint:disable-next-line:no-unused-expression840    expect(result.success).to.be.false;841  });842}843844export async function burnFromExpectSuccess(sender: IKeyringPair, from: IKeyringPair | CrossAccountId, collectionId: number, tokenId: number, value: number | bigint = 1) {845  await usingApi(async (api) => {846    const tx = api.tx.unique.burnFrom(collectionId, normalizeAccountId(from), tokenId, value);847    const events = await submitTransactionAsync(sender, tx);848    return getGenericResult(events).success;849  });850}851852export async function853approve(854  api: ApiPromise,855  collectionId: number,856  tokenId: number, owner: IKeyringPair, approved: CrossAccountId | string | IKeyringPair, amount: number | bigint,857) {858  const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);859  const events = await submitTransactionAsync(owner, approveUniqueTx);860  return getGenericResult(events).success;861}862863export async function864approveExpectSuccess(865  collectionId: number,866  tokenId: number, owner: IKeyringPair, approved: CrossAccountId | string, amount: number | bigint = 1,867) {868  await usingApi(async (api: ApiPromise) => {869    const result = await approve(api, collectionId, tokenId, owner, approved, amount);870    expect(result).to.be.true;871872    expect(await getAllowance(api, collectionId, owner, approved, tokenId)).to.be.equal(BigInt(amount));873  });874}875876export async function adminApproveFromExpectSuccess(877  collectionId: number,878  tokenId: number, admin: IKeyringPair, owner: CrossAccountId | string, approved: CrossAccountId | string, amount: number | bigint = 1,879) {880  await usingApi(async (api: ApiPromise) => {881    const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);882    const events = await submitTransactionAsync(admin, approveUniqueTx);883    const result = getGenericResult(events);884    expect(result.success).to.be.true;885886    expect(await getAllowance(api, collectionId, owner, approved, tokenId)).to.be.equal(BigInt(amount));887  });888}889890export async function891transferFrom(892  api: ApiPromise,893  collectionId: number,894  tokenId: number,895  accountApproved: IKeyringPair,896  accountFrom: IKeyringPair | CrossAccountId,897  accountTo: IKeyringPair | CrossAccountId,898  value: number | bigint,899) {900  const from = normalizeAccountId(accountFrom);901  const to = normalizeAccountId(accountTo);902  const transferFromTx = api.tx.unique.transferFrom(from, to, collectionId, tokenId, value);903  const events = await submitTransactionAsync(accountApproved, transferFromTx);904  return getGenericResult(events).success;905}906907export async function908transferFromExpectSuccess(909  collectionId: number,910  tokenId: number,911  accountApproved: IKeyringPair,912  accountFrom: IKeyringPair | CrossAccountId,913  accountTo: IKeyringPair | CrossAccountId,914  value: number | bigint = 1,915  type = 'NFT',916) {917  await usingApi(async (api: ApiPromise) => {918    const from = normalizeAccountId(accountFrom);919    const to = normalizeAccountId(accountTo);920    let balanceBefore = 0n;921    if (type === 'Fungible' || type === 'ReFungible') {922      balanceBefore = await getBalance(api, collectionId, to, tokenId);923    }924    expect(await transferFrom(api, collectionId, tokenId, accountApproved, accountFrom, accountTo, value)).to.be.true;925    if (type === 'NFT') {926      expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(to);927    }928    if (type === 'Fungible') {929      const balanceAfter = await getBalance(api, collectionId, to, tokenId);930      if (JSON.stringify(to) !== JSON.stringify(from)) {931        expect(balanceAfter - balanceBefore).to.be.equal(BigInt(value));932      } else {933        expect(balanceAfter).to.be.equal(balanceBefore);934      }935    }936    if (type === 'ReFungible') {937      expect(await getBalance(api, collectionId, to, tokenId)).to.be.equal(balanceBefore + BigInt(value));938    }939  });940}941942export async function943transferFromExpectFail(944  collectionId: number,945  tokenId: number,946  accountApproved: IKeyringPair,947  accountFrom: IKeyringPair,948  accountTo: IKeyringPair,949  value: number | bigint = 1,950) {951  await usingApi(async (api: ApiPromise) => {952    const transferFromTx = api.tx.unique.transferFrom(normalizeAccountId(accountFrom.address), normalizeAccountId(accountTo.address), collectionId, tokenId, value);953    const events = await expect(submitTransactionExpectFailAsync(accountApproved, transferFromTx)).to.be.rejected;954    const result = getCreateCollectionResult(events);955    // tslint:disable-next-line:no-unused-expression956    expect(result.success).to.be.false;957  });958}959960/* eslint no-async-promise-executor: "off" */961export async function getBlockNumber(api: ApiPromise): Promise<number> {962  return new Promise<number>(async (resolve) => {963    const unsubscribe = await api.rpc.chain.subscribeNewHeads((head) => {964      unsubscribe();965      resolve(head.number.toNumber());966    });967  });968}969970export async function addCollectionAdminExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | CrossAccountId) {971  await usingApi(async (api) => {972    const changeAdminTx = api.tx.unique.addCollectionAdmin(collectionId, normalizeAccountId(address));973    const events = await submitTransactionAsync(sender, changeAdminTx);974    const result = getCreateCollectionResult(events);975    expect(result.success).to.be.true;976  });977}978979export async function adminApproveFromExpectFail(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 expect(submitTransactionAsync(admin, approveUniqueTx)).to.be.rejected;986    const result = getGenericResult(events);987    expect(result.success).to.be.false;988  });989}990991export async function992getFreeBalance(account: IKeyringPair): Promise<bigint> {993  let balance = 0n;994  await usingApi(async (api) => {995    balance = BigInt((await api.query.system.account(account.address)).data.free.toString());996  });997998  return balance;999}10001001export async function transferBalanceTo(api: ApiPromise, source: IKeyringPair, target: string, amount = 1000n * UNIQUE) {1002  const tx = api.tx.balances.transfer(target, amount);1003  const events = await submitTransactionAsync(source, tx);1004  const result = getGenericResult(events);1005  expect(result.success).to.be.true;1006}10071008export async function1009scheduleExpectSuccess(1010  operationTx: any,1011  sender: IKeyringPair,1012  blockSchedule: number,1013  scheduledId: string,1014  period = 1,1015  repetitions = 1,1016) {1017  await usingApi(async (api: ApiPromise) => {1018    const blockNumber: number | undefined = await getBlockNumber(api);1019    const expectedBlockNumber = blockNumber + blockSchedule;10201021    expect(blockNumber).to.be.greaterThan(0);1022    const scheduleTx = api.tx.scheduler.scheduleNamed( // schedule1023      scheduledId,1024      expectedBlockNumber, 1025      repetitions > 1 ? [period, repetitions] : null, 1026      0, 1027      {Value: operationTx as any},1028    );10291030    const events = await submitTransactionAsync(sender, scheduleTx);1031    expect(getGenericResult(events).success).to.be.true;1032  });1033}10341035export async function1036scheduleExpectFailure(1037  operationTx: any,1038  sender: IKeyringPair,1039  blockSchedule: number,1040  scheduledId: string,1041  period = 1,1042  repetitions = 1,1043) {1044  await usingApi(async (api: ApiPromise) => {1045    const blockNumber: number | undefined = await getBlockNumber(api);1046    const expectedBlockNumber = blockNumber + blockSchedule;10471048    expect(blockNumber).to.be.greaterThan(0);1049    const scheduleTx = api.tx.scheduler.scheduleNamed( // schedule1050      scheduledId,1051      expectedBlockNumber, 1052      repetitions <= 1 ? null : [period, repetitions], 1053      0, 1054      {Value: operationTx as any},1055    );10561057    //const events = 1058    await expect(submitTransactionExpectFailAsync(sender, scheduleTx)).to.be.rejected;1059    //expect(getGenericResult(events).success).to.be.false;1060  });1061}10621063export async function1064scheduleTransferAndWaitExpectSuccess(1065  collectionId: number,1066  tokenId: number,1067  sender: IKeyringPair,1068  recipient: IKeyringPair,1069  value: number | bigint = 1,1070  blockSchedule: number,1071  scheduledId: string,1072) {1073  await usingApi(async (api: ApiPromise) => {1074    await scheduleTransferExpectSuccess(collectionId, tokenId, sender, recipient, value, blockSchedule, scheduledId);10751076    const recipientBalanceBefore = (await api.query.system.account(recipient.address)).data.free.toBigInt();10771078    // sleep for n + 1 blocks1079    await waitNewBlocks(blockSchedule + 1);10801081    const recipientBalanceAfter = (await api.query.system.account(recipient.address)).data.free.toBigInt();10821083    expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(recipient.address));1084    expect(recipientBalanceAfter).to.be.equal(recipientBalanceBefore);1085  });1086}10871088export async function1089scheduleTransferExpectSuccess(1090  collectionId: number,1091  tokenId: number,1092  sender: IKeyringPair,1093  recipient: IKeyringPair,1094  value: number | bigint = 1,1095  blockSchedule: number,1096  scheduledId: string,1097) {1098  await usingApi(async (api: ApiPromise) => {1099    const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient.address), collectionId, tokenId, value);11001101    await scheduleExpectSuccess(transferTx, sender, blockSchedule, scheduledId);11021103    expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(sender.address));1104  });1105}11061107export async function1108scheduleTransferFundsPeriodicExpectSuccess(1109  amount: bigint,1110  sender: IKeyringPair,1111  recipient: IKeyringPair,1112  blockSchedule: number,1113  scheduledId: string,1114  period: number,1115  repetitions: number,1116) {1117  await usingApi(async (api: ApiPromise) => {1118    const transferTx = api.tx.balances.transfer(recipient.address, amount);11191120    const balanceBefore = await getFreeBalance(recipient);1121    1122    await scheduleExpectSuccess(transferTx, sender, blockSchedule, scheduledId, period, repetitions);11231124    expect(await getFreeBalance(recipient)).to.be.equal(balanceBefore);1125  });1126}11271128export async function1129transfer(1130  api: ApiPromise,1131  collectionId: number,1132  tokenId: number,1133  sender: IKeyringPair,1134  recipient: IKeyringPair | CrossAccountId,1135  value: number | bigint,1136) : Promise<boolean> {1137  const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient), collectionId, tokenId, value);1138  const events = await executeTransaction(api, sender, transferTx);1139  return getGenericResult(events).success;1140}11411142export async function1143transferExpectSuccess(1144  collectionId: number,1145  tokenId: number,1146  sender: IKeyringPair,1147  recipient: IKeyringPair | CrossAccountId,1148  value: number | bigint = 1,1149  type = 'NFT',1150) {1151  await usingApi(async (api: ApiPromise) => {1152    const from = normalizeAccountId(sender);1153    const to = normalizeAccountId(recipient);11541155    let balanceBefore = 0n;1156    if (type === 'Fungible' || type === 'ReFungible') {1157      balanceBefore = await getBalance(api, collectionId, to, tokenId);1158    }11591160    const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient), collectionId, tokenId, value);1161    const events = await executeTransaction(api, sender, transferTx);1162    const result = getTransferResult(api, events);11631164    expect(result.collectionId).to.be.equal(collectionId);1165    expect(result.itemId).to.be.equal(tokenId);1166    expect(result.sender).to.be.deep.equal(normalizeAccountId(sender.address));1167    expect(result.recipient).to.be.deep.equal(to);1168    expect(result.value).to.be.equal(BigInt(value));11691170    if (type === 'NFT') {1171      expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(to);1172    }1173    if (type === 'Fungible' || type === 'ReFungible') {1174      const balanceAfter = await getBalance(api, collectionId, to, tokenId);1175      if (JSON.stringify(to) !== JSON.stringify(from)) {1176        expect(balanceAfter - balanceBefore).to.be.equal(BigInt(value));1177      } else {1178        expect(balanceAfter).to.be.equal(balanceBefore);1179      }1180    }1181  });1182}11831184export async function1185transferExpectFailure(1186  collectionId: number,1187  tokenId: number,1188  sender: IKeyringPair,1189  recipient: IKeyringPair | CrossAccountId,1190  value: number | bigint = 1,1191) {1192  await usingApi(async (api: ApiPromise) => {1193    const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient), collectionId, tokenId, value);1194    const events = await expect(submitTransactionExpectFailAsync(sender, transferTx)).to.be.rejected;1195    const result = getGenericResult(events);1196    // if (events && Array.isArray(events)) {1197    //   const result = getCreateCollectionResult(events);1198    // tslint:disable-next-line:no-unused-expression1199    expect(result.success).to.be.false;1200    //}1201  });1202}12031204export async function1205approveExpectFail(1206  collectionId: number,1207  tokenId: number, owner: IKeyringPair, approved: IKeyringPair, amount: number | bigint = 1,1208) {1209  await usingApi(async (api: ApiPromise) => {1210    const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved.address), collectionId, tokenId, amount);1211    const events = await expect(submitTransactionExpectFailAsync(owner, approveUniqueTx)).to.be.rejected;1212    const result = getCreateCollectionResult(events);1213    // tslint:disable-next-line:no-unused-expression1214    expect(result.success).to.be.false;1215  });1216}12171218export async function getBalance(1219  api: ApiPromise,1220  collectionId: number,1221  owner: string | CrossAccountId | IKeyringPair,1222  token: number,1223): Promise<bigint> {1224  return (await api.rpc.unique.balance(collectionId, normalizeAccountId(owner), token)).toBigInt();1225}1226export async function getTokenOwner(1227  api: ApiPromise,1228  collectionId: number,1229  token: number,1230): Promise<CrossAccountId> {1231  const owner = (await api.rpc.unique.tokenOwner(collectionId, token)).toJSON() as any;1232  if (owner == null) throw new Error('owner == null');1233  return normalizeAccountId(owner);1234}1235export async function getTopmostTokenOwner(1236  api: ApiPromise,1237  collectionId: number,1238  token: number,1239): Promise<CrossAccountId> {1240  const owner = (await api.rpc.unique.topmostTokenOwner(collectionId, token)).toJSON() as any;1241  if (owner == null) throw new Error('owner == null');1242  return normalizeAccountId(owner);1243}1244export async function getTokenChildren(1245  api: ApiPromise,1246  collectionId: number,1247  tokenId: number,1248): Promise<UpDataStructsTokenChild[]> {1249  return (await api.rpc.unique.tokenChildren(collectionId, tokenId)).toJSON() as any;1250}1251export async function isTokenExists(1252  api: ApiPromise,1253  collectionId: number,1254  token: number,1255): Promise<boolean> {1256  return (await api.rpc.unique.tokenExists(collectionId, token)).toJSON();1257}1258export async function getLastTokenId(1259  api: ApiPromise,1260  collectionId: number,1261): Promise<number> {1262  return (await api.rpc.unique.lastTokenId(collectionId)).toJSON();1263}1264export async function getAdminList(1265  api: ApiPromise,1266  collectionId: number,1267): Promise<string[]> {1268  return (await api.rpc.unique.adminlist(collectionId)).toHuman() as any;1269}1270export async function getTokenProperties(1271  api: ApiPromise,1272  collectionId: number,1273  tokenId: number,1274  propertyKeys: string[],1275): Promise<UpDataStructsProperty[]> {1276  return (await api.rpc.unique.tokenProperties(collectionId, tokenId, propertyKeys)).toHuman() as any;1277}12781279export async function createFungibleItemExpectSuccess(1280  sender: IKeyringPair,1281  collectionId: number,1282  data: CreateFungibleData,1283  owner: CrossAccountId | string = sender.address,1284) {1285  return await usingApi(async (api) => {1286    const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), {Fungible: data});12871288    const events = await submitTransactionAsync(sender, tx);1289    const result = getCreateItemResult(events);12901291    expect(result.success).to.be.true;1292    return result.itemId;1293  });1294}12951296export async function createMultipleItemsExpectSuccess(sender: IKeyringPair, collectionId: number, itemsData: any, owner: CrossAccountId | string = sender.address) {1297  await usingApi(async (api) => {1298    const to = normalizeAccountId(owner);1299    const tx = api.tx.unique.createMultipleItems(collectionId, to, itemsData);13001301    const events = await submitTransactionAsync(sender, tx);1302    expect(getGenericResult(events).success).to.be.true;1303  });1304}13051306export async function createMultipleItemsWithPropsExpectSuccess(sender: IKeyringPair, collectionId: number, itemsData: any, owner: CrossAccountId | string = sender.address) {1307  await usingApi(async (api) => {1308    const to = normalizeAccountId(owner);1309    const tx = api.tx.unique.createMultipleItems(collectionId, to, itemsData);13101311    const events = await submitTransactionAsync(sender, tx);1312    const result = getCreateItemsResult(events);13131314    for (const res of result) {1315      expect(await api.rpc.unique.tokenProperties(collectionId, res.itemId)).not.to.be.empty;1316    }1317  });1318}13191320export async function createMultipleItemsExWithPropsExpectSuccess(sender: IKeyringPair, collectionId: number, itemsData: any) {1321  await usingApi(async (api) => {1322    const tx = api.tx.unique.createMultipleItemsEx(collectionId, itemsData);13231324    const events = await submitTransactionAsync(sender, tx);1325    const result = getCreateItemsResult(events);13261327    for (const res of result) {1328      expect(await api.rpc.unique.tokenProperties(collectionId, res.itemId)).not.to.be.empty;1329    }1330  });1331}13321333export async function createItemWithPropsExpectSuccess(sender: IKeyringPair, collectionId: number, createMode: string, props:  Array<Property>, owner: CrossAccountId | string = sender.address) {1334  let newItemId = 0;1335  await usingApi(async (api) => {1336    const to = normalizeAccountId(owner);1337    const itemCountBefore = await getLastTokenId(api, collectionId);1338    const itemBalanceBefore = await getBalance(api, collectionId, to, newItemId);13391340    let tx;1341    if (createMode === 'Fungible') {1342      const createData = {fungible: {value: 10}};1343      tx = api.tx.unique.createItem(collectionId, to, createData as any);1344    } else if (createMode === 'ReFungible') {1345      const createData = {refungible: {pieces: 100}};1346      tx = api.tx.unique.createItem(collectionId, to, createData as any);1347    } else {1348      const data = api.createType('UpDataStructsCreateItemData', {NFT: {properties: props}});1349      tx = api.tx.unique.createItem(collectionId, to, data as UpDataStructsCreateItemData);1350    }13511352    const events = await submitTransactionAsync(sender, tx);1353    const result = getCreateItemResult(events);13541355    const itemCountAfter = await getLastTokenId(api, collectionId);1356    const itemBalanceAfter = await getBalance(api, collectionId, to, newItemId);13571358    if (createMode === 'NFT') {1359      expect(await api.rpc.unique.tokenProperties(collectionId, result.itemId)).not.to.be.empty;1360    }13611362    // What to expect1363    // tslint:disable-next-line:no-unused-expression1364    expect(result.success).to.be.true;1365    if (createMode === 'Fungible') {1366      expect(itemBalanceAfter - itemBalanceBefore).to.be.equal(10n);1367    } else {1368      expect(itemCountAfter).to.be.equal(itemCountBefore + 1);1369    }1370    expect(collectionId).to.be.equal(result.collectionId);1371    expect(itemCountAfter.toString()).to.be.equal(result.itemId.toString());1372    expect(to).to.be.deep.equal(result.recipient);1373    newItemId = result.itemId;1374  });1375  return newItemId;1376}13771378export async function createItemWithPropsExpectFailure(sender: IKeyringPair, collectionId: number, createMode: string, props: Array<Property>, owner: CrossAccountId | string = sender.address) {1379  await usingApi(async (api) => {13801381    let tx;1382    if (createMode === 'NFT') {1383      const data = api.createType('UpDataStructsCreateItemData', {NFT: {properties: props}}) as UpDataStructsCreateItemData;1384      tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), data);1385    } else {1386      tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), createMode);1387    }138813891390    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1391    if(events.message && events.message.toString().indexOf('1002: Verification Error') > -1) return;1392    const result = getCreateItemResult(events);13931394    expect(result.success).to.be.false;1395  });1396}13971398export async function createItemExpectSuccess(sender: IKeyringPair, collectionId: number, createMode: string, owner: CrossAccountId | string = sender.address) {1399  let newItemId = 0;1400  await usingApi(async (api) => {1401    const to = normalizeAccountId(owner);1402    const itemCountBefore = await getLastTokenId(api, collectionId);1403    const itemBalanceBefore = await getBalance(api, collectionId, to, newItemId);14041405    let tx;1406    if (createMode === 'Fungible') {1407      const createData = {fungible: {value: 10}};1408      tx = api.tx.unique.createItem(collectionId, to, createData as any);1409    } else if (createMode === 'ReFungible') {1410      const createData = {refungible: {pieces: 100}};1411      tx = api.tx.unique.createItem(collectionId, to, createData as any);1412    } else {1413      const createData = {nft: {}};1414      tx = api.tx.unique.createItem(collectionId, to, createData as any);1415    }14161417    const events = await executeTransaction(api, sender, tx);1418    const result = getCreateItemResult(events);14191420    const itemCountAfter = await getLastTokenId(api, collectionId);1421    const itemBalanceAfter = await getBalance(api, collectionId, to, newItemId);14221423    // What to expect1424    // tslint:disable-next-line:no-unused-expression1425    expect(result.success).to.be.true;1426    if (createMode === 'Fungible') {1427      expect(itemBalanceAfter - itemBalanceBefore).to.be.equal(10n);1428    } else {1429      expect(itemCountAfter).to.be.equal(itemCountBefore + 1);1430    }1431    expect(collectionId).to.be.equal(result.collectionId);1432    expect(itemCountAfter.toString()).to.be.equal(result.itemId.toString());1433    expect(to).to.be.deep.equal(result.recipient);1434    newItemId = result.itemId;1435  });1436  return newItemId;1437}14381439export async function createRefungibleToken(api: ApiPromise, sender: IKeyringPair, collectionId: number, amount: bigint, owner: CrossAccountId | IKeyringPair | string = sender.address) : Promise<CreateItemResult> {1440  const createData = {refungible: {pieces: amount}};1441  const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), createData as any);14421443  const events = await submitTransactionAsync(sender, tx);1444  return  getCreateItemResult(events);1445}14461447export async function createItemExpectFailure(sender: IKeyringPair, collectionId: number, createMode: string, owner: CrossAccountId | string = sender.address) {1448  await usingApi(async (api) => {1449    const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), createMode);14501451    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1452    const result = getCreateItemResult(events);14531454    expect(result.success).to.be.false;1455  });1456}14571458export async function setPublicAccessModeExpectSuccess(1459  sender: IKeyringPair, collectionId: number,1460  accessMode: 'Normal' | 'AllowList',1461) {1462  await usingApi(async (api) => {14631464    // Run the transaction1465    const tx = api.tx.unique.setCollectionPermissions(collectionId, {access: accessMode});1466    const events = await submitTransactionAsync(sender, tx);1467    const result = getGenericResult(events);14681469    // Get the collection1470    const collection = await queryCollectionExpectSuccess(api, collectionId);14711472    // What to expect1473    // tslint:disable-next-line:no-unused-expression1474    expect(result.success).to.be.true;1475    expect(collection.permissions.access.toHuman()).to.be.equal(accessMode);1476  });1477}14781479export async function setPublicAccessModeExpectFail(1480  sender: IKeyringPair, collectionId: number,1481  accessMode: 'Normal' | 'AllowList',1482) {1483  await usingApi(async (api) => {14841485    // Run the transaction1486    const tx = api.tx.unique.setCollectionPermissions(collectionId, {access: accessMode});1487    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1488    const result = getGenericResult(events);14891490    // What to expect1491    // tslint:disable-next-line:no-unused-expression1492    expect(result.success).to.be.false;1493  });1494}14951496export async function enableAllowListExpectSuccess(sender: IKeyringPair, collectionId: number) {1497  await setPublicAccessModeExpectSuccess(sender, collectionId, 'AllowList');1498}14991500export async function enableAllowListExpectFail(sender: IKeyringPair, collectionId: number) {1501  await setPublicAccessModeExpectFail(sender, collectionId, 'AllowList');1502}15031504export async function disableAllowListExpectSuccess(sender: IKeyringPair, collectionId: number) {1505  await setPublicAccessModeExpectSuccess(sender, collectionId, 'Normal');1506}15071508export async function setMintPermissionExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {1509  await usingApi(async (api) => {15101511    // Run the transaction1512    const tx = api.tx.unique.setCollectionPermissions(collectionId, {mintMode: enabled});1513    const events = await submitTransactionAsync(sender, tx);1514    const result = getGenericResult(events);1515    expect(result.success).to.be.true;15161517    // Get the collection1518    const collection = await queryCollectionExpectSuccess(api, collectionId);15191520    expect(collection.permissions.mintMode.toHuman()).to.be.equal(enabled);1521  });1522}15231524export async function enablePublicMintingExpectSuccess(sender: IKeyringPair, collectionId: number) {1525  await setMintPermissionExpectSuccess(sender, collectionId, true);1526}15271528export async function setMintPermissionExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {1529  await usingApi(async (api) => {1530    // Run the transaction1531    const tx = api.tx.unique.setCollectionPermissions(collectionId, {mintMode: enabled});1532    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1533    const result = getCreateCollectionResult(events);1534    // tslint:disable-next-line:no-unused-expression1535    expect(result.success).to.be.false;1536  });1537}15381539export async function setChainLimitsExpectFailure(sender: IKeyringPair, limits: IChainLimits) {1540  await usingApi(async (api) => {1541    // Run the transaction1542    const tx = api.tx.unique.setChainLimits(limits);1543    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1544    const result = getCreateCollectionResult(events);1545    // tslint:disable-next-line:no-unused-expression1546    expect(result.success).to.be.false;1547  });1548}15491550export async function isAllowlisted(api: ApiPromise, collectionId: number, address: string | CrossAccountId) {1551  return (await api.rpc.unique.allowed(collectionId, normalizeAccountId(address))).toJSON();1552}15531554export async function addToAllowListExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId | CrossAccountId) {1555  await usingApi(async (api) => {1556    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.false;15571558    // Run the transaction1559    const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1560    const events = await submitTransactionAsync(sender, tx);1561    const result = getGenericResult(events);1562    expect(result.success).to.be.true;15631564    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;1565  });1566}15671568export async function addToAllowListAgainExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId) {1569  await usingApi(async (api) => {15701571    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;15721573    // Run the transaction1574    const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1575    const events = await submitTransactionAsync(sender, tx);1576    const result = getGenericResult(events);1577    expect(result.success).to.be.true;15781579    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;1580  });1581}15821583export async function addToAllowListExpectFail(sender: IKeyringPair, collectionId: number, address: string | AccountId) {1584  await usingApi(async (api) => {15851586    // Run the transaction1587    const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1588    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1589    const result = getGenericResult(events);15901591    // What to expect1592    // tslint:disable-next-line:no-unused-expression1593    expect(result.success).to.be.false;1594  });1595}15961597export async function removeFromAllowListExpectSuccess(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1598  await usingApi(async (api) => {1599    // Run the transaction1600    const tx = api.tx.unique.removeFromAllowList(collectionId, normalizeAccountId(address));1601    const events = await submitTransactionAsync(sender, tx);1602    const result = getGenericResult(events);16031604    // What to expect1605    // tslint:disable-next-line:no-unused-expression1606    expect(result.success).to.be.true;1607  });1608}16091610export async function removeFromAllowListExpectFailure(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1611  await usingApi(async (api) => {1612    // Run the transaction1613    const tx = api.tx.unique.removeFromAllowList(collectionId, normalizeAccountId(address));1614    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1615    const result = getGenericResult(events);16161617    // What to expect1618    // tslint:disable-next-line:no-unused-expression1619    expect(result.success).to.be.false;1620  });1621}16221623export const getDetailedCollectionInfo = async (api: ApiPromise, collectionId: number)1624  : Promise<UpDataStructsRpcCollection | null> => {1625  return (await api.rpc.unique.collectionById(collectionId)).unwrapOr(null);1626};16271628export const getCreatedCollectionCount = async (api: ApiPromise): Promise<number> => {1629  // set global object - collectionsCount1630  return (await api.rpc.unique.collectionStats()).created.toNumber();1631};16321633export async function queryCollectionExpectSuccess(api: ApiPromise, collectionId: number): Promise<UpDataStructsRpcCollection> {1634  return (await api.rpc.unique.collectionById(collectionId)).unwrap();1635}16361637export async function waitNewBlocks(blocksCount = 1): Promise<void> {1638  await usingApi(async (api) => {1639    const promise = new Promise<void>(async (resolve) => {1640      const unsubscribe = await api.rpc.chain.subscribeNewHeads(() => {1641        if (blocksCount > 0) {1642          blocksCount--;1643        } else {1644          unsubscribe();1645          resolve();1646        }1647      });1648    });1649    return promise;1650  });1651}16521653export async function repartitionRFT(1654  api: ApiPromise,1655  collectionId: number,1656  sender: IKeyringPair,1657  tokenId: number,1658  amount: bigint,1659): Promise<boolean> {1660  const tx = api.tx.unique.repartition(collectionId, tokenId, amount);1661  const events = await submitTransactionAsync(sender, tx);1662  const result = getGenericResult(events);16631664  return result.success;1665}
after · tests/src/util/helpers.ts
1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617import '../interfaces/augment-api-rpc';18import '../interfaces/augment-api-query';19import {ApiPromise} from '@polkadot/api';20import type {AccountId, EventRecord, Event} from '@polkadot/types/interfaces';21import type {GenericEventData} from '@polkadot/types';22import {AnyTuple, IEvent, IKeyringPair} from '@polkadot/types/types';23import {evmToAddress} from '@polkadot/util-crypto';24import BN from 'bn.js';25import chai from 'chai';26import chaiAsPromised from 'chai-as-promised';27import {default as usingApi, executeTransaction, submitTransactionAsync, submitTransactionExpectFailAsync} from '../substrate/substrate-api';28import {hexToStr, strToUTF16, utf16ToStr} from './util';29import {UpDataStructsRpcCollection, UpDataStructsCreateItemData, UpDataStructsProperty} from '@polkadot/types/lookup';30import {UpDataStructsTokenChild} from '../interfaces';3132chai.use(chaiAsPromised);33const expect = chai.expect;3435export type CrossAccountId = {36  Substrate: string,37} | {38  Ethereum: string,39};4041export function normalizeAccountId(input: string | AccountId | CrossAccountId | IKeyringPair): CrossAccountId {42  if (typeof input === 'string') {43    if (input.length >= 47) {44      return {Substrate: input};45    } else if (input.length === 42 && input.startsWith('0x')) {46      return {Ethereum: input.toLowerCase()};47    } else if (input.length === 40 && !input.startsWith('0x')) {48      return {Ethereum: '0x' + input.toLowerCase()};49    } else {50      throw new Error(`Unknown address format: "${input}"`);51    }52  }53  if ('address' in input) {54    return {Substrate: input.address};55  }56  if ('Ethereum' in input) {57    return {58      Ethereum: input.Ethereum.toLowerCase(),59    };60  } else if ('ethereum' in input) {61    return {62      Ethereum: (input as any).ethereum.toLowerCase(),63    };64  } else if ('Substrate' in input) {65    return input;66  } else if ('substrate' in input) {67    return {68      Substrate: (input as any).substrate,69    };70  }7172  // AccountId73  return {Substrate: input.toString()};74}75export function toSubstrateAddress(input: string | CrossAccountId | IKeyringPair): string {76  input = normalizeAccountId(input);77  if ('Substrate' in input) {78    return input.Substrate;79  } else {80    return evmToAddress(input.Ethereum);81  }82}8384export const U128_MAX = (1n << 128n) - 1n;8586const MICROUNIQUE = 1_000_000_000_000n;87const MILLIUNIQUE = 1_000n * MICROUNIQUE;88const CENTIUNIQUE = 10n * MILLIUNIQUE;89export const UNIQUE = 100n * CENTIUNIQUE;9091interface GenericResult<T> {92  success: boolean;93  data: T | null;94}9596interface CreateCollectionResult {97  success: boolean;98  collectionId: number;99}100101interface CreateItemResult {102  success: boolean;103  collectionId: number;104  itemId: number;105  recipient?: CrossAccountId;106  amount?: number;107}108109interface DestroyItemResult {110  success: boolean;111  collectionId: number;112  itemId: number;113  owner: CrossAccountId;114  amount: number;115}116117interface TransferResult {118  collectionId: number;119  itemId: number;120  sender?: CrossAccountId;121  recipient?: CrossAccountId;122  value: bigint;123}124125interface IReFungibleOwner {126  fraction: BN;127  owner: number[];128}129130interface IGetMessage {131  checkMsgUnqMethod: string;132  checkMsgTrsMethod: string;133  checkMsgSysMethod: string;134}135136export interface IFungibleTokenDataType {137  value: number;138}139140export interface IChainLimits {141  collectionNumbersLimit: number;142  accountTokenOwnershipLimit: number;143  collectionsAdminsLimit: number;144  customDataLimit: number;145  nftSponsorTransferTimeout: number;146  fungibleSponsorTransferTimeout: number;147  refungibleSponsorTransferTimeout: number;148  //offchainSchemaLimit: number;149  //constOnChainSchemaLimit: number;150}151152export interface IReFungibleTokenDataType {153  owner: IReFungibleOwner[];154}155156export function uniqueEventMessage(events: EventRecord[]): IGetMessage {157  let checkMsgUnqMethod = '';158  let checkMsgTrsMethod = '';159  let checkMsgSysMethod = '';160  events.forEach(({event: {method, section}}) => {161    if (section === 'common') {162      checkMsgUnqMethod = method;163    } else if (section === 'treasury') {164      checkMsgTrsMethod = method;165    } else if (section === 'system') {166      checkMsgSysMethod = method;167    } else { return null; }168  });169  const result: IGetMessage = {170    checkMsgUnqMethod,171    checkMsgTrsMethod,172    checkMsgSysMethod,173  };174  return result;175}176177export function getEvent<T extends Event>(events: EventRecord[], check: (event: IEvent<AnyTuple>) => event is T): T | undefined {178  const event = events.find(r => check(r.event));179  if (!event) return;180  return event.event as T;181}182183export function getGenericResult<T>(events: EventRecord[]): GenericResult<T>;184export function getGenericResult<T>(185  events: EventRecord[],186  expectSection: string,187  expectMethod: string,188  extractAction: (data: GenericEventData) => T189): GenericResult<T>;190191export function getGenericResult<T>(192  events: EventRecord[],193  expectSection?: string,194  expectMethod?: string,195  extractAction?: (data: GenericEventData) => T,196): GenericResult<T> {197  let success = false;198  let successData = null;199200  events.forEach(({event: {data, method, section}}) => {201    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);202    if (method === 'ExtrinsicSuccess') {203      success = true;204    } else if ((expectSection == section) && (expectMethod == method)) {205      successData = extractAction!(data as any);206    }207  });208209  const result: GenericResult<T> = {210    success,211    data: successData,212  };213  return result;214}215216export function getCreateCollectionResult(events: EventRecord[]): CreateCollectionResult {217  const genericResult = getGenericResult(events, 'common', 'CollectionCreated', (data) => parseInt(data[0].toString(), 10));218  const result: CreateCollectionResult = {219    success: genericResult.success,220    collectionId: genericResult.data ?? 0,221  };222  return result;223}224225export function getCreateItemsResult(events: EventRecord[]): CreateItemResult[] {226  const results: CreateItemResult[] = [];227  228  const genericResult = getGenericResult<CreateItemResult[]>(events, 'common', 'ItemCreated', (data) => {229    const collectionId = parseInt(data[0].toString(), 10);230    const itemId = parseInt(data[1].toString(), 10);231    const recipient = normalizeAccountId(data[2].toJSON() as any);232    const amount = parseInt(data[3].toString(), 10);233234    const itemRes: CreateItemResult = {235      success: true,236      collectionId,237      itemId,238      recipient,239      amount,240    };241242    results.push(itemRes);243    return results;244  });245246  if (!genericResult.success) return [];247  return results;248}249250export function getCreateItemResult(events: EventRecord[]): CreateItemResult {251  const genericResult = getGenericResult<[number, number, CrossAccountId?]>(events, 'common', 'ItemCreated', (data) => [252    parseInt(data[0].toString(), 10),253    parseInt(data[1].toString(), 10),254    normalizeAccountId(data[2].toJSON() as any),255  ]);256257  if (genericResult.data == null) genericResult.data = [0, 0];258259  const result: CreateItemResult = {260    success: genericResult.success,261    collectionId: genericResult.data[0],262    itemId: genericResult.data[1],263    recipient: genericResult.data![2],264  };265  266  return result;267}268269export function getDestroyItemsResult(events: EventRecord[]): DestroyItemResult[] {270  const results: DestroyItemResult[] = [];271  272  const genericResult = getGenericResult<DestroyItemResult[]>(events, 'common', 'ItemDestroyed', (data) => {273    const collectionId = parseInt(data[0].toString(), 10);274    const itemId = parseInt(data[1].toString(), 10);275    const owner = normalizeAccountId(data[2].toJSON() as any);276    const amount = parseInt(data[3].toString(), 10);277278    const itemRes: DestroyItemResult = {279      success: true,280      collectionId,281      itemId,282      owner,283      amount,284    };285286    results.push(itemRes);287    return results;288  });289290  if (!genericResult.success) return [];291  return results;292}293294export function getTransferResult(api: ApiPromise, events: EventRecord[]): TransferResult {295  for (const {event} of events) {296    if (api.events.common.Transfer.is(event)) {297      const [collection, token, sender, recipient, value] = event.data;298      return {299        collectionId: collection.toNumber(),300        itemId: token.toNumber(),301        sender: normalizeAccountId(sender.toJSON() as any),302        recipient: normalizeAccountId(recipient.toJSON() as any),303        value: value.toBigInt(),304      };305    }306  }307  throw new Error('no transfer event');308}309310interface Nft {311  type: 'NFT';312}313314interface Fungible {315  type: 'Fungible';316  decimalPoints: number;317}318319interface ReFungible {320  type: 'ReFungible';321}322323export type CollectionMode = Nft | Fungible | ReFungible;324325export type Property = {326  key: any,327  value: any,328};329330type Permission = {331  mutable: boolean;332  collectionAdmin: boolean;333  tokenOwner: boolean;334}335336type PropertyPermission = {337  key: any;338  permission: Permission;339}340341export type CreateCollectionParams = {342  mode: CollectionMode,343  name: string,344  description: string,345  tokenPrefix: string,346  properties?: Array<Property>,347  propPerm?: Array<PropertyPermission>348};349350const defaultCreateCollectionParams: CreateCollectionParams = {351  description: 'description',352  mode: {type: 'NFT'},353  name: 'name',354  tokenPrefix: 'prefix',355};356357export async function358createCollection(359  api: ApiPromise,360  sender: IKeyringPair,361  params: Partial<CreateCollectionParams> = {},362): Promise<CreateCollectionResult> {363  const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};364365  let modeprm = {};366  if (mode.type === 'NFT') {367    modeprm = {nft: null};368  } else if (mode.type === 'Fungible') {369    modeprm = {fungible: mode.decimalPoints};370  } else if (mode.type === 'ReFungible') {371    modeprm = {refungible: null};372  }373374  const tx = api.tx.unique.createCollectionEx({375    name: strToUTF16(name),376    description: strToUTF16(description),377    tokenPrefix: strToUTF16(tokenPrefix),378    mode: modeprm as any,379  });380  const events = await submitTransactionAsync(sender, tx);381  return getCreateCollectionResult(events);382}383384export async function createCollectionExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {385  const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};386387  let collectionId = 0;388  await usingApi(async (api, privateKeyWrapper) => {389    // Get number of collections before the transaction390    const collectionCountBefore = await getCreatedCollectionCount(api);391392    // Run the CreateCollection transaction393    const alicePrivateKey = privateKeyWrapper('//Alice');394395    const result = await createCollection(api, alicePrivateKey, params);396397    // Get number of collections after the transaction398    const collectionCountAfter = await getCreatedCollectionCount(api);399400    // Get the collection401    const collection = await queryCollectionExpectSuccess(api, result.collectionId);402403    // What to expect404    // tslint:disable-next-line:no-unused-expression405    expect(result.success).to.be.true;406    expect(result.collectionId).to.be.equal(collectionCountAfter);407    // tslint:disable-next-line:no-unused-expression408    expect(collection).to.be.not.null;409    expect(collectionCountAfter).to.be.equal(collectionCountBefore + 1, 'Error: NFT collection NOT created.');410    expect(collection.owner.toString()).to.be.equal(toSubstrateAddress(alicePrivateKey));411    expect(utf16ToStr(collection.name.toJSON() as any)).to.be.equal(name);412    expect(utf16ToStr(collection.description.toJSON() as any)).to.be.equal(description);413    expect(hexToStr(collection.tokenPrefix.toJSON())).to.be.equal(tokenPrefix);414415    collectionId = result.collectionId;416  });417418  return collectionId;419}420421export async function createCollectionWithPropsExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {422  const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};423424  let collectionId = 0;425  await usingApi(async (api, privateKeyWrapper) => {426    // Get number of collections before the transaction427    const collectionCountBefore = await getCreatedCollectionCount(api);428429    // Run the CreateCollection transaction430    const alicePrivateKey = privateKeyWrapper('//Alice');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({name: strToUTF16(name), description: strToUTF16(description), tokenPrefix: strToUTF16(tokenPrefix), mode: modeprm as any, properties: params.properties, tokenPropertyPermissions: params.propPerm});442    const events = await submitTransactionAsync(alicePrivateKey, tx);443    const result = getCreateCollectionResult(events);444445    // Get number of collections after the transaction446    const collectionCountAfter = await getCreatedCollectionCount(api);447448    // Get the collection449    const collection = await queryCollectionExpectSuccess(api, result.collectionId);450451    // What to expect452    // tslint:disable-next-line:no-unused-expression453    expect(result.success).to.be.true;454    expect(result.collectionId).to.be.equal(collectionCountAfter);455    // tslint:disable-next-line:no-unused-expression456    expect(collection).to.be.not.null;457    expect(collectionCountAfter).to.be.equal(collectionCountBefore + 1, 'Error: NFT collection NOT created.');458    expect(collection.owner.toString()).to.be.equal(toSubstrateAddress(alicePrivateKey));459    expect(utf16ToStr(collection.name.toJSON() as any)).to.be.equal(name);460    expect(utf16ToStr(collection.description.toJSON() as any)).to.be.equal(description);461    expect(hexToStr(collection.tokenPrefix.toJSON())).to.be.equal(tokenPrefix);462463464    collectionId = result.collectionId;465  });466467  return collectionId;468}469470export async function createCollectionWithPropsExpectFailure(params: Partial<CreateCollectionParams> = {}) {471  const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};472473  await usingApi(async (api, privateKeyWrapper) => {474    // Get number of collections before the transaction475    const collectionCountBefore = await getCreatedCollectionCount(api);476477    // Run the CreateCollection transaction478    const alicePrivateKey = privateKeyWrapper('//Alice');479480    let modeprm = {};481    if (mode.type === 'NFT') {482      modeprm = {nft: null};483    } else if (mode.type === 'Fungible') {484      modeprm = {fungible: mode.decimalPoints};485    } else if (mode.type === 'ReFungible') {486      modeprm = {refungible: null};487    }488489    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});490    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;491492493    // Get number of collections after the transaction494    const collectionCountAfter = await getCreatedCollectionCount(api);495496    expect(collectionCountAfter).to.be.equal(collectionCountBefore, 'Error: Collection with incorrect data created.');497  });498}499500export async function createCollectionExpectFailure(params: Partial<CreateCollectionParams> = {}) {501  const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};502503  let modeprm = {};504  if (mode.type === 'NFT') {505    modeprm = {nft: null};506  } else if (mode.type === 'Fungible') {507    modeprm = {fungible: mode.decimalPoints};508  } else if (mode.type === 'ReFungible') {509    modeprm = {refungible: null};510  }511512  await usingApi(async (api, privateKeyWrapper) => {513    // Get number of collections before the transaction514    const collectionCountBefore = await getCreatedCollectionCount(api);515516    // Run the CreateCollection transaction517    const alicePrivateKey = privateKeyWrapper('//Alice');518    const tx = api.tx.unique.createCollectionEx({name: strToUTF16(name), description: strToUTF16(description), tokenPrefix: strToUTF16(tokenPrefix), mode: modeprm as any});519    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;520521    // Get number of collections after the transaction522    const collectionCountAfter = await getCreatedCollectionCount(api);523524    // What to expect525    expect(collectionCountAfter).to.be.equal(collectionCountBefore, 'Error: Collection with incorrect data created.');526  });527}528529export async function findUnusedAddress(api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair, seedAddition = ''): Promise<IKeyringPair> {530  let bal = 0n;531  let unused;532  do {533    const randomSeed = 'seed' + Math.floor(Math.random() * Math.floor(10000)) + seedAddition;534    unused = privateKeyWrapper(`//${randomSeed}`);535    bal = (await api.query.system.account(unused.address)).data.free.toBigInt();536  } while (bal !== 0n);537  return unused;538}539540export async function getAllowance(api: ApiPromise, collectionId: number, owner: CrossAccountId | string | IKeyringPair, approved: CrossAccountId | string | IKeyringPair, tokenId: number) {541  return (await api.rpc.unique.allowance(collectionId, normalizeAccountId(owner), normalizeAccountId(approved), tokenId)).toBigInt();542}543544export function findUnusedAddresses(api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair, amount: number): Promise<IKeyringPair[]> {545  return Promise.all(new Array(amount).fill(null).map(() => findUnusedAddress(api, privateKeyWrapper, '_' + Date.now())));546}547548export async function findNotExistingCollection(api: ApiPromise): Promise<number> {549  const totalNumber = await getCreatedCollectionCount(api);550  const newCollection: number = totalNumber + 1;551  return newCollection;552}553554function getDestroyResult(events: EventRecord[]): boolean {555  let success = false;556  events.forEach(({event: {method}}) => {557    if (method == 'ExtrinsicSuccess') {558      success = true;559    }560  });561  return success;562}563564export async function destroyCollectionExpectFailure(collectionId: number, senderSeed = '//Alice') {565  await usingApi(async (api, privateKeyWrapper) => {566    // Run the DestroyCollection transaction567    const alicePrivateKey = privateKeyWrapper(senderSeed);568    const tx = api.tx.unique.destroyCollection(collectionId);569    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;570  });571}572573export async function destroyCollectionExpectSuccess(collectionId: number, senderSeed = '//Alice') {574  await usingApi(async (api, privateKeyWrapper) => {575    // Run the DestroyCollection transaction576    const alicePrivateKey = privateKeyWrapper(senderSeed);577    const tx = api.tx.unique.destroyCollection(collectionId);578    const events = await submitTransactionAsync(alicePrivateKey, tx);579    const result = getDestroyResult(events);580    expect(result).to.be.true;581582    // What to expect583    expect(await getDetailedCollectionInfo(api, collectionId)).to.be.null;584  });585}586587export async function setCollectionLimitsExpectSuccess(sender: IKeyringPair, collectionId: number, limits: any) {588  await usingApi(async (api) => {589    const tx = api.tx.unique.setCollectionLimits(collectionId, limits);590    const events = await submitTransactionAsync(sender, tx);591    const result = getGenericResult(events);592593    expect(result.success).to.be.true;594  });595}596597export const setCollectionPermissionsExpectSuccess = async (sender: IKeyringPair, collectionId: number, permissions: any) => {598  await usingApi(async(api) => {599    const tx = api.tx.unique.setCollectionPermissions(collectionId, permissions);600    const events = await submitTransactionAsync(sender, tx);601    const result = getGenericResult(events);602603    expect(result.success).to.be.true;604  });605};606607export async function setCollectionLimitsExpectFailure(sender: IKeyringPair, collectionId: number, limits: any) {608  await usingApi(async (api) => {609    const tx = api.tx.unique.setCollectionLimits(collectionId, limits);610    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;611    const result = getGenericResult(events);612613    expect(result.success).to.be.false;614  });615}616617export async function setCollectionSponsorExpectSuccess(collectionId: number, sponsor: string, sender = '//Alice') {618  await usingApi(async (api, privateKeyWrapper) => {619620    // Run the transaction621    const senderPrivateKey = privateKeyWrapper(sender);622    const tx = api.tx.unique.setCollectionSponsor(collectionId, sponsor);623    const events = await submitTransactionAsync(senderPrivateKey, tx);624    const result = getGenericResult(events);625626    // Get the collection627    const collection = await queryCollectionExpectSuccess(api, collectionId);628629    // What to expect630    expect(result.success).to.be.true;631    expect(collection.sponsorship.toJSON()).to.deep.equal({632      unconfirmed: sponsor,633    });634  });635}636637export async function removeCollectionSponsorExpectSuccess(collectionId: number, sender = '//Alice') {638  await usingApi(async (api, privateKeyWrapper) => {639640    // Run the transaction641    const alicePrivateKey = privateKeyWrapper(sender);642    const tx = api.tx.unique.removeCollectionSponsor(collectionId);643    const events = await submitTransactionAsync(alicePrivateKey, tx);644    const result = getGenericResult(events);645646    // Get the collection647    const collection = await queryCollectionExpectSuccess(api, collectionId);648649    // What to expect650    expect(result.success).to.be.true;651    expect(collection.sponsorship.toJSON()).to.be.deep.equal({disabled: null});652  });653}654655export async function removeCollectionSponsorExpectFailure(collectionId: number, senderSeed = '//Alice') {656  await usingApi(async (api, privateKeyWrapper) => {657658    // Run the transaction659    const alicePrivateKey = privateKeyWrapper(senderSeed);660    const tx = api.tx.unique.removeCollectionSponsor(collectionId);661    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;662  });663}664665export async function setCollectionSponsorExpectFailure(collectionId: number, sponsor: string, senderSeed = '//Alice') {666  await usingApi(async (api, privateKeyWrapper) => {667668    // Run the transaction669    const alicePrivateKey = privateKeyWrapper(senderSeed);670    const tx = api.tx.unique.setCollectionSponsor(collectionId, sponsor);671    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;672  });673}674675export async function confirmSponsorshipExpectSuccess(collectionId: number, senderSeed = '//Alice') {676  await usingApi(async (api, privateKeyWrapper) => {677678    // Run the transaction679    const sender = privateKeyWrapper(senderSeed);680    await confirmSponsorshipByKeyExpectSuccess(collectionId, sender);681  });682}683684export async function confirmSponsorshipByKeyExpectSuccess(collectionId: number, sender: IKeyringPair) {685  await usingApi(async (api, privateKeyWrapper) => {686687    // Run the transaction688    const tx = api.tx.unique.confirmSponsorship(collectionId);689    const events = await submitTransactionAsync(sender, tx);690    const result = getGenericResult(events);691692    // Get the collection693    const collection = await queryCollectionExpectSuccess(api, collectionId);694695    // What to expect696    expect(result.success).to.be.true;697    expect(collection.sponsorship.toJSON()).to.be.deep.equal({698      confirmed: sender.address,699    });700  });701}702703704export async function confirmSponsorshipExpectFailure(collectionId: number, senderSeed = '//Alice') {705  await usingApi(async (api, privateKeyWrapper) => {706707    // Run the transaction708    const sender = privateKeyWrapper(senderSeed);709    const tx = api.tx.unique.confirmSponsorship(collectionId);710    await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;711  });712}713714export async function enableContractSponsoringExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {715  await usingApi(async (api) => {716    const tx = api.tx.unique.enableContractSponsoring(contractAddress, enable);717    const events = await submitTransactionAsync(sender, tx);718    const result = getGenericResult(events);719720    expect(result.success).to.be.true;721  });722}723724export async function enableContractSponsoringExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {725  await usingApi(async (api) => {726    const tx = api.tx.unique.enableContractSponsoring(contractAddress, enable);727    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;728    const result = getGenericResult(events);729730    expect(result.success).to.be.false;731  });732}733734export async function setTransferFlagExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {735736  await usingApi(async (api) => {737738    const tx = api.tx.unique.setTransfersEnabledFlag(collectionId, enabled);739    const events = await submitTransactionAsync(sender, tx);740    const result = getGenericResult(events);741742    expect(result.success).to.be.true;743  });744}745746export async function setTransferFlagExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {747748  await usingApi(async (api) => {749750    const tx = api.tx.unique.setTransfersEnabledFlag(collectionId, enabled);751    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;752    const result = getGenericResult(events);753754    expect(result.success).to.be.false;755  });756}757758export async function setContractSponsoringRateLimitExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {759  await usingApi(async (api) => {760    const tx = api.tx.unique.setContractSponsoringRateLimit(contractAddress, rateLimit);761    const events = await submitTransactionAsync(sender, tx);762    const result = getGenericResult(events);763764    expect(result.success).to.be.true;765  });766}767768export async function setContractSponsoringRateLimitExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {769  await usingApi(async (api) => {770    const tx = api.tx.unique.setContractSponsoringRateLimit(contractAddress, rateLimit);771    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;772    const result = getGenericResult(events);773774    expect(result.success).to.be.false;775  });776}777778export async function getNextSponsored(779  api: ApiPromise,780  collectionId: number,781  account: string | CrossAccountId,782  tokenId: number,783): Promise<number> {784  return Number((await api.rpc.unique.nextSponsored(collectionId, account, tokenId)).unwrapOr(-1));785}786787export async function toggleContractAllowlistExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, value = true) {788  await usingApi(async (api) => {789    const tx = api.tx.unique.toggleContractAllowList(contractAddress, value);790    const events = await submitTransactionAsync(sender, tx);791    const result = getGenericResult(events);792793    expect(result.success).to.be.true;794  });795}796797export async function isAllowlistedInContract(contractAddress: AccountId | string, user: string) {798  let allowlisted = false;799  await usingApi(async (api) => {800    allowlisted = (await api.query.unique.contractAllowList(contractAddress, user)).toJSON() as boolean;801  });802  return allowlisted;803}804805export async function addToContractAllowListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {806  await usingApi(async (api) => {807    const tx = api.tx.unique.addToContractAllowList(contractAddress.toString(), user.toString());808    const events = await submitTransactionAsync(sender, tx);809    const result = getGenericResult(events);810811    expect(result.success).to.be.true;812  });813}814815export async function removeFromContractAllowListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {816  await usingApi(async (api) => {817    const tx = api.tx.unique.removeFromContractAllowList(contractAddress.toString(), user.toString());818    const events = await submitTransactionAsync(sender, tx);819    const result = getGenericResult(events);820821    expect(result.success).to.be.true;822  });823}824825export async function removeFromContractAllowListExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {826  await usingApi(async (api) => {827    const tx = api.tx.unique.removeFromContractAllowList(contractAddress.toString(), user.toString());828    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;829    const result = getGenericResult(events);830831    expect(result.success).to.be.false;832  });833}834835export interface CreateFungibleData {836  readonly Value: bigint;837}838839export interface CreateReFungibleData { }840export interface CreateNftData { }841842export type CreateItemData = {843  NFT: CreateNftData;844} | {845  Fungible: CreateFungibleData;846} | {847  ReFungible: CreateReFungibleData;848};849850export async function burnItem(api: ApiPromise, sender: IKeyringPair, collectionId: number, tokenId: number, value: number | bigint) : Promise<boolean> {851  const tx = api.tx.unique.burnItem(collectionId, tokenId, value);852  const events = await submitTransactionAsync(sender, tx);853  return getGenericResult(events).success;854}855856export async function burnItemExpectSuccess(sender: IKeyringPair, collectionId: number, tokenId: number, value: number | bigint = 1) {857  await usingApi(async (api) => {858    const balanceBefore = await getBalance(api, collectionId, normalizeAccountId(sender), tokenId);859    // if burning token by admin - use adminButnItemExpectSuccess860    expect(balanceBefore >= BigInt(value)).to.be.true;861862    expect(await burnItem(api, sender, collectionId, tokenId, value)).to.be.true;863864    const balanceAfter = await getBalance(api, collectionId, normalizeAccountId(sender), tokenId);865    expect(balanceAfter + BigInt(value)).to.be.equal(balanceBefore);866  });867}868869export async function burnItemExpectFailure(sender: IKeyringPair, collectionId: number, tokenId: number, value: number | bigint = 1) {870  await usingApi(async (api) => {871    const tx = api.tx.unique.burnItem(collectionId, tokenId, value);872873    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;874    const result = getCreateCollectionResult(events);875    // tslint:disable-next-line:no-unused-expression876    expect(result.success).to.be.false;877  });878}879880export async function burnFromExpectSuccess(sender: IKeyringPair, from: IKeyringPair | CrossAccountId, collectionId: number, tokenId: number, value: number | bigint = 1) {881  await usingApi(async (api) => {882    const tx = api.tx.unique.burnFrom(collectionId, normalizeAccountId(from), tokenId, value);883    const events = await submitTransactionAsync(sender, tx);884    return getGenericResult(events).success;885  });886}887888export async function889approve(890  api: ApiPromise,891  collectionId: number,892  tokenId: number, owner: IKeyringPair, approved: CrossAccountId | string | IKeyringPair, amount: number | bigint,893) {894  const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);895  const events = await submitTransactionAsync(owner, approveUniqueTx);896  return getGenericResult(events).success;897}898899export async function900approveExpectSuccess(901  collectionId: number,902  tokenId: number, owner: IKeyringPair, approved: CrossAccountId | string, amount: number | bigint = 1,903) {904  await usingApi(async (api: ApiPromise) => {905    const result = await approve(api, collectionId, tokenId, owner, approved, amount);906    expect(result).to.be.true;907908    expect(await getAllowance(api, collectionId, owner, approved, tokenId)).to.be.equal(BigInt(amount));909  });910}911912export async function adminApproveFromExpectSuccess(913  collectionId: number,914  tokenId: number, admin: IKeyringPair, owner: CrossAccountId | string, approved: CrossAccountId | string, amount: number | bigint = 1,915) {916  await usingApi(async (api: ApiPromise) => {917    const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);918    const events = await submitTransactionAsync(admin, approveUniqueTx);919    const result = getGenericResult(events);920    expect(result.success).to.be.true;921922    expect(await getAllowance(api, collectionId, owner, approved, tokenId)).to.be.equal(BigInt(amount));923  });924}925926export async function927transferFrom(928  api: ApiPromise,929  collectionId: number,930  tokenId: number,931  accountApproved: IKeyringPair,932  accountFrom: IKeyringPair | CrossAccountId,933  accountTo: IKeyringPair | CrossAccountId,934  value: number | bigint,935) {936  const from = normalizeAccountId(accountFrom);937  const to = normalizeAccountId(accountTo);938  const transferFromTx = api.tx.unique.transferFrom(from, to, collectionId, tokenId, value);939  const events = await submitTransactionAsync(accountApproved, transferFromTx);940  return getGenericResult(events).success;941}942943export async function944transferFromExpectSuccess(945  collectionId: number,946  tokenId: number,947  accountApproved: IKeyringPair,948  accountFrom: IKeyringPair | CrossAccountId,949  accountTo: IKeyringPair | CrossAccountId,950  value: number | bigint = 1,951  type = 'NFT',952) {953  await usingApi(async (api: ApiPromise) => {954    const from = normalizeAccountId(accountFrom);955    const to = normalizeAccountId(accountTo);956    let balanceBefore = 0n;957    if (type === 'Fungible' || type === 'ReFungible') {958      balanceBefore = await getBalance(api, collectionId, to, tokenId);959    }960    expect(await transferFrom(api, collectionId, tokenId, accountApproved, accountFrom, accountTo, value)).to.be.true;961    if (type === 'NFT') {962      expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(to);963    }964    if (type === 'Fungible') {965      const balanceAfter = await getBalance(api, collectionId, to, tokenId);966      if (JSON.stringify(to) !== JSON.stringify(from)) {967        expect(balanceAfter - balanceBefore).to.be.equal(BigInt(value));968      } else {969        expect(balanceAfter).to.be.equal(balanceBefore);970      }971    }972    if (type === 'ReFungible') {973      expect(await getBalance(api, collectionId, to, tokenId)).to.be.equal(balanceBefore + BigInt(value));974    }975  });976}977978export async function979transferFromExpectFail(980  collectionId: number,981  tokenId: number,982  accountApproved: IKeyringPair,983  accountFrom: IKeyringPair,984  accountTo: IKeyringPair,985  value: number | bigint = 1,986) {987  await usingApi(async (api: ApiPromise) => {988    const transferFromTx = api.tx.unique.transferFrom(normalizeAccountId(accountFrom.address), normalizeAccountId(accountTo.address), collectionId, tokenId, value);989    const events = await expect(submitTransactionExpectFailAsync(accountApproved, transferFromTx)).to.be.rejected;990    const result = getCreateCollectionResult(events);991    // tslint:disable-next-line:no-unused-expression992    expect(result.success).to.be.false;993  });994}995996/* eslint no-async-promise-executor: "off" */997export async function getBlockNumber(api: ApiPromise): Promise<number> {998  return new Promise<number>(async (resolve) => {999    const unsubscribe = await api.rpc.chain.subscribeNewHeads((head) => {1000      unsubscribe();1001      resolve(head.number.toNumber());1002    });1003  });1004}10051006export async function addCollectionAdminExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | CrossAccountId) {1007  await usingApi(async (api) => {1008    const changeAdminTx = api.tx.unique.addCollectionAdmin(collectionId, normalizeAccountId(address));1009    const events = await submitTransactionAsync(sender, changeAdminTx);1010    const result = getCreateCollectionResult(events);1011    expect(result.success).to.be.true;1012  });1013}10141015export async function adminApproveFromExpectFail(1016  collectionId: number,1017  tokenId: number, admin: IKeyringPair, owner: CrossAccountId | string, approved: CrossAccountId | string, amount: number | bigint = 1,1018) {1019  await usingApi(async (api: ApiPromise) => {1020    const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);1021    const events = await expect(submitTransactionAsync(admin, approveUniqueTx)).to.be.rejected;1022    const result = getGenericResult(events);1023    expect(result.success).to.be.false;1024  });1025}10261027export async function1028getFreeBalance(account: IKeyringPair): Promise<bigint> {1029  let balance = 0n;1030  await usingApi(async (api) => {1031    balance = BigInt((await api.query.system.account(account.address)).data.free.toString());1032  });10331034  return balance;1035}10361037export async function transferBalanceTo(api: ApiPromise, source: IKeyringPair, target: string, amount = 1000n * UNIQUE) {1038  const tx = api.tx.balances.transfer(target, amount);1039  const events = await submitTransactionAsync(source, tx);1040  const result = getGenericResult(events);1041  expect(result.success).to.be.true;1042}10431044export async function1045scheduleExpectSuccess(1046  operationTx: any,1047  sender: IKeyringPair,1048  blockSchedule: number,1049  scheduledId: string,1050  period = 1,1051  repetitions = 1,1052) {1053  await usingApi(async (api: ApiPromise) => {1054    const blockNumber: number | undefined = await getBlockNumber(api);1055    const expectedBlockNumber = blockNumber + blockSchedule;10561057    expect(blockNumber).to.be.greaterThan(0);1058    const scheduleTx = api.tx.scheduler.scheduleNamed( // schedule1059      scheduledId,1060      expectedBlockNumber, 1061      repetitions > 1 ? [period, repetitions] : null, 1062      0, 1063      {Value: operationTx as any},1064    );10651066    const events = await submitTransactionAsync(sender, scheduleTx);1067    expect(getGenericResult(events).success).to.be.true;1068  });1069}10701071export async function1072scheduleExpectFailure(1073  operationTx: any,1074  sender: IKeyringPair,1075  blockSchedule: number,1076  scheduledId: string,1077  period = 1,1078  repetitions = 1,1079) {1080  await usingApi(async (api: ApiPromise) => {1081    const blockNumber: number | undefined = await getBlockNumber(api);1082    const expectedBlockNumber = blockNumber + blockSchedule;10831084    expect(blockNumber).to.be.greaterThan(0);1085    const scheduleTx = api.tx.scheduler.scheduleNamed( // schedule1086      scheduledId,1087      expectedBlockNumber, 1088      repetitions <= 1 ? null : [period, repetitions], 1089      0, 1090      {Value: operationTx as any},1091    );10921093    //const events = 1094    await expect(submitTransactionExpectFailAsync(sender, scheduleTx)).to.be.rejected;1095    //expect(getGenericResult(events).success).to.be.false;1096  });1097}10981099export async function1100scheduleTransferAndWaitExpectSuccess(1101  collectionId: number,1102  tokenId: number,1103  sender: IKeyringPair,1104  recipient: IKeyringPair,1105  value: number | bigint = 1,1106  blockSchedule: number,1107  scheduledId: string,1108) {1109  await usingApi(async (api: ApiPromise) => {1110    await scheduleTransferExpectSuccess(collectionId, tokenId, sender, recipient, value, blockSchedule, scheduledId);11111112    const recipientBalanceBefore = (await api.query.system.account(recipient.address)).data.free.toBigInt();11131114    // sleep for n + 1 blocks1115    await waitNewBlocks(blockSchedule + 1);11161117    const recipientBalanceAfter = (await api.query.system.account(recipient.address)).data.free.toBigInt();11181119    expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(recipient.address));1120    expect(recipientBalanceAfter).to.be.equal(recipientBalanceBefore);1121  });1122}11231124export async function1125scheduleTransferExpectSuccess(1126  collectionId: number,1127  tokenId: number,1128  sender: IKeyringPair,1129  recipient: IKeyringPair,1130  value: number | bigint = 1,1131  blockSchedule: number,1132  scheduledId: string,1133) {1134  await usingApi(async (api: ApiPromise) => {1135    const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient.address), collectionId, tokenId, value);11361137    await scheduleExpectSuccess(transferTx, sender, blockSchedule, scheduledId);11381139    expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(sender.address));1140  });1141}11421143export async function1144scheduleTransferFundsPeriodicExpectSuccess(1145  amount: bigint,1146  sender: IKeyringPair,1147  recipient: IKeyringPair,1148  blockSchedule: number,1149  scheduledId: string,1150  period: number,1151  repetitions: number,1152) {1153  await usingApi(async (api: ApiPromise) => {1154    const transferTx = api.tx.balances.transfer(recipient.address, amount);11551156    const balanceBefore = await getFreeBalance(recipient);1157    1158    await scheduleExpectSuccess(transferTx, sender, blockSchedule, scheduledId, period, repetitions);11591160    expect(await getFreeBalance(recipient)).to.be.equal(balanceBefore);1161  });1162}11631164export async function1165transfer(1166  api: ApiPromise,1167  collectionId: number,1168  tokenId: number,1169  sender: IKeyringPair,1170  recipient: IKeyringPair | CrossAccountId,1171  value: number | bigint,1172) : Promise<boolean> {1173  const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient), collectionId, tokenId, value);1174  const events = await executeTransaction(api, sender, transferTx);1175  return getGenericResult(events).success;1176}11771178export async function1179transferExpectSuccess(1180  collectionId: number,1181  tokenId: number,1182  sender: IKeyringPair,1183  recipient: IKeyringPair | CrossAccountId,1184  value: number | bigint = 1,1185  type = 'NFT',1186) {1187  await usingApi(async (api: ApiPromise) => {1188    const from = normalizeAccountId(sender);1189    const to = normalizeAccountId(recipient);11901191    let balanceBefore = 0n;1192    if (type === 'Fungible' || type === 'ReFungible') {1193      balanceBefore = await getBalance(api, collectionId, to, tokenId);1194    }11951196    const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient), collectionId, tokenId, value);1197    const events = await executeTransaction(api, sender, transferTx);1198    const result = getTransferResult(api, events);11991200    expect(result.collectionId).to.be.equal(collectionId);1201    expect(result.itemId).to.be.equal(tokenId);1202    expect(result.sender).to.be.deep.equal(normalizeAccountId(sender.address));1203    expect(result.recipient).to.be.deep.equal(to);1204    expect(result.value).to.be.equal(BigInt(value));12051206    if (type === 'NFT') {1207      expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(to);1208    }1209    if (type === 'Fungible' || type === 'ReFungible') {1210      const balanceAfter = await getBalance(api, collectionId, to, tokenId);1211      if (JSON.stringify(to) !== JSON.stringify(from)) {1212        expect(balanceAfter - balanceBefore).to.be.equal(BigInt(value));1213      } else {1214        expect(balanceAfter).to.be.equal(balanceBefore);1215      }1216    }1217  });1218}12191220export async function1221transferExpectFailure(1222  collectionId: number,1223  tokenId: number,1224  sender: IKeyringPair,1225  recipient: IKeyringPair | CrossAccountId,1226  value: number | bigint = 1,1227) {1228  await usingApi(async (api: ApiPromise) => {1229    const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient), collectionId, tokenId, value);1230    const events = await expect(submitTransactionExpectFailAsync(sender, transferTx)).to.be.rejected;1231    const result = getGenericResult(events);1232    // if (events && Array.isArray(events)) {1233    //   const result = getCreateCollectionResult(events);1234    // tslint:disable-next-line:no-unused-expression1235    expect(result.success).to.be.false;1236    //}1237  });1238}12391240export async function1241approveExpectFail(1242  collectionId: number,1243  tokenId: number, owner: IKeyringPair, approved: IKeyringPair, amount: number | bigint = 1,1244) {1245  await usingApi(async (api: ApiPromise) => {1246    const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved.address), collectionId, tokenId, amount);1247    const events = await expect(submitTransactionExpectFailAsync(owner, approveUniqueTx)).to.be.rejected;1248    const result = getCreateCollectionResult(events);1249    // tslint:disable-next-line:no-unused-expression1250    expect(result.success).to.be.false;1251  });1252}12531254export async function getBalance(1255  api: ApiPromise,1256  collectionId: number,1257  owner: string | CrossAccountId | IKeyringPair,1258  token: number,1259): Promise<bigint> {1260  return (await api.rpc.unique.balance(collectionId, normalizeAccountId(owner), token)).toBigInt();1261}1262export async function getTokenOwner(1263  api: ApiPromise,1264  collectionId: number,1265  token: number,1266): Promise<CrossAccountId> {1267  const owner = (await api.rpc.unique.tokenOwner(collectionId, token)).toJSON() as any;1268  if (owner == null) throw new Error('owner == null');1269  return normalizeAccountId(owner);1270}1271export async function getTopmostTokenOwner(1272  api: ApiPromise,1273  collectionId: number,1274  token: number,1275): Promise<CrossAccountId> {1276  const owner = (await api.rpc.unique.topmostTokenOwner(collectionId, token)).toJSON() as any;1277  if (owner == null) throw new Error('owner == null');1278  return normalizeAccountId(owner);1279}1280export async function getTokenChildren(1281  api: ApiPromise,1282  collectionId: number,1283  tokenId: number,1284): Promise<UpDataStructsTokenChild[]> {1285  return (await api.rpc.unique.tokenChildren(collectionId, tokenId)).toJSON() as any;1286}1287export async function isTokenExists(1288  api: ApiPromise,1289  collectionId: number,1290  token: number,1291): Promise<boolean> {1292  return (await api.rpc.unique.tokenExists(collectionId, token)).toJSON();1293}1294export async function getLastTokenId(1295  api: ApiPromise,1296  collectionId: number,1297): Promise<number> {1298  return (await api.rpc.unique.lastTokenId(collectionId)).toJSON();1299}1300export async function getAdminList(1301  api: ApiPromise,1302  collectionId: number,1303): Promise<string[]> {1304  return (await api.rpc.unique.adminlist(collectionId)).toHuman() as any;1305}1306export async function getTokenProperties(1307  api: ApiPromise,1308  collectionId: number,1309  tokenId: number,1310  propertyKeys: string[],1311): Promise<UpDataStructsProperty[]> {1312  return (await api.rpc.unique.tokenProperties(collectionId, tokenId, propertyKeys)).toHuman() as any;1313}13141315export async function createFungibleItemExpectSuccess(1316  sender: IKeyringPair,1317  collectionId: number,1318  data: CreateFungibleData,1319  owner: CrossAccountId | string = sender.address,1320) {1321  return await usingApi(async (api) => {1322    const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), {Fungible: data});13231324    const events = await submitTransactionAsync(sender, tx);1325    const result = getCreateItemResult(events);13261327    expect(result.success).to.be.true;1328    return result.itemId;1329  });1330}13311332export async function createMultipleItemsExpectSuccess(sender: IKeyringPair, collectionId: number, itemsData: any, owner: CrossAccountId | string = sender.address) {1333  await usingApi(async (api) => {1334    const to = normalizeAccountId(owner);1335    const tx = api.tx.unique.createMultipleItems(collectionId, to, itemsData);13361337    const events = await submitTransactionAsync(sender, tx);1338    expect(getGenericResult(events).success).to.be.true;1339  });1340}13411342export async function createMultipleItemsWithPropsExpectSuccess(sender: IKeyringPair, collectionId: number, itemsData: any, owner: CrossAccountId | string = sender.address) {1343  await usingApi(async (api) => {1344    const to = normalizeAccountId(owner);1345    const tx = api.tx.unique.createMultipleItems(collectionId, to, itemsData);13461347    const events = await submitTransactionAsync(sender, tx);1348    const result = getCreateItemsResult(events);13491350    for (const res of result) {1351      expect(await api.rpc.unique.tokenProperties(collectionId, res.itemId)).not.to.be.empty;1352    }1353  });1354}13551356export async function createMultipleItemsExWithPropsExpectSuccess(sender: IKeyringPair, collectionId: number, itemsData: any) {1357  await usingApi(async (api) => {1358    const tx = api.tx.unique.createMultipleItemsEx(collectionId, itemsData);13591360    const events = await submitTransactionAsync(sender, tx);1361    const result = getCreateItemsResult(events);13621363    for (const res of result) {1364      expect(await api.rpc.unique.tokenProperties(collectionId, res.itemId)).not.to.be.empty;1365    }1366  });1367}13681369export async function createItemWithPropsExpectSuccess(sender: IKeyringPair, collectionId: number, createMode: string, props:  Array<Property>, owner: CrossAccountId | string = sender.address) {1370  let newItemId = 0;1371  await usingApi(async (api) => {1372    const to = normalizeAccountId(owner);1373    const itemCountBefore = await getLastTokenId(api, collectionId);1374    const itemBalanceBefore = await getBalance(api, collectionId, to, newItemId);13751376    let tx;1377    if (createMode === 'Fungible') {1378      const createData = {fungible: {value: 10}};1379      tx = api.tx.unique.createItem(collectionId, to, createData as any);1380    } else if (createMode === 'ReFungible') {1381      const createData = {refungible: {pieces: 100}};1382      tx = api.tx.unique.createItem(collectionId, to, createData as any);1383    } else {1384      const data = api.createType('UpDataStructsCreateItemData', {NFT: {properties: props}});1385      tx = api.tx.unique.createItem(collectionId, to, data as UpDataStructsCreateItemData);1386    }13871388    const events = await submitTransactionAsync(sender, tx);1389    const result = getCreateItemResult(events);13901391    const itemCountAfter = await getLastTokenId(api, collectionId);1392    const itemBalanceAfter = await getBalance(api, collectionId, to, newItemId);13931394    if (createMode === 'NFT') {1395      expect(await api.rpc.unique.tokenProperties(collectionId, result.itemId)).not.to.be.empty;1396    }13971398    // What to expect1399    // tslint:disable-next-line:no-unused-expression1400    expect(result.success).to.be.true;1401    if (createMode === 'Fungible') {1402      expect(itemBalanceAfter - itemBalanceBefore).to.be.equal(10n);1403    } else {1404      expect(itemCountAfter).to.be.equal(itemCountBefore + 1);1405    }1406    expect(collectionId).to.be.equal(result.collectionId);1407    expect(itemCountAfter.toString()).to.be.equal(result.itemId.toString());1408    expect(to).to.be.deep.equal(result.recipient);1409    newItemId = result.itemId;1410  });1411  return newItemId;1412}14131414export async function createItemWithPropsExpectFailure(sender: IKeyringPair, collectionId: number, createMode: string, props: Array<Property>, owner: CrossAccountId | string = sender.address) {1415  await usingApi(async (api) => {14161417    let tx;1418    if (createMode === 'NFT') {1419      const data = api.createType('UpDataStructsCreateItemData', {NFT: {properties: props}}) as UpDataStructsCreateItemData;1420      tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), data);1421    } else {1422      tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), createMode);1423    }142414251426    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1427    if(events.message && events.message.toString().indexOf('1002: Verification Error') > -1) return;1428    const result = getCreateItemResult(events);14291430    expect(result.success).to.be.false;1431  });1432}14331434export async function createItemExpectSuccess(sender: IKeyringPair, collectionId: number, createMode: string, owner: CrossAccountId | string = sender.address) {1435  let newItemId = 0;1436  await usingApi(async (api) => {1437    const to = normalizeAccountId(owner);1438    const itemCountBefore = await getLastTokenId(api, collectionId);1439    const itemBalanceBefore = await getBalance(api, collectionId, to, newItemId);14401441    let tx;1442    if (createMode === 'Fungible') {1443      const createData = {fungible: {value: 10}};1444      tx = api.tx.unique.createItem(collectionId, to, createData as any);1445    } else if (createMode === 'ReFungible') {1446      const createData = {refungible: {pieces: 100}};1447      tx = api.tx.unique.createItem(collectionId, to, createData as any);1448    } else {1449      const createData = {nft: {}};1450      tx = api.tx.unique.createItem(collectionId, to, createData as any);1451    }14521453    const events = await executeTransaction(api, sender, tx);1454    const result = getCreateItemResult(events);14551456    const itemCountAfter = await getLastTokenId(api, collectionId);1457    const itemBalanceAfter = await getBalance(api, collectionId, to, newItemId);14581459    // What to expect1460    // tslint:disable-next-line:no-unused-expression1461    expect(result.success).to.be.true;1462    if (createMode === 'Fungible') {1463      expect(itemBalanceAfter - itemBalanceBefore).to.be.equal(10n);1464    } else {1465      expect(itemCountAfter).to.be.equal(itemCountBefore + 1);1466    }1467    expect(collectionId).to.be.equal(result.collectionId);1468    expect(itemCountAfter.toString()).to.be.equal(result.itemId.toString());1469    expect(to).to.be.deep.equal(result.recipient);1470    newItemId = result.itemId;1471  });1472  return newItemId;1473}14741475export async function createRefungibleToken(api: ApiPromise, sender: IKeyringPair, collectionId: number, amount: bigint, owner: CrossAccountId | IKeyringPair | string = sender.address) : Promise<CreateItemResult> {1476  const createData = {refungible: {pieces: amount}};1477  const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), createData as any);14781479  const events = await submitTransactionAsync(sender, tx);1480  return  getCreateItemResult(events);1481}14821483export async function createItemExpectFailure(sender: IKeyringPair, collectionId: number, createMode: string, owner: CrossAccountId | string = sender.address) {1484  await usingApi(async (api) => {1485    const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), createMode);14861487    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1488    const result = getCreateItemResult(events);14891490    expect(result.success).to.be.false;1491  });1492}14931494export async function setPublicAccessModeExpectSuccess(1495  sender: IKeyringPair, collectionId: number,1496  accessMode: 'Normal' | 'AllowList',1497) {1498  await usingApi(async (api) => {14991500    // Run the transaction1501    const tx = api.tx.unique.setCollectionPermissions(collectionId, {access: accessMode});1502    const events = await submitTransactionAsync(sender, tx);1503    const result = getGenericResult(events);15041505    // Get the collection1506    const collection = await queryCollectionExpectSuccess(api, collectionId);15071508    // What to expect1509    // tslint:disable-next-line:no-unused-expression1510    expect(result.success).to.be.true;1511    expect(collection.permissions.access.toHuman()).to.be.equal(accessMode);1512  });1513}15141515export async function setPublicAccessModeExpectFail(1516  sender: IKeyringPair, collectionId: number,1517  accessMode: 'Normal' | 'AllowList',1518) {1519  await usingApi(async (api) => {15201521    // Run the transaction1522    const tx = api.tx.unique.setCollectionPermissions(collectionId, {access: accessMode});1523    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1524    const result = getGenericResult(events);15251526    // What to expect1527    // tslint:disable-next-line:no-unused-expression1528    expect(result.success).to.be.false;1529  });1530}15311532export async function enableAllowListExpectSuccess(sender: IKeyringPair, collectionId: number) {1533  await setPublicAccessModeExpectSuccess(sender, collectionId, 'AllowList');1534}15351536export async function enableAllowListExpectFail(sender: IKeyringPair, collectionId: number) {1537  await setPublicAccessModeExpectFail(sender, collectionId, 'AllowList');1538}15391540export async function disableAllowListExpectSuccess(sender: IKeyringPair, collectionId: number) {1541  await setPublicAccessModeExpectSuccess(sender, collectionId, 'Normal');1542}15431544export async function setMintPermissionExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {1545  await usingApi(async (api) => {15461547    // Run the transaction1548    const tx = api.tx.unique.setCollectionPermissions(collectionId, {mintMode: enabled});1549    const events = await submitTransactionAsync(sender, tx);1550    const result = getGenericResult(events);1551    expect(result.success).to.be.true;15521553    // Get the collection1554    const collection = await queryCollectionExpectSuccess(api, collectionId);15551556    expect(collection.permissions.mintMode.toHuman()).to.be.equal(enabled);1557  });1558}15591560export async function enablePublicMintingExpectSuccess(sender: IKeyringPair, collectionId: number) {1561  await setMintPermissionExpectSuccess(sender, collectionId, true);1562}15631564export async function setMintPermissionExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {1565  await usingApi(async (api) => {1566    // Run the transaction1567    const tx = api.tx.unique.setCollectionPermissions(collectionId, {mintMode: enabled});1568    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1569    const result = getCreateCollectionResult(events);1570    // tslint:disable-next-line:no-unused-expression1571    expect(result.success).to.be.false;1572  });1573}15741575export async function setChainLimitsExpectFailure(sender: IKeyringPair, limits: IChainLimits) {1576  await usingApi(async (api) => {1577    // Run the transaction1578    const tx = api.tx.unique.setChainLimits(limits);1579    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1580    const result = getCreateCollectionResult(events);1581    // tslint:disable-next-line:no-unused-expression1582    expect(result.success).to.be.false;1583  });1584}15851586export async function isAllowlisted(api: ApiPromise, collectionId: number, address: string | CrossAccountId) {1587  return (await api.rpc.unique.allowed(collectionId, normalizeAccountId(address))).toJSON();1588}15891590export async function addToAllowListExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId | CrossAccountId) {1591  await usingApi(async (api) => {1592    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.false;15931594    // Run the transaction1595    const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1596    const events = await submitTransactionAsync(sender, tx);1597    const result = getGenericResult(events);1598    expect(result.success).to.be.true;15991600    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;1601  });1602}16031604export async function addToAllowListAgainExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId) {1605  await usingApi(async (api) => {16061607    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;16081609    // Run the transaction1610    const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1611    const events = await submitTransactionAsync(sender, tx);1612    const result = getGenericResult(events);1613    expect(result.success).to.be.true;16141615    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;1616  });1617}16181619export async function addToAllowListExpectFail(sender: IKeyringPair, collectionId: number, address: string | AccountId) {1620  await usingApi(async (api) => {16211622    // Run the transaction1623    const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1624    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1625    const result = getGenericResult(events);16261627    // What to expect1628    // tslint:disable-next-line:no-unused-expression1629    expect(result.success).to.be.false;1630  });1631}16321633export async function removeFromAllowListExpectSuccess(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1634  await usingApi(async (api) => {1635    // Run the transaction1636    const tx = api.tx.unique.removeFromAllowList(collectionId, normalizeAccountId(address));1637    const events = await submitTransactionAsync(sender, tx);1638    const result = getGenericResult(events);16391640    // What to expect1641    // tslint:disable-next-line:no-unused-expression1642    expect(result.success).to.be.true;1643  });1644}16451646export async function removeFromAllowListExpectFailure(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1647  await usingApi(async (api) => {1648    // Run the transaction1649    const tx = api.tx.unique.removeFromAllowList(collectionId, normalizeAccountId(address));1650    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1651    const result = getGenericResult(events);16521653    // What to expect1654    // tslint:disable-next-line:no-unused-expression1655    expect(result.success).to.be.false;1656  });1657}16581659export const getDetailedCollectionInfo = async (api: ApiPromise, collectionId: number)1660  : Promise<UpDataStructsRpcCollection | null> => {1661  return (await api.rpc.unique.collectionById(collectionId)).unwrapOr(null);1662};16631664export const getCreatedCollectionCount = async (api: ApiPromise): Promise<number> => {1665  // set global object - collectionsCount1666  return (await api.rpc.unique.collectionStats()).created.toNumber();1667};16681669export async function queryCollectionExpectSuccess(api: ApiPromise, collectionId: number): Promise<UpDataStructsRpcCollection> {1670  return (await api.rpc.unique.collectionById(collectionId)).unwrap();1671}16721673export async function waitNewBlocks(blocksCount = 1): Promise<void> {1674  await usingApi(async (api) => {1675    const promise = new Promise<void>(async (resolve) => {1676      const unsubscribe = await api.rpc.chain.subscribeNewHeads(() => {1677        if (blocksCount > 0) {1678          blocksCount--;1679        } else {1680          unsubscribe();1681          resolve();1682        }1683      });1684    });1685    return promise;1686  });1687}16881689export async function repartitionRFT(1690  api: ApiPromise,1691  collectionId: number,1692  sender: IKeyringPair,1693  tokenId: number,1694  amount: bigint,1695): Promise<boolean> {1696  const tx = api.tx.unique.repartition(collectionId, tokenId, amount);1697  const events = await submitTransactionAsync(sender, tx);1698  const result = getGenericResult(events);16991700  return result.success;1701}