difftreelog
Merge branch 'develop' into feature/NFTPAR-281_overflow_tests
in: master
3 files changed
tests/package.jsondiffbeforeafterboth--- a/tests/package.json
+++ b/tests/package.json
@@ -20,6 +20,7 @@
"scripts": {
"test": "mocha --timeout 9999999 -r ts-node/register ./**/*.test.ts",
"load": "mocha --timeout 9999999 -r ts-node/register ./**/*.load.ts",
+ "loadTransfer": "ts-node src/transfer.nload.ts",
"testAddCollectionAdmin": "mocha --timeout 9999999 -r ts-node/register ./**/addCollectionAdmin.test.ts",
"testSetSchemaVersion": "mocha --timeout 9999999 -r ts-node/register ./**/setSchemaVersion.test.ts",
"testSetVariableMetaData": "mocha --timeout 9999999 -r ts-node/register ./**/setVariableMetaData.test.ts",
tests/src/transfer.nload.tsdiffbeforeafterboth--- /dev/null
+++ b/tests/src/transfer.nload.ts
@@ -0,0 +1,113 @@
+import { ApiPromise } from "@polkadot/api";
+import { IKeyringPair } from '@polkadot/types/types';
+import privateKey from "./substrate/privateKey";
+import usingApi, { submitTransactionAsync } from "./substrate/substrate-api";
+import waitNewBlocks from "./substrate/wait-new-blocks";
+import { findUnusedAddresses } from "./util/helpers";
+import * as cluster from 'cluster';
+import os from 'os';
+
+// Innacurate transfer fee
+const FEE = 10n ** 8n;
+
+let counters: { [key: string]: number } = {};
+function increaseCounter(name: string, amount: number) {
+ if (!counters[name]) {
+ counters[name] = 0;
+ }
+ counters[name] += amount;
+}
+function flushCounterToMaster() {
+ if (Object.keys(counters).length === 0) {
+ return;
+ }
+ process.send!(counters);
+ counters = {};
+}
+
+async function distributeBalance(source: IKeyringPair, api: ApiPromise, totalAmount: bigint, stages: number) {
+ let accounts = [source];
+ // we don't need source in output array
+ const failedAccounts = [0];
+
+ const finalUserAmount = 2 ** stages - 1;
+ accounts.push(...await findUnusedAddresses(api, finalUserAmount));
+ // findUnusedAddresses produces at least 1 request per user
+ increaseCounter('requests', finalUserAmount);
+
+ for (let stage = 0; stage < stages; stage++) {
+ let usersWithBalance = 2 ** stage;
+ let amount = totalAmount / (2n ** BigInt(stage)) - FEE * BigInt(stage);
+ // console.log(`Stage ${stage}/${stages}, ${usersWithBalance} => ${usersWithBalance * 2} = ${amount}`);
+ let txs = [];
+ for (let i = 0; i < usersWithBalance; i++) {
+ let newUser = accounts[i + usersWithBalance];
+ // console.log(`${accounts[i].address} => ${newUser.address} = ${amountToSplit}`);
+ const tx = api.tx.balances.transfer(newUser.address, amount);
+ txs.push(submitTransactionAsync(accounts[i], tx).catch(e => {
+ failedAccounts.push(i + usersWithBalance);
+ increaseCounter('txFailed', 1);
+ }));
+ increaseCounter('tx', 1);
+ }
+ await Promise.all(txs);
+ }
+
+ for (let account of failedAccounts.reverse()) {
+ accounts.splice(account, 1);
+ }
+ return accounts;
+}
+
+if (cluster.isMaster) {
+ let testDone = false;
+ usingApi(async (api) => {
+ let prevCounters: { [key: string]: number } = {};
+ while (!testDone) {
+ for (let name in counters) {
+ if (!(name in prevCounters)) {
+ prevCounters[name] = 0;
+ }
+ if(counters[name] === prevCounters[name]) {
+ continue;
+ }
+ console.log(`${name.padEnd(15)} = ${counters[name] - prevCounters[name]}`);
+ prevCounters[name] = counters[name];
+ }
+ await waitNewBlocks(api, 1);
+ }
+ });
+ let waiting: Promise<void>[] = [];
+ console.log(`Starting ${os.cpus().length} workers`);
+ usingApi(async (api) => {
+ const alice = privateKey('//Alice');
+ for (let id in os.cpus()) {
+ const WORKER_NAME = `//LoadWorker${id}_${Date.now()}`;
+ const workerAccount = privateKey(WORKER_NAME);
+ const tx = api.tx.balances.transfer(workerAccount.address, 400n * 10n ** 23n);
+ await submitTransactionAsync(alice, tx);
+
+ let worker = cluster.fork({
+ WORKER_NAME,
+ STAGES: id + 2
+ });
+ worker.on('message', msg => {
+ for (let key in msg) {
+ increaseCounter(key, msg[key]);
+ }
+ });
+ waiting.push(new Promise(res => worker.on('exit', res)));
+ }
+ await Promise.all(waiting);
+ testDone = true;
+ })
+} else {
+ increaseCounter('startedWorkers', 1);
+ usingApi(async (api) => {
+ await distributeBalance(privateKey(process.env.WORKER_NAME as string), api, 400n * 10n ** 22n, 10);
+ });
+ const interval = setInterval(() => {
+ flushCounterToMaster();
+ }, 100);
+ interval.unref();
+}
\ No newline at end of file
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}4041interface IReFungibleOwner {42 Fraction: BN;43 Owner: number[];44}4546interface ITokenDataType {47 Owner: number[];48 ConstData: number[];49 VariableData: number[];50}5152interface IFungibleTokenDataType {53 Value: BN;54}5556export interface IReFungibleTokenDataType {57 Owner: IReFungibleOwner[];58 ConstData: number[];59 VariableData: number[];60}6162export function getGenericResult(events: EventRecord[]): GenericResult {63 const result: GenericResult = {64 success: false,65 };66 events.forEach(({ phase, event: { data, method, section } }) => {67 // console.log(` ${phase}: ${section}.${method}:: ${data}`);68 if (method === 'ExtrinsicSuccess') {69 result.success = true;70 }71 });72 return result;73}7475export function getCreateCollectionResult(events: EventRecord[]): CreateCollectionResult {76 let success = false;77 let collectionId: number = 0;78 events.forEach(({ phase, event: { data, method, section } }) => {79 // console.log(` ${phase}: ${section}.${method}:: ${data}`);80 if (method == 'ExtrinsicSuccess') {81 success = true;82 } else if ((section == 'nft') && (method == 'Created')) {83 collectionId = parseInt(data[0].toString());84 }85 });86 const result: CreateCollectionResult = {87 success,88 collectionId,89 };90 return result;91}9293export function getCreateItemResult(events: EventRecord[]): CreateItemResult {94 let success = false;95 let collectionId: number = 0;96 let itemId: number = 0;97 events.forEach(({ phase, event: { data, method, section } }) => {98 // console.log(` ${phase}: ${section}.${method}:: ${data}`);99 if (method == 'ExtrinsicSuccess') {100 success = true;101 } else if ((section == 'nft') && (method == 'ItemCreated')) {102 collectionId = parseInt(data[0].toString());103 itemId = parseInt(data[1].toString());104 }105 });106 const result: CreateItemResult = {107 success,108 collectionId,109 itemId,110 };111 return result;112}113114interface Invalid {115 type: 'Invalid';116}117118interface Nft {119 type: 'NFT';120}121122interface Fungible {123 type: 'Fungible';124 decimalPoints: number;125}126127interface ReFungible {128 type: 'ReFungible';129}130131type CollectionMode = Nft | Fungible | ReFungible | Invalid;132133export type CreateCollectionParams = {134 mode: CollectionMode,135 name: string,136 description: string,137 tokenPrefix: string,138};139140const defaultCreateCollectionParams: CreateCollectionParams = {141 description: 'description',142 mode: { type: 'NFT' },143 name: 'name',144 tokenPrefix: 'prefix',145}146147export async function createCollectionExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {148 const {name, description, mode, tokenPrefix } = {...defaultCreateCollectionParams, ...params};149150 let collectionId: number = 0;151 await usingApi(async (api) => {152 // Get number of collections before the transaction153 const AcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString(), 10);154155 // Run the CreateCollection transaction156 const alicePrivateKey = privateKey('//Alice');157158 let modeprm = {};159 if (mode.type === 'NFT') {160 modeprm = {nft: null};161 } else if (mode.type === 'Fungible') {162 modeprm = {fungible: mode.decimalPoints};163 } else if (mode.type === 'ReFungible') {164 modeprm = {refungible: null};165 } else if (mode.type === 'Invalid') {166 modeprm = {invalid: null};167 }168169 const tx = api.tx.nft.createCollection(strToUTF16(name), strToUTF16(description), strToUTF16(tokenPrefix), modeprm);170 const events = await submitTransactionAsync(alicePrivateKey, tx);171 const result = getCreateCollectionResult(events);172173 // Get number of collections after the transaction174 const BcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString(), 10);175176 // Get the collection177 const collection: any = (await api.query.nft.collection(result.collectionId)).toJSON();178179 // What to expect180 // tslint:disable-next-line:no-unused-expression181 expect(result.success).to.be.true;182 expect(result.collectionId).to.be.equal(BcollectionCount);183 // tslint:disable-next-line:no-unused-expression184 expect(collection).to.be.not.null;185 expect(BcollectionCount).to.be.equal(AcollectionCount + 1, 'Error: NFT collection NOT created.');186 expect(collection.Owner).to.be.equal(alicesPublicKey);187 expect(utf16ToStr(collection.Name)).to.be.equal(name);188 expect(utf16ToStr(collection.Description)).to.be.equal(description);189 expect(hexToStr(collection.TokenPrefix)).to.be.equal(tokenPrefix);190191 collectionId = result.collectionId;192 });193194 return collectionId;195}196197export async function createCollectionExpectFailure(params: Partial<CreateCollectionParams> = {}) {198 const {name, description, mode, tokenPrefix } = {...defaultCreateCollectionParams, ...params};199200 let modeprm = {};201 if (mode.type === 'NFT') {202 modeprm = {nft: null};203 } else if (mode.type === 'Fungible') {204 modeprm = {fungible: mode.decimalPoints};205 } else if (mode.type === 'ReFungible') {206 modeprm = {refungible: null};207 } else if (mode.type === 'Invalid') {208 modeprm = {invalid: null};209 }210211 await usingApi(async (api) => {212 // Get number of collections before the transaction213 const AcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString());214215 // Run the CreateCollection transaction216 const alicePrivateKey = privateKey('//Alice');217 const tx = api.tx.nft.createCollection(strToUTF16(name), strToUTF16(description), strToUTF16(tokenPrefix), modeprm);218 const events = await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;219 const result = getCreateCollectionResult(events);220221 // Get number of collections after the transaction222 const BcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString());223224 // What to expect225 // tslint:disable-next-line:no-unused-expression226 expect(result.success).to.be.false;227 expect(BcollectionCount).to.be.equal(AcollectionCount, 'Error: Collection with incorrect data created.');228 });229}230231export async function findUnusedAddress(api: ApiPromise): Promise<IKeyringPair> {232 let bal = new BigNumber(0);233 let unused;234 do {235 const randomSeed = 'seed' + Math.floor(Math.random() * Math.floor(10000));236 const keyring = new Keyring({ type: 'sr25519' });237 unused = keyring.addFromUri(`//${randomSeed}`);238 bal = new BigNumber((await api.query.system.account(unused.address)).data.free.toString());239 } while (bal.toFixed() != '0');240 return unused;241}242243export async function getAllowance(collectionId: number, tokenId: number, owner: string, approved: string) {244 return await usingApi(async (api) => {245 const bn = await api.query.nft.allowances(collectionId, [tokenId, owner, approved]) as unknown as BN;246 return BigInt(bn.toString());247 });248}249250export function findUnusedAddresses(api: ApiPromise, amount: number): Promise<IKeyringPair[]> {251 return Promise.all(new Array(amount).fill(null).map(() => findUnusedAddress(api, '_' + Date.now())));252}253254export async function findNotExistingCollection(api: ApiPromise): Promise<number> {255 const totalNumber = parseInt((await api.query.nft.createdCollectionCount()).toString(), 10) as unknown as number;256 const newCollection: number = totalNumber + 1;257 return newCollection;258}259260function getDestroyResult(events: EventRecord[]): boolean {261 let success: boolean = false;262 events.forEach(({ phase, event: { data, method, section } }) => {263 // console.log(` ${phase}: ${section}.${method}:: ${data}`);264 if (method == 'ExtrinsicSuccess') {265 success = true;266 }267 });268 return success;269}270271export async function destroyCollectionExpectFailure(collectionId: number, senderSeed: string = '//Alice') {272 await usingApi(async (api) => {273 // Run the DestroyCollection transaction274 const alicePrivateKey = privateKey(senderSeed);275 const tx = api.tx.nft.destroyCollection(collectionId);276 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;277 });278}279280export async function destroyCollectionExpectSuccess(collectionId: number, senderSeed: string = '//Alice') {281 await usingApi(async (api) => {282 // Run the DestroyCollection transaction283 const alicePrivateKey = privateKey(senderSeed);284 const tx = api.tx.nft.destroyCollection(collectionId);285 const events = await submitTransactionAsync(alicePrivateKey, tx);286 const result = getDestroyResult(events);287288 // Get the collection289 const collection: any = (await api.query.nft.collection(collectionId)).toJSON();290291 // What to expect292 expect(result).to.be.true;293 expect(collection).to.be.not.null;294 expect(collection.Owner).to.be.equal(nullPublicKey);295 });296}297298export async function setCollectionSponsorExpectSuccess(collectionId: number, sponsor: string) {299 await usingApi(async (api) => {300301 // Run the transaction302 const alicePrivateKey = privateKey('//Alice');303 const tx = api.tx.nft.setCollectionSponsor(collectionId, sponsor);304 const events = await submitTransactionAsync(alicePrivateKey, tx);305 const result = getGenericResult(events);306307 // Get the collection308 const collection: any = (await api.query.nft.collection(collectionId)).toJSON();309310 // What to expect311 expect(result.success).to.be.true;312 expect(collection.Sponsor.toString()).to.be.equal(sponsor.toString());313 expect(collection.SponsorConfirmed).to.be.false;314 });315}316317export async function removeCollectionSponsorExpectSuccess(collectionId: number) {318 await usingApi(async (api) => {319320 // Run the transaction321 const alicePrivateKey = privateKey('//Alice');322 const tx = api.tx.nft.removeCollectionSponsor(collectionId);323 const events = await submitTransactionAsync(alicePrivateKey, tx);324 const result = getGenericResult(events);325326 // Get the collection327 const collection: any = (await api.query.nft.collection(collectionId)).toJSON();328329 // What to expect330 expect(result.success).to.be.true;331 expect(collection.Sponsor).to.be.equal(nullPublicKey);332 expect(collection.SponsorConfirmed).to.be.false;333 });334}335336export async function removeCollectionSponsorExpectFailure(collectionId: number) {337 await usingApi(async (api) => {338339 // Run the transaction340 const alicePrivateKey = privateKey('//Alice');341 const tx = api.tx.nft.removeCollectionSponsor(collectionId);342 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;343 });344}345346export async function setCollectionSponsorExpectFailure(collectionId: number, sponsor: string, senderSeed: string = '//Alice') {347 await usingApi(async (api) => {348349 // Run the transaction350 const alicePrivateKey = privateKey(senderSeed);351 const tx = api.tx.nft.setCollectionSponsor(collectionId, sponsor);352 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;353 });354}355356export async function confirmSponsorshipExpectSuccess(collectionId: number, senderSeed: string = '//Alice') {357 await usingApi(async (api) => {358359 // Run the transaction360 const sender = privateKey(senderSeed);361 const tx = api.tx.nft.confirmSponsorship(collectionId);362 const events = await submitTransactionAsync(sender, tx);363 const result = getGenericResult(events);364365 // Get the collection366 const collection: any = (await api.query.nft.collection(collectionId)).toJSON();367368 // What to expect369 expect(result.success).to.be.true;370 expect(collection.Sponsor).to.be.equal(sender.address);371 expect(collection.SponsorConfirmed).to.be.true;372 });373}374375376export async function confirmSponsorshipExpectFailure(collectionId: number, senderSeed: string = '//Alice') {377 await usingApi(async (api) => {378379 // Run the transaction380 const sender = privateKey(senderSeed);381 const tx = api.tx.nft.confirmSponsorship(collectionId);382 await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;383 });384}385386export async function enableContractSponsoringExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {387 await usingApi(async (api) => {388 const tx = api.tx.nft.enableContractSponsoring(contractAddress, enable);389 const events = await submitTransactionAsync(sender, tx);390 const result = getGenericResult(events);391392 expect(result.success).to.be.true;393 });394}395396export async function enableContractSponsoringExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {397 await usingApi(async (api) => {398 const tx = api.tx.nft.enableContractSponsoring(contractAddress, enable);399 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;400 const result = getGenericResult(events);401402 expect(result.success).to.be.false;403 });404}405406export async function setContractSponsoringRateLimitExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {407 await usingApi(async (api) => {408 const tx = api.tx.nft.setContractSponsoringRateLimit(contractAddress, rateLimit);409 const events = await submitTransactionAsync(sender, tx);410 const result = getGenericResult(events);411412 expect(result.success).to.be.true;413 });414}415416export async function setContractSponsoringRateLimitExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {417 await usingApi(async (api) => {418 const tx = api.tx.nft.setContractSponsoringRateLimit(contractAddress, rateLimit);419 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;420 const result = getGenericResult(events);421422 expect(result.success).to.be.false;423 });424}425426export async function toggleContractWhitelistExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, enabled: boolean) {427 await usingApi(async (api) => {428 const tx = api.tx.nft.toggleContractWhiteList(contractAddress, true);429 const events = await submitTransactionAsync(sender, tx);430 const result = getGenericResult(events);431432 expect(result.success).to.be.true;433 });434}435436export async function isWhitelistedInContract(contractAddress: AccountId | string, user: string) {437 let whitelisted: boolean = false;438 await usingApi(async (api) => {439 whitelisted = (await api.query.nft.contractWhiteList(contractAddress, user)).toJSON() as boolean;440 });441 return whitelisted;442}443444export async function addToContractWhiteListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: string) {445 await usingApi(async (api) => {446 const tx = api.tx.nft.addToContractWhiteList(contractAddress, user);447 const events = await submitTransactionAsync(sender, tx);448 const result = getGenericResult(events);449450 expect(result.success).to.be.true;451 });452}453454export async function removeFromContractWhiteListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: string) {455 await usingApi(async (api) => {456 const tx = api.tx.nft.removeFromContractWhiteList(contractAddress, user);457 const events = await submitTransactionAsync(sender, tx);458 const result = getGenericResult(events);459460 expect(result.success).to.be.true;461 });462}463464export async function removeFromContractWhiteListExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, user: string) {465 await usingApi(async (api) => {466 const tx = api.tx.nft.removeFromContractWhiteList(contractAddress, user);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 setVariableMetaDataExpectSuccess(sender: IKeyringPair, collectionId: number, itemId: number, data: number[]) {475 await usingApi(async (api) => {476 const tx = api.tx.nft.setVariableMetaData(collectionId, itemId, '0x' + Buffer.from(data).toString('hex'));477 const events = await submitTransactionAsync(sender, tx);478 const result = getGenericResult(events);479480 expect(result.success).to.be.true;481 });482}483484export async function setVariableMetaDataExpectFailure(sender: IKeyringPair, collectionId: number, itemId: number, data: number[]) {485 await usingApi(async (api) => {486 const tx = api.tx.nft.setVariableMetaData(collectionId, itemId, '0x' + Buffer.from(data).toString('hex'));487 await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;488 });489}490491export interface CreateFungibleData {492 readonly Value: bigint;493}494495export interface CreateReFungibleData { }496export interface CreateNftData { }497498export type CreateItemData = {499 NFT: CreateNftData;500} | {501 Fungible: CreateFungibleData;502} | {503 ReFungible: CreateReFungibleData;504};505506export async function burnItemExpectSuccess(owner: IKeyringPair, collectionId: number, tokenId: number, value = 0) {507 await usingApi(async (api) => {508 const tx = api.tx.nft.burnItem(collectionId, tokenId, value);509 const events = await submitTransactionAsync(owner, tx);510 const result = getGenericResult(events);511 // Get the item512 const item: any = (await api.query.nft.nftItemList(collectionId, tokenId)).toJSON();513 // What to expect514 // tslint:disable-next-line:no-unused-expression515 expect(result.success).to.be.true;516 // tslint:disable-next-line:no-unused-expression517 expect(item).to.be.not.null;518 expect(item.Owner).to.be.equal(nullPublicKey);519 });520}521522export async function523approveExpectSuccess(collectionId: number,524 tokenId: number, owner: IKeyringPair, approved: IKeyringPair, amount: number | bigint = 1) {525 await usingApi(async (api: ApiPromise) => {526 const allowanceBefore =527 await api.query.nft.allowances(collectionId, [tokenId, owner.address, approved.address]) as unknown as BN;528 const approveNftTx = await api.tx.nft.approve(approved.address, collectionId, tokenId, amount);529 const events = await submitTransactionAsync(owner, approveNftTx);530 const result = getCreateItemResult(events);531 // tslint:disable-next-line:no-unused-expression532 expect(result.success).to.be.true;533 const allowanceAfter =534 await api.query.nft.allowances(collectionId, [tokenId, owner.address, approved.address]) as unknown as BN;535 expect(allowanceAfter.sub(allowanceBefore).toString()).to.be.equal(amount.toString());536 });537}538539export async function540transferFromExpectSuccess(collectionId: number,541 tokenId: number,542 accountApproved: IKeyringPair,543 accountFrom: IKeyringPair,544 accountTo: IKeyringPair,545 value: number | bigint = 1,546 type: string = 'NFT') {547 await usingApi(async (api: ApiPromise) => {548 let balanceBefore = new BN(0);549 if (type === 'Fungible') {550 balanceBefore = await api.query.nft.balance(collectionId, accountTo.address) as unknown as BN;551 }552 const transferFromTx = await api.tx.nft.transferFrom(553 accountFrom.address, accountTo.address, collectionId, tokenId, value);554 const events = await submitTransactionAsync(accountApproved, transferFromTx);555 const result = getCreateItemResult(events);556 // tslint:disable-next-line:no-unused-expression557 expect(result.success).to.be.true;558 if (type === 'NFT') {559 const nftItemData = await api.query.nft.nftItemList(collectionId, tokenId) as unknown as ITokenDataType;560 expect(nftItemData.Owner.toString()).to.be.equal(accountTo.address);561 }562 if (type === 'Fungible') {563 const balanceAfter = await api.query.nft.balance(collectionId, accountTo.address) as unknown as BN;564 expect(balanceAfter.sub(balanceBefore).toString()).to.be.equal(value.toString());565 }566 if (type === 'ReFungible') {567 const nftItemData =568 await api.query.nft.reFungibleItemList(collectionId, tokenId) as unknown as IReFungibleTokenDataType;569 expect(nftItemData.Owner[0].Owner.toString()).to.be.equal(accountTo.address);570 expect(nftItemData.Owner[0].Fraction.toNumber()).to.be.equal(value);571 }572 });573}574575export async function576transferFromExpectFail(collectionId: number,577 tokenId: number,578 accountApproved: IKeyringPair,579 accountFrom: IKeyringPair,580 accountTo: IKeyringPair,581 value: number | bigint = 1) {582 await usingApi(async (api: ApiPromise) => {583 const transferFromTx = await api.tx.nft.transferFrom(584 accountFrom.address, accountTo.address, collectionId, tokenId, value);585 const events = await expect(submitTransactionExpectFailAsync(accountApproved, transferFromTx)).to.be.rejected;586 const result = getCreateCollectionResult(events);587 // tslint:disable-next-line:no-unused-expression588 expect(result.success).to.be.false;589 });590}591592export async function593transferExpectSuccess(collectionId: number,594 tokenId: number,595 sender: IKeyringPair,596 recipient: IKeyringPair,597 value: number | bigint = 1,598 type: string = 'NFT') {599 await usingApi(async (api: ApiPromise) => {600 let balanceBefore = new BN(0);601 if (type === 'Fungible') {602 balanceBefore = await api.query.nft.balance(collectionId, recipient.address) as unknown as BN;603 }604 const transferTx = await api.tx.nft.transfer(recipient.address, collectionId, tokenId, value);605 const events = await submitTransactionAsync(sender, transferTx);606 const result = getCreateItemResult(events);607 // tslint:disable-next-line:no-unused-expression608 expect(result.success).to.be.true;609 if (type === 'NFT') {610 const nftItemData = await api.query.nft.nftItemList(collectionId, tokenId) as unknown as ITokenDataType;611 expect(nftItemData.Owner.toString()).to.be.equal(recipient.address);612 }613 if (type === 'Fungible') {614 const balanceAfter = await api.query.nft.balance(collectionId, recipient.address) as unknown as BN;615 expect(balanceAfter.sub(balanceBefore).toString()).to.be.equal(value.toString());616 }617 if (type === 'ReFungible') {618 const nftItemData =619 await api.query.nft.reFungibleItemList(collectionId, tokenId) as unknown as IReFungibleTokenDataType;620 expect(nftItemData.Owner[0].Owner.toString()).to.be.equal(recipient.address);621 expect(nftItemData.Owner[0].Fraction.toNumber()).to.be.equal(value);622 }623 });624}625626export async function627transferExpectFail(collectionId: number,628 tokenId: number,629 sender: IKeyringPair,630 recipient: IKeyringPair,631 value: number | bigint = 1,632 type: string = 'NFT') {633 await usingApi(async (api: ApiPromise) => {634 const transferTx = await api.tx.nft.transfer(recipient.address, collectionId, tokenId, value);635 const events = await expect(submitTransactionExpectFailAsync(sender, transferTx)).to.be.rejected;636 if (events && Array.isArray(events)) {637 const result = getCreateCollectionResult(events);638 // tslint:disable-next-line:no-unused-expression639 expect(result.success).to.be.false;640 }641 });642}643644export async function645approveExpectFail(collectionId: number,646 tokenId: number, owner: IKeyringPair, approved: IKeyringPair, amount: number | bigint = 1) {647 await usingApi(async (api: ApiPromise) => {648 const approveNftTx = await api.tx.nft.approve(approved.address, collectionId, tokenId, amount);649 const events = await expect(submitTransactionExpectFailAsync(owner, approveNftTx)).to.be.rejected;650 const result = getCreateCollectionResult(events);651 // tslint:disable-next-line:no-unused-expression652 expect(result.success).to.be.false;653 });654}655656export async function getFungibleBalance(657 collectionId: number,658 owner: string,659) {660 return await usingApi(async (api) => {661 const response = (await api.query.nft.fungibleItemList(collectionId, owner)).toJSON() as unknown as {Value: string};662 return BigInt(response.Value);663 });664}665666export async function createFungibleItemExpectSuccess(667 sender: IKeyringPair,668 collectionId: number,669 data: CreateFungibleData,670 owner: string = sender.address,671) {672 return await usingApi(async (api) => {673 const tx = api.tx.nft.createItem(collectionId, owner, { Fungible: data });674675 const events = await submitTransactionAsync(sender, tx);676 const result = getCreateItemResult(events);677678 expect(result.success).to.be.true;679 return result.itemId;680 });681}682683export async function createItemExpectSuccess(684 sender: IKeyringPair, collectionId: number, createMode: string, owner: string = '') {685 let newItemId: number = 0;686 await usingApi(async (api) => {687 const AItemCount = parseInt((await api.query.nft.itemListIndex(collectionId)).toString(), 10);688 const Aitem: any = (await api.query.nft.fungibleItemList(collectionId, owner)).toJSON();689 const AItemBalance = new BigNumber(Aitem.Value);690691 if (owner === '') {692 owner = sender.address;693 }694695 let tx;696 if (createMode === 'Fungible') {697 const createData = {fungible: {value: 10}};698 tx = api.tx.nft.createItem(collectionId, owner, createData);699 } else if (createMode === 'ReFungible') {700 const createData = {refungible: {const_data: [], variable_data: [], pieces: 100}};701 tx = api.tx.nft.createItem(collectionId, owner, createData);702 } else {703 tx = api.tx.nft.createItem(collectionId, owner, createMode);704 }705 const events = await submitTransactionAsync(sender, tx);706 const result = getCreateItemResult(events);707708 const BItemCount = parseInt((await api.query.nft.itemListIndex(collectionId)).toString(), 10);709 const Bitem: any = (await api.query.nft.fungibleItemList(collectionId, owner)).toJSON();710 const BItemBalance = new BigNumber(Bitem.Value);711712 // What to expect713 // tslint:disable-next-line:no-unused-expression714 expect(result.success).to.be.true;715 if (createMode === 'Fungible') {716 expect(BItemBalance.minus(AItemBalance).toNumber()).to.be.equal(10);717 } else {718 expect(BItemCount).to.be.equal(AItemCount + 1);719 }720 expect(collectionId).to.be.equal(result.collectionId);721 expect(BItemCount).to.be.equal(result.itemId);722 newItemId = result.itemId;723 });724 return newItemId;725}726727export async function createItemExpectFailure(728 sender: IKeyringPair, collectionId: number, createMode: string, owner: string = sender.address) {729 await usingApi(async (api) => {730 const tx = api.tx.nft.createItem(collectionId, owner, createMode);731 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;732 const result = getCreateItemResult(events);733734 expect(result.success).to.be.false;735 });736}737738export async function setPublicAccessModeExpectSuccess(739 sender: IKeyringPair, collectionId: number,740 accessMode: 'Normal' | 'WhiteList',741) {742 await usingApi(async (api) => {743744 // Run the transaction745 const tx = api.tx.nft.setPublicAccessMode(collectionId, accessMode);746 const events = await submitTransactionAsync(sender, tx);747 const result = getGenericResult(events);748749 // Get the collection750 const collection: any = (await api.query.nft.collection(collectionId)).toJSON();751752 // What to expect753 // tslint:disable-next-line:no-unused-expression754 expect(result.success).to.be.true;755 expect(collection.Access).to.be.equal(accessMode);756 });757}758759export async function enableWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number) {760 await setPublicAccessModeExpectSuccess(sender, collectionId, 'WhiteList');761}762763export async function disableWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number) {764 await setPublicAccessModeExpectSuccess(sender, collectionId, 'Normal');765}766767export async function setMintPermissionExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {768 await usingApi(async (api) => {769770 // Run the transaction771 const tx = api.tx.nft.setMintPermission(collectionId, enabled);772 const events = await submitTransactionAsync(sender, tx);773 const result = getGenericResult(events);774775 // Get the collection776 const collection: any = (await api.query.nft.collection(collectionId)).toJSON();777778 // What to expect779 // tslint:disable-next-line:no-unused-expression780 expect(result.success).to.be.true;781 expect(collection.MintMode).to.be.equal(enabled);782 });783}784785export async function enablePublicMintingExpectSuccess(sender: IKeyringPair, collectionId: number) {786 await setMintPermissionExpectSuccess(sender, collectionId, true);787}788789export async function setMintPermissionExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {790 await usingApi(async (api) => {791 // Run the transaction792 const tx = api.tx.nft.setMintPermission(collectionId, enabled);793 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;794 const result = getCreateCollectionResult(events);795 // tslint:disable-next-line:no-unused-expression796 expect(result.success).to.be.false;797 });798}799800export async function isWhitelisted(collectionId: number, address: string) {801 let whitelisted: boolean = false;802 await usingApi(async (api) => {803 whitelisted = (await api.query.nft.whiteList(collectionId, address)).toJSON() as unknown as boolean;804 });805 return whitelisted;806}807808export async function addToWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number, address: string) {809 await usingApi(async (api) => {810811 const whiteListedBefore = (await api.query.nft.whiteList(collectionId, address)).toJSON();812813 // Run the transaction814 const tx = api.tx.nft.addToWhiteList(collectionId, address);815 const events = await submitTransactionAsync(sender, tx);816 const result = getGenericResult(events);817818 const whiteListedAfter = (await api.query.nft.whiteList(collectionId, address)).toJSON();819820 // What to expect821 // tslint:disable-next-line:no-unused-expression822 expect(result.success).to.be.true;823 // tslint:disable-next-line: no-unused-expression824 expect(whiteListedBefore).to.be.false;825 // tslint:disable-next-line: no-unused-expression826 expect(whiteListedAfter).to.be.true;827 });828}829830export async function removeFromWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number, address: string) {831 await usingApi(async (api) => {832 // Run the transaction833 const tx = api.tx.nft.removeFromWhiteList(collectionId, address);834 const events = await submitTransactionAsync(sender, tx);835 const result = getGenericResult(events);836837 // What to expect838 // tslint:disable-next-line:no-unused-expression839 expect(result.success).to.be.true;840 });841}842843export async function removeFromWhiteListExpectFailure(sender: IKeyringPair, collectionId: number, address: string) {844 await usingApi(async (api) => {845 // Run the transaction846 const tx = api.tx.nft.removeFromWhiteList(collectionId, address);847 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;848 const result = getGenericResult(events);849850 // What to expect851 // tslint:disable-next-line:no-unused-expression852 expect(result.success).to.be.false;853 });854}855856export const getDetailedCollectionInfo = async (api: ApiPromise, collectionId: number)857 : Promise<ICollectionInterface | null> => {858 return await api.query.nft.collection(collectionId) as unknown as ICollectionInterface;859};860861export const getCreatedCollectionCount = async (api: ApiPromise): Promise<number> => {862 // set global object - collectionsCount863 return (await api.query.nft.createdCollectionCount() as unknown as BN).toNumber();864};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}4041interface IReFungibleOwner {42 Fraction: BN;43 Owner: number[];44}4546interface ITokenDataType {47 Owner: number[];48 ConstData: number[];49 VariableData: number[];50}5152interface IFungibleTokenDataType {53 Value: BN;54}5556export interface IReFungibleTokenDataType {57 Owner: IReFungibleOwner[];58 ConstData: number[];59 VariableData: number[];60}6162export function getGenericResult(events: EventRecord[]): GenericResult {63 const result: GenericResult = {64 success: false,65 };66 events.forEach(({ phase, event: { data, method, section } }) => {67 // console.log(` ${phase}: ${section}.${method}:: ${data}`);68 if (method === 'ExtrinsicSuccess') {69 result.success = true;70 }71 });72 return result;73}7475export function getCreateCollectionResult(events: EventRecord[]): CreateCollectionResult {76 let success = false;77 let collectionId: number = 0;78 events.forEach(({ phase, event: { data, method, section } }) => {79 // console.log(` ${phase}: ${section}.${method}:: ${data}`);80 if (method == 'ExtrinsicSuccess') {81 success = true;82 } else if ((section == 'nft') && (method == 'Created')) {83 collectionId = parseInt(data[0].toString());84 }85 });86 const result: CreateCollectionResult = {87 success,88 collectionId,89 };90 return result;91}9293export function getCreateItemResult(events: EventRecord[]): CreateItemResult {94 let success = false;95 let collectionId: number = 0;96 let itemId: number = 0;97 events.forEach(({ phase, event: { data, method, section } }) => {98 // console.log(` ${phase}: ${section}.${method}:: ${data}`);99 if (method == 'ExtrinsicSuccess') {100 success = true;101 } else if ((section == 'nft') && (method == 'ItemCreated')) {102 collectionId = parseInt(data[0].toString());103 itemId = parseInt(data[1].toString());104 }105 });106 const result: CreateItemResult = {107 success,108 collectionId,109 itemId,110 };111 return result;112}113114interface Invalid {115 type: 'Invalid';116}117118interface Nft {119 type: 'NFT';120}121122interface Fungible {123 type: 'Fungible';124 decimalPoints: number;125}126127interface ReFungible {128 type: 'ReFungible';129}130131type CollectionMode = Nft | Fungible | ReFungible | Invalid;132133export type CreateCollectionParams = {134 mode: CollectionMode,135 name: string,136 description: string,137 tokenPrefix: string,138};139140const defaultCreateCollectionParams: CreateCollectionParams = {141 description: 'description',142 mode: { type: 'NFT' },143 name: 'name',144 tokenPrefix: 'prefix',145}146147export async function createCollectionExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {148 const {name, description, mode, tokenPrefix } = {...defaultCreateCollectionParams, ...params};149150 let collectionId: number = 0;151 await usingApi(async (api) => {152 // Get number of collections before the transaction153 const AcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString(), 10);154155 // Run the CreateCollection transaction156 const alicePrivateKey = privateKey('//Alice');157158 let modeprm = {};159 if (mode.type === 'NFT') {160 modeprm = {nft: null};161 } else if (mode.type === 'Fungible') {162 modeprm = {fungible: mode.decimalPoints};163 } else if (mode.type === 'ReFungible') {164 modeprm = {refungible: null};165 } else if (mode.type === 'Invalid') {166 modeprm = {invalid: null};167 }168169 const tx = api.tx.nft.createCollection(strToUTF16(name), strToUTF16(description), strToUTF16(tokenPrefix), modeprm);170 const events = await submitTransactionAsync(alicePrivateKey, tx);171 const result = getCreateCollectionResult(events);172173 // Get number of collections after the transaction174 const BcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString(), 10);175176 // Get the collection177 const collection: any = (await api.query.nft.collection(result.collectionId)).toJSON();178179 // What to expect180 // tslint:disable-next-line:no-unused-expression181 expect(result.success).to.be.true;182 expect(result.collectionId).to.be.equal(BcollectionCount);183 // tslint:disable-next-line:no-unused-expression184 expect(collection).to.be.not.null;185 expect(BcollectionCount).to.be.equal(AcollectionCount + 1, 'Error: NFT collection NOT created.');186 expect(collection.Owner).to.be.equal(alicesPublicKey);187 expect(utf16ToStr(collection.Name)).to.be.equal(name);188 expect(utf16ToStr(collection.Description)).to.be.equal(description);189 expect(hexToStr(collection.TokenPrefix)).to.be.equal(tokenPrefix);190191 collectionId = result.collectionId;192 });193194 return collectionId;195}196197export async function createCollectionExpectFailure(params: Partial<CreateCollectionParams> = {}) {198 const {name, description, mode, tokenPrefix } = {...defaultCreateCollectionParams, ...params};199200 let modeprm = {};201 if (mode.type === 'NFT') {202 modeprm = {nft: null};203 } else if (mode.type === 'Fungible') {204 modeprm = {fungible: mode.decimalPoints};205 } else if (mode.type === 'ReFungible') {206 modeprm = {refungible: null};207 } else if (mode.type === 'Invalid') {208 modeprm = {invalid: null};209 }210211 await usingApi(async (api) => {212 // Get number of collections before the transaction213 const AcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString());214215 // Run the CreateCollection transaction216 const alicePrivateKey = privateKey('//Alice');217 const tx = api.tx.nft.createCollection(strToUTF16(name), strToUTF16(description), strToUTF16(tokenPrefix), modeprm);218 const events = await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;219 const result = getCreateCollectionResult(events);220221 // Get number of collections after the transaction222 const BcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString());223224 // What to expect225 // tslint:disable-next-line:no-unused-expression226 expect(result.success).to.be.false;227 expect(BcollectionCount).to.be.equal(AcollectionCount, 'Error: Collection with incorrect data created.');228 });229}230231export async function findUnusedAddress(api: ApiPromise, seedAddition = ''): Promise<IKeyringPair> {232 let bal = new BigNumber(0);233 let unused;234 do {235 const randomSeed = 'seed' + Math.floor(Math.random() * Math.floor(10000)) + seedAddition;236 const keyring = new Keyring({ type: 'sr25519' });237 unused = keyring.addFromUri(`//${randomSeed}`);238 bal = new BigNumber((await api.query.system.account(unused.address)).data.free.toString());239 } while (bal.toFixed() != '0');240 return unused;241}242243export async function getAllowance(collectionId: number, tokenId: number, owner: string, approved: string) {244 return await usingApi(async (api) => {245 const bn = await api.query.nft.allowances(collectionId, [tokenId, owner, approved]) as unknown as BN;246 return BigInt(bn.toString());247 });248}249250export function findUnusedAddresses(api: ApiPromise, amount: number): Promise<IKeyringPair[]> {251 return Promise.all(new Array(amount).fill(null).map(() => findUnusedAddress(api, '_' + Date.now())));252}253254export async function findNotExistingCollection(api: ApiPromise): Promise<number> {255 const totalNumber = parseInt((await api.query.nft.createdCollectionCount()).toString(), 10) as unknown as number;256 const newCollection: number = totalNumber + 1;257 return newCollection;258}259260function getDestroyResult(events: EventRecord[]): boolean {261 let success: boolean = false;262 events.forEach(({ phase, event: { data, method, section } }) => {263 // console.log(` ${phase}: ${section}.${method}:: ${data}`);264 if (method == 'ExtrinsicSuccess') {265 success = true;266 }267 });268 return success;269}270271export async function destroyCollectionExpectFailure(collectionId: number, senderSeed: string = '//Alice') {272 await usingApi(async (api) => {273 // Run the DestroyCollection transaction274 const alicePrivateKey = privateKey(senderSeed);275 const tx = api.tx.nft.destroyCollection(collectionId);276 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;277 });278}279280export async function destroyCollectionExpectSuccess(collectionId: number, senderSeed: string = '//Alice') {281 await usingApi(async (api) => {282 // Run the DestroyCollection transaction283 const alicePrivateKey = privateKey(senderSeed);284 const tx = api.tx.nft.destroyCollection(collectionId);285 const events = await submitTransactionAsync(alicePrivateKey, tx);286 const result = getDestroyResult(events);287288 // Get the collection289 const collection: any = (await api.query.nft.collection(collectionId)).toJSON();290291 // What to expect292 expect(result).to.be.true;293 expect(collection).to.be.not.null;294 expect(collection.Owner).to.be.equal(nullPublicKey);295 });296}297298export async function setCollectionSponsorExpectSuccess(collectionId: number, sponsor: string) {299 await usingApi(async (api) => {300301 // Run the transaction302 const alicePrivateKey = privateKey('//Alice');303 const tx = api.tx.nft.setCollectionSponsor(collectionId, sponsor);304 const events = await submitTransactionAsync(alicePrivateKey, tx);305 const result = getGenericResult(events);306307 // Get the collection308 const collection: any = (await api.query.nft.collection(collectionId)).toJSON();309310 // What to expect311 expect(result.success).to.be.true;312 expect(collection.Sponsor.toString()).to.be.equal(sponsor.toString());313 expect(collection.SponsorConfirmed).to.be.false;314 });315}316317export async function removeCollectionSponsorExpectSuccess(collectionId: number) {318 await usingApi(async (api) => {319320 // Run the transaction321 const alicePrivateKey = privateKey('//Alice');322 const tx = api.tx.nft.removeCollectionSponsor(collectionId);323 const events = await submitTransactionAsync(alicePrivateKey, tx);324 const result = getGenericResult(events);325326 // Get the collection327 const collection: any = (await api.query.nft.collection(collectionId)).toJSON();328329 // What to expect330 expect(result.success).to.be.true;331 expect(collection.Sponsor).to.be.equal(nullPublicKey);332 expect(collection.SponsorConfirmed).to.be.false;333 });334}335336export async function removeCollectionSponsorExpectFailure(collectionId: number) {337 await usingApi(async (api) => {338339 // Run the transaction340 const alicePrivateKey = privateKey('//Alice');341 const tx = api.tx.nft.removeCollectionSponsor(collectionId);342 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;343 });344}345346export async function setCollectionSponsorExpectFailure(collectionId: number, sponsor: string, senderSeed: string = '//Alice') {347 await usingApi(async (api) => {348349 // Run the transaction350 const alicePrivateKey = privateKey(senderSeed);351 const tx = api.tx.nft.setCollectionSponsor(collectionId, sponsor);352 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;353 });354}355356export async function confirmSponsorshipExpectSuccess(collectionId: number, senderSeed: string = '//Alice') {357 await usingApi(async (api) => {358359 // Run the transaction360 const sender = privateKey(senderSeed);361 const tx = api.tx.nft.confirmSponsorship(collectionId);362 const events = await submitTransactionAsync(sender, tx);363 const result = getGenericResult(events);364365 // Get the collection366 const collection: any = (await api.query.nft.collection(collectionId)).toJSON();367368 // What to expect369 expect(result.success).to.be.true;370 expect(collection.Sponsor).to.be.equal(sender.address);371 expect(collection.SponsorConfirmed).to.be.true;372 });373}374375376export async function confirmSponsorshipExpectFailure(collectionId: number, senderSeed: string = '//Alice') {377 await usingApi(async (api) => {378379 // Run the transaction380 const sender = privateKey(senderSeed);381 const tx = api.tx.nft.confirmSponsorship(collectionId);382 await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;383 });384}385386export async function enableContractSponsoringExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {387 await usingApi(async (api) => {388 const tx = api.tx.nft.enableContractSponsoring(contractAddress, enable);389 const events = await submitTransactionAsync(sender, tx);390 const result = getGenericResult(events);391392 expect(result.success).to.be.true;393 });394}395396export async function enableContractSponsoringExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {397 await usingApi(async (api) => {398 const tx = api.tx.nft.enableContractSponsoring(contractAddress, enable);399 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;400 const result = getGenericResult(events);401402 expect(result.success).to.be.false;403 });404}405406export async function setContractSponsoringRateLimitExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {407 await usingApi(async (api) => {408 const tx = api.tx.nft.setContractSponsoringRateLimit(contractAddress, rateLimit);409 const events = await submitTransactionAsync(sender, tx);410 const result = getGenericResult(events);411412 expect(result.success).to.be.true;413 });414}415416export async function setContractSponsoringRateLimitExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {417 await usingApi(async (api) => {418 const tx = api.tx.nft.setContractSponsoringRateLimit(contractAddress, rateLimit);419 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;420 const result = getGenericResult(events);421422 expect(result.success).to.be.false;423 });424}425426export async function toggleContractWhitelistExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, enabled: boolean) {427 await usingApi(async (api) => {428 const tx = api.tx.nft.toggleContractWhiteList(contractAddress, true);429 const events = await submitTransactionAsync(sender, tx);430 const result = getGenericResult(events);431432 expect(result.success).to.be.true;433 });434}435436export async function isWhitelistedInContract(contractAddress: AccountId | string, user: string) {437 let whitelisted: boolean = false;438 await usingApi(async (api) => {439 whitelisted = (await api.query.nft.contractWhiteList(contractAddress, user)).toJSON() as boolean;440 });441 return whitelisted;442}443444export async function addToContractWhiteListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: string) {445 await usingApi(async (api) => {446 const tx = api.tx.nft.addToContractWhiteList(contractAddress, user);447 const events = await submitTransactionAsync(sender, tx);448 const result = getGenericResult(events);449450 expect(result.success).to.be.true;451 });452}453454export async function removeFromContractWhiteListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: string) {455 await usingApi(async (api) => {456 const tx = api.tx.nft.removeFromContractWhiteList(contractAddress, user);457 const events = await submitTransactionAsync(sender, tx);458 const result = getGenericResult(events);459460 expect(result.success).to.be.true;461 });462}463464export async function removeFromContractWhiteListExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, user: string) {465 await usingApi(async (api) => {466 const tx = api.tx.nft.removeFromContractWhiteList(contractAddress, user);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 setVariableMetaDataExpectSuccess(sender: IKeyringPair, collectionId: number, itemId: number, data: number[]) {475 await usingApi(async (api) => {476 const tx = api.tx.nft.setVariableMetaData(collectionId, itemId, '0x' + Buffer.from(data).toString('hex'));477 const events = await submitTransactionAsync(sender, tx);478 const result = getGenericResult(events);479480 expect(result.success).to.be.true;481 });482}483484export async function setVariableMetaDataExpectFailure(sender: IKeyringPair, collectionId: number, itemId: number, data: number[]) {485 await usingApi(async (api) => {486 const tx = api.tx.nft.setVariableMetaData(collectionId, itemId, '0x' + Buffer.from(data).toString('hex'));487 await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;488 });489}490491export interface CreateFungibleData {492 readonly Value: bigint;493}494495export interface CreateReFungibleData { }496export interface CreateNftData { }497498export type CreateItemData = {499 NFT: CreateNftData;500} | {501 Fungible: CreateFungibleData;502} | {503 ReFungible: CreateReFungibleData;504};505506export async function burnItemExpectSuccess(owner: IKeyringPair, collectionId: number, tokenId: number, value = 0) {507 await usingApi(async (api) => {508 const tx = api.tx.nft.burnItem(collectionId, tokenId, value);509 const events = await submitTransactionAsync(owner, tx);510 const result = getGenericResult(events);511 // Get the item512 const item: any = (await api.query.nft.nftItemList(collectionId, tokenId)).toJSON();513 // What to expect514 // tslint:disable-next-line:no-unused-expression515 expect(result.success).to.be.true;516 // tslint:disable-next-line:no-unused-expression517 expect(item).to.be.not.null;518 expect(item.Owner).to.be.equal(nullPublicKey);519 });520}521522export async function523approveExpectSuccess(collectionId: number,524 tokenId: number, owner: IKeyringPair, approved: IKeyringPair, amount: number | bigint = 1) {525 await usingApi(async (api: ApiPromise) => {526 const allowanceBefore =527 await api.query.nft.allowances(collectionId, [tokenId, owner.address, approved.address]) as unknown as BN;528 const approveNftTx = await api.tx.nft.approve(approved.address, collectionId, tokenId, amount);529 const events = await submitTransactionAsync(owner, approveNftTx);530 const result = getCreateItemResult(events);531 // tslint:disable-next-line:no-unused-expression532 expect(result.success).to.be.true;533 const allowanceAfter =534 await api.query.nft.allowances(collectionId, [tokenId, owner.address, approved.address]) as unknown as BN;535 expect(allowanceAfter.sub(allowanceBefore).toString()).to.be.equal(amount.toString());536 });537}538539export async function540transferFromExpectSuccess(collectionId: number,541 tokenId: number,542 accountApproved: IKeyringPair,543 accountFrom: IKeyringPair,544 accountTo: IKeyringPair,545 value: number | bigint = 1,546 type: string = 'NFT') {547 await usingApi(async (api: ApiPromise) => {548 let balanceBefore = new BN(0);549 if (type === 'Fungible') {550 balanceBefore = await api.query.nft.balance(collectionId, accountTo.address) as unknown as BN;551 }552 const transferFromTx = await api.tx.nft.transferFrom(553 accountFrom.address, accountTo.address, collectionId, tokenId, value);554 const events = await submitTransactionAsync(accountApproved, transferFromTx);555 const result = getCreateItemResult(events);556 // tslint:disable-next-line:no-unused-expression557 expect(result.success).to.be.true;558 if (type === 'NFT') {559 const nftItemData = await api.query.nft.nftItemList(collectionId, tokenId) as unknown as ITokenDataType;560 expect(nftItemData.Owner.toString()).to.be.equal(accountTo.address);561 }562 if (type === 'Fungible') {563 const balanceAfter = await api.query.nft.balance(collectionId, accountTo.address) as unknown as BN;564 expect(balanceAfter.sub(balanceBefore).toString()).to.be.equal(value.toString());565 }566 if (type === 'ReFungible') {567 const nftItemData =568 await api.query.nft.reFungibleItemList(collectionId, tokenId) as unknown as IReFungibleTokenDataType;569 expect(nftItemData.Owner[0].Owner.toString()).to.be.equal(accountTo.address);570 expect(nftItemData.Owner[0].Fraction.toNumber()).to.be.equal(value);571 }572 });573}574575export async function576transferFromExpectFail(collectionId: number,577 tokenId: number,578 accountApproved: IKeyringPair,579 accountFrom: IKeyringPair,580 accountTo: IKeyringPair,581 value: number | bigint = 1) {582 await usingApi(async (api: ApiPromise) => {583 const transferFromTx = await api.tx.nft.transferFrom(584 accountFrom.address, accountTo.address, collectionId, tokenId, value);585 const events = await expect(submitTransactionExpectFailAsync(accountApproved, transferFromTx)).to.be.rejected;586 const result = getCreateCollectionResult(events);587 // tslint:disable-next-line:no-unused-expression588 expect(result.success).to.be.false;589 });590}591592export async function593transferExpectSuccess(collectionId: number,594 tokenId: number,595 sender: IKeyringPair,596 recipient: IKeyringPair,597 value: number | bigint = 1,598 type: string = 'NFT') {599 await usingApi(async (api: ApiPromise) => {600 let balanceBefore = new BN(0);601 if (type === 'Fungible') {602 balanceBefore = await api.query.nft.balance(collectionId, recipient.address) as unknown as BN;603 }604 const transferTx = await api.tx.nft.transfer(recipient.address, collectionId, tokenId, value);605 const events = await submitTransactionAsync(sender, transferTx);606 const result = getCreateItemResult(events);607 // tslint:disable-next-line:no-unused-expression608 expect(result.success).to.be.true;609 if (type === 'NFT') {610 const nftItemData = await api.query.nft.nftItemList(collectionId, tokenId) as unknown as ITokenDataType;611 expect(nftItemData.Owner.toString()).to.be.equal(recipient.address);612 }613 if (type === 'Fungible') {614 const balanceAfter = await api.query.nft.balance(collectionId, recipient.address) as unknown as BN;615 expect(balanceAfter.sub(balanceBefore).toString()).to.be.equal(value.toString());616 }617 if (type === 'ReFungible') {618 const nftItemData =619 await api.query.nft.reFungibleItemList(collectionId, tokenId) as unknown as IReFungibleTokenDataType;620 expect(nftItemData.Owner[0].Owner.toString()).to.be.equal(recipient.address);621 expect(nftItemData.Owner[0].Fraction.toNumber()).to.be.equal(value);622 }623 });624}625626export async function627transferExpectFail(collectionId: number,628 tokenId: number,629 sender: IKeyringPair,630 recipient: IKeyringPair,631 value: number | bigint = 1,632 type: string = 'NFT') {633 await usingApi(async (api: ApiPromise) => {634 const transferTx = await api.tx.nft.transfer(recipient.address, collectionId, tokenId, value);635 const events = await expect(submitTransactionExpectFailAsync(sender, transferTx)).to.be.rejected;636 if (events && Array.isArray(events)) {637 const result = getCreateCollectionResult(events);638 // tslint:disable-next-line:no-unused-expression639 expect(result.success).to.be.false;640 }641 });642}643644export async function645approveExpectFail(collectionId: number,646 tokenId: number, owner: IKeyringPair, approved: IKeyringPair, amount: number | bigint = 1) {647 await usingApi(async (api: ApiPromise) => {648 const approveNftTx = await api.tx.nft.approve(approved.address, collectionId, tokenId, amount);649 const events = await expect(submitTransactionExpectFailAsync(owner, approveNftTx)).to.be.rejected;650 const result = getCreateCollectionResult(events);651 // tslint:disable-next-line:no-unused-expression652 expect(result.success).to.be.false;653 });654}655656export async function getFungibleBalance(657 collectionId: number,658 owner: string,659) {660 return await usingApi(async (api) => {661 const response = (await api.query.nft.fungibleItemList(collectionId, owner)).toJSON() as unknown as {Value: string};662 return BigInt(response.Value);663 });664}665666export async function createFungibleItemExpectSuccess(667 sender: IKeyringPair,668 collectionId: number,669 data: CreateFungibleData,670 owner: string = sender.address,671) {672 return await usingApi(async (api) => {673 const tx = api.tx.nft.createItem(collectionId, owner, { Fungible: data });674675 const events = await submitTransactionAsync(sender, tx);676 const result = getCreateItemResult(events);677678 expect(result.success).to.be.true;679 return result.itemId;680 });681}682683export async function createItemExpectSuccess(684 sender: IKeyringPair, collectionId: number, createMode: string, owner: string = '') {685 let newItemId: number = 0;686 await usingApi(async (api) => {687 const AItemCount = parseInt((await api.query.nft.itemListIndex(collectionId)).toString(), 10);688 const Aitem: any = (await api.query.nft.fungibleItemList(collectionId, owner)).toJSON();689 const AItemBalance = new BigNumber(Aitem.Value);690691 if (owner === '') {692 owner = sender.address;693 }694695 let tx;696 if (createMode === 'Fungible') {697 const createData = {fungible: {value: 10}};698 tx = api.tx.nft.createItem(collectionId, owner, createData);699 } else if (createMode === 'ReFungible') {700 const createData = {refungible: {const_data: [], variable_data: [], pieces: 100}};701 tx = api.tx.nft.createItem(collectionId, owner, createData);702 } else {703 tx = api.tx.nft.createItem(collectionId, owner, createMode);704 }705 const events = await submitTransactionAsync(sender, tx);706 const result = getCreateItemResult(events);707708 const BItemCount = parseInt((await api.query.nft.itemListIndex(collectionId)).toString(), 10);709 const Bitem: any = (await api.query.nft.fungibleItemList(collectionId, owner)).toJSON();710 const BItemBalance = new BigNumber(Bitem.Value);711712 // What to expect713 // tslint:disable-next-line:no-unused-expression714 expect(result.success).to.be.true;715 if (createMode === 'Fungible') {716 expect(BItemBalance.minus(AItemBalance).toNumber()).to.be.equal(10);717 } else {718 expect(BItemCount).to.be.equal(AItemCount + 1);719 }720 expect(collectionId).to.be.equal(result.collectionId);721 expect(BItemCount).to.be.equal(result.itemId);722 newItemId = result.itemId;723 });724 return newItemId;725}726727export async function createItemExpectFailure(728 sender: IKeyringPair, collectionId: number, createMode: string, owner: string = sender.address) {729 await usingApi(async (api) => {730 const tx = api.tx.nft.createItem(collectionId, owner, createMode);731 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;732 const result = getCreateItemResult(events);733734 expect(result.success).to.be.false;735 });736}737738export async function setPublicAccessModeExpectSuccess(739 sender: IKeyringPair, collectionId: number,740 accessMode: 'Normal' | 'WhiteList',741) {742 await usingApi(async (api) => {743744 // Run the transaction745 const tx = api.tx.nft.setPublicAccessMode(collectionId, accessMode);746 const events = await submitTransactionAsync(sender, tx);747 const result = getGenericResult(events);748749 // Get the collection750 const collection: any = (await api.query.nft.collection(collectionId)).toJSON();751752 // What to expect753 // tslint:disable-next-line:no-unused-expression754 expect(result.success).to.be.true;755 expect(collection.Access).to.be.equal(accessMode);756 });757}758759export async function enableWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number) {760 await setPublicAccessModeExpectSuccess(sender, collectionId, 'WhiteList');761}762763export async function disableWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number) {764 await setPublicAccessModeExpectSuccess(sender, collectionId, 'Normal');765}766767export async function setMintPermissionExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {768 await usingApi(async (api) => {769770 // Run the transaction771 const tx = api.tx.nft.setMintPermission(collectionId, enabled);772 const events = await submitTransactionAsync(sender, tx);773 const result = getGenericResult(events);774775 // Get the collection776 const collection: any = (await api.query.nft.collection(collectionId)).toJSON();777778 // What to expect779 // tslint:disable-next-line:no-unused-expression780 expect(result.success).to.be.true;781 expect(collection.MintMode).to.be.equal(enabled);782 });783}784785export async function enablePublicMintingExpectSuccess(sender: IKeyringPair, collectionId: number) {786 await setMintPermissionExpectSuccess(sender, collectionId, true);787}788789export async function setMintPermissionExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {790 await usingApi(async (api) => {791 // Run the transaction792 const tx = api.tx.nft.setMintPermission(collectionId, enabled);793 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;794 const result = getCreateCollectionResult(events);795 // tslint:disable-next-line:no-unused-expression796 expect(result.success).to.be.false;797 });798}799800export async function isWhitelisted(collectionId: number, address: string) {801 let whitelisted: boolean = false;802 await usingApi(async (api) => {803 whitelisted = (await api.query.nft.whiteList(collectionId, address)).toJSON() as unknown as boolean;804 });805 return whitelisted;806}807808export async function addToWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number, address: string) {809 await usingApi(async (api) => {810811 const whiteListedBefore = (await api.query.nft.whiteList(collectionId, address)).toJSON();812813 // Run the transaction814 const tx = api.tx.nft.addToWhiteList(collectionId, address);815 const events = await submitTransactionAsync(sender, tx);816 const result = getGenericResult(events);817818 const whiteListedAfter = (await api.query.nft.whiteList(collectionId, address)).toJSON();819820 // What to expect821 // tslint:disable-next-line:no-unused-expression822 expect(result.success).to.be.true;823 // tslint:disable-next-line: no-unused-expression824 expect(whiteListedBefore).to.be.false;825 // tslint:disable-next-line: no-unused-expression826 expect(whiteListedAfter).to.be.true;827 });828}829830export async function removeFromWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number, address: string) {831 await usingApi(async (api) => {832 // Run the transaction833 const tx = api.tx.nft.removeFromWhiteList(collectionId, address);834 const events = await submitTransactionAsync(sender, tx);835 const result = getGenericResult(events);836837 // What to expect838 // tslint:disable-next-line:no-unused-expression839 expect(result.success).to.be.true;840 });841}842843export async function removeFromWhiteListExpectFailure(sender: IKeyringPair, collectionId: number, address: string) {844 await usingApi(async (api) => {845 // Run the transaction846 const tx = api.tx.nft.removeFromWhiteList(collectionId, address);847 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;848 const result = getGenericResult(events);849850 // What to expect851 // tslint:disable-next-line:no-unused-expression852 expect(result.success).to.be.false;853 });854}855856export const getDetailedCollectionInfo = async (api: ApiPromise, collectionId: number)857 : Promise<ICollectionInterface | null> => {858 return await api.query.nft.collection(collectionId) as unknown as ICollectionInterface;859};860861export const getCreatedCollectionCount = async (api: ApiPromise): Promise<number> => {862 // set global object - collectionsCount863 return (await api.query.nft.createdCollectionCount() as unknown as BN).toNumber();864};