git.delta.rocks / unique-network / refs/commits / 5ee5939f2c29

difftreelog

source

tests/src/util/helpers.ts45.1 KiBsourcehistory
1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617import '../interfaces/augment-api-rpc';18import '../interfaces/augment-api-query';19import {ApiPromise, Keyring} from '@polkadot/api';20import type {AccountId, EventRecord} from '@polkadot/types/interfaces';21import {IKeyringPair} from '@polkadot/types/types';22import {evmToAddress} from '@polkadot/util-crypto';23import BN from 'bn.js';24import chai from 'chai';25import chaiAsPromised from 'chai-as-promised';26import {alicesPublicKey} from '../accounts';27import privateKey from '../substrate/privateKey';28import {default as usingApi, submitTransactionAsync, submitTransactionExpectFailAsync} from '../substrate/substrate-api';29import {hexToStr, strToUTF16, utf16ToStr} from './util';30import {UpDataStructsCollection} from '@polkadot/types/lookup';3132chai.use(chaiAsPromised);33const expect = chai.expect;3435export type CrossAccountId = {36  Substrate: string,37} | {38  Ethereum: string,39};4041export function normalizeAccountId(input: string | AccountId | CrossAccountId | IKeyringPair): CrossAccountId {42  if (typeof input === 'string') {43    if (input.length === 48 || input.length === 47) {44      return {Substrate: input};45    } else if (input.length === 42 && input.startsWith('0x')) {46      return {Ethereum: input.toLowerCase()};47    } else if (input.length === 40 && !input.startsWith('0x')) {48      return {Ethereum: '0x' + input.toLowerCase()};49    } else {50      throw new Error(`Unknown address format: "${input}"`);51    }52  }53  if ('address' in input) {54    return {Substrate: input.address};55  }56  if ('Ethereum' in input) {57    return {58      Ethereum: input.Ethereum.toLowerCase(),59    };60  } else if ('ethereum' in input) {61    return {62      Ethereum: (input as any).ethereum.toLowerCase(),63    };64  } else if ('Substrate' in input) {65    return input;66  } else if ('substrate' in input) {67    return {68      Substrate: (input as any).substrate,69    };70  }7172  // AccountId73  return {Substrate: input.toString()};74}75export function toSubstrateAddress(input: string | CrossAccountId | IKeyringPair): string {76  input = normalizeAccountId(input);77  if ('Substrate' in input) {78    return input.Substrate;79  } else {80    return evmToAddress(input.Ethereum);81  }82}8384export const U128_MAX = (1n << 128n) - 1n;8586const MICROUNIQUE = 1_000_000_000_000n;87const MILLIUNIQUE = 1_000n * MICROUNIQUE;88const CENTIUNIQUE = 10n * MILLIUNIQUE;89export const UNIQUE = 100n * CENTIUNIQUE;9091type GenericResult = {92  success: boolean,93};9495interface CreateCollectionResult {96  success: boolean;97  collectionId: number;98}99100interface CreateItemResult {101  success: boolean;102  collectionId: number;103  itemId: number;104  recipient?: CrossAccountId;105}106107interface TransferResult {108  success: boolean;109  collectionId: number;110  itemId: number;111  sender?: CrossAccountId;112  recipient?: CrossAccountId;113  value: bigint;114}115116interface IReFungibleOwner {117  fraction: BN;118  owner: number[];119}120121interface IGetMessage {122  checkMsgUnqMethod: string;123  checkMsgTrsMethod: string;124  checkMsgSysMethod: string;125}126127export interface IFungibleTokenDataType {128  value: number;129}130131export interface IChainLimits {132  collectionNumbersLimit: number;133  accountTokenOwnershipLimit: number;134  collectionsAdminsLimit: number;135  customDataLimit: number;136  nftSponsorTransferTimeout: number;137  fungibleSponsorTransferTimeout: number;138  refungibleSponsorTransferTimeout: number;139  offchainSchemaLimit: number;140  variableOnChainSchemaLimit: number;141  constOnChainSchemaLimit: number;142}143144export interface IReFungibleTokenDataType {145  owner: IReFungibleOwner[];146  constData: number[];147  variableData: number[];148}149150export function uniqueEventMessage(events: EventRecord[]): IGetMessage {151  let checkMsgUnqMethod = '';152  let checkMsgTrsMethod = '';153  let checkMsgSysMethod = '';154  events.forEach(({event: {method, section}}) => {155    if (section === 'common') {156      checkMsgUnqMethod = method;157    } else if (section === 'treasury') {158      checkMsgTrsMethod = method;159    } else if (section === 'system') {160      checkMsgSysMethod = method;161    } else { return null; }162  });163  const result: IGetMessage = {164    checkMsgUnqMethod,165    checkMsgTrsMethod,166    checkMsgSysMethod,167  };168  return result;169}170171export function getGenericResult(events: EventRecord[]): GenericResult {172  const result: GenericResult = {173    success: false,174  };175  events.forEach(({event: {method}}) => {176    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);177    if (method === 'ExtrinsicSuccess') {178      result.success = true;179    }180  });181  return result;182}183184185186export function getCreateCollectionResult(events: EventRecord[]): CreateCollectionResult {187  let success = false;188  let collectionId = 0;189  events.forEach(({event: {data, method, section}}) => {190    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);191    if (method == 'ExtrinsicSuccess') {192      success = true;193    } else if ((section == 'common') && (method == 'CollectionCreated')) {194      collectionId = parseInt(data[0].toString(), 10);195    }196  });197  const result: CreateCollectionResult = {198    success,199    collectionId,200  };201  return result;202}203204export function getCreateItemResult(events: EventRecord[]): CreateItemResult {205  let success = false;206  let collectionId = 0;207  let itemId = 0;208  let recipient;209  events.forEach(({event: {data, method, section}}) => {210    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);211    if (method == 'ExtrinsicSuccess') {212      success = true;213    } else if ((section == 'common') && (method == 'ItemCreated')) {214      collectionId = parseInt(data[0].toString(), 10);215      itemId = parseInt(data[1].toString(), 10);216      recipient = normalizeAccountId(data[2].toJSON() as any);217    }218  });219  const result: CreateItemResult = {220    success,221    collectionId,222    itemId,223    recipient,224  };225  return result;226}227228export function getTransferResult(events: EventRecord[]): TransferResult {229  const result: TransferResult = {230    success: false,231    collectionId: 0,232    itemId: 0,233    value: 0n,234  };235236  events.forEach(({event: {data, method, section}}) => {237    if (method === 'ExtrinsicSuccess') {238      result.success = true;239    } else if (section === 'common' && method === 'Transfer') {240      result.collectionId = +data[0].toString();241      result.itemId = +data[1].toString();242      result.sender = normalizeAccountId(data[2].toJSON() as any);243      result.recipient = normalizeAccountId(data[3].toJSON() as any);244      result.value = BigInt(data[4].toString());245    }246  });247248  return result;249}250251interface Nft {252  type: 'NFT';253}254255interface Fungible {256  type: 'Fungible';257  decimalPoints: number;258}259260interface ReFungible {261  type: 'ReFungible';262}263264type CollectionMode = Nft | Fungible | ReFungible;265266export type CreateCollectionParams = {267  mode: CollectionMode,268  name: string,269  description: string,270  tokenPrefix: string,271};272273const defaultCreateCollectionParams: CreateCollectionParams = {274  description: 'description',275  mode: {type: 'NFT'},276  name: 'name',277  tokenPrefix: 'prefix',278};279280export async function createCollectionExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {281  const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};282283  let collectionId = 0;284  await usingApi(async (api) => {285    // Get number of collections before the transaction286    const collectionCountBefore = await getCreatedCollectionCount(api);287288    // Run the CreateCollection transaction289    const alicePrivateKey = privateKey('//Alice');290291    let modeprm = {};292    if (mode.type === 'NFT') {293      modeprm = {nft: null};294    } else if (mode.type === 'Fungible') {295      modeprm = {fungible: mode.decimalPoints};296    } else if (mode.type === 'ReFungible') {297      modeprm = {refungible: null};298    }299300    const tx = api.tx.unique.createCollectionEx({name: strToUTF16(name), description: strToUTF16(description), tokenPrefix: strToUTF16(tokenPrefix), mode: modeprm as any});301    const events = await submitTransactionAsync(alicePrivateKey, tx);302    const result = getCreateCollectionResult(events);303304    // Get number of collections after the transaction305    const collectionCountAfter = await getCreatedCollectionCount(api);306307    // Get the collection308    const collection = await queryCollectionExpectSuccess(api, result.collectionId);309310    // What to expect311    // tslint:disable-next-line:no-unused-expression312    expect(result.success).to.be.true;313    expect(result.collectionId).to.be.equal(collectionCountAfter);314    // tslint:disable-next-line:no-unused-expression315    expect(collection).to.be.not.null;316    expect(collectionCountAfter).to.be.equal(collectionCountBefore + 1, 'Error: NFT collection NOT created.');317    expect(collection.owner.toString()).to.be.equal(toSubstrateAddress(alicesPublicKey));318    expect(utf16ToStr(collection.name.toJSON() as any)).to.be.equal(name);319    expect(utf16ToStr(collection.description.toJSON() as any)).to.be.equal(description);320    expect(hexToStr(collection.tokenPrefix.toJSON())).to.be.equal(tokenPrefix);321322    collectionId = result.collectionId;323  });324325  return collectionId;326}327328export async function createCollectionExpectFailure(params: Partial<CreateCollectionParams> = {}) {329  const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};330331  let modeprm = {};332  if (mode.type === 'NFT') {333    modeprm = {nft: null};334  } else if (mode.type === 'Fungible') {335    modeprm = {fungible: mode.decimalPoints};336  } else if (mode.type === 'ReFungible') {337    modeprm = {refungible: null};338  }339340  await usingApi(async (api) => {341    // Get number of collections before the transaction342    const collectionCountBefore = await getCreatedCollectionCount(api);343344    // Run the CreateCollection transaction345    const alicePrivateKey = privateKey('//Alice');346    const tx = api.tx.unique.createCollectionEx({name: strToUTF16(name), description: strToUTF16(description), tokenPrefix: strToUTF16(tokenPrefix), mode: modeprm as any});347    const events = await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;348    const result = getCreateCollectionResult(events);349350    // Get number of collections after the transaction351    const collectionCountAfter = await getCreatedCollectionCount(api);352353    // What to expect354    // tslint:disable-next-line:no-unused-expression355    expect(result.success).to.be.false;356    expect(collectionCountAfter).to.be.equal(collectionCountBefore, 'Error: Collection with incorrect data created.');357  });358}359360export async function findUnusedAddress(api: ApiPromise, seedAddition = ''): Promise<IKeyringPair> {361  let bal = 0n;362  let unused;363  do {364    const randomSeed = 'seed' + Math.floor(Math.random() * Math.floor(10000)) + seedAddition;365    const keyring = new Keyring({type: 'sr25519'});366    unused = keyring.addFromUri(`//${randomSeed}`);367    bal = (await api.query.system.account(unused.address)).data.free.toBigInt();368  } while (bal !== 0n);369  return unused;370}371372export async function getAllowance(api: ApiPromise, collectionId: number, owner: CrossAccountId | string, approved: CrossAccountId | string, tokenId: number) {373  return (await api.rpc.unique.allowance(collectionId, normalizeAccountId(owner), normalizeAccountId(approved), tokenId)).toBigInt();374}375376export function findUnusedAddresses(api: ApiPromise, amount: number): Promise<IKeyringPair[]> {377  return Promise.all(new Array(amount).fill(null).map(() => findUnusedAddress(api, '_' + Date.now())));378}379380export async function findNotExistingCollection(api: ApiPromise): Promise<number> {381  const totalNumber = await getCreatedCollectionCount(api);382  const newCollection: number = totalNumber + 1;383  return newCollection;384}385386function getDestroyResult(events: EventRecord[]): boolean {387  let success = false;388  events.forEach(({event: {method}}) => {389    if (method == 'ExtrinsicSuccess') {390      success = true;391    }392  });393  return success;394}395396export async function destroyCollectionExpectFailure(collectionId: number, senderSeed = '//Alice') {397  await usingApi(async (api) => {398    // Run the DestroyCollection transaction399    const alicePrivateKey = privateKey(senderSeed);400    const tx = api.tx.unique.destroyCollection(collectionId);401    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;402  });403}404405export async function destroyCollectionExpectSuccess(collectionId: number, senderSeed = '//Alice') {406  await usingApi(async (api) => {407    // Run the DestroyCollection transaction408    const alicePrivateKey = privateKey(senderSeed);409    const tx = api.tx.unique.destroyCollection(collectionId);410    const events = await submitTransactionAsync(alicePrivateKey, tx);411    const result = getDestroyResult(events);412    expect(result).to.be.true;413414    // What to expect415    expect(await getDetailedCollectionInfo(api, collectionId)).to.be.null;416  });417}418419export async function setCollectionLimitsExpectSuccess(sender: IKeyringPair, collectionId: number, limits: any) {420  await usingApi(async (api) => {421    const tx = api.tx.unique.setCollectionLimits(collectionId, limits);422    const events = await submitTransactionAsync(sender, tx);423    const result = getGenericResult(events);424425    expect(result.success).to.be.true;426  });427}428429export async function setCollectionLimitsExpectFailure(sender: IKeyringPair, collectionId: number, limits: any) {430  await usingApi(async (api) => {431    const tx = api.tx.unique.setCollectionLimits(collectionId, limits);432    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;433    const result = getGenericResult(events);434435    expect(result.success).to.be.false;436  });437}438439export async function setCollectionSponsorExpectSuccess(collectionId: number, sponsor: string, sender = '//Alice') {440  await usingApi(async (api) => {441442    // Run the transaction443    const senderPrivateKey = privateKey(sender);444    const tx = api.tx.unique.setCollectionSponsor(collectionId, sponsor);445    const events = await submitTransactionAsync(senderPrivateKey, tx);446    const result = getGenericResult(events);447448    // Get the collection449    const collection = await queryCollectionExpectSuccess(api, collectionId);450451    // What to expect452    expect(result.success).to.be.true;453    expect(collection.sponsorship.toJSON()).to.deep.equal({454      unconfirmed: sponsor,455    });456  });457}458459export async function removeCollectionSponsorExpectSuccess(collectionId: number, sender = '//Alice') {460  await usingApi(async (api) => {461462    // Run the transaction463    const alicePrivateKey = privateKey(sender);464    const tx = api.tx.unique.removeCollectionSponsor(collectionId);465    const events = await submitTransactionAsync(alicePrivateKey, tx);466    const result = getGenericResult(events);467468    // Get the collection469    const collection = await queryCollectionExpectSuccess(api, collectionId);470471    // What to expect472    expect(result.success).to.be.true;473    expect(collection.sponsorship.toJSON()).to.be.deep.equal({disabled: null});474  });475}476477export async function removeCollectionSponsorExpectFailure(collectionId: number, senderSeed = '//Alice') {478  await usingApi(async (api) => {479480    // Run the transaction481    const alicePrivateKey = privateKey(senderSeed);482    const tx = api.tx.unique.removeCollectionSponsor(collectionId);483    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;484  });485}486487export async function setCollectionSponsorExpectFailure(collectionId: number, sponsor: string, senderSeed = '//Alice') {488  await usingApi(async (api) => {489490    // Run the transaction491    const alicePrivateKey = privateKey(senderSeed);492    const tx = api.tx.unique.setCollectionSponsor(collectionId, sponsor);493    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;494  });495}496497export async function confirmSponsorshipExpectSuccess(collectionId: number, senderSeed = '//Alice') {498  await usingApi(async (api) => {499500    // Run the transaction501    const sender = privateKey(senderSeed);502    const tx = api.tx.unique.confirmSponsorship(collectionId);503    const events = await submitTransactionAsync(sender, tx);504    const result = getGenericResult(events);505506    // Get the collection507    const collection = await queryCollectionExpectSuccess(api, collectionId);508509    // What to expect510    expect(result.success).to.be.true;511    expect(collection.sponsorship.toJSON()).to.be.deep.equal({512      confirmed: sender.address,513    });514  });515}516517518export async function confirmSponsorshipExpectFailure(collectionId: number, senderSeed = '//Alice') {519  await usingApi(async (api) => {520521    // Run the transaction522    const sender = privateKey(senderSeed);523    const tx = api.tx.unique.confirmSponsorship(collectionId);524    await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;525  });526}527528export async function setMetadataUpdatePermissionFlagExpectSuccess(sender: IKeyringPair, collectionId: number, flag: string) {529530  await usingApi(async (api) => {531    const tx = api.tx.unique.setMetaUpdatePermissionFlag(collectionId, flag as any);532    const events = await submitTransactionAsync(sender, tx);533    const result = getGenericResult(events);534535    expect(result.success).to.be.true;536  });537}538539export async function setMetadataUpdatePermissionFlagExpectFailure(sender: IKeyringPair, collectionId: number, flag: string) {540541  await usingApi(async (api) => {542    const tx = api.tx.unique.setMetaUpdatePermissionFlag(collectionId, flag as any);543    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;544    const result = getGenericResult(events);545546    expect(result.success).to.be.false;547  });548}549550export async function enableContractSponsoringExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {551  await usingApi(async (api) => {552    const tx = api.tx.unique.enableContractSponsoring(contractAddress, enable);553    const events = await submitTransactionAsync(sender, tx);554    const result = getGenericResult(events);555556    expect(result.success).to.be.true;557  });558}559560export async function enableContractSponsoringExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {561  await usingApi(async (api) => {562    const tx = api.tx.unique.enableContractSponsoring(contractAddress, enable);563    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;564    const result = getGenericResult(events);565566    expect(result.success).to.be.false;567  });568}569570export async function setTransferFlagExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {571572  await usingApi(async (api) => {573574    const tx = api.tx.unique.setTransfersEnabledFlag(collectionId, enabled);575    const events = await submitTransactionAsync(sender, tx);576    const result = getGenericResult(events);577578    expect(result.success).to.be.true;579  });580}581582export async function setTransferFlagExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {583584  await usingApi(async (api) => {585586    const tx = api.tx.unique.setTransfersEnabledFlag(collectionId, enabled);587    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;588    const result = getGenericResult(events);589590    expect(result.success).to.be.false;591  });592}593594export async function setContractSponsoringRateLimitExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {595  await usingApi(async (api) => {596    const tx = api.tx.unique.setContractSponsoringRateLimit(contractAddress, rateLimit);597    const events = await submitTransactionAsync(sender, tx);598    const result = getGenericResult(events);599600    expect(result.success).to.be.true;601  });602}603604export async function setContractSponsoringRateLimitExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {605  await usingApi(async (api) => {606    const tx = api.tx.unique.setContractSponsoringRateLimit(contractAddress, rateLimit);607    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;608    const result = getGenericResult(events);609610    expect(result.success).to.be.false;611  });612}613614export async function toggleContractAllowlistExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, value = true) {615  await usingApi(async (api) => {616    const tx = api.tx.unique.toggleContractAllowList(contractAddress, value);617    const events = await submitTransactionAsync(sender, tx);618    const result = getGenericResult(events);619620    expect(result.success).to.be.true;621  });622}623624export async function isAllowlistedInContract(contractAddress: AccountId | string, user: string) {625  let allowlisted = false;626  await usingApi(async (api) => {627    allowlisted = (await api.query.unique.contractAllowList(contractAddress, user)).toJSON() as boolean;628  });629  return allowlisted;630}631632export async function addToContractAllowListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {633  await usingApi(async (api) => {634    const tx = api.tx.unique.addToContractAllowList(contractAddress.toString(), user.toString());635    const events = await submitTransactionAsync(sender, tx);636    const result = getGenericResult(events);637638    expect(result.success).to.be.true;639  });640}641642export async function removeFromContractAllowListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {643  await usingApi(async (api) => {644    const tx = api.tx.unique.removeFromContractAllowList(contractAddress.toString(), user.toString());645    const events = await submitTransactionAsync(sender, tx);646    const result = getGenericResult(events);647648    expect(result.success).to.be.true;649  });650}651652export async function removeFromContractAllowListExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {653  await usingApi(async (api) => {654    const tx = api.tx.unique.removeFromContractAllowList(contractAddress.toString(), user.toString());655    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;656    const result = getGenericResult(events);657658    expect(result.success).to.be.false;659  });660}661662export async function setVariableMetaDataExpectSuccess(sender: IKeyringPair, collectionId: number, itemId: number, data: number[]) {663  await usingApi(async (api) => {664    const tx = api.tx.unique.setVariableMetaData(collectionId, itemId, '0x' + Buffer.from(data).toString('hex'));665    const events = await submitTransactionAsync(sender, tx);666    const result = getGenericResult(events);667668    expect(result.success).to.be.true;669  });670}671672export async function setVariableMetaDataExpectFailure(sender: IKeyringPair, collectionId: number, itemId: number, data: number[]) {673  await usingApi(async (api) => {674    const tx = api.tx.unique.setVariableMetaData(collectionId, itemId, '0x' + Buffer.from(data).toString('hex'));675    await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;676  });677}678679export async function setOffchainSchemaExpectSuccess(sender: IKeyringPair, collectionId: number, data: number[]) {680  await usingApi(async (api) => {681    const tx = api.tx.unique.setOffchainSchema(collectionId, '0x' + Buffer.from(data).toString('hex'));682    const events = await submitTransactionAsync(sender, tx);683    const result = getGenericResult(events);684685    expect(result.success).to.be.true;686  });687}688689export async function setOffchainSchemaExpectFailure(sender: IKeyringPair, collectionId: number, data: number[]) {690  await usingApi(async (api) => {691    const tx = api.tx.unique.setOffchainSchema(collectionId, '0x' + Buffer.from(data).toString('hex'));692    await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;693  });694}695696export interface CreateFungibleData {697  readonly Value: bigint;698}699700export interface CreateReFungibleData { }701export interface CreateNftData { }702703export type CreateItemData = {704  NFT: CreateNftData;705} | {706  Fungible: CreateFungibleData;707} | {708  ReFungible: CreateReFungibleData;709};710711export async function burnItemExpectSuccess(sender: IKeyringPair, collectionId: number, tokenId: number, value = 1) {712  await usingApi(async (api) => {713    const balanceBefore = await getBalance(api, collectionId, normalizeAccountId(sender), tokenId);714    // if burning token by admin - use adminButnItemExpectSuccess715    expect(balanceBefore >= BigInt(value)).to.be.true;716717    const tx = api.tx.unique.burnItem(collectionId, tokenId, value);718    const events = await submitTransactionAsync(sender, tx);719    const result = getGenericResult(events);720    expect(result.success).to.be.true;721722    const balanceAfter = await getBalance(api, collectionId, normalizeAccountId(sender), tokenId);723    expect(balanceAfter + BigInt(value)).to.be.equal(balanceBefore);724  });725}726727export async function728approveExpectSuccess(729  collectionId: number,730  tokenId: number, owner: IKeyringPair, approved: CrossAccountId | string, amount: number | bigint = 1,731) {732  await usingApi(async (api: ApiPromise) => {733    const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);734    const events = await submitTransactionAsync(owner, approveUniqueTx);735    const result = getGenericResult(events);736    expect(result.success).to.be.true;737738    expect(await getAllowance(api, collectionId, owner.address, approved, tokenId)).to.be.equal(BigInt(amount));739  });740}741742export async function adminApproveFromExpectSuccess(743  collectionId: number,744  tokenId: number, admin: IKeyringPair, owner: CrossAccountId | string, approved: CrossAccountId | string, amount: number | bigint = 1,745) {746  await usingApi(async (api: ApiPromise) => {747    const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);748    const events = await submitTransactionAsync(admin, approveUniqueTx);749    const result = getGenericResult(events);750    expect(result.success).to.be.true;751752    expect(await getAllowance(api, collectionId, owner, approved, tokenId)).to.be.equal(BigInt(amount));753  });754}755756export async function757transferFromExpectSuccess(758  collectionId: number,759  tokenId: number,760  accountApproved: IKeyringPair,761  accountFrom: IKeyringPair | CrossAccountId,762  accountTo: IKeyringPair | CrossAccountId,763  value: number | bigint = 1,764  type = 'NFT',765) {766  await usingApi(async (api: ApiPromise) => {767    const from = normalizeAccountId(accountFrom);768    const to = normalizeAccountId(accountTo);769    let balanceBefore = 0n;770    if (type === 'Fungible') {771      balanceBefore = await getBalance(api, collectionId, to, tokenId);772    }773    const transferFromTx = api.tx.unique.transferFrom(normalizeAccountId(accountFrom), to, collectionId, tokenId, value);774    const events = await submitTransactionAsync(accountApproved, transferFromTx);775    const result = getCreateItemResult(events);776    // tslint:disable-next-line:no-unused-expression777    expect(result.success).to.be.true;778    if (type === 'NFT') {779      expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(to);780    }781    if (type === 'Fungible') {782      const balanceAfter = await getBalance(api, collectionId, to, tokenId);783      if (JSON.stringify(to) !== JSON.stringify(from)) {784        expect(balanceAfter - balanceBefore).to.be.equal(BigInt(value));785      } else {786        expect(balanceAfter).to.be.equal(balanceBefore);787      }788    }789    if (type === 'ReFungible') {790      expect(await getBalance(api, collectionId, to, tokenId)).to.be.equal(BigInt(value));791    }792  });793}794795export async function796transferFromExpectFail(797  collectionId: number,798  tokenId: number,799  accountApproved: IKeyringPair,800  accountFrom: IKeyringPair,801  accountTo: IKeyringPair,802  value: number | bigint = 1,803) {804  await usingApi(async (api: ApiPromise) => {805    const transferFromTx = api.tx.unique.transferFrom(normalizeAccountId(accountFrom.address), normalizeAccountId(accountTo.address), collectionId, tokenId, value);806    const events = await expect(submitTransactionExpectFailAsync(accountApproved, transferFromTx)).to.be.rejected;807    const result = getCreateCollectionResult(events);808    // tslint:disable-next-line:no-unused-expression809    expect(result.success).to.be.false;810  });811}812813/* eslint no-async-promise-executor: "off" */814async function getBlockNumber(api: ApiPromise): Promise<number> {815  return new Promise<number>(async (resolve) => {816    const unsubscribe = await api.rpc.chain.subscribeNewHeads((head) => {817      unsubscribe();818      resolve(head.number.toNumber());819    });820  });821}822823export async function addCollectionAdminExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | CrossAccountId) {824  await usingApi(async (api) => {825    const changeAdminTx = api.tx.unique.addCollectionAdmin(collectionId, normalizeAccountId(address));826    const events = await submitTransactionAsync(sender, changeAdminTx);827    const result = getCreateCollectionResult(events);828    expect(result.success).to.be.true;829  });830}831832export async function833getFreeBalance(account: IKeyringPair): Promise<bigint> {834  let balance = 0n;835  await usingApi(async (api) => {836    balance = BigInt((await api.query.system.account(account.address)).data.free.toString());837  });838839  return balance;840}841842export async function transferBalanceTo(api: ApiPromise, source: IKeyringPair, target: string, amount = 1000n * UNIQUE) {843  const tx = api.tx.balances.transfer(target, amount);844  const events = await submitTransactionAsync(source, tx);845  const result = getGenericResult(events);846  expect(result.success).to.be.true;847}848849export async function850scheduleTransferExpectSuccess(851  collectionId: number,852  tokenId: number,853  sender: IKeyringPair,854  recipient: IKeyringPair,855  value: number | bigint = 1,856  blockSchedule: number,857) {858  await usingApi(async (api: ApiPromise) => {859    const blockNumber: number | undefined = await getBlockNumber(api);860    const expectedBlockNumber = blockNumber + blockSchedule;861862    expect(blockNumber).to.be.greaterThan(0);863    const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient.address), collectionId, tokenId, value);864    const scheduleTx = api.tx.scheduler.schedule(expectedBlockNumber, null, 0, transferTx as any);865866    await submitTransactionAsync(sender, scheduleTx);867868    const recipientBalanceBefore = (await api.query.system.account(recipient.address)).data.free.toBigInt();869870    expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(sender.address));871872    // sleep for 4 blocks873    await waitNewBlocks(blockSchedule + 1);874875    const recipientBalanceAfter = (await api.query.system.account(recipient.address)).data.free.toBigInt();876877    expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(recipient.address));878    expect(recipientBalanceAfter).to.be.equal(recipientBalanceBefore);879  });880}881882883export async function884transferExpectSuccess(885  collectionId: number,886  tokenId: number,887  sender: IKeyringPair,888  recipient: IKeyringPair | CrossAccountId,889  value: number | bigint = 1,890  type = 'NFT',891) {892  await usingApi(async (api: ApiPromise) => {893    const from = normalizeAccountId(sender);894    const to = normalizeAccountId(recipient);895896    let balanceBefore = 0n;897    if (type === 'Fungible') {898      balanceBefore = await getBalance(api, collectionId, to, tokenId);899    }900    const transferTx = api.tx.unique.transfer(to, collectionId, tokenId, value);901    const events = await submitTransactionAsync(sender, transferTx);902    const result = getTransferResult(events);903    // tslint:disable-next-line:no-unused-expression904    expect(result.success).to.be.true;905    expect(result.collectionId).to.be.equal(collectionId);906    expect(result.itemId).to.be.equal(tokenId);907    expect(result.sender).to.be.deep.equal(normalizeAccountId(sender.address));908    expect(result.recipient).to.be.deep.equal(to);909    expect(result.value).to.be.equal(BigInt(value));910    if (type === 'NFT') {911      expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(to);912    }913    if (type === 'Fungible') {914      const balanceAfter = await getBalance(api, collectionId, to, tokenId);915      if (JSON.stringify(to) !== JSON.stringify(from)) {916        expect(balanceAfter - balanceBefore).to.be.equal(BigInt(value));917      } else {918        expect(balanceAfter).to.be.equal(balanceBefore);919      }920    }921    if (type === 'ReFungible') {922      expect(await getBalance(api, collectionId, to, tokenId) >= value).to.be.true;923    }924  });925}926927export async function928transferExpectFailure(929  collectionId: number,930  tokenId: number,931  sender: IKeyringPair,932  recipient: IKeyringPair,933  value: number | bigint = 1,934) {935  await usingApi(async (api: ApiPromise) => {936    const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient.address), collectionId, tokenId, value);937    const events = await expect(submitTransactionExpectFailAsync(sender, transferTx)).to.be.rejected;938    const result = getGenericResult(events);939    // if (events && Array.isArray(events)) {940    //   const result = getCreateCollectionResult(events);941    // tslint:disable-next-line:no-unused-expression942    expect(result.success).to.be.false;943    //}944  });945}946947export async function948approveExpectFail(949  collectionId: number,950  tokenId: number, owner: IKeyringPair, approved: IKeyringPair, amount: number | bigint = 1,951) {952  await usingApi(async (api: ApiPromise) => {953    const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved.address), collectionId, tokenId, amount);954    const events = await expect(submitTransactionExpectFailAsync(owner, approveUniqueTx)).to.be.rejected;955    const result = getCreateCollectionResult(events);956    // tslint:disable-next-line:no-unused-expression957    expect(result.success).to.be.false;958  });959}960961export async function getBalance(962  api: ApiPromise,963  collectionId: number,964  owner: string | CrossAccountId,965  token: number,966): Promise<bigint> {967  return (await api.rpc.unique.balance(collectionId, normalizeAccountId(owner), token)).toBigInt();968}969export async function getTokenOwner(970  api: ApiPromise,971  collectionId: number,972  token: number,973): Promise<CrossAccountId> {974  return normalizeAccountId((await api.rpc.unique.tokenOwner(collectionId, token)).toJSON() as any);975}976export async function isTokenExists(977  api: ApiPromise,978  collectionId: number,979  token: number,980): Promise<boolean> {981  return (await api.rpc.unique.tokenExists(collectionId, token)).toJSON();982}983export async function getLastTokenId(984  api: ApiPromise,985  collectionId: number,986): Promise<number> {987  return (await api.rpc.unique.lastTokenId(collectionId)).toJSON();988}989export async function getAdminList(990  api: ApiPromise,991  collectionId: number,992): Promise<string[]> {993  return (await api.rpc.unique.adminlist(collectionId)).toHuman() as any;994}995export async function getVariableMetadata(996  api: ApiPromise,997  collectionId: number,998  tokenId: number,999): Promise<number[]> {1000  return [...(await api.rpc.unique.variableMetadata(collectionId, tokenId))];1001}1002export async function getConstMetadata(1003  api: ApiPromise,1004  collectionId: number,1005  tokenId: number,1006): Promise<number[]> {1007  return [...(await api.rpc.unique.constMetadata(collectionId, tokenId))];1008}10091010export async function createFungibleItemExpectSuccess(1011  sender: IKeyringPair,1012  collectionId: number,1013  data: CreateFungibleData,1014  owner: CrossAccountId | string = sender.address,1015) {1016  return await usingApi(async (api) => {1017    const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), {Fungible: data});10181019    const events = await submitTransactionAsync(sender, tx);1020    const result = getCreateItemResult(events);10211022    expect(result.success).to.be.true;1023    return result.itemId;1024  });1025}10261027export async function createItemExpectSuccess(sender: IKeyringPair, collectionId: number, createMode: string, owner: CrossAccountId | string = sender.address) {1028  let newItemId = 0;1029  await usingApi(async (api) => {1030    const to = normalizeAccountId(owner);1031    const itemCountBefore = await getLastTokenId(api, collectionId);1032    const itemBalanceBefore = await getBalance(api, collectionId, to, newItemId);10331034    let tx;1035    if (createMode === 'Fungible') {1036      const createData = {fungible: {value: 10}};1037      tx = api.tx.unique.createItem(collectionId, to, createData as any);1038    } else if (createMode === 'ReFungible') {1039      const createData = {refungible: {const_data: [], variable_data: [], pieces: 100}};1040      tx = api.tx.unique.createItem(collectionId, to, createData as any);1041    } else {1042      const createData = {nft: {const_data: [], variable_data: []}};1043      tx = api.tx.unique.createItem(collectionId, to, createData as any);1044    }10451046    const events = await submitTransactionAsync(sender, tx);1047    const result = getCreateItemResult(events);10481049    const itemCountAfter = await getLastTokenId(api, collectionId);1050    const itemBalanceAfter = await getBalance(api, collectionId, to, newItemId);10511052    // What to expect1053    // tslint:disable-next-line:no-unused-expression1054    expect(result.success).to.be.true;1055    if (createMode === 'Fungible') {1056      expect(itemBalanceAfter - itemBalanceBefore).to.be.equal(10n);1057    } else {1058      expect(itemCountAfter).to.be.equal(itemCountBefore + 1);1059    }1060    expect(collectionId).to.be.equal(result.collectionId);1061    expect(itemCountAfter.toString()).to.be.equal(result.itemId.toString());1062    expect(to).to.be.deep.equal(result.recipient);1063    newItemId = result.itemId;1064  });1065  return newItemId;1066}10671068export async function createItemExpectFailure(sender: IKeyringPair, collectionId: number, createMode: string, owner: string = sender.address) {1069  await usingApi(async (api) => {1070    const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), createMode);10711072    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1073    const result = getCreateItemResult(events);10741075    expect(result.success).to.be.false;1076  });1077}10781079export async function setPublicAccessModeExpectSuccess(1080  sender: IKeyringPair, collectionId: number,1081  accessMode: 'Normal' | 'AllowList',1082) {1083  await usingApi(async (api) => {10841085    // Run the transaction1086    const tx = api.tx.unique.setPublicAccessMode(collectionId, accessMode);1087    const events = await submitTransactionAsync(sender, tx);1088    const result = getGenericResult(events);10891090    // Get the collection1091    const collection = await queryCollectionExpectSuccess(api, collectionId);10921093    // What to expect1094    // tslint:disable-next-line:no-unused-expression1095    expect(result.success).to.be.true;1096    expect(collection.access.toHuman()).to.be.equal(accessMode);1097  });1098}10991100export async function setPublicAccessModeExpectFail(1101  sender: IKeyringPair, collectionId: number,1102  accessMode: 'Normal' | 'AllowList',1103) {1104  await usingApi(async (api) => {11051106    // Run the transaction1107    const tx = api.tx.unique.setPublicAccessMode(collectionId, accessMode);1108    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1109    const result = getGenericResult(events);11101111    // What to expect1112    // tslint:disable-next-line:no-unused-expression1113    expect(result.success).to.be.false;1114  });1115}11161117export async function enableAllowListExpectSuccess(sender: IKeyringPair, collectionId: number) {1118  await setPublicAccessModeExpectSuccess(sender, collectionId, 'AllowList');1119}11201121export async function enableAllowListExpectFail(sender: IKeyringPair, collectionId: number) {1122  await setPublicAccessModeExpectFail(sender, collectionId, 'AllowList');1123}11241125export async function disableAllowListExpectSuccess(sender: IKeyringPair, collectionId: number) {1126  await setPublicAccessModeExpectSuccess(sender, collectionId, 'Normal');1127}11281129export async function setMintPermissionExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {1130  await usingApi(async (api) => {11311132    // Run the transaction1133    const tx = api.tx.unique.setMintPermission(collectionId, enabled);1134    const events = await submitTransactionAsync(sender, tx);1135    const result = getGenericResult(events);1136    expect(result.success).to.be.true;11371138    // Get the collection1139    const collection = await queryCollectionExpectSuccess(api, collectionId);11401141    expect(collection.mintMode.toHuman()).to.be.equal(enabled);1142  });1143}11441145export async function enablePublicMintingExpectSuccess(sender: IKeyringPair, collectionId: number) {1146  await setMintPermissionExpectSuccess(sender, collectionId, true);1147}11481149export async function setMintPermissionExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {1150  await usingApi(async (api) => {1151    // Run the transaction1152    const tx = api.tx.unique.setMintPermission(collectionId, enabled);1153    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1154    const result = getCreateCollectionResult(events);1155    // tslint:disable-next-line:no-unused-expression1156    expect(result.success).to.be.false;1157  });1158}11591160export async function setChainLimitsExpectFailure(sender: IKeyringPair, limits: IChainLimits) {1161  await usingApi(async (api) => {1162    // Run the transaction1163    const tx = api.tx.unique.setChainLimits(limits);1164    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1165    const result = getCreateCollectionResult(events);1166    // tslint:disable-next-line:no-unused-expression1167    expect(result.success).to.be.false;1168  });1169}11701171export async function isAllowlisted(api: ApiPromise, collectionId: number, address: string | CrossAccountId) {1172  return (await api.rpc.unique.allowed(collectionId, normalizeAccountId(address))).toJSON();1173}11741175export async function addToAllowListExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId | CrossAccountId) {1176  await usingApi(async (api) => {1177    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.false;11781179    // Run the transaction1180    const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1181    const events = await submitTransactionAsync(sender, tx);1182    const result = getGenericResult(events);1183    expect(result.success).to.be.true;11841185    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;1186  });1187}11881189export async function addToAllowListAgainExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId) {1190  await usingApi(async (api) => {11911192    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;11931194    // Run the transaction1195    const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1196    const events = await submitTransactionAsync(sender, tx);1197    const result = getGenericResult(events);1198    expect(result.success).to.be.true;11991200    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;1201  });1202}12031204export async function addToAllowListExpectFail(sender: IKeyringPair, collectionId: number, address: string | AccountId) {1205  await usingApi(async (api) => {12061207    // Run the transaction1208    const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1209    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1210    const result = getGenericResult(events);12111212    // What to expect1213    // tslint:disable-next-line:no-unused-expression1214    expect(result.success).to.be.false;1215  });1216}12171218export async function removeFromAllowListExpectSuccess(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1219  await usingApi(async (api) => {1220    // Run the transaction1221    const tx = api.tx.unique.removeFromAllowList(collectionId, normalizeAccountId(address));1222    const events = await submitTransactionAsync(sender, tx);1223    const result = getGenericResult(events);12241225    // What to expect1226    // tslint:disable-next-line:no-unused-expression1227    expect(result.success).to.be.true;1228  });1229}12301231export async function removeFromAllowListExpectFailure(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1232  await usingApi(async (api) => {1233    // Run the transaction1234    const tx = api.tx.unique.removeFromAllowList(collectionId, normalizeAccountId(address));1235    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1236    const result = getGenericResult(events);12371238    // What to expect1239    // tslint:disable-next-line:no-unused-expression1240    expect(result.success).to.be.false;1241  });1242}12431244export const getDetailedCollectionInfo = async (api: ApiPromise, collectionId: number)1245  : Promise<UpDataStructsCollection | null> => {1246  return (await api.rpc.unique.collectionById(collectionId)).unwrapOr(null);1247};12481249export const getCreatedCollectionCount = async (api: ApiPromise): Promise<number> => {1250  // set global object - collectionsCount1251  return (await api.rpc.unique.collectionStats()).created.toNumber();1252};12531254export async function queryCollectionExpectSuccess(api: ApiPromise, collectionId: number): Promise<UpDataStructsCollection> {1255  return (await api.rpc.unique.collectionById(collectionId)).unwrap();1256}12571258export async function waitNewBlocks(blocksCount = 1): Promise<void> {1259  await usingApi(async (api) => {1260    const promise = new Promise<void>(async (resolve) => {1261      const unsubscribe = await api.rpc.chain.subscribeNewHeads(() => {1262        if (blocksCount > 0) {1263          blocksCount--;1264        } else {1265          unsubscribe();1266          resolve();1267        }1268      });1269    });1270    return promise;1271  });1272}