git.delta.rocks / unique-network / refs/commits / 0cb5e99ca2ae

difftreelog

draft: scheduler tx fees test

Daniel Shiposha2022-09-07parent: #d979915.patch.diff
in: master

4 files changed

modifiedruntime/common/scheduler.rsdiffbeforeafterboth
--- a/runtime/common/scheduler.rs
+++ b/runtime/common/scheduler.rs
@@ -24,11 +24,14 @@
 	transaction_validity::TransactionValidityError,
 	DispatchErrorWithPostInfo, DispatchError,
 };
-use crate::{Runtime, Call, Origin, Balances, ChargeTransactionPayment};
+use crate::{Runtime, Call, Origin, Balances};
 use up_common::types::{AccountId, Balance};
 use fp_self_contained::SelfContainedCall;
 use pallet_unique_scheduler::DispatchCall;
+use pallet_transaction_payment::ChargeTransactionPayment;
 
+type SponsorshipChargeTransactionPayment = pallet_charge_transaction::ChargeTransactionPayment<Runtime>;
+
 /// The SignedExtension to the basic transaction logic.
 pub type SignedExtraScheduler = (
 	frame_system::CheckSpecVersion<Runtime>,
@@ -36,6 +39,7 @@
 	frame_system::CheckEra<Runtime>,
 	frame_system::CheckNonce<Runtime>,
 	frame_system::CheckWeight<Runtime>,
+	ChargeTransactionPayment::<Runtime>,
 );
 
 fn get_signed_extras(from: <Runtime as frame_system::Config>::AccountId) -> SignedExtraScheduler {
@@ -47,8 +51,7 @@
 			from,
 		)),
 		frame_system::CheckWeight::<Runtime>::new(),
-		// sponsoring transaction logic
-		// pallet_charge_transaction::ChargeTransactionPayment::<Runtime>::new(0),
+		ChargeTransactionPayment::<Runtime>::from(0),
 	)
 }
 
@@ -100,7 +103,7 @@
 		count: u32,
 	) -> Result<(), DispatchError> {
 		let dispatch_info = call.get_dispatch_info();
-		let weight: Balance = ChargeTransactionPayment::traditional_fee(0, &dispatch_info, 0)
+		let weight: Balance = SponsorshipChargeTransactionPayment::traditional_fee(0, &dispatch_info, 0)
 			.saturating_mul(count.into());
 
 		<Balances as NamedReservableCurrency<AccountId>>::reserve_named(
@@ -116,7 +119,7 @@
 		call: <T as pallet_unique_scheduler::Config>::Call,
 	) -> Result<u128, DispatchError> {
 		let dispatch_info = call.get_dispatch_info();
-		let weight: Balance = ChargeTransactionPayment::traditional_fee(0, &dispatch_info, 0);
+		let weight: Balance = SponsorshipChargeTransactionPayment::traditional_fee(0, &dispatch_info, 0);
 		Ok(
 			<Balances as NamedReservableCurrency<AccountId>>::unreserve_named(
 				&id,
modifiedtests/src/.outdated/eth/scheduling.test.tsdiffbeforeafterboth
--- a/tests/src/.outdated/eth/scheduling.test.ts
+++ b/tests/src/.outdated/eth/scheduling.test.ts
@@ -16,7 +16,7 @@
 
 import {expect} from 'chai';
 import {createEthAccountWithBalance, deployFlipper, GAS_ARGS, itWeb3, subToEth, transferBalanceToEth} from '../../deprecated-helpers/eth/helpers';
-import {scheduleExpectSuccess, waitNewBlocks, requirePallets, Pallets} from '../../deprecated-helpers/helpers';
+import {makeScheduledId, scheduleAfter, waitNewBlocks, requirePallets, Pallets} from '../../deprecated-helpers/helpers';
 
 // TODO mrshiposha update this test in #581
 describe.skip('Scheduing EVM smart contracts', () => {
@@ -25,6 +25,7 @@
   });
 
   itWeb3('Successfully schedules and periodically executes an EVM contract', async ({api, web3, privateKeyWrapper}) => {
+    const scheduledId = await makeScheduledId();
     const deployer = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
     const flipper = await deployFlipper(web3, deployer);
     const initialValue = await flipper.methods.getValue().call();
@@ -45,8 +46,17 @@
       );
       const waitForBlocks = 4;
       const periodBlocks = 2;
+      const repetitions = 2;
 
-      await scheduleExpectSuccess(tx, alice, waitForBlocks, '0x' + '0'.repeat(32), periodBlocks, 2);
+      await expect(scheduleAfter(
+        api,
+        tx,
+        alice,
+        waitForBlocks,
+        scheduledId,
+        periodBlocks,
+        repetitions,
+      )).to.not.be.rejected;
       expect(await flipper.methods.getValue().call()).to.be.equal(initialValue);
       
       await waitNewBlocks(waitForBlocks - 1);
modifiedtests/src/.outdated/scheduler.test.tsdiffbeforeafterboth
--- a/tests/src/.outdated/scheduler.test.ts
+++ b/tests/src/.outdated/scheduler.test.ts
@@ -33,6 +33,7 @@
   enablePublicMintingExpectSuccess,
   addToAllowListExpectSuccess,
   waitNewBlocks,
+  makeScheduledId,
   normalizeAccountId,
   getTokenOwner,
   getGenericResult,
@@ -45,19 +46,12 @@
   requirePallets,
   Pallets,
 } from '../deprecated-helpers/helpers';
-import {IKeyringPair} from '@polkadot/types/types';
+import {IKeyringPair, SignatureOptions} from '@polkadot/types/types';
 import {ApiPromise} from '@polkadot/api';
+import {objectSpread} from '@polkadot/util';
 
 chai.use(chaiAsPromised);
-
-const scheduledIdBase: string = '0x' + '0'.repeat(31);
-let scheduledIdSlider = 0;
 
-// Loop scheduledId around 10. Unless there are concurrent tasks with long periods/repetitions, tests' tasks' ids shouldn't ovelap.
-function makeScheduledId(): string {
-  return scheduledIdBase + ((scheduledIdSlider++) % 10);
-}
-
 // Check that there are no failing Dispatched events in the block
 function checkForFailedSchedulerEvents(api: ApiPromise, events: any[]) {
   return new Promise((res, rej) => {
@@ -78,6 +72,13 @@
   });
 }
 
+function makeSignOptions(api: ApiPromise): SignatureOptions {
+  return objectSpread(
+    {blockHash: api.genesisHash, genesisHash: api.genesisHash},
+    {runtimeVersion: api.runtimeVersion, signedExtensions: api.registry.signedExtensions},
+  );
+}
+
 describe('Scheduling token and balance transfers', () => {
   let alice: IKeyringPair;
   let bob: IKeyringPair;
@@ -96,20 +97,22 @@
     await usingApi(async api => {
       const collectionId = await createCollectionExpectSuccess();
       const tokenId = await createItemExpectSuccess(alice, collectionId, 'NFT');
+      const scheduledId = await makeScheduledId();
 
-      await scheduleTransferAndWaitExpectSuccess(api, collectionId, tokenId, alice, bob, 1, 4, makeScheduledId());
+      await scheduleTransferAndWaitExpectSuccess(api, collectionId, tokenId, alice, bob, 1, 4, scheduledId);
     });
   });
 
   it('Can transfer funds periodically', async () => {
     await usingApi(async api => {
+      const scheduledId = await makeScheduledId();
       const waitForBlocks = 1;
       const period = 2;
       const repetitions = 2;
 
       const amount = 1n * UNIQUE;
 
-      await scheduleTransferFundsExpectSuccess(api, amount, alice, bob, waitForBlocks, makeScheduledId(), period, repetitions);
+      await scheduleTransferFundsExpectSuccess(api, amount, alice, bob, waitForBlocks, scheduledId, period, repetitions);
       const bobsBalanceBefore = await getFreeBalance(bob);
 
       await waitNewBlocks(waitForBlocks + 1);
@@ -134,7 +137,7 @@
     await usingApi(async api => {
       const collectionId = await createCollectionExpectSuccess();
       const tokenId = await createItemExpectSuccess(alice, collectionId, 'NFT');
-      const scheduledId = makeScheduledId();
+      const scheduledId = await makeScheduledId();
       const waitForBlocks = 4;
 
       const amount = 1;
@@ -154,7 +157,7 @@
       const period = 3;
       const repetitions = 2;
 
-      const scheduledId = makeScheduledId();
+      const scheduledId = await makeScheduledId();
       const amount = 1n * UNIQUE;
 
       const bobsBalanceBefore = await getFreeBalance(bob);
@@ -184,10 +187,8 @@
     await requirePallets(this, [Pallets.TestUtils]);
 
     await usingApi(async api => {
-      const scheduledId = makeScheduledId();
+      const scheduledId = await makeScheduledId();
       const waitForBlocks = 4;
-      const period = null;
-      const priority = 0;
 
       const initTestVal = 42;
       const changedTestVal = 111;
@@ -197,17 +198,15 @@
 
       const changeErrTx = api.tx.testUtils.setTestValueAndRollback(changedTestVal);
 
-      const scheduleTx = api.tx.scheduler.scheduleNamedAfter(
+      await expect(scheduleAfter(
+        api,
+        changeErrTx,
+        alice,
+        waitForBlocks,
         scheduledId,
-        waitForBlocks, 
-        period,
-        priority, 
-        {Value: changeErrTx as any},
-      );
-
-      await submitTransactionAsync(alice, scheduleTx);
+      )).to.not.be.rejected;
 
-      await waitNewBlocks(waitForBlocks);
+      await waitNewBlocks(waitForBlocks + 1);
 
       const testVal = (await api.query.testUtils.testValue()).toNumber();
       expect(testVal, 'The test value should NOT be commited')
@@ -216,18 +215,30 @@
     });
   });
 
-  it('Scheduled tasks should take some fees', async function() {
+  it.only('Scheduled tasks should take some fees', async function() {
     await requirePallets(this, [Pallets.TestUtils]);
 
     await usingApi(async api => {
-      const scheduledId = makeScheduledId();
-      const waitForBlocks = 10;
+      const scheduledId = await makeScheduledId();
+      const waitForBlocks = 8;
       const period = 2;
-      const repetitions = 1;
+      const repetitions = 2;
 
-      const dummyTxFeeAmount = 100_000_000;
+      const dummyTx = api.tx.testUtils.justTakeFee();
+      const expectedFee = (await dummyTx.paymentInfo(alice)).partialFee.toBigInt();
+      const expFee = (await api.rpc.payment.queryFeeDetails(dummyTx.toHex())).inclusionFee.unwrap().toHuman();
+
+      console.log('>>>>>> expFee = ' + JSON.stringify(expFee));
+
+      // const collectionCreate = api.tx.unique.createCollectionEx({
+      //   name: 0,
+      //   tokenPrefix: 0xfaf,
+      // });
 
-      const dummyTx = api.tx.testUtils.justTakeFee();
+      // const options = makeSignOptions(api);
+      // const signed = collectionCreate.sign(alice, options);
+      // const expFee2 = (await api.rpc.payment.queryFeeDetails(signed.toHex())).inclusionFee.unwrap().toHuman();
+      // console.log('!!!!!!!!!!!! expFee2 = ' + JSON.stringify(expFee2));
 
       await expect(scheduleAfter(
         api,
@@ -239,10 +250,12 @@
         repetitions,
       )).to.not.be.rejected;
 
+      await waitNewBlocks(1);
+
       const aliceInitBalance = await getFreeBalance(alice);
       let diff;
 
-      await waitNewBlocks(waitForBlocks + 1);
+      await waitNewBlocks(waitForBlocks);
 
       const aliceBalanceAfterFirst = await getFreeBalance(alice);
       expect(
@@ -251,7 +264,7 @@
       ).to.be.true;
 
       diff = aliceInitBalance - aliceBalanceAfterFirst;
-      expect(diff).to.be.equal(dummyTxFeeAmount, 'Scheduled task should take the right amount of fees');
+      expect(diff).to.be.equal(expectedFee, 'Scheduled task should take the right amount of fees');
 
       await waitNewBlocks(period);
 
@@ -262,14 +275,14 @@
       ).to.be.true;
 
       diff = aliceBalanceAfterFirst - aliceBalanceAfterSecond;
-      expect(diff).to.be.equal(dummyTxFeeAmount, 'Scheduled task should take the right amount of fees');
+      expect(diff).to.be.equal(expectedFee, 'Scheduled task should take the right amount of fees');
     });
   });
 
   // FIXME What purpose of this test?
   it.skip('Can schedule a scheduled operation of canceling the scheduled operation', async () => {
     await usingApi(async api => {
-      const scheduledId = makeScheduledId();
+      const scheduledId = await makeScheduledId();
 
       const waitForBlocks = 2;
       const period = 3;
@@ -323,7 +336,7 @@
     await usingApi(async api => {
       const collectionId = await createCollectionExpectSuccess();
       const tokenId = await createItemExpectSuccess(alice, collectionId, 'NFT');
-      const scheduledId = makeScheduledId();
+      const scheduledId = await makeScheduledId();
       const waitForBlocks = 4;
       const amount = 1;
 
@@ -338,7 +351,7 @@
 
       const bobsBalanceBefore = await getFreeBalance(bob);
 
-      await waitNewBlocks(waitForBlocks);
+      await waitNewBlocks(waitForBlocks + 1);
 
       expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(bob.address));
       expect(bobsBalanceBefore).to.be.equal(await getFreeBalance(bob));
@@ -347,7 +360,7 @@
 
   it("Can't cancel an operation which is not scheduled", async () => {
     await usingApi(async api => {
-      const scheduledId = makeScheduledId();
+      const scheduledId = await makeScheduledId();
       await expect(cancelScheduled(api, alice, scheduledId)).to.be.rejectedWith(/scheduler\.NotFound/);
     });
   });
@@ -356,7 +369,7 @@
     await usingApi(async api => {
       const collectionId = await createCollectionExpectSuccess();
       const tokenId = await createItemExpectSuccess(alice, collectionId, 'NFT');
-      const scheduledId = makeScheduledId();
+      const scheduledId = await makeScheduledId();
       const waitForBlocks = 8;
 
       const amount = 1;
@@ -364,7 +377,7 @@
       await scheduleTransferExpectSuccess(api, collectionId, tokenId, alice, bob, amount, waitForBlocks, scheduledId);
       await expect(cancelScheduled(api, bob, scheduledId)).to.be.rejectedWith(/BadOrigin/);
 
-      await waitNewBlocks(waitForBlocks);
+      await waitNewBlocks(waitForBlocks + 1);
 
       expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(bob.address));
     });
@@ -389,12 +402,13 @@
     await confirmSponsorshipExpectSuccess(collectionId, '//Bob');
 
     await usingApi(async api => {
+      const scheduledId = await makeScheduledId();
       const tokenId = await createItemExpectSuccess(alice, collectionId, 'NFT', alice.address);
 
       const bobBalanceBefore = await getFreeBalance(bob);
       const waitForBlocks = 4;
       // no need to wait to check, fees must be deducted on scheduling, immediately
-      await scheduleTransferExpectSuccess(api, collectionId, tokenId, alice, bob, 0, waitForBlocks, makeScheduledId());
+      await scheduleTransferExpectSuccess(api, collectionId, tokenId, alice, bob, 0, waitForBlocks, scheduledId);
       const bobBalanceAfter = await getFreeBalance(bob);
       // expect(aliceBalanceAfter == aliceBalanceBefore).to.be.true;
       expect(bobBalanceAfter < bobBalanceBefore).to.be.true;
@@ -420,10 +434,11 @@
 
       // Mint a fresh NFT
       const tokenId = await createItemExpectSuccess(zeroBalance, collectionId, 'NFT');
+      const scheduledId = await makeScheduledId();
 
       // Schedule transfer of the NFT a few blocks ahead
       const waitForBlocks = 5;
-      await scheduleTransferExpectSuccess(api, collectionId, tokenId, zeroBalance, alice, 1, waitForBlocks, makeScheduledId());
+      await scheduleTransferExpectSuccess(api, collectionId, tokenId, zeroBalance, alice, 1, waitForBlocks, scheduledId);
 
       // Get rid of the account's funds before the scheduled transaction takes place
       const balanceTx2 = api.tx.balances.transfer(alice.address, UNIQUE * 68n / 100n);
@@ -452,10 +467,11 @@
       await setCollectionSponsorExpectSuccess(collectionId, zeroBalance.address);
       await confirmSponsorshipByKeyExpectSuccess(collectionId, zeroBalance);
 
+      const scheduledId = await makeScheduledId();
       const tokenId = await createItemExpectSuccess(alice, collectionId, 'NFT', alice.address);
 
       const waitForBlocks = 5;
-      await scheduleTransferExpectSuccess(api, collectionId, tokenId, alice, zeroBalance, 1, waitForBlocks, makeScheduledId());
+      await scheduleTransferExpectSuccess(api, collectionId, tokenId, alice, zeroBalance, 1, waitForBlocks, scheduledId);
 
       const emptyBalanceSponsorTx = api.tx.balances.setBalance(zeroBalance.address, 0, 0);
       const sudoTx = api.tx.sudo.sudo(emptyBalanceSponsorTx as any);
@@ -484,13 +500,14 @@
 
       const createData = {nft: {const_data: [], variable_data: []}};
       const creationTx = api.tx.unique.createItem(collectionId, normalizeAccountId(zeroBalance), createData as any);
+      const scheduledId = await makeScheduledId();
 
       /*const badTransaction = async function () {
         await submitTransactionExpectFailAsync(zeroBalance, zeroToAlice);
       };
       await expect(badTransaction()).to.be.rejectedWith('Inability to pay some fees');*/
 
-      await expect(scheduleAfter(api, creationTx, zeroBalance, 3, makeScheduledId(), 1, 3)).to.be.rejectedWith(/Inability to pay some fees/);
+      await expect(scheduleAfter(api, creationTx, zeroBalance, 3, scheduledId, 1, 3)).to.be.rejectedWith(/Inability to pay some fees/);
 
       expect(await getFreeBalance(bob)).to.be.equal(bobBalanceBefore);
     });
modifiedtests/src/deprecated-helpers/helpers.tsdiffbeforeafterboth
before · tests/src/deprecated-helpers/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, BlockNumber} from '@polkadot/types/interfaces';21import type {GenericEventData} from '@polkadot/types';22import {AnyTuple, IEvent, IKeyringPair} from '@polkadot/types/types';23import {evmToAddress} from '@polkadot/util-crypto';24import {AnyNumber} from '@polkadot/types-codec/types';25import BN from 'bn.js';26import chai from 'chai';27import chaiAsPromised from 'chai-as-promised';28import {default as usingApi, executeTransaction, submitTransactionAsync, submitTransactionExpectFailAsync} from '../substrate/substrate-api';29import {hexToStr, strToUTF16, utf16ToStr} from './util';30import {UpDataStructsRpcCollection, UpDataStructsCreateItemData, UpDataStructsProperty} from '@polkadot/types/lookup';31import {UpDataStructsTokenChild} from '../interfaces';32import {Context} from 'mocha';3334chai.use(chaiAsPromised);35const expect = chai.expect;3637export type CrossAccountId = {38  Substrate: string,39} | {40  Ethereum: string,41};424344export enum Pallets {45  Inflation = 'inflation',46  RmrkCore = 'rmrkcore',47  RmrkEquip = 'rmrkequip',48  ReFungible = 'refungible',49  Fungible = 'fungible',50  NFT = 'nonfungible',51  Scheduler = 'scheduler',52  AppPromotion = 'apppromotion',53  TestUtils = 'testutils',54}5556export async function isUnique(): Promise<boolean> {57  return usingApi(async api => {58    const chain = await api.rpc.system.chain();5960    return chain.eq('UNIQUE');61  });62}6364export async function isQuartz(): Promise<boolean> {65  return usingApi(async api => {66    const chain = await api.rpc.system.chain();6768    return chain.eq('QUARTZ');69  });70}7172let modulesNames: any;73export function getModuleNames(api: ApiPromise): string[] {74  if (typeof modulesNames === 'undefined')75    modulesNames = api.runtimeMetadata.asLatest.pallets.map(m => m.name.toString().toLowerCase());76  return modulesNames;77}7879export async function missingRequiredPallets(requiredPallets: string[]): Promise<string[]> {80  return await usingApi(async api => {81    const pallets = getModuleNames(api);8283    return requiredPallets.filter(p => !pallets.includes(p));84  });85}8687export async function checkPalletsPresence(requiredPallets: string[]): Promise<boolean> {88  return (await missingRequiredPallets(requiredPallets)).length == 0;89}9091export async function requirePallets(mocha: Context, requiredPallets: string[]) {92  const missingPallets = await missingRequiredPallets(requiredPallets);9394  if (missingPallets.length > 0) {95    const skippingTestMsg = `\tSkipping test "${mocha.test?.title}".`;96    const missingPalletsMsg = `\tThe following pallets are missing:\n\t- ${missingPallets.join('\n\t- ')}`;97    const skipMsg = `${skippingTestMsg}\n${missingPalletsMsg}`;9899    console.error('\x1b[38:5:208m%s\x1b[0m', skipMsg);100101    mocha.skip();102  }103}104105export function bigIntToSub(api: ApiPromise, number: bigint) {106  return api.registry.createType('AccountId', '0x' + number.toString(16).padStart(64, '0')).toJSON();107}108109export function bigIntToDecimals(number: bigint, decimals = 18): string {110  const numberStr = number.toString();111  const dotPos = numberStr.length - decimals;112113  if (dotPos <= 0) {114    return '0.' + '0'.repeat(Math.abs(dotPos)) + numberStr;115  } else {116    const intPart = numberStr.substring(0, dotPos);117    const fractPart = numberStr.substring(dotPos);118    return intPart + '.' + fractPart;119  }120}121122export function normalizeAccountId(input: string | AccountId | CrossAccountId | IKeyringPair): CrossAccountId {123  if (typeof input === 'string') {124    if (input.length >= 47) {125      return {Substrate: input};126    } else if (input.length === 42 && input.startsWith('0x')) {127      return {Ethereum: input.toLowerCase()};128    } else if (input.length === 40 && !input.startsWith('0x')) {129      return {Ethereum: '0x' + input.toLowerCase()};130    } else {131      throw new Error(`Unknown address format: "${input}"`);132    }133  }134  if ('address' in input) {135    return {Substrate: input.address};136  }137  if ('Ethereum' in input) {138    return {139      Ethereum: input.Ethereum.toLowerCase(),140    };141  } else if ('ethereum' in input) {142    return {143      Ethereum: (input as any).ethereum.toLowerCase(),144    };145  } else if ('Substrate' in input) {146    return input;147  } else if ('substrate' in input) {148    return {149      Substrate: (input as any).substrate,150    };151  }152153  // AccountId154  return {Substrate: input.toString()};155}156export function toSubstrateAddress(input: string | CrossAccountId | IKeyringPair): string {157  input = normalizeAccountId(input);158  if ('Substrate' in input) {159    return input.Substrate;160  } else {161    return evmToAddress(input.Ethereum);162  }163}164165export const U128_MAX = (1n << 128n) - 1n;166167const MICROUNIQUE = 1_000_000_000_000n;168const MILLIUNIQUE = 1_000n * MICROUNIQUE;169const CENTIUNIQUE = 10n * MILLIUNIQUE;170export const UNIQUE = 100n * CENTIUNIQUE;171172interface GenericResult<T> {173  success: boolean;174  data: T | null;175}176177interface CreateCollectionResult {178  success: boolean;179  collectionId: number;180}181182interface CreateItemResult {183  success: boolean;184  collectionId: number;185  itemId: number;186  recipient?: CrossAccountId;187  amount?: number;188}189190interface DestroyItemResult {191  success: boolean;192  collectionId: number;193  itemId: number;194  owner: CrossAccountId;195  amount: number;196}197198interface TransferResult {199  collectionId: number;200  itemId: number;201  sender?: CrossAccountId;202  recipient?: CrossAccountId;203  value: bigint;204}205206interface IReFungibleOwner {207  fraction: BN;208  owner: number[];209}210211interface IGetMessage {212  checkMsgUnqMethod: string;213  checkMsgTrsMethod: string;214  checkMsgSysMethod: string;215}216217export interface IFungibleTokenDataType {218  value: number;219}220221export interface IChainLimits {222  collectionNumbersLimit: number;223  accountTokenOwnershipLimit: number;224  collectionsAdminsLimit: number;225  customDataLimit: number;226  nftSponsorTransferTimeout: number;227  fungibleSponsorTransferTimeout: number;228  refungibleSponsorTransferTimeout: number;229  //offchainSchemaLimit: number;230  //constOnChainSchemaLimit: number;231}232233export interface IReFungibleTokenDataType {234  owner: IReFungibleOwner[];235}236237export function uniqueEventMessage(events: EventRecord[]): IGetMessage {238  let checkMsgUnqMethod = '';239  let checkMsgTrsMethod = '';240  let checkMsgSysMethod = '';241  events.forEach(({event: {method, section}}) => {242    if (section === 'common') {243      checkMsgUnqMethod = method;244    } else if (section === 'treasury') {245      checkMsgTrsMethod = method;246    } else if (section === 'system') {247      checkMsgSysMethod = method;248    } else { return null; }249  });250  const result: IGetMessage = {251    checkMsgUnqMethod,252    checkMsgTrsMethod,253    checkMsgSysMethod,254  };255  return result;256}257258export function getEvent<T extends Event>(events: EventRecord[], check: (event: IEvent<AnyTuple>) => event is T): T | undefined {259  const event = events.find(r => check(r.event));260  if (!event) return;261  return event.event as T;262}263264export function getGenericResult<T>(events: EventRecord[]): GenericResult<T>;265export function getGenericResult<T>(266  events: EventRecord[],267  expectSection: string,268  expectMethod: string,269  extractAction: (data: GenericEventData) => T270): GenericResult<T>;271272export function getGenericResult<T>(273  events: EventRecord[],274  expectSection?: string,275  expectMethod?: string,276  extractAction?: (data: GenericEventData) => T,277): GenericResult<T> {278  let success = false;279  let successData = null;280281  events.forEach(({event: {data, method, section}}) => {282    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);283    if (method === 'ExtrinsicSuccess') {284      success = true;285    } else if ((expectSection == section) && (expectMethod == method)) {286      successData = extractAction!(data as any);287    }288  });289290  const result: GenericResult<T> = {291    success,292    data: successData,293  };294  return result;295}296297export function getCreateCollectionResult(events: EventRecord[]): CreateCollectionResult {298  const genericResult = getGenericResult(events, 'common', 'CollectionCreated', (data) => parseInt(data[0].toString(), 10));299  const result: CreateCollectionResult = {300    success: genericResult.success,301    collectionId: genericResult.data ?? 0,302  };303  return result;304}305306export function getCreateItemsResult(events: EventRecord[]): CreateItemResult[] {307  const results: CreateItemResult[] = [];308309  const genericResult = getGenericResult<CreateItemResult[]>(events, 'common', 'ItemCreated', (data) => {310    const collectionId = parseInt(data[0].toString(), 10);311    const itemId = parseInt(data[1].toString(), 10);312    const recipient = normalizeAccountId(data[2].toJSON() as any);313    const amount = parseInt(data[3].toString(), 10);314315    const itemRes: CreateItemResult = {316      success: true,317      collectionId,318      itemId,319      recipient,320      amount,321    };322323    results.push(itemRes);324    return results;325  });326327  if (!genericResult.success) return [];328  return results;329}330331export function getCreateItemResult(events: EventRecord[]): CreateItemResult {332  const genericResult = getGenericResult(events, 'common', 'ItemCreated', (data) => data.map(function(value) { return value.toJSON(); }));333334  if (genericResult.data == null)335    return {336      success: genericResult.success,337      collectionId: 0,338      itemId: 0,339      amount: 0,340    };341  else342    return {343      success: genericResult.success,344      collectionId: genericResult.data[0] as number,345      itemId: genericResult.data[1] as number,346      recipient: normalizeAccountId(genericResult.data![2] as any),347      amount: genericResult.data[3] as number,348    };349}350351export function getDestroyItemsResult(events: EventRecord[]): DestroyItemResult[] {352  const results: DestroyItemResult[] = [];353354  const genericResult = getGenericResult<DestroyItemResult[]>(events, 'common', 'ItemDestroyed', (data) => {355    const collectionId = parseInt(data[0].toString(), 10);356    const itemId = parseInt(data[1].toString(), 10);357    const owner = normalizeAccountId(data[2].toJSON() as any);358    const amount = parseInt(data[3].toString(), 10);359360    const itemRes: DestroyItemResult = {361      success: true,362      collectionId,363      itemId,364      owner,365      amount,366    };367368    results.push(itemRes);369    return results;370  });371372  if (!genericResult.success) return [];373  return results;374}375376export function getTransferResult(api: ApiPromise, events: EventRecord[]): TransferResult {377  for (const {event} of events) {378    if (api.events.common.Transfer.is(event)) {379      const [collection, token, sender, recipient, value] = event.data;380      return {381        collectionId: collection.toNumber(),382        itemId: token.toNumber(),383        sender: normalizeAccountId(sender.toJSON() as any),384        recipient: normalizeAccountId(recipient.toJSON() as any),385        value: value.toBigInt(),386      };387    }388  }389  throw new Error('no transfer event');390}391392interface Nft {393  type: 'NFT';394}395396interface Fungible {397  type: 'Fungible';398  decimalPoints: number;399}400401interface ReFungible {402  type: 'ReFungible';403}404405export type CollectionMode = Nft | Fungible | ReFungible;406407export type Property = {408  key: any,409  value: any,410};411412type Permission = {413  mutable: boolean;414  collectionAdmin: boolean;415  tokenOwner: boolean;416}417418type PropertyPermission = {419  key: any;420  permission: Permission;421}422423export type CreateCollectionParams = {424  mode: CollectionMode,425  name: string,426  description: string,427  tokenPrefix: string,428  properties?: Array<Property>,429  propPerm?: Array<PropertyPermission>430};431432const defaultCreateCollectionParams: CreateCollectionParams = {433  description: 'description',434  mode: {type: 'NFT'},435  name: 'name',436  tokenPrefix: 'prefix',437};438439export async function440createCollection(441  api: ApiPromise,442  sender: IKeyringPair,443  params: Partial<CreateCollectionParams> = {},444): Promise<CreateCollectionResult> {445  const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};446447  let modeprm = {};448  if (mode.type === 'NFT') {449    modeprm = {nft: null};450  } else if (mode.type === 'Fungible') {451    modeprm = {fungible: mode.decimalPoints};452  } else if (mode.type === 'ReFungible') {453    modeprm = {refungible: null};454  }455456  const tx = api.tx.unique.createCollectionEx({457    name: strToUTF16(name),458    description: strToUTF16(description),459    tokenPrefix: strToUTF16(tokenPrefix),460    mode: modeprm as any,461  });462  const events = await executeTransaction(api, sender, tx);463  return getCreateCollectionResult(events);464}465466export async function createCollectionExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {467  const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};468469  let collectionId = 0;470  await usingApi(async (api, privateKeyWrapper) => {471    // Get number of collections before the transaction472    const collectionCountBefore = await getCreatedCollectionCount(api);473474    // Run the CreateCollection transaction475    const alicePrivateKey = privateKeyWrapper('//Alice');476477    const result = await createCollection(api, alicePrivateKey, params);478479    // Get number of collections after the transaction480    const collectionCountAfter = await getCreatedCollectionCount(api);481482    // Get the collection483    const collection = await queryCollectionExpectSuccess(api, result.collectionId);484485    // What to expect486    // tslint:disable-next-line:no-unused-expression487    expect(result.success).to.be.true;488    expect(result.collectionId).to.be.equal(collectionCountAfter);489    // tslint:disable-next-line:no-unused-expression490    expect(collection).to.be.not.null;491    expect(collectionCountAfter).to.be.equal(collectionCountBefore + 1, 'Error: NFT collection NOT created.');492    expect(collection.owner.toString()).to.be.equal(toSubstrateAddress(alicePrivateKey));493    expect(utf16ToStr(collection.name.toJSON() as any)).to.be.equal(name);494    expect(utf16ToStr(collection.description.toJSON() as any)).to.be.equal(description);495    expect(hexToStr(collection.tokenPrefix.toJSON())).to.be.equal(tokenPrefix);496497    collectionId = result.collectionId;498  });499500  return collectionId;501}502503export async function createCollectionWithPropsExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {504  const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};505506  let collectionId = 0;507  await usingApi(async (api, privateKeyWrapper) => {508    // Get number of collections before the transaction509    const collectionCountBefore = await getCreatedCollectionCount(api);510511    // Run the CreateCollection transaction512    const alicePrivateKey = privateKeyWrapper('//Alice');513514    let modeprm = {};515    if (mode.type === 'NFT') {516      modeprm = {nft: null};517    } else if (mode.type === 'Fungible') {518      modeprm = {fungible: mode.decimalPoints};519    } else if (mode.type === 'ReFungible') {520      modeprm = {refungible: null};521    }522523    const tx = api.tx.unique.createCollectionEx({name: strToUTF16(name), description: strToUTF16(description), tokenPrefix: strToUTF16(tokenPrefix), mode: modeprm as any, properties: params.properties, tokenPropertyPermissions: params.propPerm});524    const events = await submitTransactionAsync(alicePrivateKey, tx);525    const result = getCreateCollectionResult(events);526527    // Get number of collections after the transaction528    const collectionCountAfter = await getCreatedCollectionCount(api);529530    // Get the collection531    const collection = await queryCollectionExpectSuccess(api, result.collectionId);532533    // What to expect534    // tslint:disable-next-line:no-unused-expression535    expect(result.success).to.be.true;536    expect(result.collectionId).to.be.equal(collectionCountAfter);537    // tslint:disable-next-line:no-unused-expression538    expect(collection).to.be.not.null;539    expect(collectionCountAfter).to.be.equal(collectionCountBefore + 1, 'Error: NFT collection NOT created.');540    expect(collection.owner.toString()).to.be.equal(toSubstrateAddress(alicePrivateKey));541    expect(utf16ToStr(collection.name.toJSON() as any)).to.be.equal(name);542    expect(utf16ToStr(collection.description.toJSON() as any)).to.be.equal(description);543    expect(hexToStr(collection.tokenPrefix.toJSON())).to.be.equal(tokenPrefix);544545546    collectionId = result.collectionId;547  });548549  return collectionId;550}551552export async function createCollectionWithPropsExpectFailure(params: Partial<CreateCollectionParams> = {}) {553  const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};554555  await usingApi(async (api, privateKeyWrapper) => {556    // Get number of collections before the transaction557    const collectionCountBefore = await getCreatedCollectionCount(api);558559    // Run the CreateCollection transaction560    const alicePrivateKey = privateKeyWrapper('//Alice');561562    let modeprm = {};563    if (mode.type === 'NFT') {564      modeprm = {nft: null};565    } else if (mode.type === 'Fungible') {566      modeprm = {fungible: mode.decimalPoints};567    } else if (mode.type === 'ReFungible') {568      modeprm = {refungible: null};569    }570571    const tx = api.tx.unique.createCollectionEx({name: strToUTF16(name), description: strToUTF16(description), tokenPrefix: strToUTF16(tokenPrefix), mode: modeprm as any, properties: params.properties, tokenPropertyPermissions: params.propPerm});572    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;573574575    // Get number of collections after the transaction576    const collectionCountAfter = await getCreatedCollectionCount(api);577578    expect(collectionCountAfter).to.be.equal(collectionCountBefore, 'Error: Collection with incorrect data created.');579  });580}581582export async function createCollectionExpectFailure(params: Partial<CreateCollectionParams> = {}) {583  const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};584585  let modeprm = {};586  if (mode.type === 'NFT') {587    modeprm = {nft: null};588  } else if (mode.type === 'Fungible') {589    modeprm = {fungible: mode.decimalPoints};590  } else if (mode.type === 'ReFungible') {591    modeprm = {refungible: null};592  }593594  await usingApi(async (api, privateKeyWrapper) => {595    // Get number of collections before the transaction596    const collectionCountBefore = await getCreatedCollectionCount(api);597598    // Run the CreateCollection transaction599    const alicePrivateKey = privateKeyWrapper('//Alice');600    const tx = api.tx.unique.createCollectionEx({name: strToUTF16(name), description: strToUTF16(description), tokenPrefix: strToUTF16(tokenPrefix), mode: modeprm as any});601    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;602603    // Get number of collections after the transaction604    const collectionCountAfter = await getCreatedCollectionCount(api);605606    // What to expect607    expect(collectionCountAfter).to.be.equal(collectionCountBefore, 'Error: Collection with incorrect data created.');608  });609}610611export async function findUnusedAddress(api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair, seedAddition = ''): Promise<IKeyringPair> {612  let bal = 0n;613  let unused;614  do {615    const randomSeed = 'seed' + Math.floor(Math.random() * Math.floor(10000)) + seedAddition;616    unused = privateKeyWrapper(`//${randomSeed}`);617    bal = (await api.query.system.account(unused.address)).data.free.toBigInt();618  } while (bal !== 0n);619  return unused;620}621622export async function getAllowance(api: ApiPromise, collectionId: number, owner: CrossAccountId | string | IKeyringPair, approved: CrossAccountId | string | IKeyringPair, tokenId: number) {623  return (await api.rpc.unique.allowance(collectionId, normalizeAccountId(owner), normalizeAccountId(approved), tokenId)).toBigInt();624}625626export function findUnusedAddresses(api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair, amount: number): Promise<IKeyringPair[]> {627  return Promise.all(new Array(amount).fill(null).map(() => findUnusedAddress(api, privateKeyWrapper, '_' + Date.now())));628}629630export async function findNotExistingCollection(api: ApiPromise): Promise<number> {631  const totalNumber = await getCreatedCollectionCount(api);632  const newCollection: number = totalNumber + 1;633  return newCollection;634}635636function getDestroyResult(events: EventRecord[]): boolean {637  let success = false;638  events.forEach(({event: {method}}) => {639    if (method == 'ExtrinsicSuccess') {640      success = true;641    }642  });643  return success;644}645646export async function destroyCollectionExpectFailure(collectionId: number, senderSeed = '//Alice') {647  await usingApi(async (api, privateKeyWrapper) => {648    // Run the DestroyCollection transaction649    const alicePrivateKey = privateKeyWrapper(senderSeed);650    const tx = api.tx.unique.destroyCollection(collectionId);651    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;652  });653}654655export async function destroyCollectionExpectSuccess(collectionId: number, senderSeed = '//Alice') {656  await usingApi(async (api, privateKeyWrapper) => {657    // Run the DestroyCollection transaction658    const alicePrivateKey = privateKeyWrapper(senderSeed);659    const tx = api.tx.unique.destroyCollection(collectionId);660    const events = await submitTransactionAsync(alicePrivateKey, tx);661    const result = getDestroyResult(events);662    expect(result).to.be.true;663664    // What to expect665    expect(await getDetailedCollectionInfo(api, collectionId)).to.be.null;666  });667}668669export async function setCollectionLimitsExpectSuccess(sender: IKeyringPair, collectionId: number, limits: any) {670  await usingApi(async (api) => {671    const tx = api.tx.unique.setCollectionLimits(collectionId, limits);672    const events = await submitTransactionAsync(sender, tx);673    const result = getGenericResult(events);674675    expect(result.success).to.be.true;676  });677}678679export const setCollectionPermissionsExpectSuccess = async (sender: IKeyringPair, collectionId: number, permissions: any) => {680  await usingApi(async(api) => {681    const tx = api.tx.unique.setCollectionPermissions(collectionId, permissions);682    const events = await submitTransactionAsync(sender, tx);683    const result = getGenericResult(events);684685    expect(result.success).to.be.true;686  });687};688689export async function setCollectionLimitsExpectFailure(sender: IKeyringPair, collectionId: number, limits: any) {690  await usingApi(async (api) => {691    const tx = api.tx.unique.setCollectionLimits(collectionId, limits);692    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;693    const result = getGenericResult(events);694695    expect(result.success).to.be.false;696  });697}698699export async function setCollectionSponsorExpectSuccess(collectionId: number, sponsor: string, sender = '//Alice') {700  await usingApi(async (api, privateKeyWrapper) => {701702    // Run the transaction703    const senderPrivateKey = privateKeyWrapper(sender);704    const tx = api.tx.unique.setCollectionSponsor(collectionId, sponsor);705    const events = await submitTransactionAsync(senderPrivateKey, tx);706    const result = getGenericResult(events);707708    // Get the collection709    const collection = await queryCollectionExpectSuccess(api, collectionId);710711    // What to expect712    expect(result.success).to.be.true;713    expect(collection.sponsorship.toJSON()).to.deep.equal({714      unconfirmed: sponsor,715    });716  });717}718719export async function removeCollectionSponsorExpectSuccess(collectionId: number, sender = '//Alice') {720  await usingApi(async (api, privateKeyWrapper) => {721722    // Run the transaction723    const alicePrivateKey = privateKeyWrapper(sender);724    const tx = api.tx.unique.removeCollectionSponsor(collectionId);725    const events = await submitTransactionAsync(alicePrivateKey, tx);726    const result = getGenericResult(events);727728    // Get the collection729    const collection = await queryCollectionExpectSuccess(api, collectionId);730731    // What to expect732    expect(result.success).to.be.true;733    expect(collection.sponsorship.toJSON()).to.be.deep.equal({disabled: null});734  });735}736737export async function removeCollectionSponsorExpectFailure(collectionId: number, senderSeed = '//Alice') {738  await usingApi(async (api, privateKeyWrapper) => {739740    // Run the transaction741    const alicePrivateKey = privateKeyWrapper(senderSeed);742    const tx = api.tx.unique.removeCollectionSponsor(collectionId);743    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;744  });745}746747export async function setCollectionSponsorExpectFailure(collectionId: number, sponsor: string, senderSeed = '//Alice') {748  await usingApi(async (api, privateKeyWrapper) => {749750    // Run the transaction751    const alicePrivateKey = privateKeyWrapper(senderSeed);752    const tx = api.tx.unique.setCollectionSponsor(collectionId, sponsor);753    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;754  });755}756757export async function confirmSponsorshipExpectSuccess(collectionId: number, senderSeed = '//Alice') {758  await usingApi(async (api, privateKeyWrapper) => {759760    // Run the transaction761    const sender = privateKeyWrapper(senderSeed);762    await confirmSponsorshipByKeyExpectSuccess(collectionId, sender);763  });764}765766export async function confirmSponsorshipByKeyExpectSuccess(collectionId: number, sender: IKeyringPair) {767  await usingApi(async (api, privateKeyWrapper) => {768769    // Run the transaction770    const tx = api.tx.unique.confirmSponsorship(collectionId);771    const events = await submitTransactionAsync(sender, tx);772    const result = getGenericResult(events);773774    // Get the collection775    const collection = await queryCollectionExpectSuccess(api, collectionId);776777    // What to expect778    expect(result.success).to.be.true;779    expect(collection.sponsorship.toJSON()).to.be.deep.equal({780      confirmed: sender.address,781    });782  });783}784785786export async function confirmSponsorshipExpectFailure(collectionId: number, senderSeed = '//Alice') {787  await usingApi(async (api, privateKeyWrapper) => {788789    // Run the transaction790    const sender = privateKeyWrapper(senderSeed);791    const tx = api.tx.unique.confirmSponsorship(collectionId);792    await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;793  });794}795796export async function enableContractSponsoringExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {797  await usingApi(async (api) => {798    const tx = api.tx.unique.enableContractSponsoring(contractAddress, enable);799    const events = await submitTransactionAsync(sender, tx);800    const result = getGenericResult(events);801802    expect(result.success).to.be.true;803  });804}805806export async function enableContractSponsoringExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {807  await usingApi(async (api) => {808    const tx = api.tx.unique.enableContractSponsoring(contractAddress, enable);809    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;810    const result = getGenericResult(events);811812    expect(result.success).to.be.false;813  });814}815816export async function setTransferFlagExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {817818  await usingApi(async (api) => {819820    const tx = api.tx.unique.setTransfersEnabledFlag(collectionId, enabled);821    const events = await submitTransactionAsync(sender, tx);822    const result = getGenericResult(events);823824    expect(result.success).to.be.true;825  });826}827828export async function setTransferFlagExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {829830  await usingApi(async (api) => {831832    const tx = api.tx.unique.setTransfersEnabledFlag(collectionId, enabled);833    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;834    const result = getGenericResult(events);835836    expect(result.success).to.be.false;837  });838}839840export async function setContractSponsoringRateLimitExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {841  await usingApi(async (api) => {842    const tx = api.tx.unique.setContractSponsoringRateLimit(contractAddress, rateLimit);843    const events = await submitTransactionAsync(sender, tx);844    const result = getGenericResult(events);845846    expect(result.success).to.be.true;847  });848}849850export async function setContractSponsoringRateLimitExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {851  await usingApi(async (api) => {852    const tx = api.tx.unique.setContractSponsoringRateLimit(contractAddress, rateLimit);853    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;854    const result = getGenericResult(events);855856    expect(result.success).to.be.false;857  });858}859860export async function getNextSponsored(861  api: ApiPromise,862  collectionId: number,863  account: string | CrossAccountId,864  tokenId: number,865): Promise<number> {866  return Number((await api.rpc.unique.nextSponsored(collectionId, account, tokenId)).unwrapOr(-1));867}868869export async function toggleContractAllowlistExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, value = true) {870  await usingApi(async (api) => {871    const tx = api.tx.unique.toggleContractAllowList(contractAddress, value);872    const events = await submitTransactionAsync(sender, tx);873    const result = getGenericResult(events);874875    expect(result.success).to.be.true;876  });877}878879export async function isAllowlistedInContract(contractAddress: AccountId | string, user: string) {880  let allowlisted = false;881  await usingApi(async (api) => {882    allowlisted = (await api.query.unique.contractAllowList(contractAddress, user)).toJSON() as boolean;883  });884  return allowlisted;885}886887export async function addToContractAllowListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {888  await usingApi(async (api) => {889    const tx = api.tx.unique.addToContractAllowList(contractAddress.toString(), user.toString());890    const events = await submitTransactionAsync(sender, tx);891    const result = getGenericResult(events);892893    expect(result.success).to.be.true;894  });895}896897export async function removeFromContractAllowListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {898  await usingApi(async (api) => {899    const tx = api.tx.unique.removeFromContractAllowList(contractAddress.toString(), user.toString());900    const events = await submitTransactionAsync(sender, tx);901    const result = getGenericResult(events);902903    expect(result.success).to.be.true;904  });905}906907export async function removeFromContractAllowListExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {908  await usingApi(async (api) => {909    const tx = api.tx.unique.removeFromContractAllowList(contractAddress.toString(), user.toString());910    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;911    const result = getGenericResult(events);912913    expect(result.success).to.be.false;914  });915}916917export interface CreateFungibleData {918  readonly Value: bigint;919}920921export interface CreateReFungibleData { }922export interface CreateNftData { }923924export type CreateItemData = {925  NFT: CreateNftData;926} | {927  Fungible: CreateFungibleData;928} | {929  ReFungible: CreateReFungibleData;930};931932export async function burnItem(api: ApiPromise, sender: IKeyringPair, collectionId: number, tokenId: number, value: number | bigint) : Promise<boolean> {933  const tx = api.tx.unique.burnItem(collectionId, tokenId, value);934  const events = await submitTransactionAsync(sender, tx);935  return getGenericResult(events).success;936}937938export async function burnItemExpectSuccess(sender: IKeyringPair, collectionId: number, tokenId: number, value: number | bigint = 1) {939  await usingApi(async (api) => {940    const balanceBefore = await getBalance(api, collectionId, normalizeAccountId(sender), tokenId);941    // if burning token by admin - use adminButnItemExpectSuccess942    expect(balanceBefore >= BigInt(value)).to.be.true;943944    expect(await burnItem(api, sender, collectionId, tokenId, value)).to.be.true;945946    const balanceAfter = await getBalance(api, collectionId, normalizeAccountId(sender), tokenId);947    expect(balanceAfter + BigInt(value)).to.be.equal(balanceBefore);948  });949}950951export async function burnItemExpectFailure(sender: IKeyringPair, collectionId: number, tokenId: number, value: number | bigint = 1) {952  await usingApi(async (api) => {953    const tx = api.tx.unique.burnItem(collectionId, tokenId, value);954955    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;956    const result = getCreateCollectionResult(events);957    // tslint:disable-next-line:no-unused-expression958    expect(result.success).to.be.false;959  });960}961962export async function burnFromExpectSuccess(sender: IKeyringPair, from: IKeyringPair | CrossAccountId, collectionId: number, tokenId: number, value: number | bigint = 1) {963  await usingApi(async (api) => {964    const tx = api.tx.unique.burnFrom(collectionId, normalizeAccountId(from), tokenId, value);965    const events = await submitTransactionAsync(sender, tx);966    return getGenericResult(events).success;967  });968}969970export async function971approve(972  api: ApiPromise,973  collectionId: number,974  tokenId: number, owner: IKeyringPair, approved: CrossAccountId | string | IKeyringPair, amount: number | bigint,975) {976  const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);977  const events = await submitTransactionAsync(owner, approveUniqueTx);978  return getGenericResult(events).success;979}980981export async function982approveExpectSuccess(983  collectionId: number,984  tokenId: number, owner: IKeyringPair, approved: CrossAccountId | string, amount: number | bigint = 1,985) {986  await usingApi(async (api: ApiPromise) => {987    const result = await approve(api, collectionId, tokenId, owner, approved, amount);988    expect(result).to.be.true;989990    expect(await getAllowance(api, collectionId, owner, approved, tokenId)).to.be.equal(BigInt(amount));991  });992}993994export async function adminApproveFromExpectSuccess(995  collectionId: number,996  tokenId: number, admin: IKeyringPair, owner: CrossAccountId | string, approved: CrossAccountId | string, amount: number | bigint = 1,997) {998  await usingApi(async (api: ApiPromise) => {999    const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);1000    const events = await submitTransactionAsync(admin, approveUniqueTx);1001    const result = getGenericResult(events);1002    expect(result.success).to.be.true;10031004    expect(await getAllowance(api, collectionId, owner, approved, tokenId)).to.be.equal(BigInt(amount));1005  });1006}10071008export async function1009transferFrom(1010  api: ApiPromise,1011  collectionId: number,1012  tokenId: number,1013  accountApproved: IKeyringPair,1014  accountFrom: IKeyringPair | CrossAccountId,1015  accountTo: IKeyringPair | CrossAccountId,1016  value: number | bigint,1017) {1018  const from = normalizeAccountId(accountFrom);1019  const to = normalizeAccountId(accountTo);1020  const transferFromTx = api.tx.unique.transferFrom(from, to, collectionId, tokenId, value);1021  const events = await submitTransactionAsync(accountApproved, transferFromTx);1022  return getGenericResult(events).success;1023}10241025export async function1026transferFromExpectSuccess(1027  collectionId: number,1028  tokenId: number,1029  accountApproved: IKeyringPair,1030  accountFrom: IKeyringPair | CrossAccountId,1031  accountTo: IKeyringPair | CrossAccountId,1032  value: number | bigint = 1,1033  type = 'NFT',1034) {1035  await usingApi(async (api: ApiPromise) => {1036    const from = normalizeAccountId(accountFrom);1037    const to = normalizeAccountId(accountTo);1038    let balanceBefore = 0n;1039    if (type === 'Fungible' || type === 'ReFungible') {1040      balanceBefore = await getBalance(api, collectionId, to, tokenId);1041    }1042    expect(await transferFrom(api, collectionId, tokenId, accountApproved, accountFrom, accountTo, value)).to.be.true;1043    if (type === 'NFT') {1044      expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(to);1045    }1046    if (type === 'Fungible') {1047      const balanceAfter = await getBalance(api, collectionId, to, tokenId);1048      if (JSON.stringify(to) !== JSON.stringify(from)) {1049        expect(balanceAfter - balanceBefore).to.be.equal(BigInt(value));1050      } else {1051        expect(balanceAfter).to.be.equal(balanceBefore);1052      }1053    }1054    if (type === 'ReFungible') {1055      expect(await getBalance(api, collectionId, to, tokenId)).to.be.equal(balanceBefore + BigInt(value));1056    }1057  });1058}10591060export async function1061transferFromExpectFail(1062  collectionId: number,1063  tokenId: number,1064  accountApproved: IKeyringPair,1065  accountFrom: IKeyringPair,1066  accountTo: IKeyringPair,1067  value: number | bigint = 1,1068) {1069  await usingApi(async (api: ApiPromise) => {1070    const transferFromTx = api.tx.unique.transferFrom(normalizeAccountId(accountFrom.address), normalizeAccountId(accountTo.address), collectionId, tokenId, value);1071    const events = await expect(submitTransactionExpectFailAsync(accountApproved, transferFromTx)).to.be.rejected;1072    const result = getCreateCollectionResult(events);1073    // tslint:disable-next-line:no-unused-expression1074    expect(result.success).to.be.false;1075  });1076}10771078/* eslint no-async-promise-executor: "off" */1079export async function getBlockNumber(api: ApiPromise): Promise<number> {1080  return new Promise<number>(async (resolve) => {1081    const unsubscribe = await api.rpc.chain.subscribeNewHeads((head) => {1082      unsubscribe();1083      resolve(head.number.toNumber());1084    });1085  });1086}10871088export async function addCollectionAdminExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | CrossAccountId) {1089  await usingApi(async (api) => {1090    const changeAdminTx = api.tx.unique.addCollectionAdmin(collectionId, normalizeAccountId(address));1091    const events = await submitTransactionAsync(sender, changeAdminTx);1092    const result = getCreateCollectionResult(events);1093    expect(result.success).to.be.true;1094  });1095}10961097export async function adminApproveFromExpectFail(1098  collectionId: number,1099  tokenId: number, admin: IKeyringPair, owner: CrossAccountId | string, approved: CrossAccountId | string, amount: number | bigint = 1,1100) {1101  await usingApi(async (api: ApiPromise) => {1102    const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);1103    const events = await expect(submitTransactionAsync(admin, approveUniqueTx)).to.be.rejected;1104    const result = getGenericResult(events);1105    expect(result.success).to.be.false;1106  });1107}11081109export async function1110getFreeBalance(account: IKeyringPair): Promise<bigint> {1111  let balance = 0n;1112  await usingApi(async (api) => {1113    balance = BigInt((await api.query.system.account(account.address)).data.free.toString());1114  });11151116  return balance;1117}11181119export async function paraSiblingSovereignAccount(paraid: number): Promise<string> {1120  return usingApi(async api => {1121    // We are getting a *sibling* parachain sovereign account,1122    // so we need a sibling prefix: encoded(b"sibl") == 0x7369626c1123    const siblingPrefix = '0x7369626c';11241125    const encodedParaId = api.createType('u32', paraid).toHex(true).substring(2);1126    const suffix = '000000000000000000000000000000000000000000000000';11271128    return siblingPrefix + encodedParaId + suffix;1129  });1130}11311132export async function transferBalanceTo(api: ApiPromise, source: IKeyringPair, target: string, amount = 1000n * UNIQUE) {1133  const tx = api.tx.balances.transfer(target, amount);1134  const events = await submitTransactionAsync(source, tx);1135  const result = getGenericResult(events);1136  expect(result.success).to.be.true;1137}11381139export async function scheduleAt(1140  api: ApiPromise,1141  operationTx: any,1142  sender: IKeyringPair,1143  executionBlockNumber: number,1144  scheduledId: string,1145  period = 1,1146  repetitions = 1,1147): Promise<any> {1148  const scheduleTx = api.tx.scheduler.scheduleNamed(1149    scheduledId,1150    executionBlockNumber, 1151    repetitions > 1 ? [period, repetitions] : null, 1152    0, 1153    {Value: operationTx as any},1154  );11551156  return executeTransaction(api, sender, scheduleTx);1157}11581159export async function scheduleAfter(1160  api: ApiPromise,1161  operationTx: any,1162  sender: IKeyringPair,1163  blocksBeforeExecution: number,1164  scheduledId: string,1165  period = 1,1166  repetitions = 1,1167): Promise<any> {1168  const scheduleTx = api.tx.scheduler.scheduleNamedAfter(1169    scheduledId,1170    blocksBeforeExecution, 1171    repetitions > 1 ? [period, repetitions] : null, 1172    0, 1173    {Value: operationTx as any},1174  );11751176  return executeTransaction(api, sender, scheduleTx);1177}11781179export async function cancelScheduled(1180  api: ApiPromise,1181  sender: IKeyringPair,1182  scheduledId: string,1183): Promise<any> {1184  const cancelTx = api.tx.scheduler.cancelNamed(scheduledId);1185  return executeTransaction(api, sender, cancelTx);1186}11871188export async function1189scheduleTransferExpectSuccess(1190  api: ApiPromise,1191  collectionId: number,1192  tokenId: number,1193  sender: IKeyringPair,1194  recipient: IKeyringPair,1195  transferAmount: number | bigint = 1,1196  blocksBeforeExecution: number,1197  scheduledId: string,1198  scheduleMethod: 'at' | 'after' = 'at',1199) {1200  const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient.address), collectionId, tokenId, transferAmount);12011202  if (scheduleMethod == 'at') {1203    const blockNumber: number | undefined = await getBlockNumber(api);1204    const expectedBlockNumber = blockNumber + blocksBeforeExecution;1205    //expect(expectedBlockNumber).to.be.greaterThan(0);12061207    await expect(scheduleAt(api, transferTx, sender, expectedBlockNumber, scheduledId)).to.not.be.rejected;1208  } else {1209    await expect(scheduleAfter(api, transferTx, sender, blocksBeforeExecution, scheduledId)).to.not.be.rejected;1210  }12111212  expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(sender.address));1213}12141215export async function1216scheduleTransferAndWaitExpectSuccess(1217  api: ApiPromise,1218  collectionId: number,1219  tokenId: number,1220  sender: IKeyringPair,1221  recipient: IKeyringPair,1222  transferAmount: number | bigint = 1,1223  blocksBeforeExecution: number,1224  scheduledId: string,1225  scheduleMethod: 'at' | 'after' = 'at',1226) {1227  await scheduleTransferExpectSuccess(1228    api, 1229    collectionId, 1230    tokenId, 1231    sender, 1232    recipient, 1233    transferAmount, 1234    blocksBeforeExecution, 1235    scheduledId, 1236    scheduleMethod,1237  );12381239  const recipientBalanceBefore = await getFreeBalance(recipient);12401241  // sleep for n + 1 blocks1242  await waitNewBlocks(blocksBeforeExecution + 1);12431244  const recipientBalanceAfter = await getFreeBalance(recipient);12451246  expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(recipient.address));1247  expect(recipientBalanceAfter).to.be.equal(recipientBalanceBefore);1248}12491250export async function1251scheduleTransferFundsExpectSuccess(1252  api: ApiPromise,1253  amount: bigint,1254  sender: IKeyringPair,1255  recipient: IKeyringPair,1256  blocksBeforeExecution: number,1257  scheduledId: string,1258  period = 1,1259  repetitions = 1,1260) {1261  const transferTx = api.tx.balances.transfer(recipient.address, amount);12621263<<<<<<< HEAD1264    const balanceBefore = await getFreeBalance(recipient);12651266    await scheduleExpectSuccess(transferTx, sender, blockSchedule, scheduledId, period, repetitions);1267=======1268  const balanceBefore = await getFreeBalance(recipient);1269  1270  await expect(scheduleAfter(api, transferTx, sender, blocksBeforeExecution, scheduledId, period, repetitions)).to.not.be.rejected;1271>>>>>>> test(scheduler): enable and add more coverage, leave sponsorship disabled12721273  expect(await getFreeBalance(recipient)).to.be.equal(balanceBefore);1274}12751276export async function1277transfer(1278  api: ApiPromise,1279  collectionId: number,1280  tokenId: number,1281  sender: IKeyringPair,1282  recipient: IKeyringPair | CrossAccountId,1283  value: number | bigint,1284) : Promise<boolean> {1285  const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient), collectionId, tokenId, value);1286  const events = await executeTransaction(api, sender, transferTx);1287  return getGenericResult(events).success;1288}12891290export async function1291transferExpectSuccess(1292  collectionId: number,1293  tokenId: number,1294  sender: IKeyringPair,1295  recipient: IKeyringPair | CrossAccountId,1296  value: number | bigint = 1,1297  type = 'NFT',1298) {1299  await usingApi(async (api: ApiPromise) => {1300    const from = normalizeAccountId(sender);1301    const to = normalizeAccountId(recipient);13021303    let balanceBefore = 0n;1304    if (type === 'Fungible' || type === 'ReFungible') {1305      balanceBefore = await getBalance(api, collectionId, to, tokenId);1306    }13071308    const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient), collectionId, tokenId, value);1309    const events = await executeTransaction(api, sender, transferTx);1310    const result = getTransferResult(api, events);13111312    expect(result.collectionId).to.be.equal(collectionId);1313    expect(result.itemId).to.be.equal(tokenId);1314    expect(result.sender).to.be.deep.equal(normalizeAccountId(sender.address));1315    expect(result.recipient).to.be.deep.equal(to);1316    expect(result.value).to.be.equal(BigInt(value));13171318    if (type === 'NFT') {1319      expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(to);1320    }1321    if (type === 'Fungible' || type === 'ReFungible') {1322      const balanceAfter = await getBalance(api, collectionId, to, tokenId);1323      if (JSON.stringify(to) !== JSON.stringify(from)) {1324        expect(balanceAfter - balanceBefore).to.be.equal(BigInt(value));1325      } else {1326        expect(balanceAfter).to.be.equal(balanceBefore);1327      }1328    }1329  });1330}13311332export async function1333transferExpectFailure(1334  collectionId: number,1335  tokenId: number,1336  sender: IKeyringPair,1337  recipient: IKeyringPair | CrossAccountId,1338  value: number | bigint = 1,1339) {1340  await usingApi(async (api: ApiPromise) => {1341    const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient), collectionId, tokenId, value);1342    const events = await expect(submitTransactionExpectFailAsync(sender, transferTx)).to.be.rejected;1343    const result = getGenericResult(events);1344    // if (events && Array.isArray(events)) {1345    //   const result = getCreateCollectionResult(events);1346    // tslint:disable-next-line:no-unused-expression1347    expect(result.success).to.be.false;1348    //}1349  });1350}13511352export async function1353approveExpectFail(1354  collectionId: number,1355  tokenId: number, owner: IKeyringPair, approved: IKeyringPair, amount: number | bigint = 1,1356) {1357  await usingApi(async (api: ApiPromise) => {1358    const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved.address), collectionId, tokenId, amount);1359    const events = await expect(submitTransactionExpectFailAsync(owner, approveUniqueTx)).to.be.rejected;1360    const result = getCreateCollectionResult(events);1361    // tslint:disable-next-line:no-unused-expression1362    expect(result.success).to.be.false;1363  });1364}13651366export async function getBalance(1367  api: ApiPromise,1368  collectionId: number,1369  owner: string | CrossAccountId | IKeyringPair,1370  token: number,1371): Promise<bigint> {1372  return (await api.rpc.unique.balance(collectionId, normalizeAccountId(owner), token)).toBigInt();1373}1374export async function getTokenOwner(1375  api: ApiPromise,1376  collectionId: number,1377  token: number,1378): Promise<CrossAccountId> {1379  const owner = (await api.rpc.unique.tokenOwner(collectionId, token)).toJSON() as any;1380  if (owner == null) throw new Error('owner == null');1381  return normalizeAccountId(owner);1382}1383export async function getTopmostTokenOwner(1384  api: ApiPromise,1385  collectionId: number,1386  token: number,1387): Promise<CrossAccountId> {1388  const owner = (await api.rpc.unique.topmostTokenOwner(collectionId, token)).toJSON() as any;1389  if (owner == null) throw new Error('owner == null');1390  return normalizeAccountId(owner);1391}1392export async function getTokenChildren(1393  api: ApiPromise,1394  collectionId: number,1395  tokenId: number,1396): Promise<UpDataStructsTokenChild[]> {1397  return (await api.rpc.unique.tokenChildren(collectionId, tokenId)).toJSON() as any;1398}1399export async function isTokenExists(1400  api: ApiPromise,1401  collectionId: number,1402  token: number,1403): Promise<boolean> {1404  return (await api.rpc.unique.tokenExists(collectionId, token)).toJSON();1405}1406export async function getLastTokenId(1407  api: ApiPromise,1408  collectionId: number,1409): Promise<number> {1410  return (await api.rpc.unique.lastTokenId(collectionId)).toJSON();1411}1412export async function getAdminList(1413  api: ApiPromise,1414  collectionId: number,1415): Promise<string[]> {1416  return (await api.rpc.unique.adminlist(collectionId)).toHuman() as any;1417}1418export async function getTokenProperties(1419  api: ApiPromise,1420  collectionId: number,1421  tokenId: number,1422  propertyKeys: string[],1423): Promise<UpDataStructsProperty[]> {1424  return (await api.rpc.unique.tokenProperties(collectionId, tokenId, propertyKeys)).toHuman() as any;1425}14261427export async function createFungibleItemExpectSuccess(1428  sender: IKeyringPair,1429  collectionId: number,1430  data: CreateFungibleData,1431  owner: CrossAccountId | string = sender.address,1432) {1433  return await usingApi(async (api) => {1434    const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), {Fungible: data});14351436    const events = await submitTransactionAsync(sender, tx);1437    const result = getCreateItemResult(events);14381439    expect(result.success).to.be.true;1440    return result.itemId;1441  });1442}14431444export async function createMultipleItemsExpectSuccess(sender: IKeyringPair, collectionId: number, itemsData: any, owner: CrossAccountId | string = sender.address) {1445  await usingApi(async (api) => {1446    const to = normalizeAccountId(owner);1447    const tx = api.tx.unique.createMultipleItems(collectionId, to, itemsData);14481449    const events = await submitTransactionAsync(sender, tx);1450    expect(getGenericResult(events).success).to.be.true;1451  });1452}14531454export async function createMultipleItemsWithPropsExpectSuccess(sender: IKeyringPair, collectionId: number, itemsData: any, owner: CrossAccountId | string = sender.address) {1455  await usingApi(async (api) => {1456    const to = normalizeAccountId(owner);1457    const tx = api.tx.unique.createMultipleItems(collectionId, to, itemsData);14581459    const events = await submitTransactionAsync(sender, tx);1460    const result = getCreateItemsResult(events);14611462    for (const res of result) {1463      expect(await api.rpc.unique.tokenProperties(collectionId, res.itemId)).not.to.be.empty;1464    }1465  });1466}14671468export async function createMultipleItemsExWithPropsExpectSuccess(sender: IKeyringPair, collectionId: number, itemsData: any) {1469  await usingApi(async (api) => {1470    const tx = api.tx.unique.createMultipleItemsEx(collectionId, itemsData);14711472    const events = await submitTransactionAsync(sender, tx);1473    const result = getCreateItemsResult(events);14741475    for (const res of result) {1476      expect(await api.rpc.unique.tokenProperties(collectionId, res.itemId)).not.to.be.empty;1477    }1478  });1479}14801481export async function createItemWithPropsExpectSuccess(sender: IKeyringPair, collectionId: number, createMode: string, props:  Array<Property>, owner: CrossAccountId | string = sender.address) {1482  let newItemId = 0;1483  await usingApi(async (api) => {1484    const to = normalizeAccountId(owner);1485    const itemCountBefore = await getLastTokenId(api, collectionId);1486    const itemBalanceBefore = await getBalance(api, collectionId, to, newItemId);14871488    let tx;1489    if (createMode === 'Fungible') {1490      const createData = {fungible: {value: 10}};1491      tx = api.tx.unique.createItem(collectionId, to, createData as any);1492    } else if (createMode === 'ReFungible') {1493      const createData = {refungible: {pieces: 100}};1494      tx = api.tx.unique.createItem(collectionId, to, createData as any);1495    } else {1496      const data = api.createType('UpDataStructsCreateItemData', {NFT: {properties: props}});1497      tx = api.tx.unique.createItem(collectionId, to, data as UpDataStructsCreateItemData);1498    }14991500    const events = await submitTransactionAsync(sender, tx);1501    const result = getCreateItemResult(events);15021503    const itemCountAfter = await getLastTokenId(api, collectionId);1504    const itemBalanceAfter = await getBalance(api, collectionId, to, newItemId);15051506    if (createMode === 'NFT') {1507      expect(await api.rpc.unique.tokenProperties(collectionId, result.itemId)).not.to.be.empty;1508    }15091510    // What to expect1511    // tslint:disable-next-line:no-unused-expression1512    expect(result.success).to.be.true;1513    if (createMode === 'Fungible') {1514      expect(itemBalanceAfter - itemBalanceBefore).to.be.equal(10n);1515    } else {1516      expect(itemCountAfter).to.be.equal(itemCountBefore + 1);1517    }1518    expect(collectionId).to.be.equal(result.collectionId);1519    expect(itemCountAfter.toString()).to.be.equal(result.itemId.toString());1520    expect(to).to.be.deep.equal(result.recipient);1521    newItemId = result.itemId;1522  });1523  return newItemId;1524}15251526export async function createItemWithPropsExpectFailure(sender: IKeyringPair, collectionId: number, createMode: string, props: Array<Property>, owner: CrossAccountId | string = sender.address) {1527  await usingApi(async (api) => {15281529    let tx;1530    if (createMode === 'NFT') {1531      const data = api.createType('UpDataStructsCreateItemData', {NFT: {properties: props}}) as UpDataStructsCreateItemData;1532      tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), data);1533    } else {1534      tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), createMode);1535    }153615371538    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1539    if(events.message && events.message.toString().indexOf('1002: Verification Error') > -1) return;1540    const result = getCreateItemResult(events);15411542    expect(result.success).to.be.false;1543  });1544}15451546export async function createItemExpectSuccess(sender: IKeyringPair, collectionId: number, createMode: string, owner: CrossAccountId | string = sender.address) {1547  let newItemId = 0;1548  await usingApi(async (api) => {1549    const to = normalizeAccountId(owner);1550    const itemCountBefore = await getLastTokenId(api, collectionId);1551    const itemBalanceBefore = await getBalance(api, collectionId, to, newItemId);15521553    let tx;1554    if (createMode === 'Fungible') {1555      const createData = {fungible: {value: 10}};1556      tx = api.tx.unique.createItem(collectionId, to, createData as any);1557    } else if (createMode === 'ReFungible') {1558      const createData = {refungible: {pieces: 100}};1559      tx = api.tx.unique.createItem(collectionId, to, createData as any);1560    } else {1561      const createData = {nft: {}};1562      tx = api.tx.unique.createItem(collectionId, to, createData as any);1563    }15641565    const events = await executeTransaction(api, sender, tx);1566    const result = getCreateItemResult(events);15671568    const itemCountAfter = await getLastTokenId(api, collectionId);1569    const itemBalanceAfter = await getBalance(api, collectionId, to, newItemId);15701571    // What to expect1572    // tslint:disable-next-line:no-unused-expression1573    expect(result.success).to.be.true;1574    if (createMode === 'Fungible') {1575      expect(itemBalanceAfter - itemBalanceBefore).to.be.equal(10n);1576    } else {1577      expect(itemCountAfter).to.be.equal(itemCountBefore + 1);1578    }1579    expect(collectionId).to.be.equal(result.collectionId);1580    expect(itemCountAfter.toString()).to.be.equal(result.itemId.toString());1581    expect(to).to.be.deep.equal(result.recipient);1582    newItemId = result.itemId;1583  });1584  return newItemId;1585}15861587export async function createRefungibleToken(api: ApiPromise, sender: IKeyringPair, collectionId: number, amount: bigint, owner: CrossAccountId | IKeyringPair | string = sender.address) : Promise<CreateItemResult> {1588  const createData = {refungible: {pieces: amount}};1589  const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), createData as any);15901591  const events = await submitTransactionAsync(sender, tx);1592  return  getCreateItemResult(events);1593}15941595export async function createItemExpectFailure(sender: IKeyringPair, collectionId: number, createMode: string, owner: CrossAccountId | string = sender.address) {1596  await usingApi(async (api) => {1597    const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), createMode);15981599    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1600    const result = getCreateItemResult(events);16011602    expect(result.success).to.be.false;1603  });1604}16051606export async function setPublicAccessModeExpectSuccess(1607  sender: IKeyringPair, collectionId: number,1608  accessMode: 'Normal' | 'AllowList',1609) {1610  await usingApi(async (api) => {16111612    // Run the transaction1613    const tx = api.tx.unique.setCollectionPermissions(collectionId, {access: accessMode});1614    const events = await submitTransactionAsync(sender, tx);1615    const result = getGenericResult(events);16161617    // Get the collection1618    const collection = await queryCollectionExpectSuccess(api, collectionId);16191620    // What to expect1621    // tslint:disable-next-line:no-unused-expression1622    expect(result.success).to.be.true;1623    expect(collection.permissions.access.toHuman()).to.be.equal(accessMode);1624  });1625}16261627export async function setPublicAccessModeExpectFail(1628  sender: IKeyringPair, collectionId: number,1629  accessMode: 'Normal' | 'AllowList',1630) {1631  await usingApi(async (api) => {16321633    // Run the transaction1634    const tx = api.tx.unique.setCollectionPermissions(collectionId, {access: accessMode});1635    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1636    const result = getGenericResult(events);16371638    // What to expect1639    // tslint:disable-next-line:no-unused-expression1640    expect(result.success).to.be.false;1641  });1642}16431644export async function enableAllowListExpectSuccess(sender: IKeyringPair, collectionId: number) {1645  await setPublicAccessModeExpectSuccess(sender, collectionId, 'AllowList');1646}16471648export async function enableAllowListExpectFail(sender: IKeyringPair, collectionId: number) {1649  await setPublicAccessModeExpectFail(sender, collectionId, 'AllowList');1650}16511652export async function disableAllowListExpectSuccess(sender: IKeyringPair, collectionId: number) {1653  await setPublicAccessModeExpectSuccess(sender, collectionId, 'Normal');1654}16551656export async function setMintPermissionExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {1657  await usingApi(async (api) => {16581659    // Run the transaction1660    const tx = api.tx.unique.setCollectionPermissions(collectionId, {mintMode: enabled});1661    const events = await submitTransactionAsync(sender, tx);1662    const result = getGenericResult(events);1663    expect(result.success).to.be.true;16641665    // Get the collection1666    const collection = await queryCollectionExpectSuccess(api, collectionId);16671668    expect(collection.permissions.mintMode.toHuman()).to.be.equal(enabled);1669  });1670}16711672export async function enablePublicMintingExpectSuccess(sender: IKeyringPair, collectionId: number) {1673  await setMintPermissionExpectSuccess(sender, collectionId, true);1674}16751676export async function setMintPermissionExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {1677  await usingApi(async (api) => {1678    // Run the transaction1679    const tx = api.tx.unique.setCollectionPermissions(collectionId, {mintMode: enabled});1680    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1681    const result = getCreateCollectionResult(events);1682    // tslint:disable-next-line:no-unused-expression1683    expect(result.success).to.be.false;1684  });1685}16861687export async function setChainLimitsExpectFailure(sender: IKeyringPair, limits: IChainLimits) {1688  await usingApi(async (api) => {1689    // Run the transaction1690    const tx = api.tx.unique.setChainLimits(limits);1691    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1692    const result = getCreateCollectionResult(events);1693    // tslint:disable-next-line:no-unused-expression1694    expect(result.success).to.be.false;1695  });1696}16971698export async function isAllowlisted(api: ApiPromise, collectionId: number, address: string | CrossAccountId | IKeyringPair) {1699  return (await api.rpc.unique.allowed(collectionId, normalizeAccountId(address))).toJSON();1700}17011702export async function addToAllowListExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId | CrossAccountId) {1703  await usingApi(async (api) => {1704    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.false;17051706    // Run the transaction1707    const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1708    const events = await submitTransactionAsync(sender, tx);1709    const result = getGenericResult(events);1710    expect(result.success).to.be.true;17111712    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;1713  });1714}17151716export async function addToAllowListAgainExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId) {1717  await usingApi(async (api) => {17181719    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;17201721    // Run the transaction1722    const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1723    const events = await submitTransactionAsync(sender, tx);1724    const result = getGenericResult(events);1725    expect(result.success).to.be.true;17261727    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;1728  });1729}17301731export async function addToAllowListExpectFail(sender: IKeyringPair, collectionId: number, address: string | AccountId) {1732  await usingApi(async (api) => {17331734    // Run the transaction1735    const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1736    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1737    const result = getGenericResult(events);17381739    // What to expect1740    // tslint:disable-next-line:no-unused-expression1741    expect(result.success).to.be.false;1742  });1743}17441745export async function removeFromAllowListExpectSuccess(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1746  await usingApi(async (api) => {1747    // Run the transaction1748    const tx = api.tx.unique.removeFromAllowList(collectionId, normalizeAccountId(address));1749    const events = await submitTransactionAsync(sender, tx);1750    const result = getGenericResult(events);17511752    // What to expect1753    // tslint:disable-next-line:no-unused-expression1754    expect(result.success).to.be.true;1755  });1756}17571758export async function removeFromAllowListExpectFailure(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1759  await usingApi(async (api) => {1760    // Run the transaction1761    const tx = api.tx.unique.removeFromAllowList(collectionId, normalizeAccountId(address));1762    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1763    const result = getGenericResult(events);17641765    // What to expect1766    // tslint:disable-next-line:no-unused-expression1767    expect(result.success).to.be.false;1768  });1769}17701771export const getDetailedCollectionInfo = async (api: ApiPromise, collectionId: number)1772  : Promise<UpDataStructsRpcCollection | null> => {1773  return (await api.rpc.unique.collectionById(collectionId)).unwrapOr(null);1774};17751776export const getCreatedCollectionCount = async (api: ApiPromise): Promise<number> => {1777  // set global object - collectionsCount1778  return (await api.rpc.unique.collectionStats()).created.toNumber();1779};17801781export async function queryCollectionExpectSuccess(api: ApiPromise, collectionId: number): Promise<UpDataStructsRpcCollection> {1782  return (await api.rpc.unique.collectionById(collectionId)).unwrap();1783}17841785export const describe_xcm = (1786  process.env.RUN_XCM_TESTS1787    ? describe1788    : describe.skip1789);17901791export async function waitNewBlocks(blocksCount = 1): Promise<void> {1792  await usingApi(async (api) => {1793    const promise = new Promise<void>(async (resolve) => {1794      const unsubscribe = await api.rpc.chain.subscribeNewHeads(() => {1795        if (blocksCount > 0) {1796          blocksCount--;1797        } else {1798          unsubscribe();1799          resolve();1800        }1801      });1802    });1803    return promise;1804  });1805}18061807export async function waitEvent(1808  api: ApiPromise,1809  maxBlocksToWait: number,1810  eventSection: string,1811  eventMethod: string,1812): Promise<EventRecord | null> {18131814  const promise = new Promise<EventRecord | null>(async (resolve) => {1815    const unsubscribe = await api.rpc.chain.subscribeNewHeads(async header => {1816      const blockNumber = header.number.toHuman();1817      const blockHash = header.hash;1818      const eventIdStr = `${eventSection}.${eventMethod}`;1819      const waitLimitStr = `wait blocks remaining: ${maxBlocksToWait}`;18201821      console.log(`[Block #${blockNumber}] Waiting for event \`${eventIdStr}\` (${waitLimitStr})`);18221823      const apiAt = await api.at(blockHash);1824      const eventRecords = await apiAt.query.system.events();18251826      const neededEvent = eventRecords.find(r => {1827        return r.event.section == eventSection && r.event.method == eventMethod;1828      });18291830      if (neededEvent) {1831        unsubscribe();1832        resolve(neededEvent);1833      } else if (maxBlocksToWait > 0) {1834        maxBlocksToWait--;1835      } else {1836        console.log(`Event \`${eventIdStr}\` is NOT found`);18371838        unsubscribe();1839        resolve(null);1840      }1841    });1842  });1843  return promise;1844}18451846export async function repartitionRFT(1847  api: ApiPromise,1848  collectionId: number,1849  sender: IKeyringPair,1850  tokenId: number,1851  amount: bigint,1852): Promise<boolean> {1853  const tx = api.tx.unique.repartition(collectionId, tokenId, amount);1854  const events = await submitTransactionAsync(sender, tx);1855  const result = getGenericResult(events);18561857  return result.success;1858}18591860export async function itApi(name: string, cb: (apis: { api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair }) => any, opts: { only?: boolean, skip?: boolean } = {}) {1861  let i: any = it;1862  if (opts.only) i = i.only;1863  else if (opts.skip) i = i.skip;1864  i(name, async () => {1865    await usingApi(async (api, privateKeyWrapper) => {1866      await cb({api, privateKeyWrapper});1867    });1868  });1869}18701871itApi.only = (name: string, cb: (apis: { api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair }) => any) => itApi(name, cb, {only: true});1872itApi.skip = (name: string, cb: (apis: { api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair }) => any) => itApi(name, cb, {skip: true});18731874let accountSeed = 10000;1875export function generateKeyringPair(keyring: Keyring) {1876  const privateKey = `0xDEADBEEF${(Date.now() + (accountSeed++)).toString(16).padStart(64 - 8, '0')}`;1877  return keyring.addFromUri(privateKey);1878}18791880export async function expectSubstrateEventsAtBlock(api: ApiPromise, blockNumber: AnyNumber | BlockNumber, section: string, methods: string[], dryRun = false) {1881  const blockHash = await api.rpc.chain.getBlockHash(blockNumber);1882  const subEvents = (await api.query.system.events.at(blockHash))1883    .filter(x => x.event.section === section)1884    .map((x) => x.toHuman());1885  const events = methods.map((m) => {1886    return {1887      event: {1888        method: m,1889        section,1890      },1891    };1892  });1893  if (!dryRun) {1894    expect(subEvents).to.be.like(events);1895  }1896  return subEvents;1897}
after · tests/src/deprecated-helpers/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, BlockNumber} from '@polkadot/types/interfaces';21import type {GenericEventData} from '@polkadot/types';22import {AnyTuple, IEvent, IKeyringPair} from '@polkadot/types/types';23import {evmToAddress} from '@polkadot/util-crypto';24import {AnyNumber} from '@polkadot/types-codec/types';25import BN from 'bn.js';26import chai from 'chai';27import chaiAsPromised from 'chai-as-promised';28import {default as usingApi, executeTransaction, submitTransactionAsync, submitTransactionExpectFailAsync} from '../substrate/substrate-api';29import {hexToStr, strToUTF16, utf16ToStr} from './util';30import {UpDataStructsRpcCollection, UpDataStructsCreateItemData, UpDataStructsProperty} from '@polkadot/types/lookup';31import {UpDataStructsTokenChild} from '../interfaces';32import {Context} from 'mocha';3334chai.use(chaiAsPromised);35const expect = chai.expect;3637export type CrossAccountId = {38  Substrate: string,39} | {40  Ethereum: string,41};424344export enum Pallets {45  Inflation = 'inflation',46  RmrkCore = 'rmrkcore',47  RmrkEquip = 'rmrkequip',48  ReFungible = 'refungible',49  Fungible = 'fungible',50  NFT = 'nonfungible',51  Scheduler = 'scheduler',52  AppPromotion = 'apppromotion',53  TestUtils = 'testutils',54}5556export async function isUnique(): Promise<boolean> {57  return usingApi(async api => {58    const chain = await api.rpc.system.chain();5960    return chain.eq('UNIQUE');61  });62}6364export async function isQuartz(): Promise<boolean> {65  return usingApi(async api => {66    const chain = await api.rpc.system.chain();6768    return chain.eq('QUARTZ');69  });70}7172let modulesNames: any;73export function getModuleNames(api: ApiPromise): string[] {74  if (typeof modulesNames === 'undefined')75    modulesNames = api.runtimeMetadata.asLatest.pallets.map(m => m.name.toString().toLowerCase());76  return modulesNames;77}7879export async function missingRequiredPallets(requiredPallets: string[]): Promise<string[]> {80  return await usingApi(async api => {81    const pallets = getModuleNames(api);8283    return requiredPallets.filter(p => !pallets.includes(p));84  });85}8687export async function checkPalletsPresence(requiredPallets: string[]): Promise<boolean> {88  return (await missingRequiredPallets(requiredPallets)).length == 0;89}9091export async function requirePallets(mocha: Context, requiredPallets: string[]) {92  const missingPallets = await missingRequiredPallets(requiredPallets);9394  if (missingPallets.length > 0) {95    const skippingTestMsg = `\tSkipping test "${mocha.test?.title}".`;96    const missingPalletsMsg = `\tThe following pallets are missing:\n\t- ${missingPallets.join('\n\t- ')}`;97    const skipMsg = `${skippingTestMsg}\n${missingPalletsMsg}`;9899    console.error('\x1b[38:5:208m%s\x1b[0m', skipMsg);100101    mocha.skip();102  }103}104105export function bigIntToSub(api: ApiPromise, number: bigint) {106  return api.registry.createType('AccountId', '0x' + number.toString(16).padStart(64, '0')).toJSON();107}108109export function bigIntToDecimals(number: bigint, decimals = 18): string {110  const numberStr = number.toString();111  const dotPos = numberStr.length - decimals;112113  if (dotPos <= 0) {114    return '0.' + '0'.repeat(Math.abs(dotPos)) + numberStr;115  } else {116    const intPart = numberStr.substring(0, dotPos);117    const fractPart = numberStr.substring(dotPos);118    return intPart + '.' + fractPart;119  }120}121122export function normalizeAccountId(input: string | AccountId | CrossAccountId | IKeyringPair): CrossAccountId {123  if (typeof input === 'string') {124    if (input.length >= 47) {125      return {Substrate: input};126    } else if (input.length === 42 && input.startsWith('0x')) {127      return {Ethereum: input.toLowerCase()};128    } else if (input.length === 40 && !input.startsWith('0x')) {129      return {Ethereum: '0x' + input.toLowerCase()};130    } else {131      throw new Error(`Unknown address format: "${input}"`);132    }133  }134  if ('address' in input) {135    return {Substrate: input.address};136  }137  if ('Ethereum' in input) {138    return {139      Ethereum: input.Ethereum.toLowerCase(),140    };141  } else if ('ethereum' in input) {142    return {143      Ethereum: (input as any).ethereum.toLowerCase(),144    };145  } else if ('Substrate' in input) {146    return input;147  } else if ('substrate' in input) {148    return {149      Substrate: (input as any).substrate,150    };151  }152153  // AccountId154  return {Substrate: input.toString()};155}156export function toSubstrateAddress(input: string | CrossAccountId | IKeyringPair): string {157  input = normalizeAccountId(input);158  if ('Substrate' in input) {159    return input.Substrate;160  } else {161    return evmToAddress(input.Ethereum);162  }163}164165export const U128_MAX = (1n << 128n) - 1n;166167const MICROUNIQUE = 1_000_000_000_000n;168const MILLIUNIQUE = 1_000n * MICROUNIQUE;169const CENTIUNIQUE = 10n * MILLIUNIQUE;170export const UNIQUE = 100n * CENTIUNIQUE;171172interface GenericResult<T> {173  success: boolean;174  data: T | null;175}176177interface CreateCollectionResult {178  success: boolean;179  collectionId: number;180}181182interface CreateItemResult {183  success: boolean;184  collectionId: number;185  itemId: number;186  recipient?: CrossAccountId;187  amount?: number;188}189190interface DestroyItemResult {191  success: boolean;192  collectionId: number;193  itemId: number;194  owner: CrossAccountId;195  amount: number;196}197198interface TransferResult {199  collectionId: number;200  itemId: number;201  sender?: CrossAccountId;202  recipient?: CrossAccountId;203  value: bigint;204}205206interface IReFungibleOwner {207  fraction: BN;208  owner: number[];209}210211interface IGetMessage {212  checkMsgUnqMethod: string;213  checkMsgTrsMethod: string;214  checkMsgSysMethod: string;215}216217export interface IFungibleTokenDataType {218  value: number;219}220221export interface IChainLimits {222  collectionNumbersLimit: number;223  accountTokenOwnershipLimit: number;224  collectionsAdminsLimit: number;225  customDataLimit: number;226  nftSponsorTransferTimeout: number;227  fungibleSponsorTransferTimeout: number;228  refungibleSponsorTransferTimeout: number;229  //offchainSchemaLimit: number;230  //constOnChainSchemaLimit: number;231}232233export interface IReFungibleTokenDataType {234  owner: IReFungibleOwner[];235}236237export function uniqueEventMessage(events: EventRecord[]): IGetMessage {238  let checkMsgUnqMethod = '';239  let checkMsgTrsMethod = '';240  let checkMsgSysMethod = '';241  events.forEach(({event: {method, section}}) => {242    if (section === 'common') {243      checkMsgUnqMethod = method;244    } else if (section === 'treasury') {245      checkMsgTrsMethod = method;246    } else if (section === 'system') {247      checkMsgSysMethod = method;248    } else { return null; }249  });250  const result: IGetMessage = {251    checkMsgUnqMethod,252    checkMsgTrsMethod,253    checkMsgSysMethod,254  };255  return result;256}257258export function getEvent<T extends Event>(events: EventRecord[], check: (event: IEvent<AnyTuple>) => event is T): T | undefined {259  const event = events.find(r => check(r.event));260  if (!event) return;261  return event.event as T;262}263264export function getGenericResult<T>(events: EventRecord[]): GenericResult<T>;265export function getGenericResult<T>(266  events: EventRecord[],267  expectSection: string,268  expectMethod: string,269  extractAction: (data: GenericEventData) => T270): GenericResult<T>;271272export function getGenericResult<T>(273  events: EventRecord[],274  expectSection?: string,275  expectMethod?: string,276  extractAction?: (data: GenericEventData) => T,277): GenericResult<T> {278  let success = false;279  let successData = null;280281  events.forEach(({event: {data, method, section}}) => {282    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);283    if (method === 'ExtrinsicSuccess') {284      success = true;285    } else if ((expectSection == section) && (expectMethod == method)) {286      successData = extractAction!(data as any);287    }288  });289290  const result: GenericResult<T> = {291    success,292    data: successData,293  };294  return result;295}296297export function getCreateCollectionResult(events: EventRecord[]): CreateCollectionResult {298  const genericResult = getGenericResult(events, 'common', 'CollectionCreated', (data) => parseInt(data[0].toString(), 10));299  const result: CreateCollectionResult = {300    success: genericResult.success,301    collectionId: genericResult.data ?? 0,302  };303  return result;304}305306export function getCreateItemsResult(events: EventRecord[]): CreateItemResult[] {307  const results: CreateItemResult[] = [];308309  const genericResult = getGenericResult<CreateItemResult[]>(events, 'common', 'ItemCreated', (data) => {310    const collectionId = parseInt(data[0].toString(), 10);311    const itemId = parseInt(data[1].toString(), 10);312    const recipient = normalizeAccountId(data[2].toJSON() as any);313    const amount = parseInt(data[3].toString(), 10);314315    const itemRes: CreateItemResult = {316      success: true,317      collectionId,318      itemId,319      recipient,320      amount,321    };322323    results.push(itemRes);324    return results;325  });326327  if (!genericResult.success) return [];328  return results;329}330331export function getCreateItemResult(events: EventRecord[]): CreateItemResult {332  const genericResult = getGenericResult(events, 'common', 'ItemCreated', (data) => data.map(function(value) { return value.toJSON(); }));333334  if (genericResult.data == null)335    return {336      success: genericResult.success,337      collectionId: 0,338      itemId: 0,339      amount: 0,340    };341  else342    return {343      success: genericResult.success,344      collectionId: genericResult.data[0] as number,345      itemId: genericResult.data[1] as number,346      recipient: normalizeAccountId(genericResult.data![2] as any),347      amount: genericResult.data[3] as number,348    };349}350351export function getDestroyItemsResult(events: EventRecord[]): DestroyItemResult[] {352  const results: DestroyItemResult[] = [];353354  const genericResult = getGenericResult<DestroyItemResult[]>(events, 'common', 'ItemDestroyed', (data) => {355    const collectionId = parseInt(data[0].toString(), 10);356    const itemId = parseInt(data[1].toString(), 10);357    const owner = normalizeAccountId(data[2].toJSON() as any);358    const amount = parseInt(data[3].toString(), 10);359360    const itemRes: DestroyItemResult = {361      success: true,362      collectionId,363      itemId,364      owner,365      amount,366    };367368    results.push(itemRes);369    return results;370  });371372  if (!genericResult.success) return [];373  return results;374}375376export function getTransferResult(api: ApiPromise, events: EventRecord[]): TransferResult {377  for (const {event} of events) {378    if (api.events.common.Transfer.is(event)) {379      const [collection, token, sender, recipient, value] = event.data;380      return {381        collectionId: collection.toNumber(),382        itemId: token.toNumber(),383        sender: normalizeAccountId(sender.toJSON() as any),384        recipient: normalizeAccountId(recipient.toJSON() as any),385        value: value.toBigInt(),386      };387    }388  }389  throw new Error('no transfer event');390}391392interface Nft {393  type: 'NFT';394}395396interface Fungible {397  type: 'Fungible';398  decimalPoints: number;399}400401interface ReFungible {402  type: 'ReFungible';403}404405export type CollectionMode = Nft | Fungible | ReFungible;406407export type Property = {408  key: any,409  value: any,410};411412type Permission = {413  mutable: boolean;414  collectionAdmin: boolean;415  tokenOwner: boolean;416}417418type PropertyPermission = {419  key: any;420  permission: Permission;421}422423export type CreateCollectionParams = {424  mode: CollectionMode,425  name: string,426  description: string,427  tokenPrefix: string,428  properties?: Array<Property>,429  propPerm?: Array<PropertyPermission>430};431432const defaultCreateCollectionParams: CreateCollectionParams = {433  description: 'description',434  mode: {type: 'NFT'},435  name: 'name',436  tokenPrefix: 'prefix',437};438439export async function440createCollection(441  api: ApiPromise,442  sender: IKeyringPair,443  params: Partial<CreateCollectionParams> = {},444): Promise<CreateCollectionResult> {445  const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};446447  let modeprm = {};448  if (mode.type === 'NFT') {449    modeprm = {nft: null};450  } else if (mode.type === 'Fungible') {451    modeprm = {fungible: mode.decimalPoints};452  } else if (mode.type === 'ReFungible') {453    modeprm = {refungible: null};454  }455456  const tx = api.tx.unique.createCollectionEx({457    name: strToUTF16(name),458    description: strToUTF16(description),459    tokenPrefix: strToUTF16(tokenPrefix),460    mode: modeprm as any,461  });462  const events = await executeTransaction(api, sender, tx);463  return getCreateCollectionResult(events);464}465466export async function createCollectionExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {467  const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};468469  let collectionId = 0;470  await usingApi(async (api, privateKeyWrapper) => {471    // Get number of collections before the transaction472    const collectionCountBefore = await getCreatedCollectionCount(api);473474    // Run the CreateCollection transaction475    const alicePrivateKey = privateKeyWrapper('//Alice');476477    const result = await createCollection(api, alicePrivateKey, params);478479    // Get number of collections after the transaction480    const collectionCountAfter = await getCreatedCollectionCount(api);481482    // Get the collection483    const collection = await queryCollectionExpectSuccess(api, result.collectionId);484485    // What to expect486    // tslint:disable-next-line:no-unused-expression487    expect(result.success).to.be.true;488    expect(result.collectionId).to.be.equal(collectionCountAfter);489    // tslint:disable-next-line:no-unused-expression490    expect(collection).to.be.not.null;491    expect(collectionCountAfter).to.be.equal(collectionCountBefore + 1, 'Error: NFT collection NOT created.');492    expect(collection.owner.toString()).to.be.equal(toSubstrateAddress(alicePrivateKey));493    expect(utf16ToStr(collection.name.toJSON() as any)).to.be.equal(name);494    expect(utf16ToStr(collection.description.toJSON() as any)).to.be.equal(description);495    expect(hexToStr(collection.tokenPrefix.toJSON())).to.be.equal(tokenPrefix);496497    collectionId = result.collectionId;498  });499500  return collectionId;501}502503export async function createCollectionWithPropsExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {504  const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};505506  let collectionId = 0;507  await usingApi(async (api, privateKeyWrapper) => {508    // Get number of collections before the transaction509    const collectionCountBefore = await getCreatedCollectionCount(api);510511    // Run the CreateCollection transaction512    const alicePrivateKey = privateKeyWrapper('//Alice');513514    let modeprm = {};515    if (mode.type === 'NFT') {516      modeprm = {nft: null};517    } else if (mode.type === 'Fungible') {518      modeprm = {fungible: mode.decimalPoints};519    } else if (mode.type === 'ReFungible') {520      modeprm = {refungible: null};521    }522523    const tx = api.tx.unique.createCollectionEx({name: strToUTF16(name), description: strToUTF16(description), tokenPrefix: strToUTF16(tokenPrefix), mode: modeprm as any, properties: params.properties, tokenPropertyPermissions: params.propPerm});524    const events = await submitTransactionAsync(alicePrivateKey, tx);525    const result = getCreateCollectionResult(events);526527    // Get number of collections after the transaction528    const collectionCountAfter = await getCreatedCollectionCount(api);529530    // Get the collection531    const collection = await queryCollectionExpectSuccess(api, result.collectionId);532533    // What to expect534    // tslint:disable-next-line:no-unused-expression535    expect(result.success).to.be.true;536    expect(result.collectionId).to.be.equal(collectionCountAfter);537    // tslint:disable-next-line:no-unused-expression538    expect(collection).to.be.not.null;539    expect(collectionCountAfter).to.be.equal(collectionCountBefore + 1, 'Error: NFT collection NOT created.');540    expect(collection.owner.toString()).to.be.equal(toSubstrateAddress(alicePrivateKey));541    expect(utf16ToStr(collection.name.toJSON() as any)).to.be.equal(name);542    expect(utf16ToStr(collection.description.toJSON() as any)).to.be.equal(description);543    expect(hexToStr(collection.tokenPrefix.toJSON())).to.be.equal(tokenPrefix);544545546    collectionId = result.collectionId;547  });548549  return collectionId;550}551552export async function createCollectionWithPropsExpectFailure(params: Partial<CreateCollectionParams> = {}) {553  const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};554555  await usingApi(async (api, privateKeyWrapper) => {556    // Get number of collections before the transaction557    const collectionCountBefore = await getCreatedCollectionCount(api);558559    // Run the CreateCollection transaction560    const alicePrivateKey = privateKeyWrapper('//Alice');561562    let modeprm = {};563    if (mode.type === 'NFT') {564      modeprm = {nft: null};565    } else if (mode.type === 'Fungible') {566      modeprm = {fungible: mode.decimalPoints};567    } else if (mode.type === 'ReFungible') {568      modeprm = {refungible: null};569    }570571    const tx = api.tx.unique.createCollectionEx({name: strToUTF16(name), description: strToUTF16(description), tokenPrefix: strToUTF16(tokenPrefix), mode: modeprm as any, properties: params.properties, tokenPropertyPermissions: params.propPerm});572    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;573574575    // Get number of collections after the transaction576    const collectionCountAfter = await getCreatedCollectionCount(api);577578    expect(collectionCountAfter).to.be.equal(collectionCountBefore, 'Error: Collection with incorrect data created.');579  });580}581582export async function createCollectionExpectFailure(params: Partial<CreateCollectionParams> = {}) {583  const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};584585  let modeprm = {};586  if (mode.type === 'NFT') {587    modeprm = {nft: null};588  } else if (mode.type === 'Fungible') {589    modeprm = {fungible: mode.decimalPoints};590  } else if (mode.type === 'ReFungible') {591    modeprm = {refungible: null};592  }593594  await usingApi(async (api, privateKeyWrapper) => {595    // Get number of collections before the transaction596    const collectionCountBefore = await getCreatedCollectionCount(api);597598    // Run the CreateCollection transaction599    const alicePrivateKey = privateKeyWrapper('//Alice');600    const tx = api.tx.unique.createCollectionEx({name: strToUTF16(name), description: strToUTF16(description), tokenPrefix: strToUTF16(tokenPrefix), mode: modeprm as any});601    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;602603    // Get number of collections after the transaction604    const collectionCountAfter = await getCreatedCollectionCount(api);605606    // What to expect607    expect(collectionCountAfter).to.be.equal(collectionCountBefore, 'Error: Collection with incorrect data created.');608  });609}610611export async function findUnusedAddress(api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair, seedAddition = ''): Promise<IKeyringPair> {612  let bal = 0n;613  let unused;614  do {615    const randomSeed = 'seed' + Math.floor(Math.random() * Math.floor(10000)) + seedAddition;616    unused = privateKeyWrapper(`//${randomSeed}`);617    bal = (await api.query.system.account(unused.address)).data.free.toBigInt();618  } while (bal !== 0n);619  return unused;620}621622export async function getAllowance(api: ApiPromise, collectionId: number, owner: CrossAccountId | string | IKeyringPair, approved: CrossAccountId | string | IKeyringPair, tokenId: number) {623  return (await api.rpc.unique.allowance(collectionId, normalizeAccountId(owner), normalizeAccountId(approved), tokenId)).toBigInt();624}625626export function findUnusedAddresses(api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair, amount: number): Promise<IKeyringPair[]> {627  return Promise.all(new Array(amount).fill(null).map(() => findUnusedAddress(api, privateKeyWrapper, '_' + Date.now())));628}629630export async function findNotExistingCollection(api: ApiPromise): Promise<number> {631  const totalNumber = await getCreatedCollectionCount(api);632  const newCollection: number = totalNumber + 1;633  return newCollection;634}635636function getDestroyResult(events: EventRecord[]): boolean {637  let success = false;638  events.forEach(({event: {method}}) => {639    if (method == 'ExtrinsicSuccess') {640      success = true;641    }642  });643  return success;644}645646export async function destroyCollectionExpectFailure(collectionId: number, senderSeed = '//Alice') {647  await usingApi(async (api, privateKeyWrapper) => {648    // Run the DestroyCollection transaction649    const alicePrivateKey = privateKeyWrapper(senderSeed);650    const tx = api.tx.unique.destroyCollection(collectionId);651    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;652  });653}654655export async function destroyCollectionExpectSuccess(collectionId: number, senderSeed = '//Alice') {656  await usingApi(async (api, privateKeyWrapper) => {657    // Run the DestroyCollection transaction658    const alicePrivateKey = privateKeyWrapper(senderSeed);659    const tx = api.tx.unique.destroyCollection(collectionId);660    const events = await submitTransactionAsync(alicePrivateKey, tx);661    const result = getDestroyResult(events);662    expect(result).to.be.true;663664    // What to expect665    expect(await getDetailedCollectionInfo(api, collectionId)).to.be.null;666  });667}668669export async function setCollectionLimitsExpectSuccess(sender: IKeyringPair, collectionId: number, limits: any) {670  await usingApi(async (api) => {671    const tx = api.tx.unique.setCollectionLimits(collectionId, limits);672    const events = await submitTransactionAsync(sender, tx);673    const result = getGenericResult(events);674675    expect(result.success).to.be.true;676  });677}678679export const setCollectionPermissionsExpectSuccess = async (sender: IKeyringPair, collectionId: number, permissions: any) => {680  await usingApi(async(api) => {681    const tx = api.tx.unique.setCollectionPermissions(collectionId, permissions);682    const events = await submitTransactionAsync(sender, tx);683    const result = getGenericResult(events);684685    expect(result.success).to.be.true;686  });687};688689export async function setCollectionLimitsExpectFailure(sender: IKeyringPair, collectionId: number, limits: any) {690  await usingApi(async (api) => {691    const tx = api.tx.unique.setCollectionLimits(collectionId, limits);692    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;693    const result = getGenericResult(events);694695    expect(result.success).to.be.false;696  });697}698699export async function setCollectionSponsorExpectSuccess(collectionId: number, sponsor: string, sender = '//Alice') {700  await usingApi(async (api, privateKeyWrapper) => {701702    // Run the transaction703    const senderPrivateKey = privateKeyWrapper(sender);704    const tx = api.tx.unique.setCollectionSponsor(collectionId, sponsor);705    const events = await submitTransactionAsync(senderPrivateKey, tx);706    const result = getGenericResult(events);707708    // Get the collection709    const collection = await queryCollectionExpectSuccess(api, collectionId);710711    // What to expect712    expect(result.success).to.be.true;713    expect(collection.sponsorship.toJSON()).to.deep.equal({714      unconfirmed: sponsor,715    });716  });717}718719export async function removeCollectionSponsorExpectSuccess(collectionId: number, sender = '//Alice') {720  await usingApi(async (api, privateKeyWrapper) => {721722    // Run the transaction723    const alicePrivateKey = privateKeyWrapper(sender);724    const tx = api.tx.unique.removeCollectionSponsor(collectionId);725    const events = await submitTransactionAsync(alicePrivateKey, tx);726    const result = getGenericResult(events);727728    // Get the collection729    const collection = await queryCollectionExpectSuccess(api, collectionId);730731    // What to expect732    expect(result.success).to.be.true;733    expect(collection.sponsorship.toJSON()).to.be.deep.equal({disabled: null});734  });735}736737export async function removeCollectionSponsorExpectFailure(collectionId: number, senderSeed = '//Alice') {738  await usingApi(async (api, privateKeyWrapper) => {739740    // Run the transaction741    const alicePrivateKey = privateKeyWrapper(senderSeed);742    const tx = api.tx.unique.removeCollectionSponsor(collectionId);743    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;744  });745}746747export async function setCollectionSponsorExpectFailure(collectionId: number, sponsor: string, senderSeed = '//Alice') {748  await usingApi(async (api, privateKeyWrapper) => {749750    // Run the transaction751    const alicePrivateKey = privateKeyWrapper(senderSeed);752    const tx = api.tx.unique.setCollectionSponsor(collectionId, sponsor);753    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;754  });755}756757export async function confirmSponsorshipExpectSuccess(collectionId: number, senderSeed = '//Alice') {758  await usingApi(async (api, privateKeyWrapper) => {759760    // Run the transaction761    const sender = privateKeyWrapper(senderSeed);762    await confirmSponsorshipByKeyExpectSuccess(collectionId, sender);763  });764}765766export async function confirmSponsorshipByKeyExpectSuccess(collectionId: number, sender: IKeyringPair) {767  await usingApi(async (api, privateKeyWrapper) => {768769    // Run the transaction770    const tx = api.tx.unique.confirmSponsorship(collectionId);771    const events = await submitTransactionAsync(sender, tx);772    const result = getGenericResult(events);773774    // Get the collection775    const collection = await queryCollectionExpectSuccess(api, collectionId);776777    // What to expect778    expect(result.success).to.be.true;779    expect(collection.sponsorship.toJSON()).to.be.deep.equal({780      confirmed: sender.address,781    });782  });783}784785786export async function confirmSponsorshipExpectFailure(collectionId: number, senderSeed = '//Alice') {787  await usingApi(async (api, privateKeyWrapper) => {788789    // Run the transaction790    const sender = privateKeyWrapper(senderSeed);791    const tx = api.tx.unique.confirmSponsorship(collectionId);792    await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;793  });794}795796export async function enableContractSponsoringExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {797  await usingApi(async (api) => {798    const tx = api.tx.unique.enableContractSponsoring(contractAddress, enable);799    const events = await submitTransactionAsync(sender, tx);800    const result = getGenericResult(events);801802    expect(result.success).to.be.true;803  });804}805806export async function enableContractSponsoringExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {807  await usingApi(async (api) => {808    const tx = api.tx.unique.enableContractSponsoring(contractAddress, enable);809    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;810    const result = getGenericResult(events);811812    expect(result.success).to.be.false;813  });814}815816export async function setTransferFlagExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {817818  await usingApi(async (api) => {819820    const tx = api.tx.unique.setTransfersEnabledFlag(collectionId, enabled);821    const events = await submitTransactionAsync(sender, tx);822    const result = getGenericResult(events);823824    expect(result.success).to.be.true;825  });826}827828export async function setTransferFlagExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {829830  await usingApi(async (api) => {831832    const tx = api.tx.unique.setTransfersEnabledFlag(collectionId, enabled);833    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;834    const result = getGenericResult(events);835836    expect(result.success).to.be.false;837  });838}839840export async function setContractSponsoringRateLimitExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {841  await usingApi(async (api) => {842    const tx = api.tx.unique.setContractSponsoringRateLimit(contractAddress, rateLimit);843    const events = await submitTransactionAsync(sender, tx);844    const result = getGenericResult(events);845846    expect(result.success).to.be.true;847  });848}849850export async function setContractSponsoringRateLimitExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {851  await usingApi(async (api) => {852    const tx = api.tx.unique.setContractSponsoringRateLimit(contractAddress, rateLimit);853    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;854    const result = getGenericResult(events);855856    expect(result.success).to.be.false;857  });858}859860export async function getNextSponsored(861  api: ApiPromise,862  collectionId: number,863  account: string | CrossAccountId,864  tokenId: number,865): Promise<number> {866  return Number((await api.rpc.unique.nextSponsored(collectionId, account, tokenId)).unwrapOr(-1));867}868869export async function toggleContractAllowlistExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, value = true) {870  await usingApi(async (api) => {871    const tx = api.tx.unique.toggleContractAllowList(contractAddress, value);872    const events = await submitTransactionAsync(sender, tx);873    const result = getGenericResult(events);874875    expect(result.success).to.be.true;876  });877}878879export async function isAllowlistedInContract(contractAddress: AccountId | string, user: string) {880  let allowlisted = false;881  await usingApi(async (api) => {882    allowlisted = (await api.query.unique.contractAllowList(contractAddress, user)).toJSON() as boolean;883  });884  return allowlisted;885}886887export async function addToContractAllowListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {888  await usingApi(async (api) => {889    const tx = api.tx.unique.addToContractAllowList(contractAddress.toString(), user.toString());890    const events = await submitTransactionAsync(sender, tx);891    const result = getGenericResult(events);892893    expect(result.success).to.be.true;894  });895}896897export async function removeFromContractAllowListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {898  await usingApi(async (api) => {899    const tx = api.tx.unique.removeFromContractAllowList(contractAddress.toString(), user.toString());900    const events = await submitTransactionAsync(sender, tx);901    const result = getGenericResult(events);902903    expect(result.success).to.be.true;904  });905}906907export async function removeFromContractAllowListExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {908  await usingApi(async (api) => {909    const tx = api.tx.unique.removeFromContractAllowList(contractAddress.toString(), user.toString());910    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;911    const result = getGenericResult(events);912913    expect(result.success).to.be.false;914  });915}916917export interface CreateFungibleData {918  readonly Value: bigint;919}920921export interface CreateReFungibleData { }922export interface CreateNftData { }923924export type CreateItemData = {925  NFT: CreateNftData;926} | {927  Fungible: CreateFungibleData;928} | {929  ReFungible: CreateReFungibleData;930};931932export async function burnItem(api: ApiPromise, sender: IKeyringPair, collectionId: number, tokenId: number, value: number | bigint) : Promise<boolean> {933  const tx = api.tx.unique.burnItem(collectionId, tokenId, value);934  const events = await submitTransactionAsync(sender, tx);935  return getGenericResult(events).success;936}937938export async function burnItemExpectSuccess(sender: IKeyringPair, collectionId: number, tokenId: number, value: number | bigint = 1) {939  await usingApi(async (api) => {940    const balanceBefore = await getBalance(api, collectionId, normalizeAccountId(sender), tokenId);941    // if burning token by admin - use adminButnItemExpectSuccess942    expect(balanceBefore >= BigInt(value)).to.be.true;943944    expect(await burnItem(api, sender, collectionId, tokenId, value)).to.be.true;945946    const balanceAfter = await getBalance(api, collectionId, normalizeAccountId(sender), tokenId);947    expect(balanceAfter + BigInt(value)).to.be.equal(balanceBefore);948  });949}950951export async function burnItemExpectFailure(sender: IKeyringPair, collectionId: number, tokenId: number, value: number | bigint = 1) {952  await usingApi(async (api) => {953    const tx = api.tx.unique.burnItem(collectionId, tokenId, value);954955    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;956    const result = getCreateCollectionResult(events);957    // tslint:disable-next-line:no-unused-expression958    expect(result.success).to.be.false;959  });960}961962export async function burnFromExpectSuccess(sender: IKeyringPair, from: IKeyringPair | CrossAccountId, collectionId: number, tokenId: number, value: number | bigint = 1) {963  await usingApi(async (api) => {964    const tx = api.tx.unique.burnFrom(collectionId, normalizeAccountId(from), tokenId, value);965    const events = await submitTransactionAsync(sender, tx);966    return getGenericResult(events).success;967  });968}969970export async function971approve(972  api: ApiPromise,973  collectionId: number,974  tokenId: number, owner: IKeyringPair, approved: CrossAccountId | string | IKeyringPair, amount: number | bigint,975) {976  const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);977  const events = await submitTransactionAsync(owner, approveUniqueTx);978  return getGenericResult(events).success;979}980981export async function982approveExpectSuccess(983  collectionId: number,984  tokenId: number, owner: IKeyringPair, approved: CrossAccountId | string, amount: number | bigint = 1,985) {986  await usingApi(async (api: ApiPromise) => {987    const result = await approve(api, collectionId, tokenId, owner, approved, amount);988    expect(result).to.be.true;989990    expect(await getAllowance(api, collectionId, owner, approved, tokenId)).to.be.equal(BigInt(amount));991  });992}993994export async function adminApproveFromExpectSuccess(995  collectionId: number,996  tokenId: number, admin: IKeyringPair, owner: CrossAccountId | string, approved: CrossAccountId | string, amount: number | bigint = 1,997) {998  await usingApi(async (api: ApiPromise) => {999    const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);1000    const events = await submitTransactionAsync(admin, approveUniqueTx);1001    const result = getGenericResult(events);1002    expect(result.success).to.be.true;10031004    expect(await getAllowance(api, collectionId, owner, approved, tokenId)).to.be.equal(BigInt(amount));1005  });1006}10071008export async function1009transferFrom(1010  api: ApiPromise,1011  collectionId: number,1012  tokenId: number,1013  accountApproved: IKeyringPair,1014  accountFrom: IKeyringPair | CrossAccountId,1015  accountTo: IKeyringPair | CrossAccountId,1016  value: number | bigint,1017) {1018  const from = normalizeAccountId(accountFrom);1019  const to = normalizeAccountId(accountTo);1020  const transferFromTx = api.tx.unique.transferFrom(from, to, collectionId, tokenId, value);1021  const events = await submitTransactionAsync(accountApproved, transferFromTx);1022  return getGenericResult(events).success;1023}10241025export async function1026transferFromExpectSuccess(1027  collectionId: number,1028  tokenId: number,1029  accountApproved: IKeyringPair,1030  accountFrom: IKeyringPair | CrossAccountId,1031  accountTo: IKeyringPair | CrossAccountId,1032  value: number | bigint = 1,1033  type = 'NFT',1034) {1035  await usingApi(async (api: ApiPromise) => {1036    const from = normalizeAccountId(accountFrom);1037    const to = normalizeAccountId(accountTo);1038    let balanceBefore = 0n;1039    if (type === 'Fungible' || type === 'ReFungible') {1040      balanceBefore = await getBalance(api, collectionId, to, tokenId);1041    }1042    expect(await transferFrom(api, collectionId, tokenId, accountApproved, accountFrom, accountTo, value)).to.be.true;1043    if (type === 'NFT') {1044      expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(to);1045    }1046    if (type === 'Fungible') {1047      const balanceAfter = await getBalance(api, collectionId, to, tokenId);1048      if (JSON.stringify(to) !== JSON.stringify(from)) {1049        expect(balanceAfter - balanceBefore).to.be.equal(BigInt(value));1050      } else {1051        expect(balanceAfter).to.be.equal(balanceBefore);1052      }1053    }1054    if (type === 'ReFungible') {1055      expect(await getBalance(api, collectionId, to, tokenId)).to.be.equal(balanceBefore + BigInt(value));1056    }1057  });1058}10591060export async function1061transferFromExpectFail(1062  collectionId: number,1063  tokenId: number,1064  accountApproved: IKeyringPair,1065  accountFrom: IKeyringPair,1066  accountTo: IKeyringPair,1067  value: number | bigint = 1,1068) {1069  await usingApi(async (api: ApiPromise) => {1070    const transferFromTx = api.tx.unique.transferFrom(normalizeAccountId(accountFrom.address), normalizeAccountId(accountTo.address), collectionId, tokenId, value);1071    const events = await expect(submitTransactionExpectFailAsync(accountApproved, transferFromTx)).to.be.rejected;1072    const result = getCreateCollectionResult(events);1073    // tslint:disable-next-line:no-unused-expression1074    expect(result.success).to.be.false;1075  });1076}10771078/* eslint no-async-promise-executor: "off" */1079export async function getBlockNumber(api: ApiPromise): Promise<number> {1080  return new Promise<number>(async (resolve) => {1081    const unsubscribe = await api.rpc.chain.subscribeNewHeads((head) => {1082      unsubscribe();1083      resolve(head.number.toNumber());1084    });1085  });1086}10871088export async function addCollectionAdminExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | CrossAccountId) {1089  await usingApi(async (api) => {1090    const changeAdminTx = api.tx.unique.addCollectionAdmin(collectionId, normalizeAccountId(address));1091    const events = await submitTransactionAsync(sender, changeAdminTx);1092    const result = getCreateCollectionResult(events);1093    expect(result.success).to.be.true;1094  });1095}10961097export async function adminApproveFromExpectFail(1098  collectionId: number,1099  tokenId: number, admin: IKeyringPair, owner: CrossAccountId | string, approved: CrossAccountId | string, amount: number | bigint = 1,1100) {1101  await usingApi(async (api: ApiPromise) => {1102    const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);1103    const events = await expect(submitTransactionAsync(admin, approveUniqueTx)).to.be.rejected;1104    const result = getGenericResult(events);1105    expect(result.success).to.be.false;1106  });1107}11081109export async function1110getFreeBalance(account: IKeyringPair): Promise<bigint> {1111  let balance = 0n;1112  await usingApi(async (api) => {1113    balance = BigInt((await api.query.system.account(account.address)).data.free.toString());1114  });11151116  return balance;1117}11181119export async function paraSiblingSovereignAccount(paraid: number): Promise<string> {1120  return usingApi(async api => {1121    // We are getting a *sibling* parachain sovereign account,1122    // so we need a sibling prefix: encoded(b"sibl") == 0x7369626c1123    const siblingPrefix = '0x7369626c';11241125    const encodedParaId = api.createType('u32', paraid).toHex(true).substring(2);1126    const suffix = '000000000000000000000000000000000000000000000000';11271128    return siblingPrefix + encodedParaId + suffix;1129  });1130}11311132export async function transferBalanceTo(api: ApiPromise, source: IKeyringPair, target: string, amount = 1000n * UNIQUE) {1133  const tx = api.tx.balances.transfer(target, amount);1134  const events = await submitTransactionAsync(source, tx);1135  const result = getGenericResult(events);1136  expect(result.success).to.be.true;1137}11381139export async function scheduleAt(1140  api: ApiPromise,1141  operationTx: any,1142  sender: IKeyringPair,1143  executionBlockNumber: number,1144  scheduledId: string,1145  period = 1,1146  repetitions = 1,1147): Promise<any> {1148  const scheduleTx = api.tx.scheduler.scheduleNamed(1149    scheduledId,1150    executionBlockNumber, 1151    repetitions > 1 ? [period, repetitions] : null, 1152    0, 1153    {Value: operationTx as any},1154  );11551156  return executeTransaction(api, sender, scheduleTx);1157}11581159export async function scheduleAfter(1160  api: ApiPromise,1161  operationTx: any,1162  sender: IKeyringPair,1163  blocksBeforeExecution: number,1164  scheduledId: string,1165  period = 1,1166  repetitions = 1,1167): Promise<any> {1168  const scheduleTx = api.tx.scheduler.scheduleNamedAfter(1169    scheduledId,1170    blocksBeforeExecution, 1171    repetitions > 1 ? [period, repetitions] : null, 1172    0, 1173    {Value: operationTx as any},1174  );11751176  return executeTransaction(api, sender, scheduleTx);1177}11781179export async function cancelScheduled(1180  api: ApiPromise,1181  sender: IKeyringPair,1182  scheduledId: string,1183): Promise<any> {1184  const cancelTx = api.tx.scheduler.cancelNamed(scheduledId);1185  return executeTransaction(api, sender, cancelTx);1186}11871188export async function1189scheduleTransferExpectSuccess(1190  api: ApiPromise,1191  collectionId: number,1192  tokenId: number,1193  sender: IKeyringPair,1194  recipient: IKeyringPair,1195  transferAmount: number | bigint = 1,1196  blocksBeforeExecution: number,1197  scheduledId: string,1198  scheduleMethod: 'at' | 'after' = 'at',1199) {1200  const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient.address), collectionId, tokenId, transferAmount);12011202  if (scheduleMethod == 'at') {1203    const blockNumber: number | undefined = await getBlockNumber(api);1204    const expectedBlockNumber = blockNumber + blocksBeforeExecution;1205    //expect(expectedBlockNumber).to.be.greaterThan(0);12061207    await expect(scheduleAt(api, transferTx, sender, expectedBlockNumber, scheduledId)).to.not.be.rejected;1208  } else {1209    await expect(scheduleAfter(api, transferTx, sender, blocksBeforeExecution, scheduledId)).to.not.be.rejected;1210  }12111212  expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(sender.address));1213}12141215export async function1216scheduleTransferAndWaitExpectSuccess(1217  api: ApiPromise,1218  collectionId: number,1219  tokenId: number,1220  sender: IKeyringPair,1221  recipient: IKeyringPair,1222  transferAmount: number | bigint = 1,1223  blocksBeforeExecution: number,1224  scheduledId: string,1225  scheduleMethod: 'at' | 'after' = 'at',1226) {1227  await scheduleTransferExpectSuccess(1228    api, 1229    collectionId, 1230    tokenId, 1231    sender, 1232    recipient, 1233    transferAmount, 1234    blocksBeforeExecution, 1235    scheduledId, 1236    scheduleMethod,1237  );12381239  const recipientBalanceBefore = await getFreeBalance(recipient);12401241  // sleep for n + 1 blocks1242  await waitNewBlocks(blocksBeforeExecution + 1);12431244  const recipientBalanceAfter = await getFreeBalance(recipient);12451246  expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(recipient.address));1247  expect(recipientBalanceAfter).to.be.equal(recipientBalanceBefore);1248}12491250export async function1251scheduleTransferFundsExpectSuccess(1252  api: ApiPromise,1253  amount: bigint,1254  sender: IKeyringPair,1255  recipient: IKeyringPair,1256  blocksBeforeExecution: number,1257  scheduledId: string,1258  period = 1,1259  repetitions = 1,1260) {1261  const transferTx = api.tx.balances.transfer(recipient.address, amount);12621263  const balanceBefore = await getFreeBalance(recipient);1264  1265  await expect(scheduleAfter(api, transferTx, sender, blocksBeforeExecution, scheduledId, period, repetitions)).to.not.be.rejected;12661267  expect(await getFreeBalance(recipient)).to.be.equal(balanceBefore);1268}12691270export async function1271transfer(1272  api: ApiPromise,1273  collectionId: number,1274  tokenId: number,1275  sender: IKeyringPair,1276  recipient: IKeyringPair | CrossAccountId,1277  value: number | bigint,1278) : Promise<boolean> {1279  const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient), collectionId, tokenId, value);1280  const events = await executeTransaction(api, sender, transferTx);1281  return getGenericResult(events).success;1282}12831284export async function1285transferExpectSuccess(1286  collectionId: number,1287  tokenId: number,1288  sender: IKeyringPair,1289  recipient: IKeyringPair | CrossAccountId,1290  value: number | bigint = 1,1291  type = 'NFT',1292) {1293  await usingApi(async (api: ApiPromise) => {1294    const from = normalizeAccountId(sender);1295    const to = normalizeAccountId(recipient);12961297    let balanceBefore = 0n;1298    if (type === 'Fungible' || type === 'ReFungible') {1299      balanceBefore = await getBalance(api, collectionId, to, tokenId);1300    }13011302    const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient), collectionId, tokenId, value);1303    const events = await executeTransaction(api, sender, transferTx);1304    const result = getTransferResult(api, events);13051306    expect(result.collectionId).to.be.equal(collectionId);1307    expect(result.itemId).to.be.equal(tokenId);1308    expect(result.sender).to.be.deep.equal(normalizeAccountId(sender.address));1309    expect(result.recipient).to.be.deep.equal(to);1310    expect(result.value).to.be.equal(BigInt(value));13111312    if (type === 'NFT') {1313      expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(to);1314    }1315    if (type === 'Fungible' || type === 'ReFungible') {1316      const balanceAfter = await getBalance(api, collectionId, to, tokenId);1317      if (JSON.stringify(to) !== JSON.stringify(from)) {1318        expect(balanceAfter - balanceBefore).to.be.equal(BigInt(value));1319      } else {1320        expect(balanceAfter).to.be.equal(balanceBefore);1321      }1322    }1323  });1324}13251326export async function1327transferExpectFailure(1328  collectionId: number,1329  tokenId: number,1330  sender: IKeyringPair,1331  recipient: IKeyringPair | CrossAccountId,1332  value: number | bigint = 1,1333) {1334  await usingApi(async (api: ApiPromise) => {1335    const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient), collectionId, tokenId, value);1336    const events = await expect(submitTransactionExpectFailAsync(sender, transferTx)).to.be.rejected;1337    const result = getGenericResult(events);1338    // if (events && Array.isArray(events)) {1339    //   const result = getCreateCollectionResult(events);1340    // tslint:disable-next-line:no-unused-expression1341    expect(result.success).to.be.false;1342    //}1343  });1344}13451346export async function1347approveExpectFail(1348  collectionId: number,1349  tokenId: number, owner: IKeyringPair, approved: IKeyringPair, amount: number | bigint = 1,1350) {1351  await usingApi(async (api: ApiPromise) => {1352    const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved.address), collectionId, tokenId, amount);1353    const events = await expect(submitTransactionExpectFailAsync(owner, approveUniqueTx)).to.be.rejected;1354    const result = getCreateCollectionResult(events);1355    // tslint:disable-next-line:no-unused-expression1356    expect(result.success).to.be.false;1357  });1358}13591360export async function getBalance(1361  api: ApiPromise,1362  collectionId: number,1363  owner: string | CrossAccountId | IKeyringPair,1364  token: number,1365): Promise<bigint> {1366  return (await api.rpc.unique.balance(collectionId, normalizeAccountId(owner), token)).toBigInt();1367}1368export async function getTokenOwner(1369  api: ApiPromise,1370  collectionId: number,1371  token: number,1372): Promise<CrossAccountId> {1373  const owner = (await api.rpc.unique.tokenOwner(collectionId, token)).toJSON() as any;1374  if (owner == null) throw new Error('owner == null');1375  return normalizeAccountId(owner);1376}1377export async function getTopmostTokenOwner(1378  api: ApiPromise,1379  collectionId: number,1380  token: number,1381): Promise<CrossAccountId> {1382  const owner = (await api.rpc.unique.topmostTokenOwner(collectionId, token)).toJSON() as any;1383  if (owner == null) throw new Error('owner == null');1384  return normalizeAccountId(owner);1385}1386export async function getTokenChildren(1387  api: ApiPromise,1388  collectionId: number,1389  tokenId: number,1390): Promise<UpDataStructsTokenChild[]> {1391  return (await api.rpc.unique.tokenChildren(collectionId, tokenId)).toJSON() as any;1392}1393export async function isTokenExists(1394  api: ApiPromise,1395  collectionId: number,1396  token: number,1397): Promise<boolean> {1398  return (await api.rpc.unique.tokenExists(collectionId, token)).toJSON();1399}1400export async function getLastTokenId(1401  api: ApiPromise,1402  collectionId: number,1403): Promise<number> {1404  return (await api.rpc.unique.lastTokenId(collectionId)).toJSON();1405}1406export async function getAdminList(1407  api: ApiPromise,1408  collectionId: number,1409): Promise<string[]> {1410  return (await api.rpc.unique.adminlist(collectionId)).toHuman() as any;1411}1412export async function getTokenProperties(1413  api: ApiPromise,1414  collectionId: number,1415  tokenId: number,1416  propertyKeys: string[],1417): Promise<UpDataStructsProperty[]> {1418  return (await api.rpc.unique.tokenProperties(collectionId, tokenId, propertyKeys)).toHuman() as any;1419}14201421export async function createFungibleItemExpectSuccess(1422  sender: IKeyringPair,1423  collectionId: number,1424  data: CreateFungibleData,1425  owner: CrossAccountId | string = sender.address,1426) {1427  return await usingApi(async (api) => {1428    const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), {Fungible: data});14291430    const events = await submitTransactionAsync(sender, tx);1431    const result = getCreateItemResult(events);14321433    expect(result.success).to.be.true;1434    return result.itemId;1435  });1436}14371438export async function createMultipleItemsExpectSuccess(sender: IKeyringPair, collectionId: number, itemsData: any, owner: CrossAccountId | string = sender.address) {1439  await usingApi(async (api) => {1440    const to = normalizeAccountId(owner);1441    const tx = api.tx.unique.createMultipleItems(collectionId, to, itemsData);14421443    const events = await submitTransactionAsync(sender, tx);1444    expect(getGenericResult(events).success).to.be.true;1445  });1446}14471448export async function createMultipleItemsWithPropsExpectSuccess(sender: IKeyringPair, collectionId: number, itemsData: any, owner: CrossAccountId | string = sender.address) {1449  await usingApi(async (api) => {1450    const to = normalizeAccountId(owner);1451    const tx = api.tx.unique.createMultipleItems(collectionId, to, itemsData);14521453    const events = await submitTransactionAsync(sender, tx);1454    const result = getCreateItemsResult(events);14551456    for (const res of result) {1457      expect(await api.rpc.unique.tokenProperties(collectionId, res.itemId)).not.to.be.empty;1458    }1459  });1460}14611462export async function createMultipleItemsExWithPropsExpectSuccess(sender: IKeyringPair, collectionId: number, itemsData: any) {1463  await usingApi(async (api) => {1464    const tx = api.tx.unique.createMultipleItemsEx(collectionId, itemsData);14651466    const events = await submitTransactionAsync(sender, tx);1467    const result = getCreateItemsResult(events);14681469    for (const res of result) {1470      expect(await api.rpc.unique.tokenProperties(collectionId, res.itemId)).not.to.be.empty;1471    }1472  });1473}14741475export async function createItemWithPropsExpectSuccess(sender: IKeyringPair, collectionId: number, createMode: string, props:  Array<Property>, owner: CrossAccountId | string = sender.address) {1476  let newItemId = 0;1477  await usingApi(async (api) => {1478    const to = normalizeAccountId(owner);1479    const itemCountBefore = await getLastTokenId(api, collectionId);1480    const itemBalanceBefore = await getBalance(api, collectionId, to, newItemId);14811482    let tx;1483    if (createMode === 'Fungible') {1484      const createData = {fungible: {value: 10}};1485      tx = api.tx.unique.createItem(collectionId, to, createData as any);1486    } else if (createMode === 'ReFungible') {1487      const createData = {refungible: {pieces: 100}};1488      tx = api.tx.unique.createItem(collectionId, to, createData as any);1489    } else {1490      const data = api.createType('UpDataStructsCreateItemData', {NFT: {properties: props}});1491      tx = api.tx.unique.createItem(collectionId, to, data as UpDataStructsCreateItemData);1492    }14931494    const events = await submitTransactionAsync(sender, tx);1495    const result = getCreateItemResult(events);14961497    const itemCountAfter = await getLastTokenId(api, collectionId);1498    const itemBalanceAfter = await getBalance(api, collectionId, to, newItemId);14991500    if (createMode === 'NFT') {1501      expect(await api.rpc.unique.tokenProperties(collectionId, result.itemId)).not.to.be.empty;1502    }15031504    // What to expect1505    // tslint:disable-next-line:no-unused-expression1506    expect(result.success).to.be.true;1507    if (createMode === 'Fungible') {1508      expect(itemBalanceAfter - itemBalanceBefore).to.be.equal(10n);1509    } else {1510      expect(itemCountAfter).to.be.equal(itemCountBefore + 1);1511    }1512    expect(collectionId).to.be.equal(result.collectionId);1513    expect(itemCountAfter.toString()).to.be.equal(result.itemId.toString());1514    expect(to).to.be.deep.equal(result.recipient);1515    newItemId = result.itemId;1516  });1517  return newItemId;1518}15191520export async function createItemWithPropsExpectFailure(sender: IKeyringPair, collectionId: number, createMode: string, props: Array<Property>, owner: CrossAccountId | string = sender.address) {1521  await usingApi(async (api) => {15221523    let tx;1524    if (createMode === 'NFT') {1525      const data = api.createType('UpDataStructsCreateItemData', {NFT: {properties: props}}) as UpDataStructsCreateItemData;1526      tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), data);1527    } else {1528      tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), createMode);1529    }153015311532    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1533    if(events.message && events.message.toString().indexOf('1002: Verification Error') > -1) return;1534    const result = getCreateItemResult(events);15351536    expect(result.success).to.be.false;1537  });1538}15391540export async function createItemExpectSuccess(sender: IKeyringPair, collectionId: number, createMode: string, owner: CrossAccountId | string = sender.address) {1541  let newItemId = 0;1542  await usingApi(async (api) => {1543    const to = normalizeAccountId(owner);1544    const itemCountBefore = await getLastTokenId(api, collectionId);1545    const itemBalanceBefore = await getBalance(api, collectionId, to, newItemId);15461547    let tx;1548    if (createMode === 'Fungible') {1549      const createData = {fungible: {value: 10}};1550      tx = api.tx.unique.createItem(collectionId, to, createData as any);1551    } else if (createMode === 'ReFungible') {1552      const createData = {refungible: {pieces: 100}};1553      tx = api.tx.unique.createItem(collectionId, to, createData as any);1554    } else {1555      const createData = {nft: {}};1556      tx = api.tx.unique.createItem(collectionId, to, createData as any);1557    }15581559    const events = await executeTransaction(api, sender, tx);1560    const result = getCreateItemResult(events);15611562    const itemCountAfter = await getLastTokenId(api, collectionId);1563    const itemBalanceAfter = await getBalance(api, collectionId, to, newItemId);15641565    // What to expect1566    // tslint:disable-next-line:no-unused-expression1567    expect(result.success).to.be.true;1568    if (createMode === 'Fungible') {1569      expect(itemBalanceAfter - itemBalanceBefore).to.be.equal(10n);1570    } else {1571      expect(itemCountAfter).to.be.equal(itemCountBefore + 1);1572    }1573    expect(collectionId).to.be.equal(result.collectionId);1574    expect(itemCountAfter.toString()).to.be.equal(result.itemId.toString());1575    expect(to).to.be.deep.equal(result.recipient);1576    newItemId = result.itemId;1577  });1578  return newItemId;1579}15801581export async function createRefungibleToken(api: ApiPromise, sender: IKeyringPair, collectionId: number, amount: bigint, owner: CrossAccountId | IKeyringPair | string = sender.address) : Promise<CreateItemResult> {1582  const createData = {refungible: {pieces: amount}};1583  const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), createData as any);15841585  const events = await submitTransactionAsync(sender, tx);1586  return  getCreateItemResult(events);1587}15881589export async function createItemExpectFailure(sender: IKeyringPair, collectionId: number, createMode: string, owner: CrossAccountId | string = sender.address) {1590  await usingApi(async (api) => {1591    const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), createMode);15921593    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1594    const result = getCreateItemResult(events);15951596    expect(result.success).to.be.false;1597  });1598}15991600export async function setPublicAccessModeExpectSuccess(1601  sender: IKeyringPair, collectionId: number,1602  accessMode: 'Normal' | 'AllowList',1603) {1604  await usingApi(async (api) => {16051606    // Run the transaction1607    const tx = api.tx.unique.setCollectionPermissions(collectionId, {access: accessMode});1608    const events = await submitTransactionAsync(sender, tx);1609    const result = getGenericResult(events);16101611    // Get the collection1612    const collection = await queryCollectionExpectSuccess(api, collectionId);16131614    // What to expect1615    // tslint:disable-next-line:no-unused-expression1616    expect(result.success).to.be.true;1617    expect(collection.permissions.access.toHuman()).to.be.equal(accessMode);1618  });1619}16201621export async function setPublicAccessModeExpectFail(1622  sender: IKeyringPair, collectionId: number,1623  accessMode: 'Normal' | 'AllowList',1624) {1625  await usingApi(async (api) => {16261627    // Run the transaction1628    const tx = api.tx.unique.setCollectionPermissions(collectionId, {access: accessMode});1629    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1630    const result = getGenericResult(events);16311632    // What to expect1633    // tslint:disable-next-line:no-unused-expression1634    expect(result.success).to.be.false;1635  });1636}16371638export async function enableAllowListExpectSuccess(sender: IKeyringPair, collectionId: number) {1639  await setPublicAccessModeExpectSuccess(sender, collectionId, 'AllowList');1640}16411642export async function enableAllowListExpectFail(sender: IKeyringPair, collectionId: number) {1643  await setPublicAccessModeExpectFail(sender, collectionId, 'AllowList');1644}16451646export async function disableAllowListExpectSuccess(sender: IKeyringPair, collectionId: number) {1647  await setPublicAccessModeExpectSuccess(sender, collectionId, 'Normal');1648}16491650export async function setMintPermissionExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {1651  await usingApi(async (api) => {16521653    // Run the transaction1654    const tx = api.tx.unique.setCollectionPermissions(collectionId, {mintMode: enabled});1655    const events = await submitTransactionAsync(sender, tx);1656    const result = getGenericResult(events);1657    expect(result.success).to.be.true;16581659    // Get the collection1660    const collection = await queryCollectionExpectSuccess(api, collectionId);16611662    expect(collection.permissions.mintMode.toHuman()).to.be.equal(enabled);1663  });1664}16651666export async function enablePublicMintingExpectSuccess(sender: IKeyringPair, collectionId: number) {1667  await setMintPermissionExpectSuccess(sender, collectionId, true);1668}16691670export async function setMintPermissionExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {1671  await usingApi(async (api) => {1672    // Run the transaction1673    const tx = api.tx.unique.setCollectionPermissions(collectionId, {mintMode: enabled});1674    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1675    const result = getCreateCollectionResult(events);1676    // tslint:disable-next-line:no-unused-expression1677    expect(result.success).to.be.false;1678  });1679}16801681export async function setChainLimitsExpectFailure(sender: IKeyringPair, limits: IChainLimits) {1682  await usingApi(async (api) => {1683    // Run the transaction1684    const tx = api.tx.unique.setChainLimits(limits);1685    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1686    const result = getCreateCollectionResult(events);1687    // tslint:disable-next-line:no-unused-expression1688    expect(result.success).to.be.false;1689  });1690}16911692export async function isAllowlisted(api: ApiPromise, collectionId: number, address: string | CrossAccountId | IKeyringPair) {1693  return (await api.rpc.unique.allowed(collectionId, normalizeAccountId(address))).toJSON();1694}16951696export async function addToAllowListExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId | CrossAccountId) {1697  await usingApi(async (api) => {1698    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.false;16991700    // Run the transaction1701    const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1702    const events = await submitTransactionAsync(sender, tx);1703    const result = getGenericResult(events);1704    expect(result.success).to.be.true;17051706    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;1707  });1708}17091710export async function addToAllowListAgainExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId) {1711  await usingApi(async (api) => {17121713    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;17141715    // Run the transaction1716    const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1717    const events = await submitTransactionAsync(sender, tx);1718    const result = getGenericResult(events);1719    expect(result.success).to.be.true;17201721    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;1722  });1723}17241725export async function addToAllowListExpectFail(sender: IKeyringPair, collectionId: number, address: string | AccountId) {1726  await usingApi(async (api) => {17271728    // Run the transaction1729    const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1730    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1731    const result = getGenericResult(events);17321733    // What to expect1734    // tslint:disable-next-line:no-unused-expression1735    expect(result.success).to.be.false;1736  });1737}17381739export async function removeFromAllowListExpectSuccess(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1740  await usingApi(async (api) => {1741    // Run the transaction1742    const tx = api.tx.unique.removeFromAllowList(collectionId, normalizeAccountId(address));1743    const events = await submitTransactionAsync(sender, tx);1744    const result = getGenericResult(events);17451746    // What to expect1747    // tslint:disable-next-line:no-unused-expression1748    expect(result.success).to.be.true;1749  });1750}17511752export async function removeFromAllowListExpectFailure(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1753  await usingApi(async (api) => {1754    // Run the transaction1755    const tx = api.tx.unique.removeFromAllowList(collectionId, normalizeAccountId(address));1756    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1757    const result = getGenericResult(events);17581759    // What to expect1760    // tslint:disable-next-line:no-unused-expression1761    expect(result.success).to.be.false;1762  });1763}17641765export const getDetailedCollectionInfo = async (api: ApiPromise, collectionId: number)1766  : Promise<UpDataStructsRpcCollection | null> => {1767  return (await api.rpc.unique.collectionById(collectionId)).unwrapOr(null);1768};17691770export const getCreatedCollectionCount = async (api: ApiPromise): Promise<number> => {1771  // set global object - collectionsCount1772  return (await api.rpc.unique.collectionStats()).created.toNumber();1773};17741775export async function queryCollectionExpectSuccess(api: ApiPromise, collectionId: number): Promise<UpDataStructsRpcCollection> {1776  return (await api.rpc.unique.collectionById(collectionId)).unwrap();1777}17781779export const describe_xcm = (1780  process.env.RUN_XCM_TESTS1781    ? describe1782    : describe.skip1783);17841785export async function waitNewBlocks(blocksCount = 1): Promise<void> {1786  await usingApi(async (api) => {1787    const promise = new Promise<void>(async (resolve) => {1788      const unsubscribe = await api.rpc.chain.subscribeNewHeads(() => {1789        if (blocksCount > 0) {1790          blocksCount--;1791        } else {1792          unsubscribe();1793          resolve();1794        }1795      });1796    });1797    return promise;1798  });1799}18001801export async function waitEvent(1802  api: ApiPromise,1803  maxBlocksToWait: number,1804  eventSection: string,1805  eventMethod: string,1806): Promise<EventRecord | null> {18071808  const promise = new Promise<EventRecord | null>(async (resolve) => {1809    const unsubscribe = await api.rpc.chain.subscribeNewHeads(async header => {1810      const blockNumber = header.number.toHuman();1811      const blockHash = header.hash;1812      const eventIdStr = `${eventSection}.${eventMethod}`;1813      const waitLimitStr = `wait blocks remaining: ${maxBlocksToWait}`;18141815      console.log(`[Block #${blockNumber}] Waiting for event \`${eventIdStr}\` (${waitLimitStr})`);18161817      const apiAt = await api.at(blockHash);1818      const eventRecords = await apiAt.query.system.events();18191820      const neededEvent = eventRecords.find(r => {1821        return r.event.section == eventSection && r.event.method == eventMethod;1822      });18231824      if (neededEvent) {1825        unsubscribe();1826        resolve(neededEvent);1827      } else if (maxBlocksToWait > 0) {1828        maxBlocksToWait--;1829      } else {1830        console.log(`Event \`${eventIdStr}\` is NOT found`);18311832        unsubscribe();1833        resolve(null);1834      }1835    });1836  });1837  return promise;1838}18391840export async function repartitionRFT(1841  api: ApiPromise,1842  collectionId: number,1843  sender: IKeyringPair,1844  tokenId: number,1845  amount: bigint,1846): Promise<boolean> {1847  const tx = api.tx.unique.repartition(collectionId, tokenId, amount);1848  const events = await submitTransactionAsync(sender, tx);1849  const result = getGenericResult(events);18501851  return result.success;1852}18531854export async function itApi(name: string, cb: (apis: { api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair }) => any, opts: { only?: boolean, skip?: boolean } = {}) {1855  let i: any = it;1856  if (opts.only) i = i.only;1857  else if (opts.skip) i = i.skip;1858  i(name, async () => {1859    await usingApi(async (api, privateKeyWrapper) => {1860      await cb({api, privateKeyWrapper});1861    });1862  });1863}18641865itApi.only = (name: string, cb: (apis: { api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair }) => any) => itApi(name, cb, {only: true});1866itApi.skip = (name: string, cb: (apis: { api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair }) => any) => itApi(name, cb, {skip: true});18671868let accountSeed = 10000;1869export function generateKeyringPair(keyring: Keyring) {1870  const privateKey = `0xDEADBEEF${(Date.now() + (accountSeed++)).toString(16).padStart(64 - 8, '0')}`;1871  return keyring.addFromUri(privateKey);1872}18731874export async function expectSubstrateEventsAtBlock(api: ApiPromise, blockNumber: AnyNumber | BlockNumber, section: string, methods: string[], dryRun = false) {1875  const blockHash = await api.rpc.chain.getBlockHash(blockNumber);1876  const subEvents = (await api.query.system.events.at(blockHash))1877    .filter(x => x.event.section === section)1878    .map((x) => x.toHuman());1879  const events = methods.map((m) => {1880    return {1881      event: {1882        method: m,1883        section,1884      },1885    };1886  });1887  if (!dryRun) {1888    expect(subEvents).to.be.like(events);1889  }1890  return subEvents;1891}