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.' + '0'.repeat(Math.abs(dotPos)) + 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 1119 1120 const siblingPrefix = '0x7369626c';11211122 const encodedParaId = api.createType('u32', paraid).toHex(true).substring(2);1123 const suffix = '000000000000000000000000000000000000000000000000';11241125 return siblingPrefix + encodedParaId + suffix;1126 });1127}11281129export async function transferBalanceTo(api: ApiPromise, source: IKeyringPair, target: string, amount = 1000n * UNIQUE) {1130 const tx = api.tx.balances.transfer(target, amount);1131 const events = await submitTransactionAsync(source, tx);1132 const result = getGenericResult(events);1133 expect(result.success).to.be.true;1134}11351136export async function1137scheduleExpectSuccess(1138 operationTx: any,1139 sender: IKeyringPair,1140 blockSchedule: number,1141 scheduledId: string,1142 period = 1,1143 repetitions = 1,1144) {1145 await usingApi(async (api: ApiPromise) => {1146 const blockNumber: number | undefined = await getBlockNumber(api);1147 const expectedBlockNumber = blockNumber + blockSchedule;11481149 expect(blockNumber).to.be.greaterThan(0);1150 const scheduleTx = api.tx.scheduler.scheduleNamed( 1151 scheduledId,1152 expectedBlockNumber, 1153 repetitions > 1 ? [period, repetitions] : null, 1154 0, 1155 {Value: operationTx as any},1156 );11571158 const events = await submitTransactionAsync(sender, scheduleTx);1159 expect(getGenericResult(events).success).to.be.true;1160 });1161}11621163export async function1164scheduleExpectFailure(1165 operationTx: any,1166 sender: IKeyringPair,1167 blockSchedule: number,1168 scheduledId: string,1169 period = 1,1170 repetitions = 1,1171) {1172 await usingApi(async (api: ApiPromise) => {1173 const blockNumber: number | undefined = await getBlockNumber(api);1174 const expectedBlockNumber = blockNumber + blockSchedule;11751176 expect(blockNumber).to.be.greaterThan(0);1177 const scheduleTx = api.tx.scheduler.scheduleNamed( 1178 scheduledId,1179 expectedBlockNumber, 1180 repetitions <= 1 ? null : [period, repetitions], 1181 0, 1182 {Value: operationTx as any},1183 );11841185 1186 await expect(submitTransactionExpectFailAsync(sender, scheduleTx)).to.be.rejected;1187 1188 });1189}11901191export async function1192scheduleTransferAndWaitExpectSuccess(1193 collectionId: number,1194 tokenId: number,1195 sender: IKeyringPair,1196 recipient: IKeyringPair,1197 value: number | bigint = 1,1198 blockSchedule: number,1199 scheduledId: string,1200) {1201 await usingApi(async (api: ApiPromise) => {1202 await scheduleTransferExpectSuccess(collectionId, tokenId, sender, recipient, value, blockSchedule, scheduledId);12031204 const recipientBalanceBefore = (await api.query.system.account(recipient.address)).data.free.toBigInt();12051206 1207 await waitNewBlocks(blockSchedule + 1);12081209 const recipientBalanceAfter = (await api.query.system.account(recipient.address)).data.free.toBigInt();12101211 expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(recipient.address));1212 expect(recipientBalanceAfter).to.be.equal(recipientBalanceBefore);1213 });1214}12151216export async function1217scheduleTransferExpectSuccess(1218 collectionId: number,1219 tokenId: number,1220 sender: IKeyringPair,1221 recipient: IKeyringPair,1222 value: number | bigint = 1,1223 blockSchedule: number,1224 scheduledId: string,1225) {1226 await usingApi(async (api: ApiPromise) => {1227 const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient.address), collectionId, tokenId, value);12281229 await scheduleExpectSuccess(transferTx, sender, blockSchedule, scheduledId);12301231 expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(sender.address));1232 });1233}12341235export async function1236scheduleTransferFundsPeriodicExpectSuccess(1237 amount: bigint,1238 sender: IKeyringPair,1239 recipient: IKeyringPair,1240 blockSchedule: number,1241 scheduledId: string,1242 period: number,1243 repetitions: number,1244) {1245 await usingApi(async (api: ApiPromise) => {1246 const transferTx = api.tx.balances.transfer(recipient.address, amount);12471248 const balanceBefore = await getFreeBalance(recipient);1249 1250 await scheduleExpectSuccess(transferTx, sender, blockSchedule, scheduledId, period, repetitions);12511252 expect(await getFreeBalance(recipient)).to.be.equal(balanceBefore);1253 });1254}12551256export async function1257transfer(1258 api: ApiPromise,1259 collectionId: number,1260 tokenId: number,1261 sender: IKeyringPair,1262 recipient: IKeyringPair | CrossAccountId,1263 value: number | bigint,1264) : Promise<boolean> {1265 const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient), collectionId, tokenId, value);1266 const events = await executeTransaction(api, sender, transferTx);1267 return getGenericResult(events).success;1268}12691270export async function1271transferExpectSuccess(1272 collectionId: number,1273 tokenId: number,1274 sender: IKeyringPair,1275 recipient: IKeyringPair | CrossAccountId,1276 value: number | bigint = 1,1277 type = 'NFT',1278) {1279 await usingApi(async (api: ApiPromise) => {1280 const from = normalizeAccountId(sender);1281 const to = normalizeAccountId(recipient);12821283 let balanceBefore = 0n;1284 if (type === 'Fungible' || type === 'ReFungible') {1285 balanceBefore = await getBalance(api, collectionId, to, tokenId);1286 }12871288 const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient), collectionId, tokenId, value);1289 const events = await executeTransaction(api, sender, transferTx);1290 const result = getTransferResult(api, events);12911292 expect(result.collectionId).to.be.equal(collectionId);1293 expect(result.itemId).to.be.equal(tokenId);1294 expect(result.sender).to.be.deep.equal(normalizeAccountId(sender.address));1295 expect(result.recipient).to.be.deep.equal(to);1296 expect(result.value).to.be.equal(BigInt(value));12971298 if (type === 'NFT') {1299 expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(to);1300 }1301 if (type === 'Fungible' || type === 'ReFungible') {1302 const balanceAfter = await getBalance(api, collectionId, to, tokenId);1303 if (JSON.stringify(to) !== JSON.stringify(from)) {1304 expect(balanceAfter - balanceBefore).to.be.equal(BigInt(value));1305 } else {1306 expect(balanceAfter).to.be.equal(balanceBefore);1307 }1308 }1309 });1310}13111312export async function1313transferExpectFailure(1314 collectionId: number,1315 tokenId: number,1316 sender: IKeyringPair,1317 recipient: IKeyringPair | CrossAccountId,1318 value: number | bigint = 1,1319) {1320 await usingApi(async (api: ApiPromise) => {1321 const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient), collectionId, tokenId, value);1322 const events = await expect(submitTransactionExpectFailAsync(sender, transferTx)).to.be.rejected;1323 const result = getGenericResult(events);1324 1325 1326 1327 expect(result.success).to.be.false;1328 1329 });1330}13311332export async function1333approveExpectFail(1334 collectionId: number,1335 tokenId: number, owner: IKeyringPair, approved: IKeyringPair, amount: number | bigint = 1,1336) {1337 await usingApi(async (api: ApiPromise) => {1338 const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved.address), collectionId, tokenId, amount);1339 const events = await expect(submitTransactionExpectFailAsync(owner, approveUniqueTx)).to.be.rejected;1340 const result = getCreateCollectionResult(events);1341 1342 expect(result.success).to.be.false;1343 });1344}13451346export async function getBalance(1347 api: ApiPromise,1348 collectionId: number,1349 owner: string | CrossAccountId | IKeyringPair,1350 token: number,1351): Promise<bigint> {1352 return (await api.rpc.unique.balance(collectionId, normalizeAccountId(owner), token)).toBigInt();1353}1354export async function getTokenOwner(1355 api: ApiPromise,1356 collectionId: number,1357 token: number,1358): Promise<CrossAccountId> {1359 const owner = (await api.rpc.unique.tokenOwner(collectionId, token)).toJSON() as any;1360 if (owner == null) throw new Error('owner == null');1361 return normalizeAccountId(owner);1362}1363export async function getTopmostTokenOwner(1364 api: ApiPromise,1365 collectionId: number,1366 token: number,1367): Promise<CrossAccountId> {1368 const owner = (await api.rpc.unique.topmostTokenOwner(collectionId, token)).toJSON() as any;1369 if (owner == null) throw new Error('owner == null');1370 return normalizeAccountId(owner);1371}1372export async function getTokenChildren(1373 api: ApiPromise,1374 collectionId: number,1375 tokenId: number,1376): Promise<UpDataStructsTokenChild[]> {1377 return (await api.rpc.unique.tokenChildren(collectionId, tokenId)).toJSON() as any;1378}1379export async function isTokenExists(1380 api: ApiPromise,1381 collectionId: number,1382 token: number,1383): Promise<boolean> {1384 return (await api.rpc.unique.tokenExists(collectionId, token)).toJSON();1385}1386export async function getLastTokenId(1387 api: ApiPromise,1388 collectionId: number,1389): Promise<number> {1390 return (await api.rpc.unique.lastTokenId(collectionId)).toJSON();1391}1392export async function getAdminList(1393 api: ApiPromise,1394 collectionId: number,1395): Promise<string[]> {1396 return (await api.rpc.unique.adminlist(collectionId)).toHuman() as any;1397}1398export async function getTokenProperties(1399 api: ApiPromise,1400 collectionId: number,1401 tokenId: number,1402 propertyKeys: string[],1403): Promise<UpDataStructsProperty[]> {1404 return (await api.rpc.unique.tokenProperties(collectionId, tokenId, propertyKeys)).toHuman() as any;1405}14061407export async function createFungibleItemExpectSuccess(1408 sender: IKeyringPair,1409 collectionId: number,1410 data: CreateFungibleData,1411 owner: CrossAccountId | string = sender.address,1412) {1413 return await usingApi(async (api) => {1414 const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), {Fungible: data});14151416 const events = await submitTransactionAsync(sender, tx);1417 const result = getCreateItemResult(events);14181419 expect(result.success).to.be.true;1420 return result.itemId;1421 });1422}14231424export async function createMultipleItemsExpectSuccess(sender: IKeyringPair, collectionId: number, itemsData: any, owner: CrossAccountId | string = sender.address) {1425 await usingApi(async (api) => {1426 const to = normalizeAccountId(owner);1427 const tx = api.tx.unique.createMultipleItems(collectionId, to, itemsData);14281429 const events = await submitTransactionAsync(sender, tx);1430 expect(getGenericResult(events).success).to.be.true;1431 });1432}14331434export async function createMultipleItemsWithPropsExpectSuccess(sender: IKeyringPair, collectionId: number, itemsData: any, owner: CrossAccountId | string = sender.address) {1435 await usingApi(async (api) => {1436 const to = normalizeAccountId(owner);1437 const tx = api.tx.unique.createMultipleItems(collectionId, to, itemsData);14381439 const events = await submitTransactionAsync(sender, tx);1440 const result = getCreateItemsResult(events);14411442 for (const res of result) {1443 expect(await api.rpc.unique.tokenProperties(collectionId, res.itemId)).not.to.be.empty;1444 }1445 });1446}14471448export async function createMultipleItemsExWithPropsExpectSuccess(sender: IKeyringPair, collectionId: number, itemsData: any) {1449 await usingApi(async (api) => {1450 const tx = api.tx.unique.createMultipleItemsEx(collectionId, itemsData);14511452 const events = await submitTransactionAsync(sender, tx);1453 const result = getCreateItemsResult(events);14541455 for (const res of result) {1456 expect(await api.rpc.unique.tokenProperties(collectionId, res.itemId)).not.to.be.empty;1457 }1458 });1459}14601461export async function createItemWithPropsExpectSuccess(sender: IKeyringPair, collectionId: number, createMode: string, props: Array<Property>, owner: CrossAccountId | string = sender.address) {1462 let newItemId = 0;1463 await usingApi(async (api) => {1464 const to = normalizeAccountId(owner);1465 const itemCountBefore = await getLastTokenId(api, collectionId);1466 const itemBalanceBefore = await getBalance(api, collectionId, to, newItemId);14671468 let tx;1469 if (createMode === 'Fungible') {1470 const createData = {fungible: {value: 10}};1471 tx = api.tx.unique.createItem(collectionId, to, createData as any);1472 } else if (createMode === 'ReFungible') {1473 const createData = {refungible: {pieces: 100}};1474 tx = api.tx.unique.createItem(collectionId, to, createData as any);1475 } else {1476 const data = api.createType('UpDataStructsCreateItemData', {NFT: {properties: props}});1477 tx = api.tx.unique.createItem(collectionId, to, data as UpDataStructsCreateItemData);1478 }14791480 const events = await submitTransactionAsync(sender, tx);1481 const result = getCreateItemResult(events);14821483 const itemCountAfter = await getLastTokenId(api, collectionId);1484 const itemBalanceAfter = await getBalance(api, collectionId, to, newItemId);14851486 if (createMode === 'NFT') {1487 expect(await api.rpc.unique.tokenProperties(collectionId, result.itemId)).not.to.be.empty;1488 }14891490 1491 1492 expect(result.success).to.be.true;1493 if (createMode === 'Fungible') {1494 expect(itemBalanceAfter - itemBalanceBefore).to.be.equal(10n);1495 } else {1496 expect(itemCountAfter).to.be.equal(itemCountBefore + 1);1497 }1498 expect(collectionId).to.be.equal(result.collectionId);1499 expect(itemCountAfter.toString()).to.be.equal(result.itemId.toString());1500 expect(to).to.be.deep.equal(result.recipient);1501 newItemId = result.itemId;1502 });1503 return newItemId;1504}15051506export async function createItemWithPropsExpectFailure(sender: IKeyringPair, collectionId: number, createMode: string, props: Array<Property>, owner: CrossAccountId | string = sender.address) {1507 await usingApi(async (api) => {15081509 let tx;1510 if (createMode === 'NFT') {1511 const data = api.createType('UpDataStructsCreateItemData', {NFT: {properties: props}}) as UpDataStructsCreateItemData;1512 tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), data);1513 } else {1514 tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), createMode);1515 }151615171518 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1519 if(events.message && events.message.toString().indexOf('1002: Verification Error') > -1) return;1520 const result = getCreateItemResult(events);15211522 expect(result.success).to.be.false;1523 });1524}15251526export async function createItemExpectSuccess(sender: IKeyringPair, collectionId: number, createMode: string, owner: CrossAccountId | string = sender.address) {1527 let newItemId = 0;1528 await usingApi(async (api) => {1529 const to = normalizeAccountId(owner);1530 const itemCountBefore = await getLastTokenId(api, collectionId);1531 const itemBalanceBefore = await getBalance(api, collectionId, to, newItemId);15321533 let tx;1534 if (createMode === 'Fungible') {1535 const createData = {fungible: {value: 10}};1536 tx = api.tx.unique.createItem(collectionId, to, createData as any);1537 } else if (createMode === 'ReFungible') {1538 const createData = {refungible: {pieces: 100}};1539 tx = api.tx.unique.createItem(collectionId, to, createData as any);1540 } else {1541 const createData = {nft: {}};1542 tx = api.tx.unique.createItem(collectionId, to, createData as any);1543 }15441545 const events = await executeTransaction(api, sender, tx);1546 const result = getCreateItemResult(events);15471548 const itemCountAfter = await getLastTokenId(api, collectionId);1549 const itemBalanceAfter = await getBalance(api, collectionId, to, newItemId);15501551 1552 1553 expect(result.success).to.be.true;1554 if (createMode === 'Fungible') {1555 expect(itemBalanceAfter - itemBalanceBefore).to.be.equal(10n);1556 } else {1557 expect(itemCountAfter).to.be.equal(itemCountBefore + 1);1558 }1559 expect(collectionId).to.be.equal(result.collectionId);1560 expect(itemCountAfter.toString()).to.be.equal(result.itemId.toString());1561 expect(to).to.be.deep.equal(result.recipient);1562 newItemId = result.itemId;1563 });1564 return newItemId;1565}15661567export async function createRefungibleToken(api: ApiPromise, sender: IKeyringPair, collectionId: number, amount: bigint, owner: CrossAccountId | IKeyringPair | string = sender.address) : Promise<CreateItemResult> {1568 const createData = {refungible: {pieces: amount}};1569 const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), createData as any);15701571 const events = await submitTransactionAsync(sender, tx);1572 return getCreateItemResult(events);1573}15741575export async function createItemExpectFailure(sender: IKeyringPair, collectionId: number, createMode: string, owner: CrossAccountId | string = sender.address) {1576 await usingApi(async (api) => {1577 const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), createMode);15781579 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1580 const result = getCreateItemResult(events);15811582 expect(result.success).to.be.false;1583 });1584}15851586export async function setPublicAccessModeExpectSuccess(1587 sender: IKeyringPair, collectionId: number,1588 accessMode: 'Normal' | 'AllowList',1589) {1590 await usingApi(async (api) => {15911592 1593 const tx = api.tx.unique.setCollectionPermissions(collectionId, {access: accessMode});1594 const events = await submitTransactionAsync(sender, tx);1595 const result = getGenericResult(events);15961597 1598 const collection = await queryCollectionExpectSuccess(api, collectionId);15991600 1601 1602 expect(result.success).to.be.true;1603 expect(collection.permissions.access.toHuman()).to.be.equal(accessMode);1604 });1605}16061607export async function setPublicAccessModeExpectFail(1608 sender: IKeyringPair, collectionId: number,1609 accessMode: 'Normal' | 'AllowList',1610) {1611 await usingApi(async (api) => {16121613 1614 const tx = api.tx.unique.setCollectionPermissions(collectionId, {access: accessMode});1615 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1616 const result = getGenericResult(events);16171618 1619 1620 expect(result.success).to.be.false;1621 });1622}16231624export async function enableAllowListExpectSuccess(sender: IKeyringPair, collectionId: number) {1625 await setPublicAccessModeExpectSuccess(sender, collectionId, 'AllowList');1626}16271628export async function enableAllowListExpectFail(sender: IKeyringPair, collectionId: number) {1629 await setPublicAccessModeExpectFail(sender, collectionId, 'AllowList');1630}16311632export async function disableAllowListExpectSuccess(sender: IKeyringPair, collectionId: number) {1633 await setPublicAccessModeExpectSuccess(sender, collectionId, 'Normal');1634}16351636export async function setMintPermissionExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {1637 await usingApi(async (api) => {16381639 1640 const tx = api.tx.unique.setCollectionPermissions(collectionId, {mintMode: enabled});1641 const events = await submitTransactionAsync(sender, tx);1642 const result = getGenericResult(events);1643 expect(result.success).to.be.true;16441645 1646 const collection = await queryCollectionExpectSuccess(api, collectionId);16471648 expect(collection.permissions.mintMode.toHuman()).to.be.equal(enabled);1649 });1650}16511652export async function enablePublicMintingExpectSuccess(sender: IKeyringPair, collectionId: number) {1653 await setMintPermissionExpectSuccess(sender, collectionId, true);1654}16551656export async function setMintPermissionExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {1657 await usingApi(async (api) => {1658 1659 const tx = api.tx.unique.setCollectionPermissions(collectionId, {mintMode: enabled});1660 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1661 const result = getCreateCollectionResult(events);1662 1663 expect(result.success).to.be.false;1664 });1665}16661667export async function setChainLimitsExpectFailure(sender: IKeyringPair, limits: IChainLimits) {1668 await usingApi(async (api) => {1669 1670 const tx = api.tx.unique.setChainLimits(limits);1671 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1672 const result = getCreateCollectionResult(events);1673 1674 expect(result.success).to.be.false;1675 });1676}16771678export async function isAllowlisted(api: ApiPromise, collectionId: number, address: string | CrossAccountId) {1679 return (await api.rpc.unique.allowed(collectionId, normalizeAccountId(address))).toJSON();1680}16811682export async function addToAllowListExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId | CrossAccountId) {1683 await usingApi(async (api) => {1684 expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.false;16851686 1687 const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1688 const events = await submitTransactionAsync(sender, tx);1689 const result = getGenericResult(events);1690 expect(result.success).to.be.true;16911692 expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;1693 });1694}16951696export async function addToAllowListAgainExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId) {1697 await usingApi(async (api) => {16981699 expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;17001701 1702 const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1703 const events = await submitTransactionAsync(sender, tx);1704 const result = getGenericResult(events);1705 expect(result.success).to.be.true;17061707 expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;1708 });1709}17101711export async function addToAllowListExpectFail(sender: IKeyringPair, collectionId: number, address: string | AccountId) {1712 await usingApi(async (api) => {17131714 1715 const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1716 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1717 const result = getGenericResult(events);17181719 1720 1721 expect(result.success).to.be.false;1722 });1723}17241725export async function removeFromAllowListExpectSuccess(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1726 await usingApi(async (api) => {1727 1728 const tx = api.tx.unique.removeFromAllowList(collectionId, normalizeAccountId(address));1729 const events = await submitTransactionAsync(sender, tx);1730 const result = getGenericResult(events);17311732 1733 1734 expect(result.success).to.be.true;1735 });1736}17371738export async function removeFromAllowListExpectFailure(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1739 await usingApi(async (api) => {1740 1741 const tx = api.tx.unique.removeFromAllowList(collectionId, normalizeAccountId(address));1742 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1743 const result = getGenericResult(events);17441745 1746 1747 expect(result.success).to.be.false;1748 });1749}17501751export const getDetailedCollectionInfo = async (api: ApiPromise, collectionId: number)1752 : Promise<UpDataStructsRpcCollection | null> => {1753 return (await api.rpc.unique.collectionById(collectionId)).unwrapOr(null);1754};17551756export const getCreatedCollectionCount = async (api: ApiPromise): Promise<number> => {1757 1758 return (await api.rpc.unique.collectionStats()).created.toNumber();1759};17601761export async function queryCollectionExpectSuccess(api: ApiPromise, collectionId: number): Promise<UpDataStructsRpcCollection> {1762 return (await api.rpc.unique.collectionById(collectionId)).unwrap();1763}17641765export const describe_xcm = (1766 process.env.RUN_XCM_TESTS1767 ? describe1768 : describe.skip1769);17701771export async function waitNewBlocks(blocksCount = 1): Promise<void> {1772 await usingApi(async (api) => {1773 const promise = new Promise<void>(async (resolve) => {1774 const unsubscribe = await api.rpc.chain.subscribeNewHeads(() => {1775 if (blocksCount > 0) {1776 blocksCount--;1777 } else {1778 unsubscribe();1779 resolve();1780 }1781 });1782 });1783 return promise;1784 });1785}17861787export async function waitEvent(1788 api: ApiPromise,1789 maxBlocksToWait: number,1790 eventSection: string,1791 eventMethod: string,1792): Promise<EventRecord | null> {17931794 const promise = new Promise<EventRecord | null>(async (resolve) => {1795 const unsubscribe = await api.rpc.chain.subscribeNewHeads(async header => {1796 const blockNumber = header.number.toHuman();1797 const blockHash = header.hash;1798 const eventIdStr = `${eventSection}.${eventMethod}`;1799 const waitLimitStr = `wait blocks remaining: ${maxBlocksToWait}`;18001801 console.log(`[Block #${blockNumber}] Waiting for event \`${eventIdStr}\` (${waitLimitStr})`);18021803 const apiAt = await api.at(blockHash);1804 const eventRecords = await apiAt.query.system.events();18051806 const neededEvent = eventRecords.find(r => {1807 return r.event.section == eventSection && r.event.method == eventMethod;1808 });18091810 if (neededEvent) {1811 unsubscribe();1812 resolve(neededEvent);1813 } else if (maxBlocksToWait > 0) {1814 maxBlocksToWait--;1815 } else {1816 console.log(`Event \`${eventIdStr}\` is NOT found`);18171818 unsubscribe();1819 resolve(null);1820 }1821 });1822 });1823 return promise;1824}18251826export async function repartitionRFT(1827 api: ApiPromise,1828 collectionId: number,1829 sender: IKeyringPair,1830 tokenId: number,1831 amount: bigint,1832): Promise<boolean> {1833 const tx = api.tx.unique.repartition(collectionId, tokenId, amount);1834 const events = await submitTransactionAsync(sender, tx);1835 const result = getGenericResult(events);18361837 return result.success;1838}18391840export async function itApi(name: string, cb: (apis: { api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair }) => any, opts: { only?: boolean, skip?: boolean } = {}) {1841 let i: any = it;1842 if (opts.only) i = i.only;1843 else if (opts.skip) i = i.skip;1844 i(name, async () => {1845 await usingApi(async (api, privateKeyWrapper) => {1846 await cb({api, privateKeyWrapper});1847 });1848 });1849}18501851itApi.only = (name: string, cb: (apis: { api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair }) => any) => itApi(name, cb, {only: true});1852itApi.skip = (name: string, cb: (apis: { api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair }) => any) => itApi(name, cb, {skip: true});18531854let accountSeed = 10000;18551856export function generateKeyringPair(keyring: Keyring) {1857 const privateKey = `0xDEADBEEF${(accountSeed++).toString(16).padStart(56, '0')}`;1858 return keyring.addFromUri(privateKey);1859}