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 BN from 'bn.js';11import chai from 'chai';12import chaiAsPromised from 'chai-as-promised';13import {alicesPublicKey} from '../accounts';14import {NftDataStructsCollection} from '../interfaces';15import privateKey from '../substrate/privateKey';16import {default as usingApi, submitTransactionAsync, submitTransactionExpectFailAsync} from '../substrate/substrate-api';17import {hexToStr, strToUTF16, utf16ToStr} from './util';1819chai.use(chaiAsPromised);20const expect = chai.expect;2122export type CrossAccountId = {23 Substrate: string,24} | {25 Ethereum: string,26};27export function normalizeAccountId(input: string | AccountId | CrossAccountId | IKeyringPair): CrossAccountId {28 if (typeof input === 'string') {29 if (input.length === 48 || input.length === 47) {30 return {Substrate: input};31 } else if (input.length === 42 && input.startsWith('0x')) {32 return {Ethereum: input.toLowerCase()};33 } else if (input.length === 40 && !input.startsWith('0x')) {34 return {Ethereum: '0x' + input.toLowerCase()};35 } else {36 throw new Error(`Unknown address format: "${input}"`);37 }38 }39 if ('address' in input) {40 return {Substrate: input.address};41 }42 if ('Ethereum' in input) {43 return {44 Ethereum: input.Ethereum.toLowerCase(),45 };46 } else if ('ethereum' in input) {47 return {48 Ethereum: (input as any).ethereum.toLowerCase(),49 };50 } else if ('Substrate' in input) {51 return input;52 }else if ('substrate' in input) {53 return {54 Substrate: (input as any).substrate,55 };56 }5758 59 return {Substrate: input.toString()};60}61export function toSubstrateAddress(input: string | CrossAccountId | IKeyringPair): string {62 input = normalizeAccountId(input);63 if ('Substrate' in input) {64 return input.Substrate;65 } else {66 return evmToAddress(input.Ethereum);67 }68}6970export const U128_MAX = (1n << 128n) - 1n;7172const MICROUNIQUE = 1_000_000_000n;73const MILLIUNIQUE = 1_000n * MICROUNIQUE;74const CENTIUNIQUE = 10n * MILLIUNIQUE;75export const UNIQUE = 100n * CENTIUNIQUE;7677type GenericResult = {78 success: boolean,79};8081interface CreateCollectionResult {82 success: boolean;83 collectionId: number;84}8586interface CreateItemResult {87 success: boolean;88 collectionId: number;89 itemId: number;90 recipient?: CrossAccountId;91}9293interface TransferResult {94 success: boolean;95 collectionId: number;96 itemId: number;97 sender?: CrossAccountId;98 recipient?: CrossAccountId;99 value: bigint;100}101102interface IReFungibleOwner {103 fraction: BN;104 owner: number[];105}106107interface IGetMessage {108 checkMsgNftMethod: string;109 checkMsgTrsMethod: string;110 checkMsgSysMethod: string;111}112113export interface IFungibleTokenDataType {114 value: number;115}116117export interface IChainLimits {118 collectionNumbersLimit: number;119 accountTokenOwnershipLimit: number;120 collectionsAdminsLimit: number;121 customDataLimit: number;122 nftSponsorTransferTimeout: number;123 fungibleSponsorTransferTimeout: number;124 refungibleSponsorTransferTimeout: number;125 offchainSchemaLimit: number;126 variableOnChainSchemaLimit: number;127 constOnChainSchemaLimit: number;128}129130export interface IReFungibleTokenDataType {131 owner: IReFungibleOwner[];132 constData: number[];133 variableData: number[];134}135136export function nftEventMessage(events: EventRecord[]): IGetMessage {137 let checkMsgNftMethod = '';138 let checkMsgTrsMethod = '';139 let checkMsgSysMethod = '';140 events.forEach(({event: {method, section}}) => {141 if (section === 'common') {142 checkMsgNftMethod = method;143 } else if (section === 'treasury') {144 checkMsgTrsMethod = method;145 } else if (section === 'system') {146 checkMsgSysMethod = method;147 } else { return null; }148 });149 const result: IGetMessage = {150 checkMsgNftMethod,151 checkMsgTrsMethod,152 checkMsgSysMethod,153 };154 return result;155}156157export function getGenericResult(events: EventRecord[]): GenericResult {158 const result: GenericResult = {159 success: false,160 };161 events.forEach(({event: {method}}) => {162 163 if (method === 'ExtrinsicSuccess') {164 result.success = true;165 }166 });167 return result;168}169170171172export function getCreateCollectionResult(events: EventRecord[]): CreateCollectionResult {173 let success = false;174 let collectionId = 0;175 events.forEach(({event: {data, method, section}}) => {176 177 if (method == 'ExtrinsicSuccess') {178 success = true;179 } else if ((section == 'common') && (method == 'CollectionCreated')) {180 collectionId = parseInt(data[0].toString(), 10);181 }182 });183 const result: CreateCollectionResult = {184 success,185 collectionId,186 };187 return result;188}189190export function getCreateItemResult(events: EventRecord[]): CreateItemResult {191 let success = false;192 let collectionId = 0;193 let itemId = 0;194 let recipient;195 events.forEach(({event: {data, method, section}}) => {196 197 if (method == 'ExtrinsicSuccess') {198 success = true;199 } else if ((section == 'common') && (method == 'ItemCreated')) {200 collectionId = parseInt(data[0].toString(), 10);201 itemId = parseInt(data[1].toString(), 10);202 recipient = normalizeAccountId(data[2].toJSON() as any);203 }204 });205 const result: CreateItemResult = {206 success,207 collectionId,208 itemId,209 recipient,210 };211 return result;212}213214export function getTransferResult(events: EventRecord[]): TransferResult {215 const result: TransferResult = {216 success: false,217 collectionId: 0,218 itemId: 0,219 value: 0n,220 };221222 events.forEach(({event: {data, method, section}}) => {223 if (method === 'ExtrinsicSuccess') {224 result.success = true;225 } else if (section === 'common' && method === 'Transfer') {226 result.collectionId = +data[0].toString();227 result.itemId = +data[1].toString();228 result.sender = normalizeAccountId(data[2].toJSON() as any);229 result.recipient = normalizeAccountId(data[3].toJSON() as any);230 result.value = BigInt(data[4].toString());231 }232 });233234 return result;235}236237interface Nft {238 type: 'NFT';239}240241interface Fungible {242 type: 'Fungible';243 decimalPoints: number;244}245246interface ReFungible {247 type: 'ReFungible';248}249250type CollectionMode = Nft | Fungible | ReFungible;251252export type CreateCollectionParams = {253 mode: CollectionMode,254 name: string,255 description: string,256 tokenPrefix: string,257};258259const defaultCreateCollectionParams: CreateCollectionParams = {260 description: 'description',261 mode: {type: 'NFT'},262 name: 'name',263 tokenPrefix: 'prefix',264};265266export async function createCollectionExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {267 const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};268269 let collectionId = 0;270 await usingApi(async (api) => {271 272 const collectionCountBefore = await getCreatedCollectionCount(api);273274 275 const alicePrivateKey = privateKey('//Alice');276277 let modeprm = {};278 if (mode.type === 'NFT') {279 modeprm = {nft: null};280 } else if (mode.type === 'Fungible') {281 modeprm = {fungible: mode.decimalPoints};282 } else if (mode.type === 'ReFungible') {283 modeprm = {refungible: null};284 }285286 const tx = api.tx.nft.createCollection(strToUTF16(name), strToUTF16(description), strToUTF16(tokenPrefix), modeprm as any);287 const events = await submitTransactionAsync(alicePrivateKey, tx);288 const result = getCreateCollectionResult(events);289290 291 const collectionCountAfter = await getCreatedCollectionCount(api);292293 294 const collection = await queryCollectionExpectSuccess(api, result.collectionId);295296 297 298 expect(result.success).to.be.true;299 expect(result.collectionId).to.be.equal(collectionCountAfter);300 301 expect(collection).to.be.not.null;302 expect(collectionCountAfter).to.be.equal(collectionCountBefore + 1, 'Error: NFT collection NOT created.');303 expect(collection.owner.toString()).to.be.equal(toSubstrateAddress(alicesPublicKey));304 expect(utf16ToStr(collection.name.toJSON() as any)).to.be.equal(name);305 expect(utf16ToStr(collection.description.toJSON() as any)).to.be.equal(description);306 expect(hexToStr(collection.tokenPrefix.toJSON())).to.be.equal(tokenPrefix);307308 collectionId = result.collectionId;309 });310311 return collectionId;312}313314export async function createCollectionExpectFailure(params: Partial<CreateCollectionParams> = {}) {315 const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};316317 let modeprm = {};318 if (mode.type === 'NFT') {319 modeprm = {nft: null};320 } else if (mode.type === 'Fungible') {321 modeprm = {fungible: mode.decimalPoints};322 } else if (mode.type === 'ReFungible') {323 modeprm = {refungible: null};324 }325326 await usingApi(async (api) => {327 328 const collectionCountBefore = await getCreatedCollectionCount(api);329330 331 const alicePrivateKey = privateKey('//Alice');332 const tx = api.tx.nft.createCollection(strToUTF16(name), strToUTF16(description), strToUTF16(tokenPrefix), modeprm as any);333 const events = await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;334 const result = getCreateCollectionResult(events);335336 337 const collectionCountAfter = await getCreatedCollectionCount(api);338339 340 341 expect(result.success).to.be.false;342 expect(collectionCountAfter).to.be.equal(collectionCountBefore, 'Error: Collection with incorrect data created.');343 });344}345346export async function findUnusedAddress(api: ApiPromise, seedAddition = ''): Promise<IKeyringPair> {347 let bal = 0n;348 let unused;349 do {350 const randomSeed = 'seed' + Math.floor(Math.random() * Math.floor(10000)) + seedAddition;351 const keyring = new Keyring({type: 'sr25519'});352 unused = keyring.addFromUri(`//${randomSeed}`);353 bal = (await api.query.system.account(unused.address)).data.free.toBigInt();354 } while (bal !== 0n);355 return unused;356}357358export async function getAllowance(api: ApiPromise, collectionId: number, owner: CrossAccountId | string, approved: CrossAccountId | string, tokenId: number) {359 return (await api.rpc.nft.allowance(collectionId, normalizeAccountId(owner), normalizeAccountId(approved), tokenId)).toBigInt();360}361362export function findUnusedAddresses(api: ApiPromise, amount: number): Promise<IKeyringPair[]> {363 return Promise.all(new Array(amount).fill(null).map(() => findUnusedAddress(api, '_' + Date.now())));364}365366export async function findNotExistingCollection(api: ApiPromise): Promise<number> {367 const totalNumber = await getCreatedCollectionCount(api);368 const newCollection: number = totalNumber + 1;369 return newCollection;370}371372function getDestroyResult(events: EventRecord[]): boolean {373 let success = false;374 events.forEach(({event: {method}}) => {375 if (method == 'ExtrinsicSuccess') {376 success = true;377 }378 });379 return success;380}381382export async function destroyCollectionExpectFailure(collectionId: number, senderSeed = '//Alice') {383 await usingApi(async (api) => {384 385 const alicePrivateKey = privateKey(senderSeed);386 const tx = api.tx.nft.destroyCollection(collectionId);387 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;388 });389}390391export async function destroyCollectionExpectSuccess(collectionId: number, senderSeed = '//Alice') {392 await usingApi(async (api) => {393 394 const alicePrivateKey = privateKey(senderSeed);395 const tx = api.tx.nft.destroyCollection(collectionId);396 const events = await submitTransactionAsync(alicePrivateKey, tx);397 const result = getDestroyResult(events);398 expect(result).to.be.true;399400 401 expect(await getDetailedCollectionInfo(api, collectionId)).to.be.null;402 });403}404405export async function setCollectionLimitsExpectSuccess(sender: IKeyringPair, collectionId: number, limits: any) {406 await usingApi(async (api) => {407 const tx = api.tx.nft.setCollectionLimits(collectionId, limits);408 const events = await submitTransactionAsync(sender, tx);409 const result = getGenericResult(events);410411 expect(result.success).to.be.true;412 });413}414415export async function setCollectionLimitsExpectFailure(sender: IKeyringPair, collectionId: number, limits: any) {416 await usingApi(async (api) => {417 const tx = api.tx.nft.setCollectionLimits(collectionId, limits);418 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;419 const result = getGenericResult(events);420421 expect(result.success).to.be.false;422 });423}424425export async function setCollectionSponsorExpectSuccess(collectionId: number, sponsor: string, sender = '//Alice') {426 await usingApi(async (api) => {427428 429 const senderPrivateKey = privateKey(sender);430 const tx = api.tx.nft.setCollectionSponsor(collectionId, sponsor);431 const events = await submitTransactionAsync(senderPrivateKey, tx);432 const result = getGenericResult(events);433434 435 const collection = await queryCollectionExpectSuccess(api, collectionId);436437 438 expect(result.success).to.be.true;439 expect(collection.sponsorship.toJSON()).to.deep.equal({440 unconfirmed: sponsor,441 });442 });443}444445export async function removeCollectionSponsorExpectSuccess(collectionId: number, sender = '//Alice') {446 await usingApi(async (api) => {447448 449 const alicePrivateKey = privateKey(sender);450 const tx = api.tx.nft.removeCollectionSponsor(collectionId);451 const events = await submitTransactionAsync(alicePrivateKey, tx);452 const result = getGenericResult(events);453454 455 const collection = await queryCollectionExpectSuccess(api, collectionId);456457 458 expect(result.success).to.be.true;459 expect(collection.sponsorship.toJSON()).to.be.deep.equal({disabled: null});460 });461}462463export async function removeCollectionSponsorExpectFailure(collectionId: number, senderSeed = '//Alice') {464 await usingApi(async (api) => {465466 467 const alicePrivateKey = privateKey(senderSeed);468 const tx = api.tx.nft.removeCollectionSponsor(collectionId);469 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;470 });471}472473export async function setCollectionSponsorExpectFailure(collectionId: number, sponsor: string, senderSeed = '//Alice') {474 await usingApi(async (api) => {475476 477 const alicePrivateKey = privateKey(senderSeed);478 const tx = api.tx.nft.setCollectionSponsor(collectionId, sponsor);479 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;480 });481}482483export async function confirmSponsorshipExpectSuccess(collectionId: number, senderSeed = '//Alice') {484 await usingApi(async (api) => {485486 487 const sender = privateKey(senderSeed);488 const tx = api.tx.nft.confirmSponsorship(collectionId);489 const events = await submitTransactionAsync(sender, tx);490 const result = getGenericResult(events);491492 493 const collection = await queryCollectionExpectSuccess(api, collectionId);494495 496 expect(result.success).to.be.true;497 expect(collection.sponsorship.toJSON()).to.be.deep.equal({498 confirmed: sender.address,499 });500 });501}502503504export async function confirmSponsorshipExpectFailure(collectionId: number, senderSeed = '//Alice') {505 await usingApi(async (api) => {506507 508 const sender = privateKey(senderSeed);509 const tx = api.tx.nft.confirmSponsorship(collectionId);510 await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;511 });512}513514export async function setMetadataUpdatePermissionFlagExpectSuccess(sender: IKeyringPair, collectionId: number, flag: string) {515516 await usingApi(async (api) => {517 const tx = api.tx.nft.setMetaUpdatePermissionFlag(collectionId, flag as any);518 const events = await submitTransactionAsync(sender, tx);519 const result = getGenericResult(events);520521 expect(result.success).to.be.true;522 });523}524525export async function setMetadataUpdatePermissionFlagExpectFailure(sender: IKeyringPair, collectionId: number, flag: string) {526527 await usingApi(async (api) => {528 const tx = api.tx.nft.setMetaUpdatePermissionFlag(collectionId, flag as any);529 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;530 const result = getGenericResult(events);531532 expect(result.success).to.be.false;533 });534}535536export async function enableContractSponsoringExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {537 await usingApi(async (api) => {538 const tx = api.tx.nft.enableContractSponsoring(contractAddress, enable);539 const events = await submitTransactionAsync(sender, tx);540 const result = getGenericResult(events);541542 expect(result.success).to.be.true;543 });544}545546export async function enableContractSponsoringExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {547 await usingApi(async (api) => {548 const tx = api.tx.nft.enableContractSponsoring(contractAddress, enable);549 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;550 const result = getGenericResult(events);551552 expect(result.success).to.be.false;553 });554}555556export async function setTransferFlagExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {557558 await usingApi(async (api) => {559560 const tx = api.tx.nft.setTransfersEnabledFlag (collectionId, enabled);561 const events = await submitTransactionAsync(sender, tx);562 const result = getGenericResult(events);563564 expect(result.success).to.be.true;565 });566}567568export async function setTransferFlagExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {569570 await usingApi(async (api) => {571572 const tx = api.tx.nft.setTransfersEnabledFlag (collectionId, enabled);573 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;574 const result = getGenericResult(events);575576 expect(result.success).to.be.false;577 });578}579580export async function setContractSponsoringRateLimitExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {581 await usingApi(async (api) => {582 const tx = api.tx.nft.setContractSponsoringRateLimit(contractAddress, rateLimit);583 const events = await submitTransactionAsync(sender, tx);584 const result = getGenericResult(events);585586 expect(result.success).to.be.true;587 });588}589590export async function setContractSponsoringRateLimitExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {591 await usingApi(async (api) => {592 const tx = api.tx.nft.setContractSponsoringRateLimit(contractAddress, rateLimit);593 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;594 const result = getGenericResult(events);595596 expect(result.success).to.be.false;597 });598}599600export async function toggleContractAllowlistExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, value = true) {601 await usingApi(async (api) => {602 const tx = api.tx.nft.toggleContractAllowList(contractAddress, value);603 const events = await submitTransactionAsync(sender, tx);604 const result = getGenericResult(events);605606 expect(result.success).to.be.true;607 });608}609610export async function isAllowlistedInContract(contractAddress: AccountId | string, user: string) {611 let allowlisted = false;612 await usingApi(async (api) => {613 allowlisted = (await api.query.nft.contractAllowList(contractAddress, user)).toJSON() as boolean;614 });615 return allowlisted;616}617618export async function addToContractAllowListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {619 await usingApi(async (api) => {620 const tx = api.tx.nft.addToContractAllowList(contractAddress.toString(), user.toString());621 const events = await submitTransactionAsync(sender, tx);622 const result = getGenericResult(events);623624 expect(result.success).to.be.true;625 });626}627628export async function removeFromContractAllowListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {629 await usingApi(async (api) => {630 const tx = api.tx.nft.removeFromContractAllowList(contractAddress.toString(), user.toString());631 const events = await submitTransactionAsync(sender, tx);632 const result = getGenericResult(events);633634 expect(result.success).to.be.true;635 });636}637638export async function removeFromContractAllowListExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {639 await usingApi(async (api) => {640 const tx = api.tx.nft.removeFromContractAllowList(contractAddress.toString(), user.toString());641 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;642 const result = getGenericResult(events);643644 expect(result.success).to.be.false;645 });646}647648export async function setVariableMetaDataExpectSuccess(sender: IKeyringPair, collectionId: number, itemId: number, data: number[]) {649 await usingApi(async (api) => {650 const tx = api.tx.nft.setVariableMetaData(collectionId, itemId, '0x' + Buffer.from(data).toString('hex'));651 const events = await submitTransactionAsync(sender, tx);652 const result = getGenericResult(events);653654 expect(result.success).to.be.true;655 });656}657658export async function setVariableMetaDataExpectFailure(sender: IKeyringPair, collectionId: number, itemId: number, data: number[]) {659 await usingApi(async (api) => {660 const tx = api.tx.nft.setVariableMetaData(collectionId, itemId, '0x' + Buffer.from(data).toString('hex'));661 await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;662 });663}664665export async function setOffchainSchemaExpectSuccess(sender: IKeyringPair, collectionId: number, data: number[]) {666 await usingApi(async (api) => {667 const tx = api.tx.nft.setOffchainSchema(collectionId, '0x' + Buffer.from(data).toString('hex'));668 const events = await submitTransactionAsync(sender, tx);669 const result = getGenericResult(events);670671 expect(result.success).to.be.true;672 });673}674675export async function setOffchainSchemaExpectFailure(sender: IKeyringPair, collectionId: number, data: number[]) {676 await usingApi(async (api) => {677 const tx = api.tx.nft.setOffchainSchema(collectionId, '0x' + Buffer.from(data).toString('hex'));678 await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;679 });680}681682export interface CreateFungibleData {683 readonly Value: bigint;684}685686export interface CreateReFungibleData { }687export interface CreateNftData { }688689export type CreateItemData = {690 NFT: CreateNftData;691} | {692 Fungible: CreateFungibleData;693} | {694 ReFungible: CreateReFungibleData;695};696697export async function burnItemExpectSuccess(sender: IKeyringPair, collectionId: number, tokenId: number, value = 1) {698 await usingApi(async (api) => {699 const balanceBefore = await getBalance(api, collectionId, normalizeAccountId(sender), tokenId);700 701 expect(balanceBefore >= BigInt(value)).to.be.true;702703 const tx = api.tx.nft.burnItem(collectionId, tokenId, value);704 const events = await submitTransactionAsync(sender, tx);705 const result = getGenericResult(events);706 expect(result.success).to.be.true;707708 const balanceAfter = await getBalance(api, collectionId, normalizeAccountId(sender), tokenId);709 expect(balanceAfter + BigInt(value)).to.be.equal(balanceBefore);710 });711}712713export async function714approveExpectSuccess(715 collectionId: number,716 tokenId: number, owner: IKeyringPair, approved: CrossAccountId | string, amount: number | bigint = 1,717) {718 await usingApi(async (api: ApiPromise) => {719 const approveNftTx = api.tx.nft.approve(normalizeAccountId(approved), collectionId, tokenId, amount);720 const events = await submitTransactionAsync(owner, approveNftTx);721 const result = getGenericResult(events);722 expect(result.success).to.be.true;723724 expect(await getAllowance(api, collectionId, owner.address, approved, tokenId)).to.be.equal(BigInt(amount));725 });726}727728export async function adminApproveFromExpectSuccess(729 collectionId: number,730 tokenId: number, admin: IKeyringPair, owner: CrossAccountId | string, approved: CrossAccountId | string, amount: number | bigint = 1,731) {732 await usingApi(async (api: ApiPromise) => {733 const approveNftTx = api.tx.nft.approve(normalizeAccountId(approved), collectionId, tokenId, amount);734 const events = await submitTransactionAsync(admin, approveNftTx);735 const result = getGenericResult(events);736 expect(result.success).to.be.true;737738 expect(await getAllowance(api, collectionId, owner, approved, tokenId)).to.be.equal(BigInt(amount));739 });740}741742export async function743transferFromExpectSuccess(744 collectionId: number,745 tokenId: number,746 accountApproved: IKeyringPair,747 accountFrom: IKeyringPair | CrossAccountId,748 accountTo: IKeyringPair | CrossAccountId,749 value: number | bigint = 1,750 type = 'NFT',751) {752 await usingApi(async (api: ApiPromise) => {753 const to = normalizeAccountId(accountTo);754 let balanceBefore = 0n;755 if (type === 'Fungible') {756 balanceBefore = await getBalance(api, collectionId, to, tokenId);757 }758 const transferFromTx = api.tx.nft.transferFrom(normalizeAccountId(accountFrom), to, collectionId, tokenId, value);759 const events = await submitTransactionAsync(accountApproved, transferFromTx);760 const result = getCreateItemResult(events);761 762 expect(result.success).to.be.true;763 if (type === 'NFT') {764 expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(to);765 }766 if (type === 'Fungible') {767 const balanceAfter = await getBalance(api, collectionId, to, tokenId);768 expect(balanceAfter - balanceBefore).to.be.equal(BigInt(value));769 }770 if (type === 'ReFungible') {771 expect(await getBalance(api, collectionId, to, tokenId)).to.be.equal(BigInt(value));772 }773 });774}775776export async function777transferFromExpectFail(778 collectionId: number,779 tokenId: number,780 accountApproved: IKeyringPair,781 accountFrom: IKeyringPair,782 accountTo: IKeyringPair,783 value: number | bigint = 1,784) {785 await usingApi(async (api: ApiPromise) => {786 const transferFromTx = api.tx.nft.transferFrom(normalizeAccountId(accountFrom.address), normalizeAccountId(accountTo.address), collectionId, tokenId, value);787 const events = await expect(submitTransactionExpectFailAsync(accountApproved, transferFromTx)).to.be.rejected;788 const result = getCreateCollectionResult(events);789 790 expect(result.success).to.be.false;791 });792}793794795async function getBlockNumber(api: ApiPromise): Promise<number> {796 return new Promise<number>(async (resolve) => {797 const unsubscribe = await api.rpc.chain.subscribeNewHeads((head) => {798 unsubscribe();799 resolve(head.number.toNumber());800 });801 });802}803804export async function addCollectionAdminExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | CrossAccountId) {805 await usingApi(async (api) => {806 const changeAdminTx = api.tx.nft.addCollectionAdmin(collectionId, normalizeAccountId(address));807 const events = await submitTransactionAsync(sender, changeAdminTx);808 const result = getCreateCollectionResult(events);809 expect(result.success).to.be.true;810 });811}812813export async function814getFreeBalance(account: IKeyringPair) : Promise<bigint>815{816 let balance = 0n;817 await usingApi(async (api) => {818 balance = BigInt((await api.query.system.account(account.address)).data.free.toString());819 });820821 return balance;822}823824export async function825scheduleTransferExpectSuccess(826 collectionId: number,827 tokenId: number,828 sender: IKeyringPair,829 recipient: IKeyringPair,830 value: number | bigint = 1,831 blockSchedule: number,832) {833 await usingApi(async (api: ApiPromise) => {834 const blockNumber: number | undefined = await getBlockNumber(api);835 const expectedBlockNumber = blockNumber + blockSchedule;836837 expect(blockNumber).to.be.greaterThan(0);838 const transferTx = api.tx.nft.transfer(normalizeAccountId(recipient.address), collectionId, tokenId, value);839 const scheduleTx = api.tx.scheduler.schedule(expectedBlockNumber, null, 0, transferTx as any);840841 await submitTransactionAsync(sender, scheduleTx);842843 const recipientBalanceBefore = (await api.query.system.account(recipient.address)).data.free.toBigInt();844845 expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(sender.address));846847 848 await waitNewBlocks(blockSchedule + 1);849850 const recipientBalanceAfter = (await api.query.system.account(recipient.address)).data.free.toBigInt();851852 expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(recipient.address));853 expect(recipientBalanceAfter).to.be.equal(recipientBalanceBefore);854 });855}856857858export async function859transferExpectSuccess(860 collectionId: number,861 tokenId: number,862 sender: IKeyringPair,863 recipient: IKeyringPair | CrossAccountId,864 value: number | bigint = 1,865 type = 'NFT',866) {867 await usingApi(async (api: ApiPromise) => {868 const to = normalizeAccountId(recipient);869870 let balanceBefore = 0n;871 if (type === 'Fungible') {872 balanceBefore = await getBalance(api, collectionId, to, tokenId);873 }874 const transferTx = api.tx.nft.transfer(to, collectionId, tokenId, value);875 const events = await submitTransactionAsync(sender, transferTx);876 const result = getTransferResult(events);877 878 expect(result.success).to.be.true;879 expect(result.collectionId).to.be.equal(collectionId);880 expect(result.itemId).to.be.equal(tokenId);881 expect(result.sender).to.be.deep.equal(normalizeAccountId(sender.address));882 expect(result.recipient).to.be.deep.equal(to);883 expect(result.value).to.be.equal(BigInt(value));884 if (type === 'NFT') {885 expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(to);886 }887 if (type === 'Fungible') {888 const balanceAfter = await getBalance(api, collectionId, to, tokenId);889 expect(balanceAfter - balanceBefore).to.be.equal(BigInt(value));890 }891 if (type === 'ReFungible') {892 expect(await getBalance(api, collectionId, to, tokenId) >= value).to.be.true;893 }894 });895}896897export async function898transferExpectFailure(899 collectionId: number,900 tokenId: number,901 sender: IKeyringPair,902 recipient: IKeyringPair,903 value: number | bigint = 1,904) {905 await usingApi(async (api: ApiPromise) => {906 const transferTx = api.tx.nft.transfer(normalizeAccountId(recipient.address), collectionId, tokenId, value);907 const events = await expect(submitTransactionExpectFailAsync(sender, transferTx)).to.be.rejected;908 if (events && Array.isArray(events)) {909 const result = getCreateCollectionResult(events);910 911 expect(result.success).to.be.false;912 }913 });914}915916export async function917approveExpectFail(918 collectionId: number,919 tokenId: number, owner: IKeyringPair, approved: IKeyringPair, amount: number | bigint = 1,920) {921 await usingApi(async (api: ApiPromise) => {922 const approveNftTx = api.tx.nft.approve(normalizeAccountId(approved.address), collectionId, tokenId, amount);923 const events = await expect(submitTransactionExpectFailAsync(owner, approveNftTx)).to.be.rejected;924 const result = getCreateCollectionResult(events);925 926 expect(result.success).to.be.false;927 });928}929930export async function getBalance(931 api: ApiPromise,932 collectionId: number,933 owner: string | CrossAccountId,934 token: number,935): Promise<bigint> {936 return (await api.rpc.nft.balance(collectionId, normalizeAccountId(owner), token)).toBigInt();937}938export async function getTokenOwner(939 api: ApiPromise,940 collectionId: number,941 token: number,942): Promise<CrossAccountId> {943 return normalizeAccountId((await api.rpc.nft.tokenOwner(collectionId, token)).toJSON() as any);944}945export async function isTokenExists(946 api: ApiPromise,947 collectionId: number,948 token: number,949): Promise<boolean> {950 return (await api.rpc.nft.tokenExists(collectionId, token)).toJSON();951}952export async function getLastTokenId(953 api: ApiPromise,954 collectionId: number,955): Promise<number> {956 return (await api.rpc.nft.lastTokenId(collectionId)).toJSON();957}958export async function getAdminList(959 api: ApiPromise,960 collectionId: number,961): Promise<string[]> {962 return (await api.rpc.nft.adminlist(collectionId)).toHuman() as any;963}964export async function getVariableMetadata(965 api: ApiPromise,966 collectionId: number,967 tokenId: number,968): Promise<number[]> {969 return [...(await api.rpc.nft.variableMetadata(collectionId, tokenId))];970}971export async function getConstMetadata(972 api: ApiPromise,973 collectionId: number,974 tokenId: number,975): Promise<number[]> {976 return [...(await api.rpc.nft.constMetadata(collectionId, tokenId))];977}978979export async function createFungibleItemExpectSuccess(980 sender: IKeyringPair,981 collectionId: number,982 data: CreateFungibleData,983 owner: CrossAccountId | string = sender.address,984) {985 return await usingApi(async (api) => {986 const tx = api.tx.nft.createItem(collectionId, normalizeAccountId(owner), {Fungible: data});987988 const events = await submitTransactionAsync(sender, tx);989 const result = getCreateItemResult(events);990991 expect(result.success).to.be.true;992 return result.itemId;993 });994}995996export async function createItemExpectSuccess(sender: IKeyringPair, collectionId: number, createMode: string, owner: CrossAccountId | string = sender.address) {997 let newItemId = 0;998 await usingApi(async (api) => {999 const to = normalizeAccountId(owner);1000 const itemCountBefore = await getLastTokenId(api, collectionId);1001 const itemBalanceBefore = await getBalance(api, collectionId, to, newItemId);10021003 let tx;1004 if (createMode === 'Fungible') {1005 const createData = {fungible: {value: 10}};1006 tx = api.tx.nft.createItem(collectionId, to, createData as any);1007 } else if (createMode === 'ReFungible') {1008 const createData = {refungible: {const_data: [], variable_data: [], pieces: 100}};1009 tx = api.tx.nft.createItem(collectionId, to, createData as any);1010 } else {1011 const createData = {nft: {const_data: [], variable_data: []}};1012 tx = api.tx.nft.createItem(collectionId, to, createData as any);1013 }10141015 const events = await submitTransactionAsync(sender, tx);1016 const result = getCreateItemResult(events);10171018 const itemCountAfter = await getLastTokenId(api, collectionId);1019 const itemBalanceAfter = await getBalance(api, collectionId, to, newItemId);10201021 1022 1023 expect(result.success).to.be.true;1024 if (createMode === 'Fungible') {1025 expect(itemBalanceAfter - itemBalanceBefore).to.be.equal(10n);1026 } else {1027 expect(itemCountAfter).to.be.equal(itemCountBefore + 1);1028 }1029 expect(collectionId).to.be.equal(result.collectionId);1030 expect(itemCountAfter.toString()).to.be.equal(result.itemId.toString());1031 expect(to).to.be.deep.equal(result.recipient);1032 newItemId = result.itemId;1033 });1034 return newItemId;1035}10361037export async function createItemExpectFailure(sender: IKeyringPair, collectionId: number, createMode: string, owner: string = sender.address) {1038 await usingApi(async (api) => {1039 const tx = api.tx.nft.createItem(collectionId, normalizeAccountId(owner), createMode);10401041 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1042 const result = getCreateItemResult(events);10431044 expect(result.success).to.be.false;1045 });1046}10471048export async function setPublicAccessModeExpectSuccess(1049 sender: IKeyringPair, collectionId: number,1050 accessMode: 'Normal' | 'AllowList',1051) {1052 await usingApi(async (api) => {10531054 1055 const tx = api.tx.nft.setPublicAccessMode(collectionId, accessMode);1056 const events = await submitTransactionAsync(sender, tx);1057 const result = getGenericResult(events);10581059 1060 const collection = await queryCollectionExpectSuccess(api, collectionId);10611062 1063 1064 expect(result.success).to.be.true;1065 expect(collection.access.toHuman()).to.be.equal(accessMode);1066 });1067}10681069export async function setPublicAccessModeExpectFail(1070 sender: IKeyringPair, collectionId: number,1071 accessMode: 'Normal' | 'AllowList',1072) {1073 await usingApi(async (api) => {10741075 1076 const tx = api.tx.nft.setPublicAccessMode(collectionId, accessMode);1077 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1078 const result = getGenericResult(events);10791080 1081 1082 expect(result.success).to.be.false;1083 });1084}10851086export async function enableAllowListExpectSuccess(sender: IKeyringPair, collectionId: number) {1087 await setPublicAccessModeExpectSuccess(sender, collectionId, 'AllowList');1088}10891090export async function enableAllowListExpectFail(sender: IKeyringPair, collectionId: number) {1091 await setPublicAccessModeExpectFail(sender, collectionId, 'AllowList');1092}10931094export async function disableAllowListExpectSuccess(sender: IKeyringPair, collectionId: number) {1095 await setPublicAccessModeExpectSuccess(sender, collectionId, 'Normal');1096}10971098export async function setMintPermissionExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {1099 await usingApi(async (api) => {11001101 1102 const tx = api.tx.nft.setMintPermission(collectionId, enabled);1103 const events = await submitTransactionAsync(sender, tx);1104 const result = getGenericResult(events);1105 expect(result.success).to.be.true;11061107 1108 const collection = await queryCollectionExpectSuccess(api, collectionId);11091110 expect(collection.mintMode.toHuman()).to.be.equal(enabled);1111 });1112}11131114export async function enablePublicMintingExpectSuccess(sender: IKeyringPair, collectionId: number) {1115 await setMintPermissionExpectSuccess(sender, collectionId, true);1116}11171118export async function setMintPermissionExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {1119 await usingApi(async (api) => {1120 1121 const tx = api.tx.nft.setMintPermission(collectionId, enabled);1122 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1123 const result = getCreateCollectionResult(events);1124 1125 expect(result.success).to.be.false;1126 });1127}11281129export async function setChainLimitsExpectFailure(sender: IKeyringPair, limits: IChainLimits) {1130 await usingApi(async (api) => {1131 1132 const tx = api.tx.nft.setChainLimits(limits);1133 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1134 const result = getCreateCollectionResult(events);1135 1136 expect(result.success).to.be.false;1137 });1138}11391140export async function isAllowlisted(api: ApiPromise, collectionId: number, address: string | CrossAccountId) {1141 return (await api.rpc.nft.allowed(collectionId, normalizeAccountId(address))).toJSON();1142}11431144export async function addToAllowListExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId | CrossAccountId) {1145 await usingApi(async (api) => {1146 expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.false;11471148 1149 const tx = api.tx.nft.addToAllowList(collectionId, normalizeAccountId(address));1150 const events = await submitTransactionAsync(sender, tx);1151 const result = getGenericResult(events);1152 expect(result.success).to.be.true;11531154 expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;1155 });1156}11571158export async function addToAllowListAgainExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId) {1159 await usingApi(async (api) => {11601161 expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;11621163 1164 const tx = api.tx.nft.addToAllowList(collectionId, normalizeAccountId(address));1165 const events = await submitTransactionAsync(sender, tx);1166 const result = getGenericResult(events);1167 expect(result.success).to.be.true;11681169 expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;1170 });1171}11721173export async function addToAllowListExpectFail(sender: IKeyringPair, collectionId: number, address: string | AccountId) {1174 await usingApi(async (api) => {11751176 1177 const tx = api.tx.nft.addToAllowList(collectionId, normalizeAccountId(address));1178 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1179 const result = getGenericResult(events);11801181 1182 1183 expect(result.success).to.be.false;1184 });1185}11861187export async function removeFromAllowListExpectSuccess(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1188 await usingApi(async (api) => {1189 1190 const tx = api.tx.nft.removeFromAllowList(collectionId, normalizeAccountId(address));1191 const events = await submitTransactionAsync(sender, tx);1192 const result = getGenericResult(events);11931194 1195 1196 expect(result.success).to.be.true;1197 });1198}11991200export async function removeFromAllowListExpectFailure(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1201 await usingApi(async (api) => {1202 1203 const tx = api.tx.nft.removeFromAllowList(collectionId, normalizeAccountId(address));1204 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1205 const result = getGenericResult(events);12061207 1208 1209 expect(result.success).to.be.false;1210 });1211}12121213export const getDetailedCollectionInfo = async (api: ApiPromise, collectionId: number)1214 : Promise<NftDataStructsCollection | null> => {1215 return (await api.rpc.nft.collectionById(collectionId)).unwrapOr(null);1216};12171218export const getCreatedCollectionCount = async (api: ApiPromise): Promise<number> => {1219 1220 return (await api.rpc.nft.collectionStats()).created.toNumber();1221};12221223export async function queryCollectionExpectSuccess(api: ApiPromise, collectionId: number): Promise<NftDataStructsCollection> {1224 return (await api.rpc.nft.collectionById(collectionId)).unwrap();1225}12261227export async function waitNewBlocks(blocksCount = 1): Promise<void> {1228 await usingApi(async (api) => {1229 const promise = new Promise<void>(async (resolve) => {1230 const unsubscribe = await api.rpc.chain.subscribeNewHeads(() => {1231 if (blocksCount > 0) {1232 blocksCount--;1233 } else {1234 unsubscribe();1235 resolve();1236 }1237 });1238 });1239 return promise;1240 });1241}