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;5556const MICROUNIQUE = 1_000_000_000n;57const MILLIUNIQUE = 1_000n * MICROUNIQUE;58const CENTIUNIQUE = 10n * MILLIUNIQUE;59export const UNIQUE = 100n * CENTIUNIQUE;6061type GenericResult = {62 success: boolean,63};6465interface CreateCollectionResult {66 success: boolean;67 collectionId: number;68}6970interface CreateItemResult {71 success: boolean;72 collectionId: number;73 itemId: number;74 recipient?: CrossAccountId;75}7677interface TransferResult {78 success: boolean;79 collectionId: number;80 itemId: number;81 sender?: CrossAccountId;82 recipient?: CrossAccountId;83 value: bigint;84}8586interface IReFungibleOwner {87 Fraction: BN;88 Owner: number[];89}9091interface ITokenDataType {92 Owner: IKeyringPair;93 ConstData: number[];94 VariableData: number[];95}9697interface IGetMessage {98 checkMsgNftMethod: string;99 checkMsgTrsMethod: string;100 checkMsgSysMethod: string;101}102103export interface IFungibleTokenDataType {104 Value: number;105}106107export interface IChainLimits {108 CollectionNumbersLimit: number;109 AccountTokenOwnershipLimit: number;110 CollectionsAdminsLimit: number;111 CustomDataLimit: number;112 NftSponsorTransferTimeout: number;113 FungibleSponsorTransferTimeout: number;114 RefungibleSponsorTransferTimeout: number;115 OffchainSchemaLimit: number;116 VariableOnChainSchemaLimit: number;117 ConstOnChainSchemaLimit: number;118}119120export interface IReFungibleTokenDataType {121 Owner: IReFungibleOwner[];122 ConstData: number[];123 VariableData: number[];124}125126export function nftEventMessage(events: EventRecord[]): IGetMessage {127 let checkMsgNftMethod = '';128 let checkMsgTrsMethod = '';129 let checkMsgSysMethod = '';130 events.forEach(({ event: { method, section } }) => {131 if (section === 'nft') {132 checkMsgNftMethod = method;133 } else if (section === 'treasury') {134 checkMsgTrsMethod = method;135 } else if (section === 'system') {136 checkMsgSysMethod = method;137 } else { return null; }138 });139 const result: IGetMessage = {140 checkMsgNftMethod,141 checkMsgTrsMethod,142 checkMsgSysMethod,143 };144 return result;145}146147export function getGenericResult(events: EventRecord[]): GenericResult {148 const result: GenericResult = {149 success: false,150 };151 events.forEach(({ event: { method } }) => {152 153 if (method === 'ExtrinsicSuccess') {154 result.success = true;155 }156 });157 return result;158}159160161162export function getCreateCollectionResult(events: EventRecord[]): CreateCollectionResult {163 let success = false;164 let collectionId = 0;165 events.forEach(({ event: { data, method, section } }) => {166 167 if (method == 'ExtrinsicSuccess') {168 success = true;169 } else if ((section == 'nft') && (method == 'CollectionCreated')) {170 collectionId = parseInt(data[0].toString());171 }172 });173 const result: CreateCollectionResult = {174 success,175 collectionId,176 };177 return result;178}179180export function getCreateItemResult(events: EventRecord[]): CreateItemResult {181 let success = false;182 let collectionId = 0;183 let itemId = 0;184 let recipient;185 events.forEach(({ event: { data, method, section } }) => {186 187 if (method == 'ExtrinsicSuccess') {188 success = true;189 } else if ((section == 'nft') && (method == 'ItemCreated')) {190 collectionId = parseInt(data[0].toString());191 itemId = parseInt(data[1].toString());192 recipient = data[2].toJSON();193 }194 });195 const result: CreateItemResult = {196 success,197 collectionId,198 itemId,199 recipient,200 };201 return result;202}203204export function getTransferResult(events: EventRecord[]): TransferResult {205 const result: TransferResult = {206 success: false,207 collectionId: 0,208 itemId: 0,209 value: 0n,210 };211212 events.forEach(({ event: { data, method, section } }) => {213 if (method === 'ExtrinsicSuccess') {214 result.success = true;215 } else if (section === 'nft' && method === 'Transfer') {216 result.collectionId = +data[0].toString();217 result.itemId = +data[1].toString();218 result.sender = data[2].toJSON() as CrossAccountId;219 result.recipient = data[3].toJSON() as CrossAccountId;220 result.value = BigInt(data[4].toString());221 }222 });223224 return result;225}226227interface Invalid {228 type: 'Invalid';229}230231interface Nft {232 type: 'NFT';233}234235interface Fungible {236 type: 'Fungible';237 decimalPoints: number;238}239240interface ReFungible {241 type: 'ReFungible';242}243244type CollectionMode = Nft | Fungible | ReFungible | Invalid;245246export type CreateCollectionParams = {247 mode: CollectionMode,248 name: string,249 description: string,250 tokenPrefix: string,251};252253const defaultCreateCollectionParams: CreateCollectionParams = {254 description: 'description',255 mode: { type: 'NFT' },256 name: 'name',257 tokenPrefix: 'prefix',258};259260export async function createCollectionExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {261 const { name, description, mode, tokenPrefix } = { ...defaultCreateCollectionParams, ...params };262263 let collectionId = 0;264 await usingApi(async (api) => {265 266 const AcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString(), 10);267268 269 const alicePrivateKey = privateKey('//Alice');270271 let modeprm = {};272 if (mode.type === 'NFT') {273 modeprm = { nft: null };274 } else if (mode.type === 'Fungible') {275 modeprm = { fungible: mode.decimalPoints };276 } else if (mode.type === 'ReFungible') {277 modeprm = { refungible: null };278 } else if (mode.type === 'Invalid') {279 modeprm = { invalid: null };280 }281282 const tx = api.tx.nft.createCollection(strToUTF16(name), strToUTF16(description), strToUTF16(tokenPrefix), modeprm);283 const events = await submitTransactionAsync(alicePrivateKey, tx);284 const result = getCreateCollectionResult(events);285286 287 const BcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString(), 10);288289 290 const collection: any = (await api.query.nft.collectionById(result.collectionId) as any).toJSON();291292 293 294 expect(result.success).to.be.true;295 expect(result.collectionId).to.be.equal(BcollectionCount);296 297 expect(collection).to.be.not.null;298 expect(BcollectionCount).to.be.equal(AcollectionCount + 1, 'Error: NFT collection NOT created.');299 expect(collection.Owner).to.be.equal(toSubstrateAddress(alicesPublicKey));300 expect(utf16ToStr(collection.Name)).to.be.equal(name);301 expect(utf16ToStr(collection.Description)).to.be.equal(description);302 expect(hexToStr(collection.TokenPrefix)).to.be.equal(tokenPrefix);303304 collectionId = result.collectionId;305 });306307 return collectionId;308}309310export async function createCollectionExpectFailure(params: Partial<CreateCollectionParams> = {}) {311 const { name, description, mode, tokenPrefix } = { ...defaultCreateCollectionParams, ...params };312313 let modeprm = {};314 if (mode.type === 'NFT') {315 modeprm = { nft: null };316 } else if (mode.type === 'Fungible') {317 modeprm = { fungible: mode.decimalPoints };318 } else if (mode.type === 'ReFungible') {319 modeprm = { refungible: null };320 } else if (mode.type === 'Invalid') {321 modeprm = { invalid: null };322 }323324 await usingApi(async (api) => {325 326 const AcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString());327328 329 const alicePrivateKey = privateKey('//Alice');330 const tx = api.tx.nft.createCollection(strToUTF16(name), strToUTF16(description), strToUTF16(tokenPrefix), modeprm);331 const events = await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;332 const result = getCreateCollectionResult(events);333334 335 const BcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString());336337 338 339 expect(result.success).to.be.false;340 expect(BcollectionCount).to.be.equal(AcollectionCount, 'Error: Collection with incorrect data created.');341 });342}343344export async function findUnusedAddress(api: ApiPromise, seedAddition = ''): Promise<IKeyringPair> {345 let bal = new BigNumber(0);346 let unused;347 do {348 const randomSeed = 'seed' + Math.floor(Math.random() * Math.floor(10000)) + seedAddition;349 const keyring = new Keyring({ type: 'sr25519' });350 unused = keyring.addFromUri(`//${randomSeed}`);351 bal = new BigNumber((await api.query.system.account(unused.address)).data.free.toString());352 } while (bal.toFixed() != '0');353 return unused;354}355356export async function getAllowance(collectionId: number, tokenId: number, owner: string, approved: string) {357 return await usingApi(async (api) => {358 const bn = await api.query.nft.allowances(collectionId, [tokenId, owner, approved]) as unknown as BN;359 return BigInt(bn.toString());360 });361}362363export function findUnusedAddresses(api: ApiPromise, amount: number): Promise<IKeyringPair[]> {364 return Promise.all(new Array(amount).fill(null).map(() => findUnusedAddress(api, '_' + Date.now())));365}366367export async function findNotExistingCollection(api: ApiPromise): Promise<number> {368 const totalNumber = parseInt((await api.query.nft.createdCollectionCount()).toString(), 10) as unknown as number;369 const newCollection: number = totalNumber + 1;370 return newCollection;371}372373function getDestroyResult(events: EventRecord[]): boolean {374 let success = false;375 events.forEach(({ event: { method } }) => {376 if (method == 'ExtrinsicSuccess') {377 success = true;378 }379 });380 return success;381}382383export async function destroyCollectionExpectFailure(collectionId: number, senderSeed = '//Alice') {384 await usingApi(async (api) => {385 386 const alicePrivateKey = privateKey(senderSeed);387 const tx = api.tx.nft.destroyCollection(collectionId);388 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;389 });390}391392export async function destroyCollectionExpectSuccess(collectionId: number, senderSeed = '//Alice') {393 await usingApi(async (api) => {394 395 const alicePrivateKey = privateKey(senderSeed);396 const tx = api.tx.nft.destroyCollection(collectionId);397 const events = await submitTransactionAsync(alicePrivateKey, tx);398 const result = getDestroyResult(events);399400 401 const collection: any = (await api.query.nft.collectionById(collectionId)).toJSON();402403 404 expect(result).to.be.true;405 expect(collection).to.be.null;406 });407}408409export async function queryCollectionLimits(collectionId: number) {410 return await usingApi(async (api) => {411 return ((await api.query.nft.collectionById(collectionId)).toJSON() as any).Limits;412 });413}414415export async function setCollectionLimitsExpectSuccess(sender: IKeyringPair, collectionId: number, limits: any) {416 await usingApi(async (api) => {417 const oldLimits = await queryCollectionLimits(collectionId);418 const newLimits = { ...oldLimits as any, ...limits };419 const tx = api.tx.nft.setCollectionLimits(collectionId, newLimits);420 const events = await submitTransactionAsync(sender, tx);421 const result = getGenericResult(events);422423 expect(result.success).to.be.true;424 });425}426427export async function setCollectionLimitsExpectFailure(sender: IKeyringPair, collectionId: number, limits: any) {428 await usingApi(async (api) => {429 const oldLimits = await queryCollectionLimits(collectionId);430 const newLimits = { ...oldLimits as any, ...limits };431 const tx = api.tx.nft.setCollectionLimits(collectionId, newLimits);432 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;433 const result = getGenericResult(events);434435 expect(result.success).to.be.false;436 });437}438439export async function setCollectionSponsorExpectSuccess(collectionId: number, sponsor: string, sender = '//Alice') {440 await usingApi(async (api) => {441442 443 const senderPrivateKey = privateKey(sender);444 const tx = api.tx.nft.setCollectionSponsor(collectionId, sponsor);445 const events = await submitTransactionAsync(senderPrivateKey, tx);446 const result = getGenericResult(events);447448 449 const collection: any = (await api.query.nft.collectionById(collectionId)).toJSON();450451 452 expect(result.success).to.be.true;453 expect(collection.Sponsorship).to.deep.equal({454 unconfirmed: sponsor,455 });456 });457}458459export async function removeCollectionSponsorExpectSuccess(collectionId: number, sender = '//Alice') {460 await usingApi(async (api) => {461462 463 const alicePrivateKey = privateKey(sender);464 const tx = api.tx.nft.removeCollectionSponsor(collectionId);465 const events = await submitTransactionAsync(alicePrivateKey, tx);466 const result = getGenericResult(events);467468 469 const collection: any = (await api.query.nft.collectionById(collectionId)).toJSON();470471 472 expect(result.success).to.be.true;473 expect(collection.Sponsorship).to.be.deep.equal({ disabled: null });474 });475}476477export async function removeCollectionSponsorExpectFailure(collectionId: number, senderSeed = '//Alice') {478 await usingApi(async (api) => {479480 481 const alicePrivateKey = privateKey(senderSeed);482 const tx = api.tx.nft.removeCollectionSponsor(collectionId);483 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;484 });485}486487export async function setCollectionSponsorExpectFailure(collectionId: number, sponsor: string, senderSeed = '//Alice') {488 await usingApi(async (api) => {489490 491 const alicePrivateKey = privateKey(senderSeed);492 const tx = api.tx.nft.setCollectionSponsor(collectionId, sponsor);493 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;494 });495}496497export async function confirmSponsorshipExpectSuccess(collectionId: number, senderSeed = '//Alice') {498 await usingApi(async (api) => {499500 501 const sender = privateKey(senderSeed);502 const tx = api.tx.nft.confirmSponsorship(collectionId);503 const events = await submitTransactionAsync(sender, tx);504 const result = getGenericResult(events);505506 507 const collection: any = (await api.query.nft.collectionById(collectionId)).toJSON();508509 510 expect(result.success).to.be.true;511 expect(collection.Sponsorship).to.be.deep.equal({512 confirmed: sender.address,513 });514 });515}516517518export async function confirmSponsorshipExpectFailure(collectionId: number, senderSeed = '//Alice') {519 await usingApi(async (api) => {520521 522 const sender = privateKey(senderSeed);523 const tx = api.tx.nft.confirmSponsorship(collectionId);524 await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;525 });526}527528export async function setMetadataUpdatePermissionFlagExpectSuccess(sender: IKeyringPair, collectionId: number, flag: string) {529530 await usingApi(async (api) => {531 const tx = api.tx.nft.setMetaUpdatePermissionFlag(collectionId, flag); 532 const events = await submitTransactionAsync(sender, tx);533 const result = getGenericResult(events);534535 expect(result.success).to.be.true;536 }); 537}538539export async function setMetadataUpdatePermissionFlagExpectFailure(sender: IKeyringPair, collectionId: number, flag: string) {540541 await usingApi(async (api) => {542 const tx = api.tx.nft.setMetaUpdatePermissionFlag(collectionId, flag); 543 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;544 const result = getGenericResult(events);545546 expect(result.success).to.be.false;547 }); 548}549550export async function enableContractSponsoringExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {551 await usingApi(async (api) => {552 const tx = api.tx.nft.enableContractSponsoring(contractAddress, enable);553 const events = await submitTransactionAsync(sender, tx);554 const result = getGenericResult(events);555556 expect(result.success).to.be.true;557 });558}559560export async function enableContractSponsoringExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {561 await usingApi(async (api) => {562 const tx = api.tx.nft.enableContractSponsoring(contractAddress, enable);563 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;564 const result = getGenericResult(events);565566 expect(result.success).to.be.false;567 });568}569570export async function setTransferFlagExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {571572 await usingApi(async (api) => {573574 const tx = api.tx.nft.setTransfersEnabledFlag (collectionId, enabled);575 const events = await submitTransactionAsync(sender, tx);576 const result = getGenericResult(events);577578 expect(result.success).to.be.true;579 }); 580}581582export async function setTransferFlagExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {583584 await usingApi(async (api) => {585586 const tx = api.tx.nft.setTransfersEnabledFlag (collectionId, enabled);587 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;588 const result = getGenericResult(events);589590 expect(result.success).to.be.false;591 }); 592}593594export async function setContractSponsoringRateLimitExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {595 await usingApi(async (api) => {596 const tx = api.tx.nft.setContractSponsoringRateLimit(contractAddress, rateLimit);597 const events = await submitTransactionAsync(sender, tx);598 const result = getGenericResult(events);599600 expect(result.success).to.be.true;601 });602}603604export async function setContractSponsoringRateLimitExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {605 await usingApi(async (api) => {606 const tx = api.tx.nft.setContractSponsoringRateLimit(contractAddress, rateLimit);607 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;608 const result = getGenericResult(events);609610 expect(result.success).to.be.false;611 });612}613614export async function toggleContractWhitelistExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, value = true) {615 await usingApi(async (api) => {616 const tx = api.tx.nft.toggleContractWhiteList(contractAddress, value);617 const events = await submitTransactionAsync(sender, tx);618 const result = getGenericResult(events);619620 expect(result.success).to.be.true;621 });622}623624export async function isWhitelistedInContract(contractAddress: AccountId | string, user: string) {625 let whitelisted = false;626 await usingApi(async (api) => {627 whitelisted = (await api.query.nft.contractWhiteList(contractAddress, user)).toJSON() as boolean;628 });629 return whitelisted;630}631632export async function addToContractWhiteListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {633 await usingApi(async (api) => {634 const tx = api.tx.nft.addToContractWhiteList(contractAddress.toString(), user.toString());635 const events = await submitTransactionAsync(sender, tx);636 const result = getGenericResult(events);637638 expect(result.success).to.be.true;639 });640}641642export async function removeFromContractWhiteListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {643 await usingApi(async (api) => {644 const tx = api.tx.nft.removeFromContractWhiteList(contractAddress.toString(), user.toString());645 const events = await submitTransactionAsync(sender, tx);646 const result = getGenericResult(events);647648 expect(result.success).to.be.true;649 });650}651652export async function removeFromContractWhiteListExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {653 await usingApi(async (api) => {654 const tx = api.tx.nft.removeFromContractWhiteList(contractAddress.toString(), user.toString());655 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;656 const result = getGenericResult(events);657658 expect(result.success).to.be.false;659 });660}661662export async function setVariableMetaDataExpectSuccess(sender: IKeyringPair, collectionId: number, itemId: number, data: number[]) {663 await usingApi(async (api) => {664 const tx = api.tx.nft.setVariableMetaData(collectionId, itemId, '0x' + Buffer.from(data).toString('hex'));665 const events = await submitTransactionAsync(sender, tx);666 const result = getGenericResult(events);667668 expect(result.success).to.be.true;669 });670}671672export async function setVariableMetaDataExpectFailure(sender: IKeyringPair, collectionId: number, itemId: number, data: number[]) {673 await usingApi(async (api) => {674 const tx = api.tx.nft.setVariableMetaData(collectionId, itemId, '0x' + Buffer.from(data).toString('hex'));675 await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;676 });677}678679export async function setOffchainSchemaExpectSuccess(sender: IKeyringPair, collectionId: number, data: number[]) {680 await usingApi(async (api) => {681 const tx = api.tx.nft.setOffchainSchema(collectionId, '0x' + Buffer.from(data).toString('hex'));682 const events = await submitTransactionAsync(sender, tx);683 const result = getGenericResult(events);684685 expect(result.success).to.be.true;686 });687}688689export async function setOffchainSchemaExpectFailure(sender: IKeyringPair, collectionId: number, data: number[]) {690 await usingApi(async (api) => {691 const tx = api.tx.nft.setOffchainSchema(collectionId, '0x' + Buffer.from(data).toString('hex'));692 await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;693 });694}695696export interface CreateFungibleData {697 readonly Value: bigint;698}699700export interface CreateReFungibleData { }701export interface CreateNftData { }702703export type CreateItemData = {704 NFT: CreateNftData;705} | {706 Fungible: CreateFungibleData;707} | {708 ReFungible: CreateReFungibleData;709};710711export async function burnItemExpectSuccess(owner: IKeyringPair, collectionId: number, tokenId: number, value = 0) {712 await usingApi(async (api) => {713 const tx = api.tx.nft.burnItem(collectionId, tokenId, value);714 const events = await submitTransactionAsync(owner, tx);715 const result = getGenericResult(events);716 717 const item: any = (await api.query.nft.nftItemList(collectionId, tokenId)).toJSON();718 719 720 expect(result.success).to.be.true;721 722 expect(item).to.be.null;723 });724}725726export async function727approveExpectSuccess(728 collectionId: number,729 tokenId: number, owner: IKeyringPair, approved: IKeyringPair | CrossAccountId | string, amount: number | bigint = 1,730) {731 await usingApi(async (api: ApiPromise) => {732 approved = normalizeAccountId(approved);733 const allowanceBefore =734 await api.query.nft.allowances(collectionId, [tokenId, owner.address, toSubstrateAddress(approved)]) as unknown as BN;735 const approveNftTx = api.tx.nft.approve(approved, collectionId, tokenId, amount);736 const events = await submitTransactionAsync(owner, approveNftTx);737 const result = getCreateItemResult(events);738 739 expect(result.success).to.be.true;740 const allowanceAfter =741 await api.query.nft.allowances(collectionId, [tokenId, owner.address, toSubstrateAddress(approved)]) as unknown as BN;742 expect(allowanceAfter.sub(allowanceBefore).toString()).to.be.equal(amount.toString());743 });744}745746export async function747transferFromExpectSuccess(748 collectionId: number,749 tokenId: number,750 accountApproved: IKeyringPair,751 accountFrom: IKeyringPair | CrossAccountId,752 accountTo: IKeyringPair | CrossAccountId,753 value: number | bigint = 1,754 type = 'NFT',755) {756 await usingApi(async (api: ApiPromise) => {757 const to = normalizeAccountId(accountTo);758 let balanceBefore = new BN(0);759 if (type === 'Fungible') {760 balanceBefore = await api.query.nft.balance(collectionId, toSubstrateAddress(to)) as unknown as BN;761 }762 const transferFromTx = api.tx.nft.transferFrom(normalizeAccountId(accountFrom), to, collectionId, tokenId, value);763 const events = await submitTransactionAsync(accountApproved, transferFromTx);764 const result = getCreateItemResult(events);765 766 expect(result.success).to.be.true;767 if (type === 'NFT') {768 const nftItemData = (await api.query.nft.nftItemList(collectionId, tokenId) as any).toJSON() as ITokenDataType;769 expect(nftItemData.Owner).to.be.deep.equal(to);770 }771 if (type === 'Fungible') {772 const balanceAfter = (await api.query.nft.fungibleItemList(collectionId, toSubstrateAddress(to)) as any).Value as unknown as BN;773 expect(balanceAfter.sub(balanceBefore).toString()).to.be.equal(value.toString());774 }775 if (type === 'ReFungible') {776 const nftItemData =777 (await api.query.nft.reFungibleItemList(collectionId, tokenId) as any).toJSON() as IReFungibleTokenDataType;778 expect(nftItemData.Owner[0].Owner).to.be.deep.equal(normalizeAccountId(to));779 expect(nftItemData.Owner[0].Fraction).to.be.equal(value);780 }781 });782}783784export async function785transferFromExpectFail(786 collectionId: number,787 tokenId: number,788 accountApproved: IKeyringPair,789 accountFrom: IKeyringPair,790 accountTo: IKeyringPair,791 value: number | bigint = 1,792) {793 await usingApi(async (api: ApiPromise) => {794 const transferFromTx = api.tx.nft.transferFrom(normalizeAccountId(accountFrom.address), normalizeAccountId(accountTo.address), collectionId, tokenId, value);795 const events = await expect(submitTransactionExpectFailAsync(accountApproved, transferFromTx)).to.be.rejected;796 const result = getCreateCollectionResult(events);797 798 expect(result.success).to.be.false;799 });800}801802803async function getBlockNumber(api: ApiPromise): Promise<number> {804 return new Promise<number>(async (resolve) => {805 const unsubscribe = await api.rpc.chain.subscribeNewHeads((head) => {806 unsubscribe();807 resolve(head.number.toNumber());808 });809 });810}811812export async function addCollectionAdminExpectSuccess(sender: IKeyringPair, collectionId: number, address: IKeyringPair) {813 await usingApi(async (api) => {814 const changeAdminTx = api.tx.nft.addCollectionAdmin(collectionId, normalizeAccountId(address.address));815 const events = await submitTransactionAsync(sender, changeAdminTx);816 const result = getCreateCollectionResult(events);817 expect(result.success).to.be.true;818 });819}820821export async function822getFreeBalance(account: IKeyringPair) : Promise<BigNumber>823{824 let balance = new BigNumber(0) ;825 await usingApi(async (api) => { 826 balance = new BigNumber((await api.query.system.account(account.address)).data.free.toString()); 827 });828829 return balance;830}831832export async function833scheduleTransferExpectSuccess(834 collectionId: number,835 tokenId: number,836 sender: IKeyringPair,837 recipient: IKeyringPair,838 value: number | bigint = 1,839 blockTimeMs: number,840 blockSchedule: number,841) {842 await usingApi(async (api: ApiPromise) => {843 const blockNumber: number | undefined = await getBlockNumber(api);844 const expectedBlockNumber = blockNumber + blockSchedule;845846 expect(blockNumber).to.be.greaterThan(0);847 const transferTx = await api.tx.nft.transfer(normalizeAccountId(recipient.address), collectionId, tokenId, value); 848 const scheduleTx = await api.tx.scheduler.schedule(expectedBlockNumber, null, 0, transferTx);849850 await submitTransactionAsync(sender, scheduleTx);851852 const recipientBalanceBefore = new BigNumber((await api.query.system.account(recipient.address)).data.free.toString());853854 const nftItemDataBefore = (await api.query.nft.nftItemList(collectionId, tokenId)).toJSON() as any as ITokenDataType;855 expect(toSubstrateAddress(nftItemDataBefore.Owner)).to.be.equal(sender.address);856857 858 await new Promise(resolve => setTimeout(resolve, blockTimeMs * (blockSchedule + 1)));859860 const recipientBalanceAfter = new BigNumber((await api.query.system.account(recipient.address)).data.free.toString());861862 const nftItemData = (await api.query.nft.nftItemList(collectionId, tokenId)).toJSON() as unknown as ITokenDataType;863 expect(toSubstrateAddress(nftItemData.Owner)).to.be.equal(recipient.address);864 expect(recipientBalanceAfter.toNumber()).to.be.equal(recipientBalanceBefore.toNumber());865 });866}867868869export async function870transferExpectSuccess(871 collectionId: number,872 tokenId: number,873 sender: IKeyringPair,874 recipient: IKeyringPair | CrossAccountId,875 value: number | bigint = 1,876 type = 'NFT',877) {878 await usingApi(async (api: ApiPromise) => {879 const to = normalizeAccountId(recipient);880881 let balanceBefore = new BN(0);882 if (type === 'Fungible') {883 balanceBefore = await api.query.nft.balance(collectionId, toSubstrateAddress(to)) as unknown as BN;884 }885 const transferTx = api.tx.nft.transfer(to, collectionId, tokenId, value);886 const events = await submitTransactionAsync(sender, transferTx);887 const result = getTransferResult(events);888 889 expect(result.success).to.be.true;890 expect(result.collectionId).to.be.equal(collectionId);891 expect(result.itemId).to.be.equal(tokenId);892 expect(result.sender).to.be.deep.equal(normalizeAccountId(sender.address));893 expect(result.recipient).to.be.deep.equal(to);894 expect(result.value.toString()).to.be.equal(value.toString());895 if (type === 'NFT') {896 const nftItemData = (await api.query.nft.nftItemList(collectionId, tokenId)).toJSON() as unknown as ITokenDataType;897 expect(nftItemData.Owner).to.be.deep.equal(to);898 }899 if (type === 'Fungible') {900 const balanceAfter = (await api.query.nft.fungibleItemList(collectionId, toSubstrateAddress(to)) as any).Value as unknown as BN;901 expect(balanceAfter.sub(balanceBefore).toString()).to.be.equal(value.toString());902 }903 if (type === 'ReFungible') {904 const nftItemData =905 (await api.query.nft.reFungibleItemList(collectionId, tokenId)).toJSON() as unknown as IReFungibleTokenDataType;906 const expectedOwner = toSubstrateAddress(to);907 const ownerIndex = nftItemData.Owner.findIndex(v => toSubstrateAddress(v.Owner as any as string) == expectedOwner);908 expect(ownerIndex).to.not.equal(-1);909 expect(nftItemData.Owner[ownerIndex].Owner).to.be.deep.equal(normalizeAccountId(to));910 expect(nftItemData.Owner[ownerIndex].Fraction).to.be.greaterThanOrEqual(value as number);911 }912 });913}914915export async function916transferExpectFailure(917 collectionId: number,918 tokenId: number,919 sender: IKeyringPair,920 recipient: IKeyringPair,921 value: number | bigint = 1,922) {923 await usingApi(async (api: ApiPromise) => {924 const transferTx = api.tx.nft.transfer(normalizeAccountId(recipient.address), collectionId, tokenId, value);925 const events = await expect(submitTransactionExpectFailAsync(sender, transferTx)).to.be.rejected;926 if (events && Array.isArray(events)) {927 const result = getCreateCollectionResult(events);928 929 expect(result.success).to.be.false;930 }931 });932}933934export async function935approveExpectFail(936 collectionId: number,937 tokenId: number, owner: IKeyringPair, approved: IKeyringPair, amount: number | bigint = 1,938) {939 await usingApi(async (api: ApiPromise) => {940 const approveNftTx = api.tx.nft.approve(normalizeAccountId(approved.address), collectionId, tokenId, amount);941 const events = await expect(submitTransactionExpectFailAsync(owner, approveNftTx)).to.be.rejected;942 const result = getCreateCollectionResult(events);943 944 expect(result.success).to.be.false;945 });946}947948export async function getFungibleBalance(949 collectionId: number,950 owner: string,951) {952 return await usingApi(async (api) => {953 const response = (await api.query.nft.fungibleItemList(collectionId, owner)).toJSON() as unknown as { Value: string };954 return BigInt(response.Value);955 });956}957958export async function createFungibleItemExpectSuccess(959 sender: IKeyringPair,960 collectionId: number,961 data: CreateFungibleData,962 owner: CrossAccountId | string = sender.address,963) {964 return await usingApi(async (api) => {965 const tx = api.tx.nft.createItem(collectionId, normalizeAccountId(owner), { Fungible: data });966967 const events = await submitTransactionAsync(sender, tx);968 const result = getCreateItemResult(events);969970 expect(result.success).to.be.true;971 return result.itemId;972 });973}974975export async function createItemExpectSuccess(sender: IKeyringPair, collectionId: number, createMode: string, owner: CrossAccountId | string = sender.address) {976 let newItemId = 0;977 await usingApi(async (api) => {978 const to = normalizeAccountId(owner);979 const AItemCount = parseInt((await api.query.nft.itemListIndex(collectionId)).toString(), 10);980 const Aitem: any = (await api.query.nft.fungibleItemList(collectionId, toSubstrateAddress(to))).toJSON();981 const AItemBalance = new BigNumber(Aitem.Value);982983 let tx;984 if (createMode === 'Fungible') {985 const createData = { fungible: { value: 10 } };986 tx = api.tx.nft.createItem(collectionId, to, createData);987 } else if (createMode === 'ReFungible') {988 const createData = { refungible: { const_data: [], variable_data: [], pieces: 100 } };989 tx = api.tx.nft.createItem(collectionId, to, createData);990 } else {991 const createData = { nft: { const_data: [], variable_data: [] } };992 tx = api.tx.nft.createItem(collectionId, to, createData);993 }994995 const events = await submitTransactionAsync(sender, tx);996 const result = getCreateItemResult(events);997998 const BItemCount = parseInt((await api.query.nft.itemListIndex(collectionId)).toString(), 10);999 const Bitem: any = (await api.query.nft.fungibleItemList(collectionId, toSubstrateAddress(to))).toJSON();1000 const BItemBalance = new BigNumber(Bitem.Value);10011002 1003 1004 expect(result.success).to.be.true;1005 if (createMode === 'Fungible') {1006 expect(BItemBalance.minus(AItemBalance).toNumber()).to.be.equal(10);1007 } else {1008 expect(BItemCount).to.be.equal(AItemCount + 1);1009 }1010 expect(collectionId).to.be.equal(result.collectionId);1011 expect(BItemCount.toString()).to.be.equal(result.itemId.toString());1012 expect(to).to.be.deep.equal(result.recipient);1013 newItemId = result.itemId;1014 });1015 return newItemId;1016}10171018export async function createItemExpectFailure(sender: IKeyringPair, collectionId: number, createMode: string, owner: string = sender.address) {1019 await usingApi(async (api) => {1020 const tx = api.tx.nft.createItem(collectionId, normalizeAccountId(owner), createMode);1021 1022 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1023 const result = getCreateItemResult(events);10241025 expect(result.success).to.be.false;1026 });1027}10281029export async function setPublicAccessModeExpectSuccess(1030 sender: IKeyringPair, collectionId: number,1031 accessMode: 'Normal' | 'WhiteList',1032) {1033 await usingApi(async (api) => {10341035 1036 const tx = api.tx.nft.setPublicAccessMode(collectionId, accessMode);1037 const events = await submitTransactionAsync(sender, tx);1038 const result = getGenericResult(events);10391040 1041 const collection: any = (await api.query.nft.collectionById(collectionId)).toJSON();10421043 1044 1045 expect(result.success).to.be.true;1046 expect(collection.Access).to.be.equal(accessMode);1047 });1048}10491050export async function setPublicAccessModeExpectFail(1051 sender: IKeyringPair, collectionId: number,1052 accessMode: 'Normal' | 'WhiteList',1053) {1054 await usingApi(async (api) => {10551056 1057 const tx = api.tx.nft.setPublicAccessMode(collectionId, accessMode);1058 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1059 const result = getGenericResult(events);10601061 1062 1063 expect(result.success).to.be.false;1064 });1065}10661067export async function enableWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number) {1068 await setPublicAccessModeExpectSuccess(sender, collectionId, 'WhiteList');1069}10701071export async function enableWhiteListExpectFail(sender: IKeyringPair, collectionId: number) {1072 await setPublicAccessModeExpectFail(sender, collectionId, 'WhiteList');1073}10741075export async function disableWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number) {1076 await setPublicAccessModeExpectSuccess(sender, collectionId, 'Normal');1077}10781079export async function setMintPermissionExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {1080 await usingApi(async (api) => {10811082 1083 const tx = api.tx.nft.setMintPermission(collectionId, enabled);1084 const events = await submitTransactionAsync(sender, tx);1085 const result = getGenericResult(events);10861087 1088 const collection: any = (await api.query.nft.collectionById(collectionId)).toJSON();10891090 1091 1092 expect(result.success).to.be.true;1093 expect(collection.MintMode).to.be.equal(enabled);1094 });1095}10961097export async function enablePublicMintingExpectSuccess(sender: IKeyringPair, collectionId: number) {1098 await setMintPermissionExpectSuccess(sender, collectionId, true);1099}11001101export async function setMintPermissionExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {1102 await usingApi(async (api) => {1103 1104 const tx = api.tx.nft.setMintPermission(collectionId, enabled);1105 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1106 const result = getCreateCollectionResult(events);1107 1108 expect(result.success).to.be.false;1109 });1110}11111112export async function setChainLimitsExpectFailure(sender: IKeyringPair, limits: IChainLimits) {1113 await usingApi(async (api) => {1114 1115 const tx = api.tx.nft.setChainLimits(limits);1116 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1117 const result = getCreateCollectionResult(events);1118 1119 expect(result.success).to.be.false;1120 });1121}11221123export async function isWhitelisted(collectionId: number, address: string) {1124 let whitelisted = false;1125 await usingApi(async (api) => {1126 whitelisted = (await api.query.nft.whiteList(collectionId, address)).toJSON() as unknown as boolean;1127 });1128 return whitelisted;1129}11301131export async function addToWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId) {1132 await usingApi(async (api) => {11331134 const whiteListedBefore = (await api.query.nft.whiteList(collectionId, address)).toJSON();11351136 1137 const tx = api.tx.nft.addToWhiteList(collectionId, normalizeAccountId(address));1138 const events = await submitTransactionAsync(sender, tx);1139 const result = getGenericResult(events);11401141 const whiteListedAfter = (await api.query.nft.whiteList(collectionId, address)).toJSON();11421143 1144 1145 expect(result.success).to.be.true;1146 1147 expect(whiteListedBefore).to.be.false;1148 1149 expect(whiteListedAfter).to.be.true;1150 });1151}11521153export async function addToWhiteListExpectFail(sender: IKeyringPair, collectionId: number, address: string | AccountId) {1154 await usingApi(async (api) => {1155 1156 const tx = api.tx.nft.addToWhiteList(collectionId, normalizeAccountId(address));1157 const events = await expect(submitTransactionAsync(sender, tx)).to.be.rejected;1158 const result = getGenericResult(events);11591160 1161 1162 expect(result.success).to.be.false;1163 });1164}11651166export async function removeFromWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1167 await usingApi(async (api) => {1168 1169 const tx = api.tx.nft.removeFromWhiteList(collectionId, normalizeAccountId(address));1170 const events = await submitTransactionAsync(sender, tx);1171 const result = getGenericResult(events);11721173 1174 1175 expect(result.success).to.be.true;1176 });1177}11781179export async function removeFromWhiteListExpectFailure(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1180 await usingApi(async (api) => {1181 1182 const tx = api.tx.nft.removeFromWhiteList(collectionId, normalizeAccountId(address));1183 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1184 const result = getGenericResult(events);11851186 1187 1188 expect(result.success).to.be.false;1189 });1190}11911192export const getDetailedCollectionInfo = async (api: ApiPromise, collectionId: number)1193 : Promise<ICollectionInterface | null> => {1194 return (await api.query.nft.collectionById(collectionId)).toJSON() as unknown as ICollectionInterface;1195};11961197export const getCreatedCollectionCount = async (api: ApiPromise): Promise<number> => {1198 1199 return (await api.query.nft.createdCollectionCount() as unknown as BN).toNumber();1200};12011202export async function queryCollectionExpectSuccess(collectionId: number): Promise<ICollectionInterface> {1203 return await usingApi(async (api) => {1204 return (await api.query.nft.collectionById(collectionId)).toJSON() as unknown as ICollectionInterface;1205 });1206}12071208export async function queryNftOwner(api: ApiPromise, collectionId: number, tokenId: number): Promise<CrossAccountId> {1209 return normalizeAccountId((await api.query.nft.nftItemList(collectionId, tokenId) as any).toJSON().Owner);1210}12111212export async function waitNewBlocks(blocksCount = 1): Promise<void> {1213 await usingApi(async (api) => {1214 const promise = new Promise<void>(async (resolve) => {1215 const unsubscribe = await api.rpc.chain.subscribeNewHeads(() => {1216 if (blocksCount > 0) {1217 blocksCount--;1218 } else {1219 unsubscribe();1220 resolve();1221 }1222 });1223 });1224 return promise;1225 });1226}