difftreelog
Merge pull request #127 from usetech-llc/feature/NFTPAR-321,325,326,324,347,345
in: master
Add test events
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 = 'CollectionCreated';
+ 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,44 @@
+//
+// 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 checkSection = 'Transfer';
+ 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(checkSection);
+ 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,43 @@
+//
+// 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 checkSection = 'Transfer';
+ 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(checkSection);
+ 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.collectionById(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.collectionById(collectionId)).toJSON();328329 // What to expect330 expect(result).to.be.true;331 expect(collection).to.be.null;332 });333}334335export async function queryCollectionLimits(collectionId: number) {336 return await usingApi(async (api) => {337 return ((await api.query.nft.collectionById(collectionId)).toJSON() as any).Limits;338 });339}340341export async function setCollectionLimitsExpectSuccess(sender: IKeyringPair, collectionId: number, limits: any) {342 await usingApi(async (api) => {343 const oldLimits = await queryCollectionLimits(collectionId);344 const newLimits = { ...oldLimits as any, ...limits };345 const tx = api.tx.nft.setCollectionLimits(collectionId, newLimits);346 const events = await submitTransactionAsync(sender, tx);347 const result = getGenericResult(events);348349 expect(result.success).to.be.true;350 });351}352353export async function setCollectionLimitsExpectFailure(sender: IKeyringPair, collectionId: number, limits: any) {354 await usingApi(async (api) => {355 const oldLimits = await queryCollectionLimits(collectionId);356 const newLimits = { ...oldLimits as any, ...limits };357 const tx = api.tx.nft.setCollectionLimits(collectionId, newLimits);358 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;359 const result = getGenericResult(events);360361 expect(result.success).to.be.false;362 });363}364365export async function setCollectionSponsorExpectSuccess(collectionId: number, sponsor: string) {366 await usingApi(async (api) => {367368 // Run the transaction369 const alicePrivateKey = privateKey('//Alice');370 const tx = api.tx.nft.setCollectionSponsor(collectionId, sponsor);371 const events = await submitTransactionAsync(alicePrivateKey, tx);372 const result = getGenericResult(events);373374 // Get the collection375 const collection: any = (await api.query.nft.collectionById(collectionId)).toJSON();376377 // What to expect378 expect(result.success).to.be.true;379 expect(collection.Sponsorship).to.deep.equal({380 Unconfirmed: sponsor.toString(),381 });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.collectionById(collectionId)).toJSON();396397 // What to expect398 expect(result.success).to.be.true;399 expect(collection.Sponsorship).to.be.deep.equal({ Disabled: null });400 });401}402403export async function removeCollectionSponsorExpectFailure(collectionId: number) {404 await usingApi(async (api) => {405406 // Run the transaction407 const alicePrivateKey = privateKey('//Alice');408 const tx = api.tx.nft.removeCollectionSponsor(collectionId);409 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;410 });411}412413export async function setCollectionSponsorExpectFailure(collectionId: number, sponsor: string, senderSeed: string = '//Alice') {414 await usingApi(async (api) => {415416 // Run the transaction417 const alicePrivateKey = privateKey(senderSeed);418 const tx = api.tx.nft.setCollectionSponsor(collectionId, sponsor);419 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;420 });421}422423export async function confirmSponsorshipExpectSuccess(collectionId: number, senderSeed: string = '//Alice') {424 await usingApi(async (api) => {425426 // Run the transaction427 const sender = privateKey(senderSeed);428 const tx = api.tx.nft.confirmSponsorship(collectionId);429 const events = await submitTransactionAsync(sender, tx);430 const result = getGenericResult(events);431432 // Get the collection433 const collection: any = (await api.query.nft.collectionById(collectionId)).toJSON();434435 // What to expect436 expect(result.success).to.be.true;437 expect(collection.Sponsorship).to.be.deep.equal({438 Confirmed: sender.address,439 });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.null;603 });604}605606export async function607approveExpectSuccess(collectionId: number,608 tokenId: number, owner: IKeyringPair, approved: IKeyringPair, amount: number | bigint = 1) {609 await usingApi(async (api: ApiPromise) => {610 const allowanceBefore =611 await api.query.nft.allowances(collectionId, [tokenId, owner.address, approved.address]) as unknown as BN;612 const approveNftTx = await api.tx.nft.approve(approved.address, collectionId, tokenId, amount);613 const events = await submitTransactionAsync(owner, approveNftTx);614 const result = getCreateItemResult(events);615 // tslint:disable-next-line:no-unused-expression616 expect(result.success).to.be.true;617 const allowanceAfter =618 await api.query.nft.allowances(collectionId, [tokenId, owner.address, approved.address]) as unknown as BN;619 expect(allowanceAfter.sub(allowanceBefore).toString()).to.be.equal(amount.toString());620 });621}622623export async function624transferFromExpectSuccess(collectionId: number,625 tokenId: number,626 accountApproved: IKeyringPair,627 accountFrom: IKeyringPair,628 accountTo: IKeyringPair,629 value: number | bigint = 1,630 type: string = 'NFT') {631 await usingApi(async (api: ApiPromise) => {632 let balanceBefore = new BN(0);633 if (type === 'Fungible') {634 balanceBefore = await api.query.nft.balance(collectionId, accountTo.address) as unknown as BN;635 }636 const transferFromTx = await api.tx.nft.transferFrom(637 accountFrom.address, accountTo.address, collectionId, tokenId, value);638 const events = await submitTransactionAsync(accountApproved, transferFromTx);639 const result = getCreateItemResult(events);640 // tslint:disable-next-line:no-unused-expression641 expect(result.success).to.be.true;642 if (type === 'NFT') {643 const nftItemData = (await api.query.nft.nftItemList(collectionId, tokenId) as any).unwrap() as ITokenDataType;644 expect(nftItemData.Owner.toString()).to.be.equal(accountTo.address);645 }646 if (type === 'Fungible') {647 const balanceAfter = (await api.query.nft.fungibleItemList(collectionId, accountTo.address) as any).Value as unknown as BN;648 expect(balanceAfter.sub(balanceBefore).toString()).to.be.equal(value.toString());649 }650 if (type === 'ReFungible') {651 const nftItemData =652 (await api.query.nft.reFungibleItemList(collectionId, tokenId) as any).unwrap() as IReFungibleTokenDataType;653 expect(nftItemData.Owner[0].Owner.toString()).to.be.equal(accountTo.address);654 expect(nftItemData.Owner[0].Fraction.toNumber()).to.be.equal(value);655 }656 });657}658659export async function660transferFromExpectFail(collectionId: number,661 tokenId: number,662 accountApproved: IKeyringPair,663 accountFrom: IKeyringPair,664 accountTo: IKeyringPair,665 value: number | bigint = 1) {666 await usingApi(async (api: ApiPromise) => {667 const transferFromTx = await api.tx.nft.transferFrom(668 accountFrom.address, accountTo.address, collectionId, tokenId, value);669 const events = await expect(submitTransactionExpectFailAsync(accountApproved, transferFromTx)).to.be.rejected;670 const result = getCreateCollectionResult(events);671 // tslint:disable-next-line:no-unused-expression672 expect(result.success).to.be.false;673 });674}675676export async function677transferExpectSuccess(collectionId: number,678 tokenId: number,679 sender: IKeyringPair,680 recipient: IKeyringPair,681 value: number | bigint = 1,682 type: string = 'NFT') {683 await usingApi(async (api: ApiPromise) => {684 let balanceBefore = new BN(0);685 if (type === 'Fungible') {686 balanceBefore = await api.query.nft.balance(collectionId, recipient.address) as unknown as BN;687 }688 const transferTx = await api.tx.nft.transfer(recipient.address, collectionId, tokenId, value);689 const events = await submitTransactionAsync(sender, transferTx);690 const result = getTransferResult(events);691 // tslint:disable-next-line:no-unused-expression692 expect(result.success).to.be.true;693 expect(result.collectionId).to.be.equal(collectionId);694 expect(result.itemId).to.be.equal(tokenId);695 expect(result.sender).to.be.equal(sender.address);696 expect(result.recipient).to.be.equal(recipient.address);697 expect(result.value.toString()).to.be.equal(value.toString());698 if (type === 'NFT') {699 const nftItemData = (await api.query.nft.nftItemList(collectionId, tokenId)).toJSON() as unknown as ITokenDataType;700 expect(nftItemData.Owner.toString()).to.be.equal(recipient.address);701 }702 if (type === 'Fungible') {703 const balanceAfter = (await api.query.nft.fungibleItemList(collectionId, recipient.address) as any).Value as unknown as BN;704 expect(balanceAfter.sub(balanceBefore).toString()).to.be.equal(value.toString());705 }706 if (type === 'ReFungible') {707 const nftItemData =708 (await api.query.nft.reFungibleItemList(collectionId, tokenId)).toJSON() as unknown as IReFungibleTokenDataType;709 expect(nftItemData.Owner[0].Owner.toString()).to.be.equal(recipient.address);710 expect(nftItemData.Owner[0].Fraction.toString()).to.be.equal(value.toString());711 }712 });713}714715export async function716transferExpectFail(collectionId: number,717 tokenId: number,718 sender: IKeyringPair,719 recipient: IKeyringPair,720 value: number | bigint = 1,721 type: string = 'NFT') {722 await usingApi(async (api: ApiPromise) => {723 const transferTx = await api.tx.nft.transfer(recipient.address, collectionId, tokenId, value);724 const events = await expect(submitTransactionExpectFailAsync(sender, transferTx)).to.be.rejected;725 if (events && Array.isArray(events)) {726 const result = getCreateCollectionResult(events);727 // tslint:disable-next-line:no-unused-expression728 expect(result.success).to.be.false;729 }730 });731}732733export async function734approveExpectFail(collectionId: number,735 tokenId: number, owner: IKeyringPair, approved: IKeyringPair, amount: number | bigint = 1) {736 await usingApi(async (api: ApiPromise) => {737 const approveNftTx = await api.tx.nft.approve(approved.address, collectionId, tokenId, amount);738 const events = await expect(submitTransactionExpectFailAsync(owner, approveNftTx)).to.be.rejected;739 const result = getCreateCollectionResult(events);740 // tslint:disable-next-line:no-unused-expression741 expect(result.success).to.be.false;742 });743}744745export async function getFungibleBalance(746 collectionId: number,747 owner: string,748) {749 return await usingApi(async (api) => {750 const response = (await api.query.nft.fungibleItemList(collectionId, owner)).toJSON() as unknown as {Value: string};751 return BigInt(response.Value);752 });753}754755export async function createFungibleItemExpectSuccess(756 sender: IKeyringPair,757 collectionId: number,758 data: CreateFungibleData,759 owner: string = sender.address,760) {761 return await usingApi(async (api) => {762 const tx = api.tx.nft.createItem(collectionId, owner, { Fungible: data });763764 const events = await submitTransactionAsync(sender, tx);765 const result = getCreateItemResult(events);766767 expect(result.success).to.be.true;768 return result.itemId;769 });770}771772export async function createItemExpectSuccess(773 sender: IKeyringPair, collectionId: number, createMode: string, owner: string = '') {774 let newItemId: number = 0;775 await usingApi(async (api) => {776 const AItemCount = parseInt((await api.query.nft.itemListIndex(collectionId)).toString(), 10);777 const Aitem: any = (await api.query.nft.fungibleItemList(collectionId, owner)).toJSON();778 const AItemBalance = new BigNumber(Aitem.Value);779780 if (owner === '') {781 owner = sender.address;782 }783784 let tx;785 if (createMode === 'Fungible') {786 const createData = {fungible: {value: 10}};787 tx = api.tx.nft.createItem(collectionId, owner, createData);788 } else if (createMode === 'ReFungible') {789 const createData = {refungible: {const_data: [], variable_data: [], pieces: 100}};790 tx = api.tx.nft.createItem(collectionId, owner, createData);791 } else {792 tx = api.tx.nft.createItem(collectionId, owner, createMode);793 }794 const events = await submitTransactionAsync(sender, tx);795 const result = getCreateItemResult(events);796797 const BItemCount = parseInt((await api.query.nft.itemListIndex(collectionId)).toString(), 10);798 const Bitem: any = (await api.query.nft.fungibleItemList(collectionId, owner)).toJSON();799 const BItemBalance = new BigNumber(Bitem.Value);800801 // What to expect802 // tslint:disable-next-line:no-unused-expression803 expect(result.success).to.be.true;804 if (createMode === 'Fungible') {805 expect(BItemBalance.minus(AItemBalance).toNumber()).to.be.equal(10);806 } else {807 expect(BItemCount).to.be.equal(AItemCount + 1);808 }809 expect(collectionId).to.be.equal(result.collectionId);810 expect(BItemCount).to.be.equal(result.itemId);811 expect(owner).to.be.equal(result.recipient);812 newItemId = result.itemId;813 });814 return newItemId;815}816817export async function createItemExpectFailure(818 sender: IKeyringPair, collectionId: number, createMode: string, owner: string = sender.address) {819 await usingApi(async (api) => {820 const tx = api.tx.nft.createItem(collectionId, owner, createMode);821 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;822 const result = getCreateItemResult(events);823824 expect(result.success).to.be.false;825 });826}827828export async function setPublicAccessModeExpectSuccess(829 sender: IKeyringPair, collectionId: number,830 accessMode: 'Normal' | 'WhiteList',831) {832 await usingApi(async (api) => {833834 // Run the transaction835 const tx = api.tx.nft.setPublicAccessMode(collectionId, accessMode);836 const events = await submitTransactionAsync(sender, tx);837 const result = getGenericResult(events);838839 // Get the collection840 const collection: any = (await api.query.nft.collectionById(collectionId)).toJSON();841842 // What to expect843 // tslint:disable-next-line:no-unused-expression844 expect(result.success).to.be.true;845 expect(collection.Access).to.be.equal(accessMode);846 });847}848849export async function enableWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number) {850 await setPublicAccessModeExpectSuccess(sender, collectionId, 'WhiteList');851}852853export async function disableWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number) {854 await setPublicAccessModeExpectSuccess(sender, collectionId, 'Normal');855}856857export async function setMintPermissionExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {858 await usingApi(async (api) => {859860 // Run the transaction861 const tx = api.tx.nft.setMintPermission(collectionId, enabled);862 const events = await submitTransactionAsync(sender, tx);863 const result = getGenericResult(events);864865 // Get the collection866 const collection: any = (await api.query.nft.collectionById(collectionId)).toJSON();867868 // What to expect869 // tslint:disable-next-line:no-unused-expression870 expect(result.success).to.be.true;871 expect(collection.MintMode).to.be.equal(enabled);872 });873}874875export async function enablePublicMintingExpectSuccess(sender: IKeyringPair, collectionId: number) {876 await setMintPermissionExpectSuccess(sender, collectionId, true);877}878879export async function setMintPermissionExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {880 await usingApi(async (api) => {881 // Run the transaction882 const tx = api.tx.nft.setMintPermission(collectionId, enabled);883 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;884 const result = getCreateCollectionResult(events);885 // tslint:disable-next-line:no-unused-expression886 expect(result.success).to.be.false;887 });888}889890export async function isWhitelisted(collectionId: number, address: string) {891 let whitelisted: boolean = false;892 await usingApi(async (api) => {893 whitelisted = (await api.query.nft.whiteList(collectionId, address)).toJSON() as unknown as boolean;894 });895 return whitelisted;896}897898export async function addToWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number, address: string) {899 await usingApi(async (api) => {900901 const whiteListedBefore = (await api.query.nft.whiteList(collectionId, address)).toJSON();902903 // Run the transaction904 const tx = api.tx.nft.addToWhiteList(collectionId, address);905 const events = await submitTransactionAsync(sender, tx);906 const result = getGenericResult(events);907908 const whiteListedAfter = (await api.query.nft.whiteList(collectionId, address)).toJSON();909910 // What to expect911 // tslint:disable-next-line:no-unused-expression912 expect(result.success).to.be.true;913 // tslint:disable-next-line: no-unused-expression914 expect(whiteListedBefore).to.be.false;915 // tslint:disable-next-line: no-unused-expression916 expect(whiteListedAfter).to.be.true;917 });918}919920export async function removeFromWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number, address: string) {921 await usingApi(async (api) => {922 // Run the transaction923 const tx = api.tx.nft.removeFromWhiteList(collectionId, address);924 const events = await submitTransactionAsync(sender, tx);925 const result = getGenericResult(events);926927 // What to expect928 // tslint:disable-next-line:no-unused-expression929 expect(result.success).to.be.true;930 });931}932933export async function removeFromWhiteListExpectFailure(sender: IKeyringPair, collectionId: number, address: string) {934 await usingApi(async (api) => {935 // Run the transaction936 const tx = api.tx.nft.removeFromWhiteList(collectionId, address);937 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;938 const result = getGenericResult(events);939940 // What to expect941 // tslint:disable-next-line:no-unused-expression942 expect(result.success).to.be.false;943 });944}945946export const getDetailedCollectionInfo = async (api: ApiPromise, collectionId: number)947 : Promise<ICollectionInterface | null> => {948 return (await api.query.nft.collectionById(collectionId)).toJSON() as unknown as ICollectionInterface;949};950951export const getCreatedCollectionCount = async (api: ApiPromise): Promise<number> => {952 // set global object - collectionsCount953 return (await api.query.nft.createdCollectionCount() as unknown as BN).toNumber();954};955956export async function queryCollectionExpectSuccess(collectionId: number): Promise<ICollectionInterface> {957 return await usingApi(async (api) => {958 return (await api.query.nft.collectionById(collectionId)).toJSON() as unknown as ICollectionInterface;959 });960}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.collectionById(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.collectionById(collectionId)).toJSON();357358 // What to expect359 expect(result).to.be.true;360 expect(collection).to.be.null;361 });362}363364export async function queryCollectionLimits(collectionId: number) {365 return await usingApi(async (api) => {366 return ((await api.query.nft.collectionById(collectionId)).toJSON() as any).Limits;367 });368}369370export async function setCollectionLimitsExpectSuccess(sender: IKeyringPair, collectionId: number, limits: any) {371 await usingApi(async (api) => {372 const oldLimits = await queryCollectionLimits(collectionId);373 const newLimits = { ...oldLimits as any, ...limits };374 const tx = api.tx.nft.setCollectionLimits(collectionId, newLimits);375 const events = await submitTransactionAsync(sender, tx);376 const result = getGenericResult(events);377378 expect(result.success).to.be.true;379 });380}381382export async function setCollectionLimitsExpectFailure(sender: IKeyringPair, collectionId: number, limits: any) {383 await usingApi(async (api) => {384 const oldLimits = await queryCollectionLimits(collectionId);385 const newLimits = { ...oldLimits as any, ...limits };386 const tx = api.tx.nft.setCollectionLimits(collectionId, newLimits);387 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;388 const result = getGenericResult(events);389390 expect(result.success).to.be.false;391 });392}393394export async function setCollectionSponsorExpectSuccess(collectionId: number, sponsor: string) {395 await usingApi(async (api) => {396397 // Run the transaction398 const alicePrivateKey = privateKey('//Alice');399 const tx = api.tx.nft.setCollectionSponsor(collectionId, sponsor);400 const events = await submitTransactionAsync(alicePrivateKey, tx);401 const result = getGenericResult(events);402403 // Get the collection404 const collection: any = (await api.query.nft.collectionById(collectionId)).toJSON();405406 // What to expect407 expect(result.success).to.be.true;408 expect(collection.Sponsorship).to.deep.equal({409 Unconfirmed: sponsor.toString(),410 });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.collectionById(collectionId)).toJSON();425426 // What to expect427 expect(result.success).to.be.true;428 expect(collection.Sponsorship).to.be.deep.equal({ Disabled: null });429 });430}431432export async function removeCollectionSponsorExpectFailure(collectionId: number) {433 await usingApi(async (api) => {434435 // Run the transaction436 const alicePrivateKey = privateKey('//Alice');437 const tx = api.tx.nft.removeCollectionSponsor(collectionId);438 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;439 });440}441442export async function setCollectionSponsorExpectFailure(collectionId: number, sponsor: string, senderSeed: string = '//Alice') {443 await usingApi(async (api) => {444445 // Run the transaction446 const alicePrivateKey = privateKey(senderSeed);447 const tx = api.tx.nft.setCollectionSponsor(collectionId, sponsor);448 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;449 });450}451452export async function confirmSponsorshipExpectSuccess(collectionId: number, senderSeed: string = '//Alice') {453 await usingApi(async (api) => {454455 // Run the transaction456 const sender = privateKey(senderSeed);457 const tx = api.tx.nft.confirmSponsorship(collectionId);458 const events = await submitTransactionAsync(sender, tx);459 const result = getGenericResult(events);460461 // Get the collection462 const collection: any = (await api.query.nft.collectionById(collectionId)).toJSON();463464 // What to expect465 expect(result.success).to.be.true;466 expect(collection.Sponsorship).to.be.deep.equal({467 Confirmed: sender.address,468 });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.null;632 });633}634635export async function636approveExpectSuccess(collectionId: number,637 tokenId: number, owner: IKeyringPair, approved: IKeyringPair, amount: number | bigint = 1) {638 await usingApi(async (api: ApiPromise) => {639 const allowanceBefore =640 await api.query.nft.allowances(collectionId, [tokenId, owner.address, approved.address]) as unknown as BN;641 const approveNftTx = await api.tx.nft.approve(approved.address, collectionId, tokenId, amount);642 const events = await submitTransactionAsync(owner, approveNftTx);643 const result = getCreateItemResult(events);644 // tslint:disable-next-line:no-unused-expression645 expect(result.success).to.be.true;646 const allowanceAfter =647 await api.query.nft.allowances(collectionId, [tokenId, owner.address, approved.address]) as unknown as BN;648 expect(allowanceAfter.sub(allowanceBefore).toString()).to.be.equal(amount.toString());649 });650}651652export async function653transferFromExpectSuccess(collectionId: number,654 tokenId: number,655 accountApproved: IKeyringPair,656 accountFrom: IKeyringPair,657 accountTo: IKeyringPair,658 value: number | bigint = 1,659 type: string = 'NFT') {660 await usingApi(async (api: ApiPromise) => {661 let balanceBefore = new BN(0);662 if (type === 'Fungible') {663 balanceBefore = await api.query.nft.balance(collectionId, accountTo.address) as unknown as BN;664 }665 const transferFromTx = await api.tx.nft.transferFrom(666 accountFrom.address, accountTo.address, collectionId, tokenId, value);667 const events = await submitTransactionAsync(accountApproved, transferFromTx);668 const result = getCreateItemResult(events);669 // tslint:disable-next-line:no-unused-expression670 expect(result.success).to.be.true;671 if (type === 'NFT') {672 const nftItemData = (await api.query.nft.nftItemList(collectionId, tokenId) as any).unwrap() as ITokenDataType;673 expect(nftItemData.Owner.toString()).to.be.equal(accountTo.address);674 }675 if (type === 'Fungible') {676 const balanceAfter = (await api.query.nft.fungibleItemList(collectionId, accountTo.address) as any).Value as unknown as BN;677 expect(balanceAfter.sub(balanceBefore).toString()).to.be.equal(value.toString());678 }679 if (type === 'ReFungible') {680 const nftItemData =681 (await api.query.nft.reFungibleItemList(collectionId, tokenId) as any).unwrap() as IReFungibleTokenDataType;682 expect(nftItemData.Owner[0].Owner.toString()).to.be.equal(accountTo.address);683 expect(nftItemData.Owner[0].Fraction.toNumber()).to.be.equal(value);684 }685 });686}687688export async function689transferFromExpectFail(collectionId: number,690 tokenId: number,691 accountApproved: IKeyringPair,692 accountFrom: IKeyringPair,693 accountTo: IKeyringPair,694 value: number | bigint = 1) {695 await usingApi(async (api: ApiPromise) => {696 const transferFromTx = await api.tx.nft.transferFrom(697 accountFrom.address, accountTo.address, collectionId, tokenId, value);698 const events = await expect(submitTransactionExpectFailAsync(accountApproved, transferFromTx)).to.be.rejected;699 const result = getCreateCollectionResult(events);700 // tslint:disable-next-line:no-unused-expression701 expect(result.success).to.be.false;702 });703}704705export async function706transferExpectSuccess(collectionId: number,707 tokenId: number,708 sender: IKeyringPair,709 recipient: IKeyringPair,710 value: number | bigint = 1,711 type: string = 'NFT') {712 await usingApi(async (api: ApiPromise) => {713 let balanceBefore = new BN(0);714 if (type === 'Fungible') {715 balanceBefore = await api.query.nft.balance(collectionId, recipient.address) as unknown as BN;716 }717 const transferTx = await api.tx.nft.transfer(recipient.address, collectionId, tokenId, value);718 const events = await submitTransactionAsync(sender, transferTx);719 const result = getTransferResult(events);720 // tslint:disable-next-line:no-unused-expression721 expect(result.success).to.be.true;722 expect(result.collectionId).to.be.equal(collectionId);723 expect(result.itemId).to.be.equal(tokenId);724 expect(result.sender).to.be.equal(sender.address);725 expect(result.recipient).to.be.equal(recipient.address);726 expect(result.value.toString()).to.be.equal(value.toString());727 if (type === 'NFT') {728 const nftItemData = (await api.query.nft.nftItemList(collectionId, tokenId)).toJSON() as unknown as ITokenDataType;729 expect(nftItemData.Owner.toString()).to.be.equal(recipient.address);730 }731 if (type === 'Fungible') {732 const balanceAfter = (await api.query.nft.fungibleItemList(collectionId, recipient.address) as any).Value as unknown as BN;733 expect(balanceAfter.sub(balanceBefore).toString()).to.be.equal(value.toString());734 }735 if (type === 'ReFungible') {736 const nftItemData =737 (await api.query.nft.reFungibleItemList(collectionId, tokenId)).toJSON() as unknown as IReFungibleTokenDataType;738 expect(nftItemData.Owner[0].Owner.toString()).to.be.equal(recipient.address);739 expect(nftItemData.Owner[0].Fraction.toString()).to.be.equal(value.toString());740 }741 });742}743744export async function745transferExpectFail(collectionId: number,746 tokenId: number,747 sender: IKeyringPair,748 recipient: IKeyringPair,749 value: number | bigint = 1,750 type: string = 'NFT') {751 await usingApi(async (api: ApiPromise) => {752 const transferTx = await api.tx.nft.transfer(recipient.address, collectionId, tokenId, value);753 const events = await expect(submitTransactionExpectFailAsync(sender, transferTx)).to.be.rejected;754 if (events && Array.isArray(events)) {755 const result = getCreateCollectionResult(events);756 // tslint:disable-next-line:no-unused-expression757 expect(result.success).to.be.false;758 }759 });760}761762export async function763approveExpectFail(collectionId: number,764 tokenId: number, owner: IKeyringPair, approved: IKeyringPair, amount: number | bigint = 1) {765 await usingApi(async (api: ApiPromise) => {766 const approveNftTx = await api.tx.nft.approve(approved.address, collectionId, tokenId, amount);767 const events = await expect(submitTransactionExpectFailAsync(owner, approveNftTx)).to.be.rejected;768 const result = getCreateCollectionResult(events);769 // tslint:disable-next-line:no-unused-expression770 expect(result.success).to.be.false;771 });772}773774export async function getFungibleBalance(775 collectionId: number,776 owner: string,777) {778 return await usingApi(async (api) => {779 const response = (await api.query.nft.fungibleItemList(collectionId, owner)).toJSON() as unknown as {Value: string};780 return BigInt(response.Value);781 });782}783784export async function createFungibleItemExpectSuccess(785 sender: IKeyringPair,786 collectionId: number,787 data: CreateFungibleData,788 owner: string = sender.address,789) {790 return await usingApi(async (api) => {791 const tx = api.tx.nft.createItem(collectionId, owner, { Fungible: data });792793 const events = await submitTransactionAsync(sender, tx);794 const result = getCreateItemResult(events);795796 expect(result.success).to.be.true;797 return result.itemId;798 });799}800801export async function createItemExpectSuccess(802 sender: IKeyringPair, collectionId: number, createMode: string, owner: string = '') {803 let newItemId: number = 0;804 await usingApi(async (api) => {805 const AItemCount = parseInt((await api.query.nft.itemListIndex(collectionId)).toString(), 10);806 const Aitem: any = (await api.query.nft.fungibleItemList(collectionId, owner)).toJSON();807 const AItemBalance = new BigNumber(Aitem.Value);808809 if (owner === '') {810 owner = sender.address;811 }812813 let tx;814 if (createMode === 'Fungible') {815 const createData = {fungible: {value: 10}};816 tx = api.tx.nft.createItem(collectionId, owner, createData);817 } else if (createMode === 'ReFungible') {818 const createData = {refungible: {const_data: [], variable_data: [], pieces: 100}};819 tx = api.tx.nft.createItem(collectionId, owner, createData);820 } else {821 tx = api.tx.nft.createItem(collectionId, owner, createMode);822 }823 const events = await submitTransactionAsync(sender, tx);824 const result = getCreateItemResult(events);825826 const BItemCount = parseInt((await api.query.nft.itemListIndex(collectionId)).toString(), 10);827 const Bitem: any = (await api.query.nft.fungibleItemList(collectionId, owner)).toJSON();828 const BItemBalance = new BigNumber(Bitem.Value);829830 // What to expect831 // tslint:disable-next-line:no-unused-expression832 expect(result.success).to.be.true;833 if (createMode === 'Fungible') {834 expect(BItemBalance.minus(AItemBalance).toNumber()).to.be.equal(10);835 } else {836 expect(BItemCount).to.be.equal(AItemCount + 1);837 }838 expect(collectionId).to.be.equal(result.collectionId);839 expect(BItemCount).to.be.equal(result.itemId);840 expect(owner).to.be.equal(result.recipient);841 newItemId = result.itemId;842 });843 return newItemId;844}845846export async function createItemExpectFailure(847 sender: IKeyringPair, collectionId: number, createMode: string, owner: string = sender.address) {848 await usingApi(async (api) => {849 const tx = api.tx.nft.createItem(collectionId, owner, createMode);850 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;851 const result = getCreateItemResult(events);852853 expect(result.success).to.be.false;854 });855}856857export async function setPublicAccessModeExpectSuccess(858 sender: IKeyringPair, collectionId: number,859 accessMode: 'Normal' | 'WhiteList',860) {861 await usingApi(async (api) => {862863 // Run the transaction864 const tx = api.tx.nft.setPublicAccessMode(collectionId, accessMode);865 const events = await submitTransactionAsync(sender, tx);866 const result = getGenericResult(events);867868 // Get the collection869 const collection: any = (await api.query.nft.collectionById(collectionId)).toJSON();870871 // What to expect872 // tslint:disable-next-line:no-unused-expression873 expect(result.success).to.be.true;874 expect(collection.Access).to.be.equal(accessMode);875 });876}877878export async function enableWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number) {879 await setPublicAccessModeExpectSuccess(sender, collectionId, 'WhiteList');880}881882export async function disableWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number) {883 await setPublicAccessModeExpectSuccess(sender, collectionId, 'Normal');884}885886export async function setMintPermissionExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {887 await usingApi(async (api) => {888889 // Run the transaction890 const tx = api.tx.nft.setMintPermission(collectionId, enabled);891 const events = await submitTransactionAsync(sender, tx);892 const result = getGenericResult(events);893894 // Get the collection895 const collection: any = (await api.query.nft.collectionById(collectionId)).toJSON();896897 // What to expect898 // tslint:disable-next-line:no-unused-expression899 expect(result.success).to.be.true;900 expect(collection.MintMode).to.be.equal(enabled);901 });902}903904export async function enablePublicMintingExpectSuccess(sender: IKeyringPair, collectionId: number) {905 await setMintPermissionExpectSuccess(sender, collectionId, true);906}907908export async function setMintPermissionExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {909 await usingApi(async (api) => {910 // Run the transaction911 const tx = api.tx.nft.setMintPermission(collectionId, enabled);912 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;913 const result = getCreateCollectionResult(events);914 // tslint:disable-next-line:no-unused-expression915 expect(result.success).to.be.false;916 });917}918919export async function isWhitelisted(collectionId: number, address: string) {920 let whitelisted: boolean = false;921 await usingApi(async (api) => {922 whitelisted = (await api.query.nft.whiteList(collectionId, address)).toJSON() as unknown as boolean;923 });924 return whitelisted;925}926927export async function addToWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number, address: string) {928 await usingApi(async (api) => {929930 const whiteListedBefore = (await api.query.nft.whiteList(collectionId, address)).toJSON();931932 // Run the transaction933 const tx = api.tx.nft.addToWhiteList(collectionId, address);934 const events = await submitTransactionAsync(sender, tx);935 const result = getGenericResult(events);936937 const whiteListedAfter = (await api.query.nft.whiteList(collectionId, address)).toJSON();938939 // What to expect940 // tslint:disable-next-line:no-unused-expression941 expect(result.success).to.be.true;942 // tslint:disable-next-line: no-unused-expression943 expect(whiteListedBefore).to.be.false;944 // tslint:disable-next-line: no-unused-expression945 expect(whiteListedAfter).to.be.true;946 });947}948949export async function removeFromWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number, address: string) {950 await usingApi(async (api) => {951 // Run the transaction952 const tx = api.tx.nft.removeFromWhiteList(collectionId, address);953 const events = await submitTransactionAsync(sender, tx);954 const result = getGenericResult(events);955956 // What to expect957 // tslint:disable-next-line:no-unused-expression958 expect(result.success).to.be.true;959 });960}961962export async function removeFromWhiteListExpectFailure(sender: IKeyringPair, collectionId: number, address: string) {963 await usingApi(async (api) => {964 // Run the transaction965 const tx = api.tx.nft.removeFromWhiteList(collectionId, address);966 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;967 const result = getGenericResult(events);968969 // What to expect970 // tslint:disable-next-line:no-unused-expression971 expect(result.success).to.be.false;972 });973}974975export const getDetailedCollectionInfo = async (api: ApiPromise, collectionId: number)976 : Promise<ICollectionInterface | null> => {977 return (await api.query.nft.collectionById(collectionId)).toJSON() as unknown as ICollectionInterface;978};979980export const getCreatedCollectionCount = async (api: ApiPromise): Promise<number> => {981 // set global object - collectionsCount982 return (await api.query.nft.createdCollectionCount() as unknown as BN).toNumber();983};984985export async function queryCollectionExpectSuccess(collectionId: number): Promise<ICollectionInterface> {986 return await usingApi(async (api) => {987 return (await api.query.nft.collectionById(collectionId)).toJSON() as unknown as ICollectionInterface;988 });989}