git.delta.rocks / unique-network / refs/commits / 7781ab982a4b

difftreelog

source

tests/src/util/helpers.ts45.2 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 {ApiPromise, Keyring} from '@polkadot/api';7import type {AccountId, EventRecord} from '@polkadot/types/interfaces';8import {IKeyringPair} from '@polkadot/types/types';9import {evmToAddress} from '@polkadot/util-crypto';10import BN from 'bn.js';11import chai from 'chai';12import chaiAsPromised from 'chai-as-promised';13import {alicesPublicKey} from '../accounts';14import {UpDataStructsCollection} from '../interfaces';15import privateKey from '../substrate/privateKey';16import {default as usingApi, submitTransactionAsync, submitTransactionExpectFailAsync} from '../substrate/substrate-api';17import {hexToStr, strToUTF16, utf16ToStr} from './util';1819chai.use(chaiAsPromised);20const expect = chai.expect;2122export type CrossAccountId = {23  Substrate: string,24} | {25  Ethereum: string,26};27export function normalizeAccountId(input: string | AccountId | CrossAccountId | IKeyringPair): CrossAccountId {28  if (typeof input === 'string') {29    if (input.length === 48 || input.length === 47) {30      return {Substrate: input};31    } else if (input.length === 42 && input.startsWith('0x')) {32      return {Ethereum: input.toLowerCase()};33    } else if (input.length === 40 && !input.startsWith('0x')) {34      return {Ethereum: '0x' + input.toLowerCase()};35    } else {36      throw new Error(`Unknown address format: "${input}"`);37    }38  }39  if ('address' in input) {40    return {Substrate: input.address};41  }42  if ('Ethereum' in input) {43    return {44      Ethereum: input.Ethereum.toLowerCase(),45    };46  } else if ('ethereum' in input) {47    return {48      Ethereum: (input as any).ethereum.toLowerCase(),49    };50  } else if ('Substrate' in input) {51    return input;52  }else if ('substrate' in input) {53    return {54      Substrate: (input as any).substrate,55    };56  }5758  // AccountId59  return {Substrate: input.toString()};60}61export function toSubstrateAddress(input: string | CrossAccountId | IKeyringPair): string {62  input = normalizeAccountId(input);63  if ('Substrate' in input) {64    return input.Substrate;65  } else {66    return evmToAddress(input.Ethereum);67  }68}6970export const U128_MAX = (1n << 128n) - 1n;7172const MICROUNIQUE = 1_000_000_000_000n;73const MILLIUNIQUE = 1_000n * MICROUNIQUE;74const CENTIUNIQUE = 10n * MILLIUNIQUE;75export const UNIQUE = 100n * CENTIUNIQUE;7677type GenericResult = {78  success: boolean,79};8081interface CreateCollectionResult {82  success: boolean;83  collectionId: number;84}8586interface CreateItemResult {87  success: boolean;88  collectionId: number;89  itemId: number;90  recipient?: CrossAccountId;91}9293interface TransferResult {94  success: boolean;95  collectionId: number;96  itemId: number;97  sender?: CrossAccountId;98  recipient?: CrossAccountId;99  value: bigint;100}101102interface IReFungibleOwner {103  fraction: BN;104  owner: number[];105}106107interface IGetMessage {108  checkMsgUnqMethod: string;109  checkMsgTrsMethod: string;110  checkMsgSysMethod: string;111}112113export interface IFungibleTokenDataType {114  value: number;115}116117export interface IChainLimits {118  collectionNumbersLimit: number;119	accountTokenOwnershipLimit: number;120	collectionsAdminsLimit: number;121	customDataLimit: number;122	nftSponsorTransferTimeout: number;123	fungibleSponsorTransferTimeout: number;124	refungibleSponsorTransferTimeout: number;125	offchainSchemaLimit: number;126	variableOnChainSchemaLimit: number;127	constOnChainSchemaLimit: number;128}129130export interface IReFungibleTokenDataType {131  owner: IReFungibleOwner[];132  constData: number[];133  variableData: number[];134}135136export function uniqueEventMessage(events: EventRecord[]): IGetMessage {137  let checkMsgUnqMethod = '';138  let checkMsgTrsMethod = '';139  let checkMsgSysMethod = '';140  events.forEach(({event: {method, section}}) => {141    if (section === 'common') {142      checkMsgUnqMethod = method;143    } else if (section === 'treasury') {144      checkMsgTrsMethod = method;145    } else if (section === 'system') {146      checkMsgSysMethod = method;147    } else { return null; }148  });149  const result: IGetMessage = {150    checkMsgUnqMethod,151    checkMsgTrsMethod,152    checkMsgSysMethod,153  };154  return result;155}156157export function getGenericResult(events: EventRecord[]): GenericResult {158  const result: GenericResult = {159    success: false,160  };161  events.forEach(({event: {method}}) => {162    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);163    if (method === 'ExtrinsicSuccess') {164      result.success = true;165    }166  });167  return result;168}169170171172export function getCreateCollectionResult(events: EventRecord[]): CreateCollectionResult {173  let success = false;174  let collectionId = 0;175  events.forEach(({event: {data, method, section}}) => {176    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);177    if (method == 'ExtrinsicSuccess') {178      success = true;179    } else if ((section == 'common') && (method == 'CollectionCreated')) {180      collectionId = parseInt(data[0].toString(), 10);181    }182  });183  const result: CreateCollectionResult = {184    success,185    collectionId,186  };187  return result;188}189190export function getCreateItemResult(events: EventRecord[]): CreateItemResult {191  let success = false;192  let collectionId = 0;193  let itemId = 0;194  let recipient;195  events.forEach(({event: {data, method, section}}) => {196    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);197    if (method == 'ExtrinsicSuccess') {198      success = true;199    } else if ((section == 'common') && (method == 'ItemCreated')) {200      collectionId = parseInt(data[0].toString(), 10);201      itemId = parseInt(data[1].toString(), 10);202      recipient = normalizeAccountId(data[2].toJSON() as any);203    }204  });205  const result: CreateItemResult = {206    success,207    collectionId,208    itemId,209    recipient,210  };211  return result;212}213214export function getTransferResult(events: EventRecord[]): TransferResult {215  const result: TransferResult = {216    success: false,217    collectionId: 0,218    itemId: 0,219    value: 0n,220  };221222  events.forEach(({event: {data, method, section}}) => {223    if (method === 'ExtrinsicSuccess') {224      result.success = true;225    } else if (section === 'common' && method === 'Transfer') {226      result.collectionId = +data[0].toString();227      result.itemId = +data[1].toString();228      result.sender = normalizeAccountId(data[2].toJSON() as any);229      result.recipient = normalizeAccountId(data[3].toJSON() as any);230      result.value = BigInt(data[4].toString());231    }232  });233234  return result;235}236237interface Nft {238  type: 'NFT';239}240241interface Fungible {242  type: 'Fungible';243  decimalPoints: number;244}245246interface ReFungible {247  type: 'ReFungible';248}249250type CollectionMode = Nft | Fungible | ReFungible;251252export type CreateCollectionParams = {253  mode: CollectionMode,254  name: string,255  description: string,256  tokenPrefix: string,257};258259const defaultCreateCollectionParams: CreateCollectionParams = {260  description: 'description',261  mode: {type: 'NFT'},262  name: 'name',263  tokenPrefix: 'prefix',264};265266export async function createCollectionExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {267  const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};268269  let collectionId = 0;270  await usingApi(async (api) => {271    // Get number of collections before the transaction272    const collectionCountBefore = await getCreatedCollectionCount(api);273274    // Run the CreateCollection transaction275    const alicePrivateKey = privateKey('//Alice');276277    let modeprm = {};278    if (mode.type === 'NFT') {279      modeprm = {nft: null};280    } else if (mode.type === 'Fungible') {281      modeprm = {fungible: mode.decimalPoints};282    } else if (mode.type === 'ReFungible') {283      modeprm = {refungible: null};284    }285286    const tx = api.tx.unique.createCollection(strToUTF16(name), strToUTF16(description), strToUTF16(tokenPrefix), modeprm as any);287    const events = await submitTransactionAsync(alicePrivateKey, tx);288    const result = getCreateCollectionResult(events);289290    // Get number of collections after the transaction291    const collectionCountAfter = await getCreatedCollectionCount(api);292293    // Get the collection294    const collection = await queryCollectionExpectSuccess(api, result.collectionId);295296    // What to expect297    // tslint:disable-next-line:no-unused-expression298    expect(result.success).to.be.true;299    expect(result.collectionId).to.be.equal(collectionCountAfter);300    // tslint:disable-next-line:no-unused-expression301    expect(collection).to.be.not.null;302    expect(collectionCountAfter).to.be.equal(collectionCountBefore + 1, 'Error: NFT collection NOT created.');303    expect(collection.owner.toString()).to.be.equal(toSubstrateAddress(alicesPublicKey));304    expect(utf16ToStr(collection.name.toJSON() as any)).to.be.equal(name);305    expect(utf16ToStr(collection.description.toJSON() as any)).to.be.equal(description);306    expect(hexToStr(collection.tokenPrefix.toJSON())).to.be.equal(tokenPrefix);307308    collectionId = result.collectionId;309  });310311  return collectionId;312}313314export async function createCollectionExpectFailure(params: Partial<CreateCollectionParams> = {}) {315  const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};316317  let modeprm = {};318  if (mode.type === 'NFT') {319    modeprm = {nft: null};320  } else if (mode.type === 'Fungible') {321    modeprm = {fungible: mode.decimalPoints};322  } else if (mode.type === 'ReFungible') {323    modeprm = {refungible: null};324  }325326  await usingApi(async (api) => {327    // Get number of collections before the transaction328    const collectionCountBefore = await getCreatedCollectionCount(api);329330    // Run the CreateCollection transaction331    const alicePrivateKey = privateKey('//Alice');332    const tx = api.tx.unique.createCollection(strToUTF16(name), strToUTF16(description), strToUTF16(tokenPrefix), modeprm as any);333    const events = await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;334    const result = getCreateCollectionResult(events);335336    // Get number of collections after the transaction337    const collectionCountAfter = await getCreatedCollectionCount(api);338339    // What to expect340    // tslint:disable-next-line:no-unused-expression341    expect(result.success).to.be.false;342    expect(collectionCountAfter).to.be.equal(collectionCountBefore, 'Error: Collection with incorrect data created.');343  });344}345346export async function findUnusedAddress(api: ApiPromise, seedAddition = ''): Promise<IKeyringPair> {347  let bal = 0n;348  let unused;349  do {350    const randomSeed = 'seed' + Math.floor(Math.random() * Math.floor(10000)) + seedAddition;351    const keyring = new Keyring({type: 'sr25519'});352    unused = keyring.addFromUri(`//${randomSeed}`);353    bal = (await api.query.system.account(unused.address)).data.free.toBigInt();354  } while (bal !== 0n);355  return unused;356}357358export async function getAllowance(api: ApiPromise, collectionId: number, owner: CrossAccountId | string, approved: CrossAccountId | string, tokenId: number) {359  return (await api.rpc.unique.allowance(collectionId, normalizeAccountId(owner), normalizeAccountId(approved), tokenId)).toBigInt();360}361362export function findUnusedAddresses(api: ApiPromise, amount: number): Promise<IKeyringPair[]> {363  return Promise.all(new Array(amount).fill(null).map(() => findUnusedAddress(api, '_' + Date.now())));364}365366export async function findNotExistingCollection(api: ApiPromise): Promise<number> {367  const totalNumber = await getCreatedCollectionCount(api);368  const newCollection: number = totalNumber + 1;369  return newCollection;370}371372function getDestroyResult(events: EventRecord[]): boolean {373  let success = false;374  events.forEach(({event: {method}}) => {375    if (method == 'ExtrinsicSuccess') {376      success = true;377    }378  });379  return success;380}381382export async function destroyCollectionExpectFailure(collectionId: number, senderSeed = '//Alice') {383  await usingApi(async (api) => {384    // Run the DestroyCollection transaction385    const alicePrivateKey = privateKey(senderSeed);386    const tx = api.tx.unique.destroyCollection(collectionId);387    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;388  });389}390391export async function destroyCollectionExpectSuccess(collectionId: number, senderSeed = '//Alice') {392  await usingApi(async (api) => {393    // Run the DestroyCollection transaction394    const alicePrivateKey = privateKey(senderSeed);395    const tx = api.tx.unique.destroyCollection(collectionId);396    const events = await submitTransactionAsync(alicePrivateKey, tx);397    const result = getDestroyResult(events);398    expect(result).to.be.true;399400    // What to expect401    expect(await getDetailedCollectionInfo(api, collectionId)).to.be.null;402  });403}404405export async function setCollectionLimitsExpectSuccess(sender: IKeyringPair, collectionId: number, limits: any) {406  await usingApi(async (api) => {407    const tx = api.tx.unique.setCollectionLimits(collectionId, limits);408    const events = await submitTransactionAsync(sender, tx);409    const result = getGenericResult(events);410411    expect(result.success).to.be.true;412  });413}414415export async function setCollectionLimitsExpectFailure(sender: IKeyringPair, collectionId: number, limits: any) {416  await usingApi(async (api) => {417    const tx = api.tx.unique.setCollectionLimits(collectionId, limits);418    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;419    const result = getGenericResult(events);420421    expect(result.success).to.be.false;422  });423}424425export async function setCollectionSponsorExpectSuccess(collectionId: number, sponsor: string, sender = '//Alice') {426  await usingApi(async (api) => {427428    // Run the transaction429    const senderPrivateKey = privateKey(sender);430    const tx = api.tx.unique.setCollectionSponsor(collectionId, sponsor);431    const events = await submitTransactionAsync(senderPrivateKey, tx);432    const result = getGenericResult(events);433434    // Get the collection435    const collection = await queryCollectionExpectSuccess(api, collectionId);436437    // What to expect438    expect(result.success).to.be.true;439    expect(collection.sponsorship.toJSON()).to.deep.equal({440      unconfirmed: sponsor,441    });442  });443}444445export async function removeCollectionSponsorExpectSuccess(collectionId: number, sender = '//Alice') {446  await usingApi(async (api) => {447448    // Run the transaction449    const alicePrivateKey = privateKey(sender);450    const tx = api.tx.unique.removeCollectionSponsor(collectionId);451    const events = await submitTransactionAsync(alicePrivateKey, tx);452    const result = getGenericResult(events);453454    // Get the collection455    const collection = await queryCollectionExpectSuccess(api, collectionId);456457    // What to expect458    expect(result.success).to.be.true;459    expect(collection.sponsorship.toJSON()).to.be.deep.equal({disabled: null});460  });461}462463export async function removeCollectionSponsorExpectFailure(collectionId: number, senderSeed = '//Alice') {464  await usingApi(async (api) => {465466    // Run the transaction467    const alicePrivateKey = privateKey(senderSeed);468    const tx = api.tx.unique.removeCollectionSponsor(collectionId);469    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;470  });471}472473export async function setCollectionSponsorExpectFailure(collectionId: number, sponsor: string, senderSeed = '//Alice') {474  await usingApi(async (api) => {475476    // Run the transaction477    const alicePrivateKey = privateKey(senderSeed);478    const tx = api.tx.unique.setCollectionSponsor(collectionId, sponsor);479    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;480  });481}482483export async function confirmSponsorshipExpectSuccess(collectionId: number, senderSeed = '//Alice') {484  await usingApi(async () => {485    const sender = privateKey(senderSeed);486    await confirmSponsorshipByKeyExpectSuccess(collectionId, sender);487  });488}489490export async function confirmSponsorshipByKeyExpectSuccess(collectionId: number, sender: IKeyringPair) {491  await usingApi(async (api) => {492493    // Run the transaction494    const tx = api.tx.unique.confirmSponsorship(collectionId);495    const events = await submitTransactionAsync(sender, tx);496    const result = getGenericResult(events);497498    // Get the collection499    const collection = await queryCollectionExpectSuccess(api, collectionId);500501    // What to expect502    expect(result.success).to.be.true;503    expect(collection.sponsorship.toJSON()).to.be.deep.equal({504      confirmed: sender.address,505    });506  });507}508509510export async function confirmSponsorshipExpectFailure(collectionId: number, senderSeed = '//Alice') {511  await usingApi(async (api) => {512513    // Run the transaction514    const sender = privateKey(senderSeed);515    const tx = api.tx.unique.confirmSponsorship(collectionId);516    await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;517  });518}519520export async function setMetadataUpdatePermissionFlagExpectSuccess(sender: IKeyringPair, collectionId: number, flag: string) {521522  await usingApi(async (api) => {523    const tx = api.tx.unique.setMetaUpdatePermissionFlag(collectionId, flag as any);524    const events = await submitTransactionAsync(sender, tx);525    const result = getGenericResult(events);526527    expect(result.success).to.be.true;528  });529}530531export async function setMetadataUpdatePermissionFlagExpectFailure(sender: IKeyringPair, collectionId: number, flag: string) {532533  await usingApi(async (api) => {534    const tx = api.tx.unique.setMetaUpdatePermissionFlag(collectionId, flag as any);535    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;536    const result = getGenericResult(events);537538    expect(result.success).to.be.false;539  });540}541542export async function enableContractSponsoringExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {543  await usingApi(async (api) => {544    const tx = api.tx.unique.enableContractSponsoring(contractAddress, enable);545    const events = await submitTransactionAsync(sender, tx);546    const result = getGenericResult(events);547548    expect(result.success).to.be.true;549  });550}551552export async function enableContractSponsoringExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {553  await usingApi(async (api) => {554    const tx = api.tx.unique.enableContractSponsoring(contractAddress, enable);555    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;556    const result = getGenericResult(events);557558    expect(result.success).to.be.false;559  });560}561562export async function setTransferFlagExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {563564  await usingApi(async (api) => {565566    const tx = api.tx.unique.setTransfersEnabledFlag (collectionId, enabled);567    const events = await submitTransactionAsync(sender, tx);568    const result = getGenericResult(events);569570    expect(result.success).to.be.true;571  });572}573574export async function setTransferFlagExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {575576  await usingApi(async (api) => {577578    const tx = api.tx.unique.setTransfersEnabledFlag (collectionId, enabled);579    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;580    const result = getGenericResult(events);581582    expect(result.success).to.be.false;583  });584}585586export async function setContractSponsoringRateLimitExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {587  await usingApi(async (api) => {588    const tx = api.tx.unique.setContractSponsoringRateLimit(contractAddress, rateLimit);589    const events = await submitTransactionAsync(sender, tx);590    const result = getGenericResult(events);591592    expect(result.success).to.be.true;593  });594}595596export async function setContractSponsoringRateLimitExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {597  await usingApi(async (api) => {598    const tx = api.tx.unique.setContractSponsoringRateLimit(contractAddress, rateLimit);599    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;600    const result = getGenericResult(events);601602    expect(result.success).to.be.false;603  });604}605606export async function toggleContractAllowlistExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, value = true) {607  await usingApi(async (api) => {608    const tx = api.tx.unique.toggleContractAllowList(contractAddress, value);609    const events = await submitTransactionAsync(sender, tx);610    const result = getGenericResult(events);611612    expect(result.success).to.be.true;613  });614}615616export async function isAllowlistedInContract(contractAddress: AccountId | string, user: string) {617  let allowlisted = false;618  await usingApi(async (api) => {619    allowlisted = (await api.query.unique.contractAllowList(contractAddress, user)).toJSON() as boolean;620  });621  return allowlisted;622}623624export async function addToContractAllowListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {625  await usingApi(async (api) => {626    const tx = api.tx.unique.addToContractAllowList(contractAddress.toString(), user.toString());627    const events = await submitTransactionAsync(sender, tx);628    const result = getGenericResult(events);629630    expect(result.success).to.be.true;631  });632}633634export async function removeFromContractAllowListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {635  await usingApi(async (api) => {636    const tx = api.tx.unique.removeFromContractAllowList(contractAddress.toString(), user.toString());637    const events = await submitTransactionAsync(sender, tx);638    const result = getGenericResult(events);639640    expect(result.success).to.be.true;641  });642}643644export async function removeFromContractAllowListExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {645  await usingApi(async (api) => {646    const tx = api.tx.unique.removeFromContractAllowList(contractAddress.toString(), user.toString());647    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;648    const result = getGenericResult(events);649650    expect(result.success).to.be.false;651  });652}653654export async function setVariableMetaDataExpectSuccess(sender: IKeyringPair, collectionId: number, itemId: number, data: number[]) {655  await usingApi(async (api) => {656    const tx = api.tx.unique.setVariableMetaData(collectionId, itemId, '0x' + Buffer.from(data).toString('hex'));657    const events = await submitTransactionAsync(sender, tx);658    const result = getGenericResult(events);659660    expect(result.success).to.be.true;661  });662}663664export async function setVariableMetaDataExpectFailure(sender: IKeyringPair, collectionId: number, itemId: number, data: number[]) {665  await usingApi(async (api) => {666    const tx = api.tx.unique.setVariableMetaData(collectionId, itemId, '0x' + Buffer.from(data).toString('hex'));667    await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;668  });669}670671export async function setOffchainSchemaExpectSuccess(sender: IKeyringPair, collectionId: number, data: number[]) {672  await usingApi(async (api) => {673    const tx = api.tx.unique.setOffchainSchema(collectionId, '0x' + Buffer.from(data).toString('hex'));674    const events = await submitTransactionAsync(sender, tx);675    const result = getGenericResult(events);676677    expect(result.success).to.be.true;678  });679}680681export async function setOffchainSchemaExpectFailure(sender: IKeyringPair, collectionId: number, data: number[]) {682  await usingApi(async (api) => {683    const tx = api.tx.unique.setOffchainSchema(collectionId, '0x' + Buffer.from(data).toString('hex'));684    await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;685  });686}687688export interface CreateFungibleData {689  readonly Value: bigint;690}691692export interface CreateReFungibleData { }693export interface CreateNftData { }694695export type CreateItemData = {696  NFT: CreateNftData;697} | {698  Fungible: CreateFungibleData;699} | {700  ReFungible: CreateReFungibleData;701};702703export async function burnItemExpectSuccess(sender: IKeyringPair, collectionId: number, tokenId: number, value = 1) {704  await usingApi(async (api) => {705    const balanceBefore = await getBalance(api, collectionId, normalizeAccountId(sender), tokenId);706    // if burning token by admin - use adminButnItemExpectSuccess707    expect(balanceBefore >= BigInt(value)).to.be.true;708709    const tx = api.tx.unique.burnItem(collectionId, tokenId, value);710    const events = await submitTransactionAsync(sender, tx);711    const result = getGenericResult(events);712    expect(result.success).to.be.true;713714    const balanceAfter = await getBalance(api, collectionId, normalizeAccountId(sender), tokenId);715    expect(balanceAfter + BigInt(value)).to.be.equal(balanceBefore);716  });717}718719export async function720approveExpectSuccess(721  collectionId: number,722  tokenId: number, owner: IKeyringPair, approved: CrossAccountId | string, amount: number | bigint = 1,723) {724  await usingApi(async (api: ApiPromise) => {725    const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);726    const events = await submitTransactionAsync(owner, approveUniqueTx);727    const result = getGenericResult(events);728    expect(result.success).to.be.true;729730    expect(await getAllowance(api, collectionId, owner.address, approved, tokenId)).to.be.equal(BigInt(amount));731  });732}733734export async function adminApproveFromExpectSuccess(735  collectionId: number,736  tokenId: number, admin: IKeyringPair, owner: CrossAccountId | string, approved: CrossAccountId | string, amount: number | bigint = 1,737) {738  await usingApi(async (api: ApiPromise) => {739    const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);740    const events = await submitTransactionAsync(admin, approveUniqueTx);741    const result = getGenericResult(events);742    expect(result.success).to.be.true;743744    expect(await getAllowance(api, collectionId, owner, approved, tokenId)).to.be.equal(BigInt(amount));745  });746}747748export async function749transferFromExpectSuccess(750  collectionId: number,751  tokenId: number,752  accountApproved: IKeyringPair,753  accountFrom: IKeyringPair | CrossAccountId,754  accountTo: IKeyringPair | CrossAccountId,755  value: number | bigint = 1,756  type = 'NFT',757) {758  await usingApi(async (api: ApiPromise) => {759    const to = normalizeAccountId(accountTo);760    let balanceBefore = 0n;761    if (type === 'Fungible') {762      balanceBefore = await getBalance(api, collectionId, to, tokenId);763    }764    const transferFromTx = api.tx.unique.transferFrom(normalizeAccountId(accountFrom), to, collectionId, tokenId, value);765    const events = await submitTransactionAsync(accountApproved, transferFromTx);766    const result = getCreateItemResult(events);767    // tslint:disable-next-line:no-unused-expression768    expect(result.success).to.be.true;769    if (type === 'NFT') {770      expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(to);771    }772    if (type === 'Fungible') {773      const balanceAfter = await getBalance(api, collectionId, to, tokenId);774      expect(balanceAfter - balanceBefore).to.be.equal(BigInt(value));775    }776    if (type === 'ReFungible') {777      expect(await getBalance(api, collectionId, to, tokenId)).to.be.equal(BigInt(value));778    }779  });780}781782export async function783transferFromExpectFail(784  collectionId: number,785  tokenId: number,786  accountApproved: IKeyringPair,787  accountFrom: IKeyringPair,788  accountTo: IKeyringPair,789  value: number | bigint = 1,790) {791  await usingApi(async (api: ApiPromise) => {792    const transferFromTx = api.tx.unique.transferFrom(normalizeAccountId(accountFrom.address), normalizeAccountId(accountTo.address), collectionId, tokenId, value);793    const events = await expect(submitTransactionExpectFailAsync(accountApproved, transferFromTx)).to.be.rejected;794    const result = getCreateCollectionResult(events);795    // tslint:disable-next-line:no-unused-expression796    expect(result.success).to.be.false;797  });798}799800/* eslint no-async-promise-executor: "off" */801export async function getBlockNumber(api: ApiPromise): Promise<number> {802  return new Promise<number>(async (resolve) => {803    const unsubscribe = await api.rpc.chain.subscribeNewHeads((head) => {804      unsubscribe();805      resolve(head.number.toNumber());806    });807  });808}809810export async function addCollectionAdminExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | CrossAccountId) {811  await usingApi(async (api) => {812    const changeAdminTx = api.tx.unique.addCollectionAdmin(collectionId, normalizeAccountId(address));813    const events = await submitTransactionAsync(sender, changeAdminTx);814    const result = getCreateCollectionResult(events);815    expect(result.success).to.be.true;816  });817}818819export async function820getFreeBalance(account: IKeyringPair) : Promise<bigint>821{822  let balance = 0n;823  await usingApi(async (api) => {824    balance = BigInt((await api.query.system.account(account.address)).data.free.toString());825  });826827  return balance;828}829830export async function831scheduleTransferAndWaitExpectSuccess(832  collectionId: number,833  tokenId: number,834  sender: IKeyringPair,835  recipient: IKeyringPair,836  value: number | bigint = 1,837  blockSchedule: number,838) {839  await usingApi(async (api: ApiPromise) => {840    await scheduleTransferExpectSuccess(collectionId, tokenId, sender, recipient, value, blockSchedule);841842    const recipientBalanceBefore = (await api.query.system.account(recipient.address)).data.free.toBigInt();843    console.log(await getFreeBalance(sender));844845    // sleep for n + 1 blocks846    await waitNewBlocks(blockSchedule + 1);847848    const recipientBalanceAfter = (await api.query.system.account(recipient.address)).data.free.toBigInt();849850    expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(recipient.address));851    expect(recipientBalanceAfter).to.be.equal(recipientBalanceBefore);852  });853}854855export async function856scheduleTransferExpectSuccess(857  collectionId: number,858  tokenId: number,859  sender: IKeyringPair,860  recipient: IKeyringPair,861  value: number | bigint = 1,862  blockSchedule: number,863) {864  await usingApi(async (api: ApiPromise) => {865    const blockNumber: number | undefined = await getBlockNumber(api);866    const expectedBlockNumber = blockNumber + blockSchedule;867868    expect(blockNumber).to.be.greaterThan(0);869    const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient.address), collectionId, tokenId, value);870    const scheduleTx = api.tx.scheduler.schedule(expectedBlockNumber, null, 0, transferTx as any);871872    const events = await submitTransactionAsync(sender, scheduleTx);873    expect(getGenericResult(events).success).to.be.true;874875    expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(sender.address));876  });877}878879export async function880scheduleTransferFundsPeriodicExpectSuccess(881  amount: bigint,882  sender: IKeyringPair,883  recipient: IKeyringPair,884  blockSchedule: number,885  period: number,886  repetitions: number,887) {888  await usingApi(async (api: ApiPromise) => {889    const blockNumber: number | undefined = await getBlockNumber(api);890    const expectedBlockNumber = blockNumber + blockSchedule;891892    const balanceBefore = await getFreeBalance(recipient);893    894    expect(blockNumber).to.be.greaterThan(0);895    const transferTx = api.tx.balances.transfer(recipient.address, amount);896    const scheduleTx = api.tx.scheduler.schedule(expectedBlockNumber, [period, repetitions], 0, transferTx as any);897898    const events = await submitTransactionAsync(sender, scheduleTx);899    expect(getGenericResult(events).success).to.be.true;900901    expect(await getFreeBalance(recipient)).to.be.equal(balanceBefore);902  });903}904905906export async function907transferExpectSuccess(908  collectionId: number,909  tokenId: number,910  sender: IKeyringPair,911  recipient: IKeyringPair | CrossAccountId,912  value: number | bigint = 1,913  type = 'NFT',914) {915  await usingApi(async (api: ApiPromise) => {916    const to = normalizeAccountId(recipient);917918    let balanceBefore = 0n;919    if (type === 'Fungible') {920      balanceBefore = await getBalance(api, collectionId, to, tokenId);921    }922    const transferTx = api.tx.unique.transfer(to, collectionId, tokenId, value);923    const events = await submitTransactionAsync(sender, transferTx);924    const result = getTransferResult(events);925    // tslint:disable-next-line:no-unused-expression926    expect(result.success).to.be.true;927    expect(result.collectionId).to.be.equal(collectionId);928    expect(result.itemId).to.be.equal(tokenId);929    expect(result.sender).to.be.deep.equal(normalizeAccountId(sender.address));930    expect(result.recipient).to.be.deep.equal(to);931    expect(result.value).to.be.equal(BigInt(value));932    if (type === 'NFT') {933      expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(to);934    }935    if (type === 'Fungible') {936      const balanceAfter = await getBalance(api, collectionId, to, tokenId);937      expect(balanceAfter - balanceBefore).to.be.equal(BigInt(value));938    }939    if (type === 'ReFungible') {940      expect(await getBalance(api, collectionId, to, tokenId) >= value).to.be.true;941    }942  });943}944945export async function946transferExpectFailure(947  collectionId: number,948  tokenId: number,949  sender: IKeyringPair,950  recipient: IKeyringPair,951  value: number | bigint = 1,952) {953  await usingApi(async (api: ApiPromise) => {954    const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient.address), collectionId, tokenId, value);955    const events = await expect(submitTransactionExpectFailAsync(sender, transferTx)).to.be.rejected;956    const result = getGenericResult(events);957    // if (events && Array.isArray(events)) {958    //   const result = getCreateCollectionResult(events);959    // tslint:disable-next-line:no-unused-expression960    expect(result.success).to.be.false;961    //}962  });963}964965export async function966approveExpectFail(967  collectionId: number,968  tokenId: number, owner: IKeyringPair, approved: IKeyringPair, amount: number | bigint = 1,969) {970  await usingApi(async (api: ApiPromise) => {971    const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved.address), collectionId, tokenId, amount);972    const events = await expect(submitTransactionExpectFailAsync(owner, approveUniqueTx)).to.be.rejected;973    const result = getCreateCollectionResult(events);974    // tslint:disable-next-line:no-unused-expression975    expect(result.success).to.be.false;976  });977}978979export async function getBalance(980  api: ApiPromise,981  collectionId: number,982  owner: string | CrossAccountId,983  token: number,984): Promise<bigint> {985  return (await api.rpc.unique.balance(collectionId, normalizeAccountId(owner), token)).toBigInt();986}987export async function getTokenOwner(988  api: ApiPromise,989  collectionId: number,990  token: number,991): Promise<CrossAccountId> {992  return normalizeAccountId((await api.rpc.unique.tokenOwner(collectionId, token)).toJSON() as any);993}994export async function isTokenExists(995  api: ApiPromise,996  collectionId: number,997  token: number,998): Promise<boolean> {999  return (await api.rpc.unique.tokenExists(collectionId, token)).toJSON();1000}1001export async function getLastTokenId(1002  api: ApiPromise,1003  collectionId: number,1004): Promise<number> {1005  return (await api.rpc.unique.lastTokenId(collectionId)).toJSON();1006}1007export async function getAdminList(1008  api: ApiPromise,1009  collectionId: number,1010): Promise<string[]> {1011  return (await api.rpc.unique.adminlist(collectionId)).toHuman() as any;1012}1013export async function getVariableMetadata(1014  api: ApiPromise,1015  collectionId: number,1016  tokenId: number,1017): Promise<number[]> {1018  return [...(await api.rpc.unique.variableMetadata(collectionId, tokenId))];1019}1020export async function getConstMetadata(1021  api: ApiPromise,1022  collectionId: number,1023  tokenId: number,1024): Promise<number[]> {1025  return [...(await api.rpc.unique.constMetadata(collectionId, tokenId))];1026}10271028export async function createFungibleItemExpectSuccess(1029  sender: IKeyringPair,1030  collectionId: number,1031  data: CreateFungibleData,1032  owner: CrossAccountId | string = sender.address,1033) {1034  return await usingApi(async (api) => {1035    const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), {Fungible: data});10361037    const events = await submitTransactionAsync(sender, tx);1038    const result = getCreateItemResult(events);10391040    expect(result.success).to.be.true;1041    return result.itemId;1042  });1043}10441045export async function createItemExpectSuccess(sender: IKeyringPair, collectionId: number, createMode: string, owner: CrossAccountId | string = sender.address) {1046  let newItemId = 0;1047  await usingApi(async (api) => {1048    const to = normalizeAccountId(owner);1049    const itemCountBefore = await getLastTokenId(api, collectionId);1050    const itemBalanceBefore = await getBalance(api, collectionId, to, newItemId);10511052    let tx;1053    if (createMode === 'Fungible') {1054      const createData = {fungible: {value: 10}};1055      tx = api.tx.unique.createItem(collectionId, to, createData as any);1056    } else if (createMode === 'ReFungible') {1057      const createData = {refungible: {const_data: [], variable_data: [], pieces: 100}};1058      tx = api.tx.unique.createItem(collectionId, to, createData as any);1059    } else {1060      const createData = {nft: {const_data: [], variable_data: []}};1061      tx = api.tx.unique.createItem(collectionId, to, createData as any);1062    }10631064    const events = await submitTransactionAsync(sender, tx);1065    const result = getCreateItemResult(events);10661067    const itemCountAfter = await getLastTokenId(api, collectionId);1068    const itemBalanceAfter = await getBalance(api, collectionId, to, newItemId);10691070    // What to expect1071    // tslint:disable-next-line:no-unused-expression1072    expect(result.success).to.be.true;1073    if (createMode === 'Fungible') {1074      expect(itemBalanceAfter - itemBalanceBefore).to.be.equal(10n);1075    } else {1076      expect(itemCountAfter).to.be.equal(itemCountBefore + 1);1077    }1078    expect(collectionId).to.be.equal(result.collectionId);1079    expect(itemCountAfter.toString()).to.be.equal(result.itemId.toString());1080    expect(to).to.be.deep.equal(result.recipient);1081    newItemId = result.itemId;1082  });1083  return newItemId;1084}10851086export async function createItemExpectFailure(sender: IKeyringPair, collectionId: number, createMode: string, owner: string = sender.address) {1087  await usingApi(async (api) => {1088    const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), createMode);10891090    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1091    const result = getCreateItemResult(events);10921093    expect(result.success).to.be.false;1094  });1095}10961097export async function setPublicAccessModeExpectSuccess(1098  sender: IKeyringPair, collectionId: number,1099  accessMode: 'Normal' | 'AllowList',1100) {1101  await usingApi(async (api) => {11021103    // Run the transaction1104    const tx = api.tx.unique.setPublicAccessMode(collectionId, accessMode);1105    const events = await submitTransactionAsync(sender, tx);1106    const result = getGenericResult(events);11071108    // Get the collection1109    const collection = await queryCollectionExpectSuccess(api, collectionId);11101111    // What to expect1112    // tslint:disable-next-line:no-unused-expression1113    expect(result.success).to.be.true;1114    expect(collection.access.toHuman()).to.be.equal(accessMode);1115  });1116}11171118export async function setPublicAccessModeExpectFail(1119  sender: IKeyringPair, collectionId: number,1120  accessMode: 'Normal' | 'AllowList',1121) {1122  await usingApi(async (api) => {11231124    // Run the transaction1125    const tx = api.tx.unique.setPublicAccessMode(collectionId, accessMode);1126    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1127    const result = getGenericResult(events);11281129    // What to expect1130    // tslint:disable-next-line:no-unused-expression1131    expect(result.success).to.be.false;1132  });1133}11341135export async function enableAllowListExpectSuccess(sender: IKeyringPair, collectionId: number) {1136  await setPublicAccessModeExpectSuccess(sender, collectionId, 'AllowList');1137}11381139export async function enableAllowListExpectFail(sender: IKeyringPair, collectionId: number) {1140  await setPublicAccessModeExpectFail(sender, collectionId, 'AllowList');1141}11421143export async function disableAllowListExpectSuccess(sender: IKeyringPair, collectionId: number) {1144  await setPublicAccessModeExpectSuccess(sender, collectionId, 'Normal');1145}11461147export async function setMintPermissionExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {1148  await usingApi(async (api) => {11491150    // Run the transaction1151    const tx = api.tx.unique.setMintPermission(collectionId, enabled);1152    const events = await submitTransactionAsync(sender, tx);1153    const result = getGenericResult(events);1154    expect(result.success).to.be.true;11551156    // Get the collection1157    const collection = await queryCollectionExpectSuccess(api, collectionId);11581159    expect(collection.mintMode.toHuman()).to.be.equal(enabled);1160  });1161}11621163export async function enablePublicMintingExpectSuccess(sender: IKeyringPair, collectionId: number) {1164  await setMintPermissionExpectSuccess(sender, collectionId, true);1165}11661167export async function setMintPermissionExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {1168  await usingApi(async (api) => {1169    // Run the transaction1170    const tx = api.tx.unique.setMintPermission(collectionId, enabled);1171    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1172    const result = getCreateCollectionResult(events);1173    // tslint:disable-next-line:no-unused-expression1174    expect(result.success).to.be.false;1175  });1176}11771178export async function setChainLimitsExpectFailure(sender: IKeyringPair, limits: IChainLimits) {1179  await usingApi(async (api) => {1180    // Run the transaction1181    const tx = api.tx.unique.setChainLimits(limits);1182    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1183    const result = getCreateCollectionResult(events);1184    // tslint:disable-next-line:no-unused-expression1185    expect(result.success).to.be.false;1186  });1187}11881189export async function isAllowlisted(api: ApiPromise, collectionId: number, address: string | CrossAccountId) {1190  return (await api.rpc.unique.allowed(collectionId, normalizeAccountId(address))).toJSON();1191}11921193export async function addToAllowListExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId | CrossAccountId) {1194  await usingApi(async (api) => {1195    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.false;11961197    // Run the transaction1198    const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1199    const events = await submitTransactionAsync(sender, tx);1200    const result = getGenericResult(events);1201    expect(result.success).to.be.true;12021203    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;1204  });1205}12061207export async function addToAllowListAgainExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId) {1208  await usingApi(async (api) => {12091210    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;12111212    // Run the transaction1213    const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1214    const events = await submitTransactionAsync(sender, tx);1215    const result = getGenericResult(events);1216    expect(result.success).to.be.true;12171218    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;1219  });1220}12211222export async function addToAllowListExpectFail(sender: IKeyringPair, collectionId: number, address: string | AccountId) {1223  await usingApi(async (api) => {12241225    // Run the transaction1226    const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1227    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1228    const result = getGenericResult(events);12291230    // What to expect1231    // tslint:disable-next-line:no-unused-expression1232    expect(result.success).to.be.false;1233  });1234}12351236export async function removeFromAllowListExpectSuccess(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1237  await usingApi(async (api) => {1238    // Run the transaction1239    const tx = api.tx.unique.removeFromAllowList(collectionId, normalizeAccountId(address));1240    const events = await submitTransactionAsync(sender, tx);1241    const result = getGenericResult(events);12421243    // What to expect1244    // tslint:disable-next-line:no-unused-expression1245    expect(result.success).to.be.true;1246  });1247}12481249export async function removeFromAllowListExpectFailure(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1250  await usingApi(async (api) => {1251    // Run the transaction1252    const tx = api.tx.unique.removeFromAllowList(collectionId, normalizeAccountId(address));1253    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1254    const result = getGenericResult(events);12551256    // What to expect1257    // tslint:disable-next-line:no-unused-expression1258    expect(result.success).to.be.false;1259  });1260}12611262export const getDetailedCollectionInfo = async (api: ApiPromise, collectionId: number)1263  : Promise<UpDataStructsCollection | null> => {1264  return (await api.rpc.unique.collectionById(collectionId)).unwrapOr(null);1265};12661267export const getCreatedCollectionCount = async (api: ApiPromise): Promise<number> => {1268  // set global object - collectionsCount1269  return (await api.rpc.unique.collectionStats()).created.toNumber();1270};12711272export async function queryCollectionExpectSuccess(api: ApiPromise, collectionId: number): Promise<UpDataStructsCollection> {1273  return (await api.rpc.unique.collectionById(collectionId)).unwrap();1274}12751276export async function waitNewBlocks(blocksCount = 1): Promise<void> {1277  await usingApi(async (api) => {1278    const promise = new Promise<void>(async (resolve) => {1279      const unsubscribe = await api.rpc.chain.subscribeNewHeads(() => {1280        if (blocksCount > 0) {1281          blocksCount--;1282        } else {1283          unsubscribe();1284          resolve();1285        }1286      });1287    });1288    return promise;1289  });1290}