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

difftreelog

source

tests/src/util/helpers.ts52.3 KiBsourcehistory
1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617import '../interfaces/augment-api-rpc';18import '../interfaces/augment-api-query';19import {ApiPromise, Keyring} from '@polkadot/api';20import type {AccountId, EventRecord, Event} from '@polkadot/types/interfaces';21import {AnyTuple, IEvent, IKeyringPair} from '@polkadot/types/types';22import {evmToAddress} from '@polkadot/util-crypto';23import BN from 'bn.js';24import chai from 'chai';25import chaiAsPromised from 'chai-as-promised';26import {alicesPublicKey} from '../accounts';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';3031chai.use(chaiAsPromised);32const expect = chai.expect;3334export type CrossAccountId = {35  Substrate: string,36} | {37  Ethereum: string,38};3940export function normalizeAccountId(input: string | AccountId | CrossAccountId | IKeyringPair): CrossAccountId {41  if (typeof input === 'string') {42    if (input.length === 48 || input.length === 47) {43      return {Substrate: input};44    } else if (input.length === 42 && input.startsWith('0x')) {45      return {Ethereum: input.toLowerCase()};46    } else if (input.length === 40 && !input.startsWith('0x')) {47      return {Ethereum: '0x' + input.toLowerCase()};48    } else {49      throw new Error(`Unknown address format: "${input}"`);50    }51  }52  if ('address' in input) {53    return {Substrate: input.address};54  }55  if ('Ethereum' in input) {56    return {57      Ethereum: input.Ethereum.toLowerCase(),58    };59  } else if ('ethereum' in input) {60    return {61      Ethereum: (input as any).ethereum.toLowerCase(),62    };63  } else if ('Substrate' in input) {64    return input;65  } else if ('substrate' in input) {66    return {67      Substrate: (input as any).substrate,68    };69  }7071  // AccountId72  return {Substrate: input.toString()};73}74export function toSubstrateAddress(input: string | CrossAccountId | IKeyringPair): string {75  input = normalizeAccountId(input);76  if ('Substrate' in input) {77    return input.Substrate;78  } else {79    return evmToAddress(input.Ethereum);80  }81}8283export const U128_MAX = (1n << 128n) - 1n;8485const MICROUNIQUE = 1_000_000_000_000n;86const MILLIUNIQUE = 1_000n * MICROUNIQUE;87const CENTIUNIQUE = 10n * MILLIUNIQUE;88export const UNIQUE = 100n * CENTIUNIQUE;8990type GenericResult = {91  success: boolean,92};9394interface CreateCollectionResult {95  success: boolean;96  collectionId: number;97}9899interface CreateItemResult {100  success: boolean;101  collectionId: number;102  itemId: number;103  recipient?: CrossAccountId;104}105106interface TransferResult {107  collectionId: number;108  itemId: number;109  sender?: CrossAccountId;110  recipient?: CrossAccountId;111  value: bigint;112}113114interface IReFungibleOwner {115  fraction: BN;116  owner: number[];117}118119interface IGetMessage {120  checkMsgUnqMethod: string;121  checkMsgTrsMethod: string;122  checkMsgSysMethod: string;123}124125export interface IFungibleTokenDataType {126  value: number;127}128129export interface IChainLimits {130  collectionNumbersLimit: number;131  accountTokenOwnershipLimit: number;132  collectionsAdminsLimit: number;133  customDataLimit: number;134  nftSponsorTransferTimeout: number;135  fungibleSponsorTransferTimeout: number;136  refungibleSponsorTransferTimeout: number;137  //offchainSchemaLimit: number;138  //constOnChainSchemaLimit: number;139}140141export interface IReFungibleTokenDataType {142  owner: IReFungibleOwner[];143}144145export function uniqueEventMessage(events: EventRecord[]): IGetMessage {146  let checkMsgUnqMethod = '';147  let checkMsgTrsMethod = '';148  let checkMsgSysMethod = '';149  events.forEach(({event: {method, section}}) => {150    if (section === 'common') {151      checkMsgUnqMethod = method;152    } else if (section === 'treasury') {153      checkMsgTrsMethod = method;154    } else if (section === 'system') {155      checkMsgSysMethod = method;156    } else { return null; }157  });158  const result: IGetMessage = {159    checkMsgUnqMethod,160    checkMsgTrsMethod,161    checkMsgSysMethod,162  };163  return result;164}165166export function getEvent<T extends Event>(events: EventRecord[], check: (event: IEvent<AnyTuple>) => event is T): T | undefined {167  const event = events.find(r => check(r.event));168  if (!event) return;169  return event.event as T;170}171172export function getGenericResult(events: EventRecord[]): GenericResult {173  const result: GenericResult = {174    success: false,175  };176  events.forEach(({event: {method}}) => {177    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);178    if (method === 'ExtrinsicSuccess') {179      result.success = true;180    }181  });182  return result;183}184185186187export function getCreateCollectionResult(events: EventRecord[]): CreateCollectionResult {188  let success = false;189  let collectionId = 0;190  events.forEach(({event: {data, method, section}}) => {191    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);192    if (method == 'ExtrinsicSuccess') {193      success = true;194    } else if ((section == 'common') && (method == 'CollectionCreated')) {195      collectionId = parseInt(data[0].toString(), 10);196    }197  });198  const result: CreateCollectionResult = {199    success,200    collectionId,201  };202  return result;203}204205export function getCreateItemsResult(events: EventRecord[]): CreateItemResult[] {206  let success = false;207  let collectionId = 0;208  let itemId = 0;209  let recipient;210211  const results : CreateItemResult[]  = [];212213  events.forEach(({event: {data, method, section}}) => {214    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);215    if (method == 'ExtrinsicSuccess') {216      success = true;217    } else if ((section == 'common') && (method == 'ItemCreated')) {218      collectionId = parseInt(data[0].toString(), 10);219      itemId = parseInt(data[1].toString(), 10);220      recipient = normalizeAccountId(data[2].toJSON() as any);221222      const itemRes: CreateItemResult = {223        success,224        collectionId,225        itemId,226        recipient,227      };228229      results.push(itemRes);230    }231  });232233  return results;234}235236export function getCreateItemResult(events: EventRecord[]): CreateItemResult {237  let success = false;238  let collectionId = 0;239  let itemId = 0;240  let recipient;241  events.forEach(({event: {data, method, section}}) => {242    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);243    if (method == 'ExtrinsicSuccess') {244      success = true;245    } else if ((section == 'common') && (method == 'ItemCreated')) {246      collectionId = parseInt(data[0].toString(), 10);247      itemId = parseInt(data[1].toString(), 10);248      recipient = normalizeAccountId(data[2].toJSON() as any);249    }250  });251  const result: CreateItemResult = {252    success,253    collectionId,254    itemId,255    recipient,256  };257  return result;258}259260export function getTransferResult(api: ApiPromise, events: EventRecord[]): TransferResult {261  for (const {event} of events) {262    if (api.events.common.Transfer.is(event)) {263      const [collection, token, sender, recipient, value] = event.data;264      return {265        collectionId: collection.toNumber(),266        itemId: token.toNumber(),267        sender: normalizeAccountId(sender.toJSON() as any),268        recipient: normalizeAccountId(recipient.toJSON() as any),269        value: value.toBigInt(),270      };271    }272  }273  throw new Error('no transfer event');274}275276interface Nft {277  type: 'NFT';278}279280interface Fungible {281  type: 'Fungible';282  decimalPoints: number;283}284285interface ReFungible {286  type: 'ReFungible';287}288289type CollectionMode = Nft | Fungible | ReFungible;290291export type Property = {292  key: any,293  value: any,294};295296type Permission = {297  mutable: boolean;298  collectionAdmin: boolean;299  tokenOwner: boolean;300}301302type PropertyPermission = {303  key: any;304  permission: Permission;305}306307export type CreateCollectionParams = {308  mode: CollectionMode,309  name: string,310  description: string,311  tokenPrefix: string,312  properties?: Array<Property>,313  propPerm?: Array<PropertyPermission>314};315316const defaultCreateCollectionParams: CreateCollectionParams = {317  description: 'description',318  mode: {type: 'NFT'},319  name: 'name',320  tokenPrefix: 'prefix',321};322323export async function createCollectionExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {324  const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};325326  let collectionId = 0;327  await usingApi(async (api, privateKeyWrapper) => {328    // Get number of collections before the transaction329    const collectionCountBefore = await getCreatedCollectionCount(api);330331    // Run the CreateCollection transaction332    const alicePrivateKey = privateKeyWrapper!('//Alice');333334    let modeprm = {};335    if (mode.type === 'NFT') {336      modeprm = {nft: null};337    } else if (mode.type === 'Fungible') {338      modeprm = {fungible: mode.decimalPoints};339    } else if (mode.type === 'ReFungible') {340      modeprm = {refungible: null};341    }342343    const tx = api.tx.unique.createCollectionEx({344      name: strToUTF16(name),345      description: strToUTF16(description),346      tokenPrefix: strToUTF16(tokenPrefix),347      mode: modeprm as any,348    });349    const events = await submitTransactionAsync(alicePrivateKey, tx);350    const result = getCreateCollectionResult(events);351352    // Get number of collections after the transaction353    const collectionCountAfter = await getCreatedCollectionCount(api);354355    // Get the collection356    const collection = await queryCollectionExpectSuccess(api, result.collectionId);357358    // What to expect359    // tslint:disable-next-line:no-unused-expression360    expect(result.success).to.be.true;361    expect(result.collectionId).to.be.equal(collectionCountAfter);362    // tslint:disable-next-line:no-unused-expression363    expect(collection).to.be.not.null;364    expect(collectionCountAfter).to.be.equal(collectionCountBefore + 1, 'Error: NFT collection NOT created.');365    expect(collection.owner.toString()).to.be.equal(toSubstrateAddress(alicesPublicKey));366    expect(utf16ToStr(collection.name.toJSON() as any)).to.be.equal(name);367    expect(utf16ToStr(collection.description.toJSON() as any)).to.be.equal(description);368    expect(hexToStr(collection.tokenPrefix.toJSON())).to.be.equal(tokenPrefix);369370    collectionId = result.collectionId;371  });372373  return collectionId;374}375376export async function createCollectionWithPropsExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {377  const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};378379  let collectionId = 0;380  await usingApi(async (api, privateKeyWrapper) => {381    // Get number of collections before the transaction382    const collectionCountBefore = await getCreatedCollectionCount(api);383384    // Run the CreateCollection transaction385    const alicePrivateKey = privateKeyWrapper!('//Alice');386387    let modeprm = {};388    if (mode.type === 'NFT') {389      modeprm = {nft: null};390    } else if (mode.type === 'Fungible') {391      modeprm = {fungible: mode.decimalPoints};392    } else if (mode.type === 'ReFungible') {393      modeprm = {refungible: null};394    }395396    const tx = api.tx.unique.createCollectionEx({name: strToUTF16(name), description: strToUTF16(description), tokenPrefix: strToUTF16(tokenPrefix), mode: modeprm as any, properties: params.properties, tokenPropertyPermissions: params.propPerm});397    const events = await submitTransactionAsync(alicePrivateKey, tx);398    const result = getCreateCollectionResult(events);399400    // Get number of collections after the transaction401    const collectionCountAfter = await getCreatedCollectionCount(api);402403    // Get the collection404    const collection = await queryCollectionExpectSuccess(api, result.collectionId);405406    // What to expect407    // tslint:disable-next-line:no-unused-expression408    expect(result.success).to.be.true;409    expect(result.collectionId).to.be.equal(collectionCountAfter);410    // tslint:disable-next-line:no-unused-expression411    expect(collection).to.be.not.null;412    expect(collectionCountAfter).to.be.equal(collectionCountBefore + 1, 'Error: NFT collection NOT created.');413    expect(collection.owner.toString()).to.be.equal(toSubstrateAddress(alicesPublicKey));414    expect(utf16ToStr(collection.name.toJSON() as any)).to.be.equal(name);415    expect(utf16ToStr(collection.description.toJSON() as any)).to.be.equal(description);416    expect(hexToStr(collection.tokenPrefix.toJSON())).to.be.equal(tokenPrefix);417418419    collectionId = result.collectionId;420  });421422  return collectionId;423}424425export async function createCollectionWithPropsExpectFailure(params: Partial<CreateCollectionParams> = {}) {426  const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};427428  await usingApi(async (api, privateKeyWrapper) => {429    // Get number of collections before the transaction430    const collectionCountBefore = await getCreatedCollectionCount(api);431432    // Run the CreateCollection transaction433    const alicePrivateKey = privateKeyWrapper!('//Alice');434435    let modeprm = {};436    if (mode.type === 'NFT') {437      modeprm = {nft: null};438    } else if (mode.type === 'Fungible') {439      modeprm = {fungible: mode.decimalPoints};440    } else if (mode.type === 'ReFungible') {441      modeprm = {refungible: null};442    }443444    const tx = api.tx.unique.createCollectionEx({name: strToUTF16(name), description: strToUTF16(description), tokenPrefix: strToUTF16(tokenPrefix), mode: modeprm as any, properties: params.properties, tokenPropertyPermissions: params.propPerm});445    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;446447448    // Get number of collections after the transaction449    const collectionCountAfter = await getCreatedCollectionCount(api);450451    expect(collectionCountAfter).to.be.equal(collectionCountBefore, 'Error: Collection with incorrect data created.');452  });453}454455export async function createCollectionExpectFailure(params: Partial<CreateCollectionParams> = {}) {456  const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};457458  let modeprm = {};459  if (mode.type === 'NFT') {460    modeprm = {nft: null};461  } else if (mode.type === 'Fungible') {462    modeprm = {fungible: mode.decimalPoints};463  } else if (mode.type === 'ReFungible') {464    modeprm = {refungible: null};465  }466467  await usingApi(async (api, privateKeyWrapper) => {468    // Get number of collections before the transaction469    const collectionCountBefore = await getCreatedCollectionCount(api);470471    // Run the CreateCollection transaction472    const alicePrivateKey = privateKeyWrapper!('//Alice');473    const tx = api.tx.unique.createCollectionEx({name: strToUTF16(name), description: strToUTF16(description), tokenPrefix: strToUTF16(tokenPrefix), mode: modeprm as any});474    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;475476    // Get number of collections after the transaction477    const collectionCountAfter = await getCreatedCollectionCount(api);478479    // What to expect480    expect(collectionCountAfter).to.be.equal(collectionCountBefore, 'Error: Collection with incorrect data created.');481  });482}483484export async function findUnusedAddress(api: ApiPromise, seedAddition = ''): Promise<IKeyringPair> {485  let bal = 0n;486  let unused;487  do {488    const randomSeed = 'seed' + Math.floor(Math.random() * Math.floor(10000)) + seedAddition;489    const keyring = new Keyring({type: 'sr25519'});490    unused = keyring.addFromUri(`//${randomSeed}`);491    bal = (await api.query.system.account(unused.address)).data.free.toBigInt();492  } while (bal !== 0n);493  return unused;494}495496export async function getAllowance(api: ApiPromise, collectionId: number, owner: CrossAccountId | string, approved: CrossAccountId | string, tokenId: number) {497  return (await api.rpc.unique.allowance(collectionId, normalizeAccountId(owner), normalizeAccountId(approved), tokenId)).toBigInt();498}499500export function findUnusedAddresses(api: ApiPromise, amount: number): Promise<IKeyringPair[]> {501  return Promise.all(new Array(amount).fill(null).map(() => findUnusedAddress(api, '_' + Date.now())));502}503504export async function findNotExistingCollection(api: ApiPromise): Promise<number> {505  const totalNumber = await getCreatedCollectionCount(api);506  const newCollection: number = totalNumber + 1;507  return newCollection;508}509510function getDestroyResult(events: EventRecord[]): boolean {511  let success = false;512  events.forEach(({event: {method}}) => {513    if (method == 'ExtrinsicSuccess') {514      success = true;515    }516  });517  return success;518}519520export async function destroyCollectionExpectFailure(collectionId: number, senderSeed = '//Alice') {521  await usingApi(async (api, privateKeyWrapper) => {522    // Run the DestroyCollection transaction523    const alicePrivateKey = privateKeyWrapper!(senderSeed);524    const tx = api.tx.unique.destroyCollection(collectionId);525    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;526  });527}528529export async function destroyCollectionExpectSuccess(collectionId: number, senderSeed = '//Alice') {530  await usingApi(async (api, privateKeyWrapper) => {531    // Run the DestroyCollection transaction532    const alicePrivateKey = privateKeyWrapper!(senderSeed);533    const tx = api.tx.unique.destroyCollection(collectionId);534    const events = await submitTransactionAsync(alicePrivateKey, tx);535    const result = getDestroyResult(events);536    expect(result).to.be.true;537538    // What to expect539    expect(await getDetailedCollectionInfo(api, collectionId)).to.be.null;540  });541}542543export async function setCollectionLimitsExpectSuccess(sender: IKeyringPair, collectionId: number, limits: any) {544  await usingApi(async (api) => {545    const tx = api.tx.unique.setCollectionLimits(collectionId, limits);546    const events = await submitTransactionAsync(sender, tx);547    const result = getGenericResult(events);548549    expect(result.success).to.be.true;550  });551}552553export const setCollectionPermissionsExpectSuccess = async (sender: IKeyringPair, collectionId: number, permissions: {mintMode?: boolean, access?: 'Normal' | 'AllowList', nesting?: 'Disabled' | 'Owner' | {OwnerRestricted: number[]}}) => {554  await usingApi(async(api) => {555    const tx = api.tx.unique.setCollectionPermissions(collectionId, permissions);556    const events = await submitTransactionAsync(sender, tx);557    const result = getGenericResult(events);558559    expect(result.success).to.be.true;560  });561};562563export async function setCollectionLimitsExpectFailure(sender: IKeyringPair, collectionId: number, limits: any) {564  await usingApi(async (api) => {565    const tx = api.tx.unique.setCollectionLimits(collectionId, limits);566    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;567    const result = getGenericResult(events);568569    expect(result.success).to.be.false;570  });571}572573export async function setCollectionSponsorExpectSuccess(collectionId: number, sponsor: string, sender = '//Alice') {574  await usingApi(async (api, privateKeyWrapper) => {575576    // Run the transaction577    const senderPrivateKey = privateKeyWrapper!(sender);578    const tx = api.tx.unique.setCollectionSponsor(collectionId, sponsor);579    const events = await submitTransactionAsync(senderPrivateKey, tx);580    const result = getGenericResult(events);581582    // Get the collection583    const collection = await queryCollectionExpectSuccess(api, collectionId);584585    // What to expect586    expect(result.success).to.be.true;587    expect(collection.sponsorship.toJSON()).to.deep.equal({588      unconfirmed: sponsor,589    });590  });591}592593export async function removeCollectionSponsorExpectSuccess(collectionId: number, sender = '//Alice') {594  await usingApi(async (api, privateKeyWrapper) => {595596    // Run the transaction597    const alicePrivateKey = privateKeyWrapper!(sender);598    const tx = api.tx.unique.removeCollectionSponsor(collectionId);599    const events = await submitTransactionAsync(alicePrivateKey, tx);600    const result = getGenericResult(events);601602    // Get the collection603    const collection = await queryCollectionExpectSuccess(api, collectionId);604605    // What to expect606    expect(result.success).to.be.true;607    expect(collection.sponsorship.toJSON()).to.be.deep.equal({disabled: null});608  });609}610611export async function removeCollectionSponsorExpectFailure(collectionId: number, senderSeed = '//Alice') {612  await usingApi(async (api, privateKeyWrapper) => {613614    // Run the transaction615    const alicePrivateKey = privateKeyWrapper!(senderSeed);616    const tx = api.tx.unique.removeCollectionSponsor(collectionId);617    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;618  });619}620621export async function setCollectionSponsorExpectFailure(collectionId: number, sponsor: string, senderSeed = '//Alice') {622  await usingApi(async (api, privateKeyWrapper) => {623624    // Run the transaction625    const alicePrivateKey = privateKeyWrapper!(senderSeed);626    const tx = api.tx.unique.setCollectionSponsor(collectionId, sponsor);627    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;628  });629}630631export async function confirmSponsorshipExpectSuccess(collectionId: number, senderSeed = '//Alice') {632  await usingApi(async (api, privateKeyWrapper) => {633634    // Run the transaction635    const sender = privateKeyWrapper!(senderSeed);636    const tx = api.tx.unique.confirmSponsorship(collectionId);637    const events = await submitTransactionAsync(sender, tx);638    const result = getGenericResult(events);639640    // Get the collection641    const collection = await queryCollectionExpectSuccess(api, collectionId);642643    // What to expect644    expect(result.success).to.be.true;645    expect(collection.sponsorship.toJSON()).to.be.deep.equal({646      confirmed: sender.address,647    });648  });649}650651652export async function confirmSponsorshipExpectFailure(collectionId: number, senderSeed = '//Alice') {653  await usingApi(async (api, privateKeyWrapper) => {654655    // Run the transaction656    const sender = privateKeyWrapper!(senderSeed);657    const tx = api.tx.unique.confirmSponsorship(collectionId);658    await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;659  });660}661662export async function enableContractSponsoringExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {663  await usingApi(async (api) => {664    const tx = api.tx.unique.enableContractSponsoring(contractAddress, enable);665    const events = await submitTransactionAsync(sender, tx);666    const result = getGenericResult(events);667668    expect(result.success).to.be.true;669  });670}671672export async function enableContractSponsoringExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {673  await usingApi(async (api) => {674    const tx = api.tx.unique.enableContractSponsoring(contractAddress, enable);675    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;676    const result = getGenericResult(events);677678    expect(result.success).to.be.false;679  });680}681682export async function setTransferFlagExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {683684  await usingApi(async (api) => {685686    const tx = api.tx.unique.setTransfersEnabledFlag(collectionId, enabled);687    const events = await submitTransactionAsync(sender, tx);688    const result = getGenericResult(events);689690    expect(result.success).to.be.true;691  });692}693694export async function setTransferFlagExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {695696  await usingApi(async (api) => {697698    const tx = api.tx.unique.setTransfersEnabledFlag(collectionId, enabled);699    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;700    const result = getGenericResult(events);701702    expect(result.success).to.be.false;703  });704}705706export async function setContractSponsoringRateLimitExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {707  await usingApi(async (api) => {708    const tx = api.tx.unique.setContractSponsoringRateLimit(contractAddress, rateLimit);709    const events = await submitTransactionAsync(sender, tx);710    const result = getGenericResult(events);711712    expect(result.success).to.be.true;713  });714}715716export async function setContractSponsoringRateLimitExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {717  await usingApi(async (api) => {718    const tx = api.tx.unique.setContractSponsoringRateLimit(contractAddress, rateLimit);719    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;720    const result = getGenericResult(events);721722    expect(result.success).to.be.false;723  });724}725726export async function getNextSponsored(727  api: ApiPromise,728  collectionId: number,729  account: string | CrossAccountId,730  tokenId: number,731): Promise<number> {732  return Number((await api.rpc.unique.nextSponsored(collectionId, account, tokenId)).unwrapOr(-1));733}734735export async function toggleContractAllowlistExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, value = true) {736  await usingApi(async (api) => {737    const tx = api.tx.unique.toggleContractAllowList(contractAddress, value);738    const events = await submitTransactionAsync(sender, tx);739    const result = getGenericResult(events);740741    expect(result.success).to.be.true;742  });743}744745export async function isAllowlistedInContract(contractAddress: AccountId | string, user: string) {746  let allowlisted = false;747  await usingApi(async (api) => {748    allowlisted = (await api.query.unique.contractAllowList(contractAddress, user)).toJSON() as boolean;749  });750  return allowlisted;751}752753export async function addToContractAllowListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {754  await usingApi(async (api) => {755    const tx = api.tx.unique.addToContractAllowList(contractAddress.toString(), user.toString());756    const events = await submitTransactionAsync(sender, tx);757    const result = getGenericResult(events);758759    expect(result.success).to.be.true;760  });761}762763export async function removeFromContractAllowListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {764  await usingApi(async (api) => {765    const tx = api.tx.unique.removeFromContractAllowList(contractAddress.toString(), user.toString());766    const events = await submitTransactionAsync(sender, tx);767    const result = getGenericResult(events);768769    expect(result.success).to.be.true;770  });771}772773export async function removeFromContractAllowListExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {774  await usingApi(async (api) => {775    const tx = api.tx.unique.removeFromContractAllowList(contractAddress.toString(), user.toString());776    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;777    const result = getGenericResult(events);778779    expect(result.success).to.be.false;780  });781}782783export interface CreateFungibleData {784  readonly Value: bigint;785}786787export interface CreateReFungibleData { }788export interface CreateNftData { }789790export type CreateItemData = {791  NFT: CreateNftData;792} | {793  Fungible: CreateFungibleData;794} | {795  ReFungible: CreateReFungibleData;796};797798export async function burnItemExpectSuccess(sender: IKeyringPair, collectionId: number, tokenId: number, value = 1) {799  await usingApi(async (api) => {800    const balanceBefore = await getBalance(api, collectionId, normalizeAccountId(sender), tokenId);801    // if burning token by admin - use adminButnItemExpectSuccess802    expect(balanceBefore >= BigInt(value)).to.be.true;803804    const tx = api.tx.unique.burnItem(collectionId, tokenId, value);805    const events = await submitTransactionAsync(sender, tx);806    const result = getGenericResult(events);807    expect(result.success).to.be.true;808809    const balanceAfter = await getBalance(api, collectionId, normalizeAccountId(sender), tokenId);810    expect(balanceAfter + BigInt(value)).to.be.equal(balanceBefore);811  });812}813814export async function815approveExpectSuccess(816  collectionId: number,817  tokenId: number, owner: IKeyringPair, approved: CrossAccountId | string, amount: number | bigint = 1,818) {819  await usingApi(async (api: ApiPromise) => {820    const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);821    const events = await submitTransactionAsync(owner, approveUniqueTx);822    const result = getGenericResult(events);823    expect(result.success).to.be.true;824825    expect(await getAllowance(api, collectionId, owner.address, approved, tokenId)).to.be.equal(BigInt(amount));826  });827}828829export async function adminApproveFromExpectSuccess(830  collectionId: number,831  tokenId: number, admin: IKeyringPair, owner: CrossAccountId | string, approved: CrossAccountId | string, amount: number | bigint = 1,832) {833  await usingApi(async (api: ApiPromise) => {834    const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);835    const events = await submitTransactionAsync(admin, approveUniqueTx);836    const result = getGenericResult(events);837    expect(result.success).to.be.true;838839    expect(await getAllowance(api, collectionId, owner, approved, tokenId)).to.be.equal(BigInt(amount));840  });841}842843export async function844transferFromExpectSuccess(845  collectionId: number,846  tokenId: number,847  accountApproved: IKeyringPair,848  accountFrom: IKeyringPair | CrossAccountId,849  accountTo: IKeyringPair | CrossAccountId,850  value: number | bigint = 1,851  type = 'NFT',852) {853  await usingApi(async (api: ApiPromise) => {854    const from = normalizeAccountId(accountFrom);855    const to = normalizeAccountId(accountTo);856    let balanceBefore = 0n;857    if (type === 'Fungible' || type === 'ReFungible') {858      balanceBefore = await getBalance(api, collectionId, to, tokenId);859    }860    const transferFromTx = api.tx.unique.transferFrom(normalizeAccountId(accountFrom), to, collectionId, tokenId, value);861    const events = await submitTransactionAsync(accountApproved, transferFromTx);862    const result = getCreateItemResult(events);863    // tslint:disable-next-line:no-unused-expression864    expect(result.success).to.be.true;865    if (type === 'NFT') {866      expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(to);867    }868    if (type === 'Fungible') {869      const balanceAfter = await getBalance(api, collectionId, to, tokenId);870      if (JSON.stringify(to) !== JSON.stringify(from)) {871        expect(balanceAfter - balanceBefore).to.be.equal(BigInt(value));872      } else {873        expect(balanceAfter).to.be.equal(balanceBefore);874      }875    }876    if (type === 'ReFungible') {877      expect(await getBalance(api, collectionId, to, tokenId)).to.be.equal(balanceBefore + BigInt(value));878    }879  });880}881882export async function883transferFromExpectFail(884  collectionId: number,885  tokenId: number,886  accountApproved: IKeyringPair,887  accountFrom: IKeyringPair,888  accountTo: IKeyringPair,889  value: number | bigint = 1,890) {891  await usingApi(async (api: ApiPromise) => {892    const transferFromTx = api.tx.unique.transferFrom(normalizeAccountId(accountFrom.address), normalizeAccountId(accountTo.address), collectionId, tokenId, value);893    const events = await expect(submitTransactionExpectFailAsync(accountApproved, transferFromTx)).to.be.rejected;894    const result = getCreateCollectionResult(events);895    // tslint:disable-next-line:no-unused-expression896    expect(result.success).to.be.false;897  });898}899900/* eslint no-async-promise-executor: "off" */901async function getBlockNumber(api: ApiPromise): Promise<number> {902  return new Promise<number>(async (resolve) => {903    const unsubscribe = await api.rpc.chain.subscribeNewHeads((head) => {904      unsubscribe();905      resolve(head.number.toNumber());906    });907  });908}909910export async function addCollectionAdminExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | CrossAccountId) {911  await usingApi(async (api) => {912    const changeAdminTx = api.tx.unique.addCollectionAdmin(collectionId, normalizeAccountId(address));913    const events = await submitTransactionAsync(sender, changeAdminTx);914    const result = getCreateCollectionResult(events);915    expect(result.success).to.be.true;916  });917}918919export async function920getFreeBalance(account: IKeyringPair): Promise<bigint> {921  let balance = 0n;922  await usingApi(async (api) => {923    balance = BigInt((await api.query.system.account(account.address)).data.free.toString());924  });925926  return balance;927}928929export async function transferBalanceTo(api: ApiPromise, source: IKeyringPair, target: string, amount = 1000n * UNIQUE) {930  const tx = api.tx.balances.transfer(target, amount);931  const events = await submitTransactionAsync(source, tx);932  const result = getGenericResult(events);933  expect(result.success).to.be.true;934}935936export async function937scheduleTransferExpectSuccess(938  collectionId: number,939  tokenId: number,940  sender: IKeyringPair,941  recipient: IKeyringPair,942  value: number | bigint = 1,943  blockSchedule: number,944) {945  await usingApi(async (api: ApiPromise) => {946    const blockNumber: number | undefined = await getBlockNumber(api);947    const expectedBlockNumber = blockNumber + blockSchedule;948949    expect(blockNumber).to.be.greaterThan(0);950    const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient.address), collectionId, tokenId, value);951    const scheduleTx = api.tx.scheduler.schedule(expectedBlockNumber, null, 0, transferTx as any);952953    await submitTransactionAsync(sender, scheduleTx);954955    const recipientBalanceBefore = (await api.query.system.account(recipient.address)).data.free.toBigInt();956957    expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(sender.address));958959    // sleep for 4 blocks960    await waitNewBlocks(blockSchedule + 1);961962    const recipientBalanceAfter = (await api.query.system.account(recipient.address)).data.free.toBigInt();963964    expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(recipient.address));965    expect(recipientBalanceAfter).to.be.equal(recipientBalanceBefore);966  });967}968969970export async function971transferExpectSuccess(972  collectionId: number,973  tokenId: number,974  sender: IKeyringPair,975  recipient: IKeyringPair | CrossAccountId,976  value: number | bigint = 1,977  type = 'NFT',978) {979  await usingApi(async (api: ApiPromise) => {980    const from = normalizeAccountId(sender);981    const to = normalizeAccountId(recipient);982983    let balanceBefore = 0n;984    if (type === 'Fungible') {985      balanceBefore = await getBalance(api, collectionId, to, tokenId);986    }987    const transferTx = api.tx.unique.transfer(to, collectionId, tokenId, value);988    const events = await executeTransaction(api, sender, transferTx);989990    const result = getTransferResult(api, events);991    expect(result.collectionId).to.be.equal(collectionId);992    expect(result.itemId).to.be.equal(tokenId);993    expect(result.sender).to.be.deep.equal(normalizeAccountId(sender.address));994    expect(result.recipient).to.be.deep.equal(to);995    expect(result.value).to.be.equal(BigInt(value));996997    if (type === 'NFT') {998      expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(to);999    }1000    if (type === 'Fungible') {1001      const balanceAfter = await getBalance(api, collectionId, to, tokenId);1002      if (JSON.stringify(to) !== JSON.stringify(from)) {1003        expect(balanceAfter - balanceBefore).to.be.equal(BigInt(value));1004      } else {1005        expect(balanceAfter).to.be.equal(balanceBefore);1006      }1007    }1008    if (type === 'ReFungible') {1009      expect(await getBalance(api, collectionId, to, tokenId) >= value).to.be.true;1010    }1011  });1012}10131014export async function1015transferExpectFailure(1016  collectionId: number,1017  tokenId: number,1018  sender: IKeyringPair,1019  recipient: IKeyringPair | CrossAccountId,1020  value: number | bigint = 1,1021) {1022  await usingApi(async (api: ApiPromise) => {1023    const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient), collectionId, tokenId, value);1024    const events = await expect(submitTransactionExpectFailAsync(sender, transferTx)).to.be.rejected;1025    const result = getGenericResult(events);1026    // if (events && Array.isArray(events)) {1027    //   const result = getCreateCollectionResult(events);1028    // tslint:disable-next-line:no-unused-expression1029    expect(result.success).to.be.false;1030    //}1031  });1032}10331034export async function1035approveExpectFail(1036  collectionId: number,1037  tokenId: number, owner: IKeyringPair, approved: IKeyringPair, amount: number | bigint = 1,1038) {1039  await usingApi(async (api: ApiPromise) => {1040    const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved.address), collectionId, tokenId, amount);1041    const events = await expect(submitTransactionExpectFailAsync(owner, approveUniqueTx)).to.be.rejected;1042    const result = getCreateCollectionResult(events);1043    // tslint:disable-next-line:no-unused-expression1044    expect(result.success).to.be.false;1045  });1046}10471048export async function getBalance(1049  api: ApiPromise,1050  collectionId: number,1051  owner: string | CrossAccountId,1052  token: number,1053): Promise<bigint> {1054  return (await api.rpc.unique.balance(collectionId, normalizeAccountId(owner), token)).toBigInt();1055}1056export async function getTokenOwner(1057  api: ApiPromise,1058  collectionId: number,1059  token: number,1060): Promise<CrossAccountId> {1061  const owner = (await api.rpc.unique.tokenOwner(collectionId, token)).toJSON() as any;1062  if (owner == null) throw new Error('owner == null');1063  return normalizeAccountId(owner);1064}1065export async function getTopmostTokenOwner(1066  api: ApiPromise,1067  collectionId: number,1068  token: number,1069): Promise<CrossAccountId> {1070  const owner = (await api.rpc.unique.topmostTokenOwner(collectionId, token)).toJSON() as any;1071  if (owner == null) throw new Error('owner == null');1072  return normalizeAccountId(owner);1073}1074export async function isTokenExists(1075  api: ApiPromise,1076  collectionId: number,1077  token: number,1078): Promise<boolean> {1079  return (await api.rpc.unique.tokenExists(collectionId, token)).toJSON();1080}1081export async function getLastTokenId(1082  api: ApiPromise,1083  collectionId: number,1084): Promise<number> {1085  return (await api.rpc.unique.lastTokenId(collectionId)).toJSON();1086}1087export async function getAdminList(1088  api: ApiPromise,1089  collectionId: number,1090): Promise<string[]> {1091  return (await api.rpc.unique.adminlist(collectionId)).toHuman() as any;1092}1093export async function getTokenProperties(1094  api: ApiPromise,1095  collectionId: number,1096  tokenId: number,1097  propertyKeys: string[],1098): Promise<UpDataStructsProperty[]> {1099  return (await api.rpc.unique.tokenProperties(collectionId, tokenId, propertyKeys)).toHuman() as any;1100}11011102export async function createFungibleItemExpectSuccess(1103  sender: IKeyringPair,1104  collectionId: number,1105  data: CreateFungibleData,1106  owner: CrossAccountId | string = sender.address,1107) {1108  return await usingApi(async (api) => {1109    const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), {Fungible: data});11101111    const events = await submitTransactionAsync(sender, tx);1112    const result = getCreateItemResult(events);11131114    expect(result.success).to.be.true;1115    return result.itemId;1116  });1117}11181119export async function createMultipleItemsWithPropsExpectSuccess(sender: IKeyringPair, collectionId: number, itemsData: any, owner: CrossAccountId | string = sender.address) {1120  await usingApi(async (api) => {1121    const to = normalizeAccountId(owner);1122    const tx = api.tx.unique.createMultipleItems(collectionId, to, itemsData);11231124    const events = await submitTransactionAsync(sender, tx);1125    const result = getCreateItemsResult(events);11261127    for (const res of result) {1128      expect(await api.rpc.unique.tokenProperties(collectionId, res.itemId)).not.to.be.empty;1129    }1130  });1131}11321133export async function createMultipleItemsExWithPropsExpectSuccess(sender: IKeyringPair, collectionId: number, itemsData: any) {1134  await usingApi(async (api) => {1135    const tx = api.tx.unique.createMultipleItemsEx(collectionId, itemsData);11361137    const events = await submitTransactionAsync(sender, tx);1138    const result = getCreateItemsResult(events);11391140    for (const res of result) {1141      expect(await api.rpc.unique.tokenProperties(collectionId, res.itemId)).not.to.be.empty;1142    }1143  });1144}11451146export async function createItemWithPropsExpectSuccess(sender: IKeyringPair, collectionId: number, createMode: string, props:  Array<Property>, owner: CrossAccountId | string = sender.address) {1147  let newItemId = 0;1148  await usingApi(async (api) => {1149    const to = normalizeAccountId(owner);1150    const itemCountBefore = await getLastTokenId(api, collectionId);1151    const itemBalanceBefore = await getBalance(api, collectionId, to, newItemId);11521153    let tx;1154    if (createMode === 'Fungible') {1155      const createData = {fungible: {value: 10}};1156      tx = api.tx.unique.createItem(collectionId, to, createData as any);1157    } else if (createMode === 'ReFungible') {1158      const createData = {refungible: {pieces: 100}};1159      tx = api.tx.unique.createItem(collectionId, to, createData as any);1160    } else {1161      const data = api.createType('UpDataStructsCreateItemData', {NFT: {properties: props}});1162      tx = api.tx.unique.createItem(collectionId, to, data as UpDataStructsCreateItemData);1163    }11641165    const events = await submitTransactionAsync(sender, tx);1166    const result = getCreateItemResult(events);11671168    const itemCountAfter = await getLastTokenId(api, collectionId);1169    const itemBalanceAfter = await getBalance(api, collectionId, to, newItemId);11701171    if (createMode === 'NFT') {1172      expect(await api.rpc.unique.tokenProperties(collectionId, result.itemId)).not.to.be.empty;1173    }11741175    // What to expect1176    // tslint:disable-next-line:no-unused-expression1177    expect(result.success).to.be.true;1178    if (createMode === 'Fungible') {1179      expect(itemBalanceAfter - itemBalanceBefore).to.be.equal(10n);1180    } else {1181      expect(itemCountAfter).to.be.equal(itemCountBefore + 1);1182    }1183    expect(collectionId).to.be.equal(result.collectionId);1184    expect(itemCountAfter.toString()).to.be.equal(result.itemId.toString());1185    expect(to).to.be.deep.equal(result.recipient);1186    newItemId = result.itemId;1187  });1188  return newItemId;1189}11901191export async function createItemWithPropsExpectFailure(sender: IKeyringPair, collectionId: number, createMode: string, props: Array<Property>, owner: CrossAccountId | string = sender.address) {1192  await usingApi(async (api) => {11931194    let tx;1195    if (createMode === 'NFT') {1196      const data = api.createType('UpDataStructsCreateItemData', {NFT: {properties: props}});1197      tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), data);1198    } else {1199      tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), createMode);1200    }120112021203    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1204    if(events.message && events.message.toString().indexOf('1002: Verification Error') > -1) return;1205    const result = getCreateItemResult(events);12061207    expect(result.success).to.be.false;1208  });1209}12101211export async function createItemExpectSuccess(sender: IKeyringPair, collectionId: number, createMode: string, owner: CrossAccountId | string = sender.address) {1212  let newItemId = 0;1213  await usingApi(async (api) => {1214    const to = normalizeAccountId(owner);1215    const itemCountBefore = await getLastTokenId(api, collectionId);1216    const itemBalanceBefore = await getBalance(api, collectionId, to, newItemId);12171218    let tx;1219    if (createMode === 'Fungible') {1220      const createData = {fungible: {value: 10}};1221      tx = api.tx.unique.createItem(collectionId, to, createData as any);1222    } else if (createMode === 'ReFungible') {1223      const createData = {refungible: {pieces: 100}};1224      tx = api.tx.unique.createItem(collectionId, to, createData as any);1225    } else {1226      const createData = {nft: {}};1227      tx = api.tx.unique.createItem(collectionId, to, createData as any);1228    }12291230    const events = await submitTransactionAsync(sender, tx);1231    const result = getCreateItemResult(events);12321233    const itemCountAfter = await getLastTokenId(api, collectionId);1234    const itemBalanceAfter = await getBalance(api, collectionId, to, newItemId);12351236    // What to expect1237    // tslint:disable-next-line:no-unused-expression1238    expect(result.success).to.be.true;1239    if (createMode === 'Fungible') {1240      expect(itemBalanceAfter - itemBalanceBefore).to.be.equal(10n);1241    } else {1242      expect(itemCountAfter).to.be.equal(itemCountBefore + 1);1243    }1244    expect(collectionId).to.be.equal(result.collectionId);1245    expect(itemCountAfter.toString()).to.be.equal(result.itemId.toString());1246    expect(to).to.be.deep.equal(result.recipient);1247    newItemId = result.itemId;1248  });1249  return newItemId;1250}12511252export async function createItemExpectFailure(sender: IKeyringPair, collectionId: number, createMode: string, owner: CrossAccountId | string = sender.address) {1253  await usingApi(async (api) => {1254    const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), createMode);12551256    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1257    const result = getCreateItemResult(events);12581259    expect(result.success).to.be.false;1260  });1261}12621263export async function setPublicAccessModeExpectSuccess(1264  sender: IKeyringPair, collectionId: number,1265  accessMode: 'Normal' | 'AllowList',1266) {1267  await usingApi(async (api) => {12681269    // Run the transaction1270    const tx = api.tx.unique.setCollectionPermissions(collectionId, {access: accessMode});1271    const events = await submitTransactionAsync(sender, tx);1272    const result = getGenericResult(events);12731274    // Get the collection1275    const collection = await queryCollectionExpectSuccess(api, collectionId);12761277    // What to expect1278    // tslint:disable-next-line:no-unused-expression1279    expect(result.success).to.be.true;1280    expect(collection.permissions.access.toHuman()).to.be.equal(accessMode);1281  });1282}12831284export async function setPublicAccessModeExpectFail(1285  sender: IKeyringPair, collectionId: number,1286  accessMode: 'Normal' | 'AllowList',1287) {1288  await usingApi(async (api) => {12891290    // Run the transaction1291    const tx = api.tx.unique.setCollectionPermissions(collectionId, {access: accessMode});1292    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1293    const result = getGenericResult(events);12941295    // What to expect1296    // tslint:disable-next-line:no-unused-expression1297    expect(result.success).to.be.false;1298  });1299}13001301export async function enableAllowListExpectSuccess(sender: IKeyringPair, collectionId: number) {1302  await setPublicAccessModeExpectSuccess(sender, collectionId, 'AllowList');1303}13041305export async function enableAllowListExpectFail(sender: IKeyringPair, collectionId: number) {1306  await setPublicAccessModeExpectFail(sender, collectionId, 'AllowList');1307}13081309export async function disableAllowListExpectSuccess(sender: IKeyringPair, collectionId: number) {1310  await setPublicAccessModeExpectSuccess(sender, collectionId, 'Normal');1311}13121313export async function setMintPermissionExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {1314  await usingApi(async (api) => {13151316    // Run the transaction1317    const tx = api.tx.unique.setCollectionPermissions(collectionId, {mintMode: enabled});1318    const events = await submitTransactionAsync(sender, tx);1319    const result = getGenericResult(events);1320    expect(result.success).to.be.true;13211322    // Get the collection1323    const collection = await queryCollectionExpectSuccess(api, collectionId);13241325    expect(collection.permissions.mintMode.toHuman()).to.be.equal(enabled);1326  });1327}13281329export async function enablePublicMintingExpectSuccess(sender: IKeyringPair, collectionId: number) {1330  await setMintPermissionExpectSuccess(sender, collectionId, true);1331}13321333export async function setMintPermissionExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {1334  await usingApi(async (api) => {1335    // Run the transaction1336    const tx = api.tx.unique.setCollectionPermissions(collectionId, {mintMode: enabled});1337    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1338    const result = getCreateCollectionResult(events);1339    // tslint:disable-next-line:no-unused-expression1340    expect(result.success).to.be.false;1341  });1342}13431344export async function setChainLimitsExpectFailure(sender: IKeyringPair, limits: IChainLimits) {1345  await usingApi(async (api) => {1346    // Run the transaction1347    const tx = api.tx.unique.setChainLimits(limits);1348    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1349    const result = getCreateCollectionResult(events);1350    // tslint:disable-next-line:no-unused-expression1351    expect(result.success).to.be.false;1352  });1353}13541355export async function isAllowlisted(api: ApiPromise, collectionId: number, address: string | CrossAccountId) {1356  return (await api.rpc.unique.allowed(collectionId, normalizeAccountId(address))).toJSON();1357}13581359export async function addToAllowListExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId | CrossAccountId) {1360  await usingApi(async (api) => {1361    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.false;13621363    // Run the transaction1364    const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1365    const events = await submitTransactionAsync(sender, tx);1366    const result = getGenericResult(events);1367    expect(result.success).to.be.true;13681369    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;1370  });1371}13721373export async function addToAllowListAgainExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId) {1374  await usingApi(async (api) => {13751376    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;13771378    // Run the transaction1379    const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1380    const events = await submitTransactionAsync(sender, tx);1381    const result = getGenericResult(events);1382    expect(result.success).to.be.true;13831384    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;1385  });1386}13871388export async function addToAllowListExpectFail(sender: IKeyringPair, collectionId: number, address: string | AccountId) {1389  await usingApi(async (api) => {13901391    // Run the transaction1392    const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1393    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1394    const result = getGenericResult(events);13951396    // What to expect1397    // tslint:disable-next-line:no-unused-expression1398    expect(result.success).to.be.false;1399  });1400}14011402export async function removeFromAllowListExpectSuccess(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1403  await usingApi(async (api) => {1404    // Run the transaction1405    const tx = api.tx.unique.removeFromAllowList(collectionId, normalizeAccountId(address));1406    const events = await submitTransactionAsync(sender, tx);1407    const result = getGenericResult(events);14081409    // What to expect1410    // tslint:disable-next-line:no-unused-expression1411    expect(result.success).to.be.true;1412  });1413}14141415export async function removeFromAllowListExpectFailure(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1416  await usingApi(async (api) => {1417    // Run the transaction1418    const tx = api.tx.unique.removeFromAllowList(collectionId, normalizeAccountId(address));1419    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1420    const result = getGenericResult(events);14211422    // What to expect1423    // tslint:disable-next-line:no-unused-expression1424    expect(result.success).to.be.false;1425  });1426}14271428export const getDetailedCollectionInfo = async (api: ApiPromise, collectionId: number)1429  : Promise<UpDataStructsRpcCollection | null> => {1430  return (await api.rpc.unique.collectionById(collectionId)).unwrapOr(null);1431};14321433export const getCreatedCollectionCount = async (api: ApiPromise): Promise<number> => {1434  // set global object - collectionsCount1435  return (await api.rpc.unique.collectionStats()).created.toNumber();1436};14371438export async function queryCollectionExpectSuccess(api: ApiPromise, collectionId: number): Promise<UpDataStructsRpcCollection> {1439  return (await api.rpc.unique.collectionById(collectionId)).unwrap();1440}14411442export async function waitNewBlocks(blocksCount = 1): Promise<void> {1443  await usingApi(async (api) => {1444    const promise = new Promise<void>(async (resolve) => {1445      const unsubscribe = await api.rpc.chain.subscribeNewHeads(() => {1446        if (blocksCount > 0) {1447          blocksCount--;1448        } else {1449          unsubscribe();1450          resolve();1451        }1452      });1453    });1454    return promise;1455  });1456}