1234567891011121314151617import '../interfaces/augment-api-rpc';18import '../interfaces/augment-api-query';19import {ApiPromise, Keyring} from '@polkadot/api';20import type {AccountId, EventRecord, Event, BlockNumber} 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 {AnyNumber} from '@polkadot/types-codec/types';25import BN from 'bn.js';26import chai from 'chai';27import chaiAsPromised from 'chai-as-promised';28import {default as usingApi, executeTransaction, submitTransactionAsync, submitTransactionExpectFailAsync} from '../substrate/substrate-api';29import {hexToStr, strToUTF16, utf16ToStr} from './util';30import {UpDataStructsRpcCollection, UpDataStructsCreateItemData, UpDataStructsProperty} from '@polkadot/types/lookup';31import {UpDataStructsTokenChild} from '../interfaces';32import {Context} from 'mocha';3334chai.use(chaiAsPromised);35const expect = chai.expect;3637export type CrossAccountId = {38 Substrate: string,39} | {40 Ethereum: string,41};424344export enum Pallets {45 Inflation = 'inflation',46 RmrkCore = 'rmrkcore',47 RmrkEquip = 'rmrkequip',48 ReFungible = 'refungible',49 Fungible = 'fungible',50 NFT = 'nonfungible',51 Scheduler = 'scheduler',52 AppPromotion = 'apppromotion',53}5455export async function isUnique(): Promise<boolean> {56 return usingApi(async api => {57 const chain = await api.rpc.system.chain();5859 return chain.eq('UNIQUE');60 });61}6263export async function isQuartz(): Promise<boolean> {64 return usingApi(async api => {65 const chain = await api.rpc.system.chain();6667 return chain.eq('QUARTZ');68 });69}7071let modulesNames: any;72export function getModuleNames(api: ApiPromise): string[] {73 if (typeof modulesNames === 'undefined')74 modulesNames = api.runtimeMetadata.asLatest.pallets.map(m => m.name.toString().toLowerCase());75 return modulesNames;76}7778export async function missingRequiredPallets(requiredPallets: string[]): Promise<string[]> {79 return await usingApi(async api => {80 const pallets = getModuleNames(api);8182 return requiredPallets.filter(p => !pallets.includes(p));83 });84}8586export async function checkPalletsPresence(requiredPallets: string[]): Promise<boolean> {87 return (await missingRequiredPallets(requiredPallets)).length == 0;88}8990export async function requirePallets(mocha: Context, requiredPallets: string[]) {91 const missingPallets = await missingRequiredPallets(requiredPallets);9293 if (missingPallets.length > 0) {94 const skippingTestMsg = `\tSkipping test "${mocha.test?.title}".`;95 const missingPalletsMsg = `\tThe following pallets are missing:\n\t- ${missingPallets.join('\n\t- ')}`;96 const skipMsg = `${skippingTestMsg}\n${missingPalletsMsg}`;9798 console.error('\x1b[38:5:208m%s\x1b[0m', skipMsg);99100 mocha.skip();101 }102}103104export function bigIntToSub(api: ApiPromise, number: bigint) {105 return api.registry.createType('AccountId', '0x' + number.toString(16).padStart(64, '0')).toJSON();106}107108export function bigIntToDecimals(number: bigint, decimals = 18): string {109 const numberStr = number.toString();110 const dotPos = numberStr.length - decimals;111112 if (dotPos <= 0) {113 return '0.' + '0'.repeat(Math.abs(dotPos)) + numberStr;114 } else {115 const intPart = numberStr.substring(0, dotPos);116 const fractPart = numberStr.substring(dotPos);117 return intPart + '.' + fractPart;118 }119}120121export function normalizeAccountId(input: string | AccountId | CrossAccountId | IKeyringPair): CrossAccountId {122 if (typeof input === 'string') {123 if (input.length >= 47) {124 return {Substrate: input};125 } else if (input.length === 42 && input.startsWith('0x')) {126 return {Ethereum: input.toLowerCase()};127 } else if (input.length === 40 && !input.startsWith('0x')) {128 return {Ethereum: '0x' + input.toLowerCase()};129 } else {130 throw new Error(`Unknown address format: "${input}"`);131 }132 }133 if ('address' in input) {134 return {Substrate: input.address};135 }136 if ('Ethereum' in input) {137 return {138 Ethereum: input.Ethereum.toLowerCase(),139 };140 } else if ('ethereum' in input) {141 return {142 Ethereum: (input as any).ethereum.toLowerCase(),143 };144 } else if ('Substrate' in input) {145 return input;146 } else if ('substrate' in input) {147 return {148 Substrate: (input as any).substrate,149 };150 }151152 153 return {Substrate: input.toString()};154}155export function toSubstrateAddress(input: string | CrossAccountId | IKeyringPair): string {156 input = normalizeAccountId(input);157 if ('Substrate' in input) {158 return input.Substrate;159 } else {160 return evmToAddress(input.Ethereum);161 }162}163164export const U128_MAX = (1n << 128n) - 1n;165166const MICROUNIQUE = 1_000_000_000_000n;167const MILLIUNIQUE = 1_000n * MICROUNIQUE;168const CENTIUNIQUE = 10n * MILLIUNIQUE;169export const UNIQUE = 100n * CENTIUNIQUE;170171interface GenericResult<T> {172 success: boolean;173 data: T | null;174}175176interface CreateCollectionResult {177 success: boolean;178 collectionId: number;179}180181interface CreateItemResult {182 success: boolean;183 collectionId: number;184 itemId: number;185 recipient?: CrossAccountId;186 amount?: number;187}188189interface DestroyItemResult {190 success: boolean;191 collectionId: number;192 itemId: number;193 owner: CrossAccountId;194 amount: number;195}196197interface TransferResult {198 collectionId: number;199 itemId: number;200 sender?: CrossAccountId;201 recipient?: CrossAccountId;202 value: bigint;203}204205interface IReFungibleOwner {206 fraction: BN;207 owner: number[];208}209210interface IGetMessage {211 checkMsgUnqMethod: string;212 checkMsgTrsMethod: string;213 checkMsgSysMethod: string;214}215216export interface IFungibleTokenDataType {217 value: number;218}219220export interface IChainLimits {221 collectionNumbersLimit: number;222 accountTokenOwnershipLimit: number;223 collectionsAdminsLimit: number;224 customDataLimit: number;225 nftSponsorTransferTimeout: number;226 fungibleSponsorTransferTimeout: number;227 refungibleSponsorTransferTimeout: number;228 229 230}231232export interface IReFungibleTokenDataType {233 owner: IReFungibleOwner[];234}235236export function uniqueEventMessage(events: EventRecord[]): IGetMessage {237 let checkMsgUnqMethod = '';238 let checkMsgTrsMethod = '';239 let checkMsgSysMethod = '';240 events.forEach(({event: {method, section}}) => {241 if (section === 'common') {242 checkMsgUnqMethod = method;243 } else if (section === 'treasury') {244 checkMsgTrsMethod = method;245 } else if (section === 'system') {246 checkMsgSysMethod = method;247 } else { return null; }248 });249 const result: IGetMessage = {250 checkMsgUnqMethod,251 checkMsgTrsMethod,252 checkMsgSysMethod,253 };254 return result;255}256257export function getEvent<T extends Event>(events: EventRecord[], check: (event: IEvent<AnyTuple>) => event is T): T | undefined {258 const event = events.find(r => check(r.event));259 if (!event) return;260 return event.event as T;261}262263export function getGenericResult<T>(events: EventRecord[]): GenericResult<T>;264export function getGenericResult<T>(265 events: EventRecord[],266 expectSection: string,267 expectMethod: string,268 extractAction: (data: GenericEventData) => T269): GenericResult<T>;270271export function getGenericResult<T>(272 events: EventRecord[],273 expectSection?: string,274 expectMethod?: string,275 extractAction?: (data: GenericEventData) => T,276): GenericResult<T> {277 let success = false;278 let successData = null;279280 events.forEach(({event: {data, method, section}}) => {281 282 if (method === 'ExtrinsicSuccess') {283 success = true;284 } else if ((expectSection == section) && (expectMethod == method)) {285 successData = extractAction!(data as any);286 }287 });288289 const result: GenericResult<T> = {290 success,291 data: successData,292 };293 return result;294}295296export function getCreateCollectionResult(events: EventRecord[]): CreateCollectionResult {297 const genericResult = getGenericResult(events, 'common', 'CollectionCreated', (data) => parseInt(data[0].toString(), 10));298 const result: CreateCollectionResult = {299 success: genericResult.success,300 collectionId: genericResult.data ?? 0,301 };302 return result;303}304305export function getCreateItemsResult(events: EventRecord[]): CreateItemResult[] {306 const results: CreateItemResult[] = [];307308 const genericResult = getGenericResult<CreateItemResult[]>(events, 'common', 'ItemCreated', (data) => {309 const collectionId = parseInt(data[0].toString(), 10);310 const itemId = parseInt(data[1].toString(), 10);311 const recipient = normalizeAccountId(data[2].toJSON() as any);312 const amount = parseInt(data[3].toString(), 10);313314 const itemRes: CreateItemResult = {315 success: true,316 collectionId,317 itemId,318 recipient,319 amount,320 };321322 results.push(itemRes);323 return results;324 });325326 if (!genericResult.success) return [];327 return results;328}329330export function getCreateItemResult(events: EventRecord[]): CreateItemResult {331 const genericResult = getGenericResult(events, 'common', 'ItemCreated', (data) => data.map(function(value) { return value.toJSON(); }));332333 if (genericResult.data == null)334 return {335 success: genericResult.success,336 collectionId: 0,337 itemId: 0,338 amount: 0,339 };340 else341 return {342 success: genericResult.success,343 collectionId: genericResult.data[0] as number,344 itemId: genericResult.data[1] as number,345 recipient: normalizeAccountId(genericResult.data![2] as any),346 amount: genericResult.data[3] as number,347 };348}349350export function getDestroyItemsResult(events: EventRecord[]): DestroyItemResult[] {351 const results: DestroyItemResult[] = [];352353 const genericResult = getGenericResult<DestroyItemResult[]>(events, 'common', 'ItemDestroyed', (data) => {354 const collectionId = parseInt(data[0].toString(), 10);355 const itemId = parseInt(data[1].toString(), 10);356 const owner = normalizeAccountId(data[2].toJSON() as any);357 const amount = parseInt(data[3].toString(), 10);358359 const itemRes: DestroyItemResult = {360 success: true,361 collectionId,362 itemId,363 owner,364 amount,365 };366367 results.push(itemRes);368 return results;369 });370371 if (!genericResult.success) return [];372 return results;373}374375export function getTransferResult(api: ApiPromise, events: EventRecord[]): TransferResult {376 for (const {event} of events) {377 if (api.events.common.Transfer.is(event)) {378 const [collection, token, sender, recipient, value] = event.data;379 return {380 collectionId: collection.toNumber(),381 itemId: token.toNumber(),382 sender: normalizeAccountId(sender.toJSON() as any),383 recipient: normalizeAccountId(recipient.toJSON() as any),384 value: value.toBigInt(),385 };386 }387 }388 throw new Error('no transfer event');389}390391interface Nft {392 type: 'NFT';393}394395interface Fungible {396 type: 'Fungible';397 decimalPoints: number;398}399400interface ReFungible {401 type: 'ReFungible';402}403404export type CollectionMode = Nft | Fungible | ReFungible;405406export type Property = {407 key: any,408 value: any,409};410411type Permission = {412 mutable: boolean;413 collectionAdmin: boolean;414 tokenOwner: boolean;415}416417type PropertyPermission = {418 key: any;419 permission: Permission;420}421422export type CreateCollectionParams = {423 mode: CollectionMode,424 name: string,425 description: string,426 tokenPrefix: string,427 properties?: Array<Property>,428 propPerm?: Array<PropertyPermission>429};430431const defaultCreateCollectionParams: CreateCollectionParams = {432 description: 'description',433 mode: {type: 'NFT'},434 name: 'name',435 tokenPrefix: 'prefix',436};437438export async function439createCollection(440 api: ApiPromise,441 sender: IKeyringPair,442 params: Partial<CreateCollectionParams> = {},443): Promise<CreateCollectionResult> {444 const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};445446 let modeprm = {};447 if (mode.type === 'NFT') {448 modeprm = {nft: null};449 } else if (mode.type === 'Fungible') {450 modeprm = {fungible: mode.decimalPoints};451 } else if (mode.type === 'ReFungible') {452 modeprm = {refungible: null};453 }454455 const tx = api.tx.unique.createCollectionEx({456 name: strToUTF16(name),457 description: strToUTF16(description),458 tokenPrefix: strToUTF16(tokenPrefix),459 mode: modeprm as any,460 });461 const events = await executeTransaction(api, sender, tx);462 return getCreateCollectionResult(events);463}464465export async function createCollectionExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {466 const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};467468 let collectionId = 0;469 await usingApi(async (api, privateKeyWrapper) => {470 471 const collectionCountBefore = await getCreatedCollectionCount(api);472473 474 const alicePrivateKey = privateKeyWrapper('//Alice');475476 const result = await createCollection(api, alicePrivateKey, params);477478 479 const collectionCountAfter = await getCreatedCollectionCount(api);480481 482 const collection = await queryCollectionExpectSuccess(api, result.collectionId);483484 485 486 expect(result.success).to.be.true;487 expect(result.collectionId).to.be.equal(collectionCountAfter);488 489 expect(collection).to.be.not.null;490 expect(collectionCountAfter).to.be.equal(collectionCountBefore + 1, 'Error: NFT collection NOT created.');491 expect(collection.owner.toString()).to.be.equal(toSubstrateAddress(alicePrivateKey));492 expect(utf16ToStr(collection.name.toJSON() as any)).to.be.equal(name);493 expect(utf16ToStr(collection.description.toJSON() as any)).to.be.equal(description);494 expect(hexToStr(collection.tokenPrefix.toJSON())).to.be.equal(tokenPrefix);495496 collectionId = result.collectionId;497 });498499 return collectionId;500}501502export async function createCollectionWithPropsExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {503 const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};504505 let collectionId = 0;506 await usingApi(async (api, privateKeyWrapper) => {507 508 const collectionCountBefore = await getCreatedCollectionCount(api);509510 511 const alicePrivateKey = privateKeyWrapper('//Alice');512513 let modeprm = {};514 if (mode.type === 'NFT') {515 modeprm = {nft: null};516 } else if (mode.type === 'Fungible') {517 modeprm = {fungible: mode.decimalPoints};518 } else if (mode.type === 'ReFungible') {519 modeprm = {refungible: null};520 }521522 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});523 const events = await submitTransactionAsync(alicePrivateKey, tx);524 const result = getCreateCollectionResult(events);525526 527 const collectionCountAfter = await getCreatedCollectionCount(api);528529 530 const collection = await queryCollectionExpectSuccess(api, result.collectionId);531532 533 534 expect(result.success).to.be.true;535 expect(result.collectionId).to.be.equal(collectionCountAfter);536 537 expect(collection).to.be.not.null;538 expect(collectionCountAfter).to.be.equal(collectionCountBefore + 1, 'Error: NFT collection NOT created.');539 expect(collection.owner.toString()).to.be.equal(toSubstrateAddress(alicePrivateKey));540 expect(utf16ToStr(collection.name.toJSON() as any)).to.be.equal(name);541 expect(utf16ToStr(collection.description.toJSON() as any)).to.be.equal(description);542 expect(hexToStr(collection.tokenPrefix.toJSON())).to.be.equal(tokenPrefix);543544545 collectionId = result.collectionId;546 });547548 return collectionId;549}550551export async function createCollectionWithPropsExpectFailure(params: Partial<CreateCollectionParams> = {}) {552 const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};553554 await usingApi(async (api, privateKeyWrapper) => {555 556 const collectionCountBefore = await getCreatedCollectionCount(api);557558 559 const alicePrivateKey = privateKeyWrapper('//Alice');560561 let modeprm = {};562 if (mode.type === 'NFT') {563 modeprm = {nft: null};564 } else if (mode.type === 'Fungible') {565 modeprm = {fungible: mode.decimalPoints};566 } else if (mode.type === 'ReFungible') {567 modeprm = {refungible: null};568 }569570 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});571 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;572573574 575 const collectionCountAfter = await getCreatedCollectionCount(api);576577 expect(collectionCountAfter).to.be.equal(collectionCountBefore, 'Error: Collection with incorrect data created.');578 });579}580581export async function createCollectionExpectFailure(params: Partial<CreateCollectionParams> = {}) {582 const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};583584 let modeprm = {};585 if (mode.type === 'NFT') {586 modeprm = {nft: null};587 } else if (mode.type === 'Fungible') {588 modeprm = {fungible: mode.decimalPoints};589 } else if (mode.type === 'ReFungible') {590 modeprm = {refungible: null};591 }592593 await usingApi(async (api, privateKeyWrapper) => {594 595 const collectionCountBefore = await getCreatedCollectionCount(api);596597 598 const alicePrivateKey = privateKeyWrapper('//Alice');599 const tx = api.tx.unique.createCollectionEx({name: strToUTF16(name), description: strToUTF16(description), tokenPrefix: strToUTF16(tokenPrefix), mode: modeprm as any});600 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;601602 603 const collectionCountAfter = await getCreatedCollectionCount(api);604605 606 expect(collectionCountAfter).to.be.equal(collectionCountBefore, 'Error: Collection with incorrect data created.');607 });608}609610export async function findUnusedAddress(api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair, seedAddition = ''): Promise<IKeyringPair> {611 let bal = 0n;612 let unused;613 do {614 const randomSeed = 'seed' + Math.floor(Math.random() * Math.floor(10000)) + seedAddition;615 unused = privateKeyWrapper(`//${randomSeed}`);616 bal = (await api.query.system.account(unused.address)).data.free.toBigInt();617 } while (bal !== 0n);618 return unused;619}620621export async function getAllowance(api: ApiPromise, collectionId: number, owner: CrossAccountId | string | IKeyringPair, approved: CrossAccountId | string | IKeyringPair, tokenId: number) {622 return (await api.rpc.unique.allowance(collectionId, normalizeAccountId(owner), normalizeAccountId(approved), tokenId)).toBigInt();623}624625export function findUnusedAddresses(api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair, amount: number): Promise<IKeyringPair[]> {626 return Promise.all(new Array(amount).fill(null).map(() => findUnusedAddress(api, privateKeyWrapper, '_' + Date.now())));627}628629export async function findNotExistingCollection(api: ApiPromise): Promise<number> {630 const totalNumber = await getCreatedCollectionCount(api);631 const newCollection: number = totalNumber + 1;632 return newCollection;633}634635function getDestroyResult(events: EventRecord[]): boolean {636 let success = false;637 events.forEach(({event: {method}}) => {638 if (method == 'ExtrinsicSuccess') {639 success = true;640 }641 });642 return success;643}644645export async function destroyCollectionExpectFailure(collectionId: number, senderSeed = '//Alice') {646 await usingApi(async (api, privateKeyWrapper) => {647 648 const alicePrivateKey = privateKeyWrapper(senderSeed);649 const tx = api.tx.unique.destroyCollection(collectionId);650 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;651 });652}653654export async function destroyCollectionExpectSuccess(collectionId: number, senderSeed = '//Alice') {655 await usingApi(async (api, privateKeyWrapper) => {656 657 const alicePrivateKey = privateKeyWrapper(senderSeed);658 const tx = api.tx.unique.destroyCollection(collectionId);659 const events = await submitTransactionAsync(alicePrivateKey, tx);660 const result = getDestroyResult(events);661 expect(result).to.be.true;662663 664 expect(await getDetailedCollectionInfo(api, collectionId)).to.be.null;665 });666}667668export async function setCollectionLimitsExpectSuccess(sender: IKeyringPair, collectionId: number, limits: any) {669 await usingApi(async (api) => {670 const tx = api.tx.unique.setCollectionLimits(collectionId, limits);671 const events = await submitTransactionAsync(sender, tx);672 const result = getGenericResult(events);673674 expect(result.success).to.be.true;675 });676}677678export const setCollectionPermissionsExpectSuccess = async (sender: IKeyringPair, collectionId: number, permissions: any) => {679 await usingApi(async(api) => {680 const tx = api.tx.unique.setCollectionPermissions(collectionId, permissions);681 const events = await submitTransactionAsync(sender, tx);682 const result = getGenericResult(events);683684 expect(result.success).to.be.true;685 });686};687688export async function setCollectionLimitsExpectFailure(sender: IKeyringPair, collectionId: number, limits: any) {689 await usingApi(async (api) => {690 const tx = api.tx.unique.setCollectionLimits(collectionId, limits);691 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;692 const result = getGenericResult(events);693694 expect(result.success).to.be.false;695 });696}697698export async function setCollectionSponsorExpectSuccess(collectionId: number, sponsor: string, sender = '//Alice') {699 await usingApi(async (api, privateKeyWrapper) => {700701 702 const senderPrivateKey = privateKeyWrapper(sender);703 const tx = api.tx.unique.setCollectionSponsor(collectionId, sponsor);704 const events = await submitTransactionAsync(senderPrivateKey, tx);705 const result = getGenericResult(events);706707 708 const collection = await queryCollectionExpectSuccess(api, collectionId);709710 711 expect(result.success).to.be.true;712 expect(collection.sponsorship.toJSON()).to.deep.equal({713 unconfirmed: sponsor,714 });715 });716}717718export async function removeCollectionSponsorExpectSuccess(collectionId: number, sender = '//Alice') {719 await usingApi(async (api, privateKeyWrapper) => {720721 722 const alicePrivateKey = privateKeyWrapper(sender);723 const tx = api.tx.unique.removeCollectionSponsor(collectionId);724 const events = await submitTransactionAsync(alicePrivateKey, tx);725 const result = getGenericResult(events);726727 728 const collection = await queryCollectionExpectSuccess(api, collectionId);729730 731 expect(result.success).to.be.true;732 expect(collection.sponsorship.toJSON()).to.be.deep.equal({disabled: null});733 });734}735736export async function removeCollectionSponsorExpectFailure(collectionId: number, senderSeed = '//Alice') {737 await usingApi(async (api, privateKeyWrapper) => {738739 740 const alicePrivateKey = privateKeyWrapper(senderSeed);741 const tx = api.tx.unique.removeCollectionSponsor(collectionId);742 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;743 });744}745746export async function setCollectionSponsorExpectFailure(collectionId: number, sponsor: string, senderSeed = '//Alice') {747 await usingApi(async (api, privateKeyWrapper) => {748749 750 const alicePrivateKey = privateKeyWrapper(senderSeed);751 const tx = api.tx.unique.setCollectionSponsor(collectionId, sponsor);752 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;753 });754}755756export async function confirmSponsorshipExpectSuccess(collectionId: number, senderSeed = '//Alice') {757 await usingApi(async (api, privateKeyWrapper) => {758759 760 const sender = privateKeyWrapper(senderSeed);761 await confirmSponsorshipByKeyExpectSuccess(collectionId, sender);762 });763}764765export async function confirmSponsorshipByKeyExpectSuccess(collectionId: number, sender: IKeyringPair) {766 await usingApi(async (api, privateKeyWrapper) => {767768 769 const tx = api.tx.unique.confirmSponsorship(collectionId);770 const events = await submitTransactionAsync(sender, tx);771 const result = getGenericResult(events);772773 774 const collection = await queryCollectionExpectSuccess(api, collectionId);775776 777 expect(result.success).to.be.true;778 expect(collection.sponsorship.toJSON()).to.be.deep.equal({779 confirmed: sender.address,780 });781 });782}783784785export async function confirmSponsorshipExpectFailure(collectionId: number, senderSeed = '//Alice') {786 await usingApi(async (api, privateKeyWrapper) => {787788 789 const sender = privateKeyWrapper(senderSeed);790 const tx = api.tx.unique.confirmSponsorship(collectionId);791 await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;792 });793}794795export async function enableContractSponsoringExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {796 await usingApi(async (api) => {797 const tx = api.tx.unique.enableContractSponsoring(contractAddress, enable);798 const events = await submitTransactionAsync(sender, tx);799 const result = getGenericResult(events);800801 expect(result.success).to.be.true;802 });803}804805export async function enableContractSponsoringExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {806 await usingApi(async (api) => {807 const tx = api.tx.unique.enableContractSponsoring(contractAddress, enable);808 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;809 const result = getGenericResult(events);810811 expect(result.success).to.be.false;812 });813}814815export async function setTransferFlagExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {816817 await usingApi(async (api) => {818819 const tx = api.tx.unique.setTransfersEnabledFlag(collectionId, enabled);820 const events = await submitTransactionAsync(sender, tx);821 const result = getGenericResult(events);822823 expect(result.success).to.be.true;824 });825}826827export async function setTransferFlagExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {828829 await usingApi(async (api) => {830831 const tx = api.tx.unique.setTransfersEnabledFlag(collectionId, enabled);832 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;833 const result = getGenericResult(events);834835 expect(result.success).to.be.false;836 });837}838839export async function setContractSponsoringRateLimitExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {840 await usingApi(async (api) => {841 const tx = api.tx.unique.setContractSponsoringRateLimit(contractAddress, rateLimit);842 const events = await submitTransactionAsync(sender, tx);843 const result = getGenericResult(events);844845 expect(result.success).to.be.true;846 });847}848849export async function setContractSponsoringRateLimitExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {850 await usingApi(async (api) => {851 const tx = api.tx.unique.setContractSponsoringRateLimit(contractAddress, rateLimit);852 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;853 const result = getGenericResult(events);854855 expect(result.success).to.be.false;856 });857}858859export async function getNextSponsored(860 api: ApiPromise,861 collectionId: number,862 account: string | CrossAccountId,863 tokenId: number,864): Promise<number> {865 return Number((await api.rpc.unique.nextSponsored(collectionId, account, tokenId)).unwrapOr(-1));866}867868export async function toggleContractAllowlistExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, value = true) {869 await usingApi(async (api) => {870 const tx = api.tx.unique.toggleContractAllowList(contractAddress, value);871 const events = await submitTransactionAsync(sender, tx);872 const result = getGenericResult(events);873874 expect(result.success).to.be.true;875 });876}877878export async function isAllowlistedInContract(contractAddress: AccountId | string, user: string) {879 let allowlisted = false;880 await usingApi(async (api) => {881 allowlisted = (await api.query.unique.contractAllowList(contractAddress, user)).toJSON() as boolean;882 });883 return allowlisted;884}885886export async function addToContractAllowListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {887 await usingApi(async (api) => {888 const tx = api.tx.unique.addToContractAllowList(contractAddress.toString(), user.toString());889 const events = await submitTransactionAsync(sender, tx);890 const result = getGenericResult(events);891892 expect(result.success).to.be.true;893 });894}895896export async function removeFromContractAllowListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {897 await usingApi(async (api) => {898 const tx = api.tx.unique.removeFromContractAllowList(contractAddress.toString(), user.toString());899 const events = await submitTransactionAsync(sender, tx);900 const result = getGenericResult(events);901902 expect(result.success).to.be.true;903 });904}905906export async function removeFromContractAllowListExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {907 await usingApi(async (api) => {908 const tx = api.tx.unique.removeFromContractAllowList(contractAddress.toString(), user.toString());909 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;910 const result = getGenericResult(events);911912 expect(result.success).to.be.false;913 });914}915916export interface CreateFungibleData {917 readonly Value: bigint;918}919920export interface CreateReFungibleData { }921export interface CreateNftData { }922923export type CreateItemData = {924 NFT: CreateNftData;925} | {926 Fungible: CreateFungibleData;927} | {928 ReFungible: CreateReFungibleData;929};930931export async function burnItem(api: ApiPromise, sender: IKeyringPair, collectionId: number, tokenId: number, value: number | bigint) : Promise<boolean> {932 const tx = api.tx.unique.burnItem(collectionId, tokenId, value);933 const events = await submitTransactionAsync(sender, tx);934 return getGenericResult(events).success;935}936937export async function burnItemExpectSuccess(sender: IKeyringPair, collectionId: number, tokenId: number, value: number | bigint = 1) {938 await usingApi(async (api) => {939 const balanceBefore = await getBalance(api, collectionId, normalizeAccountId(sender), tokenId);940 941 expect(balanceBefore >= BigInt(value)).to.be.true;942943 expect(await burnItem(api, sender, collectionId, tokenId, value)).to.be.true;944945 const balanceAfter = await getBalance(api, collectionId, normalizeAccountId(sender), tokenId);946 expect(balanceAfter + BigInt(value)).to.be.equal(balanceBefore);947 });948}949950export async function burnItemExpectFailure(sender: IKeyringPair, collectionId: number, tokenId: number, value: number | bigint = 1) {951 await usingApi(async (api) => {952 const tx = api.tx.unique.burnItem(collectionId, tokenId, value);953954 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;955 const result = getCreateCollectionResult(events);956 957 expect(result.success).to.be.false;958 });959}960961export async function burnFromExpectSuccess(sender: IKeyringPair, from: IKeyringPair | CrossAccountId, collectionId: number, tokenId: number, value: number | bigint = 1) {962 await usingApi(async (api) => {963 const tx = api.tx.unique.burnFrom(collectionId, normalizeAccountId(from), tokenId, value);964 const events = await submitTransactionAsync(sender, tx);965 return getGenericResult(events).success;966 });967}968969export async function970approve(971 api: ApiPromise,972 collectionId: number,973 tokenId: number, owner: IKeyringPair, approved: CrossAccountId | string | IKeyringPair, amount: number | bigint,974) {975 const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);976 const events = await submitTransactionAsync(owner, approveUniqueTx);977 return getGenericResult(events).success;978}979980export async function981approveExpectSuccess(982 collectionId: number,983 tokenId: number, owner: IKeyringPair, approved: CrossAccountId | string, amount: number | bigint = 1,984) {985 await usingApi(async (api: ApiPromise) => {986 const result = await approve(api, collectionId, tokenId, owner, approved, amount);987 expect(result).to.be.true;988989 expect(await getAllowance(api, collectionId, owner, approved, tokenId)).to.be.equal(BigInt(amount));990 });991}992993export async function adminApproveFromExpectSuccess(994 collectionId: number,995 tokenId: number, admin: IKeyringPair, owner: CrossAccountId | string, approved: CrossAccountId | string, amount: number | bigint = 1,996) {997 await usingApi(async (api: ApiPromise) => {998 const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);999 const events = await submitTransactionAsync(admin, approveUniqueTx);1000 const result = getGenericResult(events);1001 expect(result.success).to.be.true;10021003 expect(await getAllowance(api, collectionId, owner, approved, tokenId)).to.be.equal(BigInt(amount));1004 });1005}10061007export async function1008transferFrom(1009 api: ApiPromise,1010 collectionId: number,1011 tokenId: number,1012 accountApproved: IKeyringPair,1013 accountFrom: IKeyringPair | CrossAccountId,1014 accountTo: IKeyringPair | CrossAccountId,1015 value: number | bigint,1016) {1017 const from = normalizeAccountId(accountFrom);1018 const to = normalizeAccountId(accountTo);1019 const transferFromTx = api.tx.unique.transferFrom(from, to, collectionId, tokenId, value);1020 const events = await submitTransactionAsync(accountApproved, transferFromTx);1021 return getGenericResult(events).success;1022}10231024export async function1025transferFromExpectSuccess(1026 collectionId: number,1027 tokenId: number,1028 accountApproved: IKeyringPair,1029 accountFrom: IKeyringPair | CrossAccountId,1030 accountTo: IKeyringPair | CrossAccountId,1031 value: number | bigint = 1,1032 type = 'NFT',1033) {1034 await usingApi(async (api: ApiPromise) => {1035 const from = normalizeAccountId(accountFrom);1036 const to = normalizeAccountId(accountTo);1037 let balanceBefore = 0n;1038 if (type === 'Fungible' || type === 'ReFungible') {1039 balanceBefore = await getBalance(api, collectionId, to, tokenId);1040 }1041 expect(await transferFrom(api, collectionId, tokenId, accountApproved, accountFrom, accountTo, value)).to.be.true;1042 if (type === 'NFT') {1043 expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(to);1044 }1045 if (type === 'Fungible') {1046 const balanceAfter = await getBalance(api, collectionId, to, tokenId);1047 if (JSON.stringify(to) !== JSON.stringify(from)) {1048 expect(balanceAfter - balanceBefore).to.be.equal(BigInt(value));1049 } else {1050 expect(balanceAfter).to.be.equal(balanceBefore);1051 }1052 }1053 if (type === 'ReFungible') {1054 expect(await getBalance(api, collectionId, to, tokenId)).to.be.equal(balanceBefore + BigInt(value));1055 }1056 });1057}10581059export async function1060transferFromExpectFail(1061 collectionId: number,1062 tokenId: number,1063 accountApproved: IKeyringPair,1064 accountFrom: IKeyringPair,1065 accountTo: IKeyringPair,1066 value: number | bigint = 1,1067) {1068 await usingApi(async (api: ApiPromise) => {1069 const transferFromTx = api.tx.unique.transferFrom(normalizeAccountId(accountFrom.address), normalizeAccountId(accountTo.address), collectionId, tokenId, value);1070 const events = await expect(submitTransactionExpectFailAsync(accountApproved, transferFromTx)).to.be.rejected;1071 const result = getCreateCollectionResult(events);1072 1073 expect(result.success).to.be.false;1074 });1075}107610771078export async function getBlockNumber(api: ApiPromise): Promise<number> {1079 return new Promise<number>(async (resolve) => {1080 const unsubscribe = await api.rpc.chain.subscribeNewHeads((head) => {1081 unsubscribe();1082 resolve(head.number.toNumber());1083 });1084 });1085}10861087export async function addCollectionAdminExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | CrossAccountId) {1088 await usingApi(async (api) => {1089 const changeAdminTx = api.tx.unique.addCollectionAdmin(collectionId, normalizeAccountId(address));1090 const events = await submitTransactionAsync(sender, changeAdminTx);1091 const result = getCreateCollectionResult(events);1092 expect(result.success).to.be.true;1093 });1094}10951096export async function adminApproveFromExpectFail(1097 collectionId: number,1098 tokenId: number, admin: IKeyringPair, owner: CrossAccountId | string, approved: CrossAccountId | string, amount: number | bigint = 1,1099) {1100 await usingApi(async (api: ApiPromise) => {1101 const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);1102 const events = await expect(submitTransactionAsync(admin, approveUniqueTx)).to.be.rejected;1103 const result = getGenericResult(events);1104 expect(result.success).to.be.false;1105 });1106}11071108export async function1109getFreeBalance(account: IKeyringPair): Promise<bigint> {1110 let balance = 0n;1111 await usingApi(async (api) => {1112 balance = BigInt((await api.query.system.account(account.address)).data.free.toString());1113 });11141115 return balance;1116}11171118export async function paraSiblingSovereignAccount(paraid: number): Promise<string> {1119 return usingApi(async api => {1120 1121 1122 const siblingPrefix = '0x7369626c';11231124 const encodedParaId = api.createType('u32', paraid).toHex(true).substring(2);1125 const suffix = '000000000000000000000000000000000000000000000000';11261127 return siblingPrefix + encodedParaId + suffix;1128 });1129}11301131export async function transferBalanceTo(api: ApiPromise, source: IKeyringPair, target: string, amount = 1000n * UNIQUE) {1132 const tx = api.tx.balances.transfer(target, amount);1133 const events = await submitTransactionAsync(source, tx);1134 const result = getGenericResult(events);1135 expect(result.success).to.be.true;1136}11371138export async function1139scheduleExpectSuccess(1140 operationTx: any,1141 sender: IKeyringPair,1142 blockSchedule: number,1143 scheduledId: string,1144 period = 1,1145 repetitions = 1,1146) {1147 await usingApi(async (api: ApiPromise) => {1148 const blockNumber: number | undefined = await getBlockNumber(api);1149 const expectedBlockNumber = blockNumber + blockSchedule;11501151 expect(blockNumber).to.be.greaterThan(0);1152 const scheduleTx = api.tx.scheduler.scheduleNamed( 1153 scheduledId,1154 expectedBlockNumber,1155 repetitions > 1 ? [period, repetitions] : null,1156 0,1157 {Value: operationTx as any},1158 );11591160 const events = await submitTransactionAsync(sender, scheduleTx);1161 expect(getGenericResult(events).success).to.be.true;1162 });1163}11641165export async function1166scheduleExpectFailure(1167 operationTx: any,1168 sender: IKeyringPair,1169 blockSchedule: number,1170 scheduledId: string,1171 period = 1,1172 repetitions = 1,1173) {1174 await usingApi(async (api: ApiPromise) => {1175 const blockNumber: number | undefined = await getBlockNumber(api);1176 const expectedBlockNumber = blockNumber + blockSchedule;11771178 expect(blockNumber).to.be.greaterThan(0);1179 const scheduleTx = api.tx.scheduler.scheduleNamed( 1180 scheduledId,1181 expectedBlockNumber,1182 repetitions <= 1 ? null : [period, repetitions],1183 0,1184 {Value: operationTx as any},1185 );11861187 1188 await expect(submitTransactionExpectFailAsync(sender, scheduleTx)).to.be.rejected;1189 1190 });1191}11921193export async function1194scheduleTransferAndWaitExpectSuccess(1195 collectionId: number,1196 tokenId: number,1197 sender: IKeyringPair,1198 recipient: IKeyringPair,1199 value: number | bigint = 1,1200 blockSchedule: number,1201 scheduledId: string,1202) {1203 await usingApi(async (api: ApiPromise) => {1204 await scheduleTransferExpectSuccess(collectionId, tokenId, sender, recipient, value, blockSchedule, scheduledId);12051206 const recipientBalanceBefore = (await api.query.system.account(recipient.address)).data.free.toBigInt();12071208 1209 await waitNewBlocks(blockSchedule + 1);12101211 const recipientBalanceAfter = (await api.query.system.account(recipient.address)).data.free.toBigInt();12121213 expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(recipient.address));1214 expect(recipientBalanceAfter).to.be.equal(recipientBalanceBefore);1215 });1216}12171218export async function1219scheduleTransferExpectSuccess(1220 collectionId: number,1221 tokenId: number,1222 sender: IKeyringPair,1223 recipient: IKeyringPair,1224 value: number | bigint = 1,1225 blockSchedule: number,1226 scheduledId: string,1227) {1228 await usingApi(async (api: ApiPromise) => {1229 const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient.address), collectionId, tokenId, value);12301231 await scheduleExpectSuccess(transferTx, sender, blockSchedule, scheduledId);12321233 expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(sender.address));1234 });1235}12361237export async function1238scheduleTransferFundsPeriodicExpectSuccess(1239 amount: bigint,1240 sender: IKeyringPair,1241 recipient: IKeyringPair,1242 blockSchedule: number,1243 scheduledId: string,1244 period: number,1245 repetitions: number,1246) {1247 await usingApi(async (api: ApiPromise) => {1248 const transferTx = api.tx.balances.transfer(recipient.address, amount);12491250 const balanceBefore = await getFreeBalance(recipient);12511252 await scheduleExpectSuccess(transferTx, sender, blockSchedule, scheduledId, period, repetitions);12531254 expect(await getFreeBalance(recipient)).to.be.equal(balanceBefore);1255 });1256}12571258export async function1259transfer(1260 api: ApiPromise,1261 collectionId: number,1262 tokenId: number,1263 sender: IKeyringPair,1264 recipient: IKeyringPair | CrossAccountId,1265 value: number | bigint,1266) : Promise<boolean> {1267 const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient), collectionId, tokenId, value);1268 const events = await executeTransaction(api, sender, transferTx);1269 return getGenericResult(events).success;1270}12711272export async function1273transferExpectSuccess(1274 collectionId: number,1275 tokenId: number,1276 sender: IKeyringPair,1277 recipient: IKeyringPair | CrossAccountId,1278 value: number | bigint = 1,1279 type = 'NFT',1280) {1281 await usingApi(async (api: ApiPromise) => {1282 const from = normalizeAccountId(sender);1283 const to = normalizeAccountId(recipient);12841285 let balanceBefore = 0n;1286 if (type === 'Fungible' || type === 'ReFungible') {1287 balanceBefore = await getBalance(api, collectionId, to, tokenId);1288 }12891290 const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient), collectionId, tokenId, value);1291 const events = await executeTransaction(api, sender, transferTx);1292 const result = getTransferResult(api, events);12931294 expect(result.collectionId).to.be.equal(collectionId);1295 expect(result.itemId).to.be.equal(tokenId);1296 expect(result.sender).to.be.deep.equal(normalizeAccountId(sender.address));1297 expect(result.recipient).to.be.deep.equal(to);1298 expect(result.value).to.be.equal(BigInt(value));12991300 if (type === 'NFT') {1301 expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(to);1302 }1303 if (type === 'Fungible' || type === 'ReFungible') {1304 const balanceAfter = await getBalance(api, collectionId, to, tokenId);1305 if (JSON.stringify(to) !== JSON.stringify(from)) {1306 expect(balanceAfter - balanceBefore).to.be.equal(BigInt(value));1307 } else {1308 expect(balanceAfter).to.be.equal(balanceBefore);1309 }1310 }1311 });1312}13131314export async function1315transferExpectFailure(1316 collectionId: number,1317 tokenId: number,1318 sender: IKeyringPair,1319 recipient: IKeyringPair | CrossAccountId,1320 value: number | bigint = 1,1321) {1322 await usingApi(async (api: ApiPromise) => {1323 const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient), collectionId, tokenId, value);1324 const events = await expect(submitTransactionExpectFailAsync(sender, transferTx)).to.be.rejected;1325 const result = getGenericResult(events);1326 1327 1328 1329 expect(result.success).to.be.false;1330 1331 });1332}13331334export async function1335approveExpectFail(1336 collectionId: number,1337 tokenId: number, owner: IKeyringPair, approved: IKeyringPair, amount: number | bigint = 1,1338) {1339 await usingApi(async (api: ApiPromise) => {1340 const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved.address), collectionId, tokenId, amount);1341 const events = await expect(submitTransactionExpectFailAsync(owner, approveUniqueTx)).to.be.rejected;1342 const result = getCreateCollectionResult(events);1343 1344 expect(result.success).to.be.false;1345 });1346}13471348export async function getBalance(1349 api: ApiPromise,1350 collectionId: number,1351 owner: string | CrossAccountId | IKeyringPair,1352 token: number,1353): Promise<bigint> {1354 return (await api.rpc.unique.balance(collectionId, normalizeAccountId(owner), token)).toBigInt();1355}1356export async function getTokenOwner(1357 api: ApiPromise,1358 collectionId: number,1359 token: number,1360): Promise<CrossAccountId> {1361 const owner = (await api.rpc.unique.tokenOwner(collectionId, token)).toJSON() as any;1362 if (owner == null) throw new Error('owner == null');1363 return normalizeAccountId(owner);1364}1365export async function getTopmostTokenOwner(1366 api: ApiPromise,1367 collectionId: number,1368 token: number,1369): Promise<CrossAccountId> {1370 const owner = (await api.rpc.unique.topmostTokenOwner(collectionId, token)).toJSON() as any;1371 if (owner == null) throw new Error('owner == null');1372 return normalizeAccountId(owner);1373}1374export async function getTokenChildren(1375 api: ApiPromise,1376 collectionId: number,1377 tokenId: number,1378): Promise<UpDataStructsTokenChild[]> {1379 return (await api.rpc.unique.tokenChildren(collectionId, tokenId)).toJSON() as any;1380}1381export async function isTokenExists(1382 api: ApiPromise,1383 collectionId: number,1384 token: number,1385): Promise<boolean> {1386 return (await api.rpc.unique.tokenExists(collectionId, token)).toJSON();1387}1388export async function getLastTokenId(1389 api: ApiPromise,1390 collectionId: number,1391): Promise<number> {1392 return (await api.rpc.unique.lastTokenId(collectionId)).toJSON();1393}1394export async function getAdminList(1395 api: ApiPromise,1396 collectionId: number,1397): Promise<string[]> {1398 return (await api.rpc.unique.adminlist(collectionId)).toHuman() as any;1399}1400export async function getTokenProperties(1401 api: ApiPromise,1402 collectionId: number,1403 tokenId: number,1404 propertyKeys: string[],1405): Promise<UpDataStructsProperty[]> {1406 return (await api.rpc.unique.tokenProperties(collectionId, tokenId, propertyKeys)).toHuman() as any;1407}14081409export async function createFungibleItemExpectSuccess(1410 sender: IKeyringPair,1411 collectionId: number,1412 data: CreateFungibleData,1413 owner: CrossAccountId | string = sender.address,1414) {1415 return await usingApi(async (api) => {1416 const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), {Fungible: data});14171418 const events = await submitTransactionAsync(sender, tx);1419 const result = getCreateItemResult(events);14201421 expect(result.success).to.be.true;1422 return result.itemId;1423 });1424}14251426export async function createMultipleItemsExpectSuccess(sender: IKeyringPair, collectionId: number, itemsData: any, owner: CrossAccountId | string = sender.address) {1427 await usingApi(async (api) => {1428 const to = normalizeAccountId(owner);1429 const tx = api.tx.unique.createMultipleItems(collectionId, to, itemsData);14301431 const events = await submitTransactionAsync(sender, tx);1432 expect(getGenericResult(events).success).to.be.true;1433 });1434}14351436export async function createMultipleItemsWithPropsExpectSuccess(sender: IKeyringPair, collectionId: number, itemsData: any, owner: CrossAccountId | string = sender.address) {1437 await usingApi(async (api) => {1438 const to = normalizeAccountId(owner);1439 const tx = api.tx.unique.createMultipleItems(collectionId, to, itemsData);14401441 const events = await submitTransactionAsync(sender, tx);1442 const result = getCreateItemsResult(events);14431444 for (const res of result) {1445 expect(await api.rpc.unique.tokenProperties(collectionId, res.itemId)).not.to.be.empty;1446 }1447 });1448}14491450export async function createMultipleItemsExWithPropsExpectSuccess(sender: IKeyringPair, collectionId: number, itemsData: any) {1451 await usingApi(async (api) => {1452 const tx = api.tx.unique.createMultipleItemsEx(collectionId, itemsData);14531454 const events = await submitTransactionAsync(sender, tx);1455 const result = getCreateItemsResult(events);14561457 for (const res of result) {1458 expect(await api.rpc.unique.tokenProperties(collectionId, res.itemId)).not.to.be.empty;1459 }1460 });1461}14621463export async function createItemWithPropsExpectSuccess(sender: IKeyringPair, collectionId: number, createMode: string, props: Array<Property>, owner: CrossAccountId | string = sender.address) {1464 let newItemId = 0;1465 await usingApi(async (api) => {1466 const to = normalizeAccountId(owner);1467 const itemCountBefore = await getLastTokenId(api, collectionId);1468 const itemBalanceBefore = await getBalance(api, collectionId, to, newItemId);14691470 let tx;1471 if (createMode === 'Fungible') {1472 const createData = {fungible: {value: 10}};1473 tx = api.tx.unique.createItem(collectionId, to, createData as any);1474 } else if (createMode === 'ReFungible') {1475 const createData = {refungible: {pieces: 100}};1476 tx = api.tx.unique.createItem(collectionId, to, createData as any);1477 } else {1478 const data = api.createType('UpDataStructsCreateItemData', {NFT: {properties: props}});1479 tx = api.tx.unique.createItem(collectionId, to, data as UpDataStructsCreateItemData);1480 }14811482 const events = await submitTransactionAsync(sender, tx);1483 const result = getCreateItemResult(events);14841485 const itemCountAfter = await getLastTokenId(api, collectionId);1486 const itemBalanceAfter = await getBalance(api, collectionId, to, newItemId);14871488 if (createMode === 'NFT') {1489 expect(await api.rpc.unique.tokenProperties(collectionId, result.itemId)).not.to.be.empty;1490 }14911492 1493 1494 expect(result.success).to.be.true;1495 if (createMode === 'Fungible') {1496 expect(itemBalanceAfter - itemBalanceBefore).to.be.equal(10n);1497 } else {1498 expect(itemCountAfter).to.be.equal(itemCountBefore + 1);1499 }1500 expect(collectionId).to.be.equal(result.collectionId);1501 expect(itemCountAfter.toString()).to.be.equal(result.itemId.toString());1502 expect(to).to.be.deep.equal(result.recipient);1503 newItemId = result.itemId;1504 });1505 return newItemId;1506}15071508export async function createItemWithPropsExpectFailure(sender: IKeyringPair, collectionId: number, createMode: string, props: Array<Property>, owner: CrossAccountId | string = sender.address) {1509 await usingApi(async (api) => {15101511 let tx;1512 if (createMode === 'NFT') {1513 const data = api.createType('UpDataStructsCreateItemData', {NFT: {properties: props}}) as UpDataStructsCreateItemData;1514 tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), data);1515 } else {1516 tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), createMode);1517 }151815191520 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1521 if(events.message && events.message.toString().indexOf('1002: Verification Error') > -1) return;1522 const result = getCreateItemResult(events);15231524 expect(result.success).to.be.false;1525 });1526}15271528export async function createItemExpectSuccess(sender: IKeyringPair, collectionId: number, createMode: string, owner: CrossAccountId | string = sender.address) {1529 let newItemId = 0;1530 await usingApi(async (api) => {1531 const to = normalizeAccountId(owner);1532 const itemCountBefore = await getLastTokenId(api, collectionId);1533 const itemBalanceBefore = await getBalance(api, collectionId, to, newItemId);15341535 let tx;1536 if (createMode === 'Fungible') {1537 const createData = {fungible: {value: 10}};1538 tx = api.tx.unique.createItem(collectionId, to, createData as any);1539 } else if (createMode === 'ReFungible') {1540 const createData = {refungible: {pieces: 100}};1541 tx = api.tx.unique.createItem(collectionId, to, createData as any);1542 } else {1543 const createData = {nft: {}};1544 tx = api.tx.unique.createItem(collectionId, to, createData as any);1545 }15461547 const events = await executeTransaction(api, sender, tx);1548 const result = getCreateItemResult(events);15491550 const itemCountAfter = await getLastTokenId(api, collectionId);1551 const itemBalanceAfter = await getBalance(api, collectionId, to, newItemId);15521553 1554 1555 expect(result.success).to.be.true;1556 if (createMode === 'Fungible') {1557 expect(itemBalanceAfter - itemBalanceBefore).to.be.equal(10n);1558 } else {1559 expect(itemCountAfter).to.be.equal(itemCountBefore + 1);1560 }1561 expect(collectionId).to.be.equal(result.collectionId);1562 expect(itemCountAfter.toString()).to.be.equal(result.itemId.toString());1563 expect(to).to.be.deep.equal(result.recipient);1564 newItemId = result.itemId;1565 });1566 return newItemId;1567}15681569export async function createRefungibleToken(api: ApiPromise, sender: IKeyringPair, collectionId: number, amount: bigint, owner: CrossAccountId | IKeyringPair | string = sender.address) : Promise<CreateItemResult> {1570 const createData = {refungible: {pieces: amount}};1571 const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), createData as any);15721573 const events = await submitTransactionAsync(sender, tx);1574 return getCreateItemResult(events);1575}15761577export async function createItemExpectFailure(sender: IKeyringPair, collectionId: number, createMode: string, owner: CrossAccountId | string = sender.address) {1578 await usingApi(async (api) => {1579 const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), createMode);15801581 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1582 const result = getCreateItemResult(events);15831584 expect(result.success).to.be.false;1585 });1586}15871588export async function setPublicAccessModeExpectSuccess(1589 sender: IKeyringPair, collectionId: number,1590 accessMode: 'Normal' | 'AllowList',1591) {1592 await usingApi(async (api) => {15931594 1595 const tx = api.tx.unique.setCollectionPermissions(collectionId, {access: accessMode});1596 const events = await submitTransactionAsync(sender, tx);1597 const result = getGenericResult(events);15981599 1600 const collection = await queryCollectionExpectSuccess(api, collectionId);16011602 1603 1604 expect(result.success).to.be.true;1605 expect(collection.permissions.access.toHuman()).to.be.equal(accessMode);1606 });1607}16081609export async function setPublicAccessModeExpectFail(1610 sender: IKeyringPair, collectionId: number,1611 accessMode: 'Normal' | 'AllowList',1612) {1613 await usingApi(async (api) => {16141615 1616 const tx = api.tx.unique.setCollectionPermissions(collectionId, {access: accessMode});1617 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1618 const result = getGenericResult(events);16191620 1621 1622 expect(result.success).to.be.false;1623 });1624}16251626export async function enableAllowListExpectSuccess(sender: IKeyringPair, collectionId: number) {1627 await setPublicAccessModeExpectSuccess(sender, collectionId, 'AllowList');1628}16291630export async function enableAllowListExpectFail(sender: IKeyringPair, collectionId: number) {1631 await setPublicAccessModeExpectFail(sender, collectionId, 'AllowList');1632}16331634export async function disableAllowListExpectSuccess(sender: IKeyringPair, collectionId: number) {1635 await setPublicAccessModeExpectSuccess(sender, collectionId, 'Normal');1636}16371638export async function setMintPermissionExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {1639 await usingApi(async (api) => {16401641 1642 const tx = api.tx.unique.setCollectionPermissions(collectionId, {mintMode: enabled});1643 const events = await submitTransactionAsync(sender, tx);1644 const result = getGenericResult(events);1645 expect(result.success).to.be.true;16461647 1648 const collection = await queryCollectionExpectSuccess(api, collectionId);16491650 expect(collection.permissions.mintMode.toHuman()).to.be.equal(enabled);1651 });1652}16531654export async function enablePublicMintingExpectSuccess(sender: IKeyringPair, collectionId: number) {1655 await setMintPermissionExpectSuccess(sender, collectionId, true);1656}16571658export async function setMintPermissionExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {1659 await usingApi(async (api) => {1660 1661 const tx = api.tx.unique.setCollectionPermissions(collectionId, {mintMode: enabled});1662 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1663 const result = getCreateCollectionResult(events);1664 1665 expect(result.success).to.be.false;1666 });1667}16681669export async function setChainLimitsExpectFailure(sender: IKeyringPair, limits: IChainLimits) {1670 await usingApi(async (api) => {1671 1672 const tx = api.tx.unique.setChainLimits(limits);1673 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1674 const result = getCreateCollectionResult(events);1675 1676 expect(result.success).to.be.false;1677 });1678}16791680export async function isAllowlisted(api: ApiPromise, collectionId: number, address: string | CrossAccountId | IKeyringPair) {1681 return (await api.rpc.unique.allowed(collectionId, normalizeAccountId(address))).toJSON();1682}16831684export async function addToAllowListExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId | CrossAccountId) {1685 await usingApi(async (api) => {1686 expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.false;16871688 1689 const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1690 const events = await submitTransactionAsync(sender, tx);1691 const result = getGenericResult(events);1692 expect(result.success).to.be.true;16931694 expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;1695 });1696}16971698export async function addToAllowListAgainExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId) {1699 await usingApi(async (api) => {17001701 expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;17021703 1704 const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1705 const events = await submitTransactionAsync(sender, tx);1706 const result = getGenericResult(events);1707 expect(result.success).to.be.true;17081709 expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;1710 });1711}17121713export async function addToAllowListExpectFail(sender: IKeyringPair, collectionId: number, address: string | AccountId) {1714 await usingApi(async (api) => {17151716 1717 const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1718 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1719 const result = getGenericResult(events);17201721 1722 1723 expect(result.success).to.be.false;1724 });1725}17261727export async function removeFromAllowListExpectSuccess(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1728 await usingApi(async (api) => {1729 1730 const tx = api.tx.unique.removeFromAllowList(collectionId, normalizeAccountId(address));1731 const events = await submitTransactionAsync(sender, tx);1732 const result = getGenericResult(events);17331734 1735 1736 expect(result.success).to.be.true;1737 });1738}17391740export async function removeFromAllowListExpectFailure(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1741 await usingApi(async (api) => {1742 1743 const tx = api.tx.unique.removeFromAllowList(collectionId, normalizeAccountId(address));1744 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1745 const result = getGenericResult(events);17461747 1748 1749 expect(result.success).to.be.false;1750 });1751}17521753export const getDetailedCollectionInfo = async (api: ApiPromise, collectionId: number)1754 : Promise<UpDataStructsRpcCollection | null> => {1755 return (await api.rpc.unique.collectionById(collectionId)).unwrapOr(null);1756};17571758export const getCreatedCollectionCount = async (api: ApiPromise): Promise<number> => {1759 1760 return (await api.rpc.unique.collectionStats()).created.toNumber();1761};17621763export async function queryCollectionExpectSuccess(api: ApiPromise, collectionId: number): Promise<UpDataStructsRpcCollection> {1764 return (await api.rpc.unique.collectionById(collectionId)).unwrap();1765}17661767export async function waitNewBlocks(blocksCount = 1): Promise<void> {1768 await usingApi(async (api) => {1769 const promise = new Promise<void>(async (resolve) => {1770 const unsubscribe = await api.rpc.chain.subscribeNewHeads(() => {1771 if (blocksCount > 0) {1772 blocksCount--;1773 } else {1774 unsubscribe();1775 resolve();1776 }1777 });1778 });1779 return promise;1780 });1781}17821783export async function waitEvent(1784 api: ApiPromise,1785 maxBlocksToWait: number,1786 eventSection: string,1787 eventMethod: string,1788): Promise<EventRecord | null> {17891790 const promise = new Promise<EventRecord | null>(async (resolve) => {1791 const unsubscribe = await api.rpc.chain.subscribeNewHeads(async header => {1792 const blockNumber = header.number.toHuman();1793 const blockHash = header.hash;1794 const eventIdStr = `${eventSection}.${eventMethod}`;1795 const waitLimitStr = `wait blocks remaining: ${maxBlocksToWait}`;17961797 console.log(`[Block #${blockNumber}] Waiting for event \`${eventIdStr}\` (${waitLimitStr})`);17981799 const apiAt = await api.at(blockHash);1800 const eventRecords = await apiAt.query.system.events();18011802 const neededEvent = eventRecords.find(r => {1803 return r.event.section == eventSection && r.event.method == eventMethod;1804 });18051806 if (neededEvent) {1807 unsubscribe();1808 resolve(neededEvent);1809 } else if (maxBlocksToWait > 0) {1810 maxBlocksToWait--;1811 } else {1812 console.log(`Event \`${eventIdStr}\` is NOT found`);18131814 unsubscribe();1815 resolve(null);1816 }1817 });1818 });1819 return promise;1820}18211822export async function repartitionRFT(1823 api: ApiPromise,1824 collectionId: number,1825 sender: IKeyringPair,1826 tokenId: number,1827 amount: bigint,1828): Promise<boolean> {1829 const tx = api.tx.unique.repartition(collectionId, tokenId, amount);1830 const events = await submitTransactionAsync(sender, tx);1831 const result = getGenericResult(events);18321833 return result.success;1834}18351836export async function itApi(name: string, cb: (apis: { api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair }) => any, opts: { only?: boolean, skip?: boolean } = {}) {1837 let i: any = it;1838 if (opts.only) i = i.only;1839 else if (opts.skip) i = i.skip;1840 i(name, async () => {1841 await usingApi(async (api, privateKeyWrapper) => {1842 await cb({api, privateKeyWrapper});1843 });1844 });1845}18461847itApi.only = (name: string, cb: (apis: { api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair }) => any) => itApi(name, cb, {only: true});1848itApi.skip = (name: string, cb: (apis: { api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair }) => any) => itApi(name, cb, {skip: true});18491850let accountSeed = 10000;1851export function generateKeyringPair(keyring: Keyring) {1852 const privateKey = `0xDEADBEEF${(Date.now() + (accountSeed++)).toString(16).padStart(64 - 8, '0')}`;1853 return keyring.addFromUri(privateKey);1854}18551856export async function expectSubstrateEventsAtBlock(api: ApiPromise, blockNumber: AnyNumber | BlockNumber, section: string, methods: string[], dryRun = false) {1857 const blockHash = await api.rpc.chain.getBlockHash(blockNumber);1858 const subEvents = (await api.query.system.events.at(blockHash))1859 .filter(x => x.event.section === section)1860 .map((x) => x.toHuman());1861 const events = methods.map((m) => {1862 return {1863 event: {1864 method: m,1865 section,1866 },1867 };1868 });1869 if (!dryRun) {1870 expect(subEvents).to.be.like(events);1871 }1872 return subEvents;1873}