difftreelog
tests: add createItemExpectFailure helper
in: master
1 file changed
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;2324type GenericResult = {25 success: boolean,26};2728interface CreateCollectionResult {29 success: boolean;30 collectionId: number;31}3233interface CreateItemResult {34 success: boolean;35 collectionId: number;36 itemId: number;37}3839interface IReFungibleOwner {40 Fraction: BN;41 Owner: number[];42}4344interface ITokenDataType {45 Owner: number[];46 ConstData: number[];47 VariableData: number[];48}4950interface IFungibleTokenDataType {51 Value: BN;52}5354interface IReFungibleTokenDataType {55 Owner: IReFungibleOwner[];56 ConstData: number[];57 VariableData: number[];58}5960export function getGenericResult(events: EventRecord[]): GenericResult {61 const result: GenericResult = {62 success: false,63 };64 events.forEach(({ phase, event: { data, method, section } }) => {65 // console.log(` ${phase}: ${section}.${method}:: ${data}`);66 if (method === 'ExtrinsicSuccess') {67 result.success = true;68 }69 });70 return result;71}7273export function getCreateCollectionResult(events: EventRecord[]): CreateCollectionResult {74 let success = false;75 let collectionId: number = 0;76 events.forEach(({ phase, event: { data, method, section } }) => {77 // console.log(` ${phase}: ${section}.${method}:: ${data}`);78 if (method == 'ExtrinsicSuccess') {79 success = true;80 } else if ((section == 'nft') && (method == 'Created')) {81 collectionId = parseInt(data[0].toString());82 }83 });84 const result: CreateCollectionResult = {85 success,86 collectionId,87 };88 return result;89}9091export function getCreateItemResult(events: EventRecord[]): CreateItemResult {92 let success = false;93 let collectionId: number = 0;94 let itemId: number = 0;95 events.forEach(({ phase, event: { data, method, section } }) => {96 // console.log(` ${phase}: ${section}.${method}:: ${data}`);97 if (method == 'ExtrinsicSuccess') {98 success = true;99 } else if ((section == 'nft') && (method == 'ItemCreated')) {100 collectionId = parseInt(data[0].toString());101 itemId = parseInt(data[1].toString());102 }103 });104 const result: CreateItemResult = {105 success,106 collectionId,107 itemId,108 };109 return result;110}111112interface Invalid {113 type: 'Invalid';114}115116interface Nft {117 type: 'NFT';118}119120interface Fungible {121 type: 'Fungible';122 decimalPoints: number;123}124125interface ReFungible {126 type: 'ReFungible';127 decimalPoints: number;128}129130interface Nft {131 type: 'NFT'132}133134interface Fungible {135 type: 'Fungible',136 decimalPoints: number137}138139interface ReFungible {140 type: 'ReFungible',141 decimalPoints: number142}143144type CollectionMode = Nft | Fungible | ReFungible | Invalid;145146export type CreateCollectionParams = {147 mode: CollectionMode,148 name: string,149 description: string,150 tokenPrefix: string,151};152153const defaultCreateCollectionParams: CreateCollectionParams = {154 description: 'description',155 mode: { type: 'NFT' },156 name: 'name',157 tokenPrefix: 'prefix',158}159160export async function createCollectionExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {161 const {name, description, mode, tokenPrefix } = {...defaultCreateCollectionParams, ...params};162163 let collectionId: number = 0;164 await usingApi(async (api) => {165 // Get number of collections before the transaction166 const AcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString(), 10);167168 // Run the CreateCollection transaction169 const alicePrivateKey = privateKey('//Alice');170171 let modeprm = {};172 if (mode.type === 'NFT') {173 modeprm = {nft: null};174 } else if (mode.type === 'Fungible') {175 modeprm = {fungible: mode.decimalPoints};176 } else if (mode.type === 'ReFungible') {177 modeprm = {refungible: mode.decimalPoints};178 } else if (mode.type === 'Invalid') {179 modeprm = {invalid: null};180 }181182 const tx = api.tx.nft.createCollection(strToUTF16(name), strToUTF16(description), strToUTF16(tokenPrefix), modeprm);183 const events = await submitTransactionAsync(alicePrivateKey, tx);184 const result = getCreateCollectionResult(events);185186 // Get number of collections after the transaction187 const BcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString(), 10);188189 // Get the collection190 const collection: any = (await api.query.nft.collection(result.collectionId)).toJSON();191192 // What to expect193 // tslint:disable-next-line:no-unused-expression194 expect(result.success).to.be.true;195 expect(result.collectionId).to.be.equal(BcollectionCount);196 // tslint:disable-next-line:no-unused-expression197 expect(collection).to.be.not.null;198 expect(BcollectionCount).to.be.equal(AcollectionCount + 1, 'Error: NFT collection NOT created.');199 expect(collection.Owner).to.be.equal(alicesPublicKey);200 expect(utf16ToStr(collection.Name)).to.be.equal(name);201 expect(utf16ToStr(collection.Description)).to.be.equal(description);202 expect(hexToStr(collection.TokenPrefix)).to.be.equal(tokenPrefix);203204 collectionId = result.collectionId;205 });206207 return collectionId;208}209210export async function createCollectionExpectFailure(params: Partial<CreateCollectionParams> = {}) {211 const {name, description, mode, tokenPrefix } = {...defaultCreateCollectionParams, ...params};212213 let modeprm = {};214 if (mode.type === 'NFT') {215 modeprm = {nft: null};216 } else if (mode.type === 'Fungible') {217 modeprm = {fungible: mode.decimalPoints};218 } else if (mode.type === 'ReFungible') {219 modeprm = {refungible: mode.decimalPoints};220 } else if (mode.type === 'Invalid') {221 modeprm = {invalid: null};222 }223224 await usingApi(async (api) => {225 // Get number of collections before the transaction226 const AcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString());227228 // Run the CreateCollection transaction229 const alicePrivateKey = privateKey('//Alice');230 const tx = api.tx.nft.createCollection(strToUTF16(name), strToUTF16(description), strToUTF16(tokenPrefix), modeprm);231 const events = await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;232 const result = getCreateCollectionResult(events);233234 // Get number of collections after the transaction235 const BcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString());236237 // What to expect238 // tslint:disable-next-line:no-unused-expression239 expect(result.success).to.be.false;240 expect(BcollectionCount).to.be.equal(AcollectionCount, 'Error: Collection with incorrect data created.');241 });242}243244export async function findUnusedAddress(api: ApiPromise): Promise<IKeyringPair> {245 let bal = new BigNumber(0);246 let unused;247 do {248 const randomSeed = 'seed' + Math.floor(Math.random() * Math.floor(10000));249 const keyring = new Keyring({ type: 'sr25519' });250 unused = keyring.addFromUri(`//${randomSeed}`);251 bal = new BigNumber((await api.query.system.account(unused.address)).data.free.toString());252 } while (bal.toFixed() != '0');253 return unused;254}255256export async function findNotExistingCollection(api: ApiPromise): Promise<number> {257 const totalNumber = parseInt((await api.query.nft.createdCollectionCount()).toString(), 10) as unknown as number;258 const newCollection: number = totalNumber + 1;259 return newCollection;260}261262function getDestroyResult(events: EventRecord[]): boolean {263 let success: boolean = false;264 events.forEach(({ phase, event: { data, method, section } }) => {265 // console.log(` ${phase}: ${section}.${method}:: ${data}`);266 if (method == 'ExtrinsicSuccess') {267 success = true;268 }269 });270 return success;271}272273export async function destroyCollectionExpectFailure(collectionId: number, senderSeed: string = '//Alice') {274 await usingApi(async (api) => {275 // Run the DestroyCollection transaction276 const alicePrivateKey = privateKey(senderSeed);277 const tx = api.tx.nft.destroyCollection(collectionId);278 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;279 });280}281282export async function destroyCollectionExpectSuccess(collectionId: number, senderSeed: string = '//Alice') {283 await usingApi(async (api) => {284 // Run the DestroyCollection transaction285 const alicePrivateKey = privateKey(senderSeed);286 const tx = api.tx.nft.destroyCollection(collectionId);287 const events = await submitTransactionAsync(alicePrivateKey, tx);288 const result = getDestroyResult(events);289290 // Get the collection291 const collection: any = (await api.query.nft.collection(collectionId)).toJSON();292293 // What to expect294 expect(result).to.be.true;295 expect(collection).to.be.not.null;296 expect(collection.Owner).to.be.equal(nullPublicKey);297 });298}299300export async function setCollectionSponsorExpectSuccess(collectionId: number, sponsor: string) {301 await usingApi(async (api) => {302303 // Run the transaction304 const alicePrivateKey = privateKey('//Alice');305 const tx = api.tx.nft.setCollectionSponsor(collectionId, sponsor);306 const events = await submitTransactionAsync(alicePrivateKey, tx);307 const result = getGenericResult(events);308309 // Get the collection310 const collection: any = (await api.query.nft.collection(collectionId)).toJSON();311312 // What to expect313 expect(result.success).to.be.true;314 expect(collection.Sponsor.toString()).to.be.equal(sponsor.toString());315 expect(collection.SponsorConfirmed).to.be.false;316 });317}318319export async function removeCollectionSponsorExpectSuccess(collectionId: number) {320 await usingApi(async (api) => {321322 // Run the transaction323 const alicePrivateKey = privateKey('//Alice');324 const tx = api.tx.nft.removeCollectionSponsor(collectionId);325 const events = await submitTransactionAsync(alicePrivateKey, tx);326 const result = getGenericResult(events);327328 // Get the collection329 const collection: any = (await api.query.nft.collection(collectionId)).toJSON();330331 // What to expect332 expect(result.success).to.be.true;333 expect(collection.Sponsor).to.be.equal(nullPublicKey);334 expect(collection.SponsorConfirmed).to.be.false;335 });336}337338export async function removeCollectionSponsorExpectFailure(collectionId: number) {339 await usingApi(async (api) => {340341 // Run the transaction342 const alicePrivateKey = privateKey('//Alice');343 const tx = api.tx.nft.removeCollectionSponsor(collectionId);344 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;345 });346}347348export async function setCollectionSponsorExpectFailure(collectionId: number, sponsor: string, senderSeed: string = '//Alice') {349 await usingApi(async (api) => {350351 // Run the transaction352 const alicePrivateKey = privateKey(senderSeed);353 const tx = api.tx.nft.setCollectionSponsor(collectionId, sponsor);354 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;355 });356}357358export async function confirmSponsorshipExpectSuccess(collectionId: number, senderSeed: string = '//Alice') {359 await usingApi(async (api) => {360361 // Run the transaction362 const sender = privateKey(senderSeed);363 const tx = api.tx.nft.confirmSponsorship(collectionId);364 const events = await submitTransactionAsync(sender, tx);365 const result = getGenericResult(events);366367 // Get the collection368 const collection: any = (await api.query.nft.collection(collectionId)).toJSON();369370 // What to expect371 expect(result.success).to.be.true;372 expect(collection.Sponsor).to.be.equal(sender.address);373 expect(collection.SponsorConfirmed).to.be.true;374 });375}376377export async function confirmSponsorshipExpectFailure(collectionId: number, senderSeed: string = '//Alice') {378 await usingApi(async (api) => {379380 // Run the transaction381 const sender = privateKey(senderSeed);382 const tx = api.tx.nft.confirmSponsorship(collectionId);383 await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;384 });385}386387export interface CreateFungibleData extends Struct {388 readonly value: u128;389}390391export interface CreateReFungibleData extends Struct {}392export interface CreateNftData extends Struct {}393394export interface CreateItemData extends Enum {395 NFT: CreateNftData;396 Fungible: CreateFungibleData;397 ReFungible: CreateReFungibleData;398}399400export async function burnItemExpectSuccess(owner: IKeyringPair, collectionId: number, tokenId: number, value = 0) {401 await usingApi(async (api) => {402 const tx = api.tx.nft.burnItem(collectionId, tokenId, value);403 const events = await submitTransactionAsync(owner, tx);404 const result = getGenericResult(events);405 // Get the item406 const item: any = (await api.query.nft.nftItemList(collectionId, tokenId)).toJSON();407 // What to expect408 // tslint:disable-next-line:no-unused-expression409 expect(result.success).to.be.true;410 // tslint:disable-next-line:no-unused-expression411 expect(item).to.be.not.null;412 expect(item.Owner).to.be.equal(nullPublicKey);413 });414}415416export async function417approveExpectSuccess(collectionId: number,418 tokenId: number, owner: IKeyringPair, approved: IKeyringPair, amount: number = 1) {419 await usingApi(async (api: ApiPromise) => {420 const allowanceBefore =421 await api.query.nft.allowances(collectionId, [tokenId, owner.address, approved.address]) as unknown as BN;422 const approveNftTx = await api.tx.nft.approve(approved.address, collectionId, tokenId, amount);423 const events = await submitTransactionAsync(owner, approveNftTx);424 const result = getCreateItemResult(events);425 // tslint:disable-next-line:no-unused-expression426 expect(result.success).to.be.true;427 const allowanceAfter =428 await api.query.nft.allowances(collectionId, [tokenId, owner.address, approved.address]) as unknown as BN;429 expect(allowanceAfter.toNumber() - allowanceBefore.toNumber()).to.be.equal(amount);430 });431}432433export async function434transferFromExpectSuccess(collectionId: number,435 tokenId: number,436 accountApproved: IKeyringPair,437 accountFrom: IKeyringPair,438 accountTo: IKeyringPair,439 value: number = 1,440 type: string = 'NFT') {441 await usingApi(async (api: ApiPromise) => {442 let balanceBefore = new BN(0);443 if (type === 'Fungible') {444 balanceBefore = await api.query.nft.balance(collectionId, accountTo.address) as unknown as BN;445 }446 const transferFromTx = await api.tx.nft.transferFrom(447 accountFrom.address, accountTo.address, collectionId, tokenId, value);448 const events = await submitTransactionAsync(accountFrom, transferFromTx);449 const result = getCreateItemResult(events);450 // tslint:disable-next-line:no-unused-expression451 expect(result.success).to.be.true;452 if (type === 'NFT') {453 const nftItemData = await api.query.nft.nftItemList(collectionId, tokenId) as unknown as ITokenDataType;454 expect(nftItemData.Owner.toString()).to.be.equal(accountTo.address);455 }456 if (type === 'Fungible') {457 const balanceAfter = await api.query.nft.balance(collectionId, accountTo.address) as unknown as BN;458 expect(balanceAfter.sub(balanceBefore).toNumber()).to.be.equal(value);459 }460 if (type === 'ReFungible') {461 const nftItemData =462 await api.query.nft.reFungibleItemList(collectionId, tokenId) as unknown as IReFungibleTokenDataType;463 expect(nftItemData.Owner[0].Owner.toString()).to.be.equal(accountTo.address);464 expect(nftItemData.Owner[0].Fraction.toNumber()).to.be.equal(value);465 }466 });467}468469export async function470transferFromExpectFail(collectionId: number,471 tokenId: number,472 accountApproved: IKeyringPair,473 accountFrom: IKeyringPair,474 accountTo: IKeyringPair,475 value: number = 1) {476 await usingApi(async (api: ApiPromise) => {477 const transferFromTx = await api.tx.nft.transferFrom(478 accountFrom.address, accountTo.address, collectionId, tokenId, value);479 const events = await expect(submitTransactionExpectFailAsync(accountApproved, transferFromTx)).to.be.rejected;480 const result = getCreateCollectionResult(events);481 // tslint:disable-next-line:no-unused-expression482 expect(result.success).to.be.false;483 });484}485486export async function487transferExpectSuccess(collectionId: number,488 tokenId: number,489 sender: IKeyringPair,490 recipient: IKeyringPair,491 value: number = 1,492 type: string = 'NFT') {493 await usingApi(async (api: ApiPromise) => {494 let balanceBefore = new BN(0);495 if (type === 'Fungible') {496 balanceBefore = await api.query.nft.balance(collectionId, recipient.address) as unknown as BN;497 }498 const transferTx = await api.tx.nft.transfer(recipient.address, collectionId, tokenId, value);499 const events = await submitTransactionAsync(sender, transferTx);500 const result = getCreateItemResult(events);501 // tslint:disable-next-line:no-unused-expression502 expect(result.success).to.be.true;503 if (type === 'NFT') {504 const nftItemData = await api.query.nft.nftItemList(collectionId, tokenId) as unknown as ITokenDataType;505 expect(nftItemData.Owner.toString()).to.be.equal(recipient.address);506 }507 if (type === 'Fungible') {508 const balanceAfter = await api.query.nft.balance(collectionId, recipient.address) as unknown as BN;509 expect(balanceAfter.sub(balanceBefore).toNumber()).to.be.equal(value);510 }511 if (type === 'ReFungible') {512 const nftItemData =513 await api.query.nft.reFungibleItemList(collectionId, tokenId) as unknown as IReFungibleTokenDataType;514 expect(nftItemData.Owner[0].Owner.toString()).to.be.equal(recipient.address);515 expect(nftItemData.Owner[0].Fraction.toNumber()).to.be.equal(value);516 }517 });518}519520export async function521transferExpectFail(collectionId: number,522 tokenId: number,523 sender: IKeyringPair,524 recipient: IKeyringPair,525 value: number = 1,526 type: string = 'NFT') {527 await usingApi(async (api: ApiPromise) => {528 const transferTx = await api.tx.nft.transfer(recipient.address, collectionId, tokenId, value);529 const events = await expect(submitTransactionExpectFailAsync(sender, transferTx)).to.be.rejected;530 if (events && Array.isArray(events)) {531 const result = getCreateCollectionResult(events);532 // tslint:disable-next-line:no-unused-expression533 expect(result.success).to.be.false;534 }535 });536}537538export async function539approveExpectFail(collectionId: number,540 tokenId: number, owner: IKeyringPair, approved: IKeyringPair, amount: number = 1) {541 await usingApi(async (api: ApiPromise) => {542 const approveNftTx = await api.tx.nft.approve(approved.address, collectionId, tokenId, amount);543 const events = await expect(submitTransactionExpectFailAsync(owner, approveNftTx)).to.be.rejected;544 const result = getCreateCollectionResult(events);545 // tslint:disable-next-line:no-unused-expression546 expect(result.success).to.be.false;547 });548}549550export async function createItemExpectSuccess(551 sender: IKeyringPair, collectionId: number, createMode: string, owner: string = '') {552 let newItemId: number = 0;553 await usingApi(async (api) => {554 const AItemCount = parseInt((await api.query.nft.itemListIndex(collectionId)).toString(), 10);555 const Aitem: any = (await api.query.nft.fungibleItemList(collectionId, owner)).toJSON();556 const AItemBalance = new BigNumber(Aitem.Value);557558 if (owner === '') {559 owner = sender.address;560 }561562 let tx;563 if (createMode === 'Fungible') {564 const createData = {fungible: {value: 10}};565 tx = api.tx.nft.createItem(collectionId, owner, createData);566 } else {567 tx = api.tx.nft.createItem(collectionId, owner, createMode);568 }569 const events = await submitTransactionAsync(sender, tx);570 const result = getCreateItemResult(events);571572 const BItemCount = parseInt((await api.query.nft.itemListIndex(collectionId)).toString(), 10);573 const Bitem: any = (await api.query.nft.fungibleItemList(collectionId, owner)).toJSON();574 const BItemBalance = new BigNumber(Bitem.Value);575576 // What to expect577 // tslint:disable-next-line:no-unused-expression578 expect(result.success).to.be.true;579 if (createMode === 'Fungible') {580 expect(BItemBalance.minus(AItemBalance).toNumber()).to.be.equal(10);581 } else {582 expect(BItemCount).to.be.equal(AItemCount + 1);583 }584 expect(collectionId).to.be.equal(result.collectionId);585 expect(BItemCount).to.be.equal(result.itemId);586 newItemId = result.itemId;587 });588 return newItemId;589}590591export async function enableWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number) {592 await usingApi(async (api) => {593594 // Run the transaction595 const tx = api.tx.nft.setPublicAccessMode(collectionId, 'WhiteList');596 const events = await submitTransactionAsync(sender, tx);597 const result = getGenericResult(events);598599 // Get the collection600 const collection: any = (await api.query.nft.collection(collectionId)).toJSON();601602 // What to expect603 // tslint:disable-next-line:no-unused-expression604 expect(result.success).to.be.true;605 expect(collection.Access).to.be.equal('WhiteList');606 });607}608609export async function setMintPermissionExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {610 await usingApi(async (api) => {611612 // Run the transaction613 const tx = api.tx.nft.setMintPermission(collectionId, enabled);614 const events = await submitTransactionAsync(sender, tx);615 const result = getGenericResult(events);616617 // Get the collection618 const collection: any = (await api.query.nft.collection(collectionId)).toJSON();619620 // What to expect621 // tslint:disable-next-line:no-unused-expression622 expect(result.success).to.be.true;623 expect(collection.MintMode).to.be.equal(enabled);624 });625}626627export async function enablePublicMintingExpectSuccess(sender: IKeyringPair, collectionId: number) {628 await setMintPermissionExpectSuccess(sender, collectionId, true);629}630631export async function setMintPermissionExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {632 await usingApi(async (api) => {633 // Run the transaction634 const tx = api.tx.nft.setMintPermission(collectionId, enabled);635 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;636 const result = getCreateCollectionResult(events);637 // tslint:disable-next-line:no-unused-expression638 expect(result.success).to.be.false;639 });640}641642export async function addToWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number, address: string) {643 await usingApi(async (api) => {644645 const whiteListedBefore = (await api.query.nft.whiteList(collectionId, address)).toJSON();646647 // Run the transaction648 const tx = api.tx.nft.addToWhiteList(collectionId, address);649 const events = await submitTransactionAsync(sender, tx);650 const result = getGenericResult(events);651652 const whiteListedAfter = (await api.query.nft.whiteList(collectionId, address)).toJSON();653654 // What to expect655 // tslint:disable-next-line:no-unused-expression656 expect(result.success).to.be.true;657 // tslint:disable-next-line: no-unused-expression658 expect(whiteListedBefore).to.be.false;659 // tslint:disable-next-line: no-unused-expression660 expect(whiteListedAfter).to.be.true;661 });662}663664export const getDetailedCollectionInfo = async (api: ApiPromise, collectionId: number)665 : Promise<ICollectionInterface | null> => {666 return await api.query.nft.collection(collectionId) as unknown as ICollectionInterface;667};668669export const getCreatedCollectionCount = async (api: ApiPromise): Promise<number> => {670 // set global object - collectionsCount671 return (await api.query.nft.createdCollectionCount() as unknown as BN).toNumber();672};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;2324type GenericResult = {25 success: boolean,26};2728interface CreateCollectionResult {29 success: boolean;30 collectionId: number;31}3233interface CreateItemResult {34 success: boolean;35 collectionId: number;36 itemId: number;37}3839interface IReFungibleOwner {40 Fraction: BN;41 Owner: number[];42}4344interface ITokenDataType {45 Owner: number[];46 ConstData: number[];47 VariableData: number[];48}4950interface IFungibleTokenDataType {51 Value: BN;52}5354interface IReFungibleTokenDataType {55 Owner: IReFungibleOwner[];56 ConstData: number[];57 VariableData: number[];58}5960export function getGenericResult(events: EventRecord[]): GenericResult {61 const result: GenericResult = {62 success: false,63 };64 events.forEach(({ phase, event: { data, method, section } }) => {65 // console.log(` ${phase}: ${section}.${method}:: ${data}`);66 if (method === 'ExtrinsicSuccess') {67 result.success = true;68 }69 });70 return result;71}7273export function getCreateCollectionResult(events: EventRecord[]): CreateCollectionResult {74 let success = false;75 let collectionId: number = 0;76 events.forEach(({ phase, event: { data, method, section } }) => {77 // console.log(` ${phase}: ${section}.${method}:: ${data}`);78 if (method == 'ExtrinsicSuccess') {79 success = true;80 } else if ((section == 'nft') && (method == 'Created')) {81 collectionId = parseInt(data[0].toString());82 }83 });84 const result: CreateCollectionResult = {85 success,86 collectionId,87 };88 return result;89}9091export function getCreateItemResult(events: EventRecord[]): CreateItemResult {92 let success = false;93 let collectionId: number = 0;94 let itemId: number = 0;95 events.forEach(({ phase, event: { data, method, section } }) => {96 // console.log(` ${phase}: ${section}.${method}:: ${data}`);97 if (method == 'ExtrinsicSuccess') {98 success = true;99 } else if ((section == 'nft') && (method == 'ItemCreated')) {100 collectionId = parseInt(data[0].toString());101 itemId = parseInt(data[1].toString());102 }103 });104 const result: CreateItemResult = {105 success,106 collectionId,107 itemId,108 };109 return result;110}111112interface Invalid {113 type: 'Invalid';114}115116interface Nft {117 type: 'NFT';118}119120interface Fungible {121 type: 'Fungible';122 decimalPoints: number;123}124125interface ReFungible {126 type: 'ReFungible';127 decimalPoints: number;128}129130interface Nft {131 type: 'NFT'132}133134interface Fungible {135 type: 'Fungible',136 decimalPoints: number137}138139interface ReFungible {140 type: 'ReFungible',141 decimalPoints: number142}143144type CollectionMode = Nft | Fungible | ReFungible | Invalid;145146export type CreateCollectionParams = {147 mode: CollectionMode,148 name: string,149 description: string,150 tokenPrefix: string,151};152153const defaultCreateCollectionParams: CreateCollectionParams = {154 description: 'description',155 mode: { type: 'NFT' },156 name: 'name',157 tokenPrefix: 'prefix',158}159160export async function createCollectionExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {161 const {name, description, mode, tokenPrefix } = {...defaultCreateCollectionParams, ...params};162163 let collectionId: number = 0;164 await usingApi(async (api) => {165 // Get number of collections before the transaction166 const AcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString(), 10);167168 // Run the CreateCollection transaction169 const alicePrivateKey = privateKey('//Alice');170171 let modeprm = {};172 if (mode.type === 'NFT') {173 modeprm = {nft: null};174 } else if (mode.type === 'Fungible') {175 modeprm = {fungible: mode.decimalPoints};176 } else if (mode.type === 'ReFungible') {177 modeprm = {refungible: mode.decimalPoints};178 } else if (mode.type === 'Invalid') {179 modeprm = {invalid: null};180 }181182 const tx = api.tx.nft.createCollection(strToUTF16(name), strToUTF16(description), strToUTF16(tokenPrefix), modeprm);183 const events = await submitTransactionAsync(alicePrivateKey, tx);184 const result = getCreateCollectionResult(events);185186 // Get number of collections after the transaction187 const BcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString(), 10);188189 // Get the collection190 const collection: any = (await api.query.nft.collection(result.collectionId)).toJSON();191192 // What to expect193 // tslint:disable-next-line:no-unused-expression194 expect(result.success).to.be.true;195 expect(result.collectionId).to.be.equal(BcollectionCount);196 // tslint:disable-next-line:no-unused-expression197 expect(collection).to.be.not.null;198 expect(BcollectionCount).to.be.equal(AcollectionCount + 1, 'Error: NFT collection NOT created.');199 expect(collection.Owner).to.be.equal(alicesPublicKey);200 expect(utf16ToStr(collection.Name)).to.be.equal(name);201 expect(utf16ToStr(collection.Description)).to.be.equal(description);202 expect(hexToStr(collection.TokenPrefix)).to.be.equal(tokenPrefix);203204 collectionId = result.collectionId;205 });206207 return collectionId;208}209210export async function createCollectionExpectFailure(params: Partial<CreateCollectionParams> = {}) {211 const {name, description, mode, tokenPrefix } = {...defaultCreateCollectionParams, ...params};212213 let modeprm = {};214 if (mode.type === 'NFT') {215 modeprm = {nft: null};216 } else if (mode.type === 'Fungible') {217 modeprm = {fungible: mode.decimalPoints};218 } else if (mode.type === 'ReFungible') {219 modeprm = {refungible: mode.decimalPoints};220 } else if (mode.type === 'Invalid') {221 modeprm = {invalid: null};222 }223224 await usingApi(async (api) => {225 // Get number of collections before the transaction226 const AcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString());227228 // Run the CreateCollection transaction229 const alicePrivateKey = privateKey('//Alice');230 const tx = api.tx.nft.createCollection(strToUTF16(name), strToUTF16(description), strToUTF16(tokenPrefix), modeprm);231 const events = await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;232 const result = getCreateCollectionResult(events);233234 // Get number of collections after the transaction235 const BcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString());236237 // What to expect238 // tslint:disable-next-line:no-unused-expression239 expect(result.success).to.be.false;240 expect(BcollectionCount).to.be.equal(AcollectionCount, 'Error: Collection with incorrect data created.');241 });242}243244export async function findUnusedAddress(api: ApiPromise): Promise<IKeyringPair> {245 let bal = new BigNumber(0);246 let unused;247 do {248 const randomSeed = 'seed' + Math.floor(Math.random() * Math.floor(10000));249 const keyring = new Keyring({ type: 'sr25519' });250 unused = keyring.addFromUri(`//${randomSeed}`);251 bal = new BigNumber((await api.query.system.account(unused.address)).data.free.toString());252 } while (bal.toFixed() != '0');253 return unused;254}255256export async function findNotExistingCollection(api: ApiPromise): Promise<number> {257 const totalNumber = parseInt((await api.query.nft.createdCollectionCount()).toString(), 10) as unknown as number;258 const newCollection: number = totalNumber + 1;259 return newCollection;260}261262function getDestroyResult(events: EventRecord[]): boolean {263 let success: boolean = false;264 events.forEach(({ phase, event: { data, method, section } }) => {265 // console.log(` ${phase}: ${section}.${method}:: ${data}`);266 if (method == 'ExtrinsicSuccess') {267 success = true;268 }269 });270 return success;271}272273export async function destroyCollectionExpectFailure(collectionId: number, senderSeed: string = '//Alice') {274 await usingApi(async (api) => {275 // Run the DestroyCollection transaction276 const alicePrivateKey = privateKey(senderSeed);277 const tx = api.tx.nft.destroyCollection(collectionId);278 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;279 });280}281282export async function destroyCollectionExpectSuccess(collectionId: number, senderSeed: string = '//Alice') {283 await usingApi(async (api) => {284 // Run the DestroyCollection transaction285 const alicePrivateKey = privateKey(senderSeed);286 const tx = api.tx.nft.destroyCollection(collectionId);287 const events = await submitTransactionAsync(alicePrivateKey, tx);288 const result = getDestroyResult(events);289290 // Get the collection291 const collection: any = (await api.query.nft.collection(collectionId)).toJSON();292293 // What to expect294 expect(result).to.be.true;295 expect(collection).to.be.not.null;296 expect(collection.Owner).to.be.equal(nullPublicKey);297 });298}299300export async function setCollectionSponsorExpectSuccess(collectionId: number, sponsor: string) {301 await usingApi(async (api) => {302303 // Run the transaction304 const alicePrivateKey = privateKey('//Alice');305 const tx = api.tx.nft.setCollectionSponsor(collectionId, sponsor);306 const events = await submitTransactionAsync(alicePrivateKey, tx);307 const result = getGenericResult(events);308309 // Get the collection310 const collection: any = (await api.query.nft.collection(collectionId)).toJSON();311312 // What to expect313 expect(result.success).to.be.true;314 expect(collection.Sponsor.toString()).to.be.equal(sponsor.toString());315 expect(collection.SponsorConfirmed).to.be.false;316 });317}318319export async function removeCollectionSponsorExpectSuccess(collectionId: number) {320 await usingApi(async (api) => {321322 // Run the transaction323 const alicePrivateKey = privateKey('//Alice');324 const tx = api.tx.nft.removeCollectionSponsor(collectionId);325 const events = await submitTransactionAsync(alicePrivateKey, tx);326 const result = getGenericResult(events);327328 // Get the collection329 const collection: any = (await api.query.nft.collection(collectionId)).toJSON();330331 // What to expect332 expect(result.success).to.be.true;333 expect(collection.Sponsor).to.be.equal(nullPublicKey);334 expect(collection.SponsorConfirmed).to.be.false;335 });336}337338export async function removeCollectionSponsorExpectFailure(collectionId: number) {339 await usingApi(async (api) => {340341 // Run the transaction342 const alicePrivateKey = privateKey('//Alice');343 const tx = api.tx.nft.removeCollectionSponsor(collectionId);344 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;345 });346}347348export async function setCollectionSponsorExpectFailure(collectionId: number, sponsor: string, senderSeed: string = '//Alice') {349 await usingApi(async (api) => {350351 // Run the transaction352 const alicePrivateKey = privateKey(senderSeed);353 const tx = api.tx.nft.setCollectionSponsor(collectionId, sponsor);354 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;355 });356}357358export async function confirmSponsorshipExpectSuccess(collectionId: number, senderSeed: string = '//Alice') {359 await usingApi(async (api) => {360361 // Run the transaction362 const sender = privateKey(senderSeed);363 const tx = api.tx.nft.confirmSponsorship(collectionId);364 const events = await submitTransactionAsync(sender, tx);365 const result = getGenericResult(events);366367 // Get the collection368 const collection: any = (await api.query.nft.collection(collectionId)).toJSON();369370 // What to expect371 expect(result.success).to.be.true;372 expect(collection.Sponsor).to.be.equal(sender.address);373 expect(collection.SponsorConfirmed).to.be.true;374 });375}376377export async function confirmSponsorshipExpectFailure(collectionId: number, senderSeed: string = '//Alice') {378 await usingApi(async (api) => {379380 // Run the transaction381 const sender = privateKey(senderSeed);382 const tx = api.tx.nft.confirmSponsorship(collectionId);383 await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;384 });385}386387export interface CreateFungibleData extends Struct {388 readonly value: u128;389}390391export interface CreateReFungibleData extends Struct {}392export interface CreateNftData extends Struct {}393394export interface CreateItemData extends Enum {395 NFT: CreateNftData;396 Fungible: CreateFungibleData;397 ReFungible: CreateReFungibleData;398}399400export async function burnItemExpectSuccess(owner: IKeyringPair, collectionId: number, tokenId: number, value = 0) {401 await usingApi(async (api) => {402 const tx = api.tx.nft.burnItem(collectionId, tokenId, value);403 const events = await submitTransactionAsync(owner, tx);404 const result = getGenericResult(events);405 // Get the item406 const item: any = (await api.query.nft.nftItemList(collectionId, tokenId)).toJSON();407 // What to expect408 // tslint:disable-next-line:no-unused-expression409 expect(result.success).to.be.true;410 // tslint:disable-next-line:no-unused-expression411 expect(item).to.be.not.null;412 expect(item.Owner).to.be.equal(nullPublicKey);413 });414}415416export async function417approveExpectSuccess(collectionId: number,418 tokenId: number, owner: IKeyringPair, approved: IKeyringPair, amount: number = 1) {419 await usingApi(async (api: ApiPromise) => {420 const allowanceBefore =421 await api.query.nft.allowances(collectionId, [tokenId, owner.address, approved.address]) as unknown as BN;422 const approveNftTx = await api.tx.nft.approve(approved.address, collectionId, tokenId, amount);423 const events = await submitTransactionAsync(owner, approveNftTx);424 const result = getCreateItemResult(events);425 // tslint:disable-next-line:no-unused-expression426 expect(result.success).to.be.true;427 const allowanceAfter =428 await api.query.nft.allowances(collectionId, [tokenId, owner.address, approved.address]) as unknown as BN;429 expect(allowanceAfter.toNumber() - allowanceBefore.toNumber()).to.be.equal(amount);430 });431}432433export async function434transferFromExpectSuccess(collectionId: number,435 tokenId: number,436 accountApproved: IKeyringPair,437 accountFrom: IKeyringPair,438 accountTo: IKeyringPair,439 value: number = 1,440 type: string = 'NFT') {441 await usingApi(async (api: ApiPromise) => {442 let balanceBefore = new BN(0);443 if (type === 'Fungible') {444 balanceBefore = await api.query.nft.balance(collectionId, accountTo.address) as unknown as BN;445 }446 const transferFromTx = await api.tx.nft.transferFrom(447 accountFrom.address, accountTo.address, collectionId, tokenId, value);448 const events = await submitTransactionAsync(accountFrom, transferFromTx);449 const result = getCreateItemResult(events);450 // tslint:disable-next-line:no-unused-expression451 expect(result.success).to.be.true;452 if (type === 'NFT') {453 const nftItemData = await api.query.nft.nftItemList(collectionId, tokenId) as unknown as ITokenDataType;454 expect(nftItemData.Owner.toString()).to.be.equal(accountTo.address);455 }456 if (type === 'Fungible') {457 const balanceAfter = await api.query.nft.balance(collectionId, accountTo.address) as unknown as BN;458 expect(balanceAfter.sub(balanceBefore).toNumber()).to.be.equal(value);459 }460 if (type === 'ReFungible') {461 const nftItemData =462 await api.query.nft.reFungibleItemList(collectionId, tokenId) as unknown as IReFungibleTokenDataType;463 expect(nftItemData.Owner[0].Owner.toString()).to.be.equal(accountTo.address);464 expect(nftItemData.Owner[0].Fraction.toNumber()).to.be.equal(value);465 }466 });467}468469export async function470transferFromExpectFail(collectionId: number,471 tokenId: number,472 accountApproved: IKeyringPair,473 accountFrom: IKeyringPair,474 accountTo: IKeyringPair,475 value: number = 1) {476 await usingApi(async (api: ApiPromise) => {477 const transferFromTx = await api.tx.nft.transferFrom(478 accountFrom.address, accountTo.address, collectionId, tokenId, value);479 const events = await expect(submitTransactionExpectFailAsync(accountApproved, transferFromTx)).to.be.rejected;480 const result = getCreateCollectionResult(events);481 // tslint:disable-next-line:no-unused-expression482 expect(result.success).to.be.false;483 });484}485486export async function487transferExpectSuccess(collectionId: number,488 tokenId: number,489 sender: IKeyringPair,490 recipient: IKeyringPair,491 value: number = 1,492 type: string = 'NFT') {493 await usingApi(async (api: ApiPromise) => {494 let balanceBefore = new BN(0);495 if (type === 'Fungible') {496 balanceBefore = await api.query.nft.balance(collectionId, recipient.address) as unknown as BN;497 }498 const transferTx = await api.tx.nft.transfer(recipient.address, collectionId, tokenId, value);499 const events = await submitTransactionAsync(sender, transferTx);500 const result = getCreateItemResult(events);501 // tslint:disable-next-line:no-unused-expression502 expect(result.success).to.be.true;503 if (type === 'NFT') {504 const nftItemData = await api.query.nft.nftItemList(collectionId, tokenId) as unknown as ITokenDataType;505 expect(nftItemData.Owner.toString()).to.be.equal(recipient.address);506 }507 if (type === 'Fungible') {508 const balanceAfter = await api.query.nft.balance(collectionId, recipient.address) as unknown as BN;509 expect(balanceAfter.sub(balanceBefore).toNumber()).to.be.equal(value);510 }511 if (type === 'ReFungible') {512 const nftItemData =513 await api.query.nft.reFungibleItemList(collectionId, tokenId) as unknown as IReFungibleTokenDataType;514 expect(nftItemData.Owner[0].Owner.toString()).to.be.equal(recipient.address);515 expect(nftItemData.Owner[0].Fraction.toNumber()).to.be.equal(value);516 }517 });518}519520export async function521transferExpectFail(collectionId: number,522 tokenId: number,523 sender: IKeyringPair,524 recipient: IKeyringPair,525 value: number = 1,526 type: string = 'NFT') {527 await usingApi(async (api: ApiPromise) => {528 const transferTx = await api.tx.nft.transfer(recipient.address, collectionId, tokenId, value);529 const events = await expect(submitTransactionExpectFailAsync(sender, transferTx)).to.be.rejected;530 if (events && Array.isArray(events)) {531 const result = getCreateCollectionResult(events);532 // tslint:disable-next-line:no-unused-expression533 expect(result.success).to.be.false;534 }535 });536}537538export async function539approveExpectFail(collectionId: number,540 tokenId: number, owner: IKeyringPair, approved: IKeyringPair, amount: number = 1) {541 await usingApi(async (api: ApiPromise) => {542 const approveNftTx = await api.tx.nft.approve(approved.address, collectionId, tokenId, amount);543 const events = await expect(submitTransactionExpectFailAsync(owner, approveNftTx)).to.be.rejected;544 const result = getCreateCollectionResult(events);545 // tslint:disable-next-line:no-unused-expression546 expect(result.success).to.be.false;547 });548}549550export async function createItemExpectSuccess(551 sender: IKeyringPair, collectionId: number, createMode: string, owner: string = '') {552 let newItemId: number = 0;553 await usingApi(async (api) => {554 const AItemCount = parseInt((await api.query.nft.itemListIndex(collectionId)).toString(), 10);555 const Aitem: any = (await api.query.nft.fungibleItemList(collectionId, owner)).toJSON();556 const AItemBalance = new BigNumber(Aitem.Value);557558 if (owner === '') {559 owner = sender.address;560 }561562 let tx;563 if (createMode === 'Fungible') {564 const createData = {fungible: {value: 10}};565 tx = api.tx.nft.createItem(collectionId, owner, createData);566 } else {567 tx = api.tx.nft.createItem(collectionId, owner, createMode);568 }569 const events = await submitTransactionAsync(sender, tx);570 const result = getCreateItemResult(events);571572 const BItemCount = parseInt((await api.query.nft.itemListIndex(collectionId)).toString(), 10);573 const Bitem: any = (await api.query.nft.fungibleItemList(collectionId, owner)).toJSON();574 const BItemBalance = new BigNumber(Bitem.Value);575576 // What to expect577 // tslint:disable-next-line:no-unused-expression578 expect(result.success).to.be.true;579 if (createMode === 'Fungible') {580 expect(BItemBalance.minus(AItemBalance).toNumber()).to.be.equal(10);581 } else {582 expect(BItemCount).to.be.equal(AItemCount + 1);583 }584 expect(collectionId).to.be.equal(result.collectionId);585 expect(BItemCount).to.be.equal(result.itemId);586 newItemId = result.itemId;587 });588 return newItemId;589}590591export async function createItemExpectFailure(592 sender: IKeyringPair, collectionId: number, createMode: string, owner: string = sender.address) {593 await usingApi(async (api) => {594 const tx = api.tx.nft.createItem(collectionId, owner, createMode);595 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;596 const result = getCreateItemResult(events);597598 expect(result.success).to.be.false;599 });600}601602export async function enableWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number) {603 await usingApi(async (api) => {604605 // Run the transaction606 const tx = api.tx.nft.setPublicAccessMode(collectionId, 'WhiteList');607 const events = await submitTransactionAsync(sender, tx);608 const result = getGenericResult(events);609610 // Get the collection611 const collection: any = (await api.query.nft.collection(collectionId)).toJSON();612613 // What to expect614 // tslint:disable-next-line:no-unused-expression615 expect(result.success).to.be.true;616 expect(collection.Access).to.be.equal('WhiteList');617 });618}619620export async function setMintPermissionExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {621 await usingApi(async (api) => {622623 // Run the transaction624 const tx = api.tx.nft.setMintPermission(collectionId, enabled);625 const events = await submitTransactionAsync(sender, tx);626 const result = getGenericResult(events);627628 // Get the collection629 const collection: any = (await api.query.nft.collection(collectionId)).toJSON();630631 // What to expect632 // tslint:disable-next-line:no-unused-expression633 expect(result.success).to.be.true;634 expect(collection.MintMode).to.be.equal(enabled);635 });636}637638export async function enablePublicMintingExpectSuccess(sender: IKeyringPair, collectionId: number) {639 await setMintPermissionExpectSuccess(sender, collectionId, true);640}641642export async function setMintPermissionExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {643 await usingApi(async (api) => {644 // Run the transaction645 const tx = api.tx.nft.setMintPermission(collectionId, enabled);646 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;647 const result = getCreateCollectionResult(events);648 // tslint:disable-next-line:no-unused-expression649 expect(result.success).to.be.false;650 });651}652653export async function addToWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number, address: string) {654 await usingApi(async (api) => {655656 const whiteListedBefore = (await api.query.nft.whiteList(collectionId, address)).toJSON();657658 // Run the transaction659 const tx = api.tx.nft.addToWhiteList(collectionId, address);660 const events = await submitTransactionAsync(sender, tx);661 const result = getGenericResult(events);662663 const whiteListedAfter = (await api.query.nft.whiteList(collectionId, address)).toJSON();664665 // What to expect666 // tslint:disable-next-line:no-unused-expression667 expect(result.success).to.be.true;668 // tslint:disable-next-line: no-unused-expression669 expect(whiteListedBefore).to.be.false;670 // tslint:disable-next-line: no-unused-expression671 expect(whiteListedAfter).to.be.true;672 });673}674675export const getDetailedCollectionInfo = async (api: ApiPromise, collectionId: number)676 : Promise<ICollectionInterface | null> => {677 return await api.query.nft.collection(collectionId) as unknown as ICollectionInterface;678};679680export const getCreatedCollectionCount = async (api: ApiPromise): Promise<number> => {681 // set global object - collectionsCount682 return (await api.query.nft.createdCollectionCount() as unknown as BN).toNumber();683};