123456import { ApiPromise, Keyring } from '@polkadot/api';7import type { AccountId, EventRecord } from '@polkadot/types/interfaces';8import { IKeyringPair } from '@polkadot/types/types';9import { evmToAddress } from '@polkadot/util-crypto';10import { BigNumber } from 'bignumber.js';11import BN from 'bn.js';12import chai from 'chai';13import chaiAsPromised from 'chai-as-promised';14import { alicesPublicKey } from '../accounts';15import privateKey from '../substrate/privateKey';16import { default as usingApi, submitTransactionAsync, submitTransactionExpectFailAsync } from '../substrate/substrate-api';17import { ICollectionInterface } from '../types';18import { hexToStr, strToUTF16, utf16ToStr } from './util';1920chai.use(chaiAsPromised);21const expect = chai.expect;2223export type CrossAccountId = {24 substrate: string,25} | {26 ethereum: string,27};28export function normalizeAccountId(input: string | AccountId | CrossAccountId | IKeyringPair): CrossAccountId {29 if (typeof input === 'string')30 return { substrate: input };31 if ('address' in input) {32 return { substrate: input.address };33 }34 if ('ethereum' in input) {35 input.ethereum = input.ethereum.toLowerCase();36 return input;37 }38 if ('substrate' in input) {39 return input;40 }4142 43 return {substrate: input.toString()};44}45export function toSubstrateAddress(input: string | CrossAccountId | IKeyringPair): string {46 input = normalizeAccountId(input);47 if ('substrate' in input) {48 return input.substrate;49 } else {50 return evmToAddress(input.ethereum);51 }52}5354export const U128_MAX = (1n << 128n) - 1n;5556type GenericResult = {57 success: boolean,58};5960interface CreateCollectionResult {61 success: boolean;62 collectionId: number;63}6465interface CreateItemResult {66 success: boolean;67 collectionId: number;68 itemId: number;69 recipient?: CrossAccountId;70}7172interface TransferResult {73 success: boolean;74 collectionId: number;75 itemId: number;76 sender?: CrossAccountId;77 recipient?: CrossAccountId;78 value: bigint;79}8081interface IReFungibleOwner {82 Fraction: BN;83 Owner: number[];84}8586interface ITokenDataType {87 Owner: IKeyringPair;88 ConstData: number[];89 VariableData: number[];90}9192interface IGetMessage {93 checkMsgNftMethod: string;94 checkMsgTrsMethod: string;95 checkMsgSysMethod: string;96}9798export interface IReFungibleTokenDataType {99 Owner: IReFungibleOwner[];100 ConstData: number[];101 VariableData: number[];102}103104export function nftEventMessage(events: EventRecord[]): IGetMessage {105 let checkMsgNftMethod = '';106 let checkMsgTrsMethod = '';107 let checkMsgSysMethod = '';108 events.forEach(({ event: { method, section } }) => {109 if (section === 'nft') {110 checkMsgNftMethod = method;111 } else if (section === 'treasury') {112 checkMsgTrsMethod = method;113 } else if (section === 'system') {114 checkMsgSysMethod = method;115 } else { return null; }116 });117 const result: IGetMessage = {118 checkMsgNftMethod,119 checkMsgTrsMethod,120 checkMsgSysMethod,121 };122 return result;123}124125export function getGenericResult(events: EventRecord[]): GenericResult {126 const result: GenericResult = {127 success: false,128 };129 events.forEach(({ event: { method } }) => {130 131 if (method === 'ExtrinsicSuccess') {132 result.success = true;133 }134 });135 return result;136}137138139140export function getCreateCollectionResult(events: EventRecord[]): CreateCollectionResult {141 let success = false;142 let collectionId = 0;143 events.forEach(({ event: { data, method, section } }) => {144 145 if (method == 'ExtrinsicSuccess') {146 success = true;147 } else if ((section == 'nft') && (method == 'CollectionCreated')) {148 collectionId = parseInt(data[0].toString());149 }150 });151 const result: CreateCollectionResult = {152 success,153 collectionId,154 };155 return result;156}157158export function getCreateItemResult(events: EventRecord[]): CreateItemResult {159 let success = false;160 let collectionId = 0;161 let itemId = 0;162 let recipient;163 events.forEach(({ event: { data, method, section } }) => {164 165 if (method == 'ExtrinsicSuccess') {166 success = true;167 } else if ((section == 'nft') && (method == 'ItemCreated')) {168 collectionId = parseInt(data[0].toString());169 itemId = parseInt(data[1].toString());170 recipient = data[2].toJSON();171 }172 });173 const result: CreateItemResult = {174 success,175 collectionId,176 itemId,177 recipient,178 };179 return result;180}181182export function getTransferResult(events: EventRecord[]): TransferResult {183 const result: TransferResult = {184 success: false,185 collectionId: 0,186 itemId: 0,187 value: 0n,188 };189190 events.forEach(({ event: { data, method, section } }) => {191 if (method === 'ExtrinsicSuccess') {192 result.success = true;193 } else if (section === 'nft' && method === 'Transfer') {194 result.collectionId = +data[0].toString();195 result.itemId = +data[1].toString();196 result.sender = data[2].toJSON() as CrossAccountId;197 result.recipient = data[3].toJSON() as CrossAccountId;198 result.value = BigInt(data[4].toString());199 }200 });201202 return result;203}204205interface Invalid {206 type: 'Invalid';207}208209interface Nft {210 type: 'NFT';211}212213interface Fungible {214 type: 'Fungible';215 decimalPoints: number;216}217218interface ReFungible {219 type: 'ReFungible';220}221222type CollectionMode = Nft | Fungible | ReFungible | Invalid;223224export type CreateCollectionParams = {225 mode: CollectionMode,226 name: string,227 description: string,228 tokenPrefix: string,229};230231const defaultCreateCollectionParams: CreateCollectionParams = {232 description: 'description',233 mode: { type: 'NFT' },234 name: 'name',235 tokenPrefix: 'prefix',236};237238export async function createCollectionExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {239 const { name, description, mode, tokenPrefix } = { ...defaultCreateCollectionParams, ...params };240241 let collectionId = 0;242 await usingApi(async (api) => {243 244 const AcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString(), 10);245246 247 const alicePrivateKey = privateKey('//Alice');248249 let modeprm = {};250 if (mode.type === 'NFT') {251 modeprm = { nft: null };252 } else if (mode.type === 'Fungible') {253 modeprm = { fungible: mode.decimalPoints };254 } else if (mode.type === 'ReFungible') {255 modeprm = { refungible: null };256 } else if (mode.type === 'Invalid') {257 modeprm = { invalid: null };258 }259260 const tx = api.tx.nft.createCollection(strToUTF16(name), strToUTF16(description), strToUTF16(tokenPrefix), modeprm);261 const events = await submitTransactionAsync(alicePrivateKey, tx);262 const result = getCreateCollectionResult(events);263264 265 const BcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString(), 10);266267 268 const collection: any = (await api.query.nft.collectionById(result.collectionId) as any).toJSON();269270 271 272 expect(result.success).to.be.true;273 expect(result.collectionId).to.be.equal(BcollectionCount);274 275 expect(collection).to.be.not.null;276 expect(BcollectionCount).to.be.equal(AcollectionCount + 1, 'Error: NFT collection NOT created.');277 expect(collection.Owner).to.be.equal(toSubstrateAddress(alicesPublicKey));278 expect(utf16ToStr(collection.Name)).to.be.equal(name);279 expect(utf16ToStr(collection.Description)).to.be.equal(description);280 expect(hexToStr(collection.TokenPrefix)).to.be.equal(tokenPrefix);281282 collectionId = result.collectionId;283 });284285 return collectionId;286}287288export async function createCollectionExpectFailure(params: Partial<CreateCollectionParams> = {}) {289 const { name, description, mode, tokenPrefix } = { ...defaultCreateCollectionParams, ...params };290291 let modeprm = {};292 if (mode.type === 'NFT') {293 modeprm = { nft: null };294 } else if (mode.type === 'Fungible') {295 modeprm = { fungible: mode.decimalPoints };296 } else if (mode.type === 'ReFungible') {297 modeprm = { refungible: null };298 } else if (mode.type === 'Invalid') {299 modeprm = { invalid: null };300 }301302 await usingApi(async (api) => {303 304 const AcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString());305306 307 const alicePrivateKey = privateKey('//Alice');308 const tx = api.tx.nft.createCollection(strToUTF16(name), strToUTF16(description), strToUTF16(tokenPrefix), modeprm);309 const events = await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;310 const result = getCreateCollectionResult(events);311312 313 const BcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString());314315 316 317 expect(result.success).to.be.false;318 expect(BcollectionCount).to.be.equal(AcollectionCount, 'Error: Collection with incorrect data created.');319 });320}321322export async function findUnusedAddress(api: ApiPromise, seedAddition = ''): Promise<IKeyringPair> {323 let bal = new BigNumber(0);324 let unused;325 do {326 const randomSeed = 'seed' + Math.floor(Math.random() * Math.floor(10000)) + seedAddition;327 const keyring = new Keyring({ type: 'sr25519' });328 unused = keyring.addFromUri(`//${randomSeed}`);329 bal = new BigNumber((await api.query.system.account(unused.address)).data.free.toString());330 } while (bal.toFixed() != '0');331 return unused;332}333334export async function getAllowance(collectionId: number, tokenId: number, owner: string, approved: string) {335 return await usingApi(async (api) => {336 const bn = await api.query.nft.allowances(collectionId, [tokenId, owner, approved]) as unknown as BN;337 return BigInt(bn.toString());338 });339}340341export function findUnusedAddresses(api: ApiPromise, amount: number): Promise<IKeyringPair[]> {342 return Promise.all(new Array(amount).fill(null).map(() => findUnusedAddress(api, '_' + Date.now())));343}344345export async function findNotExistingCollection(api: ApiPromise): Promise<number> {346 const totalNumber = parseInt((await api.query.nft.createdCollectionCount()).toString(), 10) as unknown as number;347 const newCollection: number = totalNumber + 1;348 return newCollection;349}350351function getDestroyResult(events: EventRecord[]): boolean {352 let success = false;353 events.forEach(({ event: { method } }) => {354 if (method == 'ExtrinsicSuccess') {355 success = true;356 }357 });358 return success;359}360361export async function destroyCollectionExpectFailure(collectionId: number, senderSeed = '//Alice') {362 await usingApi(async (api) => {363 364 const alicePrivateKey = privateKey(senderSeed);365 const tx = api.tx.nft.destroyCollection(collectionId);366 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;367 });368}369370export async function destroyCollectionExpectSuccess(collectionId: number, senderSeed = '//Alice') {371 await usingApi(async (api) => {372 373 const alicePrivateKey = privateKey(senderSeed);374 const tx = api.tx.nft.destroyCollection(collectionId);375 const events = await submitTransactionAsync(alicePrivateKey, tx);376 const result = getDestroyResult(events);377378 379 const collection: any = (await api.query.nft.collectionById(collectionId)).toJSON();380381 382 expect(result).to.be.true;383 expect(collection).to.be.null;384 });385}386387export async function queryCollectionLimits(collectionId: number) {388 return await usingApi(async (api) => {389 return ((await api.query.nft.collectionById(collectionId)).toJSON() as any).Limits;390 });391}392393export async function setCollectionLimitsExpectSuccess(sender: IKeyringPair, collectionId: number, limits: any) {394 await usingApi(async (api) => {395 const oldLimits = await queryCollectionLimits(collectionId);396 const newLimits = { ...oldLimits as any, ...limits };397 const tx = api.tx.nft.setCollectionLimits(collectionId, newLimits);398 const events = await submitTransactionAsync(sender, tx);399 const result = getGenericResult(events);400401 expect(result.success).to.be.true;402 });403}404405export async function setCollectionLimitsExpectFailure(sender: IKeyringPair, collectionId: number, limits: any) {406 await usingApi(async (api) => {407 const oldLimits = await queryCollectionLimits(collectionId);408 const newLimits = { ...oldLimits as any, ...limits };409 const tx = api.tx.nft.setCollectionLimits(collectionId, newLimits);410 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;411 const result = getGenericResult(events);412413 expect(result.success).to.be.false;414 });415}416417export async function setCollectionSponsorExpectSuccess(collectionId: number, sponsor: string) {418 await usingApi(async (api) => {419420 421 const alicePrivateKey = privateKey('//Alice');422 const tx = api.tx.nft.setCollectionSponsor(collectionId, sponsor);423 const events = await submitTransactionAsync(alicePrivateKey, tx);424 const result = getGenericResult(events);425426 427 const collection: any = (await api.query.nft.collectionById(collectionId)).toJSON();428429 430 expect(result.success).to.be.true;431 expect(collection.Sponsorship).to.deep.equal({432 unconfirmed: sponsor,433 });434 });435}436437export async function removeCollectionSponsorExpectSuccess(collectionId: number) {438 await usingApi(async (api) => {439440 441 const alicePrivateKey = privateKey('//Alice');442 const tx = api.tx.nft.removeCollectionSponsor(collectionId);443 const events = await submitTransactionAsync(alicePrivateKey, tx);444 const result = getGenericResult(events);445446 447 const collection: any = (await api.query.nft.collectionById(collectionId)).toJSON();448449 450 expect(result.success).to.be.true;451 expect(collection.Sponsorship).to.be.deep.equal({ disabled: null });452 });453}454455export async function removeCollectionSponsorExpectFailure(collectionId: number) {456 await usingApi(async (api) => {457458 459 const alicePrivateKey = privateKey('//Alice');460 const tx = api.tx.nft.removeCollectionSponsor(collectionId);461 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;462 });463}464465export async function setCollectionSponsorExpectFailure(collectionId: number, sponsor: string, senderSeed = '//Alice') {466 await usingApi(async (api) => {467468 469 const alicePrivateKey = privateKey(senderSeed);470 const tx = api.tx.nft.setCollectionSponsor(collectionId, sponsor);471 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;472 });473}474475export async function confirmSponsorshipExpectSuccess(collectionId: number, senderSeed = '//Alice') {476 await usingApi(async (api) => {477478 479 const sender = privateKey(senderSeed);480 const tx = api.tx.nft.confirmSponsorship(collectionId);481 const events = await submitTransactionAsync(sender, tx);482 const result = getGenericResult(events);483484 485 const collection: any = (await api.query.nft.collectionById(collectionId)).toJSON();486487 488 expect(result.success).to.be.true;489 expect(collection.Sponsorship).to.be.deep.equal({490 confirmed: sender.address,491 });492 });493}494495496export async function confirmSponsorshipExpectFailure(collectionId: number, senderSeed = '//Alice') {497 await usingApi(async (api) => {498499 500 const sender = privateKey(senderSeed);501 const tx = api.tx.nft.confirmSponsorship(collectionId);502 await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;503 });504}505506export async function enableContractSponsoringExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {507 await usingApi(async (api) => {508 const tx = api.tx.nft.enableContractSponsoring(contractAddress, enable);509 const events = await submitTransactionAsync(sender, tx);510 const result = getGenericResult(events);511512 expect(result.success).to.be.true;513 });514}515516export async function enableContractSponsoringExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {517 await usingApi(async (api) => {518 const tx = api.tx.nft.enableContractSponsoring(contractAddress, enable);519 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;520 const result = getGenericResult(events);521522 expect(result.success).to.be.false;523 });524}525526export async function setTransferFlagExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {527528 await usingApi(async (api) => {529530 const tx = api.tx.nft.setTransfersEnabledFlag (collectionId, enabled);531 const events = await submitTransactionAsync(sender, tx);532 const result = getGenericResult(events);533534 expect(result.success).to.be.true;535 }); 536}537538export async function setContractSponsoringRateLimitExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {539 await usingApi(async (api) => {540 const tx = api.tx.nft.setContractSponsoringRateLimit(contractAddress, rateLimit);541 const events = await submitTransactionAsync(sender, tx);542 const result = getGenericResult(events);543544 expect(result.success).to.be.true;545 });546}547548export async function setContractSponsoringRateLimitExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {549 await usingApi(async (api) => {550 const tx = api.tx.nft.setContractSponsoringRateLimit(contractAddress, rateLimit);551 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;552 const result = getGenericResult(events);553554 expect(result.success).to.be.false;555 });556}557558export async function toggleContractWhitelistExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, value: boolean = true) {559 await usingApi(async (api) => {560 const tx = api.tx.nft.toggleContractWhiteList(contractAddress, value);561 const events = await submitTransactionAsync(sender, tx);562 const result = getGenericResult(events);563564 expect(result.success).to.be.true;565 });566}567568export async function isWhitelistedInContract(contractAddress: AccountId | string, user: string) {569 let whitelisted = false;570 await usingApi(async (api) => {571 whitelisted = (await api.query.nft.contractWhiteList(contractAddress, user)).toJSON() as boolean;572 });573 return whitelisted;574}575576export async function addToContractWhiteListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {577 await usingApi(async (api) => {578 const tx = api.tx.nft.addToContractWhiteList(contractAddress.toString(), user.toString());579 const events = await submitTransactionAsync(sender, tx);580 const result = getGenericResult(events);581582 expect(result.success).to.be.true;583 });584}585586export async function removeFromContractWhiteListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {587 await usingApi(async (api) => {588 const tx = api.tx.nft.removeFromContractWhiteList(contractAddress.toString(), user.toString());589 const events = await submitTransactionAsync(sender, tx);590 const result = getGenericResult(events);591592 expect(result.success).to.be.true;593 });594}595596export async function removeFromContractWhiteListExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {597 await usingApi(async (api) => {598 const tx = api.tx.nft.removeFromContractWhiteList(contractAddress.toString(), user.toString());599 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;600 const result = getGenericResult(events);601602 expect(result.success).to.be.false;603 });604}605606export async function setVariableMetaDataExpectSuccess(sender: IKeyringPair, collectionId: number, itemId: number, data: number[]) {607 await usingApi(async (api) => {608 const tx = api.tx.nft.setVariableMetaData(collectionId, itemId, '0x' + Buffer.from(data).toString('hex'));609 const events = await submitTransactionAsync(sender, tx);610 const result = getGenericResult(events);611612 expect(result.success).to.be.true;613 });614}615616export async function setVariableMetaDataExpectFailure(sender: IKeyringPair, collectionId: number, itemId: number, data: number[]) {617 await usingApi(async (api) => {618 const tx = api.tx.nft.setVariableMetaData(collectionId, itemId, '0x' + Buffer.from(data).toString('hex'));619 await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;620 });621}622623export async function setOffchainSchemaExpectSuccess(sender: IKeyringPair, collectionId: number, data: number[]) {624 await usingApi(async (api) => {625 const tx = api.tx.nft.setOffchainSchema(collectionId, '0x' + Buffer.from(data).toString('hex'));626 const events = await submitTransactionAsync(sender, tx);627 const result = getGenericResult(events);628629 expect(result.success).to.be.true;630 });631}632633export async function setOffchainSchemaExpectFailure(sender: IKeyringPair, collectionId: number, data: number[]) {634 await usingApi(async (api) => {635 const tx = api.tx.nft.setOffchainSchema(collectionId, '0x' + Buffer.from(data).toString('hex'));636 await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;637 });638}639640export interface CreateFungibleData {641 readonly Value: bigint;642}643644export interface CreateReFungibleData { }645export interface CreateNftData { }646647export type CreateItemData = {648 NFT: CreateNftData;649} | {650 Fungible: CreateFungibleData;651} | {652 ReFungible: CreateReFungibleData;653};654655export async function burnItemExpectSuccess(owner: IKeyringPair, collectionId: number, tokenId: number, value = 0) {656 await usingApi(async (api) => {657 const tx = api.tx.nft.burnItem(collectionId, tokenId, value);658 const events = await submitTransactionAsync(owner, tx);659 const result = getGenericResult(events);660 661 const item: any = (await api.query.nft.nftItemList(collectionId, tokenId)).toJSON();662 663 664 expect(result.success).to.be.true;665 666 expect(item).to.be.null;667 });668}669670export async function671approveExpectSuccess(672 collectionId: number,673 tokenId: number, owner: IKeyringPair, approved: IKeyringPair | CrossAccountId | string, amount: number | bigint = 1,674) {675 await usingApi(async (api: ApiPromise) => {676 approved = normalizeAccountId(approved);677 const allowanceBefore =678 await api.query.nft.allowances(collectionId, [tokenId, owner.address, toSubstrateAddress(approved)]) as unknown as BN;679 const approveNftTx = api.tx.nft.approve(approved, collectionId, tokenId, amount);680 const events = await submitTransactionAsync(owner, approveNftTx);681 const result = getCreateItemResult(events);682 683 expect(result.success).to.be.true;684 const allowanceAfter =685 await api.query.nft.allowances(collectionId, [tokenId, owner.address, toSubstrateAddress(approved)]) as unknown as BN;686 expect(allowanceAfter.sub(allowanceBefore).toString()).to.be.equal(amount.toString());687 });688}689690export async function691transferFromExpectSuccess(692 collectionId: number,693 tokenId: number,694 accountApproved: IKeyringPair,695 accountFrom: IKeyringPair | CrossAccountId,696 accountTo: IKeyringPair | CrossAccountId,697 value: number | bigint = 1,698 type = 'NFT',699) {700 await usingApi(async (api: ApiPromise) => {701 const to = normalizeAccountId(accountTo);702 let balanceBefore = new BN(0);703 if (type === 'Fungible') {704 balanceBefore = await api.query.nft.balance(collectionId, toSubstrateAddress(to)) as unknown as BN;705 }706 const transferFromTx = api.tx.nft.transferFrom(normalizeAccountId(accountFrom), to, collectionId, tokenId, value);707 const events = await submitTransactionAsync(accountApproved, transferFromTx);708 const result = getCreateItemResult(events);709 710 expect(result.success).to.be.true;711 if (type === 'NFT') {712 const nftItemData = (await api.query.nft.nftItemList(collectionId, tokenId) as any).toJSON() as ITokenDataType;713 expect(nftItemData.Owner).to.be.deep.equal(to);714 }715 if (type === 'Fungible') {716 const balanceAfter = (await api.query.nft.fungibleItemList(collectionId, toSubstrateAddress(to)) as any).Value as unknown as BN;717 expect(balanceAfter.sub(balanceBefore).toString()).to.be.equal(value.toString());718 }719 if (type === 'ReFungible') {720 const nftItemData =721 (await api.query.nft.reFungibleItemList(collectionId, tokenId) as any).toJSON() as IReFungibleTokenDataType;722 expect(nftItemData.Owner[0].Owner).to.be.deep.equal(normalizeAccountId(to));723 expect(nftItemData.Owner[0].Fraction).to.be.equal(value);724 }725 });726}727728export async function729transferFromExpectFail(730 collectionId: number,731 tokenId: number,732 accountApproved: IKeyringPair,733 accountFrom: IKeyringPair,734 accountTo: IKeyringPair,735 value: number | bigint = 1,736) {737 await usingApi(async (api: ApiPromise) => {738 const transferFromTx = api.tx.nft.transferFrom(normalizeAccountId(accountFrom.address), normalizeAccountId(accountTo.address), collectionId, tokenId, value);739 const events = await expect(submitTransactionExpectFailAsync(accountApproved, transferFromTx)).to.be.rejected;740 const result = getCreateCollectionResult(events);741 742 expect(result.success).to.be.false;743 });744}745746747async function getBlockNumber(api: ApiPromise): Promise<number> {748 return new Promise<number>(async (resolve) => {749 const unsubscribe = await api.rpc.chain.subscribeNewHeads((head) => {750 unsubscribe();751 resolve(head.number.toNumber());752 });753 });754}755756export async function757scheduleTransferExpectSuccess(758 collectionId: number,759 tokenId: number,760 sender: IKeyringPair,761 recipient: IKeyringPair,762 value: number | bigint = 1,763 blockTimeMs: number,764 blockSchedule: number765) {766 await usingApi(async (api: ApiPromise) => {767 const blockNumber: number | undefined = await getBlockNumber(api);768 const expectedBlockNumber = blockNumber + blockSchedule;769770 expect(blockNumber).to.be.greaterThan(0);771 const transferTx = await api.tx.nft.transfer(normalizeAccountId(recipient.address), collectionId, tokenId, value); 772 const scheduleTx = await api.tx.scheduler.schedule(expectedBlockNumber, null, 0, transferTx);773774 await submitTransactionAsync(sender, scheduleTx);775776 const recipientBalanceBefore = new BigNumber((await api.query.system.account(recipient.address)).data.free.toString());777778 const nftItemDataBefore = (await api.query.nft.nftItemList(collectionId, tokenId)).toJSON() as any as ITokenDataType;779 expect(toSubstrateAddress(nftItemDataBefore.Owner)).to.be.equal(sender.address);780781 782 await new Promise(resolve => setTimeout(resolve, blockTimeMs * (blockSchedule + 1)));783784 const recipientBalanceAfter = new BigNumber((await api.query.system.account(recipient.address)).data.free.toString());785786 const nftItemData = (await api.query.nft.nftItemList(collectionId, tokenId)).toJSON() as unknown as ITokenDataType;787 expect(toSubstrateAddress(nftItemData.Owner)).to.be.equal(recipient.address);788 expect(recipientBalanceAfter.toNumber()).to.be.equal(recipientBalanceBefore.toNumber());789 });790}791792793export async function794transferExpectSuccess(795 collectionId: number,796 tokenId: number,797 sender: IKeyringPair,798 recipient: IKeyringPair | CrossAccountId,799 value: number | bigint = 1,800 type = 'NFT',801) {802 await usingApi(async (api: ApiPromise) => {803 const to = normalizeAccountId(recipient);804805 let balanceBefore = new BN(0);806 if (type === 'Fungible') {807 balanceBefore = await api.query.nft.balance(collectionId, toSubstrateAddress(to)) as unknown as BN;808 }809 const transferTx = api.tx.nft.transfer(to, collectionId, tokenId, value);810 const events = await submitTransactionAsync(sender, transferTx);811 const result = getTransferResult(events);812 813 expect(result.success).to.be.true;814 expect(result.collectionId).to.be.equal(collectionId);815 expect(result.itemId).to.be.equal(tokenId);816 expect(result.sender).to.be.deep.equal(normalizeAccountId(sender.address));817 expect(result.recipient).to.be.deep.equal(to);818 expect(result.value.toString()).to.be.equal(value.toString());819 if (type === 'NFT') {820 const nftItemData = (await api.query.nft.nftItemList(collectionId, tokenId)).toJSON() as unknown as ITokenDataType;821 expect(nftItemData.Owner).to.be.deep.equal(to);822 }823 if (type === 'Fungible') {824 const balanceAfter = (await api.query.nft.fungibleItemList(collectionId, toSubstrateAddress(to)) as any).Value as unknown as BN;825 expect(balanceAfter.sub(balanceBefore).toString()).to.be.equal(value.toString());826 }827 if (type === 'ReFungible') {828 const nftItemData =829 (await api.query.nft.reFungibleItemList(collectionId, tokenId)).toJSON() as unknown as IReFungibleTokenDataType;830 expect(nftItemData.Owner[0].Owner).to.be.deep.equal(to);831 expect(nftItemData.Owner[0].Fraction.toString()).to.be.equal(value.toString());832 }833 });834}835836export async function837transferExpectFailure(838 collectionId: number,839 tokenId: number,840 sender: IKeyringPair,841 recipient: IKeyringPair,842 value: number | bigint = 1,843) {844 await usingApi(async (api: ApiPromise) => {845 const transferTx = api.tx.nft.transfer(normalizeAccountId(recipient.address), collectionId, tokenId, value);846 const events = await expect(submitTransactionExpectFailAsync(sender, transferTx)).to.be.rejected;847 if (events && Array.isArray(events)) {848 const result = getCreateCollectionResult(events);849 850 expect(result.success).to.be.false;851 }852 });853}854855export async function856approveExpectFail(857 collectionId: number,858 tokenId: number, owner: IKeyringPair, approved: IKeyringPair, amount: number | bigint = 1,859) {860 await usingApi(async (api: ApiPromise) => {861 const approveNftTx = api.tx.nft.approve(normalizeAccountId(approved.address), collectionId, tokenId, amount);862 const events = await expect(submitTransactionExpectFailAsync(owner, approveNftTx)).to.be.rejected;863 const result = getCreateCollectionResult(events);864 865 expect(result.success).to.be.false;866 });867}868869export async function getFungibleBalance(870 collectionId: number,871 owner: string,872) {873 return await usingApi(async (api) => {874 const response = (await api.query.nft.fungibleItemList(collectionId, owner)).toJSON() as unknown as { Value: string };875 return BigInt(response.Value);876 });877}878879export async function createFungibleItemExpectSuccess(880 sender: IKeyringPair,881 collectionId: number,882 data: CreateFungibleData,883 owner: CrossAccountId | string = sender.address,884) {885 return await usingApi(async (api) => {886 const tx = api.tx.nft.createItem(collectionId, normalizeAccountId(owner), { Fungible: data });887888 const events = await submitTransactionAsync(sender, tx);889 const result = getCreateItemResult(events);890891 expect(result.success).to.be.true;892 return result.itemId;893 });894}895896export async function createItemExpectSuccess(sender: IKeyringPair, collectionId: number, createMode: string, owner: CrossAccountId | string = sender.address) {897 let newItemId = 0;898 await usingApi(async (api) => {899 const to = normalizeAccountId(owner);900 const AItemCount = parseInt((await api.query.nft.itemListIndex(collectionId)).toString(), 10);901 const Aitem: any = (await api.query.nft.fungibleItemList(collectionId, toSubstrateAddress(to))).toJSON();902 const AItemBalance = new BigNumber(Aitem.Value);903904 let tx;905 if (createMode === 'Fungible') {906 const createData = { fungible: { value: 10 } };907 tx = api.tx.nft.createItem(collectionId, to, createData);908 } else if (createMode === 'ReFungible') {909 const createData = { refungible: { const_data: [], variable_data: [], pieces: 100 } };910 tx = api.tx.nft.createItem(collectionId, to, createData);911 } else {912 const createData = { nft: { const_data: [], variable_data: [] } };913 tx = api.tx.nft.createItem(collectionId, to, createData);914 }915916 const events = await submitTransactionAsync(sender, tx);917 const result = getCreateItemResult(events);918919 const BItemCount = parseInt((await api.query.nft.itemListIndex(collectionId)).toString(), 10);920 const Bitem: any = (await api.query.nft.fungibleItemList(collectionId, toSubstrateAddress(to))).toJSON();921 const BItemBalance = new BigNumber(Bitem.Value);922923 924 925 expect(result.success).to.be.true;926 if (createMode === 'Fungible') {927 expect(BItemBalance.minus(AItemBalance).toNumber()).to.be.equal(10);928 } else {929 expect(BItemCount).to.be.equal(AItemCount + 1);930 }931 expect(collectionId).to.be.equal(result.collectionId);932 expect(BItemCount.toString()).to.be.equal(result.itemId.toString());933 expect(to).to.be.deep.equal(result.recipient);934 newItemId = result.itemId;935 });936 return newItemId;937}938939export async function createItemExpectFailure(sender: IKeyringPair, collectionId: number, createMode: string, owner: string = sender.address) {940 await usingApi(async (api) => {941 const tx = api.tx.nft.createItem(collectionId, normalizeAccountId(owner), createMode);942 943 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;944 const result = getCreateItemResult(events);945946 expect(result.success).to.be.false;947 });948}949950export async function setPublicAccessModeExpectSuccess(951 sender: IKeyringPair, collectionId: number,952 accessMode: 'Normal' | 'WhiteList',953) {954 await usingApi(async (api) => {955956 957 const tx = api.tx.nft.setPublicAccessMode(collectionId, accessMode);958 const events = await submitTransactionAsync(sender, tx);959 const result = getGenericResult(events);960961 962 const collection: any = (await api.query.nft.collectionById(collectionId)).toJSON();963964 965 966 expect(result.success).to.be.true;967 expect(collection.Access).to.be.equal(accessMode);968 });969}970971export async function enableWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number) {972 await setPublicAccessModeExpectSuccess(sender, collectionId, 'WhiteList');973}974975export async function disableWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number) {976 await setPublicAccessModeExpectSuccess(sender, collectionId, 'Normal');977}978979export async function setMintPermissionExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {980 await usingApi(async (api) => {981982 983 const tx = api.tx.nft.setMintPermission(collectionId, enabled);984 const events = await submitTransactionAsync(sender, tx);985 const result = getGenericResult(events);986987 988 const collection: any = (await api.query.nft.collectionById(collectionId)).toJSON();989990 991 992 expect(result.success).to.be.true;993 expect(collection.MintMode).to.be.equal(enabled);994 });995}996997export async function enablePublicMintingExpectSuccess(sender: IKeyringPair, collectionId: number) {998 await setMintPermissionExpectSuccess(sender, collectionId, true);999}10001001export async function setMintPermissionExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {1002 await usingApi(async (api) => {1003 1004 const tx = api.tx.nft.setMintPermission(collectionId, enabled);1005 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1006 const result = getCreateCollectionResult(events);1007 1008 expect(result.success).to.be.false;1009 });1010}10111012export async function isWhitelisted(collectionId: number, address: string) {1013 let whitelisted = false;1014 await usingApi(async (api) => {1015 whitelisted = (await api.query.nft.whiteList(collectionId, address)).toJSON() as unknown as boolean;1016 });1017 return whitelisted;1018}10191020export async function addToWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId) {1021 await usingApi(async (api) => {10221023 const whiteListedBefore = (await api.query.nft.whiteList(collectionId, address)).toJSON();10241025 1026 const tx = api.tx.nft.addToWhiteList(collectionId, normalizeAccountId(address));1027 const events = await submitTransactionAsync(sender, tx);1028 const result = getGenericResult(events);10291030 const whiteListedAfter = (await api.query.nft.whiteList(collectionId, address)).toJSON();10311032 1033 1034 expect(result.success).to.be.true;1035 1036 expect(whiteListedBefore).to.be.false;1037 1038 expect(whiteListedAfter).to.be.true;1039 });1040}10411042export async function removeFromWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1043 await usingApi(async (api) => {1044 1045 const tx = api.tx.nft.removeFromWhiteList(collectionId, normalizeAccountId(address));1046 const events = await submitTransactionAsync(sender, tx);1047 const result = getGenericResult(events);10481049 1050 1051 expect(result.success).to.be.true;1052 });1053}10541055export async function removeFromWhiteListExpectFailure(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1056 await usingApi(async (api) => {1057 1058 const tx = api.tx.nft.removeFromWhiteList(collectionId, normalizeAccountId(address));1059 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1060 const result = getGenericResult(events);10611062 1063 1064 expect(result.success).to.be.false;1065 });1066}10671068export const getDetailedCollectionInfo = async (api: ApiPromise, collectionId: number)1069 : Promise<ICollectionInterface | null> => {1070 return (await api.query.nft.collectionById(collectionId)).toJSON() as unknown as ICollectionInterface;1071};10721073export const getCreatedCollectionCount = async (api: ApiPromise): Promise<number> => {1074 1075 return (await api.query.nft.createdCollectionCount() as unknown as BN).toNumber();1076};10771078export async function queryCollectionExpectSuccess(collectionId: number): Promise<ICollectionInterface> {1079 return await usingApi(async (api) => {1080 return (await api.query.nft.collectionById(collectionId)).toJSON() as unknown as ICollectionInterface;1081 });1082}