git.delta.rocks / unique-network / refs/commits / 386b66a0b7e2

difftreelog

test fix for new ouroboros behavior

Yaroslav Bolyukin2022-05-11parent: #2934957.patch.diff
in: master

4 files changed

modifiedcrates/struct-versioning/src/lib.rsdiffbeforeafterboth
--- a/crates/struct-versioning/src/lib.rs
+++ b/crates/struct-versioning/src/lib.rs
@@ -199,7 +199,7 @@
 	let mut out = Vec::new();
 	for version in attr.first_version..=attr.current_version {
 		let name = if version == attr.current_version {
-			input.ident.clone()	
+			input.ident.clone()
 		} else {
 			format_ident!("{}Version{}", &input.ident, version)
 		};
modifiedtests/src/nesting/unnest.test.tsdiffbeforeafterboth
--- a/tests/src/nesting/unnest.test.ts
+++ b/tests/src/nesting/unnest.test.ts
@@ -4,14 +4,13 @@
 import usingApi, {executeTransaction} from '../substrate/substrate-api';
 import {
   createCollectionExpectSuccess,
-  createItemExpectFailure, 
+  createItemExpectFailure,
   createItemExpectSuccess,
-  getTokenOwner, 
-  getTopmostTokenOwner, 
-  normalizeAccountId, 
-  setCollectionLimitsExpectSuccess, 
-  transferExpectFailure, 
-  transferExpectSuccess, 
+  getTokenOwner,
+  getTopmostTokenOwner,
+  normalizeAccountId,
+  setCollectionLimitsExpectSuccess,
+  transferExpectSuccess,
 } from '../util/helpers';
 import {IKeyringPair} from '@polkadot/types/types';
 
@@ -36,8 +35,8 @@
 
       // Unnest
       await expect(executeTransaction(
-        api, 
-        alice, 
+        api,
+        alice,
         api.tx.unique.transferFrom(normalizeAccountId(targetAddress), normalizeAccountId(alice), collection, nestedToken, 1),
       )).to.not.be.rejected;
       expect(await getTokenOwner(api, collection, nestedToken)).to.be.deep.equal({Substrate: alice.address});
@@ -45,8 +44,8 @@
       // Nest and burn
       await transferExpectSuccess(collection, nestedToken, alice, targetAddress);
       await expect(executeTransaction(
-        api, 
-        alice, 
+        api,
+        alice,
         api.tx.unique.burnFrom(collection, normalizeAccountId(alice.address), nestedToken, 1),
       )).to.not.be.rejected;
       await expect(getTokenOwner(api, collection, nestedToken)).to.be.rejected; // 'owner == null'
@@ -61,7 +60,7 @@
     alice = privateKey('//Alice');
     bob = privateKey('//Bob');
   });
-  
+
   it('Disallows a non-owner to unnest/burn a token', async () => {
     await usingApi(async api => {
       const collection = await createCollectionExpectSuccess({mode: {type: 'NFT'}});
@@ -74,8 +73,8 @@
 
       // Try to unnest
       await expect(executeTransaction(
-        api, 
-        bob, 
+        api,
+        bob,
         api.tx.unique.transferFrom(normalizeAccountId(targetAddress), normalizeAccountId(bob), collection, nestedToken, 1),
       )).to.be.rejectedWith(/^common\.ApprovedValueTooLow$/);
       //await transferFromExpectSuccess(collection, nestedToken, bob, targetAddress, {Substrate: bob.address});
@@ -83,14 +82,14 @@
 
       // Try to burn
       await expect(executeTransaction(
-        api, 
-        bob, 
+        api,
+        bob,
         api.tx.unique.burnFrom(collection, normalizeAccountId(bob.address), nestedToken, 1),
       )).to.not.be.rejectedWith(/^common\.ApprovedValueTooLow$/);
       expect(await getTokenOwner(api, collection, nestedToken)).to.be.deep.equal({Ethereum: tokenIdToAddress(collection, targetToken).toLowerCase()});
     });
   });
-  
+
   it('Disallows excessive token nesting', async () => {
     await usingApi(async api => {
       const collection = await createCollectionExpectSuccess({mode: {type: 'NFT'}});
@@ -108,23 +107,15 @@
   });
 
   // todo another test for creating excessive depth matryoshka with Ethereum, move this one to nest ^
-  
-  // Recursive nesting
-  it('Prevents Ouroboros-nested operations', async () => { 
-    await usingApi(async api => {
-      const collection = await createCollectionExpectSuccess({mode: {type: 'NFT'}});
-      await setCollectionLimitsExpectSuccess(alice, collection, {nestingRule: 'Owner'});
-      const targetToken = await createItemExpectSuccess(alice, collection, 'NFT');
 
-      // Create a nested token ouroboros
-      const nestedToken = await createItemExpectSuccess(alice, collection, 'NFT', {Ethereum: tokenIdToAddress(collection, targetToken)});
-      await transferExpectSuccess(collection, targetToken, alice, {Ethereum: tokenIdToAddress(collection, nestedToken)});
-
-      expect(await getTokenOwner(api, collection, nestedToken)).to.be.deep.equal({Ethereum: tokenIdToAddress(collection, targetToken).toLowerCase()});
+  // Recursive nesting
+  it('Prevents ouroboros creation', async () => {
+    const collection = await createCollectionExpectSuccess({mode: {type: 'NFT'}});
+    await setCollectionLimitsExpectSuccess(alice, collection, {nestingRule: 'Owner'});
+    const targetToken = await createItemExpectSuccess(alice, collection, 'NFT');
 
-      // Make sure the ouroboros is detected
-      await expect(getTopmostTokenOwner(api, collection, nestedToken)).to.be.rejected; // With(/^common\.DepthLimit$/);
-      // todo transferFrom, must exit with Ouroboros error
-    });
+    // Create a nested token ouroboros
+    const nestedToken = await createItemExpectSuccess(alice, collection, 'NFT', {Ethereum: tokenIdToAddress(collection, targetToken)});
+    expect(transferExpectSuccess(collection, targetToken, alice, {Ethereum: tokenIdToAddress(collection, nestedToken)})).to.be.rejectedWith(/^structure\.OuroborosDetected$/);
   });
-});
\ No newline at end of file
+});
modifiedtests/src/pallet-presence.test.tsdiffbeforeafterboth
--- a/tests/src/pallet-presence.test.ts
+++ b/tests/src/pallet-presence.test.ts
@@ -30,6 +30,7 @@
   'timestamp',
   'transactionpayment',
   'treasury',
+  'structure',
   'system',
   'vesting',
   'parachainsystem',
modifiedtests/src/util/helpers.tsdiffbeforeafterboth
before · tests/src/util/helpers.ts
1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617import '../interfaces/augment-api-rpc';18import '../interfaces/augment-api-query';19import {ApiPromise, Keyring} from '@polkadot/api';20import type {AccountId, EventRecord} from '@polkadot/types/interfaces';21import {IKeyringPair} from '@polkadot/types/types';22import {evmToAddress} from '@polkadot/util-crypto';23import BN from 'bn.js';24import chai from 'chai';25import chaiAsPromised from 'chai-as-promised';26import {alicesPublicKey} from '../accounts';27import privateKey from '../substrate/privateKey';28import {default as usingApi, submitTransactionAsync, submitTransactionExpectFailAsync} from '../substrate/substrate-api';29import {hexToStr, strToUTF16, utf16ToStr} from './util';30import {UpDataStructsRpcCollection} from '@polkadot/types/lookup';3132chai.use(chaiAsPromised);33const expect = chai.expect;3435export type CrossAccountId = {36  Substrate: string,37} | {38  Ethereum: string,39};4041export function normalizeAccountId(input: string | AccountId | CrossAccountId | IKeyringPair): CrossAccountId {42  if (typeof input === 'string') {43    if (input.length === 48 || input.length === 47) {44      return {Substrate: input};45    } else if (input.length === 42 && input.startsWith('0x')) {46      return {Ethereum: input.toLowerCase()};47    } else if (input.length === 40 && !input.startsWith('0x')) {48      return {Ethereum: '0x' + input.toLowerCase()};49    } else {50      throw new Error(`Unknown address format: "${input}"`);51    }52  }53  if ('address' in input) {54    return {Substrate: input.address};55  }56  if ('Ethereum' in input) {57    return {58      Ethereum: input.Ethereum.toLowerCase(),59    };60  } else if ('ethereum' in input) {61    return {62      Ethereum: (input as any).ethereum.toLowerCase(),63    };64  } else if ('Substrate' in input) {65    return input;66  } else if ('substrate' in input) {67    return {68      Substrate: (input as any).substrate,69    };70  }7172  // AccountId73  return {Substrate: input.toString()};74}75export function toSubstrateAddress(input: string | CrossAccountId | IKeyringPair): string {76  input = normalizeAccountId(input);77  if ('Substrate' in input) {78    return input.Substrate;79  } else {80    return evmToAddress(input.Ethereum);81  }82}8384export const U128_MAX = (1n << 128n) - 1n;8586const MICROUNIQUE = 1_000_000_000_000n;87const MILLIUNIQUE = 1_000n * MICROUNIQUE;88const CENTIUNIQUE = 10n * MILLIUNIQUE;89export const UNIQUE = 100n * CENTIUNIQUE;9091type GenericResult = {92  success: boolean,93};9495interface CreateCollectionResult {96  success: boolean;97  collectionId: number;98}99100interface CreateItemResult {101  success: boolean;102  collectionId: number;103  itemId: number;104  recipient?: CrossAccountId;105}106107interface TransferResult {108  success: boolean;109  collectionId: number;110  itemId: number;111  sender?: CrossAccountId;112  recipient?: CrossAccountId;113  value: bigint;114}115116interface IReFungibleOwner {117  fraction: BN;118  owner: number[];119}120121interface IGetMessage {122  checkMsgUnqMethod: string;123  checkMsgTrsMethod: string;124  checkMsgSysMethod: string;125}126127export interface IFungibleTokenDataType {128  value: number;129}130131export interface IChainLimits {132  collectionNumbersLimit: number;133  accountTokenOwnershipLimit: number;134  collectionsAdminsLimit: number;135  customDataLimit: number;136  nftSponsorTransferTimeout: number;137  fungibleSponsorTransferTimeout: number;138  refungibleSponsorTransferTimeout: number;139  offchainSchemaLimit: number;140  variableOnChainSchemaLimit: number;141  constOnChainSchemaLimit: number;142}143144export interface IReFungibleTokenDataType {145  owner: IReFungibleOwner[];146  constData: number[];147  variableData: number[];148}149150export function uniqueEventMessage(events: EventRecord[]): IGetMessage {151  let checkMsgUnqMethod = '';152  let checkMsgTrsMethod = '';153  let checkMsgSysMethod = '';154  events.forEach(({event: {method, section}}) => {155    if (section === 'common') {156      checkMsgUnqMethod = method;157    } else if (section === 'treasury') {158      checkMsgTrsMethod = method;159    } else if (section === 'system') {160      checkMsgSysMethod = method;161    } else { return null; }162  });163  const result: IGetMessage = {164    checkMsgUnqMethod,165    checkMsgTrsMethod,166    checkMsgSysMethod,167  };168  return result;169}170171export function getGenericResult(events: EventRecord[]): GenericResult {172  const result: GenericResult = {173    success: false,174  };175  events.forEach(({event: {method}}) => {176    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);177    if (method === 'ExtrinsicSuccess') {178      result.success = true;179    }180  });181  return result;182}183184185186export function getCreateCollectionResult(events: EventRecord[]): CreateCollectionResult {187  let success = false;188  let collectionId = 0;189  events.forEach(({event: {data, method, section}}) => {190    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);191    if (method == 'ExtrinsicSuccess') {192      success = true;193    } else if ((section == 'common') && (method == 'CollectionCreated')) {194      collectionId = parseInt(data[0].toString(), 10);195    }196  });197  const result: CreateCollectionResult = {198    success,199    collectionId,200  };201  return result;202}203204export function getCreateItemResult(events: EventRecord[]): CreateItemResult {205  let success = false;206  let collectionId = 0;207  let itemId = 0;208  let recipient;209  events.forEach(({event: {data, method, section}}) => {210    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);211    if (method == 'ExtrinsicSuccess') {212      success = true;213    } else if ((section == 'common') && (method == 'ItemCreated')) {214      collectionId = parseInt(data[0].toString(), 10);215      itemId = parseInt(data[1].toString(), 10);216      recipient = normalizeAccountId(data[2].toJSON() as any);217    }218  });219  const result: CreateItemResult = {220    success,221    collectionId,222    itemId,223    recipient,224  };225  return result;226}227228export function getTransferResult(events: EventRecord[]): TransferResult {229  const result: TransferResult = {230    success: false,231    collectionId: 0,232    itemId: 0,233    value: 0n,234  };235236  events.forEach(({event: {data, method, section}}) => {237    if (method === 'ExtrinsicSuccess') {238      result.success = true;239    } else if (section === 'common' && method === 'Transfer') {240      result.collectionId = +data[0].toString();241      result.itemId = +data[1].toString();242      result.sender = normalizeAccountId(data[2].toJSON() as any);243      result.recipient = normalizeAccountId(data[3].toJSON() as any);244      result.value = BigInt(data[4].toString());245    }246  });247248  return result;249}250251interface Nft {252  type: 'NFT';253}254255interface Fungible {256  type: 'Fungible';257  decimalPoints: number;258}259260interface ReFungible {261  type: 'ReFungible';262}263264type CollectionMode = Nft | Fungible | ReFungible;265266export type CreateCollectionParams = {267  mode: CollectionMode,268  name: string,269  description: string,270  tokenPrefix: string,271  schemaVersion: string,272};273274const defaultCreateCollectionParams: CreateCollectionParams = {275  description: 'description',276  mode: {type: 'NFT'},277  name: 'name',278  tokenPrefix: 'prefix',279  schemaVersion: 'ImageURL',280};281282export async function createCollectionExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {283  const {name, description, mode, tokenPrefix, schemaVersion} = {...defaultCreateCollectionParams, ...params};284285  let collectionId = 0;286  await usingApi(async (api) => {287    // Get number of collections before the transaction288    const collectionCountBefore = await getCreatedCollectionCount(api);289290    // Run the CreateCollection transaction291    const alicePrivateKey = privateKey('//Alice');292293    let modeprm = {};294    if (mode.type === 'NFT') {295      modeprm = {nft: null};296    } else if (mode.type === 'Fungible') {297      modeprm = {fungible: mode.decimalPoints};298    } else if (mode.type === 'ReFungible') {299      modeprm = {refungible: null};300    }301302    const tx = api.tx.unique.createCollectionEx({303      name: strToUTF16(name), 304      description: strToUTF16(description), 305      tokenPrefix: strToUTF16(tokenPrefix), 306      mode: modeprm as any,307      schemaVersion: schemaVersion,308    });309    const events = await submitTransactionAsync(alicePrivateKey, tx);310    const result = getCreateCollectionResult(events);311312    // Get number of collections after the transaction313    const collectionCountAfter = await getCreatedCollectionCount(api);314315    // Get the collection316    const collection = await queryCollectionExpectSuccess(api, result.collectionId);317318    // What to expect319    // tslint:disable-next-line:no-unused-expression320    expect(result.success).to.be.true;321    expect(result.collectionId).to.be.equal(collectionCountAfter);322    // tslint:disable-next-line:no-unused-expression323    expect(collection).to.be.not.null;324    expect(collectionCountAfter).to.be.equal(collectionCountBefore + 1, 'Error: NFT collection NOT created.');325    expect(collection.owner.toString()).to.be.equal(toSubstrateAddress(alicesPublicKey));326    expect(utf16ToStr(collection.name.toJSON() as any)).to.be.equal(name);327    expect(utf16ToStr(collection.description.toJSON() as any)).to.be.equal(description);328    expect(hexToStr(collection.tokenPrefix.toJSON())).to.be.equal(tokenPrefix);329330    collectionId = result.collectionId;331  });332333  return collectionId;334}335336export async function createCollectionExpectFailure(params: Partial<CreateCollectionParams> = {}) {337  const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};338339  let modeprm = {};340  if (mode.type === 'NFT') {341    modeprm = {nft: null};342  } else if (mode.type === 'Fungible') {343    modeprm = {fungible: mode.decimalPoints};344  } else if (mode.type === 'ReFungible') {345    modeprm = {refungible: null};346  }347348  await usingApi(async (api) => {349    // Get number of collections before the transaction350    const collectionCountBefore = await getCreatedCollectionCount(api);351352    // Run the CreateCollection transaction353    const alicePrivateKey = privateKey('//Alice');354    const tx = api.tx.unique.createCollectionEx({name: strToUTF16(name), description: strToUTF16(description), tokenPrefix: strToUTF16(tokenPrefix), mode: modeprm as any});355    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;356357    // Get number of collections after the transaction358    const collectionCountAfter = await getCreatedCollectionCount(api);359360    // What to expect361    expect(collectionCountAfter).to.be.equal(collectionCountBefore, 'Error: Collection with incorrect data created.');362  });363}364365export async function findUnusedAddress(api: ApiPromise, seedAddition = ''): Promise<IKeyringPair> {366  let bal = 0n;367  let unused;368  do {369    const randomSeed = 'seed' + Math.floor(Math.random() * Math.floor(10000)) + seedAddition;370    const keyring = new Keyring({type: 'sr25519'});371    unused = keyring.addFromUri(`//${randomSeed}`);372    bal = (await api.query.system.account(unused.address)).data.free.toBigInt();373  } while (bal !== 0n);374  return unused;375}376377export async function getAllowance(api: ApiPromise, collectionId: number, owner: CrossAccountId | string, approved: CrossAccountId | string, tokenId: number) {378  return (await api.rpc.unique.allowance(collectionId, normalizeAccountId(owner), normalizeAccountId(approved), tokenId)).toBigInt();379}380381export function findUnusedAddresses(api: ApiPromise, amount: number): Promise<IKeyringPair[]> {382  return Promise.all(new Array(amount).fill(null).map(() => findUnusedAddress(api, '_' + Date.now())));383}384385export async function findNotExistingCollection(api: ApiPromise): Promise<number> {386  const totalNumber = await getCreatedCollectionCount(api);387  const newCollection: number = totalNumber + 1;388  return newCollection;389}390391function getDestroyResult(events: EventRecord[]): boolean {392  let success = false;393  events.forEach(({event: {method}}) => {394    if (method == 'ExtrinsicSuccess') {395      success = true;396    }397  });398  return success;399}400401export async function destroyCollectionExpectFailure(collectionId: number, senderSeed = '//Alice') {402  await usingApi(async (api) => {403    // Run the DestroyCollection transaction404    const alicePrivateKey = privateKey(senderSeed);405    const tx = api.tx.unique.destroyCollection(collectionId);406    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;407  });408}409410export async function destroyCollectionExpectSuccess(collectionId: number, senderSeed = '//Alice') {411  await usingApi(async (api) => {412    // Run the DestroyCollection transaction413    const alicePrivateKey = privateKey(senderSeed);414    const tx = api.tx.unique.destroyCollection(collectionId);415    const events = await submitTransactionAsync(alicePrivateKey, tx);416    const result = getDestroyResult(events);417    expect(result).to.be.true;418419    // What to expect420    expect(await getDetailedCollectionInfo(api, collectionId)).to.be.null;421  });422}423424export async function setCollectionLimitsExpectSuccess(sender: IKeyringPair, collectionId: number, limits: any) {425  await usingApi(async (api) => {426    const tx = api.tx.unique.setCollectionLimits(collectionId, limits);427    const events = await submitTransactionAsync(sender, tx);428    const result = getGenericResult(events);429430    expect(result.success).to.be.true;431  });432}433434export async function setCollectionLimitsExpectFailure(sender: IKeyringPair, collectionId: number, limits: any) {435  await usingApi(async (api) => {436    const tx = api.tx.unique.setCollectionLimits(collectionId, limits);437    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;438    const result = getGenericResult(events);439440    expect(result.success).to.be.false;441  });442}443444export async function setCollectionSponsorExpectSuccess(collectionId: number, sponsor: string, sender = '//Alice') {445  await usingApi(async (api) => {446447    // Run the transaction448    const senderPrivateKey = privateKey(sender);449    const tx = api.tx.unique.setCollectionSponsor(collectionId, sponsor);450    const events = await submitTransactionAsync(senderPrivateKey, tx);451    const result = getGenericResult(events);452453    // Get the collection454    const collection = await queryCollectionExpectSuccess(api, collectionId);455456    // What to expect457    expect(result.success).to.be.true;458    expect(collection.sponsorship.toJSON()).to.deep.equal({459      unconfirmed: sponsor,460    });461  });462}463464export async function removeCollectionSponsorExpectSuccess(collectionId: number, sender = '//Alice') {465  await usingApi(async (api) => {466467    // Run the transaction468    const alicePrivateKey = privateKey(sender);469    const tx = api.tx.unique.removeCollectionSponsor(collectionId);470    const events = await submitTransactionAsync(alicePrivateKey, tx);471    const result = getGenericResult(events);472473    // Get the collection474    const collection = await queryCollectionExpectSuccess(api, collectionId);475476    // What to expect477    expect(result.success).to.be.true;478    expect(collection.sponsorship.toJSON()).to.be.deep.equal({disabled: null});479  });480}481482export async function removeCollectionSponsorExpectFailure(collectionId: number, senderSeed = '//Alice') {483  await usingApi(async (api) => {484485    // Run the transaction486    const alicePrivateKey = privateKey(senderSeed);487    const tx = api.tx.unique.removeCollectionSponsor(collectionId);488    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;489  });490}491492export async function setCollectionSponsorExpectFailure(collectionId: number, sponsor: string, senderSeed = '//Alice') {493  await usingApi(async (api) => {494495    // Run the transaction496    const alicePrivateKey = privateKey(senderSeed);497    const tx = api.tx.unique.setCollectionSponsor(collectionId, sponsor);498    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;499  });500}501502export async function confirmSponsorshipExpectSuccess(collectionId: number, senderSeed = '//Alice') {503  await usingApi(async (api) => {504505    // Run the transaction506    const sender = privateKey(senderSeed);507    const tx = api.tx.unique.confirmSponsorship(collectionId);508    const events = await submitTransactionAsync(sender, tx);509    const result = getGenericResult(events);510511    // Get the collection512    const collection = await queryCollectionExpectSuccess(api, collectionId);513514    // What to expect515    expect(result.success).to.be.true;516    expect(collection.sponsorship.toJSON()).to.be.deep.equal({517      confirmed: sender.address,518    });519  });520}521522523export async function confirmSponsorshipExpectFailure(collectionId: number, senderSeed = '//Alice') {524  await usingApi(async (api) => {525526    // Run the transaction527    const sender = privateKey(senderSeed);528    const tx = api.tx.unique.confirmSponsorship(collectionId);529    await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;530  });531}532533export async function setMetadataUpdatePermissionFlagExpectSuccess(sender: IKeyringPair, collectionId: number, flag: string) {534535  await usingApi(async (api) => {536    const tx = api.tx.unique.setMetaUpdatePermissionFlag(collectionId, flag as any);537    const events = await submitTransactionAsync(sender, tx);538    const result = getGenericResult(events);539540    expect(result.success).to.be.true;541  });542}543544export async function setMetadataUpdatePermissionFlagExpectFailure(sender: IKeyringPair, collectionId: number, flag: string) {545546  await usingApi(async (api) => {547    const tx = api.tx.unique.setMetaUpdatePermissionFlag(collectionId, flag as any);548    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;549    const result = getGenericResult(events);550551    expect(result.success).to.be.false;552  });553}554555export async function enableContractSponsoringExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {556  await usingApi(async (api) => {557    const tx = api.tx.unique.enableContractSponsoring(contractAddress, enable);558    const events = await submitTransactionAsync(sender, tx);559    const result = getGenericResult(events);560561    expect(result.success).to.be.true;562  });563}564565export async function enableContractSponsoringExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {566  await usingApi(async (api) => {567    const tx = api.tx.unique.enableContractSponsoring(contractAddress, enable);568    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;569    const result = getGenericResult(events);570571    expect(result.success).to.be.false;572  });573}574575export async function setTransferFlagExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {576577  await usingApi(async (api) => {578579    const tx = api.tx.unique.setTransfersEnabledFlag(collectionId, enabled);580    const events = await submitTransactionAsync(sender, tx);581    const result = getGenericResult(events);582583    expect(result.success).to.be.true;584  });585}586587export async function setTransferFlagExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {588589  await usingApi(async (api) => {590591    const tx = api.tx.unique.setTransfersEnabledFlag(collectionId, enabled);592    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;593    const result = getGenericResult(events);594595    expect(result.success).to.be.false;596  });597}598599export async function setContractSponsoringRateLimitExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {600  await usingApi(async (api) => {601    const tx = api.tx.unique.setContractSponsoringRateLimit(contractAddress, rateLimit);602    const events = await submitTransactionAsync(sender, tx);603    const result = getGenericResult(events);604605    expect(result.success).to.be.true;606  });607}608609export async function setContractSponsoringRateLimitExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {610  await usingApi(async (api) => {611    const tx = api.tx.unique.setContractSponsoringRateLimit(contractAddress, rateLimit);612    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;613    const result = getGenericResult(events);614615    expect(result.success).to.be.false;616  });617}618619export async function getNextSponsored(620  api: ApiPromise,621  collectionId: number,622  account: string | CrossAccountId,623  tokenId: number,624): Promise<number> {625  return Number((await api.rpc.unique.nextSponsored(collectionId, account, tokenId)).unwrapOr(-1));626}627628export async function toggleContractAllowlistExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, value = true) {629  await usingApi(async (api) => {630    const tx = api.tx.unique.toggleContractAllowList(contractAddress, value);631    const events = await submitTransactionAsync(sender, tx);632    const result = getGenericResult(events);633634    expect(result.success).to.be.true;635  });636}637638export async function isAllowlistedInContract(contractAddress: AccountId | string, user: string) {639  let allowlisted = false;640  await usingApi(async (api) => {641    allowlisted = (await api.query.unique.contractAllowList(contractAddress, user)).toJSON() as boolean;642  });643  return allowlisted;644}645646export async function addToContractAllowListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {647  await usingApi(async (api) => {648    const tx = api.tx.unique.addToContractAllowList(contractAddress.toString(), user.toString());649    const events = await submitTransactionAsync(sender, tx);650    const result = getGenericResult(events);651652    expect(result.success).to.be.true;653  });654}655656export async function removeFromContractAllowListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {657  await usingApi(async (api) => {658    const tx = api.tx.unique.removeFromContractAllowList(contractAddress.toString(), user.toString());659    const events = await submitTransactionAsync(sender, tx);660    const result = getGenericResult(events);661662    expect(result.success).to.be.true;663  });664}665666export async function removeFromContractAllowListExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {667  await usingApi(async (api) => {668    const tx = api.tx.unique.removeFromContractAllowList(contractAddress.toString(), user.toString());669    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;670    const result = getGenericResult(events);671672    expect(result.success).to.be.false;673  });674}675676export async function setVariableMetaDataExpectSuccess(sender: IKeyringPair, collectionId: number, itemId: number, data: number[]) {677  await usingApi(async (api) => {678    const tx = api.tx.unique.setVariableMetaData(collectionId, itemId, '0x' + Buffer.from(data).toString('hex'));679    const events = await submitTransactionAsync(sender, tx);680    const result = getGenericResult(events);681682    expect(result.success).to.be.true;683  });684}685686export async function setVariableMetaDataExpectFailure(sender: IKeyringPair, collectionId: number, itemId: number, data: number[]) {687  await usingApi(async (api) => {688    const tx = api.tx.unique.setVariableMetaData(collectionId, itemId, '0x' + Buffer.from(data).toString('hex'));689    await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;690  });691}692693export async function setOffchainSchemaExpectSuccess(sender: IKeyringPair, collectionId: number, data: number[]) {694  await usingApi(async (api) => {695    const tx = api.tx.unique.setOffchainSchema(collectionId, '0x' + Buffer.from(data).toString('hex'));696    const events = await submitTransactionAsync(sender, tx);697    const result = getGenericResult(events);698699    expect(result.success).to.be.true;700  });701}702703export async function setOffchainSchemaExpectFailure(sender: IKeyringPair, collectionId: number, data: number[]) {704  await usingApi(async (api) => {705    const tx = api.tx.unique.setOffchainSchema(collectionId, '0x' + Buffer.from(data).toString('hex'));706    await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;707  });708}709710export interface CreateFungibleData {711  readonly Value: bigint;712}713714export interface CreateReFungibleData { }715export interface CreateNftData { }716717export type CreateItemData = {718  NFT: CreateNftData;719} | {720  Fungible: CreateFungibleData;721} | {722  ReFungible: CreateReFungibleData;723};724725export async function burnItemExpectSuccess(sender: IKeyringPair, collectionId: number, tokenId: number, value = 1) {726  await usingApi(async (api) => {727    const balanceBefore = await getBalance(api, collectionId, normalizeAccountId(sender), tokenId);728    // if burning token by admin - use adminButnItemExpectSuccess729    expect(balanceBefore >= BigInt(value)).to.be.true;730731    const tx = api.tx.unique.burnItem(collectionId, tokenId, value);732    const events = await submitTransactionAsync(sender, tx);733    const result = getGenericResult(events);734    expect(result.success).to.be.true;735736    const balanceAfter = await getBalance(api, collectionId, normalizeAccountId(sender), tokenId);737    expect(balanceAfter + BigInt(value)).to.be.equal(balanceBefore);738  });739}740741export async function742approveExpectSuccess(743  collectionId: number,744  tokenId: number, owner: IKeyringPair, approved: CrossAccountId | string, amount: number | bigint = 1,745) {746  await usingApi(async (api: ApiPromise) => {747    const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);748    const events = await submitTransactionAsync(owner, approveUniqueTx);749    const result = getGenericResult(events);750    expect(result.success).to.be.true;751752    expect(await getAllowance(api, collectionId, owner.address, approved, tokenId)).to.be.equal(BigInt(amount));753  });754}755756export async function adminApproveFromExpectSuccess(757  collectionId: number,758  tokenId: number, admin: IKeyringPair, owner: CrossAccountId | string, approved: CrossAccountId | string, amount: number | bigint = 1,759) {760  await usingApi(async (api: ApiPromise) => {761    const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);762    const events = await submitTransactionAsync(admin, approveUniqueTx);763    const result = getGenericResult(events);764    expect(result.success).to.be.true;765766    expect(await getAllowance(api, collectionId, owner, approved, tokenId)).to.be.equal(BigInt(amount));767  });768}769770export async function771transferFromExpectSuccess(772  collectionId: number,773  tokenId: number,774  accountApproved: IKeyringPair,775  accountFrom: IKeyringPair | CrossAccountId,776  accountTo: IKeyringPair | CrossAccountId,777  value: number | bigint = 1,778  type = 'NFT',779) {780  await usingApi(async (api: ApiPromise) => {781    const from = normalizeAccountId(accountFrom);782    const to = normalizeAccountId(accountTo);783    let balanceBefore = 0n;784    if (type === 'Fungible') {785      balanceBefore = await getBalance(api, collectionId, to, tokenId);786    }787    const transferFromTx = api.tx.unique.transferFrom(normalizeAccountId(accountFrom), to, collectionId, tokenId, value);788    const events = await submitTransactionAsync(accountApproved, transferFromTx);789    const result = getCreateItemResult(events);790    // tslint:disable-next-line:no-unused-expression791    expect(result.success).to.be.true;792    if (type === 'NFT') {793      expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(to);794    }795    if (type === 'Fungible') {796      const balanceAfter = await getBalance(api, collectionId, to, tokenId);797      if (JSON.stringify(to) !== JSON.stringify(from)) {798        expect(balanceAfter - balanceBefore).to.be.equal(BigInt(value));799      } else {800        expect(balanceAfter).to.be.equal(balanceBefore);801      }802    }803    if (type === 'ReFungible') {804      expect(await getBalance(api, collectionId, to, tokenId)).to.be.equal(BigInt(value));805    }806  });807}808809export async function810transferFromExpectFail(811  collectionId: number,812  tokenId: number,813  accountApproved: IKeyringPair,814  accountFrom: IKeyringPair,815  accountTo: IKeyringPair,816  value: number | bigint = 1,817) {818  await usingApi(async (api: ApiPromise) => {819    const transferFromTx = api.tx.unique.transferFrom(normalizeAccountId(accountFrom.address), normalizeAccountId(accountTo.address), collectionId, tokenId, value);820    const events = await expect(submitTransactionExpectFailAsync(accountApproved, transferFromTx)).to.be.rejected;821    const result = getCreateCollectionResult(events);822    // tslint:disable-next-line:no-unused-expression823    expect(result.success).to.be.false;824  });825}826827/* eslint no-async-promise-executor: "off" */828async function getBlockNumber(api: ApiPromise): Promise<number> {829  return new Promise<number>(async (resolve) => {830    const unsubscribe = await api.rpc.chain.subscribeNewHeads((head) => {831      unsubscribe();832      resolve(head.number.toNumber());833    });834  });835}836837export async function addCollectionAdminExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | CrossAccountId) {838  await usingApi(async (api) => {839    const changeAdminTx = api.tx.unique.addCollectionAdmin(collectionId, normalizeAccountId(address));840    const events = await submitTransactionAsync(sender, changeAdminTx);841    const result = getCreateCollectionResult(events);842    expect(result.success).to.be.true;843  });844}845846export async function847getFreeBalance(account: IKeyringPair): Promise<bigint> {848  let balance = 0n;849  await usingApi(async (api) => {850    balance = BigInt((await api.query.system.account(account.address)).data.free.toString());851  });852853  return balance;854}855856export async function transferBalanceTo(api: ApiPromise, source: IKeyringPair, target: string, amount = 1000n * UNIQUE) {857  const tx = api.tx.balances.transfer(target, amount);858  const events = await submitTransactionAsync(source, tx);859  const result = getGenericResult(events);860  expect(result.success).to.be.true;861}862863export async function864scheduleTransferExpectSuccess(865  collectionId: number,866  tokenId: number,867  sender: IKeyringPair,868  recipient: IKeyringPair,869  value: number | bigint = 1,870  blockSchedule: number,871) {872  await usingApi(async (api: ApiPromise) => {873    const blockNumber: number | undefined = await getBlockNumber(api);874    const expectedBlockNumber = blockNumber + blockSchedule;875876    expect(blockNumber).to.be.greaterThan(0);877    const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient.address), collectionId, tokenId, value);878    const scheduleTx = api.tx.scheduler.schedule(expectedBlockNumber, null, 0, transferTx as any);879880    await submitTransactionAsync(sender, scheduleTx);881882    const recipientBalanceBefore = (await api.query.system.account(recipient.address)).data.free.toBigInt();883884    expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(sender.address));885886    // sleep for 4 blocks887    await waitNewBlocks(blockSchedule + 1);888889    const recipientBalanceAfter = (await api.query.system.account(recipient.address)).data.free.toBigInt();890891    expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(recipient.address));892    expect(recipientBalanceAfter).to.be.equal(recipientBalanceBefore);893  });894}895896897export async function898transferExpectSuccess(899  collectionId: number,900  tokenId: number,901  sender: IKeyringPair,902  recipient: IKeyringPair | CrossAccountId,903  value: number | bigint = 1,904  type = 'NFT',905) {906  await usingApi(async (api: ApiPromise) => {907    const from = normalizeAccountId(sender);908    const to = normalizeAccountId(recipient);909910    let balanceBefore = 0n;911    if (type === 'Fungible') {912      balanceBefore = await getBalance(api, collectionId, to, tokenId);913    }914    const transferTx = api.tx.unique.transfer(to, collectionId, tokenId, value);915    const events = await submitTransactionAsync(sender, transferTx);916    const result = getTransferResult(events);917    // tslint:disable-next-line:no-unused-expression918    expect(result.success).to.be.true;919    expect(result.collectionId).to.be.equal(collectionId);920    expect(result.itemId).to.be.equal(tokenId);921    expect(result.sender).to.be.deep.equal(normalizeAccountId(sender.address));922    expect(result.recipient).to.be.deep.equal(to);923    expect(result.value).to.be.equal(BigInt(value));924    if (type === 'NFT') {925      expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(to);926    }927    if (type === 'Fungible') {928      const balanceAfter = await getBalance(api, collectionId, to, tokenId);929      if (JSON.stringify(to) !== JSON.stringify(from)) {930        expect(balanceAfter - balanceBefore).to.be.equal(BigInt(value));931      } else {932        expect(balanceAfter).to.be.equal(balanceBefore);933      }934    }935    if (type === 'ReFungible') {936      expect(await getBalance(api, collectionId, to, tokenId) >= value).to.be.true;937    }938  });939}940941export async function942transferExpectFailure(943  collectionId: number,944  tokenId: number,945  sender: IKeyringPair,946  recipient: IKeyringPair | CrossAccountId,947  value: number | bigint = 1,948) {949  await usingApi(async (api: ApiPromise) => {950    const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient), collectionId, tokenId, value);951    const events = await expect(submitTransactionExpectFailAsync(sender, transferTx)).to.be.rejected;952    const result = getGenericResult(events);953    // if (events && Array.isArray(events)) {954    //   const result = getCreateCollectionResult(events);955    // tslint:disable-next-line:no-unused-expression956    expect(result.success).to.be.false;957    //}958  });959}960961export async function962approveExpectFail(963  collectionId: number,964  tokenId: number, owner: IKeyringPair, approved: IKeyringPair, amount: number | bigint = 1,965) {966  await usingApi(async (api: ApiPromise) => {967    const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved.address), collectionId, tokenId, amount);968    const events = await expect(submitTransactionExpectFailAsync(owner, approveUniqueTx)).to.be.rejected;969    const result = getCreateCollectionResult(events);970    // tslint:disable-next-line:no-unused-expression971    expect(result.success).to.be.false;972  });973}974975export async function getBalance(976  api: ApiPromise,977  collectionId: number,978  owner: string | CrossAccountId,979  token: number,980): Promise<bigint> {981  return (await api.rpc.unique.balance(collectionId, normalizeAccountId(owner), token)).toBigInt();982}983export async function getTokenOwner(984  api: ApiPromise,985  collectionId: number,986  token: number,987): Promise<CrossAccountId> {988  const owner = (await api.rpc.unique.tokenOwner(collectionId, token)).toJSON() as any;989  if (owner == null) throw new Error('owner == null');990  return normalizeAccountId(owner);991}992export async function getTopmostTokenOwner(993  api: ApiPromise,994  collectionId: number,995  token: number,996): Promise<CrossAccountId> {997  const owner = (await api.rpc.unique.topmostTokenOwner(collectionId, token)).toJSON() as any;998  if (owner == null) throw new Error('owner == null');999  return normalizeAccountId(owner);1000}1001export async function isTokenExists(1002  api: ApiPromise,1003  collectionId: number,1004  token: number,1005): Promise<boolean> {1006  return (await api.rpc.unique.tokenExists(collectionId, token)).toJSON();1007}1008export async function getLastTokenId(1009  api: ApiPromise,1010  collectionId: number,1011): Promise<number> {1012  return (await api.rpc.unique.lastTokenId(collectionId)).toJSON();1013}1014export async function getAdminList(1015  api: ApiPromise,1016  collectionId: number,1017): Promise<string[]> {1018  return (await api.rpc.unique.adminlist(collectionId)).toHuman() as any;1019}1020export async function getVariableMetadata(1021  api: ApiPromise,1022  collectionId: number,1023  tokenId: number,1024): Promise<number[]> {1025  return [...(await api.rpc.unique.variableMetadata(collectionId, tokenId))];1026}1027export async function getConstMetadata(1028  api: ApiPromise,1029  collectionId: number,1030  tokenId: number,1031): Promise<number[]> {1032  return [...(await api.rpc.unique.constMetadata(collectionId, tokenId))];1033}10341035export async function createFungibleItemExpectSuccess(1036  sender: IKeyringPair,1037  collectionId: number,1038  data: CreateFungibleData,1039  owner: CrossAccountId | string = sender.address,1040) {1041  return await usingApi(async (api) => {1042    const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), {Fungible: data});10431044    const events = await submitTransactionAsync(sender, tx);1045    const result = getCreateItemResult(events);10461047    expect(result.success).to.be.true;1048    return result.itemId;1049  });1050}10511052export async function createItemExpectSuccess(sender: IKeyringPair, collectionId: number, createMode: string, owner: CrossAccountId | string = sender.address) {1053  let newItemId = 0;1054  await usingApi(async (api) => {1055    const to = normalizeAccountId(owner);1056    const itemCountBefore = await getLastTokenId(api, collectionId);1057    const itemBalanceBefore = await getBalance(api, collectionId, to, newItemId);10581059    let tx;1060    if (createMode === 'Fungible') {1061      const createData = {fungible: {value: 10}};1062      tx = api.tx.unique.createItem(collectionId, to, createData as any);1063    } else if (createMode === 'ReFungible') {1064      const createData = {refungible: {const_data: [], variable_data: [], pieces: 100}};1065      tx = api.tx.unique.createItem(collectionId, to, createData as any);1066    } else {1067      const createData = {nft: {const_data: [], variable_data: []}};1068      tx = api.tx.unique.createItem(collectionId, to, createData as any);1069    }10701071    const events = await submitTransactionAsync(sender, tx);1072    const result = getCreateItemResult(events);10731074    const itemCountAfter = await getLastTokenId(api, collectionId);1075    const itemBalanceAfter = await getBalance(api, collectionId, to, newItemId);10761077    // What to expect1078    // tslint:disable-next-line:no-unused-expression1079    expect(result.success).to.be.true;1080    if (createMode === 'Fungible') {1081      expect(itemBalanceAfter - itemBalanceBefore).to.be.equal(10n);1082    } else {1083      expect(itemCountAfter).to.be.equal(itemCountBefore + 1);1084    }1085    expect(collectionId).to.be.equal(result.collectionId);1086    expect(itemCountAfter.toString()).to.be.equal(result.itemId.toString());1087    expect(to).to.be.deep.equal(result.recipient);1088    newItemId = result.itemId;1089  });1090  return newItemId;1091}10921093export async function createItemExpectFailure(sender: IKeyringPair, collectionId: number, createMode: string, owner: CrossAccountId | string = sender.address) {1094  await usingApi(async (api) => {1095    const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), createMode);10961097    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1098    const result = getCreateItemResult(events);10991100    expect(result.success).to.be.false;1101  });1102}11031104export async function setPublicAccessModeExpectSuccess(1105  sender: IKeyringPair, collectionId: number,1106  accessMode: 'Normal' | 'AllowList',1107) {1108  await usingApi(async (api) => {11091110    // Run the transaction1111    const tx = api.tx.unique.setPublicAccessMode(collectionId, accessMode);1112    const events = await submitTransactionAsync(sender, tx);1113    const result = getGenericResult(events);11141115    // Get the collection1116    const collection = await queryCollectionExpectSuccess(api, collectionId);11171118    // What to expect1119    // tslint:disable-next-line:no-unused-expression1120    expect(result.success).to.be.true;1121    expect(collection.access.toHuman()).to.be.equal(accessMode);1122  });1123}11241125export async function setPublicAccessModeExpectFail(1126  sender: IKeyringPair, collectionId: number,1127  accessMode: 'Normal' | 'AllowList',1128) {1129  await usingApi(async (api) => {11301131    // Run the transaction1132    const tx = api.tx.unique.setPublicAccessMode(collectionId, accessMode);1133    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1134    const result = getGenericResult(events);11351136    // What to expect1137    // tslint:disable-next-line:no-unused-expression1138    expect(result.success).to.be.false;1139  });1140}11411142export async function enableAllowListExpectSuccess(sender: IKeyringPair, collectionId: number) {1143  await setPublicAccessModeExpectSuccess(sender, collectionId, 'AllowList');1144}11451146export async function enableAllowListExpectFail(sender: IKeyringPair, collectionId: number) {1147  await setPublicAccessModeExpectFail(sender, collectionId, 'AllowList');1148}11491150export async function disableAllowListExpectSuccess(sender: IKeyringPair, collectionId: number) {1151  await setPublicAccessModeExpectSuccess(sender, collectionId, 'Normal');1152}11531154export async function setMintPermissionExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {1155  await usingApi(async (api) => {11561157    // Run the transaction1158    const tx = api.tx.unique.setMintPermission(collectionId, enabled);1159    const events = await submitTransactionAsync(sender, tx);1160    const result = getGenericResult(events);1161    expect(result.success).to.be.true;11621163    // Get the collection1164    const collection = await queryCollectionExpectSuccess(api, collectionId);11651166    expect(collection.mintMode.toHuman()).to.be.equal(enabled);1167  });1168}11691170export async function enablePublicMintingExpectSuccess(sender: IKeyringPair, collectionId: number) {1171  await setMintPermissionExpectSuccess(sender, collectionId, true);1172}11731174export async function setMintPermissionExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {1175  await usingApi(async (api) => {1176    // Run the transaction1177    const tx = api.tx.unique.setMintPermission(collectionId, enabled);1178    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1179    const result = getCreateCollectionResult(events);1180    // tslint:disable-next-line:no-unused-expression1181    expect(result.success).to.be.false;1182  });1183}11841185export async function setChainLimitsExpectFailure(sender: IKeyringPair, limits: IChainLimits) {1186  await usingApi(async (api) => {1187    // Run the transaction1188    const tx = api.tx.unique.setChainLimits(limits);1189    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1190    const result = getCreateCollectionResult(events);1191    // tslint:disable-next-line:no-unused-expression1192    expect(result.success).to.be.false;1193  });1194}11951196export async function isAllowlisted(api: ApiPromise, collectionId: number, address: string | CrossAccountId) {1197  return (await api.rpc.unique.allowed(collectionId, normalizeAccountId(address))).toJSON();1198}11991200export async function addToAllowListExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId | CrossAccountId) {1201  await usingApi(async (api) => {1202    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.false;12031204    // Run the transaction1205    const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1206    const events = await submitTransactionAsync(sender, tx);1207    const result = getGenericResult(events);1208    expect(result.success).to.be.true;12091210    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;1211  });1212}12131214export async function addToAllowListAgainExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId) {1215  await usingApi(async (api) => {12161217    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;12181219    // Run the transaction1220    const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1221    const events = await submitTransactionAsync(sender, tx);1222    const result = getGenericResult(events);1223    expect(result.success).to.be.true;12241225    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;1226  });1227}12281229export async function addToAllowListExpectFail(sender: IKeyringPair, collectionId: number, address: string | AccountId) {1230  await usingApi(async (api) => {12311232    // Run the transaction1233    const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1234    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1235    const result = getGenericResult(events);12361237    // What to expect1238    // tslint:disable-next-line:no-unused-expression1239    expect(result.success).to.be.false;1240  });1241}12421243export async function removeFromAllowListExpectSuccess(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1244  await usingApi(async (api) => {1245    // Run the transaction1246    const tx = api.tx.unique.removeFromAllowList(collectionId, normalizeAccountId(address));1247    const events = await submitTransactionAsync(sender, tx);1248    const result = getGenericResult(events);12491250    // What to expect1251    // tslint:disable-next-line:no-unused-expression1252    expect(result.success).to.be.true;1253  });1254}12551256export async function removeFromAllowListExpectFailure(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1257  await usingApi(async (api) => {1258    // Run the transaction1259    const tx = api.tx.unique.removeFromAllowList(collectionId, normalizeAccountId(address));1260    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1261    const result = getGenericResult(events);12621263    // What to expect1264    // tslint:disable-next-line:no-unused-expression1265    expect(result.success).to.be.false;1266  });1267}12681269export const getDetailedCollectionInfo = async (api: ApiPromise, collectionId: number)1270  : Promise<UpDataStructsRpcCollection | null> => {1271  return (await api.rpc.unique.collectionById(collectionId)).unwrapOr(null);1272};12731274export const getCreatedCollectionCount = async (api: ApiPromise): Promise<number> => {1275  // set global object - collectionsCount1276  return (await api.rpc.unique.collectionStats()).created.toNumber();1277};12781279export async function queryCollectionExpectSuccess(api: ApiPromise, collectionId: number): Promise<UpDataStructsRpcCollection> {1280  return (await api.rpc.unique.collectionById(collectionId)).unwrap();1281}12821283export async function waitNewBlocks(blocksCount = 1): Promise<void> {1284  await usingApi(async (api) => {1285    const promise = new Promise<void>(async (resolve) => {1286      const unsubscribe = await api.rpc.chain.subscribeNewHeads(() => {1287        if (blocksCount > 0) {1288          blocksCount--;1289        } else {1290          unsubscribe();1291          resolve();1292        }1293      });1294    });1295    return promise;1296  });1297}
after · tests/src/util/helpers.ts
1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617import '../interfaces/augment-api-rpc';18import '../interfaces/augment-api-query';19import {ApiPromise, Keyring} from '@polkadot/api';20import type {AccountId, EventRecord, Event} from '@polkadot/types/interfaces';21import {AnyTuple, IEvent, IKeyringPair} from '@polkadot/types/types';22import {evmToAddress} from '@polkadot/util-crypto';23import BN from 'bn.js';24import chai from 'chai';25import chaiAsPromised from 'chai-as-promised';26import {alicesPublicKey} from '../accounts';27import privateKey from '../substrate/privateKey';28import {default as usingApi, executeTransaction, submitTransactionAsync, submitTransactionExpectFailAsync} from '../substrate/substrate-api';29import {hexToStr, strToUTF16, utf16ToStr} from './util';30import {UpDataStructsRpcCollection} from '@polkadot/types/lookup';3132chai.use(chaiAsPromised);33const expect = chai.expect;3435export type CrossAccountId = {36  Substrate: string,37} | {38  Ethereum: string,39};4041export function normalizeAccountId(input: string | AccountId | CrossAccountId | IKeyringPair): CrossAccountId {42  if (typeof input === 'string') {43    if (input.length === 48 || input.length === 47) {44      return {Substrate: input};45    } else if (input.length === 42 && input.startsWith('0x')) {46      return {Ethereum: input.toLowerCase()};47    } else if (input.length === 40 && !input.startsWith('0x')) {48      return {Ethereum: '0x' + input.toLowerCase()};49    } else {50      throw new Error(`Unknown address format: "${input}"`);51    }52  }53  if ('address' in input) {54    return {Substrate: input.address};55  }56  if ('Ethereum' in input) {57    return {58      Ethereum: input.Ethereum.toLowerCase(),59    };60  } else if ('ethereum' in input) {61    return {62      Ethereum: (input as any).ethereum.toLowerCase(),63    };64  } else if ('Substrate' in input) {65    return input;66  } else if ('substrate' in input) {67    return {68      Substrate: (input as any).substrate,69    };70  }7172  // AccountId73  return {Substrate: input.toString()};74}75export function toSubstrateAddress(input: string | CrossAccountId | IKeyringPair): string {76  input = normalizeAccountId(input);77  if ('Substrate' in input) {78    return input.Substrate;79  } else {80    return evmToAddress(input.Ethereum);81  }82}8384export const U128_MAX = (1n << 128n) - 1n;8586const MICROUNIQUE = 1_000_000_000_000n;87const MILLIUNIQUE = 1_000n * MICROUNIQUE;88const CENTIUNIQUE = 10n * MILLIUNIQUE;89export const UNIQUE = 100n * CENTIUNIQUE;9091type GenericResult = {92  success: boolean,93};9495interface CreateCollectionResult {96  success: boolean;97  collectionId: number;98}99100interface CreateItemResult {101  success: boolean;102  collectionId: number;103  itemId: number;104  recipient?: CrossAccountId;105}106107interface TransferResult {108  collectionId: number;109  itemId: number;110  sender?: CrossAccountId;111  recipient?: CrossAccountId;112  value: bigint;113}114115interface IReFungibleOwner {116  fraction: BN;117  owner: number[];118}119120interface IGetMessage {121  checkMsgUnqMethod: string;122  checkMsgTrsMethod: string;123  checkMsgSysMethod: string;124}125126export interface IFungibleTokenDataType {127  value: number;128}129130export interface IChainLimits {131  collectionNumbersLimit: number;132  accountTokenOwnershipLimit: number;133  collectionsAdminsLimit: number;134  customDataLimit: number;135  nftSponsorTransferTimeout: number;136  fungibleSponsorTransferTimeout: number;137  refungibleSponsorTransferTimeout: number;138  offchainSchemaLimit: number;139  variableOnChainSchemaLimit: number;140  constOnChainSchemaLimit: number;141}142143export interface IReFungibleTokenDataType {144  owner: IReFungibleOwner[];145  constData: number[];146  variableData: number[];147}148149export function uniqueEventMessage(events: EventRecord[]): IGetMessage {150  let checkMsgUnqMethod = '';151  let checkMsgTrsMethod = '';152  let checkMsgSysMethod = '';153  events.forEach(({event: {method, section}}) => {154    if (section === 'common') {155      checkMsgUnqMethod = method;156    } else if (section === 'treasury') {157      checkMsgTrsMethod = method;158    } else if (section === 'system') {159      checkMsgSysMethod = method;160    } else { return null; }161  });162  const result: IGetMessage = {163    checkMsgUnqMethod,164    checkMsgTrsMethod,165    checkMsgSysMethod,166  };167  return result;168}169170export function getEvent<T extends Event>(events: EventRecord[], check: (event: IEvent<AnyTuple>) => event is T): T | undefined {171  const event = events.find(r => check(r.event));172  if (!event) return;173  return event.event as T;174}175176export function getGenericResult(events: EventRecord[]): GenericResult {177  const result: GenericResult = {178    success: false,179  };180  events.forEach(({event: {method}}) => {181    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);182    if (method === 'ExtrinsicSuccess') {183      result.success = true;184    }185  });186  return result;187}188189190191export function getCreateCollectionResult(events: EventRecord[]): CreateCollectionResult {192  let success = false;193  let collectionId = 0;194  events.forEach(({event: {data, method, section}}) => {195    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);196    if (method == 'ExtrinsicSuccess') {197      success = true;198    } else if ((section == 'common') && (method == 'CollectionCreated')) {199      collectionId = parseInt(data[0].toString(), 10);200    }201  });202  const result: CreateCollectionResult = {203    success,204    collectionId,205  };206  return result;207}208209export function getCreateItemResult(events: EventRecord[]): CreateItemResult {210  let success = false;211  let collectionId = 0;212  let itemId = 0;213  let recipient;214  events.forEach(({event: {data, method, section}}) => {215    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);216    if (method == 'ExtrinsicSuccess') {217      success = true;218    } else if ((section == 'common') && (method == 'ItemCreated')) {219      collectionId = parseInt(data[0].toString(), 10);220      itemId = parseInt(data[1].toString(), 10);221      recipient = normalizeAccountId(data[2].toJSON() as any);222    }223  });224  const result: CreateItemResult = {225    success,226    collectionId,227    itemId,228    recipient,229  };230  return result;231}232233export function getTransferResult(api: ApiPromise, events: EventRecord[]): TransferResult {234  for (const {event} of events) {235    if (api.events.common.Transfer.is(event)) {236      const [collection, token, sender, recipient, value] = event.data;237      return {238        collectionId: collection.toNumber(),239        itemId: token.toNumber(),240        sender: normalizeAccountId(sender.toJSON() as any),241        recipient: normalizeAccountId(recipient.toJSON() as any),242        value: value.toBigInt(),243      };244    }245  }246  throw new Error('no transfer event');247}248249interface Nft {250  type: 'NFT';251}252253interface Fungible {254  type: 'Fungible';255  decimalPoints: number;256}257258interface ReFungible {259  type: 'ReFungible';260}261262type CollectionMode = Nft | Fungible | ReFungible;263264export type CreateCollectionParams = {265  mode: CollectionMode,266  name: string,267  description: string,268  tokenPrefix: string,269  schemaVersion: string,270};271272const defaultCreateCollectionParams: CreateCollectionParams = {273  description: 'description',274  mode: {type: 'NFT'},275  name: 'name',276  tokenPrefix: 'prefix',277  schemaVersion: 'ImageURL',278};279280export async function createCollectionExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {281  const {name, description, mode, tokenPrefix, schemaVersion} = {...defaultCreateCollectionParams, ...params};282283  let collectionId = 0;284  await usingApi(async (api) => {285    // Get number of collections before the transaction286    const collectionCountBefore = await getCreatedCollectionCount(api);287288    // Run the CreateCollection transaction289    const alicePrivateKey = privateKey('//Alice');290291    let modeprm = {};292    if (mode.type === 'NFT') {293      modeprm = {nft: null};294    } else if (mode.type === 'Fungible') {295      modeprm = {fungible: mode.decimalPoints};296    } else if (mode.type === 'ReFungible') {297      modeprm = {refungible: null};298    }299300    const tx = api.tx.unique.createCollectionEx({301      name: strToUTF16(name),302      description: strToUTF16(description),303      tokenPrefix: strToUTF16(tokenPrefix),304      mode: modeprm as any,305      schemaVersion: schemaVersion,306    });307    const events = await submitTransactionAsync(alicePrivateKey, tx);308    const result = getCreateCollectionResult(events);309310    // Get number of collections after the transaction311    const collectionCountAfter = await getCreatedCollectionCount(api);312313    // Get the collection314    const collection = await queryCollectionExpectSuccess(api, result.collectionId);315316    // What to expect317    // tslint:disable-next-line:no-unused-expression318    expect(result.success).to.be.true;319    expect(result.collectionId).to.be.equal(collectionCountAfter);320    // tslint:disable-next-line:no-unused-expression321    expect(collection).to.be.not.null;322    expect(collectionCountAfter).to.be.equal(collectionCountBefore + 1, 'Error: NFT collection NOT created.');323    expect(collection.owner.toString()).to.be.equal(toSubstrateAddress(alicesPublicKey));324    expect(utf16ToStr(collection.name.toJSON() as any)).to.be.equal(name);325    expect(utf16ToStr(collection.description.toJSON() as any)).to.be.equal(description);326    expect(hexToStr(collection.tokenPrefix.toJSON())).to.be.equal(tokenPrefix);327328    collectionId = result.collectionId;329  });330331  return collectionId;332}333334export async function createCollectionExpectFailure(params: Partial<CreateCollectionParams> = {}) {335  const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};336337  let modeprm = {};338  if (mode.type === 'NFT') {339    modeprm = {nft: null};340  } else if (mode.type === 'Fungible') {341    modeprm = {fungible: mode.decimalPoints};342  } else if (mode.type === 'ReFungible') {343    modeprm = {refungible: null};344  }345346  await usingApi(async (api) => {347    // Get number of collections before the transaction348    const collectionCountBefore = await getCreatedCollectionCount(api);349350    // Run the CreateCollection transaction351    const alicePrivateKey = privateKey('//Alice');352    const tx = api.tx.unique.createCollectionEx({name: strToUTF16(name), description: strToUTF16(description), tokenPrefix: strToUTF16(tokenPrefix), mode: modeprm as any});353    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;354355    // Get number of collections after the transaction356    const collectionCountAfter = await getCreatedCollectionCount(api);357358    // What to expect359    expect(collectionCountAfter).to.be.equal(collectionCountBefore, 'Error: Collection with incorrect data created.');360  });361}362363export async function findUnusedAddress(api: ApiPromise, seedAddition = ''): Promise<IKeyringPair> {364  let bal = 0n;365  let unused;366  do {367    const randomSeed = 'seed' + Math.floor(Math.random() * Math.floor(10000)) + seedAddition;368    const keyring = new Keyring({type: 'sr25519'});369    unused = keyring.addFromUri(`//${randomSeed}`);370    bal = (await api.query.system.account(unused.address)).data.free.toBigInt();371  } while (bal !== 0n);372  return unused;373}374375export async function getAllowance(api: ApiPromise, collectionId: number, owner: CrossAccountId | string, approved: CrossAccountId | string, tokenId: number) {376  return (await api.rpc.unique.allowance(collectionId, normalizeAccountId(owner), normalizeAccountId(approved), tokenId)).toBigInt();377}378379export function findUnusedAddresses(api: ApiPromise, amount: number): Promise<IKeyringPair[]> {380  return Promise.all(new Array(amount).fill(null).map(() => findUnusedAddress(api, '_' + Date.now())));381}382383export async function findNotExistingCollection(api: ApiPromise): Promise<number> {384  const totalNumber = await getCreatedCollectionCount(api);385  const newCollection: number = totalNumber + 1;386  return newCollection;387}388389function getDestroyResult(events: EventRecord[]): boolean {390  let success = false;391  events.forEach(({event: {method}}) => {392    if (method == 'ExtrinsicSuccess') {393      success = true;394    }395  });396  return success;397}398399export async function destroyCollectionExpectFailure(collectionId: number, senderSeed = '//Alice') {400  await usingApi(async (api) => {401    // Run the DestroyCollection transaction402    const alicePrivateKey = privateKey(senderSeed);403    const tx = api.tx.unique.destroyCollection(collectionId);404    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;405  });406}407408export async function destroyCollectionExpectSuccess(collectionId: number, senderSeed = '//Alice') {409  await usingApi(async (api) => {410    // Run the DestroyCollection transaction411    const alicePrivateKey = privateKey(senderSeed);412    const tx = api.tx.unique.destroyCollection(collectionId);413    const events = await submitTransactionAsync(alicePrivateKey, tx);414    const result = getDestroyResult(events);415    expect(result).to.be.true;416417    // What to expect418    expect(await getDetailedCollectionInfo(api, collectionId)).to.be.null;419  });420}421422export async function setCollectionLimitsExpectSuccess(sender: IKeyringPair, collectionId: number, limits: any) {423  await usingApi(async (api) => {424    const tx = api.tx.unique.setCollectionLimits(collectionId, limits);425    const events = await submitTransactionAsync(sender, tx);426    const result = getGenericResult(events);427428    expect(result.success).to.be.true;429  });430}431432export async function setCollectionLimitsExpectFailure(sender: IKeyringPair, collectionId: number, limits: any) {433  await usingApi(async (api) => {434    const tx = api.tx.unique.setCollectionLimits(collectionId, limits);435    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;436    const result = getGenericResult(events);437438    expect(result.success).to.be.false;439  });440}441442export async function setCollectionSponsorExpectSuccess(collectionId: number, sponsor: string, sender = '//Alice') {443  await usingApi(async (api) => {444445    // Run the transaction446    const senderPrivateKey = privateKey(sender);447    const tx = api.tx.unique.setCollectionSponsor(collectionId, sponsor);448    const events = await submitTransactionAsync(senderPrivateKey, tx);449    const result = getGenericResult(events);450451    // Get the collection452    const collection = await queryCollectionExpectSuccess(api, collectionId);453454    // What to expect455    expect(result.success).to.be.true;456    expect(collection.sponsorship.toJSON()).to.deep.equal({457      unconfirmed: sponsor,458    });459  });460}461462export async function removeCollectionSponsorExpectSuccess(collectionId: number, sender = '//Alice') {463  await usingApi(async (api) => {464465    // Run the transaction466    const alicePrivateKey = privateKey(sender);467    const tx = api.tx.unique.removeCollectionSponsor(collectionId);468    const events = await submitTransactionAsync(alicePrivateKey, tx);469    const result = getGenericResult(events);470471    // Get the collection472    const collection = await queryCollectionExpectSuccess(api, collectionId);473474    // What to expect475    expect(result.success).to.be.true;476    expect(collection.sponsorship.toJSON()).to.be.deep.equal({disabled: null});477  });478}479480export async function removeCollectionSponsorExpectFailure(collectionId: number, senderSeed = '//Alice') {481  await usingApi(async (api) => {482483    // Run the transaction484    const alicePrivateKey = privateKey(senderSeed);485    const tx = api.tx.unique.removeCollectionSponsor(collectionId);486    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;487  });488}489490export async function setCollectionSponsorExpectFailure(collectionId: number, sponsor: string, senderSeed = '//Alice') {491  await usingApi(async (api) => {492493    // Run the transaction494    const alicePrivateKey = privateKey(senderSeed);495    const tx = api.tx.unique.setCollectionSponsor(collectionId, sponsor);496    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;497  });498}499500export async function confirmSponsorshipExpectSuccess(collectionId: number, senderSeed = '//Alice') {501  await usingApi(async (api) => {502503    // Run the transaction504    const sender = privateKey(senderSeed);505    const tx = api.tx.unique.confirmSponsorship(collectionId);506    const events = await submitTransactionAsync(sender, tx);507    const result = getGenericResult(events);508509    // Get the collection510    const collection = await queryCollectionExpectSuccess(api, collectionId);511512    // What to expect513    expect(result.success).to.be.true;514    expect(collection.sponsorship.toJSON()).to.be.deep.equal({515      confirmed: sender.address,516    });517  });518}519520521export async function confirmSponsorshipExpectFailure(collectionId: number, senderSeed = '//Alice') {522  await usingApi(async (api) => {523524    // Run the transaction525    const sender = privateKey(senderSeed);526    const tx = api.tx.unique.confirmSponsorship(collectionId);527    await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;528  });529}530531export async function setMetadataUpdatePermissionFlagExpectSuccess(sender: IKeyringPair, collectionId: number, flag: string) {532533  await usingApi(async (api) => {534    const tx = api.tx.unique.setMetaUpdatePermissionFlag(collectionId, flag as any);535    const events = await submitTransactionAsync(sender, tx);536    const result = getGenericResult(events);537538    expect(result.success).to.be.true;539  });540}541542export async function setMetadataUpdatePermissionFlagExpectFailure(sender: IKeyringPair, collectionId: number, flag: string) {543544  await usingApi(async (api) => {545    const tx = api.tx.unique.setMetaUpdatePermissionFlag(collectionId, flag as any);546    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;547    const result = getGenericResult(events);548549    expect(result.success).to.be.false;550  });551}552553export async function enableContractSponsoringExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {554  await usingApi(async (api) => {555    const tx = api.tx.unique.enableContractSponsoring(contractAddress, enable);556    const events = await submitTransactionAsync(sender, tx);557    const result = getGenericResult(events);558559    expect(result.success).to.be.true;560  });561}562563export async function enableContractSponsoringExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {564  await usingApi(async (api) => {565    const tx = api.tx.unique.enableContractSponsoring(contractAddress, enable);566    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;567    const result = getGenericResult(events);568569    expect(result.success).to.be.false;570  });571}572573export async function setTransferFlagExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {574575  await usingApi(async (api) => {576577    const tx = api.tx.unique.setTransfersEnabledFlag(collectionId, enabled);578    const events = await submitTransactionAsync(sender, tx);579    const result = getGenericResult(events);580581    expect(result.success).to.be.true;582  });583}584585export async function setTransferFlagExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {586587  await usingApi(async (api) => {588589    const tx = api.tx.unique.setTransfersEnabledFlag(collectionId, enabled);590    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;591    const result = getGenericResult(events);592593    expect(result.success).to.be.false;594  });595}596597export async function setContractSponsoringRateLimitExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {598  await usingApi(async (api) => {599    const tx = api.tx.unique.setContractSponsoringRateLimit(contractAddress, rateLimit);600    const events = await submitTransactionAsync(sender, tx);601    const result = getGenericResult(events);602603    expect(result.success).to.be.true;604  });605}606607export async function setContractSponsoringRateLimitExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {608  await usingApi(async (api) => {609    const tx = api.tx.unique.setContractSponsoringRateLimit(contractAddress, rateLimit);610    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;611    const result = getGenericResult(events);612613    expect(result.success).to.be.false;614  });615}616617export async function getNextSponsored(618  api: ApiPromise,619  collectionId: number,620  account: string | CrossAccountId,621  tokenId: number,622): Promise<number> {623  return Number((await api.rpc.unique.nextSponsored(collectionId, account, tokenId)).unwrapOr(-1));624}625626export async function toggleContractAllowlistExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, value = true) {627  await usingApi(async (api) => {628    const tx = api.tx.unique.toggleContractAllowList(contractAddress, value);629    const events = await submitTransactionAsync(sender, tx);630    const result = getGenericResult(events);631632    expect(result.success).to.be.true;633  });634}635636export async function isAllowlistedInContract(contractAddress: AccountId | string, user: string) {637  let allowlisted = false;638  await usingApi(async (api) => {639    allowlisted = (await api.query.unique.contractAllowList(contractAddress, user)).toJSON() as boolean;640  });641  return allowlisted;642}643644export async function addToContractAllowListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {645  await usingApi(async (api) => {646    const tx = api.tx.unique.addToContractAllowList(contractAddress.toString(), user.toString());647    const events = await submitTransactionAsync(sender, tx);648    const result = getGenericResult(events);649650    expect(result.success).to.be.true;651  });652}653654export async function removeFromContractAllowListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {655  await usingApi(async (api) => {656    const tx = api.tx.unique.removeFromContractAllowList(contractAddress.toString(), user.toString());657    const events = await submitTransactionAsync(sender, tx);658    const result = getGenericResult(events);659660    expect(result.success).to.be.true;661  });662}663664export async function removeFromContractAllowListExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {665  await usingApi(async (api) => {666    const tx = api.tx.unique.removeFromContractAllowList(contractAddress.toString(), user.toString());667    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;668    const result = getGenericResult(events);669670    expect(result.success).to.be.false;671  });672}673674export async function setVariableMetaDataExpectSuccess(sender: IKeyringPair, collectionId: number, itemId: number, data: number[]) {675  await usingApi(async (api) => {676    const tx = api.tx.unique.setVariableMetaData(collectionId, itemId, '0x' + Buffer.from(data).toString('hex'));677    const events = await submitTransactionAsync(sender, tx);678    const result = getGenericResult(events);679680    expect(result.success).to.be.true;681  });682}683684export async function setVariableMetaDataExpectFailure(sender: IKeyringPair, collectionId: number, itemId: number, data: number[]) {685  await usingApi(async (api) => {686    const tx = api.tx.unique.setVariableMetaData(collectionId, itemId, '0x' + Buffer.from(data).toString('hex'));687    await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;688  });689}690691export async function setOffchainSchemaExpectSuccess(sender: IKeyringPair, collectionId: number, data: number[]) {692  await usingApi(async (api) => {693    const tx = api.tx.unique.setOffchainSchema(collectionId, '0x' + Buffer.from(data).toString('hex'));694    const events = await submitTransactionAsync(sender, tx);695    const result = getGenericResult(events);696697    expect(result.success).to.be.true;698  });699}700701export async function setOffchainSchemaExpectFailure(sender: IKeyringPair, collectionId: number, data: number[]) {702  await usingApi(async (api) => {703    const tx = api.tx.unique.setOffchainSchema(collectionId, '0x' + Buffer.from(data).toString('hex'));704    await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;705  });706}707708export interface CreateFungibleData {709  readonly Value: bigint;710}711712export interface CreateReFungibleData { }713export interface CreateNftData { }714715export type CreateItemData = {716  NFT: CreateNftData;717} | {718  Fungible: CreateFungibleData;719} | {720  ReFungible: CreateReFungibleData;721};722723export async function burnItemExpectSuccess(sender: IKeyringPair, collectionId: number, tokenId: number, value = 1) {724  await usingApi(async (api) => {725    const balanceBefore = await getBalance(api, collectionId, normalizeAccountId(sender), tokenId);726    // if burning token by admin - use adminButnItemExpectSuccess727    expect(balanceBefore >= BigInt(value)).to.be.true;728729    const tx = api.tx.unique.burnItem(collectionId, tokenId, value);730    const events = await submitTransactionAsync(sender, tx);731    const result = getGenericResult(events);732    expect(result.success).to.be.true;733734    const balanceAfter = await getBalance(api, collectionId, normalizeAccountId(sender), tokenId);735    expect(balanceAfter + BigInt(value)).to.be.equal(balanceBefore);736  });737}738739export async function740approveExpectSuccess(741  collectionId: number,742  tokenId: number, owner: IKeyringPair, approved: CrossAccountId | string, amount: number | bigint = 1,743) {744  await usingApi(async (api: ApiPromise) => {745    const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);746    const events = await submitTransactionAsync(owner, approveUniqueTx);747    const result = getGenericResult(events);748    expect(result.success).to.be.true;749750    expect(await getAllowance(api, collectionId, owner.address, approved, tokenId)).to.be.equal(BigInt(amount));751  });752}753754export async function adminApproveFromExpectSuccess(755  collectionId: number,756  tokenId: number, admin: IKeyringPair, owner: CrossAccountId | string, approved: CrossAccountId | string, amount: number | bigint = 1,757) {758  await usingApi(async (api: ApiPromise) => {759    const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);760    const events = await submitTransactionAsync(admin, approveUniqueTx);761    const result = getGenericResult(events);762    expect(result.success).to.be.true;763764    expect(await getAllowance(api, collectionId, owner, approved, tokenId)).to.be.equal(BigInt(amount));765  });766}767768export async function769transferFromExpectSuccess(770  collectionId: number,771  tokenId: number,772  accountApproved: IKeyringPair,773  accountFrom: IKeyringPair | CrossAccountId,774  accountTo: IKeyringPair | CrossAccountId,775  value: number | bigint = 1,776  type = 'NFT',777) {778  await usingApi(async (api: ApiPromise) => {779    const from = normalizeAccountId(accountFrom);780    const to = normalizeAccountId(accountTo);781    let balanceBefore = 0n;782    if (type === 'Fungible') {783      balanceBefore = await getBalance(api, collectionId, to, tokenId);784    }785    const transferFromTx = api.tx.unique.transferFrom(normalizeAccountId(accountFrom), to, collectionId, tokenId, value);786    const events = await submitTransactionAsync(accountApproved, transferFromTx);787    const result = getCreateItemResult(events);788    // tslint:disable-next-line:no-unused-expression789    expect(result.success).to.be.true;790    if (type === 'NFT') {791      expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(to);792    }793    if (type === 'Fungible') {794      const balanceAfter = await getBalance(api, collectionId, to, tokenId);795      if (JSON.stringify(to) !== JSON.stringify(from)) {796        expect(balanceAfter - balanceBefore).to.be.equal(BigInt(value));797      } else {798        expect(balanceAfter).to.be.equal(balanceBefore);799      }800    }801    if (type === 'ReFungible') {802      expect(await getBalance(api, collectionId, to, tokenId)).to.be.equal(BigInt(value));803    }804  });805}806807export async function808transferFromExpectFail(809  collectionId: number,810  tokenId: number,811  accountApproved: IKeyringPair,812  accountFrom: IKeyringPair,813  accountTo: IKeyringPair,814  value: number | bigint = 1,815) {816  await usingApi(async (api: ApiPromise) => {817    const transferFromTx = api.tx.unique.transferFrom(normalizeAccountId(accountFrom.address), normalizeAccountId(accountTo.address), collectionId, tokenId, value);818    const events = await expect(submitTransactionExpectFailAsync(accountApproved, transferFromTx)).to.be.rejected;819    const result = getCreateCollectionResult(events);820    // tslint:disable-next-line:no-unused-expression821    expect(result.success).to.be.false;822  });823}824825/* eslint no-async-promise-executor: "off" */826async function getBlockNumber(api: ApiPromise): Promise<number> {827  return new Promise<number>(async (resolve) => {828    const unsubscribe = await api.rpc.chain.subscribeNewHeads((head) => {829      unsubscribe();830      resolve(head.number.toNumber());831    });832  });833}834835export async function addCollectionAdminExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | CrossAccountId) {836  await usingApi(async (api) => {837    const changeAdminTx = api.tx.unique.addCollectionAdmin(collectionId, normalizeAccountId(address));838    const events = await submitTransactionAsync(sender, changeAdminTx);839    const result = getCreateCollectionResult(events);840    expect(result.success).to.be.true;841  });842}843844export async function845getFreeBalance(account: IKeyringPair): Promise<bigint> {846  let balance = 0n;847  await usingApi(async (api) => {848    balance = BigInt((await api.query.system.account(account.address)).data.free.toString());849  });850851  return balance;852}853854export async function transferBalanceTo(api: ApiPromise, source: IKeyringPair, target: string, amount = 1000n * UNIQUE) {855  const tx = api.tx.balances.transfer(target, amount);856  const events = await submitTransactionAsync(source, tx);857  const result = getGenericResult(events);858  expect(result.success).to.be.true;859}860861export async function862scheduleTransferExpectSuccess(863  collectionId: number,864  tokenId: number,865  sender: IKeyringPair,866  recipient: IKeyringPair,867  value: number | bigint = 1,868  blockSchedule: number,869) {870  await usingApi(async (api: ApiPromise) => {871    const blockNumber: number | undefined = await getBlockNumber(api);872    const expectedBlockNumber = blockNumber + blockSchedule;873874    expect(blockNumber).to.be.greaterThan(0);875    const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient.address), collectionId, tokenId, value);876    const scheduleTx = api.tx.scheduler.schedule(expectedBlockNumber, null, 0, transferTx as any);877878    await submitTransactionAsync(sender, scheduleTx);879880    const recipientBalanceBefore = (await api.query.system.account(recipient.address)).data.free.toBigInt();881882    expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(sender.address));883884    // sleep for 4 blocks885    await waitNewBlocks(blockSchedule + 1);886887    const recipientBalanceAfter = (await api.query.system.account(recipient.address)).data.free.toBigInt();888889    expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(recipient.address));890    expect(recipientBalanceAfter).to.be.equal(recipientBalanceBefore);891  });892}893894895export async function896transferExpectSuccess(897  collectionId: number,898  tokenId: number,899  sender: IKeyringPair,900  recipient: IKeyringPair | CrossAccountId,901  value: number | bigint = 1,902  type = 'NFT',903) {904  await usingApi(async (api: ApiPromise) => {905    const from = normalizeAccountId(sender);906    const to = normalizeAccountId(recipient);907908    let balanceBefore = 0n;909    if (type === 'Fungible') {910      balanceBefore = await getBalance(api, collectionId, to, tokenId);911    }912    const transferTx = api.tx.unique.transfer(to, collectionId, tokenId, value);913    const events = await executeTransaction(api, sender, transferTx);914915    const result = getTransferResult(api, events);916    expect(result.collectionId).to.be.equal(collectionId);917    expect(result.itemId).to.be.equal(tokenId);918    expect(result.sender).to.be.deep.equal(normalizeAccountId(sender.address));919    expect(result.recipient).to.be.deep.equal(to);920    expect(result.value).to.be.equal(BigInt(value));921922    if (type === 'NFT') {923      expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(to);924    }925    if (type === 'Fungible') {926      const balanceAfter = await getBalance(api, collectionId, to, tokenId);927      if (JSON.stringify(to) !== JSON.stringify(from)) {928        expect(balanceAfter - balanceBefore).to.be.equal(BigInt(value));929      } else {930        expect(balanceAfter).to.be.equal(balanceBefore);931      }932    }933    if (type === 'ReFungible') {934      expect(await getBalance(api, collectionId, to, tokenId) >= value).to.be.true;935    }936  });937}938939export async function940transferExpectFailure(941  collectionId: number,942  tokenId: number,943  sender: IKeyringPair,944  recipient: IKeyringPair | CrossAccountId,945  value: number | bigint = 1,946) {947  await usingApi(async (api: ApiPromise) => {948    const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient), collectionId, tokenId, value);949    const events = await expect(submitTransactionExpectFailAsync(sender, transferTx)).to.be.rejected;950    const result = getGenericResult(events);951    // if (events && Array.isArray(events)) {952    //   const result = getCreateCollectionResult(events);953    // tslint:disable-next-line:no-unused-expression954    expect(result.success).to.be.false;955    //}956  });957}958959export async function960approveExpectFail(961  collectionId: number,962  tokenId: number, owner: IKeyringPair, approved: IKeyringPair, amount: number | bigint = 1,963) {964  await usingApi(async (api: ApiPromise) => {965    const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved.address), collectionId, tokenId, amount);966    const events = await expect(submitTransactionExpectFailAsync(owner, approveUniqueTx)).to.be.rejected;967    const result = getCreateCollectionResult(events);968    // tslint:disable-next-line:no-unused-expression969    expect(result.success).to.be.false;970  });971}972973export async function getBalance(974  api: ApiPromise,975  collectionId: number,976  owner: string | CrossAccountId,977  token: number,978): Promise<bigint> {979  return (await api.rpc.unique.balance(collectionId, normalizeAccountId(owner), token)).toBigInt();980}981export async function getTokenOwner(982  api: ApiPromise,983  collectionId: number,984  token: number,985): Promise<CrossAccountId> {986  const owner = (await api.rpc.unique.tokenOwner(collectionId, token)).toJSON() as any;987  if (owner == null) throw new Error('owner == null');988  return normalizeAccountId(owner);989}990export async function getTopmostTokenOwner(991  api: ApiPromise,992  collectionId: number,993  token: number,994): Promise<CrossAccountId> {995  const owner = (await api.rpc.unique.topmostTokenOwner(collectionId, token)).toJSON() as any;996  if (owner == null) throw new Error('owner == null');997  return normalizeAccountId(owner);998}999export async function isTokenExists(1000  api: ApiPromise,1001  collectionId: number,1002  token: number,1003): Promise<boolean> {1004  return (await api.rpc.unique.tokenExists(collectionId, token)).toJSON();1005}1006export async function getLastTokenId(1007  api: ApiPromise,1008  collectionId: number,1009): Promise<number> {1010  return (await api.rpc.unique.lastTokenId(collectionId)).toJSON();1011}1012export async function getAdminList(1013  api: ApiPromise,1014  collectionId: number,1015): Promise<string[]> {1016  return (await api.rpc.unique.adminlist(collectionId)).toHuman() as any;1017}1018export async function getVariableMetadata(1019  api: ApiPromise,1020  collectionId: number,1021  tokenId: number,1022): Promise<number[]> {1023  return [...(await api.rpc.unique.variableMetadata(collectionId, tokenId))];1024}1025export async function getConstMetadata(1026  api: ApiPromise,1027  collectionId: number,1028  tokenId: number,1029): Promise<number[]> {1030  return [...(await api.rpc.unique.constMetadata(collectionId, tokenId))];1031}10321033export async function createFungibleItemExpectSuccess(1034  sender: IKeyringPair,1035  collectionId: number,1036  data: CreateFungibleData,1037  owner: CrossAccountId | string = sender.address,1038) {1039  return await usingApi(async (api) => {1040    const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), {Fungible: data});10411042    const events = await submitTransactionAsync(sender, tx);1043    const result = getCreateItemResult(events);10441045    expect(result.success).to.be.true;1046    return result.itemId;1047  });1048}10491050export async function createItemExpectSuccess(sender: IKeyringPair, collectionId: number, createMode: string, owner: CrossAccountId | string = sender.address) {1051  let newItemId = 0;1052  await usingApi(async (api) => {1053    const to = normalizeAccountId(owner);1054    const itemCountBefore = await getLastTokenId(api, collectionId);1055    const itemBalanceBefore = await getBalance(api, collectionId, to, newItemId);10561057    let tx;1058    if (createMode === 'Fungible') {1059      const createData = {fungible: {value: 10}};1060      tx = api.tx.unique.createItem(collectionId, to, createData as any);1061    } else if (createMode === 'ReFungible') {1062      const createData = {refungible: {const_data: [], variable_data: [], pieces: 100}};1063      tx = api.tx.unique.createItem(collectionId, to, createData as any);1064    } else {1065      const createData = {nft: {const_data: [], variable_data: []}};1066      tx = api.tx.unique.createItem(collectionId, to, createData as any);1067    }10681069    const events = await submitTransactionAsync(sender, tx);1070    const result = getCreateItemResult(events);10711072    const itemCountAfter = await getLastTokenId(api, collectionId);1073    const itemBalanceAfter = await getBalance(api, collectionId, to, newItemId);10741075    // What to expect1076    // tslint:disable-next-line:no-unused-expression1077    expect(result.success).to.be.true;1078    if (createMode === 'Fungible') {1079      expect(itemBalanceAfter - itemBalanceBefore).to.be.equal(10n);1080    } else {1081      expect(itemCountAfter).to.be.equal(itemCountBefore + 1);1082    }1083    expect(collectionId).to.be.equal(result.collectionId);1084    expect(itemCountAfter.toString()).to.be.equal(result.itemId.toString());1085    expect(to).to.be.deep.equal(result.recipient);1086    newItemId = result.itemId;1087  });1088  return newItemId;1089}10901091export async function createItemExpectFailure(sender: IKeyringPair, collectionId: number, createMode: string, owner: CrossAccountId | string = sender.address) {1092  await usingApi(async (api) => {1093    const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), createMode);10941095    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1096    const result = getCreateItemResult(events);10971098    expect(result.success).to.be.false;1099  });1100}11011102export async function setPublicAccessModeExpectSuccess(1103  sender: IKeyringPair, collectionId: number,1104  accessMode: 'Normal' | 'AllowList',1105) {1106  await usingApi(async (api) => {11071108    // Run the transaction1109    const tx = api.tx.unique.setPublicAccessMode(collectionId, accessMode);1110    const events = await submitTransactionAsync(sender, tx);1111    const result = getGenericResult(events);11121113    // Get the collection1114    const collection = await queryCollectionExpectSuccess(api, collectionId);11151116    // What to expect1117    // tslint:disable-next-line:no-unused-expression1118    expect(result.success).to.be.true;1119    expect(collection.access.toHuman()).to.be.equal(accessMode);1120  });1121}11221123export async function setPublicAccessModeExpectFail(1124  sender: IKeyringPair, collectionId: number,1125  accessMode: 'Normal' | 'AllowList',1126) {1127  await usingApi(async (api) => {11281129    // Run the transaction1130    const tx = api.tx.unique.setPublicAccessMode(collectionId, accessMode);1131    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1132    const result = getGenericResult(events);11331134    // What to expect1135    // tslint:disable-next-line:no-unused-expression1136    expect(result.success).to.be.false;1137  });1138}11391140export async function enableAllowListExpectSuccess(sender: IKeyringPair, collectionId: number) {1141  await setPublicAccessModeExpectSuccess(sender, collectionId, 'AllowList');1142}11431144export async function enableAllowListExpectFail(sender: IKeyringPair, collectionId: number) {1145  await setPublicAccessModeExpectFail(sender, collectionId, 'AllowList');1146}11471148export async function disableAllowListExpectSuccess(sender: IKeyringPair, collectionId: number) {1149  await setPublicAccessModeExpectSuccess(sender, collectionId, 'Normal');1150}11511152export async function setMintPermissionExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {1153  await usingApi(async (api) => {11541155    // Run the transaction1156    const tx = api.tx.unique.setMintPermission(collectionId, enabled);1157    const events = await submitTransactionAsync(sender, tx);1158    const result = getGenericResult(events);1159    expect(result.success).to.be.true;11601161    // Get the collection1162    const collection = await queryCollectionExpectSuccess(api, collectionId);11631164    expect(collection.mintMode.toHuman()).to.be.equal(enabled);1165  });1166}11671168export async function enablePublicMintingExpectSuccess(sender: IKeyringPair, collectionId: number) {1169  await setMintPermissionExpectSuccess(sender, collectionId, true);1170}11711172export async function setMintPermissionExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {1173  await usingApi(async (api) => {1174    // Run the transaction1175    const tx = api.tx.unique.setMintPermission(collectionId, enabled);1176    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1177    const result = getCreateCollectionResult(events);1178    // tslint:disable-next-line:no-unused-expression1179    expect(result.success).to.be.false;1180  });1181}11821183export async function setChainLimitsExpectFailure(sender: IKeyringPair, limits: IChainLimits) {1184  await usingApi(async (api) => {1185    // Run the transaction1186    const tx = api.tx.unique.setChainLimits(limits);1187    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1188    const result = getCreateCollectionResult(events);1189    // tslint:disable-next-line:no-unused-expression1190    expect(result.success).to.be.false;1191  });1192}11931194export async function isAllowlisted(api: ApiPromise, collectionId: number, address: string | CrossAccountId) {1195  return (await api.rpc.unique.allowed(collectionId, normalizeAccountId(address))).toJSON();1196}11971198export async function addToAllowListExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId | CrossAccountId) {1199  await usingApi(async (api) => {1200    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.false;12011202    // Run the transaction1203    const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1204    const events = await submitTransactionAsync(sender, tx);1205    const result = getGenericResult(events);1206    expect(result.success).to.be.true;12071208    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;1209  });1210}12111212export async function addToAllowListAgainExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId) {1213  await usingApi(async (api) => {12141215    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;12161217    // Run the transaction1218    const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1219    const events = await submitTransactionAsync(sender, tx);1220    const result = getGenericResult(events);1221    expect(result.success).to.be.true;12221223    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;1224  });1225}12261227export async function addToAllowListExpectFail(sender: IKeyringPair, collectionId: number, address: string | AccountId) {1228  await usingApi(async (api) => {12291230    // Run the transaction1231    const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1232    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1233    const result = getGenericResult(events);12341235    // What to expect1236    // tslint:disable-next-line:no-unused-expression1237    expect(result.success).to.be.false;1238  });1239}12401241export async function removeFromAllowListExpectSuccess(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1242  await usingApi(async (api) => {1243    // Run the transaction1244    const tx = api.tx.unique.removeFromAllowList(collectionId, normalizeAccountId(address));1245    const events = await submitTransactionAsync(sender, tx);1246    const result = getGenericResult(events);12471248    // What to expect1249    // tslint:disable-next-line:no-unused-expression1250    expect(result.success).to.be.true;1251  });1252}12531254export async function removeFromAllowListExpectFailure(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1255  await usingApi(async (api) => {1256    // Run the transaction1257    const tx = api.tx.unique.removeFromAllowList(collectionId, normalizeAccountId(address));1258    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1259    const result = getGenericResult(events);12601261    // What to expect1262    // tslint:disable-next-line:no-unused-expression1263    expect(result.success).to.be.false;1264  });1265}12661267export const getDetailedCollectionInfo = async (api: ApiPromise, collectionId: number)1268  : Promise<UpDataStructsRpcCollection | null> => {1269  return (await api.rpc.unique.collectionById(collectionId)).unwrapOr(null);1270};12711272export const getCreatedCollectionCount = async (api: ApiPromise): Promise<number> => {1273  // set global object - collectionsCount1274  return (await api.rpc.unique.collectionStats()).created.toNumber();1275};12761277export async function queryCollectionExpectSuccess(api: ApiPromise, collectionId: number): Promise<UpDataStructsRpcCollection> {1278  return (await api.rpc.unique.collectionById(collectionId)).unwrap();1279}12801281export async function waitNewBlocks(blocksCount = 1): Promise<void> {1282  await usingApi(async (api) => {1283    const promise = new Promise<void>(async (resolve) => {1284      const unsubscribe = await api.rpc.chain.subscribeNewHeads(() => {1285        if (blocksCount > 0) {1286          blocksCount--;1287        } else {1288          unsubscribe();1289          resolve();1290        }1291      });1292    });1293    return promise;1294  });1295}