1234567891011121314151617import '../interfaces/augment-api-rpc';18import '../interfaces/augment-api-query';19import {ApiPromise, Keyring} from '@polkadot/api';20import type {AccountId, EventRecord, Event} from '@polkadot/types/interfaces';21import type {GenericEventData} from '@polkadot/types';22import {AnyTuple, IEvent, IKeyringPair} from '@polkadot/types/types';23import {evmToAddress} from '@polkadot/util-crypto';24import BN from 'bn.js';25import chai from 'chai';26import chaiAsPromised from 'chai-as-promised';27import {default as usingApi, executeTransaction, submitTransactionAsync, submitTransactionExpectFailAsync} from '../substrate/substrate-api';28import {hexToStr, strToUTF16, utf16ToStr} from './util';29import {UpDataStructsRpcCollection, UpDataStructsCreateItemData, UpDataStructsProperty} from '@polkadot/types/lookup';30import {UpDataStructsTokenChild} from '../interfaces';31import {Context} from 'mocha';3233chai.use(chaiAsPromised);34const expect = chai.expect;3536export type CrossAccountId = {37 Substrate: string,38} | {39 Ethereum: string,40};414243export enum Pallets {44 Inflation = 'inflation',45 RmrkCore = 'rmrkcore',46 RmrkEquip = 'rmrkequip',47 ReFungible = 'refungible',48 Fungible = 'fungible',49 NFT = 'nonfungible',50 Scheduler = 'scheduler',51}5253export async function isUnique(): Promise<boolean> {54 return usingApi(async api => {55 const chain = await api.rpc.system.chain();5657 return chain.eq('UNIQUE');58 });59}6061export async function isQuartz(): Promise<boolean> {62 return usingApi(async api => {63 const chain = await api.rpc.system.chain();64 65 return chain.eq('QUARTZ');66 });67}6869let modulesNames: any;70export function getModuleNames(api: ApiPromise): string[] {71 if (typeof modulesNames === 'undefined') 72 modulesNames = api.runtimeMetadata.asLatest.pallets.map(m => m.name.toString().toLowerCase());73 return modulesNames;74}7576export async function missingRequiredPallets(requiredPallets: string[]): Promise<string[]> {77 return await usingApi(async api => {78 const pallets = getModuleNames(api);7980 return requiredPallets.filter(p => !pallets.includes(p));81 });82}8384export async function checkPalletsPresence(requiredPallets: string[]): Promise<boolean> {85 return (await missingRequiredPallets(requiredPallets)).length == 0;86}8788export async function requirePallets(mocha: Context, requiredPallets: string[]) {89 const missingPallets = await missingRequiredPallets(requiredPallets);9091 if (missingPallets.length > 0) {92 const skippingTestMsg = `\tSkipping test "${mocha.test?.title}".`;93 const missingPalletsMsg = `\tThe following pallets are missing:\n\t- ${missingPallets.join('\n\t- ')}`;94 const skipMsg = `${skippingTestMsg}\n${missingPalletsMsg}`;9596 console.error('\x1b[38:5:208m%s\x1b[0m', skipMsg);9798 mocha.skip();99 }100}101102export function bigIntToSub(api: ApiPromise, number: bigint) {103 return api.registry.createType('AccountId', '0x' + number.toString(16).padStart(64, '0')).toJSON();104}105106export function bigIntToDecimals(number: bigint, decimals = 18): string {107 const numberStr = number.toString();108 const dotPos = numberStr.length - decimals;109110 if (dotPos <= 0) {111 return '0.' + numberStr;112 } else {113 const intPart = numberStr.substring(0, dotPos);114 const fractPart = numberStr.substring(dotPos);115 return intPart + '.' + fractPart;116 }117}118119export function normalizeAccountId(input: string | AccountId | CrossAccountId | IKeyringPair): CrossAccountId {120 if (typeof input === 'string') {121 if (input.length >= 47) {122 return {Substrate: input};123 } else if (input.length === 42 && input.startsWith('0x')) {124 return {Ethereum: input.toLowerCase()};125 } else if (input.length === 40 && !input.startsWith('0x')) {126 return {Ethereum: '0x' + input.toLowerCase()};127 } else {128 throw new Error(`Unknown address format: "${input}"`);129 }130 }131 if ('address' in input) {132 return {Substrate: input.address};133 }134 if ('Ethereum' in input) {135 return {136 Ethereum: input.Ethereum.toLowerCase(),137 };138 } else if ('ethereum' in input) {139 return {140 Ethereum: (input as any).ethereum.toLowerCase(),141 };142 } else if ('Substrate' in input) {143 return input;144 } else if ('substrate' in input) {145 return {146 Substrate: (input as any).substrate,147 };148 }149150 151 return {Substrate: input.toString()};152}153export function toSubstrateAddress(input: string | CrossAccountId | IKeyringPair): string {154 input = normalizeAccountId(input);155 if ('Substrate' in input) {156 return input.Substrate;157 } else {158 return evmToAddress(input.Ethereum);159 }160}161162export const U128_MAX = (1n << 128n) - 1n;163164const MICROUNIQUE = 1_000_000_000_000n;165const MILLIUNIQUE = 1_000n * MICROUNIQUE;166const CENTIUNIQUE = 10n * MILLIUNIQUE;167export const UNIQUE = 100n * CENTIUNIQUE;168169interface GenericResult<T> {170 success: boolean;171 data: T | null;172}173174interface CreateCollectionResult {175 success: boolean;176 collectionId: number;177}178179interface CreateItemResult {180 success: boolean;181 collectionId: number;182 itemId: number;183 recipient?: CrossAccountId;184 amount?: number;185}186187interface DestroyItemResult {188 success: boolean;189 collectionId: number;190 itemId: number;191 owner: CrossAccountId;192 amount: number;193}194195interface TransferResult {196 collectionId: number;197 itemId: number;198 sender?: CrossAccountId;199 recipient?: CrossAccountId;200 value: bigint;201}202203interface IReFungibleOwner {204 fraction: BN;205 owner: number[];206}207208interface IGetMessage {209 checkMsgUnqMethod: string;210 checkMsgTrsMethod: string;211 checkMsgSysMethod: string;212}213214export interface IFungibleTokenDataType {215 value: number;216}217218export interface IChainLimits {219 collectionNumbersLimit: number;220 accountTokenOwnershipLimit: number;221 collectionsAdminsLimit: number;222 customDataLimit: number;223 nftSponsorTransferTimeout: number;224 fungibleSponsorTransferTimeout: number;225 refungibleSponsorTransferTimeout: number;226 227 228}229230export interface IReFungibleTokenDataType {231 owner: IReFungibleOwner[];232}233234export function uniqueEventMessage(events: EventRecord[]): IGetMessage {235 let checkMsgUnqMethod = '';236 let checkMsgTrsMethod = '';237 let checkMsgSysMethod = '';238 events.forEach(({event: {method, section}}) => {239 if (section === 'common') {240 checkMsgUnqMethod = method;241 } else if (section === 'treasury') {242 checkMsgTrsMethod = method;243 } else if (section === 'system') {244 checkMsgSysMethod = method;245 } else { return null; }246 });247 const result: IGetMessage = {248 checkMsgUnqMethod,249 checkMsgTrsMethod,250 checkMsgSysMethod,251 };252 return result;253}254255export function getEvent<T extends Event>(events: EventRecord[], check: (event: IEvent<AnyTuple>) => event is T): T | undefined {256 const event = events.find(r => check(r.event));257 if (!event) return;258 return event.event as T;259}260261export function getGenericResult<T>(events: EventRecord[]): GenericResult<T>;262export function getGenericResult<T>(263 events: EventRecord[],264 expectSection: string,265 expectMethod: string,266 extractAction: (data: GenericEventData) => T267): GenericResult<T>;268269export function getGenericResult<T>(270 events: EventRecord[],271 expectSection?: string,272 expectMethod?: string,273 extractAction?: (data: GenericEventData) => T,274): GenericResult<T> {275 let success = false;276 let successData = null;277278 events.forEach(({event: {data, method, section}}) => {279 280 if (method === 'ExtrinsicSuccess') {281 success = true;282 } else if ((expectSection == section) && (expectMethod == method)) {283 successData = extractAction!(data as any);284 }285 });286287 const result: GenericResult<T> = {288 success,289 data: successData,290 };291 return result;292}293294export function getCreateCollectionResult(events: EventRecord[]): CreateCollectionResult {295 const genericResult = getGenericResult(events, 'common', 'CollectionCreated', (data) => parseInt(data[0].toString(), 10));296 const result: CreateCollectionResult = {297 success: genericResult.success,298 collectionId: genericResult.data ?? 0,299 };300 return result;301}302303export function getCreateItemsResult(events: EventRecord[]): CreateItemResult[] {304 const results: CreateItemResult[] = [];305 306 const genericResult = getGenericResult<CreateItemResult[]>(events, 'common', 'ItemCreated', (data) => {307 const collectionId = parseInt(data[0].toString(), 10);308 const itemId = parseInt(data[1].toString(), 10);309 const recipient = normalizeAccountId(data[2].toJSON() as any);310 const amount = parseInt(data[3].toString(), 10);311312 const itemRes: CreateItemResult = {313 success: true,314 collectionId,315 itemId,316 recipient,317 amount,318 };319320 results.push(itemRes);321 return results;322 });323324 if (!genericResult.success) return [];325 return results;326}327328export function getCreateItemResult(events: EventRecord[]): CreateItemResult {329 const genericResult = getGenericResult(events, 'common', 'ItemCreated', (data) => data.map(function(value) { return value.toJSON(); }));330 331 if (genericResult.data == null) 332 return {333 success: genericResult.success,334 collectionId: 0,335 itemId: 0,336 amount: 0,337 };338 else 339 return {340 success: genericResult.success,341 collectionId: genericResult.data[0] as number,342 itemId: genericResult.data[1] as number,343 recipient: normalizeAccountId(genericResult.data![2] as any),344 amount: genericResult.data[3] as number,345 };346}347348export function getDestroyItemsResult(events: EventRecord[]): DestroyItemResult[] {349 const results: DestroyItemResult[] = [];350 351 const genericResult = getGenericResult<DestroyItemResult[]>(events, 'common', 'ItemDestroyed', (data) => {352 const collectionId = parseInt(data[0].toString(), 10);353 const itemId = parseInt(data[1].toString(), 10);354 const owner = normalizeAccountId(data[2].toJSON() as any);355 const amount = parseInt(data[3].toString(), 10);356357 const itemRes: DestroyItemResult = {358 success: true,359 collectionId,360 itemId,361 owner,362 amount,363 };364365 results.push(itemRes);366 return results;367 });368369 if (!genericResult.success) return [];370 return results;371}372373export function getTransferResult(api: ApiPromise, events: EventRecord[]): TransferResult {374 for (const {event} of events) {375 if (api.events.common.Transfer.is(event)) {376 const [collection, token, sender, recipient, value] = event.data;377 return {378 collectionId: collection.toNumber(),379 itemId: token.toNumber(),380 sender: normalizeAccountId(sender.toJSON() as any),381 recipient: normalizeAccountId(recipient.toJSON() as any),382 value: value.toBigInt(),383 };384 }385 }386 throw new Error('no transfer event');387}388389interface Nft {390 type: 'NFT';391}392393interface Fungible {394 type: 'Fungible';395 decimalPoints: number;396}397398interface ReFungible {399 type: 'ReFungible';400}401402export type CollectionMode = Nft | Fungible | ReFungible;403404export type Property = {405 key: any,406 value: any,407};408409type Permission = {410 mutable: boolean;411 collectionAdmin: boolean;412 tokenOwner: boolean;413}414415type PropertyPermission = {416 key: any;417 permission: Permission;418}419420export type CreateCollectionParams = {421 mode: CollectionMode,422 name: string,423 description: string,424 tokenPrefix: string,425 properties?: Array<Property>,426 propPerm?: Array<PropertyPermission>427};428429const defaultCreateCollectionParams: CreateCollectionParams = {430 description: 'description',431 mode: {type: 'NFT'},432 name: 'name',433 tokenPrefix: 'prefix',434};435436export async function437createCollection(438 api: ApiPromise,439 sender: IKeyringPair,440 params: Partial<CreateCollectionParams> = {},441): Promise<CreateCollectionResult> {442 const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};443444 let modeprm = {};445 if (mode.type === 'NFT') {446 modeprm = {nft: null};447 } else if (mode.type === 'Fungible') {448 modeprm = {fungible: mode.decimalPoints};449 } else if (mode.type === 'ReFungible') {450 modeprm = {refungible: null};451 }452453 const tx = api.tx.unique.createCollectionEx({454 name: strToUTF16(name),455 description: strToUTF16(description),456 tokenPrefix: strToUTF16(tokenPrefix),457 mode: modeprm as any,458 });459 const events = await executeTransaction(api, sender, tx);460 return getCreateCollectionResult(events);461}462463export async function createCollectionExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {464 const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};465466 let collectionId = 0;467 await usingApi(async (api, privateKeyWrapper) => {468 469 const collectionCountBefore = await getCreatedCollectionCount(api);470471 472 const alicePrivateKey = privateKeyWrapper('//Alice');473474 const result = await createCollection(api, alicePrivateKey, params);475476 477 const collectionCountAfter = await getCreatedCollectionCount(api);478479 480 const collection = await queryCollectionExpectSuccess(api, result.collectionId);481482 483 484 expect(result.success).to.be.true;485 expect(result.collectionId).to.be.equal(collectionCountAfter);486 487 expect(collection).to.be.not.null;488 expect(collectionCountAfter).to.be.equal(collectionCountBefore + 1, 'Error: NFT collection NOT created.');489 expect(collection.owner.toString()).to.be.equal(toSubstrateAddress(alicePrivateKey));490 expect(utf16ToStr(collection.name.toJSON() as any)).to.be.equal(name);491 expect(utf16ToStr(collection.description.toJSON() as any)).to.be.equal(description);492 expect(hexToStr(collection.tokenPrefix.toJSON())).to.be.equal(tokenPrefix);493494 collectionId = result.collectionId;495 });496497 return collectionId;498}499500export async function createCollectionWithPropsExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {501 const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};502503 let collectionId = 0;504 await usingApi(async (api, privateKeyWrapper) => {505 506 const collectionCountBefore = await getCreatedCollectionCount(api);507508 509 const alicePrivateKey = privateKeyWrapper('//Alice');510511 let modeprm = {};512 if (mode.type === 'NFT') {513 modeprm = {nft: null};514 } else if (mode.type === 'Fungible') {515 modeprm = {fungible: mode.decimalPoints};516 } else if (mode.type === 'ReFungible') {517 modeprm = {refungible: null};518 }519520 const tx = api.tx.unique.createCollectionEx({name: strToUTF16(name), description: strToUTF16(description), tokenPrefix: strToUTF16(tokenPrefix), mode: modeprm as any, properties: params.properties, tokenPropertyPermissions: params.propPerm});521 const events = await submitTransactionAsync(alicePrivateKey, tx);522 const result = getCreateCollectionResult(events);523524 525 const collectionCountAfter = await getCreatedCollectionCount(api);526527 528 const collection = await queryCollectionExpectSuccess(api, result.collectionId);529530 531 532 expect(result.success).to.be.true;533 expect(result.collectionId).to.be.equal(collectionCountAfter);534 535 expect(collection).to.be.not.null;536 expect(collectionCountAfter).to.be.equal(collectionCountBefore + 1, 'Error: NFT collection NOT created.');537 expect(collection.owner.toString()).to.be.equal(toSubstrateAddress(alicePrivateKey));538 expect(utf16ToStr(collection.name.toJSON() as any)).to.be.equal(name);539 expect(utf16ToStr(collection.description.toJSON() as any)).to.be.equal(description);540 expect(hexToStr(collection.tokenPrefix.toJSON())).to.be.equal(tokenPrefix);541542543 collectionId = result.collectionId;544 });545546 return collectionId;547}548549export async function createCollectionWithPropsExpectFailure(params: Partial<CreateCollectionParams> = {}) {550 const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};551552 await usingApi(async (api, privateKeyWrapper) => {553 554 const collectionCountBefore = await getCreatedCollectionCount(api);555556 557 const alicePrivateKey = privateKeyWrapper('//Alice');558559 let modeprm = {};560 if (mode.type === 'NFT') {561 modeprm = {nft: null};562 } else if (mode.type === 'Fungible') {563 modeprm = {fungible: mode.decimalPoints};564 } else if (mode.type === 'ReFungible') {565 modeprm = {refungible: null};566 }567568 const tx = api.tx.unique.createCollectionEx({name: strToUTF16(name), description: strToUTF16(description), tokenPrefix: strToUTF16(tokenPrefix), mode: modeprm as any, properties: params.properties, tokenPropertyPermissions: params.propPerm});569 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;570571572 573 const collectionCountAfter = await getCreatedCollectionCount(api);574575 expect(collectionCountAfter).to.be.equal(collectionCountBefore, 'Error: Collection with incorrect data created.');576 });577}578579export async function createCollectionExpectFailure(params: Partial<CreateCollectionParams> = {}) {580 const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};581582 let modeprm = {};583 if (mode.type === 'NFT') {584 modeprm = {nft: null};585 } else if (mode.type === 'Fungible') {586 modeprm = {fungible: mode.decimalPoints};587 } else if (mode.type === 'ReFungible') {588 modeprm = {refungible: null};589 }590591 await usingApi(async (api, privateKeyWrapper) => {592 593 const collectionCountBefore = await getCreatedCollectionCount(api);594595 596 const alicePrivateKey = privateKeyWrapper('//Alice');597 const tx = api.tx.unique.createCollectionEx({name: strToUTF16(name), description: strToUTF16(description), tokenPrefix: strToUTF16(tokenPrefix), mode: modeprm as any});598 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;599600 601 const collectionCountAfter = await getCreatedCollectionCount(api);602603 604 expect(collectionCountAfter).to.be.equal(collectionCountBefore, 'Error: Collection with incorrect data created.');605 });606}607608export async function findUnusedAddress(api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair, seedAddition = ''): Promise<IKeyringPair> {609 let bal = 0n;610 let unused;611 do {612 const randomSeed = 'seed' + Math.floor(Math.random() * Math.floor(10000)) + seedAddition;613 unused = privateKeyWrapper(`//${randomSeed}`);614 bal = (await api.query.system.account(unused.address)).data.free.toBigInt();615 } while (bal !== 0n);616 return unused;617}618619export async function getAllowance(api: ApiPromise, collectionId: number, owner: CrossAccountId | string | IKeyringPair, approved: CrossAccountId | string | IKeyringPair, tokenId: number) {620 return (await api.rpc.unique.allowance(collectionId, normalizeAccountId(owner), normalizeAccountId(approved), tokenId)).toBigInt();621}622623export function findUnusedAddresses(api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair, amount: number): Promise<IKeyringPair[]> {624 return Promise.all(new Array(amount).fill(null).map(() => findUnusedAddress(api, privateKeyWrapper, '_' + Date.now())));625}626627export async function findNotExistingCollection(api: ApiPromise): Promise<number> {628 const totalNumber = await getCreatedCollectionCount(api);629 const newCollection: number = totalNumber + 1;630 return newCollection;631}632633function getDestroyResult(events: EventRecord[]): boolean {634 let success = false;635 events.forEach(({event: {method}}) => {636 if (method == 'ExtrinsicSuccess') {637 success = true;638 }639 });640 return success;641}642643export async function destroyCollectionExpectFailure(collectionId: number, senderSeed = '//Alice') {644 await usingApi(async (api, privateKeyWrapper) => {645 646 const alicePrivateKey = privateKeyWrapper(senderSeed);647 const tx = api.tx.unique.destroyCollection(collectionId);648 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;649 });650}651652export async function destroyCollectionExpectSuccess(collectionId: number, senderSeed = '//Alice') {653 await usingApi(async (api, privateKeyWrapper) => {654 655 const alicePrivateKey = privateKeyWrapper(senderSeed);656 const tx = api.tx.unique.destroyCollection(collectionId);657 const events = await submitTransactionAsync(alicePrivateKey, tx);658 const result = getDestroyResult(events);659 expect(result).to.be.true;660661 662 expect(await getDetailedCollectionInfo(api, collectionId)).to.be.null;663 });664}665666export async function setCollectionLimitsExpectSuccess(sender: IKeyringPair, collectionId: number, limits: any) {667 await usingApi(async (api) => {668 const tx = api.tx.unique.setCollectionLimits(collectionId, limits);669 const events = await submitTransactionAsync(sender, tx);670 const result = getGenericResult(events);671672 expect(result.success).to.be.true;673 });674}675676export const setCollectionPermissionsExpectSuccess = async (sender: IKeyringPair, collectionId: number, permissions: any) => {677 await usingApi(async(api) => {678 const tx = api.tx.unique.setCollectionPermissions(collectionId, permissions);679 const events = await submitTransactionAsync(sender, tx);680 const result = getGenericResult(events);681682 expect(result.success).to.be.true;683 });684};685686export async function setCollectionLimitsExpectFailure(sender: IKeyringPair, collectionId: number, limits: any) {687 await usingApi(async (api) => {688 const tx = api.tx.unique.setCollectionLimits(collectionId, limits);689 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;690 const result = getGenericResult(events);691692 expect(result.success).to.be.false;693 });694}695696export async function setCollectionSponsorExpectSuccess(collectionId: number, sponsor: string, sender = '//Alice') {697 await usingApi(async (api, privateKeyWrapper) => {698699 700 const senderPrivateKey = privateKeyWrapper(sender);701 const tx = api.tx.unique.setCollectionSponsor(collectionId, sponsor);702 const events = await submitTransactionAsync(senderPrivateKey, tx);703 const result = getGenericResult(events);704705 706 const collection = await queryCollectionExpectSuccess(api, collectionId);707708 709 expect(result.success).to.be.true;710 expect(collection.sponsorship.toJSON()).to.deep.equal({711 unconfirmed: sponsor,712 });713 });714}715716export async function removeCollectionSponsorExpectSuccess(collectionId: number, sender = '//Alice') {717 await usingApi(async (api, privateKeyWrapper) => {718719 720 const alicePrivateKey = privateKeyWrapper(sender);721 const tx = api.tx.unique.removeCollectionSponsor(collectionId);722 const events = await submitTransactionAsync(alicePrivateKey, tx);723 const result = getGenericResult(events);724725 726 const collection = await queryCollectionExpectSuccess(api, collectionId);727728 729 expect(result.success).to.be.true;730 expect(collection.sponsorship.toJSON()).to.be.deep.equal({disabled: null});731 });732}733734export async function removeCollectionSponsorExpectFailure(collectionId: number, senderSeed = '//Alice') {735 await usingApi(async (api, privateKeyWrapper) => {736737 738 const alicePrivateKey = privateKeyWrapper(senderSeed);739 const tx = api.tx.unique.removeCollectionSponsor(collectionId);740 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;741 });742}743744export async function setCollectionSponsorExpectFailure(collectionId: number, sponsor: string, senderSeed = '//Alice') {745 await usingApi(async (api, privateKeyWrapper) => {746747 748 const alicePrivateKey = privateKeyWrapper(senderSeed);749 const tx = api.tx.unique.setCollectionSponsor(collectionId, sponsor);750 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;751 });752}753754export async function confirmSponsorshipExpectSuccess(collectionId: number, senderSeed = '//Alice') {755 await usingApi(async (api, privateKeyWrapper) => {756757 758 const sender = privateKeyWrapper(senderSeed);759 await confirmSponsorshipByKeyExpectSuccess(collectionId, sender);760 });761}762763export async function confirmSponsorshipByKeyExpectSuccess(collectionId: number, sender: IKeyringPair) {764 await usingApi(async (api, privateKeyWrapper) => {765766 767 const tx = api.tx.unique.confirmSponsorship(collectionId);768 const events = await submitTransactionAsync(sender, tx);769 const result = getGenericResult(events);770771 772 const collection = await queryCollectionExpectSuccess(api, collectionId);773774 775 expect(result.success).to.be.true;776 expect(collection.sponsorship.toJSON()).to.be.deep.equal({777 confirmed: sender.address,778 });779 });780}781782783export async function confirmSponsorshipExpectFailure(collectionId: number, senderSeed = '//Alice') {784 await usingApi(async (api, privateKeyWrapper) => {785786 787 const sender = privateKeyWrapper(senderSeed);788 const tx = api.tx.unique.confirmSponsorship(collectionId);789 await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;790 });791}792793export async function enableContractSponsoringExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {794 await usingApi(async (api) => {795 const tx = api.tx.unique.enableContractSponsoring(contractAddress, enable);796 const events = await submitTransactionAsync(sender, tx);797 const result = getGenericResult(events);798799 expect(result.success).to.be.true;800 });801}802803export async function enableContractSponsoringExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {804 await usingApi(async (api) => {805 const tx = api.tx.unique.enableContractSponsoring(contractAddress, enable);806 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;807 const result = getGenericResult(events);808809 expect(result.success).to.be.false;810 });811}812813export async function setTransferFlagExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {814815 await usingApi(async (api) => {816817 const tx = api.tx.unique.setTransfersEnabledFlag(collectionId, enabled);818 const events = await submitTransactionAsync(sender, tx);819 const result = getGenericResult(events);820821 expect(result.success).to.be.true;822 });823}824825export async function setTransferFlagExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {826827 await usingApi(async (api) => {828829 const tx = api.tx.unique.setTransfersEnabledFlag(collectionId, enabled);830 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;831 const result = getGenericResult(events);832833 expect(result.success).to.be.false;834 });835}836837export async function setContractSponsoringRateLimitExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {838 await usingApi(async (api) => {839 const tx = api.tx.unique.setContractSponsoringRateLimit(contractAddress, rateLimit);840 const events = await submitTransactionAsync(sender, tx);841 const result = getGenericResult(events);842843 expect(result.success).to.be.true;844 });845}846847export async function setContractSponsoringRateLimitExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {848 await usingApi(async (api) => {849 const tx = api.tx.unique.setContractSponsoringRateLimit(contractAddress, rateLimit);850 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;851 const result = getGenericResult(events);852853 expect(result.success).to.be.false;854 });855}856857export async function getNextSponsored(858 api: ApiPromise,859 collectionId: number,860 account: string | CrossAccountId,861 tokenId: number,862): Promise<number> {863 return Number((await api.rpc.unique.nextSponsored(collectionId, account, tokenId)).unwrapOr(-1));864}865866export async function toggleContractAllowlistExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, value = true) {867 await usingApi(async (api) => {868 const tx = api.tx.unique.toggleContractAllowList(contractAddress, value);869 const events = await submitTransactionAsync(sender, tx);870 const result = getGenericResult(events);871872 expect(result.success).to.be.true;873 });874}875876export async function isAllowlistedInContract(contractAddress: AccountId | string, user: string) {877 let allowlisted = false;878 await usingApi(async (api) => {879 allowlisted = (await api.query.unique.contractAllowList(contractAddress, user)).toJSON() as boolean;880 });881 return allowlisted;882}883884export async function addToContractAllowListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {885 await usingApi(async (api) => {886 const tx = api.tx.unique.addToContractAllowList(contractAddress.toString(), user.toString());887 const events = await submitTransactionAsync(sender, tx);888 const result = getGenericResult(events);889890 expect(result.success).to.be.true;891 });892}893894export async function removeFromContractAllowListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {895 await usingApi(async (api) => {896 const tx = api.tx.unique.removeFromContractAllowList(contractAddress.toString(), user.toString());897 const events = await submitTransactionAsync(sender, tx);898 const result = getGenericResult(events);899900 expect(result.success).to.be.true;901 });902}903904export async function removeFromContractAllowListExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {905 await usingApi(async (api) => {906 const tx = api.tx.unique.removeFromContractAllowList(contractAddress.toString(), user.toString());907 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;908 const result = getGenericResult(events);909910 expect(result.success).to.be.false;911 });912}913914export interface CreateFungibleData {915 readonly Value: bigint;916}917918export interface CreateReFungibleData { }919export interface CreateNftData { }920921export type CreateItemData = {922 NFT: CreateNftData;923} | {924 Fungible: CreateFungibleData;925} | {926 ReFungible: CreateReFungibleData;927};928929export async function burnItem(api: ApiPromise, sender: IKeyringPair, collectionId: number, tokenId: number, value: number | bigint) : Promise<boolean> {930 const tx = api.tx.unique.burnItem(collectionId, tokenId, value);931 const events = await submitTransactionAsync(sender, tx);932 return getGenericResult(events).success;933}934935export async function burnItemExpectSuccess(sender: IKeyringPair, collectionId: number, tokenId: number, value: number | bigint = 1) {936 await usingApi(async (api) => {937 const balanceBefore = await getBalance(api, collectionId, normalizeAccountId(sender), tokenId);938 939 expect(balanceBefore >= BigInt(value)).to.be.true;940941 expect(await burnItem(api, sender, collectionId, tokenId, value)).to.be.true;942943 const balanceAfter = await getBalance(api, collectionId, normalizeAccountId(sender), tokenId);944 expect(balanceAfter + BigInt(value)).to.be.equal(balanceBefore);945 });946}947948export async function burnItemExpectFailure(sender: IKeyringPair, collectionId: number, tokenId: number, value: number | bigint = 1) {949 await usingApi(async (api) => {950 const tx = api.tx.unique.burnItem(collectionId, tokenId, value);951952 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;953 const result = getCreateCollectionResult(events);954 955 expect(result.success).to.be.false;956 });957}958959export async function burnFromExpectSuccess(sender: IKeyringPair, from: IKeyringPair | CrossAccountId, collectionId: number, tokenId: number, value: number | bigint = 1) {960 await usingApi(async (api) => {961 const tx = api.tx.unique.burnFrom(collectionId, normalizeAccountId(from), tokenId, value);962 const events = await submitTransactionAsync(sender, tx);963 return getGenericResult(events).success;964 });965}966967export async function968approve(969 api: ApiPromise,970 collectionId: number,971 tokenId: number, owner: IKeyringPair, approved: CrossAccountId | string | IKeyringPair, amount: number | bigint,972) {973 const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);974 const events = await submitTransactionAsync(owner, approveUniqueTx);975 return getGenericResult(events).success;976}977978export async function979approveExpectSuccess(980 collectionId: number,981 tokenId: number, owner: IKeyringPair, approved: CrossAccountId | string, amount: number | bigint = 1,982) {983 await usingApi(async (api: ApiPromise) => {984 const result = await approve(api, collectionId, tokenId, owner, approved, amount);985 expect(result).to.be.true;986987 expect(await getAllowance(api, collectionId, owner, approved, tokenId)).to.be.equal(BigInt(amount));988 });989}990991export async function adminApproveFromExpectSuccess(992 collectionId: number,993 tokenId: number, admin: IKeyringPair, owner: CrossAccountId | string, approved: CrossAccountId | string, amount: number | bigint = 1,994) {995 await usingApi(async (api: ApiPromise) => {996 const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);997 const events = await submitTransactionAsync(admin, approveUniqueTx);998 const result = getGenericResult(events);999 expect(result.success).to.be.true;10001001 expect(await getAllowance(api, collectionId, owner, approved, tokenId)).to.be.equal(BigInt(amount));1002 });1003}10041005export async function1006transferFrom(1007 api: ApiPromise,1008 collectionId: number,1009 tokenId: number,1010 accountApproved: IKeyringPair,1011 accountFrom: IKeyringPair | CrossAccountId,1012 accountTo: IKeyringPair | CrossAccountId,1013 value: number | bigint,1014) {1015 const from = normalizeAccountId(accountFrom);1016 const to = normalizeAccountId(accountTo);1017 const transferFromTx = api.tx.unique.transferFrom(from, to, collectionId, tokenId, value);1018 const events = await submitTransactionAsync(accountApproved, transferFromTx);1019 return getGenericResult(events).success;1020}10211022export async function1023transferFromExpectSuccess(1024 collectionId: number,1025 tokenId: number,1026 accountApproved: IKeyringPair,1027 accountFrom: IKeyringPair | CrossAccountId,1028 accountTo: IKeyringPair | CrossAccountId,1029 value: number | bigint = 1,1030 type = 'NFT',1031) {1032 await usingApi(async (api: ApiPromise) => {1033 const from = normalizeAccountId(accountFrom);1034 const to = normalizeAccountId(accountTo);1035 let balanceBefore = 0n;1036 if (type === 'Fungible' || type === 'ReFungible') {1037 balanceBefore = await getBalance(api, collectionId, to, tokenId);1038 }1039 expect(await transferFrom(api, collectionId, tokenId, accountApproved, accountFrom, accountTo, value)).to.be.true;1040 if (type === 'NFT') {1041 expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(to);1042 }1043 if (type === 'Fungible') {1044 const balanceAfter = await getBalance(api, collectionId, to, tokenId);1045 if (JSON.stringify(to) !== JSON.stringify(from)) {1046 expect(balanceAfter - balanceBefore).to.be.equal(BigInt(value));1047 } else {1048 expect(balanceAfter).to.be.equal(balanceBefore);1049 }1050 }1051 if (type === 'ReFungible') {1052 expect(await getBalance(api, collectionId, to, tokenId)).to.be.equal(balanceBefore + BigInt(value));1053 }1054 });1055}10561057export async function1058transferFromExpectFail(1059 collectionId: number,1060 tokenId: number,1061 accountApproved: IKeyringPair,1062 accountFrom: IKeyringPair,1063 accountTo: IKeyringPair,1064 value: number | bigint = 1,1065) {1066 await usingApi(async (api: ApiPromise) => {1067 const transferFromTx = api.tx.unique.transferFrom(normalizeAccountId(accountFrom.address), normalizeAccountId(accountTo.address), collectionId, tokenId, value);1068 const events = await expect(submitTransactionExpectFailAsync(accountApproved, transferFromTx)).to.be.rejected;1069 const result = getCreateCollectionResult(events);1070 1071 expect(result.success).to.be.false;1072 });1073}107410751076export async function getBlockNumber(api: ApiPromise): Promise<number> {1077 return new Promise<number>(async (resolve) => {1078 const unsubscribe = await api.rpc.chain.subscribeNewHeads((head) => {1079 unsubscribe();1080 resolve(head.number.toNumber());1081 });1082 });1083}10841085export async function addCollectionAdminExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | CrossAccountId) {1086 await usingApi(async (api) => {1087 const changeAdminTx = api.tx.unique.addCollectionAdmin(collectionId, normalizeAccountId(address));1088 const events = await submitTransactionAsync(sender, changeAdminTx);1089 const result = getCreateCollectionResult(events);1090 expect(result.success).to.be.true;1091 });1092}10931094export async function adminApproveFromExpectFail(1095 collectionId: number,1096 tokenId: number, admin: IKeyringPair, owner: CrossAccountId | string, approved: CrossAccountId | string, amount: number | bigint = 1,1097) {1098 await usingApi(async (api: ApiPromise) => {1099 const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);1100 const events = await expect(submitTransactionAsync(admin, approveUniqueTx)).to.be.rejected;1101 const result = getGenericResult(events);1102 expect(result.success).to.be.false;1103 });1104}11051106export async function1107getFreeBalance(account: IKeyringPair): Promise<bigint> {1108 let balance = 0n;1109 await usingApi(async (api) => {1110 balance = BigInt((await api.query.system.account(account.address)).data.free.toString());1111 });11121113 return balance;1114}11151116export async function paraSiblingSovereignAccount(paraid: number): Promise<string> {1117 return usingApi(async api => {1118 const siblingPrefix = '0x7369626c';1119 const encodedParaId = api.createType('u32', paraid).toHex(true).substring(2);1120 const suffix = '000000000000000000000000000000000000000000000000';11211122 return siblingPrefix + encodedParaId + suffix;1123 });1124}11251126export async function transferBalanceTo(api: ApiPromise, source: IKeyringPair, target: string, amount = 1000n * UNIQUE) {1127 const tx = api.tx.balances.transfer(target, amount);1128 const events = await submitTransactionAsync(source, tx);1129 const result = getGenericResult(events);1130 expect(result.success).to.be.true;1131}11321133export async function1134scheduleExpectSuccess(1135 operationTx: any,1136 sender: IKeyringPair,1137 blockSchedule: number,1138 scheduledId: string,1139 period = 1,1140 repetitions = 1,1141) {1142 await usingApi(async (api: ApiPromise) => {1143 const blockNumber: number | undefined = await getBlockNumber(api);1144 const expectedBlockNumber = blockNumber + blockSchedule;11451146 expect(blockNumber).to.be.greaterThan(0);1147 const scheduleTx = api.tx.scheduler.scheduleNamed( 1148 scheduledId,1149 expectedBlockNumber, 1150 repetitions > 1 ? [period, repetitions] : null, 1151 0, 1152 {Value: operationTx as any},1153 );11541155 const events = await submitTransactionAsync(sender, scheduleTx);1156 expect(getGenericResult(events).success).to.be.true;1157 });1158}11591160export async function1161scheduleExpectFailure(1162 operationTx: any,1163 sender: IKeyringPair,1164 blockSchedule: number,1165 scheduledId: string,1166 period = 1,1167 repetitions = 1,1168) {1169 await usingApi(async (api: ApiPromise) => {1170 const blockNumber: number | undefined = await getBlockNumber(api);1171 const expectedBlockNumber = blockNumber + blockSchedule;11721173 expect(blockNumber).to.be.greaterThan(0);1174 const scheduleTx = api.tx.scheduler.scheduleNamed( 1175 scheduledId,1176 expectedBlockNumber, 1177 repetitions <= 1 ? null : [period, repetitions], 1178 0, 1179 {Value: operationTx as any},1180 );11811182 1183 await expect(submitTransactionExpectFailAsync(sender, scheduleTx)).to.be.rejected;1184 1185 });1186}11871188export async function1189scheduleTransferAndWaitExpectSuccess(1190 collectionId: number,1191 tokenId: number,1192 sender: IKeyringPair,1193 recipient: IKeyringPair,1194 value: number | bigint = 1,1195 blockSchedule: number,1196 scheduledId: string,1197) {1198 await usingApi(async (api: ApiPromise) => {1199 await scheduleTransferExpectSuccess(collectionId, tokenId, sender, recipient, value, blockSchedule, scheduledId);12001201 const recipientBalanceBefore = (await api.query.system.account(recipient.address)).data.free.toBigInt();12021203 1204 await waitNewBlocks(blockSchedule + 1);12051206 const recipientBalanceAfter = (await api.query.system.account(recipient.address)).data.free.toBigInt();12071208 expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(recipient.address));1209 expect(recipientBalanceAfter).to.be.equal(recipientBalanceBefore);1210 });1211}12121213export async function1214scheduleTransferExpectSuccess(1215 collectionId: number,1216 tokenId: number,1217 sender: IKeyringPair,1218 recipient: IKeyringPair,1219 value: number | bigint = 1,1220 blockSchedule: number,1221 scheduledId: string,1222) {1223 await usingApi(async (api: ApiPromise) => {1224 const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient.address), collectionId, tokenId, value);12251226 await scheduleExpectSuccess(transferTx, sender, blockSchedule, scheduledId);12271228 expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(sender.address));1229 });1230}12311232export async function1233scheduleTransferFundsPeriodicExpectSuccess(1234 amount: bigint,1235 sender: IKeyringPair,1236 recipient: IKeyringPair,1237 blockSchedule: number,1238 scheduledId: string,1239 period: number,1240 repetitions: number,1241) {1242 await usingApi(async (api: ApiPromise) => {1243 const transferTx = api.tx.balances.transfer(recipient.address, amount);12441245 const balanceBefore = await getFreeBalance(recipient);1246 1247 await scheduleExpectSuccess(transferTx, sender, blockSchedule, scheduledId, period, repetitions);12481249 expect(await getFreeBalance(recipient)).to.be.equal(balanceBefore);1250 });1251}12521253export async function1254transfer(1255 api: ApiPromise,1256 collectionId: number,1257 tokenId: number,1258 sender: IKeyringPair,1259 recipient: IKeyringPair | CrossAccountId,1260 value: number | bigint,1261) : Promise<boolean> {1262 const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient), collectionId, tokenId, value);1263 const events = await executeTransaction(api, sender, transferTx);1264 return getGenericResult(events).success;1265}12661267export async function1268transferExpectSuccess(1269 collectionId: number,1270 tokenId: number,1271 sender: IKeyringPair,1272 recipient: IKeyringPair | CrossAccountId,1273 value: number | bigint = 1,1274 type = 'NFT',1275) {1276 await usingApi(async (api: ApiPromise) => {1277 const from = normalizeAccountId(sender);1278 const to = normalizeAccountId(recipient);12791280 let balanceBefore = 0n;1281 if (type === 'Fungible' || type === 'ReFungible') {1282 balanceBefore = await getBalance(api, collectionId, to, tokenId);1283 }12841285 const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient), collectionId, tokenId, value);1286 const events = await executeTransaction(api, sender, transferTx);1287 const result = getTransferResult(api, events);12881289 expect(result.collectionId).to.be.equal(collectionId);1290 expect(result.itemId).to.be.equal(tokenId);1291 expect(result.sender).to.be.deep.equal(normalizeAccountId(sender.address));1292 expect(result.recipient).to.be.deep.equal(to);1293 expect(result.value).to.be.equal(BigInt(value));12941295 if (type === 'NFT') {1296 expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(to);1297 }1298 if (type === 'Fungible' || type === 'ReFungible') {1299 const balanceAfter = await getBalance(api, collectionId, to, tokenId);1300 if (JSON.stringify(to) !== JSON.stringify(from)) {1301 expect(balanceAfter - balanceBefore).to.be.equal(BigInt(value));1302 } else {1303 expect(balanceAfter).to.be.equal(balanceBefore);1304 }1305 }1306 });1307}13081309export async function1310transferExpectFailure(1311 collectionId: number,1312 tokenId: number,1313 sender: IKeyringPair,1314 recipient: IKeyringPair | CrossAccountId,1315 value: number | bigint = 1,1316) {1317 await usingApi(async (api: ApiPromise) => {1318 const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient), collectionId, tokenId, value);1319 const events = await expect(submitTransactionExpectFailAsync(sender, transferTx)).to.be.rejected;1320 const result = getGenericResult(events);1321 1322 1323 1324 expect(result.success).to.be.false;1325 1326 });1327}13281329export async function1330approveExpectFail(1331 collectionId: number,1332 tokenId: number, owner: IKeyringPair, approved: IKeyringPair, amount: number | bigint = 1,1333) {1334 await usingApi(async (api: ApiPromise) => {1335 const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved.address), collectionId, tokenId, amount);1336 const events = await expect(submitTransactionExpectFailAsync(owner, approveUniqueTx)).to.be.rejected;1337 const result = getCreateCollectionResult(events);1338 1339 expect(result.success).to.be.false;1340 });1341}13421343export async function getBalance(1344 api: ApiPromise,1345 collectionId: number,1346 owner: string | CrossAccountId | IKeyringPair,1347 token: number,1348): Promise<bigint> {1349 return (await api.rpc.unique.balance(collectionId, normalizeAccountId(owner), token)).toBigInt();1350}1351export async function getTokenOwner(1352 api: ApiPromise,1353 collectionId: number,1354 token: number,1355): Promise<CrossAccountId> {1356 const owner = (await api.rpc.unique.tokenOwner(collectionId, token)).toJSON() as any;1357 if (owner == null) throw new Error('owner == null');1358 return normalizeAccountId(owner);1359}1360export async function getTopmostTokenOwner(1361 api: ApiPromise,1362 collectionId: number,1363 token: number,1364): Promise<CrossAccountId> {1365 const owner = (await api.rpc.unique.topmostTokenOwner(collectionId, token)).toJSON() as any;1366 if (owner == null) throw new Error('owner == null');1367 return normalizeAccountId(owner);1368}1369export async function getTokenChildren(1370 api: ApiPromise,1371 collectionId: number,1372 tokenId: number,1373): Promise<UpDataStructsTokenChild[]> {1374 return (await api.rpc.unique.tokenChildren(collectionId, tokenId)).toJSON() as any;1375}1376export async function isTokenExists(1377 api: ApiPromise,1378 collectionId: number,1379 token: number,1380): Promise<boolean> {1381 return (await api.rpc.unique.tokenExists(collectionId, token)).toJSON();1382}1383export async function getLastTokenId(1384 api: ApiPromise,1385 collectionId: number,1386): Promise<number> {1387 return (await api.rpc.unique.lastTokenId(collectionId)).toJSON();1388}1389export async function getAdminList(1390 api: ApiPromise,1391 collectionId: number,1392): Promise<string[]> {1393 return (await api.rpc.unique.adminlist(collectionId)).toHuman() as any;1394}1395export async function getTokenProperties(1396 api: ApiPromise,1397 collectionId: number,1398 tokenId: number,1399 propertyKeys: string[],1400): Promise<UpDataStructsProperty[]> {1401 return (await api.rpc.unique.tokenProperties(collectionId, tokenId, propertyKeys)).toHuman() as any;1402}14031404export async function createFungibleItemExpectSuccess(1405 sender: IKeyringPair,1406 collectionId: number,1407 data: CreateFungibleData,1408 owner: CrossAccountId | string = sender.address,1409) {1410 return await usingApi(async (api) => {1411 const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), {Fungible: data});14121413 const events = await submitTransactionAsync(sender, tx);1414 const result = getCreateItemResult(events);14151416 expect(result.success).to.be.true;1417 return result.itemId;1418 });1419}14201421export async function createMultipleItemsExpectSuccess(sender: IKeyringPair, collectionId: number, itemsData: any, owner: CrossAccountId | string = sender.address) {1422 await usingApi(async (api) => {1423 const to = normalizeAccountId(owner);1424 const tx = api.tx.unique.createMultipleItems(collectionId, to, itemsData);14251426 const events = await submitTransactionAsync(sender, tx);1427 expect(getGenericResult(events).success).to.be.true;1428 });1429}14301431export async function createMultipleItemsWithPropsExpectSuccess(sender: IKeyringPair, collectionId: number, itemsData: any, owner: CrossAccountId | string = sender.address) {1432 await usingApi(async (api) => {1433 const to = normalizeAccountId(owner);1434 const tx = api.tx.unique.createMultipleItems(collectionId, to, itemsData);14351436 const events = await submitTransactionAsync(sender, tx);1437 const result = getCreateItemsResult(events);14381439 for (const res of result) {1440 expect(await api.rpc.unique.tokenProperties(collectionId, res.itemId)).not.to.be.empty;1441 }1442 });1443}14441445export async function createMultipleItemsExWithPropsExpectSuccess(sender: IKeyringPair, collectionId: number, itemsData: any) {1446 await usingApi(async (api) => {1447 const tx = api.tx.unique.createMultipleItemsEx(collectionId, itemsData);14481449 const events = await submitTransactionAsync(sender, tx);1450 const result = getCreateItemsResult(events);14511452 for (const res of result) {1453 expect(await api.rpc.unique.tokenProperties(collectionId, res.itemId)).not.to.be.empty;1454 }1455 });1456}14571458export async function createItemWithPropsExpectSuccess(sender: IKeyringPair, collectionId: number, createMode: string, props: Array<Property>, owner: CrossAccountId | string = sender.address) {1459 let newItemId = 0;1460 await usingApi(async (api) => {1461 const to = normalizeAccountId(owner);1462 const itemCountBefore = await getLastTokenId(api, collectionId);1463 const itemBalanceBefore = await getBalance(api, collectionId, to, newItemId);14641465 let tx;1466 if (createMode === 'Fungible') {1467 const createData = {fungible: {value: 10}};1468 tx = api.tx.unique.createItem(collectionId, to, createData as any);1469 } else if (createMode === 'ReFungible') {1470 const createData = {refungible: {pieces: 100}};1471 tx = api.tx.unique.createItem(collectionId, to, createData as any);1472 } else {1473 const data = api.createType('UpDataStructsCreateItemData', {NFT: {properties: props}});1474 tx = api.tx.unique.createItem(collectionId, to, data as UpDataStructsCreateItemData);1475 }14761477 const events = await submitTransactionAsync(sender, tx);1478 const result = getCreateItemResult(events);14791480 const itemCountAfter = await getLastTokenId(api, collectionId);1481 const itemBalanceAfter = await getBalance(api, collectionId, to, newItemId);14821483 if (createMode === 'NFT') {1484 expect(await api.rpc.unique.tokenProperties(collectionId, result.itemId)).not.to.be.empty;1485 }14861487 1488 1489 expect(result.success).to.be.true;1490 if (createMode === 'Fungible') {1491 expect(itemBalanceAfter - itemBalanceBefore).to.be.equal(10n);1492 } else {1493 expect(itemCountAfter).to.be.equal(itemCountBefore + 1);1494 }1495 expect(collectionId).to.be.equal(result.collectionId);1496 expect(itemCountAfter.toString()).to.be.equal(result.itemId.toString());1497 expect(to).to.be.deep.equal(result.recipient);1498 newItemId = result.itemId;1499 });1500 return newItemId;1501}15021503export async function createItemWithPropsExpectFailure(sender: IKeyringPair, collectionId: number, createMode: string, props: Array<Property>, owner: CrossAccountId | string = sender.address) {1504 await usingApi(async (api) => {15051506 let tx;1507 if (createMode === 'NFT') {1508 const data = api.createType('UpDataStructsCreateItemData', {NFT: {properties: props}}) as UpDataStructsCreateItemData;1509 tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), data);1510 } else {1511 tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), createMode);1512 }151315141515 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1516 if(events.message && events.message.toString().indexOf('1002: Verification Error') > -1) return;1517 const result = getCreateItemResult(events);15181519 expect(result.success).to.be.false;1520 });1521}15221523export async function createItemExpectSuccess(sender: IKeyringPair, collectionId: number, createMode: string, owner: CrossAccountId | string = sender.address) {1524 let newItemId = 0;1525 await usingApi(async (api) => {1526 const to = normalizeAccountId(owner);1527 const itemCountBefore = await getLastTokenId(api, collectionId);1528 const itemBalanceBefore = await getBalance(api, collectionId, to, newItemId);15291530 let tx;1531 if (createMode === 'Fungible') {1532 const createData = {fungible: {value: 10}};1533 tx = api.tx.unique.createItem(collectionId, to, createData as any);1534 } else if (createMode === 'ReFungible') {1535 const createData = {refungible: {pieces: 100}};1536 tx = api.tx.unique.createItem(collectionId, to, createData as any);1537 } else {1538 const createData = {nft: {}};1539 tx = api.tx.unique.createItem(collectionId, to, createData as any);1540 }15411542 const events = await executeTransaction(api, sender, tx);1543 const result = getCreateItemResult(events);15441545 const itemCountAfter = await getLastTokenId(api, collectionId);1546 const itemBalanceAfter = await getBalance(api, collectionId, to, newItemId);15471548 1549 1550 expect(result.success).to.be.true;1551 if (createMode === 'Fungible') {1552 expect(itemBalanceAfter - itemBalanceBefore).to.be.equal(10n);1553 } else {1554 expect(itemCountAfter).to.be.equal(itemCountBefore + 1);1555 }1556 expect(collectionId).to.be.equal(result.collectionId);1557 expect(itemCountAfter.toString()).to.be.equal(result.itemId.toString());1558 expect(to).to.be.deep.equal(result.recipient);1559 newItemId = result.itemId;1560 });1561 return newItemId;1562}15631564export async function createRefungibleToken(api: ApiPromise, sender: IKeyringPair, collectionId: number, amount: bigint, owner: CrossAccountId | IKeyringPair | string = sender.address) : Promise<CreateItemResult> {1565 const createData = {refungible: {pieces: amount}};1566 const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), createData as any);15671568 const events = await submitTransactionAsync(sender, tx);1569 return getCreateItemResult(events);1570}15711572export async function createItemExpectFailure(sender: IKeyringPair, collectionId: number, createMode: string, owner: CrossAccountId | string = sender.address) {1573 await usingApi(async (api) => {1574 const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), createMode);15751576 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1577 const result = getCreateItemResult(events);15781579 expect(result.success).to.be.false;1580 });1581}15821583export async function setPublicAccessModeExpectSuccess(1584 sender: IKeyringPair, collectionId: number,1585 accessMode: 'Normal' | 'AllowList',1586) {1587 await usingApi(async (api) => {15881589 1590 const tx = api.tx.unique.setCollectionPermissions(collectionId, {access: accessMode});1591 const events = await submitTransactionAsync(sender, tx);1592 const result = getGenericResult(events);15931594 1595 const collection = await queryCollectionExpectSuccess(api, collectionId);15961597 1598 1599 expect(result.success).to.be.true;1600 expect(collection.permissions.access.toHuman()).to.be.equal(accessMode);1601 });1602}16031604export async function setPublicAccessModeExpectFail(1605 sender: IKeyringPair, collectionId: number,1606 accessMode: 'Normal' | 'AllowList',1607) {1608 await usingApi(async (api) => {16091610 1611 const tx = api.tx.unique.setCollectionPermissions(collectionId, {access: accessMode});1612 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1613 const result = getGenericResult(events);16141615 1616 1617 expect(result.success).to.be.false;1618 });1619}16201621export async function enableAllowListExpectSuccess(sender: IKeyringPair, collectionId: number) {1622 await setPublicAccessModeExpectSuccess(sender, collectionId, 'AllowList');1623}16241625export async function enableAllowListExpectFail(sender: IKeyringPair, collectionId: number) {1626 await setPublicAccessModeExpectFail(sender, collectionId, 'AllowList');1627}16281629export async function disableAllowListExpectSuccess(sender: IKeyringPair, collectionId: number) {1630 await setPublicAccessModeExpectSuccess(sender, collectionId, 'Normal');1631}16321633export async function setMintPermissionExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {1634 await usingApi(async (api) => {16351636 1637 const tx = api.tx.unique.setCollectionPermissions(collectionId, {mintMode: enabled});1638 const events = await submitTransactionAsync(sender, tx);1639 const result = getGenericResult(events);1640 expect(result.success).to.be.true;16411642 1643 const collection = await queryCollectionExpectSuccess(api, collectionId);16441645 expect(collection.permissions.mintMode.toHuman()).to.be.equal(enabled);1646 });1647}16481649export async function enablePublicMintingExpectSuccess(sender: IKeyringPair, collectionId: number) {1650 await setMintPermissionExpectSuccess(sender, collectionId, true);1651}16521653export async function setMintPermissionExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {1654 await usingApi(async (api) => {1655 1656 const tx = api.tx.unique.setCollectionPermissions(collectionId, {mintMode: enabled});1657 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1658 const result = getCreateCollectionResult(events);1659 1660 expect(result.success).to.be.false;1661 });1662}16631664export async function setChainLimitsExpectFailure(sender: IKeyringPair, limits: IChainLimits) {1665 await usingApi(async (api) => {1666 1667 const tx = api.tx.unique.setChainLimits(limits);1668 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1669 const result = getCreateCollectionResult(events);1670 1671 expect(result.success).to.be.false;1672 });1673}16741675export async function isAllowlisted(api: ApiPromise, collectionId: number, address: string | CrossAccountId) {1676 return (await api.rpc.unique.allowed(collectionId, normalizeAccountId(address))).toJSON();1677}16781679export async function addToAllowListExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId | CrossAccountId) {1680 await usingApi(async (api) => {1681 expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.false;16821683 1684 const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1685 const events = await submitTransactionAsync(sender, tx);1686 const result = getGenericResult(events);1687 expect(result.success).to.be.true;16881689 expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;1690 });1691}16921693export async function addToAllowListAgainExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId) {1694 await usingApi(async (api) => {16951696 expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;16971698 1699 const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1700 const events = await submitTransactionAsync(sender, tx);1701 const result = getGenericResult(events);1702 expect(result.success).to.be.true;17031704 expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;1705 });1706}17071708export async function addToAllowListExpectFail(sender: IKeyringPair, collectionId: number, address: string | AccountId) {1709 await usingApi(async (api) => {17101711 1712 const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1713 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1714 const result = getGenericResult(events);17151716 1717 1718 expect(result.success).to.be.false;1719 });1720}17211722export async function removeFromAllowListExpectSuccess(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1723 await usingApi(async (api) => {1724 1725 const tx = api.tx.unique.removeFromAllowList(collectionId, normalizeAccountId(address));1726 const events = await submitTransactionAsync(sender, tx);1727 const result = getGenericResult(events);17281729 1730 1731 expect(result.success).to.be.true;1732 });1733}17341735export async function removeFromAllowListExpectFailure(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1736 await usingApi(async (api) => {1737 1738 const tx = api.tx.unique.removeFromAllowList(collectionId, normalizeAccountId(address));1739 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1740 const result = getGenericResult(events);17411742 1743 1744 expect(result.success).to.be.false;1745 });1746}17471748export const getDetailedCollectionInfo = async (api: ApiPromise, collectionId: number)1749 : Promise<UpDataStructsRpcCollection | null> => {1750 return (await api.rpc.unique.collectionById(collectionId)).unwrapOr(null);1751};17521753export const getCreatedCollectionCount = async (api: ApiPromise): Promise<number> => {1754 1755 return (await api.rpc.unique.collectionStats()).created.toNumber();1756};17571758export async function queryCollectionExpectSuccess(api: ApiPromise, collectionId: number): Promise<UpDataStructsRpcCollection> {1759 return (await api.rpc.unique.collectionById(collectionId)).unwrap();1760}17611762export const describe_xcm = (1763 process.env.RUN_XCM_TESTS1764 ? describe1765 : describe.skip1766);17671768export async function waitNewBlocks(blocksCount = 1): Promise<void> {1769 await usingApi(async (api) => {1770 const promise = new Promise<void>(async (resolve) => {1771 const unsubscribe = await api.rpc.chain.subscribeNewHeads(() => {1772 if (blocksCount > 0) {1773 blocksCount--;1774 } else {1775 unsubscribe();1776 resolve();1777 }1778 });1779 });1780 return promise;1781 });1782}17831784export async function waitEvent(1785 api: ApiPromise,1786 maxBlocksToWait: number,1787 eventSection: string,1788 eventMethod: string,1789): Promise<EventRecord | null> {17901791 const promise = new Promise<EventRecord | null>(async (resolve) => {1792 const unsubscribe = await api.rpc.chain.subscribeNewHeads(async header => {1793 const blockNumber = header.number.toHuman();1794 const blockHash = header.hash;1795 const eventIdStr = `${eventSection}.${eventMethod}`;1796 const waitLimitStr = `wait blocks remaining: ${maxBlocksToWait}`;17971798 console.log(`[Block #${blockNumber}] Waiting for event \`${eventIdStr}\` (${waitLimitStr})`);17991800 const apiAt = await api.at(blockHash);1801 const eventRecords = await apiAt.query.system.events();18021803 const neededEvent = eventRecords.find(r => {1804 return r.event.section == eventSection && r.event.method == eventMethod;1805 });18061807 if (neededEvent) {1808 console.log(`Event \`${eventIdStr}\` is found`);18091810 unsubscribe();1811 resolve(neededEvent);1812 } else if (maxBlocksToWait > 0) {1813 maxBlocksToWait--;1814 } else {1815 console.log(`Event \`${eventIdStr}\` is NOT found`);18161817 unsubscribe();1818 resolve(null);1819 }1820 });1821 });1822 return promise;1823}18241825export async function repartitionRFT(1826 api: ApiPromise,1827 collectionId: number,1828 sender: IKeyringPair,1829 tokenId: number,1830 amount: bigint,1831): Promise<boolean> {1832 const tx = api.tx.unique.repartition(collectionId, tokenId, amount);1833 const events = await submitTransactionAsync(sender, tx);1834 const result = getGenericResult(events);18351836 return result.success;1837}18381839export async function itApi(name: string, cb: (apis: { api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair }) => any, opts: { only?: boolean, skip?: boolean } = {}) {1840 let i: any = it;1841 if (opts.only) i = i.only;1842 else if (opts.skip) i = i.skip;1843 i(name, async () => {1844 await usingApi(async (api, privateKeyWrapper) => {1845 await cb({api, privateKeyWrapper});1846 });1847 });1848}18491850itApi.only = (name: string, cb: (apis: { api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair }) => any) => itApi(name, cb, {only: true});1851itApi.skip = (name: string, cb: (apis: { api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair }) => any) => itApi(name, cb, {skip: true});18521853let accountSeed = 10000;18541855const keyringEth = new Keyring({type: 'ethereum'});1856const keyringEd25519 = new Keyring({type: 'ed25519'});1857const keyringSr25519 = new Keyring({type: 'sr25519'});18581859export function generateKeyringPair(type: 'ethereum' | 'sr25519' | 'ed25519' = 'sr25519') {1860 const privateKey = `0xDEADBEEF${(accountSeed++).toString(16).padStart(56, '0')}`;1861 if (type == 'sr25519') {1862 return keyringSr25519.addFromUri(privateKey);1863 } else if (type == 'ed25519') {1864 return keyringEd25519.addFromUri(privateKey);1865 }1866 return keyringEth.addFromUri(privateKey);1867}