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

difftreelog

source

tests/src/util/helpers.ts43.8 KiBsourcehistory
1//2// This file is subject to the terms and conditions defined in3// file 'LICENSE', which is part of this source code package.4//56import '../interfaces/augment-api-rpc';7import '../interfaces/augment-api-query';8import {ApiPromise, Keyring} from '@polkadot/api';9import type {AccountId, EventRecord} from '@polkadot/types/interfaces';10import {IKeyringPair} from '@polkadot/types/types';11import {evmToAddress} from '@polkadot/util-crypto';12import BN from 'bn.js';13import chai from 'chai';14import chaiAsPromised from 'chai-as-promised';15import {alicesPublicKey} from '../accounts';16import privateKey from '../substrate/privateKey';17import {default as usingApi, submitTransactionAsync, submitTransactionExpectFailAsync} from '../substrate/substrate-api';18import {hexToStr, strToUTF16, utf16ToStr} from './util';19import {UpDataStructsCollection} from '@polkadot/types/lookup';2021chai.use(chaiAsPromised);22const expect = chai.expect;2324export type CrossAccountId = {25  Substrate: string,26} | {27  Ethereum: string,28};29export function normalizeAccountId(input: string | AccountId | CrossAccountId | IKeyringPair): CrossAccountId {30  if (typeof input === 'string') {31    if (input.length === 48 || input.length === 47) {32      return {Substrate: input};33    } else if (input.length === 42 && input.startsWith('0x')) {34      return {Ethereum: input.toLowerCase()};35    } else if (input.length === 40 && !input.startsWith('0x')) {36      return {Ethereum: '0x' + input.toLowerCase()};37    } else {38      throw new Error(`Unknown address format: "${input}"`);39    }40  }41  if ('address' in input) {42    return {Substrate: input.address};43  }44  if ('Ethereum' in input) {45    return {46      Ethereum: input.Ethereum.toLowerCase(),47    };48  } else if ('ethereum' in input) {49    return {50      Ethereum: (input as any).ethereum.toLowerCase(),51    };52  } else if ('Substrate' in input) {53    return input;54  } else if ('substrate' in input) {55    return {56      Substrate: (input as any).substrate,57    };58  }5960  // AccountId61  return {Substrate: input.toString()};62}63export function toSubstrateAddress(input: string | CrossAccountId | IKeyringPair): string {64  input = normalizeAccountId(input);65  if ('Substrate' in input) {66    return input.Substrate;67  } else {68    return evmToAddress(input.Ethereum);69  }70}7172export const U128_MAX = (1n << 128n) - 1n;7374const MICROUNIQUE = 1_000_000_000_000n;75const MILLIUNIQUE = 1_000n * MICROUNIQUE;76const CENTIUNIQUE = 10n * MILLIUNIQUE;77export const UNIQUE = 100n * CENTIUNIQUE;7879type GenericResult = {80  success: boolean,81};8283interface CreateCollectionResult {84  success: boolean;85  collectionId: number;86}8788interface CreateItemResult {89  success: boolean;90  collectionId: number;91  itemId: number;92  recipient?: CrossAccountId;93}9495interface TransferResult {96  success: boolean;97  collectionId: number;98  itemId: number;99  sender?: CrossAccountId;100  recipient?: CrossAccountId;101  value: bigint;102}103104interface IReFungibleOwner {105  fraction: BN;106  owner: number[];107}108109interface IGetMessage {110  checkMsgUnqMethod: string;111  checkMsgTrsMethod: string;112  checkMsgSysMethod: string;113}114115export interface IFungibleTokenDataType {116  value: number;117}118119export interface IChainLimits {120  collectionNumbersLimit: number;121  accountTokenOwnershipLimit: number;122  collectionsAdminsLimit: number;123  customDataLimit: number;124  nftSponsorTransferTimeout: number;125  fungibleSponsorTransferTimeout: number;126  refungibleSponsorTransferTimeout: number;127  offchainSchemaLimit: number;128  variableOnChainSchemaLimit: number;129  constOnChainSchemaLimit: number;130}131132export interface IReFungibleTokenDataType {133  owner: IReFungibleOwner[];134  constData: number[];135  variableData: number[];136}137138export function uniqueEventMessage(events: EventRecord[]): IGetMessage {139  let checkMsgUnqMethod = '';140  let checkMsgTrsMethod = '';141  let checkMsgSysMethod = '';142  events.forEach(({event: {method, section}}) => {143    if (section === 'common') {144      checkMsgUnqMethod = method;145    } else if (section === 'treasury') {146      checkMsgTrsMethod = method;147    } else if (section === 'system') {148      checkMsgSysMethod = method;149    } else { return null; }150  });151  const result: IGetMessage = {152    checkMsgUnqMethod,153    checkMsgTrsMethod,154    checkMsgSysMethod,155  };156  return result;157}158159export function getGenericResult(events: EventRecord[]): GenericResult {160  const result: GenericResult = {161    success: false,162  };163  events.forEach(({event: {method}}) => {164    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);165    if (method === 'ExtrinsicSuccess') {166      result.success = true;167    }168  });169  return result;170}171172173174export function getCreateCollectionResult(events: EventRecord[]): CreateCollectionResult {175  let success = false;176  let collectionId = 0;177  events.forEach(({event: {data, method, section}}) => {178    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);179    if (method == 'ExtrinsicSuccess') {180      success = true;181    } else if ((section == 'common') && (method == 'CollectionCreated')) {182      collectionId = parseInt(data[0].toString(), 10);183    }184  });185  const result: CreateCollectionResult = {186    success,187    collectionId,188  };189  return result;190}191192export function getCreateItemResult(events: EventRecord[]): CreateItemResult {193  let success = false;194  let collectionId = 0;195  let itemId = 0;196  let recipient;197  events.forEach(({event: {data, method, section}}) => {198    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);199    if (method == 'ExtrinsicSuccess') {200      success = true;201    } else if ((section == 'common') && (method == 'ItemCreated')) {202      collectionId = parseInt(data[0].toString(), 10);203      itemId = parseInt(data[1].toString(), 10);204      recipient = normalizeAccountId(data[2].toJSON() as any);205    }206  });207  const result: CreateItemResult = {208    success,209    collectionId,210    itemId,211    recipient,212  };213  return result;214}215216export function getTransferResult(events: EventRecord[]): TransferResult {217  const result: TransferResult = {218    success: false,219    collectionId: 0,220    itemId: 0,221    value: 0n,222  };223224  events.forEach(({event: {data, method, section}}) => {225    if (method === 'ExtrinsicSuccess') {226      result.success = true;227    } else if (section === 'common' && method === 'Transfer') {228      result.collectionId = +data[0].toString();229      result.itemId = +data[1].toString();230      result.sender = normalizeAccountId(data[2].toJSON() as any);231      result.recipient = normalizeAccountId(data[3].toJSON() as any);232      result.value = BigInt(data[4].toString());233    }234  });235236  return result;237}238239interface Nft {240  type: 'NFT';241}242243interface Fungible {244  type: 'Fungible';245  decimalPoints: number;246}247248interface ReFungible {249  type: 'ReFungible';250}251252type CollectionMode = Nft | Fungible | ReFungible;253254export type CreateCollectionParams = {255  mode: CollectionMode,256  name: string,257  description: string,258  tokenPrefix: string,259};260261const defaultCreateCollectionParams: CreateCollectionParams = {262  description: 'description',263  mode: {type: 'NFT'},264  name: 'name',265  tokenPrefix: 'prefix',266};267268export async function createCollectionExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {269  const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};270271  let collectionId = 0;272  await usingApi(async (api) => {273    // Get number of collections before the transaction274    const collectionCountBefore = await getCreatedCollectionCount(api);275276    // Run the CreateCollection transaction277    const alicePrivateKey = privateKey('//Alice');278279    let modeprm = {};280    if (mode.type === 'NFT') {281      modeprm = {nft: null};282    } else if (mode.type === 'Fungible') {283      modeprm = {fungible: mode.decimalPoints};284    } else if (mode.type === 'ReFungible') {285      modeprm = {refungible: null};286    }287288    const tx = api.tx.unique.createCollectionEx({name: strToUTF16(name), description: strToUTF16(description), tokenPrefix: strToUTF16(tokenPrefix), mode: modeprm as any});289    const events = await submitTransactionAsync(alicePrivateKey, tx);290    const result = getCreateCollectionResult(events);291292    // Get number of collections after the transaction293    const collectionCountAfter = await getCreatedCollectionCount(api);294295    // Get the collection296    const collection = await queryCollectionExpectSuccess(api, result.collectionId);297298    // What to expect299    // tslint:disable-next-line:no-unused-expression300    expect(result.success).to.be.true;301    expect(result.collectionId).to.be.equal(collectionCountAfter);302    // tslint:disable-next-line:no-unused-expression303    expect(collection).to.be.not.null;304    expect(collectionCountAfter).to.be.equal(collectionCountBefore + 1, 'Error: NFT collection NOT created.');305    expect(collection.owner.toString()).to.be.equal(toSubstrateAddress(alicesPublicKey));306    expect(utf16ToStr(collection.name.toJSON() as any)).to.be.equal(name);307    expect(utf16ToStr(collection.description.toJSON() as any)).to.be.equal(description);308    expect(hexToStr(collection.tokenPrefix.toJSON())).to.be.equal(tokenPrefix);309310    collectionId = result.collectionId;311  });312313  return collectionId;314}315316export async function createCollectionExpectFailure(params: Partial<CreateCollectionParams> = {}) {317  const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};318319  let modeprm = {};320  if (mode.type === 'NFT') {321    modeprm = {nft: null};322  } else if (mode.type === 'Fungible') {323    modeprm = {fungible: mode.decimalPoints};324  } else if (mode.type === 'ReFungible') {325    modeprm = {refungible: null};326  }327328  await usingApi(async (api) => {329    // Get number of collections before the transaction330    const collectionCountBefore = await getCreatedCollectionCount(api);331332    // Run the CreateCollection transaction333    const alicePrivateKey = privateKey('//Alice');334    const tx = api.tx.unique.createCollectionEx({name: strToUTF16(name), description: strToUTF16(description), tokenPrefix: strToUTF16(tokenPrefix), mode: modeprm as any});335    const events = await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;336    const result = getCreateCollectionResult(events);337338    // Get number of collections after the transaction339    const collectionCountAfter = await getCreatedCollectionCount(api);340341    // What to expect342    // tslint:disable-next-line:no-unused-expression343    expect(result.success).to.be.false;344    expect(collectionCountAfter).to.be.equal(collectionCountBefore, 'Error: Collection with incorrect data created.');345  });346}347348export async function findUnusedAddress(api: ApiPromise, seedAddition = ''): Promise<IKeyringPair> {349  let bal = 0n;350  let unused;351  do {352    const randomSeed = 'seed' + Math.floor(Math.random() * Math.floor(10000)) + seedAddition;353    const keyring = new Keyring({type: 'sr25519'});354    unused = keyring.addFromUri(`//${randomSeed}`);355    bal = (await api.query.system.account(unused.address)).data.free.toBigInt();356  } while (bal !== 0n);357  return unused;358}359360export async function getAllowance(api: ApiPromise, collectionId: number, owner: CrossAccountId | string, approved: CrossAccountId | string, tokenId: number) {361  return (await api.rpc.unique.allowance(collectionId, normalizeAccountId(owner), normalizeAccountId(approved), tokenId)).toBigInt();362}363364export function findUnusedAddresses(api: ApiPromise, amount: number): Promise<IKeyringPair[]> {365  return Promise.all(new Array(amount).fill(null).map(() => findUnusedAddress(api, '_' + Date.now())));366}367368export async function findNotExistingCollection(api: ApiPromise): Promise<number> {369  const totalNumber = await getCreatedCollectionCount(api);370  const newCollection: number = totalNumber + 1;371  return newCollection;372}373374function getDestroyResult(events: EventRecord[]): boolean {375  let success = false;376  events.forEach(({event: {method}}) => {377    if (method == 'ExtrinsicSuccess') {378      success = true;379    }380  });381  return success;382}383384export async function destroyCollectionExpectFailure(collectionId: number, senderSeed = '//Alice') {385  await usingApi(async (api) => {386    // Run the DestroyCollection transaction387    const alicePrivateKey = privateKey(senderSeed);388    const tx = api.tx.unique.destroyCollection(collectionId);389    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;390  });391}392393export async function destroyCollectionExpectSuccess(collectionId: number, senderSeed = '//Alice') {394  await usingApi(async (api) => {395    // Run the DestroyCollection transaction396    const alicePrivateKey = privateKey(senderSeed);397    const tx = api.tx.unique.destroyCollection(collectionId);398    const events = await submitTransactionAsync(alicePrivateKey, tx);399    const result = getDestroyResult(events);400    expect(result).to.be.true;401402    // What to expect403    expect(await getDetailedCollectionInfo(api, collectionId)).to.be.null;404  });405}406407export async function setCollectionLimitsExpectSuccess(sender: IKeyringPair, collectionId: number, limits: any) {408  await usingApi(async (api) => {409    const tx = api.tx.unique.setCollectionLimits(collectionId, limits);410    const events = await submitTransactionAsync(sender, tx);411    const result = getGenericResult(events);412413    expect(result.success).to.be.true;414  });415}416417export async function setCollectionLimitsExpectFailure(sender: IKeyringPair, collectionId: number, limits: any) {418  await usingApi(async (api) => {419    const tx = api.tx.unique.setCollectionLimits(collectionId, limits);420    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;421    const result = getGenericResult(events);422423    expect(result.success).to.be.false;424  });425}426427export async function setCollectionSponsorExpectSuccess(collectionId: number, sponsor: string, sender = '//Alice') {428  await usingApi(async (api) => {429430    // Run the transaction431    const senderPrivateKey = privateKey(sender);432    const tx = api.tx.unique.setCollectionSponsor(collectionId, sponsor);433    const events = await submitTransactionAsync(senderPrivateKey, tx);434    const result = getGenericResult(events);435436    // Get the collection437    const collection = await queryCollectionExpectSuccess(api, collectionId);438439    // What to expect440    expect(result.success).to.be.true;441    expect(collection.sponsorship.toJSON()).to.deep.equal({442      unconfirmed: sponsor,443    });444  });445}446447export async function removeCollectionSponsorExpectSuccess(collectionId: number, sender = '//Alice') {448  await usingApi(async (api) => {449450    // Run the transaction451    const alicePrivateKey = privateKey(sender);452    const tx = api.tx.unique.removeCollectionSponsor(collectionId);453    const events = await submitTransactionAsync(alicePrivateKey, tx);454    const result = getGenericResult(events);455456    // Get the collection457    const collection = await queryCollectionExpectSuccess(api, collectionId);458459    // What to expect460    expect(result.success).to.be.true;461    expect(collection.sponsorship.toJSON()).to.be.deep.equal({disabled: null});462  });463}464465export async function removeCollectionSponsorExpectFailure(collectionId: number, senderSeed = '//Alice') {466  await usingApi(async (api) => {467468    // Run the transaction469    const alicePrivateKey = privateKey(senderSeed);470    const tx = api.tx.unique.removeCollectionSponsor(collectionId);471    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;472  });473}474475export async function setCollectionSponsorExpectFailure(collectionId: number, sponsor: string, senderSeed = '//Alice') {476  await usingApi(async (api) => {477478    // Run the transaction479    const alicePrivateKey = privateKey(senderSeed);480    const tx = api.tx.unique.setCollectionSponsor(collectionId, sponsor);481    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;482  });483}484485export async function confirmSponsorshipExpectSuccess(collectionId: number, senderSeed = '//Alice') {486  await usingApi(async (api) => {487488    // Run the transaction489    const sender = privateKey(senderSeed);490    const tx = api.tx.unique.confirmSponsorship(collectionId);491    const events = await submitTransactionAsync(sender, tx);492    const result = getGenericResult(events);493494    // Get the collection495    const collection = await queryCollectionExpectSuccess(api, collectionId);496497    // What to expect498    expect(result.success).to.be.true;499    expect(collection.sponsorship.toJSON()).to.be.deep.equal({500      confirmed: sender.address,501    });502  });503}504505506export async function confirmSponsorshipExpectFailure(collectionId: number, senderSeed = '//Alice') {507  await usingApi(async (api) => {508509    // Run the transaction510    const sender = privateKey(senderSeed);511    const tx = api.tx.unique.confirmSponsorship(collectionId);512    await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;513  });514}515516export async function setMetadataUpdatePermissionFlagExpectSuccess(sender: IKeyringPair, collectionId: number, flag: string) {517518  await usingApi(async (api) => {519    const tx = api.tx.unique.setMetaUpdatePermissionFlag(collectionId, flag as any);520    const events = await submitTransactionAsync(sender, tx);521    const result = getGenericResult(events);522523    expect(result.success).to.be.true;524  });525}526527export async function setMetadataUpdatePermissionFlagExpectFailure(sender: IKeyringPair, collectionId: number, flag: string) {528529  await usingApi(async (api) => {530    const tx = api.tx.unique.setMetaUpdatePermissionFlag(collectionId, flag as any);531    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;532    const result = getGenericResult(events);533534    expect(result.success).to.be.false;535  });536}537538export async function enableContractSponsoringExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {539  await usingApi(async (api) => {540    const tx = api.tx.unique.enableContractSponsoring(contractAddress, enable);541    const events = await submitTransactionAsync(sender, tx);542    const result = getGenericResult(events);543544    expect(result.success).to.be.true;545  });546}547548export async function enableContractSponsoringExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {549  await usingApi(async (api) => {550    const tx = api.tx.unique.enableContractSponsoring(contractAddress, enable);551    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;552    const result = getGenericResult(events);553554    expect(result.success).to.be.false;555  });556}557558export async function setTransferFlagExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {559560  await usingApi(async (api) => {561562    const tx = api.tx.unique.setTransfersEnabledFlag(collectionId, enabled);563    const events = await submitTransactionAsync(sender, tx);564    const result = getGenericResult(events);565566    expect(result.success).to.be.true;567  });568}569570export async function setTransferFlagExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {571572  await usingApi(async (api) => {573574    const tx = api.tx.unique.setTransfersEnabledFlag(collectionId, enabled);575    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;576    const result = getGenericResult(events);577578    expect(result.success).to.be.false;579  });580}581582export async function setContractSponsoringRateLimitExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {583  await usingApi(async (api) => {584    const tx = api.tx.unique.setContractSponsoringRateLimit(contractAddress, rateLimit);585    const events = await submitTransactionAsync(sender, tx);586    const result = getGenericResult(events);587588    expect(result.success).to.be.true;589  });590}591592export async function setContractSponsoringRateLimitExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {593  await usingApi(async (api) => {594    const tx = api.tx.unique.setContractSponsoringRateLimit(contractAddress, rateLimit);595    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;596    const result = getGenericResult(events);597598    expect(result.success).to.be.false;599  });600}601602export async function toggleContractAllowlistExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, value = true) {603  await usingApi(async (api) => {604    const tx = api.tx.unique.toggleContractAllowList(contractAddress, value);605    const events = await submitTransactionAsync(sender, tx);606    const result = getGenericResult(events);607608    expect(result.success).to.be.true;609  });610}611612export async function isAllowlistedInContract(contractAddress: AccountId | string, user: string) {613  let allowlisted = false;614  await usingApi(async (api) => {615    allowlisted = (await api.query.unique.contractAllowList(contractAddress, user)).toJSON() as boolean;616  });617  return allowlisted;618}619620export async function addToContractAllowListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {621  await usingApi(async (api) => {622    const tx = api.tx.unique.addToContractAllowList(contractAddress.toString(), user.toString());623    const events = await submitTransactionAsync(sender, tx);624    const result = getGenericResult(events);625626    expect(result.success).to.be.true;627  });628}629630export async function removeFromContractAllowListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {631  await usingApi(async (api) => {632    const tx = api.tx.unique.removeFromContractAllowList(contractAddress.toString(), user.toString());633    const events = await submitTransactionAsync(sender, tx);634    const result = getGenericResult(events);635636    expect(result.success).to.be.true;637  });638}639640export async function removeFromContractAllowListExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {641  await usingApi(async (api) => {642    const tx = api.tx.unique.removeFromContractAllowList(contractAddress.toString(), user.toString());643    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;644    const result = getGenericResult(events);645646    expect(result.success).to.be.false;647  });648}649650export async function setVariableMetaDataExpectSuccess(sender: IKeyringPair, collectionId: number, itemId: number, data: number[]) {651  await usingApi(async (api) => {652    const tx = api.tx.unique.setVariableMetaData(collectionId, itemId, '0x' + Buffer.from(data).toString('hex'));653    const events = await submitTransactionAsync(sender, tx);654    const result = getGenericResult(events);655656    expect(result.success).to.be.true;657  });658}659660export async function setVariableMetaDataExpectFailure(sender: IKeyringPair, collectionId: number, itemId: number, data: number[]) {661  await usingApi(async (api) => {662    const tx = api.tx.unique.setVariableMetaData(collectionId, itemId, '0x' + Buffer.from(data).toString('hex'));663    await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;664  });665}666667export async function setOffchainSchemaExpectSuccess(sender: IKeyringPair, collectionId: number, data: number[]) {668  await usingApi(async (api) => {669    const tx = api.tx.unique.setOffchainSchema(collectionId, '0x' + Buffer.from(data).toString('hex'));670    const events = await submitTransactionAsync(sender, tx);671    const result = getGenericResult(events);672673    expect(result.success).to.be.true;674  });675}676677export async function setOffchainSchemaExpectFailure(sender: IKeyringPair, collectionId: number, data: number[]) {678  await usingApi(async (api) => {679    const tx = api.tx.unique.setOffchainSchema(collectionId, '0x' + Buffer.from(data).toString('hex'));680    await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;681  });682}683684export interface CreateFungibleData {685  readonly Value: bigint;686}687688export interface CreateReFungibleData { }689export interface CreateNftData { }690691export type CreateItemData = {692  NFT: CreateNftData;693} | {694  Fungible: CreateFungibleData;695} | {696  ReFungible: CreateReFungibleData;697};698699export async function burnItemExpectSuccess(sender: IKeyringPair, collectionId: number, tokenId: number, value = 1) {700  await usingApi(async (api) => {701    const balanceBefore = await getBalance(api, collectionId, normalizeAccountId(sender), tokenId);702    // if burning token by admin - use adminButnItemExpectSuccess703    expect(balanceBefore >= BigInt(value)).to.be.true;704705    const tx = api.tx.unique.burnItem(collectionId, tokenId, value);706    const events = await submitTransactionAsync(sender, tx);707    const result = getGenericResult(events);708    expect(result.success).to.be.true;709710    const balanceAfter = await getBalance(api, collectionId, normalizeAccountId(sender), tokenId);711    expect(balanceAfter + BigInt(value)).to.be.equal(balanceBefore);712  });713}714715export async function716approveExpectSuccess(717  collectionId: number,718  tokenId: number, owner: IKeyringPair, approved: CrossAccountId | string, amount: number | bigint = 1,719) {720  await usingApi(async (api: ApiPromise) => {721    const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);722    const events = await submitTransactionAsync(owner, approveUniqueTx);723    const result = getGenericResult(events);724    expect(result.success).to.be.true;725726    expect(await getAllowance(api, collectionId, owner.address, approved, tokenId)).to.be.equal(BigInt(amount));727  });728}729730export async function adminApproveFromExpectSuccess(731  collectionId: number,732  tokenId: number, admin: IKeyringPair, owner: CrossAccountId | string, approved: CrossAccountId | string, amount: number | bigint = 1,733) {734  await usingApi(async (api: ApiPromise) => {735    const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);736    const events = await submitTransactionAsync(admin, approveUniqueTx);737    const result = getGenericResult(events);738    expect(result.success).to.be.true;739740    expect(await getAllowance(api, collectionId, owner, approved, tokenId)).to.be.equal(BigInt(amount));741  });742}743744export async function745transferFromExpectSuccess(746  collectionId: number,747  tokenId: number,748  accountApproved: IKeyringPair,749  accountFrom: IKeyringPair | CrossAccountId,750  accountTo: IKeyringPair | CrossAccountId,751  value: number | bigint = 1,752  type = 'NFT',753) {754  await usingApi(async (api: ApiPromise) => {755    const to = normalizeAccountId(accountTo);756    let balanceBefore = 0n;757    if (type === 'Fungible') {758      balanceBefore = await getBalance(api, collectionId, to, tokenId);759    }760    const transferFromTx = api.tx.unique.transferFrom(normalizeAccountId(accountFrom), to, collectionId, tokenId, value);761    const events = await submitTransactionAsync(accountApproved, transferFromTx);762    const result = getCreateItemResult(events);763    // tslint:disable-next-line:no-unused-expression764    expect(result.success).to.be.true;765    if (type === 'NFT') {766      expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(to);767    }768    if (type === 'Fungible') {769      const balanceAfter = await getBalance(api, collectionId, to, tokenId);770      expect(balanceAfter - balanceBefore).to.be.equal(BigInt(value));771    }772    if (type === 'ReFungible') {773      expect(await getBalance(api, collectionId, to, tokenId)).to.be.equal(BigInt(value));774    }775  });776}777778export async function779transferFromExpectFail(780  collectionId: number,781  tokenId: number,782  accountApproved: IKeyringPair,783  accountFrom: IKeyringPair,784  accountTo: IKeyringPair,785  value: number | bigint = 1,786) {787  await usingApi(async (api: ApiPromise) => {788    const transferFromTx = api.tx.unique.transferFrom(normalizeAccountId(accountFrom.address), normalizeAccountId(accountTo.address), collectionId, tokenId, value);789    const events = await expect(submitTransactionExpectFailAsync(accountApproved, transferFromTx)).to.be.rejected;790    const result = getCreateCollectionResult(events);791    // tslint:disable-next-line:no-unused-expression792    expect(result.success).to.be.false;793  });794}795796/* eslint no-async-promise-executor: "off" */797async function getBlockNumber(api: ApiPromise): Promise<number> {798  return new Promise<number>(async (resolve) => {799    const unsubscribe = await api.rpc.chain.subscribeNewHeads((head) => {800      unsubscribe();801      resolve(head.number.toNumber());802    });803  });804}805806export async function addCollectionAdminExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | CrossAccountId) {807  await usingApi(async (api) => {808    const changeAdminTx = api.tx.unique.addCollectionAdmin(collectionId, normalizeAccountId(address));809    const events = await submitTransactionAsync(sender, changeAdminTx);810    const result = getCreateCollectionResult(events);811    expect(result.success).to.be.true;812  });813}814815export async function816getFreeBalance(account: IKeyringPair): Promise<bigint> {817  let balance = 0n;818  await usingApi(async (api) => {819    balance = BigInt((await api.query.system.account(account.address)).data.free.toString());820  });821822  return balance;823}824825export async function826scheduleTransferExpectSuccess(827  collectionId: number,828  tokenId: number,829  sender: IKeyringPair,830  recipient: IKeyringPair,831  value: number | bigint = 1,832  blockSchedule: number,833) {834  await usingApi(async (api: ApiPromise) => {835    const blockNumber: number | undefined = await getBlockNumber(api);836    const expectedBlockNumber = blockNumber + blockSchedule;837838    expect(blockNumber).to.be.greaterThan(0);839    const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient.address), collectionId, tokenId, value);840    const scheduleTx = api.tx.scheduler.schedule(expectedBlockNumber, null, 0, transferTx as any);841842    await submitTransactionAsync(sender, scheduleTx);843844    const recipientBalanceBefore = (await api.query.system.account(recipient.address)).data.free.toBigInt();845846    expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(sender.address));847848    // sleep for 4 blocks849    await waitNewBlocks(blockSchedule + 1);850851    const recipientBalanceAfter = (await api.query.system.account(recipient.address)).data.free.toBigInt();852853    expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(recipient.address));854    expect(recipientBalanceAfter).to.be.equal(recipientBalanceBefore);855  });856}857858859export async function860transferExpectSuccess(861  collectionId: number,862  tokenId: number,863  sender: IKeyringPair,864  recipient: IKeyringPair | CrossAccountId,865  value: number | bigint = 1,866  type = 'NFT',867) {868  await usingApi(async (api: ApiPromise) => {869    const to = normalizeAccountId(recipient);870871    let balanceBefore = 0n;872    if (type === 'Fungible') {873      balanceBefore = await getBalance(api, collectionId, to, tokenId);874    }875    const transferTx = api.tx.unique.transfer(to, collectionId, tokenId, value);876    const events = await submitTransactionAsync(sender, transferTx);877    const result = getTransferResult(events);878    // tslint:disable-next-line:no-unused-expression879    expect(result.success).to.be.true;880    expect(result.collectionId).to.be.equal(collectionId);881    expect(result.itemId).to.be.equal(tokenId);882    expect(result.sender).to.be.deep.equal(normalizeAccountId(sender.address));883    expect(result.recipient).to.be.deep.equal(to);884    expect(result.value).to.be.equal(BigInt(value));885    if (type === 'NFT') {886      expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(to);887    }888    if (type === 'Fungible') {889      const balanceAfter = await getBalance(api, collectionId, to, tokenId);890      expect(balanceAfter - balanceBefore).to.be.equal(BigInt(value));891    }892    if (type === 'ReFungible') {893      expect(await getBalance(api, collectionId, to, tokenId) >= value).to.be.true;894    }895  });896}897898export async function899transferExpectFailure(900  collectionId: number,901  tokenId: number,902  sender: IKeyringPair,903  recipient: IKeyringPair,904  value: number | bigint = 1,905) {906  await usingApi(async (api: ApiPromise) => {907    const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient.address), collectionId, tokenId, value);908    const events = await expect(submitTransactionExpectFailAsync(sender, transferTx)).to.be.rejected;909    const result = getGenericResult(events);910    // if (events && Array.isArray(events)) {911    //   const result = getCreateCollectionResult(events);912    // tslint:disable-next-line:no-unused-expression913    expect(result.success).to.be.false;914    //}915  });916}917918export async function919approveExpectFail(920  collectionId: number,921  tokenId: number, owner: IKeyringPair, approved: IKeyringPair, amount: number | bigint = 1,922) {923  await usingApi(async (api: ApiPromise) => {924    const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved.address), collectionId, tokenId, amount);925    const events = await expect(submitTransactionExpectFailAsync(owner, approveUniqueTx)).to.be.rejected;926    const result = getCreateCollectionResult(events);927    // tslint:disable-next-line:no-unused-expression928    expect(result.success).to.be.false;929  });930}931932export async function getBalance(933  api: ApiPromise,934  collectionId: number,935  owner: string | CrossAccountId,936  token: number,937): Promise<bigint> {938  return (await api.rpc.unique.balance(collectionId, normalizeAccountId(owner), token)).toBigInt();939}940export async function getTokenOwner(941  api: ApiPromise,942  collectionId: number,943  token: number,944): Promise<CrossAccountId> {945  return normalizeAccountId((await api.rpc.unique.tokenOwner(collectionId, token)).toJSON() as any);946}947export async function isTokenExists(948  api: ApiPromise,949  collectionId: number,950  token: number,951): Promise<boolean> {952  return (await api.rpc.unique.tokenExists(collectionId, token)).toJSON();953}954export async function getLastTokenId(955  api: ApiPromise,956  collectionId: number,957): Promise<number> {958  return (await api.rpc.unique.lastTokenId(collectionId)).toJSON();959}960export async function getAdminList(961  api: ApiPromise,962  collectionId: number,963): Promise<string[]> {964  return (await api.rpc.unique.adminlist(collectionId)).toHuman() as any;965}966export async function getVariableMetadata(967  api: ApiPromise,968  collectionId: number,969  tokenId: number,970): Promise<number[]> {971  return [...(await api.rpc.unique.variableMetadata(collectionId, tokenId))];972}973export async function getConstMetadata(974  api: ApiPromise,975  collectionId: number,976  tokenId: number,977): Promise<number[]> {978  return [...(await api.rpc.unique.constMetadata(collectionId, tokenId))];979}980981export async function createFungibleItemExpectSuccess(982  sender: IKeyringPair,983  collectionId: number,984  data: CreateFungibleData,985  owner: CrossAccountId | string = sender.address,986) {987  return await usingApi(async (api) => {988    const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), {Fungible: data});989990    const events = await submitTransactionAsync(sender, tx);991    const result = getCreateItemResult(events);992993    expect(result.success).to.be.true;994    return result.itemId;995  });996}997998export async function createItemExpectSuccess(sender: IKeyringPair, collectionId: number, createMode: string, owner: CrossAccountId | string = sender.address) {999  let newItemId = 0;1000  await usingApi(async (api) => {1001    const to = normalizeAccountId(owner);1002    const itemCountBefore = await getLastTokenId(api, collectionId);1003    const itemBalanceBefore = await getBalance(api, collectionId, to, newItemId);10041005    let tx;1006    if (createMode === 'Fungible') {1007      const createData = {fungible: {value: 10}};1008      tx = api.tx.unique.createItem(collectionId, to, createData as any);1009    } else if (createMode === 'ReFungible') {1010      const createData = {refungible: {const_data: [], variable_data: [], pieces: 100}};1011      tx = api.tx.unique.createItem(collectionId, to, createData as any);1012    } else {1013      const createData = {nft: {const_data: [], variable_data: []}};1014      tx = api.tx.unique.createItem(collectionId, to, createData as any);1015    }10161017    const events = await submitTransactionAsync(sender, tx);1018    const result = getCreateItemResult(events);10191020    const itemCountAfter = await getLastTokenId(api, collectionId);1021    const itemBalanceAfter = await getBalance(api, collectionId, to, newItemId);10221023    // What to expect1024    // tslint:disable-next-line:no-unused-expression1025    expect(result.success).to.be.true;1026    if (createMode === 'Fungible') {1027      expect(itemBalanceAfter - itemBalanceBefore).to.be.equal(10n);1028    } else {1029      expect(itemCountAfter).to.be.equal(itemCountBefore + 1);1030    }1031    expect(collectionId).to.be.equal(result.collectionId);1032    expect(itemCountAfter.toString()).to.be.equal(result.itemId.toString());1033    expect(to).to.be.deep.equal(result.recipient);1034    newItemId = result.itemId;1035  });1036  return newItemId;1037}10381039export async function createItemExpectFailure(sender: IKeyringPair, collectionId: number, createMode: string, owner: string = sender.address) {1040  await usingApi(async (api) => {1041    const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), createMode);10421043    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1044    const result = getCreateItemResult(events);10451046    expect(result.success).to.be.false;1047  });1048}10491050export async function setPublicAccessModeExpectSuccess(1051  sender: IKeyringPair, collectionId: number,1052  accessMode: 'Normal' | 'AllowList',1053) {1054  await usingApi(async (api) => {10551056    // Run the transaction1057    const tx = api.tx.unique.setPublicAccessMode(collectionId, accessMode);1058    const events = await submitTransactionAsync(sender, tx);1059    const result = getGenericResult(events);10601061    // Get the collection1062    const collection = await queryCollectionExpectSuccess(api, collectionId);10631064    // What to expect1065    // tslint:disable-next-line:no-unused-expression1066    expect(result.success).to.be.true;1067    expect(collection.access.toHuman()).to.be.equal(accessMode);1068  });1069}10701071export async function setPublicAccessModeExpectFail(1072  sender: IKeyringPair, collectionId: number,1073  accessMode: 'Normal' | 'AllowList',1074) {1075  await usingApi(async (api) => {10761077    // Run the transaction1078    const tx = api.tx.unique.setPublicAccessMode(collectionId, accessMode);1079    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1080    const result = getGenericResult(events);10811082    // What to expect1083    // tslint:disable-next-line:no-unused-expression1084    expect(result.success).to.be.false;1085  });1086}10871088export async function enableAllowListExpectSuccess(sender: IKeyringPair, collectionId: number) {1089  await setPublicAccessModeExpectSuccess(sender, collectionId, 'AllowList');1090}10911092export async function enableAllowListExpectFail(sender: IKeyringPair, collectionId: number) {1093  await setPublicAccessModeExpectFail(sender, collectionId, 'AllowList');1094}10951096export async function disableAllowListExpectSuccess(sender: IKeyringPair, collectionId: number) {1097  await setPublicAccessModeExpectSuccess(sender, collectionId, 'Normal');1098}10991100export async function setMintPermissionExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {1101  await usingApi(async (api) => {11021103    // Run the transaction1104    const tx = api.tx.unique.setMintPermission(collectionId, enabled);1105    const events = await submitTransactionAsync(sender, tx);1106    const result = getGenericResult(events);1107    expect(result.success).to.be.true;11081109    // Get the collection1110    const collection = await queryCollectionExpectSuccess(api, collectionId);11111112    expect(collection.mintMode.toHuman()).to.be.equal(enabled);1113  });1114}11151116export async function enablePublicMintingExpectSuccess(sender: IKeyringPair, collectionId: number) {1117  await setMintPermissionExpectSuccess(sender, collectionId, true);1118}11191120export async function setMintPermissionExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {1121  await usingApi(async (api) => {1122    // Run the transaction1123    const tx = api.tx.unique.setMintPermission(collectionId, enabled);1124    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1125    const result = getCreateCollectionResult(events);1126    // tslint:disable-next-line:no-unused-expression1127    expect(result.success).to.be.false;1128  });1129}11301131export async function setChainLimitsExpectFailure(sender: IKeyringPair, limits: IChainLimits) {1132  await usingApi(async (api) => {1133    // Run the transaction1134    const tx = api.tx.unique.setChainLimits(limits);1135    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1136    const result = getCreateCollectionResult(events);1137    // tslint:disable-next-line:no-unused-expression1138    expect(result.success).to.be.false;1139  });1140}11411142export async function isAllowlisted(api: ApiPromise, collectionId: number, address: string | CrossAccountId) {1143  return (await api.rpc.unique.allowed(collectionId, normalizeAccountId(address))).toJSON();1144}11451146export async function addToAllowListExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId | CrossAccountId) {1147  await usingApi(async (api) => {1148    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.false;11491150    // Run the transaction1151    const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1152    const events = await submitTransactionAsync(sender, tx);1153    const result = getGenericResult(events);1154    expect(result.success).to.be.true;11551156    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;1157  });1158}11591160export async function addToAllowListAgainExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId) {1161  await usingApi(async (api) => {11621163    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;11641165    // Run the transaction1166    const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1167    const events = await submitTransactionAsync(sender, tx);1168    const result = getGenericResult(events);1169    expect(result.success).to.be.true;11701171    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;1172  });1173}11741175export async function addToAllowListExpectFail(sender: IKeyringPair, collectionId: number, address: string | AccountId) {1176  await usingApi(async (api) => {11771178    // Run the transaction1179    const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1180    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1181    const result = getGenericResult(events);11821183    // What to expect1184    // tslint:disable-next-line:no-unused-expression1185    expect(result.success).to.be.false;1186  });1187}11881189export async function removeFromAllowListExpectSuccess(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1190  await usingApi(async (api) => {1191    // Run the transaction1192    const tx = api.tx.unique.removeFromAllowList(collectionId, normalizeAccountId(address));1193    const events = await submitTransactionAsync(sender, tx);1194    const result = getGenericResult(events);11951196    // What to expect1197    // tslint:disable-next-line:no-unused-expression1198    expect(result.success).to.be.true;1199  });1200}12011202export async function removeFromAllowListExpectFailure(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1203  await usingApi(async (api) => {1204    // Run the transaction1205    const tx = api.tx.unique.removeFromAllowList(collectionId, normalizeAccountId(address));1206    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1207    const result = getGenericResult(events);12081209    // What to expect1210    // tslint:disable-next-line:no-unused-expression1211    expect(result.success).to.be.false;1212  });1213}12141215export const getDetailedCollectionInfo = async (api: ApiPromise, collectionId: number)1216  : Promise<UpDataStructsCollection | null> => {1217  return (await api.rpc.unique.collectionById(collectionId)).unwrapOr(null);1218};12191220export const getCreatedCollectionCount = async (api: ApiPromise): Promise<number> => {1221  // set global object - collectionsCount1222  return (await api.rpc.unique.collectionStats()).created.toNumber();1223};12241225export async function queryCollectionExpectSuccess(api: ApiPromise, collectionId: number): Promise<UpDataStructsCollection> {1226  return (await api.rpc.unique.collectionById(collectionId)).unwrap();1227}12281229export async function waitNewBlocks(blocksCount = 1): Promise<void> {1230  await usingApi(async (api) => {1231    const promise = new Promise<void>(async (resolve) => {1232      const unsubscribe = await api.rpc.chain.subscribeNewHeads(() => {1233        if (blocksCount > 0) {1234          blocksCount--;1235        } else {1236          unsubscribe();1237          resolve();1238        }1239      });1240    });1241    return promise;1242  });1243}