123456import { ApiPromise, Keyring } from '@polkadot/api';7import { Enum, Struct } from '@polkadot/types/codec';8import type { AccountId, BlockNumber, Call, 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';20import { Compact, Option, Raw, Vec } from '@polkadot/types/codec';212223chai.use(chaiAsPromised);24const expect = chai.expect;2526export const U128_MAX = (1n << 128n) - 1n;2728type GenericResult = {29 success: boolean,30};3132interface CreateCollectionResult {33 success: boolean;34 collectionId: number;35}3637interface CreateItemResult {38 success: boolean;39 collectionId: number;40 itemId: number;41 recipient: string;42}4344interface TransferResult {45 success: boolean;46 collectionId: number;47 itemId: number;48 sender: string;49 recipient: string;50 value: bigint;51}5253interface IReFungibleOwner {54 Fraction: BN;55 Owner: number[];56}5758interface ITokenDataType {59 Owner: number[];60 ConstData: number[];61 VariableData: number[];62}6364interface IFungibleTokenDataType {65 Value: BN;66}6768interface IGetMessage {69 checkMsgNftMethod: string;70 checkMsgTrsMethod: string;71 checkMsgSysMethod: string;72}7374export interface IReFungibleTokenDataType {75 Owner: IReFungibleOwner[];76 ConstData: number[];77 VariableData: number[];78}7980export function nftEventMessage(events: EventRecord[]): IGetMessage {81 let checkMsgNftMethod: string = '';82 let checkMsgTrsMethod: string = '';83 let checkMsgSysMethod: string = '';84 events.forEach(({ event: { method, section } }) => {85 if (section === 'nft') {86 checkMsgNftMethod = method;87 } else if (section === 'treasury') {88 checkMsgTrsMethod = method;89 } else if (section === 'system') {90 checkMsgSysMethod = method;91 } else { return null; }92 });93 const result: IGetMessage = {94 checkMsgNftMethod,95 checkMsgTrsMethod,96 checkMsgSysMethod,97 };98 return result;99}100101export function getGenericResult(events: EventRecord[]): GenericResult {102 const result: GenericResult = {103 success: false,104 };105 events.forEach(({ phase, event: { data, method, section } }) => {106 107 if (method === 'ExtrinsicSuccess') {108 result.success = true;109 }110 });111 return result;112}113114115116export function getCreateCollectionResult(events: EventRecord[]): CreateCollectionResult {117 let success = false;118 let collectionId: number = 0;119 events.forEach(({ phase, event: { data, method, section } }) => {120 121 if (method == 'ExtrinsicSuccess') {122 success = true;123 } else if ((section == 'nft') && (method == 'CollectionCreated')) {124 collectionId = parseInt(data[0].toString());125 }126 });127 const result: CreateCollectionResult = {128 success,129 collectionId,130 };131 return result;132}133134export function getCreateItemResult(events: EventRecord[]): CreateItemResult {135 let success = false;136 let collectionId: number = 0;137 let itemId: number = 0;138 let recipient: string = '';139 events.forEach(({ phase, event: { data, method, section } }) => {140 141 if (method == 'ExtrinsicSuccess') {142 success = true;143 } else if ((section == 'nft') && (method == 'ItemCreated')) {144 collectionId = parseInt(data[0].toString());145 itemId = parseInt(data[1].toString());146 recipient = data[2].toString();147 }148 });149 const result: CreateItemResult = {150 success,151 collectionId,152 itemId,153 recipient,154 };155 return result;156}157158export function getTransferResult(events: EventRecord[]): TransferResult {159 const result: TransferResult = {160 success: false,161 collectionId: 0,162 itemId: 0,163 sender: '',164 recipient: '',165 value: 0n,166 };167168 events.forEach(({event: {data, method, section}}) => {169 if (method === 'ExtrinsicSuccess') {170 result.success = true;171 } else if (section === 'nft' && method === 'Transfer') {172 result.collectionId = +data[0].toString();173 result.itemId = +data[1].toString();174 result.sender = data[2].toString();175 result.recipient = data[3].toString();176 result.value = BigInt(data[4].toString());177 }178 });179180 return result;181}182183interface Invalid {184 type: 'Invalid';185}186187interface Nft {188 type: 'NFT';189}190191interface Fungible {192 type: 'Fungible';193 decimalPoints: number;194}195196interface ReFungible {197 type: 'ReFungible';198}199200type CollectionMode = Nft | Fungible | ReFungible | Invalid;201202export type CreateCollectionParams = {203 mode: CollectionMode,204 name: string,205 description: string,206 tokenPrefix: string,207};208209const defaultCreateCollectionParams: CreateCollectionParams = {210 description: 'description',211 mode: { type: 'NFT' },212 name: 'name',213 tokenPrefix: 'prefix',214}215216export async function createCollectionExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {217 const {name, description, mode, tokenPrefix } = {...defaultCreateCollectionParams, ...params};218219 let collectionId: number = 0;220 await usingApi(async (api) => {221 222 const AcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString(), 10);223224 225 const alicePrivateKey = privateKey('//Alice');226227 let modeprm = {};228 if (mode.type === 'NFT') {229 modeprm = {nft: null};230 } else if (mode.type === 'Fungible') {231 modeprm = {fungible: mode.decimalPoints};232 } else if (mode.type === 'ReFungible') {233 modeprm = {refungible: null};234 } else if (mode.type === 'Invalid') {235 modeprm = {invalid: null};236 }237238 const tx = api.tx.nft.createCollection(strToUTF16(name), strToUTF16(description), strToUTF16(tokenPrefix), modeprm);239 const events = await submitTransactionAsync(alicePrivateKey, tx);240 const result = getCreateCollectionResult(events);241242 243 const BcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString(), 10);244245 246 const collection: any = (await api.query.nft.collectionById(result.collectionId)).toJSON();247248 249 250 expect(result.success).to.be.true;251 expect(result.collectionId).to.be.equal(BcollectionCount);252 253 expect(collection).to.be.not.null;254 expect(BcollectionCount).to.be.equal(AcollectionCount + 1, 'Error: NFT collection NOT created.');255 expect(collection.Owner).to.be.equal(alicesPublicKey);256 expect(utf16ToStr(collection.Name)).to.be.equal(name);257 expect(utf16ToStr(collection.Description)).to.be.equal(description);258 expect(hexToStr(collection.TokenPrefix)).to.be.equal(tokenPrefix);259260 collectionId = result.collectionId;261 });262263 return collectionId;264}265266export async function createCollectionExpectFailure(params: Partial<CreateCollectionParams> = {}) {267 const {name, description, mode, tokenPrefix } = {...defaultCreateCollectionParams, ...params};268269 let modeprm = {};270 if (mode.type === 'NFT') {271 modeprm = {nft: null};272 } else if (mode.type === 'Fungible') {273 modeprm = {fungible: mode.decimalPoints};274 } else if (mode.type === 'ReFungible') {275 modeprm = {refungible: null};276 } else if (mode.type === 'Invalid') {277 modeprm = {invalid: null};278 }279280 await usingApi(async (api) => {281 282 const AcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString());283284 285 const alicePrivateKey = privateKey('//Alice');286 const tx = api.tx.nft.createCollection(strToUTF16(name), strToUTF16(description), strToUTF16(tokenPrefix), modeprm);287 const events = await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;288 const result = getCreateCollectionResult(events);289290 291 const BcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString());292293 294 295 expect(result.success).to.be.false;296 expect(BcollectionCount).to.be.equal(AcollectionCount, 'Error: Collection with incorrect data created.');297 });298}299300export async function findUnusedAddress(api: ApiPromise, seedAddition = ''): Promise<IKeyringPair> {301 let bal = new BigNumber(0);302 let unused;303 do {304 const randomSeed = 'seed' + Math.floor(Math.random() * Math.floor(10000)) + seedAddition;305 const keyring = new Keyring({ type: 'sr25519' });306 unused = keyring.addFromUri(`//${randomSeed}`);307 bal = new BigNumber((await api.query.system.account(unused.address)).data.free.toString());308 } while (bal.toFixed() != '0');309 return unused;310}311312export async function getAllowance(collectionId: number, tokenId: number, owner: string, approved: string) {313 return await usingApi(async (api) => {314 const bn = await api.query.nft.allowances(collectionId, [tokenId, owner, approved]) as unknown as BN;315 return BigInt(bn.toString());316 });317}318319export function findUnusedAddresses(api: ApiPromise, amount: number): Promise<IKeyringPair[]> {320 return Promise.all(new Array(amount).fill(null).map(() => findUnusedAddress(api, '_' + Date.now())));321}322323export async function findNotExistingCollection(api: ApiPromise): Promise<number> {324 const totalNumber = parseInt((await api.query.nft.createdCollectionCount()).toString(), 10) as unknown as number;325 const newCollection: number = totalNumber + 1;326 return newCollection;327}328329function getDestroyResult(events: EventRecord[]): boolean {330 let success: boolean = false;331 events.forEach(({ phase, event: { data, method, section } }) => {332 333 if (method == 'ExtrinsicSuccess') {334 success = true;335 }336 });337 return success;338}339340export async function destroyCollectionExpectFailure(collectionId: number, senderSeed: string = '//Alice') {341 await usingApi(async (api) => {342 343 const alicePrivateKey = privateKey(senderSeed);344 const tx = api.tx.nft.destroyCollection(collectionId);345 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;346 });347}348349export async function destroyCollectionExpectSuccess(collectionId: number, senderSeed: string = '//Alice') {350 await usingApi(async (api) => {351 352 const alicePrivateKey = privateKey(senderSeed);353 const tx = api.tx.nft.destroyCollection(collectionId);354 const events = await submitTransactionAsync(alicePrivateKey, tx);355 const result = getDestroyResult(events);356357 358 const collection: any = (await api.query.nft.collectionById(collectionId)).toJSON();359360 361 expect(result).to.be.true;362 expect(collection).to.be.null;363 });364}365366export async function queryCollectionLimits(collectionId: number) {367 return await usingApi(async (api) => {368 return ((await api.query.nft.collectionById(collectionId)).toJSON() as any).Limits;369 });370}371372export async function setCollectionLimitsExpectSuccess(sender: IKeyringPair, collectionId: number, limits: any) {373 await usingApi(async (api) => {374 const oldLimits = await queryCollectionLimits(collectionId);375 const newLimits = { ...oldLimits as any, ...limits };376 const tx = api.tx.nft.setCollectionLimits(collectionId, newLimits);377 const events = await submitTransactionAsync(sender, tx);378 const result = getGenericResult(events);379380 expect(result.success).to.be.true;381 });382}383384export async function setCollectionLimitsExpectFailure(sender: IKeyringPair, collectionId: number, limits: any) {385 await usingApi(async (api) => {386 const oldLimits = await queryCollectionLimits(collectionId);387 const newLimits = { ...oldLimits as any, ...limits };388 const tx = api.tx.nft.setCollectionLimits(collectionId, newLimits);389 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;390 const result = getGenericResult(events);391392 expect(result.success).to.be.false;393 });394}395396export async function setCollectionSponsorExpectSuccess(collectionId: number, sponsor: string) {397 await usingApi(async (api) => {398399 400 const alicePrivateKey = privateKey('//Alice');401 const tx = api.tx.nft.setCollectionSponsor(collectionId, sponsor);402 const events = await submitTransactionAsync(alicePrivateKey, tx);403 const result = getGenericResult(events);404405 406 const collection: any = (await api.query.nft.collectionById(collectionId)).toJSON();407408 409 expect(result.success).to.be.true;410 expect(collection.Sponsorship).to.deep.equal({411 Unconfirmed: sponsor.toString(),412 });413 });414}415416export async function removeCollectionSponsorExpectSuccess(collectionId: number) {417 await usingApi(async (api) => {418419 420 const alicePrivateKey = privateKey('//Alice');421 const tx = api.tx.nft.removeCollectionSponsor(collectionId);422 const events = await submitTransactionAsync(alicePrivateKey, tx);423 const result = getGenericResult(events);424425 426 const collection: any = (await api.query.nft.collectionById(collectionId)).toJSON();427428 429 expect(result.success).to.be.true;430 expect(collection.Sponsorship).to.be.deep.equal({ Disabled: null });431 });432}433434export async function removeCollectionSponsorExpectFailure(collectionId: number) {435 await usingApi(async (api) => {436437 438 const alicePrivateKey = privateKey('//Alice');439 const tx = api.tx.nft.removeCollectionSponsor(collectionId);440 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;441 });442}443444export async function setCollectionSponsorExpectFailure(collectionId: number, sponsor: string, senderSeed: string = '//Alice') {445 await usingApi(async (api) => {446447 448 const alicePrivateKey = privateKey(senderSeed);449 const tx = api.tx.nft.setCollectionSponsor(collectionId, sponsor);450 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;451 });452}453454export async function confirmSponsorshipExpectSuccess(collectionId: number, senderSeed: string = '//Alice') {455 await usingApi(async (api) => {456457 458 const sender = privateKey(senderSeed);459 const tx = api.tx.nft.confirmSponsorship(collectionId);460 const events = await submitTransactionAsync(sender, tx);461 const result = getGenericResult(events);462463 464 const collection: any = (await api.query.nft.collectionById(collectionId)).toJSON();465466 467 expect(result.success).to.be.true;468 expect(collection.Sponsorship).to.be.deep.equal({469 Confirmed: sender.address,470 });471 });472}473474475export async function confirmSponsorshipExpectFailure(collectionId: number, senderSeed: string = '//Alice') {476 await usingApi(async (api) => {477478 479 const sender = privateKey(senderSeed);480 const tx = api.tx.nft.confirmSponsorship(collectionId);481 await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;482 });483}484485export async function enableContractSponsoringExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {486 await usingApi(async (api) => {487 const tx = api.tx.nft.enableContractSponsoring(contractAddress, enable);488 const events = await submitTransactionAsync(sender, tx);489 const result = getGenericResult(events);490491 expect(result.success).to.be.true;492 });493}494495export async function enableContractSponsoringExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {496 await usingApi(async (api) => {497 const tx = api.tx.nft.enableContractSponsoring(contractAddress, enable);498 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;499 const result = getGenericResult(events);500501 expect(result.success).to.be.false;502 });503}504505export async function setContractSponsoringRateLimitExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {506 await usingApi(async (api) => {507 const tx = api.tx.nft.setContractSponsoringRateLimit(contractAddress, rateLimit);508 const events = await submitTransactionAsync(sender, tx);509 const result = getGenericResult(events);510511 expect(result.success).to.be.true;512 });513}514515export async function setContractSponsoringRateLimitExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {516 await usingApi(async (api) => {517 const tx = api.tx.nft.setContractSponsoringRateLimit(contractAddress, rateLimit);518 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;519 const result = getGenericResult(events);520521 expect(result.success).to.be.false;522 });523}524525export async function toggleContractWhitelistExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, enabled: boolean) {526 await usingApi(async (api) => {527 const tx = api.tx.nft.toggleContractWhiteList(contractAddress, true);528 const events = await submitTransactionAsync(sender, tx);529 const result = getGenericResult(events);530531 expect(result.success).to.be.true;532 });533}534535export async function isWhitelistedInContract(contractAddress: AccountId | string, user: string) {536 let whitelisted: boolean = false;537 await usingApi(async (api) => {538 whitelisted = (await api.query.nft.contractWhiteList(contractAddress, user)).toJSON() as boolean;539 });540 return whitelisted;541}542543export async function addToContractWhiteListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: string) {544 await usingApi(async (api) => {545 const tx = api.tx.nft.addToContractWhiteList(contractAddress, user);546 const events = await submitTransactionAsync(sender, tx);547 const result = getGenericResult(events);548549 expect(result.success).to.be.true;550 });551}552553export async function removeFromContractWhiteListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: string) {554 await usingApi(async (api) => {555 const tx = api.tx.nft.removeFromContractWhiteList(contractAddress, user);556 const events = await submitTransactionAsync(sender, tx);557 const result = getGenericResult(events);558559 expect(result.success).to.be.true;560 });561}562563export async function removeFromContractWhiteListExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, user: string) {564 await usingApi(async (api) => {565 const tx = api.tx.nft.removeFromContractWhiteList(contractAddress, user);566 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;567 const result = getGenericResult(events);568569 expect(result.success).to.be.false;570 });571}572573export async function setVariableMetaDataExpectSuccess(sender: IKeyringPair, collectionId: number, itemId: number, data: number[]) {574 await usingApi(async (api) => {575 const tx = api.tx.nft.setVariableMetaData(collectionId, itemId, '0x' + Buffer.from(data).toString('hex'));576 const events = await submitTransactionAsync(sender, tx);577 const result = getGenericResult(events);578579 expect(result.success).to.be.true;580 });581}582583export async function setVariableMetaDataExpectFailure(sender: IKeyringPair, collectionId: number, itemId: number, data: number[]) {584 await usingApi(async (api) => {585 const tx = api.tx.nft.setVariableMetaData(collectionId, itemId, '0x' + Buffer.from(data).toString('hex'));586 await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;587 });588}589590export async function setOffchainSchemaExpectSuccess(sender: IKeyringPair, collectionId: number, data: number[]) {591 await usingApi(async (api) => {592 const tx = api.tx.nft.setOffchainSchema(collectionId, '0x' + Buffer.from(data).toString('hex'));593 const events = await submitTransactionAsync(sender, tx);594 const result = getGenericResult(events);595596 expect(result.success).to.be.true;597 });598}599600export async function setOffchainSchemaExpectFailure(sender: IKeyringPair, collectionId: number, data: number[]) {601 await usingApi(async (api) => {602 const tx = api.tx.nft.setOffchainSchema(collectionId, '0x' + Buffer.from(data).toString('hex'));603 await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;604 });605}606607export interface CreateFungibleData {608 readonly Value: bigint;609}610611export interface CreateReFungibleData { }612export interface CreateNftData { }613614export type CreateItemData = {615 NFT: CreateNftData;616} | {617 Fungible: CreateFungibleData;618} | {619 ReFungible: CreateReFungibleData;620};621622export async function burnItemExpectSuccess(owner: IKeyringPair, collectionId: number, tokenId: number, value = 0) {623 await usingApi(async (api) => {624 const tx = api.tx.nft.burnItem(collectionId, tokenId, value);625 const events = await submitTransactionAsync(owner, tx);626 const result = getGenericResult(events);627 628 const item: any = (await api.query.nft.nftItemList(collectionId, tokenId)).toJSON();629 630 631 expect(result.success).to.be.true;632 633 expect(item).to.be.null;634 });635}636637export async function638approveExpectSuccess(collectionId: number,639 tokenId: number, owner: IKeyringPair, approved: IKeyringPair, amount: number | bigint = 1) {640 await usingApi(async (api: ApiPromise) => {641 const allowanceBefore =642 await api.query.nft.allowances(collectionId, [tokenId, owner.address, approved.address]) as unknown as BN;643 const approveNftTx = await api.tx.nft.approve(approved.address, collectionId, tokenId, amount);644 const events = await submitTransactionAsync(owner, approveNftTx);645 const result = getCreateItemResult(events);646 647 expect(result.success).to.be.true;648 const allowanceAfter =649 await api.query.nft.allowances(collectionId, [tokenId, owner.address, approved.address]) as unknown as BN;650 expect(allowanceAfter.sub(allowanceBefore).toString()).to.be.equal(amount.toString());651 });652}653654export async function655transferFromExpectSuccess(collectionId: number,656 tokenId: number,657 accountApproved: IKeyringPair,658 accountFrom: IKeyringPair,659 accountTo: IKeyringPair,660 value: number | bigint = 1,661 type: string = 'NFT') {662 await usingApi(async (api: ApiPromise) => {663 let balanceBefore = new BN(0);664 if (type === 'Fungible') {665 balanceBefore = await api.query.nft.balance(collectionId, accountTo.address) as unknown as BN;666 }667 const transferFromTx = await api.tx.nft.transferFrom(668 accountFrom.address, accountTo.address, collectionId, tokenId, value);669 const events = await submitTransactionAsync(accountApproved, transferFromTx);670 const result = getCreateItemResult(events);671 672 expect(result.success).to.be.true;673 if (type === 'NFT') {674 const nftItemData = (await api.query.nft.nftItemList(collectionId, tokenId) as any).unwrap() as ITokenDataType;675 expect(nftItemData.Owner.toString()).to.be.equal(accountTo.address);676 }677 if (type === 'Fungible') {678 const balanceAfter = (await api.query.nft.fungibleItemList(collectionId, accountTo.address) as any).Value as unknown as BN;679 expect(balanceAfter.sub(balanceBefore).toString()).to.be.equal(value.toString());680 }681 if (type === 'ReFungible') {682 const nftItemData =683 (await api.query.nft.reFungibleItemList(collectionId, tokenId) as any).unwrap() as IReFungibleTokenDataType;684 expect(nftItemData.Owner[0].Owner.toString()).to.be.equal(accountTo.address);685 expect(nftItemData.Owner[0].Fraction.toNumber()).to.be.equal(value);686 }687 });688}689690export async function691transferFromExpectFail(collectionId: number,692 tokenId: number,693 accountApproved: IKeyringPair,694 accountFrom: IKeyringPair,695 accountTo: IKeyringPair,696 value: number | bigint = 1) {697 await usingApi(async (api: ApiPromise) => {698 const transferFromTx = await api.tx.nft.transferFrom(699 accountFrom.address, accountTo.address, collectionId, tokenId, value);700 const events = await expect(submitTransactionExpectFailAsync(accountApproved, transferFromTx)).to.be.rejected;701 const result = getCreateCollectionResult(events);702 703 expect(result.success).to.be.false;704 });705}706707async function getBlockNumber(api: ApiPromise): Promise<number> {708 return new Promise<number>(async (resolve, reject) => {709 const unsubscribe = await api.rpc.chain.subscribeNewHeads((head) => {710 unsubscribe();711 resolve(head.number.toNumber());712 });713 });714}715716export async function717scheduleTransferExpectSuccess(collectionId: number,718 tokenId: number,719 sender: IKeyringPair,720 recipient: IKeyringPair,721 value: number | bigint = 1,722 type: string = 'NFT') {723 await usingApi(async (api: ApiPromise) => {724 let balanceBefore = new BN(0);725726727 let blockNumber: number | undefined = await getBlockNumber(api);728 let expectedBlockNumber = blockNumber + 2;729730 expect(blockNumber).to.be.greaterThan(0);731 const transferTx = await api.tx.nft.transfer(recipient.address, collectionId, tokenId, value); 732 const scheduleTx = await api.tx.scheduler.schedule(expectedBlockNumber, null, 0, transferTx);733734 const events = await submitTransactionAsync(sender, scheduleTx);735736 const sponsorBalanceBefore = new BigNumber((await api.query.system.account(sender.address)).data.free.toString());737 const recipientBalanceBefore = new BigNumber((await api.query.system.account(recipient.address)).data.free.toString());738739 const nftItemDataBefore = (await api.query.nft.nftItemList(collectionId, tokenId)).toJSON() as unknown as ITokenDataType;740 expect(nftItemDataBefore.Owner.toString()).to.be.equal(sender.address);741742 743 await new Promise(resolve => setTimeout(resolve, 6000 * 2));744745 const sponsorBalanceAfter = new BigNumber((await api.query.system.account(sender.address)).data.free.toString());746 const recipientBalanceAfter = new BigNumber((await api.query.system.account(recipient.address)).data.free.toString());747748 const nftItemData = (await api.query.nft.nftItemList(collectionId, tokenId)).toJSON() as unknown as ITokenDataType;749 expect(nftItemData.Owner.toString()).to.be.equal(recipient.address);750 expect(recipientBalanceAfter.toNumber()).to.be.equal(recipientBalanceBefore.toNumber());751 });752}753754755export async function756transferExpectSuccess(collectionId: number,757 tokenId: number,758 sender: IKeyringPair,759 recipient: IKeyringPair,760 value: number | bigint = 1,761 type: string = 'NFT') {762 await usingApi(async (api: ApiPromise) => {763 let balanceBefore = new BN(0);764 if (type === 'Fungible') {765 balanceBefore = await api.query.nft.balance(collectionId, recipient.address) as unknown as BN;766 }767 const transferTx = await api.tx.nft.transfer(recipient.address, collectionId, tokenId, value);768 const events = await submitTransactionAsync(sender, transferTx);769 const result = getTransferResult(events);770 771 expect(result.success).to.be.true;772 expect(result.collectionId).to.be.equal(collectionId);773 expect(result.itemId).to.be.equal(tokenId);774 expect(result.sender).to.be.equal(sender.address);775 expect(result.recipient).to.be.equal(recipient.address);776 expect(result.value.toString()).to.be.equal(value.toString());777 if (type === 'NFT') {778 const nftItemData = (await api.query.nft.nftItemList(collectionId, tokenId)).toJSON() as unknown as ITokenDataType;779 expect(nftItemData.Owner.toString()).to.be.equal(recipient.address);780 }781 if (type === 'Fungible') {782 const balanceAfter = (await api.query.nft.fungibleItemList(collectionId, recipient.address) as any).Value as unknown as BN;783 expect(balanceAfter.sub(balanceBefore).toString()).to.be.equal(value.toString());784 }785 if (type === 'ReFungible') {786 const nftItemData =787 (await api.query.nft.reFungibleItemList(collectionId, tokenId)).toJSON() as unknown as IReFungibleTokenDataType;788 expect(nftItemData.Owner[0].Owner.toString()).to.be.equal(recipient.address);789 expect(nftItemData.Owner[0].Fraction.toString()).to.be.equal(value.toString());790 }791 });792}793794export async function795transferExpectFail(collectionId: number,796 tokenId: number,797 sender: IKeyringPair,798 recipient: IKeyringPair,799 value: number | bigint = 1,800 type: string = 'NFT') {801 await usingApi(async (api: ApiPromise) => {802 const transferTx = await api.tx.nft.transfer(recipient.address, collectionId, tokenId, value);803 const events = await expect(submitTransactionExpectFailAsync(sender, transferTx)).to.be.rejected;804 if (events && Array.isArray(events)) {805 const result = getCreateCollectionResult(events);806 807 expect(result.success).to.be.false;808 }809 });810}811812export async function813approveExpectFail(collectionId: number,814 tokenId: number, owner: IKeyringPair, approved: IKeyringPair, amount: number | bigint = 1) {815 await usingApi(async (api: ApiPromise) => {816 const approveNftTx = await api.tx.nft.approve(approved.address, collectionId, tokenId, amount);817 const events = await expect(submitTransactionExpectFailAsync(owner, approveNftTx)).to.be.rejected;818 const result = getCreateCollectionResult(events);819 820 expect(result.success).to.be.false;821 });822}823824export async function getFungibleBalance(825 collectionId: number,826 owner: string,827) {828 return await usingApi(async (api) => {829 const response = (await api.query.nft.fungibleItemList(collectionId, owner)).toJSON() as unknown as {Value: string};830 return BigInt(response.Value);831 });832}833834export async function createFungibleItemExpectSuccess(835 sender: IKeyringPair,836 collectionId: number,837 data: CreateFungibleData,838 owner: string = sender.address,839) {840 return await usingApi(async (api) => {841 const tx = api.tx.nft.createItem(collectionId, owner, { Fungible: data });842843 const events = await submitTransactionAsync(sender, tx);844 const result = getCreateItemResult(events);845846 expect(result.success).to.be.true;847 return result.itemId;848 });849}850851export async function createItemExpectSuccess(852 sender: IKeyringPair, collectionId: number, createMode: string, owner: string = '') {853 let newItemId: number = 0;854 await usingApi(async (api) => {855 const AItemCount = parseInt((await api.query.nft.itemListIndex(collectionId)).toString(), 10);856 const Aitem: any = (await api.query.nft.fungibleItemList(collectionId, owner)).toJSON();857 const AItemBalance = new BigNumber(Aitem.Value);858859 if (owner === '') {860 owner = sender.address;861 }862863 let tx;864 if (createMode === 'Fungible') {865 const createData = {fungible: {value: 10}};866 tx = api.tx.nft.createItem(collectionId, owner, createData);867 } else if (createMode === 'ReFungible') {868 const createData = {refungible: {const_data: [], variable_data: [], pieces: 100}};869 tx = api.tx.nft.createItem(collectionId, owner, createData);870 } else {871 tx = api.tx.nft.createItem(collectionId, owner, createMode);872 }873 const events = await submitTransactionAsync(sender, tx);874 const result = getCreateItemResult(events);875876 const BItemCount = parseInt((await api.query.nft.itemListIndex(collectionId)).toString(), 10);877 const Bitem: any = (await api.query.nft.fungibleItemList(collectionId, owner)).toJSON();878 const BItemBalance = new BigNumber(Bitem.Value);879880 881 882 expect(result.success).to.be.true;883 if (createMode === 'Fungible') {884 expect(BItemBalance.minus(AItemBalance).toNumber()).to.be.equal(10);885 } else {886 expect(BItemCount).to.be.equal(AItemCount + 1);887 }888 expect(collectionId).to.be.equal(result.collectionId);889 expect(BItemCount).to.be.equal(result.itemId);890 expect(owner).to.be.equal(result.recipient);891 newItemId = result.itemId;892 });893 return newItemId;894}895896export async function createItemExpectFailure(897 sender: IKeyringPair, collectionId: number, createMode: string, owner: string = sender.address) {898 await usingApi(async (api) => {899 const tx = api.tx.nft.createItem(collectionId, owner, createMode);900 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;901 const result = getCreateItemResult(events);902903 expect(result.success).to.be.false;904 });905}906907export async function setPublicAccessModeExpectSuccess(908 sender: IKeyringPair, collectionId: number,909 accessMode: 'Normal' | 'WhiteList',910) {911 await usingApi(async (api) => {912913 914 const tx = api.tx.nft.setPublicAccessMode(collectionId, accessMode);915 const events = await submitTransactionAsync(sender, tx);916 const result = getGenericResult(events);917918 919 const collection: any = (await api.query.nft.collectionById(collectionId)).toJSON();920921 922 923 expect(result.success).to.be.true;924 expect(collection.Access).to.be.equal(accessMode);925 });926}927928export async function enableWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number) {929 await setPublicAccessModeExpectSuccess(sender, collectionId, 'WhiteList');930}931932export async function disableWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number) {933 await setPublicAccessModeExpectSuccess(sender, collectionId, 'Normal');934}935936export async function setMintPermissionExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {937 await usingApi(async (api) => {938939 940 const tx = api.tx.nft.setMintPermission(collectionId, enabled);941 const events = await submitTransactionAsync(sender, tx);942 const result = getGenericResult(events);943944 945 const collection: any = (await api.query.nft.collectionById(collectionId)).toJSON();946947 948 949 expect(result.success).to.be.true;950 expect(collection.MintMode).to.be.equal(enabled);951 });952}953954export async function enablePublicMintingExpectSuccess(sender: IKeyringPair, collectionId: number) {955 await setMintPermissionExpectSuccess(sender, collectionId, true);956}957958export async function setMintPermissionExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {959 await usingApi(async (api) => {960 961 const tx = api.tx.nft.setMintPermission(collectionId, enabled);962 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;963 const result = getCreateCollectionResult(events);964 965 expect(result.success).to.be.false;966 });967}968969export async function isWhitelisted(collectionId: number, address: string) {970 let whitelisted: boolean = false;971 await usingApi(async (api) => {972 whitelisted = (await api.query.nft.whiteList(collectionId, address)).toJSON() as unknown as boolean;973 });974 return whitelisted;975}976977export async function addToWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number, address: string) {978 await usingApi(async (api) => {979980 const whiteListedBefore = (await api.query.nft.whiteList(collectionId, address)).toJSON();981982 983 const tx = api.tx.nft.addToWhiteList(collectionId, address);984 const events = await submitTransactionAsync(sender, tx);985 const result = getGenericResult(events);986987 const whiteListedAfter = (await api.query.nft.whiteList(collectionId, address)).toJSON();988989 990 991 expect(result.success).to.be.true;992 993 expect(whiteListedBefore).to.be.false;994 995 expect(whiteListedAfter).to.be.true;996 });997}998999export async function removeFromWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number, address: string) {1000 await usingApi(async (api) => {1001 1002 const tx = api.tx.nft.removeFromWhiteList(collectionId, address);1003 const events = await submitTransactionAsync(sender, tx);1004 const result = getGenericResult(events);10051006 1007 1008 expect(result.success).to.be.true;1009 });1010}10111012export async function removeFromWhiteListExpectFailure(sender: IKeyringPair, collectionId: number, address: string) {1013 await usingApi(async (api) => {1014 1015 const tx = api.tx.nft.removeFromWhiteList(collectionId, address);1016 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1017 const result = getGenericResult(events);10181019 1020 1021 expect(result.success).to.be.false;1022 });1023}10241025export const getDetailedCollectionInfo = async (api: ApiPromise, collectionId: number)1026 : Promise<ICollectionInterface | null> => {1027 return (await api.query.nft.collectionById(collectionId)).toJSON() as unknown as ICollectionInterface;1028};10291030export const getCreatedCollectionCount = async (api: ApiPromise): Promise<number> => {1031 1032 return (await api.query.nft.createdCollectionCount() as unknown as BN).toNumber();1033};10341035export async function queryCollectionExpectSuccess(collectionId: number): Promise<ICollectionInterface> {1036 return await usingApi(async (api) => {1037 return (await api.query.nft.collectionById(collectionId)).toJSON() as unknown as ICollectionInterface;1038 });1039}