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

difftreelog

source

tests/src/util/helpers.ts62.8 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';31import {Context} from 'mocha';3233chai.use(chaiAsPromised);34const expect = chai.expect;3536export type CrossAccountId = {37  Substrate: string,38} | {39  Ethereum: string,40};414243export enum Pallets {44  Inflation = 'inflation',45  RmrkCore = 'rmrkcore',46  RmrkEquip = 'rmrkequip',47  ReFungible = 'refungible',48  Fungible = 'fungible',49  NFT = 'nonfungible',50  Scheduler = 'scheduler',51}5253export async function isUnique(): Promise<boolean> {54  return usingApi(async api => {55    const chain = await api.rpc.system.chain();5657    return chain.eq('UNIQUE');58  });59}6061export async function isQuartz(): Promise<boolean> {62  return usingApi(async api => {63    const chain = await api.rpc.system.chain();64    65    return chain.eq('QUARTZ');66  });67}6869let modulesNames: any;70export function getModuleNames(api: ApiPromise): string[] {71  if (typeof modulesNames === 'undefined') 72    modulesNames = api.runtimeMetadata.asLatest.pallets.map(m => m.name.toString().toLowerCase());73  return modulesNames;74}7576export async function missingRequiredPallets(requiredPallets: string[]): Promise<string[]> {77  return await usingApi(async api => {78    const pallets = getModuleNames(api);7980    return requiredPallets.filter(p => !pallets.includes(p));81  });82}8384export async function checkPalletsPresence(requiredPallets: string[]): Promise<boolean> {85  return (await missingRequiredPallets(requiredPallets)).length == 0;86}8788export async function requirePallets(mocha: Context, requiredPallets: string[]) {89  const missingPallets = await missingRequiredPallets(requiredPallets);9091  if (missingPallets.length > 0) {92    const skippingTestMsg = `\tSkipping test "${mocha.test?.title}".`;93    const missingPalletsMsg = `\tThe following pallets are missing:\n\t- ${missingPallets.join('\n\t- ')}`;94    const skipMsg = `${skippingTestMsg}\n${missingPalletsMsg}`;9596    console.error('\x1b[38:5:208m%s\x1b[0m', skipMsg);9798    mocha.skip();99  }100}101102export function normalizeAccountId(input: string | AccountId | CrossAccountId | IKeyringPair): CrossAccountId {103  if (typeof input === 'string') {104    if (input.length >= 47) {105      return {Substrate: input};106    } else if (input.length === 42 && input.startsWith('0x')) {107      return {Ethereum: input.toLowerCase()};108    } else if (input.length === 40 && !input.startsWith('0x')) {109      return {Ethereum: '0x' + input.toLowerCase()};110    } else {111      throw new Error(`Unknown address format: "${input}"`);112    }113  }114  if ('address' in input) {115    return {Substrate: input.address};116  }117  if ('Ethereum' in input) {118    return {119      Ethereum: input.Ethereum.toLowerCase(),120    };121  } else if ('ethereum' in input) {122    return {123      Ethereum: (input as any).ethereum.toLowerCase(),124    };125  } else if ('Substrate' in input) {126    return input;127  } else if ('substrate' in input) {128    return {129      Substrate: (input as any).substrate,130    };131  }132133  // AccountId134  return {Substrate: input.toString()};135}136export function toSubstrateAddress(input: string | CrossAccountId | IKeyringPair): string {137  input = normalizeAccountId(input);138  if ('Substrate' in input) {139    return input.Substrate;140  } else {141    return evmToAddress(input.Ethereum);142  }143}144145export const U128_MAX = (1n << 128n) - 1n;146147const MICROUNIQUE = 1_000_000_000_000n;148const MILLIUNIQUE = 1_000n * MICROUNIQUE;149const CENTIUNIQUE = 10n * MILLIUNIQUE;150export const UNIQUE = 100n * CENTIUNIQUE;151152interface GenericResult<T> {153  success: boolean;154  data: T | null;155}156157interface CreateCollectionResult {158  success: boolean;159  collectionId: number;160}161162interface CreateItemResult {163  success: boolean;164  collectionId: number;165  itemId: number;166  recipient?: CrossAccountId;167  amount?: number;168}169170interface DestroyItemResult {171  success: boolean;172  collectionId: number;173  itemId: number;174  owner: CrossAccountId;175  amount: number;176}177178interface TransferResult {179  collectionId: number;180  itemId: number;181  sender?: CrossAccountId;182  recipient?: CrossAccountId;183  value: bigint;184}185186interface IReFungibleOwner {187  fraction: BN;188  owner: number[];189}190191interface IGetMessage {192  checkMsgUnqMethod: string;193  checkMsgTrsMethod: string;194  checkMsgSysMethod: string;195}196197export interface IFungibleTokenDataType {198  value: number;199}200201export interface IChainLimits {202  collectionNumbersLimit: number;203  accountTokenOwnershipLimit: number;204  collectionsAdminsLimit: number;205  customDataLimit: number;206  nftSponsorTransferTimeout: number;207  fungibleSponsorTransferTimeout: number;208  refungibleSponsorTransferTimeout: number;209  //offchainSchemaLimit: number;210  //constOnChainSchemaLimit: number;211}212213export interface IReFungibleTokenDataType {214  owner: IReFungibleOwner[];215}216217export function uniqueEventMessage(events: EventRecord[]): IGetMessage {218  let checkMsgUnqMethod = '';219  let checkMsgTrsMethod = '';220  let checkMsgSysMethod = '';221  events.forEach(({event: {method, section}}) => {222    if (section === 'common') {223      checkMsgUnqMethod = method;224    } else if (section === 'treasury') {225      checkMsgTrsMethod = method;226    } else if (section === 'system') {227      checkMsgSysMethod = method;228    } else { return null; }229  });230  const result: IGetMessage = {231    checkMsgUnqMethod,232    checkMsgTrsMethod,233    checkMsgSysMethod,234  };235  return result;236}237238export function getEvent<T extends Event>(events: EventRecord[], check: (event: IEvent<AnyTuple>) => event is T): T | undefined {239  const event = events.find(r => check(r.event));240  if (!event) return;241  return event.event as T;242}243244export function getGenericResult<T>(events: EventRecord[]): GenericResult<T>;245export function getGenericResult<T>(246  events: EventRecord[],247  expectSection: string,248  expectMethod: string,249  extractAction: (data: GenericEventData) => T250): GenericResult<T>;251252export function getGenericResult<T>(253  events: EventRecord[],254  expectSection?: string,255  expectMethod?: string,256  extractAction?: (data: GenericEventData) => T,257): GenericResult<T> {258  let success = false;259  let successData = null;260261  events.forEach(({event: {data, method, section}}) => {262    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);263    if (method === 'ExtrinsicSuccess') {264      success = true;265    } else if ((expectSection == section) && (expectMethod == method)) {266      successData = extractAction!(data as any);267    }268  });269270  const result: GenericResult<T> = {271    success,272    data: successData,273  };274  return result;275}276277export function getCreateCollectionResult(events: EventRecord[]): CreateCollectionResult {278  const genericResult = getGenericResult(events, 'common', 'CollectionCreated', (data) => parseInt(data[0].toString(), 10));279  const result: CreateCollectionResult = {280    success: genericResult.success,281    collectionId: genericResult.data ?? 0,282  };283  return result;284}285286export function getCreateItemsResult(events: EventRecord[]): CreateItemResult[] {287  const results: CreateItemResult[] = [];288  289  const genericResult = getGenericResult<CreateItemResult[]>(events, 'common', 'ItemCreated', (data) => {290    const collectionId = parseInt(data[0].toString(), 10);291    const itemId = parseInt(data[1].toString(), 10);292    const recipient = normalizeAccountId(data[2].toJSON() as any);293    const amount = parseInt(data[3].toString(), 10);294295    const itemRes: CreateItemResult = {296      success: true,297      collectionId,298      itemId,299      recipient,300      amount,301    };302303    results.push(itemRes);304    return results;305  });306307  if (!genericResult.success) return [];308  return results;309}310311export function getCreateItemResult(events: EventRecord[]): CreateItemResult {312  const genericResult = getGenericResult(events, 'common', 'ItemCreated', (data) => data.map(function(value) { return value.toJSON(); }));313  314  if (genericResult.data == null) 315    return {316      success: genericResult.success,317      collectionId: 0,318      itemId: 0,319      amount: 0,320    };321  else 322    return {323      success: genericResult.success,324      collectionId: genericResult.data[0] as number,325      itemId: genericResult.data[1] as number,326      recipient: normalizeAccountId(genericResult.data![2] as any),327      amount: genericResult.data[3] as number,328    };329}330331export function getDestroyItemsResult(events: EventRecord[]): DestroyItemResult[] {332  const results: DestroyItemResult[] = [];333  334  const genericResult = getGenericResult<DestroyItemResult[]>(events, 'common', 'ItemDestroyed', (data) => {335    const collectionId = parseInt(data[0].toString(), 10);336    const itemId = parseInt(data[1].toString(), 10);337    const owner = normalizeAccountId(data[2].toJSON() as any);338    const amount = parseInt(data[3].toString(), 10);339340    const itemRes: DestroyItemResult = {341      success: true,342      collectionId,343      itemId,344      owner,345      amount,346    };347348    results.push(itemRes);349    return results;350  });351352  if (!genericResult.success) return [];353  return results;354}355356export function getTransferResult(api: ApiPromise, events: EventRecord[]): TransferResult {357  for (const {event} of events) {358    if (api.events.common.Transfer.is(event)) {359      const [collection, token, sender, recipient, value] = event.data;360      return {361        collectionId: collection.toNumber(),362        itemId: token.toNumber(),363        sender: normalizeAccountId(sender.toJSON() as any),364        recipient: normalizeAccountId(recipient.toJSON() as any),365        value: value.toBigInt(),366      };367    }368  }369  throw new Error('no transfer event');370}371372interface Nft {373  type: 'NFT';374}375376interface Fungible {377  type: 'Fungible';378  decimalPoints: number;379}380381interface ReFungible {382  type: 'ReFungible';383}384385export type CollectionMode = Nft | Fungible | ReFungible;386387export type Property = {388  key: any,389  value: any,390};391392type Permission = {393  mutable: boolean;394  collectionAdmin: boolean;395  tokenOwner: boolean;396}397398type PropertyPermission = {399  key: any;400  permission: Permission;401}402403export type CreateCollectionParams = {404  mode: CollectionMode,405  name: string,406  description: string,407  tokenPrefix: string,408  properties?: Array<Property>,409  propPerm?: Array<PropertyPermission>410};411412const defaultCreateCollectionParams: CreateCollectionParams = {413  description: 'description',414  mode: {type: 'NFT'},415  name: 'name',416  tokenPrefix: 'prefix',417};418419export async function420createCollection(421  api: ApiPromise,422  sender: IKeyringPair,423  params: Partial<CreateCollectionParams> = {},424): Promise<CreateCollectionResult> {425  const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};426427  let modeprm = {};428  if (mode.type === 'NFT') {429    modeprm = {nft: null};430  } else if (mode.type === 'Fungible') {431    modeprm = {fungible: mode.decimalPoints};432  } else if (mode.type === 'ReFungible') {433    modeprm = {refungible: null};434  }435436  const tx = api.tx.unique.createCollectionEx({437    name: strToUTF16(name),438    description: strToUTF16(description),439    tokenPrefix: strToUTF16(tokenPrefix),440    mode: modeprm as any,441  });442  const events = await submitTransactionAsync(sender, tx);443  return getCreateCollectionResult(events);444}445446export async function createCollectionExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {447  const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};448449  let collectionId = 0;450  await usingApi(async (api, privateKeyWrapper) => {451    // Get number of collections before the transaction452    const collectionCountBefore = await getCreatedCollectionCount(api);453454    // Run the CreateCollection transaction455    const alicePrivateKey = privateKeyWrapper('//Alice');456457    const result = await createCollection(api, alicePrivateKey, params);458459    // Get number of collections after the transaction460    const collectionCountAfter = await getCreatedCollectionCount(api);461462    // Get the collection463    const collection = await queryCollectionExpectSuccess(api, result.collectionId);464465    // What to expect466    // tslint:disable-next-line:no-unused-expression467    expect(result.success).to.be.true;468    expect(result.collectionId).to.be.equal(collectionCountAfter);469    // tslint:disable-next-line:no-unused-expression470    expect(collection).to.be.not.null;471    expect(collectionCountAfter).to.be.equal(collectionCountBefore + 1, 'Error: NFT collection NOT created.');472    expect(collection.owner.toString()).to.be.equal(toSubstrateAddress(alicePrivateKey));473    expect(utf16ToStr(collection.name.toJSON() as any)).to.be.equal(name);474    expect(utf16ToStr(collection.description.toJSON() as any)).to.be.equal(description);475    expect(hexToStr(collection.tokenPrefix.toJSON())).to.be.equal(tokenPrefix);476477    collectionId = result.collectionId;478  });479480  return collectionId;481}482483export async function createCollectionWithPropsExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {484  const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};485486  let collectionId = 0;487  await usingApi(async (api, privateKeyWrapper) => {488    // Get number of collections before the transaction489    const collectionCountBefore = await getCreatedCollectionCount(api);490491    // Run the CreateCollection transaction492    const alicePrivateKey = privateKeyWrapper('//Alice');493494    let modeprm = {};495    if (mode.type === 'NFT') {496      modeprm = {nft: null};497    } else if (mode.type === 'Fungible') {498      modeprm = {fungible: mode.decimalPoints};499    } else if (mode.type === 'ReFungible') {500      modeprm = {refungible: null};501    }502503    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});504    const events = await submitTransactionAsync(alicePrivateKey, tx);505    const result = getCreateCollectionResult(events);506507    // Get number of collections after the transaction508    const collectionCountAfter = await getCreatedCollectionCount(api);509510    // Get the collection511    const collection = await queryCollectionExpectSuccess(api, result.collectionId);512513    // What to expect514    // tslint:disable-next-line:no-unused-expression515    expect(result.success).to.be.true;516    expect(result.collectionId).to.be.equal(collectionCountAfter);517    // tslint:disable-next-line:no-unused-expression518    expect(collection).to.be.not.null;519    expect(collectionCountAfter).to.be.equal(collectionCountBefore + 1, 'Error: NFT collection NOT created.');520    expect(collection.owner.toString()).to.be.equal(toSubstrateAddress(alicePrivateKey));521    expect(utf16ToStr(collection.name.toJSON() as any)).to.be.equal(name);522    expect(utf16ToStr(collection.description.toJSON() as any)).to.be.equal(description);523    expect(hexToStr(collection.tokenPrefix.toJSON())).to.be.equal(tokenPrefix);524525526    collectionId = result.collectionId;527  });528529  return collectionId;530}531532export async function createCollectionWithPropsExpectFailure(params: Partial<CreateCollectionParams> = {}) {533  const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};534535  await usingApi(async (api, privateKeyWrapper) => {536    // Get number of collections before the transaction537    const collectionCountBefore = await getCreatedCollectionCount(api);538539    // Run the CreateCollection transaction540    const alicePrivateKey = privateKeyWrapper('//Alice');541542    let modeprm = {};543    if (mode.type === 'NFT') {544      modeprm = {nft: null};545    } else if (mode.type === 'Fungible') {546      modeprm = {fungible: mode.decimalPoints};547    } else if (mode.type === 'ReFungible') {548      modeprm = {refungible: null};549    }550551    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});552    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;553554555    // Get number of collections after the transaction556    const collectionCountAfter = await getCreatedCollectionCount(api);557558    expect(collectionCountAfter).to.be.equal(collectionCountBefore, 'Error: Collection with incorrect data created.');559  });560}561562export async function createCollectionExpectFailure(params: Partial<CreateCollectionParams> = {}) {563  const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};564565  let modeprm = {};566  if (mode.type === 'NFT') {567    modeprm = {nft: null};568  } else if (mode.type === 'Fungible') {569    modeprm = {fungible: mode.decimalPoints};570  } else if (mode.type === 'ReFungible') {571    modeprm = {refungible: null};572  }573574  await usingApi(async (api, privateKeyWrapper) => {575    // Get number of collections before the transaction576    const collectionCountBefore = await getCreatedCollectionCount(api);577578    // Run the CreateCollection transaction579    const alicePrivateKey = privateKeyWrapper('//Alice');580    const tx = api.tx.unique.createCollectionEx({name: strToUTF16(name), description: strToUTF16(description), tokenPrefix: strToUTF16(tokenPrefix), mode: modeprm as any});581    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;582583    // Get number of collections after the transaction584    const collectionCountAfter = await getCreatedCollectionCount(api);585586    // What to expect587    expect(collectionCountAfter).to.be.equal(collectionCountBefore, 'Error: Collection with incorrect data created.');588  });589}590591export async function findUnusedAddress(api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair, seedAddition = ''): Promise<IKeyringPair> {592  let bal = 0n;593  let unused;594  do {595    const randomSeed = 'seed' + Math.floor(Math.random() * Math.floor(10000)) + seedAddition;596    unused = privateKeyWrapper(`//${randomSeed}`);597    bal = (await api.query.system.account(unused.address)).data.free.toBigInt();598  } while (bal !== 0n);599  return unused;600}601602export async function getAllowance(api: ApiPromise, collectionId: number, owner: CrossAccountId | string | IKeyringPair, approved: CrossAccountId | string | IKeyringPair, tokenId: number) {603  return (await api.rpc.unique.allowance(collectionId, normalizeAccountId(owner), normalizeAccountId(approved), tokenId)).toBigInt();604}605606export function findUnusedAddresses(api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair, amount: number): Promise<IKeyringPair[]> {607  return Promise.all(new Array(amount).fill(null).map(() => findUnusedAddress(api, privateKeyWrapper, '_' + Date.now())));608}609610export async function findNotExistingCollection(api: ApiPromise): Promise<number> {611  const totalNumber = await getCreatedCollectionCount(api);612  const newCollection: number = totalNumber + 1;613  return newCollection;614}615616function getDestroyResult(events: EventRecord[]): boolean {617  let success = false;618  events.forEach(({event: {method}}) => {619    if (method == 'ExtrinsicSuccess') {620      success = true;621    }622  });623  return success;624}625626export async function destroyCollectionExpectFailure(collectionId: number, senderSeed = '//Alice') {627  await usingApi(async (api, privateKeyWrapper) => {628    // Run the DestroyCollection transaction629    const alicePrivateKey = privateKeyWrapper(senderSeed);630    const tx = api.tx.unique.destroyCollection(collectionId);631    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;632  });633}634635export async function destroyCollectionExpectSuccess(collectionId: number, senderSeed = '//Alice') {636  await usingApi(async (api, privateKeyWrapper) => {637    // Run the DestroyCollection transaction638    const alicePrivateKey = privateKeyWrapper(senderSeed);639    const tx = api.tx.unique.destroyCollection(collectionId);640    const events = await submitTransactionAsync(alicePrivateKey, tx);641    const result = getDestroyResult(events);642    expect(result).to.be.true;643644    // What to expect645    expect(await getDetailedCollectionInfo(api, collectionId)).to.be.null;646  });647}648649export async function setCollectionLimitsExpectSuccess(sender: IKeyringPair, collectionId: number, limits: any) {650  await usingApi(async (api) => {651    const tx = api.tx.unique.setCollectionLimits(collectionId, limits);652    const events = await submitTransactionAsync(sender, tx);653    const result = getGenericResult(events);654655    expect(result.success).to.be.true;656  });657}658659export const setCollectionPermissionsExpectSuccess = async (sender: IKeyringPair, collectionId: number, permissions: any) => {660  await usingApi(async(api) => {661    const tx = api.tx.unique.setCollectionPermissions(collectionId, permissions);662    const events = await submitTransactionAsync(sender, tx);663    const result = getGenericResult(events);664665    expect(result.success).to.be.true;666  });667};668669export async function setCollectionLimitsExpectFailure(sender: IKeyringPair, collectionId: number, limits: any) {670  await usingApi(async (api) => {671    const tx = api.tx.unique.setCollectionLimits(collectionId, limits);672    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;673    const result = getGenericResult(events);674675    expect(result.success).to.be.false;676  });677}678679export async function setCollectionSponsorExpectSuccess(collectionId: number, sponsor: string, sender = '//Alice') {680  await usingApi(async (api, privateKeyWrapper) => {681682    // Run the transaction683    const senderPrivateKey = privateKeyWrapper(sender);684    const tx = api.tx.unique.setCollectionSponsor(collectionId, sponsor);685    const events = await submitTransactionAsync(senderPrivateKey, tx);686    const result = getGenericResult(events);687688    // Get the collection689    const collection = await queryCollectionExpectSuccess(api, collectionId);690691    // What to expect692    expect(result.success).to.be.true;693    expect(collection.sponsorship.toJSON()).to.deep.equal({694      unconfirmed: sponsor,695    });696  });697}698699export async function removeCollectionSponsorExpectSuccess(collectionId: number, sender = '//Alice') {700  await usingApi(async (api, privateKeyWrapper) => {701702    // Run the transaction703    const alicePrivateKey = privateKeyWrapper(sender);704    const tx = api.tx.unique.removeCollectionSponsor(collectionId);705    const events = await submitTransactionAsync(alicePrivateKey, tx);706    const result = getGenericResult(events);707708    // Get the collection709    const collection = await queryCollectionExpectSuccess(api, collectionId);710711    // What to expect712    expect(result.success).to.be.true;713    expect(collection.sponsorship.toJSON()).to.be.deep.equal({disabled: null});714  });715}716717export async function removeCollectionSponsorExpectFailure(collectionId: number, senderSeed = '//Alice') {718  await usingApi(async (api, privateKeyWrapper) => {719720    // Run the transaction721    const alicePrivateKey = privateKeyWrapper(senderSeed);722    const tx = api.tx.unique.removeCollectionSponsor(collectionId);723    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;724  });725}726727export async function setCollectionSponsorExpectFailure(collectionId: number, sponsor: string, senderSeed = '//Alice') {728  await usingApi(async (api, privateKeyWrapper) => {729730    // Run the transaction731    const alicePrivateKey = privateKeyWrapper(senderSeed);732    const tx = api.tx.unique.setCollectionSponsor(collectionId, sponsor);733    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;734  });735}736737export async function confirmSponsorshipExpectSuccess(collectionId: number, senderSeed = '//Alice') {738  await usingApi(async (api, privateKeyWrapper) => {739740    // Run the transaction741    const sender = privateKeyWrapper(senderSeed);742    await confirmSponsorshipByKeyExpectSuccess(collectionId, sender);743  });744}745746export async function confirmSponsorshipByKeyExpectSuccess(collectionId: number, sender: IKeyringPair) {747  await usingApi(async (api, privateKeyWrapper) => {748749    // Run the transaction750    const tx = api.tx.unique.confirmSponsorship(collectionId);751    const events = await submitTransactionAsync(sender, tx);752    const result = getGenericResult(events);753754    // Get the collection755    const collection = await queryCollectionExpectSuccess(api, collectionId);756757    // What to expect758    expect(result.success).to.be.true;759    expect(collection.sponsorship.toJSON()).to.be.deep.equal({760      confirmed: sender.address,761    });762  });763}764765766export async function confirmSponsorshipExpectFailure(collectionId: number, senderSeed = '//Alice') {767  await usingApi(async (api, privateKeyWrapper) => {768769    // Run the transaction770    const sender = privateKeyWrapper(senderSeed);771    const tx = api.tx.unique.confirmSponsorship(collectionId);772    await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;773  });774}775776export async function enableContractSponsoringExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {777  await usingApi(async (api) => {778    const tx = api.tx.unique.enableContractSponsoring(contractAddress, enable);779    const events = await submitTransactionAsync(sender, tx);780    const result = getGenericResult(events);781782    expect(result.success).to.be.true;783  });784}785786export async function enableContractSponsoringExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {787  await usingApi(async (api) => {788    const tx = api.tx.unique.enableContractSponsoring(contractAddress, enable);789    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;790    const result = getGenericResult(events);791792    expect(result.success).to.be.false;793  });794}795796export async function setTransferFlagExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {797798  await usingApi(async (api) => {799800    const tx = api.tx.unique.setTransfersEnabledFlag(collectionId, enabled);801    const events = await submitTransactionAsync(sender, tx);802    const result = getGenericResult(events);803804    expect(result.success).to.be.true;805  });806}807808export async function setTransferFlagExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {809810  await usingApi(async (api) => {811812    const tx = api.tx.unique.setTransfersEnabledFlag(collectionId, enabled);813    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;814    const result = getGenericResult(events);815816    expect(result.success).to.be.false;817  });818}819820export async function setContractSponsoringRateLimitExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {821  await usingApi(async (api) => {822    const tx = api.tx.unique.setContractSponsoringRateLimit(contractAddress, rateLimit);823    const events = await submitTransactionAsync(sender, tx);824    const result = getGenericResult(events);825826    expect(result.success).to.be.true;827  });828}829830export async function setContractSponsoringRateLimitExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {831  await usingApi(async (api) => {832    const tx = api.tx.unique.setContractSponsoringRateLimit(contractAddress, rateLimit);833    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;834    const result = getGenericResult(events);835836    expect(result.success).to.be.false;837  });838}839840export async function getNextSponsored(841  api: ApiPromise,842  collectionId: number,843  account: string | CrossAccountId,844  tokenId: number,845): Promise<number> {846  return Number((await api.rpc.unique.nextSponsored(collectionId, account, tokenId)).unwrapOr(-1));847}848849export async function toggleContractAllowlistExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, value = true) {850  await usingApi(async (api) => {851    const tx = api.tx.unique.toggleContractAllowList(contractAddress, value);852    const events = await submitTransactionAsync(sender, tx);853    const result = getGenericResult(events);854855    expect(result.success).to.be.true;856  });857}858859export async function isAllowlistedInContract(contractAddress: AccountId | string, user: string) {860  let allowlisted = false;861  await usingApi(async (api) => {862    allowlisted = (await api.query.unique.contractAllowList(contractAddress, user)).toJSON() as boolean;863  });864  return allowlisted;865}866867export async function addToContractAllowListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {868  await usingApi(async (api) => {869    const tx = api.tx.unique.addToContractAllowList(contractAddress.toString(), user.toString());870    const events = await submitTransactionAsync(sender, tx);871    const result = getGenericResult(events);872873    expect(result.success).to.be.true;874  });875}876877export async function removeFromContractAllowListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {878  await usingApi(async (api) => {879    const tx = api.tx.unique.removeFromContractAllowList(contractAddress.toString(), user.toString());880    const events = await submitTransactionAsync(sender, tx);881    const result = getGenericResult(events);882883    expect(result.success).to.be.true;884  });885}886887export async function removeFromContractAllowListExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {888  await usingApi(async (api) => {889    const tx = api.tx.unique.removeFromContractAllowList(contractAddress.toString(), user.toString());890    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;891    const result = getGenericResult(events);892893    expect(result.success).to.be.false;894  });895}896897export interface CreateFungibleData {898  readonly Value: bigint;899}900901export interface CreateReFungibleData { }902export interface CreateNftData { }903904export type CreateItemData = {905  NFT: CreateNftData;906} | {907  Fungible: CreateFungibleData;908} | {909  ReFungible: CreateReFungibleData;910};911912export async function burnItem(api: ApiPromise, sender: IKeyringPair, collectionId: number, tokenId: number, value: number | bigint) : Promise<boolean> {913  const tx = api.tx.unique.burnItem(collectionId, tokenId, value);914  const events = await submitTransactionAsync(sender, tx);915  return getGenericResult(events).success;916}917918export async function burnItemExpectSuccess(sender: IKeyringPair, collectionId: number, tokenId: number, value: number | bigint = 1) {919  await usingApi(async (api) => {920    const balanceBefore = await getBalance(api, collectionId, normalizeAccountId(sender), tokenId);921    // if burning token by admin - use adminButnItemExpectSuccess922    expect(balanceBefore >= BigInt(value)).to.be.true;923924    expect(await burnItem(api, sender, collectionId, tokenId, value)).to.be.true;925926    const balanceAfter = await getBalance(api, collectionId, normalizeAccountId(sender), tokenId);927    expect(balanceAfter + BigInt(value)).to.be.equal(balanceBefore);928  });929}930931export async function burnItemExpectFailure(sender: IKeyringPair, collectionId: number, tokenId: number, value: number | bigint = 1) {932  await usingApi(async (api) => {933    const tx = api.tx.unique.burnItem(collectionId, tokenId, value);934935    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;936    const result = getCreateCollectionResult(events);937    // tslint:disable-next-line:no-unused-expression938    expect(result.success).to.be.false;939  });940}941942export async function burnFromExpectSuccess(sender: IKeyringPair, from: IKeyringPair | CrossAccountId, collectionId: number, tokenId: number, value: number | bigint = 1) {943  await usingApi(async (api) => {944    const tx = api.tx.unique.burnFrom(collectionId, normalizeAccountId(from), tokenId, value);945    const events = await submitTransactionAsync(sender, tx);946    return getGenericResult(events).success;947  });948}949950export async function951approve(952  api: ApiPromise,953  collectionId: number,954  tokenId: number, owner: IKeyringPair, approved: CrossAccountId | string | IKeyringPair, amount: number | bigint,955) {956  const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);957  const events = await submitTransactionAsync(owner, approveUniqueTx);958  return getGenericResult(events).success;959}960961export async function962approveExpectSuccess(963  collectionId: number,964  tokenId: number, owner: IKeyringPair, approved: CrossAccountId | string, amount: number | bigint = 1,965) {966  await usingApi(async (api: ApiPromise) => {967    const result = await approve(api, collectionId, tokenId, owner, approved, amount);968    expect(result).to.be.true;969970    expect(await getAllowance(api, collectionId, owner, approved, tokenId)).to.be.equal(BigInt(amount));971  });972}973974export async function adminApproveFromExpectSuccess(975  collectionId: number,976  tokenId: number, admin: IKeyringPair, owner: CrossAccountId | string, approved: CrossAccountId | string, amount: number | bigint = 1,977) {978  await usingApi(async (api: ApiPromise) => {979    const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);980    const events = await submitTransactionAsync(admin, approveUniqueTx);981    const result = getGenericResult(events);982    expect(result.success).to.be.true;983984    expect(await getAllowance(api, collectionId, owner, approved, tokenId)).to.be.equal(BigInt(amount));985  });986}987988export async function989transferFrom(990  api: ApiPromise,991  collectionId: number,992  tokenId: number,993  accountApproved: IKeyringPair,994  accountFrom: IKeyringPair | CrossAccountId,995  accountTo: IKeyringPair | CrossAccountId,996  value: number | bigint,997) {998  const from = normalizeAccountId(accountFrom);999  const to = normalizeAccountId(accountTo);1000  const transferFromTx = api.tx.unique.transferFrom(from, to, collectionId, tokenId, value);1001  const events = await submitTransactionAsync(accountApproved, transferFromTx);1002  return getGenericResult(events).success;1003}10041005export async function1006transferFromExpectSuccess(1007  collectionId: number,1008  tokenId: number,1009  accountApproved: IKeyringPair,1010  accountFrom: IKeyringPair | CrossAccountId,1011  accountTo: IKeyringPair | CrossAccountId,1012  value: number | bigint = 1,1013  type = 'NFT',1014) {1015  await usingApi(async (api: ApiPromise) => {1016    const from = normalizeAccountId(accountFrom);1017    const to = normalizeAccountId(accountTo);1018    let balanceBefore = 0n;1019    if (type === 'Fungible' || type === 'ReFungible') {1020      balanceBefore = await getBalance(api, collectionId, to, tokenId);1021    }1022    expect(await transferFrom(api, collectionId, tokenId, accountApproved, accountFrom, accountTo, value)).to.be.true;1023    if (type === 'NFT') {1024      expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(to);1025    }1026    if (type === 'Fungible') {1027      const balanceAfter = await getBalance(api, collectionId, to, tokenId);1028      if (JSON.stringify(to) !== JSON.stringify(from)) {1029        expect(balanceAfter - balanceBefore).to.be.equal(BigInt(value));1030      } else {1031        expect(balanceAfter).to.be.equal(balanceBefore);1032      }1033    }1034    if (type === 'ReFungible') {1035      expect(await getBalance(api, collectionId, to, tokenId)).to.be.equal(balanceBefore + BigInt(value));1036    }1037  });1038}10391040export async function1041transferFromExpectFail(1042  collectionId: number,1043  tokenId: number,1044  accountApproved: IKeyringPair,1045  accountFrom: IKeyringPair,1046  accountTo: IKeyringPair,1047  value: number | bigint = 1,1048) {1049  await usingApi(async (api: ApiPromise) => {1050    const transferFromTx = api.tx.unique.transferFrom(normalizeAccountId(accountFrom.address), normalizeAccountId(accountTo.address), collectionId, tokenId, value);1051    const events = await expect(submitTransactionExpectFailAsync(accountApproved, transferFromTx)).to.be.rejected;1052    const result = getCreateCollectionResult(events);1053    // tslint:disable-next-line:no-unused-expression1054    expect(result.success).to.be.false;1055  });1056}10571058/* eslint no-async-promise-executor: "off" */1059export async function getBlockNumber(api: ApiPromise): Promise<number> {1060  return new Promise<number>(async (resolve) => {1061    const unsubscribe = await api.rpc.chain.subscribeNewHeads((head) => {1062      unsubscribe();1063      resolve(head.number.toNumber());1064    });1065  });1066}10671068export async function addCollectionAdminExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | CrossAccountId) {1069  await usingApi(async (api) => {1070    const changeAdminTx = api.tx.unique.addCollectionAdmin(collectionId, normalizeAccountId(address));1071    const events = await submitTransactionAsync(sender, changeAdminTx);1072    const result = getCreateCollectionResult(events);1073    expect(result.success).to.be.true;1074  });1075}10761077export async function adminApproveFromExpectFail(1078  collectionId: number,1079  tokenId: number, admin: IKeyringPair, owner: CrossAccountId | string, approved: CrossAccountId | string, amount: number | bigint = 1,1080) {1081  await usingApi(async (api: ApiPromise) => {1082    const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);1083    const events = await expect(submitTransactionAsync(admin, approveUniqueTx)).to.be.rejected;1084    const result = getGenericResult(events);1085    expect(result.success).to.be.false;1086  });1087}10881089export async function1090getFreeBalance(account: IKeyringPair): Promise<bigint> {1091  let balance = 0n;1092  await usingApi(async (api) => {1093    balance = BigInt((await api.query.system.account(account.address)).data.free.toString());1094  });10951096  return balance;1097}10981099export async function transferBalanceTo(api: ApiPromise, source: IKeyringPair, target: string, amount = 1000n * UNIQUE) {1100  const tx = api.tx.balances.transfer(target, amount);1101  const events = await submitTransactionAsync(source, tx);1102  const result = getGenericResult(events);1103  expect(result.success).to.be.true;1104}11051106export async function1107scheduleExpectSuccess(1108  operationTx: any,1109  sender: IKeyringPair,1110  blockSchedule: number,1111  scheduledId: string,1112  period = 1,1113  repetitions = 1,1114) {1115  await usingApi(async (api: ApiPromise) => {1116    const blockNumber: number | undefined = await getBlockNumber(api);1117    const expectedBlockNumber = blockNumber + blockSchedule;11181119    expect(blockNumber).to.be.greaterThan(0);1120    const scheduleTx = api.tx.scheduler.scheduleNamed( // schedule1121      scheduledId,1122      expectedBlockNumber, 1123      repetitions > 1 ? [period, repetitions] : null, 1124      0, 1125      {Value: operationTx as any},1126    );11271128    const events = await submitTransactionAsync(sender, scheduleTx);1129    expect(getGenericResult(events).success).to.be.true;1130  });1131}11321133export async function1134scheduleExpectFailure(1135  operationTx: any,1136  sender: IKeyringPair,1137  blockSchedule: number,1138  scheduledId: string,1139  period = 1,1140  repetitions = 1,1141) {1142  await usingApi(async (api: ApiPromise) => {1143    const blockNumber: number | undefined = await getBlockNumber(api);1144    const expectedBlockNumber = blockNumber + blockSchedule;11451146    expect(blockNumber).to.be.greaterThan(0);1147    const scheduleTx = api.tx.scheduler.scheduleNamed( // schedule1148      scheduledId,1149      expectedBlockNumber, 1150      repetitions <= 1 ? null : [period, repetitions], 1151      0, 1152      {Value: operationTx as any},1153    );11541155    //const events = 1156    await expect(submitTransactionExpectFailAsync(sender, scheduleTx)).to.be.rejected;1157    //expect(getGenericResult(events).success).to.be.false;1158  });1159}11601161export async function1162scheduleTransferAndWaitExpectSuccess(1163  collectionId: number,1164  tokenId: number,1165  sender: IKeyringPair,1166  recipient: IKeyringPair,1167  value: number | bigint = 1,1168  blockSchedule: number,1169  scheduledId: string,1170) {1171  await usingApi(async (api: ApiPromise) => {1172    await scheduleTransferExpectSuccess(collectionId, tokenId, sender, recipient, value, blockSchedule, scheduledId);11731174    const recipientBalanceBefore = (await api.query.system.account(recipient.address)).data.free.toBigInt();11751176    // sleep for n + 1 blocks1177    await waitNewBlocks(blockSchedule + 1);11781179    const recipientBalanceAfter = (await api.query.system.account(recipient.address)).data.free.toBigInt();11801181    expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(recipient.address));1182    expect(recipientBalanceAfter).to.be.equal(recipientBalanceBefore);1183  });1184}11851186export async function1187scheduleTransferExpectSuccess(1188  collectionId: number,1189  tokenId: number,1190  sender: IKeyringPair,1191  recipient: IKeyringPair,1192  value: number | bigint = 1,1193  blockSchedule: number,1194  scheduledId: string,1195) {1196  await usingApi(async (api: ApiPromise) => {1197    const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient.address), collectionId, tokenId, value);11981199    await scheduleExpectSuccess(transferTx, sender, blockSchedule, scheduledId);12001201    expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(sender.address));1202  });1203}12041205export async function1206scheduleTransferFundsPeriodicExpectSuccess(1207  amount: bigint,1208  sender: IKeyringPair,1209  recipient: IKeyringPair,1210  blockSchedule: number,1211  scheduledId: string,1212  period: number,1213  repetitions: number,1214) {1215  await usingApi(async (api: ApiPromise) => {1216    const transferTx = api.tx.balances.transfer(recipient.address, amount);12171218    const balanceBefore = await getFreeBalance(recipient);1219    1220    await scheduleExpectSuccess(transferTx, sender, blockSchedule, scheduledId, period, repetitions);12211222    expect(await getFreeBalance(recipient)).to.be.equal(balanceBefore);1223  });1224}12251226export async function1227transfer(1228  api: ApiPromise,1229  collectionId: number,1230  tokenId: number,1231  sender: IKeyringPair,1232  recipient: IKeyringPair | CrossAccountId,1233  value: number | bigint,1234) : Promise<boolean> {1235  const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient), collectionId, tokenId, value);1236  const events = await executeTransaction(api, sender, transferTx);1237  return getGenericResult(events).success;1238}12391240export async function1241transferExpectSuccess(1242  collectionId: number,1243  tokenId: number,1244  sender: IKeyringPair,1245  recipient: IKeyringPair | CrossAccountId,1246  value: number | bigint = 1,1247  type = 'NFT',1248) {1249  await usingApi(async (api: ApiPromise) => {1250    const from = normalizeAccountId(sender);1251    const to = normalizeAccountId(recipient);12521253    let balanceBefore = 0n;1254    if (type === 'Fungible' || type === 'ReFungible') {1255      balanceBefore = await getBalance(api, collectionId, to, tokenId);1256    }12571258    const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient), collectionId, tokenId, value);1259    const events = await executeTransaction(api, sender, transferTx);1260    const result = getTransferResult(api, events);12611262    expect(result.collectionId).to.be.equal(collectionId);1263    expect(result.itemId).to.be.equal(tokenId);1264    expect(result.sender).to.be.deep.equal(normalizeAccountId(sender.address));1265    expect(result.recipient).to.be.deep.equal(to);1266    expect(result.value).to.be.equal(BigInt(value));12671268    if (type === 'NFT') {1269      expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(to);1270    }1271    if (type === 'Fungible' || type === 'ReFungible') {1272      const balanceAfter = await getBalance(api, collectionId, to, tokenId);1273      if (JSON.stringify(to) !== JSON.stringify(from)) {1274        expect(balanceAfter - balanceBefore).to.be.equal(BigInt(value));1275      } else {1276        expect(balanceAfter).to.be.equal(balanceBefore);1277      }1278    }1279  });1280}12811282export async function1283transferExpectFailure(1284  collectionId: number,1285  tokenId: number,1286  sender: IKeyringPair,1287  recipient: IKeyringPair | CrossAccountId,1288  value: number | bigint = 1,1289) {1290  await usingApi(async (api: ApiPromise) => {1291    const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient), collectionId, tokenId, value);1292    const events = await expect(submitTransactionExpectFailAsync(sender, transferTx)).to.be.rejected;1293    const result = getGenericResult(events);1294    // if (events && Array.isArray(events)) {1295    //   const result = getCreateCollectionResult(events);1296    // tslint:disable-next-line:no-unused-expression1297    expect(result.success).to.be.false;1298    //}1299  });1300}13011302export async function1303approveExpectFail(1304  collectionId: number,1305  tokenId: number, owner: IKeyringPair, approved: IKeyringPair, amount: number | bigint = 1,1306) {1307  await usingApi(async (api: ApiPromise) => {1308    const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved.address), collectionId, tokenId, amount);1309    const events = await expect(submitTransactionExpectFailAsync(owner, approveUniqueTx)).to.be.rejected;1310    const result = getCreateCollectionResult(events);1311    // tslint:disable-next-line:no-unused-expression1312    expect(result.success).to.be.false;1313  });1314}13151316export async function getBalance(1317  api: ApiPromise,1318  collectionId: number,1319  owner: string | CrossAccountId | IKeyringPair,1320  token: number,1321): Promise<bigint> {1322  return (await api.rpc.unique.balance(collectionId, normalizeAccountId(owner), token)).toBigInt();1323}1324export async function getTokenOwner(1325  api: ApiPromise,1326  collectionId: number,1327  token: number,1328): Promise<CrossAccountId> {1329  const owner = (await api.rpc.unique.tokenOwner(collectionId, token)).toJSON() as any;1330  if (owner == null) throw new Error('owner == null');1331  return normalizeAccountId(owner);1332}1333export async function getTopmostTokenOwner(1334  api: ApiPromise,1335  collectionId: number,1336  token: number,1337): Promise<CrossAccountId> {1338  const owner = (await api.rpc.unique.topmostTokenOwner(collectionId, token)).toJSON() as any;1339  if (owner == null) throw new Error('owner == null');1340  return normalizeAccountId(owner);1341}1342export async function getTokenChildren(1343  api: ApiPromise,1344  collectionId: number,1345  tokenId: number,1346): Promise<UpDataStructsTokenChild[]> {1347  return (await api.rpc.unique.tokenChildren(collectionId, tokenId)).toJSON() as any;1348}1349export async function isTokenExists(1350  api: ApiPromise,1351  collectionId: number,1352  token: number,1353): Promise<boolean> {1354  return (await api.rpc.unique.tokenExists(collectionId, token)).toJSON();1355}1356export async function getLastTokenId(1357  api: ApiPromise,1358  collectionId: number,1359): Promise<number> {1360  return (await api.rpc.unique.lastTokenId(collectionId)).toJSON();1361}1362export async function getAdminList(1363  api: ApiPromise,1364  collectionId: number,1365): Promise<string[]> {1366  return (await api.rpc.unique.adminlist(collectionId)).toHuman() as any;1367}1368export async function getTokenProperties(1369  api: ApiPromise,1370  collectionId: number,1371  tokenId: number,1372  propertyKeys: string[],1373): Promise<UpDataStructsProperty[]> {1374  return (await api.rpc.unique.tokenProperties(collectionId, tokenId, propertyKeys)).toHuman() as any;1375}13761377export async function createFungibleItemExpectSuccess(1378  sender: IKeyringPair,1379  collectionId: number,1380  data: CreateFungibleData,1381  owner: CrossAccountId | string = sender.address,1382) {1383  return await usingApi(async (api) => {1384    const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), {Fungible: data});13851386    const events = await submitTransactionAsync(sender, tx);1387    const result = getCreateItemResult(events);13881389    expect(result.success).to.be.true;1390    return result.itemId;1391  });1392}13931394export async function createMultipleItemsExpectSuccess(sender: IKeyringPair, collectionId: number, itemsData: any, owner: CrossAccountId | string = sender.address) {1395  await usingApi(async (api) => {1396    const to = normalizeAccountId(owner);1397    const tx = api.tx.unique.createMultipleItems(collectionId, to, itemsData);13981399    const events = await submitTransactionAsync(sender, tx);1400    expect(getGenericResult(events).success).to.be.true;1401  });1402}14031404export async function createMultipleItemsWithPropsExpectSuccess(sender: IKeyringPair, collectionId: number, itemsData: any, owner: CrossAccountId | string = sender.address) {1405  await usingApi(async (api) => {1406    const to = normalizeAccountId(owner);1407    const tx = api.tx.unique.createMultipleItems(collectionId, to, itemsData);14081409    const events = await submitTransactionAsync(sender, tx);1410    const result = getCreateItemsResult(events);14111412    for (const res of result) {1413      expect(await api.rpc.unique.tokenProperties(collectionId, res.itemId)).not.to.be.empty;1414    }1415  });1416}14171418export async function createMultipleItemsExWithPropsExpectSuccess(sender: IKeyringPair, collectionId: number, itemsData: any) {1419  await usingApi(async (api) => {1420    const tx = api.tx.unique.createMultipleItemsEx(collectionId, itemsData);14211422    const events = await submitTransactionAsync(sender, tx);1423    const result = getCreateItemsResult(events);14241425    for (const res of result) {1426      expect(await api.rpc.unique.tokenProperties(collectionId, res.itemId)).not.to.be.empty;1427    }1428  });1429}14301431export async function createItemWithPropsExpectSuccess(sender: IKeyringPair, collectionId: number, createMode: string, props:  Array<Property>, owner: CrossAccountId | string = sender.address) {1432  let newItemId = 0;1433  await usingApi(async (api) => {1434    const to = normalizeAccountId(owner);1435    const itemCountBefore = await getLastTokenId(api, collectionId);1436    const itemBalanceBefore = await getBalance(api, collectionId, to, newItemId);14371438    let tx;1439    if (createMode === 'Fungible') {1440      const createData = {fungible: {value: 10}};1441      tx = api.tx.unique.createItem(collectionId, to, createData as any);1442    } else if (createMode === 'ReFungible') {1443      const createData = {refungible: {pieces: 100}};1444      tx = api.tx.unique.createItem(collectionId, to, createData as any);1445    } else {1446      const data = api.createType('UpDataStructsCreateItemData', {NFT: {properties: props}});1447      tx = api.tx.unique.createItem(collectionId, to, data as UpDataStructsCreateItemData);1448    }14491450    const events = await submitTransactionAsync(sender, tx);1451    const result = getCreateItemResult(events);14521453    const itemCountAfter = await getLastTokenId(api, collectionId);1454    const itemBalanceAfter = await getBalance(api, collectionId, to, newItemId);14551456    if (createMode === 'NFT') {1457      expect(await api.rpc.unique.tokenProperties(collectionId, result.itemId)).not.to.be.empty;1458    }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 createItemWithPropsExpectFailure(sender: IKeyringPair, collectionId: number, createMode: string, props: Array<Property>, owner: CrossAccountId | string = sender.address) {1477  await usingApi(async (api) => {14781479    let tx;1480    if (createMode === 'NFT') {1481      const data = api.createType('UpDataStructsCreateItemData', {NFT: {properties: props}}) as UpDataStructsCreateItemData;1482      tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), data);1483    } else {1484      tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), createMode);1485    }148614871488    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1489    if(events.message && events.message.toString().indexOf('1002: Verification Error') > -1) return;1490    const result = getCreateItemResult(events);14911492    expect(result.success).to.be.false;1493  });1494}14951496export async function createItemExpectSuccess(sender: IKeyringPair, collectionId: number, createMode: string, owner: CrossAccountId | string = sender.address) {1497  let newItemId = 0;1498  await usingApi(async (api) => {1499    const to = normalizeAccountId(owner);1500    const itemCountBefore = await getLastTokenId(api, collectionId);1501    const itemBalanceBefore = await getBalance(api, collectionId, to, newItemId);15021503    let tx;1504    if (createMode === 'Fungible') {1505      const createData = {fungible: {value: 10}};1506      tx = api.tx.unique.createItem(collectionId, to, createData as any);1507    } else if (createMode === 'ReFungible') {1508      const createData = {refungible: {pieces: 100}};1509      tx = api.tx.unique.createItem(collectionId, to, createData as any);1510    } else {1511      const createData = {nft: {}};1512      tx = api.tx.unique.createItem(collectionId, to, createData as any);1513    }15141515    const events = await executeTransaction(api, sender, tx);1516    const result = getCreateItemResult(events);15171518    const itemCountAfter = await getLastTokenId(api, collectionId);1519    const itemBalanceAfter = await getBalance(api, collectionId, to, newItemId);15201521    // What to expect1522    // tslint:disable-next-line:no-unused-expression1523    expect(result.success).to.be.true;1524    if (createMode === 'Fungible') {1525      expect(itemBalanceAfter - itemBalanceBefore).to.be.equal(10n);1526    } else {1527      expect(itemCountAfter).to.be.equal(itemCountBefore + 1);1528    }1529    expect(collectionId).to.be.equal(result.collectionId);1530    expect(itemCountAfter.toString()).to.be.equal(result.itemId.toString());1531    expect(to).to.be.deep.equal(result.recipient);1532    newItemId = result.itemId;1533  });1534  return newItemId;1535}15361537export async function createRefungibleToken(api: ApiPromise, sender: IKeyringPair, collectionId: number, amount: bigint, owner: CrossAccountId | IKeyringPair | string = sender.address) : Promise<CreateItemResult> {1538  const createData = {refungible: {pieces: amount}};1539  const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), createData as any);15401541  const events = await submitTransactionAsync(sender, tx);1542  return  getCreateItemResult(events);1543}15441545export async function createItemExpectFailure(sender: IKeyringPair, collectionId: number, createMode: string, owner: CrossAccountId | string = sender.address) {1546  await usingApi(async (api) => {1547    const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), createMode);15481549    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1550    const result = getCreateItemResult(events);15511552    expect(result.success).to.be.false;1553  });1554}15551556export async function setPublicAccessModeExpectSuccess(1557  sender: IKeyringPair, collectionId: number,1558  accessMode: 'Normal' | 'AllowList',1559) {1560  await usingApi(async (api) => {15611562    // Run the transaction1563    const tx = api.tx.unique.setCollectionPermissions(collectionId, {access: accessMode});1564    const events = await submitTransactionAsync(sender, tx);1565    const result = getGenericResult(events);15661567    // Get the collection1568    const collection = await queryCollectionExpectSuccess(api, collectionId);15691570    // What to expect1571    // tslint:disable-next-line:no-unused-expression1572    expect(result.success).to.be.true;1573    expect(collection.permissions.access.toHuman()).to.be.equal(accessMode);1574  });1575}15761577export async function setPublicAccessModeExpectFail(1578  sender: IKeyringPair, collectionId: number,1579  accessMode: 'Normal' | 'AllowList',1580) {1581  await usingApi(async (api) => {15821583    // Run the transaction1584    const tx = api.tx.unique.setCollectionPermissions(collectionId, {access: accessMode});1585    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1586    const result = getGenericResult(events);15871588    // What to expect1589    // tslint:disable-next-line:no-unused-expression1590    expect(result.success).to.be.false;1591  });1592}15931594export async function enableAllowListExpectSuccess(sender: IKeyringPair, collectionId: number) {1595  await setPublicAccessModeExpectSuccess(sender, collectionId, 'AllowList');1596}15971598export async function enableAllowListExpectFail(sender: IKeyringPair, collectionId: number) {1599  await setPublicAccessModeExpectFail(sender, collectionId, 'AllowList');1600}16011602export async function disableAllowListExpectSuccess(sender: IKeyringPair, collectionId: number) {1603  await setPublicAccessModeExpectSuccess(sender, collectionId, 'Normal');1604}16051606export async function setMintPermissionExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {1607  await usingApi(async (api) => {16081609    // Run the transaction1610    const tx = api.tx.unique.setCollectionPermissions(collectionId, {mintMode: enabled});1611    const events = await submitTransactionAsync(sender, tx);1612    const result = getGenericResult(events);1613    expect(result.success).to.be.true;16141615    // Get the collection1616    const collection = await queryCollectionExpectSuccess(api, collectionId);16171618    expect(collection.permissions.mintMode.toHuman()).to.be.equal(enabled);1619  });1620}16211622export async function enablePublicMintingExpectSuccess(sender: IKeyringPair, collectionId: number) {1623  await setMintPermissionExpectSuccess(sender, collectionId, true);1624}16251626export async function setMintPermissionExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {1627  await usingApi(async (api) => {1628    // Run the transaction1629    const tx = api.tx.unique.setCollectionPermissions(collectionId, {mintMode: enabled});1630    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1631    const result = getCreateCollectionResult(events);1632    // tslint:disable-next-line:no-unused-expression1633    expect(result.success).to.be.false;1634  });1635}16361637export async function setChainLimitsExpectFailure(sender: IKeyringPair, limits: IChainLimits) {1638  await usingApi(async (api) => {1639    // Run the transaction1640    const tx = api.tx.unique.setChainLimits(limits);1641    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1642    const result = getCreateCollectionResult(events);1643    // tslint:disable-next-line:no-unused-expression1644    expect(result.success).to.be.false;1645  });1646}16471648export async function isAllowlisted(api: ApiPromise, collectionId: number, address: string | CrossAccountId) {1649  return (await api.rpc.unique.allowed(collectionId, normalizeAccountId(address))).toJSON();1650}16511652export async function addToAllowListExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId | CrossAccountId) {1653  await usingApi(async (api) => {1654    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.false;16551656    // Run the transaction1657    const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1658    const events = await submitTransactionAsync(sender, tx);1659    const result = getGenericResult(events);1660    expect(result.success).to.be.true;16611662    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;1663  });1664}16651666export async function addToAllowListAgainExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId) {1667  await usingApi(async (api) => {16681669    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;16701671    // Run the transaction1672    const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1673    const events = await submitTransactionAsync(sender, tx);1674    const result = getGenericResult(events);1675    expect(result.success).to.be.true;16761677    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;1678  });1679}16801681export async function addToAllowListExpectFail(sender: IKeyringPair, collectionId: number, address: string | AccountId) {1682  await usingApi(async (api) => {16831684    // Run the transaction1685    const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1686    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1687    const result = getGenericResult(events);16881689    // What to expect1690    // tslint:disable-next-line:no-unused-expression1691    expect(result.success).to.be.false;1692  });1693}16941695export async function removeFromAllowListExpectSuccess(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1696  await usingApi(async (api) => {1697    // Run the transaction1698    const tx = api.tx.unique.removeFromAllowList(collectionId, normalizeAccountId(address));1699    const events = await submitTransactionAsync(sender, tx);1700    const result = getGenericResult(events);17011702    // What to expect1703    // tslint:disable-next-line:no-unused-expression1704    expect(result.success).to.be.true;1705  });1706}17071708export async function removeFromAllowListExpectFailure(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1709  await usingApi(async (api) => {1710    // Run the transaction1711    const tx = api.tx.unique.removeFromAllowList(collectionId, normalizeAccountId(address));1712    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1713    const result = getGenericResult(events);17141715    // What to expect1716    // tslint:disable-next-line:no-unused-expression1717    expect(result.success).to.be.false;1718  });1719}17201721export const getDetailedCollectionInfo = async (api: ApiPromise, collectionId: number)1722  : Promise<UpDataStructsRpcCollection | null> => {1723  return (await api.rpc.unique.collectionById(collectionId)).unwrapOr(null);1724};17251726export const getCreatedCollectionCount = async (api: ApiPromise): Promise<number> => {1727  // set global object - collectionsCount1728  return (await api.rpc.unique.collectionStats()).created.toNumber();1729};17301731export async function queryCollectionExpectSuccess(api: ApiPromise, collectionId: number): Promise<UpDataStructsRpcCollection> {1732  return (await api.rpc.unique.collectionById(collectionId)).unwrap();1733}17341735export async function waitNewBlocks(blocksCount = 1): Promise<void> {1736  await usingApi(async (api) => {1737    const promise = new Promise<void>(async (resolve) => {1738      const unsubscribe = await api.rpc.chain.subscribeNewHeads(() => {1739        if (blocksCount > 0) {1740          blocksCount--;1741        } else {1742          unsubscribe();1743          resolve();1744        }1745      });1746    });1747    return promise;1748  });1749}17501751export async function repartitionRFT(1752  api: ApiPromise,1753  collectionId: number,1754  sender: IKeyringPair,1755  tokenId: number,1756  amount: bigint,1757): Promise<boolean> {1758  const tx = api.tx.unique.repartition(collectionId, tokenId, amount);1759  const events = await submitTransactionAsync(sender, tx);1760  const result = getGenericResult(events);17611762  return result.success;1763}17641765export async function itApi(name: string, cb: (apis: { api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair }) => any, opts: { only?: boolean, skip?: boolean } = {}) {1766  let i: any = it;1767  if (opts.only) i = i.only;1768  else if (opts.skip) i = i.skip;1769  i(name, async () => {1770    await usingApi(async (api, privateKeyWrapper) => {1771      await cb({api, privateKeyWrapper});1772    });1773  });1774}17751776itApi.only = (name: string, cb: (apis: { api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair }) => any) => itApi(name, cb, {only: true});1777itApi.skip = (name: string, cb: (apis: { api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair }) => any) => itApi(name, cb, {skip: true});