123456import { 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 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 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 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 166 const AcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString(), 10);167168 169 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 187 const BcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString(), 10);188189 190 const collection: any = (await api.query.nft.collection(result.collectionId)).toJSON();191192 193 194 expect(result.success).to.be.true;195 expect(result.collectionId).to.be.equal(BcollectionCount);196 197 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 226 const AcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString());227228 229 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 235 const BcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString());236237 238 239 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}255256function getDestroyResult(events: EventRecord[]): boolean {257 let success: boolean = false;258 events.forEach(({ phase, event: { data, method, section } }) => {259 260 if (method == 'ExtrinsicSuccess') {261 success = true;262 }263 });264 return success;265}266267export async function destroyCollectionExpectFailure(collectionId: number, senderSeed: string = '//Alice') {268 await usingApi(async (api) => {269 270 const alicePrivateKey = privateKey(senderSeed);271 const tx = api.tx.nft.destroyCollection(collectionId);272 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;273 });274}275276export async function destroyCollectionExpectSuccess(collectionId: number, senderSeed: string = '//Alice') {277 await usingApi(async (api) => {278 279 const alicePrivateKey = privateKey(senderSeed);280 const tx = api.tx.nft.destroyCollection(collectionId);281 const events = await submitTransactionAsync(alicePrivateKey, tx);282 const result = getDestroyResult(events);283284 285 const collection: any = (await api.query.nft.collection(collectionId)).toJSON();286287 288 expect(result).to.be.true;289 expect(collection).to.be.not.null;290 expect(collection.Owner).to.be.equal(nullPublicKey);291 });292}293294export async function setCollectionSponsorExpectSuccess(collectionId: number, sponsor: string) {295 await usingApi(async (api) => {296297 298 const alicePrivateKey = privateKey('//Alice');299 const tx = api.tx.nft.setCollectionSponsor(collectionId, sponsor);300 const events = await submitTransactionAsync(alicePrivateKey, tx);301 const result = getGenericResult(events);302303 304 const collection: any = (await api.query.nft.collection(collectionId)).toJSON();305306 307 expect(result.success).to.be.true;308 expect(collection.Sponsor.toString()).to.be.equal(sponsor.toString());309 expect(collection.SponsorConfirmed).to.be.false;310 });311}312313export async function removeCollectionSponsorExpectSuccess(collectionId: number) {314 await usingApi(async (api) => {315316 317 const alicePrivateKey = privateKey('//Alice');318 const tx = api.tx.nft.removeCollectionSponsor(collectionId);319 const events = await submitTransactionAsync(alicePrivateKey, tx);320 const result = getGenericResult(events);321322 323 const collection: any = (await api.query.nft.collection(collectionId)).toJSON();324325 326 expect(result.success).to.be.true;327 expect(collection.Sponsor).to.be.equal(nullPublicKey);328 expect(collection.SponsorConfirmed).to.be.false;329 });330}331332export async function removeCollectionSponsorExpectFailure(collectionId: number) {333 await usingApi(async (api) => {334335 336 const alicePrivateKey = privateKey('//Alice');337 const tx = api.tx.nft.removeCollectionSponsor(collectionId);338 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;339 });340}341342export async function setCollectionSponsorExpectFailure(collectionId: number, sponsor: string, senderSeed: string = '//Alice') {343 await usingApi(async (api) => {344345 346 const alicePrivateKey = privateKey(senderSeed);347 const tx = api.tx.nft.setCollectionSponsor(collectionId, sponsor);348 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;349 });350}351352export async function confirmSponsorshipExpectSuccess(collectionId: number, senderSeed: string = '//Alice') {353 await usingApi(async (api) => {354355 356 const sender = privateKey(senderSeed);357 const tx = api.tx.nft.confirmSponsorship(collectionId);358 const events = await submitTransactionAsync(sender, tx);359 const result = getGenericResult(events);360361 362 const collection: any = (await api.query.nft.collection(collectionId)).toJSON();363364 365 expect(result.success).to.be.true;366 expect(collection.Sponsor).to.be.equal(sender.address);367 expect(collection.SponsorConfirmed).to.be.true;368 });369}370371372export async function confirmSponsorshipExpectFailure(collectionId: number, senderSeed: string = '//Alice') {373 await usingApi(async (api) => {374375 376 const sender = privateKey(senderSeed);377 const tx = api.tx.nft.confirmSponsorship(collectionId);378 await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;379 });380}381382export interface CreateFungibleData extends Struct {383 readonly value: u128;384}385386export interface CreateReFungibleData extends Struct {}387export interface CreateNftData extends Struct {}388389export interface CreateItemData extends Enum {390 NFT: CreateNftData;391 Fungible: CreateFungibleData;392 ReFungible: CreateReFungibleData;393}394395export async function burnItemExpectSuccess(owner: IKeyringPair, collectionId: number, tokenId: number, value = 0) {396 await usingApi(async (api) => {397 const tx = api.tx.nft.burnItem(collectionId, tokenId, value);398 const events = await submitTransactionAsync(owner, tx);399 const result = getGenericResult(events);400 401 const item: any = (await api.query.nft.nftItemList(collectionId, tokenId)).toJSON();402 403 404 expect(result.success).to.be.true;405 406 expect(item).to.be.not.null;407 expect(item.Owner).to.be.equal(nullPublicKey);408 });409}410411export async function412approveExpectSuccess(collectionId: number,413 tokenId: number, owner: IKeyringPair, approved: IKeyringPair, amount: number = 1) { 414 await usingApi(async (api: ApiPromise) => {415 const allowanceBefore =416 await api.query.nft.allowances(collectionId, [tokenId, owner.address, approved.address]) as unknown as BN;417 const approveNftTx = await api.tx.nft.approve(approved.address, collectionId, tokenId, amount);418 const events = await submitTransactionAsync(owner, approveNftTx);419 const result = getCreateItemResult(events);420 421 expect(result.success).to.be.true;422 const allowanceAfter =423 await api.query.nft.allowances(collectionId, [tokenId, owner.address, approved.address]) as unknown as BN;424 expect(allowanceAfter.toNumber() - allowanceBefore.toNumber()).to.be.equal(amount);425 });426}427428export async function429transferFromExpectSuccess(collectionId: number,430 tokenId: number,431 accountApproved: IKeyringPair, 432 accountFrom: IKeyringPair, 433 accountTo: IKeyringPair, 434 value: number = 1,435 type: string = 'NFT') {436 await usingApi(async (api: ApiPromise) => {437 let balanceBefore = new BN(0);438 if (type === 'Fungible') {439 balanceBefore = await api.query.nft.balance(collectionId, accountTo.address) as unknown as BN;440 }441 const transferFromTx = await api.tx.nft.transferFrom(442 accountFrom.address, accountTo.address, collectionId, tokenId, value);443 const events = await submitTransactionAsync(accountFrom, transferFromTx);444 const result = getCreateItemResult(events);445 446 expect(result.success).to.be.true;447 if (type === 'NFT') {448 const nftItemData = await api.query.nft.nftItemList(collectionId, tokenId) as unknown as ITokenDataType;449 expect(nftItemData.Owner.toString()).to.be.equal(accountTo.address);450 }451 if (type === 'Fungible') {452 const balanceAfter = await api.query.nft.balance(collectionId, accountTo.address) as unknown as BN;453 expect(balanceAfter.sub(balanceBefore).toNumber()).to.be.equal(value);454 }455 if (type === 'ReFungible') {456 const nftItemData =457 await api.query.nft.reFungibleItemList(collectionId, tokenId) as unknown as IReFungibleTokenDataType;458 expect(nftItemData.Owner[0].Owner.toString()).to.be.equal(accountTo.address);459 expect(nftItemData.Owner[0].Fraction.toNumber()).to.be.equal(value);460 }461 });462}463464export async function465transferFromExpectFail(collectionId: number,466 tokenId: number,467 accountApproved: IKeyringPair,468 accountFrom: IKeyringPair,469 accountTo: IKeyringPair,470 value: number = 1) {471 await usingApi(async (api: ApiPromise) => {472 const transferFromTx = await api.tx.nft.transferFrom(473 accountFrom.address, accountTo.address, collectionId, tokenId, value);474 const events = await expect(submitTransactionExpectFailAsync(accountApproved, transferFromTx)).to.be.rejected;475 const result = getCreateCollectionResult(events);476 477 expect(result.success).to.be.false;478 });479}480481export async function482transferExpectSuccess(collectionId: number,483 tokenId: number,484 sender: IKeyringPair,485 recipient: IKeyringPair,486 value: number = 1,487 type: string = 'NFT') {488 await usingApi(async (api: ApiPromise) => {489 let balanceBefore = new BN(0);490 if (type === 'Fungible') {491 balanceBefore = await api.query.nft.balance(collectionId, recipient.address) as unknown as BN;492 }493 const transferTx = await api.tx.nft.transfer(recipient.address, collectionId, tokenId, value);494 const events = await submitTransactionAsync(sender, transferTx);495 const result = getCreateItemResult(events);496 497 expect(result.success).to.be.true;498 if (type === 'NFT') {499 const nftItemData = await api.query.nft.nftItemList(collectionId, tokenId) as unknown as ITokenDataType;500 expect(nftItemData.Owner.toString()).to.be.equal(recipient.address);501 }502 if (type === 'Fungible') {503 const balanceAfter = await api.query.nft.balance(collectionId, recipient.address) as unknown as BN;504 expect(balanceAfter.sub(balanceBefore).toNumber()).to.be.equal(value);505 }506 if (type === 'ReFungible') {507 const nftItemData =508 await api.query.nft.reFungibleItemList(collectionId, tokenId) as unknown as IReFungibleTokenDataType;509 expect(nftItemData.Owner[0].Owner.toString()).to.be.equal(recipient.address);510 expect(nftItemData.Owner[0].Fraction.toNumber()).to.be.equal(value);511 }512 });513}514515export async function516transferExpectFail(collectionId: number,517 tokenId: number,518 sender: IKeyringPair,519 recipient: IKeyringPair,520 value: number = 1,521 type: string = 'NFT') {522 await usingApi(async (api: ApiPromise) => {523 const transferTx = await api.tx.nft.transfer(recipient.address, collectionId, tokenId, value);524 const events = await expect(submitTransactionExpectFailAsync(sender, transferTx)).to.be.rejected;525 if (events && Array.isArray(events)) {526 const result = getCreateCollectionResult(events);527 528 expect(result.success).to.be.false;529 }530 });531}532533export async function534approveExpectFail(collectionId: number,535 tokenId: number, owner: IKeyringPair, approved: IKeyringPair, amount: number = 1) {536 await usingApi(async (api: ApiPromise) => {537 const approveNftTx = await api.tx.nft.approve(approved.address, collectionId, tokenId, amount);538 const events = await expect(submitTransactionExpectFailAsync(owner, approveNftTx)).to.be.rejected;539 const result = getCreateCollectionResult(events);540 541 expect(result.success).to.be.false;542 });543}544545export async function createItemExpectSuccess(546 sender: IKeyringPair, collectionId: number, createMode: string, owner: string = '') {547 let newItemId: number = 0;548 await usingApi(async (api) => {549 const AItemCount = parseInt((await api.query.nft.itemListIndex(collectionId)).toString(), 10);550 const Aitem: any = (await api.query.nft.fungibleItemList(collectionId, owner)).toJSON();551 const AItemBalance = new BigNumber(Aitem.Value);552553 if (owner === '') {554 owner = sender.address;555 }556557 let tx;558 if (createMode === 'Fungible') {559 const createData = {fungible: {value: 10}};560 tx = api.tx.nft.createItem(collectionId, owner, createData);561 } else {562 tx = api.tx.nft.createItem(collectionId, owner, createMode);563 }564 const events = await submitTransactionAsync(sender, tx);565 const result = getCreateItemResult(events);566567 const BItemCount = parseInt((await api.query.nft.itemListIndex(collectionId)).toString(), 10);568 const Bitem: any = (await api.query.nft.fungibleItemList(collectionId, owner)).toJSON();569 const BItemBalance = new BigNumber(Bitem.Value);570571 572 573 expect(result.success).to.be.true;574 if (createMode === 'Fungible') {575 expect(BItemBalance.minus(AItemBalance).toNumber()).to.be.equal(10);576 } else {577 expect(BItemCount).to.be.equal(AItemCount + 1);578 }579 expect(collectionId).to.be.equal(result.collectionId);580 expect(BItemCount).to.be.equal(result.itemId);581 newItemId = result.itemId;582 });583 return newItemId;584}585586export async function enableWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number) {587 await usingApi(async (api) => {588589 590 const tx = api.tx.nft.setPublicAccessMode(collectionId, 'WhiteList');591 const events = await submitTransactionAsync(sender, tx);592 const result = getGenericResult(events);593594 595 const collection: any = (await api.query.nft.collection(collectionId)).toJSON();596597 598 599 expect(result.success).to.be.true;600 expect(collection.Access).to.be.equal('WhiteList');601 });602}603604export async function enablePublicMintingExpectSuccess(sender: IKeyringPair, collectionId: number) {605 await usingApi(async (api) => {606607 608 const tx = api.tx.nft.setMintPermission(collectionId, true);609 const events = await submitTransactionAsync(sender, tx);610 const result = getGenericResult(events);611612 613 const collection: any = (await api.query.nft.collection(collectionId)).toJSON();614615 616 expect(result.success).to.be.true;617 expect(collection.MintMode).to.be.equal(true);618 });619}620621export async function addToWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number, address: string) {622 await usingApi(async (api) => {623624 const whiteListedBefore = (await api.query.nft.whiteList(collectionId, address)).toJSON();625626 627 const tx = api.tx.nft.addToWhiteList(collectionId, address);628 const events = await submitTransactionAsync(sender, tx);629 const result = getGenericResult(events);630631 const whiteListedAfter = (await api.query.nft.whiteList(collectionId, address)).toJSON();632633 634 635 expect(result.success).to.be.true;636 637 expect(whiteListedBefore).to.be.false;638 639 expect(whiteListedAfter).to.be.true;640 });641}642643export const getDetailedCollectionInfo = async (api: ApiPromise, collectionId: number)644 : Promise<ICollectionInterface | null> => {645 return await api.query.nft.collection(collectionId) as unknown as ICollectionInterface;646};647648export const getCreatedCollectionCount = async (api: ApiPromise): Promise<number> => {649 650 return (await api.query.nft.createdCollectionCount() as unknown as BN).toNumber();651};