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

difftreelog

source

tests/src/util/helpers.ts61.0 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} from '@polkadot/api';20import type {AccountId, EventRecord, Event} from '@polkadot/types/interfaces';21import type {GenericEventData} from '@polkadot/types';22import {AnyTuple, IEvent, IKeyringPair} from '@polkadot/types/types';23import {evmToAddress} from '@polkadot/util-crypto';24import BN from 'bn.js';25import chai from 'chai';26import chaiAsPromised from 'chai-as-promised';27import {default as usingApi, executeTransaction, submitTransactionAsync, submitTransactionExpectFailAsync} from '../substrate/substrate-api';28import {hexToStr, strToUTF16, utf16ToStr} from './util';29import {UpDataStructsRpcCollection, UpDataStructsCreateItemData, UpDataStructsProperty} from '@polkadot/types/lookup';30import {UpDataStructsTokenChild} from '../interfaces';3132chai.use(chaiAsPromised);33const expect = chai.expect;3435export type CrossAccountId = {36  Substrate: string,37} | {38  Ethereum: string,39};4041export function normalizeAccountId(input: string | AccountId | CrossAccountId | IKeyringPair): CrossAccountId {42  if (typeof input === 'string') {43    if (input.length >= 47) {44      return {Substrate: input};45    } else if (input.length === 42 && input.startsWith('0x')) {46      return {Ethereum: input.toLowerCase()};47    } else if (input.length === 40 && !input.startsWith('0x')) {48      return {Ethereum: '0x' + input.toLowerCase()};49    } else {50      throw new Error(`Unknown address format: "${input}"`);51    }52  }53  if ('address' in input) {54    return {Substrate: input.address};55  }56  if ('Ethereum' in input) {57    return {58      Ethereum: input.Ethereum.toLowerCase(),59    };60  } else if ('ethereum' in input) {61    return {62      Ethereum: (input as any).ethereum.toLowerCase(),63    };64  } else if ('Substrate' in input) {65    return input;66  } else if ('substrate' in input) {67    return {68      Substrate: (input as any).substrate,69    };70  }7172  // AccountId73  return {Substrate: input.toString()};74}75export function toSubstrateAddress(input: string | CrossAccountId | IKeyringPair): string {76  input = normalizeAccountId(input);77  if ('Substrate' in input) {78    return input.Substrate;79  } else {80    return evmToAddress(input.Ethereum);81  }82}8384export const U128_MAX = (1n << 128n) - 1n;8586const MICROUNIQUE = 1_000_000_000_000n;87const MILLIUNIQUE = 1_000n * MICROUNIQUE;88const CENTIUNIQUE = 10n * MILLIUNIQUE;89export const UNIQUE = 100n * CENTIUNIQUE;9091interface GenericResult<T> {92  success: boolean;93  data: T | null;94}9596interface CreateCollectionResult {97  success: boolean;98  collectionId: number;99}100101interface CreateItemResult {102  success: boolean;103  collectionId: number;104  itemId: number;105  recipient?: CrossAccountId;106  amount?: number;107}108109interface DestroyItemResult {110  success: boolean;111  collectionId: number;112  itemId: number;113  owner: CrossAccountId;114  amount: number;115}116117interface TransferResult {118  collectionId: number;119  itemId: number;120  sender?: CrossAccountId;121  recipient?: CrossAccountId;122  value: bigint;123}124125interface IReFungibleOwner {126  fraction: BN;127  owner: number[];128}129130interface IGetMessage {131  checkMsgUnqMethod: string;132  checkMsgTrsMethod: string;133  checkMsgSysMethod: string;134}135136export interface IFungibleTokenDataType {137  value: number;138}139140export interface IChainLimits {141  collectionNumbersLimit: number;142  accountTokenOwnershipLimit: number;143  collectionsAdminsLimit: number;144  customDataLimit: number;145  nftSponsorTransferTimeout: number;146  fungibleSponsorTransferTimeout: number;147  refungibleSponsorTransferTimeout: number;148  //offchainSchemaLimit: number;149  //constOnChainSchemaLimit: number;150}151152export interface IReFungibleTokenDataType {153  owner: IReFungibleOwner[];154}155156export function uniqueEventMessage(events: EventRecord[]): IGetMessage {157  let checkMsgUnqMethod = '';158  let checkMsgTrsMethod = '';159  let checkMsgSysMethod = '';160  events.forEach(({event: {method, section}}) => {161    if (section === 'common') {162      checkMsgUnqMethod = method;163    } else if (section === 'treasury') {164      checkMsgTrsMethod = method;165    } else if (section === 'system') {166      checkMsgSysMethod = method;167    } else { return null; }168  });169  const result: IGetMessage = {170    checkMsgUnqMethod,171    checkMsgTrsMethod,172    checkMsgSysMethod,173  };174  return result;175}176177export function getEvent<T extends Event>(events: EventRecord[], check: (event: IEvent<AnyTuple>) => event is T): T | undefined {178  const event = events.find(r => check(r.event));179  if (!event) return;180  return event.event as T;181}182183export function getGenericResult<T>(events: EventRecord[]): GenericResult<T>;184export function getGenericResult<T>(185  events: EventRecord[],186  expectSection: string,187  expectMethod: string,188  extractAction: (data: GenericEventData) => T189): GenericResult<T>;190191export function getGenericResult<T>(192  events: EventRecord[],193  expectSection?: string,194  expectMethod?: string,195  extractAction?: (data: GenericEventData) => T,196): GenericResult<T> {197  let success = false;198  let successData = null;199200  events.forEach(({event: {data, method, section}}) => {201    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);202    if (method === 'ExtrinsicSuccess') {203      success = true;204    } else if ((expectSection == section) && (expectMethod == method)) {205      successData = extractAction!(data as any);206    }207  });208209  const result: GenericResult<T> = {210    success,211    data: successData,212  };213  return result;214}215216export function getCreateCollectionResult(events: EventRecord[]): CreateCollectionResult {217  const genericResult = getGenericResult(events, 'common', 'CollectionCreated', (data) => parseInt(data[0].toString(), 10));218  const result: CreateCollectionResult = {219    success: genericResult.success,220    collectionId: genericResult.data ?? 0,221  };222  return result;223}224225export function getCreateItemsResult(events: EventRecord[]): CreateItemResult[] {226  const results: CreateItemResult[] = [];227  228  const genericResult = getGenericResult<CreateItemResult[]>(events, 'common', 'ItemCreated', (data) => {229    const collectionId = parseInt(data[0].toString(), 10);230    const itemId = parseInt(data[1].toString(), 10);231    const recipient = normalizeAccountId(data[2].toJSON() as any);232    const amount = parseInt(data[3].toString(), 10);233234    const itemRes: CreateItemResult = {235      success: true,236      collectionId,237      itemId,238      recipient,239      amount,240    };241242    results.push(itemRes);243    return results;244  });245246  if (!genericResult.success) return [];247  return results;248}249250export function getCreateItemResult(events: EventRecord[]): CreateItemResult {251  const genericResult = getGenericResult(events, 'common', 'ItemCreated', (data) => data.map(function(value) { return value.toJSON(); }));252  253  if (genericResult.data == null) 254    return {255      success: genericResult.success,256      collectionId: 0,257      itemId: 0,258      amount: 0,259    };260  else 261    return {262      success: genericResult.success,263      collectionId: genericResult.data[0] as number,264      itemId: genericResult.data[1] as number,265      recipient: normalizeAccountId(genericResult.data![2] as any),266      amount: genericResult.data[3] as number,267    };268}269270export function getDestroyItemsResult(events: EventRecord[]): DestroyItemResult[] {271  const results: DestroyItemResult[] = [];272  273  const genericResult = getGenericResult<DestroyItemResult[]>(events, 'common', 'ItemDestroyed', (data) => {274    const collectionId = parseInt(data[0].toString(), 10);275    const itemId = parseInt(data[1].toString(), 10);276    const owner = normalizeAccountId(data[2].toJSON() as any);277    const amount = parseInt(data[3].toString(), 10);278279    const itemRes: DestroyItemResult = {280      success: true,281      collectionId,282      itemId,283      owner,284      amount,285    };286287    results.push(itemRes);288    return results;289  });290291  if (!genericResult.success) return [];292  return results;293}294295export function getTransferResult(api: ApiPromise, events: EventRecord[]): TransferResult {296  for (const {event} of events) {297    if (api.events.common.Transfer.is(event)) {298      const [collection, token, sender, recipient, value] = event.data;299      return {300        collectionId: collection.toNumber(),301        itemId: token.toNumber(),302        sender: normalizeAccountId(sender.toJSON() as any),303        recipient: normalizeAccountId(recipient.toJSON() as any),304        value: value.toBigInt(),305      };306    }307  }308  throw new Error('no transfer event');309}310311interface Nft {312  type: 'NFT';313}314315interface Fungible {316  type: 'Fungible';317  decimalPoints: number;318}319320interface ReFungible {321  type: 'ReFungible';322}323324export type CollectionMode = Nft | Fungible | ReFungible;325326export type Property = {327  key: any,328  value: any,329};330331type Permission = {332  mutable: boolean;333  collectionAdmin: boolean;334  tokenOwner: boolean;335}336337type PropertyPermission = {338  key: any;339  permission: Permission;340}341342export type CreateCollectionParams = {343  mode: CollectionMode,344  name: string,345  description: string,346  tokenPrefix: string,347  properties?: Array<Property>,348  propPerm?: Array<PropertyPermission>349};350351const defaultCreateCollectionParams: CreateCollectionParams = {352  description: 'description',353  mode: {type: 'NFT'},354  name: 'name',355  tokenPrefix: 'prefix',356};357358export async function359createCollection(360  api: ApiPromise,361  sender: IKeyringPair,362  params: Partial<CreateCollectionParams> = {},363): Promise<CreateCollectionResult> {364  const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};365366  let modeprm = {};367  if (mode.type === 'NFT') {368    modeprm = {nft: null};369  } else if (mode.type === 'Fungible') {370    modeprm = {fungible: mode.decimalPoints};371  } else if (mode.type === 'ReFungible') {372    modeprm = {refungible: null};373  }374375  const tx = api.tx.unique.createCollectionEx({376    name: strToUTF16(name),377    description: strToUTF16(description),378    tokenPrefix: strToUTF16(tokenPrefix),379    mode: modeprm as any,380  });381  const events = await submitTransactionAsync(sender, tx);382  return getCreateCollectionResult(events);383}384385export async function createCollectionExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {386  const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};387388  let collectionId = 0;389  await usingApi(async (api, privateKeyWrapper) => {390    // Get number of collections before the transaction391    const collectionCountBefore = await getCreatedCollectionCount(api);392393    // Run the CreateCollection transaction394    const alicePrivateKey = privateKeyWrapper('//Alice');395396    const result = await createCollection(api, alicePrivateKey, params);397398    // Get number of collections after the transaction399    const collectionCountAfter = await getCreatedCollectionCount(api);400401    // Get the collection402    const collection = await queryCollectionExpectSuccess(api, result.collectionId);403404    // What to expect405    // tslint:disable-next-line:no-unused-expression406    expect(result.success).to.be.true;407    expect(result.collectionId).to.be.equal(collectionCountAfter);408    // tslint:disable-next-line:no-unused-expression409    expect(collection).to.be.not.null;410    expect(collectionCountAfter).to.be.equal(collectionCountBefore + 1, 'Error: NFT collection NOT created.');411    expect(collection.owner.toString()).to.be.equal(toSubstrateAddress(alicePrivateKey));412    expect(utf16ToStr(collection.name.toJSON() as any)).to.be.equal(name);413    expect(utf16ToStr(collection.description.toJSON() as any)).to.be.equal(description);414    expect(hexToStr(collection.tokenPrefix.toJSON())).to.be.equal(tokenPrefix);415416    collectionId = result.collectionId;417  });418419  return collectionId;420}421422export async function createCollectionWithPropsExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {423  const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};424425  let collectionId = 0;426  await usingApi(async (api, privateKeyWrapper) => {427    // Get number of collections before the transaction428    const collectionCountBefore = await getCreatedCollectionCount(api);429430    // Run the CreateCollection transaction431    const alicePrivateKey = privateKeyWrapper('//Alice');432433    let modeprm = {};434    if (mode.type === 'NFT') {435      modeprm = {nft: null};436    } else if (mode.type === 'Fungible') {437      modeprm = {fungible: mode.decimalPoints};438    } else if (mode.type === 'ReFungible') {439      modeprm = {refungible: null};440    }441442    const tx = api.tx.unique.createCollectionEx({name: strToUTF16(name), description: strToUTF16(description), tokenPrefix: strToUTF16(tokenPrefix), mode: modeprm as any, properties: params.properties, tokenPropertyPermissions: params.propPerm});443    const events = await submitTransactionAsync(alicePrivateKey, tx);444    const result = getCreateCollectionResult(events);445446    // Get number of collections after the transaction447    const collectionCountAfter = await getCreatedCollectionCount(api);448449    // Get the collection450    const collection = await queryCollectionExpectSuccess(api, result.collectionId);451452    // What to expect453    // tslint:disable-next-line:no-unused-expression454    expect(result.success).to.be.true;455    expect(result.collectionId).to.be.equal(collectionCountAfter);456    // tslint:disable-next-line:no-unused-expression457    expect(collection).to.be.not.null;458    expect(collectionCountAfter).to.be.equal(collectionCountBefore + 1, 'Error: NFT collection NOT created.');459    expect(collection.owner.toString()).to.be.equal(toSubstrateAddress(alicePrivateKey));460    expect(utf16ToStr(collection.name.toJSON() as any)).to.be.equal(name);461    expect(utf16ToStr(collection.description.toJSON() as any)).to.be.equal(description);462    expect(hexToStr(collection.tokenPrefix.toJSON())).to.be.equal(tokenPrefix);463464465    collectionId = result.collectionId;466  });467468  return collectionId;469}470471export async function createCollectionWithPropsExpectFailure(params: Partial<CreateCollectionParams> = {}) {472  const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};473474  await usingApi(async (api, privateKeyWrapper) => {475    // Get number of collections before the transaction476    const collectionCountBefore = await getCreatedCollectionCount(api);477478    // Run the CreateCollection transaction479    const alicePrivateKey = privateKeyWrapper('//Alice');480481    let modeprm = {};482    if (mode.type === 'NFT') {483      modeprm = {nft: null};484    } else if (mode.type === 'Fungible') {485      modeprm = {fungible: mode.decimalPoints};486    } else if (mode.type === 'ReFungible') {487      modeprm = {refungible: null};488    }489490    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});491    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;492493494    // Get number of collections after the transaction495    const collectionCountAfter = await getCreatedCollectionCount(api);496497    expect(collectionCountAfter).to.be.equal(collectionCountBefore, 'Error: Collection with incorrect data created.');498  });499}500501export async function createCollectionExpectFailure(params: Partial<CreateCollectionParams> = {}) {502  const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};503504  let modeprm = {};505  if (mode.type === 'NFT') {506    modeprm = {nft: null};507  } else if (mode.type === 'Fungible') {508    modeprm = {fungible: mode.decimalPoints};509  } else if (mode.type === 'ReFungible') {510    modeprm = {refungible: null};511  }512513  await usingApi(async (api, privateKeyWrapper) => {514    // Get number of collections before the transaction515    const collectionCountBefore = await getCreatedCollectionCount(api);516517    // Run the CreateCollection transaction518    const alicePrivateKey = privateKeyWrapper('//Alice');519    const tx = api.tx.unique.createCollectionEx({name: strToUTF16(name), description: strToUTF16(description), tokenPrefix: strToUTF16(tokenPrefix), mode: modeprm as any});520    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;521522    // Get number of collections after the transaction523    const collectionCountAfter = await getCreatedCollectionCount(api);524525    // What to expect526    expect(collectionCountAfter).to.be.equal(collectionCountBefore, 'Error: Collection with incorrect data created.');527  });528}529530export async function findUnusedAddress(api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair, seedAddition = ''): Promise<IKeyringPair> {531  let bal = 0n;532  let unused;533  do {534    const randomSeed = 'seed' + Math.floor(Math.random() * Math.floor(10000)) + seedAddition;535    unused = privateKeyWrapper(`//${randomSeed}`);536    bal = (await api.query.system.account(unused.address)).data.free.toBigInt();537  } while (bal !== 0n);538  return unused;539}540541export async function getAllowance(api: ApiPromise, collectionId: number, owner: CrossAccountId | string | IKeyringPair, approved: CrossAccountId | string | IKeyringPair, tokenId: number) {542  return (await api.rpc.unique.allowance(collectionId, normalizeAccountId(owner), normalizeAccountId(approved), tokenId)).toBigInt();543}544545export function findUnusedAddresses(api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair, amount: number): Promise<IKeyringPair[]> {546  return Promise.all(new Array(amount).fill(null).map(() => findUnusedAddress(api, privateKeyWrapper, '_' + Date.now())));547}548549export async function findNotExistingCollection(api: ApiPromise): Promise<number> {550  const totalNumber = await getCreatedCollectionCount(api);551  const newCollection: number = totalNumber + 1;552  return newCollection;553}554555function getDestroyResult(events: EventRecord[]): boolean {556  let success = false;557  events.forEach(({event: {method}}) => {558    if (method == 'ExtrinsicSuccess') {559      success = true;560    }561  });562  return success;563}564565export async function destroyCollectionExpectFailure(collectionId: number, senderSeed = '//Alice') {566  await usingApi(async (api, privateKeyWrapper) => {567    // Run the DestroyCollection transaction568    const alicePrivateKey = privateKeyWrapper(senderSeed);569    const tx = api.tx.unique.destroyCollection(collectionId);570    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;571  });572}573574export async function destroyCollectionExpectSuccess(collectionId: number, senderSeed = '//Alice') {575  await usingApi(async (api, privateKeyWrapper) => {576    // Run the DestroyCollection transaction577    const alicePrivateKey = privateKeyWrapper(senderSeed);578    const tx = api.tx.unique.destroyCollection(collectionId);579    const events = await submitTransactionAsync(alicePrivateKey, tx);580    const result = getDestroyResult(events);581    expect(result).to.be.true;582583    // What to expect584    expect(await getDetailedCollectionInfo(api, collectionId)).to.be.null;585  });586}587588export async function setCollectionLimitsExpectSuccess(sender: IKeyringPair, collectionId: number, limits: any) {589  await usingApi(async (api) => {590    const tx = api.tx.unique.setCollectionLimits(collectionId, limits);591    const events = await submitTransactionAsync(sender, tx);592    const result = getGenericResult(events);593594    expect(result.success).to.be.true;595  });596}597598export const setCollectionPermissionsExpectSuccess = async (sender: IKeyringPair, collectionId: number, permissions: any) => {599  await usingApi(async(api) => {600    const tx = api.tx.unique.setCollectionPermissions(collectionId, permissions);601    const events = await submitTransactionAsync(sender, tx);602    const result = getGenericResult(events);603604    expect(result.success).to.be.true;605  });606};607608export async function setCollectionLimitsExpectFailure(sender: IKeyringPair, collectionId: number, limits: any) {609  await usingApi(async (api) => {610    const tx = api.tx.unique.setCollectionLimits(collectionId, limits);611    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;612    const result = getGenericResult(events);613614    expect(result.success).to.be.false;615  });616}617618export async function setCollectionSponsorExpectSuccess(collectionId: number, sponsor: string, sender = '//Alice') {619  await usingApi(async (api, privateKeyWrapper) => {620621    // Run the transaction622    const senderPrivateKey = privateKeyWrapper(sender);623    const tx = api.tx.unique.setCollectionSponsor(collectionId, sponsor);624    const events = await submitTransactionAsync(senderPrivateKey, tx);625    const result = getGenericResult(events);626627    // Get the collection628    const collection = await queryCollectionExpectSuccess(api, collectionId);629630    // What to expect631    expect(result.success).to.be.true;632    expect(collection.sponsorship.toJSON()).to.deep.equal({633      unconfirmed: sponsor,634    });635  });636}637638export async function removeCollectionSponsorExpectSuccess(collectionId: number, sender = '//Alice') {639  await usingApi(async (api, privateKeyWrapper) => {640641    // Run the transaction642    const alicePrivateKey = privateKeyWrapper(sender);643    const tx = api.tx.unique.removeCollectionSponsor(collectionId);644    const events = await submitTransactionAsync(alicePrivateKey, 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({disabled: null});653  });654}655656export async function removeCollectionSponsorExpectFailure(collectionId: number, senderSeed = '//Alice') {657  await usingApi(async (api, privateKeyWrapper) => {658659    // Run the transaction660    const alicePrivateKey = privateKeyWrapper(senderSeed);661    const tx = api.tx.unique.removeCollectionSponsor(collectionId);662    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;663  });664}665666export async function setCollectionSponsorExpectFailure(collectionId: number, sponsor: string, senderSeed = '//Alice') {667  await usingApi(async (api, privateKeyWrapper) => {668669    // Run the transaction670    const alicePrivateKey = privateKeyWrapper(senderSeed);671    const tx = api.tx.unique.setCollectionSponsor(collectionId, sponsor);672    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;673  });674}675676export async function confirmSponsorshipExpectSuccess(collectionId: number, senderSeed = '//Alice') {677  await usingApi(async (api, privateKeyWrapper) => {678679    // Run the transaction680    const sender = privateKeyWrapper(senderSeed);681    await confirmSponsorshipByKeyExpectSuccess(collectionId, sender);682  });683}684685export async function confirmSponsorshipByKeyExpectSuccess(collectionId: number, sender: IKeyringPair) {686  await usingApi(async (api, privateKeyWrapper) => {687688    // Run the transaction689    const tx = api.tx.unique.confirmSponsorship(collectionId);690    const events = await submitTransactionAsync(sender, tx);691    const result = getGenericResult(events);692693    // Get the collection694    const collection = await queryCollectionExpectSuccess(api, collectionId);695696    // What to expect697    expect(result.success).to.be.true;698    expect(collection.sponsorship.toJSON()).to.be.deep.equal({699      confirmed: sender.address,700    });701  });702}703704705export async function confirmSponsorshipExpectFailure(collectionId: number, senderSeed = '//Alice') {706  await usingApi(async (api, privateKeyWrapper) => {707708    // Run the transaction709    const sender = privateKeyWrapper(senderSeed);710    const tx = api.tx.unique.confirmSponsorship(collectionId);711    await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;712  });713}714715export async function enableContractSponsoringExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {716  await usingApi(async (api) => {717    const tx = api.tx.unique.enableContractSponsoring(contractAddress, enable);718    const events = await submitTransactionAsync(sender, tx);719    const result = getGenericResult(events);720721    expect(result.success).to.be.true;722  });723}724725export async function enableContractSponsoringExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {726  await usingApi(async (api) => {727    const tx = api.tx.unique.enableContractSponsoring(contractAddress, enable);728    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;729    const result = getGenericResult(events);730731    expect(result.success).to.be.false;732  });733}734735export async function setTransferFlagExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {736737  await usingApi(async (api) => {738739    const tx = api.tx.unique.setTransfersEnabledFlag(collectionId, enabled);740    const events = await submitTransactionAsync(sender, tx);741    const result = getGenericResult(events);742743    expect(result.success).to.be.true;744  });745}746747export async function setTransferFlagExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {748749  await usingApi(async (api) => {750751    const tx = api.tx.unique.setTransfersEnabledFlag(collectionId, enabled);752    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;753    const result = getGenericResult(events);754755    expect(result.success).to.be.false;756  });757}758759export async function setContractSponsoringRateLimitExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {760  await usingApi(async (api) => {761    const tx = api.tx.unique.setContractSponsoringRateLimit(contractAddress, rateLimit);762    const events = await submitTransactionAsync(sender, tx);763    const result = getGenericResult(events);764765    expect(result.success).to.be.true;766  });767}768769export async function setContractSponsoringRateLimitExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {770  await usingApi(async (api) => {771    const tx = api.tx.unique.setContractSponsoringRateLimit(contractAddress, rateLimit);772    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;773    const result = getGenericResult(events);774775    expect(result.success).to.be.false;776  });777}778779export async function getNextSponsored(780  api: ApiPromise,781  collectionId: number,782  account: string | CrossAccountId,783  tokenId: number,784): Promise<number> {785  return Number((await api.rpc.unique.nextSponsored(collectionId, account, tokenId)).unwrapOr(-1));786}787788export async function toggleContractAllowlistExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, value = true) {789  await usingApi(async (api) => {790    const tx = api.tx.unique.toggleContractAllowList(contractAddress, value);791    const events = await submitTransactionAsync(sender, tx);792    const result = getGenericResult(events);793794    expect(result.success).to.be.true;795  });796}797798export async function isAllowlistedInContract(contractAddress: AccountId | string, user: string) {799  let allowlisted = false;800  await usingApi(async (api) => {801    allowlisted = (await api.query.unique.contractAllowList(contractAddress, user)).toJSON() as boolean;802  });803  return allowlisted;804}805806export async function addToContractAllowListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {807  await usingApi(async (api) => {808    const tx = api.tx.unique.addToContractAllowList(contractAddress.toString(), user.toString());809    const events = await submitTransactionAsync(sender, tx);810    const result = getGenericResult(events);811812    expect(result.success).to.be.true;813  });814}815816export async function removeFromContractAllowListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {817  await usingApi(async (api) => {818    const tx = api.tx.unique.removeFromContractAllowList(contractAddress.toString(), user.toString());819    const events = await submitTransactionAsync(sender, tx);820    const result = getGenericResult(events);821822    expect(result.success).to.be.true;823  });824}825826export async function removeFromContractAllowListExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {827  await usingApi(async (api) => {828    const tx = api.tx.unique.removeFromContractAllowList(contractAddress.toString(), user.toString());829    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;830    const result = getGenericResult(events);831832    expect(result.success).to.be.false;833  });834}835836export interface CreateFungibleData {837  readonly Value: bigint;838}839840export interface CreateReFungibleData { }841export interface CreateNftData { }842843export type CreateItemData = {844  NFT: CreateNftData;845} | {846  Fungible: CreateFungibleData;847} | {848  ReFungible: CreateReFungibleData;849};850851export async function burnItem(api: ApiPromise, sender: IKeyringPair, collectionId: number, tokenId: number, value: number | bigint) : Promise<boolean> {852  const tx = api.tx.unique.burnItem(collectionId, tokenId, value);853  const events = await submitTransactionAsync(sender, tx);854  return getGenericResult(events).success;855}856857export async function burnItemExpectSuccess(sender: IKeyringPair, collectionId: number, tokenId: number, value: number | bigint = 1) {858  await usingApi(async (api) => {859    const balanceBefore = await getBalance(api, collectionId, normalizeAccountId(sender), tokenId);860    // if burning token by admin - use adminButnItemExpectSuccess861    expect(balanceBefore >= BigInt(value)).to.be.true;862863    expect(await burnItem(api, sender, collectionId, tokenId, value)).to.be.true;864865    const balanceAfter = await getBalance(api, collectionId, normalizeAccountId(sender), tokenId);866    expect(balanceAfter + BigInt(value)).to.be.equal(balanceBefore);867  });868}869870export async function burnItemExpectFailure(sender: IKeyringPair, collectionId: number, tokenId: number, value: number | bigint = 1) {871  await usingApi(async (api) => {872    const tx = api.tx.unique.burnItem(collectionId, tokenId, value);873874    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;875    const result = getCreateCollectionResult(events);876    // tslint:disable-next-line:no-unused-expression877    expect(result.success).to.be.false;878  });879}880881export async function burnFromExpectSuccess(sender: IKeyringPair, from: IKeyringPair | CrossAccountId, collectionId: number, tokenId: number, value: number | bigint = 1) {882  await usingApi(async (api) => {883    const tx = api.tx.unique.burnFrom(collectionId, normalizeAccountId(from), tokenId, value);884    const events = await submitTransactionAsync(sender, tx);885    return getGenericResult(events).success;886  });887}888889export async function890approve(891  api: ApiPromise,892  collectionId: number,893  tokenId: number, owner: IKeyringPair, approved: CrossAccountId | string | IKeyringPair, amount: number | bigint,894) {895  const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);896  const events = await submitTransactionAsync(owner, approveUniqueTx);897  return getGenericResult(events).success;898}899900export async function901approveExpectSuccess(902  collectionId: number,903  tokenId: number, owner: IKeyringPair, approved: CrossAccountId | string, amount: number | bigint = 1,904) {905  await usingApi(async (api: ApiPromise) => {906    const result = await approve(api, collectionId, tokenId, owner, approved, amount);907    expect(result).to.be.true;908909    expect(await getAllowance(api, collectionId, owner, approved, tokenId)).to.be.equal(BigInt(amount));910  });911}912913export async function adminApproveFromExpectSuccess(914  collectionId: number,915  tokenId: number, admin: IKeyringPair, owner: CrossAccountId | string, approved: CrossAccountId | string, amount: number | bigint = 1,916) {917  await usingApi(async (api: ApiPromise) => {918    const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);919    const events = await submitTransactionAsync(admin, approveUniqueTx);920    const result = getGenericResult(events);921    expect(result.success).to.be.true;922923    expect(await getAllowance(api, collectionId, owner, approved, tokenId)).to.be.equal(BigInt(amount));924  });925}926927export async function928transferFrom(929  api: ApiPromise,930  collectionId: number,931  tokenId: number,932  accountApproved: IKeyringPair,933  accountFrom: IKeyringPair | CrossAccountId,934  accountTo: IKeyringPair | CrossAccountId,935  value: number | bigint,936) {937  const from = normalizeAccountId(accountFrom);938  const to = normalizeAccountId(accountTo);939  const transferFromTx = api.tx.unique.transferFrom(from, to, collectionId, tokenId, value);940  const events = await submitTransactionAsync(accountApproved, transferFromTx);941  return getGenericResult(events).success;942}943944export async function945transferFromExpectSuccess(946  collectionId: number,947  tokenId: number,948  accountApproved: IKeyringPair,949  accountFrom: IKeyringPair | CrossAccountId,950  accountTo: IKeyringPair | CrossAccountId,951  value: number | bigint = 1,952  type = 'NFT',953) {954  await usingApi(async (api: ApiPromise) => {955    const from = normalizeAccountId(accountFrom);956    const to = normalizeAccountId(accountTo);957    let balanceBefore = 0n;958    if (type === 'Fungible' || type === 'ReFungible') {959      balanceBefore = await getBalance(api, collectionId, to, tokenId);960    }961    expect(await transferFrom(api, collectionId, tokenId, accountApproved, accountFrom, accountTo, value)).to.be.true;962    if (type === 'NFT') {963      expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(to);964    }965    if (type === 'Fungible') {966      const balanceAfter = await getBalance(api, collectionId, to, tokenId);967      if (JSON.stringify(to) !== JSON.stringify(from)) {968        expect(balanceAfter - balanceBefore).to.be.equal(BigInt(value));969      } else {970        expect(balanceAfter).to.be.equal(balanceBefore);971      }972    }973    if (type === 'ReFungible') {974      expect(await getBalance(api, collectionId, to, tokenId)).to.be.equal(balanceBefore + BigInt(value));975    }976  });977}978979export async function980transferFromExpectFail(981  collectionId: number,982  tokenId: number,983  accountApproved: IKeyringPair,984  accountFrom: IKeyringPair,985  accountTo: IKeyringPair,986  value: number | bigint = 1,987) {988  await usingApi(async (api: ApiPromise) => {989    const transferFromTx = api.tx.unique.transferFrom(normalizeAccountId(accountFrom.address), normalizeAccountId(accountTo.address), collectionId, tokenId, value);990    const events = await expect(submitTransactionExpectFailAsync(accountApproved, transferFromTx)).to.be.rejected;991    const result = getCreateCollectionResult(events);992    // tslint:disable-next-line:no-unused-expression993    expect(result.success).to.be.false;994  });995}996997/* eslint no-async-promise-executor: "off" */998export async function getBlockNumber(api: ApiPromise): Promise<number> {999  return new Promise<number>(async (resolve) => {1000    const unsubscribe = await api.rpc.chain.subscribeNewHeads((head) => {1001      unsubscribe();1002      resolve(head.number.toNumber());1003    });1004  });1005}10061007export async function addCollectionAdminExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | CrossAccountId) {1008  await usingApi(async (api) => {1009    const changeAdminTx = api.tx.unique.addCollectionAdmin(collectionId, normalizeAccountId(address));1010    const events = await submitTransactionAsync(sender, changeAdminTx);1011    const result = getCreateCollectionResult(events);1012    expect(result.success).to.be.true;1013  });1014}10151016export async function adminApproveFromExpectFail(1017  collectionId: number,1018  tokenId: number, admin: IKeyringPair, owner: CrossAccountId | string, approved: CrossAccountId | string, amount: number | bigint = 1,1019) {1020  await usingApi(async (api: ApiPromise) => {1021    const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);1022    const events = await expect(submitTransactionAsync(admin, approveUniqueTx)).to.be.rejected;1023    const result = getGenericResult(events);1024    expect(result.success).to.be.false;1025  });1026}10271028export async function1029getFreeBalance(account: IKeyringPair): Promise<bigint> {1030  let balance = 0n;1031  await usingApi(async (api) => {1032    balance = BigInt((await api.query.system.account(account.address)).data.free.toString());1033  });10341035  return balance;1036}10371038export async function transferBalanceTo(api: ApiPromise, source: IKeyringPair, target: string, amount = 1000n * UNIQUE) {1039  const tx = api.tx.balances.transfer(target, amount);1040  const events = await submitTransactionAsync(source, tx);1041  const result = getGenericResult(events);1042  expect(result.success).to.be.true;1043}10441045export async function1046scheduleExpectSuccess(1047  operationTx: any,1048  sender: IKeyringPair,1049  blockSchedule: number,1050  scheduledId: string,1051  period = 1,1052  repetitions = 1,1053) {1054  await usingApi(async (api: ApiPromise) => {1055    const blockNumber: number | undefined = await getBlockNumber(api);1056    const expectedBlockNumber = blockNumber + blockSchedule;10571058    expect(blockNumber).to.be.greaterThan(0);1059    const scheduleTx = api.tx.scheduler.scheduleNamed( // schedule1060      scheduledId,1061      expectedBlockNumber, 1062      repetitions > 1 ? [period, repetitions] : null, 1063      0, 1064      {Value: operationTx as any},1065    );10661067    const events = await submitTransactionAsync(sender, scheduleTx);1068    expect(getGenericResult(events).success).to.be.true;1069  });1070}10711072export async function1073scheduleExpectFailure(1074  operationTx: any,1075  sender: IKeyringPair,1076  blockSchedule: number,1077  scheduledId: string,1078  period = 1,1079  repetitions = 1,1080) {1081  await usingApi(async (api: ApiPromise) => {1082    const blockNumber: number | undefined = await getBlockNumber(api);1083    const expectedBlockNumber = blockNumber + blockSchedule;10841085    expect(blockNumber).to.be.greaterThan(0);1086    const scheduleTx = api.tx.scheduler.scheduleNamed( // schedule1087      scheduledId,1088      expectedBlockNumber, 1089      repetitions <= 1 ? null : [period, repetitions], 1090      0, 1091      {Value: operationTx as any},1092    );10931094    //const events = 1095    await expect(submitTransactionExpectFailAsync(sender, scheduleTx)).to.be.rejected;1096    //expect(getGenericResult(events).success).to.be.false;1097  });1098}10991100export async function1101scheduleTransferAndWaitExpectSuccess(1102  collectionId: number,1103  tokenId: number,1104  sender: IKeyringPair,1105  recipient: IKeyringPair,1106  value: number | bigint = 1,1107  blockSchedule: number,1108  scheduledId: string,1109) {1110  await usingApi(async (api: ApiPromise) => {1111    await scheduleTransferExpectSuccess(collectionId, tokenId, sender, recipient, value, blockSchedule, scheduledId);11121113    const recipientBalanceBefore = (await api.query.system.account(recipient.address)).data.free.toBigInt();11141115    // sleep for n + 1 blocks1116    await waitNewBlocks(blockSchedule + 1);11171118    const recipientBalanceAfter = (await api.query.system.account(recipient.address)).data.free.toBigInt();11191120    expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(recipient.address));1121    expect(recipientBalanceAfter).to.be.equal(recipientBalanceBefore);1122  });1123}11241125export async function1126scheduleTransferExpectSuccess(1127  collectionId: number,1128  tokenId: number,1129  sender: IKeyringPair,1130  recipient: IKeyringPair,1131  value: number | bigint = 1,1132  blockSchedule: number,1133  scheduledId: string,1134) {1135  await usingApi(async (api: ApiPromise) => {1136    const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient.address), collectionId, tokenId, value);11371138    await scheduleExpectSuccess(transferTx, sender, blockSchedule, scheduledId);11391140    expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(sender.address));1141  });1142}11431144export async function1145scheduleTransferFundsPeriodicExpectSuccess(1146  amount: bigint,1147  sender: IKeyringPair,1148  recipient: IKeyringPair,1149  blockSchedule: number,1150  scheduledId: string,1151  period: number,1152  repetitions: number,1153) {1154  await usingApi(async (api: ApiPromise) => {1155    const transferTx = api.tx.balances.transfer(recipient.address, amount);11561157    const balanceBefore = await getFreeBalance(recipient);1158    1159    await scheduleExpectSuccess(transferTx, sender, blockSchedule, scheduledId, period, repetitions);11601161    expect(await getFreeBalance(recipient)).to.be.equal(balanceBefore);1162  });1163}11641165export async function1166transfer(1167  api: ApiPromise,1168  collectionId: number,1169  tokenId: number,1170  sender: IKeyringPair,1171  recipient: IKeyringPair | CrossAccountId,1172  value: number | bigint,1173) : Promise<boolean> {1174  const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient), collectionId, tokenId, value);1175  const events = await executeTransaction(api, sender, transferTx);1176  return getGenericResult(events).success;1177}11781179export async function1180transferExpectSuccess(1181  collectionId: number,1182  tokenId: number,1183  sender: IKeyringPair,1184  recipient: IKeyringPair | CrossAccountId,1185  value: number | bigint = 1,1186  type = 'NFT',1187) {1188  await usingApi(async (api: ApiPromise) => {1189    const from = normalizeAccountId(sender);1190    const to = normalizeAccountId(recipient);11911192    let balanceBefore = 0n;1193    if (type === 'Fungible' || type === 'ReFungible') {1194      balanceBefore = await getBalance(api, collectionId, to, tokenId);1195    }11961197    const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient), collectionId, tokenId, value);1198    const events = await executeTransaction(api, sender, transferTx);1199    const result = getTransferResult(api, events);12001201    expect(result.collectionId).to.be.equal(collectionId);1202    expect(result.itemId).to.be.equal(tokenId);1203    expect(result.sender).to.be.deep.equal(normalizeAccountId(sender.address));1204    expect(result.recipient).to.be.deep.equal(to);1205    expect(result.value).to.be.equal(BigInt(value));12061207    if (type === 'NFT') {1208      expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(to);1209    }1210    if (type === 'Fungible' || type === 'ReFungible') {1211      const balanceAfter = await getBalance(api, collectionId, to, tokenId);1212      if (JSON.stringify(to) !== JSON.stringify(from)) {1213        expect(balanceAfter - balanceBefore).to.be.equal(BigInt(value));1214      } else {1215        expect(balanceAfter).to.be.equal(balanceBefore);1216      }1217    }1218  });1219}12201221export async function1222transferExpectFailure(1223  collectionId: number,1224  tokenId: number,1225  sender: IKeyringPair,1226  recipient: IKeyringPair | CrossAccountId,1227  value: number | bigint = 1,1228) {1229  await usingApi(async (api: ApiPromise) => {1230    const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient), collectionId, tokenId, value);1231    const events = await expect(submitTransactionExpectFailAsync(sender, transferTx)).to.be.rejected;1232    const result = getGenericResult(events);1233    // if (events && Array.isArray(events)) {1234    //   const result = getCreateCollectionResult(events);1235    // tslint:disable-next-line:no-unused-expression1236    expect(result.success).to.be.false;1237    //}1238  });1239}12401241export async function1242approveExpectFail(1243  collectionId: number,1244  tokenId: number, owner: IKeyringPair, approved: IKeyringPair, amount: number | bigint = 1,1245) {1246  await usingApi(async (api: ApiPromise) => {1247    const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved.address), collectionId, tokenId, amount);1248    const events = await expect(submitTransactionExpectFailAsync(owner, approveUniqueTx)).to.be.rejected;1249    const result = getCreateCollectionResult(events);1250    // tslint:disable-next-line:no-unused-expression1251    expect(result.success).to.be.false;1252  });1253}12541255export async function getBalance(1256  api: ApiPromise,1257  collectionId: number,1258  owner: string | CrossAccountId | IKeyringPair,1259  token: number,1260): Promise<bigint> {1261  return (await api.rpc.unique.balance(collectionId, normalizeAccountId(owner), token)).toBigInt();1262}1263export async function getTokenOwner(1264  api: ApiPromise,1265  collectionId: number,1266  token: number,1267): Promise<CrossAccountId> {1268  const owner = (await api.rpc.unique.tokenOwner(collectionId, token)).toJSON() as any;1269  if (owner == null) throw new Error('owner == null');1270  return normalizeAccountId(owner);1271}1272export async function getTopmostTokenOwner(1273  api: ApiPromise,1274  collectionId: number,1275  token: number,1276): Promise<CrossAccountId> {1277  const owner = (await api.rpc.unique.topmostTokenOwner(collectionId, token)).toJSON() as any;1278  if (owner == null) throw new Error('owner == null');1279  return normalizeAccountId(owner);1280}1281export async function getTokenChildren(1282  api: ApiPromise,1283  collectionId: number,1284  tokenId: number,1285): Promise<UpDataStructsTokenChild[]> {1286  return (await api.rpc.unique.tokenChildren(collectionId, tokenId)).toJSON() as any;1287}1288export async function isTokenExists(1289  api: ApiPromise,1290  collectionId: number,1291  token: number,1292): Promise<boolean> {1293  return (await api.rpc.unique.tokenExists(collectionId, token)).toJSON();1294}1295export async function getLastTokenId(1296  api: ApiPromise,1297  collectionId: number,1298): Promise<number> {1299  return (await api.rpc.unique.lastTokenId(collectionId)).toJSON();1300}1301export async function getAdminList(1302  api: ApiPromise,1303  collectionId: number,1304): Promise<string[]> {1305  return (await api.rpc.unique.adminlist(collectionId)).toHuman() as any;1306}1307export async function getTokenProperties(1308  api: ApiPromise,1309  collectionId: number,1310  tokenId: number,1311  propertyKeys: string[],1312): Promise<UpDataStructsProperty[]> {1313  return (await api.rpc.unique.tokenProperties(collectionId, tokenId, propertyKeys)).toHuman() as any;1314}13151316export async function createFungibleItemExpectSuccess(1317  sender: IKeyringPair,1318  collectionId: number,1319  data: CreateFungibleData,1320  owner: CrossAccountId | string = sender.address,1321) {1322  return await usingApi(async (api) => {1323    const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), {Fungible: data});13241325    const events = await submitTransactionAsync(sender, tx);1326    const result = getCreateItemResult(events);13271328    expect(result.success).to.be.true;1329    return result.itemId;1330  });1331}13321333export async function createMultipleItemsExpectSuccess(sender: IKeyringPair, collectionId: number, itemsData: any, owner: CrossAccountId | string = sender.address) {1334  await usingApi(async (api) => {1335    const to = normalizeAccountId(owner);1336    const tx = api.tx.unique.createMultipleItems(collectionId, to, itemsData);13371338    const events = await submitTransactionAsync(sender, tx);1339    expect(getGenericResult(events).success).to.be.true;1340  });1341}13421343export async function createMultipleItemsWithPropsExpectSuccess(sender: IKeyringPair, collectionId: number, itemsData: any, owner: CrossAccountId | string = sender.address) {1344  await usingApi(async (api) => {1345    const to = normalizeAccountId(owner);1346    const tx = api.tx.unique.createMultipleItems(collectionId, to, itemsData);13471348    const events = await submitTransactionAsync(sender, tx);1349    const result = getCreateItemsResult(events);13501351    for (const res of result) {1352      expect(await api.rpc.unique.tokenProperties(collectionId, res.itemId)).not.to.be.empty;1353    }1354  });1355}13561357export async function createMultipleItemsExWithPropsExpectSuccess(sender: IKeyringPair, collectionId: number, itemsData: any) {1358  await usingApi(async (api) => {1359    const tx = api.tx.unique.createMultipleItemsEx(collectionId, itemsData);13601361    const events = await submitTransactionAsync(sender, tx);1362    const result = getCreateItemsResult(events);13631364    for (const res of result) {1365      expect(await api.rpc.unique.tokenProperties(collectionId, res.itemId)).not.to.be.empty;1366    }1367  });1368}13691370export async function createItemWithPropsExpectSuccess(sender: IKeyringPair, collectionId: number, createMode: string, props:  Array<Property>, owner: CrossAccountId | string = sender.address) {1371  let newItemId = 0;1372  await usingApi(async (api) => {1373    const to = normalizeAccountId(owner);1374    const itemCountBefore = await getLastTokenId(api, collectionId);1375    const itemBalanceBefore = await getBalance(api, collectionId, to, newItemId);13761377    let tx;1378    if (createMode === 'Fungible') {1379      const createData = {fungible: {value: 10}};1380      tx = api.tx.unique.createItem(collectionId, to, createData as any);1381    } else if (createMode === 'ReFungible') {1382      const createData = {refungible: {pieces: 100}};1383      tx = api.tx.unique.createItem(collectionId, to, createData as any);1384    } else {1385      const data = api.createType('UpDataStructsCreateItemData', {NFT: {properties: props}});1386      tx = api.tx.unique.createItem(collectionId, to, data as UpDataStructsCreateItemData);1387    }13881389    const events = await submitTransactionAsync(sender, tx);1390    const result = getCreateItemResult(events);13911392    const itemCountAfter = await getLastTokenId(api, collectionId);1393    const itemBalanceAfter = await getBalance(api, collectionId, to, newItemId);13941395    if (createMode === 'NFT') {1396      expect(await api.rpc.unique.tokenProperties(collectionId, result.itemId)).not.to.be.empty;1397    }13981399    // What to expect1400    // tslint:disable-next-line:no-unused-expression1401    expect(result.success).to.be.true;1402    if (createMode === 'Fungible') {1403      expect(itemBalanceAfter - itemBalanceBefore).to.be.equal(10n);1404    } else {1405      expect(itemCountAfter).to.be.equal(itemCountBefore + 1);1406    }1407    expect(collectionId).to.be.equal(result.collectionId);1408    expect(itemCountAfter.toString()).to.be.equal(result.itemId.toString());1409    expect(to).to.be.deep.equal(result.recipient);1410    newItemId = result.itemId;1411  });1412  return newItemId;1413}14141415export async function createItemWithPropsExpectFailure(sender: IKeyringPair, collectionId: number, createMode: string, props: Array<Property>, owner: CrossAccountId | string = sender.address) {1416  await usingApi(async (api) => {14171418    let tx;1419    if (createMode === 'NFT') {1420      const data = api.createType('UpDataStructsCreateItemData', {NFT: {properties: props}}) as UpDataStructsCreateItemData;1421      tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), data);1422    } else {1423      tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), createMode);1424    }142514261427    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1428    if(events.message && events.message.toString().indexOf('1002: Verification Error') > -1) return;1429    const result = getCreateItemResult(events);14301431    expect(result.success).to.be.false;1432  });1433}14341435export async function createItemExpectSuccess(sender: IKeyringPair, collectionId: number, createMode: string, owner: CrossAccountId | string = sender.address) {1436  let newItemId = 0;1437  await usingApi(async (api) => {1438    const to = normalizeAccountId(owner);1439    const itemCountBefore = await getLastTokenId(api, collectionId);1440    const itemBalanceBefore = await getBalance(api, collectionId, to, newItemId);14411442    let tx;1443    if (createMode === 'Fungible') {1444      const createData = {fungible: {value: 10}};1445      tx = api.tx.unique.createItem(collectionId, to, createData as any);1446    } else if (createMode === 'ReFungible') {1447      const createData = {refungible: {pieces: 100}};1448      tx = api.tx.unique.createItem(collectionId, to, createData as any);1449    } else {1450      const createData = {nft: {}};1451      tx = api.tx.unique.createItem(collectionId, to, createData as any);1452    }14531454    const events = await executeTransaction(api, sender, tx);1455    const result = getCreateItemResult(events);14561457    const itemCountAfter = await getLastTokenId(api, collectionId);1458    const itemBalanceAfter = await getBalance(api, collectionId, to, newItemId);14591460    // What to expect1461    // tslint:disable-next-line:no-unused-expression1462    expect(result.success).to.be.true;1463    if (createMode === 'Fungible') {1464      expect(itemBalanceAfter - itemBalanceBefore).to.be.equal(10n);1465    } else {1466      expect(itemCountAfter).to.be.equal(itemCountBefore + 1);1467    }1468    expect(collectionId).to.be.equal(result.collectionId);1469    expect(itemCountAfter.toString()).to.be.equal(result.itemId.toString());1470    expect(to).to.be.deep.equal(result.recipient);1471    newItemId = result.itemId;1472  });1473  return newItemId;1474}14751476export async function createRefungibleToken(api: ApiPromise, sender: IKeyringPair, collectionId: number, amount: bigint, owner: CrossAccountId | IKeyringPair | string = sender.address) : Promise<CreateItemResult> {1477  const createData = {refungible: {pieces: amount}};1478  const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), createData as any);14791480  const events = await submitTransactionAsync(sender, tx);1481  return  getCreateItemResult(events);1482}14831484export async function createItemExpectFailure(sender: IKeyringPair, collectionId: number, createMode: string, owner: CrossAccountId | string = sender.address) {1485  await usingApi(async (api) => {1486    const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), createMode);14871488    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1489    const result = getCreateItemResult(events);14901491    expect(result.success).to.be.false;1492  });1493}14941495export async function setPublicAccessModeExpectSuccess(1496  sender: IKeyringPair, collectionId: number,1497  accessMode: 'Normal' | 'AllowList',1498) {1499  await usingApi(async (api) => {15001501    // Run the transaction1502    const tx = api.tx.unique.setCollectionPermissions(collectionId, {access: accessMode});1503    const events = await submitTransactionAsync(sender, tx);1504    const result = getGenericResult(events);15051506    // Get the collection1507    const collection = await queryCollectionExpectSuccess(api, collectionId);15081509    // What to expect1510    // tslint:disable-next-line:no-unused-expression1511    expect(result.success).to.be.true;1512    expect(collection.permissions.access.toHuman()).to.be.equal(accessMode);1513  });1514}15151516export async function setPublicAccessModeExpectFail(1517  sender: IKeyringPair, collectionId: number,1518  accessMode: 'Normal' | 'AllowList',1519) {1520  await usingApi(async (api) => {15211522    // Run the transaction1523    const tx = api.tx.unique.setCollectionPermissions(collectionId, {access: accessMode});1524    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1525    const result = getGenericResult(events);15261527    // What to expect1528    // tslint:disable-next-line:no-unused-expression1529    expect(result.success).to.be.false;1530  });1531}15321533export async function enableAllowListExpectSuccess(sender: IKeyringPair, collectionId: number) {1534  await setPublicAccessModeExpectSuccess(sender, collectionId, 'AllowList');1535}15361537export async function enableAllowListExpectFail(sender: IKeyringPair, collectionId: number) {1538  await setPublicAccessModeExpectFail(sender, collectionId, 'AllowList');1539}15401541export async function disableAllowListExpectSuccess(sender: IKeyringPair, collectionId: number) {1542  await setPublicAccessModeExpectSuccess(sender, collectionId, 'Normal');1543}15441545export async function setMintPermissionExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {1546  await usingApi(async (api) => {15471548    // Run the transaction1549    const tx = api.tx.unique.setCollectionPermissions(collectionId, {mintMode: enabled});1550    const events = await submitTransactionAsync(sender, tx);1551    const result = getGenericResult(events);1552    expect(result.success).to.be.true;15531554    // Get the collection1555    const collection = await queryCollectionExpectSuccess(api, collectionId);15561557    expect(collection.permissions.mintMode.toHuman()).to.be.equal(enabled);1558  });1559}15601561export async function enablePublicMintingExpectSuccess(sender: IKeyringPair, collectionId: number) {1562  await setMintPermissionExpectSuccess(sender, collectionId, true);1563}15641565export async function setMintPermissionExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {1566  await usingApi(async (api) => {1567    // Run the transaction1568    const tx = api.tx.unique.setCollectionPermissions(collectionId, {mintMode: enabled});1569    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1570    const result = getCreateCollectionResult(events);1571    // tslint:disable-next-line:no-unused-expression1572    expect(result.success).to.be.false;1573  });1574}15751576export async function setChainLimitsExpectFailure(sender: IKeyringPair, limits: IChainLimits) {1577  await usingApi(async (api) => {1578    // Run the transaction1579    const tx = api.tx.unique.setChainLimits(limits);1580    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1581    const result = getCreateCollectionResult(events);1582    // tslint:disable-next-line:no-unused-expression1583    expect(result.success).to.be.false;1584  });1585}15861587export async function isAllowlisted(api: ApiPromise, collectionId: number, address: string | CrossAccountId) {1588  return (await api.rpc.unique.allowed(collectionId, normalizeAccountId(address))).toJSON();1589}15901591export async function addToAllowListExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId | CrossAccountId) {1592  await usingApi(async (api) => {1593    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.false;15941595    // Run the transaction1596    const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1597    const events = await submitTransactionAsync(sender, tx);1598    const result = getGenericResult(events);1599    expect(result.success).to.be.true;16001601    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;1602  });1603}16041605export async function addToAllowListAgainExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId) {1606  await usingApi(async (api) => {16071608    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;16091610    // Run the transaction1611    const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1612    const events = await submitTransactionAsync(sender, tx);1613    const result = getGenericResult(events);1614    expect(result.success).to.be.true;16151616    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;1617  });1618}16191620export async function addToAllowListExpectFail(sender: IKeyringPair, collectionId: number, address: string | AccountId) {1621  await usingApi(async (api) => {16221623    // Run the transaction1624    const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1625    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1626    const result = getGenericResult(events);16271628    // What to expect1629    // tslint:disable-next-line:no-unused-expression1630    expect(result.success).to.be.false;1631  });1632}16331634export async function removeFromAllowListExpectSuccess(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1635  await usingApi(async (api) => {1636    // Run the transaction1637    const tx = api.tx.unique.removeFromAllowList(collectionId, normalizeAccountId(address));1638    const events = await submitTransactionAsync(sender, tx);1639    const result = getGenericResult(events);16401641    // What to expect1642    // tslint:disable-next-line:no-unused-expression1643    expect(result.success).to.be.true;1644  });1645}16461647export async function removeFromAllowListExpectFailure(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1648  await usingApi(async (api) => {1649    // Run the transaction1650    const tx = api.tx.unique.removeFromAllowList(collectionId, normalizeAccountId(address));1651    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1652    const result = getGenericResult(events);16531654    // What to expect1655    // tslint:disable-next-line:no-unused-expression1656    expect(result.success).to.be.false;1657  });1658}16591660export const getDetailedCollectionInfo = async (api: ApiPromise, collectionId: number)1661  : Promise<UpDataStructsRpcCollection | null> => {1662  return (await api.rpc.unique.collectionById(collectionId)).unwrapOr(null);1663};16641665export const getCreatedCollectionCount = async (api: ApiPromise): Promise<number> => {1666  // set global object - collectionsCount1667  return (await api.rpc.unique.collectionStats()).created.toNumber();1668};16691670export async function queryCollectionExpectSuccess(api: ApiPromise, collectionId: number): Promise<UpDataStructsRpcCollection> {1671  return (await api.rpc.unique.collectionById(collectionId)).unwrap();1672}16731674export async function waitNewBlocks(blocksCount = 1): Promise<void> {1675  await usingApi(async (api) => {1676    const promise = new Promise<void>(async (resolve) => {1677      const unsubscribe = await api.rpc.chain.subscribeNewHeads(() => {1678        if (blocksCount > 0) {1679          blocksCount--;1680        } else {1681          unsubscribe();1682          resolve();1683        }1684      });1685    });1686    return promise;1687  });1688}16891690export async function repartitionRFT(1691  api: ApiPromise,1692  collectionId: number,1693  sender: IKeyringPair,1694  tokenId: number,1695  amount: bigint,1696): Promise<boolean> {1697  const tx = api.tx.unique.repartition(collectionId, tokenId, amount);1698  const events = await submitTransactionAsync(sender, tx);1699  const result = getGenericResult(events);17001701  return result.success;1702}17031704export async function itApi(name: string, cb: (apis: { api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair }) => any, opts: { only?: boolean, skip?: boolean } = {}) {1705  let i: any = it;1706  if (opts.only) i = i.only;1707  else if (opts.skip) i = i.skip;1708  i(name, async () => {1709    await usingApi(async (api, privateKeyWrapper) => {1710      await cb({api, privateKeyWrapper});1711    });1712  });1713}17141715itApi.only = (name: string, cb: (apis: { api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair }) => any) => itApi(name, cb, {only: true});1716itApi.skip = (name: string, cb: (apis: { api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair }) => any) => itApi(name, cb, {skip: true});