git.delta.rocks / unique-network / refs/commits / 1e0a302bebd7

difftreelog

CORE-37. Integration tests

str-mv2021-07-16parent: #dab0214.patch.diff
in: master

2 files changed

addedtests/src/metadataUpdate.test.tsdiffbeforeafterboth
--- /dev/null
+++ b/tests/src/metadataUpdate.test.ts
@@ -0,0 +1,112 @@
+
+//
+// This file is subject to the terms and conditions defined in
+// file 'LICENSE', which is part of this source code package.
+//
+
+import chai from 'chai';
+import chaiAsPromised from 'chai-as-promised';
+import privateKey from './substrate/privateKey';
+import usingApi from './substrate/substrate-api';
+import {
+  createItemExpectSuccess,
+  createCollectionExpectSuccess,
+  setMetadataUpdatePermissionFlagExpectSuccess,
+  setVariableMetaDataExpectSuccess,
+  setMintPermissionExpectSuccess,
+  addToWhiteListExpectSuccess,
+  addCollectionAdminExpectSuccess,
+  setVariableMetaDataExpectFailure,
+  setMetadataUpdatePermissionFlagExpectFailure
+} from './util/helpers';
+
+chai.use(chaiAsPromised);
+
+describe('Metadata update permissions ', () => {
+  it('Set variable metadata with ItemOwner permission flag', async () => {
+    await usingApi(async () => {
+      const Alice = privateKey('//Alice');
+      const Bob = privateKey('//Bob');
+
+      const data = [1, 2, 254, 255];
+
+      // nft
+      const nftCollectionId = await createCollectionExpectSuccess();
+      const newNftTokenId = await createItemExpectSuccess(Alice, nftCollectionId, 'NFT');
+      await setMetadataUpdatePermissionFlagExpectSuccess(Alice, nftCollectionId, "ItemOwner");
+
+      await setVariableMetaDataExpectSuccess(Alice, nftCollectionId, newNftTokenId, data);
+    });
+  });
+
+  it('User can\'n set variable metadata with ItemOwner permission flag', async () => {
+    await usingApi(async () => {
+        const Alice = privateKey('//Alice');
+        const Bob = privateKey('//Bob');
+  
+        const data = [1, 2, 254, 255];
+  
+        // nft
+        const nftCollectionId = await createCollectionExpectSuccess();
+        const newNftTokenId = await createItemExpectSuccess(Alice, nftCollectionId, 'NFT');
+        await setMetadataUpdatePermissionFlagExpectSuccess(Alice, nftCollectionId, "ItemOwner");
+
+        await setMintPermissionExpectSuccess(Alice, nftCollectionId, true);
+        await addToWhiteListExpectSuccess(Alice, nftCollectionId, Bob.address);
+        await addCollectionAdminExpectSuccess(Alice, nftCollectionId, Bob);
+  
+        await setVariableMetaDataExpectFailure(Bob, nftCollectionId, newNftTokenId, data);
+    });
+  });
+
+  it('Admin can set variable metadata with Admin permission flag', async () => {
+    await usingApi(async () => {
+        const Alice = privateKey('//Alice');
+        const Bob = privateKey('//Bob');
+  
+        const data = [1, 2, 254, 255];
+  
+        // nft
+        const nftCollectionId = await createCollectionExpectSuccess();
+        const newNftTokenId = await createItemExpectSuccess(Alice, nftCollectionId, 'NFT');
+        await setMetadataUpdatePermissionFlagExpectSuccess(Alice, nftCollectionId, "Admin");
+
+        await setMintPermissionExpectSuccess(Alice, nftCollectionId, true);
+        await addToWhiteListExpectSuccess(Alice, nftCollectionId, Bob.address);
+        await addCollectionAdminExpectSuccess(Alice, nftCollectionId, Bob);
+  
+        await setVariableMetaDataExpectSuccess(Bob, nftCollectionId, newNftTokenId, data);
+    });
+  });
+
+  it('Nobody can set variable metadata with None flag', async () => {
+    await usingApi(async () => {
+        const Alice = privateKey('//Alice');
+        const Bob = privateKey('//Bob');
+  
+        const data = [1, 2, 254, 255];
+  
+        // nft
+        const nftCollectionId = await createCollectionExpectSuccess();
+        const newNftTokenId = await createItemExpectSuccess(Alice, nftCollectionId, 'NFT');
+        await setMetadataUpdatePermissionFlagExpectSuccess(Alice, nftCollectionId, "None");
+  
+        await setVariableMetaDataExpectFailure(Alice, nftCollectionId, newNftTokenId, data);
+    });
+  });
+
+  it('Nobody can set variable metadata flag after freeze', async () => {
+    await usingApi(async () => {
+        const Alice = privateKey('//Alice');
+        const Bob = privateKey('//Bob');
+  
+        const data = [1, 2, 254, 255];
+  
+        // nft
+        const nftCollectionId = await createCollectionExpectSuccess();
+        await setMetadataUpdatePermissionFlagExpectSuccess(Alice, nftCollectionId, "None");
+        await setMetadataUpdatePermissionFlagExpectFailure(Alice, nftCollectionId, "Admin");
+        
+    });
+  });
+});
modifiedtests/src/util/helpers.tsdiffbeforeafterboth
before · tests/src/util/helpers.ts
1//2// This file is subject to the terms and conditions defined in3// file 'LICENSE', which is part of this source code package.4//56import { ApiPromise, Keyring } from '@polkadot/api';7import type { AccountId, EventRecord } from '@polkadot/types/interfaces';8import { IKeyringPair } from '@polkadot/types/types';9import { evmToAddress } from '@polkadot/util-crypto';10import { BigNumber } from 'bignumber.js';11import BN from 'bn.js';12import chai from 'chai';13import chaiAsPromised from 'chai-as-promised';14import { alicesPublicKey } from '../accounts';15import privateKey from '../substrate/privateKey';16import { default as usingApi, submitTransactionAsync, submitTransactionExpectFailAsync } from '../substrate/substrate-api';17import { ICollectionInterface } from '../types';18import { hexToStr, strToUTF16, utf16ToStr } from './util';1920chai.use(chaiAsPromised);21const expect = chai.expect;2223export type CrossAccountId = {24  substrate: string,25} | {26  ethereum: string,27};28export function normalizeAccountId(input: string | AccountId | CrossAccountId | IKeyringPair): CrossAccountId {29  if (typeof input === 'string')30    return { substrate: input };31  if ('address' in input) {32    return { substrate: input.address };33  }34  if ('ethereum' in input) {35    input.ethereum = input.ethereum.toLowerCase();36    return input;37  }38  if ('substrate' in input) {39    return input;40  }4142  // AccountId43  return {substrate: input.toString()};44}45export function toSubstrateAddress(input: string | CrossAccountId | IKeyringPair): string {46  input = normalizeAccountId(input);47  if ('substrate' in input) {48    return input.substrate;49  } else {50    return evmToAddress(input.ethereum);51  }52}5354export const U128_MAX = (1n << 128n) - 1n;5556type GenericResult = {57  success: boolean,58};5960interface CreateCollectionResult {61  success: boolean;62  collectionId: number;63}6465interface CreateItemResult {66  success: boolean;67  collectionId: number;68  itemId: number;69  recipient?: CrossAccountId;70}7172interface TransferResult {73  success: boolean;74  collectionId: number;75  itemId: number;76  sender?: CrossAccountId;77  recipient?: CrossAccountId;78  value: bigint;79}8081interface IReFungibleOwner {82  Fraction: BN;83  Owner: number[];84}8586interface ITokenDataType {87  Owner: IKeyringPair;88  ConstData: number[];89  VariableData: number[];90}9192interface IGetMessage {93  checkMsgNftMethod: string;94  checkMsgTrsMethod: string;95  checkMsgSysMethod: string;96}9798export interface IReFungibleTokenDataType {99  Owner: IReFungibleOwner[];100  ConstData: number[];101  VariableData: number[];102}103104export function nftEventMessage(events: EventRecord[]): IGetMessage {105  let checkMsgNftMethod = '';106  let checkMsgTrsMethod = '';107  let checkMsgSysMethod = '';108  events.forEach(({ event: { method, section } }) => {109    if (section === 'nft') {110      checkMsgNftMethod = method;111    } else if (section === 'treasury') {112      checkMsgTrsMethod = method;113    } else if (section === 'system') {114      checkMsgSysMethod = method;115    } else { return null; }116  });117  const result: IGetMessage = {118    checkMsgNftMethod,119    checkMsgTrsMethod,120    checkMsgSysMethod,121  };122  return result;123}124125export function getGenericResult(events: EventRecord[]): GenericResult {126  const result: GenericResult = {127    success: false,128  };129  events.forEach(({ event: { method } }) => {130    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);131    if (method === 'ExtrinsicSuccess') {132      result.success = true;133    }134  });135  return result;136}137138139140export function getCreateCollectionResult(events: EventRecord[]): CreateCollectionResult {141  let success = false;142  let collectionId = 0;143  events.forEach(({ event: { data, method, section } }) => {144    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);145    if (method == 'ExtrinsicSuccess') {146      success = true;147    } else if ((section == 'nft') && (method == 'CollectionCreated')) {148      collectionId = parseInt(data[0].toString());149    }150  });151  const result: CreateCollectionResult = {152    success,153    collectionId,154  };155  return result;156}157158export function getCreateItemResult(events: EventRecord[]): CreateItemResult {159  let success = false;160  let collectionId = 0;161  let itemId = 0;162  let recipient;163  events.forEach(({ event: { data, method, section } }) => {164    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);165    if (method == 'ExtrinsicSuccess') {166      success = true;167    } else if ((section == 'nft') && (method == 'ItemCreated')) {168      collectionId = parseInt(data[0].toString());169      itemId = parseInt(data[1].toString());170      recipient = data[2].toJSON();171    }172  });173  const result: CreateItemResult = {174    success,175    collectionId,176    itemId,177    recipient,178  };179  return result;180}181182export function getTransferResult(events: EventRecord[]): TransferResult {183  const result: TransferResult = {184    success: false,185    collectionId: 0,186    itemId: 0,187    value: 0n,188  };189190  events.forEach(({ event: { data, method, section } }) => {191    if (method === 'ExtrinsicSuccess') {192      result.success = true;193    } else if (section === 'nft' && method === 'Transfer') {194      result.collectionId = +data[0].toString();195      result.itemId = +data[1].toString();196      result.sender = data[2].toJSON() as CrossAccountId;197      result.recipient = data[3].toJSON() as CrossAccountId;198      result.value = BigInt(data[4].toString());199    }200  });201202  return result;203}204205interface Invalid {206  type: 'Invalid';207}208209interface Nft {210  type: 'NFT';211}212213interface Fungible {214  type: 'Fungible';215  decimalPoints: number;216}217218interface ReFungible {219  type: 'ReFungible';220}221222type CollectionMode = Nft | Fungible | ReFungible | Invalid;223224export type CreateCollectionParams = {225  mode: CollectionMode,226  name: string,227  description: string,228  tokenPrefix: string,229};230231const defaultCreateCollectionParams: CreateCollectionParams = {232  description: 'description',233  mode: { type: 'NFT' },234  name: 'name',235  tokenPrefix: 'prefix',236};237238export async function createCollectionExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {239  const { name, description, mode, tokenPrefix } = { ...defaultCreateCollectionParams, ...params };240241  let collectionId = 0;242  await usingApi(async (api) => {243    // Get number of collections before the transaction244    const AcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString(), 10);245246    // Run the CreateCollection transaction247    const alicePrivateKey = privateKey('//Alice');248249    let modeprm = {};250    if (mode.type === 'NFT') {251      modeprm = { nft: null };252    } else if (mode.type === 'Fungible') {253      modeprm = { fungible: mode.decimalPoints };254    } else if (mode.type === 'ReFungible') {255      modeprm = { refungible: null };256    } else if (mode.type === 'Invalid') {257      modeprm = { invalid: null };258    }259260    const tx = api.tx.nft.createCollection(strToUTF16(name), strToUTF16(description), strToUTF16(tokenPrefix), modeprm);261    const events = await submitTransactionAsync(alicePrivateKey, tx);262    const result = getCreateCollectionResult(events);263264    // Get number of collections after the transaction265    const BcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString(), 10);266267    // Get the collection268    const collection: any = (await api.query.nft.collectionById(result.collectionId) as any).toJSON();269270    // What to expect271    // tslint:disable-next-line:no-unused-expression272    expect(result.success).to.be.true;273    expect(result.collectionId).to.be.equal(BcollectionCount);274    // tslint:disable-next-line:no-unused-expression275    expect(collection).to.be.not.null;276    expect(BcollectionCount).to.be.equal(AcollectionCount + 1, 'Error: NFT collection NOT created.');277    expect(collection.Owner).to.be.equal(toSubstrateAddress(alicesPublicKey));278    expect(utf16ToStr(collection.Name)).to.be.equal(name);279    expect(utf16ToStr(collection.Description)).to.be.equal(description);280    expect(hexToStr(collection.TokenPrefix)).to.be.equal(tokenPrefix);281282    collectionId = result.collectionId;283  });284285  return collectionId;286}287288export async function createCollectionExpectFailure(params: Partial<CreateCollectionParams> = {}) {289  const { name, description, mode, tokenPrefix } = { ...defaultCreateCollectionParams, ...params };290291  let modeprm = {};292  if (mode.type === 'NFT') {293    modeprm = { nft: null };294  } else if (mode.type === 'Fungible') {295    modeprm = { fungible: mode.decimalPoints };296  } else if (mode.type === 'ReFungible') {297    modeprm = { refungible: null };298  } else if (mode.type === 'Invalid') {299    modeprm = { invalid: null };300  }301302  await usingApi(async (api) => {303    // Get number of collections before the transaction304    const AcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString());305306    // Run the CreateCollection transaction307    const alicePrivateKey = privateKey('//Alice');308    const tx = api.tx.nft.createCollection(strToUTF16(name), strToUTF16(description), strToUTF16(tokenPrefix), modeprm);309    const events = await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;310    const result = getCreateCollectionResult(events);311312    // Get number of collections after the transaction313    const BcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString());314315    // What to expect316    // tslint:disable-next-line:no-unused-expression317    expect(result.success).to.be.false;318    expect(BcollectionCount).to.be.equal(AcollectionCount, 'Error: Collection with incorrect data created.');319  });320}321322export async function findUnusedAddress(api: ApiPromise, seedAddition = ''): Promise<IKeyringPair> {323  let bal = new BigNumber(0);324  let unused;325  do {326    const randomSeed = 'seed' + Math.floor(Math.random() * Math.floor(10000)) + seedAddition;327    const keyring = new Keyring({ type: 'sr25519' });328    unused = keyring.addFromUri(`//${randomSeed}`);329    bal = new BigNumber((await api.query.system.account(unused.address)).data.free.toString());330  } while (bal.toFixed() != '0');331  return unused;332}333334export async function getAllowance(collectionId: number, tokenId: number, owner: string, approved: string) {335  return await usingApi(async (api) => {336    const bn = await api.query.nft.allowances(collectionId, [tokenId, owner, approved]) as unknown as BN;337    return BigInt(bn.toString());338  });339}340341export function findUnusedAddresses(api: ApiPromise, amount: number): Promise<IKeyringPair[]> {342  return Promise.all(new Array(amount).fill(null).map(() => findUnusedAddress(api, '_' + Date.now())));343}344345export async function findNotExistingCollection(api: ApiPromise): Promise<number> {346  const totalNumber = parseInt((await api.query.nft.createdCollectionCount()).toString(), 10) as unknown as number;347  const newCollection: number = totalNumber + 1;348  return newCollection;349}350351function getDestroyResult(events: EventRecord[]): boolean {352  let success = false;353  events.forEach(({ event: { method } }) => {354    if (method == 'ExtrinsicSuccess') {355      success = true;356    }357  });358  return success;359}360361export async function destroyCollectionExpectFailure(collectionId: number, senderSeed = '//Alice') {362  await usingApi(async (api) => {363    // Run the DestroyCollection transaction364    const alicePrivateKey = privateKey(senderSeed);365    const tx = api.tx.nft.destroyCollection(collectionId);366    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;367  });368}369370export async function destroyCollectionExpectSuccess(collectionId: number, senderSeed = '//Alice') {371  await usingApi(async (api) => {372    // Run the DestroyCollection transaction373    const alicePrivateKey = privateKey(senderSeed);374    const tx = api.tx.nft.destroyCollection(collectionId);375    const events = await submitTransactionAsync(alicePrivateKey, tx);376    const result = getDestroyResult(events);377378    // Get the collection379    const collection: any = (await api.query.nft.collectionById(collectionId)).toJSON();380381    // What to expect382    expect(result).to.be.true;383    expect(collection).to.be.null;384  });385}386387export async function queryCollectionLimits(collectionId: number) {388  return await usingApi(async (api) => {389    return ((await api.query.nft.collectionById(collectionId)).toJSON() as any).Limits;390  });391}392393export async function setCollectionLimitsExpectSuccess(sender: IKeyringPair, collectionId: number, limits: any) {394  await usingApi(async (api) => {395    const oldLimits = await queryCollectionLimits(collectionId);396    const newLimits = { ...oldLimits as any, ...limits };397    const tx = api.tx.nft.setCollectionLimits(collectionId, newLimits);398    const events = await submitTransactionAsync(sender, tx);399    const result = getGenericResult(events);400401    expect(result.success).to.be.true;402  });403}404405export async function setCollectionLimitsExpectFailure(sender: IKeyringPair, collectionId: number, limits: any) {406  await usingApi(async (api) => {407    const oldLimits = await queryCollectionLimits(collectionId);408    const newLimits = { ...oldLimits as any, ...limits };409    const tx = api.tx.nft.setCollectionLimits(collectionId, newLimits);410    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;411    const result = getGenericResult(events);412413    expect(result.success).to.be.false;414  });415}416417export async function setCollectionSponsorExpectSuccess(collectionId: number, sponsor: string) {418  await usingApi(async (api) => {419420    // Run the transaction421    const alicePrivateKey = privateKey('//Alice');422    const tx = api.tx.nft.setCollectionSponsor(collectionId, sponsor);423    const events = await submitTransactionAsync(alicePrivateKey, tx);424    const result = getGenericResult(events);425426    // Get the collection427    const collection: any = (await api.query.nft.collectionById(collectionId)).toJSON();428429    // What to expect430    expect(result.success).to.be.true;431    expect(collection.Sponsorship).to.deep.equal({432      unconfirmed: sponsor,433    });434  });435}436437export async function removeCollectionSponsorExpectSuccess(collectionId: number) {438  await usingApi(async (api) => {439440    // Run the transaction441    const alicePrivateKey = privateKey('//Alice');442    const tx = api.tx.nft.removeCollectionSponsor(collectionId);443    const events = await submitTransactionAsync(alicePrivateKey, tx);444    const result = getGenericResult(events);445446    // Get the collection447    const collection: any = (await api.query.nft.collectionById(collectionId)).toJSON();448449    // What to expect450    expect(result.success).to.be.true;451    expect(collection.Sponsorship).to.be.deep.equal({ disabled: null });452  });453}454455export async function removeCollectionSponsorExpectFailure(collectionId: number) {456  await usingApi(async (api) => {457458    // Run the transaction459    const alicePrivateKey = privateKey('//Alice');460    const tx = api.tx.nft.removeCollectionSponsor(collectionId);461    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;462  });463}464465export async function setCollectionSponsorExpectFailure(collectionId: number, sponsor: string, senderSeed = '//Alice') {466  await usingApi(async (api) => {467468    // Run the transaction469    const alicePrivateKey = privateKey(senderSeed);470    const tx = api.tx.nft.setCollectionSponsor(collectionId, sponsor);471    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;472  });473}474475export async function confirmSponsorshipExpectSuccess(collectionId: number, senderSeed = '//Alice') {476  await usingApi(async (api) => {477478    // Run the transaction479    const sender = privateKey(senderSeed);480    const tx = api.tx.nft.confirmSponsorship(collectionId);481    const events = await submitTransactionAsync(sender, tx);482    const result = getGenericResult(events);483484    // Get the collection485    const collection: any = (await api.query.nft.collectionById(collectionId)).toJSON();486487    // What to expect488    expect(result.success).to.be.true;489    expect(collection.Sponsorship).to.be.deep.equal({490      confirmed: sender.address,491    });492  });493}494495496export async function confirmSponsorshipExpectFailure(collectionId: number, senderSeed = '//Alice') {497  await usingApi(async (api) => {498499    // Run the transaction500    const sender = privateKey(senderSeed);501    const tx = api.tx.nft.confirmSponsorship(collectionId);502    await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;503  });504}505506export async function enableContractSponsoringExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {507  await usingApi(async (api) => {508    const tx = api.tx.nft.enableContractSponsoring(contractAddress, enable);509    const events = await submitTransactionAsync(sender, tx);510    const result = getGenericResult(events);511512    expect(result.success).to.be.true;513  });514}515516export async function enableContractSponsoringExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {517  await usingApi(async (api) => {518    const tx = api.tx.nft.enableContractSponsoring(contractAddress, enable);519    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;520    const result = getGenericResult(events);521522    expect(result.success).to.be.false;523  });524}525526export async function setContractSponsoringRateLimitExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {527  await usingApi(async (api) => {528    const tx = api.tx.nft.setContractSponsoringRateLimit(contractAddress, rateLimit);529    const events = await submitTransactionAsync(sender, tx);530    const result = getGenericResult(events);531532    expect(result.success).to.be.true;533  });534}535536export async function setContractSponsoringRateLimitExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {537  await usingApi(async (api) => {538    const tx = api.tx.nft.setContractSponsoringRateLimit(contractAddress, rateLimit);539    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;540    const result = getGenericResult(events);541542    expect(result.success).to.be.false;543  });544}545546export async function toggleContractWhitelistExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, value: boolean = true) {547  await usingApi(async (api) => {548    const tx = api.tx.nft.toggleContractWhiteList(contractAddress, value);549    const events = await submitTransactionAsync(sender, tx);550    const result = getGenericResult(events);551552    expect(result.success).to.be.true;553  });554}555556export async function isWhitelistedInContract(contractAddress: AccountId | string, user: string) {557  let whitelisted = false;558  await usingApi(async (api) => {559    whitelisted = (await api.query.nft.contractWhiteList(contractAddress, user)).toJSON() as boolean;560  });561  return whitelisted;562}563564export async function addToContractWhiteListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {565  await usingApi(async (api) => {566    const tx = api.tx.nft.addToContractWhiteList(contractAddress.toString(), user.toString());567    const events = await submitTransactionAsync(sender, tx);568    const result = getGenericResult(events);569570    expect(result.success).to.be.true;571  });572}573574export async function removeFromContractWhiteListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {575  await usingApi(async (api) => {576    const tx = api.tx.nft.removeFromContractWhiteList(contractAddress.toString(), user.toString());577    const events = await submitTransactionAsync(sender, tx);578    const result = getGenericResult(events);579580    expect(result.success).to.be.true;581  });582}583584export async function removeFromContractWhiteListExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {585  await usingApi(async (api) => {586    const tx = api.tx.nft.removeFromContractWhiteList(contractAddress.toString(), user.toString());587    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;588    const result = getGenericResult(events);589590    expect(result.success).to.be.false;591  });592}593594export async function setVariableMetaDataExpectSuccess(sender: IKeyringPair, collectionId: number, itemId: number, data: number[]) {595  await usingApi(async (api) => {596    const tx = api.tx.nft.setVariableMetaData(collectionId, itemId, '0x' + Buffer.from(data).toString('hex'));597    const events = await submitTransactionAsync(sender, tx);598    const result = getGenericResult(events);599600    expect(result.success).to.be.true;601  });602}603604export async function setVariableMetaDataExpectFailure(sender: IKeyringPair, collectionId: number, itemId: number, data: number[]) {605  await usingApi(async (api) => {606    const tx = api.tx.nft.setVariableMetaData(collectionId, itemId, '0x' + Buffer.from(data).toString('hex'));607    await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;608  });609}610611export async function setOffchainSchemaExpectSuccess(sender: IKeyringPair, collectionId: number, data: number[]) {612  await usingApi(async (api) => {613    const tx = api.tx.nft.setOffchainSchema(collectionId, '0x' + Buffer.from(data).toString('hex'));614    const events = await submitTransactionAsync(sender, tx);615    const result = getGenericResult(events);616617    expect(result.success).to.be.true;618  });619}620621export async function setOffchainSchemaExpectFailure(sender: IKeyringPair, collectionId: number, data: number[]) {622  await usingApi(async (api) => {623    const tx = api.tx.nft.setOffchainSchema(collectionId, '0x' + Buffer.from(data).toString('hex'));624    await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;625  });626}627628export interface CreateFungibleData {629  readonly Value: bigint;630}631632export interface CreateReFungibleData { }633export interface CreateNftData { }634635export type CreateItemData = {636  NFT: CreateNftData;637} | {638  Fungible: CreateFungibleData;639} | {640  ReFungible: CreateReFungibleData;641};642643export async function burnItemExpectSuccess(owner: IKeyringPair, collectionId: number, tokenId: number, value = 0) {644  await usingApi(async (api) => {645    const tx = api.tx.nft.burnItem(collectionId, tokenId, value);646    const events = await submitTransactionAsync(owner, tx);647    const result = getGenericResult(events);648    // Get the item649    const item: any = (await api.query.nft.nftItemList(collectionId, tokenId)).toJSON();650    // What to expect651    // tslint:disable-next-line:no-unused-expression652    expect(result.success).to.be.true;653    // tslint:disable-next-line:no-unused-expression654    expect(item).to.be.null;655  });656}657658export async function659approveExpectSuccess(660  collectionId: number,661  tokenId: number, owner: IKeyringPair, approved: IKeyringPair | CrossAccountId | string, amount: number | bigint = 1,662) {663  await usingApi(async (api: ApiPromise) => {664    approved = normalizeAccountId(approved);665    const allowanceBefore =666      await api.query.nft.allowances(collectionId, [tokenId, owner.address, toSubstrateAddress(approved)]) as unknown as BN;667    const approveNftTx = api.tx.nft.approve(approved, collectionId, tokenId, amount);668    const events = await submitTransactionAsync(owner, approveNftTx);669    const result = getCreateItemResult(events);670    // tslint:disable-next-line:no-unused-expression671    expect(result.success).to.be.true;672    const allowanceAfter =673      await api.query.nft.allowances(collectionId, [tokenId, owner.address, toSubstrateAddress(approved)]) as unknown as BN;674    expect(allowanceAfter.sub(allowanceBefore).toString()).to.be.equal(amount.toString());675  });676}677678export async function679transferFromExpectSuccess(680  collectionId: number,681  tokenId: number,682  accountApproved: IKeyringPair,683  accountFrom: IKeyringPair | CrossAccountId,684  accountTo: IKeyringPair | CrossAccountId,685  value: number | bigint = 1,686  type = 'NFT',687) {688  await usingApi(async (api: ApiPromise) => {689    const to = normalizeAccountId(accountTo);690    let balanceBefore = new BN(0);691    if (type === 'Fungible') {692      balanceBefore = await api.query.nft.balance(collectionId, toSubstrateAddress(to)) as unknown as BN;693    }694    const transferFromTx = api.tx.nft.transferFrom(normalizeAccountId(accountFrom), to, collectionId, tokenId, value);695    const events = await submitTransactionAsync(accountApproved, transferFromTx);696    const result = getCreateItemResult(events);697    // tslint:disable-next-line:no-unused-expression698    expect(result.success).to.be.true;699    if (type === 'NFT') {700      const nftItemData = (await api.query.nft.nftItemList(collectionId, tokenId) as any).toJSON() as ITokenDataType;701      expect(nftItemData.Owner).to.be.deep.equal(to);702    }703    if (type === 'Fungible') {704      const balanceAfter = (await api.query.nft.fungibleItemList(collectionId, toSubstrateAddress(to)) as any).Value as unknown as BN;705      expect(balanceAfter.sub(balanceBefore).toString()).to.be.equal(value.toString());706    }707    if (type === 'ReFungible') {708      const nftItemData =709        (await api.query.nft.reFungibleItemList(collectionId, tokenId) as any).toJSON() as IReFungibleTokenDataType;710      expect(nftItemData.Owner[0].Owner).to.be.deep.equal(normalizeAccountId(to));711      expect(nftItemData.Owner[0].Fraction).to.be.equal(value);712    }713  });714}715716export async function717transferFromExpectFail(718  collectionId: number,719  tokenId: number,720  accountApproved: IKeyringPair,721  accountFrom: IKeyringPair,722  accountTo: IKeyringPair,723  value: number | bigint = 1,724) {725  await usingApi(async (api: ApiPromise) => {726    const transferFromTx = api.tx.nft.transferFrom(normalizeAccountId(accountFrom.address), normalizeAccountId(accountTo.address), collectionId, tokenId, value);727    const events = await expect(submitTransactionExpectFailAsync(accountApproved, transferFromTx)).to.be.rejected;728    const result = getCreateCollectionResult(events);729    // tslint:disable-next-line:no-unused-expression730    expect(result.success).to.be.false;731  });732}733734/* eslint no-async-promise-executor: "off" */735async function getBlockNumber(api: ApiPromise): Promise<number> {736  return new Promise<number>(async (resolve) => {737    const unsubscribe = await api.rpc.chain.subscribeNewHeads((head) => {738      unsubscribe();739      resolve(head.number.toNumber());740    });741  });742}743744export async function745scheduleTransferExpectSuccess(746  collectionId: number,747  tokenId: number,748  sender: IKeyringPair,749  recipient: IKeyringPair,750  value: number | bigint = 1,751  blockTimeMs: number,752  blockSchedule: number753) {754  await usingApi(async (api: ApiPromise) => {755    const blockNumber: number | undefined = await getBlockNumber(api);756    const expectedBlockNumber = blockNumber + blockSchedule;757758    expect(blockNumber).to.be.greaterThan(0);759    const transferTx = await api.tx.nft.transfer(normalizeAccountId(recipient.address), collectionId, tokenId, value); 760    const scheduleTx = await api.tx.scheduler.schedule(expectedBlockNumber, null, 0, transferTx);761762    await submitTransactionAsync(sender, scheduleTx);763764    const recipientBalanceBefore = new BigNumber((await api.query.system.account(recipient.address)).data.free.toString());765766    const nftItemDataBefore = (await api.query.nft.nftItemList(collectionId, tokenId)).toJSON() as any as ITokenDataType;767    expect(toSubstrateAddress(nftItemDataBefore.Owner)).to.be.equal(sender.address);768769    // sleep for 4 blocks770    await new Promise(resolve => setTimeout(resolve, blockTimeMs * (blockSchedule + 1)));771772    const recipientBalanceAfter = new BigNumber((await api.query.system.account(recipient.address)).data.free.toString());773774    const nftItemData = (await api.query.nft.nftItemList(collectionId, tokenId)).toJSON() as unknown as ITokenDataType;775    expect(toSubstrateAddress(nftItemData.Owner)).to.be.equal(recipient.address);776    expect(recipientBalanceAfter.toNumber()).to.be.equal(recipientBalanceBefore.toNumber());777  });778}779780781export async function782transferExpectSuccess(783  collectionId: number,784  tokenId: number,785  sender: IKeyringPair,786  recipient: IKeyringPair | CrossAccountId,787  value: number | bigint = 1,788  type = 'NFT',789) {790  await usingApi(async (api: ApiPromise) => {791    const to = normalizeAccountId(recipient);792793    let balanceBefore = new BN(0);794    if (type === 'Fungible') {795      balanceBefore = await api.query.nft.balance(collectionId, toSubstrateAddress(to)) as unknown as BN;796    }797    const transferTx = api.tx.nft.transfer(to, collectionId, tokenId, value);798    const events = await submitTransactionAsync(sender, transferTx);799    const result = getTransferResult(events);800    // tslint:disable-next-line:no-unused-expression801    expect(result.success).to.be.true;802    expect(result.collectionId).to.be.equal(collectionId);803    expect(result.itemId).to.be.equal(tokenId);804    expect(result.sender).to.be.deep.equal(normalizeAccountId(sender.address));805    expect(result.recipient).to.be.deep.equal(to);806    expect(result.value.toString()).to.be.equal(value.toString());807    if (type === 'NFT') {808      const nftItemData = (await api.query.nft.nftItemList(collectionId, tokenId)).toJSON() as unknown as ITokenDataType;809      expect(nftItemData.Owner).to.be.deep.equal(to);810    }811    if (type === 'Fungible') {812      const balanceAfter = (await api.query.nft.fungibleItemList(collectionId, toSubstrateAddress(to)) as any).Value as unknown as BN;813      expect(balanceAfter.sub(balanceBefore).toString()).to.be.equal(value.toString());814    }815    if (type === 'ReFungible') {816      const nftItemData =817        (await api.query.nft.reFungibleItemList(collectionId, tokenId)).toJSON() as unknown as IReFungibleTokenDataType;818      expect(nftItemData.Owner[0].Owner).to.be.deep.equal(to);819      expect(nftItemData.Owner[0].Fraction.toString()).to.be.equal(value.toString());820    }821  });822}823824export async function825transferExpectFailure(826  collectionId: number,827  tokenId: number,828  sender: IKeyringPair,829  recipient: IKeyringPair,830  value: number | bigint = 1,831) {832  await usingApi(async (api: ApiPromise) => {833    const transferTx = api.tx.nft.transfer(normalizeAccountId(recipient.address), collectionId, tokenId, value);834    const events = await expect(submitTransactionExpectFailAsync(sender, transferTx)).to.be.rejected;835    if (events && Array.isArray(events)) {836      const result = getCreateCollectionResult(events);837      // tslint:disable-next-line:no-unused-expression838      expect(result.success).to.be.false;839    }840  });841}842843export async function844approveExpectFail(845  collectionId: number,846  tokenId: number, owner: IKeyringPair, approved: IKeyringPair, amount: number | bigint = 1,847) {848  await usingApi(async (api: ApiPromise) => {849    const approveNftTx = api.tx.nft.approve(normalizeAccountId(approved.address), collectionId, tokenId, amount);850    const events = await expect(submitTransactionExpectFailAsync(owner, approveNftTx)).to.be.rejected;851    const result = getCreateCollectionResult(events);852    // tslint:disable-next-line:no-unused-expression853    expect(result.success).to.be.false;854  });855}856857export async function getFungibleBalance(858  collectionId: number,859  owner: string,860) {861  return await usingApi(async (api) => {862    const response = (await api.query.nft.fungibleItemList(collectionId, owner)).toJSON() as unknown as { Value: string };863    return BigInt(response.Value);864  });865}866867export async function createFungibleItemExpectSuccess(868  sender: IKeyringPair,869  collectionId: number,870  data: CreateFungibleData,871  owner: CrossAccountId | string = sender.address,872) {873  return await usingApi(async (api) => {874    const tx = api.tx.nft.createItem(collectionId, normalizeAccountId(owner), { Fungible: data });875876    const events = await submitTransactionAsync(sender, tx);877    const result = getCreateItemResult(events);878879    expect(result.success).to.be.true;880    return result.itemId;881  });882}883884export async function createItemExpectSuccess(sender: IKeyringPair, collectionId: number, createMode: string, owner: CrossAccountId | string = sender.address) {885  let newItemId = 0;886  await usingApi(async (api) => {887    const to = normalizeAccountId(owner);888    const AItemCount = parseInt((await api.query.nft.itemListIndex(collectionId)).toString(), 10);889    const Aitem: any = (await api.query.nft.fungibleItemList(collectionId, toSubstrateAddress(to))).toJSON();890    const AItemBalance = new BigNumber(Aitem.Value);891892    let tx;893    if (createMode === 'Fungible') {894      const createData = { fungible: { value: 10 } };895      tx = api.tx.nft.createItem(collectionId, to, createData);896    } else if (createMode === 'ReFungible') {897      const createData = { refungible: { const_data: [], variable_data: [], pieces: 100 } };898      tx = api.tx.nft.createItem(collectionId, to, createData);899    } else {900      const createData = { nft: { const_data: [], variable_data: [] } };901      tx = api.tx.nft.createItem(collectionId, to, createData);902    }903904    const events = await submitTransactionAsync(sender, tx);905    const result = getCreateItemResult(events);906907    const BItemCount = parseInt((await api.query.nft.itemListIndex(collectionId)).toString(), 10);908    const Bitem: any = (await api.query.nft.fungibleItemList(collectionId, toSubstrateAddress(to))).toJSON();909    const BItemBalance = new BigNumber(Bitem.Value);910911    // What to expect912    // tslint:disable-next-line:no-unused-expression913    expect(result.success).to.be.true;914    if (createMode === 'Fungible') {915      expect(BItemBalance.minus(AItemBalance).toNumber()).to.be.equal(10);916    } else {917      expect(BItemCount).to.be.equal(AItemCount + 1);918    }919    expect(collectionId).to.be.equal(result.collectionId);920    expect(BItemCount.toString()).to.be.equal(result.itemId.toString());921    expect(to).to.be.deep.equal(result.recipient);922    newItemId = result.itemId;923  });924  return newItemId;925}926927export async function createItemExpectFailure(sender: IKeyringPair, collectionId: number, createMode: string, owner: string = sender.address) {928  await usingApi(async (api) => {929    const tx = api.tx.nft.createItem(collectionId, normalizeAccountId(owner), createMode);930    931    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;932    const result = getCreateItemResult(events);933934    expect(result.success).to.be.false;935  });936}937938export async function setPublicAccessModeExpectSuccess(939  sender: IKeyringPair, collectionId: number,940  accessMode: 'Normal' | 'WhiteList',941) {942  await usingApi(async (api) => {943944    // Run the transaction945    const tx = api.tx.nft.setPublicAccessMode(collectionId, accessMode);946    const events = await submitTransactionAsync(sender, tx);947    const result = getGenericResult(events);948949    // Get the collection950    const collection: any = (await api.query.nft.collectionById(collectionId)).toJSON();951952    // What to expect953    // tslint:disable-next-line:no-unused-expression954    expect(result.success).to.be.true;955    expect(collection.Access).to.be.equal(accessMode);956  });957}958959export async function enableWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number) {960  await setPublicAccessModeExpectSuccess(sender, collectionId, 'WhiteList');961}962963export async function disableWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number) {964  await setPublicAccessModeExpectSuccess(sender, collectionId, 'Normal');965}966967export async function setMintPermissionExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {968  await usingApi(async (api) => {969970    // Run the transaction971    const tx = api.tx.nft.setMintPermission(collectionId, enabled);972    const events = await submitTransactionAsync(sender, tx);973    const result = getGenericResult(events);974975    // Get the collection976    const collection: any = (await api.query.nft.collectionById(collectionId)).toJSON();977978    // What to expect979    // tslint:disable-next-line:no-unused-expression980    expect(result.success).to.be.true;981    expect(collection.MintMode).to.be.equal(enabled);982  });983}984985export async function enablePublicMintingExpectSuccess(sender: IKeyringPair, collectionId: number) {986  await setMintPermissionExpectSuccess(sender, collectionId, true);987}988989export async function setMintPermissionExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {990  await usingApi(async (api) => {991    // Run the transaction992    const tx = api.tx.nft.setMintPermission(collectionId, enabled);993    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;994    const result = getCreateCollectionResult(events);995    // tslint:disable-next-line:no-unused-expression996    expect(result.success).to.be.false;997  });998}9991000export async function isWhitelisted(collectionId: number, address: string) {1001  let whitelisted = false;1002  await usingApi(async (api) => {1003    whitelisted = (await api.query.nft.whiteList(collectionId, address)).toJSON() as unknown as boolean;1004  });1005  return whitelisted;1006}10071008export async function addToWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId) {1009  await usingApi(async (api) => {10101011    const whiteListedBefore = (await api.query.nft.whiteList(collectionId, address)).toJSON();10121013    // Run the transaction1014    const tx = api.tx.nft.addToWhiteList(collectionId, normalizeAccountId(address));1015    const events = await submitTransactionAsync(sender, tx);1016    const result = getGenericResult(events);10171018    const whiteListedAfter = (await api.query.nft.whiteList(collectionId, address)).toJSON();10191020    // What to expect1021    // tslint:disable-next-line:no-unused-expression1022    expect(result.success).to.be.true;1023    // tslint:disable-next-line: no-unused-expression1024    expect(whiteListedBefore).to.be.false;1025    // tslint:disable-next-line: no-unused-expression1026    expect(whiteListedAfter).to.be.true;1027  });1028}10291030export async function removeFromWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1031  await usingApi(async (api) => {1032    // Run the transaction1033    const tx = api.tx.nft.removeFromWhiteList(collectionId, normalizeAccountId(address));1034    const events = await submitTransactionAsync(sender, tx);1035    const result = getGenericResult(events);10361037    // What to expect1038    // tslint:disable-next-line:no-unused-expression1039    expect(result.success).to.be.true;1040  });1041}10421043export async function removeFromWhiteListExpectFailure(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1044  await usingApi(async (api) => {1045    // Run the transaction1046    const tx = api.tx.nft.removeFromWhiteList(collectionId, normalizeAccountId(address));1047    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1048    const result = getGenericResult(events);10491050    // What to expect1051    // tslint:disable-next-line:no-unused-expression1052    expect(result.success).to.be.false;1053  });1054}10551056export const getDetailedCollectionInfo = async (api: ApiPromise, collectionId: number)1057  : Promise<ICollectionInterface | null> => {1058  return (await api.query.nft.collectionById(collectionId)).toJSON() as unknown as ICollectionInterface;1059};10601061export const getCreatedCollectionCount = async (api: ApiPromise): Promise<number> => {1062  // set global object - collectionsCount1063  return (await api.query.nft.createdCollectionCount() as unknown as BN).toNumber();1064};10651066export async function queryCollectionExpectSuccess(collectionId: number): Promise<ICollectionInterface> {1067  return await usingApi(async (api) => {1068    return (await api.query.nft.collectionById(collectionId)).toJSON() as unknown as ICollectionInterface;1069  });1070}
after · tests/src/util/helpers.ts
1//2// This file is subject to the terms and conditions defined in3// file 'LICENSE', which is part of this source code package.4//56import { ApiPromise, Keyring } from '@polkadot/api';7import type { AccountId, EventRecord } from '@polkadot/types/interfaces';8import { IKeyringPair } from '@polkadot/types/types';9import { evmToAddress } from '@polkadot/util-crypto';10import { BigNumber } from 'bignumber.js';11import BN from 'bn.js';12import chai from 'chai';13import chaiAsPromised from 'chai-as-promised';14import { alicesPublicKey } from '../accounts';15import privateKey from '../substrate/privateKey';16import { default as usingApi, submitTransactionAsync, submitTransactionExpectFailAsync } from '../substrate/substrate-api';17import { ICollectionInterface } from '../types';18import { hexToStr, strToUTF16, utf16ToStr } from './util';1920chai.use(chaiAsPromised);21const expect = chai.expect;2223export type CrossAccountId = {24  substrate: string,25} | {26  ethereum: string,27};28export function normalizeAccountId(input: string | AccountId | CrossAccountId | IKeyringPair): CrossAccountId {29  if (typeof input === 'string')30    return { substrate: input };31  if ('address' in input) {32    return { substrate: input.address };33  }34  if ('ethereum' in input) {35    input.ethereum = input.ethereum.toLowerCase();36    return input;37  }38  if ('substrate' in input) {39    return input;40  }4142  // AccountId43  return {substrate: input.toString()};44}45export function toSubstrateAddress(input: string | CrossAccountId | IKeyringPair): string {46  input = normalizeAccountId(input);47  if ('substrate' in input) {48    return input.substrate;49  } else {50    return evmToAddress(input.ethereum);51  }52}5354export const U128_MAX = (1n << 128n) - 1n;5556type GenericResult = {57  success: boolean,58};5960interface CreateCollectionResult {61  success: boolean;62  collectionId: number;63}6465interface CreateItemResult {66  success: boolean;67  collectionId: number;68  itemId: number;69  recipient?: CrossAccountId;70}7172interface TransferResult {73  success: boolean;74  collectionId: number;75  itemId: number;76  sender?: CrossAccountId;77  recipient?: CrossAccountId;78  value: bigint;79}8081interface IReFungibleOwner {82  Fraction: BN;83  Owner: number[];84}8586interface ITokenDataType {87  Owner: IKeyringPair;88  ConstData: number[];89  VariableData: number[];90}9192interface IGetMessage {93  checkMsgNftMethod: string;94  checkMsgTrsMethod: string;95  checkMsgSysMethod: string;96}9798export interface IReFungibleTokenDataType {99  Owner: IReFungibleOwner[];100  ConstData: number[];101  VariableData: number[];102}103104export function nftEventMessage(events: EventRecord[]): IGetMessage {105  let checkMsgNftMethod = '';106  let checkMsgTrsMethod = '';107  let checkMsgSysMethod = '';108  events.forEach(({ event: { method, section } }) => {109    if (section === 'nft') {110      checkMsgNftMethod = method;111    } else if (section === 'treasury') {112      checkMsgTrsMethod = method;113    } else if (section === 'system') {114      checkMsgSysMethod = method;115    } else { return null; }116  });117  const result: IGetMessage = {118    checkMsgNftMethod,119    checkMsgTrsMethod,120    checkMsgSysMethod,121  };122  return result;123}124125export function getGenericResult(events: EventRecord[]): GenericResult {126  const result: GenericResult = {127    success: false,128  };129  events.forEach(({ event: { method } }) => {130    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);131    if (method === 'ExtrinsicSuccess') {132      result.success = true;133    }134  });135  return result;136}137138139140export function getCreateCollectionResult(events: EventRecord[]): CreateCollectionResult {141  let success = false;142  let collectionId = 0;143  events.forEach(({ event: { data, method, section } }) => {144    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);145    if (method == 'ExtrinsicSuccess') {146      success = true;147    } else if ((section == 'nft') && (method == 'CollectionCreated')) {148      collectionId = parseInt(data[0].toString());149    }150  });151  const result: CreateCollectionResult = {152    success,153    collectionId,154  };155  return result;156}157158export function getCreateItemResult(events: EventRecord[]): CreateItemResult {159  let success = false;160  let collectionId = 0;161  let itemId = 0;162  let recipient;163  events.forEach(({ event: { data, method, section } }) => {164    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);165    if (method == 'ExtrinsicSuccess') {166      success = true;167    } else if ((section == 'nft') && (method == 'ItemCreated')) {168      collectionId = parseInt(data[0].toString());169      itemId = parseInt(data[1].toString());170      recipient = data[2].toJSON();171    }172  });173  const result: CreateItemResult = {174    success,175    collectionId,176    itemId,177    recipient,178  };179  return result;180}181182export function getTransferResult(events: EventRecord[]): TransferResult {183  const result: TransferResult = {184    success: false,185    collectionId: 0,186    itemId: 0,187    value: 0n,188  };189190  events.forEach(({ event: { data, method, section } }) => {191    if (method === 'ExtrinsicSuccess') {192      result.success = true;193    } else if (section === 'nft' && method === 'Transfer') {194      result.collectionId = +data[0].toString();195      result.itemId = +data[1].toString();196      result.sender = data[2].toJSON() as CrossAccountId;197      result.recipient = data[3].toJSON() as CrossAccountId;198      result.value = BigInt(data[4].toString());199    }200  });201202  return result;203}204205interface Invalid {206  type: 'Invalid';207}208209interface Nft {210  type: 'NFT';211}212213interface Fungible {214  type: 'Fungible';215  decimalPoints: number;216}217218interface ReFungible {219  type: 'ReFungible';220}221222type CollectionMode = Nft | Fungible | ReFungible | Invalid;223224export type CreateCollectionParams = {225  mode: CollectionMode,226  name: string,227  description: string,228  tokenPrefix: string,229};230231const defaultCreateCollectionParams: CreateCollectionParams = {232  description: 'description',233  mode: { type: 'NFT' },234  name: 'name',235  tokenPrefix: 'prefix',236};237238export async function createCollectionExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {239  const { name, description, mode, tokenPrefix } = { ...defaultCreateCollectionParams, ...params };240241  let collectionId = 0;242  await usingApi(async (api) => {243    // Get number of collections before the transaction244    const AcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString(), 10);245246    // Run the CreateCollection transaction247    const alicePrivateKey = privateKey('//Alice');248249    let modeprm = {};250    if (mode.type === 'NFT') {251      modeprm = { nft: null };252    } else if (mode.type === 'Fungible') {253      modeprm = { fungible: mode.decimalPoints };254    } else if (mode.type === 'ReFungible') {255      modeprm = { refungible: null };256    } else if (mode.type === 'Invalid') {257      modeprm = { invalid: null };258    }259260    const tx = api.tx.nft.createCollection(strToUTF16(name), strToUTF16(description), strToUTF16(tokenPrefix), modeprm);261    const events = await submitTransactionAsync(alicePrivateKey, tx);262    const result = getCreateCollectionResult(events);263264    // Get number of collections after the transaction265    const BcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString(), 10);266267    // Get the collection268    const collection: any = (await api.query.nft.collectionById(result.collectionId) as any).toJSON();269270    // What to expect271    // tslint:disable-next-line:no-unused-expression272    expect(result.success).to.be.true;273    expect(result.collectionId).to.be.equal(BcollectionCount);274    // tslint:disable-next-line:no-unused-expression275    expect(collection).to.be.not.null;276    expect(BcollectionCount).to.be.equal(AcollectionCount + 1, 'Error: NFT collection NOT created.');277    expect(collection.Owner).to.be.equal(toSubstrateAddress(alicesPublicKey));278    expect(utf16ToStr(collection.Name)).to.be.equal(name);279    expect(utf16ToStr(collection.Description)).to.be.equal(description);280    expect(hexToStr(collection.TokenPrefix)).to.be.equal(tokenPrefix);281282    collectionId = result.collectionId;283  });284285  return collectionId;286}287288export async function createCollectionExpectFailure(params: Partial<CreateCollectionParams> = {}) {289  const { name, description, mode, tokenPrefix } = { ...defaultCreateCollectionParams, ...params };290291  let modeprm = {};292  if (mode.type === 'NFT') {293    modeprm = { nft: null };294  } else if (mode.type === 'Fungible') {295    modeprm = { fungible: mode.decimalPoints };296  } else if (mode.type === 'ReFungible') {297    modeprm = { refungible: null };298  } else if (mode.type === 'Invalid') {299    modeprm = { invalid: null };300  }301302  await usingApi(async (api) => {303    // Get number of collections before the transaction304    const AcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString());305306    // Run the CreateCollection transaction307    const alicePrivateKey = privateKey('//Alice');308    const tx = api.tx.nft.createCollection(strToUTF16(name), strToUTF16(description), strToUTF16(tokenPrefix), modeprm);309    const events = await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;310    const result = getCreateCollectionResult(events);311312    // Get number of collections after the transaction313    const BcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString());314315    // What to expect316    // tslint:disable-next-line:no-unused-expression317    expect(result.success).to.be.false;318    expect(BcollectionCount).to.be.equal(AcollectionCount, 'Error: Collection with incorrect data created.');319  });320}321322export async function findUnusedAddress(api: ApiPromise, seedAddition = ''): Promise<IKeyringPair> {323  let bal = new BigNumber(0);324  let unused;325  do {326    const randomSeed = 'seed' + Math.floor(Math.random() * Math.floor(10000)) + seedAddition;327    const keyring = new Keyring({ type: 'sr25519' });328    unused = keyring.addFromUri(`//${randomSeed}`);329    bal = new BigNumber((await api.query.system.account(unused.address)).data.free.toString());330  } while (bal.toFixed() != '0');331  return unused;332}333334export async function getAllowance(collectionId: number, tokenId: number, owner: string, approved: string) {335  return await usingApi(async (api) => {336    const bn = await api.query.nft.allowances(collectionId, [tokenId, owner, approved]) as unknown as BN;337    return BigInt(bn.toString());338  });339}340341export function findUnusedAddresses(api: ApiPromise, amount: number): Promise<IKeyringPair[]> {342  return Promise.all(new Array(amount).fill(null).map(() => findUnusedAddress(api, '_' + Date.now())));343}344345export async function findNotExistingCollection(api: ApiPromise): Promise<number> {346  const totalNumber = parseInt((await api.query.nft.createdCollectionCount()).toString(), 10) as unknown as number;347  const newCollection: number = totalNumber + 1;348  return newCollection;349}350351function getDestroyResult(events: EventRecord[]): boolean {352  let success = false;353  events.forEach(({ event: { method } }) => {354    if (method == 'ExtrinsicSuccess') {355      success = true;356    }357  });358  return success;359}360361export async function destroyCollectionExpectFailure(collectionId: number, senderSeed = '//Alice') {362  await usingApi(async (api) => {363    // Run the DestroyCollection transaction364    const alicePrivateKey = privateKey(senderSeed);365    const tx = api.tx.nft.destroyCollection(collectionId);366    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;367  });368}369370export async function destroyCollectionExpectSuccess(collectionId: number, senderSeed = '//Alice') {371  await usingApi(async (api) => {372    // Run the DestroyCollection transaction373    const alicePrivateKey = privateKey(senderSeed);374    const tx = api.tx.nft.destroyCollection(collectionId);375    const events = await submitTransactionAsync(alicePrivateKey, tx);376    const result = getDestroyResult(events);377378    // Get the collection379    const collection: any = (await api.query.nft.collectionById(collectionId)).toJSON();380381    // What to expect382    expect(result).to.be.true;383    expect(collection).to.be.null;384  });385}386387export async function queryCollectionLimits(collectionId: number) {388  return await usingApi(async (api) => {389    return ((await api.query.nft.collectionById(collectionId)).toJSON() as any).Limits;390  });391}392393export async function setCollectionLimitsExpectSuccess(sender: IKeyringPair, collectionId: number, limits: any) {394  await usingApi(async (api) => {395    const oldLimits = await queryCollectionLimits(collectionId);396    const newLimits = { ...oldLimits as any, ...limits };397    const tx = api.tx.nft.setCollectionLimits(collectionId, newLimits);398    const events = await submitTransactionAsync(sender, tx);399    const result = getGenericResult(events);400401    expect(result.success).to.be.true;402  });403}404405export async function setCollectionLimitsExpectFailure(sender: IKeyringPair, collectionId: number, limits: any) {406  await usingApi(async (api) => {407    const oldLimits = await queryCollectionLimits(collectionId);408    const newLimits = { ...oldLimits as any, ...limits };409    const tx = api.tx.nft.setCollectionLimits(collectionId, newLimits);410    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;411    const result = getGenericResult(events);412413    expect(result.success).to.be.false;414  });415}416417export async function setCollectionSponsorExpectSuccess(collectionId: number, sponsor: string) {418  await usingApi(async (api) => {419420    // Run the transaction421    const alicePrivateKey = privateKey('//Alice');422    const tx = api.tx.nft.setCollectionSponsor(collectionId, sponsor);423    const events = await submitTransactionAsync(alicePrivateKey, tx);424    const result = getGenericResult(events);425426    // Get the collection427    const collection: any = (await api.query.nft.collectionById(collectionId)).toJSON();428429    // What to expect430    expect(result.success).to.be.true;431    expect(collection.Sponsorship).to.deep.equal({432      unconfirmed: sponsor,433    });434  });435}436437export async function removeCollectionSponsorExpectSuccess(collectionId: number) {438  await usingApi(async (api) => {439440    // Run the transaction441    const alicePrivateKey = privateKey('//Alice');442    const tx = api.tx.nft.removeCollectionSponsor(collectionId);443    const events = await submitTransactionAsync(alicePrivateKey, tx);444    const result = getGenericResult(events);445446    // Get the collection447    const collection: any = (await api.query.nft.collectionById(collectionId)).toJSON();448449    // What to expect450    expect(result.success).to.be.true;451    expect(collection.Sponsorship).to.be.deep.equal({ disabled: null });452  });453}454455export async function removeCollectionSponsorExpectFailure(collectionId: number) {456  await usingApi(async (api) => {457458    // Run the transaction459    const alicePrivateKey = privateKey('//Alice');460    const tx = api.tx.nft.removeCollectionSponsor(collectionId);461    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;462  });463}464465export async function setCollectionSponsorExpectFailure(collectionId: number, sponsor: string, senderSeed = '//Alice') {466  await usingApi(async (api) => {467468    // Run the transaction469    const alicePrivateKey = privateKey(senderSeed);470    const tx = api.tx.nft.setCollectionSponsor(collectionId, sponsor);471    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;472  });473}474475export async function confirmSponsorshipExpectSuccess(collectionId: number, senderSeed = '//Alice') {476  await usingApi(async (api) => {477478    // Run the transaction479    const sender = privateKey(senderSeed);480    const tx = api.tx.nft.confirmSponsorship(collectionId);481    const events = await submitTransactionAsync(sender, tx);482    const result = getGenericResult(events);483484    // Get the collection485    const collection: any = (await api.query.nft.collectionById(collectionId)).toJSON();486487    // What to expect488    expect(result.success).to.be.true;489    expect(collection.Sponsorship).to.be.deep.equal({490      confirmed: sender.address,491    });492  });493}494495496export async function confirmSponsorshipExpectFailure(collectionId: number, senderSeed = '//Alice') {497  await usingApi(async (api) => {498499    // Run the transaction500    const sender = privateKey(senderSeed);501    const tx = api.tx.nft.confirmSponsorship(collectionId);502    await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;503  });504}505506export async function setMetadataUpdatePermissionFlagExpectSuccess(sender: IKeyringPair, collectionId: number, flag: string) {507508  await usingApi(async (api) => {509    const tx = api.tx.nft.setMetaUpdatePermissionFlag(collectionId, flag); 510    const events = await submitTransactionAsync(sender, tx);511    const result = getGenericResult(events);512513    expect(result.success).to.be.true;514  }); 515}516517export async function setMetadataUpdatePermissionFlagExpectFailure(sender: IKeyringPair, collectionId: number, flag: string) {518519  await usingApi(async (api) => {520    const tx = api.tx.nft.setMetaUpdatePermissionFlag(collectionId, flag); 521    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;522    const result = getGenericResult(events);523524    expect(result.success).to.be.false;525  }); 526}527528export async function enableContractSponsoringExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {529  await usingApi(async (api) => {530    const tx = api.tx.nft.enableContractSponsoring(contractAddress, enable);531    const events = await submitTransactionAsync(sender, tx);532    const result = getGenericResult(events);533534    expect(result.success).to.be.true;535  });536}537538export async function enableContractSponsoringExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {539  await usingApi(async (api) => {540    const tx = api.tx.nft.enableContractSponsoring(contractAddress, enable);541    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;542    const result = getGenericResult(events);543544    expect(result.success).to.be.false;545  });546}547548export async function setContractSponsoringRateLimitExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {549  await usingApi(async (api) => {550    const tx = api.tx.nft.setContractSponsoringRateLimit(contractAddress, rateLimit);551    const events = await submitTransactionAsync(sender, tx);552    const result = getGenericResult(events);553554    expect(result.success).to.be.true;555  });556}557558export async function setContractSponsoringRateLimitExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {559  await usingApi(async (api) => {560    const tx = api.tx.nft.setContractSponsoringRateLimit(contractAddress, rateLimit);561    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;562    const result = getGenericResult(events);563564    expect(result.success).to.be.false;565  });566}567568export async function toggleContractWhitelistExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, value: boolean = true) {569  await usingApi(async (api) => {570    const tx = api.tx.nft.toggleContractWhiteList(contractAddress, value);571    const events = await submitTransactionAsync(sender, tx);572    const result = getGenericResult(events);573574    expect(result.success).to.be.true;575  });576}577578export async function isWhitelistedInContract(contractAddress: AccountId | string, user: string) {579  let whitelisted = false;580  await usingApi(async (api) => {581    whitelisted = (await api.query.nft.contractWhiteList(contractAddress, user)).toJSON() as boolean;582  });583  return whitelisted;584}585586export async function addToContractWhiteListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {587  await usingApi(async (api) => {588    const tx = api.tx.nft.addToContractWhiteList(contractAddress.toString(), user.toString());589    const events = await submitTransactionAsync(sender, tx);590    const result = getGenericResult(events);591592    expect(result.success).to.be.true;593  });594}595596export async function removeFromContractWhiteListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {597  await usingApi(async (api) => {598    const tx = api.tx.nft.removeFromContractWhiteList(contractAddress.toString(), user.toString());599    const events = await submitTransactionAsync(sender, tx);600    const result = getGenericResult(events);601602    expect(result.success).to.be.true;603  });604}605606export async function removeFromContractWhiteListExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {607  await usingApi(async (api) => {608    const tx = api.tx.nft.removeFromContractWhiteList(contractAddress.toString(), user.toString());609    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;610    const result = getGenericResult(events);611612    expect(result.success).to.be.false;613  });614}615616export async function setVariableMetaDataExpectSuccess(sender: IKeyringPair, collectionId: number, itemId: number, data: number[]) {617  await usingApi(async (api) => {618    const tx = api.tx.nft.setVariableMetaData(collectionId, itemId, '0x' + Buffer.from(data).toString('hex'));619    const events = await submitTransactionAsync(sender, tx);620    const result = getGenericResult(events);621622    expect(result.success).to.be.true;623  });624}625626export async function setVariableMetaDataExpectFailure(sender: IKeyringPair, collectionId: number, itemId: number, data: number[]) {627  await usingApi(async (api) => {628    const tx = api.tx.nft.setVariableMetaData(collectionId, itemId, '0x' + Buffer.from(data).toString('hex'));629    await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;630  });631}632633export async function setOffchainSchemaExpectSuccess(sender: IKeyringPair, collectionId: number, data: number[]) {634  await usingApi(async (api) => {635    const tx = api.tx.nft.setOffchainSchema(collectionId, '0x' + Buffer.from(data).toString('hex'));636    const events = await submitTransactionAsync(sender, tx);637    const result = getGenericResult(events);638639    expect(result.success).to.be.true;640  });641}642643export async function setOffchainSchemaExpectFailure(sender: IKeyringPair, collectionId: number, data: number[]) {644  await usingApi(async (api) => {645    const tx = api.tx.nft.setOffchainSchema(collectionId, '0x' + Buffer.from(data).toString('hex'));646    await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;647  });648}649650export interface CreateFungibleData {651  readonly Value: bigint;652}653654export interface CreateReFungibleData { }655export interface CreateNftData { }656657export type CreateItemData = {658  NFT: CreateNftData;659} | {660  Fungible: CreateFungibleData;661} | {662  ReFungible: CreateReFungibleData;663};664665export async function burnItemExpectSuccess(owner: IKeyringPair, collectionId: number, tokenId: number, value = 0) {666  await usingApi(async (api) => {667    const tx = api.tx.nft.burnItem(collectionId, tokenId, value);668    const events = await submitTransactionAsync(owner, tx);669    const result = getGenericResult(events);670    // Get the item671    const item: any = (await api.query.nft.nftItemList(collectionId, tokenId)).toJSON();672    // What to expect673    // tslint:disable-next-line:no-unused-expression674    expect(result.success).to.be.true;675    // tslint:disable-next-line:no-unused-expression676    expect(item).to.be.null;677  });678}679680export async function681approveExpectSuccess(682  collectionId: number,683  tokenId: number, owner: IKeyringPair, approved: IKeyringPair | CrossAccountId | string, amount: number | bigint = 1,684) {685  await usingApi(async (api: ApiPromise) => {686    approved = normalizeAccountId(approved);687    const allowanceBefore =688      await api.query.nft.allowances(collectionId, [tokenId, owner.address, toSubstrateAddress(approved)]) as unknown as BN;689    const approveNftTx = api.tx.nft.approve(approved, collectionId, tokenId, amount);690    const events = await submitTransactionAsync(owner, approveNftTx);691    const result = getCreateItemResult(events);692    // tslint:disable-next-line:no-unused-expression693    expect(result.success).to.be.true;694    const allowanceAfter =695      await api.query.nft.allowances(collectionId, [tokenId, owner.address, toSubstrateAddress(approved)]) as unknown as BN;696    expect(allowanceAfter.sub(allowanceBefore).toString()).to.be.equal(amount.toString());697  });698}699700export async function701transferFromExpectSuccess(702  collectionId: number,703  tokenId: number,704  accountApproved: IKeyringPair,705  accountFrom: IKeyringPair | CrossAccountId,706  accountTo: IKeyringPair | CrossAccountId,707  value: number | bigint = 1,708  type = 'NFT',709) {710  await usingApi(async (api: ApiPromise) => {711    const to = normalizeAccountId(accountTo);712    let balanceBefore = new BN(0);713    if (type === 'Fungible') {714      balanceBefore = await api.query.nft.balance(collectionId, toSubstrateAddress(to)) as unknown as BN;715    }716    const transferFromTx = api.tx.nft.transferFrom(normalizeAccountId(accountFrom), to, collectionId, tokenId, value);717    const events = await submitTransactionAsync(accountApproved, transferFromTx);718    const result = getCreateItemResult(events);719    // tslint:disable-next-line:no-unused-expression720    expect(result.success).to.be.true;721    if (type === 'NFT') {722      const nftItemData = (await api.query.nft.nftItemList(collectionId, tokenId) as any).toJSON() as ITokenDataType;723      expect(nftItemData.Owner).to.be.deep.equal(to);724    }725    if (type === 'Fungible') {726      const balanceAfter = (await api.query.nft.fungibleItemList(collectionId, toSubstrateAddress(to)) as any).Value as unknown as BN;727      expect(balanceAfter.sub(balanceBefore).toString()).to.be.equal(value.toString());728    }729    if (type === 'ReFungible') {730      const nftItemData =731        (await api.query.nft.reFungibleItemList(collectionId, tokenId) as any).toJSON() as IReFungibleTokenDataType;732      expect(nftItemData.Owner[0].Owner).to.be.deep.equal(normalizeAccountId(to));733      expect(nftItemData.Owner[0].Fraction).to.be.equal(value);734    }735  });736}737738export async function739transferFromExpectFail(740  collectionId: number,741  tokenId: number,742  accountApproved: IKeyringPair,743  accountFrom: IKeyringPair,744  accountTo: IKeyringPair,745  value: number | bigint = 1,746) {747  await usingApi(async (api: ApiPromise) => {748    const transferFromTx = api.tx.nft.transferFrom(normalizeAccountId(accountFrom.address), normalizeAccountId(accountTo.address), collectionId, tokenId, value);749    const events = await expect(submitTransactionExpectFailAsync(accountApproved, transferFromTx)).to.be.rejected;750    const result = getCreateCollectionResult(events);751    // tslint:disable-next-line:no-unused-expression752    expect(result.success).to.be.false;753  });754}755756/* eslint no-async-promise-executor: "off" */757async function getBlockNumber(api: ApiPromise): Promise<number> {758  return new Promise<number>(async (resolve) => {759    const unsubscribe = await api.rpc.chain.subscribeNewHeads((head) => {760      unsubscribe();761      resolve(head.number.toNumber());762    });763  });764}765766export async function767scheduleTransferExpectSuccess(768  collectionId: number,769  tokenId: number,770  sender: IKeyringPair,771  recipient: IKeyringPair,772  value: number | bigint = 1,773  blockTimeMs: number,774  blockSchedule: number775) {776  await usingApi(async (api: ApiPromise) => {777    const blockNumber: number | undefined = await getBlockNumber(api);778    const expectedBlockNumber = blockNumber + blockSchedule;779780    expect(blockNumber).to.be.greaterThan(0);781    const transferTx = await api.tx.nft.transfer(normalizeAccountId(recipient.address), collectionId, tokenId, value); 782    const scheduleTx = await api.tx.scheduler.schedule(expectedBlockNumber, null, 0, transferTx);783784    await submitTransactionAsync(sender, scheduleTx);785786    const recipientBalanceBefore = new BigNumber((await api.query.system.account(recipient.address)).data.free.toString());787788    const nftItemDataBefore = (await api.query.nft.nftItemList(collectionId, tokenId)).toJSON() as any as ITokenDataType;789    expect(toSubstrateAddress(nftItemDataBefore.Owner)).to.be.equal(sender.address);790791    // sleep for 4 blocks792    await new Promise(resolve => setTimeout(resolve, blockTimeMs * (blockSchedule + 1)));793794    const recipientBalanceAfter = new BigNumber((await api.query.system.account(recipient.address)).data.free.toString());795796    const nftItemData = (await api.query.nft.nftItemList(collectionId, tokenId)).toJSON() as unknown as ITokenDataType;797    expect(toSubstrateAddress(nftItemData.Owner)).to.be.equal(recipient.address);798    expect(recipientBalanceAfter.toNumber()).to.be.equal(recipientBalanceBefore.toNumber());799  });800}801802803export async function804transferExpectSuccess(805  collectionId: number,806  tokenId: number,807  sender: IKeyringPair,808  recipient: IKeyringPair | CrossAccountId,809  value: number | bigint = 1,810  type = 'NFT',811) {812  await usingApi(async (api: ApiPromise) => {813    const to = normalizeAccountId(recipient);814815    let balanceBefore = new BN(0);816    if (type === 'Fungible') {817      balanceBefore = await api.query.nft.balance(collectionId, toSubstrateAddress(to)) as unknown as BN;818    }819    const transferTx = api.tx.nft.transfer(to, collectionId, tokenId, value);820    const events = await submitTransactionAsync(sender, transferTx);821    const result = getTransferResult(events);822    // tslint:disable-next-line:no-unused-expression823    expect(result.success).to.be.true;824    expect(result.collectionId).to.be.equal(collectionId);825    expect(result.itemId).to.be.equal(tokenId);826    expect(result.sender).to.be.deep.equal(normalizeAccountId(sender.address));827    expect(result.recipient).to.be.deep.equal(to);828    expect(result.value.toString()).to.be.equal(value.toString());829    if (type === 'NFT') {830      const nftItemData = (await api.query.nft.nftItemList(collectionId, tokenId)).toJSON() as unknown as ITokenDataType;831      expect(nftItemData.Owner).to.be.deep.equal(to);832    }833    if (type === 'Fungible') {834      const balanceAfter = (await api.query.nft.fungibleItemList(collectionId, toSubstrateAddress(to)) as any).Value as unknown as BN;835      expect(balanceAfter.sub(balanceBefore).toString()).to.be.equal(value.toString());836    }837    if (type === 'ReFungible') {838      const nftItemData =839        (await api.query.nft.reFungibleItemList(collectionId, tokenId)).toJSON() as unknown as IReFungibleTokenDataType;840      expect(nftItemData.Owner[0].Owner).to.be.deep.equal(to);841      expect(nftItemData.Owner[0].Fraction.toString()).to.be.equal(value.toString());842    }843  });844}845846export async function847transferExpectFailure(848  collectionId: number,849  tokenId: number,850  sender: IKeyringPair,851  recipient: IKeyringPair,852  value: number | bigint = 1,853) {854  await usingApi(async (api: ApiPromise) => {855    const transferTx = api.tx.nft.transfer(normalizeAccountId(recipient.address), collectionId, tokenId, value);856    const events = await expect(submitTransactionExpectFailAsync(sender, transferTx)).to.be.rejected;857    if (events && Array.isArray(events)) {858      const result = getCreateCollectionResult(events);859      // tslint:disable-next-line:no-unused-expression860      expect(result.success).to.be.false;861    }862  });863}864865export async function866approveExpectFail(867  collectionId: number,868  tokenId: number, owner: IKeyringPair, approved: IKeyringPair, amount: number | bigint = 1,869) {870  await usingApi(async (api: ApiPromise) => {871    const approveNftTx = api.tx.nft.approve(normalizeAccountId(approved.address), collectionId, tokenId, amount);872    const events = await expect(submitTransactionExpectFailAsync(owner, approveNftTx)).to.be.rejected;873    const result = getCreateCollectionResult(events);874    // tslint:disable-next-line:no-unused-expression875    expect(result.success).to.be.false;876  });877}878879export async function getFungibleBalance(880  collectionId: number,881  owner: string,882) {883  return await usingApi(async (api) => {884    const response = (await api.query.nft.fungibleItemList(collectionId, owner)).toJSON() as unknown as { Value: string };885    return BigInt(response.Value);886  });887}888889export async function createFungibleItemExpectSuccess(890  sender: IKeyringPair,891  collectionId: number,892  data: CreateFungibleData,893  owner: CrossAccountId | string = sender.address,894) {895  return await usingApi(async (api) => {896    const tx = api.tx.nft.createItem(collectionId, normalizeAccountId(owner), { Fungible: data });897898    const events = await submitTransactionAsync(sender, tx);899    const result = getCreateItemResult(events);900901    expect(result.success).to.be.true;902    return result.itemId;903  });904}905906export async function createItemExpectSuccess(sender: IKeyringPair, collectionId: number, createMode: string, owner: CrossAccountId | string = sender.address) {907  let newItemId = 0;908  await usingApi(async (api) => {909    const to = normalizeAccountId(owner);910    const AItemCount = parseInt((await api.query.nft.itemListIndex(collectionId)).toString(), 10);911    const Aitem: any = (await api.query.nft.fungibleItemList(collectionId, toSubstrateAddress(to))).toJSON();912    const AItemBalance = new BigNumber(Aitem.Value);913914    let tx;915    if (createMode === 'Fungible') {916      const createData = { fungible: { value: 10 } };917      tx = api.tx.nft.createItem(collectionId, to, createData);918    } else if (createMode === 'ReFungible') {919      const createData = { refungible: { const_data: [], variable_data: [], pieces: 100 } };920      tx = api.tx.nft.createItem(collectionId, to, createData);921    } else {922      const createData = { nft: { const_data: [], variable_data: [] } };923      tx = api.tx.nft.createItem(collectionId, to, createData);924    }925926    const events = await submitTransactionAsync(sender, tx);927    const result = getCreateItemResult(events);928929    const BItemCount = parseInt((await api.query.nft.itemListIndex(collectionId)).toString(), 10);930    const Bitem: any = (await api.query.nft.fungibleItemList(collectionId, toSubstrateAddress(to))).toJSON();931    const BItemBalance = new BigNumber(Bitem.Value);932933    // What to expect934    // tslint:disable-next-line:no-unused-expression935    expect(result.success).to.be.true;936    if (createMode === 'Fungible') {937      expect(BItemBalance.minus(AItemBalance).toNumber()).to.be.equal(10);938    } else {939      expect(BItemCount).to.be.equal(AItemCount + 1);940    }941    expect(collectionId).to.be.equal(result.collectionId);942    expect(BItemCount.toString()).to.be.equal(result.itemId.toString());943    expect(to).to.be.deep.equal(result.recipient);944    newItemId = result.itemId;945  });946  return newItemId;947}948949export async function createItemExpectFailure(sender: IKeyringPair, collectionId: number, createMode: string, owner: string = sender.address) {950  await usingApi(async (api) => {951    const tx = api.tx.nft.createItem(collectionId, normalizeAccountId(owner), createMode);952    953    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;954    const result = getCreateItemResult(events);955956    expect(result.success).to.be.false;957  });958}959960export async function setPublicAccessModeExpectSuccess(961  sender: IKeyringPair, collectionId: number,962  accessMode: 'Normal' | 'WhiteList',963) {964  await usingApi(async (api) => {965966    // Run the transaction967    const tx = api.tx.nft.setPublicAccessMode(collectionId, accessMode);968    const events = await submitTransactionAsync(sender, tx);969    const result = getGenericResult(events);970971    // Get the collection972    const collection: any = (await api.query.nft.collectionById(collectionId)).toJSON();973974    // What to expect975    // tslint:disable-next-line:no-unused-expression976    expect(result.success).to.be.true;977    expect(collection.Access).to.be.equal(accessMode);978  });979}980981export async function enableWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number) {982  await setPublicAccessModeExpectSuccess(sender, collectionId, 'WhiteList');983}984985export async function disableWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number) {986  await setPublicAccessModeExpectSuccess(sender, collectionId, 'Normal');987}988989export async function setMintPermissionExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {990  await usingApi(async (api) => {991992    // Run the transaction993    const tx = api.tx.nft.setMintPermission(collectionId, enabled);994    const events = await submitTransactionAsync(sender, tx);995    const result = getGenericResult(events);996997    // Get the collection998    const collection: any = (await api.query.nft.collectionById(collectionId)).toJSON();9991000    // What to expect1001    // tslint:disable-next-line:no-unused-expression1002    expect(result.success).to.be.true;1003    expect(collection.MintMode).to.be.equal(enabled);1004  });1005}10061007export async function enablePublicMintingExpectSuccess(sender: IKeyringPair, collectionId: number) {1008  await setMintPermissionExpectSuccess(sender, collectionId, true);1009}10101011export async function addCollectionAdminExpectSuccess(sender: IKeyringPair, collectionId: number, address: IKeyringPair) {1012  await usingApi(async (api) => {1013    const changeAdminTx = api.tx.nft.addCollectionAdmin(collectionId, normalizeAccountId(address.address));1014    const events = await submitTransactionAsync(sender, changeAdminTx);1015    const result = getCreateCollectionResult(events);1016    expect(result.success).to.be.true;1017  });1018}10191020export async function setMintPermissionExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {1021  await usingApi(async (api) => {1022    // Run the transaction1023    const tx = api.tx.nft.setMintPermission(collectionId, enabled);1024    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1025    const result = getCreateCollectionResult(events);1026    // tslint:disable-next-line:no-unused-expression1027    expect(result.success).to.be.false;1028  });1029}10301031export async function isWhitelisted(collectionId: number, address: string) {1032  let whitelisted = false;1033  await usingApi(async (api) => {1034    whitelisted = (await api.query.nft.whiteList(collectionId, address)).toJSON() as unknown as boolean;1035  });1036  return whitelisted;1037}10381039export async function addToWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId) {1040  await usingApi(async (api) => {10411042    const whiteListedBefore = (await api.query.nft.whiteList(collectionId, address)).toJSON();10431044    // Run the transaction1045    const tx = api.tx.nft.addToWhiteList(collectionId, normalizeAccountId(address));1046    const events = await submitTransactionAsync(sender, tx);1047    const result = getGenericResult(events);10481049    const whiteListedAfter = (await api.query.nft.whiteList(collectionId, address)).toJSON();10501051    // What to expect1052    // tslint:disable-next-line:no-unused-expression1053    expect(result.success).to.be.true;1054    // tslint:disable-next-line: no-unused-expression1055    expect(whiteListedBefore).to.be.false;1056    // tslint:disable-next-line: no-unused-expression1057    expect(whiteListedAfter).to.be.true;1058  });1059}10601061export async function removeFromWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1062  await usingApi(async (api) => {1063    // Run the transaction1064    const tx = api.tx.nft.removeFromWhiteList(collectionId, normalizeAccountId(address));1065    const events = await submitTransactionAsync(sender, tx);1066    const result = getGenericResult(events);10671068    // What to expect1069    // tslint:disable-next-line:no-unused-expression1070    expect(result.success).to.be.true;1071  });1072}10731074export async function removeFromWhiteListExpectFailure(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1075  await usingApi(async (api) => {1076    // Run the transaction1077    const tx = api.tx.nft.removeFromWhiteList(collectionId, normalizeAccountId(address));1078    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1079    const result = getGenericResult(events);10801081    // What to expect1082    // tslint:disable-next-line:no-unused-expression1083    expect(result.success).to.be.false;1084  });1085}10861087export const getDetailedCollectionInfo = async (api: ApiPromise, collectionId: number)1088  : Promise<ICollectionInterface | null> => {1089  return (await api.query.nft.collectionById(collectionId)).toJSON() as unknown as ICollectionInterface;1090};10911092export const getCreatedCollectionCount = async (api: ApiPromise): Promise<number> => {1093  // set global object - collectionsCount1094  return (await api.query.nft.createdCollectionCount() as unknown as BN).toNumber();1095};10961097export async function queryCollectionExpectSuccess(collectionId: number): Promise<ICollectionInterface> {1098  return await usingApi(async (api) => {1099    return (await api.query.nft.collectionById(collectionId)).toJSON() as unknown as ICollectionInterface;1100  });1101}