difftreelog
Add test events
in: master
Add NFTPAR-321,325,326,324,347,345
8 files changed
tests/src/check-event/burnItemEvent.test.tsdiffbeforeafterboth--- /dev/null
+++ b/tests/src/check-event/burnItemEvent.test.ts
@@ -0,0 +1,41 @@
+//
+// This file is subject to the terms and conditions defined in
+// file 'LICENSE', which is part of this source code package.
+//
+
+// https://unique-network.readthedocs.io/en/latest/jsapi.html#setchainlimits
+import { ApiPromise } from '@polkadot/api';
+import { IKeyringPair } from '@polkadot/types/types';
+import chai from 'chai';
+import chaiAsPromised from 'chai-as-promised';
+import privateKey from '../substrate/privateKey';
+import usingApi, {submitTransactionAsync} from '../substrate/substrate-api';
+import { createCollectionExpectSuccess, createItemExpectSuccess, nftEventMessage } from '../util/helpers';
+
+chai.use(chaiAsPromised);
+const expect = chai.expect;
+
+describe('Burn Item event ', () => {
+ let Alice: IKeyringPair;
+ const checkSection = 'ItemDestroyed';
+ const checkTreasury = 'Deposit';
+ const checkSystem = 'ExtrinsicSuccess';
+ before(async () => {
+ await usingApi(async () => {
+ Alice = privateKey('//Alice');
+ });
+ });
+ it('Check event from burnItem(): ', async () => {
+ await usingApi(async (api: ApiPromise) => {
+ const collectionID = await createCollectionExpectSuccess();
+ const itemID = await createItemExpectSuccess(Alice, collectionID, 'NFT');
+ const burnItem = api.tx.nft.burnItem(collectionID, itemID, 1);
+ const events = await submitTransactionAsync(Alice, burnItem);
+ const msg = JSON.stringify(nftEventMessage(events));
+ expect(msg).to.be.contain(checkSection);
+ expect(msg).to.be.contain(checkTreasury);
+ expect(msg).to.be.contain(checkSystem);
+ });
+ });
+});
+
tests/src/check-event/createCollectionEvent.test.tsdiffbeforeafterboth--- /dev/null
+++ b/tests/src/check-event/createCollectionEvent.test.ts
@@ -0,0 +1,39 @@
+//
+// This file is subject to the terms and conditions defined in
+// file 'LICENSE', which is part of this source code package.
+//
+
+// https://unique-network.readthedocs.io/en/latest/jsapi.html#setchainlimits
+import { ApiPromise } from '@polkadot/api';
+import { IKeyringPair } from '@polkadot/types/types';
+import chai from 'chai';
+import chaiAsPromised from 'chai-as-promised';
+import privateKey from '../substrate/privateKey';
+import usingApi, {submitTransactionAsync} from '../substrate/substrate-api';
+import { nftEventMessage } from '../util/helpers';
+
+chai.use(chaiAsPromised);
+const expect = chai.expect;
+
+describe('Create collection event ', () => {
+ let Alice: IKeyringPair;
+ const checkSection = 'Created';
+ const checkTreasury = 'Deposit';
+ const checkSystem = 'ExtrinsicSuccess';
+ before(async () => {
+ await usingApi(async () => {
+ Alice = privateKey('//Alice');
+ });
+ });
+ it('Check event from createCollection(): ', async () => {
+ await usingApi(async (api: ApiPromise) => {
+ const tx = api.tx.nft.createCollection('0x31', '0x32', '0x33', 'NFT');
+ const events = await submitTransactionAsync(Alice, tx);
+ const msg = JSON.stringify(nftEventMessage(events));
+ expect(msg).to.be.contain(checkSection);
+ expect(msg).to.be.contain(checkTreasury);
+ expect(msg).to.be.contain(checkSystem);
+ });
+ });
+});
+
\ No newline at end of file
tests/src/check-event/createItemEvent.test.tsdiffbeforeafterboth--- /dev/null
+++ b/tests/src/check-event/createItemEvent.test.ts
@@ -0,0 +1,40 @@
+//
+// This file is subject to the terms and conditions defined in
+// file 'LICENSE', which is part of this source code package.
+//
+
+// https://unique-network.readthedocs.io/en/latest/jsapi.html#setchainlimits
+import { ApiPromise } from '@polkadot/api';
+import { IKeyringPair } from '@polkadot/types/types';
+import chai from 'chai';
+import chaiAsPromised from 'chai-as-promised';
+import privateKey from '../substrate/privateKey';
+import usingApi, {submitTransactionAsync} from '../substrate/substrate-api';
+import { createCollectionExpectSuccess, createItemExpectSuccess, nftEventMessage } from '../util/helpers';
+
+chai.use(chaiAsPromised);
+const expect = chai.expect;
+
+describe('Create Item event ', () => {
+ let Alice: IKeyringPair;
+ const checkSection = 'ItemCreated';
+ const checkTreasury = 'Deposit';
+ const checkSystem = 'ExtrinsicSuccess';
+ before(async () => {
+ await usingApi(async () => {
+ Alice = privateKey('//Alice');
+ });
+ });
+ it('Check event from createItem(): ', async () => {
+ await usingApi(async (api: ApiPromise) => {
+ const collectionID = await createCollectionExpectSuccess();
+ const createItem = api.tx.nft.createItem(collectionID, Alice.address, 'NFT');
+ const events = await submitTransactionAsync(Alice, createItem);
+ const msg = JSON.stringify(nftEventMessage(events));
+ expect(msg).to.be.contain(checkSection);
+ expect(msg).to.be.contain(checkTreasury);
+ expect(msg).to.be.contain(checkSystem);
+ });
+ });
+});
+
tests/src/check-event/createMultipleItemsEvent.test.tsdiffbeforeafterboth--- /dev/null
+++ b/tests/src/check-event/createMultipleItemsEvent.test.ts
@@ -0,0 +1,41 @@
+//
+// This file is subject to the terms and conditions defined in
+// file 'LICENSE', which is part of this source code package.
+//
+
+// https://unique-network.readthedocs.io/en/latest/jsapi.html#setchainlimits
+import { ApiPromise } from '@polkadot/api';
+import { IKeyringPair } from '@polkadot/types/types';
+import chai from 'chai';
+import chaiAsPromised from 'chai-as-promised';
+import privateKey from '../substrate/privateKey';
+import usingApi, {submitTransactionAsync} from '../substrate/substrate-api';
+import { createCollectionExpectSuccess, createItemExpectSuccess, nftEventMessage } from '../util/helpers';
+
+chai.use(chaiAsPromised);
+const expect = chai.expect;
+
+describe('Create Multiple Items Event event ', () => {
+ let Alice: IKeyringPair;
+ const checkSection = 'ItemCreated (x3)';
+ const checkTreasury = 'Deposit';
+ const checkSystem = 'ExtrinsicSuccess';
+ before(async () => {
+ await usingApi(async () => {
+ Alice = privateKey('//Alice');
+ });
+ });
+ it('Check event from createMultipleItems(): ', async () => {
+ await usingApi(async (api: ApiPromise) => {
+ const collectionID = await createCollectionExpectSuccess();
+ const args = [{ nft: ['0x31', '0x31'] }, { nft: ['0x32', '0x32'] }, { nft: ['0x33', '0x33'] }];
+ const createMultipleItems = api.tx.nft.createMultipleItems(collectionID, Alice.address, args);
+ const events = await submitTransactionAsync(Alice, createMultipleItems);
+ const msg = JSON.stringify(nftEventMessage(events));
+ expect(msg).to.be.contain(checkSection);
+ expect(msg).to.be.contain(checkTreasury);
+ expect(msg).to.be.contain(checkSystem);
+ });
+ });
+});
+
tests/src/check-event/destroyCollectionEvent.test.tsdiffbeforeafterboth--- /dev/null
+++ b/tests/src/check-event/destroyCollectionEvent.test.ts
@@ -0,0 +1,38 @@
+//
+// This file is subject to the terms and conditions defined in
+// file 'LICENSE', which is part of this source code package.
+//
+
+// https://unique-network.readthedocs.io/en/latest/jsapi.html#setchainlimits
+import { ApiPromise } from '@polkadot/api';
+import { IKeyringPair } from '@polkadot/types/types';
+import chai from 'chai';
+import chaiAsPromised from 'chai-as-promised';
+import privateKey from '../substrate/privateKey';
+import usingApi, {submitTransactionAsync} from '../substrate/substrate-api';
+import { createCollectionExpectSuccess, nftEventMessage } from '../util/helpers';
+
+chai.use(chaiAsPromised);
+const expect = chai.expect;
+
+describe('Destroy collection event ', () => {
+ let Alice: IKeyringPair;
+ const checkTreasury = 'Deposit';
+ const checkSystem = 'ExtrinsicSuccess';
+ before(async () => {
+ await usingApi(async () => {
+ Alice = privateKey('//Alice');
+ });
+ });
+ it('Check event from destroyCollection(): ', async () => {
+ await usingApi(async (api: ApiPromise) => {
+ const collectionID = await createCollectionExpectSuccess();
+ const destroyCollection = api.tx.nft.destroyCollection(collectionID);
+ const events = await submitTransactionAsync(Alice, destroyCollection);
+ const msg = JSON.stringify(nftEventMessage(events));
+ expect(msg).to.be.contain(checkTreasury);
+ expect(msg).to.be.contain(checkSystem);
+ });
+ });
+});
+
tests/src/check-event/transferEvent.test.tsdiffbeforeafterboth--- /dev/null
+++ b/tests/src/check-event/transferEvent.test.ts
@@ -0,0 +1,42 @@
+//
+// This file is subject to the terms and conditions defined in
+// file 'LICENSE', which is part of this source code package.
+//
+
+// https://unique-network.readthedocs.io/en/latest/jsapi.html#setchainlimits
+import { ApiPromise } from '@polkadot/api';
+import { IKeyringPair } from '@polkadot/types/types';
+import chai from 'chai';
+import chaiAsPromised from 'chai-as-promised';
+import privateKey from '../substrate/privateKey';
+import usingApi, {submitTransactionAsync} from '../substrate/substrate-api';
+import { createCollectionExpectSuccess, createItemExpectSuccess, nftEventMessage } from '../util/helpers';
+
+chai.use(chaiAsPromised);
+const expect = chai.expect;
+
+describe('Transfer event ', () => {
+ let Alice: IKeyringPair;
+ let Bob: IKeyringPair;
+ const checkTreasury = 'Deposit';
+ const checkSystem = 'ExtrinsicSuccess';
+ before(async () => {
+ await usingApi(async () => {
+ Alice = privateKey('//Alice');
+ Bob = privateKey('//Bob');
+ });
+ });
+ it('Check event from transfer(): ', async () => {
+ await usingApi(async (api: ApiPromise) => {
+ const collectionID = await createCollectionExpectSuccess();
+ const itemID = await createItemExpectSuccess(Alice, collectionID, 'NFT');
+ const transfer = api.tx.nft.transfer(Bob.address, collectionID, itemID, 1);
+ const events = await submitTransactionAsync(Alice, transfer);
+ const msg = JSON.stringify(nftEventMessage(events));
+ expect(msg).to.be.contain(checkTreasury);
+ expect(msg).to.be.contain(checkSystem);
+ });
+ });
+});
+
+
tests/src/check-event/transferFromEvent.test.tsdiffbeforeafterboth--- /dev/null
+++ b/tests/src/check-event/transferFromEvent.test.ts
@@ -0,0 +1,41 @@
+//
+// This file is subject to the terms and conditions defined in
+// file 'LICENSE', which is part of this source code package.
+//
+
+// https://unique-network.readthedocs.io/en/latest/jsapi.html#setchainlimits
+import { ApiPromise } from '@polkadot/api';
+import { IKeyringPair } from '@polkadot/types/types';
+import chai from 'chai';
+import chaiAsPromised from 'chai-as-promised';
+import privateKey from '../substrate/privateKey';
+import usingApi, {submitTransactionAsync} from '../substrate/substrate-api';
+import { createCollectionExpectSuccess, createItemExpectSuccess, nftEventMessage } from '../util/helpers';
+
+chai.use(chaiAsPromised);
+const expect = chai.expect;
+
+describe('Transfer from event ', () => {
+ let Alice: IKeyringPair;
+ let Bob: IKeyringPair;
+ const checkTreasury = 'Deposit';
+ const checkSystem = 'ExtrinsicSuccess';
+ before(async () => {
+ await usingApi(async () => {
+ Alice = privateKey('//Alice');
+ Bob = privateKey('//Bob');
+ });
+ });
+ it('Check event from transferFrom(): ', async () => {
+ await usingApi(async (api: ApiPromise) => {
+ const collectionID = await createCollectionExpectSuccess();
+ const itemID = await createItemExpectSuccess(Alice, collectionID, 'NFT');
+ const transferFrom = api.tx.nft.transferFrom(Alice.address, Bob.address, collectionID, itemID, 1);
+ const events = await submitTransactionAsync(Alice, transferFrom);
+ const msg = JSON.stringify(nftEventMessage(events));
+ expect(msg).to.be.contain(checkTreasury);
+ expect(msg).to.be.contain(checkSystem);
+ });
+ });
+});
+
tests/src/util/helpers.tsdiffbeforeafterboth1//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 { Enum, Struct } from '@polkadot/types/codec';8import type { AccountId, EventRecord } from '@polkadot/types/interfaces';9import { u128 } from '@polkadot/types/primitive';10import { IKeyringPair } from '@polkadot/types/types';11import { BigNumber } from 'bignumber.js';12import BN from 'bn.js';13import chai from 'chai';14import chaiAsPromised from 'chai-as-promised';15import { alicesPublicKey, nullPublicKey } from '../accounts';16import privateKey from '../substrate/privateKey';17import { default as usingApi, submitTransactionAsync, submitTransactionExpectFailAsync } from '../substrate/substrate-api';18import { ICollectionInterface } from '../types';19import { hexToStr, strToUTF16, utf16ToStr } from './util';2021chai.use(chaiAsPromised);22const expect = chai.expect;2324export const U128_MAX = (1n << 128n) - 1n;2526type GenericResult = {27 success: boolean,28};2930interface CreateCollectionResult {31 success: boolean;32 collectionId: number;33}3435interface CreateItemResult {36 success: boolean;37 collectionId: number;38 itemId: number;39 recipient: string;40}4142interface TransferResult {43 success: boolean;44 collectionId: number;45 itemId: number;46 sender: string;47 recipient: string;48 value: bigint;49}5051interface IReFungibleOwner {52 Fraction: BN;53 Owner: number[];54}5556interface ITokenDataType {57 Owner: number[];58 ConstData: number[];59 VariableData: number[];60}6162interface IFungibleTokenDataType {63 Value: BN;64}6566export interface IReFungibleTokenDataType {67 Owner: IReFungibleOwner[];68 ConstData: number[];69 VariableData: number[];70}7172export function getGenericResult(events: EventRecord[]): GenericResult {73 const result: GenericResult = {74 success: false,75 };76 events.forEach(({ phase, event: { data, method, section } }) => {77 // console.log(` ${phase}: ${section}.${method}:: ${data}`);78 if (method === 'ExtrinsicSuccess') {79 result.success = true;80 }81 });82 return result;83}8485export function getCreateCollectionResult(events: EventRecord[]): CreateCollectionResult {86 let success = false;87 let collectionId: number = 0;88 events.forEach(({ phase, event: { data, method, section } }) => {89 // console.log(` ${phase}: ${section}.${method}:: ${data}`);90 if (method == 'ExtrinsicSuccess') {91 success = true;92 } else if ((section == 'nft') && (method == 'Created')) {93 collectionId = parseInt(data[0].toString());94 }95 });96 const result: CreateCollectionResult = {97 success,98 collectionId,99 };100 return result;101}102103export function getCreateItemResult(events: EventRecord[]): CreateItemResult {104 let success = false;105 let collectionId: number = 0;106 let itemId: number = 0;107 let recipient: string = '';108 events.forEach(({ phase, event: { data, method, section } }) => {109 // console.log(` ${phase}: ${section}.${method}:: ${data}`);110 if (method == 'ExtrinsicSuccess') {111 success = true;112 } else if ((section == 'nft') && (method == 'ItemCreated')) {113 collectionId = parseInt(data[0].toString());114 itemId = parseInt(data[1].toString());115 recipient = data[2].toString();116 }117 });118 const result: CreateItemResult = {119 success,120 collectionId,121 itemId,122 recipient,123 };124 return result;125}126127export function getTransferResult(events: EventRecord[]): TransferResult {128 const result: TransferResult = {129 success: false,130 collectionId: 0,131 itemId: 0,132 sender: '',133 recipient: '',134 value: 0n,135 };136137 events.forEach(({event: {data, method, section}}) => {138 if (method === 'ExtrinsicSuccess') {139 result.success = true;140 } else if (section === 'nft' && method === 'Transfer') {141 result.collectionId = +data[0].toString();142 result.itemId = +data[1].toString();143 result.sender = data[2].toString();144 result.recipient = data[3].toString();145 result.value = BigInt(data[4].toString());146 }147 });148149 return result;150}151152interface Invalid {153 type: 'Invalid';154}155156interface Nft {157 type: 'NFT';158}159160interface Fungible {161 type: 'Fungible';162 decimalPoints: number;163}164165interface ReFungible {166 type: 'ReFungible';167}168169type CollectionMode = Nft | Fungible | ReFungible | Invalid;170171export type CreateCollectionParams = {172 mode: CollectionMode,173 name: string,174 description: string,175 tokenPrefix: string,176};177178const defaultCreateCollectionParams: CreateCollectionParams = {179 description: 'description',180 mode: { type: 'NFT' },181 name: 'name',182 tokenPrefix: 'prefix',183}184185export async function createCollectionExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {186 const {name, description, mode, tokenPrefix } = {...defaultCreateCollectionParams, ...params};187188 let collectionId: number = 0;189 await usingApi(async (api) => {190 // Get number of collections before the transaction191 const AcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString(), 10);192193 // Run the CreateCollection transaction194 const alicePrivateKey = privateKey('//Alice');195196 let modeprm = {};197 if (mode.type === 'NFT') {198 modeprm = {nft: null};199 } else if (mode.type === 'Fungible') {200 modeprm = {fungible: mode.decimalPoints};201 } else if (mode.type === 'ReFungible') {202 modeprm = {refungible: null};203 } else if (mode.type === 'Invalid') {204 modeprm = {invalid: null};205 }206207 const tx = api.tx.nft.createCollection(strToUTF16(name), strToUTF16(description), strToUTF16(tokenPrefix), modeprm);208 const events = await submitTransactionAsync(alicePrivateKey, tx);209 const result = getCreateCollectionResult(events);210211 // Get number of collections after the transaction212 const BcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString(), 10);213214 // Get the collection215 const collection: any = (await api.query.nft.collection(result.collectionId)).toJSON();216217 // What to expect218 // tslint:disable-next-line:no-unused-expression219 expect(result.success).to.be.true;220 expect(result.collectionId).to.be.equal(BcollectionCount);221 // tslint:disable-next-line:no-unused-expression222 expect(collection).to.be.not.null;223 expect(BcollectionCount).to.be.equal(AcollectionCount + 1, 'Error: NFT collection NOT created.');224 expect(collection.Owner).to.be.equal(alicesPublicKey);225 expect(utf16ToStr(collection.Name)).to.be.equal(name);226 expect(utf16ToStr(collection.Description)).to.be.equal(description);227 expect(hexToStr(collection.TokenPrefix)).to.be.equal(tokenPrefix);228229 collectionId = result.collectionId;230 });231232 return collectionId;233}234235export async function createCollectionExpectFailure(params: Partial<CreateCollectionParams> = {}) {236 const {name, description, mode, tokenPrefix } = {...defaultCreateCollectionParams, ...params};237238 let modeprm = {};239 if (mode.type === 'NFT') {240 modeprm = {nft: null};241 } else if (mode.type === 'Fungible') {242 modeprm = {fungible: mode.decimalPoints};243 } else if (mode.type === 'ReFungible') {244 modeprm = {refungible: null};245 } else if (mode.type === 'Invalid') {246 modeprm = {invalid: null};247 }248249 await usingApi(async (api) => {250 // Get number of collections before the transaction251 const AcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString());252253 // Run the CreateCollection transaction254 const alicePrivateKey = privateKey('//Alice');255 const tx = api.tx.nft.createCollection(strToUTF16(name), strToUTF16(description), strToUTF16(tokenPrefix), modeprm);256 const events = await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;257 const result = getCreateCollectionResult(events);258259 // Get number of collections after the transaction260 const BcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString());261262 // What to expect263 // tslint:disable-next-line:no-unused-expression264 expect(result.success).to.be.false;265 expect(BcollectionCount).to.be.equal(AcollectionCount, 'Error: Collection with incorrect data created.');266 });267}268269export async function findUnusedAddress(api: ApiPromise, seedAddition = ''): Promise<IKeyringPair> {270 let bal = new BigNumber(0);271 let unused;272 do {273 const randomSeed = 'seed' + Math.floor(Math.random() * Math.floor(10000)) + seedAddition;274 const keyring = new Keyring({ type: 'sr25519' });275 unused = keyring.addFromUri(`//${randomSeed}`);276 bal = new BigNumber((await api.query.system.account(unused.address)).data.free.toString());277 } while (bal.toFixed() != '0');278 return unused;279}280281export async function getAllowance(collectionId: number, tokenId: number, owner: string, approved: string) {282 return await usingApi(async (api) => {283 const bn = await api.query.nft.allowances(collectionId, [tokenId, owner, approved]) as unknown as BN;284 return BigInt(bn.toString());285 });286}287288export function findUnusedAddresses(api: ApiPromise, amount: number): Promise<IKeyringPair[]> {289 return Promise.all(new Array(amount).fill(null).map(() => findUnusedAddress(api, '_' + Date.now())));290}291292export async function findNotExistingCollection(api: ApiPromise): Promise<number> {293 const totalNumber = parseInt((await api.query.nft.createdCollectionCount()).toString(), 10) as unknown as number;294 const newCollection: number = totalNumber + 1;295 return newCollection;296}297298function getDestroyResult(events: EventRecord[]): boolean {299 let success: boolean = false;300 events.forEach(({ phase, event: { data, method, section } }) => {301 // console.log(` ${phase}: ${section}.${method}:: ${data}`);302 if (method == 'ExtrinsicSuccess') {303 success = true;304 }305 });306 return success;307}308309export async function destroyCollectionExpectFailure(collectionId: number, senderSeed: string = '//Alice') {310 await usingApi(async (api) => {311 // Run the DestroyCollection transaction312 const alicePrivateKey = privateKey(senderSeed);313 const tx = api.tx.nft.destroyCollection(collectionId);314 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;315 });316}317318export async function destroyCollectionExpectSuccess(collectionId: number, senderSeed: string = '//Alice') {319 await usingApi(async (api) => {320 // Run the DestroyCollection transaction321 const alicePrivateKey = privateKey(senderSeed);322 const tx = api.tx.nft.destroyCollection(collectionId);323 const events = await submitTransactionAsync(alicePrivateKey, tx);324 const result = getDestroyResult(events);325326 // Get the collection327 const collection: any = (await api.query.nft.collection(collectionId)).toJSON();328329 // What to expect330 expect(result).to.be.true;331 expect(collection).to.be.not.null;332 expect(collection.Owner).to.be.equal(nullPublicKey);333 });334}335336export async function queryCollectionLimits(collectionId: number) {337 return await usingApi(async (api) => {338 return ((await api.query.nft.collection(collectionId)).toJSON() as any).Limits;339 });340}341342export async function setCollectionLimitsExpectSuccess(sender: IKeyringPair, collectionId: number, limits: any) {343 await usingApi(async (api) => {344 const oldLimits = await queryCollectionLimits(collectionId);345 const newLimits = { ...oldLimits as any, ...limits };346 const tx = api.tx.nft.setCollectionLimits(collectionId, newLimits);347 const events = await submitTransactionAsync(sender, tx);348 const result = getGenericResult(events);349350 expect(result.success).to.be.true;351 });352}353354export async function setCollectionLimitsExpectFailure(sender: IKeyringPair, collectionId: number, limits: any) {355 await usingApi(async (api) => {356 const oldLimits = await queryCollectionLimits(collectionId);357 const newLimits = { ...oldLimits as any, ...limits };358 const tx = api.tx.nft.setCollectionLimits(collectionId, newLimits);359 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;360 const result = getGenericResult(events);361362 expect(result.success).to.be.false;363 });364}365366export async function setCollectionSponsorExpectSuccess(collectionId: number, sponsor: string) {367 await usingApi(async (api) => {368369 // Run the transaction370 const alicePrivateKey = privateKey('//Alice');371 const tx = api.tx.nft.setCollectionSponsor(collectionId, sponsor);372 const events = await submitTransactionAsync(alicePrivateKey, tx);373 const result = getGenericResult(events);374375 // Get the collection376 const collection: any = (await api.query.nft.collection(collectionId)).toJSON();377378 // What to expect379 expect(result.success).to.be.true;380 expect(collection.Sponsor.toString()).to.be.equal(sponsor.toString());381 expect(collection.SponsorConfirmed).to.be.false;382 });383}384385export async function removeCollectionSponsorExpectSuccess(collectionId: number) {386 await usingApi(async (api) => {387388 // Run the transaction389 const alicePrivateKey = privateKey('//Alice');390 const tx = api.tx.nft.removeCollectionSponsor(collectionId);391 const events = await submitTransactionAsync(alicePrivateKey, tx);392 const result = getGenericResult(events);393394 // Get the collection395 const collection: any = (await api.query.nft.collection(collectionId)).toJSON();396397 // What to expect398 expect(result.success).to.be.true;399 expect(collection.Sponsor).to.be.equal(nullPublicKey);400 expect(collection.SponsorConfirmed).to.be.false;401 });402}403404export async function removeCollectionSponsorExpectFailure(collectionId: number) {405 await usingApi(async (api) => {406407 // Run the transaction408 const alicePrivateKey = privateKey('//Alice');409 const tx = api.tx.nft.removeCollectionSponsor(collectionId);410 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;411 });412}413414export async function setCollectionSponsorExpectFailure(collectionId: number, sponsor: string, senderSeed: string = '//Alice') {415 await usingApi(async (api) => {416417 // Run the transaction418 const alicePrivateKey = privateKey(senderSeed);419 const tx = api.tx.nft.setCollectionSponsor(collectionId, sponsor);420 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;421 });422}423424export async function confirmSponsorshipExpectSuccess(collectionId: number, senderSeed: string = '//Alice') {425 await usingApi(async (api) => {426427 // Run the transaction428 const sender = privateKey(senderSeed);429 const tx = api.tx.nft.confirmSponsorship(collectionId);430 const events = await submitTransactionAsync(sender, tx);431 const result = getGenericResult(events);432433 // Get the collection434 const collection: any = (await api.query.nft.collection(collectionId)).toJSON();435436 // What to expect437 expect(result.success).to.be.true;438 expect(collection.Sponsor).to.be.equal(sender.address);439 expect(collection.SponsorConfirmed).to.be.true;440 });441}442443444export async function confirmSponsorshipExpectFailure(collectionId: number, senderSeed: string = '//Alice') {445 await usingApi(async (api) => {446447 // Run the transaction448 const sender = privateKey(senderSeed);449 const tx = api.tx.nft.confirmSponsorship(collectionId);450 await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;451 });452}453454export async function enableContractSponsoringExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {455 await usingApi(async (api) => {456 const tx = api.tx.nft.enableContractSponsoring(contractAddress, enable);457 const events = await submitTransactionAsync(sender, tx);458 const result = getGenericResult(events);459460 expect(result.success).to.be.true;461 });462}463464export async function enableContractSponsoringExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {465 await usingApi(async (api) => {466 const tx = api.tx.nft.enableContractSponsoring(contractAddress, enable);467 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;468 const result = getGenericResult(events);469470 expect(result.success).to.be.false;471 });472}473474export async function setContractSponsoringRateLimitExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {475 await usingApi(async (api) => {476 const tx = api.tx.nft.setContractSponsoringRateLimit(contractAddress, rateLimit);477 const events = await submitTransactionAsync(sender, tx);478 const result = getGenericResult(events);479480 expect(result.success).to.be.true;481 });482}483484export async function setContractSponsoringRateLimitExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {485 await usingApi(async (api) => {486 const tx = api.tx.nft.setContractSponsoringRateLimit(contractAddress, rateLimit);487 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;488 const result = getGenericResult(events);489490 expect(result.success).to.be.false;491 });492}493494export async function toggleContractWhitelistExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, enabled: boolean) {495 await usingApi(async (api) => {496 const tx = api.tx.nft.toggleContractWhiteList(contractAddress, true);497 const events = await submitTransactionAsync(sender, tx);498 const result = getGenericResult(events);499500 expect(result.success).to.be.true;501 });502}503504export async function isWhitelistedInContract(contractAddress: AccountId | string, user: string) {505 let whitelisted: boolean = false;506 await usingApi(async (api) => {507 whitelisted = (await api.query.nft.contractWhiteList(contractAddress, user)).toJSON() as boolean;508 });509 return whitelisted;510}511512export async function addToContractWhiteListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: string) {513 await usingApi(async (api) => {514 const tx = api.tx.nft.addToContractWhiteList(contractAddress, user);515 const events = await submitTransactionAsync(sender, tx);516 const result = getGenericResult(events);517518 expect(result.success).to.be.true;519 });520}521522export async function removeFromContractWhiteListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: string) {523 await usingApi(async (api) => {524 const tx = api.tx.nft.removeFromContractWhiteList(contractAddress, user);525 const events = await submitTransactionAsync(sender, tx);526 const result = getGenericResult(events);527528 expect(result.success).to.be.true;529 });530}531532export async function removeFromContractWhiteListExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, user: string) {533 await usingApi(async (api) => {534 const tx = api.tx.nft.removeFromContractWhiteList(contractAddress, user);535 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;536 const result = getGenericResult(events);537538 expect(result.success).to.be.false;539 });540}541542export async function setVariableMetaDataExpectSuccess(sender: IKeyringPair, collectionId: number, itemId: number, data: number[]) {543 await usingApi(async (api) => {544 const tx = api.tx.nft.setVariableMetaData(collectionId, itemId, '0x' + Buffer.from(data).toString('hex'));545 const events = await submitTransactionAsync(sender, tx);546 const result = getGenericResult(events);547548 expect(result.success).to.be.true;549 });550}551552export async function setVariableMetaDataExpectFailure(sender: IKeyringPair, collectionId: number, itemId: number, data: number[]) {553 await usingApi(async (api) => {554 const tx = api.tx.nft.setVariableMetaData(collectionId, itemId, '0x' + Buffer.from(data).toString('hex'));555 await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;556 });557}558559export async function setOffchainSchemaExpectSuccess(sender: IKeyringPair, collectionId: number, data: number[]) {560 await usingApi(async (api) => {561 const tx = api.tx.nft.setOffchainSchema(collectionId, '0x' + Buffer.from(data).toString('hex'));562 const events = await submitTransactionAsync(sender, tx);563 const result = getGenericResult(events);564565 expect(result.success).to.be.true;566 });567}568569export async function setOffchainSchemaExpectFailure(sender: IKeyringPair, collectionId: number, data: number[]) {570 await usingApi(async (api) => {571 const tx = api.tx.nft.setOffchainSchema(collectionId, '0x' + Buffer.from(data).toString('hex'));572 await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;573 });574}575576export interface CreateFungibleData {577 readonly Value: bigint;578}579580export interface CreateReFungibleData { }581export interface CreateNftData { }582583export type CreateItemData = {584 NFT: CreateNftData;585} | {586 Fungible: CreateFungibleData;587} | {588 ReFungible: CreateReFungibleData;589};590591export async function burnItemExpectSuccess(owner: IKeyringPair, collectionId: number, tokenId: number, value = 0) {592 await usingApi(async (api) => {593 const tx = api.tx.nft.burnItem(collectionId, tokenId, value);594 const events = await submitTransactionAsync(owner, tx);595 const result = getGenericResult(events);596 // Get the item597 const item: any = (await api.query.nft.nftItemList(collectionId, tokenId)).toJSON();598 // What to expect599 // tslint:disable-next-line:no-unused-expression600 expect(result.success).to.be.true;601 // tslint:disable-next-line:no-unused-expression602 expect(item).to.be.not.null;603 expect(item.Owner).to.be.equal(nullPublicKey);604 });605}606607export async function608approveExpectSuccess(collectionId: number,609 tokenId: number, owner: IKeyringPair, approved: IKeyringPair, amount: number | bigint = 1) {610 await usingApi(async (api: ApiPromise) => {611 const allowanceBefore =612 await api.query.nft.allowances(collectionId, [tokenId, owner.address, approved.address]) as unknown as BN;613 const approveNftTx = await api.tx.nft.approve(approved.address, collectionId, tokenId, amount);614 const events = await submitTransactionAsync(owner, approveNftTx);615 const result = getCreateItemResult(events);616 // tslint:disable-next-line:no-unused-expression617 expect(result.success).to.be.true;618 const allowanceAfter =619 await api.query.nft.allowances(collectionId, [tokenId, owner.address, approved.address]) as unknown as BN;620 expect(allowanceAfter.sub(allowanceBefore).toString()).to.be.equal(amount.toString());621 });622}623624export async function625transferFromExpectSuccess(collectionId: number,626 tokenId: number,627 accountApproved: IKeyringPair,628 accountFrom: IKeyringPair,629 accountTo: IKeyringPair,630 value: number | bigint = 1,631 type: string = 'NFT') {632 await usingApi(async (api: ApiPromise) => {633 let balanceBefore = new BN(0);634 if (type === 'Fungible') {635 balanceBefore = await api.query.nft.balance(collectionId, accountTo.address) as unknown as BN;636 }637 const transferFromTx = await api.tx.nft.transferFrom(638 accountFrom.address, accountTo.address, collectionId, tokenId, value);639 const events = await submitTransactionAsync(accountApproved, transferFromTx);640 const result = getCreateItemResult(events);641 // tslint:disable-next-line:no-unused-expression642 expect(result.success).to.be.true;643 if (type === 'NFT') {644 const nftItemData = await api.query.nft.nftItemList(collectionId, tokenId) as unknown as ITokenDataType;645 expect(nftItemData.Owner.toString()).to.be.equal(accountTo.address);646 }647 if (type === 'Fungible') {648 const balanceAfter = await api.query.nft.balance(collectionId, accountTo.address) as unknown as BN;649 expect(balanceAfter.sub(balanceBefore).toString()).to.be.equal(value.toString());650 }651 if (type === 'ReFungible') {652 const nftItemData =653 await api.query.nft.reFungibleItemList(collectionId, tokenId) as unknown as IReFungibleTokenDataType;654 expect(nftItemData.Owner[0].Owner.toString()).to.be.equal(accountTo.address);655 expect(nftItemData.Owner[0].Fraction.toNumber()).to.be.equal(value);656 }657 });658}659660export async function661transferFromExpectFail(collectionId: number,662 tokenId: number,663 accountApproved: IKeyringPair,664 accountFrom: IKeyringPair,665 accountTo: IKeyringPair,666 value: number | bigint = 1) {667 await usingApi(async (api: ApiPromise) => {668 const transferFromTx = await api.tx.nft.transferFrom(669 accountFrom.address, accountTo.address, collectionId, tokenId, value);670 const events = await expect(submitTransactionExpectFailAsync(accountApproved, transferFromTx)).to.be.rejected;671 const result = getCreateCollectionResult(events);672 // tslint:disable-next-line:no-unused-expression673 expect(result.success).to.be.false;674 });675}676677export async function678transferExpectSuccess(collectionId: number,679 tokenId: number,680 sender: IKeyringPair,681 recipient: IKeyringPair,682 value: number | bigint = 1,683 type: string = 'NFT') {684 await usingApi(async (api: ApiPromise) => {685 let balanceBefore = new BN(0);686 if (type === 'Fungible') {687 balanceBefore = await api.query.nft.balance(collectionId, recipient.address) as unknown as BN;688 }689 const transferTx = await api.tx.nft.transfer(recipient.address, collectionId, tokenId, value);690 const events = await submitTransactionAsync(sender, transferTx);691 const result = getTransferResult(events);692 // tslint:disable-next-line:no-unused-expression693 expect(result.success).to.be.true;694 expect(result.collectionId).to.be.equal(collectionId);695 expect(result.itemId).to.be.equal(tokenId);696 expect(result.sender).to.be.equal(sender.address);697 expect(result.recipient).to.be.equal(recipient.address);698 expect(result.value.toString()).to.be.equal(value.toString());699 if (type === 'NFT') {700 const nftItemData = await api.query.nft.nftItemList(collectionId, tokenId) as unknown as ITokenDataType;701 expect(nftItemData.Owner.toString()).to.be.equal(recipient.address);702 }703 if (type === 'Fungible') {704 const balanceAfter = await api.query.nft.balance(collectionId, recipient.address) 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 unknown as IReFungibleTokenDataType;710 expect(nftItemData.Owner[0].Owner.toString()).to.be.equal(recipient.address);711 expect(nftItemData.Owner[0].Fraction.toNumber()).to.be.equal(value);712 }713 });714}715716export async function717transferExpectFail(collectionId: number,718 tokenId: number,719 sender: IKeyringPair,720 recipient: IKeyringPair,721 value: number | bigint = 1,722 type: string = 'NFT') {723 await usingApi(async (api: ApiPromise) => {724 const transferTx = await api.tx.nft.transfer(recipient.address, collectionId, tokenId, value);725 const events = await expect(submitTransactionExpectFailAsync(sender, transferTx)).to.be.rejected;726 if (events && Array.isArray(events)) {727 const result = getCreateCollectionResult(events);728 // tslint:disable-next-line:no-unused-expression729 expect(result.success).to.be.false;730 }731 });732}733734export async function735approveExpectFail(collectionId: number,736 tokenId: number, owner: IKeyringPair, approved: IKeyringPair, amount: number | bigint = 1) {737 await usingApi(async (api: ApiPromise) => {738 const approveNftTx = await api.tx.nft.approve(approved.address, collectionId, tokenId, amount);739 const events = await expect(submitTransactionExpectFailAsync(owner, approveNftTx)).to.be.rejected;740 const result = getCreateCollectionResult(events);741 // tslint:disable-next-line:no-unused-expression742 expect(result.success).to.be.false;743 });744}745746export async function getFungibleBalance(747 collectionId: number,748 owner: string,749) {750 return await usingApi(async (api) => {751 const response = (await api.query.nft.fungibleItemList(collectionId, owner)).toJSON() as unknown as {Value: string};752 return BigInt(response.Value);753 });754}755756export async function createFungibleItemExpectSuccess(757 sender: IKeyringPair,758 collectionId: number,759 data: CreateFungibleData,760 owner: string = sender.address,761) {762 return await usingApi(async (api) => {763 const tx = api.tx.nft.createItem(collectionId, owner, { Fungible: data });764765 const events = await submitTransactionAsync(sender, tx);766 const result = getCreateItemResult(events);767768 expect(result.success).to.be.true;769 return result.itemId;770 });771}772773export async function createItemExpectSuccess(774 sender: IKeyringPair, collectionId: number, createMode: string, owner: string = '') {775 let newItemId: number = 0;776 await usingApi(async (api) => {777 const AItemCount = parseInt((await api.query.nft.itemListIndex(collectionId)).toString(), 10);778 const Aitem: any = (await api.query.nft.fungibleItemList(collectionId, owner)).toJSON();779 const AItemBalance = new BigNumber(Aitem.Value);780781 if (owner === '') {782 owner = sender.address;783 }784785 let tx;786 if (createMode === 'Fungible') {787 const createData = {fungible: {value: 10}};788 tx = api.tx.nft.createItem(collectionId, owner, createData);789 } else if (createMode === 'ReFungible') {790 const createData = {refungible: {const_data: [], variable_data: [], pieces: 100}};791 tx = api.tx.nft.createItem(collectionId, owner, createData);792 } else {793 tx = api.tx.nft.createItem(collectionId, owner, createMode);794 }795 const events = await submitTransactionAsync(sender, tx);796 const result = getCreateItemResult(events);797798 const BItemCount = parseInt((await api.query.nft.itemListIndex(collectionId)).toString(), 10);799 const Bitem: any = (await api.query.nft.fungibleItemList(collectionId, owner)).toJSON();800 const BItemBalance = new BigNumber(Bitem.Value);801802 // What to expect803 // tslint:disable-next-line:no-unused-expression804 expect(result.success).to.be.true;805 if (createMode === 'Fungible') {806 expect(BItemBalance.minus(AItemBalance).toNumber()).to.be.equal(10);807 } else {808 expect(BItemCount).to.be.equal(AItemCount + 1);809 }810 expect(collectionId).to.be.equal(result.collectionId);811 expect(BItemCount).to.be.equal(result.itemId);812 expect(owner).to.be.equal(result.recipient);813 newItemId = result.itemId;814 });815 return newItemId;816}817818export async function createItemExpectFailure(819 sender: IKeyringPair, collectionId: number, createMode: string, owner: string = sender.address) {820 await usingApi(async (api) => {821 const tx = api.tx.nft.createItem(collectionId, owner, createMode);822 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;823 const result = getCreateItemResult(events);824825 expect(result.success).to.be.false;826 });827}828829export async function setPublicAccessModeExpectSuccess(830 sender: IKeyringPair, collectionId: number,831 accessMode: 'Normal' | 'WhiteList',832) {833 await usingApi(async (api) => {834835 // Run the transaction836 const tx = api.tx.nft.setPublicAccessMode(collectionId, accessMode);837 const events = await submitTransactionAsync(sender, tx);838 const result = getGenericResult(events);839840 // Get the collection841 const collection: any = (await api.query.nft.collection(collectionId)).toJSON();842843 // What to expect844 // tslint:disable-next-line:no-unused-expression845 expect(result.success).to.be.true;846 expect(collection.Access).to.be.equal(accessMode);847 });848}849850export async function enableWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number) {851 await setPublicAccessModeExpectSuccess(sender, collectionId, 'WhiteList');852}853854export async function disableWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number) {855 await setPublicAccessModeExpectSuccess(sender, collectionId, 'Normal');856}857858export async function setMintPermissionExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {859 await usingApi(async (api) => {860861 // Run the transaction862 const tx = api.tx.nft.setMintPermission(collectionId, enabled);863 const events = await submitTransactionAsync(sender, tx);864 const result = getGenericResult(events);865866 // Get the collection867 const collection: any = (await api.query.nft.collection(collectionId)).toJSON();868869 // What to expect870 // tslint:disable-next-line:no-unused-expression871 expect(result.success).to.be.true;872 expect(collection.MintMode).to.be.equal(enabled);873 });874}875876export async function enablePublicMintingExpectSuccess(sender: IKeyringPair, collectionId: number) {877 await setMintPermissionExpectSuccess(sender, collectionId, true);878}879880export async function setMintPermissionExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {881 await usingApi(async (api) => {882 // Run the transaction883 const tx = api.tx.nft.setMintPermission(collectionId, enabled);884 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;885 const result = getCreateCollectionResult(events);886 // tslint:disable-next-line:no-unused-expression887 expect(result.success).to.be.false;888 });889}890891export async function isWhitelisted(collectionId: number, address: string) {892 let whitelisted: boolean = false;893 await usingApi(async (api) => {894 whitelisted = (await api.query.nft.whiteList(collectionId, address)).toJSON() as unknown as boolean;895 });896 return whitelisted;897}898899export async function addToWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number, address: string) {900 await usingApi(async (api) => {901902 const whiteListedBefore = (await api.query.nft.whiteList(collectionId, address)).toJSON();903904 // Run the transaction905 const tx = api.tx.nft.addToWhiteList(collectionId, address);906 const events = await submitTransactionAsync(sender, tx);907 const result = getGenericResult(events);908909 const whiteListedAfter = (await api.query.nft.whiteList(collectionId, address)).toJSON();910911 // What to expect912 // tslint:disable-next-line:no-unused-expression913 expect(result.success).to.be.true;914 // tslint:disable-next-line: no-unused-expression915 expect(whiteListedBefore).to.be.false;916 // tslint:disable-next-line: no-unused-expression917 expect(whiteListedAfter).to.be.true;918 });919}920921export async function removeFromWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number, address: string) {922 await usingApi(async (api) => {923 // Run the transaction924 const tx = api.tx.nft.removeFromWhiteList(collectionId, address);925 const events = await submitTransactionAsync(sender, tx);926 const result = getGenericResult(events);927928 // What to expect929 // tslint:disable-next-line:no-unused-expression930 expect(result.success).to.be.true;931 });932}933934export async function removeFromWhiteListExpectFailure(sender: IKeyringPair, collectionId: number, address: string) {935 await usingApi(async (api) => {936 // Run the transaction937 const tx = api.tx.nft.removeFromWhiteList(collectionId, address);938 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;939 const result = getGenericResult(events);940941 // What to expect942 // tslint:disable-next-line:no-unused-expression943 expect(result.success).to.be.false;944 });945}946947export const getDetailedCollectionInfo = async (api: ApiPromise, collectionId: number)948 : Promise<ICollectionInterface | null> => {949 return await api.query.nft.collection(collectionId) as unknown as ICollectionInterface;950};951952export const getCreatedCollectionCount = async (api: ApiPromise): Promise<number> => {953 // set global object - collectionsCount954 return (await api.query.nft.createdCollectionCount() as unknown as BN).toNumber();955};956957export async function queryCollectionExpectSuccess(collectionId: number): Promise<ICollectionInterface> {958 return await usingApi(async (api) => {959 return (await api.query.nft.collection(collectionId)) as unknown as ICollectionInterface;960 });961}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 { Enum, Struct } from '@polkadot/types/codec';8import type { AccountId, EventRecord } from '@polkadot/types/interfaces';9import { u128 } from '@polkadot/types/primitive';10import { IKeyringPair } from '@polkadot/types/types';11import { BigNumber } from 'bignumber.js';12import BN from 'bn.js';13import chai from 'chai';14import chaiAsPromised from 'chai-as-promised';15import { alicesPublicKey, nullPublicKey } from '../accounts';16import privateKey from '../substrate/privateKey';17import { default as usingApi, submitTransactionAsync, submitTransactionExpectFailAsync } from '../substrate/substrate-api';18import { ICollectionInterface } from '../types';19import { hexToStr, strToUTF16, utf16ToStr } from './util';2021chai.use(chaiAsPromised);22const expect = chai.expect;2324export const U128_MAX = (1n << 128n) - 1n;2526type GenericResult = {27 success: boolean,28};2930interface CreateCollectionResult {31 success: boolean;32 collectionId: number;33}3435interface CreateItemResult {36 success: boolean;37 collectionId: number;38 itemId: number;39 recipient: string;40}4142interface TransferResult {43 success: boolean;44 collectionId: number;45 itemId: number;46 sender: string;47 recipient: string;48 value: bigint;49}5051interface IReFungibleOwner {52 Fraction: BN;53 Owner: number[];54}5556interface ITokenDataType {57 Owner: number[];58 ConstData: number[];59 VariableData: number[];60}6162interface IFungibleTokenDataType {63 Value: BN;64}6566interface IGetMessage {67 checkMsgNftMethod: string;68 checkMsgTrsMethod: string;69 checkMsgSysMethod: string;70}7172export interface IReFungibleTokenDataType {73 Owner: IReFungibleOwner[];74 ConstData: number[];75 VariableData: number[];76}7778export function nftEventMessage(events: EventRecord[]): IGetMessage {79 let checkMsgNftMethod: string = '';80 let checkMsgTrsMethod: string = '';81 let checkMsgSysMethod: string = '';82 events.forEach(({ event: { method, section } }) => {83 if (section === 'nft') {84 checkMsgNftMethod = method;85 } else if (section === 'treasury') {86 checkMsgTrsMethod = method;87 } else if (section === 'system') {88 checkMsgSysMethod = method;89 } else { return null; }90 });91 const result: IGetMessage = {92 checkMsgNftMethod,93 checkMsgTrsMethod,94 checkMsgSysMethod,95 };96 return result;97}9899export function getGenericResult(events: EventRecord[]): GenericResult {100 const result: GenericResult = {101 success: false,102 };103 events.forEach(({ phase, event: { data, method, section } }) => {104 // console.log(` ${phase}: ${section}.${method}:: ${data}`);105 if (method === 'ExtrinsicSuccess') {106 result.success = true;107 }108 });109 return result;110}111112113114export function getCreateCollectionResult(events: EventRecord[]): CreateCollectionResult {115 let success = false;116 let collectionId: number = 0;117 events.forEach(({ phase, event: { data, method, section } }) => {118 // console.log(` ${phase}: ${section}.${method}:: ${data}`);119 if (method == 'ExtrinsicSuccess') {120 success = true;121 } else if ((section == 'nft') && (method == 'Created')) {122 collectionId = parseInt(data[0].toString());123 }124 });125 const result: CreateCollectionResult = {126 success,127 collectionId,128 };129 return result;130}131132export function getCreateItemResult(events: EventRecord[]): CreateItemResult {133 let success = false;134 let collectionId: number = 0;135 let itemId: number = 0;136 let recipient: string = '';137 events.forEach(({ phase, event: { data, method, section } }) => {138 // console.log(` ${phase}: ${section}.${method}:: ${data}`);139 if (method == 'ExtrinsicSuccess') {140 success = true;141 } else if ((section == 'nft') && (method == 'ItemCreated')) {142 collectionId = parseInt(data[0].toString());143 itemId = parseInt(data[1].toString());144 recipient = data[2].toString();145 }146 });147 const result: CreateItemResult = {148 success,149 collectionId,150 itemId,151 recipient,152 };153 return result;154}155156export function getTransferResult(events: EventRecord[]): TransferResult {157 const result: TransferResult = {158 success: false,159 collectionId: 0,160 itemId: 0,161 sender: '',162 recipient: '',163 value: 0n,164 };165166 events.forEach(({event: {data, method, section}}) => {167 if (method === 'ExtrinsicSuccess') {168 result.success = true;169 } else if (section === 'nft' && method === 'Transfer') {170 result.collectionId = +data[0].toString();171 result.itemId = +data[1].toString();172 result.sender = data[2].toString();173 result.recipient = data[3].toString();174 result.value = BigInt(data[4].toString());175 }176 });177178 return result;179}180181interface Invalid {182 type: 'Invalid';183}184185interface Nft {186 type: 'NFT';187}188189interface Fungible {190 type: 'Fungible';191 decimalPoints: number;192}193194interface ReFungible {195 type: 'ReFungible';196}197198type CollectionMode = Nft | Fungible | ReFungible | Invalid;199200export type CreateCollectionParams = {201 mode: CollectionMode,202 name: string,203 description: string,204 tokenPrefix: string,205};206207const defaultCreateCollectionParams: CreateCollectionParams = {208 description: 'description',209 mode: { type: 'NFT' },210 name: 'name',211 tokenPrefix: 'prefix',212}213214export async function createCollectionExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {215 const {name, description, mode, tokenPrefix } = {...defaultCreateCollectionParams, ...params};216217 let collectionId: number = 0;218 await usingApi(async (api) => {219 // Get number of collections before the transaction220 const AcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString(), 10);221222 // Run the CreateCollection transaction223 const alicePrivateKey = privateKey('//Alice');224225 let modeprm = {};226 if (mode.type === 'NFT') {227 modeprm = {nft: null};228 } else if (mode.type === 'Fungible') {229 modeprm = {fungible: mode.decimalPoints};230 } else if (mode.type === 'ReFungible') {231 modeprm = {refungible: null};232 } else if (mode.type === 'Invalid') {233 modeprm = {invalid: null};234 }235236 const tx = api.tx.nft.createCollection(strToUTF16(name), strToUTF16(description), strToUTF16(tokenPrefix), modeprm);237 const events = await submitTransactionAsync(alicePrivateKey, tx);238 const result = getCreateCollectionResult(events);239240 // Get number of collections after the transaction241 const BcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString(), 10);242243 // Get the collection244 const collection: any = (await api.query.nft.collection(result.collectionId)).toJSON();245246 // What to expect247 // tslint:disable-next-line:no-unused-expression248 expect(result.success).to.be.true;249 expect(result.collectionId).to.be.equal(BcollectionCount);250 // tslint:disable-next-line:no-unused-expression251 expect(collection).to.be.not.null;252 expect(BcollectionCount).to.be.equal(AcollectionCount + 1, 'Error: NFT collection NOT created.');253 expect(collection.Owner).to.be.equal(alicesPublicKey);254 expect(utf16ToStr(collection.Name)).to.be.equal(name);255 expect(utf16ToStr(collection.Description)).to.be.equal(description);256 expect(hexToStr(collection.TokenPrefix)).to.be.equal(tokenPrefix);257258 collectionId = result.collectionId;259 });260261 return collectionId;262}263264export async function createCollectionExpectFailure(params: Partial<CreateCollectionParams> = {}) {265 const {name, description, mode, tokenPrefix } = {...defaultCreateCollectionParams, ...params};266267 let modeprm = {};268 if (mode.type === 'NFT') {269 modeprm = {nft: null};270 } else if (mode.type === 'Fungible') {271 modeprm = {fungible: mode.decimalPoints};272 } else if (mode.type === 'ReFungible') {273 modeprm = {refungible: null};274 } else if (mode.type === 'Invalid') {275 modeprm = {invalid: null};276 }277278 await usingApi(async (api) => {279 // Get number of collections before the transaction280 const AcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString());281282 // Run the CreateCollection transaction283 const alicePrivateKey = privateKey('//Alice');284 const tx = api.tx.nft.createCollection(strToUTF16(name), strToUTF16(description), strToUTF16(tokenPrefix), modeprm);285 const events = await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;286 const result = getCreateCollectionResult(events);287288 // Get number of collections after the transaction289 const BcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString());290291 // What to expect292 // tslint:disable-next-line:no-unused-expression293 expect(result.success).to.be.false;294 expect(BcollectionCount).to.be.equal(AcollectionCount, 'Error: Collection with incorrect data created.');295 });296}297298export async function findUnusedAddress(api: ApiPromise, seedAddition = ''): Promise<IKeyringPair> {299 let bal = new BigNumber(0);300 let unused;301 do {302 const randomSeed = 'seed' + Math.floor(Math.random() * Math.floor(10000)) + seedAddition;303 const keyring = new Keyring({ type: 'sr25519' });304 unused = keyring.addFromUri(`//${randomSeed}`);305 bal = new BigNumber((await api.query.system.account(unused.address)).data.free.toString());306 } while (bal.toFixed() != '0');307 return unused;308}309310export async function getAllowance(collectionId: number, tokenId: number, owner: string, approved: string) {311 return await usingApi(async (api) => {312 const bn = await api.query.nft.allowances(collectionId, [tokenId, owner, approved]) as unknown as BN;313 return BigInt(bn.toString());314 });315}316317export function findUnusedAddresses(api: ApiPromise, amount: number): Promise<IKeyringPair[]> {318 return Promise.all(new Array(amount).fill(null).map(() => findUnusedAddress(api, '_' + Date.now())));319}320321export async function findNotExistingCollection(api: ApiPromise): Promise<number> {322 const totalNumber = parseInt((await api.query.nft.createdCollectionCount()).toString(), 10) as unknown as number;323 const newCollection: number = totalNumber + 1;324 return newCollection;325}326327function getDestroyResult(events: EventRecord[]): boolean {328 let success: boolean = false;329 events.forEach(({ phase, event: { data, method, section } }) => {330 // console.log(` ${phase}: ${section}.${method}:: ${data}`);331 if (method == 'ExtrinsicSuccess') {332 success = true;333 }334 });335 return success;336}337338export async function destroyCollectionExpectFailure(collectionId: number, senderSeed: string = '//Alice') {339 await usingApi(async (api) => {340 // Run the DestroyCollection transaction341 const alicePrivateKey = privateKey(senderSeed);342 const tx = api.tx.nft.destroyCollection(collectionId);343 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;344 });345}346347export async function destroyCollectionExpectSuccess(collectionId: number, senderSeed: string = '//Alice') {348 await usingApi(async (api) => {349 // Run the DestroyCollection transaction350 const alicePrivateKey = privateKey(senderSeed);351 const tx = api.tx.nft.destroyCollection(collectionId);352 const events = await submitTransactionAsync(alicePrivateKey, tx);353 const result = getDestroyResult(events);354355 // Get the collection356 const collection: any = (await api.query.nft.collection(collectionId)).toJSON();357358 // What to expect359 expect(result).to.be.true;360 expect(collection).to.be.not.null;361 expect(collection.Owner).to.be.equal(nullPublicKey);362 });363}364365export async function queryCollectionLimits(collectionId: number) {366 return await usingApi(async (api) => {367 return ((await api.query.nft.collection(collectionId)).toJSON() as any).Limits;368 });369}370371export async function setCollectionLimitsExpectSuccess(sender: IKeyringPair, collectionId: number, limits: any) {372 await usingApi(async (api) => {373 const oldLimits = await queryCollectionLimits(collectionId);374 const newLimits = { ...oldLimits as any, ...limits };375 const tx = api.tx.nft.setCollectionLimits(collectionId, newLimits);376 const events = await submitTransactionAsync(sender, tx);377 const result = getGenericResult(events);378379 expect(result.success).to.be.true;380 });381}382383export async function setCollectionLimitsExpectFailure(sender: IKeyringPair, collectionId: number, limits: any) {384 await usingApi(async (api) => {385 const oldLimits = await queryCollectionLimits(collectionId);386 const newLimits = { ...oldLimits as any, ...limits };387 const tx = api.tx.nft.setCollectionLimits(collectionId, newLimits);388 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;389 const result = getGenericResult(events);390391 expect(result.success).to.be.false;392 });393}394395export async function setCollectionSponsorExpectSuccess(collectionId: number, sponsor: string) {396 await usingApi(async (api) => {397398 // Run the transaction399 const alicePrivateKey = privateKey('//Alice');400 const tx = api.tx.nft.setCollectionSponsor(collectionId, sponsor);401 const events = await submitTransactionAsync(alicePrivateKey, tx);402 const result = getGenericResult(events);403404 // Get the collection405 const collection: any = (await api.query.nft.collection(collectionId)).toJSON();406407 // What to expect408 expect(result.success).to.be.true;409 expect(collection.Sponsor.toString()).to.be.equal(sponsor.toString());410 expect(collection.SponsorConfirmed).to.be.false;411 });412}413414export async function removeCollectionSponsorExpectSuccess(collectionId: number) {415 await usingApi(async (api) => {416417 // Run the transaction418 const alicePrivateKey = privateKey('//Alice');419 const tx = api.tx.nft.removeCollectionSponsor(collectionId);420 const events = await submitTransactionAsync(alicePrivateKey, tx);421 const result = getGenericResult(events);422423 // Get the collection424 const collection: any = (await api.query.nft.collection(collectionId)).toJSON();425426 // What to expect427 expect(result.success).to.be.true;428 expect(collection.Sponsor).to.be.equal(nullPublicKey);429 expect(collection.SponsorConfirmed).to.be.false;430 });431}432433export async function removeCollectionSponsorExpectFailure(collectionId: number) {434 await usingApi(async (api) => {435436 // Run the transaction437 const alicePrivateKey = privateKey('//Alice');438 const tx = api.tx.nft.removeCollectionSponsor(collectionId);439 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;440 });441}442443export async function setCollectionSponsorExpectFailure(collectionId: number, sponsor: string, senderSeed: string = '//Alice') {444 await usingApi(async (api) => {445446 // Run the transaction447 const alicePrivateKey = privateKey(senderSeed);448 const tx = api.tx.nft.setCollectionSponsor(collectionId, sponsor);449 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;450 });451}452453export async function confirmSponsorshipExpectSuccess(collectionId: number, senderSeed: string = '//Alice') {454 await usingApi(async (api) => {455456 // Run the transaction457 const sender = privateKey(senderSeed);458 const tx = api.tx.nft.confirmSponsorship(collectionId);459 const events = await submitTransactionAsync(sender, tx);460 const result = getGenericResult(events);461462 // Get the collection463 const collection: any = (await api.query.nft.collection(collectionId)).toJSON();464465 // What to expect466 expect(result.success).to.be.true;467 expect(collection.Sponsor).to.be.equal(sender.address);468 expect(collection.SponsorConfirmed).to.be.true;469 });470}471472473export async function confirmSponsorshipExpectFailure(collectionId: number, senderSeed: string = '//Alice') {474 await usingApi(async (api) => {475476 // Run the transaction477 const sender = privateKey(senderSeed);478 const tx = api.tx.nft.confirmSponsorship(collectionId);479 await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;480 });481}482483export async function enableContractSponsoringExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {484 await usingApi(async (api) => {485 const tx = api.tx.nft.enableContractSponsoring(contractAddress, enable);486 const events = await submitTransactionAsync(sender, tx);487 const result = getGenericResult(events);488489 expect(result.success).to.be.true;490 });491}492493export async function enableContractSponsoringExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {494 await usingApi(async (api) => {495 const tx = api.tx.nft.enableContractSponsoring(contractAddress, enable);496 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;497 const result = getGenericResult(events);498499 expect(result.success).to.be.false;500 });501}502503export async function setContractSponsoringRateLimitExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {504 await usingApi(async (api) => {505 const tx = api.tx.nft.setContractSponsoringRateLimit(contractAddress, rateLimit);506 const events = await submitTransactionAsync(sender, tx);507 const result = getGenericResult(events);508509 expect(result.success).to.be.true;510 });511}512513export async function setContractSponsoringRateLimitExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {514 await usingApi(async (api) => {515 const tx = api.tx.nft.setContractSponsoringRateLimit(contractAddress, rateLimit);516 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;517 const result = getGenericResult(events);518519 expect(result.success).to.be.false;520 });521}522523export async function toggleContractWhitelistExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, enabled: boolean) {524 await usingApi(async (api) => {525 const tx = api.tx.nft.toggleContractWhiteList(contractAddress, true);526 const events = await submitTransactionAsync(sender, tx);527 const result = getGenericResult(events);528529 expect(result.success).to.be.true;530 });531}532533export async function isWhitelistedInContract(contractAddress: AccountId | string, user: string) {534 let whitelisted: boolean = false;535 await usingApi(async (api) => {536 whitelisted = (await api.query.nft.contractWhiteList(contractAddress, user)).toJSON() as boolean;537 });538 return whitelisted;539}540541export async function addToContractWhiteListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: string) {542 await usingApi(async (api) => {543 const tx = api.tx.nft.addToContractWhiteList(contractAddress, user);544 const events = await submitTransactionAsync(sender, tx);545 const result = getGenericResult(events);546547 expect(result.success).to.be.true;548 });549}550551export async function removeFromContractWhiteListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: string) {552 await usingApi(async (api) => {553 const tx = api.tx.nft.removeFromContractWhiteList(contractAddress, user);554 const events = await submitTransactionAsync(sender, tx);555 const result = getGenericResult(events);556557 expect(result.success).to.be.true;558 });559}560561export async function removeFromContractWhiteListExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, user: string) {562 await usingApi(async (api) => {563 const tx = api.tx.nft.removeFromContractWhiteList(contractAddress, user);564 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;565 const result = getGenericResult(events);566567 expect(result.success).to.be.false;568 });569}570571export async function setVariableMetaDataExpectSuccess(sender: IKeyringPair, collectionId: number, itemId: number, data: number[]) {572 await usingApi(async (api) => {573 const tx = api.tx.nft.setVariableMetaData(collectionId, itemId, '0x' + Buffer.from(data).toString('hex'));574 const events = await submitTransactionAsync(sender, tx);575 const result = getGenericResult(events);576577 expect(result.success).to.be.true;578 });579}580581export async function setVariableMetaDataExpectFailure(sender: IKeyringPair, collectionId: number, itemId: number, data: number[]) {582 await usingApi(async (api) => {583 const tx = api.tx.nft.setVariableMetaData(collectionId, itemId, '0x' + Buffer.from(data).toString('hex'));584 await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;585 });586}587588export async function setOffchainSchemaExpectSuccess(sender: IKeyringPair, collectionId: number, data: number[]) {589 await usingApi(async (api) => {590 const tx = api.tx.nft.setOffchainSchema(collectionId, '0x' + Buffer.from(data).toString('hex'));591 const events = await submitTransactionAsync(sender, tx);592 const result = getGenericResult(events);593594 expect(result.success).to.be.true;595 });596}597598export async function setOffchainSchemaExpectFailure(sender: IKeyringPair, collectionId: number, data: number[]) {599 await usingApi(async (api) => {600 const tx = api.tx.nft.setOffchainSchema(collectionId, '0x' + Buffer.from(data).toString('hex'));601 await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;602 });603}604605export interface CreateFungibleData {606 readonly Value: bigint;607}608609export interface CreateReFungibleData { }610export interface CreateNftData { }611612export type CreateItemData = {613 NFT: CreateNftData;614} | {615 Fungible: CreateFungibleData;616} | {617 ReFungible: CreateReFungibleData;618};619620export async function burnItemExpectSuccess(owner: IKeyringPair, collectionId: number, tokenId: number, value = 0) {621 await usingApi(async (api) => {622 const tx = api.tx.nft.burnItem(collectionId, tokenId, value);623 const events = await submitTransactionAsync(owner, tx);624 const result = getGenericResult(events);625 // Get the item626 const item: any = (await api.query.nft.nftItemList(collectionId, tokenId)).toJSON();627 // What to expect628 // tslint:disable-next-line:no-unused-expression629 expect(result.success).to.be.true;630 // tslint:disable-next-line:no-unused-expression631 expect(item).to.be.not.null;632 expect(item.Owner).to.be.equal(nullPublicKey);633 });634}635636export async function637approveExpectSuccess(collectionId: number,638 tokenId: number, owner: IKeyringPair, approved: IKeyringPair, amount: number | bigint = 1) {639 await usingApi(async (api: ApiPromise) => {640 const allowanceBefore =641 await api.query.nft.allowances(collectionId, [tokenId, owner.address, approved.address]) as unknown as BN;642 const approveNftTx = await api.tx.nft.approve(approved.address, collectionId, tokenId, amount);643 const events = await submitTransactionAsync(owner, approveNftTx);644 const result = getCreateItemResult(events);645 // tslint:disable-next-line:no-unused-expression646 expect(result.success).to.be.true;647 const allowanceAfter =648 await api.query.nft.allowances(collectionId, [tokenId, owner.address, approved.address]) as unknown as BN;649 expect(allowanceAfter.sub(allowanceBefore).toString()).to.be.equal(amount.toString());650 });651}652653export async function654transferFromExpectSuccess(collectionId: number,655 tokenId: number,656 accountApproved: IKeyringPair,657 accountFrom: IKeyringPair,658 accountTo: IKeyringPair,659 value: number | bigint = 1,660 type: string = 'NFT') {661 await usingApi(async (api: ApiPromise) => {662 let balanceBefore = new BN(0);663 if (type === 'Fungible') {664 balanceBefore = await api.query.nft.balance(collectionId, accountTo.address) as unknown as BN;665 }666 const transferFromTx = await api.tx.nft.transferFrom(667 accountFrom.address, accountTo.address, collectionId, tokenId, value);668 const events = await submitTransactionAsync(accountApproved, transferFromTx);669 const result = getCreateItemResult(events);670 // tslint:disable-next-line:no-unused-expression671 expect(result.success).to.be.true;672 if (type === 'NFT') {673 const nftItemData = await api.query.nft.nftItemList(collectionId, tokenId) as unknown as ITokenDataType;674 expect(nftItemData.Owner.toString()).to.be.equal(accountTo.address);675 }676 if (type === 'Fungible') {677 const balanceAfter = await api.query.nft.balance(collectionId, accountTo.address) as unknown as BN;678 expect(balanceAfter.sub(balanceBefore).toString()).to.be.equal(value.toString());679 }680 if (type === 'ReFungible') {681 const nftItemData =682 await api.query.nft.reFungibleItemList(collectionId, tokenId) as unknown as IReFungibleTokenDataType;683 expect(nftItemData.Owner[0].Owner.toString()).to.be.equal(accountTo.address);684 expect(nftItemData.Owner[0].Fraction.toNumber()).to.be.equal(value);685 }686 });687}688689export async function690transferFromExpectFail(collectionId: number,691 tokenId: number,692 accountApproved: IKeyringPair,693 accountFrom: IKeyringPair,694 accountTo: IKeyringPair,695 value: number | bigint = 1) {696 await usingApi(async (api: ApiPromise) => {697 const transferFromTx = await api.tx.nft.transferFrom(698 accountFrom.address, accountTo.address, collectionId, tokenId, value);699 const events = await expect(submitTransactionExpectFailAsync(accountApproved, transferFromTx)).to.be.rejected;700 const result = getCreateCollectionResult(events);701 // tslint:disable-next-line:no-unused-expression702 expect(result.success).to.be.false;703 });704}705706export async function707transferExpectSuccess(collectionId: number,708 tokenId: number,709 sender: IKeyringPair,710 recipient: IKeyringPair,711 value: number | bigint = 1,712 type: string = 'NFT') {713 await usingApi(async (api: ApiPromise) => {714 let balanceBefore = new BN(0);715 if (type === 'Fungible') {716 balanceBefore = await api.query.nft.balance(collectionId, recipient.address) as unknown as BN;717 }718 const transferTx = await api.tx.nft.transfer(recipient.address, collectionId, tokenId, value);719 const events = await submitTransactionAsync(sender, transferTx);720 const result = getTransferResult(events);721 // tslint:disable-next-line:no-unused-expression722 expect(result.success).to.be.true;723 expect(result.collectionId).to.be.equal(collectionId);724 expect(result.itemId).to.be.equal(tokenId);725 expect(result.sender).to.be.equal(sender.address);726 expect(result.recipient).to.be.equal(recipient.address);727 expect(result.value.toString()).to.be.equal(value.toString());728 if (type === 'NFT') {729 const nftItemData = await api.query.nft.nftItemList(collectionId, tokenId) as unknown as ITokenDataType;730 expect(nftItemData.Owner.toString()).to.be.equal(recipient.address);731 }732 if (type === 'Fungible') {733 const balanceAfter = await api.query.nft.balance(collectionId, recipient.address) as unknown as BN;734 expect(balanceAfter.sub(balanceBefore).toString()).to.be.equal(value.toString());735 }736 if (type === 'ReFungible') {737 const nftItemData =738 await api.query.nft.reFungibleItemList(collectionId, tokenId) as unknown as IReFungibleTokenDataType;739 expect(nftItemData.Owner[0].Owner.toString()).to.be.equal(recipient.address);740 expect(nftItemData.Owner[0].Fraction.toNumber()).to.be.equal(value);741 }742 });743}744745export async function746transferExpectFail(collectionId: number,747 tokenId: number,748 sender: IKeyringPair,749 recipient: IKeyringPair,750 value: number | bigint = 1,751 type: string = 'NFT') {752 await usingApi(async (api: ApiPromise) => {753 const transferTx = await api.tx.nft.transfer(recipient.address, collectionId, tokenId, value);754 const events = await expect(submitTransactionExpectFailAsync(sender, transferTx)).to.be.rejected;755 if (events && Array.isArray(events)) {756 const result = getCreateCollectionResult(events);757 // tslint:disable-next-line:no-unused-expression758 expect(result.success).to.be.false;759 }760 });761}762763export async function764approveExpectFail(collectionId: number,765 tokenId: number, owner: IKeyringPair, approved: IKeyringPair, amount: number | bigint = 1) {766 await usingApi(async (api: ApiPromise) => {767 const approveNftTx = await api.tx.nft.approve(approved.address, collectionId, tokenId, amount);768 const events = await expect(submitTransactionExpectFailAsync(owner, approveNftTx)).to.be.rejected;769 const result = getCreateCollectionResult(events);770 // tslint:disable-next-line:no-unused-expression771 expect(result.success).to.be.false;772 });773}774775export async function getFungibleBalance(776 collectionId: number,777 owner: string,778) {779 return await usingApi(async (api) => {780 const response = (await api.query.nft.fungibleItemList(collectionId, owner)).toJSON() as unknown as {Value: string};781 return BigInt(response.Value);782 });783}784785export async function createFungibleItemExpectSuccess(786 sender: IKeyringPair,787 collectionId: number,788 data: CreateFungibleData,789 owner: string = sender.address,790) {791 return await usingApi(async (api) => {792 const tx = api.tx.nft.createItem(collectionId, owner, { Fungible: data });793794 const events = await submitTransactionAsync(sender, tx);795 const result = getCreateItemResult(events);796797 expect(result.success).to.be.true;798 return result.itemId;799 });800}801802export async function createItemExpectSuccess(803 sender: IKeyringPair, collectionId: number, createMode: string, owner: string = '') {804 let newItemId: number = 0;805 await usingApi(async (api) => {806 const AItemCount = parseInt((await api.query.nft.itemListIndex(collectionId)).toString(), 10);807 const Aitem: any = (await api.query.nft.fungibleItemList(collectionId, owner)).toJSON();808 const AItemBalance = new BigNumber(Aitem.Value);809810 if (owner === '') {811 owner = sender.address;812 }813814 let tx;815 if (createMode === 'Fungible') {816 const createData = {fungible: {value: 10}};817 tx = api.tx.nft.createItem(collectionId, owner, createData);818 } else if (createMode === 'ReFungible') {819 const createData = {refungible: {const_data: [], variable_data: [], pieces: 100}};820 tx = api.tx.nft.createItem(collectionId, owner, createData);821 } else {822 tx = api.tx.nft.createItem(collectionId, owner, createMode);823 }824 const events = await submitTransactionAsync(sender, tx);825 const result = getCreateItemResult(events);826827 const BItemCount = parseInt((await api.query.nft.itemListIndex(collectionId)).toString(), 10);828 const Bitem: any = (await api.query.nft.fungibleItemList(collectionId, owner)).toJSON();829 const BItemBalance = new BigNumber(Bitem.Value);830831 // What to expect832 // tslint:disable-next-line:no-unused-expression833 expect(result.success).to.be.true;834 if (createMode === 'Fungible') {835 expect(BItemBalance.minus(AItemBalance).toNumber()).to.be.equal(10);836 } else {837 expect(BItemCount).to.be.equal(AItemCount + 1);838 }839 expect(collectionId).to.be.equal(result.collectionId);840 expect(BItemCount).to.be.equal(result.itemId);841 expect(owner).to.be.equal(result.recipient);842 newItemId = result.itemId;843 });844 return newItemId;845}846847export async function createItemExpectFailure(848 sender: IKeyringPair, collectionId: number, createMode: string, owner: string = sender.address) {849 await usingApi(async (api) => {850 const tx = api.tx.nft.createItem(collectionId, owner, createMode);851 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;852 const result = getCreateItemResult(events);853854 expect(result.success).to.be.false;855 });856}857858export async function setPublicAccessModeExpectSuccess(859 sender: IKeyringPair, collectionId: number,860 accessMode: 'Normal' | 'WhiteList',861) {862 await usingApi(async (api) => {863864 // Run the transaction865 const tx = api.tx.nft.setPublicAccessMode(collectionId, accessMode);866 const events = await submitTransactionAsync(sender, tx);867 const result = getGenericResult(events);868869 // Get the collection870 const collection: any = (await api.query.nft.collection(collectionId)).toJSON();871872 // What to expect873 // tslint:disable-next-line:no-unused-expression874 expect(result.success).to.be.true;875 expect(collection.Access).to.be.equal(accessMode);876 });877}878879export async function enableWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number) {880 await setPublicAccessModeExpectSuccess(sender, collectionId, 'WhiteList');881}882883export async function disableWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number) {884 await setPublicAccessModeExpectSuccess(sender, collectionId, 'Normal');885}886887export async function setMintPermissionExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {888 await usingApi(async (api) => {889890 // Run the transaction891 const tx = api.tx.nft.setMintPermission(collectionId, enabled);892 const events = await submitTransactionAsync(sender, tx);893 const result = getGenericResult(events);894895 // Get the collection896 const collection: any = (await api.query.nft.collection(collectionId)).toJSON();897898 // What to expect899 // tslint:disable-next-line:no-unused-expression900 expect(result.success).to.be.true;901 expect(collection.MintMode).to.be.equal(enabled);902 });903}904905export async function enablePublicMintingExpectSuccess(sender: IKeyringPair, collectionId: number) {906 await setMintPermissionExpectSuccess(sender, collectionId, true);907}908909export async function setMintPermissionExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {910 await usingApi(async (api) => {911 // Run the transaction912 const tx = api.tx.nft.setMintPermission(collectionId, enabled);913 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;914 const result = getCreateCollectionResult(events);915 // tslint:disable-next-line:no-unused-expression916 expect(result.success).to.be.false;917 });918}919920export async function isWhitelisted(collectionId: number, address: string) {921 let whitelisted: boolean = false;922 await usingApi(async (api) => {923 whitelisted = (await api.query.nft.whiteList(collectionId, address)).toJSON() as unknown as boolean;924 });925 return whitelisted;926}927928export async function addToWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number, address: string) {929 await usingApi(async (api) => {930931 const whiteListedBefore = (await api.query.nft.whiteList(collectionId, address)).toJSON();932933 // Run the transaction934 const tx = api.tx.nft.addToWhiteList(collectionId, address);935 const events = await submitTransactionAsync(sender, tx);936 const result = getGenericResult(events);937938 const whiteListedAfter = (await api.query.nft.whiteList(collectionId, address)).toJSON();939940 // What to expect941 // tslint:disable-next-line:no-unused-expression942 expect(result.success).to.be.true;943 // tslint:disable-next-line: no-unused-expression944 expect(whiteListedBefore).to.be.false;945 // tslint:disable-next-line: no-unused-expression946 expect(whiteListedAfter).to.be.true;947 });948}949950export async function removeFromWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number, address: string) {951 await usingApi(async (api) => {952 // Run the transaction953 const tx = api.tx.nft.removeFromWhiteList(collectionId, address);954 const events = await submitTransactionAsync(sender, tx);955 const result = getGenericResult(events);956957 // What to expect958 // tslint:disable-next-line:no-unused-expression959 expect(result.success).to.be.true;960 });961}962963export async function removeFromWhiteListExpectFailure(sender: IKeyringPair, collectionId: number, address: string) {964 await usingApi(async (api) => {965 // Run the transaction966 const tx = api.tx.nft.removeFromWhiteList(collectionId, address);967 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;968 const result = getGenericResult(events);969970 // What to expect971 // tslint:disable-next-line:no-unused-expression972 expect(result.success).to.be.false;973 });974}975976export const getDetailedCollectionInfo = async (api: ApiPromise, collectionId: number)977 : Promise<ICollectionInterface | null> => {978 return await api.query.nft.collection(collectionId) as unknown as ICollectionInterface;979};980981export const getCreatedCollectionCount = async (api: ApiPromise): Promise<number> => {982 // set global object - collectionsCount983 return (await api.query.nft.createdCollectionCount() as unknown as BN).toNumber();984};985986export async function queryCollectionExpectSuccess(collectionId: number): Promise<ICollectionInterface> {987 return await usingApi(async (api) => {988 return (await api.query.nft.collection(collectionId)) as unknown as ICollectionInterface;989 });990}