git.delta.rocks / unique-network / refs/commits / 8b54ea00d9b8

difftreelog

source

tests/src/util/helpers.ts46.0 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};40export function normalizeAccountId(input: string | AccountId | CrossAccountId | IKeyringPair): CrossAccountId {41  if (typeof input === 'string') {42    if (input.length === 48 || input.length === 47) {43      return {Substrate: input};44    } else if (input.length === 42 && input.startsWith('0x')) {45      return {Ethereum: input.toLowerCase()};46    } else if (input.length === 40 && !input.startsWith('0x')) {47      return {Ethereum: '0x' + input.toLowerCase()};48    } else {49      throw new Error(`Unknown address format: "${input}"`);50    }51  }52  if ('address' in input) {53    return {Substrate: input.address};54  }55  if ('Ethereum' in input) {56    return {57      Ethereum: input.Ethereum.toLowerCase(),58    };59  } else if ('ethereum' in input) {60    return {61      Ethereum: (input as any).ethereum.toLowerCase(),62    };63  } else if ('Substrate' in input) {64    return input;65  } else if ('substrate' in input) {66    return {67      Substrate: (input as any).substrate,68    };69  }7071  // AccountId72  return {Substrate: input.toString()};73}74export function toSubstrateAddress(input: string | CrossAccountId | IKeyringPair): string {75  input = normalizeAccountId(input);76  if ('Substrate' in input) {77    return input.Substrate;78  } else {79    return evmToAddress(input.Ethereum);80  }81}8283export const U128_MAX = (1n << 128n) - 1n;8485const MICROUNIQUE = 1_000_000_000_000n;86const MILLIUNIQUE = 1_000n * MICROUNIQUE;87const CENTIUNIQUE = 10n * MILLIUNIQUE;88export const UNIQUE = 100n * CENTIUNIQUE;8990type GenericResult = {91  success: boolean,92};9394interface CreateCollectionResult {95  success: boolean;96  collectionId: number;97}9899interface CreateItemResult {100  success: boolean;101  collectionId: number;102  itemId: number;103  recipient?: CrossAccountId;104}105106interface TransferResult {107  success: boolean;108  collectionId: number;109  itemId: number;110  sender?: CrossAccountId;111  recipient?: CrossAccountId;112  value: bigint;113}114115interface IReFungibleOwner {116  fraction: BN;117  owner: number[];118}119120interface IGetMessage {121  checkMsgUnqMethod: string;122  checkMsgTrsMethod: string;123  checkMsgSysMethod: string;124}125126export interface IFungibleTokenDataType {127  value: number;128}129130export interface IChainLimits {131  collectionNumbersLimit: number;132  accountTokenOwnershipLimit: number;133  collectionsAdminsLimit: number;134  customDataLimit: number;135  nftSponsorTransferTimeout: number;136  fungibleSponsorTransferTimeout: number;137  refungibleSponsorTransferTimeout: number;138  offchainSchemaLimit: number;139  variableOnChainSchemaLimit: number;140  constOnChainSchemaLimit: number;141}142143export interface IReFungibleTokenDataType {144  owner: IReFungibleOwner[];145  constData: number[];146  variableData: number[];147}148149export function uniqueEventMessage(events: EventRecord[]): IGetMessage {150  let checkMsgUnqMethod = '';151  let checkMsgTrsMethod = '';152  let checkMsgSysMethod = '';153  events.forEach(({event: {method, section}}) => {154    if (section === 'common') {155      checkMsgUnqMethod = method;156    } else if (section === 'treasury') {157      checkMsgTrsMethod = method;158    } else if (section === 'system') {159      checkMsgSysMethod = method;160    } else { return null; }161  });162  const result: IGetMessage = {163    checkMsgUnqMethod,164    checkMsgTrsMethod,165    checkMsgSysMethod,166  };167  return result;168}169170export function getGenericResult(events: EventRecord[]): GenericResult {171  const result: GenericResult = {172    success: false,173  };174  events.forEach(({event: {method}}) => {175    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);176    if (method === 'ExtrinsicSuccess') {177      result.success = true;178    }179  });180  return result;181}182183184185export function getCreateCollectionResult(events: EventRecord[]): CreateCollectionResult {186  let success = false;187  let collectionId = 0;188  events.forEach(({event: {data, method, section}}) => {189    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);190    if (method == 'ExtrinsicSuccess') {191      success = true;192    } else if ((section == 'common') && (method == 'CollectionCreated')) {193      collectionId = parseInt(data[0].toString(), 10);194    }195  });196  const result: CreateCollectionResult = {197    success,198    collectionId,199  };200  return result;201}202203export function getCreateItemResult(events: EventRecord[]): CreateItemResult {204  let success = false;205  let collectionId = 0;206  let itemId = 0;207  let recipient;208  events.forEach(({event: {data, method, section}}) => {209    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);210    if (method == 'ExtrinsicSuccess') {211      success = true;212    } else if ((section == 'common') && (method == 'ItemCreated')) {213      collectionId = parseInt(data[0].toString(), 10);214      itemId = parseInt(data[1].toString(), 10);215      recipient = normalizeAccountId(data[2].toJSON() as any);216    }217  });218  const result: CreateItemResult = {219    success,220    collectionId,221    itemId,222    recipient,223  };224  return result;225}226227export function getTransferResult(events: EventRecord[]): TransferResult {228  const result: TransferResult = {229    success: false,230    collectionId: 0,231    itemId: 0,232    value: 0n,233  };234235  events.forEach(({event: {data, method, section}}) => {236    if (method === 'ExtrinsicSuccess') {237      result.success = true;238    } else if (section === 'common' && method === 'Transfer') {239      result.collectionId = +data[0].toString();240      result.itemId = +data[1].toString();241      result.sender = normalizeAccountId(data[2].toJSON() as any);242      result.recipient = normalizeAccountId(data[3].toJSON() as any);243      result.value = BigInt(data[4].toString());244    }245  });246247  return result;248}249250interface Nft {251  type: 'NFT';252}253254interface Fungible {255  type: 'Fungible';256  decimalPoints: number;257}258259interface ReFungible {260  type: 'ReFungible';261}262263type CollectionMode = Nft | Fungible | ReFungible;264265export type CreateCollectionParams = {266  mode: CollectionMode,267  name: string,268  description: string,269  tokenPrefix: string,270};271272const defaultCreateCollectionParams: CreateCollectionParams = {273  description: 'description',274  mode: {type: 'NFT'},275  name: 'name',276  tokenPrefix: 'prefix',277};278279export async function createCollectionExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {280  const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};281282  let collectionId = 0;283  await usingApi(async (api) => {284    // Get number of collections before the transaction285    const collectionCountBefore = await getCreatedCollectionCount(api);286287    // Run the CreateCollection transaction288    const alicePrivateKey = privateKey('//Alice');289290    let modeprm = {};291    if (mode.type === 'NFT') {292      modeprm = {nft: null};293    } else if (mode.type === 'Fungible') {294      modeprm = {fungible: mode.decimalPoints};295    } else if (mode.type === 'ReFungible') {296      modeprm = {refungible: null};297    }298299    const tx = api.tx.unique.createCollectionEx({name: strToUTF16(name), description: strToUTF16(description), tokenPrefix: strToUTF16(tokenPrefix), mode: modeprm as any});300    const events = await submitTransactionAsync(alicePrivateKey, tx);301    const result = getCreateCollectionResult(events);302303    // Get number of collections after the transaction304    const collectionCountAfter = await getCreatedCollectionCount(api);305306    // Get the collection307    const collection = await queryCollectionExpectSuccess(api, result.collectionId);308309    // What to expect310    // tslint:disable-next-line:no-unused-expression311    expect(result.success).to.be.true;312    expect(result.collectionId).to.be.equal(collectionCountAfter);313    // tslint:disable-next-line:no-unused-expression314    expect(collection).to.be.not.null;315    expect(collectionCountAfter).to.be.equal(collectionCountBefore + 1, 'Error: NFT collection NOT created.');316    expect(collection.owner.toString()).to.be.equal(toSubstrateAddress(alicesPublicKey));317    expect(utf16ToStr(collection.name.toJSON() as any)).to.be.equal(name);318    expect(utf16ToStr(collection.description.toJSON() as any)).to.be.equal(description);319    expect(hexToStr(collection.tokenPrefix.toJSON())).to.be.equal(tokenPrefix);320321    collectionId = result.collectionId;322  });323324  return collectionId;325}326327export async function createCollectionExpectFailure(params: Partial<CreateCollectionParams> = {}) {328  const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};329330  let modeprm = {};331  if (mode.type === 'NFT') {332    modeprm = {nft: null};333  } else if (mode.type === 'Fungible') {334    modeprm = {fungible: mode.decimalPoints};335  } else if (mode.type === 'ReFungible') {336    modeprm = {refungible: null};337  }338339  await usingApi(async (api) => {340    // Get number of collections before the transaction341    const collectionCountBefore = await getCreatedCollectionCount(api);342343    // Run the CreateCollection transaction344    const alicePrivateKey = privateKey('//Alice');345    const tx = api.tx.unique.createCollectionEx({name: strToUTF16(name), description: strToUTF16(description), tokenPrefix: strToUTF16(tokenPrefix), mode: modeprm as any});346    const events = await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;347    const result = getCreateCollectionResult(events);348349    // Get number of collections after the transaction350    const collectionCountAfter = await getCreatedCollectionCount(api);351352    // What to expect353    // tslint:disable-next-line:no-unused-expression354    expect(result.success).to.be.false;355    expect(collectionCountAfter).to.be.equal(collectionCountBefore, 'Error: Collection with incorrect data created.');356  });357}358359export async function findUnusedAddress(api: ApiPromise, seedAddition = ''): Promise<IKeyringPair> {360  let bal = 0n;361  let unused;362  do {363    const randomSeed = 'seed' + Math.floor(Math.random() * Math.floor(10000)) + seedAddition;364    const keyring = new Keyring({type: 'sr25519'});365    unused = keyring.addFromUri(`//${randomSeed}`);366    bal = (await api.query.system.account(unused.address)).data.free.toBigInt();367  } while (bal !== 0n);368  return unused;369}370371export async function getAllowance(api: ApiPromise, collectionId: number, owner: CrossAccountId | string, approved: CrossAccountId | string, tokenId: number) {372  return (await api.rpc.unique.allowance(collectionId, normalizeAccountId(owner), normalizeAccountId(approved), tokenId)).toBigInt();373}374375export function findUnusedAddresses(api: ApiPromise, amount: number): Promise<IKeyringPair[]> {376  return Promise.all(new Array(amount).fill(null).map(() => findUnusedAddress(api, '_' + Date.now())));377}378379export async function findNotExistingCollection(api: ApiPromise): Promise<number> {380  const totalNumber = await getCreatedCollectionCount(api);381  const newCollection: number = totalNumber + 1;382  return newCollection;383}384385function getDestroyResult(events: EventRecord[]): boolean {386  let success = false;387  events.forEach(({event: {method}}) => {388    if (method == 'ExtrinsicSuccess') {389      success = true;390    }391  });392  return success;393}394395export async function destroyCollectionExpectFailure(collectionId: number, senderSeed = '//Alice') {396  await usingApi(async (api) => {397    // Run the DestroyCollection transaction398    const alicePrivateKey = privateKey(senderSeed);399    const tx = api.tx.unique.destroyCollection(collectionId);400    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;401  });402}403404export async function destroyCollectionExpectSuccess(collectionId: number, senderSeed = '//Alice') {405  await usingApi(async (api) => {406    // Run the DestroyCollection transaction407    const alicePrivateKey = privateKey(senderSeed);408    const tx = api.tx.unique.destroyCollection(collectionId);409    const events = await submitTransactionAsync(alicePrivateKey, tx);410    const result = getDestroyResult(events);411    expect(result).to.be.true;412413    // What to expect414    expect(await getDetailedCollectionInfo(api, collectionId)).to.be.null;415  });416}417418export async function setCollectionLimitsExpectSuccess(sender: IKeyringPair, collectionId: number, limits: any) {419  await usingApi(async (api) => {420    const tx = api.tx.unique.setCollectionLimits(collectionId, limits);421    const events = await submitTransactionAsync(sender, tx);422    const result = getGenericResult(events);423424    expect(result.success).to.be.true;425  });426}427428export async function setCollectionLimitsExpectFailure(sender: IKeyringPair, collectionId: number, limits: any) {429  await usingApi(async (api) => {430    const tx = api.tx.unique.setCollectionLimits(collectionId, limits);431    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;432    const result = getGenericResult(events);433434    expect(result.success).to.be.false;435  });436}437438export async function setCollectionSponsorExpectSuccess(collectionId: number, sponsor: string, sender = '//Alice') {439  await usingApi(async (api) => {440441    // Run the transaction442    const senderPrivateKey = privateKey(sender);443    const tx = api.tx.unique.setCollectionSponsor(collectionId, sponsor);444    const events = await submitTransactionAsync(senderPrivateKey, tx);445    const result = getGenericResult(events);446447    // Get the collection448    const collection = await queryCollectionExpectSuccess(api, collectionId);449450    // What to expect451    expect(result.success).to.be.true;452    expect(collection.sponsorship.toJSON()).to.deep.equal({453      unconfirmed: sponsor,454    });455  });456}457458export async function removeCollectionSponsorExpectSuccess(collectionId: number, sender = '//Alice') {459  await usingApi(async (api) => {460461    // Run the transaction462    const alicePrivateKey = privateKey(sender);463    const tx = api.tx.unique.removeCollectionSponsor(collectionId);464    const events = await submitTransactionAsync(alicePrivateKey, tx);465    const result = getGenericResult(events);466467    // Get the collection468    const collection = await queryCollectionExpectSuccess(api, collectionId);469470    // What to expect471    expect(result.success).to.be.true;472    expect(collection.sponsorship.toJSON()).to.be.deep.equal({disabled: null});473  });474}475476export async function removeCollectionSponsorExpectFailure(collectionId: number, senderSeed = '//Alice') {477  await usingApi(async (api) => {478479    // Run the transaction480    const alicePrivateKey = privateKey(senderSeed);481    const tx = api.tx.unique.removeCollectionSponsor(collectionId);482    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;483  });484}485486export async function setCollectionSponsorExpectFailure(collectionId: number, sponsor: string, senderSeed = '//Alice') {487  await usingApi(async (api) => {488489    // Run the transaction490    const alicePrivateKey = privateKey(senderSeed);491    const tx = api.tx.unique.setCollectionSponsor(collectionId, sponsor);492    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;493  });494}495496export async function confirmSponsorshipExpectSuccess(collectionId: number, senderSeed = '//Alice') {497  await usingApi(async () => {498    const sender = privateKey(senderSeed);499    await confirmSponsorshipByKeyExpectSuccess(collectionId, sender);500  });501}502503export async function confirmSponsorshipByKeyExpectSuccess(collectionId: number, sender: IKeyringPair) {504  await usingApi(async (api) => {505506    // Run the transaction507    const tx = api.tx.unique.confirmSponsorship(collectionId);508    const events = await submitTransactionAsync(sender, tx);509    const result = getGenericResult(events);510511    // Get the collection512    const collection = await queryCollectionExpectSuccess(api, collectionId);513514    // What to expect515    expect(result.success).to.be.true;516    expect(collection.sponsorship.toJSON()).to.be.deep.equal({517      confirmed: sender.address,518    });519  });520}521522523export async function confirmSponsorshipExpectFailure(collectionId: number, senderSeed = '//Alice') {524  await usingApi(async (api) => {525526    // Run the transaction527    const sender = privateKey(senderSeed);528    const tx = api.tx.unique.confirmSponsorship(collectionId);529    await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;530  });531}532533export async function setMetadataUpdatePermissionFlagExpectSuccess(sender: IKeyringPair, collectionId: number, flag: string) {534535  await usingApi(async (api) => {536    const tx = api.tx.unique.setMetaUpdatePermissionFlag(collectionId, flag as any);537    const events = await submitTransactionAsync(sender, tx);538    const result = getGenericResult(events);539540    expect(result.success).to.be.true;541  });542}543544export async function setMetadataUpdatePermissionFlagExpectFailure(sender: IKeyringPair, collectionId: number, flag: string) {545546  await usingApi(async (api) => {547    const tx = api.tx.unique.setMetaUpdatePermissionFlag(collectionId, flag as any);548    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;549    const result = getGenericResult(events);550551    expect(result.success).to.be.false;552  });553}554555export async function enableContractSponsoringExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {556  await usingApi(async (api) => {557    const tx = api.tx.unique.enableContractSponsoring(contractAddress, enable);558    const events = await submitTransactionAsync(sender, tx);559    const result = getGenericResult(events);560561    expect(result.success).to.be.true;562  });563}564565export async function enableContractSponsoringExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {566  await usingApi(async (api) => {567    const tx = api.tx.unique.enableContractSponsoring(contractAddress, enable);568    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;569    const result = getGenericResult(events);570571    expect(result.success).to.be.false;572  });573}574575export async function setTransferFlagExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {576577  await usingApi(async (api) => {578579    const tx = api.tx.unique.setTransfersEnabledFlag(collectionId, enabled);580    const events = await submitTransactionAsync(sender, tx);581    const result = getGenericResult(events);582583    expect(result.success).to.be.true;584  });585}586587export async function setTransferFlagExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {588589  await usingApi(async (api) => {590591    const tx = api.tx.unique.setTransfersEnabledFlag(collectionId, enabled);592    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;593    const result = getGenericResult(events);594595    expect(result.success).to.be.false;596  });597}598599export async function setContractSponsoringRateLimitExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {600  await usingApi(async (api) => {601    const tx = api.tx.unique.setContractSponsoringRateLimit(contractAddress, rateLimit);602    const events = await submitTransactionAsync(sender, tx);603    const result = getGenericResult(events);604605    expect(result.success).to.be.true;606  });607}608609export async function setContractSponsoringRateLimitExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {610  await usingApi(async (api) => {611    const tx = api.tx.unique.setContractSponsoringRateLimit(contractAddress, rateLimit);612    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;613    const result = getGenericResult(events);614615    expect(result.success).to.be.false;616  });617}618619export async function toggleContractAllowlistExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, value = true) {620  await usingApi(async (api) => {621    const tx = api.tx.unique.toggleContractAllowList(contractAddress, value);622    const events = await submitTransactionAsync(sender, tx);623    const result = getGenericResult(events);624625    expect(result.success).to.be.true;626  });627}628629export async function isAllowlistedInContract(contractAddress: AccountId | string, user: string) {630  let allowlisted = false;631  await usingApi(async (api) => {632    allowlisted = (await api.query.unique.contractAllowList(contractAddress, user)).toJSON() as boolean;633  });634  return allowlisted;635}636637export async function addToContractAllowListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {638  await usingApi(async (api) => {639    const tx = api.tx.unique.addToContractAllowList(contractAddress.toString(), user.toString());640    const events = await submitTransactionAsync(sender, tx);641    const result = getGenericResult(events);642643    expect(result.success).to.be.true;644  });645}646647export async function removeFromContractAllowListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {648  await usingApi(async (api) => {649    const tx = api.tx.unique.removeFromContractAllowList(contractAddress.toString(), user.toString());650    const events = await submitTransactionAsync(sender, tx);651    const result = getGenericResult(events);652653    expect(result.success).to.be.true;654  });655}656657export async function removeFromContractAllowListExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {658  await usingApi(async (api) => {659    const tx = api.tx.unique.removeFromContractAllowList(contractAddress.toString(), user.toString());660    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;661    const result = getGenericResult(events);662663    expect(result.success).to.be.false;664  });665}666667export async function setVariableMetaDataExpectSuccess(sender: IKeyringPair, collectionId: number, itemId: number, data: number[]) {668  await usingApi(async (api) => {669    const tx = api.tx.unique.setVariableMetaData(collectionId, itemId, '0x' + Buffer.from(data).toString('hex'));670    const events = await submitTransactionAsync(sender, tx);671    const result = getGenericResult(events);672673    expect(result.success).to.be.true;674  });675}676677export async function setVariableMetaDataExpectFailure(sender: IKeyringPair, collectionId: number, itemId: number, data: number[]) {678  await usingApi(async (api) => {679    const tx = api.tx.unique.setVariableMetaData(collectionId, itemId, '0x' + Buffer.from(data).toString('hex'));680    await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;681  });682}683684export async function setOffchainSchemaExpectSuccess(sender: IKeyringPair, collectionId: number, data: number[]) {685  await usingApi(async (api) => {686    const tx = api.tx.unique.setOffchainSchema(collectionId, '0x' + Buffer.from(data).toString('hex'));687    const events = await submitTransactionAsync(sender, tx);688    const result = getGenericResult(events);689690    expect(result.success).to.be.true;691  });692}693694export async function setOffchainSchemaExpectFailure(sender: IKeyringPair, collectionId: number, data: number[]) {695  await usingApi(async (api) => {696    const tx = api.tx.unique.setOffchainSchema(collectionId, '0x' + Buffer.from(data).toString('hex'));697    await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;698  });699}700701export interface CreateFungibleData {702  readonly Value: bigint;703}704705export interface CreateReFungibleData { }706export interface CreateNftData { }707708export type CreateItemData = {709  NFT: CreateNftData;710} | {711  Fungible: CreateFungibleData;712} | {713  ReFungible: CreateReFungibleData;714};715716export async function burnItemExpectSuccess(sender: IKeyringPair, collectionId: number, tokenId: number, value = 1) {717  await usingApi(async (api) => {718    const balanceBefore = await getBalance(api, collectionId, normalizeAccountId(sender), tokenId);719    // if burning token by admin - use adminButnItemExpectSuccess720    expect(balanceBefore >= BigInt(value)).to.be.true;721722    const tx = api.tx.unique.burnItem(collectionId, tokenId, value);723    const events = await submitTransactionAsync(sender, tx);724    const result = getGenericResult(events);725    expect(result.success).to.be.true;726727    const balanceAfter = await getBalance(api, collectionId, normalizeAccountId(sender), tokenId);728    expect(balanceAfter + BigInt(value)).to.be.equal(balanceBefore);729  });730}731732export async function733approveExpectSuccess(734  collectionId: number,735  tokenId: number, owner: IKeyringPair, approved: CrossAccountId | string, amount: number | bigint = 1,736) {737  await usingApi(async (api: ApiPromise) => {738    const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);739    const events = await submitTransactionAsync(owner, approveUniqueTx);740    const result = getGenericResult(events);741    expect(result.success).to.be.true;742743    expect(await getAllowance(api, collectionId, owner.address, approved, tokenId)).to.be.equal(BigInt(amount));744  });745}746747export async function adminApproveFromExpectSuccess(748  collectionId: number,749  tokenId: number, admin: IKeyringPair, owner: CrossAccountId | string, approved: CrossAccountId | string, amount: number | bigint = 1,750) {751  await usingApi(async (api: ApiPromise) => {752    const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);753    const events = await submitTransactionAsync(admin, approveUniqueTx);754    const result = getGenericResult(events);755    expect(result.success).to.be.true;756757    expect(await getAllowance(api, collectionId, owner, approved, tokenId)).to.be.equal(BigInt(amount));758  });759}760761export async function762transferFromExpectSuccess(763  collectionId: number,764  tokenId: number,765  accountApproved: IKeyringPair,766  accountFrom: IKeyringPair | CrossAccountId,767  accountTo: IKeyringPair | CrossAccountId,768  value: number | bigint = 1,769  type = 'NFT',770) {771  await usingApi(async (api: ApiPromise) => {772    const to = normalizeAccountId(accountTo);773    let balanceBefore = 0n;774    if (type === 'Fungible') {775      balanceBefore = await getBalance(api, collectionId, to, tokenId);776    }777    const transferFromTx = api.tx.unique.transferFrom(normalizeAccountId(accountFrom), to, collectionId, tokenId, value);778    const events = await submitTransactionAsync(accountApproved, transferFromTx);779    const result = getCreateItemResult(events);780    // tslint:disable-next-line:no-unused-expression781    expect(result.success).to.be.true;782    if (type === 'NFT') {783      expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(to);784    }785    if (type === 'Fungible') {786      const balanceAfter = await getBalance(api, collectionId, to, tokenId);787      expect(balanceAfter - balanceBefore).to.be.equal(BigInt(value));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" */814export async 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 function843scheduleTransferAndWaitExpectSuccess(844  collectionId: number,845  tokenId: number,846  sender: IKeyringPair,847  recipient: IKeyringPair,848  value: number | bigint = 1,849  blockSchedule: number,850) {851  await usingApi(async (api: ApiPromise) => {852    await scheduleTransferExpectSuccess(collectionId, tokenId, sender, recipient, value, blockSchedule);853854    const recipientBalanceBefore = (await api.query.system.account(recipient.address)).data.free.toBigInt();855    console.log(await getFreeBalance(sender));856857    // sleep for n + 1 blocks858    await waitNewBlocks(blockSchedule + 1);859860    const recipientBalanceAfter = (await api.query.system.account(recipient.address)).data.free.toBigInt();861862    expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(recipient.address));863    expect(recipientBalanceAfter).to.be.equal(recipientBalanceBefore);864  });865}866867export async function868scheduleTransferExpectSuccess(869  collectionId: number,870  tokenId: number,871  sender: IKeyringPair,872  recipient: IKeyringPair,873  value: number | bigint = 1,874  blockSchedule: number,875) {876  await usingApi(async (api: ApiPromise) => {877    const blockNumber: number | undefined = await getBlockNumber(api);878    const expectedBlockNumber = blockNumber + blockSchedule;879880    expect(blockNumber).to.be.greaterThan(0);881    const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient.address), collectionId, tokenId, value);882    const scheduleTx = api.tx.scheduler.schedule(expectedBlockNumber, null, 0, transferTx as any);883884    const events = await submitTransactionAsync(sender, scheduleTx);885    expect(getGenericResult(events).success).to.be.true;886887    expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(sender.address));888  });889}890891export async function892scheduleTransferFundsPeriodicExpectSuccess(893  amount: bigint,894  sender: IKeyringPair,895  recipient: IKeyringPair,896  blockSchedule: number,897  period: number,898  repetitions: number,899) {900  await usingApi(async (api: ApiPromise) => {901    const blockNumber: number | undefined = await getBlockNumber(api);902    const expectedBlockNumber = blockNumber + blockSchedule;903904    const balanceBefore = await getFreeBalance(recipient);905    906    expect(blockNumber).to.be.greaterThan(0);907    const transferTx = api.tx.balances.transfer(recipient.address, amount);908    const scheduleTx = api.tx.scheduler.schedule(expectedBlockNumber, [period, repetitions], 0, transferTx as any);909910    const events = await submitTransactionAsync(sender, scheduleTx);911    expect(getGenericResult(events).success).to.be.true;912913    expect(await getFreeBalance(recipient)).to.be.equal(balanceBefore);914  });915}916917918export async function919transferExpectSuccess(920  collectionId: number,921  tokenId: number,922  sender: IKeyringPair,923  recipient: IKeyringPair | CrossAccountId,924  value: number | bigint = 1,925  type = 'NFT',926) {927  await usingApi(async (api: ApiPromise) => {928    const to = normalizeAccountId(recipient);929930    let balanceBefore = 0n;931    if (type === 'Fungible') {932      balanceBefore = await getBalance(api, collectionId, to, tokenId);933    }934    const transferTx = api.tx.unique.transfer(to, collectionId, tokenId, value);935    const events = await submitTransactionAsync(sender, transferTx);936    const result = getTransferResult(events);937    // tslint:disable-next-line:no-unused-expression938    expect(result.success).to.be.true;939    expect(result.collectionId).to.be.equal(collectionId);940    expect(result.itemId).to.be.equal(tokenId);941    expect(result.sender).to.be.deep.equal(normalizeAccountId(sender.address));942    expect(result.recipient).to.be.deep.equal(to);943    expect(result.value).to.be.equal(BigInt(value));944    if (type === 'NFT') {945      expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(to);946    }947    if (type === 'Fungible') {948      const balanceAfter = await getBalance(api, collectionId, to, tokenId);949      expect(balanceAfter - balanceBefore).to.be.equal(BigInt(value));950    }951    if (type === 'ReFungible') {952      expect(await getBalance(api, collectionId, to, tokenId) >= value).to.be.true;953    }954  });955}956957export async function958transferExpectFailure(959  collectionId: number,960  tokenId: number,961  sender: IKeyringPair,962  recipient: IKeyringPair,963  value: number | bigint = 1,964) {965  await usingApi(async (api: ApiPromise) => {966    const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient.address), collectionId, tokenId, value);967    const events = await expect(submitTransactionExpectFailAsync(sender, transferTx)).to.be.rejected;968    const result = getGenericResult(events);969    // if (events && Array.isArray(events)) {970    //   const result = getCreateCollectionResult(events);971    // tslint:disable-next-line:no-unused-expression972    expect(result.success).to.be.false;973    //}974  });975}976977export async function978approveExpectFail(979  collectionId: number,980  tokenId: number, owner: IKeyringPair, approved: IKeyringPair, amount: number | bigint = 1,981) {982  await usingApi(async (api: ApiPromise) => {983    const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved.address), collectionId, tokenId, amount);984    const events = await expect(submitTransactionExpectFailAsync(owner, approveUniqueTx)).to.be.rejected;985    const result = getCreateCollectionResult(events);986    // tslint:disable-next-line:no-unused-expression987    expect(result.success).to.be.false;988  });989}990991export async function getBalance(992  api: ApiPromise,993  collectionId: number,994  owner: string | CrossAccountId,995  token: number,996): Promise<bigint> {997  return (await api.rpc.unique.balance(collectionId, normalizeAccountId(owner), token)).toBigInt();998}999export async function getTokenOwner(1000  api: ApiPromise,1001  collectionId: number,1002  token: number,1003): Promise<CrossAccountId> {1004  return normalizeAccountId((await api.rpc.unique.tokenOwner(collectionId, token)).toJSON() as any);1005}1006export async function isTokenExists(1007  api: ApiPromise,1008  collectionId: number,1009  token: number,1010): Promise<boolean> {1011  return (await api.rpc.unique.tokenExists(collectionId, token)).toJSON();1012}1013export async function getLastTokenId(1014  api: ApiPromise,1015  collectionId: number,1016): Promise<number> {1017  return (await api.rpc.unique.lastTokenId(collectionId)).toJSON();1018}1019export async function getAdminList(1020  api: ApiPromise,1021  collectionId: number,1022): Promise<string[]> {1023  return (await api.rpc.unique.adminlist(collectionId)).toHuman() as any;1024}1025export async function getVariableMetadata(1026  api: ApiPromise,1027  collectionId: number,1028  tokenId: number,1029): Promise<number[]> {1030  return [...(await api.rpc.unique.variableMetadata(collectionId, tokenId))];1031}1032export async function getConstMetadata(1033  api: ApiPromise,1034  collectionId: number,1035  tokenId: number,1036): Promise<number[]> {1037  return [...(await api.rpc.unique.constMetadata(collectionId, tokenId))];1038}10391040export async function createFungibleItemExpectSuccess(1041  sender: IKeyringPair,1042  collectionId: number,1043  data: CreateFungibleData,1044  owner: CrossAccountId | string = sender.address,1045) {1046  return await usingApi(async (api) => {1047    const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), {Fungible: data});10481049    const events = await submitTransactionAsync(sender, tx);1050    const result = getCreateItemResult(events);10511052    expect(result.success).to.be.true;1053    return result.itemId;1054  });1055}10561057export async function createItemExpectSuccess(sender: IKeyringPair, collectionId: number, createMode: string, owner: CrossAccountId | string = sender.address) {1058  let newItemId = 0;1059  await usingApi(async (api) => {1060    const to = normalizeAccountId(owner);1061    const itemCountBefore = await getLastTokenId(api, collectionId);1062    const itemBalanceBefore = await getBalance(api, collectionId, to, newItemId);10631064    let tx;1065    if (createMode === 'Fungible') {1066      const createData = {fungible: {value: 10}};1067      tx = api.tx.unique.createItem(collectionId, to, createData as any);1068    } else if (createMode === 'ReFungible') {1069      const createData = {refungible: {const_data: [], variable_data: [], pieces: 100}};1070      tx = api.tx.unique.createItem(collectionId, to, createData as any);1071    } else {1072      const createData = {nft: {const_data: [], variable_data: []}};1073      tx = api.tx.unique.createItem(collectionId, to, createData as any);1074    }10751076    const events = await submitTransactionAsync(sender, tx);1077    const result = getCreateItemResult(events);10781079    const itemCountAfter = await getLastTokenId(api, collectionId);1080    const itemBalanceAfter = await getBalance(api, collectionId, to, newItemId);10811082    // What to expect1083    // tslint:disable-next-line:no-unused-expression1084    expect(result.success).to.be.true;1085    if (createMode === 'Fungible') {1086      expect(itemBalanceAfter - itemBalanceBefore).to.be.equal(10n);1087    } else {1088      expect(itemCountAfter).to.be.equal(itemCountBefore + 1);1089    }1090    expect(collectionId).to.be.equal(result.collectionId);1091    expect(itemCountAfter.toString()).to.be.equal(result.itemId.toString());1092    expect(to).to.be.deep.equal(result.recipient);1093    newItemId = result.itemId;1094  });1095  return newItemId;1096}10971098export async function createItemExpectFailure(sender: IKeyringPair, collectionId: number, createMode: string, owner: string = sender.address) {1099  await usingApi(async (api) => {1100    const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), createMode);11011102    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1103    const result = getCreateItemResult(events);11041105    expect(result.success).to.be.false;1106  });1107}11081109export async function setPublicAccessModeExpectSuccess(1110  sender: IKeyringPair, collectionId: number,1111  accessMode: 'Normal' | 'AllowList',1112) {1113  await usingApi(async (api) => {11141115    // Run the transaction1116    const tx = api.tx.unique.setPublicAccessMode(collectionId, accessMode);1117    const events = await submitTransactionAsync(sender, tx);1118    const result = getGenericResult(events);11191120    // Get the collection1121    const collection = await queryCollectionExpectSuccess(api, collectionId);11221123    // What to expect1124    // tslint:disable-next-line:no-unused-expression1125    expect(result.success).to.be.true;1126    expect(collection.access.toHuman()).to.be.equal(accessMode);1127  });1128}11291130export async function setPublicAccessModeExpectFail(1131  sender: IKeyringPair, collectionId: number,1132  accessMode: 'Normal' | 'AllowList',1133) {1134  await usingApi(async (api) => {11351136    // Run the transaction1137    const tx = api.tx.unique.setPublicAccessMode(collectionId, accessMode);1138    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1139    const result = getGenericResult(events);11401141    // What to expect1142    // tslint:disable-next-line:no-unused-expression1143    expect(result.success).to.be.false;1144  });1145}11461147export async function enableAllowListExpectSuccess(sender: IKeyringPair, collectionId: number) {1148  await setPublicAccessModeExpectSuccess(sender, collectionId, 'AllowList');1149}11501151export async function enableAllowListExpectFail(sender: IKeyringPair, collectionId: number) {1152  await setPublicAccessModeExpectFail(sender, collectionId, 'AllowList');1153}11541155export async function disableAllowListExpectSuccess(sender: IKeyringPair, collectionId: number) {1156  await setPublicAccessModeExpectSuccess(sender, collectionId, 'Normal');1157}11581159export async function setMintPermissionExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {1160  await usingApi(async (api) => {11611162    // Run the transaction1163    const tx = api.tx.unique.setMintPermission(collectionId, enabled);1164    const events = await submitTransactionAsync(sender, tx);1165    const result = getGenericResult(events);1166    expect(result.success).to.be.true;11671168    // Get the collection1169    const collection = await queryCollectionExpectSuccess(api, collectionId);11701171    expect(collection.mintMode.toHuman()).to.be.equal(enabled);1172  });1173}11741175export async function enablePublicMintingExpectSuccess(sender: IKeyringPair, collectionId: number) {1176  await setMintPermissionExpectSuccess(sender, collectionId, true);1177}11781179export async function setMintPermissionExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {1180  await usingApi(async (api) => {1181    // Run the transaction1182    const tx = api.tx.unique.setMintPermission(collectionId, enabled);1183    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1184    const result = getCreateCollectionResult(events);1185    // tslint:disable-next-line:no-unused-expression1186    expect(result.success).to.be.false;1187  });1188}11891190export async function setChainLimitsExpectFailure(sender: IKeyringPair, limits: IChainLimits) {1191  await usingApi(async (api) => {1192    // Run the transaction1193    const tx = api.tx.unique.setChainLimits(limits);1194    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1195    const result = getCreateCollectionResult(events);1196    // tslint:disable-next-line:no-unused-expression1197    expect(result.success).to.be.false;1198  });1199}12001201export async function isAllowlisted(api: ApiPromise, collectionId: number, address: string | CrossAccountId) {1202  return (await api.rpc.unique.allowed(collectionId, normalizeAccountId(address))).toJSON();1203}12041205export async function addToAllowListExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId | CrossAccountId) {1206  await usingApi(async (api) => {1207    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.false;12081209    // Run the transaction1210    const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1211    const events = await submitTransactionAsync(sender, tx);1212    const result = getGenericResult(events);1213    expect(result.success).to.be.true;12141215    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;1216  });1217}12181219export async function addToAllowListAgainExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId) {1220  await usingApi(async (api) => {12211222    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;12231224    // Run the transaction1225    const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1226    const events = await submitTransactionAsync(sender, tx);1227    const result = getGenericResult(events);1228    expect(result.success).to.be.true;12291230    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;1231  });1232}12331234export async function addToAllowListExpectFail(sender: IKeyringPair, collectionId: number, address: string | AccountId) {1235  await usingApi(async (api) => {12361237    // Run the transaction1238    const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1239    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1240    const result = getGenericResult(events);12411242    // What to expect1243    // tslint:disable-next-line:no-unused-expression1244    expect(result.success).to.be.false;1245  });1246}12471248export async function removeFromAllowListExpectSuccess(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1249  await usingApi(async (api) => {1250    // Run the transaction1251    const tx = api.tx.unique.removeFromAllowList(collectionId, normalizeAccountId(address));1252    const events = await submitTransactionAsync(sender, tx);1253    const result = getGenericResult(events);12541255    // What to expect1256    // tslint:disable-next-line:no-unused-expression1257    expect(result.success).to.be.true;1258  });1259}12601261export async function removeFromAllowListExpectFailure(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1262  await usingApi(async (api) => {1263    // Run the transaction1264    const tx = api.tx.unique.removeFromAllowList(collectionId, normalizeAccountId(address));1265    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1266    const result = getGenericResult(events);12671268    // What to expect1269    // tslint:disable-next-line:no-unused-expression1270    expect(result.success).to.be.false;1271  });1272}12731274export const getDetailedCollectionInfo = async (api: ApiPromise, collectionId: number)1275  : Promise<UpDataStructsCollection | null> => {1276  return (await api.rpc.unique.collectionById(collectionId)).unwrapOr(null);1277};12781279export const getCreatedCollectionCount = async (api: ApiPromise): Promise<number> => {1280  // set global object - collectionsCount1281  return (await api.rpc.unique.collectionStats()).created.toNumber();1282};12831284export async function queryCollectionExpectSuccess(api: ApiPromise, collectionId: number): Promise<UpDataStructsCollection> {1285  return (await api.rpc.unique.collectionById(collectionId)).unwrap();1286}12871288export async function waitNewBlocks(blocksCount = 1): Promise<void> {1289  await usingApi(async (api) => {1290    const promise = new Promise<void>(async (resolve) => {1291      const unsubscribe = await api.rpc.chain.subscribeNewHeads(() => {1292        if (blocksCount > 0) {1293          blocksCount--;1294        } else {1295          unsubscribe();1296          resolve();1297        }1298      });1299    });1300    return promise;1301  });1302}