git.delta.rocks / unique-network / refs/commits / 3b5acf80d0a1

difftreelog

source

tests/src/util/helpers.ts54.5 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 privateKey from '../substrate/privateKey';28import {default as usingApi, executeTransaction, submitTransactionAsync, submitTransactionExpectFailAsync} from '../substrate/substrate-api';29import {hexToStr, strToUTF16, utf16ToStr} from './util';30import {UpDataStructsRpcCollection, UpDataStructsCreateItemData, UpDataStructsProperty} from '@polkadot/types/lookup';3132chai.use(chaiAsPromised);33const expect = chai.expect;3435export type CrossAccountId = {36  Substrate: string,37} | {38  Ethereum: string,39};4041export function normalizeAccountId(input: string | AccountId | CrossAccountId | IKeyringPair): CrossAccountId {42  if (typeof input === 'string') {43    if (input.length === 48 || input.length === 47) {44      return {Substrate: input};45    } else if (input.length === 42 && input.startsWith('0x')) {46      return {Ethereum: input.toLowerCase()};47    } else if (input.length === 40 && !input.startsWith('0x')) {48      return {Ethereum: '0x' + input.toLowerCase()};49    } else {50      throw new Error(`Unknown address format: "${input}"`);51    }52  }53  if ('address' in input) {54    return {Substrate: input.address};55  }56  if ('Ethereum' in input) {57    return {58      Ethereum: input.Ethereum.toLowerCase(),59    };60  } else if ('ethereum' in input) {61    return {62      Ethereum: (input as any).ethereum.toLowerCase(),63    };64  } else if ('Substrate' in input) {65    return input;66  } else if ('substrate' in input) {67    return {68      Substrate: (input as any).substrate,69    };70  }7172  // AccountId73  return {Substrate: input.toString()};74}75export function toSubstrateAddress(input: string | CrossAccountId | IKeyringPair): string {76  input = normalizeAccountId(input);77  if ('Substrate' in input) {78    return input.Substrate;79  } else {80    return evmToAddress(input.Ethereum);81  }82}8384export const U128_MAX = (1n << 128n) - 1n;8586const MICROUNIQUE = 1_000_000_000_000n;87const MILLIUNIQUE = 1_000n * MICROUNIQUE;88const CENTIUNIQUE = 10n * MILLIUNIQUE;89export const UNIQUE = 100n * CENTIUNIQUE;9091type GenericResult = {92  success: boolean,93};9495interface CreateCollectionResult {96  success: boolean;97  collectionId: number;98}99100interface CreateItemResult {101  success: boolean;102  collectionId: number;103  itemId: number;104  recipient?: CrossAccountId;105}106107interface TransferResult {108  collectionId: number;109  itemId: number;110  sender?: CrossAccountId;111  recipient?: CrossAccountId;112  value: bigint;113}114115interface IReFungibleOwner {116  fraction: BN;117  owner: number[];118}119120interface IGetMessage {121  checkMsgUnqMethod: string;122  checkMsgTrsMethod: string;123  checkMsgSysMethod: string;124}125126export interface IFungibleTokenDataType {127  value: number;128}129130export interface IChainLimits {131  collectionNumbersLimit: number;132  accountTokenOwnershipLimit: number;133  collectionsAdminsLimit: number;134  customDataLimit: number;135  nftSponsorTransferTimeout: number;136  fungibleSponsorTransferTimeout: number;137  refungibleSponsorTransferTimeout: number;138  //offchainSchemaLimit: number;139  //constOnChainSchemaLimit: number;140}141142export interface IReFungibleTokenDataType {143  owner: IReFungibleOwner[];144}145146export function uniqueEventMessage(events: EventRecord[]): IGetMessage {147  let checkMsgUnqMethod = '';148  let checkMsgTrsMethod = '';149  let checkMsgSysMethod = '';150  events.forEach(({event: {method, section}}) => {151    if (section === 'common') {152      checkMsgUnqMethod = method;153    } else if (section === 'treasury') {154      checkMsgTrsMethod = method;155    } else if (section === 'system') {156      checkMsgSysMethod = method;157    } else { return null; }158  });159  const result: IGetMessage = {160    checkMsgUnqMethod,161    checkMsgTrsMethod,162    checkMsgSysMethod,163  };164  return result;165}166167export function getEvent<T extends Event>(events: EventRecord[], check: (event: IEvent<AnyTuple>) => event is T): T | undefined {168  const event = events.find(r => check(r.event));169  if (!event) return;170  return event.event as T;171}172173export function getGenericResult(events: EventRecord[]): GenericResult {174  const result: GenericResult = {175    success: false,176  };177  events.forEach(({event: {method}}) => {178    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);179    if (method === 'ExtrinsicSuccess') {180      result.success = true;181    }182  });183  return result;184}185186187188export function getCreateCollectionResult(events: EventRecord[]): CreateCollectionResult {189  let success = false;190  let collectionId = 0;191  events.forEach(({event: {data, method, section}}) => {192    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);193    if (method == 'ExtrinsicSuccess') {194      success = true;195    } else if ((section == 'common') && (method == 'CollectionCreated')) {196      collectionId = parseInt(data[0].toString(), 10);197    }198  });199  const result: CreateCollectionResult = {200    success,201    collectionId,202  };203  return result;204}205206export function getCreateItemsResult(events: EventRecord[]): CreateItemResult[] {207  let success = false;208  let collectionId = 0;209  let itemId = 0;210  let recipient;211212  const results : CreateItemResult[]  = [];213214  events.forEach(({event: {data, method, section}}) => {215    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);216    if (method == 'ExtrinsicSuccess') {217      success = true;218    } else if ((section == 'common') && (method == 'ItemCreated')) {219      collectionId = parseInt(data[0].toString(), 10);220      itemId = parseInt(data[1].toString(), 10);221      recipient = normalizeAccountId(data[2].toJSON() as any);222223      const itemRes: CreateItemResult = {224        success,225        collectionId,226        itemId,227        recipient,228      };229230      results.push(itemRes);231    }232  });233234  return results;235}236237export function getCreateItemResult(events: EventRecord[]): CreateItemResult {238  let success = false;239  let collectionId = 0;240  let itemId = 0;241  let recipient;242  events.forEach(({event: {data, method, section}}) => {243    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);244    if (method == 'ExtrinsicSuccess') {245      success = true;246    } else if ((section == 'common') && (method == 'ItemCreated')) {247      collectionId = parseInt(data[0].toString(), 10);248      itemId = parseInt(data[1].toString(), 10);249      recipient = normalizeAccountId(data[2].toJSON() as any);250    }251  });252  const result: CreateItemResult = {253    success,254    collectionId,255    itemId,256    recipient,257  };258  return result;259}260261export function getTransferResult(api: ApiPromise, events: EventRecord[]): TransferResult {262  for (const {event} of events) {263    if (api.events.common.Transfer.is(event)) {264      const [collection, token, sender, recipient, value] = event.data;265      return {266        collectionId: collection.toNumber(),267        itemId: token.toNumber(),268        sender: normalizeAccountId(sender.toJSON() as any),269        recipient: normalizeAccountId(recipient.toJSON() as any),270        value: value.toBigInt(),271      };272    }273  }274  throw new Error('no transfer event');275}276277interface Nft {278  type: 'NFT';279}280281interface Fungible {282  type: 'Fungible';283  decimalPoints: number;284}285286interface ReFungible {287  type: 'ReFungible';288}289290type CollectionMode = Nft | Fungible | ReFungible;291292export type Property = {293  key: any,294  value: any,295};296297type Permission = {298  mutable: boolean;299  collectionAdmin: boolean;300  tokenOwner: boolean;301}302303type PropertyPermission = {304  key: any;305  permission: Permission;306}307308export type CreateCollectionParams = {309  mode: CollectionMode,310  name: string,311  description: string,312  tokenPrefix: string,313  properties?: Array<Property>,314  propPerm?: Array<PropertyPermission>315};316317const defaultCreateCollectionParams: CreateCollectionParams = {318  description: 'description',319  mode: {type: 'NFT'},320  name: 'name',321  tokenPrefix: 'prefix',322};323324export async function createCollectionExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {325  const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};326327  let collectionId = 0;328  await usingApi(async (api) => {329    // Get number of collections before the transaction330    const collectionCountBefore = await getCreatedCollectionCount(api);331332    // Run the CreateCollection transaction333    const alicePrivateKey = privateKey('//Alice');334335    let modeprm = {};336    if (mode.type === 'NFT') {337      modeprm = {nft: null};338    } else if (mode.type === 'Fungible') {339      modeprm = {fungible: mode.decimalPoints};340    } else if (mode.type === 'ReFungible') {341      modeprm = {refungible: null};342    }343344    const tx = api.tx.unique.createCollectionEx({345      name: strToUTF16(name),346      description: strToUTF16(description),347      tokenPrefix: strToUTF16(tokenPrefix),348      mode: modeprm as any,349    });350    const events = await submitTransactionAsync(alicePrivateKey, tx);351    const result = getCreateCollectionResult(events);352353    // Get number of collections after the transaction354    const collectionCountAfter = await getCreatedCollectionCount(api);355356    // Get the collection357    const collection = await queryCollectionExpectSuccess(api, result.collectionId);358359    // What to expect360    // tslint:disable-next-line:no-unused-expression361    expect(result.success).to.be.true;362    expect(result.collectionId).to.be.equal(collectionCountAfter);363    // tslint:disable-next-line:no-unused-expression364    expect(collection).to.be.not.null;365    expect(collectionCountAfter).to.be.equal(collectionCountBefore + 1, 'Error: NFT collection NOT created.');366    expect(collection.owner.toString()).to.be.equal(toSubstrateAddress(alicesPublicKey));367    expect(utf16ToStr(collection.name.toJSON() as any)).to.be.equal(name);368    expect(utf16ToStr(collection.description.toJSON() as any)).to.be.equal(description);369    expect(hexToStr(collection.tokenPrefix.toJSON())).to.be.equal(tokenPrefix);370371    collectionId = result.collectionId;372  });373374  return collectionId;375}376377export async function createCollectionWithPropsExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {378  const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};379380  let collectionId = 0;381  await usingApi(async (api) => {382    // Get number of collections before the transaction383    const collectionCountBefore = await getCreatedCollectionCount(api);384385    // Run the CreateCollection transaction386    const alicePrivateKey = privateKey('//Alice');387388    let modeprm = {};389    if (mode.type === 'NFT') {390      modeprm = {nft: null};391    } else if (mode.type === 'Fungible') {392      modeprm = {fungible: mode.decimalPoints};393    } else if (mode.type === 'ReFungible') {394      modeprm = {refungible: null};395    }396397    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});398    const events = await submitTransactionAsync(alicePrivateKey, tx);399    const result = getCreateCollectionResult(events);400401    // Get number of collections after the transaction402    const collectionCountAfter = await getCreatedCollectionCount(api);403404    // Get the collection405    const collection = await queryCollectionExpectSuccess(api, result.collectionId);406407    // What to expect408    // tslint:disable-next-line:no-unused-expression409    expect(result.success).to.be.true;410    expect(result.collectionId).to.be.equal(collectionCountAfter);411    // tslint:disable-next-line:no-unused-expression412    expect(collection).to.be.not.null;413    expect(collectionCountAfter).to.be.equal(collectionCountBefore + 1, 'Error: NFT collection NOT created.');414    expect(collection.owner.toString()).to.be.equal(toSubstrateAddress(alicesPublicKey));415    expect(utf16ToStr(collection.name.toJSON() as any)).to.be.equal(name);416    expect(utf16ToStr(collection.description.toJSON() as any)).to.be.equal(description);417    expect(hexToStr(collection.tokenPrefix.toJSON())).to.be.equal(tokenPrefix);418419420    collectionId = result.collectionId;421  });422423  return collectionId;424}425426export async function createCollectionWithPropsExpectFailure(params: Partial<CreateCollectionParams> = {}) {427  const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};428429  await usingApi(async (api) => {430    // Get number of collections before the transaction431    const collectionCountBefore = await getCreatedCollectionCount(api);432433    // Run the CreateCollection transaction434    const alicePrivateKey = privateKey('//Alice');435436    let modeprm = {};437    if (mode.type === 'NFT') {438      modeprm = {nft: null};439    } else if (mode.type === 'Fungible') {440      modeprm = {fungible: mode.decimalPoints};441    } else if (mode.type === 'ReFungible') {442      modeprm = {refungible: null};443    }444445    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});446    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;447448449    // Get number of collections after the transaction450    const collectionCountAfter = await getCreatedCollectionCount(api);451452    expect(collectionCountAfter).to.be.equal(collectionCountBefore, 'Error: Collection with incorrect data created.');453  });454}455456export async function createCollectionExpectFailure(params: Partial<CreateCollectionParams> = {}) {457  const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};458459  let modeprm = {};460  if (mode.type === 'NFT') {461    modeprm = {nft: null};462  } else if (mode.type === 'Fungible') {463    modeprm = {fungible: mode.decimalPoints};464  } else if (mode.type === 'ReFungible') {465    modeprm = {refungible: null};466  }467468  await usingApi(async (api) => {469    // Get number of collections before the transaction470    const collectionCountBefore = await getCreatedCollectionCount(api);471472    // Run the CreateCollection transaction473    const alicePrivateKey = privateKey('//Alice');474    const tx = api.tx.unique.createCollectionEx({name: strToUTF16(name), description: strToUTF16(description), tokenPrefix: strToUTF16(tokenPrefix), mode: modeprm as any});475    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;476477    // Get number of collections after the transaction478    const collectionCountAfter = await getCreatedCollectionCount(api);479480    // What to expect481    expect(collectionCountAfter).to.be.equal(collectionCountBefore, 'Error: Collection with incorrect data created.');482  });483}484485export async function findUnusedAddress(api: ApiPromise, seedAddition = ''): Promise<IKeyringPair> {486  let bal = 0n;487  let unused;488  do {489    const randomSeed = 'seed' + Math.floor(Math.random() * Math.floor(10000)) + seedAddition;490    const keyring = new Keyring({type: 'sr25519'});491    unused = keyring.addFromUri(`//${randomSeed}`);492    bal = (await api.query.system.account(unused.address)).data.free.toBigInt();493  } while (bal !== 0n);494  return unused;495}496497export async function getAllowance(api: ApiPromise, collectionId: number, owner: CrossAccountId | string, approved: CrossAccountId | string, tokenId: number) {498  return (await api.rpc.unique.allowance(collectionId, normalizeAccountId(owner), normalizeAccountId(approved), tokenId)).toBigInt();499}500501export function findUnusedAddresses(api: ApiPromise, amount: number): Promise<IKeyringPair[]> {502  return Promise.all(new Array(amount).fill(null).map(() => findUnusedAddress(api, '_' + Date.now())));503}504505export async function findNotExistingCollection(api: ApiPromise): Promise<number> {506  const totalNumber = await getCreatedCollectionCount(api);507  const newCollection: number = totalNumber + 1;508  return newCollection;509}510511function getDestroyResult(events: EventRecord[]): boolean {512  let success = false;513  events.forEach(({event: {method}}) => {514    if (method == 'ExtrinsicSuccess') {515      success = true;516    }517  });518  return success;519}520521export async function destroyCollectionExpectFailure(collectionId: number, senderSeed = '//Alice') {522  await usingApi(async (api) => {523    // Run the DestroyCollection transaction524    const alicePrivateKey = privateKey(senderSeed);525    const tx = api.tx.unique.destroyCollection(collectionId);526    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;527  });528}529530export async function destroyCollectionExpectSuccess(collectionId: number, senderSeed = '//Alice') {531  await usingApi(async (api) => {532    // Run the DestroyCollection transaction533    const alicePrivateKey = privateKey(senderSeed);534    const tx = api.tx.unique.destroyCollection(collectionId);535    const events = await submitTransactionAsync(alicePrivateKey, tx);536    const result = getDestroyResult(events);537    expect(result).to.be.true;538539    // What to expect540    expect(await getDetailedCollectionInfo(api, collectionId)).to.be.null;541  });542}543544export async function setCollectionLimitsExpectSuccess(sender: IKeyringPair, collectionId: number, limits: any) {545  await usingApi(async (api) => {546    const tx = api.tx.unique.setCollectionLimits(collectionId, limits);547    const events = await submitTransactionAsync(sender, tx);548    const result = getGenericResult(events);549550    expect(result.success).to.be.true;551  });552}553554export const setCollectionPermissionsExpectSuccess = async (sender: IKeyringPair, collectionId: number, permissions: {mintMode?: boolean, access?: 'Normal' | 'AllowList', nesting?: 'Disabled' | 'Owner' | {OwnerRestricted: number[]}}) => {555  await usingApi(async(api) => {556    const tx = api.tx.unique.setCollectionPermissions(collectionId, permissions);557    const events = await submitTransactionAsync(sender, tx);558    const result = getGenericResult(events);559560    expect(result.success).to.be.true;561  });562};563564export async function setCollectionLimitsExpectFailure(sender: IKeyringPair, collectionId: number, limits: any) {565  await usingApi(async (api) => {566    const tx = api.tx.unique.setCollectionLimits(collectionId, limits);567    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;568    const result = getGenericResult(events);569570    expect(result.success).to.be.false;571  });572}573574export async function setCollectionSponsorExpectSuccess(collectionId: number, sponsor: string, sender = '//Alice') {575  await usingApi(async (api) => {576577    // Run the transaction578    const senderPrivateKey = privateKey(sender);579    const tx = api.tx.unique.setCollectionSponsor(collectionId, sponsor);580    const events = await submitTransactionAsync(senderPrivateKey, tx);581    const result = getGenericResult(events);582583    // Get the collection584    const collection = await queryCollectionExpectSuccess(api, collectionId);585586    // What to expect587    expect(result.success).to.be.true;588    expect(collection.sponsorship.toJSON()).to.deep.equal({589      unconfirmed: sponsor,590    });591  });592}593594export async function removeCollectionSponsorExpectSuccess(collectionId: number, sender = '//Alice') {595  await usingApi(async (api) => {596597    // Run the transaction598    const alicePrivateKey = privateKey(sender);599    const tx = api.tx.unique.removeCollectionSponsor(collectionId);600    const events = await submitTransactionAsync(alicePrivateKey, tx);601    const result = getGenericResult(events);602603    // Get the collection604    const collection = await queryCollectionExpectSuccess(api, collectionId);605606    // What to expect607    expect(result.success).to.be.true;608    expect(collection.sponsorship.toJSON()).to.be.deep.equal({disabled: null});609  });610}611612export async function removeCollectionSponsorExpectFailure(collectionId: number, senderSeed = '//Alice') {613  await usingApi(async (api) => {614615    // Run the transaction616    const alicePrivateKey = privateKey(senderSeed);617    const tx = api.tx.unique.removeCollectionSponsor(collectionId);618    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;619  });620}621622export async function setCollectionSponsorExpectFailure(collectionId: number, sponsor: string, senderSeed = '//Alice') {623  await usingApi(async (api) => {624625    // Run the transaction626    const alicePrivateKey = privateKey(senderSeed);627    const tx = api.tx.unique.setCollectionSponsor(collectionId, sponsor);628    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;629  });630}631632export async function confirmSponsorshipExpectSuccess(collectionId: number, senderSeed = '//Alice') {633  await usingApi(async () => {634    const sender = privateKey(senderSeed);635    await confirmSponsorshipByKeyExpectSuccess(collectionId, sender);636  });637}638639export async function confirmSponsorshipByKeyExpectSuccess(collectionId: number, sender: IKeyringPair) {640  await usingApi(async (api) => {641642    // Run the transaction643    const tx = api.tx.unique.confirmSponsorship(collectionId);644    const events = await submitTransactionAsync(sender, tx);645    const result = getGenericResult(events);646647    // Get the collection648    const collection = await queryCollectionExpectSuccess(api, collectionId);649650    // What to expect651    expect(result.success).to.be.true;652    expect(collection.sponsorship.toJSON()).to.be.deep.equal({653      confirmed: sender.address,654    });655  });656}657658659export async function confirmSponsorshipExpectFailure(collectionId: number, senderSeed = '//Alice') {660  await usingApi(async (api) => {661662    // Run the transaction663    const sender = privateKey(senderSeed);664    const tx = api.tx.unique.confirmSponsorship(collectionId);665    await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;666  });667}668669export async function enableContractSponsoringExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {670  await usingApi(async (api) => {671    const tx = api.tx.unique.enableContractSponsoring(contractAddress, enable);672    const events = await submitTransactionAsync(sender, tx);673    const result = getGenericResult(events);674675    expect(result.success).to.be.true;676  });677}678679export async function enableContractSponsoringExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {680  await usingApi(async (api) => {681    const tx = api.tx.unique.enableContractSponsoring(contractAddress, enable);682    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;683    const result = getGenericResult(events);684685    expect(result.success).to.be.false;686  });687}688689export async function setTransferFlagExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {690691  await usingApi(async (api) => {692693    const tx = api.tx.unique.setTransfersEnabledFlag(collectionId, enabled);694    const events = await submitTransactionAsync(sender, tx);695    const result = getGenericResult(events);696697    expect(result.success).to.be.true;698  });699}700701export async function setTransferFlagExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {702703  await usingApi(async (api) => {704705    const tx = api.tx.unique.setTransfersEnabledFlag(collectionId, enabled);706    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;707    const result = getGenericResult(events);708709    expect(result.success).to.be.false;710  });711}712713export async function setContractSponsoringRateLimitExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {714  await usingApi(async (api) => {715    const tx = api.tx.unique.setContractSponsoringRateLimit(contractAddress, rateLimit);716    const events = await submitTransactionAsync(sender, tx);717    const result = getGenericResult(events);718719    expect(result.success).to.be.true;720  });721}722723export async function setContractSponsoringRateLimitExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {724  await usingApi(async (api) => {725    const tx = api.tx.unique.setContractSponsoringRateLimit(contractAddress, rateLimit);726    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;727    const result = getGenericResult(events);728729    expect(result.success).to.be.false;730  });731}732733export async function getNextSponsored(734  api: ApiPromise,735  collectionId: number,736  account: string | CrossAccountId,737  tokenId: number,738): Promise<number> {739  return Number((await api.rpc.unique.nextSponsored(collectionId, account, tokenId)).unwrapOr(-1));740}741742export async function toggleContractAllowlistExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, value = true) {743  await usingApi(async (api) => {744    const tx = api.tx.unique.toggleContractAllowList(contractAddress, value);745    const events = await submitTransactionAsync(sender, tx);746    const result = getGenericResult(events);747748    expect(result.success).to.be.true;749  });750}751752export async function isAllowlistedInContract(contractAddress: AccountId | string, user: string) {753  let allowlisted = false;754  await usingApi(async (api) => {755    allowlisted = (await api.query.unique.contractAllowList(contractAddress, user)).toJSON() as boolean;756  });757  return allowlisted;758}759760export async function addToContractAllowListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {761  await usingApi(async (api) => {762    const tx = api.tx.unique.addToContractAllowList(contractAddress.toString(), user.toString());763    const events = await submitTransactionAsync(sender, tx);764    const result = getGenericResult(events);765766    expect(result.success).to.be.true;767  });768}769770export async function removeFromContractAllowListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {771  await usingApi(async (api) => {772    const tx = api.tx.unique.removeFromContractAllowList(contractAddress.toString(), user.toString());773    const events = await submitTransactionAsync(sender, tx);774    const result = getGenericResult(events);775776    expect(result.success).to.be.true;777  });778}779780export async function removeFromContractAllowListExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {781  await usingApi(async (api) => {782    const tx = api.tx.unique.removeFromContractAllowList(contractAddress.toString(), user.toString());783    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;784    const result = getGenericResult(events);785786    expect(result.success).to.be.false;787  });788}789790export interface CreateFungibleData {791  readonly Value: bigint;792}793794export interface CreateReFungibleData { }795export interface CreateNftData { }796797export type CreateItemData = {798  NFT: CreateNftData;799} | {800  Fungible: CreateFungibleData;801} | {802  ReFungible: CreateReFungibleData;803};804805export async function burnItemExpectSuccess(sender: IKeyringPair, collectionId: number, tokenId: number, value = 1) {806  await usingApi(async (api) => {807    const balanceBefore = await getBalance(api, collectionId, normalizeAccountId(sender), tokenId);808    // if burning token by admin - use adminButnItemExpectSuccess809    expect(balanceBefore >= BigInt(value)).to.be.true;810811    const tx = api.tx.unique.burnItem(collectionId, tokenId, value);812    const events = await submitTransactionAsync(sender, tx);813    const result = getGenericResult(events);814    expect(result.success).to.be.true;815816    const balanceAfter = await getBalance(api, collectionId, normalizeAccountId(sender), tokenId);817    expect(balanceAfter + BigInt(value)).to.be.equal(balanceBefore);818  });819}820821export async function822approveExpectSuccess(823  collectionId: number,824  tokenId: number, owner: IKeyringPair, approved: CrossAccountId | string, amount: number | bigint = 1,825) {826  await usingApi(async (api: ApiPromise) => {827    const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);828    const events = await submitTransactionAsync(owner, approveUniqueTx);829    const result = getGenericResult(events);830    expect(result.success).to.be.true;831832    expect(await getAllowance(api, collectionId, owner.address, approved, tokenId)).to.be.equal(BigInt(amount));833  });834}835836export async function adminApproveFromExpectSuccess(837  collectionId: number,838  tokenId: number, admin: IKeyringPair, owner: CrossAccountId | string, approved: CrossAccountId | string, amount: number | bigint = 1,839) {840  await usingApi(async (api: ApiPromise) => {841    const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);842    const events = await submitTransactionAsync(admin, approveUniqueTx);843    const result = getGenericResult(events);844    expect(result.success).to.be.true;845846    expect(await getAllowance(api, collectionId, owner, approved, tokenId)).to.be.equal(BigInt(amount));847  });848}849850export async function851transferFromExpectSuccess(852  collectionId: number,853  tokenId: number,854  accountApproved: IKeyringPair,855  accountFrom: IKeyringPair | CrossAccountId,856  accountTo: IKeyringPair | CrossAccountId,857  value: number | bigint = 1,858  type = 'NFT',859) {860  await usingApi(async (api: ApiPromise) => {861    const from = normalizeAccountId(accountFrom);862    const to = normalizeAccountId(accountTo);863    let balanceBefore = 0n;864    if (type === 'Fungible' || type === 'ReFungible') {865      balanceBefore = await getBalance(api, collectionId, to, tokenId);866    }867    const transferFromTx = api.tx.unique.transferFrom(normalizeAccountId(accountFrom), to, collectionId, tokenId, value);868    const events = await submitTransactionAsync(accountApproved, transferFromTx);869    const result = getCreateItemResult(events);870    // tslint:disable-next-line:no-unused-expression871    expect(result.success).to.be.true;872    if (type === 'NFT') {873      expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(to);874    }875    if (type === 'Fungible') {876      const balanceAfter = await getBalance(api, collectionId, to, tokenId);877      if (JSON.stringify(to) !== JSON.stringify(from)) {878        expect(balanceAfter - balanceBefore).to.be.equal(BigInt(value));879      } else {880        expect(balanceAfter).to.be.equal(balanceBefore);881      }882    }883    if (type === 'ReFungible') {884      expect(await getBalance(api, collectionId, to, tokenId)).to.be.equal(balanceBefore + BigInt(value));885    }886  });887}888889export async function890transferFromExpectFail(891  collectionId: number,892  tokenId: number,893  accountApproved: IKeyringPair,894  accountFrom: IKeyringPair,895  accountTo: IKeyringPair,896  value: number | bigint = 1,897) {898  await usingApi(async (api: ApiPromise) => {899    const transferFromTx = api.tx.unique.transferFrom(normalizeAccountId(accountFrom.address), normalizeAccountId(accountTo.address), collectionId, tokenId, value);900    const events = await expect(submitTransactionExpectFailAsync(accountApproved, transferFromTx)).to.be.rejected;901    const result = getCreateCollectionResult(events);902    // tslint:disable-next-line:no-unused-expression903    expect(result.success).to.be.false;904  });905}906907/* eslint no-async-promise-executor: "off" */908export async function getBlockNumber(api: ApiPromise): Promise<number> {909  return new Promise<number>(async (resolve) => {910    const unsubscribe = await api.rpc.chain.subscribeNewHeads((head) => {911      unsubscribe();912      resolve(head.number.toNumber());913    });914  });915}916917export async function addCollectionAdminExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | CrossAccountId) {918  await usingApi(async (api) => {919    const changeAdminTx = api.tx.unique.addCollectionAdmin(collectionId, normalizeAccountId(address));920    const events = await submitTransactionAsync(sender, changeAdminTx);921    const result = getCreateCollectionResult(events);922    expect(result.success).to.be.true;923  });924}925926export async function927getFreeBalance(account: IKeyringPair): Promise<bigint> {928  let balance = 0n;929  await usingApi(async (api) => {930    balance = BigInt((await api.query.system.account(account.address)).data.free.toString());931  });932933  return balance;934}935936export async function transferBalanceTo(api: ApiPromise, source: IKeyringPair, target: string, amount = 1000n * UNIQUE) {937  const tx = api.tx.balances.transfer(target, amount);938  const events = await submitTransactionAsync(source, tx);939  const result = getGenericResult(events);940  expect(result.success).to.be.true;941}942943export async function944scheduleExpectSuccess(945  operationTx: any,946  sender: IKeyringPair,947  blockSchedule: number,948  scheduledId: string,949  period = 1,950  repetitions = 1,951) {952  await usingApi(async (api: ApiPromise) => {953    const blockNumber: number | undefined = await getBlockNumber(api);954    const expectedBlockNumber = blockNumber + blockSchedule;955956    expect(blockNumber).to.be.greaterThan(0);957    const scheduleTx = api.tx.scheduler.scheduleNamed( // schedule958      scheduledId,959      expectedBlockNumber, 960      repetitions > 1 ? [period, repetitions] : null, 961      0, 962      {value: operationTx as any},963    );964965    const events = await submitTransactionAsync(sender, scheduleTx);966    expect(getGenericResult(events).success).to.be.true;967  });968}969970export async function971scheduleExpectFailure(972  operationTx: any,973  sender: IKeyringPair,974  blockSchedule: number,975  scheduledId: string,976  period = 1,977  repetitions = 1,978) {979  await usingApi(async (api: ApiPromise) => {980    const blockNumber: number | undefined = await getBlockNumber(api);981    const expectedBlockNumber = blockNumber + blockSchedule;982983    expect(blockNumber).to.be.greaterThan(0);984    const scheduleTx = api.tx.scheduler.scheduleNamed( // schedule985      scheduledId,986      expectedBlockNumber, 987      repetitions <= 1 ? null : [period, repetitions], 988      0, 989      {value: operationTx as any},990    );991992    //const events = 993    await expect(submitTransactionExpectFailAsync(sender, scheduleTx)).to.be.rejected;994    //expect(getGenericResult(events).success).to.be.false;995  });996}997998export async function999scheduleTransferAndWaitExpectSuccess(1000  collectionId: number,1001  tokenId: number,1002  sender: IKeyringPair,1003  recipient: IKeyringPair,1004  value: number | bigint = 1,1005  blockSchedule: number,1006  scheduledId: string,1007) {1008  await usingApi(async (api: ApiPromise) => {1009    await scheduleTransferExpectSuccess(collectionId, tokenId, sender, recipient, value, blockSchedule, scheduledId);10101011    const recipientBalanceBefore = (await api.query.system.account(recipient.address)).data.free.toBigInt();10121013    // sleep for n + 1 blocks1014    await waitNewBlocks(blockSchedule + 1);10151016    const recipientBalanceAfter = (await api.query.system.account(recipient.address)).data.free.toBigInt();10171018    expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(recipient.address));1019    expect(recipientBalanceAfter).to.be.equal(recipientBalanceBefore);1020  });1021}10221023export async function1024scheduleTransferExpectSuccess(1025  collectionId: number,1026  tokenId: number,1027  sender: IKeyringPair,1028  recipient: IKeyringPair,1029  value: number | bigint = 1,1030  blockSchedule: number,1031  scheduledId: string,1032) {1033  await usingApi(async (api: ApiPromise) => {1034    const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient.address), collectionId, tokenId, value);10351036    await scheduleExpectSuccess(transferTx, sender, blockSchedule, scheduledId);10371038    expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(sender.address));1039  });1040}10411042export async function1043scheduleTransferFundsPeriodicExpectSuccess(1044  amount: bigint,1045  sender: IKeyringPair,1046  recipient: IKeyringPair,1047  blockSchedule: number,1048  scheduledId: string,1049  period: number,1050  repetitions: number,1051) {1052  await usingApi(async (api: ApiPromise) => {1053    const transferTx = api.tx.balances.transfer(recipient.address, amount);10541055    const balanceBefore = await getFreeBalance(recipient);1056    1057    await scheduleExpectSuccess(transferTx, sender, blockSchedule, scheduledId, period, repetitions);10581059    expect(await getFreeBalance(recipient)).to.be.equal(balanceBefore);1060  });1061}10621063export async function1064transferExpectSuccess(1065  collectionId: number,1066  tokenId: number,1067  sender: IKeyringPair,1068  recipient: IKeyringPair | CrossAccountId,1069  value: number | bigint = 1,1070  type = 'NFT',1071) {1072  await usingApi(async (api: ApiPromise) => {1073    const from = normalizeAccountId(sender);1074    const to = normalizeAccountId(recipient);10751076    let balanceBefore = 0n;1077    if (type === 'Fungible') {1078      balanceBefore = await getBalance(api, collectionId, to, tokenId);1079    }1080    const transferTx = api.tx.unique.transfer(to, collectionId, tokenId, value);1081    const events = await executeTransaction(api, sender, transferTx);10821083    const result = getTransferResult(api, events);1084    expect(result.collectionId).to.be.equal(collectionId);1085    expect(result.itemId).to.be.equal(tokenId);1086    expect(result.sender).to.be.deep.equal(normalizeAccountId(sender.address));1087    expect(result.recipient).to.be.deep.equal(to);1088    expect(result.value).to.be.equal(BigInt(value));10891090    if (type === 'NFT') {1091      expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(to);1092    }1093    if (type === 'Fungible') {1094      const balanceAfter = await getBalance(api, collectionId, to, tokenId);1095      if (JSON.stringify(to) !== JSON.stringify(from)) {1096        expect(balanceAfter - balanceBefore).to.be.equal(BigInt(value));1097      } else {1098        expect(balanceAfter).to.be.equal(balanceBefore);1099      }1100    }1101    if (type === 'ReFungible') {1102      expect(await getBalance(api, collectionId, to, tokenId) >= value).to.be.true;1103    }1104  });1105}11061107export async function1108transferExpectFailure(1109  collectionId: number,1110  tokenId: number,1111  sender: IKeyringPair,1112  recipient: IKeyringPair | CrossAccountId,1113  value: number | bigint = 1,1114) {1115  await usingApi(async (api: ApiPromise) => {1116    const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient), collectionId, tokenId, value);1117    const events = await expect(submitTransactionExpectFailAsync(sender, transferTx)).to.be.rejected;1118    const result = getGenericResult(events);1119    // if (events && Array.isArray(events)) {1120    //   const result = getCreateCollectionResult(events);1121    // tslint:disable-next-line:no-unused-expression1122    expect(result.success).to.be.false;1123    //}1124  });1125}11261127export async function1128approveExpectFail(1129  collectionId: number,1130  tokenId: number, owner: IKeyringPair, approved: IKeyringPair, amount: number | bigint = 1,1131) {1132  await usingApi(async (api: ApiPromise) => {1133    const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved.address), collectionId, tokenId, amount);1134    const events = await expect(submitTransactionExpectFailAsync(owner, approveUniqueTx)).to.be.rejected;1135    const result = getCreateCollectionResult(events);1136    // tslint:disable-next-line:no-unused-expression1137    expect(result.success).to.be.false;1138  });1139}11401141export async function getBalance(1142  api: ApiPromise,1143  collectionId: number,1144  owner: string | CrossAccountId,1145  token: number,1146): Promise<bigint> {1147  return (await api.rpc.unique.balance(collectionId, normalizeAccountId(owner), token)).toBigInt();1148}1149export async function getTokenOwner(1150  api: ApiPromise,1151  collectionId: number,1152  token: number,1153): Promise<CrossAccountId> {1154  const owner = (await api.rpc.unique.tokenOwner(collectionId, token)).toJSON() as any;1155  if (owner == null) throw new Error('owner == null');1156  return normalizeAccountId(owner);1157}1158export async function getTopmostTokenOwner(1159  api: ApiPromise,1160  collectionId: number,1161  token: number,1162): Promise<CrossAccountId> {1163  const owner = (await api.rpc.unique.topmostTokenOwner(collectionId, token)).toJSON() as any;1164  if (owner == null) throw new Error('owner == null');1165  return normalizeAccountId(owner);1166}1167export async function isTokenExists(1168  api: ApiPromise,1169  collectionId: number,1170  token: number,1171): Promise<boolean> {1172  return (await api.rpc.unique.tokenExists(collectionId, token)).toJSON();1173}1174export async function getLastTokenId(1175  api: ApiPromise,1176  collectionId: number,1177): Promise<number> {1178  return (await api.rpc.unique.lastTokenId(collectionId)).toJSON();1179}1180export async function getAdminList(1181  api: ApiPromise,1182  collectionId: number,1183): Promise<string[]> {1184  return (await api.rpc.unique.adminlist(collectionId)).toHuman() as any;1185}1186export async function getTokenProperties(1187  api: ApiPromise,1188  collectionId: number,1189  tokenId: number,1190  propertyKeys: string[],1191): Promise<UpDataStructsProperty[]> {1192  return (await api.rpc.unique.tokenProperties(collectionId, tokenId, propertyKeys)).toHuman() as any;1193}11941195export async function createFungibleItemExpectSuccess(1196  sender: IKeyringPair,1197  collectionId: number,1198  data: CreateFungibleData,1199  owner: CrossAccountId | string = sender.address,1200) {1201  return await usingApi(async (api) => {1202    const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), {Fungible: data});12031204    const events = await submitTransactionAsync(sender, tx);1205    const result = getCreateItemResult(events);12061207    expect(result.success).to.be.true;1208    return result.itemId;1209  });1210}12111212export async function createMultipleItemsWithPropsExpectSuccess(sender: IKeyringPair, collectionId: number, itemsData: any, owner: CrossAccountId | string = sender.address) {1213  await usingApi(async (api) => {1214    const to = normalizeAccountId(owner);1215    const tx = api.tx.unique.createMultipleItems(collectionId, to, itemsData);12161217    const events = await submitTransactionAsync(sender, tx);1218    const result = getCreateItemsResult(events);12191220    for (const res of result) {1221      expect(await api.rpc.unique.tokenProperties(collectionId, res.itemId)).not.to.be.empty;1222    }1223  });1224}12251226export async function createMultipleItemsExWithPropsExpectSuccess(sender: IKeyringPair, collectionId: number, itemsData: any) {1227  await usingApi(async (api) => {1228    const tx = api.tx.unique.createMultipleItemsEx(collectionId, itemsData);12291230    const events = await submitTransactionAsync(sender, tx);1231    const result = getCreateItemsResult(events);12321233    for (const res of result) {1234      expect(await api.rpc.unique.tokenProperties(collectionId, res.itemId)).not.to.be.empty;1235    }1236  });1237}12381239export async function createItemWithPropsExpectSuccess(sender: IKeyringPair, collectionId: number, createMode: string, props:  Array<Property>, owner: CrossAccountId | string = sender.address) {1240  let newItemId = 0;1241  await usingApi(async (api) => {1242    const to = normalizeAccountId(owner);1243    const itemCountBefore = await getLastTokenId(api, collectionId);1244    const itemBalanceBefore = await getBalance(api, collectionId, to, newItemId);12451246    let tx;1247    if (createMode === 'Fungible') {1248      const createData = {fungible: {value: 10}};1249      tx = api.tx.unique.createItem(collectionId, to, createData as any);1250    } else if (createMode === 'ReFungible') {1251      const createData = {refungible: {pieces: 100}};1252      tx = api.tx.unique.createItem(collectionId, to, createData as any);1253    } else {1254      const data = api.createType('UpDataStructsCreateItemData', {NFT: {properties: props}});1255      tx = api.tx.unique.createItem(collectionId, to, data as UpDataStructsCreateItemData);1256    }12571258    const events = await submitTransactionAsync(sender, tx);1259    const result = getCreateItemResult(events);12601261    const itemCountAfter = await getLastTokenId(api, collectionId);1262    const itemBalanceAfter = await getBalance(api, collectionId, to, newItemId);12631264    if (createMode === 'NFT') {1265      expect(await api.rpc.unique.tokenProperties(collectionId, result.itemId)).not.to.be.empty;1266    }12671268    // What to expect1269    // tslint:disable-next-line:no-unused-expression1270    expect(result.success).to.be.true;1271    if (createMode === 'Fungible') {1272      expect(itemBalanceAfter - itemBalanceBefore).to.be.equal(10n);1273    } else {1274      expect(itemCountAfter).to.be.equal(itemCountBefore + 1);1275    }1276    expect(collectionId).to.be.equal(result.collectionId);1277    expect(itemCountAfter.toString()).to.be.equal(result.itemId.toString());1278    expect(to).to.be.deep.equal(result.recipient);1279    newItemId = result.itemId;1280  });1281  return newItemId;1282}12831284export async function createItemWithPropsExpectFailure(sender: IKeyringPair, collectionId: number, createMode: string, props: Array<Property>, owner: CrossAccountId | string = sender.address) {1285  await usingApi(async (api) => {12861287    let tx;1288    if (createMode === 'NFT') {1289      const data = api.createType('UpDataStructsCreateItemData', {NFT: {properties: props}});1290      tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), data);1291    } else {1292      tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), createMode);1293    }129412951296    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1297    if(events.message && events.message.toString().indexOf('1002: Verification Error') > -1) return;1298    const result = getCreateItemResult(events);12991300    expect(result.success).to.be.false;1301  });1302}13031304export async function createItemExpectSuccess(sender: IKeyringPair, collectionId: number, createMode: string, owner: CrossAccountId | string = sender.address) {1305  let newItemId = 0;1306  await usingApi(async (api) => {1307    const to = normalizeAccountId(owner);1308    const itemCountBefore = await getLastTokenId(api, collectionId);1309    const itemBalanceBefore = await getBalance(api, collectionId, to, newItemId);13101311    let tx;1312    if (createMode === 'Fungible') {1313      const createData = {fungible: {value: 10}};1314      tx = api.tx.unique.createItem(collectionId, to, createData as any);1315    } else if (createMode === 'ReFungible') {1316      const createData = {refungible: {pieces: 100}};1317      tx = api.tx.unique.createItem(collectionId, to, createData as any);1318    } else {1319      const createData = {nft: {}};1320      tx = api.tx.unique.createItem(collectionId, to, createData as any);1321    }13221323    const events = await submitTransactionAsync(sender, tx);1324    const result = getCreateItemResult(events);13251326    const itemCountAfter = await getLastTokenId(api, collectionId);1327    const itemBalanceAfter = await getBalance(api, collectionId, to, newItemId);13281329    // What to expect1330    // tslint:disable-next-line:no-unused-expression1331    expect(result.success).to.be.true;1332    if (createMode === 'Fungible') {1333      expect(itemBalanceAfter - itemBalanceBefore).to.be.equal(10n);1334    } else {1335      expect(itemCountAfter).to.be.equal(itemCountBefore + 1);1336    }1337    expect(collectionId).to.be.equal(result.collectionId);1338    expect(itemCountAfter.toString()).to.be.equal(result.itemId.toString());1339    expect(to).to.be.deep.equal(result.recipient);1340    newItemId = result.itemId;1341  });1342  return newItemId;1343}13441345export async function createItemExpectFailure(sender: IKeyringPair, collectionId: number, createMode: string, owner: CrossAccountId | string = sender.address) {1346  await usingApi(async (api) => {1347    const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), createMode);13481349    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1350    const result = getCreateItemResult(events);13511352    expect(result.success).to.be.false;1353  });1354}13551356export async function setPublicAccessModeExpectSuccess(1357  sender: IKeyringPair, collectionId: number,1358  accessMode: 'Normal' | 'AllowList',1359) {1360  await usingApi(async (api) => {13611362    // Run the transaction1363    const tx = api.tx.unique.setCollectionPermissions(collectionId, {access: accessMode});1364    const events = await submitTransactionAsync(sender, tx);1365    const result = getGenericResult(events);13661367    // Get the collection1368    const collection = await queryCollectionExpectSuccess(api, collectionId);13691370    // What to expect1371    // tslint:disable-next-line:no-unused-expression1372    expect(result.success).to.be.true;1373    expect(collection.permissions.access.toHuman()).to.be.equal(accessMode);1374  });1375}13761377export async function setPublicAccessModeExpectFail(1378  sender: IKeyringPair, collectionId: number,1379  accessMode: 'Normal' | 'AllowList',1380) {1381  await usingApi(async (api) => {13821383    // Run the transaction1384    const tx = api.tx.unique.setCollectionPermissions(collectionId, {access: accessMode});1385    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1386    const result = getGenericResult(events);13871388    // What to expect1389    // tslint:disable-next-line:no-unused-expression1390    expect(result.success).to.be.false;1391  });1392}13931394export async function enableAllowListExpectSuccess(sender: IKeyringPair, collectionId: number) {1395  await setPublicAccessModeExpectSuccess(sender, collectionId, 'AllowList');1396}13971398export async function enableAllowListExpectFail(sender: IKeyringPair, collectionId: number) {1399  await setPublicAccessModeExpectFail(sender, collectionId, 'AllowList');1400}14011402export async function disableAllowListExpectSuccess(sender: IKeyringPair, collectionId: number) {1403  await setPublicAccessModeExpectSuccess(sender, collectionId, 'Normal');1404}14051406export async function setMintPermissionExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {1407  await usingApi(async (api) => {14081409    // Run the transaction1410    const tx = api.tx.unique.setCollectionPermissions(collectionId, {mintMode: enabled});1411    const events = await submitTransactionAsync(sender, tx);1412    const result = getGenericResult(events);1413    expect(result.success).to.be.true;14141415    // Get the collection1416    const collection = await queryCollectionExpectSuccess(api, collectionId);14171418    expect(collection.permissions.mintMode.toHuman()).to.be.equal(enabled);1419  });1420}14211422export async function enablePublicMintingExpectSuccess(sender: IKeyringPair, collectionId: number) {1423  await setMintPermissionExpectSuccess(sender, collectionId, true);1424}14251426export async function setMintPermissionExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {1427  await usingApi(async (api) => {1428    // Run the transaction1429    const tx = api.tx.unique.setCollectionPermissions(collectionId, {mintMode: enabled});1430    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1431    const result = getCreateCollectionResult(events);1432    // tslint:disable-next-line:no-unused-expression1433    expect(result.success).to.be.false;1434  });1435}14361437export async function setChainLimitsExpectFailure(sender: IKeyringPair, limits: IChainLimits) {1438  await usingApi(async (api) => {1439    // Run the transaction1440    const tx = api.tx.unique.setChainLimits(limits);1441    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1442    const result = getCreateCollectionResult(events);1443    // tslint:disable-next-line:no-unused-expression1444    expect(result.success).to.be.false;1445  });1446}14471448export async function isAllowlisted(api: ApiPromise, collectionId: number, address: string | CrossAccountId) {1449  return (await api.rpc.unique.allowed(collectionId, normalizeAccountId(address))).toJSON();1450}14511452export async function addToAllowListExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId | CrossAccountId) {1453  await usingApi(async (api) => {1454    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.false;14551456    // Run the transaction1457    const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1458    const events = await submitTransactionAsync(sender, tx);1459    const result = getGenericResult(events);1460    expect(result.success).to.be.true;14611462    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;1463  });1464}14651466export async function addToAllowListAgainExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId) {1467  await usingApi(async (api) => {14681469    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;14701471    // Run the transaction1472    const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1473    const events = await submitTransactionAsync(sender, tx);1474    const result = getGenericResult(events);1475    expect(result.success).to.be.true;14761477    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;1478  });1479}14801481export async function addToAllowListExpectFail(sender: IKeyringPair, collectionId: number, address: string | AccountId) {1482  await usingApi(async (api) => {14831484    // Run the transaction1485    const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1486    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1487    const result = getGenericResult(events);14881489    // What to expect1490    // tslint:disable-next-line:no-unused-expression1491    expect(result.success).to.be.false;1492  });1493}14941495export async function removeFromAllowListExpectSuccess(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1496  await usingApi(async (api) => {1497    // Run the transaction1498    const tx = api.tx.unique.removeFromAllowList(collectionId, normalizeAccountId(address));1499    const events = await submitTransactionAsync(sender, tx);1500    const result = getGenericResult(events);15011502    // What to expect1503    // tslint:disable-next-line:no-unused-expression1504    expect(result.success).to.be.true;1505  });1506}15071508export async function removeFromAllowListExpectFailure(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1509  await usingApi(async (api) => {1510    // Run the transaction1511    const tx = api.tx.unique.removeFromAllowList(collectionId, normalizeAccountId(address));1512    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1513    const result = getGenericResult(events);15141515    // What to expect1516    // tslint:disable-next-line:no-unused-expression1517    expect(result.success).to.be.false;1518  });1519}15201521export const getDetailedCollectionInfo = async (api: ApiPromise, collectionId: number)1522  : Promise<UpDataStructsRpcCollection | null> => {1523  return (await api.rpc.unique.collectionById(collectionId)).unwrapOr(null);1524};15251526export const getCreatedCollectionCount = async (api: ApiPromise): Promise<number> => {1527  // set global object - collectionsCount1528  return (await api.rpc.unique.collectionStats()).created.toNumber();1529};15301531export async function queryCollectionExpectSuccess(api: ApiPromise, collectionId: number): Promise<UpDataStructsRpcCollection> {1532  return (await api.rpc.unique.collectionById(collectionId)).unwrap();1533}15341535export async function waitNewBlocks(blocksCount = 1): Promise<void> {1536  await usingApi(async (api) => {1537    const promise = new Promise<void>(async (resolve) => {1538      const unsubscribe = await api.rpc.chain.subscribeNewHeads(() => {1539        if (blocksCount > 0) {1540          blocksCount--;1541        } else {1542          unsubscribe();1543          resolve();1544        }1545      });1546    });1547    return promise;1548  });1549}