git.delta.rocks / unique-network / refs/commits / 0d4bed32f053

difftreelog

source

tests/src/util/helpers.ts63.6 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, BlockNumber} 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 {AnyNumber} from '@polkadot/types-codec/types';25import BN from 'bn.js';26import chai from 'chai';27import chaiAsPromised from 'chai-as-promised';28import {default as usingApi, executeTransaction, submitTransactionAsync, submitTransactionExpectFailAsync} from '../substrate/substrate-api';29import {hexToStr, strToUTF16, utf16ToStr} from './util';30import {UpDataStructsRpcCollection, UpDataStructsCreateItemData, UpDataStructsProperty} from '@polkadot/types/lookup';31import {UpDataStructsTokenChild} from '../interfaces';32import {Context} from 'mocha';3334chai.use(chaiAsPromised);35const expect = chai.expect;3637export type CrossAccountId = {38  Substrate: string,39} | {40  Ethereum: string,41};424344export enum Pallets {45  Inflation = 'inflation',46  RmrkCore = 'rmrkcore',47  RmrkEquip = 'rmrkequip',48  ReFungible = 'refungible',49  Fungible = 'fungible',50  NFT = 'nonfungible',51  Scheduler = 'scheduler',52  AppPromotion = 'apppromotion',53}5455export async function isUnique(): Promise<boolean> {56  return usingApi(async api => {57    const chain = await api.rpc.system.chain();5859    return chain.eq('UNIQUE');60  });61}6263export async function isQuartz(): Promise<boolean> {64  return usingApi(async api => {65    const chain = await api.rpc.system.chain();66    67    return chain.eq('QUARTZ');68  });69}7071let modulesNames: any;72export function getModuleNames(api: ApiPromise): string[] {73  if (typeof modulesNames === 'undefined') 74    modulesNames = api.runtimeMetadata.asLatest.pallets.map(m => m.name.toString().toLowerCase());75  return modulesNames;76}7778export async function missingRequiredPallets(requiredPallets: string[]): Promise<string[]> {79  return await usingApi(async api => {80    const pallets = getModuleNames(api);8182    return requiredPallets.filter(p => !pallets.includes(p));83  });84}8586export async function checkPalletsPresence(requiredPallets: string[]): Promise<boolean> {87  return (await missingRequiredPallets(requiredPallets)).length == 0;88}8990export async function requirePallets(mocha: Context, requiredPallets: string[]) {91  const missingPallets = await missingRequiredPallets(requiredPallets);9293  if (missingPallets.length > 0) {94    const skippingTestMsg = `\tSkipping test "${mocha.test?.title}".`;95    const missingPalletsMsg = `\tThe following pallets are missing:\n\t- ${missingPallets.join('\n\t- ')}`;96    const skipMsg = `${skippingTestMsg}\n${missingPalletsMsg}`;9798    console.error('\x1b[38:5:208m%s\x1b[0m', skipMsg);99100    mocha.skip();101  }102}103104export function bigIntToSub(api: ApiPromise, number: bigint) {105  return api.registry.createType('AccountId', '0x' + number.toString(16).padStart(64, '0')).toJSON();106}107108export function normalizeAccountId(input: string | AccountId | CrossAccountId | IKeyringPair): CrossAccountId {109  if (typeof input === 'string') {110    if (input.length >= 47) {111      return {Substrate: input};112    } else if (input.length === 42 && input.startsWith('0x')) {113      return {Ethereum: input.toLowerCase()};114    } else if (input.length === 40 && !input.startsWith('0x')) {115      return {Ethereum: '0x' + input.toLowerCase()};116    } else {117      throw new Error(`Unknown address format: "${input}"`);118    }119  }120  if ('address' in input) {121    return {Substrate: input.address};122  }123  if ('Ethereum' in input) {124    return {125      Ethereum: input.Ethereum.toLowerCase(),126    };127  } else if ('ethereum' in input) {128    return {129      Ethereum: (input as any).ethereum.toLowerCase(),130    };131  } else if ('Substrate' in input) {132    return input;133  } else if ('substrate' in input) {134    return {135      Substrate: (input as any).substrate,136    };137  }138139  // AccountId140  return {Substrate: input.toString()};141}142export function toSubstrateAddress(input: string | CrossAccountId | IKeyringPair): string {143  input = normalizeAccountId(input);144  if ('Substrate' in input) {145    return input.Substrate;146  } else {147    return evmToAddress(input.Ethereum);148  }149}150151export const U128_MAX = (1n << 128n) - 1n;152153const MICROUNIQUE = 1_000_000_000_000n;154const MILLIUNIQUE = 1_000n * MICROUNIQUE;155const CENTIUNIQUE = 10n * MILLIUNIQUE;156export const UNIQUE = 100n * CENTIUNIQUE;157158interface GenericResult<T> {159  success: boolean;160  data: T | null;161}162163interface CreateCollectionResult {164  success: boolean;165  collectionId: number;166}167168interface CreateItemResult {169  success: boolean;170  collectionId: number;171  itemId: number;172  recipient?: CrossAccountId;173  amount?: number;174}175176interface DestroyItemResult {177  success: boolean;178  collectionId: number;179  itemId: number;180  owner: CrossAccountId;181  amount: number;182}183184interface TransferResult {185  collectionId: number;186  itemId: number;187  sender?: CrossAccountId;188  recipient?: CrossAccountId;189  value: bigint;190}191192interface IReFungibleOwner {193  fraction: BN;194  owner: number[];195}196197interface IGetMessage {198  checkMsgUnqMethod: string;199  checkMsgTrsMethod: string;200  checkMsgSysMethod: string;201}202203export interface IFungibleTokenDataType {204  value: number;205}206207export interface IChainLimits {208  collectionNumbersLimit: number;209  accountTokenOwnershipLimit: number;210  collectionsAdminsLimit: number;211  customDataLimit: number;212  nftSponsorTransferTimeout: number;213  fungibleSponsorTransferTimeout: number;214  refungibleSponsorTransferTimeout: number;215  //offchainSchemaLimit: number;216  //constOnChainSchemaLimit: number;217}218219export interface IReFungibleTokenDataType {220  owner: IReFungibleOwner[];221}222223export function uniqueEventMessage(events: EventRecord[]): IGetMessage {224  let checkMsgUnqMethod = '';225  let checkMsgTrsMethod = '';226  let checkMsgSysMethod = '';227  events.forEach(({event: {method, section}}) => {228    if (section === 'common') {229      checkMsgUnqMethod = method;230    } else if (section === 'treasury') {231      checkMsgTrsMethod = method;232    } else if (section === 'system') {233      checkMsgSysMethod = method;234    } else { return null; }235  });236  const result: IGetMessage = {237    checkMsgUnqMethod,238    checkMsgTrsMethod,239    checkMsgSysMethod,240  };241  return result;242}243244export function getEvent<T extends Event>(events: EventRecord[], check: (event: IEvent<AnyTuple>) => event is T): T | undefined {245  const event = events.find(r => check(r.event));246  if (!event) return;247  return event.event as T;248}249250export function getGenericResult<T>(events: EventRecord[]): GenericResult<T>;251export function getGenericResult<T>(252  events: EventRecord[],253  expectSection: string,254  expectMethod: string,255  extractAction: (data: GenericEventData) => T256): GenericResult<T>;257258export function getGenericResult<T>(259  events: EventRecord[],260  expectSection?: string,261  expectMethod?: string,262  extractAction?: (data: GenericEventData) => T,263): GenericResult<T> {264  let success = false;265  let successData = null;266267  events.forEach(({event: {data, method, section}}) => {268    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);269    if (method === 'ExtrinsicSuccess') {270      success = true;271    } else if ((expectSection == section) && (expectMethod == method)) {272      successData = extractAction!(data as any);273    }274  });275276  const result: GenericResult<T> = {277    success,278    data: successData,279  };280  return result;281}282283export function getCreateCollectionResult(events: EventRecord[]): CreateCollectionResult {284  const genericResult = getGenericResult(events, 'common', 'CollectionCreated', (data) => parseInt(data[0].toString(), 10));285  const result: CreateCollectionResult = {286    success: genericResult.success,287    collectionId: genericResult.data ?? 0,288  };289  return result;290}291292export function getCreateItemsResult(events: EventRecord[]): CreateItemResult[] {293  const results: CreateItemResult[] = [];294  295  const genericResult = getGenericResult<CreateItemResult[]>(events, 'common', 'ItemCreated', (data) => {296    const collectionId = parseInt(data[0].toString(), 10);297    const itemId = parseInt(data[1].toString(), 10);298    const recipient = normalizeAccountId(data[2].toJSON() as any);299    const amount = parseInt(data[3].toString(), 10);300301    const itemRes: CreateItemResult = {302      success: true,303      collectionId,304      itemId,305      recipient,306      amount,307    };308309    results.push(itemRes);310    return results;311  });312313  if (!genericResult.success) return [];314  return results;315}316317export function getCreateItemResult(events: EventRecord[]): CreateItemResult {318  const genericResult = getGenericResult(events, 'common', 'ItemCreated', (data) => data.map(function(value) { return value.toJSON(); }));319  320  if (genericResult.data == null) 321    return {322      success: genericResult.success,323      collectionId: 0,324      itemId: 0,325      amount: 0,326    };327  else 328    return {329      success: genericResult.success,330      collectionId: genericResult.data[0] as number,331      itemId: genericResult.data[1] as number,332      recipient: normalizeAccountId(genericResult.data![2] as any),333      amount: genericResult.data[3] as number,334    };335}336337export function getDestroyItemsResult(events: EventRecord[]): DestroyItemResult[] {338  const results: DestroyItemResult[] = [];339  340  const genericResult = getGenericResult<DestroyItemResult[]>(events, 'common', 'ItemDestroyed', (data) => {341    const collectionId = parseInt(data[0].toString(), 10);342    const itemId = parseInt(data[1].toString(), 10);343    const owner = normalizeAccountId(data[2].toJSON() as any);344    const amount = parseInt(data[3].toString(), 10);345346    const itemRes: DestroyItemResult = {347      success: true,348      collectionId,349      itemId,350      owner,351      amount,352    };353354    results.push(itemRes);355    return results;356  });357358  if (!genericResult.success) return [];359  return results;360}361362export function getTransferResult(api: ApiPromise, events: EventRecord[]): TransferResult {363  for (const {event} of events) {364    if (api.events.common.Transfer.is(event)) {365      const [collection, token, sender, recipient, value] = event.data;366      return {367        collectionId: collection.toNumber(),368        itemId: token.toNumber(),369        sender: normalizeAccountId(sender.toJSON() as any),370        recipient: normalizeAccountId(recipient.toJSON() as any),371        value: value.toBigInt(),372      };373    }374  }375  throw new Error('no transfer event');376}377378interface Nft {379  type: 'NFT';380}381382interface Fungible {383  type: 'Fungible';384  decimalPoints: number;385}386387interface ReFungible {388  type: 'ReFungible';389}390391export type CollectionMode = Nft | Fungible | ReFungible;392393export type Property = {394  key: any,395  value: any,396};397398type Permission = {399  mutable: boolean;400  collectionAdmin: boolean;401  tokenOwner: boolean;402}403404type PropertyPermission = {405  key: any;406  permission: Permission;407}408409export type CreateCollectionParams = {410  mode: CollectionMode,411  name: string,412  description: string,413  tokenPrefix: string,414  properties?: Array<Property>,415  propPerm?: Array<PropertyPermission>416};417418const defaultCreateCollectionParams: CreateCollectionParams = {419  description: 'description',420  mode: {type: 'NFT'},421  name: 'name',422  tokenPrefix: 'prefix',423};424425export async function426createCollection(427  api: ApiPromise,428  sender: IKeyringPair,429  params: Partial<CreateCollectionParams> = {},430): Promise<CreateCollectionResult> {431  const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};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({443    name: strToUTF16(name),444    description: strToUTF16(description),445    tokenPrefix: strToUTF16(tokenPrefix),446    mode: modeprm as any,447  });448  const events = await executeTransaction(api, sender, tx);449  return getCreateCollectionResult(events);450}451452export async function createCollectionExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {453  const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};454455  let collectionId = 0;456  await usingApi(async (api, privateKeyWrapper) => {457    // Get number of collections before the transaction458    const collectionCountBefore = await getCreatedCollectionCount(api);459460    // Run the CreateCollection transaction461    const alicePrivateKey = privateKeyWrapper('//Alice');462463    const result = await createCollection(api, alicePrivateKey, params);464465    // Get number of collections after the transaction466    const collectionCountAfter = await getCreatedCollectionCount(api);467468    // Get the collection469    const collection = await queryCollectionExpectSuccess(api, result.collectionId);470471    // What to expect472    // tslint:disable-next-line:no-unused-expression473    expect(result.success).to.be.true;474    expect(result.collectionId).to.be.equal(collectionCountAfter);475    // tslint:disable-next-line:no-unused-expression476    expect(collection).to.be.not.null;477    expect(collectionCountAfter).to.be.equal(collectionCountBefore + 1, 'Error: NFT collection NOT created.');478    expect(collection.owner.toString()).to.be.equal(toSubstrateAddress(alicePrivateKey));479    expect(utf16ToStr(collection.name.toJSON() as any)).to.be.equal(name);480    expect(utf16ToStr(collection.description.toJSON() as any)).to.be.equal(description);481    expect(hexToStr(collection.tokenPrefix.toJSON())).to.be.equal(tokenPrefix);482483    collectionId = result.collectionId;484  });485486  return collectionId;487}488489export async function createCollectionWithPropsExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {490  const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};491492  let collectionId = 0;493  await usingApi(async (api, privateKeyWrapper) => {494    // Get number of collections before the transaction495    const collectionCountBefore = await getCreatedCollectionCount(api);496497    // Run the CreateCollection transaction498    const alicePrivateKey = privateKeyWrapper('//Alice');499500    let modeprm = {};501    if (mode.type === 'NFT') {502      modeprm = {nft: null};503    } else if (mode.type === 'Fungible') {504      modeprm = {fungible: mode.decimalPoints};505    } else if (mode.type === 'ReFungible') {506      modeprm = {refungible: null};507    }508509    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});510    const events = await submitTransactionAsync(alicePrivateKey, tx);511    const result = getCreateCollectionResult(events);512513    // Get number of collections after the transaction514    const collectionCountAfter = await getCreatedCollectionCount(api);515516    // Get the collection517    const collection = await queryCollectionExpectSuccess(api, result.collectionId);518519    // What to expect520    // tslint:disable-next-line:no-unused-expression521    expect(result.success).to.be.true;522    expect(result.collectionId).to.be.equal(collectionCountAfter);523    // tslint:disable-next-line:no-unused-expression524    expect(collection).to.be.not.null;525    expect(collectionCountAfter).to.be.equal(collectionCountBefore + 1, 'Error: NFT collection NOT created.');526    expect(collection.owner.toString()).to.be.equal(toSubstrateAddress(alicePrivateKey));527    expect(utf16ToStr(collection.name.toJSON() as any)).to.be.equal(name);528    expect(utf16ToStr(collection.description.toJSON() as any)).to.be.equal(description);529    expect(hexToStr(collection.tokenPrefix.toJSON())).to.be.equal(tokenPrefix);530531532    collectionId = result.collectionId;533  });534535  return collectionId;536}537538export async function createCollectionWithPropsExpectFailure(params: Partial<CreateCollectionParams> = {}) {539  const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};540541  await usingApi(async (api, privateKeyWrapper) => {542    // Get number of collections before the transaction543    const collectionCountBefore = await getCreatedCollectionCount(api);544545    // Run the CreateCollection transaction546    const alicePrivateKey = privateKeyWrapper('//Alice');547548    let modeprm = {};549    if (mode.type === 'NFT') {550      modeprm = {nft: null};551    } else if (mode.type === 'Fungible') {552      modeprm = {fungible: mode.decimalPoints};553    } else if (mode.type === 'ReFungible') {554      modeprm = {refungible: null};555    }556557    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});558    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;559560561    // Get number of collections after the transaction562    const collectionCountAfter = await getCreatedCollectionCount(api);563564    expect(collectionCountAfter).to.be.equal(collectionCountBefore, 'Error: Collection with incorrect data created.');565  });566}567568export async function createCollectionExpectFailure(params: Partial<CreateCollectionParams> = {}) {569  const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};570571  let modeprm = {};572  if (mode.type === 'NFT') {573    modeprm = {nft: null};574  } else if (mode.type === 'Fungible') {575    modeprm = {fungible: mode.decimalPoints};576  } else if (mode.type === 'ReFungible') {577    modeprm = {refungible: null};578  }579580  await usingApi(async (api, privateKeyWrapper) => {581    // Get number of collections before the transaction582    const collectionCountBefore = await getCreatedCollectionCount(api);583584    // Run the CreateCollection transaction585    const alicePrivateKey = privateKeyWrapper('//Alice');586    const tx = api.tx.unique.createCollectionEx({name: strToUTF16(name), description: strToUTF16(description), tokenPrefix: strToUTF16(tokenPrefix), mode: modeprm as any});587    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;588589    // Get number of collections after the transaction590    const collectionCountAfter = await getCreatedCollectionCount(api);591592    // What to expect593    expect(collectionCountAfter).to.be.equal(collectionCountBefore, 'Error: Collection with incorrect data created.');594  });595}596597export async function findUnusedAddress(api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair, seedAddition = ''): Promise<IKeyringPair> {598  let bal = 0n;599  let unused;600  do {601    const randomSeed = 'seed' + Math.floor(Math.random() * Math.floor(10000)) + seedAddition;602    unused = privateKeyWrapper(`//${randomSeed}`);603    bal = (await api.query.system.account(unused.address)).data.free.toBigInt();604  } while (bal !== 0n);605  return unused;606}607608export async function getAllowance(api: ApiPromise, collectionId: number, owner: CrossAccountId | string | IKeyringPair, approved: CrossAccountId | string | IKeyringPair, tokenId: number) {609  return (await api.rpc.unique.allowance(collectionId, normalizeAccountId(owner), normalizeAccountId(approved), tokenId)).toBigInt();610}611612export function findUnusedAddresses(api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair, amount: number): Promise<IKeyringPair[]> {613  return Promise.all(new Array(amount).fill(null).map(() => findUnusedAddress(api, privateKeyWrapper, '_' + Date.now())));614}615616export async function findNotExistingCollection(api: ApiPromise): Promise<number> {617  const totalNumber = await getCreatedCollectionCount(api);618  const newCollection: number = totalNumber + 1;619  return newCollection;620}621622function getDestroyResult(events: EventRecord[]): boolean {623  let success = false;624  events.forEach(({event: {method}}) => {625    if (method == 'ExtrinsicSuccess') {626      success = true;627    }628  });629  return success;630}631632export async function destroyCollectionExpectFailure(collectionId: number, senderSeed = '//Alice') {633  await usingApi(async (api, privateKeyWrapper) => {634    // Run the DestroyCollection transaction635    const alicePrivateKey = privateKeyWrapper(senderSeed);636    const tx = api.tx.unique.destroyCollection(collectionId);637    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;638  });639}640641export async function destroyCollectionExpectSuccess(collectionId: number, senderSeed = '//Alice') {642  await usingApi(async (api, privateKeyWrapper) => {643    // Run the DestroyCollection transaction644    const alicePrivateKey = privateKeyWrapper(senderSeed);645    const tx = api.tx.unique.destroyCollection(collectionId);646    const events = await submitTransactionAsync(alicePrivateKey, tx);647    const result = getDestroyResult(events);648    expect(result).to.be.true;649650    // What to expect651    expect(await getDetailedCollectionInfo(api, collectionId)).to.be.null;652  });653}654655export async function setCollectionLimitsExpectSuccess(sender: IKeyringPair, collectionId: number, limits: any) {656  await usingApi(async (api) => {657    const tx = api.tx.unique.setCollectionLimits(collectionId, limits);658    const events = await submitTransactionAsync(sender, tx);659    const result = getGenericResult(events);660661    expect(result.success).to.be.true;662  });663}664665export const setCollectionPermissionsExpectSuccess = async (sender: IKeyringPair, collectionId: number, permissions: any) => {666  await usingApi(async(api) => {667    const tx = api.tx.unique.setCollectionPermissions(collectionId, permissions);668    const events = await submitTransactionAsync(sender, tx);669    const result = getGenericResult(events);670671    expect(result.success).to.be.true;672  });673};674675export async function setCollectionLimitsExpectFailure(sender: IKeyringPair, collectionId: number, limits: any) {676  await usingApi(async (api) => {677    const tx = api.tx.unique.setCollectionLimits(collectionId, limits);678    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;679    const result = getGenericResult(events);680681    expect(result.success).to.be.false;682  });683}684685export async function setCollectionSponsorExpectSuccess(collectionId: number, sponsor: string, sender = '//Alice') {686  await usingApi(async (api, privateKeyWrapper) => {687688    // Run the transaction689    const senderPrivateKey = privateKeyWrapper(sender);690    const tx = api.tx.unique.setCollectionSponsor(collectionId, sponsor);691    const events = await submitTransactionAsync(senderPrivateKey, tx);692    const result = getGenericResult(events);693694    // Get the collection695    const collection = await queryCollectionExpectSuccess(api, collectionId);696697    // What to expect698    expect(result.success).to.be.true;699    expect(collection.sponsorship.toJSON()).to.deep.equal({700      unconfirmed: sponsor,701    });702  });703}704705export async function removeCollectionSponsorExpectSuccess(collectionId: number, sender = '//Alice') {706  await usingApi(async (api, privateKeyWrapper) => {707708    // Run the transaction709    const alicePrivateKey = privateKeyWrapper(sender);710    const tx = api.tx.unique.removeCollectionSponsor(collectionId);711    const events = await submitTransactionAsync(alicePrivateKey, tx);712    const result = getGenericResult(events);713714    // Get the collection715    const collection = await queryCollectionExpectSuccess(api, collectionId);716717    // What to expect718    expect(result.success).to.be.true;719    expect(collection.sponsorship.toJSON()).to.be.deep.equal({disabled: null});720  });721}722723export async function removeCollectionSponsorExpectFailure(collectionId: number, senderSeed = '//Alice') {724  await usingApi(async (api, privateKeyWrapper) => {725726    // Run the transaction727    const alicePrivateKey = privateKeyWrapper(senderSeed);728    const tx = api.tx.unique.removeCollectionSponsor(collectionId);729    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;730  });731}732733export async function setCollectionSponsorExpectFailure(collectionId: number, sponsor: string, senderSeed = '//Alice') {734  await usingApi(async (api, privateKeyWrapper) => {735736    // Run the transaction737    const alicePrivateKey = privateKeyWrapper(senderSeed);738    const tx = api.tx.unique.setCollectionSponsor(collectionId, sponsor);739    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;740  });741}742743export async function confirmSponsorshipExpectSuccess(collectionId: number, senderSeed = '//Alice') {744  await usingApi(async (api, privateKeyWrapper) => {745746    // Run the transaction747    const sender = privateKeyWrapper(senderSeed);748    await confirmSponsorshipByKeyExpectSuccess(collectionId, sender);749  });750}751752export async function confirmSponsorshipByKeyExpectSuccess(collectionId: number, sender: IKeyringPair) {753  await usingApi(async (api, privateKeyWrapper) => {754755    // Run the transaction756    const tx = api.tx.unique.confirmSponsorship(collectionId);757    const events = await submitTransactionAsync(sender, tx);758    const result = getGenericResult(events);759760    // Get the collection761    const collection = await queryCollectionExpectSuccess(api, collectionId);762763    // What to expect764    expect(result.success).to.be.true;765    expect(collection.sponsorship.toJSON()).to.be.deep.equal({766      confirmed: sender.address,767    });768  });769}770771772export async function confirmSponsorshipExpectFailure(collectionId: number, senderSeed = '//Alice') {773  await usingApi(async (api, privateKeyWrapper) => {774775    // Run the transaction776    const sender = privateKeyWrapper(senderSeed);777    const tx = api.tx.unique.confirmSponsorship(collectionId);778    await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;779  });780}781782export async function enableContractSponsoringExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {783  await usingApi(async (api) => {784    const tx = api.tx.unique.enableContractSponsoring(contractAddress, enable);785    const events = await submitTransactionAsync(sender, tx);786    const result = getGenericResult(events);787788    expect(result.success).to.be.true;789  });790}791792export async function enableContractSponsoringExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {793  await usingApi(async (api) => {794    const tx = api.tx.unique.enableContractSponsoring(contractAddress, enable);795    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;796    const result = getGenericResult(events);797798    expect(result.success).to.be.false;799  });800}801802export async function setTransferFlagExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {803804  await usingApi(async (api) => {805806    const tx = api.tx.unique.setTransfersEnabledFlag(collectionId, enabled);807    const events = await submitTransactionAsync(sender, tx);808    const result = getGenericResult(events);809810    expect(result.success).to.be.true;811  });812}813814export async function setTransferFlagExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {815816  await usingApi(async (api) => {817818    const tx = api.tx.unique.setTransfersEnabledFlag(collectionId, enabled);819    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;820    const result = getGenericResult(events);821822    expect(result.success).to.be.false;823  });824}825826export async function setContractSponsoringRateLimitExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {827  await usingApi(async (api) => {828    const tx = api.tx.unique.setContractSponsoringRateLimit(contractAddress, rateLimit);829    const events = await submitTransactionAsync(sender, tx);830    const result = getGenericResult(events);831832    expect(result.success).to.be.true;833  });834}835836export async function setContractSponsoringRateLimitExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {837  await usingApi(async (api) => {838    const tx = api.tx.unique.setContractSponsoringRateLimit(contractAddress, rateLimit);839    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;840    const result = getGenericResult(events);841842    expect(result.success).to.be.false;843  });844}845846export async function getNextSponsored(847  api: ApiPromise,848  collectionId: number,849  account: string | CrossAccountId,850  tokenId: number,851): Promise<number> {852  return Number((await api.rpc.unique.nextSponsored(collectionId, account, tokenId)).unwrapOr(-1));853}854855export async function toggleContractAllowlistExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, value = true) {856  await usingApi(async (api) => {857    const tx = api.tx.unique.toggleContractAllowList(contractAddress, value);858    const events = await submitTransactionAsync(sender, tx);859    const result = getGenericResult(events);860861    expect(result.success).to.be.true;862  });863}864865export async function isAllowlistedInContract(contractAddress: AccountId | string, user: string) {866  let allowlisted = false;867  await usingApi(async (api) => {868    allowlisted = (await api.query.unique.contractAllowList(contractAddress, user)).toJSON() as boolean;869  });870  return allowlisted;871}872873export async function addToContractAllowListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {874  await usingApi(async (api) => {875    const tx = api.tx.unique.addToContractAllowList(contractAddress.toString(), user.toString());876    const events = await submitTransactionAsync(sender, tx);877    const result = getGenericResult(events);878879    expect(result.success).to.be.true;880  });881}882883export async function removeFromContractAllowListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {884  await usingApi(async (api) => {885    const tx = api.tx.unique.removeFromContractAllowList(contractAddress.toString(), user.toString());886    const events = await submitTransactionAsync(sender, tx);887    const result = getGenericResult(events);888889    expect(result.success).to.be.true;890  });891}892893export async function removeFromContractAllowListExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {894  await usingApi(async (api) => {895    const tx = api.tx.unique.removeFromContractAllowList(contractAddress.toString(), user.toString());896    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;897    const result = getGenericResult(events);898899    expect(result.success).to.be.false;900  });901}902903export interface CreateFungibleData {904  readonly Value: bigint;905}906907export interface CreateReFungibleData { }908export interface CreateNftData { }909910export type CreateItemData = {911  NFT: CreateNftData;912} | {913  Fungible: CreateFungibleData;914} | {915  ReFungible: CreateReFungibleData;916};917918export async function burnItem(api: ApiPromise, sender: IKeyringPair, collectionId: number, tokenId: number, value: number | bigint) : Promise<boolean> {919  const tx = api.tx.unique.burnItem(collectionId, tokenId, value);920  const events = await submitTransactionAsync(sender, tx);921  return getGenericResult(events).success;922}923924export async function burnItemExpectSuccess(sender: IKeyringPair, collectionId: number, tokenId: number, value: number | bigint = 1) {925  await usingApi(async (api) => {926    const balanceBefore = await getBalance(api, collectionId, normalizeAccountId(sender), tokenId);927    // if burning token by admin - use adminButnItemExpectSuccess928    expect(balanceBefore >= BigInt(value)).to.be.true;929930    expect(await burnItem(api, sender, collectionId, tokenId, value)).to.be.true;931932    const balanceAfter = await getBalance(api, collectionId, normalizeAccountId(sender), tokenId);933    expect(balanceAfter + BigInt(value)).to.be.equal(balanceBefore);934  });935}936937export async function burnItemExpectFailure(sender: IKeyringPair, collectionId: number, tokenId: number, value: number | bigint = 1) {938  await usingApi(async (api) => {939    const tx = api.tx.unique.burnItem(collectionId, tokenId, value);940941    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;942    const result = getCreateCollectionResult(events);943    // tslint:disable-next-line:no-unused-expression944    expect(result.success).to.be.false;945  });946}947948export async function burnFromExpectSuccess(sender: IKeyringPair, from: IKeyringPair | CrossAccountId, collectionId: number, tokenId: number, value: number | bigint = 1) {949  await usingApi(async (api) => {950    const tx = api.tx.unique.burnFrom(collectionId, normalizeAccountId(from), tokenId, value);951    const events = await submitTransactionAsync(sender, tx);952    return getGenericResult(events).success;953  });954}955956export async function957approve(958  api: ApiPromise,959  collectionId: number,960  tokenId: number, owner: IKeyringPair, approved: CrossAccountId | string | IKeyringPair, amount: number | bigint,961) {962  const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);963  const events = await submitTransactionAsync(owner, approveUniqueTx);964  return getGenericResult(events).success;965}966967export async function968approveExpectSuccess(969  collectionId: number,970  tokenId: number, owner: IKeyringPair, approved: CrossAccountId | string, amount: number | bigint = 1,971) {972  await usingApi(async (api: ApiPromise) => {973    const result = await approve(api, collectionId, tokenId, owner, approved, amount);974    expect(result).to.be.true;975976    expect(await getAllowance(api, collectionId, owner, approved, tokenId)).to.be.equal(BigInt(amount));977  });978}979980export async function adminApproveFromExpectSuccess(981  collectionId: number,982  tokenId: number, admin: IKeyringPair, owner: CrossAccountId | string, approved: CrossAccountId | string, amount: number | bigint = 1,983) {984  await usingApi(async (api: ApiPromise) => {985    const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);986    const events = await submitTransactionAsync(admin, approveUniqueTx);987    const result = getGenericResult(events);988    expect(result.success).to.be.true;989990    expect(await getAllowance(api, collectionId, owner, approved, tokenId)).to.be.equal(BigInt(amount));991  });992}993994export async function995transferFrom(996  api: ApiPromise,997  collectionId: number,998  tokenId: number,999  accountApproved: IKeyringPair,1000  accountFrom: IKeyringPair | CrossAccountId,1001  accountTo: IKeyringPair | CrossAccountId,1002  value: number | bigint,1003) {1004  const from = normalizeAccountId(accountFrom);1005  const to = normalizeAccountId(accountTo);1006  const transferFromTx = api.tx.unique.transferFrom(from, to, collectionId, tokenId, value);1007  const events = await submitTransactionAsync(accountApproved, transferFromTx);1008  return getGenericResult(events).success;1009}10101011export async function1012transferFromExpectSuccess(1013  collectionId: number,1014  tokenId: number,1015  accountApproved: IKeyringPair,1016  accountFrom: IKeyringPair | CrossAccountId,1017  accountTo: IKeyringPair | CrossAccountId,1018  value: number | bigint = 1,1019  type = 'NFT',1020) {1021  await usingApi(async (api: ApiPromise) => {1022    const from = normalizeAccountId(accountFrom);1023    const to = normalizeAccountId(accountTo);1024    let balanceBefore = 0n;1025    if (type === 'Fungible' || type === 'ReFungible') {1026      balanceBefore = await getBalance(api, collectionId, to, tokenId);1027    }1028    expect(await transferFrom(api, collectionId, tokenId, accountApproved, accountFrom, accountTo, value)).to.be.true;1029    if (type === 'NFT') {1030      expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(to);1031    }1032    if (type === 'Fungible') {1033      const balanceAfter = await getBalance(api, collectionId, to, tokenId);1034      if (JSON.stringify(to) !== JSON.stringify(from)) {1035        expect(balanceAfter - balanceBefore).to.be.equal(BigInt(value));1036      } else {1037        expect(balanceAfter).to.be.equal(balanceBefore);1038      }1039    }1040    if (type === 'ReFungible') {1041      expect(await getBalance(api, collectionId, to, tokenId)).to.be.equal(balanceBefore + BigInt(value));1042    }1043  });1044}10451046export async function1047transferFromExpectFail(1048  collectionId: number,1049  tokenId: number,1050  accountApproved: IKeyringPair,1051  accountFrom: IKeyringPair,1052  accountTo: IKeyringPair,1053  value: number | bigint = 1,1054) {1055  await usingApi(async (api: ApiPromise) => {1056    const transferFromTx = api.tx.unique.transferFrom(normalizeAccountId(accountFrom.address), normalizeAccountId(accountTo.address), collectionId, tokenId, value);1057    const events = await expect(submitTransactionExpectFailAsync(accountApproved, transferFromTx)).to.be.rejected;1058    const result = getCreateCollectionResult(events);1059    // tslint:disable-next-line:no-unused-expression1060    expect(result.success).to.be.false;1061  });1062}10631064/* eslint no-async-promise-executor: "off" */1065export async function getBlockNumber(api: ApiPromise): Promise<number> {1066  return new Promise<number>(async (resolve) => {1067    const unsubscribe = await api.rpc.chain.subscribeNewHeads((head) => {1068      unsubscribe();1069      resolve(head.number.toNumber());1070    });1071  });1072}10731074export async function addCollectionAdminExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | CrossAccountId) {1075  await usingApi(async (api) => {1076    const changeAdminTx = api.tx.unique.addCollectionAdmin(collectionId, normalizeAccountId(address));1077    const events = await submitTransactionAsync(sender, changeAdminTx);1078    const result = getCreateCollectionResult(events);1079    expect(result.success).to.be.true;1080  });1081}10821083export async function adminApproveFromExpectFail(1084  collectionId: number,1085  tokenId: number, admin: IKeyringPair, owner: CrossAccountId | string, approved: CrossAccountId | string, amount: number | bigint = 1,1086) {1087  await usingApi(async (api: ApiPromise) => {1088    const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);1089    const events = await expect(submitTransactionAsync(admin, approveUniqueTx)).to.be.rejected;1090    const result = getGenericResult(events);1091    expect(result.success).to.be.false;1092  });1093}10941095export async function1096getFreeBalance(account: IKeyringPair): Promise<bigint> {1097  let balance = 0n;1098  await usingApi(async (api) => {1099    balance = BigInt((await api.query.system.account(account.address)).data.free.toString());1100  });11011102  return balance;1103}11041105export async function transferBalanceTo(api: ApiPromise, source: IKeyringPair, target: string, amount = 1000n * UNIQUE) {1106  const tx = api.tx.balances.transfer(target, amount);1107  const events = await submitTransactionAsync(source, tx);1108  const result = getGenericResult(events);1109  expect(result.success).to.be.true;1110}11111112export async function1113scheduleExpectSuccess(1114  operationTx: any,1115  sender: IKeyringPair,1116  blockSchedule: number,1117  scheduledId: string,1118  period = 1,1119  repetitions = 1,1120) {1121  await usingApi(async (api: ApiPromise) => {1122    const blockNumber: number | undefined = await getBlockNumber(api);1123    const expectedBlockNumber = blockNumber + blockSchedule;11241125    expect(blockNumber).to.be.greaterThan(0);1126    const scheduleTx = api.tx.scheduler.scheduleNamed( // schedule1127      scheduledId,1128      expectedBlockNumber, 1129      repetitions > 1 ? [period, repetitions] : null, 1130      0, 1131      {Value: operationTx as any},1132    );11331134    const events = await submitTransactionAsync(sender, scheduleTx);1135    expect(getGenericResult(events).success).to.be.true;1136  });1137}11381139export async function1140scheduleExpectFailure(1141  operationTx: any,1142  sender: IKeyringPair,1143  blockSchedule: number,1144  scheduledId: string,1145  period = 1,1146  repetitions = 1,1147) {1148  await usingApi(async (api: ApiPromise) => {1149    const blockNumber: number | undefined = await getBlockNumber(api);1150    const expectedBlockNumber = blockNumber + blockSchedule;11511152    expect(blockNumber).to.be.greaterThan(0);1153    const scheduleTx = api.tx.scheduler.scheduleNamed( // schedule1154      scheduledId,1155      expectedBlockNumber, 1156      repetitions <= 1 ? null : [period, repetitions], 1157      0, 1158      {Value: operationTx as any},1159    );11601161    //const events = 1162    await expect(submitTransactionExpectFailAsync(sender, scheduleTx)).to.be.rejected;1163    //expect(getGenericResult(events).success).to.be.false;1164  });1165}11661167export async function1168scheduleTransferAndWaitExpectSuccess(1169  collectionId: number,1170  tokenId: number,1171  sender: IKeyringPair,1172  recipient: IKeyringPair,1173  value: number | bigint = 1,1174  blockSchedule: number,1175  scheduledId: string,1176) {1177  await usingApi(async (api: ApiPromise) => {1178    await scheduleTransferExpectSuccess(collectionId, tokenId, sender, recipient, value, blockSchedule, scheduledId);11791180    const recipientBalanceBefore = (await api.query.system.account(recipient.address)).data.free.toBigInt();11811182    // sleep for n + 1 blocks1183    await waitNewBlocks(blockSchedule + 1);11841185    const recipientBalanceAfter = (await api.query.system.account(recipient.address)).data.free.toBigInt();11861187    expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(recipient.address));1188    expect(recipientBalanceAfter).to.be.equal(recipientBalanceBefore);1189  });1190}11911192export async function1193scheduleTransferExpectSuccess(1194  collectionId: number,1195  tokenId: number,1196  sender: IKeyringPair,1197  recipient: IKeyringPair,1198  value: number | bigint = 1,1199  blockSchedule: number,1200  scheduledId: string,1201) {1202  await usingApi(async (api: ApiPromise) => {1203    const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient.address), collectionId, tokenId, value);12041205    await scheduleExpectSuccess(transferTx, sender, blockSchedule, scheduledId);12061207    expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(sender.address));1208  });1209}12101211export async function1212scheduleTransferFundsPeriodicExpectSuccess(1213  amount: bigint,1214  sender: IKeyringPair,1215  recipient: IKeyringPair,1216  blockSchedule: number,1217  scheduledId: string,1218  period: number,1219  repetitions: number,1220) {1221  await usingApi(async (api: ApiPromise) => {1222    const transferTx = api.tx.balances.transfer(recipient.address, amount);12231224    const balanceBefore = await getFreeBalance(recipient);1225    1226    await scheduleExpectSuccess(transferTx, sender, blockSchedule, scheduledId, period, repetitions);12271228    expect(await getFreeBalance(recipient)).to.be.equal(balanceBefore);1229  });1230}12311232export async function1233transfer(1234  api: ApiPromise,1235  collectionId: number,1236  tokenId: number,1237  sender: IKeyringPair,1238  recipient: IKeyringPair | CrossAccountId,1239  value: number | bigint,1240) : Promise<boolean> {1241  const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient), collectionId, tokenId, value);1242  const events = await executeTransaction(api, sender, transferTx);1243  return getGenericResult(events).success;1244}12451246export async function1247transferExpectSuccess(1248  collectionId: number,1249  tokenId: number,1250  sender: IKeyringPair,1251  recipient: IKeyringPair | CrossAccountId,1252  value: number | bigint = 1,1253  type = 'NFT',1254) {1255  await usingApi(async (api: ApiPromise) => {1256    const from = normalizeAccountId(sender);1257    const to = normalizeAccountId(recipient);12581259    let balanceBefore = 0n;1260    if (type === 'Fungible' || type === 'ReFungible') {1261      balanceBefore = await getBalance(api, collectionId, to, tokenId);1262    }12631264    const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient), collectionId, tokenId, value);1265    const events = await executeTransaction(api, sender, transferTx);1266    const result = getTransferResult(api, events);12671268    expect(result.collectionId).to.be.equal(collectionId);1269    expect(result.itemId).to.be.equal(tokenId);1270    expect(result.sender).to.be.deep.equal(normalizeAccountId(sender.address));1271    expect(result.recipient).to.be.deep.equal(to);1272    expect(result.value).to.be.equal(BigInt(value));12731274    if (type === 'NFT') {1275      expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(to);1276    }1277    if (type === 'Fungible' || type === 'ReFungible') {1278      const balanceAfter = await getBalance(api, collectionId, to, tokenId);1279      if (JSON.stringify(to) !== JSON.stringify(from)) {1280        expect(balanceAfter - balanceBefore).to.be.equal(BigInt(value));1281      } else {1282        expect(balanceAfter).to.be.equal(balanceBefore);1283      }1284    }1285  });1286}12871288export async function1289transferExpectFailure(1290  collectionId: number,1291  tokenId: number,1292  sender: IKeyringPair,1293  recipient: IKeyringPair | CrossAccountId,1294  value: number | bigint = 1,1295) {1296  await usingApi(async (api: ApiPromise) => {1297    const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient), collectionId, tokenId, value);1298    const events = await expect(submitTransactionExpectFailAsync(sender, transferTx)).to.be.rejected;1299    const result = getGenericResult(events);1300    // if (events && Array.isArray(events)) {1301    //   const result = getCreateCollectionResult(events);1302    // tslint:disable-next-line:no-unused-expression1303    expect(result.success).to.be.false;1304    //}1305  });1306}13071308export async function1309approveExpectFail(1310  collectionId: number,1311  tokenId: number, owner: IKeyringPair, approved: IKeyringPair, amount: number | bigint = 1,1312) {1313  await usingApi(async (api: ApiPromise) => {1314    const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved.address), collectionId, tokenId, amount);1315    const events = await expect(submitTransactionExpectFailAsync(owner, approveUniqueTx)).to.be.rejected;1316    const result = getCreateCollectionResult(events);1317    // tslint:disable-next-line:no-unused-expression1318    expect(result.success).to.be.false;1319  });1320}13211322export async function getBalance(1323  api: ApiPromise,1324  collectionId: number,1325  owner: string | CrossAccountId | IKeyringPair,1326  token: number,1327): Promise<bigint> {1328  return (await api.rpc.unique.balance(collectionId, normalizeAccountId(owner), token)).toBigInt();1329}1330export async function getTokenOwner(1331  api: ApiPromise,1332  collectionId: number,1333  token: number,1334): Promise<CrossAccountId> {1335  const owner = (await api.rpc.unique.tokenOwner(collectionId, token)).toJSON() as any;1336  if (owner == null) throw new Error('owner == null');1337  return normalizeAccountId(owner);1338}1339export async function getTopmostTokenOwner(1340  api: ApiPromise,1341  collectionId: number,1342  token: number,1343): Promise<CrossAccountId> {1344  const owner = (await api.rpc.unique.topmostTokenOwner(collectionId, token)).toJSON() as any;1345  if (owner == null) throw new Error('owner == null');1346  return normalizeAccountId(owner);1347}1348export async function getTokenChildren(1349  api: ApiPromise,1350  collectionId: number,1351  tokenId: number,1352): Promise<UpDataStructsTokenChild[]> {1353  return (await api.rpc.unique.tokenChildren(collectionId, tokenId)).toJSON() as any;1354}1355export async function isTokenExists(1356  api: ApiPromise,1357  collectionId: number,1358  token: number,1359): Promise<boolean> {1360  return (await api.rpc.unique.tokenExists(collectionId, token)).toJSON();1361}1362export async function getLastTokenId(1363  api: ApiPromise,1364  collectionId: number,1365): Promise<number> {1366  return (await api.rpc.unique.lastTokenId(collectionId)).toJSON();1367}1368export async function getAdminList(1369  api: ApiPromise,1370  collectionId: number,1371): Promise<string[]> {1372  return (await api.rpc.unique.adminlist(collectionId)).toHuman() as any;1373}1374export async function getTokenProperties(1375  api: ApiPromise,1376  collectionId: number,1377  tokenId: number,1378  propertyKeys: string[],1379): Promise<UpDataStructsProperty[]> {1380  return (await api.rpc.unique.tokenProperties(collectionId, tokenId, propertyKeys)).toHuman() as any;1381}13821383export async function createFungibleItemExpectSuccess(1384  sender: IKeyringPair,1385  collectionId: number,1386  data: CreateFungibleData,1387  owner: CrossAccountId | string = sender.address,1388) {1389  return await usingApi(async (api) => {1390    const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), {Fungible: data});13911392    const events = await submitTransactionAsync(sender, tx);1393    const result = getCreateItemResult(events);13941395    expect(result.success).to.be.true;1396    return result.itemId;1397  });1398}13991400export async function createMultipleItemsExpectSuccess(sender: IKeyringPair, collectionId: number, itemsData: any, owner: CrossAccountId | string = sender.address) {1401  await usingApi(async (api) => {1402    const to = normalizeAccountId(owner);1403    const tx = api.tx.unique.createMultipleItems(collectionId, to, itemsData);14041405    const events = await submitTransactionAsync(sender, tx);1406    expect(getGenericResult(events).success).to.be.true;1407  });1408}14091410export async function createMultipleItemsWithPropsExpectSuccess(sender: IKeyringPair, collectionId: number, itemsData: any, owner: CrossAccountId | string = sender.address) {1411  await usingApi(async (api) => {1412    const to = normalizeAccountId(owner);1413    const tx = api.tx.unique.createMultipleItems(collectionId, to, itemsData);14141415    const events = await submitTransactionAsync(sender, tx);1416    const result = getCreateItemsResult(events);14171418    for (const res of result) {1419      expect(await api.rpc.unique.tokenProperties(collectionId, res.itemId)).not.to.be.empty;1420    }1421  });1422}14231424export async function createMultipleItemsExWithPropsExpectSuccess(sender: IKeyringPair, collectionId: number, itemsData: any) {1425  await usingApi(async (api) => {1426    const tx = api.tx.unique.createMultipleItemsEx(collectionId, itemsData);14271428    const events = await submitTransactionAsync(sender, tx);1429    const result = getCreateItemsResult(events);14301431    for (const res of result) {1432      expect(await api.rpc.unique.tokenProperties(collectionId, res.itemId)).not.to.be.empty;1433    }1434  });1435}14361437export async function createItemWithPropsExpectSuccess(sender: IKeyringPair, collectionId: number, createMode: string, props:  Array<Property>, owner: CrossAccountId | string = sender.address) {1438  let newItemId = 0;1439  await usingApi(async (api) => {1440    const to = normalizeAccountId(owner);1441    const itemCountBefore = await getLastTokenId(api, collectionId);1442    const itemBalanceBefore = await getBalance(api, collectionId, to, newItemId);14431444    let tx;1445    if (createMode === 'Fungible') {1446      const createData = {fungible: {value: 10}};1447      tx = api.tx.unique.createItem(collectionId, to, createData as any);1448    } else if (createMode === 'ReFungible') {1449      const createData = {refungible: {pieces: 100}};1450      tx = api.tx.unique.createItem(collectionId, to, createData as any);1451    } else {1452      const data = api.createType('UpDataStructsCreateItemData', {NFT: {properties: props}});1453      tx = api.tx.unique.createItem(collectionId, to, data as UpDataStructsCreateItemData);1454    }14551456    const events = await submitTransactionAsync(sender, tx);1457    const result = getCreateItemResult(events);14581459    const itemCountAfter = await getLastTokenId(api, collectionId);1460    const itemBalanceAfter = await getBalance(api, collectionId, to, newItemId);14611462    if (createMode === 'NFT') {1463      expect(await api.rpc.unique.tokenProperties(collectionId, result.itemId)).not.to.be.empty;1464    }14651466    // What to expect1467    // tslint:disable-next-line:no-unused-expression1468    expect(result.success).to.be.true;1469    if (createMode === 'Fungible') {1470      expect(itemBalanceAfter - itemBalanceBefore).to.be.equal(10n);1471    } else {1472      expect(itemCountAfter).to.be.equal(itemCountBefore + 1);1473    }1474    expect(collectionId).to.be.equal(result.collectionId);1475    expect(itemCountAfter.toString()).to.be.equal(result.itemId.toString());1476    expect(to).to.be.deep.equal(result.recipient);1477    newItemId = result.itemId;1478  });1479  return newItemId;1480}14811482export async function createItemWithPropsExpectFailure(sender: IKeyringPair, collectionId: number, createMode: string, props: Array<Property>, owner: CrossAccountId | string = sender.address) {1483  await usingApi(async (api) => {14841485    let tx;1486    if (createMode === 'NFT') {1487      const data = api.createType('UpDataStructsCreateItemData', {NFT: {properties: props}}) as UpDataStructsCreateItemData;1488      tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), data);1489    } else {1490      tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), createMode);1491    }149214931494    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1495    if(events.message && events.message.toString().indexOf('1002: Verification Error') > -1) return;1496    const result = getCreateItemResult(events);14971498    expect(result.success).to.be.false;1499  });1500}15011502export async function createItemExpectSuccess(sender: IKeyringPair, collectionId: number, createMode: string, owner: CrossAccountId | string = sender.address) {1503  let newItemId = 0;1504  await usingApi(async (api) => {1505    const to = normalizeAccountId(owner);1506    const itemCountBefore = await getLastTokenId(api, collectionId);1507    const itemBalanceBefore = await getBalance(api, collectionId, to, newItemId);15081509    let tx;1510    if (createMode === 'Fungible') {1511      const createData = {fungible: {value: 10}};1512      tx = api.tx.unique.createItem(collectionId, to, createData as any);1513    } else if (createMode === 'ReFungible') {1514      const createData = {refungible: {pieces: 100}};1515      tx = api.tx.unique.createItem(collectionId, to, createData as any);1516    } else {1517      const createData = {nft: {}};1518      tx = api.tx.unique.createItem(collectionId, to, createData as any);1519    }15201521    const events = await executeTransaction(api, sender, tx);1522    const result = getCreateItemResult(events);15231524    const itemCountAfter = await getLastTokenId(api, collectionId);1525    const itemBalanceAfter = await getBalance(api, collectionId, to, newItemId);15261527    // What to expect1528    // tslint:disable-next-line:no-unused-expression1529    expect(result.success).to.be.true;1530    if (createMode === 'Fungible') {1531      expect(itemBalanceAfter - itemBalanceBefore).to.be.equal(10n);1532    } else {1533      expect(itemCountAfter).to.be.equal(itemCountBefore + 1);1534    }1535    expect(collectionId).to.be.equal(result.collectionId);1536    expect(itemCountAfter.toString()).to.be.equal(result.itemId.toString());1537    expect(to).to.be.deep.equal(result.recipient);1538    newItemId = result.itemId;1539  });1540  return newItemId;1541}15421543export async function createRefungibleToken(api: ApiPromise, sender: IKeyringPair, collectionId: number, amount: bigint, owner: CrossAccountId | IKeyringPair | string = sender.address) : Promise<CreateItemResult> {1544  const createData = {refungible: {pieces: amount}};1545  const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), createData as any);15461547  const events = await submitTransactionAsync(sender, tx);1548  return  getCreateItemResult(events);1549}15501551export async function createItemExpectFailure(sender: IKeyringPair, collectionId: number, createMode: string, owner: CrossAccountId | string = sender.address) {1552  await usingApi(async (api) => {1553    const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), createMode);15541555    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1556    const result = getCreateItemResult(events);15571558    expect(result.success).to.be.false;1559  });1560}15611562export async function setPublicAccessModeExpectSuccess(1563  sender: IKeyringPair, collectionId: number,1564  accessMode: 'Normal' | 'AllowList',1565) {1566  await usingApi(async (api) => {15671568    // Run the transaction1569    const tx = api.tx.unique.setCollectionPermissions(collectionId, {access: accessMode});1570    const events = await submitTransactionAsync(sender, tx);1571    const result = getGenericResult(events);15721573    // Get the collection1574    const collection = await queryCollectionExpectSuccess(api, collectionId);15751576    // What to expect1577    // tslint:disable-next-line:no-unused-expression1578    expect(result.success).to.be.true;1579    expect(collection.permissions.access.toHuman()).to.be.equal(accessMode);1580  });1581}15821583export async function setPublicAccessModeExpectFail(1584  sender: IKeyringPair, collectionId: number,1585  accessMode: 'Normal' | 'AllowList',1586) {1587  await usingApi(async (api) => {15881589    // Run the transaction1590    const tx = api.tx.unique.setCollectionPermissions(collectionId, {access: accessMode});1591    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1592    const result = getGenericResult(events);15931594    // What to expect1595    // tslint:disable-next-line:no-unused-expression1596    expect(result.success).to.be.false;1597  });1598}15991600export async function enableAllowListExpectSuccess(sender: IKeyringPair, collectionId: number) {1601  await setPublicAccessModeExpectSuccess(sender, collectionId, 'AllowList');1602}16031604export async function enableAllowListExpectFail(sender: IKeyringPair, collectionId: number) {1605  await setPublicAccessModeExpectFail(sender, collectionId, 'AllowList');1606}16071608export async function disableAllowListExpectSuccess(sender: IKeyringPair, collectionId: number) {1609  await setPublicAccessModeExpectSuccess(sender, collectionId, 'Normal');1610}16111612export async function setMintPermissionExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {1613  await usingApi(async (api) => {16141615    // Run the transaction1616    const tx = api.tx.unique.setCollectionPermissions(collectionId, {mintMode: enabled});1617    const events = await submitTransactionAsync(sender, tx);1618    const result = getGenericResult(events);1619    expect(result.success).to.be.true;16201621    // Get the collection1622    const collection = await queryCollectionExpectSuccess(api, collectionId);16231624    expect(collection.permissions.mintMode.toHuman()).to.be.equal(enabled);1625  });1626}16271628export async function enablePublicMintingExpectSuccess(sender: IKeyringPair, collectionId: number) {1629  await setMintPermissionExpectSuccess(sender, collectionId, true);1630}16311632export async function setMintPermissionExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {1633  await usingApi(async (api) => {1634    // Run the transaction1635    const tx = api.tx.unique.setCollectionPermissions(collectionId, {mintMode: enabled});1636    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1637    const result = getCreateCollectionResult(events);1638    // tslint:disable-next-line:no-unused-expression1639    expect(result.success).to.be.false;1640  });1641}16421643export async function setChainLimitsExpectFailure(sender: IKeyringPair, limits: IChainLimits) {1644  await usingApi(async (api) => {1645    // Run the transaction1646    const tx = api.tx.unique.setChainLimits(limits);1647    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1648    const result = getCreateCollectionResult(events);1649    // tslint:disable-next-line:no-unused-expression1650    expect(result.success).to.be.false;1651  });1652}16531654export async function isAllowlisted(api: ApiPromise, collectionId: number, address: string | CrossAccountId | IKeyringPair) {1655  return (await api.rpc.unique.allowed(collectionId, normalizeAccountId(address))).toJSON();1656}16571658export async function addToAllowListExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId | CrossAccountId) {1659  await usingApi(async (api) => {1660    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.false;16611662    // Run the transaction1663    const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1664    const events = await submitTransactionAsync(sender, tx);1665    const result = getGenericResult(events);1666    expect(result.success).to.be.true;16671668    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;1669  });1670}16711672export async function addToAllowListAgainExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId) {1673  await usingApi(async (api) => {16741675    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;16761677    // Run the transaction1678    const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1679    const events = await submitTransactionAsync(sender, tx);1680    const result = getGenericResult(events);1681    expect(result.success).to.be.true;16821683    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;1684  });1685}16861687export async function addToAllowListExpectFail(sender: IKeyringPair, collectionId: number, address: string | AccountId) {1688  await usingApi(async (api) => {16891690    // Run the transaction1691    const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1692    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1693    const result = getGenericResult(events);16941695    // What to expect1696    // tslint:disable-next-line:no-unused-expression1697    expect(result.success).to.be.false;1698  });1699}17001701export async function removeFromAllowListExpectSuccess(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1702  await usingApi(async (api) => {1703    // Run the transaction1704    const tx = api.tx.unique.removeFromAllowList(collectionId, normalizeAccountId(address));1705    const events = await submitTransactionAsync(sender, tx);1706    const result = getGenericResult(events);17071708    // What to expect1709    // tslint:disable-next-line:no-unused-expression1710    expect(result.success).to.be.true;1711  });1712}17131714export async function removeFromAllowListExpectFailure(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1715  await usingApi(async (api) => {1716    // Run the transaction1717    const tx = api.tx.unique.removeFromAllowList(collectionId, normalizeAccountId(address));1718    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1719    const result = getGenericResult(events);17201721    // What to expect1722    // tslint:disable-next-line:no-unused-expression1723    expect(result.success).to.be.false;1724  });1725}17261727export const getDetailedCollectionInfo = async (api: ApiPromise, collectionId: number)1728  : Promise<UpDataStructsRpcCollection | null> => {1729  return (await api.rpc.unique.collectionById(collectionId)).unwrapOr(null);1730};17311732export const getCreatedCollectionCount = async (api: ApiPromise): Promise<number> => {1733  // set global object - collectionsCount1734  return (await api.rpc.unique.collectionStats()).created.toNumber();1735};17361737export async function queryCollectionExpectSuccess(api: ApiPromise, collectionId: number): Promise<UpDataStructsRpcCollection> {1738  return (await api.rpc.unique.collectionById(collectionId)).unwrap();1739}17401741export async function waitNewBlocks(blocksCount = 1): Promise<void> {1742  await usingApi(async (api) => {1743    const promise = new Promise<void>(async (resolve) => {1744      const unsubscribe = await api.rpc.chain.subscribeNewHeads(() => {1745        if (blocksCount > 0) {1746          blocksCount--;1747        } else {1748          unsubscribe();1749          resolve();1750        }1751      });1752    });1753    return promise;1754  });1755}17561757export async function repartitionRFT(1758  api: ApiPromise,1759  collectionId: number,1760  sender: IKeyringPair,1761  tokenId: number,1762  amount: bigint,1763): Promise<boolean> {1764  const tx = api.tx.unique.repartition(collectionId, tokenId, amount);1765  const events = await submitTransactionAsync(sender, tx);1766  const result = getGenericResult(events);17671768  return result.success;1769}17701771export async function itApi(name: string, cb: (apis: { api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair }) => any, opts: { only?: boolean, skip?: boolean } = {}) {1772  let i: any = it;1773  if (opts.only) i = i.only;1774  else if (opts.skip) i = i.skip;1775  i(name, async () => {1776    await usingApi(async (api, privateKeyWrapper) => {1777      await cb({api, privateKeyWrapper});1778    });1779  });1780}17811782itApi.only = (name: string, cb: (apis: { api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair }) => any) => itApi(name, cb, {only: true});1783itApi.skip = (name: string, cb: (apis: { api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair }) => any) => itApi(name, cb, {skip: true});178417851786export async function expectSubstrateEventsAtBlock(api: ApiPromise, blockNumber: AnyNumber | BlockNumber, section: string, methods: string[], dryRun = false) {1787  const blockHash = await api.rpc.chain.getBlockHash(blockNumber);1788  const subEvents = (await api.query.system.events.at(blockHash))1789    .filter(x => x.event.section === section)1790    .map((x) => x.toHuman());1791  const events = methods.map((m) => {1792    return {1793      event: {1794        method: m,1795        section,1796      },1797    };1798  });1799  if (!dryRun) {1800    expect(subEvents).to.be.like(events);1801  }1802  return subEvents;1803}