123456import chai from 'chai';7import chaiAsPromised from 'chai-as-promised';8import type { AccountId, EventRecord } from '@polkadot/types/interfaces';9import { ApiPromise, Keyring } from "@polkadot/api";10import { default as usingApi, submitTransactionAsync, submitTransactionExpectFailAsync } from "../substrate/substrate-api";11import privateKey from '../substrate/privateKey';12import { alicesPublicKey, nullPublicKey } from "../accounts";13import { strToUTF16, utf16ToStr, hexToStr } from './util';14import { IKeyringPair } from '@polkadot/types/types';15import { BigNumber } from 'bignumber.js';16import { Struct, Enum } from '@polkadot/types/codec';17import { u128 } from '@polkadot/types/primitive';18import { ICollectionInterface } from '../types';19import BN from "bn.js";2021chai.use(chaiAsPromised);22const expect = chai.expect;2324type GenericResult = {25 success: boolean,26};2728type CreateCollectionResult = {29 success: boolean,30 collectionId: number31};3233type CreateItemResult = {34 success: boolean,35 collectionId: number,36 itemId: number37};3839export function getGenericResult(events: EventRecord[]): GenericResult {40 let result: GenericResult = {41 success: false42 }43 events.forEach(({ phase, event: { data, method, section } }) => {44 45 if (method == 'ExtrinsicSuccess') {46 result.success = true;47 }48 });49 return result;50}5152export function getCreateCollectionResult(events: EventRecord[]): CreateCollectionResult {53 let success = false;54 let collectionId: number = 0;55 events.forEach(({ phase, event: { data, method, section } }) => {56 57 if (method == 'ExtrinsicSuccess') {58 success = true;59 } else if ((section == 'nft') && (method == 'Created')) {60 collectionId = parseInt(data[0].toString());61 }62 });63 let result: CreateCollectionResult = {64 success,65 collectionId66 }67 return result;68}6970export function getCreateItemResult(events: EventRecord[]): CreateItemResult {71 let success = false;72 let collectionId: number = 0;73 let itemId: number = 0;74 events.forEach(({ phase, event: { data, method, section } }) => {75 76 if (method == 'ExtrinsicSuccess') {77 success = true;78 } else if ((section == 'nft') && (method == 'ItemCreated')) {79 collectionId = parseInt(data[0].toString());80 itemId = parseInt(data[1].toString());81 }82 });83 let result: CreateItemResult = {84 success,85 collectionId,86 itemId87 }88 return result;89}9091interface Invalid {92 type: 'Invalid'93}9495interface Nft {96 type: 'NFT'97}9899interface Fungible {100 type: 'Fungible',101 decimalPoints: number102}103104interface ReFungible {105 type: 'ReFungible',106 decimalPoints: number107}108109type CollectionMode = Nft | Fungible | ReFungible | Invalid;110111export type CreateCollectionParams = {112 mode: CollectionMode,113 name: string,114 description: string,115 tokenPrefix: string116};117118const defaultCreateCollectionParams: CreateCollectionParams = {119 name: 'name',120 description: 'description',121 mode: { type: "NFT" },122 tokenPrefix: 'prefix'123}124125export async function createCollectionExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {126 const {name, description, mode, tokenPrefix } = {...defaultCreateCollectionParams, ...params};127128 let collectionId: number = 0;129 await usingApi(async (api) => {130 131 const AcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString());132133 134 const alicePrivateKey = privateKey('//Alice');135136 let modeprm = {};137 if (mode.type == 'NFT') {138 modeprm = {nft: null};139 }140 else if (mode.type == 'Fungible') {141 modeprm = {fungible: mode.decimalPoints};142 }143 else if (mode.type == 'ReFungible') {144 modeprm = {refungible: mode.decimalPoints};145 }146 else if (mode.type == 'Invalid') {147 modeprm = {invalid: null};148 }149150 const tx = api.tx.nft.createCollection(strToUTF16(name), strToUTF16(description), strToUTF16(tokenPrefix), modeprm);151 const events = await submitTransactionAsync(alicePrivateKey, tx);152 const result = getCreateCollectionResult(events);153154 155 const BcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString());156157 158 const collection: any = (await api.query.nft.collection(result.collectionId)).toJSON();159160 161 expect(result.success).to.be.true;162 expect(result.collectionId).to.be.equal(BcollectionCount);163 expect(collection).to.be.not.null;164 expect(BcollectionCount).to.be.equal(AcollectionCount+1, 'Error: NFT collection NOT created.');165 expect(collection.Owner).to.be.equal(alicesPublicKey);166 expect(utf16ToStr(collection.Name)).to.be.equal(name);167 expect(utf16ToStr(collection.Description)).to.be.equal(description);168 expect(hexToStr(collection.TokenPrefix)).to.be.equal(tokenPrefix);169170 collectionId = result.collectionId;171 });172173 return collectionId;174}175 176export async function createCollectionExpectFailure(params: Partial<CreateCollectionParams> = {}) {177 const {name, description, mode, tokenPrefix } = {...defaultCreateCollectionParams, ...params};178179 await usingApi(async (api) => {180 181 const AcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString());182183 184 const alicePrivateKey = privateKey('//Alice');185 const tx = api.tx.nft.createCollection(strToUTF16(name), strToUTF16(description), strToUTF16(tokenPrefix), mode);186 const events = await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;187 const result = getCreateCollectionResult(events);188189 190 const BcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString());191192 193 expect(result.success).to.be.false;194 expect(BcollectionCount).to.be.equal(AcollectionCount, 'Error: Collection with incorrect data created.');195 });196}197 198export async function findUnusedAddress(api: ApiPromise): Promise<IKeyringPair> {199 let bal = new BigNumber(0);200 let unused;201 do {202 const randomSeed = 'seed' + Math.floor(Math.random() * Math.floor(10000));203 const keyring = new Keyring({ type: 'sr25519' });204 unused = keyring.addFromUri(`//${randomSeed}`);205 bal = new BigNumber((await api.query.system.account(unused.address)).data.free.toString());206 } while (bal.toFixed() != '0');207 return unused; 208}209210function getDestroyResult(events: EventRecord[]): boolean {211 let success: boolean = false;212 events.forEach(({ phase, event: { data, method, section } }) => {213 214 if (method == 'ExtrinsicSuccess') {215 success = true;216 }217 });218 return success;219}220221export async function destroyCollectionExpectFailure(collectionId: number, senderSeed: string = '//Alice') {222 await usingApi(async (api) => {223 224 const alicePrivateKey = privateKey(senderSeed);225 const tx = api.tx.nft.destroyCollection(collectionId);226 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;227 });228}229230export async function destroyCollectionExpectSuccess(collectionId: number, senderSeed: string = '//Alice') {231 await usingApi(async (api) => {232 233 const alicePrivateKey = privateKey(senderSeed);234 const tx = api.tx.nft.destroyCollection(collectionId);235 const events = await submitTransactionAsync(alicePrivateKey, tx);236 const result = getDestroyResult(events);237238 239 const collection: any = (await api.query.nft.collection(collectionId)).toJSON();240241 242 expect(result).to.be.true;243 expect(collection).to.be.not.null;244 expect(collection.Owner).to.be.equal(nullPublicKey);245 });246}247248export async function setCollectionSponsorExpectSuccess(collectionId: number, sponsor: string) {249 await usingApi(async (api) => {250251 252 const alicePrivateKey = privateKey('//Alice');253 const tx = api.tx.nft.setCollectionSponsor(collectionId, sponsor);254 const events = await submitTransactionAsync(alicePrivateKey, tx);255 const result = getGenericResult(events);256257 258 const collection: any = (await api.query.nft.collection(collectionId)).toJSON();259260 261 expect(result.success).to.be.true;262 expect(collection.Sponsor.toString()).to.be.equal(sponsor.toString());263 expect(collection.SponsorConfirmed).to.be.false;264 });265}266267export async function removeCollectionSponsorExpectSuccess(collectionId: number) {268 await usingApi(async (api) => {269270 271 const alicePrivateKey = privateKey('//Alice');272 const tx = api.tx.nft.removeCollectionSponsor(collectionId);273 const events = await submitTransactionAsync(alicePrivateKey, tx);274 const result = getGenericResult(events);275276 277 const collection: any = (await api.query.nft.collection(collectionId)).toJSON();278279 280 expect(result.success).to.be.true;281 expect(collection.Sponsor).to.be.equal(nullPublicKey);282 expect(collection.SponsorConfirmed).to.be.false;283 });284}285286export async function removeCollectionSponsorExpectFailure(collectionId: number) {287 await usingApi(async (api) => {288289 290 const alicePrivateKey = privateKey('//Alice');291 const tx = api.tx.nft.removeCollectionSponsor(collectionId);292 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;293 });294}295296export async function setCollectionSponsorExpectFailure(collectionId: number, sponsor: string, senderSeed: string = '//Alice') {297 await usingApi(async (api) => {298299 300 const alicePrivateKey = privateKey(senderSeed);301 const tx = api.tx.nft.setCollectionSponsor(collectionId, sponsor);302 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;303 });304}305306export async function confirmSponsorshipExpectSuccess(collectionId: number, senderSeed: string = '//Alice') {307 await usingApi(async (api) => {308309 310 const sender = privateKey(senderSeed);311 const tx = api.tx.nft.confirmSponsorship(collectionId);312 const events = await submitTransactionAsync(sender, tx);313 const result = getGenericResult(events);314315 316 const collection: any = (await api.query.nft.collection(collectionId)).toJSON();317318 319 expect(result.success).to.be.true;320 expect(collection.Sponsor).to.be.equal(sender.address);321 expect(collection.SponsorConfirmed).to.be.true;322 });323}324325export async function confirmSponsorshipExpectFailure(collectionId: number, senderSeed: string = '//Alice') {326 await usingApi(async (api) => {327328 329 const sender = privateKey(senderSeed);330 const tx = api.tx.nft.confirmSponsorship(collectionId);331 await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;332 });333}334335export interface CreateFungibleData extends Struct {336 readonly value: u128;337};338339export interface CreateReFungibleData extends Struct {};340export interface CreateNftData extends Struct {};341342export interface CreateItemData extends Enum {343 NFT: CreateNftData,344 Fungible: CreateFungibleData,345 ReFungible: CreateReFungibleData346};347348export async function createItemExpectSuccess(sender: IKeyringPair, collectionId: number, createMode: string, owner: string = '') {349 let newItemId: number = 0;350 await usingApi(async (api) => {351 const AItemCount = parseInt((await api.query.nft.itemListIndex(collectionId)).toString());352 const Aitem: any = (await api.query.nft.fungibleItemList(collectionId, owner)).toJSON(); 353 const AItemBalance = new BigNumber(Aitem.Value);354355 if (owner === '') owner = sender.address;356357 let tx;358 if (createMode == 'Fungible') {359 let createData = {fungible: {value: 10}};360 tx = api.tx.nft.createItem(collectionId, owner, createData);361 }362 else {363 tx = api.tx.nft.createItem(collectionId, owner, createMode);364 }365 const events = await submitTransactionAsync(sender, tx);366 const result = getCreateItemResult(events);367368 const BItemCount = parseInt((await api.query.nft.itemListIndex(collectionId)).toString());369 const Bitem: any = (await api.query.nft.fungibleItemList(collectionId, owner)).toJSON(); 370 const BItemBalance = new BigNumber(Bitem.Value);371372 373 expect(result.success).to.be.true;374 if (createMode == 'Fungible') {375 expect(BItemBalance.minus(AItemBalance).toNumber()).to.be.equal(10);376 }377 else {378 expect(BItemCount).to.be.equal(AItemCount+1);379 }380 expect(collectionId).to.be.equal(result.collectionId);381 expect(BItemCount).to.be.equal(result.itemId);382 newItemId = result.itemId;383 });384 return newItemId;385}386387export async function enableWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number) {388 await usingApi(async (api) => {389390 391 const tx = api.tx.nft.setPublicAccessMode(collectionId, 'WhiteList');392 const events = await submitTransactionAsync(sender, tx);393 const result = getGenericResult(events);394395 396 const collection: any = (await api.query.nft.collection(collectionId)).toJSON();397398 399 expect(result.success).to.be.true;400 expect(collection.Access).to.be.equal('WhiteList');401 });402}403404export async function enablePublicMintingExpectSuccess(sender: IKeyringPair, collectionId: number) {405 await usingApi(async (api) => {406407 408 const tx = api.tx.nft.setMintPermission(collectionId, true);409 const events = await submitTransactionAsync(sender, tx);410 const result = getGenericResult(events);411412 413 const collection: any = (await api.query.nft.collection(collectionId)).toJSON();414415 416 expect(result.success).to.be.true;417 expect(collection.MintMode).to.be.equal(true);418 });419}420421export async function addToWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number, address: string) {422 await usingApi(async (api) => {423424 425 const tx = api.tx.nft.addToWhiteList(collectionId, address);426 const events = await submitTransactionAsync(sender, tx);427 const result = getGenericResult(events);428429 430 const collection: any = (await api.query.nft.collection(collectionId)).toJSON();431432 433 expect(result.success).to.be.true;434 expect(collection.MintMode).to.be.equal(true);435 });436}437438export const getDetailedCollectionInfo = async (api: ApiPromise, collectionId: number)439 : Promise<ICollectionInterface | null> => {440 return await api.query.nft.collection(collectionId) as unknown as ICollectionInterface;441};442443export const getCreatedCollectionCount = async (api: ApiPromise): Promise<number> => {444 445 return (await api.query.nft.createdCollectionCount() as unknown as BN).toNumber();446};