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

difftreelog

CORE-215 Fix helpers: check same sender and recepient

Trubnikov Sergey2022-03-02parent: #980a35f.patch.diff
in: master

2 files changed

modifiedtests/src/transfer.test.tsdiffbeforeafterboth
--- a/tests/src/transfer.test.ts
+++ b/tests/src/transfer.test.ts
@@ -325,7 +325,7 @@
     expect(balanceAliceBefore).to.be.eq(balanceAliceAfter);
   });
 
-  itWeb3.only('Transfers to self. In case of inside substrate-evm', async ({api}) => {
+  itWeb3('Transfers to self. In case of inside substrate-evm', async ({api}) => {
     const collectionId = await createCollectionExpectSuccess({mode: {type: 'Fungible', decimalPoints: 0}});
     const alice = privateKey('//Alice');
     const tokenId = await createItemExpectSuccess(alice, collectionId, 'Fungible', {Substrate: alice.address});
modifiedtests/src/util/helpers.tsdiffbeforeafterboth
before · tests/src/util/helpers.ts
1//2// This file is subject to the terms and conditions defined in3// file 'LICENSE', which is part of this source code package.4//56import '../interfaces/augment-api-rpc';7import '../interfaces/augment-api-query';8import {ApiPromise, Keyring} from '@polkadot/api';9import type {AccountId, EventRecord} from '@polkadot/types/interfaces';10import {IKeyringPair} from '@polkadot/types/types';11import {evmToAddress} from '@polkadot/util-crypto';12import BN from 'bn.js';13import chai from 'chai';14import chaiAsPromised from 'chai-as-promised';15import {alicesPublicKey} from '../accounts';16import privateKey from '../substrate/privateKey';17import {default as usingApi, submitTransactionAsync, submitTransactionExpectFailAsync} from '../substrate/substrate-api';18import {hexToStr, strToUTF16, utf16ToStr} from './util';19import {UpDataStructsCollection} from '@polkadot/types/lookup';2021chai.use(chaiAsPromised);22const expect = chai.expect;2324export type CrossAccountId = {25  Substrate: string,26} | {27  Ethereum: string,28};29export function normalizeAccountId(input: string | AccountId | CrossAccountId | IKeyringPair): CrossAccountId {30  if (typeof input === 'string') {31    if (input.length === 48 || input.length === 47) {32      return {Substrate: input};33    } else if (input.length === 42 && input.startsWith('0x')) {34      return {Ethereum: input.toLowerCase()};35    } else if (input.length === 40 && !input.startsWith('0x')) {36      return {Ethereum: '0x' + input.toLowerCase()};37    } else {38      throw new Error(`Unknown address format: "${input}"`);39    }40  }41  if ('address' in input) {42    return {Substrate: input.address};43  }44  if ('Ethereum' in input) {45    return {46      Ethereum: input.Ethereum.toLowerCase(),47    };48  } else if ('ethereum' in input) {49    return {50      Ethereum: (input as any).ethereum.toLowerCase(),51    };52  } else if ('Substrate' in input) {53    return input;54  } else if ('substrate' in input) {55    return {56      Substrate: (input as any).substrate,57    };58  }5960  // AccountId61  return {Substrate: input.toString()};62}63export function toSubstrateAddress(input: string | CrossAccountId | IKeyringPair): string {64  input = normalizeAccountId(input);65  if ('Substrate' in input) {66    return input.Substrate;67  } else {68    return evmToAddress(input.Ethereum);69  }70}7172export const U128_MAX = (1n << 128n) - 1n;7374const MICROUNIQUE = 1_000_000_000_000n;75const MILLIUNIQUE = 1_000n * MICROUNIQUE;76const CENTIUNIQUE = 10n * MILLIUNIQUE;77export const UNIQUE = 100n * CENTIUNIQUE;7879type GenericResult = {80  success: boolean,81};8283interface CreateCollectionResult {84  success: boolean;85  collectionId: number;86}8788interface CreateItemResult {89  success: boolean;90  collectionId: number;91  itemId: number;92  recipient?: CrossAccountId;93}9495interface TransferResult {96  success: boolean;97  collectionId: number;98  itemId: number;99  sender?: CrossAccountId;100  recipient?: CrossAccountId;101  value: bigint;102}103104interface IReFungibleOwner {105  fraction: BN;106  owner: number[];107}108109interface IGetMessage {110  checkMsgUnqMethod: string;111  checkMsgTrsMethod: string;112  checkMsgSysMethod: string;113}114115export interface IFungibleTokenDataType {116  value: number;117}118119export interface IChainLimits {120  collectionNumbersLimit: number;121  accountTokenOwnershipLimit: number;122  collectionsAdminsLimit: number;123  customDataLimit: number;124  nftSponsorTransferTimeout: number;125  fungibleSponsorTransferTimeout: number;126  refungibleSponsorTransferTimeout: number;127  offchainSchemaLimit: number;128  variableOnChainSchemaLimit: number;129  constOnChainSchemaLimit: number;130}131132export interface IReFungibleTokenDataType {133  owner: IReFungibleOwner[];134  constData: number[];135  variableData: number[];136}137138export function uniqueEventMessage(events: EventRecord[]): IGetMessage {139  let checkMsgUnqMethod = '';140  let checkMsgTrsMethod = '';141  let checkMsgSysMethod = '';142  events.forEach(({event: {method, section}}) => {143    if (section === 'common') {144      checkMsgUnqMethod = method;145    } else if (section === 'treasury') {146      checkMsgTrsMethod = method;147    } else if (section === 'system') {148      checkMsgSysMethod = method;149    } else { return null; }150  });151  const result: IGetMessage = {152    checkMsgUnqMethod,153    checkMsgTrsMethod,154    checkMsgSysMethod,155  };156  return result;157}158159export function getGenericResult(events: EventRecord[]): GenericResult {160  const result: GenericResult = {161    success: false,162  };163  events.forEach(({event: {method}}) => {164    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);165    if (method === 'ExtrinsicSuccess') {166      result.success = true;167    }168  });169  return result;170}171172173174export function getCreateCollectionResult(events: EventRecord[]): CreateCollectionResult {175  let success = false;176  let collectionId = 0;177  events.forEach(({event: {data, method, section}}) => {178    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);179    if (method == 'ExtrinsicSuccess') {180      success = true;181    } else if ((section == 'common') && (method == 'CollectionCreated')) {182      collectionId = parseInt(data[0].toString(), 10);183    }184  });185  const result: CreateCollectionResult = {186    success,187    collectionId,188  };189  return result;190}191192export function getCreateItemResult(events: EventRecord[]): CreateItemResult {193  let success = false;194  let collectionId = 0;195  let itemId = 0;196  let recipient;197  events.forEach(({event: {data, method, section}}) => {198    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);199    if (method == 'ExtrinsicSuccess') {200      success = true;201    } else if ((section == 'common') && (method == 'ItemCreated')) {202      collectionId = parseInt(data[0].toString(), 10);203      itemId = parseInt(data[1].toString(), 10);204      recipient = normalizeAccountId(data[2].toJSON() as any);205    }206  });207  const result: CreateItemResult = {208    success,209    collectionId,210    itemId,211    recipient,212  };213  return result;214}215216export function getTransferResult(events: EventRecord[]): TransferResult {217  const result: TransferResult = {218    success: false,219    collectionId: 0,220    itemId: 0,221    value: 0n,222  };223224  events.forEach(({event: {data, method, section}}) => {225    if (method === 'ExtrinsicSuccess') {226      result.success = true;227    } else if (section === 'common' && method === 'Transfer') {228      result.collectionId = +data[0].toString();229      result.itemId = +data[1].toString();230      result.sender = normalizeAccountId(data[2].toJSON() as any);231      result.recipient = normalizeAccountId(data[3].toJSON() as any);232      result.value = BigInt(data[4].toString());233    }234  });235236  return result;237}238239interface Nft {240  type: 'NFT';241}242243interface Fungible {244  type: 'Fungible';245  decimalPoints: number;246}247248interface ReFungible {249  type: 'ReFungible';250}251252type CollectionMode = Nft | Fungible | ReFungible;253254export type CreateCollectionParams = {255  mode: CollectionMode,256  name: string,257  description: string,258  tokenPrefix: string,259};260261const defaultCreateCollectionParams: CreateCollectionParams = {262  description: 'description',263  mode: {type: 'NFT'},264  name: 'name',265  tokenPrefix: 'prefix',266};267268export async function createCollectionExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {269  const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};270271  let collectionId = 0;272  await usingApi(async (api) => {273    // Get number of collections before the transaction274    const collectionCountBefore = await getCreatedCollectionCount(api);275276    // Run the CreateCollection transaction277    const alicePrivateKey = privateKey('//Alice');278279    let modeprm = {};280    if (mode.type === 'NFT') {281      modeprm = {nft: null};282    } else if (mode.type === 'Fungible') {283      modeprm = {fungible: mode.decimalPoints};284    } else if (mode.type === 'ReFungible') {285      modeprm = {refungible: null};286    }287288    const tx = api.tx.unique.createCollectionEx({name: strToUTF16(name), description: strToUTF16(description), tokenPrefix: strToUTF16(tokenPrefix), mode: modeprm as any});289    const events = await submitTransactionAsync(alicePrivateKey, tx);290    const result = getCreateCollectionResult(events);291292    // Get number of collections after the transaction293    const collectionCountAfter = await getCreatedCollectionCount(api);294295    // Get the collection296    const collection = await queryCollectionExpectSuccess(api, result.collectionId);297298    // What to expect299    // tslint:disable-next-line:no-unused-expression300    expect(result.success).to.be.true;301    expect(result.collectionId).to.be.equal(collectionCountAfter);302    // tslint:disable-next-line:no-unused-expression303    expect(collection).to.be.not.null;304    expect(collectionCountAfter).to.be.equal(collectionCountBefore + 1, 'Error: NFT collection NOT created.');305    expect(collection.owner.toString()).to.be.equal(toSubstrateAddress(alicesPublicKey));306    expect(utf16ToStr(collection.name.toJSON() as any)).to.be.equal(name);307    expect(utf16ToStr(collection.description.toJSON() as any)).to.be.equal(description);308    expect(hexToStr(collection.tokenPrefix.toJSON())).to.be.equal(tokenPrefix);309310    collectionId = result.collectionId;311  });312313  return collectionId;314}315316export async function createCollectionExpectFailure(params: Partial<CreateCollectionParams> = {}) {317  const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};318319  let modeprm = {};320  if (mode.type === 'NFT') {321    modeprm = {nft: null};322  } else if (mode.type === 'Fungible') {323    modeprm = {fungible: mode.decimalPoints};324  } else if (mode.type === 'ReFungible') {325    modeprm = {refungible: null};326  }327328  await usingApi(async (api) => {329    // Get number of collections before the transaction330    const collectionCountBefore = await getCreatedCollectionCount(api);331332    // Run the CreateCollection transaction333    const alicePrivateKey = privateKey('//Alice');334    const tx = api.tx.unique.createCollectionEx({name: strToUTF16(name), description: strToUTF16(description), tokenPrefix: strToUTF16(tokenPrefix), mode: modeprm as any});335    const events = await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;336    const result = getCreateCollectionResult(events);337338    // Get number of collections after the transaction339    const collectionCountAfter = await getCreatedCollectionCount(api);340341    // What to expect342    // tslint:disable-next-line:no-unused-expression343    expect(result.success).to.be.false;344    expect(collectionCountAfter).to.be.equal(collectionCountBefore, 'Error: Collection with incorrect data created.');345  });346}347348export async function findUnusedAddress(api: ApiPromise, seedAddition = ''): Promise<IKeyringPair> {349  let bal = 0n;350  let unused;351  do {352    const randomSeed = 'seed' + Math.floor(Math.random() * Math.floor(10000)) + seedAddition;353    const keyring = new Keyring({type: 'sr25519'});354    unused = keyring.addFromUri(`//${randomSeed}`);355    bal = (await api.query.system.account(unused.address)).data.free.toBigInt();356  } while (bal !== 0n);357  return unused;358}359360export async function getAllowance(api: ApiPromise, collectionId: number, owner: CrossAccountId | string, approved: CrossAccountId | string, tokenId: number) {361  return (await api.rpc.unique.allowance(collectionId, normalizeAccountId(owner), normalizeAccountId(approved), tokenId)).toBigInt();362}363364export function findUnusedAddresses(api: ApiPromise, amount: number): Promise<IKeyringPair[]> {365  return Promise.all(new Array(amount).fill(null).map(() => findUnusedAddress(api, '_' + Date.now())));366}367368export async function findNotExistingCollection(api: ApiPromise): Promise<number> {369  const totalNumber = await getCreatedCollectionCount(api);370  const newCollection: number = totalNumber + 1;371  return newCollection;372}373374function getDestroyResult(events: EventRecord[]): boolean {375  let success = false;376  events.forEach(({event: {method}}) => {377    if (method == 'ExtrinsicSuccess') {378      success = true;379    }380  });381  return success;382}383384export async function destroyCollectionExpectFailure(collectionId: number, senderSeed = '//Alice') {385  await usingApi(async (api) => {386    // Run the DestroyCollection transaction387    const alicePrivateKey = privateKey(senderSeed);388    const tx = api.tx.unique.destroyCollection(collectionId);389    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;390  });391}392393export async function destroyCollectionExpectSuccess(collectionId: number, senderSeed = '//Alice') {394  await usingApi(async (api) => {395    // Run the DestroyCollection transaction396    const alicePrivateKey = privateKey(senderSeed);397    const tx = api.tx.unique.destroyCollection(collectionId);398    const events = await submitTransactionAsync(alicePrivateKey, tx);399    const result = getDestroyResult(events);400    expect(result).to.be.true;401402    // What to expect403    expect(await getDetailedCollectionInfo(api, collectionId)).to.be.null;404  });405}406407export async function setCollectionLimitsExpectSuccess(sender: IKeyringPair, collectionId: number, limits: any) {408  await usingApi(async (api) => {409    const tx = api.tx.unique.setCollectionLimits(collectionId, limits);410    const events = await submitTransactionAsync(sender, tx);411    const result = getGenericResult(events);412413    expect(result.success).to.be.true;414  });415}416417export async function setCollectionLimitsExpectFailure(sender: IKeyringPair, collectionId: number, limits: any) {418  await usingApi(async (api) => {419    const tx = api.tx.unique.setCollectionLimits(collectionId, limits);420    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;421    const result = getGenericResult(events);422423    expect(result.success).to.be.false;424  });425}426427export async function setCollectionSponsorExpectSuccess(collectionId: number, sponsor: string, sender = '//Alice') {428  await usingApi(async (api) => {429430    // Run the transaction431    const senderPrivateKey = privateKey(sender);432    const tx = api.tx.unique.setCollectionSponsor(collectionId, sponsor);433    const events = await submitTransactionAsync(senderPrivateKey, tx);434    const result = getGenericResult(events);435436    // Get the collection437    const collection = await queryCollectionExpectSuccess(api, collectionId);438439    // What to expect440    expect(result.success).to.be.true;441    expect(collection.sponsorship.toJSON()).to.deep.equal({442      unconfirmed: sponsor,443    });444  });445}446447export async function removeCollectionSponsorExpectSuccess(collectionId: number, sender = '//Alice') {448  await usingApi(async (api) => {449450    // Run the transaction451    const alicePrivateKey = privateKey(sender);452    const tx = api.tx.unique.removeCollectionSponsor(collectionId);453    const events = await submitTransactionAsync(alicePrivateKey, tx);454    const result = getGenericResult(events);455456    // Get the collection457    const collection = await queryCollectionExpectSuccess(api, collectionId);458459    // What to expect460    expect(result.success).to.be.true;461    expect(collection.sponsorship.toJSON()).to.be.deep.equal({disabled: null});462  });463}464465export async function removeCollectionSponsorExpectFailure(collectionId: number, senderSeed = '//Alice') {466  await usingApi(async (api) => {467468    // Run the transaction469    const alicePrivateKey = privateKey(senderSeed);470    const tx = api.tx.unique.removeCollectionSponsor(collectionId);471    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;472  });473}474475export async function setCollectionSponsorExpectFailure(collectionId: number, sponsor: string, senderSeed = '//Alice') {476  await usingApi(async (api) => {477478    // Run the transaction479    const alicePrivateKey = privateKey(senderSeed);480    const tx = api.tx.unique.setCollectionSponsor(collectionId, sponsor);481    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;482  });483}484485export async function confirmSponsorshipExpectSuccess(collectionId: number, senderSeed = '//Alice') {486  await usingApi(async (api) => {487488    // Run the transaction489    const sender = privateKey(senderSeed);490    const tx = api.tx.unique.confirmSponsorship(collectionId);491    const events = await submitTransactionAsync(sender, tx);492    const result = getGenericResult(events);493494    // Get the collection495    const collection = await queryCollectionExpectSuccess(api, collectionId);496497    // What to expect498    expect(result.success).to.be.true;499    expect(collection.sponsorship.toJSON()).to.be.deep.equal({500      confirmed: sender.address,501    });502  });503}504505506export async function confirmSponsorshipExpectFailure(collectionId: number, senderSeed = '//Alice') {507  await usingApi(async (api) => {508509    // Run the transaction510    const sender = privateKey(senderSeed);511    const tx = api.tx.unique.confirmSponsorship(collectionId);512    await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;513  });514}515516export async function setMetadataUpdatePermissionFlagExpectSuccess(sender: IKeyringPair, collectionId: number, flag: string) {517518  await usingApi(async (api) => {519    const tx = api.tx.unique.setMetaUpdatePermissionFlag(collectionId, flag as any);520    const events = await submitTransactionAsync(sender, tx);521    const result = getGenericResult(events);522523    expect(result.success).to.be.true;524  });525}526527export async function setMetadataUpdatePermissionFlagExpectFailure(sender: IKeyringPair, collectionId: number, flag: string) {528529  await usingApi(async (api) => {530    const tx = api.tx.unique.setMetaUpdatePermissionFlag(collectionId, flag as any);531    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;532    const result = getGenericResult(events);533534    expect(result.success).to.be.false;535  });536}537538export async function enableContractSponsoringExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {539  await usingApi(async (api) => {540    const tx = api.tx.unique.enableContractSponsoring(contractAddress, enable);541    const events = await submitTransactionAsync(sender, tx);542    const result = getGenericResult(events);543544    expect(result.success).to.be.true;545  });546}547548export async function enableContractSponsoringExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {549  await usingApi(async (api) => {550    const tx = api.tx.unique.enableContractSponsoring(contractAddress, enable);551    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;552    const result = getGenericResult(events);553554    expect(result.success).to.be.false;555  });556}557558export async function setTransferFlagExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {559560  await usingApi(async (api) => {561562    const tx = api.tx.unique.setTransfersEnabledFlag(collectionId, enabled);563    const events = await submitTransactionAsync(sender, tx);564    const result = getGenericResult(events);565566    expect(result.success).to.be.true;567  });568}569570export async function setTransferFlagExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {571572  await usingApi(async (api) => {573574    const tx = api.tx.unique.setTransfersEnabledFlag(collectionId, enabled);575    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;576    const result = getGenericResult(events);577578    expect(result.success).to.be.false;579  });580}581582export async function setContractSponsoringRateLimitExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {583  await usingApi(async (api) => {584    const tx = api.tx.unique.setContractSponsoringRateLimit(contractAddress, rateLimit);585    const events = await submitTransactionAsync(sender, tx);586    const result = getGenericResult(events);587588    expect(result.success).to.be.true;589  });590}591592export async function setContractSponsoringRateLimitExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {593  await usingApi(async (api) => {594    const tx = api.tx.unique.setContractSponsoringRateLimit(contractAddress, rateLimit);595    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;596    const result = getGenericResult(events);597598    expect(result.success).to.be.false;599  });600}601602export async function toggleContractAllowlistExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, value = true) {603  await usingApi(async (api) => {604    const tx = api.tx.unique.toggleContractAllowList(contractAddress, value);605    const events = await submitTransactionAsync(sender, tx);606    const result = getGenericResult(events);607608    expect(result.success).to.be.true;609  });610}611612export async function isAllowlistedInContract(contractAddress: AccountId | string, user: string) {613  let allowlisted = false;614  await usingApi(async (api) => {615    allowlisted = (await api.query.unique.contractAllowList(contractAddress, user)).toJSON() as boolean;616  });617  return allowlisted;618}619620export async function addToContractAllowListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {621  await usingApi(async (api) => {622    const tx = api.tx.unique.addToContractAllowList(contractAddress.toString(), user.toString());623    const events = await submitTransactionAsync(sender, tx);624    const result = getGenericResult(events);625626    expect(result.success).to.be.true;627  });628}629630export async function removeFromContractAllowListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {631  await usingApi(async (api) => {632    const tx = api.tx.unique.removeFromContractAllowList(contractAddress.toString(), user.toString());633    const events = await submitTransactionAsync(sender, tx);634    const result = getGenericResult(events);635636    expect(result.success).to.be.true;637  });638}639640export async function removeFromContractAllowListExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {641  await usingApi(async (api) => {642    const tx = api.tx.unique.removeFromContractAllowList(contractAddress.toString(), user.toString());643    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;644    const result = getGenericResult(events);645646    expect(result.success).to.be.false;647  });648}649650export async function setVariableMetaDataExpectSuccess(sender: IKeyringPair, collectionId: number, itemId: number, data: number[]) {651  await usingApi(async (api) => {652    const tx = api.tx.unique.setVariableMetaData(collectionId, itemId, '0x' + Buffer.from(data).toString('hex'));653    const events = await submitTransactionAsync(sender, tx);654    const result = getGenericResult(events);655656    expect(result.success).to.be.true;657  });658}659660export async function setVariableMetaDataExpectFailure(sender: IKeyringPair, collectionId: number, itemId: number, data: number[]) {661  await usingApi(async (api) => {662    const tx = api.tx.unique.setVariableMetaData(collectionId, itemId, '0x' + Buffer.from(data).toString('hex'));663    await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;664  });665}666667export async function setOffchainSchemaExpectSuccess(sender: IKeyringPair, collectionId: number, data: number[]) {668  await usingApi(async (api) => {669    const tx = api.tx.unique.setOffchainSchema(collectionId, '0x' + Buffer.from(data).toString('hex'));670    const events = await submitTransactionAsync(sender, tx);671    const result = getGenericResult(events);672673    expect(result.success).to.be.true;674  });675}676677export async function setOffchainSchemaExpectFailure(sender: IKeyringPair, collectionId: number, data: number[]) {678  await usingApi(async (api) => {679    const tx = api.tx.unique.setOffchainSchema(collectionId, '0x' + Buffer.from(data).toString('hex'));680    await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;681  });682}683684export interface CreateFungibleData {685  readonly Value: bigint;686}687688export interface CreateReFungibleData { }689export interface CreateNftData { }690691export type CreateItemData = {692  NFT: CreateNftData;693} | {694  Fungible: CreateFungibleData;695} | {696  ReFungible: CreateReFungibleData;697};698699export async function burnItemExpectSuccess(sender: IKeyringPair, collectionId: number, tokenId: number, value = 1) {700  await usingApi(async (api) => {701    const balanceBefore = await getBalance(api, collectionId, normalizeAccountId(sender), tokenId);702    // if burning token by admin - use adminButnItemExpectSuccess703    expect(balanceBefore >= BigInt(value)).to.be.true;704705    const tx = api.tx.unique.burnItem(collectionId, tokenId, value);706    const events = await submitTransactionAsync(sender, tx);707    const result = getGenericResult(events);708    expect(result.success).to.be.true;709710    const balanceAfter = await getBalance(api, collectionId, normalizeAccountId(sender), tokenId);711    expect(balanceAfter + BigInt(value)).to.be.equal(balanceBefore);712  });713}714715export async function716approveExpectSuccess(717  collectionId: number,718  tokenId: number, owner: IKeyringPair, approved: CrossAccountId | string, amount: number | bigint = 1,719) {720  await usingApi(async (api: ApiPromise) => {721    const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);722    const events = await submitTransactionAsync(owner, approveUniqueTx);723    const result = getGenericResult(events);724    expect(result.success).to.be.true;725726    expect(await getAllowance(api, collectionId, owner.address, approved, tokenId)).to.be.equal(BigInt(amount));727  });728}729730export async function adminApproveFromExpectSuccess(731  collectionId: number,732  tokenId: number, admin: IKeyringPair, owner: CrossAccountId | string, approved: CrossAccountId | string, amount: number | bigint = 1,733) {734  await usingApi(async (api: ApiPromise) => {735    const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);736    const events = await submitTransactionAsync(admin, approveUniqueTx);737    const result = getGenericResult(events);738    expect(result.success).to.be.true;739740    expect(await getAllowance(api, collectionId, owner, approved, tokenId)).to.be.equal(BigInt(amount));741  });742}743744export async function745transferFromExpectSuccess(746  collectionId: number,747  tokenId: number,748  accountApproved: IKeyringPair,749  accountFrom: IKeyringPair | CrossAccountId,750  accountTo: IKeyringPair | CrossAccountId,751  value: number | bigint = 1,752  type = 'NFT',753) {754  await usingApi(async (api: ApiPromise) => {755    const to = normalizeAccountId(accountTo);756    let balanceBefore = 0n;757    if (type === 'Fungible') {758      balanceBefore = await getBalance(api, collectionId, to, tokenId);759    }760    const transferFromTx = api.tx.unique.transferFrom(normalizeAccountId(accountFrom), to, collectionId, tokenId, value);761    const events = await submitTransactionAsync(accountApproved, transferFromTx);762    const result = getCreateItemResult(events);763    // tslint:disable-next-line:no-unused-expression764    expect(result.success).to.be.true;765    if (type === 'NFT') {766      expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(to);767    }768    if (type === 'Fungible') {769      const balanceAfter = await getBalance(api, collectionId, to, tokenId);770      expect(balanceAfter - balanceBefore).to.be.equal(BigInt(value));771    }772    if (type === 'ReFungible') {773      expect(await getBalance(api, collectionId, to, tokenId)).to.be.equal(BigInt(value));774    }775  });776}777778export async function779transferFromExpectFail(780  collectionId: number,781  tokenId: number,782  accountApproved: IKeyringPair,783  accountFrom: IKeyringPair,784  accountTo: IKeyringPair,785  value: number | bigint = 1,786) {787  await usingApi(async (api: ApiPromise) => {788    const transferFromTx = api.tx.unique.transferFrom(normalizeAccountId(accountFrom.address), normalizeAccountId(accountTo.address), collectionId, tokenId, value);789    const events = await expect(submitTransactionExpectFailAsync(accountApproved, transferFromTx)).to.be.rejected;790    const result = getCreateCollectionResult(events);791    // tslint:disable-next-line:no-unused-expression792    expect(result.success).to.be.false;793  });794}795796/* eslint no-async-promise-executor: "off" */797async function getBlockNumber(api: ApiPromise): Promise<number> {798  return new Promise<number>(async (resolve) => {799    const unsubscribe = await api.rpc.chain.subscribeNewHeads((head) => {800      unsubscribe();801      resolve(head.number.toNumber());802    });803  });804}805806export async function addCollectionAdminExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | CrossAccountId) {807  await usingApi(async (api) => {808    const changeAdminTx = api.tx.unique.addCollectionAdmin(collectionId, normalizeAccountId(address));809    const events = await submitTransactionAsync(sender, changeAdminTx);810    const result = getCreateCollectionResult(events);811    expect(result.success).to.be.true;812  });813}814815export async function816getFreeBalance(account: IKeyringPair): Promise<bigint> {817  let balance = 0n;818  await usingApi(async (api) => {819    balance = BigInt((await api.query.system.account(account.address)).data.free.toString());820  });821822  return balance;823}824825export async function826scheduleTransferExpectSuccess(827  collectionId: number,828  tokenId: number,829  sender: IKeyringPair,830  recipient: IKeyringPair,831  value: number | bigint = 1,832  blockSchedule: number,833) {834  await usingApi(async (api: ApiPromise) => {835    const blockNumber: number | undefined = await getBlockNumber(api);836    const expectedBlockNumber = blockNumber + blockSchedule;837838    expect(blockNumber).to.be.greaterThan(0);839    const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient.address), collectionId, tokenId, value);840    const scheduleTx = api.tx.scheduler.schedule(expectedBlockNumber, null, 0, transferTx as any);841842    await submitTransactionAsync(sender, scheduleTx);843844    const recipientBalanceBefore = (await api.query.system.account(recipient.address)).data.free.toBigInt();845846    expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(sender.address));847848    // sleep for 4 blocks849    await waitNewBlocks(blockSchedule + 1);850851    const recipientBalanceAfter = (await api.query.system.account(recipient.address)).data.free.toBigInt();852853    expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(recipient.address));854    expect(recipientBalanceAfter).to.be.equal(recipientBalanceBefore);855  });856}857858859export async function860transferExpectSuccess(861  collectionId: number,862  tokenId: number,863  sender: IKeyringPair,864  recipient: IKeyringPair | CrossAccountId,865  value: number | bigint = 1,866  type = 'NFT',867) {868  await usingApi(async (api: ApiPromise) => {869    const to = normalizeAccountId(recipient);870871    let balanceBefore = 0n;872    if (type === 'Fungible') {873      balanceBefore = await getBalance(api, collectionId, to, tokenId);874    }875    const transferTx = api.tx.unique.transfer(to, collectionId, tokenId, value);876    const events = await submitTransactionAsync(sender, transferTx);877    const result = getTransferResult(events);878    // tslint:disable-next-line:no-unused-expression879    expect(result.success).to.be.true;880    expect(result.collectionId).to.be.equal(collectionId);881    expect(result.itemId).to.be.equal(tokenId);882    expect(result.sender).to.be.deep.equal(normalizeAccountId(sender.address));883    expect(result.recipient).to.be.deep.equal(to);884    expect(result.value).to.be.equal(BigInt(value));885    if (type === 'NFT') {886      expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(to);887    }888    if (type === 'Fungible') {889      const balanceAfter = await getBalance(api, collectionId, to, tokenId);890      expect(balanceAfter - balanceBefore).to.be.equal(BigInt(value));891    }892    if (type === 'ReFungible') {893      expect(await getBalance(api, collectionId, to, tokenId) >= value).to.be.true;894    }895  });896}897898export async function899transferExpectFailure(900  collectionId: number,901  tokenId: number,902  sender: IKeyringPair,903  recipient: IKeyringPair,904  value: number | bigint = 1,905) {906  await usingApi(async (api: ApiPromise) => {907    const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient.address), collectionId, tokenId, value);908    const events = await expect(submitTransactionExpectFailAsync(sender, transferTx)).to.be.rejected;909    const result = getGenericResult(events);910    // if (events && Array.isArray(events)) {911    //   const result = getCreateCollectionResult(events);912    // tslint:disable-next-line:no-unused-expression913    expect(result.success).to.be.false;914    //}915  });916}917918export async function919approveExpectFail(920  collectionId: number,921  tokenId: number, owner: IKeyringPair, approved: IKeyringPair, amount: number | bigint = 1,922) {923  await usingApi(async (api: ApiPromise) => {924    const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved.address), collectionId, tokenId, amount);925    const events = await expect(submitTransactionExpectFailAsync(owner, approveUniqueTx)).to.be.rejected;926    const result = getCreateCollectionResult(events);927    // tslint:disable-next-line:no-unused-expression928    expect(result.success).to.be.false;929  });930}931932export async function getBalance(933  api: ApiPromise,934  collectionId: number,935  owner: string | CrossAccountId,936  token: number,937): Promise<bigint> {938  return (await api.rpc.unique.balance(collectionId, normalizeAccountId(owner), token)).toBigInt();939}940export async function getTokenOwner(941  api: ApiPromise,942  collectionId: number,943  token: number,944): Promise<CrossAccountId> {945  return normalizeAccountId((await api.rpc.unique.tokenOwner(collectionId, token)).toJSON() as any);946}947export async function isTokenExists(948  api: ApiPromise,949  collectionId: number,950  token: number,951): Promise<boolean> {952  return (await api.rpc.unique.tokenExists(collectionId, token)).toJSON();953}954export async function getLastTokenId(955  api: ApiPromise,956  collectionId: number,957): Promise<number> {958  return (await api.rpc.unique.lastTokenId(collectionId)).toJSON();959}960export async function getAdminList(961  api: ApiPromise,962  collectionId: number,963): Promise<string[]> {964  return (await api.rpc.unique.adminlist(collectionId)).toHuman() as any;965}966export async function getVariableMetadata(967  api: ApiPromise,968  collectionId: number,969  tokenId: number,970): Promise<number[]> {971  return [...(await api.rpc.unique.variableMetadata(collectionId, tokenId))];972}973export async function getConstMetadata(974  api: ApiPromise,975  collectionId: number,976  tokenId: number,977): Promise<number[]> {978  return [...(await api.rpc.unique.constMetadata(collectionId, tokenId))];979}980981export async function createFungibleItemExpectSuccess(982  sender: IKeyringPair,983  collectionId: number,984  data: CreateFungibleData,985  owner: CrossAccountId | string = sender.address,986) {987  return await usingApi(async (api) => {988    const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), {Fungible: data});989990    const events = await submitTransactionAsync(sender, tx);991    const result = getCreateItemResult(events);992993    expect(result.success).to.be.true;994    return result.itemId;995  });996}997998export async function createItemExpectSuccess(sender: IKeyringPair, collectionId: number, createMode: string, owner: CrossAccountId | string = sender.address) {999  let newItemId = 0;1000  await usingApi(async (api) => {1001    const to = normalizeAccountId(owner);1002    const itemCountBefore = await getLastTokenId(api, collectionId);1003    const itemBalanceBefore = await getBalance(api, collectionId, to, newItemId);10041005    let tx;1006    if (createMode === 'Fungible') {1007      const createData = {fungible: {value: 10}};1008      tx = api.tx.unique.createItem(collectionId, to, createData as any);1009    } else if (createMode === 'ReFungible') {1010      const createData = {refungible: {const_data: [], variable_data: [], pieces: 100}};1011      tx = api.tx.unique.createItem(collectionId, to, createData as any);1012    } else {1013      const createData = {nft: {const_data: [], variable_data: []}};1014      tx = api.tx.unique.createItem(collectionId, to, createData as any);1015    }10161017    const events = await submitTransactionAsync(sender, tx);1018    const result = getCreateItemResult(events);10191020    const itemCountAfter = await getLastTokenId(api, collectionId);1021    const itemBalanceAfter = await getBalance(api, collectionId, to, newItemId);10221023    // What to expect1024    // tslint:disable-next-line:no-unused-expression1025    expect(result.success).to.be.true;1026    if (createMode === 'Fungible') {1027      expect(itemBalanceAfter - itemBalanceBefore).to.be.equal(10n);1028    } else {1029      expect(itemCountAfter).to.be.equal(itemCountBefore + 1);1030    }1031    expect(collectionId).to.be.equal(result.collectionId);1032    expect(itemCountAfter.toString()).to.be.equal(result.itemId.toString());1033    expect(to).to.be.deep.equal(result.recipient);1034    newItemId = result.itemId;1035  });1036  return newItemId;1037}10381039export async function createItemExpectFailure(sender: IKeyringPair, collectionId: number, createMode: string, owner: string = sender.address) {1040  await usingApi(async (api) => {1041    const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), createMode);10421043    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1044    const result = getCreateItemResult(events);10451046    expect(result.success).to.be.false;1047  });1048}10491050export async function setPublicAccessModeExpectSuccess(1051  sender: IKeyringPair, collectionId: number,1052  accessMode: 'Normal' | 'AllowList',1053) {1054  await usingApi(async (api) => {10551056    // Run the transaction1057    const tx = api.tx.unique.setPublicAccessMode(collectionId, accessMode);1058    const events = await submitTransactionAsync(sender, tx);1059    const result = getGenericResult(events);10601061    // Get the collection1062    const collection = await queryCollectionExpectSuccess(api, collectionId);10631064    // What to expect1065    // tslint:disable-next-line:no-unused-expression1066    expect(result.success).to.be.true;1067    expect(collection.access.toHuman()).to.be.equal(accessMode);1068  });1069}10701071export async function setPublicAccessModeExpectFail(1072  sender: IKeyringPair, collectionId: number,1073  accessMode: 'Normal' | 'AllowList',1074) {1075  await usingApi(async (api) => {10761077    // Run the transaction1078    const tx = api.tx.unique.setPublicAccessMode(collectionId, accessMode);1079    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1080    const result = getGenericResult(events);10811082    // What to expect1083    // tslint:disable-next-line:no-unused-expression1084    expect(result.success).to.be.false;1085  });1086}10871088export async function enableAllowListExpectSuccess(sender: IKeyringPair, collectionId: number) {1089  await setPublicAccessModeExpectSuccess(sender, collectionId, 'AllowList');1090}10911092export async function enableAllowListExpectFail(sender: IKeyringPair, collectionId: number) {1093  await setPublicAccessModeExpectFail(sender, collectionId, 'AllowList');1094}10951096export async function disableAllowListExpectSuccess(sender: IKeyringPair, collectionId: number) {1097  await setPublicAccessModeExpectSuccess(sender, collectionId, 'Normal');1098}10991100export async function setMintPermissionExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {1101  await usingApi(async (api) => {11021103    // Run the transaction1104    const tx = api.tx.unique.setMintPermission(collectionId, enabled);1105    const events = await submitTransactionAsync(sender, tx);1106    const result = getGenericResult(events);1107    expect(result.success).to.be.true;11081109    // Get the collection1110    const collection = await queryCollectionExpectSuccess(api, collectionId);11111112    expect(collection.mintMode.toHuman()).to.be.equal(enabled);1113  });1114}11151116export async function enablePublicMintingExpectSuccess(sender: IKeyringPair, collectionId: number) {1117  await setMintPermissionExpectSuccess(sender, collectionId, true);1118}11191120export async function setMintPermissionExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {1121  await usingApi(async (api) => {1122    // Run the transaction1123    const tx = api.tx.unique.setMintPermission(collectionId, enabled);1124    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1125    const result = getCreateCollectionResult(events);1126    // tslint:disable-next-line:no-unused-expression1127    expect(result.success).to.be.false;1128  });1129}11301131export async function setChainLimitsExpectFailure(sender: IKeyringPair, limits: IChainLimits) {1132  await usingApi(async (api) => {1133    // Run the transaction1134    const tx = api.tx.unique.setChainLimits(limits);1135    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1136    const result = getCreateCollectionResult(events);1137    // tslint:disable-next-line:no-unused-expression1138    expect(result.success).to.be.false;1139  });1140}11411142export async function isAllowlisted(api: ApiPromise, collectionId: number, address: string | CrossAccountId) {1143  return (await api.rpc.unique.allowed(collectionId, normalizeAccountId(address))).toJSON();1144}11451146export async function addToAllowListExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId | CrossAccountId) {1147  await usingApi(async (api) => {1148    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.false;11491150    // Run the transaction1151    const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1152    const events = await submitTransactionAsync(sender, tx);1153    const result = getGenericResult(events);1154    expect(result.success).to.be.true;11551156    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;1157  });1158}11591160export async function addToAllowListAgainExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId) {1161  await usingApi(async (api) => {11621163    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;11641165    // Run the transaction1166    const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1167    const events = await submitTransactionAsync(sender, tx);1168    const result = getGenericResult(events);1169    expect(result.success).to.be.true;11701171    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;1172  });1173}11741175export async function addToAllowListExpectFail(sender: IKeyringPair, collectionId: number, address: string | AccountId) {1176  await usingApi(async (api) => {11771178    // Run the transaction1179    const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1180    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1181    const result = getGenericResult(events);11821183    // What to expect1184    // tslint:disable-next-line:no-unused-expression1185    expect(result.success).to.be.false;1186  });1187}11881189export async function removeFromAllowListExpectSuccess(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1190  await usingApi(async (api) => {1191    // Run the transaction1192    const tx = api.tx.unique.removeFromAllowList(collectionId, normalizeAccountId(address));1193    const events = await submitTransactionAsync(sender, tx);1194    const result = getGenericResult(events);11951196    // What to expect1197    // tslint:disable-next-line:no-unused-expression1198    expect(result.success).to.be.true;1199  });1200}12011202export async function removeFromAllowListExpectFailure(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1203  await usingApi(async (api) => {1204    // Run the transaction1205    const tx = api.tx.unique.removeFromAllowList(collectionId, normalizeAccountId(address));1206    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1207    const result = getGenericResult(events);12081209    // What to expect1210    // tslint:disable-next-line:no-unused-expression1211    expect(result.success).to.be.false;1212  });1213}12141215export const getDetailedCollectionInfo = async (api: ApiPromise, collectionId: number)1216  : Promise<UpDataStructsCollection | null> => {1217  return (await api.rpc.unique.collectionById(collectionId)).unwrapOr(null);1218};12191220export const getCreatedCollectionCount = async (api: ApiPromise): Promise<number> => {1221  // set global object - collectionsCount1222  return (await api.rpc.unique.collectionStats()).created.toNumber();1223};12241225export async function queryCollectionExpectSuccess(api: ApiPromise, collectionId: number): Promise<UpDataStructsCollection> {1226  return (await api.rpc.unique.collectionById(collectionId)).unwrap();1227}12281229export async function waitNewBlocks(blocksCount = 1): Promise<void> {1230  await usingApi(async (api) => {1231    const promise = new Promise<void>(async (resolve) => {1232      const unsubscribe = await api.rpc.chain.subscribeNewHeads(() => {1233        if (blocksCount > 0) {1234          blocksCount--;1235        } else {1236          unsubscribe();1237          resolve();1238        }1239      });1240    });1241    return promise;1242  });1243}
after · tests/src/util/helpers.ts
1//2// This file is subject to the terms and conditions defined in3// file 'LICENSE', which is part of this source code package.4//56import '../interfaces/augment-api-rpc';7import '../interfaces/augment-api-query';8import {ApiPromise, Keyring} from '@polkadot/api';9import type {AccountId, EventRecord} from '@polkadot/types/interfaces';10import {IKeyringPair} from '@polkadot/types/types';11import {evmToAddress} from '@polkadot/util-crypto';12import BN from 'bn.js';13import chai from 'chai';14import chaiAsPromised from 'chai-as-promised';15import {alicesPublicKey} from '../accounts';16import privateKey from '../substrate/privateKey';17import {default as usingApi, submitTransactionAsync, submitTransactionExpectFailAsync} from '../substrate/substrate-api';18import {hexToStr, strToUTF16, utf16ToStr} from './util';19import {UpDataStructsCollection} from '@polkadot/types/lookup';2021chai.use(chaiAsPromised);22const expect = chai.expect;2324export type CrossAccountId = {25  Substrate: string,26} | {27  Ethereum: string,28};2930export function normalizeAccountId(input: string | AccountId | CrossAccountId | IKeyringPair): CrossAccountId {31  if (typeof input === 'string') {32    if (input.length === 48 || input.length === 47) {33      return {Substrate: input};34    } else if (input.length === 42 && input.startsWith('0x')) {35      return {Ethereum: input.toLowerCase()};36    } else if (input.length === 40 && !input.startsWith('0x')) {37      return {Ethereum: '0x' + input.toLowerCase()};38    } else {39      throw new Error(`Unknown address format: "${input}"`);40    }41  }42  if ('address' in input) {43    return {Substrate: input.address};44  }45  if ('Ethereum' in input) {46    return {47      Ethereum: input.Ethereum.toLowerCase(),48    };49  } else if ('ethereum' in input) {50    return {51      Ethereum: (input as any).ethereum.toLowerCase(),52    };53  } else if ('Substrate' in input) {54    return input;55  } else if ('substrate' in input) {56    return {57      Substrate: (input as any).substrate,58    };59  }6061  // AccountId62  return {Substrate: input.toString()};63}64export function toSubstrateAddress(input: string | CrossAccountId | IKeyringPair): string {65  input = normalizeAccountId(input);66  if ('Substrate' in input) {67    return input.Substrate;68  } else {69    return evmToAddress(input.Ethereum);70  }71}7273export const U128_MAX = (1n << 128n) - 1n;7475const MICROUNIQUE = 1_000_000_000_000n;76const MILLIUNIQUE = 1_000n * MICROUNIQUE;77const CENTIUNIQUE = 10n * MILLIUNIQUE;78export const UNIQUE = 100n * CENTIUNIQUE;7980type GenericResult = {81  success: boolean,82};8384interface CreateCollectionResult {85  success: boolean;86  collectionId: number;87}8889interface CreateItemResult {90  success: boolean;91  collectionId: number;92  itemId: number;93  recipient?: CrossAccountId;94}9596interface TransferResult {97  success: boolean;98  collectionId: number;99  itemId: number;100  sender?: CrossAccountId;101  recipient?: CrossAccountId;102  value: bigint;103}104105interface IReFungibleOwner {106  fraction: BN;107  owner: number[];108}109110interface IGetMessage {111  checkMsgUnqMethod: string;112  checkMsgTrsMethod: string;113  checkMsgSysMethod: string;114}115116export interface IFungibleTokenDataType {117  value: number;118}119120export interface IChainLimits {121  collectionNumbersLimit: number;122  accountTokenOwnershipLimit: number;123  collectionsAdminsLimit: number;124  customDataLimit: number;125  nftSponsorTransferTimeout: number;126  fungibleSponsorTransferTimeout: number;127  refungibleSponsorTransferTimeout: number;128  offchainSchemaLimit: number;129  variableOnChainSchemaLimit: number;130  constOnChainSchemaLimit: number;131}132133export interface IReFungibleTokenDataType {134  owner: IReFungibleOwner[];135  constData: number[];136  variableData: number[];137}138139export function uniqueEventMessage(events: EventRecord[]): IGetMessage {140  let checkMsgUnqMethod = '';141  let checkMsgTrsMethod = '';142  let checkMsgSysMethod = '';143  events.forEach(({event: {method, section}}) => {144    if (section === 'common') {145      checkMsgUnqMethod = method;146    } else if (section === 'treasury') {147      checkMsgTrsMethod = method;148    } else if (section === 'system') {149      checkMsgSysMethod = method;150    } else { return null; }151  });152  const result: IGetMessage = {153    checkMsgUnqMethod,154    checkMsgTrsMethod,155    checkMsgSysMethod,156  };157  return result;158}159160export function getGenericResult(events: EventRecord[]): GenericResult {161  const result: GenericResult = {162    success: false,163  };164  events.forEach(({event: {method}}) => {165    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);166    if (method === 'ExtrinsicSuccess') {167      result.success = true;168    }169  });170  return result;171}172173174175export function getCreateCollectionResult(events: EventRecord[]): CreateCollectionResult {176  let success = false;177  let collectionId = 0;178  events.forEach(({event: {data, method, section}}) => {179    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);180    if (method == 'ExtrinsicSuccess') {181      success = true;182    } else if ((section == 'common') && (method == 'CollectionCreated')) {183      collectionId = parseInt(data[0].toString(), 10);184    }185  });186  const result: CreateCollectionResult = {187    success,188    collectionId,189  };190  return result;191}192193export function getCreateItemResult(events: EventRecord[]): CreateItemResult {194  let success = false;195  let collectionId = 0;196  let itemId = 0;197  let recipient;198  events.forEach(({event: {data, method, section}}) => {199    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);200    if (method == 'ExtrinsicSuccess') {201      success = true;202    } else if ((section == 'common') && (method == 'ItemCreated')) {203      collectionId = parseInt(data[0].toString(), 10);204      itemId = parseInt(data[1].toString(), 10);205      recipient = normalizeAccountId(data[2].toJSON() as any);206    }207  });208  const result: CreateItemResult = {209    success,210    collectionId,211    itemId,212    recipient,213  };214  return result;215}216217export function getTransferResult(events: EventRecord[]): TransferResult {218  const result: TransferResult = {219    success: false,220    collectionId: 0,221    itemId: 0,222    value: 0n,223  };224225  events.forEach(({event: {data, method, section}}) => {226    if (method === 'ExtrinsicSuccess') {227      result.success = true;228    } else if (section === 'common' && method === 'Transfer') {229      result.collectionId = +data[0].toString();230      result.itemId = +data[1].toString();231      result.sender = normalizeAccountId(data[2].toJSON() as any);232      result.recipient = normalizeAccountId(data[3].toJSON() as any);233      result.value = BigInt(data[4].toString());234    }235  });236237  return result;238}239240interface Nft {241  type: 'NFT';242}243244interface Fungible {245  type: 'Fungible';246  decimalPoints: number;247}248249interface ReFungible {250  type: 'ReFungible';251}252253type CollectionMode = Nft | Fungible | ReFungible;254255export type CreateCollectionParams = {256  mode: CollectionMode,257  name: string,258  description: string,259  tokenPrefix: string,260};261262const defaultCreateCollectionParams: CreateCollectionParams = {263  description: 'description',264  mode: {type: 'NFT'},265  name: 'name',266  tokenPrefix: 'prefix',267};268269export async function createCollectionExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {270  const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};271272  let collectionId = 0;273  await usingApi(async (api) => {274    // Get number of collections before the transaction275    const collectionCountBefore = await getCreatedCollectionCount(api);276277    // Run the CreateCollection transaction278    const alicePrivateKey = privateKey('//Alice');279280    let modeprm = {};281    if (mode.type === 'NFT') {282      modeprm = {nft: null};283    } else if (mode.type === 'Fungible') {284      modeprm = {fungible: mode.decimalPoints};285    } else if (mode.type === 'ReFungible') {286      modeprm = {refungible: null};287    }288289    const tx = api.tx.unique.createCollectionEx({name: strToUTF16(name), description: strToUTF16(description), tokenPrefix: strToUTF16(tokenPrefix), mode: modeprm as any});290    const events = await submitTransactionAsync(alicePrivateKey, tx);291    const result = getCreateCollectionResult(events);292293    // Get number of collections after the transaction294    const collectionCountAfter = await getCreatedCollectionCount(api);295296    // Get the collection297    const collection = await queryCollectionExpectSuccess(api, result.collectionId);298299    // What to expect300    // tslint:disable-next-line:no-unused-expression301    expect(result.success).to.be.true;302    expect(result.collectionId).to.be.equal(collectionCountAfter);303    // tslint:disable-next-line:no-unused-expression304    expect(collection).to.be.not.null;305    expect(collectionCountAfter).to.be.equal(collectionCountBefore + 1, 'Error: NFT collection NOT created.');306    expect(collection.owner.toString()).to.be.equal(toSubstrateAddress(alicesPublicKey));307    expect(utf16ToStr(collection.name.toJSON() as any)).to.be.equal(name);308    expect(utf16ToStr(collection.description.toJSON() as any)).to.be.equal(description);309    expect(hexToStr(collection.tokenPrefix.toJSON())).to.be.equal(tokenPrefix);310311    collectionId = result.collectionId;312  });313314  return collectionId;315}316317export async function createCollectionExpectFailure(params: Partial<CreateCollectionParams> = {}) {318  const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};319320  let modeprm = {};321  if (mode.type === 'NFT') {322    modeprm = {nft: null};323  } else if (mode.type === 'Fungible') {324    modeprm = {fungible: mode.decimalPoints};325  } else if (mode.type === 'ReFungible') {326    modeprm = {refungible: null};327  }328329  await usingApi(async (api) => {330    // Get number of collections before the transaction331    const collectionCountBefore = await getCreatedCollectionCount(api);332333    // Run the CreateCollection transaction334    const alicePrivateKey = privateKey('//Alice');335    const tx = api.tx.unique.createCollectionEx({name: strToUTF16(name), description: strToUTF16(description), tokenPrefix: strToUTF16(tokenPrefix), mode: modeprm as any});336    const events = await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;337    const result = getCreateCollectionResult(events);338339    // Get number of collections after the transaction340    const collectionCountAfter = await getCreatedCollectionCount(api);341342    // What to expect343    // tslint:disable-next-line:no-unused-expression344    expect(result.success).to.be.false;345    expect(collectionCountAfter).to.be.equal(collectionCountBefore, 'Error: Collection with incorrect data created.');346  });347}348349export async function findUnusedAddress(api: ApiPromise, seedAddition = ''): Promise<IKeyringPair> {350  let bal = 0n;351  let unused;352  do {353    const randomSeed = 'seed' + Math.floor(Math.random() * Math.floor(10000)) + seedAddition;354    const keyring = new Keyring({type: 'sr25519'});355    unused = keyring.addFromUri(`//${randomSeed}`);356    bal = (await api.query.system.account(unused.address)).data.free.toBigInt();357  } while (bal !== 0n);358  return unused;359}360361export async function getAllowance(api: ApiPromise, collectionId: number, owner: CrossAccountId | string, approved: CrossAccountId | string, tokenId: number) {362  return (await api.rpc.unique.allowance(collectionId, normalizeAccountId(owner), normalizeAccountId(approved), tokenId)).toBigInt();363}364365export function findUnusedAddresses(api: ApiPromise, amount: number): Promise<IKeyringPair[]> {366  return Promise.all(new Array(amount).fill(null).map(() => findUnusedAddress(api, '_' + Date.now())));367}368369export async function findNotExistingCollection(api: ApiPromise): Promise<number> {370  const totalNumber = await getCreatedCollectionCount(api);371  const newCollection: number = totalNumber + 1;372  return newCollection;373}374375function getDestroyResult(events: EventRecord[]): boolean {376  let success = false;377  events.forEach(({event: {method}}) => {378    if (method == 'ExtrinsicSuccess') {379      success = true;380    }381  });382  return success;383}384385export async function destroyCollectionExpectFailure(collectionId: number, senderSeed = '//Alice') {386  await usingApi(async (api) => {387    // Run the DestroyCollection transaction388    const alicePrivateKey = privateKey(senderSeed);389    const tx = api.tx.unique.destroyCollection(collectionId);390    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;391  });392}393394export async function destroyCollectionExpectSuccess(collectionId: number, senderSeed = '//Alice') {395  await usingApi(async (api) => {396    // Run the DestroyCollection transaction397    const alicePrivateKey = privateKey(senderSeed);398    const tx = api.tx.unique.destroyCollection(collectionId);399    const events = await submitTransactionAsync(alicePrivateKey, tx);400    const result = getDestroyResult(events);401    expect(result).to.be.true;402403    // What to expect404    expect(await getDetailedCollectionInfo(api, collectionId)).to.be.null;405  });406}407408export async function setCollectionLimitsExpectSuccess(sender: IKeyringPair, collectionId: number, limits: any) {409  await usingApi(async (api) => {410    const tx = api.tx.unique.setCollectionLimits(collectionId, limits);411    const events = await submitTransactionAsync(sender, tx);412    const result = getGenericResult(events);413414    expect(result.success).to.be.true;415  });416}417418export async function setCollectionLimitsExpectFailure(sender: IKeyringPair, collectionId: number, limits: any) {419  await usingApi(async (api) => {420    const tx = api.tx.unique.setCollectionLimits(collectionId, limits);421    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;422    const result = getGenericResult(events);423424    expect(result.success).to.be.false;425  });426}427428export async function setCollectionSponsorExpectSuccess(collectionId: number, sponsor: string, sender = '//Alice') {429  await usingApi(async (api) => {430431    // Run the transaction432    const senderPrivateKey = privateKey(sender);433    const tx = api.tx.unique.setCollectionSponsor(collectionId, sponsor);434    const events = await submitTransactionAsync(senderPrivateKey, tx);435    const result = getGenericResult(events);436437    // Get the collection438    const collection = await queryCollectionExpectSuccess(api, collectionId);439440    // What to expect441    expect(result.success).to.be.true;442    expect(collection.sponsorship.toJSON()).to.deep.equal({443      unconfirmed: sponsor,444    });445  });446}447448export async function removeCollectionSponsorExpectSuccess(collectionId: number, sender = '//Alice') {449  await usingApi(async (api) => {450451    // Run the transaction452    const alicePrivateKey = privateKey(sender);453    const tx = api.tx.unique.removeCollectionSponsor(collectionId);454    const events = await submitTransactionAsync(alicePrivateKey, tx);455    const result = getGenericResult(events);456457    // Get the collection458    const collection = await queryCollectionExpectSuccess(api, collectionId);459460    // What to expect461    expect(result.success).to.be.true;462    expect(collection.sponsorship.toJSON()).to.be.deep.equal({disabled: null});463  });464}465466export async function removeCollectionSponsorExpectFailure(collectionId: number, senderSeed = '//Alice') {467  await usingApi(async (api) => {468469    // Run the transaction470    const alicePrivateKey = privateKey(senderSeed);471    const tx = api.tx.unique.removeCollectionSponsor(collectionId);472    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;473  });474}475476export async function setCollectionSponsorExpectFailure(collectionId: number, sponsor: string, senderSeed = '//Alice') {477  await usingApi(async (api) => {478479    // Run the transaction480    const alicePrivateKey = privateKey(senderSeed);481    const tx = api.tx.unique.setCollectionSponsor(collectionId, sponsor);482    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;483  });484}485486export async function confirmSponsorshipExpectSuccess(collectionId: number, senderSeed = '//Alice') {487  await usingApi(async (api) => {488489    // Run the transaction490    const sender = privateKey(senderSeed);491    const tx = api.tx.unique.confirmSponsorship(collectionId);492    const events = await submitTransactionAsync(sender, tx);493    const result = getGenericResult(events);494495    // Get the collection496    const collection = await queryCollectionExpectSuccess(api, collectionId);497498    // What to expect499    expect(result.success).to.be.true;500    expect(collection.sponsorship.toJSON()).to.be.deep.equal({501      confirmed: sender.address,502    });503  });504}505506507export async function confirmSponsorshipExpectFailure(collectionId: number, senderSeed = '//Alice') {508  await usingApi(async (api) => {509510    // Run the transaction511    const sender = privateKey(senderSeed);512    const tx = api.tx.unique.confirmSponsorship(collectionId);513    await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;514  });515}516517export async function setMetadataUpdatePermissionFlagExpectSuccess(sender: IKeyringPair, collectionId: number, flag: string) {518519  await usingApi(async (api) => {520    const tx = api.tx.unique.setMetaUpdatePermissionFlag(collectionId, flag as any);521    const events = await submitTransactionAsync(sender, tx);522    const result = getGenericResult(events);523524    expect(result.success).to.be.true;525  });526}527528export async function setMetadataUpdatePermissionFlagExpectFailure(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 expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;533    const result = getGenericResult(events);534535    expect(result.success).to.be.false;536  });537}538539export async function enableContractSponsoringExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {540  await usingApi(async (api) => {541    const tx = api.tx.unique.enableContractSponsoring(contractAddress, enable);542    const events = await submitTransactionAsync(sender, tx);543    const result = getGenericResult(events);544545    expect(result.success).to.be.true;546  });547}548549export async function enableContractSponsoringExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {550  await usingApi(async (api) => {551    const tx = api.tx.unique.enableContractSponsoring(contractAddress, enable);552    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;553    const result = getGenericResult(events);554555    expect(result.success).to.be.false;556  });557}558559export async function setTransferFlagExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {560561  await usingApi(async (api) => {562563    const tx = api.tx.unique.setTransfersEnabledFlag(collectionId, enabled);564    const events = await submitTransactionAsync(sender, tx);565    const result = getGenericResult(events);566567    expect(result.success).to.be.true;568  });569}570571export async function setTransferFlagExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {572573  await usingApi(async (api) => {574575    const tx = api.tx.unique.setTransfersEnabledFlag(collectionId, enabled);576    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;577    const result = getGenericResult(events);578579    expect(result.success).to.be.false;580  });581}582583export async function setContractSponsoringRateLimitExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {584  await usingApi(async (api) => {585    const tx = api.tx.unique.setContractSponsoringRateLimit(contractAddress, rateLimit);586    const events = await submitTransactionAsync(sender, tx);587    const result = getGenericResult(events);588589    expect(result.success).to.be.true;590  });591}592593export async function setContractSponsoringRateLimitExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {594  await usingApi(async (api) => {595    const tx = api.tx.unique.setContractSponsoringRateLimit(contractAddress, rateLimit);596    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;597    const result = getGenericResult(events);598599    expect(result.success).to.be.false;600  });601}602603export async function toggleContractAllowlistExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, value = true) {604  await usingApi(async (api) => {605    const tx = api.tx.unique.toggleContractAllowList(contractAddress, value);606    const events = await submitTransactionAsync(sender, tx);607    const result = getGenericResult(events);608609    expect(result.success).to.be.true;610  });611}612613export async function isAllowlistedInContract(contractAddress: AccountId | string, user: string) {614  let allowlisted = false;615  await usingApi(async (api) => {616    allowlisted = (await api.query.unique.contractAllowList(contractAddress, user)).toJSON() as boolean;617  });618  return allowlisted;619}620621export async function addToContractAllowListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {622  await usingApi(async (api) => {623    const tx = api.tx.unique.addToContractAllowList(contractAddress.toString(), user.toString());624    const events = await submitTransactionAsync(sender, tx);625    const result = getGenericResult(events);626627    expect(result.success).to.be.true;628  });629}630631export async function removeFromContractAllowListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {632  await usingApi(async (api) => {633    const tx = api.tx.unique.removeFromContractAllowList(contractAddress.toString(), user.toString());634    const events = await submitTransactionAsync(sender, tx);635    const result = getGenericResult(events);636637    expect(result.success).to.be.true;638  });639}640641export async function removeFromContractAllowListExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {642  await usingApi(async (api) => {643    const tx = api.tx.unique.removeFromContractAllowList(contractAddress.toString(), user.toString());644    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;645    const result = getGenericResult(events);646647    expect(result.success).to.be.false;648  });649}650651export async function setVariableMetaDataExpectSuccess(sender: IKeyringPair, collectionId: number, itemId: number, data: number[]) {652  await usingApi(async (api) => {653    const tx = api.tx.unique.setVariableMetaData(collectionId, itemId, '0x' + Buffer.from(data).toString('hex'));654    const events = await submitTransactionAsync(sender, tx);655    const result = getGenericResult(events);656657    expect(result.success).to.be.true;658  });659}660661export async function setVariableMetaDataExpectFailure(sender: IKeyringPair, collectionId: number, itemId: number, data: number[]) {662  await usingApi(async (api) => {663    const tx = api.tx.unique.setVariableMetaData(collectionId, itemId, '0x' + Buffer.from(data).toString('hex'));664    await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;665  });666}667668export async function setOffchainSchemaExpectSuccess(sender: IKeyringPair, collectionId: number, data: number[]) {669  await usingApi(async (api) => {670    const tx = api.tx.unique.setOffchainSchema(collectionId, '0x' + Buffer.from(data).toString('hex'));671    const events = await submitTransactionAsync(sender, tx);672    const result = getGenericResult(events);673674    expect(result.success).to.be.true;675  });676}677678export async function setOffchainSchemaExpectFailure(sender: IKeyringPair, collectionId: number, data: number[]) {679  await usingApi(async (api) => {680    const tx = api.tx.unique.setOffchainSchema(collectionId, '0x' + Buffer.from(data).toString('hex'));681    await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;682  });683}684685export interface CreateFungibleData {686  readonly Value: bigint;687}688689export interface CreateReFungibleData { }690export interface CreateNftData { }691692export type CreateItemData = {693  NFT: CreateNftData;694} | {695  Fungible: CreateFungibleData;696} | {697  ReFungible: CreateReFungibleData;698};699700export async function burnItemExpectSuccess(sender: IKeyringPair, collectionId: number, tokenId: number, value = 1) {701  await usingApi(async (api) => {702    const balanceBefore = await getBalance(api, collectionId, normalizeAccountId(sender), tokenId);703    // if burning token by admin - use adminButnItemExpectSuccess704    expect(balanceBefore >= BigInt(value)).to.be.true;705706    const tx = api.tx.unique.burnItem(collectionId, tokenId, value);707    const events = await submitTransactionAsync(sender, tx);708    const result = getGenericResult(events);709    expect(result.success).to.be.true;710711    const balanceAfter = await getBalance(api, collectionId, normalizeAccountId(sender), tokenId);712    expect(balanceAfter + BigInt(value)).to.be.equal(balanceBefore);713  });714}715716export async function717approveExpectSuccess(718  collectionId: number,719  tokenId: number, owner: IKeyringPair, approved: CrossAccountId | string, amount: number | bigint = 1,720) {721  await usingApi(async (api: ApiPromise) => {722    const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);723    const events = await submitTransactionAsync(owner, approveUniqueTx);724    const result = getGenericResult(events);725    expect(result.success).to.be.true;726727    expect(await getAllowance(api, collectionId, owner.address, approved, tokenId)).to.be.equal(BigInt(amount));728  });729}730731export async function adminApproveFromExpectSuccess(732  collectionId: number,733  tokenId: number, admin: IKeyringPair, owner: CrossAccountId | string, approved: CrossAccountId | string, amount: number | bigint = 1,734) {735  await usingApi(async (api: ApiPromise) => {736    const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);737    const events = await submitTransactionAsync(admin, approveUniqueTx);738    const result = getGenericResult(events);739    expect(result.success).to.be.true;740741    expect(await getAllowance(api, collectionId, owner, approved, tokenId)).to.be.equal(BigInt(amount));742  });743}744745export async function746transferFromExpectSuccess(747  collectionId: number,748  tokenId: number,749  accountApproved: IKeyringPair,750  accountFrom: IKeyringPair | CrossAccountId,751  accountTo: IKeyringPair | CrossAccountId,752  value: number | bigint = 1,753  type = 'NFT',754) {755  await usingApi(async (api: ApiPromise) => {756    const from = normalizeAccountId(accountFrom);757    const to = normalizeAccountId(accountTo);758    let balanceBefore = 0n;759    if (type === 'Fungible') {760      balanceBefore = await getBalance(api, collectionId, to, tokenId);761    }762    const transferFromTx = api.tx.unique.transferFrom(normalizeAccountId(accountFrom), to, collectionId, tokenId, value);763    const events = await submitTransactionAsync(accountApproved, transferFromTx);764    const result = getCreateItemResult(events);765    // tslint:disable-next-line:no-unused-expression766    expect(result.success).to.be.true;767    if (type === 'NFT') {768      expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(to);769    }770    if (type === 'Fungible') {771      const balanceAfter = await getBalance(api, collectionId, to, tokenId);772      if (JSON.stringify(to) !== JSON.stringify(from)) {773        expect(balanceAfter - balanceBefore).to.be.equal(BigInt(value));774      } else {775        expect(balanceAfter).to.be.equal(balanceBefore);776      }777    }778    if (type === 'ReFungible') {779      expect(await getBalance(api, collectionId, to, tokenId)).to.be.equal(BigInt(value));780    }781  });782}783784export async function785transferFromExpectFail(786  collectionId: number,787  tokenId: number,788  accountApproved: IKeyringPair,789  accountFrom: IKeyringPair,790  accountTo: IKeyringPair,791  value: number | bigint = 1,792) {793  await usingApi(async (api: ApiPromise) => {794    const transferFromTx = api.tx.unique.transferFrom(normalizeAccountId(accountFrom.address), normalizeAccountId(accountTo.address), collectionId, tokenId, value);795    const events = await expect(submitTransactionExpectFailAsync(accountApproved, transferFromTx)).to.be.rejected;796    const result = getCreateCollectionResult(events);797    // tslint:disable-next-line:no-unused-expression798    expect(result.success).to.be.false;799  });800}801802/* eslint no-async-promise-executor: "off" */803async function getBlockNumber(api: ApiPromise): Promise<number> {804  return new Promise<number>(async (resolve) => {805    const unsubscribe = await api.rpc.chain.subscribeNewHeads((head) => {806      unsubscribe();807      resolve(head.number.toNumber());808    });809  });810}811812export async function addCollectionAdminExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | CrossAccountId) {813  await usingApi(async (api) => {814    const changeAdminTx = api.tx.unique.addCollectionAdmin(collectionId, normalizeAccountId(address));815    const events = await submitTransactionAsync(sender, changeAdminTx);816    const result = getCreateCollectionResult(events);817    expect(result.success).to.be.true;818  });819}820821export async function822getFreeBalance(account: IKeyringPair): Promise<bigint> {823  let balance = 0n;824  await usingApi(async (api) => {825    balance = BigInt((await api.query.system.account(account.address)).data.free.toString());826  });827828  return balance;829}830831export async function832scheduleTransferExpectSuccess(833  collectionId: number,834  tokenId: number,835  sender: IKeyringPair,836  recipient: IKeyringPair,837  value: number | bigint = 1,838  blockSchedule: number,839) {840  await usingApi(async (api: ApiPromise) => {841    const blockNumber: number | undefined = await getBlockNumber(api);842    const expectedBlockNumber = blockNumber + blockSchedule;843844    expect(blockNumber).to.be.greaterThan(0);845    const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient.address), collectionId, tokenId, value);846    const scheduleTx = api.tx.scheduler.schedule(expectedBlockNumber, null, 0, transferTx as any);847848    await submitTransactionAsync(sender, scheduleTx);849850    const recipientBalanceBefore = (await api.query.system.account(recipient.address)).data.free.toBigInt();851852    expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(sender.address));853854    // sleep for 4 blocks855    await waitNewBlocks(blockSchedule + 1);856857    const recipientBalanceAfter = (await api.query.system.account(recipient.address)).data.free.toBigInt();858859    expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(recipient.address));860    expect(recipientBalanceAfter).to.be.equal(recipientBalanceBefore);861  });862}863864865export async function866transferExpectSuccess(867  collectionId: number,868  tokenId: number,869  sender: IKeyringPair,870  recipient: IKeyringPair | CrossAccountId,871  value: number | bigint = 1,872  type = 'NFT',873) {874  await usingApi(async (api: ApiPromise) => {875    const from = normalizeAccountId(sender);876    const to = normalizeAccountId(recipient);877878    let balanceBefore = 0n;879    if (type === 'Fungible') {880      balanceBefore = await getBalance(api, collectionId, to, tokenId);881    }882    const transferTx = api.tx.unique.transfer(to, collectionId, tokenId, value);883    const events = await submitTransactionAsync(sender, transferTx);884    const result = getTransferResult(events);885    // tslint:disable-next-line:no-unused-expression886    expect(result.success).to.be.true;887    expect(result.collectionId).to.be.equal(collectionId);888    expect(result.itemId).to.be.equal(tokenId);889    expect(result.sender).to.be.deep.equal(normalizeAccountId(sender.address));890    expect(result.recipient).to.be.deep.equal(to);891    expect(result.value).to.be.equal(BigInt(value));892    if (type === 'NFT') {893      expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(to);894    }895    if (type === 'Fungible') {896      const balanceAfter = await getBalance(api, collectionId, to, tokenId);897      if (JSON.stringify(to) !== JSON.stringify(from)) {898        expect(balanceAfter - balanceBefore).to.be.equal(BigInt(value));899      } else {900        expect(balanceAfter).to.be.equal(balanceBefore);901      }902    }903    if (type === 'ReFungible') {904      expect(await getBalance(api, collectionId, to, tokenId) >= value).to.be.true;905    }906  });907}908909export async function910transferExpectFailure(911  collectionId: number,912  tokenId: number,913  sender: IKeyringPair,914  recipient: IKeyringPair,915  value: number | bigint = 1,916) {917  await usingApi(async (api: ApiPromise) => {918    const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient.address), collectionId, tokenId, value);919    const events = await expect(submitTransactionExpectFailAsync(sender, transferTx)).to.be.rejected;920    const result = getGenericResult(events);921    // if (events && Array.isArray(events)) {922    //   const result = getCreateCollectionResult(events);923    // tslint:disable-next-line:no-unused-expression924    expect(result.success).to.be.false;925    //}926  });927}928929export async function930approveExpectFail(931  collectionId: number,932  tokenId: number, owner: IKeyringPair, approved: IKeyringPair, amount: number | bigint = 1,933) {934  await usingApi(async (api: ApiPromise) => {935    const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved.address), collectionId, tokenId, amount);936    const events = await expect(submitTransactionExpectFailAsync(owner, approveUniqueTx)).to.be.rejected;937    const result = getCreateCollectionResult(events);938    // tslint:disable-next-line:no-unused-expression939    expect(result.success).to.be.false;940  });941}942943export async function getBalance(944  api: ApiPromise,945  collectionId: number,946  owner: string | CrossAccountId,947  token: number,948): Promise<bigint> {949  return (await api.rpc.unique.balance(collectionId, normalizeAccountId(owner), token)).toBigInt();950}951export async function getTokenOwner(952  api: ApiPromise,953  collectionId: number,954  token: number,955): Promise<CrossAccountId> {956  return normalizeAccountId((await api.rpc.unique.tokenOwner(collectionId, token)).toJSON() as any);957}958export async function isTokenExists(959  api: ApiPromise,960  collectionId: number,961  token: number,962): Promise<boolean> {963  return (await api.rpc.unique.tokenExists(collectionId, token)).toJSON();964}965export async function getLastTokenId(966  api: ApiPromise,967  collectionId: number,968): Promise<number> {969  return (await api.rpc.unique.lastTokenId(collectionId)).toJSON();970}971export async function getAdminList(972  api: ApiPromise,973  collectionId: number,974): Promise<string[]> {975  return (await api.rpc.unique.adminlist(collectionId)).toHuman() as any;976}977export async function getVariableMetadata(978  api: ApiPromise,979  collectionId: number,980  tokenId: number,981): Promise<number[]> {982  return [...(await api.rpc.unique.variableMetadata(collectionId, tokenId))];983}984export async function getConstMetadata(985  api: ApiPromise,986  collectionId: number,987  tokenId: number,988): Promise<number[]> {989  return [...(await api.rpc.unique.constMetadata(collectionId, tokenId))];990}991992export async function createFungibleItemExpectSuccess(993  sender: IKeyringPair,994  collectionId: number,995  data: CreateFungibleData,996  owner: CrossAccountId | string = sender.address,997) {998  return await usingApi(async (api) => {999    const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), {Fungible: data});10001001    const events = await submitTransactionAsync(sender, tx);1002    const result = getCreateItemResult(events);10031004    expect(result.success).to.be.true;1005    return result.itemId;1006  });1007}10081009export async function createItemExpectSuccess(sender: IKeyringPair, collectionId: number, createMode: string, owner: CrossAccountId | string = sender.address) {1010  let newItemId = 0;1011  await usingApi(async (api) => {1012    const to = normalizeAccountId(owner);1013    const itemCountBefore = await getLastTokenId(api, collectionId);1014    const itemBalanceBefore = await getBalance(api, collectionId, to, newItemId);10151016    let tx;1017    if (createMode === 'Fungible') {1018      const createData = {fungible: {value: 10}};1019      tx = api.tx.unique.createItem(collectionId, to, createData as any);1020    } else if (createMode === 'ReFungible') {1021      const createData = {refungible: {const_data: [], variable_data: [], pieces: 100}};1022      tx = api.tx.unique.createItem(collectionId, to, createData as any);1023    } else {1024      const createData = {nft: {const_data: [], variable_data: []}};1025      tx = api.tx.unique.createItem(collectionId, to, createData as any);1026    }10271028    const events = await submitTransactionAsync(sender, tx);1029    const result = getCreateItemResult(events);10301031    const itemCountAfter = await getLastTokenId(api, collectionId);1032    const itemBalanceAfter = await getBalance(api, collectionId, to, newItemId);10331034    // What to expect1035    // tslint:disable-next-line:no-unused-expression1036    expect(result.success).to.be.true;1037    if (createMode === 'Fungible') {1038      expect(itemBalanceAfter - itemBalanceBefore).to.be.equal(10n);1039    } else {1040      expect(itemCountAfter).to.be.equal(itemCountBefore + 1);1041    }1042    expect(collectionId).to.be.equal(result.collectionId);1043    expect(itemCountAfter.toString()).to.be.equal(result.itemId.toString());1044    expect(to).to.be.deep.equal(result.recipient);1045    newItemId = result.itemId;1046  });1047  return newItemId;1048}10491050export async function createItemExpectFailure(sender: IKeyringPair, collectionId: number, createMode: string, owner: string = sender.address) {1051  await usingApi(async (api) => {1052    const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), createMode);10531054    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1055    const result = getCreateItemResult(events);10561057    expect(result.success).to.be.false;1058  });1059}10601061export async function setPublicAccessModeExpectSuccess(1062  sender: IKeyringPair, collectionId: number,1063  accessMode: 'Normal' | 'AllowList',1064) {1065  await usingApi(async (api) => {10661067    // Run the transaction1068    const tx = api.tx.unique.setPublicAccessMode(collectionId, accessMode);1069    const events = await submitTransactionAsync(sender, tx);1070    const result = getGenericResult(events);10711072    // Get the collection1073    const collection = await queryCollectionExpectSuccess(api, collectionId);10741075    // What to expect1076    // tslint:disable-next-line:no-unused-expression1077    expect(result.success).to.be.true;1078    expect(collection.access.toHuman()).to.be.equal(accessMode);1079  });1080}10811082export async function setPublicAccessModeExpectFail(1083  sender: IKeyringPair, collectionId: number,1084  accessMode: 'Normal' | 'AllowList',1085) {1086  await usingApi(async (api) => {10871088    // Run the transaction1089    const tx = api.tx.unique.setPublicAccessMode(collectionId, accessMode);1090    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1091    const result = getGenericResult(events);10921093    // What to expect1094    // tslint:disable-next-line:no-unused-expression1095    expect(result.success).to.be.false;1096  });1097}10981099export async function enableAllowListExpectSuccess(sender: IKeyringPair, collectionId: number) {1100  await setPublicAccessModeExpectSuccess(sender, collectionId, 'AllowList');1101}11021103export async function enableAllowListExpectFail(sender: IKeyringPair, collectionId: number) {1104  await setPublicAccessModeExpectFail(sender, collectionId, 'AllowList');1105}11061107export async function disableAllowListExpectSuccess(sender: IKeyringPair, collectionId: number) {1108  await setPublicAccessModeExpectSuccess(sender, collectionId, 'Normal');1109}11101111export async function setMintPermissionExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {1112  await usingApi(async (api) => {11131114    // Run the transaction1115    const tx = api.tx.unique.setMintPermission(collectionId, enabled);1116    const events = await submitTransactionAsync(sender, tx);1117    const result = getGenericResult(events);1118    expect(result.success).to.be.true;11191120    // Get the collection1121    const collection = await queryCollectionExpectSuccess(api, collectionId);11221123    expect(collection.mintMode.toHuman()).to.be.equal(enabled);1124  });1125}11261127export async function enablePublicMintingExpectSuccess(sender: IKeyringPair, collectionId: number) {1128  await setMintPermissionExpectSuccess(sender, collectionId, true);1129}11301131export async function setMintPermissionExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {1132  await usingApi(async (api) => {1133    // Run the transaction1134    const tx = api.tx.unique.setMintPermission(collectionId, enabled);1135    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1136    const result = getCreateCollectionResult(events);1137    // tslint:disable-next-line:no-unused-expression1138    expect(result.success).to.be.false;1139  });1140}11411142export async function setChainLimitsExpectFailure(sender: IKeyringPair, limits: IChainLimits) {1143  await usingApi(async (api) => {1144    // Run the transaction1145    const tx = api.tx.unique.setChainLimits(limits);1146    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1147    const result = getCreateCollectionResult(events);1148    // tslint:disable-next-line:no-unused-expression1149    expect(result.success).to.be.false;1150  });1151}11521153export async function isAllowlisted(api: ApiPromise, collectionId: number, address: string | CrossAccountId) {1154  return (await api.rpc.unique.allowed(collectionId, normalizeAccountId(address))).toJSON();1155}11561157export async function addToAllowListExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId | CrossAccountId) {1158  await usingApi(async (api) => {1159    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.false;11601161    // Run the transaction1162    const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1163    const events = await submitTransactionAsync(sender, tx);1164    const result = getGenericResult(events);1165    expect(result.success).to.be.true;11661167    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;1168  });1169}11701171export async function addToAllowListAgainExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId) {1172  await usingApi(async (api) => {11731174    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;11751176    // Run the transaction1177    const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1178    const events = await submitTransactionAsync(sender, tx);1179    const result = getGenericResult(events);1180    expect(result.success).to.be.true;11811182    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;1183  });1184}11851186export async function addToAllowListExpectFail(sender: IKeyringPair, collectionId: number, address: string | AccountId) {1187  await usingApi(async (api) => {11881189    // Run the transaction1190    const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1191    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1192    const result = getGenericResult(events);11931194    // What to expect1195    // tslint:disable-next-line:no-unused-expression1196    expect(result.success).to.be.false;1197  });1198}11991200export async function removeFromAllowListExpectSuccess(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1201  await usingApi(async (api) => {1202    // Run the transaction1203    const tx = api.tx.unique.removeFromAllowList(collectionId, normalizeAccountId(address));1204    const events = await submitTransactionAsync(sender, tx);1205    const result = getGenericResult(events);12061207    // What to expect1208    // tslint:disable-next-line:no-unused-expression1209    expect(result.success).to.be.true;1210  });1211}12121213export async function removeFromAllowListExpectFailure(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1214  await usingApi(async (api) => {1215    // Run the transaction1216    const tx = api.tx.unique.removeFromAllowList(collectionId, normalizeAccountId(address));1217    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1218    const result = getGenericResult(events);12191220    // What to expect1221    // tslint:disable-next-line:no-unused-expression1222    expect(result.success).to.be.false;1223  });1224}12251226export const getDetailedCollectionInfo = async (api: ApiPromise, collectionId: number)1227  : Promise<UpDataStructsCollection | null> => {1228  return (await api.rpc.unique.collectionById(collectionId)).unwrapOr(null);1229};12301231export const getCreatedCollectionCount = async (api: ApiPromise): Promise<number> => {1232  // set global object - collectionsCount1233  return (await api.rpc.unique.collectionStats()).created.toNumber();1234};12351236export async function queryCollectionExpectSuccess(api: ApiPromise, collectionId: number): Promise<UpDataStructsCollection> {1237  return (await api.rpc.unique.collectionById(collectionId)).unwrap();1238}12391240export async function waitNewBlocks(blocksCount = 1): Promise<void> {1241  await usingApi(async (api) => {1242    const promise = new Promise<void>(async (resolve) => {1243      const unsubscribe = await api.rpc.chain.subscribeNewHeads(() => {1244        if (blocksCount > 0) {1245          blocksCount--;1246        } else {1247          unsubscribe();1248          resolve();1249        }1250      });1251    });1252    return promise;1253  });1254}